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

Add real android support #577

Merged
merged 8 commits into from
Aug 2, 2022
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
1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -86,4 +86,3 @@ objc = "0.2"
objc_id = "0.1"

[target."cfg(target_os = \"android\")".dependencies]
jni = "0.18.0"
9 changes: 8 additions & 1 deletion examples/custom_protocol.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ fn main() -> wry::Result<()> {
.build(&event_loop)
.unwrap();

let _webview = WebViewBuilder::new(window)
let webview = WebViewBuilder::new(window)
.unwrap()
.with_custom_protocol("wry".into(), move |request| {
// Remove url scheme
Expand All @@ -46,13 +46,20 @@ fn main() -> wry::Result<()> {
})
// tell the webview to load the custom protocol
.with_url("wry://examples/index.html")?
.with_devtools(true)
.build()?;

event_loop.run(move |event, _, control_flow| {
*control_flow = ControlFlow::Wait;

match event {
Event::NewEvents(StartCause::Init) => println!("Wry application started!"),
Event::WindowEvent {
event: WindowEvent::Moved { .. },
..
} => {
webview.evaluate_script("console.log('hello');");
}
Event::WindowEvent {
event: WindowEvent::CloseRequested,
..
Expand Down
23 changes: 0 additions & 23 deletions src/application.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,27 +9,4 @@
//!
//! [tao]: https://crates.io/crates/tao

#[cfg(not(target_os = "android"))]
pub use tao::*;

// TODO Implement actual Window library of Android
#[cfg(target_os = "android")]
pub use tao::{dpi, error};

#[cfg(target_os = "android")]
pub mod window {
use tao::dpi::PhysicalSize;
pub use tao::window::BadIcon;

pub struct Window;

impl Window {
pub fn new() -> Self {
Self
}

pub fn inner_size(&self) -> PhysicalSize<u32> {
todo!()
}
}
}
3 changes: 0 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -177,7 +177,4 @@ pub enum Error {
InvalidMethod(#[from] InvalidMethod),
#[error("Infallible error, something went really wrong: {0}")]
Infallible(#[from] std::convert::Infallible),
#[cfg(target_os = "android")]
#[error("JNI error: {0}")]
JNIError(#[from] jni::errors::Error),
}
128 changes: 35 additions & 93 deletions src/webview/android/mod.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,10 @@
use std::{collections::HashSet, ffi::c_void, ptr::null_mut, rc::Rc, sync::RwLock};

use crate::{application::window::Window, Result};

use super::{WebContext, WebViewAttributes};

use jni::{
objects::{JClass, JObject},
sys::jobject,
JNIEnv,
};

use once_cell::sync::Lazy;

static IPC: Lazy<RwLock<UnsafeIpc>> = Lazy::new(|| RwLock::new(UnsafeIpc(null_mut())));
use crate::{application::window::Window, Result};
use std::rc::Rc;
use tao::platform::android::ndk_glue::*;

pub struct InnerWebView {
pub window: Rc<Window>,
pub attributes: WebViewAttributes,
}

impl InnerWebView {
Expand All @@ -25,7 +13,37 @@ impl InnerWebView {
attributes: WebViewAttributes,
_web_context: Option<&mut WebContext>,
) -> Result<Self> {
Ok(Self { window, attributes })
let WebViewAttributes {
url,
initialization_scripts,
ipc_handler,
devtools,
..
} = attributes;

if let Some(u) = url {
let mut url_string = String::from(u.as_str());
let name = u.scheme();
// TODO: Expands custom protocols with real configurations
let schemes = vec!["assets", "res"];
if schemes.contains(&name) {
url_string = u
.as_str()
.replace(&format!("{}://", name), "https://tauri.mobile/")
}
MainPipe::send(WebViewMessage::CreateWebView(
url_string,
initialization_scripts,
devtools,
));
}

let w = window.clone();
if let Some(i) = ipc_handler {
IPC.get_or_init(move || UnsafeIpc::new(Box::into_raw(Box::new(i)) as *mut _, w));
}

Ok(Self { window })
}

pub fn print(&self) {}
Expand All @@ -47,85 +65,9 @@ impl InnerWebView {
false
}

pub fn run(self, env: JNIEnv, _jclass: JClass, jobject: JObject) -> Result<jobject> {
let string_class = env.find_class("java/lang/String")?;
// let client = env.call_method(
// jobject,
// "getWebViewClient",
// "()Landroid/webkit/WebViewClient;",
// &[],
// )?;
let WebViewAttributes {
url,
custom_protocols,
initialization_scripts,
ipc_handler,
devtools,
..
} = self.attributes;

if let Some(i) = ipc_handler {
let i = UnsafeIpc(Box::into_raw(Box::new(i)) as *mut _);
let mut ipc = IPC.write().unwrap();
*ipc = i;
}

if devtools {
#[cfg(any(debug_assertions, feature = "devtools"))]
{
let class = env.find_class("android/webkit/WebView")?;
env.call_static_method(
class,
"setWebContentsDebuggingEnabled",
"(Z)V",
&[devtools.into()],
)?;
}
}

if let Some(u) = url {
let mut url_string = String::from(u.as_str());
let schemes = custom_protocols
.into_iter()
.map(|(s, _)| s)
.collect::<HashSet<_>>();
let name = u.scheme();
if schemes.contains(name) {
url_string = u
.as_str()
.replace(&format!("{}://", name), "https://tauri.wry/")
}
let url = env.new_string(url_string)?;
env.call_method(jobject, "loadUrl", "(Ljava/lang/String;)V", &[url.into()])?;
}

// Return initialization scripts
let len = initialization_scripts.len();
let scripts = env.new_object_array(len as i32, string_class, env.new_string("")?)?;
for (idx, s) in initialization_scripts.into_iter().enumerate() {
env.set_object_array_element(scripts, idx as i32, env.new_string(s)?)?;
}
Ok(scripts)
}

pub fn ipc_handler(window: &Window, arg: String) {
let function = IPC.read().unwrap();
unsafe {
let ipc = function.0;
if !ipc.is_null() {
let ipc = &*(ipc as *mut Box<dyn Fn(&Window, String)>);
ipc(window, arg)
}
}
}

pub fn zoom(&self, scale_factor: f64) {}
pub fn zoom(&self, _scale_factor: f64) {}
}

pub struct UnsafeIpc(*mut c_void);
unsafe impl Send for UnsafeIpc {}
unsafe impl Sync for UnsafeIpc {}

pub fn platform_webview_version() -> Result<String> {
todo!()
}
16 changes: 0 additions & 16 deletions src/webview/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,6 @@ pub(crate) mod webview2;
#[cfg(target_os = "windows")]
use self::webview2::*;
use crate::Result;
#[cfg(target_os = "android")]
use jni::{
objects::{JClass, JObject},
sys::jobject,
JNIEnv,
};
#[cfg(target_os = "windows")]
use webview2_com::Microsoft::Web::WebView2::Win32::ICoreWebView2Controller;
#[cfg(target_os = "windows")]
Expand Down Expand Up @@ -537,16 +531,6 @@ impl WebView {
pub fn zoom(&self, scale_factor: f64) {
self.webview.zoom(scale_factor);
}

#[cfg(target_os = "android")]
pub fn run(self, env: JNIEnv, jclass: JClass, jobject: JObject) -> jobject {
self.webview.run(env, jclass, jobject).unwrap()
}

#[cfg(target_os = "android")]
pub fn ipc_handler(window: &Window, arg: String) {
InnerWebView::ipc_handler(window, arg)
}
}

/// An event enumeration sent to [`FileDropHandler`].
Expand Down