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

Added android support #40

Open
wants to merge 6 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 5 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
4 changes: 4 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,10 @@ objc = "0.2"
objc_id = "0.1"
objc-foundation = "0.1"

[target.'cfg(target_os = "android")'.dependencies]
jni = "0.19"
ndk-context = "0"
Fancyflame marked this conversation as resolved.
Show resolved Hide resolved

[target.'cfg(all(unix, not(any(target_os="macos", target_os="android", target_os="ios", target_os="emscripten"))))'.dependencies]
x11-clipboard = { version = "0.5.1", optional = true }
smithay-clipboard = { version = "0.6.0", optional = true }
12 changes: 11 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,17 @@ fn get_contents(&mut self) -> Result<String, Box<Error>>;
fn set_contents(&mut self, String) -> Result<(), Box<Error>>;
```

`ClipboardContext` is a type alias for one of {`WindowsClipboardContext`, `OSXClipboardContext`, `X11ClipboardContext`, `NopClipboardContext`}, all of which implement `ClipboardProvider`. Which concrete type is chosen for `ClipboardContext` depends on the OS (via conditional compilation).
`ClipboardContext` is a type alias for one of
{

- `WindowsClipboardContext`
- `AndroidClipboardContext`
- `OSXClipboardContext`
- `X11ClipboardContext`
- `NopClipboardContext`

}
,all of which implement `ClipboardProvider`. Which concrete type is chosen for `ClipboardContext` depends on the OS (via conditional compilation).
Fancyflame marked this conversation as resolved.
Show resolved Hide resolved

## License

Expand Down
93 changes: 93 additions & 0 deletions src/android_clipboard.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,93 @@
use crate::common::{ClipboardProvider, Result};
use jni::objects::JString;
use std::ffi::CStr;

pub struct AndroidClipboardContext;

impl ClipboardProvider for AndroidClipboardContext {
fn get_contents(&mut self) -> Result<String> {
let ctx = ndk_context::android_context();
let vm = unsafe { jni::JavaVM::from_raw(ctx.vm().cast()) }?;
let env = vm.attach_current_thread()?;
let class_ctx = env.find_class("android/content/Context")?;
let cb = env.get_static_field(class_ctx, "CLIPBOARD_SERVICE", "Ljava/lang/String;")?;
let cb_manager = env
Fancyflame marked this conversation as resolved.
Show resolved Hide resolved
.call_method(
ctx.context() as jni::sys::jobject,
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There's a bunch of instances here where you have specified multiple path objects. For structs and other types the import should always go up to the last path element, so a use jni::sys::jobject should be used here.

This applies to other areas too like jni::JavaVM for example.

Copy link
Author

@Fancyflame Fancyflame May 23, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

JObject must live with env, storage JObject is not easy due to the limitation of API form.

"getSystemService",
"(Ljava/lang/String;)Ljava/lang/Object;",
&[cb],
)?
.l()
.unwrap();

let clip_data = env
.call_method(cb_manager, "getPrimaryClip", "()Landroid/content/ClipData;", &[])?
.l()
.unwrap();
Fancyflame marked this conversation as resolved.
Show resolved Hide resolved

// return Ok(format!("{:?}", clip_data));
Fancyflame marked this conversation as resolved.
Show resolved Hide resolved

let item = env
.call_method(clip_data, "getItemAt", "(I)Landroid/content/ClipData$Item;", &[
0i32.into()
])?
.l()
.unwrap();
Fancyflame marked this conversation as resolved.
Show resolved Hide resolved

let char_seq = env.call_method(item, "getText", "()Ljava/lang/CharSequence;", &[])?.l()?;

let string =
env.call_method(char_seq, "toString", "()Ljava/lang/String;", &[])?.l().unwrap();

let jstring = JString::from(string.into_inner());

let ptr = env.get_string_utf_chars(jstring)?;
let s;
unsafe {
s = CStr::from_ptr(ptr).to_owned().into_string()?;
}
Fancyflame marked this conversation as resolved.
Show resolved Hide resolved
env.release_string_utf_chars(jstring, ptr)?;
Ok(s)
}

fn set_contents(&mut self, text: String) -> Result<()> {
let ctx = ndk_context::android_context();
let vm = unsafe { jni::JavaVM::from_raw(ctx.vm().cast()) }?;
let env = vm.attach_current_thread()?;
let class_ctx = env.find_class("android/content/Context")?;
let cb = env.get_static_field(class_ctx, "CLIPBOARD_SERVICE", "Ljava/lang/String;")?;
let cb_manager = env
.call_method(
ctx.context() as jni::sys::jobject,
"getSystemService",
"(Ljava/lang/String;)Ljava/lang/Object;",
&[cb],
)?
.l()
.unwrap();
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

All of this seems duplicated between the two methods. It also seems to repeatedly access system stuff again and again. Can this not be persisted on the AndroidClipboardContext struct?

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

About this part, I have considered storage the duplicated part into a struct, but cb_manager here borrows vm, which is related to self-reference. I have made a crate to support self-reference: https://github.com/Fancyflame/Any-ref-rs. Its stability should be fine (code reviewed by rust forum) but it requires a high rustc version. Alternatively, we can merge the duplicate part into a function, which can re-use the code but it will not increase any performance, that is to say it still will access the system repeatedly. I prefer the latter, What do you think?


let class_clip_data = env.find_class("android/content/ClipData")?;

let clip_data = env.call_static_method(
class_clip_data,
"newPlainText",
"(Ljava/lang/CharSequence;Ljava/lang/CharSequence;)Landroid/content/ClipData;",
&[env.new_string("text").unwrap().into(), env.new_string(text).unwrap().into()],
)?;

env.call_method(cb_manager, "setPrimaryClip", "(Landroid/content/ClipData;)V", &[
clip_data,
])?
.v()?;

Ok(())
}
}

impl AndroidClipboardContext {
#[inline]
pub fn new() -> Result<Self> {
Ok(AndroidClipboardContext)
}
}
Fancyflame marked this conversation as resolved.
Show resolved Hide resolved
5 changes: 4 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,9 @@ pub mod x11_clipboard;
#[cfg(windows)]
pub mod windows_clipboard;

#[cfg(target_os = "android")]
pub mod android_clipboard;

#[cfg(target_os = "macos")]
pub mod osx_clipboard;

Expand All @@ -63,7 +66,7 @@ pub type ClipboardContext = windows_clipboard::WindowsClipboardContext;
#[cfg(target_os = "macos")]
pub type ClipboardContext = osx_clipboard::OSXClipboardContext;
#[cfg(target_os = "android")]
pub type ClipboardContext = nop_clipboard::NopClipboardContext; // TODO: implement AndroidClipboardContext
pub type ClipboardContext = android_clipboard::AndroidClipboardContext;
#[cfg(target_os = "ios")]
pub type ClipboardContext = nop_clipboard::NopClipboardContext; // TODO: implement IOSClipboardContext
#[cfg(not(any(
Expand Down