Skip to content

Commit

Permalink
feat(android): JNI execution handle (#689)
Browse files Browse the repository at this point in the history
* feat(android): JNI execution handle

* changefile

Co-authored-by: Amr Bashir <amr.bashir2015@gmail.com>
  • Loading branch information
jhutchins and amrbashir committed Sep 7, 2022
1 parent 9183de4 commit 2bfc6c3
Show file tree
Hide file tree
Showing 4 changed files with 40 additions and 1 deletion.
5 changes: 5 additions & 0 deletions .changes/android-jni-handle.md
@@ -0,0 +1,5 @@
---
"wry": patch
---

Add `WebviewExtAndroid::handle` which can be used to execute some code using JNI context.
7 changes: 6 additions & 1 deletion src/webview/android/main_pipe.rs
Expand Up @@ -161,6 +161,11 @@ impl MainPipe<'_> {
Err(e) => tx.send(Err(e.into())).unwrap(),
}
}
WebViewMessage::Jni(f) => {
if let Some(webview) = &self.webview {
f(env, activity, webview.as_obj());
}
}
}
}
Ok(())
Expand Down Expand Up @@ -188,12 +193,12 @@ fn set_background_color<'a>(
Ok(())
}

#[derive(Debug)]
pub enum WebViewMessage {
CreateWebView(CreateWebViewAttributes),
Eval(String),
SetBackgroundColor(RGBA),
GetWebViewVersion(Sender<Result<String, Error>>),
Jni(Box<dyn FnOnce(JNIEnv, JObject, JObject) + Send>),
}

#[derive(Debug)]
Expand Down
14 changes: 14 additions & 0 deletions src/webview/android/mod.rs
Expand Up @@ -242,6 +242,20 @@ impl InnerWebView {
}
}

#[derive(Clone, Copy)]
pub struct JniHandle;

impl JniHandle {
/// Execute jni code on the thread of the webview.
/// Provided function will be provided with the jni evironment, Android activity and WebView
pub fn exec<F>(&self, func: F)
where
F: FnOnce(JNIEnv, JObject, JObject) + Send + 'static,
{
MainPipe::send(WebViewMessage::Jni(Box::new(func)));
}
}

pub fn platform_webview_version() -> Result<String> {
let (tx, rx) = bounded(1);
MainPipe::send(WebViewMessage::GetWebViewVersion(tx));
Expand Down
15 changes: 15 additions & 0 deletions src/webview/mod.rs
Expand Up @@ -15,6 +15,8 @@ pub mod prelude {
pub use super::android::{binding::*, setup};
}
#[cfg(target_os = "android")]
pub use android::JniHandle;
#[cfg(target_os = "android")]
use android::*;
#[cfg(any(
target_os = "linux",
Expand Down Expand Up @@ -662,6 +664,19 @@ impl WebviewExtMacOS for WebView {
}
}

#[cfg(target_os = "android")]
/// Additional methods on `WebView` that are specific to Android
pub trait WebviewExtAndroid {
fn handle(&self) -> JniHandle;
}

#[cfg(target_os = "android")]
impl WebviewExtAndroid for WebView {
fn handle(&self) -> JniHandle {
JniHandle
}
}

#[cfg(test)]
mod tests {
use super::*;
Expand Down

0 comments on commit 2bfc6c3

Please sign in to comment.