Skip to content

Commit

Permalink
android: add missing impl for clipboard
Browse files Browse the repository at this point in the history
  • Loading branch information
jkds authored and not-fl3 committed Jan 8, 2025
1 parent 467791b commit 3a5b563
Show file tree
Hide file tree
Showing 2 changed files with 55 additions and 2 deletions.
22 changes: 22 additions & 0 deletions java/MainActivity.java
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,8 @@
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.content.ClipData;
import android.content.ClipboardManager;

import android.graphics.Color;
import android.graphics.Insets;
Expand Down Expand Up @@ -342,5 +344,25 @@ public void run() {
}
});
}

public String getClipboardText() {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);

if (clipboard == null || !clipboard.hasPrimaryClip()) {
return null;
}

CharSequence clipData = clipboard.getPrimaryClip().getItemAt(0).getText();
if (clipData == null) {
return null;
}

return clipData.toString();
}
public void setClipboardText(String text) {
ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("label", text);
clipboard.setPrimaryClip(clip);
}
}

35 changes: 33 additions & 2 deletions src/native/android.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,10 +331,41 @@ impl AndroidClipboard {
}
impl crate::native::Clipboard for AndroidClipboard {
fn get(&mut self) -> Option<String> {
None
unsafe {
let env = attach_jni_env();

let text = ndk_utils::call_object_method!(
env,
ACTIVITY,
"getClipboardText",
"()Ljava/lang/String;"
);
if text.is_null() {
return None;
}

let text = ndk_utils::get_utf_str!(env, text).to_string();
Some(text)
}
}

fn set(&mut self, data: &str) {}
fn set(&mut self, data: &str) {
let data = std::ffi::CString::new(data).unwrap();
unsafe {
let env = attach_jni_env();

let new_string_utf = (**env).NewStringUTF.unwrap();
let jtext = new_string_utf(env, data.as_ptr());

ndk_utils::call_void_method!(
env,
ACTIVITY,
"setClipboardText",
"(Ljava/lang/String;)V",
jtext
);
}
}
}

pub unsafe fn run<F>(conf: crate::conf::Conf, f: F)
Expand Down

0 comments on commit 3a5b563

Please sign in to comment.