From 64bddbafc371c727e1e709eca80c40fe389f23ea Mon Sep 17 00:00:00 2001 From: jkds Date: Wed, 8 Jan 2025 12:00:26 +0100 Subject: [PATCH] android: add missing impl for clipboard --- java/MainActivity.java | 22 ++++++++++++++++++++++ src/native/android.rs | 35 +++++++++++++++++++++++++++++++++-- 2 files changed, 55 insertions(+), 2 deletions(-) diff --git a/java/MainActivity.java b/java/MainActivity.java index 7c89d32c..ea1a1fb0 100644 --- a/java/MainActivity.java +++ b/java/MainActivity.java @@ -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; @@ -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); + } } diff --git a/src/native/android.rs b/src/native/android.rs index 6cab4fa8..4c2a42ae 100644 --- a/src/native/android.rs +++ b/src/native/android.rs @@ -331,10 +331,41 @@ impl AndroidClipboard { } impl crate::native::Clipboard for AndroidClipboard { fn get(&mut self) -> Option { - 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(conf: crate::conf::Conf, f: F)