Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

android: add missing impl for clipboard #510

Merged
merged 1 commit into from
Jan 8, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading