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

feat(android): JNI execution handle #689

Merged
merged 2 commits into from Sep 7, 2022
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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;
}
amrbashir marked this conversation as resolved.
Show resolved Hide resolved

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

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