fix(windows): restore Windows 7 startup compatibility
This commit is contained in:
81 files changed
+17157
-66
No files matched your search
Vendored
+483
@@ -0,0 +1,483 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use http::{
|
||||
header::{HeaderName, HeaderValue, CONTENT_LENGTH, CONTENT_TYPE},
|
||||
Request,
|
||||
};
|
||||
use jni::errors::Result as JniResult;
|
||||
pub use jni::{
|
||||
self,
|
||||
objects::{GlobalRef, JClass, JMap, JObject, JString},
|
||||
sys::{jboolean, jint, jobject, jstring},
|
||||
JNIEnv,
|
||||
};
|
||||
pub use ndk;
|
||||
use ndk::looper::{FdEvent, ThreadLooper};
|
||||
use std::os::fd::{AsFd, AsRawFd};
|
||||
|
||||
use super::{
|
||||
main_pipe::{MainPipe, MAIN_PIPE},
|
||||
ASSET_LOADER_DOMAIN, EVAL_CALLBACKS, IPC, ON_LOAD_HANDLER, REQUEST_HANDLER, TITLE_CHANGE_HANDLER,
|
||||
URL_LOADING_OVERRIDE, WITH_ASSET_LOADER,
|
||||
};
|
||||
|
||||
use crate::PageLoadEvent;
|
||||
|
||||
#[macro_export]
|
||||
macro_rules! android_binding {
|
||||
($domain:ident, $package:ident) => {
|
||||
::wry::android_binding!($domain, $package, ::wry)
|
||||
};
|
||||
// use imported `android_setup` just to force the import path to use `wry::{}`
|
||||
// as the macro breaks without braces
|
||||
($domain:ident, $package:ident, $wry:path) => {{
|
||||
use $wry::{android_setup as _, prelude::*};
|
||||
|
||||
android_fn!($domain, $package, Rust, wryCreate, []);
|
||||
android_fn!(
|
||||
$domain,
|
||||
$package,
|
||||
Rust,
|
||||
onWebviewDestroy,
|
||||
[JObject, JString]
|
||||
);
|
||||
|
||||
android_fn!(
|
||||
$domain,
|
||||
$package,
|
||||
Rust,
|
||||
handleRequest,
|
||||
[JString, JObject, jboolean],
|
||||
jobject
|
||||
);
|
||||
android_fn!(
|
||||
$domain,
|
||||
$package,
|
||||
Rust,
|
||||
withAssetLoader,
|
||||
[JString],
|
||||
jboolean
|
||||
);
|
||||
android_fn!(
|
||||
$domain,
|
||||
$package,
|
||||
Rust,
|
||||
assetLoaderDomain,
|
||||
[JString],
|
||||
jstring
|
||||
);
|
||||
android_fn!(
|
||||
$domain,
|
||||
$package,
|
||||
Rust,
|
||||
shouldOverride,
|
||||
[JString, JString],
|
||||
jboolean
|
||||
);
|
||||
android_fn!($domain, $package, Rust, onEval, [JString, jint, JString]);
|
||||
android_fn!($domain, $package, Rust, onPageLoading, [JString, JString]);
|
||||
android_fn!($domain, $package, Rust, onPageLoaded, [JString, JString]);
|
||||
android_fn!($domain, $package, Rust, ipc, [JString, JString, JString]);
|
||||
android_fn!(
|
||||
$domain,
|
||||
$package,
|
||||
Rust,
|
||||
handleReceivedTitle,
|
||||
[JString, JString],
|
||||
);
|
||||
}};
|
||||
}
|
||||
|
||||
fn handle_request(
|
||||
env: &mut JNIEnv,
|
||||
webview_id: JString,
|
||||
request: JObject,
|
||||
is_document_start_script_enabled: jboolean,
|
||||
) -> JniResult<jobject> {
|
||||
let webview_id = env.get_string(&webview_id)?;
|
||||
let webview_id = webview_id.to_str().ok().unwrap_or_default();
|
||||
|
||||
if let Some(handler) = REQUEST_HANDLER.lock().unwrap().get(webview_id) {
|
||||
#[cfg(feature = "tracing")]
|
||||
let span =
|
||||
tracing::info_span!(parent: None, "wry::custom_protocol::handle", uri = tracing::field::Empty).entered();
|
||||
|
||||
let mut request_builder = Request::builder();
|
||||
|
||||
let uri = env
|
||||
.call_method(&request, "getUrl", "()Landroid/net/Uri;", &[])?
|
||||
.l()?;
|
||||
let url: JString = env
|
||||
.call_method(&uri, "toString", "()Ljava/lang/String;", &[])?
|
||||
.l()?
|
||||
.into();
|
||||
let url = env.get_string(&url)?.to_string_lossy().to_string();
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
span.record("uri", &url);
|
||||
|
||||
request_builder = request_builder.uri(&url);
|
||||
|
||||
let method = env
|
||||
.call_method(&request, "getMethod", "()Ljava/lang/String;", &[])?
|
||||
.l()
|
||||
.map(JString::from)?;
|
||||
request_builder = request_builder.method(
|
||||
env
|
||||
.get_string(&method)?
|
||||
.to_string_lossy()
|
||||
.to_string()
|
||||
.as_str(),
|
||||
);
|
||||
|
||||
let request_headers = env
|
||||
.call_method(request, "getRequestHeaders", "()Ljava/util/Map;", &[])?
|
||||
.l()?;
|
||||
let request_headers = JMap::from_env(env, &request_headers)?;
|
||||
let mut iter = request_headers.iter(env)?;
|
||||
while let Some((header, value)) = iter.next(env)? {
|
||||
let header = JString::from(header);
|
||||
let value = JString::from(value);
|
||||
let header = env.get_string(&header)?;
|
||||
let value = env.get_string(&value)?;
|
||||
if let (Ok(header), Ok(value)) = (
|
||||
HeaderName::from_bytes(header.to_bytes()),
|
||||
HeaderValue::from_bytes(value.to_bytes()),
|
||||
) {
|
||||
request_builder = request_builder.header(header, value);
|
||||
}
|
||||
}
|
||||
|
||||
let final_request = match request_builder.body(Vec::new()) {
|
||||
Ok(req) => req,
|
||||
Err(_e) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("Failed to build response: {_e}");
|
||||
return Ok(*JObject::null());
|
||||
}
|
||||
};
|
||||
|
||||
let response = {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _span = tracing::info_span!("wry::custom_protocol::call_handler").entered();
|
||||
(handler.handler)(
|
||||
webview_id,
|
||||
final_request,
|
||||
is_document_start_script_enabled != 0,
|
||||
)
|
||||
};
|
||||
if let Some(response) = response {
|
||||
let status = response.status();
|
||||
let status_code = status.as_u16() as i32;
|
||||
let status_err = if status_code < 100 {
|
||||
Some("Status code can't be less than 100")
|
||||
} else if status_code > 599 {
|
||||
Some("statusCode can't be greater than 599.")
|
||||
} else if status_code > 299 && status_code < 400 {
|
||||
Some("statusCode can't be in the [300, 399] range.")
|
||||
} else {
|
||||
None
|
||||
};
|
||||
if let Some(_err) = status_err {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("{_err}");
|
||||
return Ok(*JObject::null());
|
||||
}
|
||||
|
||||
let reason_phrase = status.canonical_reason().unwrap_or("OK");
|
||||
let (mime_type, encoding) = if let Some(content_type) = response.headers().get(CONTENT_TYPE) {
|
||||
let content_type = content_type.to_str().unwrap().trim();
|
||||
let mut s = content_type.split(';');
|
||||
let mime_type = s.next().unwrap().trim();
|
||||
let mut encoding = None;
|
||||
for token in s {
|
||||
let token = token.trim();
|
||||
if token.starts_with("charset=") {
|
||||
encoding.replace(token.split('=').nth(1).unwrap());
|
||||
break;
|
||||
}
|
||||
}
|
||||
(
|
||||
env.new_string(mime_type)?,
|
||||
if let Some(encoding) = encoding {
|
||||
env.new_string(encoding)?
|
||||
} else {
|
||||
JString::default()
|
||||
},
|
||||
)
|
||||
} else {
|
||||
(JString::default(), JString::default())
|
||||
};
|
||||
|
||||
let headers = response.headers();
|
||||
let obj = env.new_object("java/util/HashMap", "()V", &[])?;
|
||||
let response_headers = {
|
||||
let headers_map = JMap::from_env(env, &obj)?;
|
||||
for (name, value) in headers.iter() {
|
||||
// WebResourceResponse will automatically generate Content-Type and
|
||||
// Content-Length headers so we should skip them to avoid duplication.
|
||||
if name == CONTENT_TYPE || name == CONTENT_LENGTH {
|
||||
continue;
|
||||
}
|
||||
let key = env.new_string(name)?;
|
||||
let value = env.new_string(value.to_str().unwrap_or_default())?;
|
||||
headers_map.put(env, &key, &value)?;
|
||||
}
|
||||
headers_map
|
||||
};
|
||||
|
||||
let bytes = response.body();
|
||||
|
||||
let byte_array_input_stream = env.find_class("java/io/ByteArrayInputStream")?;
|
||||
let byte_array = env.byte_array_from_slice(bytes)?;
|
||||
let stream = env.new_object(byte_array_input_stream, "([B)V", &[(&byte_array).into()])?;
|
||||
|
||||
let reason_phrase = env.new_string(reason_phrase)?;
|
||||
|
||||
let web_resource_response_class = env.find_class("android/webkit/WebResourceResponse")?;
|
||||
let web_resource_response = env.new_object(
|
||||
web_resource_response_class,
|
||||
"(Ljava/lang/String;Ljava/lang/String;ILjava/lang/String;Ljava/util/Map;Ljava/io/InputStream;)V",
|
||||
&[(&mime_type).into(), (&encoding).into(), status_code.into(), (&reason_phrase).into(), (&response_headers).into(), (&stream).into()],
|
||||
)?;
|
||||
|
||||
return Ok(*web_resource_response);
|
||||
}
|
||||
}
|
||||
|
||||
Ok(*JObject::null())
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub unsafe fn wryCreate(env: JNIEnv, _: JClass) {
|
||||
let mut main_pipe = MainPipe { env };
|
||||
|
||||
let looper = ThreadLooper::for_thread().unwrap();
|
||||
|
||||
looper
|
||||
.add_fd_with_callback(MAIN_PIPE[0].as_fd(), FdEvent::INPUT, move |fd, _event| {
|
||||
let size = std::mem::size_of::<bool>();
|
||||
let mut wake = false;
|
||||
if libc::read(fd.as_raw_fd(), &mut wake as *mut _ as *mut _, size) == size as libc::ssize_t {
|
||||
// unregister itself on errors
|
||||
main_pipe.recv().is_ok()
|
||||
} else {
|
||||
// unregister itself
|
||||
false
|
||||
}
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub unsafe fn onWebviewDestroy(mut env: JNIEnv, _: JClass, activity: JObject, webview_id: JString) {
|
||||
let activity_id = env
|
||||
.call_method(&activity, "getId", "()I", &[])
|
||||
.unwrap()
|
||||
.i()
|
||||
.unwrap();
|
||||
|
||||
let webview_id = env
|
||||
.get_string(&webview_id)
|
||||
.unwrap()
|
||||
.to_string_lossy()
|
||||
.to_string();
|
||||
|
||||
let is_changing_configurations = env
|
||||
.call_method(&activity, "isChangingConfigurations", "()Z", &[])
|
||||
.unwrap()
|
||||
.z()
|
||||
.unwrap();
|
||||
|
||||
super::MainPipe::send(
|
||||
activity_id,
|
||||
super::WebViewMessage::OnDestroy {
|
||||
activity_id,
|
||||
webview_id,
|
||||
is_changing_configurations,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub unsafe fn handleRequest(
|
||||
mut env: JNIEnv,
|
||||
_: JClass,
|
||||
webview_id: JString,
|
||||
request: JObject,
|
||||
is_document_start_script_enabled: jboolean,
|
||||
) -> jobject {
|
||||
match handle_request(
|
||||
&mut env,
|
||||
webview_id,
|
||||
request,
|
||||
is_document_start_script_enabled,
|
||||
) {
|
||||
Ok(response) => response,
|
||||
Err(_e) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("Failed to handle request: {_e}");
|
||||
JObject::null().as_raw()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub unsafe fn shouldOverride(
|
||||
mut env: JNIEnv,
|
||||
_: JClass,
|
||||
webview_id: JString,
|
||||
url: JString,
|
||||
) -> jboolean {
|
||||
match env.get_string(&url) {
|
||||
Ok(url) => {
|
||||
let url = url.to_string_lossy().to_string();
|
||||
|
||||
let Ok(webview_id) = env.get_string(&webview_id) else {
|
||||
return false.into();
|
||||
};
|
||||
let webview_id = webview_id.to_str().ok().unwrap_or_default();
|
||||
|
||||
URL_LOADING_OVERRIDE
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(webview_id)
|
||||
// We negate the result of the function because the logic for the android
|
||||
// client is different from how the navigation_handler is defined.
|
||||
//
|
||||
// https://developer.android.com/reference/android/webkit/WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView,%20android.webkit.WebResourceRequest)
|
||||
.map(|f| !(f.handler)(url))
|
||||
.unwrap_or_default()
|
||||
}
|
||||
Err(_e) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("Failed to parse JString: {_e}");
|
||||
false
|
||||
}
|
||||
}
|
||||
.into()
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub unsafe fn onEval(mut env: JNIEnv, _: JClass, _webview_id: JString, id: jint, result: JString) {
|
||||
match env.get_string(&result) {
|
||||
Ok(result) => {
|
||||
if let Some(cb) = EVAL_CALLBACKS
|
||||
.get_or_init(Default::default)
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&id)
|
||||
{
|
||||
cb(result.into());
|
||||
}
|
||||
}
|
||||
Err(_e) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("Failed to parse JString: {_e}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub unsafe fn ipc(mut env: JNIEnv, _: JClass, webview_id: JString, url: JString, body: JString) {
|
||||
match (
|
||||
env.get_string(&url),
|
||||
env.get_string(&body),
|
||||
env.get_string(&webview_id),
|
||||
) {
|
||||
(Ok(url), Ok(body), Ok(webview_id)) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _span = tracing::info_span!(parent: None, "wry::ipc::handle").entered();
|
||||
|
||||
let url = url.to_string_lossy().to_string();
|
||||
let body = body.to_string_lossy().to_string();
|
||||
let webview_id = webview_id.to_string_lossy().to_string();
|
||||
if let Some(ipc) = IPC.lock().unwrap().get(&webview_id) {
|
||||
(ipc.handler)(Request::builder().uri(url).body(body).unwrap())
|
||||
}
|
||||
}
|
||||
(Err(_e), _, _) | (_, Err(_e), _) | (_, _, Err(_e)) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("Failed to parse JString: {_e}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub unsafe fn handleReceivedTitle(mut env: JNIEnv, _: JClass, webview_id: JString, title: JString) {
|
||||
match (env.get_string(&title), env.get_string(&webview_id)) {
|
||||
(Ok(title), Ok(webview_id)) => {
|
||||
let title = title.to_string_lossy().to_string();
|
||||
let webview_id = webview_id.to_string_lossy().to_string();
|
||||
if let Some(title_handler) = TITLE_CHANGE_HANDLER.lock().unwrap().get(&webview_id) {
|
||||
(title_handler.handler)(title)
|
||||
}
|
||||
}
|
||||
(Err(_e), _) | (_, Err(_e)) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("Failed to parse JString: {_e}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub unsafe fn withAssetLoader(mut env: JNIEnv, _: JClass, webview_id: JString) -> jboolean {
|
||||
let Ok(webview_id) = env.get_string(&webview_id) else {
|
||||
return false.into();
|
||||
};
|
||||
let webview_id = webview_id.to_str().ok().unwrap_or_default();
|
||||
(*WITH_ASSET_LOADER
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(webview_id)
|
||||
.unwrap_or(&false))
|
||||
.into()
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub unsafe fn assetLoaderDomain(mut env: JNIEnv, _: JClass, webview_id: JString) -> jstring {
|
||||
let Ok(webview_id) = env.get_string(&webview_id) else {
|
||||
return env.new_string("wry.assets").unwrap().as_raw();
|
||||
};
|
||||
let webview_id = webview_id.to_str().ok().unwrap_or_default();
|
||||
if let Some(domain) = ASSET_LOADER_DOMAIN.lock().unwrap().get(webview_id) {
|
||||
env.new_string(domain).unwrap().as_raw()
|
||||
} else {
|
||||
env.new_string("wry.assets").unwrap().as_raw()
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub unsafe fn onPageLoading(mut env: JNIEnv, _: JClass, webview_id: JString, url: JString) {
|
||||
match (env.get_string(&url), env.get_string(&webview_id)) {
|
||||
(Ok(url), Ok(webview_id)) => {
|
||||
let url = url.to_string_lossy().to_string();
|
||||
let webview_id = webview_id.to_string_lossy().to_string();
|
||||
if let Some(on_load) = ON_LOAD_HANDLER.lock().unwrap().get(&webview_id) {
|
||||
(on_load.handler)(PageLoadEvent::Started, url)
|
||||
}
|
||||
}
|
||||
(Err(_e), _) | (_, Err(_e)) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("Failed to parse JString: {_e}")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub unsafe fn onPageLoaded(mut env: JNIEnv, _: JClass, webview_id: JString, url: JString) {
|
||||
match (env.get_string(&url), env.get_string(&webview_id)) {
|
||||
(Ok(url), Ok(webview_id)) => {
|
||||
let url = url.to_string_lossy().to_string();
|
||||
let webview_id = webview_id.to_string_lossy().to_string();
|
||||
if let Some(on_load) = ON_LOAD_HANDLER.lock().unwrap().get(&webview_id) {
|
||||
(on_load.handler)(PageLoadEvent::Finished, url)
|
||||
}
|
||||
}
|
||||
(Err(_e), _) | (_, Err(_e)) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("Failed to parse JString: {_e}")
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+23
@@ -0,0 +1,23 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
@file:Suppress("unused")
|
||||
|
||||
package {{package}}
|
||||
|
||||
import android.webkit.*
|
||||
|
||||
class Ipc(val webView: RustWebView, val webViewClient: RustWebViewClient) {
|
||||
@JavascriptInterface
|
||||
fun postMessage(message: String?) {
|
||||
message?.let {m ->
|
||||
// we're not using WebView::getUrl() here because it needs to be executed on the main thread
|
||||
// and it would slow down the Ipc
|
||||
// so instead we track the current URL on the webview client
|
||||
Rust.ipc(webView.id, webViewClient.currentUrl, m)
|
||||
}
|
||||
}
|
||||
|
||||
{{class-extension}}
|
||||
}
|
||||
+87
@@ -0,0 +1,87 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
@file:Suppress("unused", "MemberVisibilityCanBePrivate")
|
||||
|
||||
package {{package}}
|
||||
|
||||
// taken from https://github.com/ionic-team/capacitor/blob/6658bca41e78239347e458175b14ca8bd5c1d6e8/android/capacitor/src/main/java/com/getcapacitor/Logger.java
|
||||
|
||||
import android.text.TextUtils
|
||||
import android.util.Log
|
||||
|
||||
class Logger {
|
||||
companion object {
|
||||
private const val LOG_TAG_CORE = "Tauri"
|
||||
|
||||
fun tags(vararg subtags: String): String {
|
||||
return if (subtags.isNotEmpty()) {
|
||||
LOG_TAG_CORE + "/" + TextUtils.join("/", subtags)
|
||||
} else LOG_TAG_CORE
|
||||
}
|
||||
|
||||
fun verbose(message: String) {
|
||||
verbose(LOG_TAG_CORE, message)
|
||||
}
|
||||
|
||||
private fun verbose(tag: String, message: String) {
|
||||
if (!shouldLog()) {
|
||||
return
|
||||
}
|
||||
Log.v(tag, message)
|
||||
}
|
||||
|
||||
fun debug(message: String) {
|
||||
debug(LOG_TAG_CORE, message)
|
||||
}
|
||||
|
||||
fun debug(tag: String, message: String) {
|
||||
if (!shouldLog()) {
|
||||
return
|
||||
}
|
||||
Log.d(tag, message)
|
||||
}
|
||||
|
||||
fun info(message: String) {
|
||||
info(LOG_TAG_CORE, message)
|
||||
}
|
||||
|
||||
fun info(tag: String, message: String) {
|
||||
if (!shouldLog()) {
|
||||
return
|
||||
}
|
||||
Log.i(tag, message)
|
||||
}
|
||||
|
||||
fun warn(message: String) {
|
||||
warn(LOG_TAG_CORE, message)
|
||||
}
|
||||
|
||||
fun warn(tag: String, message: String) {
|
||||
if (!shouldLog()) {
|
||||
return
|
||||
}
|
||||
Log.w(tag, message)
|
||||
}
|
||||
|
||||
fun error(message: String) {
|
||||
error(LOG_TAG_CORE, message, null)
|
||||
}
|
||||
|
||||
fun error(message: String, e: Throwable?) {
|
||||
error(LOG_TAG_CORE, message, e)
|
||||
}
|
||||
|
||||
fun error(tag: String, message: String, e: Throwable?) {
|
||||
if (!shouldLog()) {
|
||||
return
|
||||
}
|
||||
Log.e(tag, message, e)
|
||||
}
|
||||
|
||||
private fun shouldLog(): Boolean {
|
||||
return BuildConfig.DEBUG
|
||||
}
|
||||
}
|
||||
}
|
||||
+115
@@ -0,0 +1,115 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package {{package}}
|
||||
|
||||
// taken from https://github.com/ionic-team/capacitor/blob/6658bca41e78239347e458175b14ca8bd5c1d6e8/android/capacitor/src/main/java/com/getcapacitor/PermissionHelper.java
|
||||
|
||||
import android.content.Context
|
||||
import android.content.pm.PackageManager
|
||||
import android.os.Build
|
||||
import androidx.core.app.ActivityCompat
|
||||
import java.util.ArrayList
|
||||
|
||||
object PermissionHelper {
|
||||
/**
|
||||
* Checks if a list of given permissions are all granted by the user
|
||||
*
|
||||
* @param permissions Permissions to check.
|
||||
* @return True if all permissions are granted, false if at least one is not.
|
||||
*/
|
||||
fun hasPermissions(context: Context?, permissions: Array<String>): Boolean {
|
||||
for (perm in permissions) {
|
||||
if (ActivityCompat.checkSelfPermission(
|
||||
context!!,
|
||||
perm
|
||||
) != PackageManager.PERMISSION_GRANTED
|
||||
) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether the given permission has been defined in the AndroidManifest.xml
|
||||
*
|
||||
* @param permission A permission to check.
|
||||
* @return True if the permission has been defined in the Manifest, false if not.
|
||||
*/
|
||||
fun hasDefinedPermission(context: Context, permission: String): Boolean {
|
||||
var hasPermission = false
|
||||
val requestedPermissions = getManifestPermissions(context)
|
||||
if (!requestedPermissions.isNullOrEmpty()) {
|
||||
val requestedPermissionsList = listOf(*requestedPermissions)
|
||||
val requestedPermissionsArrayList = ArrayList(requestedPermissionsList)
|
||||
if (requestedPermissionsArrayList.contains(permission)) {
|
||||
hasPermission = true
|
||||
}
|
||||
}
|
||||
return hasPermission
|
||||
}
|
||||
|
||||
/**
|
||||
* Check whether all of the given permissions have been defined in the AndroidManifest.xml
|
||||
* @param context the app context
|
||||
* @param permissions a list of permissions
|
||||
* @return true only if all permissions are defined in the AndroidManifest.xml
|
||||
*/
|
||||
fun hasDefinedPermissions(context: Context, permissions: Array<String>): Boolean {
|
||||
for (permission in permissions) {
|
||||
if (!hasDefinedPermission(context, permission)) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Get the permissions defined in AndroidManifest.xml
|
||||
*
|
||||
* @return The permissions defined in AndroidManifest.xml
|
||||
*/
|
||||
private fun getManifestPermissions(context: Context): Array<String>? {
|
||||
var requestedPermissions: Array<String>? = null
|
||||
try {
|
||||
val pm = context.packageManager
|
||||
val packageInfo = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
|
||||
pm.getPackageInfo(context.packageName, PackageManager.PackageInfoFlags.of(PackageManager.GET_PERMISSIONS.toLong()))
|
||||
} else {
|
||||
@Suppress("DEPRECATION")
|
||||
pm.getPackageInfo(context.packageName, PackageManager.GET_PERMISSIONS)
|
||||
}
|
||||
if (packageInfo != null) {
|
||||
requestedPermissions = packageInfo.requestedPermissions
|
||||
}
|
||||
} catch (_: Exception) {
|
||||
}
|
||||
return requestedPermissions
|
||||
}
|
||||
|
||||
/**
|
||||
* Given a list of permissions, return a new list with the ones not present in AndroidManifest.xml
|
||||
*
|
||||
* @param neededPermissions The permissions needed.
|
||||
* @return The permissions not present in AndroidManifest.xml
|
||||
*/
|
||||
fun getUndefinedPermissions(context: Context, neededPermissions: Array<String?>): Array<String?> {
|
||||
val undefinedPermissions = ArrayList<String?>()
|
||||
val requestedPermissions = getManifestPermissions(context)
|
||||
if (!requestedPermissions.isNullOrEmpty()) {
|
||||
val requestedPermissionsList = listOf(*requestedPermissions)
|
||||
val requestedPermissionsArrayList = ArrayList(requestedPermissionsList)
|
||||
for (permission in neededPermissions) {
|
||||
if (!requestedPermissionsArrayList.contains(permission)) {
|
||||
undefinedPermissions.add(permission)
|
||||
}
|
||||
}
|
||||
var undefinedPermissionArray = arrayOfNulls<String>(undefinedPermissions.size)
|
||||
undefinedPermissionArray = undefinedPermissions.toArray(undefinedPermissionArray)
|
||||
return undefinedPermissionArray
|
||||
}
|
||||
return neededPermissions
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
@file:Suppress("unused")
|
||||
|
||||
package {{package}}
|
||||
|
||||
import android.content.Intent
|
||||
import android.webkit.WebView
|
||||
import android.webkit.WebResourceRequest
|
||||
import android.webkit.WebResourceResponse
|
||||
|
||||
object Rust {
|
||||
init {
|
||||
System.loadLibrary("{{library}}")
|
||||
}
|
||||
|
||||
@JvmStatic external fun onActivityCreate(activity: WryActivity)
|
||||
@JvmStatic external fun onActivityDestroy(activity: WryActivity)
|
||||
@JvmStatic external fun onActivitySaveInstanceState()
|
||||
@JvmStatic external fun onActivityLowMemory()
|
||||
@JvmStatic external fun onWindowFocusChanged(activity: WryActivity, focus: Boolean)
|
||||
@JvmStatic external fun onNewIntent(intent: Intent)
|
||||
|
||||
@JvmStatic external fun create()
|
||||
@JvmStatic external fun start()
|
||||
@JvmStatic external fun resume()
|
||||
@JvmStatic external fun pause()
|
||||
@JvmStatic external fun stop()
|
||||
|
||||
@JvmStatic external fun wryCreate()
|
||||
@JvmStatic external fun onWebviewDestroy(activity: WryActivity, webviewId: String)
|
||||
|
||||
@JvmStatic external fun ipc(webviewId: String, url: String, message: String)
|
||||
|
||||
@JvmStatic external fun assetLoaderDomain(webviewId: String): String
|
||||
@JvmStatic external fun withAssetLoader(webviewId: String): Boolean
|
||||
@JvmStatic external fun handleRequest(webviewId: String, request: WebResourceRequest, isDocumentStartScriptEnabled: Boolean): WebResourceResponse?
|
||||
@JvmStatic external fun shouldOverride(webviewId: String, url: String): Boolean
|
||||
@JvmStatic external fun onPageLoading(webviewId: String, url: String)
|
||||
@JvmStatic external fun onPageLoaded(webviewId: String, url: String)
|
||||
@JvmStatic external fun onEval(webviewId: String, id: Int, result: String)
|
||||
|
||||
@JvmStatic external fun handleReceivedTitle(webviewId: String, title: String)
|
||||
}
|
||||
@@ -0,0 +1,491 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
@file:Suppress("ObsoleteSdkInt", "RedundantOverride", "QueryPermissionsNeeded", "SimpleDateFormat")
|
||||
|
||||
package {{package}}
|
||||
|
||||
// taken from https://github.com/ionic-team/capacitor/blob/6658bca41e78239347e458175b14ca8bd5c1d6e8/android/capacitor/src/main/java/com/getcapacitor/BridgeWebChromeClient.java
|
||||
|
||||
import android.Manifest
|
||||
import android.app.Activity
|
||||
import android.app.AlertDialog
|
||||
import android.content.ActivityNotFoundException
|
||||
import android.content.DialogInterface
|
||||
import android.content.Intent
|
||||
import android.net.Uri
|
||||
import android.os.Build
|
||||
import android.os.Environment
|
||||
import android.provider.MediaStore
|
||||
import android.view.View
|
||||
import android.webkit.*
|
||||
import android.widget.EditText
|
||||
import androidx.activity.result.ActivityResult
|
||||
import androidx.activity.result.ActivityResultCallback
|
||||
import androidx.activity.result.ActivityResultLauncher
|
||||
import androidx.activity.result.contract.ActivityResultContracts
|
||||
import androidx.core.content.FileProvider
|
||||
import java.io.File
|
||||
import java.io.IOException
|
||||
import java.text.SimpleDateFormat
|
||||
import java.util.*
|
||||
|
||||
class RustWebChromeClient(appActivity: WryActivity) : WebChromeClient() {
|
||||
private interface PermissionListener {
|
||||
fun onPermissionSelect(isGranted: Boolean?)
|
||||
}
|
||||
|
||||
private interface ActivityResultListener {
|
||||
fun onActivityResult(result: ActivityResult?)
|
||||
}
|
||||
|
||||
private val activity: WryActivity
|
||||
private var permissionLauncher: ActivityResultLauncher<Array<String>>
|
||||
private var activityLauncher: ActivityResultLauncher<Intent>
|
||||
private var permissionListener: PermissionListener? = null
|
||||
private var activityListener: ActivityResultListener? = null
|
||||
|
||||
init {
|
||||
activity = appActivity
|
||||
val permissionCallback =
|
||||
ActivityResultCallback { isGranted: Map<String, Boolean> ->
|
||||
if (permissionListener != null) {
|
||||
var granted = true
|
||||
for ((_, value) in isGranted) {
|
||||
if (!value) granted = false
|
||||
}
|
||||
permissionListener!!.onPermissionSelect(granted)
|
||||
}
|
||||
}
|
||||
permissionLauncher =
|
||||
activity.registerForActivityResult(ActivityResultContracts.RequestMultiplePermissions(), permissionCallback)
|
||||
activityLauncher = activity.registerForActivityResult(
|
||||
ActivityResultContracts.StartActivityForResult()
|
||||
) { result ->
|
||||
if (activityListener != null) {
|
||||
activityListener!!.onActivityResult(result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Render web content in `view`.
|
||||
*
|
||||
* Both this method and [.onHideCustomView] are required for
|
||||
* rendering web content in full screen.
|
||||
*
|
||||
* @see [](https://developer.android.com/reference/android/webkit/WebChromeClient.onShowCustomView
|
||||
) */
|
||||
override fun onShowCustomView(view: View, callback: CustomViewCallback) {
|
||||
callback.onCustomViewHidden()
|
||||
super.onShowCustomView(view, callback)
|
||||
}
|
||||
|
||||
/**
|
||||
* Render web content in the original Web View again.
|
||||
*
|
||||
* Do not remove this method--@see #onShowCustomView(View, CustomViewCallback).
|
||||
*/
|
||||
override fun onHideCustomView() {
|
||||
super.onHideCustomView()
|
||||
}
|
||||
|
||||
override fun onPermissionRequest(request: PermissionRequest) {
|
||||
val isRequestPermissionRequired = Build.VERSION.SDK_INT >= Build.VERSION_CODES.M
|
||||
val permissionList: MutableList<String> = ArrayList()
|
||||
if (listOf(*request.resources).contains("android.webkit.resource.VIDEO_CAPTURE")) {
|
||||
permissionList.add(Manifest.permission.CAMERA)
|
||||
}
|
||||
if (listOf(*request.resources).contains("android.webkit.resource.AUDIO_CAPTURE")) {
|
||||
permissionList.add(Manifest.permission.MODIFY_AUDIO_SETTINGS)
|
||||
permissionList.add(Manifest.permission.RECORD_AUDIO)
|
||||
}
|
||||
if (permissionList.isNotEmpty() && isRequestPermissionRequired) {
|
||||
val permissions = permissionList.toTypedArray()
|
||||
permissionListener = object : PermissionListener {
|
||||
override fun onPermissionSelect(isGranted: Boolean?) {
|
||||
if (isGranted == true) {
|
||||
request.grant(request.resources)
|
||||
} else {
|
||||
request.deny()
|
||||
}
|
||||
}
|
||||
}
|
||||
permissionLauncher.launch(permissions)
|
||||
} else {
|
||||
request.grant(request.resources)
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the browser alert modal
|
||||
* @param view
|
||||
* @param url
|
||||
* @param message
|
||||
* @param result
|
||||
* @return
|
||||
*/
|
||||
override fun onJsAlert(view: WebView, url: String, message: String, result: JsResult): Boolean {
|
||||
if (activity.isFinishing) {
|
||||
return true
|
||||
}
|
||||
val builder = AlertDialog.Builder(view.context)
|
||||
builder
|
||||
.setMessage(message)
|
||||
.setPositiveButton(
|
||||
"OK"
|
||||
) { dialog: DialogInterface, _: Int ->
|
||||
dialog.dismiss()
|
||||
result.confirm()
|
||||
}
|
||||
.setOnCancelListener { dialog: DialogInterface ->
|
||||
dialog.dismiss()
|
||||
result.cancel()
|
||||
}
|
||||
val dialog = builder.create()
|
||||
dialog.show()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the browser confirm modal
|
||||
* @param view
|
||||
* @param url
|
||||
* @param message
|
||||
* @param result
|
||||
* @return
|
||||
*/
|
||||
override fun onJsConfirm(view: WebView, url: String, message: String, result: JsResult): Boolean {
|
||||
if (activity.isFinishing) {
|
||||
return true
|
||||
}
|
||||
val builder = AlertDialog.Builder(view.context)
|
||||
builder
|
||||
.setMessage(message)
|
||||
.setPositiveButton(
|
||||
"OK"
|
||||
) { dialog: DialogInterface, _: Int ->
|
||||
dialog.dismiss()
|
||||
result.confirm()
|
||||
}
|
||||
.setNegativeButton(
|
||||
"Cancel"
|
||||
) { dialog: DialogInterface, _: Int ->
|
||||
dialog.dismiss()
|
||||
result.cancel()
|
||||
}
|
||||
.setOnCancelListener { dialog: DialogInterface ->
|
||||
dialog.dismiss()
|
||||
result.cancel()
|
||||
}
|
||||
val dialog = builder.create()
|
||||
dialog.show()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Show the browser prompt modal
|
||||
* @param view
|
||||
* @param url
|
||||
* @param message
|
||||
* @param defaultValue
|
||||
* @param result
|
||||
* @return
|
||||
*/
|
||||
override fun onJsPrompt(
|
||||
view: WebView,
|
||||
url: String,
|
||||
message: String,
|
||||
defaultValue: String,
|
||||
result: JsPromptResult
|
||||
): Boolean {
|
||||
if (activity.isFinishing) {
|
||||
return true
|
||||
}
|
||||
val builder = AlertDialog.Builder(view.context)
|
||||
val input = EditText(view.context)
|
||||
builder
|
||||
.setMessage(message)
|
||||
.setView(input)
|
||||
.setPositiveButton(
|
||||
"OK"
|
||||
) { dialog: DialogInterface, _: Int ->
|
||||
dialog.dismiss()
|
||||
val inputText1 = input.text.toString().trim { it <= ' ' }
|
||||
result.confirm(inputText1)
|
||||
}
|
||||
.setNegativeButton(
|
||||
"Cancel"
|
||||
) { dialog: DialogInterface, _: Int ->
|
||||
dialog.dismiss()
|
||||
result.cancel()
|
||||
}
|
||||
.setOnCancelListener { dialog: DialogInterface ->
|
||||
dialog.dismiss()
|
||||
result.cancel()
|
||||
}
|
||||
val dialog = builder.create()
|
||||
dialog.show()
|
||||
return true
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle the browser geolocation permission prompt
|
||||
* @param origin
|
||||
* @param callback
|
||||
*/
|
||||
override fun onGeolocationPermissionsShowPrompt(
|
||||
origin: String,
|
||||
callback: GeolocationPermissions.Callback
|
||||
) {
|
||||
super.onGeolocationPermissionsShowPrompt(origin, callback)
|
||||
Logger.debug("onGeolocationPermissionsShowPrompt: DOING IT HERE FOR ORIGIN: $origin")
|
||||
val geoPermissions =
|
||||
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)
|
||||
if (!PermissionHelper.hasPermissions(activity, geoPermissions)) {
|
||||
permissionListener = object : PermissionListener {
|
||||
override fun onPermissionSelect(isGranted: Boolean?) {
|
||||
if (isGranted == true) {
|
||||
callback.invoke(origin, true, false)
|
||||
} else {
|
||||
val coarsePermission =
|
||||
arrayOf(Manifest.permission.ACCESS_COARSE_LOCATION)
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S &&
|
||||
PermissionHelper.hasPermissions(activity, coarsePermission)
|
||||
) {
|
||||
callback.invoke(origin, true, false)
|
||||
} else {
|
||||
callback.invoke(origin, false, false)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
permissionLauncher.launch(geoPermissions)
|
||||
} else {
|
||||
// permission is already granted
|
||||
callback.invoke(origin, true, false)
|
||||
Logger.debug("onGeolocationPermissionsShowPrompt: has required permission")
|
||||
}
|
||||
}
|
||||
|
||||
override fun onShowFileChooser(
|
||||
webView: WebView,
|
||||
filePathCallback: ValueCallback<Array<Uri?>?>,
|
||||
fileChooserParams: FileChooserParams
|
||||
): Boolean {
|
||||
val acceptTypes = listOf(*fileChooserParams.acceptTypes)
|
||||
val captureEnabled = fileChooserParams.isCaptureEnabled
|
||||
val capturePhoto = captureEnabled && acceptTypes.contains("image/*")
|
||||
val captureVideo = captureEnabled && acceptTypes.contains("video/*")
|
||||
if (capturePhoto || captureVideo) {
|
||||
if (isMediaCaptureSupported) {
|
||||
showMediaCaptureOrFilePicker(filePathCallback, fileChooserParams, captureVideo)
|
||||
} else {
|
||||
permissionListener = object : PermissionListener {
|
||||
override fun onPermissionSelect(isGranted: Boolean?) {
|
||||
if (isGranted == true) {
|
||||
showMediaCaptureOrFilePicker(filePathCallback, fileChooserParams, captureVideo)
|
||||
} else {
|
||||
Logger.warn(Logger.tags("FileChooser"), "Camera permission not granted")
|
||||
filePathCallback.onReceiveValue(null)
|
||||
}
|
||||
}
|
||||
}
|
||||
val camPermission = arrayOf(Manifest.permission.CAMERA)
|
||||
permissionLauncher.launch(camPermission)
|
||||
}
|
||||
} else {
|
||||
showFilePicker(filePathCallback, fileChooserParams)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private val isMediaCaptureSupported: Boolean
|
||||
get() {
|
||||
val permissions = arrayOf(Manifest.permission.CAMERA)
|
||||
return PermissionHelper.hasPermissions(activity, permissions) ||
|
||||
!PermissionHelper.hasDefinedPermission(activity, Manifest.permission.CAMERA)
|
||||
}
|
||||
|
||||
private fun showMediaCaptureOrFilePicker(
|
||||
filePathCallback: ValueCallback<Array<Uri?>?>,
|
||||
fileChooserParams: FileChooserParams,
|
||||
isVideo: Boolean
|
||||
) {
|
||||
val isVideoCaptureSupported = true
|
||||
val shown = if (isVideo && isVideoCaptureSupported) {
|
||||
showVideoCapturePicker(filePathCallback)
|
||||
} else {
|
||||
showImageCapturePicker(filePathCallback)
|
||||
}
|
||||
if (!shown) {
|
||||
Logger.warn(
|
||||
Logger.tags("FileChooser"),
|
||||
"Media capture intent could not be launched. Falling back to default file picker."
|
||||
)
|
||||
showFilePicker(filePathCallback, fileChooserParams)
|
||||
}
|
||||
}
|
||||
|
||||
private fun showImageCapturePicker(filePathCallback: ValueCallback<Array<Uri?>?>): Boolean {
|
||||
val takePictureIntent = Intent(MediaStore.ACTION_IMAGE_CAPTURE)
|
||||
if (takePictureIntent.resolveActivity(activity.packageManager) == null) {
|
||||
return false
|
||||
}
|
||||
val imageFileUri: Uri = try {
|
||||
createImageFileUri()
|
||||
} catch (ex: Exception) {
|
||||
Logger.error("Unable to create temporary media capture file: " + ex.message)
|
||||
return false
|
||||
}
|
||||
takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageFileUri)
|
||||
activityListener = object : ActivityResultListener {
|
||||
override fun onActivityResult(result: ActivityResult?) {
|
||||
var res: Array<Uri?>? = null
|
||||
if (result?.resultCode == Activity.RESULT_OK) {
|
||||
res = arrayOf(imageFileUri)
|
||||
}
|
||||
filePathCallback.onReceiveValue(res)
|
||||
}
|
||||
}
|
||||
activityLauncher.launch(takePictureIntent)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun showVideoCapturePicker(filePathCallback: ValueCallback<Array<Uri?>?>): Boolean {
|
||||
val takeVideoIntent = Intent(MediaStore.ACTION_VIDEO_CAPTURE)
|
||||
if (takeVideoIntent.resolveActivity(activity.packageManager) == null) {
|
||||
return false
|
||||
}
|
||||
activityListener = object : ActivityResultListener {
|
||||
override fun onActivityResult(result: ActivityResult?) {
|
||||
var res: Array<Uri?>? = null
|
||||
if (result?.resultCode == Activity.RESULT_OK) {
|
||||
res = arrayOf(result.data!!.data)
|
||||
}
|
||||
filePathCallback.onReceiveValue(res)
|
||||
}
|
||||
}
|
||||
activityLauncher.launch(takeVideoIntent)
|
||||
return true
|
||||
}
|
||||
|
||||
private fun showFilePicker(
|
||||
filePathCallback: ValueCallback<Array<Uri?>?>,
|
||||
fileChooserParams: FileChooserParams
|
||||
) {
|
||||
val intent = fileChooserParams.createIntent()
|
||||
if (fileChooserParams.mode == FileChooserParams.MODE_OPEN_MULTIPLE) {
|
||||
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true)
|
||||
}
|
||||
if (fileChooserParams.acceptTypes.size > 1 || intent.type!!.startsWith(".")) {
|
||||
val validTypes = getValidTypes(fileChooserParams.acceptTypes)
|
||||
intent.putExtra(Intent.EXTRA_MIME_TYPES, validTypes)
|
||||
if (intent.type!!.startsWith(".")) {
|
||||
intent.type = validTypes[0]
|
||||
}
|
||||
}
|
||||
try {
|
||||
activityListener = object : ActivityResultListener {
|
||||
override fun onActivityResult(result: ActivityResult?) {
|
||||
val res: Array<Uri?>?
|
||||
val resultIntent = result?.data
|
||||
if (result?.resultCode == Activity.RESULT_OK && resultIntent!!.clipData != null) {
|
||||
val numFiles = resultIntent.clipData!!.itemCount
|
||||
res = arrayOfNulls(numFiles)
|
||||
for (i in 0 until numFiles) {
|
||||
res[i] = resultIntent.clipData!!.getItemAt(i).uri
|
||||
}
|
||||
} else {
|
||||
res = FileChooserParams.parseResult(
|
||||
result?.resultCode ?: 0,
|
||||
resultIntent
|
||||
)
|
||||
}
|
||||
filePathCallback.onReceiveValue(res)
|
||||
}
|
||||
}
|
||||
activityLauncher.launch(intent)
|
||||
} catch (e: ActivityNotFoundException) {
|
||||
filePathCallback.onReceiveValue(null)
|
||||
}
|
||||
}
|
||||
|
||||
private fun getValidTypes(currentTypes: Array<String>): Array<String> {
|
||||
val validTypes: MutableList<String> = ArrayList()
|
||||
val mtm = MimeTypeMap.getSingleton()
|
||||
for (mime in currentTypes) {
|
||||
if (mime.startsWith(".")) {
|
||||
val extension = mime.substring(1)
|
||||
val extensionMime = mtm.getMimeTypeFromExtension(extension)
|
||||
if (extensionMime != null && !validTypes.contains(extensionMime)) {
|
||||
validTypes.add(extensionMime)
|
||||
}
|
||||
} else if (!validTypes.contains(mime)) {
|
||||
validTypes.add(mime)
|
||||
}
|
||||
}
|
||||
val validObj: Array<Any> = validTypes.toTypedArray()
|
||||
return Arrays.copyOf(
|
||||
validObj, validObj.size,
|
||||
Array<String>::class.java
|
||||
)
|
||||
}
|
||||
|
||||
override fun onConsoleMessage(consoleMessage: ConsoleMessage): Boolean {
|
||||
val tag: String = Logger.tags("Console")
|
||||
if (consoleMessage.message() != null && isValidMsg(consoleMessage.message())) {
|
||||
val msg = String.format(
|
||||
"File: %s - Line %d - Msg: %s",
|
||||
consoleMessage.sourceId(),
|
||||
consoleMessage.lineNumber(),
|
||||
consoleMessage.message()
|
||||
)
|
||||
val level = consoleMessage.messageLevel().name
|
||||
if ("ERROR".equals(level, ignoreCase = true)) {
|
||||
Logger.error(tag, msg, null)
|
||||
} else if ("WARNING".equals(level, ignoreCase = true)) {
|
||||
Logger.warn(tag, msg)
|
||||
} else if ("TIP".equals(level, ignoreCase = true)) {
|
||||
Logger.debug(tag, msg)
|
||||
} else {
|
||||
Logger.info(tag, msg)
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
private fun isValidMsg(msg: String): Boolean {
|
||||
return !(msg.contains("%cresult %c") ||
|
||||
msg.contains("%cnative %c") ||
|
||||
msg.equals("[object Object]", ignoreCase = true) ||
|
||||
msg.equals("console.groupEnd", ignoreCase = true))
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
private fun createImageFileUri(): Uri {
|
||||
val photoFile = createImageFile(activity)
|
||||
return FileProvider.getUriForFile(
|
||||
activity,
|
||||
activity.packageName.toString() + ".fileprovider",
|
||||
photoFile
|
||||
)
|
||||
}
|
||||
|
||||
@Throws(IOException::class)
|
||||
private fun createImageFile(activity: Activity): File {
|
||||
// Create an image file name
|
||||
val timeStamp = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
|
||||
val imageFileName = "JPEG_" + timeStamp + "_"
|
||||
val storageDir = activity.getExternalFilesDir(Environment.DIRECTORY_PICTURES)
|
||||
return File.createTempFile(imageFileName, ".jpg", storageDir)
|
||||
}
|
||||
|
||||
override fun onReceivedTitle(
|
||||
view: WebView,
|
||||
title: String
|
||||
) {
|
||||
Rust.handleReceivedTitle((view as RustWebView).id, title)
|
||||
}
|
||||
}
|
||||
+96
@@ -0,0 +1,96 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
@file:Suppress("unused", "SetJavaScriptEnabled")
|
||||
|
||||
package {{package}}
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.webkit.*
|
||||
import android.content.Context
|
||||
import androidx.webkit.WebViewCompat
|
||||
import androidx.webkit.WebViewFeature
|
||||
import kotlin.collections.Map
|
||||
|
||||
@SuppressLint("RestrictedApi")
|
||||
class RustWebView(context: Context, val initScripts: Array<String>, val id: String): WebView(context) {
|
||||
val isDocumentStartScriptEnabled: Boolean
|
||||
|
||||
init {
|
||||
settings.javaScriptEnabled = true
|
||||
settings.domStorageEnabled = true
|
||||
settings.setGeolocationEnabled(true)
|
||||
settings.databaseEnabled = true
|
||||
settings.mediaPlaybackRequiresUserGesture = false
|
||||
settings.javaScriptCanOpenWindowsAutomatically = true
|
||||
|
||||
if (WebViewFeature.isFeatureSupported(WebViewFeature.DOCUMENT_START_SCRIPT)) {
|
||||
isDocumentStartScriptEnabled = true
|
||||
for (script in initScripts) {
|
||||
WebViewCompat.addDocumentStartJavaScript(this, script, setOf("*"));
|
||||
}
|
||||
} else {
|
||||
isDocumentStartScriptEnabled = false
|
||||
}
|
||||
|
||||
{{class-init}}
|
||||
}
|
||||
|
||||
fun loadUrlMainThread(url: String) {
|
||||
post {
|
||||
loadUrl(url)
|
||||
}
|
||||
}
|
||||
|
||||
fun loadUrlMainThread(url: String, additionalHttpHeaders: Map<String, String>) {
|
||||
post {
|
||||
loadUrl(url, additionalHttpHeaders)
|
||||
}
|
||||
}
|
||||
|
||||
override fun loadUrl(url: String) {
|
||||
if (!Rust.shouldOverride(id, url)) {
|
||||
super.loadUrl(url);
|
||||
}
|
||||
}
|
||||
|
||||
override fun loadUrl(url: String, additionalHttpHeaders: Map<String, String>) {
|
||||
if (!Rust.shouldOverride(id, url)) {
|
||||
super.loadUrl(url, additionalHttpHeaders);
|
||||
}
|
||||
}
|
||||
|
||||
fun loadHTMLMainThread(html: String) {
|
||||
post {
|
||||
super.loadData(html, "text/html", null)
|
||||
}
|
||||
}
|
||||
|
||||
fun evalScript(id: Int, script: String) {
|
||||
post {
|
||||
super.evaluateJavascript(script) { result ->
|
||||
Rust.onEval(this.id, id, result)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fun clearAllBrowsingData() {
|
||||
try {
|
||||
super.getContext().deleteDatabase("webviewCache.db")
|
||||
super.getContext().deleteDatabase("webview.db")
|
||||
super.clearCache(true)
|
||||
super.clearHistory()
|
||||
super.clearFormData()
|
||||
} catch (ex: Exception) {
|
||||
Logger.error("Unable to create temporary media capture file: " + ex.message)
|
||||
}
|
||||
}
|
||||
|
||||
fun getCookies(url: String): String {
|
||||
val cookieManager = CookieManager.getInstance()
|
||||
return cookieManager.getCookie(url)
|
||||
}
|
||||
|
||||
{{class-extension}}
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package {{package}}
|
||||
|
||||
import android.net.Uri
|
||||
import android.webkit.*
|
||||
import android.content.Context
|
||||
import android.graphics.Bitmap
|
||||
import android.os.Handler
|
||||
import android.os.Looper
|
||||
import androidx.webkit.WebViewAssetLoader
|
||||
|
||||
class RustWebViewClient(webView: RustWebView, context: Context): WebViewClient() {
|
||||
private val interceptedState = mutableMapOf<String, Boolean>()
|
||||
var currentUrl: String = "about:blank"
|
||||
private var lastInterceptedUrl: Uri? = null
|
||||
private var pendingUrlRedirect: String? = null
|
||||
|
||||
private val assetLoader = WebViewAssetLoader.Builder()
|
||||
.setDomain(Rust.assetLoaderDomain(webView.id))
|
||||
.addPathHandler("/", WebViewAssetLoader.AssetsPathHandler(context))
|
||||
.build()
|
||||
|
||||
override fun shouldInterceptRequest(
|
||||
view: WebView,
|
||||
request: WebResourceRequest
|
||||
): WebResourceResponse? {
|
||||
pendingUrlRedirect?.let {
|
||||
Handler(Looper.getMainLooper()).post {
|
||||
view.loadUrl(it)
|
||||
}
|
||||
pendingUrlRedirect = null
|
||||
return null
|
||||
}
|
||||
|
||||
lastInterceptedUrl = request.url
|
||||
return if (Rust.withAssetLoader((view as RustWebView).id)) {
|
||||
assetLoader.shouldInterceptRequest(request.url)
|
||||
} else {
|
||||
val response = Rust.handleRequest(view.id, request, view.isDocumentStartScriptEnabled)
|
||||
if (response != null) {
|
||||
if (response.responseHeaders != null) {
|
||||
response.responseHeaders["Cache-Control"] = "no-store"
|
||||
} else {
|
||||
response.responseHeaders = mapOf("Cache-Control" to "no-store")
|
||||
}
|
||||
}
|
||||
interceptedState[request.url.toString()] = response != null
|
||||
return response
|
||||
}
|
||||
}
|
||||
|
||||
override fun shouldOverrideUrlLoading(
|
||||
view: WebView,
|
||||
request: WebResourceRequest
|
||||
): Boolean {
|
||||
return Rust.shouldOverride((view as RustWebView).id, request.url.toString())
|
||||
}
|
||||
|
||||
override fun onPageStarted(view: WebView, url: String, favicon: Bitmap?) {
|
||||
currentUrl = url
|
||||
if (interceptedState[url] == false) {
|
||||
val webView = view as RustWebView
|
||||
for (script in webView.initScripts) {
|
||||
view.evaluateJavascript(script, null)
|
||||
}
|
||||
}
|
||||
return Rust.onPageLoading((view as RustWebView).id, url)
|
||||
}
|
||||
|
||||
override fun onPageFinished(view: WebView, url: String) {
|
||||
Rust.onPageLoaded((view as RustWebView).id, url)
|
||||
}
|
||||
|
||||
override fun onReceivedError(
|
||||
view: WebView,
|
||||
request: WebResourceRequest,
|
||||
error: WebResourceError
|
||||
) {
|
||||
// we get a net::ERR_CONNECTION_REFUSED when an external URL redirects to a custom protocol
|
||||
// e.g. oauth flow, because shouldInterceptRequest is not called on redirects
|
||||
// so we must force retry here with loadUrl() to get a chance of the custom protocol to kick in
|
||||
if (error.errorCode == ERROR_CONNECT && request.isForMainFrame && request.url != lastInterceptedUrl) {
|
||||
// prevent the default error page from showing
|
||||
view.stopLoading()
|
||||
// without this initial loadUrl the app is stuck
|
||||
view.loadUrl(request.url.toString())
|
||||
// ensure the URL is actually loaded - for some reason there's a race condition and we need to call loadUrl() again later
|
||||
pendingUrlRedirect = request.url.toString()
|
||||
} else {
|
||||
super.onReceivedError(view, request, error)
|
||||
}
|
||||
}
|
||||
|
||||
{{class-extension}}
|
||||
}
|
||||
+173
@@ -0,0 +1,173 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
package {{package}}
|
||||
|
||||
import android.annotation.SuppressLint
|
||||
import android.content.Intent
|
||||
import android.os.Build
|
||||
import android.os.Bundle
|
||||
import android.webkit.WebView
|
||||
import android.view.KeyEvent
|
||||
import androidx.activity.OnBackPressedCallback
|
||||
import androidx.appcompat.app.AppCompatActivity
|
||||
import androidx.lifecycle.DefaultLifecycleObserver
|
||||
import androidx.lifecycle.LifecycleOwner
|
||||
import androidx.lifecycle.ProcessLifecycleOwner
|
||||
|
||||
private val ACTIVITY_ID_KEY = "__wryActivityId"
|
||||
|
||||
object WryLifecycleObserver : DefaultLifecycleObserver {
|
||||
override fun onCreate(owner: LifecycleOwner) {
|
||||
super.onCreate(owner)
|
||||
Rust.create()
|
||||
Rust.wryCreate()
|
||||
}
|
||||
|
||||
override fun onStart(owner: LifecycleOwner) {
|
||||
super.onStart(owner)
|
||||
Rust.start()
|
||||
}
|
||||
|
||||
override fun onResume(owner: LifecycleOwner) {
|
||||
super.onResume(owner)
|
||||
Rust.resume()
|
||||
}
|
||||
|
||||
override fun onPause(owner: LifecycleOwner) {
|
||||
super.onPause(owner)
|
||||
Rust.pause()
|
||||
}
|
||||
|
||||
override fun onStop(owner: LifecycleOwner) {
|
||||
super.onStop(owner)
|
||||
Rust.stop()
|
||||
}
|
||||
}
|
||||
|
||||
abstract class WryActivity : AppCompatActivity() {
|
||||
private lateinit var mWebView: RustWebView
|
||||
var id: Int = 0
|
||||
open val handleBackNavigation: Boolean = true
|
||||
|
||||
open fun onWebViewCreate(webView: WebView) { }
|
||||
|
||||
fun setWebView(webView: RustWebView) {
|
||||
mWebView = webView
|
||||
|
||||
if (handleBackNavigation) {
|
||||
val callback = object : OnBackPressedCallback(true) {
|
||||
override fun handleOnBackPressed() {
|
||||
if (this@WryActivity::mWebView.isInitialized) {
|
||||
if (this@WryActivity.mWebView.canGoBack()) {
|
||||
this@WryActivity.mWebView.goBack()
|
||||
} else {
|
||||
this.isEnabled = false
|
||||
this@WryActivity.onBackPressed()
|
||||
this.isEnabled = true
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
onBackPressedDispatcher.addCallback(this, callback)
|
||||
}
|
||||
|
||||
onWebViewCreate(webView)
|
||||
}
|
||||
|
||||
val version: String
|
||||
@SuppressLint("WebViewApiAvailability", "ObsoleteSdkInt")
|
||||
get() {
|
||||
// Check getCurrentWebViewPackage() directly if above Android 8
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
|
||||
return WebView.getCurrentWebViewPackage()?.versionName ?: ""
|
||||
}
|
||||
|
||||
// Otherwise manually check WebView versions
|
||||
var webViewPackage = "com.google.android.webview"
|
||||
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
|
||||
webViewPackage = "com.android.chrome"
|
||||
}
|
||||
try {
|
||||
@Suppress("DEPRECATION")
|
||||
val info = packageManager.getPackageInfo(webViewPackage, 0)
|
||||
return info.versionName.toString()
|
||||
} catch (ex: Exception) {
|
||||
Logger.warn("Unable to get package info for '$webViewPackage'$ex")
|
||||
}
|
||||
|
||||
try {
|
||||
@Suppress("DEPRECATION")
|
||||
val info = packageManager.getPackageInfo("com.android.webview", 0)
|
||||
return info.versionName.toString()
|
||||
} catch (ex: Exception) {
|
||||
Logger.warn("Unable to get package info for 'com.android.webview'$ex")
|
||||
}
|
||||
|
||||
// Could not detect any webview, return empty string
|
||||
return ""
|
||||
}
|
||||
|
||||
override fun onCreate(savedInstanceState: Bundle?) {
|
||||
super.onCreate(savedInstanceState)
|
||||
id = savedInstanceState?.getInt(ACTIVITY_ID_KEY) ?: intent.extras?.getInt(ACTIVITY_ID_KEY) ?: hashCode()
|
||||
ProcessLifecycleOwner.get().lifecycle.addObserver(WryLifecycleObserver)
|
||||
Rust.onActivityCreate(this)
|
||||
}
|
||||
|
||||
override fun onWindowFocusChanged(hasFocus: Boolean) {
|
||||
super.onWindowFocusChanged(hasFocus)
|
||||
Rust.onWindowFocusChanged(this, hasFocus)
|
||||
}
|
||||
|
||||
override fun onSaveInstanceState(outState: Bundle) {
|
||||
super.onSaveInstanceState(outState)
|
||||
outState.putInt(ACTIVITY_ID_KEY, id)
|
||||
Rust.onActivitySaveInstanceState()
|
||||
}
|
||||
|
||||
override fun onPause() {
|
||||
super.onPause()
|
||||
if (::mWebView.isInitialized) {
|
||||
mWebView.onPause()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onResume() {
|
||||
super.onResume()
|
||||
if (::mWebView.isInitialized) {
|
||||
mWebView.onResume()
|
||||
}
|
||||
}
|
||||
|
||||
override fun onDestroy() {
|
||||
super.onDestroy()
|
||||
Rust.onActivityDestroy(this)
|
||||
Rust.onWebviewDestroy(this, if (::mWebView.isInitialized) { mWebView.id } else { "" })
|
||||
}
|
||||
|
||||
override fun onLowMemory() {
|
||||
super.onLowMemory()
|
||||
Rust.onActivityLowMemory()
|
||||
}
|
||||
|
||||
override fun onNewIntent(intent: Intent) {
|
||||
super.onNewIntent(intent)
|
||||
Rust.onNewIntent(intent)
|
||||
}
|
||||
|
||||
fun getAppClass(name: String): Class<*> {
|
||||
return Class.forName(name)
|
||||
}
|
||||
|
||||
fun startActivity(cls: Class<*>): Int {
|
||||
val intent = Intent(this, cls)
|
||||
val id = kotlin.random.Random.nextInt()
|
||||
intent.putExtra(ACTIVITY_ID_KEY, id)
|
||||
startActivity(intent)
|
||||
return id
|
||||
}
|
||||
|
||||
{{class-extension}}
|
||||
}
|
||||
+35
@@ -0,0 +1,35 @@
|
||||
# Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
# SPDX-License-Identifier: Apache-2.0
|
||||
# SPDX-License-Identifier: MIT
|
||||
|
||||
-keep class {{package-unescaped}}.* {
|
||||
native <methods>;
|
||||
}
|
||||
|
||||
-keep class {{package-unescaped}}.WryActivity {
|
||||
public <init>(...);
|
||||
|
||||
void setWebView({{package-unescaped}}.RustWebView);
|
||||
java.lang.Class getAppClass(...);
|
||||
int getId();
|
||||
java.lang.String getVersion();
|
||||
int startActivity(...);
|
||||
}
|
||||
|
||||
-keep class {{package-unescaped}}.Ipc {
|
||||
public <init>(...);
|
||||
|
||||
@android.webkit.JavascriptInterface public <methods>;
|
||||
}
|
||||
|
||||
-keep class {{package-unescaped}}.RustWebView {
|
||||
public <init>(...);
|
||||
|
||||
void loadUrlMainThread(...);
|
||||
void loadHTMLMainThread(...);
|
||||
void evalScript(...);
|
||||
}
|
||||
|
||||
-keep class {{package-unescaped}}.RustWebChromeClient,{{package-unescaped}}.RustWebViewClient {
|
||||
public <init>(...);
|
||||
}
|
||||
Vendored
+607
@@ -0,0 +1,607 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use crate::{Error, InitializationScript, RGBA};
|
||||
use crossbeam_channel::*;
|
||||
use jni::{
|
||||
errors::Result as JniResult,
|
||||
objects::{GlobalRef, JMap, JObject, JString},
|
||||
JNIEnv, JavaVM,
|
||||
};
|
||||
use once_cell::sync::Lazy;
|
||||
use std::{
|
||||
collections::BTreeMap,
|
||||
ffi::c_void,
|
||||
os::unix::prelude::*,
|
||||
sync::{Arc, Mutex},
|
||||
};
|
||||
|
||||
use super::{find_class, EvalCallback, WebviewId, EVAL_CALLBACKS, EVAL_ID_GENERATOR, PACKAGE};
|
||||
|
||||
pub type ActivityId = i32;
|
||||
|
||||
static CHANNEL: Lazy<(
|
||||
Sender<(ActivityId, WebViewMessage)>,
|
||||
Receiver<(ActivityId, WebViewMessage)>,
|
||||
)> = Lazy::new(|| bounded(8));
|
||||
pub static MAIN_PIPE: Lazy<[OwnedFd; 2]> = Lazy::new(|| {
|
||||
let mut pipe: [RawFd; 2] = Default::default();
|
||||
unsafe { libc::pipe(pipe.as_mut_ptr()) };
|
||||
unsafe { pipe.map(|fd| OwnedFd::from_raw_fd(fd)) }
|
||||
});
|
||||
|
||||
#[derive(Clone)]
|
||||
pub struct ActivityProxy {
|
||||
pub activity: GlobalRef,
|
||||
pub window_manager: GlobalRef,
|
||||
pub webview: Option<GlobalRef>,
|
||||
pub webchrome_client: GlobalRef,
|
||||
pub java_vm: *mut c_void,
|
||||
}
|
||||
|
||||
unsafe impl Send for ActivityProxy {}
|
||||
|
||||
impl ActivityProxy {
|
||||
pub fn new(
|
||||
vm: JavaVM,
|
||||
activity: GlobalRef,
|
||||
window_manager: GlobalRef,
|
||||
webchrome_client: GlobalRef,
|
||||
) -> Self {
|
||||
Self {
|
||||
activity,
|
||||
window_manager,
|
||||
webview: None,
|
||||
webchrome_client,
|
||||
java_vm: vm.get_java_vm_pointer() as *mut _,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
static ACTIVITY_PROXY: once_cell::sync::Lazy<Mutex<BTreeMap<ActivityId, ActivityProxy>>> =
|
||||
Lazy::new(|| Mutex::new(BTreeMap::new()));
|
||||
|
||||
pub fn activity_proxy(id: ActivityId) -> Option<ActivityProxy> {
|
||||
ACTIVITY_PROXY.lock().unwrap().get(&id).cloned()
|
||||
}
|
||||
|
||||
fn remove_activity_proxy(id: ActivityId) {
|
||||
ACTIVITY_PROXY.lock().unwrap().remove(&id);
|
||||
}
|
||||
|
||||
pub fn register_activity_proxy(
|
||||
vm: JavaVM,
|
||||
id: ActivityId,
|
||||
activity: GlobalRef,
|
||||
window_manager: GlobalRef,
|
||||
webchrome_client: GlobalRef,
|
||||
) {
|
||||
let mut activity_proxy = ACTIVITY_PROXY.lock().unwrap();
|
||||
if let Some(proxy) = activity_proxy.get_mut(&id) {
|
||||
proxy.activity = activity;
|
||||
proxy.window_manager = window_manager;
|
||||
proxy.webchrome_client = webchrome_client;
|
||||
proxy.java_vm = vm.get_java_vm_pointer() as *mut _;
|
||||
} else {
|
||||
let proxy = ActivityProxy::new(vm, activity, window_manager, webchrome_client);
|
||||
activity_proxy.insert(id, proxy.clone());
|
||||
}
|
||||
}
|
||||
|
||||
pub fn activity_id_for_window_manager(window_manager: JObject) -> Option<ActivityId> {
|
||||
for (activity_id, proxy) in ACTIVITY_PROXY.lock().unwrap().iter() {
|
||||
let vm = unsafe { JavaVM::from_raw(proxy.java_vm.cast()) }.unwrap();
|
||||
let mut env = vm.attach_current_thread_as_daemon().unwrap();
|
||||
let equals = env
|
||||
.call_method(
|
||||
proxy.window_manager.as_obj(),
|
||||
"equals",
|
||||
"(Ljava/lang/Object;)Z",
|
||||
&[(&window_manager).into()],
|
||||
)
|
||||
.and_then(|v| v.z())
|
||||
.unwrap_or_default();
|
||||
if equals {
|
||||
return Some(*activity_id);
|
||||
}
|
||||
}
|
||||
None
|
||||
}
|
||||
|
||||
pub fn first_activity_id() -> Option<ActivityId> {
|
||||
ACTIVITY_PROXY.lock().unwrap().keys().next().cloned()
|
||||
}
|
||||
|
||||
pub fn get_webview(activity_id: ActivityId) -> Option<GlobalRef> {
|
||||
ACTIVITY_PROXY
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&activity_id)
|
||||
.unwrap()
|
||||
.webview
|
||||
.as_ref()
|
||||
.cloned()
|
||||
}
|
||||
|
||||
pub struct MainPipe<'a> {
|
||||
pub env: JNIEnv<'a>,
|
||||
}
|
||||
|
||||
impl<'a> MainPipe<'a> {
|
||||
pub(crate) fn send(activity_id: ActivityId, message: WebViewMessage) {
|
||||
let size = std::mem::size_of::<bool>();
|
||||
if CHANNEL.0.send((activity_id, message)).is_ok() {
|
||||
unsafe {
|
||||
libc::write(
|
||||
MAIN_PIPE[1].as_raw_fd(),
|
||||
&true as *const _ as *const _,
|
||||
size,
|
||||
)
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
pub fn recv(&mut self) -> JniResult<()> {
|
||||
if let Ok((activity_id, message)) = CHANNEL.1.recv() {
|
||||
match message {
|
||||
WebViewMessage::CreateWebView(attrs) => {
|
||||
let Some((activity, web_chrome_client)) =
|
||||
activity_proxy(activity_id).map(|p| (p.activity.clone(), p.webchrome_client.clone()))
|
||||
else {
|
||||
#[cfg(debug_assertions)]
|
||||
eprintln!("no activity found for activity id: {}", activity_id);
|
||||
return Ok(());
|
||||
};
|
||||
let CreateWebViewAttributes {
|
||||
url,
|
||||
html,
|
||||
#[cfg(any(debug_assertions, feature = "devtools"))]
|
||||
devtools,
|
||||
transparent,
|
||||
background_color,
|
||||
headers,
|
||||
on_webview_created,
|
||||
autoplay,
|
||||
user_agent,
|
||||
initialization_scripts,
|
||||
id,
|
||||
javascript_disabled,
|
||||
..
|
||||
} = attrs;
|
||||
|
||||
let string_class = self.env.find_class("java/lang/String")?;
|
||||
let initialization_scripts_array = self.env.new_object_array(
|
||||
initialization_scripts.len() as i32,
|
||||
string_class,
|
||||
self.env.new_string("")?,
|
||||
)?;
|
||||
for (i, init_script) in initialization_scripts.into_iter().enumerate() {
|
||||
self.env.set_object_array_element(
|
||||
&initialization_scripts_array,
|
||||
i as i32,
|
||||
self.env.new_string(init_script.script)?,
|
||||
)?;
|
||||
}
|
||||
let id = self.env.new_string(id)?;
|
||||
// Create webview
|
||||
let rust_webview_class = find_class(
|
||||
&mut self.env,
|
||||
&activity,
|
||||
format!("{}/RustWebView", PACKAGE.get().unwrap()),
|
||||
)?;
|
||||
let webview = self.env.new_object(
|
||||
&rust_webview_class,
|
||||
"(Landroid/content/Context;[Ljava/lang/String;Ljava/lang/String;)V",
|
||||
&[
|
||||
(&activity).into(),
|
||||
(&initialization_scripts_array).into(),
|
||||
(&id).into(),
|
||||
],
|
||||
)?;
|
||||
// get settings
|
||||
let web_settings = self
|
||||
.env
|
||||
.call_method(
|
||||
&webview,
|
||||
"getSettings",
|
||||
"()Landroid/webkit/WebSettings;",
|
||||
&[],
|
||||
)?
|
||||
.l()?;
|
||||
// set media autoplay
|
||||
self.env.call_method(
|
||||
&web_settings,
|
||||
"setMediaPlaybackRequiresUserGesture",
|
||||
"(Z)V",
|
||||
&[(!autoplay).into()],
|
||||
)?;
|
||||
// set user-agent
|
||||
if let Some(user_agent) = user_agent {
|
||||
let user_agent = self.env.new_string(user_agent)?;
|
||||
self.env.call_method(
|
||||
&web_settings,
|
||||
"setUserAgentString",
|
||||
"(Ljava/lang/String;)V",
|
||||
&[(&user_agent).into()],
|
||||
)?;
|
||||
}
|
||||
|
||||
// disable javascript
|
||||
if javascript_disabled {
|
||||
self.env.call_method(
|
||||
&web_settings,
|
||||
"setJavaScriptEnabled",
|
||||
"(Z)V",
|
||||
&[false.into()],
|
||||
)?;
|
||||
}
|
||||
|
||||
let webview_class_name = format!("{}/RustWebView", PACKAGE.get().unwrap());
|
||||
self.env.call_method(
|
||||
&activity,
|
||||
"setWebView",
|
||||
format!("(L{webview_class_name};)V"),
|
||||
&[(&webview).into()],
|
||||
)?;
|
||||
// Navigation
|
||||
if let Some(u) = url {
|
||||
if let Ok(url) = self.env.new_string(u) {
|
||||
load_url(&mut self.env, &webview, &url, headers, true)?;
|
||||
}
|
||||
} else if let Some(h) = html {
|
||||
if let Ok(html) = self.env.new_string(h) {
|
||||
load_html(&mut self.env, &webview, &html)?;
|
||||
}
|
||||
}
|
||||
// Enable devtools
|
||||
#[cfg(any(debug_assertions, feature = "devtools"))]
|
||||
self.env.call_static_method(
|
||||
&rust_webview_class,
|
||||
"setWebContentsDebuggingEnabled",
|
||||
"(Z)V",
|
||||
&[devtools.into()],
|
||||
)?;
|
||||
if transparent {
|
||||
set_background_color(&mut self.env, &webview, (0, 0, 0, 0))?;
|
||||
} else if let Some(color) = background_color {
|
||||
set_background_color(&mut self.env, &webview, color)?;
|
||||
}
|
||||
// Create and set webview client
|
||||
let client_class_name = format!("{}/RustWebViewClient", PACKAGE.get().unwrap());
|
||||
let rust_webview_client_class =
|
||||
find_class(&mut self.env, &activity, client_class_name.clone())?;
|
||||
let webview_client = self.env.new_object(
|
||||
&rust_webview_client_class,
|
||||
format!("(L{webview_class_name};Landroid/content/Context;)V"),
|
||||
&[(&webview).into(), (&activity).into()],
|
||||
)?;
|
||||
self.env.call_method(
|
||||
&webview,
|
||||
"setWebViewClient",
|
||||
"(Landroid/webkit/WebViewClient;)V",
|
||||
&[(&webview_client).into()],
|
||||
)?;
|
||||
// set webchrome client
|
||||
self.env.call_method(
|
||||
&webview,
|
||||
"setWebChromeClient",
|
||||
"(Landroid/webkit/WebChromeClient;)V",
|
||||
&[web_chrome_client.as_obj().into()],
|
||||
)?;
|
||||
|
||||
// Add javascript interface (IPC)
|
||||
let ipc_class = find_class(
|
||||
&mut self.env,
|
||||
&activity,
|
||||
format!("{}/Ipc", PACKAGE.get().unwrap()),
|
||||
)?;
|
||||
let ipc = self.env.new_object(
|
||||
ipc_class,
|
||||
format!("(L{webview_class_name};L{client_class_name};)V"),
|
||||
&[(&webview).into(), (&webview_client).into()],
|
||||
)?;
|
||||
let ipc_str = self.env.new_string("ipc")?;
|
||||
self.env.call_method(
|
||||
&webview,
|
||||
"addJavascriptInterface",
|
||||
"(Ljava/lang/Object;Ljava/lang/String;)V",
|
||||
&[(&ipc).into(), (&ipc_str).into()],
|
||||
)?;
|
||||
|
||||
// Set content view
|
||||
self.env.call_method(
|
||||
&activity,
|
||||
"setContentView",
|
||||
"(Landroid/view/View;)V",
|
||||
&[(&webview).into()],
|
||||
)?;
|
||||
|
||||
if let Some(on_webview_created) = on_webview_created {
|
||||
if let Err(_e) = on_webview_created(super::Context {
|
||||
env: &mut self.env,
|
||||
activity: &activity,
|
||||
webview: &webview,
|
||||
}) {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("failed to run webview created hook: {_e}");
|
||||
}
|
||||
}
|
||||
|
||||
let webview = self.env.new_global_ref(webview)?;
|
||||
|
||||
ACTIVITY_PROXY
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get_mut(&activity_id)
|
||||
.unwrap()
|
||||
.webview
|
||||
.replace(webview);
|
||||
}
|
||||
WebViewMessage::Eval(script, callback) => {
|
||||
if let Some(webview) = get_webview(activity_id) {
|
||||
let id = EVAL_ID_GENERATOR.next() as i32;
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
let span = std::sync::Mutex::new(Some(SendEnteredSpan(
|
||||
tracing::debug_span!("wry::eval").entered(),
|
||||
)));
|
||||
|
||||
EVAL_CALLBACKS
|
||||
.get_or_init(Default::default)
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(
|
||||
id,
|
||||
Box::new(move |result| {
|
||||
#[cfg(feature = "tracing")]
|
||||
span.lock().unwrap().take();
|
||||
|
||||
if let Some(callback) = &callback {
|
||||
callback(result);
|
||||
}
|
||||
}),
|
||||
);
|
||||
|
||||
let s = self.env.new_string(script)?;
|
||||
self.env.call_method(
|
||||
webview.as_obj(),
|
||||
"evalScript",
|
||||
"(ILjava/lang/String;)V",
|
||||
&[id.into(), (&s).into()],
|
||||
)?;
|
||||
}
|
||||
}
|
||||
WebViewMessage::SetBackgroundColor(background_color) => {
|
||||
if let Some(webview) = get_webview(activity_id) {
|
||||
set_background_color(&mut self.env, webview.as_obj(), background_color)?;
|
||||
}
|
||||
}
|
||||
WebViewMessage::GetWebViewVersion(tx) => {
|
||||
if let Some(activity) = activity_proxy(activity_id).map(|p| p.activity.clone()) {
|
||||
match self
|
||||
.env
|
||||
.call_method(activity, "getVersion", "()Ljava/lang/String;", &[])
|
||||
.and_then(|v| v.l())
|
||||
.and_then(|s| {
|
||||
let s = JString::from(s);
|
||||
self
|
||||
.env
|
||||
.get_string(&s)
|
||||
.map(|v| v.to_string_lossy().to_string())
|
||||
}) {
|
||||
Ok(version) => {
|
||||
tx.send(Ok(version)).unwrap();
|
||||
}
|
||||
Err(e) => tx.send(Err(e.into())).unwrap(),
|
||||
}
|
||||
} else {
|
||||
tx.send(Err(Error::ActivityNotFound)).unwrap();
|
||||
}
|
||||
}
|
||||
WebViewMessage::GetUrl(tx) => {
|
||||
if let Some(webview) = get_webview(activity_id) {
|
||||
let url = self
|
||||
.env
|
||||
.call_method(webview.as_obj(), "getUrl", "()Ljava/lang/String;", &[])
|
||||
.and_then(|v| v.l())
|
||||
.and_then(|s| {
|
||||
let s = JString::from(s);
|
||||
self
|
||||
.env
|
||||
.get_string(&s)
|
||||
.map(|v| v.to_string_lossy().to_string())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
tx.send(url).unwrap()
|
||||
}
|
||||
}
|
||||
WebViewMessage::Jni(f) => {
|
||||
match activity_proxy(activity_id).map(|p| (p.activity.clone(), p.webview.clone())) {
|
||||
Some((activity, Some(webview))) => {
|
||||
f(&mut self.env, &activity, webview.as_obj());
|
||||
}
|
||||
Some((activity, None)) => {
|
||||
f(&mut self.env, &activity, &JObject::null());
|
||||
}
|
||||
_ => {
|
||||
f(&mut self.env, &JObject::null(), &JObject::null());
|
||||
}
|
||||
}
|
||||
}
|
||||
WebViewMessage::LoadUrl(url, headers) => {
|
||||
if let Some(webview) = get_webview(activity_id) {
|
||||
let url = self.env.new_string(url)?;
|
||||
load_url(&mut self.env, webview.as_obj(), &url, headers, false)?;
|
||||
}
|
||||
}
|
||||
WebViewMessage::ClearAllBrowsingData => {
|
||||
if let Some(webview) = get_webview(activity_id) {
|
||||
self
|
||||
.env
|
||||
.call_method(webview, "clearAllBrowsingData", "()V", &[])?;
|
||||
}
|
||||
}
|
||||
WebViewMessage::LoadHtml(html) => {
|
||||
if let Some(webview) = get_webview(activity_id) {
|
||||
let html = self.env.new_string(html)?;
|
||||
load_html(&mut self.env, webview.as_obj(), &html)?;
|
||||
}
|
||||
}
|
||||
WebViewMessage::Reload => {
|
||||
if let Some(webview) = get_webview(activity_id) {
|
||||
reload(&mut self.env, webview.as_obj())?;
|
||||
}
|
||||
}
|
||||
WebViewMessage::GetCookies(tx, url) => {
|
||||
if let Some(webview) = get_webview(activity_id) {
|
||||
let url = self.env.new_string(url)?;
|
||||
let cookies = self
|
||||
.env
|
||||
.call_method(
|
||||
webview,
|
||||
"getCookies",
|
||||
"(Ljava/lang/String;)Ljava/lang/String;",
|
||||
&[(&url).into()],
|
||||
)
|
||||
.and_then(|v| v.l())
|
||||
.and_then(|s| {
|
||||
let s = JString::from(s);
|
||||
self
|
||||
.env
|
||||
.get_string(&s)
|
||||
.map(|v| v.to_string_lossy().to_string())
|
||||
})
|
||||
.unwrap_or_default();
|
||||
|
||||
tx.send(
|
||||
cookies
|
||||
.split("; ")
|
||||
.flat_map(|c| cookie::Cookie::parse(c.to_string()))
|
||||
.collect(),
|
||||
)
|
||||
.unwrap();
|
||||
}
|
||||
}
|
||||
WebViewMessage::OnDestroy {
|
||||
activity_id,
|
||||
webview_id,
|
||||
is_changing_configurations,
|
||||
} => {
|
||||
// keep our webview references (callbacks etc) alive if the activity is going to be recreated due to configuration changes
|
||||
// e.g. rotation, multi-window mode change, etc
|
||||
if !is_changing_configurations {
|
||||
super::destroy_webview(activity_id, &webview_id);
|
||||
remove_activity_proxy(activity_id);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
fn load_url<'a>(
|
||||
env: &mut JNIEnv<'a>,
|
||||
webview: &JObject<'a>,
|
||||
url: &JString<'a>,
|
||||
headers: Option<http::HeaderMap>,
|
||||
main_thread: bool,
|
||||
) -> JniResult<()> {
|
||||
let function = if main_thread {
|
||||
"loadUrlMainThread"
|
||||
} else {
|
||||
"loadUrl"
|
||||
};
|
||||
if let Some(headers) = headers {
|
||||
let obj = env.new_object("java/util/HashMap", "()V", &[])?;
|
||||
let headers_map = {
|
||||
let headers_map = JMap::from_env(env, &obj)?;
|
||||
for (name, value) in headers.iter() {
|
||||
let key = env.new_string(name)?;
|
||||
let value = env.new_string(value.to_str().unwrap_or_default())?;
|
||||
headers_map.put(env, &key, &value)?;
|
||||
}
|
||||
headers_map
|
||||
};
|
||||
env.call_method(
|
||||
webview,
|
||||
function,
|
||||
"(Ljava/lang/String;Ljava/util/Map;)V",
|
||||
&[url.into(), (&headers_map).into()],
|
||||
)?;
|
||||
} else {
|
||||
env.call_method(webview, function, "(Ljava/lang/String;)V", &[url.into()])?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_html<'a>(env: &mut JNIEnv<'a>, webview: &JObject<'a>, html: &JString<'a>) -> JniResult<()> {
|
||||
env.call_method(
|
||||
webview,
|
||||
"loadHTMLMainThread",
|
||||
"(Ljava/lang/String;)V",
|
||||
&[html.into()],
|
||||
)?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn reload<'a>(env: &mut JNIEnv<'a>, webview: &JObject<'a>) -> JniResult<()> {
|
||||
env.call_method(webview, "reload", "()V", &[])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn set_background_color<'a>(
|
||||
env: &mut JNIEnv<'a>,
|
||||
webview: &JObject<'a>,
|
||||
(r, g, b, a): RGBA,
|
||||
) -> JniResult<()> {
|
||||
let color = (a as i32) << 24 | (r as i32) << 16 | (g as i32) << 8 | (b as i32);
|
||||
env.call_method(webview, "setBackgroundColor", "(I)V", &[color.into()])?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) enum WebViewMessage {
|
||||
CreateWebView(CreateWebViewAttributes),
|
||||
Eval(String, Option<EvalCallback>),
|
||||
SetBackgroundColor(RGBA),
|
||||
GetWebViewVersion(Sender<Result<String, Error>>),
|
||||
GetUrl(Sender<String>),
|
||||
GetCookies(Sender<Vec<cookie::Cookie<'static>>>, String),
|
||||
Jni(Box<dyn FnOnce(&mut JNIEnv, &JObject, &JObject) + Send>),
|
||||
LoadUrl(String, Option<http::HeaderMap>),
|
||||
LoadHtml(String),
|
||||
Reload,
|
||||
ClearAllBrowsingData,
|
||||
OnDestroy {
|
||||
activity_id: ActivityId,
|
||||
webview_id: WebviewId,
|
||||
is_changing_configurations: bool,
|
||||
},
|
||||
}
|
||||
|
||||
#[derive(Clone)]
|
||||
pub(crate) struct CreateWebViewAttributes {
|
||||
pub id: String,
|
||||
pub url: Option<String>,
|
||||
pub html: Option<String>,
|
||||
#[cfg(any(debug_assertions, feature = "devtools"))]
|
||||
pub devtools: bool,
|
||||
pub transparent: bool,
|
||||
pub background_color: Option<RGBA>,
|
||||
pub headers: Option<http::HeaderMap>,
|
||||
pub autoplay: bool,
|
||||
pub on_webview_created:
|
||||
Option<Arc<dyn Fn(super::Context) -> JniResult<()> + Send + Sync + 'static>>,
|
||||
pub user_agent: Option<String>,
|
||||
pub initialization_scripts: Vec<InitializationScript>,
|
||||
pub javascript_disabled: bool,
|
||||
}
|
||||
|
||||
// SAFETY: only use this when you are sure the span will be dropped on the same thread it was entered
|
||||
#[cfg(feature = "tracing")]
|
||||
struct SendEnteredSpan(tracing::span::EnteredSpan);
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
unsafe impl Send for SendEnteredSpan {}
|
||||
Vendored
+530
@@ -0,0 +1,530 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use super::{PageLoadEvent, WebViewAttributes, RGBA};
|
||||
use crate::{
|
||||
custom_protocol_workaround, inject_initialization_scripts::inject_scripts_into_html, Error,
|
||||
RequestAsyncResponder, Result,
|
||||
};
|
||||
use crossbeam_channel::*;
|
||||
|
||||
use http::{Request, Response as HttpResponse};
|
||||
use jni::{
|
||||
errors::Result as JniResult,
|
||||
objects::{GlobalRef, JClass, JObject},
|
||||
JNIEnv,
|
||||
};
|
||||
use ndk::looper::ThreadLooper;
|
||||
use once_cell::sync::{Lazy, OnceCell};
|
||||
use raw_window_handle::HasWindowHandle;
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
collections::HashMap,
|
||||
sync::{mpsc::channel, Mutex},
|
||||
time::Duration,
|
||||
};
|
||||
|
||||
pub(crate) mod binding;
|
||||
mod main_pipe;
|
||||
use main_pipe::{
|
||||
activity_id_for_window_manager, first_activity_id, register_activity_proxy, ActivityId,
|
||||
CreateWebViewAttributes, MainPipe, WebViewMessage,
|
||||
};
|
||||
|
||||
use crate::util::Counter;
|
||||
|
||||
static COUNTER: Counter = Counter::new();
|
||||
const MAIN_PIPE_TIMEOUT: Duration = Duration::from_secs(10);
|
||||
|
||||
pub struct Context<'a, 'b> {
|
||||
pub env: &'a mut JNIEnv<'b>,
|
||||
pub activity: &'a JObject<'b>,
|
||||
pub webview: &'a JObject<'b>,
|
||||
}
|
||||
|
||||
type WebviewId = String;
|
||||
|
||||
macro_rules! define_static_handlers {
|
||||
($($key: ident, $var:ident = $type_name:ident);+ $(;)?) => {
|
||||
$(static $var: Lazy<Mutex<HashMap<$key, $type_name>>> = Lazy::new(||Mutex::new(HashMap::new()));)*
|
||||
};
|
||||
|
||||
($($var:ident = $type_name:ident { $($fields:ident:$types:ty),+ $(,)? });+ $(;)?) => {
|
||||
$(
|
||||
static $var: Lazy<Mutex<HashMap<WebviewId, $type_name>>> = Lazy::new(||Mutex::new(HashMap::new()));
|
||||
pub struct $type_name {
|
||||
$($fields: $types,)*
|
||||
}
|
||||
impl $type_name {
|
||||
pub fn new($($fields: $types,)*) -> Self {
|
||||
Self {
|
||||
$($fields,)*
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe impl Send for $type_name {}
|
||||
unsafe impl Sync for $type_name {})*
|
||||
};
|
||||
}
|
||||
|
||||
define_static_handlers! {
|
||||
IPC = UnsafeIpc { handler: Box<dyn Fn(Request<String>)> };
|
||||
REQUEST_HANDLER = UnsafeRequestHandler { handler: Box<dyn Fn(&str, Request<Vec<u8>>, bool) -> Option<HttpResponse<Cow<'static, [u8]>>>> };
|
||||
TITLE_CHANGE_HANDLER = UnsafeTitleHandler { handler: Box<dyn Fn(String)> };
|
||||
URL_LOADING_OVERRIDE = UnsafeUrlLoadingOverride { handler: Box<dyn Fn(String) -> bool> };
|
||||
ON_LOAD_HANDLER = UnsafeOnPageLoadHandler { handler: Box<dyn Fn(PageLoadEvent, String)> };
|
||||
}
|
||||
define_static_handlers! {
|
||||
WebviewId, WITH_ASSET_LOADER = bool;
|
||||
WebviewId, ASSET_LOADER_DOMAIN = String;
|
||||
ActivityId, WEBVIEW_ATTRIBUTES = CreateWebViewAttributes;
|
||||
}
|
||||
|
||||
pub(crate) static PACKAGE: OnceCell<String> = OnceCell::new();
|
||||
|
||||
type EvalCallback = Box<dyn Fn(String) + Send + 'static>;
|
||||
|
||||
pub static EVAL_ID_GENERATOR: Counter = Counter::new();
|
||||
pub static EVAL_CALLBACKS: OnceCell<Mutex<HashMap<i32, EvalCallback>>> = OnceCell::new();
|
||||
|
||||
pub fn destroy_webview(activity_id: ActivityId, webview_id: &WebviewId) {
|
||||
WEBVIEW_ATTRIBUTES.lock().unwrap().remove(&activity_id);
|
||||
IPC.lock().unwrap().remove(webview_id);
|
||||
REQUEST_HANDLER.lock().unwrap().remove(webview_id);
|
||||
TITLE_CHANGE_HANDLER.lock().unwrap().remove(webview_id);
|
||||
URL_LOADING_OVERRIDE.lock().unwrap().remove(webview_id);
|
||||
ON_LOAD_HANDLER.lock().unwrap().remove(webview_id);
|
||||
WITH_ASSET_LOADER.lock().unwrap().remove(webview_id);
|
||||
ASSET_LOADER_DOMAIN.lock().unwrap().remove(webview_id);
|
||||
}
|
||||
|
||||
/// Sets up the necessary logic for wry to be able to create the webviews later.
|
||||
///
|
||||
/// This function must be run on the thread where the [`JNIEnv`] is registered and the looper is local,
|
||||
/// hence the requirement for a [`ThreadLooper`].
|
||||
pub unsafe fn android_setup(
|
||||
package: &str,
|
||||
mut env: JNIEnv,
|
||||
_looper: &ThreadLooper,
|
||||
activity: GlobalRef,
|
||||
) {
|
||||
PACKAGE.get_or_init(move || package.to_string());
|
||||
|
||||
let vm = env.get_java_vm().unwrap();
|
||||
|
||||
let activity_id = env
|
||||
.call_method(activity.as_obj(), "getId", "()I", &[])
|
||||
.unwrap()
|
||||
.i()
|
||||
.unwrap();
|
||||
|
||||
let window_manager = env
|
||||
.call_method(
|
||||
&activity,
|
||||
"getWindowManager",
|
||||
"()Landroid/view/WindowManager;",
|
||||
&[],
|
||||
)
|
||||
.unwrap()
|
||||
.l()
|
||||
.unwrap();
|
||||
let window_manager = env.new_global_ref(window_manager).unwrap();
|
||||
|
||||
// we must create the WebChromeClient here because it calls `registerForActivityResult`,
|
||||
// which gives an `LifecycleOwners must call register before they are STARTED.` error when called outside the onCreate hook
|
||||
let rust_webchrome_client_class = find_class(
|
||||
&mut env,
|
||||
activity.as_obj(),
|
||||
format!("{}/RustWebChromeClient", PACKAGE.get().unwrap()),
|
||||
)
|
||||
.unwrap();
|
||||
let webchrome_client = env
|
||||
.new_object(
|
||||
&rust_webchrome_client_class,
|
||||
format!("(L{}/WryActivity;)V", PACKAGE.get().unwrap()),
|
||||
&[activity.as_obj().into()],
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
let webchrome_client = env.new_global_ref(webchrome_client).unwrap();
|
||||
|
||||
register_activity_proxy(vm, activity_id, activity, window_manager, webchrome_client);
|
||||
|
||||
if let Some(webview_attributes) = WEBVIEW_ATTRIBUTES.lock().unwrap().get(&activity_id) {
|
||||
MainPipe::send(
|
||||
activity_id,
|
||||
WebViewMessage::CreateWebView(webview_attributes.clone()),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) struct InnerWebView {
|
||||
id: String,
|
||||
pub activity_id: ActivityId,
|
||||
}
|
||||
|
||||
impl InnerWebView {
|
||||
pub fn new_as_child(
|
||||
window: &impl HasWindowHandle,
|
||||
attributes: WebViewAttributes,
|
||||
pl_attrs: super::PlatformSpecificWebViewAttributes,
|
||||
) -> Result<Self> {
|
||||
Self::new(window, attributes, pl_attrs)
|
||||
}
|
||||
|
||||
pub fn new(
|
||||
window: &impl HasWindowHandle,
|
||||
attributes: WebViewAttributes,
|
||||
pl_attrs: super::PlatformSpecificWebViewAttributes,
|
||||
) -> Result<Self> {
|
||||
let window_manager = match window.window_handle()?.as_raw() {
|
||||
raw_window_handle::RawWindowHandle::AndroidNdk(window_manager) => {
|
||||
window_manager.a_native_window
|
||||
}
|
||||
_ => return Err(Error::UnsupportedWindowHandle),
|
||||
};
|
||||
let window_manager = unsafe { JObject::from_raw(window_manager.as_ptr().cast()) };
|
||||
let activity_id =
|
||||
activity_id_for_window_manager(window_manager).expect("no available activity");
|
||||
let WebViewAttributes {
|
||||
url,
|
||||
html,
|
||||
initialization_scripts,
|
||||
ipc_handler,
|
||||
#[cfg(any(debug_assertions, feature = "devtools"))]
|
||||
devtools,
|
||||
custom_protocols,
|
||||
background_color,
|
||||
transparent,
|
||||
headers,
|
||||
autoplay,
|
||||
user_agent,
|
||||
javascript_disabled,
|
||||
..
|
||||
} = attributes;
|
||||
|
||||
let super::PlatformSpecificWebViewAttributes {
|
||||
on_webview_created,
|
||||
with_asset_loader,
|
||||
asset_loader_domain,
|
||||
https_scheme,
|
||||
} = pl_attrs;
|
||||
|
||||
let http_or_https = if https_scheme { "https" } else { "http" };
|
||||
|
||||
let url = if let Some(mut url) = url {
|
||||
if let Some((protocol, _)) = url.split_once("://") {
|
||||
if custom_protocols.contains_key(protocol) {
|
||||
url = custom_protocol_workaround::apply_uri_work_around(&url, http_or_https, protocol)
|
||||
}
|
||||
}
|
||||
|
||||
Some(url)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let id = attributes
|
||||
.id
|
||||
.map(|id| id.to_string())
|
||||
.unwrap_or_else(|| COUNTER.next().to_string());
|
||||
|
||||
WITH_ASSET_LOADER
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), with_asset_loader);
|
||||
if let Some(domain) = asset_loader_domain {
|
||||
ASSET_LOADER_DOMAIN
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), domain);
|
||||
}
|
||||
|
||||
let initialization_scripts_ = initialization_scripts.clone();
|
||||
REQUEST_HANDLER
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(
|
||||
id.clone(),
|
||||
UnsafeRequestHandler::new(Box::new(
|
||||
move |webview_id: &str, mut request, is_document_start_script_enabled| {
|
||||
let uri = request.uri().to_string();
|
||||
if let Some((custom_protocol, custom_protocol_handler)) =
|
||||
custom_protocols.iter().find(|(protocol, _)| {
|
||||
custom_protocol_workaround::is_work_around_uri(&uri, http_or_https, protocol)
|
||||
})
|
||||
{
|
||||
let uri_res = custom_protocol_workaround::revert_uri_work_around(
|
||||
&uri,
|
||||
http_or_https,
|
||||
custom_protocol,
|
||||
)
|
||||
.parse();
|
||||
|
||||
if let Ok(uri) = uri_res {
|
||||
*request.uri_mut() = uri;
|
||||
}
|
||||
|
||||
let (tx, rx) = channel();
|
||||
let initialization_scripts = initialization_scripts_.clone();
|
||||
let responder: Box<dyn FnOnce(HttpResponse<Cow<'static, [u8]>>)> =
|
||||
Box::new(move |mut response| {
|
||||
if !is_document_start_script_enabled {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::info!("`addDocumentStartJavaScript` is not supported; injecting initialization scripts via custom protocol handler");
|
||||
response = inject_scripts_into_html(response, &initialization_scripts);
|
||||
}
|
||||
let _ = tx.send(response);
|
||||
});
|
||||
|
||||
(custom_protocol_handler)(webview_id, request, RequestAsyncResponder { responder });
|
||||
// 3x the timeout while we monitor https://github.com/tauri-apps/wry/issues/1551
|
||||
// TODO: Remove timeout
|
||||
return rx.recv_timeout(MAIN_PIPE_TIMEOUT * 3).inspect_err(|e| {eprintln!("custom protocol timed out: {e}");}).ok();
|
||||
}
|
||||
None
|
||||
},
|
||||
)));
|
||||
|
||||
if let Some(i) = ipc_handler {
|
||||
IPC
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), UnsafeIpc::new(Box::new(i)));
|
||||
}
|
||||
|
||||
if let Some(i) = attributes.document_title_changed_handler {
|
||||
TITLE_CHANGE_HANDLER
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), UnsafeTitleHandler::new(i));
|
||||
}
|
||||
|
||||
if let Some(i) = attributes.navigation_handler {
|
||||
URL_LOADING_OVERRIDE
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), UnsafeUrlLoadingOverride::new(i));
|
||||
}
|
||||
|
||||
if let Some(h) = attributes.on_page_load_handler {
|
||||
ON_LOAD_HANDLER
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(id.clone(), UnsafeOnPageLoadHandler::new(h));
|
||||
}
|
||||
|
||||
let attributes = CreateWebViewAttributes {
|
||||
id: id.clone(),
|
||||
url,
|
||||
html,
|
||||
#[cfg(any(debug_assertions, feature = "devtools"))]
|
||||
devtools,
|
||||
background_color,
|
||||
transparent,
|
||||
headers,
|
||||
on_webview_created,
|
||||
autoplay,
|
||||
user_agent,
|
||||
initialization_scripts,
|
||||
javascript_disabled,
|
||||
};
|
||||
|
||||
WEBVIEW_ATTRIBUTES
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(activity_id, attributes.clone());
|
||||
|
||||
MainPipe::send(activity_id, WebViewMessage::CreateWebView(attributes));
|
||||
|
||||
Ok(Self { id, activity_id })
|
||||
}
|
||||
|
||||
pub fn print(&self) -> crate::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn id(&self) -> crate::WebViewId<'_> {
|
||||
&self.id
|
||||
}
|
||||
|
||||
pub fn url(&self) -> crate::Result<String> {
|
||||
let (tx, rx) = bounded(1);
|
||||
MainPipe::send(self.activity_id, WebViewMessage::GetUrl(tx));
|
||||
rx.recv_timeout(MAIN_PIPE_TIMEOUT).map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn eval(&self, js: &str, callback: Option<impl Fn(String) + Send + 'static>) -> Result<()> {
|
||||
MainPipe::send(
|
||||
self.activity_id,
|
||||
WebViewMessage::Eval(
|
||||
js.into(),
|
||||
callback.map(|c| Box::new(c) as Box<dyn Fn(String) + Send + 'static>),
|
||||
),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(any(debug_assertions, feature = "devtools"))]
|
||||
pub fn open_devtools(&self) {}
|
||||
|
||||
#[cfg(any(debug_assertions, feature = "devtools"))]
|
||||
pub fn close_devtools(&self) {}
|
||||
|
||||
#[cfg(any(debug_assertions, feature = "devtools"))]
|
||||
pub fn is_devtools_open(&self) -> bool {
|
||||
false
|
||||
}
|
||||
|
||||
pub fn zoom(&self, _scale_factor: f64) -> Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_background_color(&self, background_color: RGBA) -> Result<()> {
|
||||
MainPipe::send(
|
||||
self.activity_id,
|
||||
WebViewMessage::SetBackgroundColor(background_color),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_url(&self, url: &str) -> Result<()> {
|
||||
MainPipe::send(
|
||||
self.activity_id,
|
||||
WebViewMessage::LoadUrl(url.to_string(), None),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_url_with_headers(&self, url: &str, headers: http::HeaderMap) -> Result<()> {
|
||||
MainPipe::send(
|
||||
self.activity_id,
|
||||
WebViewMessage::LoadUrl(url.to_string(), Some(headers)),
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn load_html(&self, html: &str) -> Result<()> {
|
||||
MainPipe::send(self.activity_id, WebViewMessage::LoadHtml(html.to_string()));
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn reload(&self) -> Result<()> {
|
||||
MainPipe::send(self.activity_id, WebViewMessage::Reload);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn clear_all_browsing_data(&self) -> Result<()> {
|
||||
MainPipe::send(self.activity_id, WebViewMessage::ClearAllBrowsingData);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn cookies_for_url(&self, url: &str) -> Result<Vec<cookie::Cookie<'static>>> {
|
||||
let (tx, rx) = bounded(1);
|
||||
MainPipe::send(
|
||||
self.activity_id,
|
||||
WebViewMessage::GetCookies(tx, url.to_string()),
|
||||
);
|
||||
rx.recv_timeout(MAIN_PIPE_TIMEOUT).map_err(Into::into)
|
||||
}
|
||||
|
||||
pub fn set_cookie(&self, #[allow(unused)] cookie: &cookie::Cookie<'_>) -> Result<()> {
|
||||
// Unsupported
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn delete_cookie(&self, #[allow(unused)] cookie: &cookie::Cookie<'_>) -> Result<()> {
|
||||
// Unsupported
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn cookies(&self) -> Result<Vec<cookie::Cookie<'static>>> {
|
||||
Ok(Vec::new())
|
||||
}
|
||||
|
||||
pub fn bounds(&self) -> Result<crate::Rect> {
|
||||
Ok(crate::Rect::default())
|
||||
}
|
||||
|
||||
pub fn set_bounds(&self, _bounds: crate::Rect) -> Result<()> {
|
||||
// Unsupported
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn set_visible(&self, _visible: bool) -> Result<()> {
|
||||
// Unsupported
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn focus(&self) -> Result<()> {
|
||||
// Unsupported
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn focus_parent(&self) -> Result<()> {
|
||||
// Unsupported
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
pub struct JniHandle {
|
||||
pub(crate) activity_id: ActivityId,
|
||||
}
|
||||
|
||||
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(&mut JNIEnv, &JObject, &JObject) + Send + 'static,
|
||||
{
|
||||
MainPipe::send(self.activity_id, WebViewMessage::Jni(Box::new(func)));
|
||||
}
|
||||
}
|
||||
|
||||
pub fn platform_webview_version() -> Result<String> {
|
||||
let (tx, rx) = bounded(1);
|
||||
let activity_id = loop {
|
||||
match first_activity_id() {
|
||||
Some(id) => break id,
|
||||
None => {
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
}
|
||||
};
|
||||
MainPipe::send(activity_id, WebViewMessage::GetWebViewVersion(tx));
|
||||
rx.recv_timeout(MAIN_PIPE_TIMEOUT)?
|
||||
}
|
||||
|
||||
/// Finds a class in the project scope.
|
||||
pub fn find_class<'a>(
|
||||
env: &mut JNIEnv<'a>,
|
||||
activity: &JObject<'_>,
|
||||
name: String,
|
||||
) -> JniResult<JClass<'a>> {
|
||||
let class_name = env.new_string(name.replace('/', "."))?;
|
||||
let my_class = env
|
||||
.call_method(
|
||||
activity,
|
||||
"getAppClass",
|
||||
"(Ljava/lang/String;)Ljava/lang/Class;",
|
||||
&[(&class_name).into()],
|
||||
)?
|
||||
.l()?;
|
||||
Ok(my_class.into())
|
||||
}
|
||||
|
||||
/// Dispatch a closure to run on the Android context.
|
||||
///
|
||||
/// The closure takes the JNI env, the Android activity instance and the possibly null webview.
|
||||
pub fn dispatch<F>(func: F)
|
||||
where
|
||||
F: FnOnce(&mut JNIEnv, &JObject, &JObject) + Send + 'static,
|
||||
{
|
||||
MainPipe::send(
|
||||
first_activity_id().expect("no available activity"),
|
||||
WebViewMessage::Jni(Box::new(func)),
|
||||
);
|
||||
}
|
||||
+56
@@ -0,0 +1,56 @@
|
||||
//! - WebView2 supports non-standard protocols only on Windows 10+, so we have to use a workaround.
|
||||
//! See <https://github.com/MicrosoftEdge/WebView2Feedback/issues/73>
|
||||
//! - On Android, there's no API for registering custom protocols, so this workaround is also used.
|
||||
//!
|
||||
//! The process looks like this:
|
||||
//!
|
||||
//! 1. Use [`apply_uri_work_around`] to convert the URI we want to navigate to
|
||||
//! 2. Intercept http(s) requests, test the request URI against [`is_work_around_uri`],
|
||||
//! if it matches, we apply [`revert_uri_work_around`] to the URI and feed it to the custom protocol handler
|
||||
|
||||
/// If the URI is a work around URI for this protocol which starts with `{http_or_https}://{protocol}.`
|
||||
pub fn is_work_around_uri(uri: &str, http_or_https: &str, protocol: &str) -> bool {
|
||||
uri
|
||||
.strip_prefix(http_or_https)
|
||||
.and_then(|rest| rest.strip_prefix("://"))
|
||||
.and_then(|rest| rest.strip_prefix(protocol))
|
||||
.and_then(|rest| rest.strip_prefix("."))
|
||||
.is_some()
|
||||
}
|
||||
|
||||
/// Conveting `{protocol}://localhost/abc` to `{http_or_https}://{protocol}.localhost/abc`
|
||||
pub fn apply_uri_work_around(uri: &str, http_or_https: &str, protocol: &str) -> String {
|
||||
uri.replace(
|
||||
&original_uri_prefix(protocol),
|
||||
&work_around_uri_prefix(http_or_https, protocol),
|
||||
)
|
||||
}
|
||||
|
||||
/// Conveting `{http_or_https}://{protocol}.localhost/abc` back to `{protocol}://localhost/abc`
|
||||
pub fn revert_uri_work_around(uri: &str, http_or_https: &str, protocol: &str) -> String {
|
||||
uri.replace(
|
||||
&work_around_uri_prefix(http_or_https, protocol),
|
||||
&original_uri_prefix(protocol),
|
||||
)
|
||||
}
|
||||
|
||||
pub fn original_uri_prefix(protocol: &str) -> String {
|
||||
format!("{protocol}://")
|
||||
}
|
||||
|
||||
pub fn work_around_uri_prefix(http_or_https: &str, protocol: &str) -> String {
|
||||
format!("{http_or_https}://{protocol}.")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::is_work_around_uri;
|
||||
|
||||
#[test]
|
||||
fn checks_if_custom_protocol_uri() {
|
||||
let scheme = "http";
|
||||
let uri = "http://wry.localhost/path/to/page";
|
||||
assert!(is_work_around_uri(uri, scheme, "wry"));
|
||||
assert!(!is_work_around_uri(uri, scheme, "asset"));
|
||||
}
|
||||
}
|
||||
Vendored
+80
@@ -0,0 +1,80 @@
|
||||
/// Convenient type alias of Result type for wry.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// Errors returned by wry.
|
||||
#[non_exhaustive]
|
||||
#[derive(thiserror::Error, Debug)]
|
||||
pub enum Error {
|
||||
#[cfg(gtk)]
|
||||
#[error(transparent)]
|
||||
GlibError(#[from] gtk::glib::Error),
|
||||
#[cfg(gtk)]
|
||||
#[error(transparent)]
|
||||
GlibBoolError(#[from] gtk::glib::BoolError),
|
||||
#[cfg(gtk)]
|
||||
#[error("Fail to fetch security manager")]
|
||||
MissingManager,
|
||||
#[cfg(gtk)]
|
||||
#[error("Couldn't find X11 Display")]
|
||||
X11DisplayNotFound,
|
||||
#[cfg(all(gtk, feature = "x11"))]
|
||||
#[error(transparent)]
|
||||
XlibError(#[from] x11_dl::error::OpenError),
|
||||
#[error("Failed to initialize the script")]
|
||||
InitScriptError,
|
||||
#[error("Bad RPC request: {0} ((1))")]
|
||||
RpcScriptError(String, String),
|
||||
#[error(transparent)]
|
||||
NulError(#[from] std::ffi::NulError),
|
||||
#[error(transparent)]
|
||||
ReceiverError(#[from] std::sync::mpsc::RecvError),
|
||||
#[cfg(target_os = "android")]
|
||||
#[error(transparent)]
|
||||
ReceiverTimeoutError(#[from] crossbeam_channel::RecvTimeoutError),
|
||||
#[error(transparent)]
|
||||
SenderError(#[from] std::sync::mpsc::SendError<String>),
|
||||
#[error("Failed to send the message")]
|
||||
MessageSender,
|
||||
#[error("IO error: {0}")]
|
||||
Io(#[from] std::io::Error),
|
||||
#[cfg(target_os = "windows")]
|
||||
#[error("WebView2 error: {0}")]
|
||||
WebView2Error(webview2_com::Error),
|
||||
#[error(transparent)]
|
||||
HttpError(#[from] http::Error),
|
||||
#[error("Infallible error, something went really wrong: {0}")]
|
||||
Infallible(#[from] std::convert::Infallible),
|
||||
#[cfg(target_os = "android")]
|
||||
#[error(transparent)]
|
||||
JniError(#[from] jni::errors::Error),
|
||||
#[error("Failed to create proxy endpoint")]
|
||||
ProxyEndpointCreationFailed,
|
||||
#[error(transparent)]
|
||||
WindowHandleError(#[from] raw_window_handle::HandleError),
|
||||
#[error("the window handle kind is not supported")]
|
||||
UnsupportedWindowHandle,
|
||||
#[error(transparent)]
|
||||
Utf8Error(#[from] std::str::Utf8Error),
|
||||
#[cfg(target_os = "android")]
|
||||
#[error(transparent)]
|
||||
CrossBeamRecvError(#[from] crossbeam_channel::RecvError),
|
||||
#[error("not on the main thread")]
|
||||
NotMainThread,
|
||||
#[error("Custom protocol task is invalid.")]
|
||||
CustomProtocolTaskInvalid,
|
||||
#[error("Failed to register URL scheme: {0}, could be due to invalid URL scheme or the scheme is already registered.")]
|
||||
UrlSchemeRegisterError(String),
|
||||
#[error("Duplicate custom protocol '{0}' registered on the WebViewBuilder")]
|
||||
DuplicateCustomProtocol(String),
|
||||
#[error("Duplicate custom protocol '{0}' registered on the same web context on Linux")]
|
||||
ContextDuplicateCustomProtocol(String),
|
||||
#[error(transparent)]
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
UrlParse(#[from] url::ParseError),
|
||||
#[cfg(any(target_os = "macos", target_os = "ios"))]
|
||||
#[error("data store is currently opened")]
|
||||
DataStoreInUse,
|
||||
#[cfg(target_os = "android")]
|
||||
#[error("Activity not found")]
|
||||
ActivityNotFound,
|
||||
}
|
||||
+225
@@ -0,0 +1,225 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! This is an internal implementation detail used by the Android backend to inject
|
||||
//! initialization scripts when `addDocumentStartJavaScript` is not supported.
|
||||
|
||||
use base64::{prelude::BASE64_STANDARD, Engine};
|
||||
use dom_query::Document;
|
||||
use http::{
|
||||
header::{HeaderValue, CONTENT_SECURITY_POLICY, CONTENT_TYPE},
|
||||
Response as HttpResponse,
|
||||
};
|
||||
use sha2::{Digest, Sha256};
|
||||
use std::borrow::Cow;
|
||||
|
||||
use crate::InitializationScript;
|
||||
|
||||
pub fn inject_scripts_into_html(
|
||||
mut response: HttpResponse<Cow<'static, [u8]>>,
|
||||
scripts: &[InitializationScript],
|
||||
) -> HttpResponse<Cow<'static, [u8]>> {
|
||||
if scripts.is_empty() {
|
||||
return response;
|
||||
}
|
||||
|
||||
let should_inject_scripts = response
|
||||
.headers()
|
||||
.get(CONTENT_TYPE)
|
||||
// Content-Type must begin with the media type, but is case-insensitive.
|
||||
// It may also be followed by any number of semicolon-delimited key value pairs.
|
||||
// We don't care about these here.
|
||||
// source: https://httpwg.org/specs/rfc9110.html#rfc.section.8.3.1
|
||||
.and_then(|content_type| content_type.to_str().ok())
|
||||
.map(|content_type_str| content_type_str.to_lowercase().starts_with("text/html"))
|
||||
.unwrap_or_default();
|
||||
|
||||
if !should_inject_scripts {
|
||||
return response;
|
||||
}
|
||||
|
||||
let document = Document::from(String::from_utf8_lossy(response.body()).as_ref());
|
||||
let csp = response.headers_mut().get_mut(CONTENT_SECURITY_POLICY);
|
||||
|
||||
// Get or create head element
|
||||
let head = document.head().unwrap_or_else(|| {
|
||||
let html = document.html_root();
|
||||
let head = document.tree.new_element("head");
|
||||
html.prepend_child(&head);
|
||||
head
|
||||
});
|
||||
|
||||
// Iterate in reverse order since we are prepending each script to the head tag
|
||||
let mut hashes = Vec::new();
|
||||
for script in scripts.iter().rev().map(|s| &s.script) {
|
||||
let script_tag = document.tree.new_element("script");
|
||||
script_tag.set_text(script.as_str());
|
||||
head.prepend_child(&script_tag);
|
||||
if csp.is_some() {
|
||||
hashes.push(hash_script(script));
|
||||
}
|
||||
}
|
||||
|
||||
if let Some(csp) = csp {
|
||||
let csp_string = csp.to_str().unwrap().to_string();
|
||||
let csp_string = if csp_string.contains("script-src") {
|
||||
csp_string.replace("script-src", &format!("script-src {}", hashes.join(" ")))
|
||||
} else {
|
||||
format!("{csp_string} script-src {}", hashes.join(" "))
|
||||
};
|
||||
*csp = HeaderValue::from_str(&csp_string).unwrap();
|
||||
}
|
||||
|
||||
*response.body_mut() = Cow::Owned(document.html().as_bytes().to_vec());
|
||||
response
|
||||
}
|
||||
|
||||
fn hash_script(script: &str) -> String {
|
||||
let mut hasher = Sha256::new();
|
||||
hasher.update(script);
|
||||
let hash = hasher.finalize();
|
||||
format!("'sha256-{}'", BASE64_STANDARD.encode(hash))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use http::StatusCode;
|
||||
|
||||
#[test]
|
||||
fn test_no_scripts_returns_original_response() {
|
||||
let body = "<html><head></head><body>Test</body></html>";
|
||||
|
||||
let result = run(body, "text/html", vec![]);
|
||||
|
||||
assert_eq!(result, body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_non_html_response_not_modified() {
|
||||
let body = r#"{"key": "value"}"#;
|
||||
let scripts = vec!["console.log('test');".to_string()];
|
||||
|
||||
let result = run(body, "application/json", scripts);
|
||||
|
||||
assert_eq!(result, body);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inject_single_script() {
|
||||
let body = "<html><head></head><body>Content</body></html>";
|
||||
let scripts = vec!["console.log('injected');".to_string()];
|
||||
|
||||
let result = run(body, "text/html", scripts);
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
"<html><head><script>console.log('injected');</script></head><body>Content</body></html>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inject_multiple_scripts() {
|
||||
let body = "<html><head></head><body>Content</body></html>";
|
||||
let scripts = vec![
|
||||
"var first = 1;".to_owned(),
|
||||
"let second = 2;".to_owned(),
|
||||
"const third = 3;".to_owned(),
|
||||
"window.test = () => console.log('test');".to_owned(),
|
||||
];
|
||||
|
||||
let result = run(body, "text/html", scripts);
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
"<html><head><script>var first = 1;</script><script>let second = 2;</script><script>const third = 3;</script><script>window.test = () => console.log('test');</script></head><body>Content</body></html>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inject_script_creates_head_if_missing() {
|
||||
let body = "<html><body>Content</body></html>";
|
||||
let scripts = vec!["console.log('test');".to_string()];
|
||||
|
||||
let result = run(body, "text/html", scripts);
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
"<html><head><script>console.log('test');</script></head><body>Content</body></html>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_inject_script_creates_html_structure_if_missing() {
|
||||
let body = "Just some text";
|
||||
let scripts = vec!["console.log('test');".to_string()];
|
||||
|
||||
let result = run(body, "text/html", scripts);
|
||||
|
||||
assert_eq!(
|
||||
result,
|
||||
"<html><head><script>console.log('test');</script></head><body>Just some text</body></html>"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_csp_header_updated_with_script_hashes() {
|
||||
let body = "<html><head></head><body>Content</body></html>";
|
||||
let mut response = create_response(body, "text/html");
|
||||
response.headers_mut().insert(
|
||||
CONTENT_SECURITY_POLICY,
|
||||
HeaderValue::from_static("default-src 'self'"),
|
||||
);
|
||||
|
||||
let script_code = "console.log('test');";
|
||||
let scripts = vec![script_code.to_string()];
|
||||
|
||||
let scripts: Vec<InitializationScript> = scripts
|
||||
.into_iter()
|
||||
.map(|script| InitializationScript {
|
||||
script,
|
||||
for_main_frame_only: true,
|
||||
})
|
||||
.collect();
|
||||
let result = inject_scripts_into_html(response, &scripts);
|
||||
let result_body = String::from_utf8_lossy(result.body()).to_string();
|
||||
let csp = result.headers().get(CONTENT_SECURITY_POLICY).unwrap();
|
||||
let csp_str = csp.to_str().unwrap();
|
||||
|
||||
assert_eq!(
|
||||
result_body,
|
||||
"<html><head><script>console.log('test');</script></head><body>Content</body></html>"
|
||||
);
|
||||
assert_eq!(
|
||||
csp_str,
|
||||
"default-src 'self' script-src 'sha256-3x8DE279hr8o/Aq0dEdH4WApIwn5rbRKhugPzn6Bofw='"
|
||||
);
|
||||
}
|
||||
|
||||
fn create_response(body: &str, content_type: &'static str) -> HttpResponse<Cow<'static, [u8]>> {
|
||||
let mut response = HttpResponse::builder()
|
||||
.status(StatusCode::OK)
|
||||
.body(Cow::Owned(body.as_bytes().to_vec()))
|
||||
.unwrap();
|
||||
response
|
||||
.headers_mut()
|
||||
.insert(CONTENT_TYPE, HeaderValue::from_static(content_type));
|
||||
|
||||
response
|
||||
}
|
||||
|
||||
/// Helper function to create a response, inject scripts, and return the body as a string
|
||||
fn run(body: &str, content_type: &'static str, scripts: Vec<String>) -> String {
|
||||
let response = create_response(body, content_type);
|
||||
let scripts: Vec<InitializationScript> = scripts
|
||||
.into_iter()
|
||||
.map(|script| InitializationScript {
|
||||
script,
|
||||
for_main_frame_only: true,
|
||||
})
|
||||
.collect();
|
||||
let result = inject_scripts_into_html(response, &scripts);
|
||||
String::from_utf8_lossy(result.body()).to_string()
|
||||
}
|
||||
}
|
||||
Vendored
+2514
File diff suppressed because it is too large.
Load diff
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ProxyEndpoint {
|
||||
/// Proxy server host (e.g. 192.168.0.100, localhost, example.com, etc.)
|
||||
pub host: String,
|
||||
/// Proxy server port (e.g. 1080, 3128, etc.)
|
||||
pub port: String,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub enum ProxyConfig {
|
||||
/// Connect to proxy server via HTTP CONNECT
|
||||
Http(ProxyEndpoint),
|
||||
/// Connect to proxy server via SOCKSv5
|
||||
Socks5(ProxyEndpoint),
|
||||
}
|
||||
Vendored
+13
@@ -0,0 +1,13 @@
|
||||
use std::sync::atomic::{AtomicU32, Ordering};
|
||||
|
||||
pub struct Counter(AtomicU32);
|
||||
|
||||
impl Counter {
|
||||
pub const fn new() -> Self {
|
||||
Self(AtomicU32::new(1))
|
||||
}
|
||||
|
||||
pub fn next(&self) -> u32 {
|
||||
self.0.fetch_add(1, Ordering::Relaxed)
|
||||
}
|
||||
}
|
||||
Vendored
+113
@@ -0,0 +1,113 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#[cfg(gtk)]
|
||||
use crate::webkitgtk::WebContextImpl;
|
||||
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
path::{Path, PathBuf},
|
||||
};
|
||||
|
||||
/// A context that is shared between multiple [`WebView`]s.
|
||||
///
|
||||
/// A browser would have a context for all the normal tabs and a different context for all the
|
||||
/// private/incognito tabs.
|
||||
///
|
||||
/// # Warning
|
||||
///
|
||||
/// If [`WebView`] is created by a WebContext. Dropping `WebContext` will cause [`WebView`] lose
|
||||
/// some actions like custom protocol on Mac. Please keep both instances when you still wish to
|
||||
/// interact with them.
|
||||
///
|
||||
/// [`WebView`]: crate::WebView
|
||||
#[derive(Debug)]
|
||||
pub struct WebContext {
|
||||
data_directory: Option<PathBuf>,
|
||||
#[allow(dead_code)] // It's not needed on Windows and macOS.
|
||||
pub(crate) os: WebContextImpl,
|
||||
#[allow(dead_code)] // It's not needed on Windows and macOS.
|
||||
pub(crate) custom_protocols: HashSet<String>,
|
||||
}
|
||||
|
||||
impl WebContext {
|
||||
/// Create a new [`WebContext`].
|
||||
///
|
||||
/// - `data_directory`: Whether the WebView window should have a custom user data path.
|
||||
/// This is useful in Windows when a bundled application can't have the webview data inside `Program Files`.
|
||||
///
|
||||
/// ## Platform-specific:
|
||||
///
|
||||
/// - **Windows**: Webview instances with different `CoreWebView2EnvironmentOptions` must have different `data_directory`s [^1]
|
||||
///
|
||||
/// [^1]: <https://learn.microsoft.com/en-us/dotnet/api/microsoft.web.webview2.core.corewebview2environment.createcorewebview2controllerasync?view=webview2-dotnet-1.0.3719.77#:~:text=WebView%20creation%20fails%20if%20a%20running%20instance%20using%20the%20same%20user%20data%20folder%20exists%2C%20and%20the%20Environment%20objects%20have%20different%20CoreWebView2EnvironmentOptions.>
|
||||
pub fn new(data_directory: Option<PathBuf>) -> Self {
|
||||
Self {
|
||||
os: WebContextImpl::new(data_directory.as_deref()),
|
||||
data_directory,
|
||||
custom_protocols: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(gtk)]
|
||||
pub(crate) fn new_ephemeral() -> Self {
|
||||
Self {
|
||||
os: WebContextImpl::new_ephemeral(),
|
||||
data_directory: None,
|
||||
custom_protocols: Default::default(),
|
||||
}
|
||||
}
|
||||
|
||||
/// A reference to the data directory the context was created with.
|
||||
pub fn data_directory(&self) -> Option<&Path> {
|
||||
self.data_directory.as_deref()
|
||||
}
|
||||
|
||||
#[cfg(any(
|
||||
target_os = "linux",
|
||||
target_os = "dragonfly",
|
||||
target_os = "freebsd",
|
||||
target_os = "netbsd",
|
||||
target_os = "openbsd",
|
||||
))]
|
||||
pub(crate) fn register_custom_protocol(&mut self, name: String) -> Result<(), crate::Error> {
|
||||
if self.is_custom_protocol_registered(&name) {
|
||||
return Err(crate::Error::ContextDuplicateCustomProtocol(name));
|
||||
}
|
||||
self.custom_protocols.insert(name);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Check if a custom protocol has been registered on this context.
|
||||
pub fn is_custom_protocol_registered(&self, name: &str) -> bool {
|
||||
self.custom_protocols.contains(name)
|
||||
}
|
||||
|
||||
/// Set if this context allows automation.
|
||||
///
|
||||
/// **Note:** This is currently only enforced on Linux, and has the stipulation that
|
||||
/// only 1 context allows automation at a time.
|
||||
pub fn set_allows_automation(&mut self, flag: bool) {
|
||||
self.os.set_allows_automation(flag);
|
||||
}
|
||||
}
|
||||
|
||||
impl Default for WebContext {
|
||||
fn default() -> Self {
|
||||
Self::new(None)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(not(gtk))]
|
||||
#[derive(Debug)]
|
||||
pub(crate) struct WebContextImpl;
|
||||
|
||||
#[cfg(not(gtk))]
|
||||
impl WebContextImpl {
|
||||
fn new(_: Option<&Path>) -> Self {
|
||||
Self
|
||||
}
|
||||
|
||||
fn set_allows_automation(&mut self, _flag: bool) {}
|
||||
}
|
||||
+143
@@ -0,0 +1,143 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{
|
||||
cell::{Cell, UnsafeCell},
|
||||
path::PathBuf,
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
use gtk::{glib::GString, prelude::*};
|
||||
use webkit2gtk::WebView;
|
||||
|
||||
use crate::DragDropEvent;
|
||||
|
||||
#[derive(PartialEq, Eq, PartialOrd, Ord, Clone, Copy, Debug)]
|
||||
enum DragControllerState {
|
||||
Entered,
|
||||
Leaving,
|
||||
Left,
|
||||
}
|
||||
|
||||
struct DragDropController {
|
||||
paths: UnsafeCell<Option<Vec<PathBuf>>>,
|
||||
state: Cell<DragControllerState>,
|
||||
position: Cell<(i32, i32)>,
|
||||
handler: Box<dyn Fn(DragDropEvent) -> bool>,
|
||||
}
|
||||
|
||||
impl DragDropController {
|
||||
fn new(handler: Box<dyn Fn(DragDropEvent) -> bool>) -> Self {
|
||||
Self {
|
||||
handler,
|
||||
paths: UnsafeCell::new(None),
|
||||
state: Cell::new(DragControllerState::Left),
|
||||
position: Cell::new((0, 0)),
|
||||
}
|
||||
}
|
||||
|
||||
fn store_paths(&self, paths: Vec<PathBuf>) {
|
||||
unsafe { *self.paths.get() = Some(paths) };
|
||||
}
|
||||
|
||||
fn take_paths(&self) -> Option<Vec<PathBuf>> {
|
||||
unsafe { &mut *self.paths.get() }.take()
|
||||
}
|
||||
|
||||
fn store_position(&self, position: (i32, i32)) {
|
||||
self.position.replace(position);
|
||||
}
|
||||
|
||||
fn enter(&self) {
|
||||
self.state.set(DragControllerState::Entered);
|
||||
}
|
||||
|
||||
fn leaving(&self) {
|
||||
self.state.set(DragControllerState::Leaving);
|
||||
}
|
||||
|
||||
fn leave(&self) {
|
||||
self.state.set(DragControllerState::Left);
|
||||
}
|
||||
|
||||
fn state(&self) -> DragControllerState {
|
||||
self.state.get()
|
||||
}
|
||||
|
||||
fn call(&self, event: DragDropEvent) -> bool {
|
||||
(self.handler)(event)
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn connect_drag_event(webview: &WebView, handler: Box<dyn Fn(DragDropEvent) -> bool>) {
|
||||
let controller = Rc::new(DragDropController::new(handler));
|
||||
|
||||
{
|
||||
let controller = controller.clone();
|
||||
webview.connect_drag_data_received(move |_, _, _, _, data, info, _| {
|
||||
if info == 2 {
|
||||
let uris = data.uris();
|
||||
let paths = uris.iter().map(path_buf_from_uri).collect::<Vec<_>>();
|
||||
controller.enter();
|
||||
controller.call(DragDropEvent::Enter {
|
||||
paths: paths.clone(),
|
||||
position: controller.position.get(),
|
||||
});
|
||||
controller.store_paths(paths);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
let controller = controller.clone();
|
||||
webview.connect_drag_motion(move |_, _, x, y, _| {
|
||||
if controller.state() == DragControllerState::Entered {
|
||||
controller.call(DragDropEvent::Over { position: (x, y) });
|
||||
} else {
|
||||
controller.store_position((x, y));
|
||||
}
|
||||
false
|
||||
});
|
||||
}
|
||||
|
||||
{
|
||||
let controller = controller.clone();
|
||||
webview.connect_drag_drop(move |_, ctx, x, y, time| {
|
||||
if controller.state() == DragControllerState::Leaving {
|
||||
if let Some(paths) = controller.take_paths() {
|
||||
ctx.drop_finish(true, time);
|
||||
controller.leave();
|
||||
return controller.call(DragDropEvent::Drop {
|
||||
paths,
|
||||
position: (x, y),
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
false
|
||||
});
|
||||
}
|
||||
|
||||
webview.connect_drag_leave(move |_w, _, _| {
|
||||
if controller.state() != DragControllerState::Left {
|
||||
controller.leaving();
|
||||
let controller = controller.clone();
|
||||
gtk::glib::idle_add_local_once(move || {
|
||||
if controller.state() == DragControllerState::Leaving {
|
||||
controller.leave();
|
||||
controller.call(DragDropEvent::Leave);
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn path_buf_from_uri(gstr: &GString) -> PathBuf {
|
||||
let path = gstr.as_str();
|
||||
let path = path.strip_prefix("file://").unwrap_or(path);
|
||||
let path = percent_encoding::percent_decode(path.as_bytes())
|
||||
.decode_utf8_lossy()
|
||||
.to_string();
|
||||
PathBuf::from(path)
|
||||
}
|
||||
Vendored
+1249
File diff suppressed because it is too large.
Load diff
+187
@@ -0,0 +1,187 @@
|
||||
use std::{cell::RefCell, rc::Rc};
|
||||
|
||||
use gtk::{
|
||||
gdk::{EventButton, EventMask, ModifierType},
|
||||
prelude::*,
|
||||
};
|
||||
use webkit2gtk::{WebView, WebViewExt};
|
||||
|
||||
pub fn setup(webview: &WebView) {
|
||||
webview.add_events(EventMask::BUTTON1_MOTION_MASK | EventMask::BUTTON_PRESS_MASK);
|
||||
|
||||
let bf_state = BackForwardState(Rc::new(RefCell::new(0)));
|
||||
|
||||
let bf_state_c = bf_state.clone();
|
||||
webview.connect_button_press_event(move |webview, event| {
|
||||
let mut inhibit = false;
|
||||
match event.button() {
|
||||
// back button
|
||||
8 => {
|
||||
inhibit = true;
|
||||
bf_state_c.set(BACK);
|
||||
webview.run_javascript(
|
||||
&create_js_mouse_event(event, true, &bf_state_c),
|
||||
None::<>k::gio::Cancellable>,
|
||||
|_| {},
|
||||
);
|
||||
}
|
||||
// forward button
|
||||
9 => {
|
||||
inhibit = true;
|
||||
bf_state_c.set(FORWARD);
|
||||
webview.run_javascript(
|
||||
&create_js_mouse_event(event, true, &bf_state_c),
|
||||
None::<>k::gio::Cancellable>,
|
||||
|_| {},
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
|
||||
if inhibit {
|
||||
gtk::glib::Propagation::Stop
|
||||
} else {
|
||||
gtk::glib::Propagation::Proceed
|
||||
}
|
||||
});
|
||||
|
||||
let bf_state_c = bf_state.clone();
|
||||
webview.connect_button_release_event(move |webview, event| {
|
||||
let mut inhibit = false;
|
||||
match event.button() {
|
||||
// back button
|
||||
8 => {
|
||||
inhibit = true;
|
||||
bf_state_c.remove(BACK);
|
||||
webview.run_javascript(
|
||||
&create_js_mouse_event(event, false, &bf_state_c),
|
||||
None::<>k::gio::Cancellable>,
|
||||
|_| {},
|
||||
);
|
||||
}
|
||||
// forward button
|
||||
9 => {
|
||||
inhibit = true;
|
||||
bf_state_c.remove(FORWARD);
|
||||
webview.run_javascript(
|
||||
&create_js_mouse_event(event, false, &bf_state_c),
|
||||
None::<>k::gio::Cancellable>,
|
||||
|_| {},
|
||||
);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
if inhibit {
|
||||
gtk::glib::Propagation::Stop
|
||||
} else {
|
||||
gtk::glib::Propagation::Proceed
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
fn create_js_mouse_event(event: &EventButton, pressed: bool, state: &BackForwardState) -> String {
|
||||
let event_name = if pressed { "mousedown" } else { "mouseup" };
|
||||
// js equivalent https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
|
||||
let button = if event.button() == 8 { 3 } else { 4 };
|
||||
let (x, y) = event.position();
|
||||
let (x, y) = (x as i32, y as i32);
|
||||
let modifers_state = event.state();
|
||||
let mut buttons = 0;
|
||||
// left button
|
||||
if modifers_state.contains(ModifierType::BUTTON1_MASK) {
|
||||
buttons += 1;
|
||||
}
|
||||
// right button
|
||||
if modifers_state.contains(ModifierType::BUTTON3_MASK) {
|
||||
buttons += 2;
|
||||
}
|
||||
// middle button
|
||||
if modifers_state.contains(ModifierType::BUTTON2_MASK) {
|
||||
buttons += 4;
|
||||
}
|
||||
// back button
|
||||
if state.has(BACK) {
|
||||
buttons += 8;
|
||||
}
|
||||
// if modifers_state.contains(ModifierType::BUTTON4_MASK) {
|
||||
// buttons += 8;
|
||||
// }
|
||||
// forward button
|
||||
if state.has(FORWARD) {
|
||||
buttons += 16;
|
||||
}
|
||||
// if modifers_state.contains(ModifierType::BUTTON5_MASK) {
|
||||
// buttons += 16;
|
||||
// }
|
||||
format!(
|
||||
r#"(() => {{
|
||||
const el = document.elementFromPoint({x},{y});
|
||||
const ev = new MouseEvent('{event_name}', {{
|
||||
view: window,
|
||||
button: {button},
|
||||
buttons: {buttons},
|
||||
x: {x},
|
||||
y: {y},
|
||||
bubbles: true,
|
||||
detail: {detail},
|
||||
cancelBubble: false,
|
||||
cancelable: true,
|
||||
clientX: {x},
|
||||
clientY: {y},
|
||||
composed: true,
|
||||
layerX: {x},
|
||||
layerY: {y},
|
||||
pageX: {x},
|
||||
pageY: {y},
|
||||
screenX: window.screenX + {x},
|
||||
screenY: window.screenY + {y},
|
||||
ctrlKey: {ctrl_key},
|
||||
metaKey: {meta_key},
|
||||
shiftKey: {shift_key},
|
||||
altKey: {alt_key},
|
||||
}});
|
||||
el.dispatchEvent(ev)
|
||||
if (!ev.defaultPrevented && "{event_name}" === "mouseup") {{
|
||||
if (ev.button === 3) {{
|
||||
window.history.back();
|
||||
}}
|
||||
if (ev.button === 4) {{
|
||||
window.history.forward();
|
||||
}}
|
||||
}}
|
||||
}})()"#,
|
||||
event_name = event_name,
|
||||
x = x,
|
||||
y = y,
|
||||
detail = event.click_count().unwrap_or(1),
|
||||
ctrl_key = modifers_state.contains(ModifierType::CONTROL_MASK),
|
||||
alt_key = modifers_state.contains(ModifierType::MOD1_MASK),
|
||||
shift_key = modifers_state.contains(ModifierType::SHIFT_MASK),
|
||||
meta_key = modifers_state.contains(ModifierType::SUPER_MASK),
|
||||
button = button,
|
||||
buttons = buttons,
|
||||
)
|
||||
}
|
||||
|
||||
// Internal modifiers to track whether BACK/FORWARD buttons are pressed
|
||||
const BACK: u8 = 0b01;
|
||||
const FORWARD: u8 = 0b10;
|
||||
|
||||
/// A single u8 that stores whether [BACK] and [FORWARD] are pressed or not
|
||||
#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
|
||||
struct BackForwardState(Rc<RefCell<u8>>);
|
||||
|
||||
impl BackForwardState {
|
||||
fn set(&self, button: u8) {
|
||||
*self.0.borrow_mut() |= button
|
||||
}
|
||||
|
||||
fn remove(&self, button: u8) {
|
||||
*self.0.borrow_mut() &= !button
|
||||
}
|
||||
|
||||
fn has(&self, button: u8) -> bool {
|
||||
let state = *self.0.borrow();
|
||||
state & !button != state
|
||||
}
|
||||
}
|
||||
+404
@@ -0,0 +1,404 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
//! Unix platform extensions for [`WebContext`](super::WebContext).
|
||||
|
||||
use crate::{Error, RequestAsyncResponder};
|
||||
use gtk::glib::{self, MainContext, ObjectExt};
|
||||
use http::{header::CONTENT_TYPE, HeaderName, HeaderValue, Request, Response as HttpResponse};
|
||||
use soup::{MessageHeaders, MessageHeadersType};
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
cell::RefCell,
|
||||
env::current_dir,
|
||||
path::{Path, PathBuf},
|
||||
rc::Rc,
|
||||
};
|
||||
use webkit2gtk::{
|
||||
ApplicationInfo, AutomationSessionExt, CookiePersistentStorage, DownloadExt, SecurityManagerExt,
|
||||
URIRequest, URIRequestExt, URISchemeRequest, URISchemeRequestExt, URISchemeResponse,
|
||||
URISchemeResponseExt, WebContext, WebContextExt as Webkit2gtkContextExt, WebView, WebViewExt,
|
||||
};
|
||||
|
||||
#[derive(Debug)]
|
||||
pub struct WebContextImpl {
|
||||
context: WebContext,
|
||||
automation: bool,
|
||||
app_info: Option<ApplicationInfo>,
|
||||
}
|
||||
|
||||
impl WebContextImpl {
|
||||
pub fn new(data_directory: Option<&Path>) -> Self {
|
||||
use webkit2gtk::{CookieManagerExt, WebsiteDataManager, WebsiteDataManagerExt};
|
||||
let mut context_builder = WebContext::builder();
|
||||
if let Some(data_directory) = data_directory {
|
||||
let data_manager = WebsiteDataManager::builder()
|
||||
// TODO: Consider taking a cache_directory so this can be in XDG_CACHE_HOME.
|
||||
.base_cache_directory(data_directory.to_string_lossy())
|
||||
.base_data_directory(data_directory.to_string_lossy())
|
||||
.build();
|
||||
if let Some(cookie_manager) = data_manager.cookie_manager() {
|
||||
cookie_manager.set_persistent_storage(
|
||||
&data_directory.join("cookies").to_string_lossy(),
|
||||
CookiePersistentStorage::Text,
|
||||
);
|
||||
}
|
||||
context_builder = context_builder.website_data_manager(&data_manager);
|
||||
}
|
||||
let context = context_builder.build();
|
||||
|
||||
Self::create_context(context)
|
||||
}
|
||||
|
||||
pub fn new_ephemeral() -> Self {
|
||||
let context = WebContext::new_ephemeral();
|
||||
|
||||
Self::create_context(context)
|
||||
}
|
||||
|
||||
pub fn create_context(context: WebContext) -> Self {
|
||||
let automation = false;
|
||||
context.set_automation_allowed(automation);
|
||||
|
||||
// e.g. wry 0.9.4
|
||||
let app_info = ApplicationInfo::new();
|
||||
app_info.set_name(env!("CARGO_PKG_NAME"));
|
||||
app_info.set_version(
|
||||
env!("CARGO_PKG_VERSION_MAJOR")
|
||||
.parse()
|
||||
.expect("invalid wry version major"),
|
||||
env!("CARGO_PKG_VERSION_MINOR")
|
||||
.parse()
|
||||
.expect("invalid wry version minor"),
|
||||
env!("CARGO_PKG_VERSION_PATCH")
|
||||
.parse()
|
||||
.expect("invalid wry version patch"),
|
||||
);
|
||||
|
||||
Self {
|
||||
context,
|
||||
automation,
|
||||
app_info: Some(app_info),
|
||||
}
|
||||
}
|
||||
|
||||
pub fn set_allows_automation(&mut self, flag: bool) {
|
||||
self.automation = flag;
|
||||
self.context.set_automation_allowed(flag);
|
||||
}
|
||||
|
||||
pub fn set_web_extensions_directory(&mut self, path: &Path) {
|
||||
self
|
||||
.context
|
||||
.set_web_extensions_directory(&path.to_string_lossy());
|
||||
}
|
||||
}
|
||||
|
||||
/// [`WebContext`](super::WebContext) items that only matter on unix.
|
||||
pub trait WebContextExt {
|
||||
/// The GTK [`WebContext`] of all webviews in the context.
|
||||
fn context(&self) -> &WebContext;
|
||||
|
||||
/// Register a custom protocol to the web context.
|
||||
fn register_uri_scheme<F>(&mut self, name: &str, handler: F) -> crate::Result<()>
|
||||
where
|
||||
F: Fn(crate::WebViewId, Request<Vec<u8>>, RequestAsyncResponder) + 'static;
|
||||
|
||||
/// Loads a URI for a [`WebView`].
|
||||
fn load_uri(&self, webview: WebView, url: String, headers: Option<http::HeaderMap>);
|
||||
|
||||
/// If the context allows automation.
|
||||
///
|
||||
/// **Note:** `libwebkit2gtk` only allows 1 automation context at a time.
|
||||
fn allows_automation(&self) -> bool;
|
||||
|
||||
fn register_automation(&mut self, webview: WebView);
|
||||
|
||||
fn register_download_handler(
|
||||
&mut self,
|
||||
download_started_callback: Option<Box<dyn FnMut(String, &mut PathBuf) -> bool>>,
|
||||
download_completed_callback: Option<Rc<dyn Fn(String, Option<PathBuf>, bool) + 'static>>,
|
||||
);
|
||||
}
|
||||
|
||||
impl WebContextExt for super::WebContext {
|
||||
fn context(&self) -> &WebContext {
|
||||
&self.os.context
|
||||
}
|
||||
|
||||
fn register_uri_scheme<F>(&mut self, name: &str, handler: F) -> crate::Result<()>
|
||||
where
|
||||
F: Fn(crate::WebViewId, Request<Vec<u8>>, RequestAsyncResponder) + 'static,
|
||||
{
|
||||
self.register_custom_protocol(name.to_owned())?;
|
||||
|
||||
// Enable secure context
|
||||
self
|
||||
.os
|
||||
.context
|
||||
.security_manager()
|
||||
.ok_or(Error::MissingManager)?
|
||||
.register_uri_scheme_as_secure(name);
|
||||
|
||||
self.os.context.register_uri_scheme(name, move |request| {
|
||||
#[cfg(feature = "tracing")]
|
||||
let span = tracing::info_span!(parent: None, "wry::custom_protocol::handle", uri = tracing::field::Empty).entered();
|
||||
|
||||
if let Some(uri) = request.uri() {
|
||||
let uri = uri.as_str();
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
span.record("uri", uri);
|
||||
|
||||
#[allow(unused_mut)]
|
||||
let mut http_request = Request::builder().uri(uri).method("GET");
|
||||
|
||||
// Set request http headers
|
||||
if let Some(headers) = request.http_headers() {
|
||||
if let Some(map) = http_request.headers_mut() {
|
||||
headers.foreach(move |k, v| {
|
||||
if let Ok(name) = HeaderName::from_bytes(k.as_bytes()) {
|
||||
if let Ok(value) = HeaderValue::from_bytes(v.as_bytes()) {
|
||||
map.insert(name, value);
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Set request http method
|
||||
if let Some(method) = request.http_method() {
|
||||
http_request = http_request.method(method.as_str());
|
||||
}
|
||||
|
||||
let body;
|
||||
#[cfg(feature = "linux-body")]
|
||||
{
|
||||
use gtk::{gdk::prelude::InputStreamExtManual, gio::Cancellable};
|
||||
|
||||
// Set request http body
|
||||
let cancellable: Option<&Cancellable> = None;
|
||||
body = request
|
||||
.http_body()
|
||||
.map(|s| {
|
||||
const BUFFER_LEN: usize = 1024;
|
||||
let mut result = Vec::new();
|
||||
let mut buffer = vec![0; BUFFER_LEN];
|
||||
while let Ok(count) = s.read(&mut buffer[..], cancellable) {
|
||||
if count == BUFFER_LEN {
|
||||
result.append(&mut buffer);
|
||||
buffer.resize(BUFFER_LEN, 0);
|
||||
} else {
|
||||
buffer.truncate(count);
|
||||
result.append(&mut buffer);
|
||||
break;
|
||||
}
|
||||
}
|
||||
result
|
||||
})
|
||||
.unwrap_or_default();
|
||||
}
|
||||
#[cfg(not(feature = "linux-body"))]
|
||||
{
|
||||
body = Vec::new();
|
||||
}
|
||||
|
||||
let http_request = match http_request.body(body) {
|
||||
Ok(req) => req,
|
||||
Err(_) => {
|
||||
request.finish_error(&mut gtk::glib::Error::new(
|
||||
glib::UriError::Failed,
|
||||
"Internal server error: could not create request.",
|
||||
));
|
||||
return;
|
||||
}
|
||||
};
|
||||
|
||||
let request_ = MainThreadRequest(request.clone());
|
||||
let responder: Box<dyn FnOnce(HttpResponse<Cow<'static, [u8]>>)> =
|
||||
Box::new(move |http_response| {
|
||||
MainContext::default().invoke(move || {
|
||||
let buffer = http_response.body();
|
||||
let input = gtk::gio::MemoryInputStream::from_bytes(>k::glib::Bytes::from(buffer));
|
||||
let content_type = http_response
|
||||
.headers()
|
||||
.get(CONTENT_TYPE)
|
||||
.and_then(|h| h.to_str().ok());
|
||||
|
||||
let response = URISchemeResponse::new(&input, buffer.len() as i64);
|
||||
response.set_status(http_response.status().as_u16() as u32, None);
|
||||
if let Some(content_type) = content_type {
|
||||
response.set_content_type(content_type);
|
||||
}
|
||||
|
||||
let headers = MessageHeaders::new(MessageHeadersType::Response);
|
||||
for (name, value) in http_response.headers().into_iter() {
|
||||
headers.append(name.as_str(), value.to_str().unwrap_or(""));
|
||||
}
|
||||
response.set_http_headers(headers);
|
||||
request_.finish_with_response(&response);
|
||||
});
|
||||
|
||||
});
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
let _span = tracing::info_span!("wry::custom_protocol::call_handler").entered();
|
||||
|
||||
let webview_id = request
|
||||
.web_view()
|
||||
.and_then(|w| unsafe { w.data::<String>(super::WEBVIEW_ID) })
|
||||
.map(|id| unsafe { id.as_ref().clone() })
|
||||
.unwrap_or_default();
|
||||
|
||||
handler(&webview_id, http_request, RequestAsyncResponder { responder });
|
||||
} else {
|
||||
request.finish_error(&mut glib::Error::new(
|
||||
glib::FileError::Exist,
|
||||
"Could not get uri.",
|
||||
));
|
||||
}
|
||||
});
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn load_uri(&self, webview: WebView, uri: String, headers: Option<http::HeaderMap>) {
|
||||
if let Some(headers) = headers {
|
||||
let req = URIRequest::builder().uri(&uri).build();
|
||||
|
||||
if let Some(ref mut req_headers) = req.http_headers() {
|
||||
for (header, value) in headers.iter() {
|
||||
req_headers.append(
|
||||
header.to_string().as_str(),
|
||||
value.to_str().unwrap_or_default(),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
webview.load_request(&req);
|
||||
} else {
|
||||
webview.load_uri(&uri);
|
||||
}
|
||||
}
|
||||
|
||||
fn allows_automation(&self) -> bool {
|
||||
self.os.automation
|
||||
}
|
||||
|
||||
fn register_automation(&mut self, webview: WebView) {
|
||||
if let (true, Some(app_info)) = (self.os.automation, self.os.app_info.take()) {
|
||||
self.os.context.connect_automation_started(move |_, auto| {
|
||||
let webview = webview.clone();
|
||||
auto.set_application_info(&app_info);
|
||||
|
||||
// We do **NOT** support arbitrarily creating new webviews.
|
||||
// To support this in the future, we would need a way to specify the
|
||||
// default WindowBuilder to use to create the window it will use, and
|
||||
// possibly "default" webview attributes. Difficulty comes in for controlling
|
||||
// the owned Window that would need to be used.
|
||||
//
|
||||
// Instead, we just pass the first created webview.
|
||||
auto.connect_create_web_view(None, move |_| webview.clone());
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
fn register_download_handler(
|
||||
&mut self,
|
||||
download_started_handler: Option<Box<dyn FnMut(String, &mut PathBuf) -> bool>>,
|
||||
download_completed_handler: Option<Rc<dyn Fn(String, Option<PathBuf>, bool) + 'static>>,
|
||||
) {
|
||||
let context = &self.os.context;
|
||||
|
||||
let download_started_handler = Rc::new(RefCell::new(download_started_handler));
|
||||
let failed = Rc::new(RefCell::new(false));
|
||||
|
||||
context.connect_download_started(move |_context, download| {
|
||||
let download_started_handler = download_started_handler.clone();
|
||||
download.connect_decide_destination(move |download, suggested_filename| {
|
||||
if let Some(uri) = download.request().and_then(|req| req.uri()) {
|
||||
let uri = uri.to_string();
|
||||
|
||||
if let Some(download_started_handler) = download_started_handler.borrow_mut().as_mut() {
|
||||
let mut download_destination =
|
||||
dirs::download_dir().unwrap_or_else(|| current_dir().unwrap_or_default());
|
||||
|
||||
let (mut suggested_filename, ext) = suggested_filename
|
||||
.split_once('.')
|
||||
.map(|(base, ext)| (base, format!(".{ext}")))
|
||||
.unwrap_or((suggested_filename, "".to_string()));
|
||||
|
||||
// For `data:` downloads, webkitgtk will suggest to use the raw data as the filename if the dev provided no name,
|
||||
// for example `"data:attachment/text,sometext"` will result in `text,sometext` but longer data URLs will
|
||||
// result in a cut-off filename, which makes it hard to predict reliably.
|
||||
// TODO: If this keeps causing problems, just remove it and use whatever file name webkitgtk suggests.
|
||||
if uri.starts_with("data:") {
|
||||
if let Some((_, uri_stripped)) = uri.split_once('/') {
|
||||
if let Some((uri_stripped, _)) = uri_stripped.split_once(',') {
|
||||
if suggested_filename.starts_with(&format!("{uri_stripped},")) {
|
||||
suggested_filename = "Unknown";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
download_destination.push(format!("{suggested_filename}{ext}"));
|
||||
|
||||
// WebView2 does not overwrite files but appends numbers
|
||||
let mut counter = 1;
|
||||
while download_destination.exists() {
|
||||
download_destination.set_file_name(format!("{suggested_filename} ({counter}){ext}"));
|
||||
counter += 1;
|
||||
}
|
||||
|
||||
if download_started_handler(uri, &mut download_destination) {
|
||||
download.set_destination(&download_destination.to_string_lossy());
|
||||
} else {
|
||||
download.cancel();
|
||||
}
|
||||
}
|
||||
}
|
||||
// TODO: check if we may also need `false`
|
||||
true
|
||||
});
|
||||
|
||||
download.connect_failed({
|
||||
let failed = failed.clone();
|
||||
move |_, _error| {
|
||||
*failed.borrow_mut() = true;
|
||||
}
|
||||
});
|
||||
|
||||
if let Some(download_completed_handler) = download_completed_handler.clone() {
|
||||
download.connect_finished({
|
||||
let failed = failed.clone();
|
||||
move |download| {
|
||||
if let Some(uri) = download.request().and_then(|req| req.uri()) {
|
||||
let failed = *failed.borrow();
|
||||
let uri = uri.to_string();
|
||||
download_completed_handler(
|
||||
uri,
|
||||
(!failed)
|
||||
.then(|| download.destination().map(PathBuf::from))
|
||||
.flatten(),
|
||||
!failed,
|
||||
)
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
struct MainThreadRequest(URISchemeRequest);
|
||||
|
||||
impl MainThreadRequest {
|
||||
fn finish_with_response(&self, response: &URISchemeResponse) {
|
||||
self.0.finish_with_response(response);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl Send for MainThreadRequest {}
|
||||
unsafe impl Sync for MainThreadRequest {}
|
||||
Vendored
+251
@@ -0,0 +1,251 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
// A silly implementation of file drop handling for Windows!
|
||||
|
||||
use crate::DragDropEvent;
|
||||
|
||||
use std::{
|
||||
cell::UnsafeCell,
|
||||
ffi::OsString,
|
||||
os::{raw::c_void, windows::ffi::OsStringExt},
|
||||
path::PathBuf,
|
||||
ptr,
|
||||
rc::Rc,
|
||||
};
|
||||
|
||||
use windows::{
|
||||
core::{implement, BOOL},
|
||||
Win32::{
|
||||
Foundation::{DRAGDROP_E_INVALIDHWND, HWND, LPARAM, POINT, POINTL},
|
||||
Graphics::Gdi::ScreenToClient,
|
||||
System::{
|
||||
Com::{IDataObject, DVASPECT_CONTENT, FORMATETC, TYMED_HGLOBAL},
|
||||
Ole::{
|
||||
IDropTarget, IDropTarget_Impl, RegisterDragDrop, RevokeDragDrop, CF_HDROP, DROPEFFECT,
|
||||
DROPEFFECT_COPY, DROPEFFECT_NONE,
|
||||
},
|
||||
SystemServices::MODIFIERKEYS_FLAGS,
|
||||
},
|
||||
UI::{
|
||||
Shell::{DragFinish, DragQueryFileW, HDROP},
|
||||
WindowsAndMessaging::EnumChildWindows,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct DragDropController {
|
||||
drop_targets: Vec<IDropTarget>,
|
||||
}
|
||||
|
||||
impl DragDropController {
|
||||
#[inline]
|
||||
pub(crate) fn new(hwnd: HWND, handler: Box<dyn Fn(DragDropEvent) -> bool>) -> Self {
|
||||
let mut controller = DragDropController::default();
|
||||
|
||||
let handler = Rc::new(handler);
|
||||
|
||||
// Enumerate child windows to find the WebView2 "window" and override!
|
||||
{
|
||||
let mut callback = |hwnd| controller.inject_in_hwnd(hwnd, handler.clone());
|
||||
let mut trait_obj: &mut dyn FnMut(HWND) -> bool = &mut callback;
|
||||
let closure_pointer_pointer: *mut c_void = unsafe { std::mem::transmute(&mut trait_obj) };
|
||||
let lparam = LPARAM(closure_pointer_pointer as _);
|
||||
unsafe extern "system" fn enumerate_callback(hwnd: HWND, lparam: LPARAM) -> BOOL {
|
||||
let closure = &mut *(lparam.0 as *mut c_void as *mut &mut dyn FnMut(HWND) -> bool);
|
||||
closure(hwnd).into()
|
||||
}
|
||||
let _ = unsafe { EnumChildWindows(Some(hwnd), Some(enumerate_callback), lparam) };
|
||||
}
|
||||
|
||||
controller
|
||||
}
|
||||
|
||||
#[inline]
|
||||
fn inject_in_hwnd(&mut self, hwnd: HWND, handler: Rc<dyn Fn(DragDropEvent) -> bool>) -> bool {
|
||||
let drag_drop_target: IDropTarget = DragDropTarget::new(hwnd, handler).into();
|
||||
if unsafe { RevokeDragDrop(hwnd) } != Err(DRAGDROP_E_INVALIDHWND.into())
|
||||
&& unsafe { RegisterDragDrop(hwnd, &drag_drop_target) }.is_ok()
|
||||
{
|
||||
self.drop_targets.push(drag_drop_target);
|
||||
}
|
||||
|
||||
true
|
||||
}
|
||||
}
|
||||
|
||||
#[implement(IDropTarget)]
|
||||
pub struct DragDropTarget {
|
||||
hwnd: HWND,
|
||||
listener: Rc<dyn Fn(DragDropEvent) -> bool>,
|
||||
cursor_effect: UnsafeCell<DROPEFFECT>,
|
||||
enter_is_valid: UnsafeCell<bool>, /* If the currently hovered item is not valid there must not be any `HoveredFileCancelled` emitted */
|
||||
}
|
||||
|
||||
impl DragDropTarget {
|
||||
pub fn new(hwnd: HWND, listener: Rc<dyn Fn(DragDropEvent) -> bool>) -> DragDropTarget {
|
||||
Self {
|
||||
hwnd,
|
||||
listener,
|
||||
cursor_effect: DROPEFFECT_NONE.into(),
|
||||
enter_is_valid: false.into(),
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn iterate_filenames<F>(
|
||||
data_obj: windows_core::Ref<'_, IDataObject>,
|
||||
mut callback: F,
|
||||
) -> Option<HDROP>
|
||||
where
|
||||
F: FnMut(PathBuf),
|
||||
{
|
||||
let drop_format = FORMATETC {
|
||||
cfFormat: CF_HDROP.0,
|
||||
ptd: ptr::null_mut(),
|
||||
dwAspect: DVASPECT_CONTENT.0,
|
||||
lindex: -1,
|
||||
tymed: TYMED_HGLOBAL.0 as u32,
|
||||
};
|
||||
|
||||
match data_obj
|
||||
.as_ref()
|
||||
.expect("Received null IDataObject")
|
||||
.GetData(&drop_format)
|
||||
{
|
||||
Ok(medium) => {
|
||||
let hdrop = HDROP(medium.u.hGlobal.0 as _);
|
||||
|
||||
// The second parameter (0xFFFFFFFF) instructs the function to return the item count
|
||||
let item_count = DragQueryFileW(hdrop, 0xFFFFFFFF, None);
|
||||
|
||||
for i in 0..item_count {
|
||||
// Get the length of the path string NOT including the terminating null character.
|
||||
// Previously, this was using a fixed size array of MAX_PATH length, but the
|
||||
// Windows API allows longer paths under certain circumstances.
|
||||
let character_count = DragQueryFileW(hdrop, i, None) as usize;
|
||||
|
||||
// Fill path_buf with the null-terminated file name
|
||||
let str_len = character_count + 1;
|
||||
let mut path_buf = vec![0; str_len];
|
||||
DragQueryFileW(hdrop, i, Some(&mut path_buf));
|
||||
callback(OsString::from_wide(&path_buf[0..character_count]).into());
|
||||
}
|
||||
|
||||
Some(hdrop)
|
||||
}
|
||||
Err(_error) => {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!(
|
||||
"{}",
|
||||
match _error.code() {
|
||||
windows::Win32::Foundation::DV_E_FORMATETC => {
|
||||
// If the dropped item is not a file this error will occur.
|
||||
// In this case it is OK to return without taking further action.
|
||||
"Error occurred while processing dropped/hovered item: item is not a file."
|
||||
}
|
||||
_ => "Unexpected error occurred while processing dropped/hovered item.",
|
||||
}
|
||||
);
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
impl IDropTarget_Impl for DragDropTarget_Impl {
|
||||
fn DragEnter(
|
||||
&self,
|
||||
pDataObj: windows_core::Ref<'_, IDataObject>,
|
||||
_grfKeyState: MODIFIERKEYS_FLAGS,
|
||||
pt: &POINTL,
|
||||
pdwEffect: *mut DROPEFFECT,
|
||||
) -> windows::core::Result<()> {
|
||||
let mut pt = POINT { x: pt.x, y: pt.y };
|
||||
let _ = unsafe { ScreenToClient(self.hwnd, &mut pt) };
|
||||
|
||||
let mut paths = Vec::new();
|
||||
let hdrop = unsafe { DragDropTarget::iterate_filenames(pDataObj, |path| paths.push(path)) };
|
||||
|
||||
let enter_is_valid = hdrop.is_some();
|
||||
|
||||
if !enter_is_valid {
|
||||
return Ok(());
|
||||
};
|
||||
|
||||
unsafe {
|
||||
*self.enter_is_valid.get() = enter_is_valid;
|
||||
}
|
||||
|
||||
(self.listener)(DragDropEvent::Enter {
|
||||
paths,
|
||||
position: (pt.x as _, pt.y as _),
|
||||
});
|
||||
|
||||
let cursor_effect = if enter_is_valid {
|
||||
DROPEFFECT_COPY
|
||||
} else {
|
||||
DROPEFFECT_NONE
|
||||
};
|
||||
|
||||
unsafe {
|
||||
*pdwEffect = cursor_effect;
|
||||
*self.cursor_effect.get() = cursor_effect;
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn DragOver(
|
||||
&self,
|
||||
_grfKeyState: MODIFIERKEYS_FLAGS,
|
||||
pt: &POINTL,
|
||||
pdwEffect: *mut DROPEFFECT,
|
||||
) -> windows::core::Result<()> {
|
||||
if unsafe { *self.enter_is_valid.get() } {
|
||||
let mut pt = POINT { x: pt.x, y: pt.y };
|
||||
let _ = unsafe { ScreenToClient(self.hwnd, &mut pt) };
|
||||
(self.listener)(DragDropEvent::Over {
|
||||
position: (pt.x as _, pt.y as _),
|
||||
});
|
||||
}
|
||||
|
||||
unsafe { *pdwEffect = *self.cursor_effect.get() };
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn DragLeave(&self) -> windows::core::Result<()> {
|
||||
if unsafe { *self.enter_is_valid.get() } {
|
||||
(self.listener)(DragDropEvent::Leave);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn Drop(
|
||||
&self,
|
||||
pDataObj: windows_core::Ref<'_, IDataObject>,
|
||||
_grfKeyState: MODIFIERKEYS_FLAGS,
|
||||
pt: &POINTL,
|
||||
_pdwEffect: *mut DROPEFFECT,
|
||||
) -> windows::core::Result<()> {
|
||||
if unsafe { *self.enter_is_valid.get() } {
|
||||
let mut pt = POINT { x: pt.x, y: pt.y };
|
||||
let _ = unsafe { ScreenToClient(self.hwnd, &mut pt) };
|
||||
|
||||
let mut paths = Vec::new();
|
||||
let hdrop = unsafe { DragDropTarget::iterate_filenames(pDataObj, |path| paths.push(path)) };
|
||||
(self.listener)(DragDropEvent::Drop {
|
||||
paths,
|
||||
position: (pt.x as _, pt.y as _),
|
||||
});
|
||||
|
||||
if let Some(hdrop) = hdrop {
|
||||
unsafe { DragFinish(hdrop) };
|
||||
}
|
||||
}
|
||||
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
Vendored
+1909
File diff suppressed because it is too large.
Load diff
Vendored
+101
@@ -0,0 +1,101 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use once_cell::sync::Lazy;
|
||||
use windows::{
|
||||
core::{HRESULT, HSTRING, PCSTR},
|
||||
Win32::{
|
||||
Foundation::{FARPROC, HWND, S_OK},
|
||||
Graphics::Gdi::{
|
||||
GetDC, GetDeviceCaps, MonitorFromWindow, HMONITOR, LOGPIXELSX, MONITOR_DEFAULTTONEAREST,
|
||||
},
|
||||
System::LibraryLoader::{GetProcAddress, LoadLibraryW},
|
||||
UI::{
|
||||
HiDpi::{MDT_EFFECTIVE_DPI, MONITOR_DPI_TYPE},
|
||||
WindowsAndMessaging::IsProcessDPIAware,
|
||||
},
|
||||
},
|
||||
};
|
||||
|
||||
fn get_function_impl(library: &str, function: &str) -> FARPROC {
|
||||
let library = HSTRING::from(library);
|
||||
assert_eq!(function.chars().last(), Some('\0'));
|
||||
|
||||
// Library names we will use are ASCII so we can use the A version to avoid string conversion.
|
||||
let module = unsafe { LoadLibraryW(&library) }.unwrap_or_default();
|
||||
if module.is_invalid() {
|
||||
return None;
|
||||
}
|
||||
|
||||
unsafe { GetProcAddress(module, PCSTR::from_raw(function.as_ptr())) }
|
||||
}
|
||||
|
||||
macro_rules! get_function {
|
||||
($lib:expr, $func:ident) => {
|
||||
crate::webview2::util::get_function_impl($lib, concat!(stringify!($func), '\0'))
|
||||
.map(|f| unsafe { std::mem::transmute::<_, $func>(f) })
|
||||
};
|
||||
}
|
||||
|
||||
pub type GetDpiForWindow = unsafe extern "system" fn(hwnd: HWND) -> u32;
|
||||
pub type GetDpiForMonitor = unsafe extern "system" fn(
|
||||
hmonitor: HMONITOR,
|
||||
dpi_type: MONITOR_DPI_TYPE,
|
||||
dpi_x: *mut u32,
|
||||
dpi_y: *mut u32,
|
||||
) -> HRESULT;
|
||||
|
||||
static GET_DPI_FOR_WINDOW: Lazy<Option<GetDpiForWindow>> =
|
||||
Lazy::new(|| get_function!("user32.dll", GetDpiForWindow));
|
||||
static GET_DPI_FOR_MONITOR: Lazy<Option<GetDpiForMonitor>> =
|
||||
Lazy::new(|| get_function!("shcore.dll", GetDpiForMonitor));
|
||||
|
||||
pub const BASE_DPI: u32 = 96;
|
||||
pub fn dpi_to_scale_factor(dpi: u32) -> f64 {
|
||||
dpi as f64 / BASE_DPI as f64
|
||||
}
|
||||
|
||||
#[allow(non_snake_case)]
|
||||
pub unsafe fn hwnd_dpi(hwnd: HWND) -> u32 {
|
||||
if let Some(GetDpiForWindow) = *GET_DPI_FOR_WINDOW {
|
||||
// We are on Windows 10 Anniversary Update (1607) or later.
|
||||
match GetDpiForWindow(hwnd) {
|
||||
0 => BASE_DPI, // 0 is returned if hwnd is invalid
|
||||
#[allow(clippy::unnecessary_cast)]
|
||||
dpi => dpi as u32,
|
||||
}
|
||||
} else if let Some(GetDpiForMonitor) = *GET_DPI_FOR_MONITOR {
|
||||
// We are on Windows 8.1 or later.
|
||||
let monitor = MonitorFromWindow(hwnd, MONITOR_DEFAULTTONEAREST);
|
||||
if monitor.is_invalid() {
|
||||
return BASE_DPI;
|
||||
}
|
||||
|
||||
let mut dpi_x = 0;
|
||||
let mut dpi_y = 0;
|
||||
#[allow(clippy::unnecessary_cast)]
|
||||
if GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) == S_OK {
|
||||
dpi_x as u32
|
||||
} else {
|
||||
BASE_DPI
|
||||
}
|
||||
} else {
|
||||
let hdc = GetDC(Some(hwnd));
|
||||
if hdc.is_invalid() {
|
||||
return BASE_DPI;
|
||||
}
|
||||
|
||||
// We are on Vista or later.
|
||||
if IsProcessDPIAware().as_bool() {
|
||||
// If the process is DPI aware, then scaling must be handled by the application using
|
||||
// this DPI value.
|
||||
GetDeviceCaps(Some(hdc), LOGPIXELSX) as u32
|
||||
} else {
|
||||
// If the process is DPI unaware, then scaling is performed by the OS; we thus return
|
||||
// 96 (scale factor 1.0) to prevent the window from being re-scaled by both the
|
||||
// application and the WM.
|
||||
BASE_DPI
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,90 @@
|
||||
// Copyright 2020-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{ffi::c_void, ptr::null_mut};
|
||||
|
||||
use objc2::{
|
||||
define_class, msg_send,
|
||||
rc::Retained,
|
||||
runtime::{AnyObject, NSObject},
|
||||
AllocAnyThread, DefinedClass,
|
||||
};
|
||||
use objc2_foundation::{
|
||||
ns_string, NSDictionary, NSKeyValueChangeKey, NSKeyValueObservingOptions,
|
||||
NSObjectNSKeyValueObserverRegistration, NSObjectProtocol, NSString,
|
||||
};
|
||||
|
||||
use crate::WryWebView;
|
||||
pub struct DocumentTitleChangedObserverIvars {
|
||||
pub object: Retained<WryWebView>,
|
||||
pub handler: Box<dyn Fn(String)>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSObject))]
|
||||
#[ivars = DocumentTitleChangedObserverIvars]
|
||||
pub struct DocumentTitleChangedObserver;
|
||||
|
||||
/// NSKeyValueObserving.
|
||||
impl DocumentTitleChangedObserver {
|
||||
#[unsafe(method(observeValueForKeyPath:ofObject:change:context:))]
|
||||
fn observe_value_for_key_path(
|
||||
&self,
|
||||
key_path: Option<&NSString>,
|
||||
of_object: Option<&AnyObject>,
|
||||
_change: Option<&NSDictionary<NSKeyValueChangeKey, AnyObject>>,
|
||||
_context: *mut c_void,
|
||||
) {
|
||||
if let (Some(key_path), Some(object)) = (key_path, of_object) {
|
||||
unsafe {
|
||||
if key_path.isEqualToString(ns_string!("title")) {
|
||||
let handler = &self.ivars().handler;
|
||||
// if !handler.is_null() {
|
||||
let title: *const NSString = msg_send![object, title];
|
||||
handler((*title).to_string());
|
||||
// }
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
unsafe impl NSObjectProtocol for DocumentTitleChangedObserver {}
|
||||
);
|
||||
|
||||
impl DocumentTitleChangedObserver {
|
||||
pub fn new(webview: Retained<WryWebView>, handler: Box<dyn Fn(String)>) -> Retained<Self> {
|
||||
let observer = Self::alloc().set_ivars(DocumentTitleChangedObserverIvars {
|
||||
object: webview,
|
||||
handler,
|
||||
});
|
||||
|
||||
let observer: Retained<Self> = unsafe { msg_send![super(observer), init] };
|
||||
|
||||
unsafe {
|
||||
observer
|
||||
.ivars()
|
||||
.object
|
||||
.addObserver_forKeyPath_options_context(
|
||||
&observer,
|
||||
ns_string!("title"),
|
||||
NSKeyValueObservingOptions::New,
|
||||
null_mut(),
|
||||
);
|
||||
}
|
||||
|
||||
observer
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for DocumentTitleChangedObserver {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
self
|
||||
.ivars()
|
||||
.object
|
||||
.removeObserver_forKeyPath(self, ns_string!("title"));
|
||||
}
|
||||
}
|
||||
}
|
||||
+12
@@ -0,0 +1,12 @@
|
||||
// Copyright 2020-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
pub mod document_title_changed_observer;
|
||||
pub mod url_scheme_handler;
|
||||
pub mod wry_download_delegate;
|
||||
pub mod wry_navigation_delegate;
|
||||
pub mod wry_web_view;
|
||||
pub mod wry_web_view_delegate;
|
||||
pub mod wry_web_view_parent;
|
||||
pub mod wry_web_view_ui_delegate;
|
||||
@@ -0,0 +1,346 @@
|
||||
// Copyright 2020-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{
|
||||
borrow::Cow,
|
||||
ffi::{c_char, c_void, CStr},
|
||||
panic::AssertUnwindSafe,
|
||||
ptr::NonNull,
|
||||
};
|
||||
|
||||
use http::{
|
||||
header::{CONTENT_LENGTH, CONTENT_TYPE},
|
||||
Request, Response as HttpResponse, StatusCode, Version,
|
||||
};
|
||||
use objc2::{
|
||||
rc::Retained,
|
||||
runtime::{AnyClass, AnyObject, ClassBuilder, ProtocolObject},
|
||||
AllocAnyThread, ClassType, Message,
|
||||
};
|
||||
use objc2_foundation::{
|
||||
NSData, NSHTTPURLResponse, NSMutableDictionary, NSObject, NSObjectProtocol, NSString, NSURL,
|
||||
NSUUID,
|
||||
};
|
||||
use objc2_web_kit::{WKURLSchemeHandler, WKURLSchemeTask};
|
||||
|
||||
use crate::{wkwebview::WEBVIEW_STATE, RequestAsyncResponder, WryWebView};
|
||||
|
||||
pub fn create(name: &str) -> &AnyClass {
|
||||
unsafe {
|
||||
// Include the address of WEBVIEW_STATE in the class name so that each dylib in the process
|
||||
// gets its own ObjC class with method pointers into its own code and data segments.
|
||||
let unique_id = std::ptr::addr_of!(WEBVIEW_STATE) as usize;
|
||||
let scheme_name = format!("{name}URLSchemeHandler_{unique_id:x}\0");
|
||||
let scheme_name = CStr::from_bytes_with_nul(scheme_name.as_bytes()).unwrap();
|
||||
let cls = ClassBuilder::new(scheme_name, NSObject::class());
|
||||
match cls {
|
||||
Some(mut cls) => {
|
||||
cls.add_ivar::<*mut c_char>(c"webview_id");
|
||||
cls.add_ivar::<usize>(c"protocol_index");
|
||||
cls.add_method(
|
||||
objc2::sel!(webView:startURLSchemeTask:),
|
||||
start_task as extern "C" fn(_, _, _, _),
|
||||
);
|
||||
cls.add_method(
|
||||
objc2::sel!(webView:stopURLSchemeTask:),
|
||||
stop_task as extern "C" fn(_, _, _, _),
|
||||
);
|
||||
cls.register()
|
||||
}
|
||||
None => AnyClass::get(scheme_name).expect("Failed to get the class definition"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Task handler for custom protocol
|
||||
extern "C" fn start_task(
|
||||
this: &AnyObject,
|
||||
_sel: objc2::runtime::Sel,
|
||||
webview: &WryWebView,
|
||||
task: &ProtocolObject<dyn WKURLSchemeTask>,
|
||||
) {
|
||||
unsafe {
|
||||
#[cfg(feature = "tracing")]
|
||||
let span = tracing::info_span!(parent: None, "wry::custom_protocol::handle", uri = tracing::field::Empty)
|
||||
.entered();
|
||||
|
||||
let task_key = task.hash(); // hash by task object address
|
||||
let task_uuid = webview.add_custom_task_key(task_key);
|
||||
|
||||
let ivar = this.class().instance_variable(c"webview_id").unwrap();
|
||||
let webview_id_ptr: *mut c_char = *ivar.load(this);
|
||||
let webview_id = CStr::from_ptr(webview_id_ptr)
|
||||
.to_str()
|
||||
.ok()
|
||||
.unwrap_or_default();
|
||||
|
||||
let ivar = this.class().instance_variable(c"protocol_index").unwrap();
|
||||
let protocol_index: usize = *ivar.load(this);
|
||||
|
||||
let function = WEBVIEW_STATE
|
||||
.read()
|
||||
.unwrap()
|
||||
.get(webview_id)
|
||||
.and_then(|v| v.protocol_ptrs.get(protocol_index))
|
||||
.cloned();
|
||||
|
||||
if let Some(function) = function {
|
||||
// Get url request
|
||||
let request = task.request();
|
||||
let url = request.URL().unwrap();
|
||||
|
||||
let uri = url.absoluteString().unwrap().to_string();
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
span.record("uri", uri.clone());
|
||||
|
||||
// Get request method (GET, POST, PUT etc...)
|
||||
let method = request.HTTPMethod().unwrap().to_string();
|
||||
|
||||
// Prepare our HttpRequest
|
||||
let mut http_request = Request::builder().uri(uri).method(method.as_str());
|
||||
|
||||
// Get body
|
||||
let mut sent_form_body = Vec::new();
|
||||
let body = request.HTTPBody();
|
||||
let body_stream = request.HTTPBodyStream();
|
||||
if let Some(body) = body {
|
||||
sent_form_body = body.to_vec();
|
||||
} else if let Some(body_stream) = body_stream {
|
||||
body_stream.open();
|
||||
|
||||
while body_stream.hasBytesAvailable() {
|
||||
sent_form_body.reserve(128);
|
||||
let p = sent_form_body.as_mut_ptr().add(sent_form_body.len());
|
||||
let read_length = sent_form_body.capacity() - sent_form_body.len();
|
||||
let count = body_stream.read_maxLength(NonNull::new(p).unwrap(), read_length);
|
||||
sent_form_body.set_len(sent_form_body.len() + count as usize);
|
||||
}
|
||||
|
||||
body_stream.close();
|
||||
}
|
||||
|
||||
// Extract all headers fields
|
||||
let all_headers = request.allHTTPHeaderFields();
|
||||
|
||||
// get all our headers values and inject them in our request
|
||||
if let Some(all_headers) = all_headers {
|
||||
for current_header in all_headers.allKeys().iter() {
|
||||
let header_value = all_headers.valueForKey(¤t_header).unwrap();
|
||||
// inject the header into the request
|
||||
http_request = http_request.header(current_header.to_string(), header_value.to_string());
|
||||
}
|
||||
}
|
||||
|
||||
let respond_with_404 = || {
|
||||
let urlresponse = NSHTTPURLResponse::alloc();
|
||||
let response = NSHTTPURLResponse::initWithURL_statusCode_HTTPVersion_headerFields(
|
||||
urlresponse,
|
||||
&url,
|
||||
StatusCode::NOT_FOUND.as_u16().try_into().unwrap(),
|
||||
Some(&NSString::from_str(
|
||||
format!("{:#?}", Version::HTTP_11).as_str(),
|
||||
)),
|
||||
None,
|
||||
)
|
||||
.unwrap();
|
||||
task.didReceiveResponse(&response);
|
||||
// Finish
|
||||
task.didFinish();
|
||||
};
|
||||
|
||||
fn check_webview_id_valid(webview_id: &str) -> crate::Result<()> {
|
||||
if !WEBVIEW_STATE.read().unwrap().contains_key(webview_id) {
|
||||
return Err(crate::Error::CustomProtocolTaskInvalid);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Task may not live longer than async custom protocol handler.
|
||||
///
|
||||
/// There are roughly 2 ways to cause segfault:
|
||||
/// 1. Task has stopped. pointer of the task not valid anymore.
|
||||
/// 2. Task had stopped, but the pointer of the task has allocated to a new task.
|
||||
/// Outdated custom handler may call to the new task instance and cause segfault.
|
||||
fn check_task_is_valid(
|
||||
webview: &WryWebView,
|
||||
task_key: usize,
|
||||
current_uuid: Retained<NSUUID>,
|
||||
) -> crate::Result<()> {
|
||||
let latest_task_uuid = webview.get_custom_task_uuid(task_key);
|
||||
let Some(latest_uuid) = latest_task_uuid else {
|
||||
return Err(crate::Error::CustomProtocolTaskInvalid);
|
||||
};
|
||||
if latest_uuid != current_uuid {
|
||||
return Err(crate::Error::CustomProtocolTaskInvalid);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
// send response
|
||||
match http_request.body(sent_form_body) {
|
||||
Ok(final_request) => {
|
||||
let webview = webview.retain();
|
||||
let task = task.retain();
|
||||
let responder: Box<dyn FnOnce(HttpResponse<Cow<'static, [u8]>>)> =
|
||||
Box::new(move |sent_response| {
|
||||
// Consolidate checks before calling into `did*` methods.
|
||||
let validate = || -> crate::Result<()> {
|
||||
check_webview_id_valid(webview_id)?;
|
||||
check_task_is_valid(&webview, task_key, task_uuid.clone())?;
|
||||
Ok(())
|
||||
};
|
||||
|
||||
// Perform an upfront validation
|
||||
if let Err(_e) = validate() {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("Task invalid before sending response: {:?}", _e);
|
||||
return; // If invalid, return early without calling task methods.
|
||||
}
|
||||
|
||||
unsafe fn response(
|
||||
// FIXME: though we give it a static lifetime, it's not guaranteed to be valid.
|
||||
task: Retained<ProtocolObject<dyn WKURLSchemeTask>>,
|
||||
// FIXME: though we give it a static lifetime, it's not guaranteed to be valid.
|
||||
webview: Retained<WryWebView>,
|
||||
task_key: usize,
|
||||
task_uuid: Retained<NSUUID>,
|
||||
webview_id: &str,
|
||||
url: Retained<NSURL>,
|
||||
sent_response: HttpResponse<Cow<'_, [u8]>>,
|
||||
) -> crate::Result<()> {
|
||||
// Validate
|
||||
check_webview_id_valid(webview_id)?;
|
||||
check_task_is_valid(&webview, task_key, task_uuid.clone())?;
|
||||
|
||||
let content = sent_response.body();
|
||||
// default: application/octet-stream, but should be provided by the client
|
||||
let wanted_mime = sent_response.headers().get(CONTENT_TYPE);
|
||||
// default to 200
|
||||
let wanted_status_code = sent_response.status().as_u16() as i32;
|
||||
// default to HTTP/1.1
|
||||
let wanted_version = format!("{:#?}", sent_response.version());
|
||||
|
||||
let headers = NSMutableDictionary::new();
|
||||
if let Some(mime) = wanted_mime {
|
||||
headers.insert(
|
||||
&*NSString::from_str(CONTENT_TYPE.as_str()),
|
||||
&*NSString::from_str(mime.to_str().unwrap()),
|
||||
);
|
||||
}
|
||||
headers.insert(
|
||||
&*NSString::from_str(CONTENT_LENGTH.as_str()),
|
||||
&*NSString::from_str(&content.len().to_string()),
|
||||
);
|
||||
|
||||
// add headers
|
||||
for (name, value) in sent_response.headers().iter() {
|
||||
if let Ok(value) = value.to_str() {
|
||||
headers.insert(
|
||||
&*NSString::from_str(name.as_str()),
|
||||
&*NSString::from_str(value),
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
let urlresponse = NSHTTPURLResponse::alloc();
|
||||
let response = NSHTTPURLResponse::initWithURL_statusCode_HTTPVersion_headerFields(
|
||||
urlresponse,
|
||||
&url,
|
||||
wanted_status_code.try_into().unwrap(),
|
||||
Some(&NSString::from_str(&wanted_version)),
|
||||
Some(&headers),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
// Re-validate before calling didReceiveResponse
|
||||
check_webview_id_valid(webview_id)?;
|
||||
check_task_is_valid(&webview, task_key, task_uuid.clone())?;
|
||||
|
||||
// Use map_err to convert Option<Retained<Exception>> to crate::Error
|
||||
objc2::exception::catch(AssertUnwindSafe(|| {
|
||||
task.didReceiveResponse(&response);
|
||||
}))
|
||||
.map_err(|_e| crate::Error::CustomProtocolTaskInvalid)?;
|
||||
|
||||
// Send data
|
||||
let data = NSData::alloc();
|
||||
// MIGRATE NOTE: we copied the content to the NSData because content will be freed
|
||||
// when out of scope but NSData will also free the content when it's done and cause doube free.
|
||||
let data = NSData::initWithBytes_length(
|
||||
data,
|
||||
content.as_ptr() as *mut c_void,
|
||||
content.len(),
|
||||
);
|
||||
|
||||
// Check validity again
|
||||
check_webview_id_valid(webview_id)?;
|
||||
check_task_is_valid(&webview, task_key, task_uuid.clone())?;
|
||||
|
||||
objc2::exception::catch(AssertUnwindSafe(|| {
|
||||
task.didReceiveData(&data);
|
||||
}))
|
||||
.map_err(|_e| crate::Error::CustomProtocolTaskInvalid)?;
|
||||
|
||||
check_webview_id_valid(webview_id)?;
|
||||
check_task_is_valid(&webview, task_key, task_uuid)?;
|
||||
|
||||
objc2::exception::catch(AssertUnwindSafe(|| {
|
||||
task.didFinish();
|
||||
}))
|
||||
.map_err(|_e| crate::Error::CustomProtocolTaskInvalid)?;
|
||||
|
||||
if WEBVIEW_STATE.read().unwrap().contains_key(webview_id) {
|
||||
webview.remove_custom_task_key(task_key);
|
||||
Ok(())
|
||||
} else {
|
||||
Err(crate::Error::CustomProtocolTaskInvalid)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
let _span = tracing::info_span!("wry::custom_protocol::call_handler").entered();
|
||||
|
||||
if let Err(_e) = response(
|
||||
task,
|
||||
webview,
|
||||
task_key,
|
||||
task_uuid,
|
||||
webview_id,
|
||||
url,
|
||||
sent_response,
|
||||
) {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::error!("Error responding to task: {:?}", _e);
|
||||
}
|
||||
});
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
let _span = tracing::info_span!("wry::custom_protocol::call_handler").entered();
|
||||
|
||||
function(
|
||||
webview_id,
|
||||
final_request,
|
||||
RequestAsyncResponder { responder },
|
||||
);
|
||||
}
|
||||
Err(_) => respond_with_404(),
|
||||
};
|
||||
} else {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!(
|
||||
"Either WebView or WebContext instance is dropped! This handler shouldn't be called."
|
||||
);
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
extern "C" fn stop_task(
|
||||
_this: &ProtocolObject<dyn WKURLSchemeHandler>,
|
||||
_sel: objc2::runtime::Sel,
|
||||
webview: &WryWebView,
|
||||
task: &ProtocolObject<dyn WKURLSchemeTask>,
|
||||
) {
|
||||
webview.remove_custom_task_key(task.hash());
|
||||
}
|
||||
@@ -0,0 +1,67 @@
|
||||
// Copyright 2020-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{cell::RefCell, path::PathBuf, rc::Rc};
|
||||
|
||||
use objc2::{define_class, msg_send, rc::Retained, runtime::NSObject, MainThreadOnly};
|
||||
use objc2_foundation::{
|
||||
MainThreadMarker, NSData, NSError, NSObjectProtocol, NSString, NSURLResponse, NSURL,
|
||||
};
|
||||
use objc2_web_kit::{WKDownload, WKDownloadDelegate};
|
||||
|
||||
use crate::wkwebview::download::{download_did_fail, download_did_finish, download_policy};
|
||||
|
||||
pub struct WryDownloadDelegateIvars {
|
||||
pub started: Option<RefCell<Box<dyn FnMut(String, &mut PathBuf) -> bool + 'static>>>,
|
||||
pub completed: Option<Rc<dyn Fn(String, Option<PathBuf>, bool) + 'static>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = WryDownloadDelegateIvars]
|
||||
pub struct WryDownloadDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for WryDownloadDelegate {}
|
||||
|
||||
unsafe impl WKDownloadDelegate for WryDownloadDelegate {
|
||||
#[unsafe(method(download:decideDestinationUsingResponse:suggestedFilename:completionHandler:))]
|
||||
fn download_policy(
|
||||
&self,
|
||||
download: &WKDownload,
|
||||
response: &NSURLResponse,
|
||||
suggested_filename: &NSString,
|
||||
handler: &block2::Block<dyn Fn(*const NSURL)>,
|
||||
) {
|
||||
download_policy(self, download, response, suggested_filename, handler);
|
||||
}
|
||||
|
||||
#[unsafe(method(downloadDidFinish:))]
|
||||
fn download_did_finish(&self, download: &WKDownload) {
|
||||
download_did_finish(self, download);
|
||||
}
|
||||
|
||||
#[unsafe(method(download:didFailWithError:resumeData:))]
|
||||
fn download_did_fail(&self, download: &WKDownload, error: &NSError, resume_data: &NSData) {
|
||||
download_did_fail(self, download, error, resume_data);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl WryDownloadDelegate {
|
||||
pub fn new(
|
||||
download_started_handler: Option<Box<dyn FnMut(String, &mut PathBuf) -> bool + 'static>>,
|
||||
download_completed_handler: Option<Rc<dyn Fn(String, Option<PathBuf>, bool) + 'static>>,
|
||||
mtm: MainThreadMarker,
|
||||
) -> Retained<Self> {
|
||||
let delegate = mtm
|
||||
.alloc::<WryDownloadDelegate>()
|
||||
.set_ivars(WryDownloadDelegateIvars {
|
||||
started: download_started_handler.map(|handler| RefCell::new(handler)),
|
||||
completed: download_completed_handler,
|
||||
});
|
||||
|
||||
unsafe { msg_send![super(delegate), init] }
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,158 @@
|
||||
// Copyright 2020-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::sync::{Arc, Mutex};
|
||||
|
||||
use objc2::{define_class, msg_send, rc::Retained, runtime::NSObject, MainThreadOnly};
|
||||
use objc2_foundation::{MainThreadMarker, NSObjectProtocol};
|
||||
use objc2_web_kit::{
|
||||
WKDownload, WKNavigation, WKNavigationAction, WKNavigationActionPolicy, WKNavigationDelegate,
|
||||
WKNavigationResponse, WKNavigationResponsePolicy,
|
||||
};
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
use crate::wkwebview::ios::WKWebView::WKWebView;
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use crate::{
|
||||
url_from_webview,
|
||||
wkwebview::{
|
||||
download::{navigation_download_action, navigation_download_response},
|
||||
navigation::{
|
||||
did_commit_navigation, did_finish_navigation, navigation_policy, navigation_policy_response,
|
||||
web_content_process_did_terminate,
|
||||
},
|
||||
},
|
||||
PageLoadEvent, WryWebView,
|
||||
};
|
||||
|
||||
use super::wry_download_delegate::WryDownloadDelegate;
|
||||
|
||||
pub struct WryNavigationDelegateIvars {
|
||||
pub pending_scripts: Arc<Mutex<Option<Vec<String>>>>,
|
||||
pub has_download_handler: bool,
|
||||
pub navigation_policy_function: Box<dyn Fn(String) -> bool>,
|
||||
pub download_delegate: Option<Retained<WryDownloadDelegate>>,
|
||||
pub on_page_load_handler: Option<Box<dyn Fn(PageLoadEvent)>>,
|
||||
pub on_web_content_process_terminate_handler: Option<Box<dyn Fn()>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = WryNavigationDelegateIvars]
|
||||
pub struct WryNavigationDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for WryNavigationDelegate {}
|
||||
|
||||
unsafe impl WKNavigationDelegate for WryNavigationDelegate {
|
||||
#[unsafe(method(webView:decidePolicyForNavigationAction:decisionHandler:))]
|
||||
fn navigation_policy(
|
||||
&self,
|
||||
webview: &WKWebView,
|
||||
action: &WKNavigationAction,
|
||||
handler: &block2::Block<dyn Fn(WKNavigationActionPolicy)>,
|
||||
) {
|
||||
navigation_policy(self, webview, action, handler);
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:decidePolicyForNavigationResponse:decisionHandler:))]
|
||||
fn navigation_policy_response(
|
||||
&self,
|
||||
webview: &WKWebView,
|
||||
response: &WKNavigationResponse,
|
||||
handler: &block2::Block<dyn Fn(WKNavigationResponsePolicy)>,
|
||||
) {
|
||||
navigation_policy_response(self, webview, response, handler);
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didFinishNavigation:))]
|
||||
fn did_finish_navigation(&self, webview: &WKWebView, navigation: &WKNavigation) {
|
||||
did_finish_navigation(self, webview, navigation);
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:didCommitNavigation:))]
|
||||
fn did_commit_navigation(&self, webview: &WKWebView, navigation: &WKNavigation) {
|
||||
did_commit_navigation(self, webview, navigation);
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:navigationAction:didBecomeDownload:))]
|
||||
fn navigation_download_action(
|
||||
&self,
|
||||
webview: &WKWebView,
|
||||
action: &WKNavigationAction,
|
||||
download: &WKDownload,
|
||||
) {
|
||||
navigation_download_action(self, webview, action, download);
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:navigationResponse:didBecomeDownload:))]
|
||||
fn navigation_download_response(
|
||||
&self,
|
||||
webview: &WKWebView,
|
||||
response: &WKNavigationResponse,
|
||||
download: &WKDownload,
|
||||
) {
|
||||
navigation_download_response(self, webview, response, download);
|
||||
}
|
||||
|
||||
#[unsafe(method(webViewWebContentProcessDidTerminate:))]
|
||||
fn web_content_process_did_terminate(&self, webview: &WKWebView) {
|
||||
web_content_process_did_terminate(self, webview);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl WryNavigationDelegate {
|
||||
#[allow(clippy::too_many_arguments)]
|
||||
pub fn new(
|
||||
webview: Retained<WryWebView>,
|
||||
pending_scripts: Arc<Mutex<Option<Vec<String>>>>,
|
||||
has_download_handler: bool,
|
||||
navigation_handler: Option<Box<dyn Fn(String) -> bool>>,
|
||||
download_delegate: Option<Retained<WryDownloadDelegate>>,
|
||||
on_page_load_handler: Option<Box<dyn Fn(PageLoadEvent, String)>>,
|
||||
on_web_content_process_terminate_handler: Option<Box<dyn Fn()>>,
|
||||
mtm: MainThreadMarker,
|
||||
) -> Retained<Self> {
|
||||
let navigation_policy_function = Box::new(move |url: String| -> bool {
|
||||
navigation_handler
|
||||
.as_ref()
|
||||
.map_or(true, |navigation_handler| (navigation_handler)(url))
|
||||
});
|
||||
|
||||
let on_page_load_handler = if let Some(handler) = on_page_load_handler {
|
||||
let custom_handler = Box::new(move |event| {
|
||||
handler(event, url_from_webview(&webview).unwrap_or_default());
|
||||
}) as Box<dyn Fn(PageLoadEvent)>;
|
||||
Some(custom_handler)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let on_web_content_process_terminate_handler =
|
||||
if let Some(handler) = on_web_content_process_terminate_handler {
|
||||
let custom_handler = Box::new(move || {
|
||||
handler();
|
||||
}) as Box<dyn Fn()>;
|
||||
Some(custom_handler)
|
||||
} else {
|
||||
None
|
||||
};
|
||||
|
||||
let delegate = mtm
|
||||
.alloc::<WryNavigationDelegate>()
|
||||
.set_ivars(WryNavigationDelegateIvars {
|
||||
pending_scripts,
|
||||
navigation_policy_function,
|
||||
has_download_handler,
|
||||
download_delegate,
|
||||
on_page_load_handler,
|
||||
on_web_content_process_terminate_handler,
|
||||
});
|
||||
|
||||
unsafe { msg_send![super(delegate), init] }
|
||||
}
|
||||
}
|
||||
+153
@@ -0,0 +1,153 @@
|
||||
// Copyright 2020-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{collections::HashMap, sync::Mutex};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2::runtime::ProtocolObject;
|
||||
use objc2::{define_class, rc::Retained, runtime::Bool, DeclaredClass};
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2_app_kit::{NSDraggingDestination, NSEvent};
|
||||
use objc2_foundation::{NSObjectProtocol, NSUUID};
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
use crate::wkwebview::ios::WKWebView::WKWebView;
|
||||
#[cfg(target_os = "macos")]
|
||||
use crate::{
|
||||
wkwebview::{drag_drop, synthetic_mouse_events},
|
||||
DragDropEvent,
|
||||
};
|
||||
#[cfg(target_os = "ios")]
|
||||
use objc2_ui_kit::UIEvent as NSEvent;
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
pub struct WryWebViewIvars {
|
||||
pub(crate) is_child: bool,
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) drag_drop_handler: Box<dyn Fn(DragDropEvent) -> bool>,
|
||||
#[cfg(target_os = "macos")]
|
||||
pub(crate) accept_first_mouse: objc2::runtime::Bool,
|
||||
#[cfg(target_os = "ios")]
|
||||
pub(crate) input_accessory_view_builder: Option<Box<crate::InputAccessoryViewBuilder>>,
|
||||
pub(crate) custom_protocol_task_ids: Mutex<HashMap<usize, Retained<NSUUID>>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(WKWebView))]
|
||||
#[ivars = WryWebViewIvars]
|
||||
pub struct WryWebView;
|
||||
|
||||
/// Overridden NSView methods.
|
||||
impl WryWebView {
|
||||
#[unsafe(method(performKeyEquivalent:))]
|
||||
fn perform_key_equivalent(&self, event: &NSEvent) -> Bool {
|
||||
// This is a temporary workaround for https://github.com/tauri-apps/tauri/issues/9426
|
||||
// FIXME: When the webview is a child webview, performKeyEquivalent always return YES
|
||||
// and stop propagating the event to the window, hence the menu shortcut won't be
|
||||
// triggered. However, overriding this method also means the cmd+key event won't be
|
||||
// handled in webview, which means the key cannot be listened by JavaScript.
|
||||
if self.ivars().is_child {
|
||||
Bool::NO
|
||||
} else {
|
||||
unsafe { objc2::msg_send![super(self), performKeyEquivalent: event] }
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[unsafe(method(acceptsFirstMouse:))]
|
||||
fn accept_first_mouse(&self, _event: &NSEvent) -> Bool {
|
||||
self.ivars().accept_first_mouse
|
||||
}
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
#[unsafe(method_id(inputAccessoryView))]
|
||||
fn input_accessory_view(&self) -> Option<Retained<objc2_ui_kit::UIView>> {
|
||||
if let Some(builder) = &self.ivars().input_accessory_view_builder {
|
||||
builder(self)
|
||||
} else {
|
||||
unsafe { objc2::msg_send![super(self), inputAccessoryView] }
|
||||
}
|
||||
}
|
||||
}
|
||||
unsafe impl NSObjectProtocol for WryWebView {}
|
||||
|
||||
// Drag & Drop
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe impl NSDraggingDestination for WryWebView {
|
||||
#[unsafe(method(draggingEntered:))]
|
||||
fn dragging_entered(
|
||||
&self,
|
||||
drag_info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
|
||||
) -> objc2_app_kit::NSDragOperation {
|
||||
drag_drop::dragging_entered(self, drag_info)
|
||||
}
|
||||
|
||||
#[unsafe(method(draggingUpdated:))]
|
||||
fn dragging_updated(
|
||||
&self,
|
||||
drag_info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
|
||||
) -> objc2_app_kit::NSDragOperation {
|
||||
drag_drop::dragging_updated(self, drag_info)
|
||||
}
|
||||
|
||||
#[unsafe(method(performDragOperation:))]
|
||||
fn perform_drag_operation(
|
||||
&self,
|
||||
drag_info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>,
|
||||
) -> Bool {
|
||||
drag_drop::perform_drag_operation(self, drag_info)
|
||||
}
|
||||
|
||||
#[unsafe(method(draggingExited:))]
|
||||
fn dragging_exited(&self, drag_info: &ProtocolObject<dyn objc2_app_kit::NSDraggingInfo>) {
|
||||
drag_drop::dragging_exited(self, drag_info)
|
||||
}
|
||||
}
|
||||
|
||||
// Synthetic mouse events
|
||||
#[cfg(target_os = "macos")]
|
||||
impl WryWebView {
|
||||
#[unsafe(method(otherMouseDown:))]
|
||||
fn other_mouse_down(&self, event: &NSEvent) {
|
||||
synthetic_mouse_events::other_mouse_down(self, event)
|
||||
}
|
||||
|
||||
#[unsafe(method(otherMouseUp:))]
|
||||
fn other_mouse_up(&self, event: &NSEvent) {
|
||||
synthetic_mouse_events::other_mouse_up(self, event)
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// Custom Protocol Task Checker
|
||||
impl WryWebView {
|
||||
pub(crate) fn add_custom_task_key(&self, task_id: usize) -> Retained<NSUUID> {
|
||||
let task_uuid = NSUUID::new();
|
||||
self
|
||||
.ivars()
|
||||
.custom_protocol_task_ids
|
||||
.lock()
|
||||
.unwrap()
|
||||
.insert(task_id, task_uuid.clone());
|
||||
task_uuid
|
||||
}
|
||||
pub(crate) fn remove_custom_task_key(&self, task_id: usize) {
|
||||
self
|
||||
.ivars()
|
||||
.custom_protocol_task_ids
|
||||
.lock()
|
||||
.unwrap()
|
||||
.remove(&task_id);
|
||||
}
|
||||
pub(crate) fn get_custom_task_uuid(&self, task_id: usize) -> Option<Retained<NSUUID>> {
|
||||
self
|
||||
.ivars()
|
||||
.custom_protocol_task_ids
|
||||
.lock()
|
||||
.unwrap()
|
||||
.get(&task_id)
|
||||
.cloned()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,105 @@
|
||||
// Copyright 2020-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{ffi::CStr, panic::AssertUnwindSafe};
|
||||
|
||||
use http::Request;
|
||||
use objc2::{
|
||||
define_class, msg_send,
|
||||
rc::Retained,
|
||||
runtime::{NSObject, ProtocolObject},
|
||||
DeclaredClass, MainThreadOnly,
|
||||
};
|
||||
use objc2_foundation::{ns_string, MainThreadMarker, NSObjectProtocol, NSString};
|
||||
use objc2_web_kit::{WKScriptMessage, WKScriptMessageHandler, WKUserContentController};
|
||||
|
||||
pub const IPC_MESSAGE_HANDLER_NAME: &str = "ipc";
|
||||
|
||||
pub struct WryWebViewDelegateIvars {
|
||||
pub controller: Retained<WKUserContentController>,
|
||||
pub ipc_handler: Box<dyn Fn(Request<String>)>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = WryWebViewDelegateIvars]
|
||||
pub struct WryWebViewDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for WryWebViewDelegate {}
|
||||
|
||||
unsafe impl WKScriptMessageHandler for WryWebViewDelegate {
|
||||
// Function for ipc handler
|
||||
#[unsafe(method(userContentController:didReceiveScriptMessage:))]
|
||||
fn did_receive(
|
||||
this: &WryWebViewDelegate,
|
||||
_controller: &WKUserContentController,
|
||||
msg: &WKScriptMessage,
|
||||
) {
|
||||
// Safety: objc runtime calls are unsafe
|
||||
unsafe {
|
||||
#[cfg(feature = "tracing")]
|
||||
let _span = tracing::info_span!(parent: None, "wry::ipc::handle").entered();
|
||||
|
||||
let ipc_handler = &this.ivars().ipc_handler;
|
||||
let body = msg.body();
|
||||
if let Ok(body) = body.downcast::<NSString>() {
|
||||
let js_utf8 = body.UTF8String();
|
||||
|
||||
let frame_info = msg.frameInfo();
|
||||
let request = frame_info.request();
|
||||
let url = request.URL().unwrap();
|
||||
let absolute_url = url.absoluteString().unwrap();
|
||||
let url_utf8 = absolute_url.UTF8String();
|
||||
|
||||
if let (Ok(url), Ok(js)) = (
|
||||
CStr::from_ptr(url_utf8).to_str(),
|
||||
CStr::from_ptr(js_utf8).to_str(),
|
||||
) {
|
||||
if let Ok(r) = Request::builder().uri(url).body(js.to_string()) {
|
||||
ipc_handler(r);
|
||||
} else {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("WebView received invalid IPC request: {}", js);
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("WebView received invalid IPC call.");
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl WryWebViewDelegate {
|
||||
pub fn new(
|
||||
controller: Retained<WKUserContentController>,
|
||||
ipc_handler: Box<dyn Fn(Request<String>)>,
|
||||
mtm: MainThreadMarker,
|
||||
) -> Retained<Self> {
|
||||
let delegate = mtm
|
||||
.alloc::<WryWebViewDelegate>()
|
||||
.set_ivars(WryWebViewDelegateIvars {
|
||||
ipc_handler,
|
||||
controller,
|
||||
});
|
||||
|
||||
let delegate: Retained<Self> = unsafe { msg_send![super(delegate), init] };
|
||||
|
||||
let proto_delegate = ProtocolObject::from_ref(&*delegate);
|
||||
unsafe {
|
||||
// this will increase the retain count of the delegate
|
||||
let _res = objc2::exception::catch(AssertUnwindSafe(|| {
|
||||
delegate
|
||||
.ivars()
|
||||
.controller
|
||||
.addScriptMessageHandler_name(proto_delegate, ns_string!(IPC_MESSAGE_HANDLER_NAME));
|
||||
}));
|
||||
}
|
||||
|
||||
delegate
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,110 @@
|
||||
// Copyright 2020-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2::DefinedClass;
|
||||
use objc2::{define_class, msg_send, rc::Retained, MainThreadOnly};
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2_app_kit::{NSApplication, NSEvent, NSView, NSWindow, NSWindowButton};
|
||||
use objc2_foundation::MainThreadMarker;
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2_foundation::NSRect;
|
||||
#[cfg(target_os = "ios")]
|
||||
use objc2_ui_kit::UIView as NSView;
|
||||
|
||||
pub struct WryWebViewParentIvars {
|
||||
#[cfg(target_os = "macos")]
|
||||
traffic_light_inset: std::cell::Cell<Option<(f64, f64)>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSView))]
|
||||
#[ivars = WryWebViewParentIvars]
|
||||
pub struct WryWebViewParent;
|
||||
|
||||
/// Overridden NSView methods.
|
||||
impl WryWebViewParent {
|
||||
#[cfg(target_os = "macos")]
|
||||
#[unsafe(method(keyDown:))]
|
||||
fn key_down(&self, event: &NSEvent) {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
let app = NSApplication::sharedApplication(mtm);
|
||||
unsafe {
|
||||
if let Some(menu) = app.mainMenu() {
|
||||
menu.performKeyEquivalent(event);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[unsafe(method(drawRect:))]
|
||||
fn draw(&self, _dirty_rect: NSRect) {
|
||||
if let Some((x, y)) = self.ivars().traffic_light_inset.get() {
|
||||
unsafe { inset_traffic_lights(&self.window().unwrap(), x, y) };
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl WryWebViewParent {
|
||||
#[allow(dead_code)]
|
||||
pub fn new(mtm: MainThreadMarker) -> Retained<Self> {
|
||||
let delegate = WryWebViewParent::alloc(mtm).set_ivars(WryWebViewParentIvars {
|
||||
#[cfg(target_os = "macos")]
|
||||
traffic_light_inset: Default::default(),
|
||||
});
|
||||
unsafe { msg_send![super(delegate), init] }
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub fn set_traffic_light_inset(&self, ns_window: &NSWindow, position: dpi::Position) {
|
||||
let scale_factor = NSWindow::backingScaleFactor(ns_window);
|
||||
let position = position.to_logical(scale_factor);
|
||||
self
|
||||
.ivars()
|
||||
.traffic_light_inset
|
||||
.replace(Some((position.x, position.y)));
|
||||
|
||||
unsafe {
|
||||
inset_traffic_lights(ns_window, position.x, position.y);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
pub unsafe fn inset_traffic_lights(window: &NSWindow, x: f64, y: f64) {
|
||||
let Some(close) = window.standardWindowButton(NSWindowButton::CloseButton) else {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("skipping inset_traffic_lights, close button not found");
|
||||
return;
|
||||
};
|
||||
let Some(miniaturize) = window.standardWindowButton(NSWindowButton::MiniaturizeButton) else {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("skipping inset_traffic_lights, miniaturize button not found");
|
||||
return;
|
||||
};
|
||||
let zoom = window.standardWindowButton(NSWindowButton::ZoomButton);
|
||||
|
||||
let title_bar_container_view = close.superview().unwrap().superview().unwrap();
|
||||
|
||||
let close_rect = NSView::frame(&close);
|
||||
let title_bar_frame_height = close_rect.size.height + y;
|
||||
let mut title_bar_rect = NSView::frame(&title_bar_container_view);
|
||||
title_bar_rect.size.height = title_bar_frame_height;
|
||||
title_bar_rect.origin.y = window.frame().size.height - title_bar_frame_height;
|
||||
title_bar_container_view.setFrame(title_bar_rect);
|
||||
|
||||
let space_between = NSView::frame(&miniaturize).origin.x - close_rect.origin.x;
|
||||
|
||||
let mut window_buttons = vec![close, miniaturize];
|
||||
if let Some(zoom) = zoom {
|
||||
window_buttons.push(zoom);
|
||||
}
|
||||
|
||||
for (i, button) in window_buttons.into_iter().enumerate() {
|
||||
let mut rect = NSView::frame(&button);
|
||||
rect.origin.x = x + (i as f64 * space_between);
|
||||
button.setFrameOrigin(rect.origin);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,282 @@
|
||||
// Copyright 2020-2024 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use std::{cell::RefCell, ptr::null_mut, rc::Rc};
|
||||
|
||||
use block2::Block;
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2::DefinedClass;
|
||||
use objc2::{define_class, msg_send, rc::Retained, runtime::NSObject, MainThreadOnly};
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2_app_kit::{NSModalResponse, NSModalResponseOK, NSOpenPanel, NSWindowDelegate};
|
||||
use objc2_foundation::{MainThreadMarker, NSObjectProtocol};
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2_foundation::{NSArray, NSURL};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2_web_kit::WKOpenPanelParameters;
|
||||
use objc2_web_kit::{
|
||||
WKFrameInfo, WKMediaCaptureType, WKPermissionDecision, WKSecurityOrigin, WKUIDelegate,
|
||||
};
|
||||
|
||||
use crate::{NewWindowFeatures, NewWindowResponse, WryWebView};
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
struct NewWindow {
|
||||
#[allow(dead_code)]
|
||||
ns_window: Retained<objc2_app_kit::NSWindow>,
|
||||
#[allow(dead_code)]
|
||||
webview: Retained<objc2_web_kit::WKWebView>,
|
||||
#[allow(dead_code)]
|
||||
delegate: Retained<WryNSWindowDelegate>,
|
||||
}
|
||||
|
||||
// SAFETY: we are not using the new window at all, just dropping it on another thread
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe impl Send for NewWindow {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl Drop for NewWindow {
|
||||
fn drop(&mut self) {
|
||||
unsafe {
|
||||
self.webview.removeFromSuperview();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
struct WryNSWindowDelegateIvars {
|
||||
on_close: Box<dyn Fn()>,
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
define_class!(
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = WryNSWindowDelegateIvars]
|
||||
struct WryNSWindowDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for WryNSWindowDelegate {}
|
||||
|
||||
unsafe impl NSWindowDelegate for WryNSWindowDelegate {
|
||||
#[unsafe(method(windowWillClose:))]
|
||||
unsafe fn will_close(&self, _notification: &objc2_foundation::NSNotification) {
|
||||
let on_close = &self.ivars().on_close;
|
||||
on_close();
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
impl WryNSWindowDelegate {
|
||||
pub fn new(mtm: MainThreadMarker, on_close: Box<dyn Fn()>) -> Retained<Self> {
|
||||
let delegate = mtm
|
||||
.alloc::<WryNSWindowDelegate>()
|
||||
.set_ivars(WryNSWindowDelegateIvars { on_close });
|
||||
unsafe { msg_send![super(delegate), init] }
|
||||
}
|
||||
}
|
||||
|
||||
pub struct WryWebViewUIDelegateIvars {
|
||||
#[cfg(target_os = "macos")]
|
||||
new_window_req_handler: Option<Box<dyn Fn(String, NewWindowFeatures) -> NewWindowResponse>>,
|
||||
#[cfg(target_os = "macos")]
|
||||
new_windows: Rc<RefCell<Vec<NewWindow>>>,
|
||||
}
|
||||
|
||||
define_class!(
|
||||
#[unsafe(super(NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[ivars = WryWebViewUIDelegateIvars]
|
||||
pub struct WryWebViewUIDelegate;
|
||||
|
||||
unsafe impl NSObjectProtocol for WryWebViewUIDelegate {}
|
||||
|
||||
unsafe impl WKUIDelegate for WryWebViewUIDelegate {
|
||||
#[cfg(target_os = "macos")]
|
||||
#[unsafe(method(webView:runOpenPanelWithParameters:initiatedByFrame:completionHandler:))]
|
||||
fn run_file_upload_panel(
|
||||
&self,
|
||||
_webview: &WryWebView,
|
||||
open_panel_params: &WKOpenPanelParameters,
|
||||
_frame: &WKFrameInfo,
|
||||
handler: &block2::Block<dyn Fn(*const NSArray<NSURL>)>,
|
||||
) {
|
||||
unsafe {
|
||||
if let Some(mtm) = MainThreadMarker::new() {
|
||||
let open_panel = NSOpenPanel::openPanel(mtm);
|
||||
open_panel.setCanChooseFiles(true);
|
||||
let allow_multi = open_panel_params.allowsMultipleSelection();
|
||||
open_panel.setAllowsMultipleSelection(allow_multi);
|
||||
let allow_dir = open_panel_params.allowsDirectories();
|
||||
open_panel.setCanChooseDirectories(allow_dir);
|
||||
let ok: NSModalResponse = open_panel.runModal();
|
||||
if ok == NSModalResponseOK {
|
||||
let url = open_panel.URLs();
|
||||
(*handler).call((Retained::as_ptr(&url),));
|
||||
} else {
|
||||
(*handler).call((null_mut(),));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[unsafe(method(webView:requestMediaCapturePermissionForOrigin:initiatedByFrame:type:decisionHandler:))]
|
||||
fn request_media_capture_permission(
|
||||
&self,
|
||||
_webview: &WryWebView,
|
||||
_origin: &WKSecurityOrigin,
|
||||
_frame: &WKFrameInfo,
|
||||
_capture_type: WKMediaCaptureType,
|
||||
decision_handler: &Block<dyn Fn(WKPermissionDecision)>,
|
||||
) {
|
||||
//https://developer.apple.com/documentation/webkit/wkpermissiondecision?language=objc
|
||||
(*decision_handler).call((WKPermissionDecision::Grant,));
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[unsafe(method_id(webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:))]
|
||||
unsafe fn create_web_view_for_navigation_action(
|
||||
&self,
|
||||
webview: &WryWebView,
|
||||
configuration: &objc2_web_kit::WKWebViewConfiguration,
|
||||
action: &objc2_web_kit::WKNavigationAction,
|
||||
window_features: &objc2_web_kit::WKWindowFeatures,
|
||||
) -> Option<Retained<objc2_web_kit::WKWebView>> {
|
||||
if let Some(new_window_req_handler) = &self.ivars().new_window_req_handler {
|
||||
let request = action.request();
|
||||
let url = request.URL().unwrap().absoluteString().unwrap();
|
||||
|
||||
let current_window = webview.window().unwrap();
|
||||
let screen = current_window.screen().unwrap();
|
||||
let screen_frame = screen.frame();
|
||||
|
||||
match new_window_req_handler(
|
||||
url.to_string(),
|
||||
NewWindowFeatures {
|
||||
size: if let (Some(width), Some(height)) =
|
||||
(window_features.width(), window_features.height())
|
||||
{
|
||||
Some(dpi::LogicalSize::new(
|
||||
width.doubleValue(),
|
||||
height.doubleValue(),
|
||||
))
|
||||
} else {
|
||||
None
|
||||
},
|
||||
position: if let (Some(x), Some(y)) = (window_features.x(), window_features.y()) {
|
||||
Some(dpi::LogicalPosition::new(x.doubleValue(), y.doubleValue()))
|
||||
} else {
|
||||
None
|
||||
},
|
||||
opener: crate::NewWindowOpener {
|
||||
webview: webview.into(),
|
||||
target_configuration: configuration.into(),
|
||||
},
|
||||
},
|
||||
) {
|
||||
NewWindowResponse::Allow => {
|
||||
let mtm = MainThreadMarker::new().unwrap();
|
||||
|
||||
let defaults = current_window.frame();
|
||||
let size = objc2_foundation::NSSize::new(
|
||||
window_features
|
||||
.width()
|
||||
.map_or(defaults.size.width, |width| width.doubleValue()),
|
||||
window_features
|
||||
.height()
|
||||
.map_or(defaults.size.height, |height| height.doubleValue()),
|
||||
);
|
||||
let position = objc2_foundation::NSPoint::new(
|
||||
window_features
|
||||
.x()
|
||||
.map_or(defaults.origin.x, |x| x.doubleValue()),
|
||||
window_features.y().map_or(defaults.origin.y, |y| {
|
||||
screen_frame.size.height - y.doubleValue() - size.height
|
||||
}),
|
||||
);
|
||||
let rect = objc2_foundation::NSRect::new(position, size);
|
||||
|
||||
let mut flags = objc2_app_kit::NSWindowStyleMask::Titled
|
||||
| objc2_app_kit::NSWindowStyleMask::Closable
|
||||
| objc2_app_kit::NSWindowStyleMask::Miniaturizable;
|
||||
let resizable = window_features
|
||||
.allowsResizing()
|
||||
.map_or(true, |resizable| resizable.boolValue());
|
||||
if resizable {
|
||||
flags |= objc2_app_kit::NSWindowStyleMask::Resizable;
|
||||
}
|
||||
|
||||
let window = objc2_app_kit::NSWindow::initWithContentRect_styleMask_backing_defer(
|
||||
mtm.alloc::<objc2_app_kit::NSWindow>(),
|
||||
rect,
|
||||
flags,
|
||||
objc2_app_kit::NSBackingStoreType::Buffered,
|
||||
false,
|
||||
);
|
||||
|
||||
// SAFETY: Disable auto-release when closing windows.
|
||||
// This is required when creating `NSWindow` outside a window
|
||||
// controller.
|
||||
window.setReleasedWhenClosed(false);
|
||||
|
||||
let webview = objc2_web_kit::WKWebView::initWithFrame_configuration(
|
||||
mtm.alloc::<objc2_web_kit::WKWebView>(),
|
||||
window.frame(),
|
||||
configuration,
|
||||
);
|
||||
|
||||
let new_windows = self.ivars().new_windows.clone();
|
||||
let window_id = Retained::as_ptr(&window) as usize;
|
||||
let delegate = WryNSWindowDelegate::new(
|
||||
mtm,
|
||||
Box::new(move || {
|
||||
new_windows
|
||||
.borrow_mut()
|
||||
.retain(|window| Retained::as_ptr(&window.ns_window) as usize != window_id);
|
||||
}),
|
||||
);
|
||||
window.setDelegate(Some(objc2::runtime::ProtocolObject::from_ref(&*delegate)));
|
||||
|
||||
window.setContentView(Some(&webview));
|
||||
window.makeKeyAndOrderFront(None);
|
||||
|
||||
self.ivars().new_windows.borrow_mut().push(NewWindow {
|
||||
ns_window: window,
|
||||
webview: webview.clone(),
|
||||
delegate,
|
||||
});
|
||||
|
||||
Some(webview)
|
||||
}
|
||||
NewWindowResponse::Create { webview } => Some(webview),
|
||||
NewWindowResponse::Deny => None,
|
||||
}
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
impl WryWebViewUIDelegate {
|
||||
pub fn new(
|
||||
mtm: MainThreadMarker,
|
||||
new_window_req_handler: Option<Box<dyn Fn(String, NewWindowFeatures) -> NewWindowResponse>>,
|
||||
) -> Retained<Self> {
|
||||
#[cfg(target_os = "ios")]
|
||||
let _new_window_req_handler = new_window_req_handler;
|
||||
|
||||
let delegate = mtm
|
||||
.alloc::<WryWebViewUIDelegate>()
|
||||
.set_ivars(WryWebViewUIDelegateIvars {
|
||||
#[cfg(target_os = "macos")]
|
||||
new_window_req_handler,
|
||||
#[cfg(target_os = "macos")]
|
||||
new_windows: Rc::new(RefCell::new(vec![])),
|
||||
});
|
||||
unsafe { msg_send![super(delegate), init] }
|
||||
}
|
||||
}
|
||||
Vendored
+122
@@ -0,0 +1,122 @@
|
||||
use std::{env::current_dir, ptr::null_mut};
|
||||
|
||||
use objc2::{rc::Retained, runtime::ProtocolObject, DeclaredClass};
|
||||
use objc2_foundation::{NSData, NSError, NSString, NSURLResponse, NSURL};
|
||||
use objc2_web_kit::{WKDownload, WKNavigationAction, WKNavigationResponse};
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
use crate::wkwebview::ios::WKWebView::WKWebView;
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use super::class::{
|
||||
wry_download_delegate::WryDownloadDelegate, wry_navigation_delegate::WryNavigationDelegate,
|
||||
};
|
||||
|
||||
// Download action handler
|
||||
pub(crate) fn navigation_download_action(
|
||||
this: &WryNavigationDelegate,
|
||||
_webview: &WKWebView,
|
||||
_action: &WKNavigationAction,
|
||||
download: &WKDownload,
|
||||
) {
|
||||
unsafe {
|
||||
if let Some(delegate) = &this.ivars().download_delegate {
|
||||
let proto_delegate = ProtocolObject::from_ref(&**delegate);
|
||||
download.setDelegate(Some(proto_delegate));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Download response handler
|
||||
pub(crate) fn navigation_download_response(
|
||||
this: &WryNavigationDelegate,
|
||||
_webview: &WKWebView,
|
||||
_response: &WKNavigationResponse,
|
||||
download: &WKDownload,
|
||||
) {
|
||||
unsafe {
|
||||
if let Some(delegate) = &this.ivars().download_delegate {
|
||||
let proto_delegate = ProtocolObject::from_ref(&**delegate);
|
||||
download.setDelegate(Some(proto_delegate));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn download_policy(
|
||||
this: &WryDownloadDelegate,
|
||||
download: &WKDownload,
|
||||
_response: &NSURLResponse,
|
||||
suggested_filename: &NSString,
|
||||
completion_handler: &block2::Block<dyn Fn(*const NSURL)>,
|
||||
) {
|
||||
unsafe {
|
||||
let request = download.originalRequest().unwrap();
|
||||
let url = request.URL().unwrap().absoluteString().unwrap();
|
||||
let suggested_filename = suggested_filename.to_string();
|
||||
let mut download_destination =
|
||||
dirs::download_dir().unwrap_or_else(|| current_dir().unwrap_or_default());
|
||||
|
||||
download_destination.push(&suggested_filename);
|
||||
|
||||
let (suggested_filename, ext) = suggested_filename
|
||||
.split_once('.')
|
||||
.map(|(base, ext)| (base, format!(".{ext}")))
|
||||
.unwrap_or((&suggested_filename, "".to_string()));
|
||||
|
||||
// WebView2 does not overwrite files but appends numbers
|
||||
let mut counter = 1;
|
||||
while download_destination.exists() {
|
||||
download_destination.set_file_name(format!("{suggested_filename} ({counter}){ext}"));
|
||||
counter += 1;
|
||||
}
|
||||
|
||||
let started_fn = &this.ivars().started;
|
||||
if let Some(started_fn) = started_fn {
|
||||
let mut started_fn = started_fn.borrow_mut();
|
||||
match started_fn(url.to_string(), &mut download_destination) {
|
||||
true => {
|
||||
let path = NSString::from_str(&download_destination.display().to_string());
|
||||
let ns_url = NSURL::fileURLWithPath_isDirectory(&path, false);
|
||||
(*completion_handler).call((Retained::as_ptr(&ns_url),))
|
||||
}
|
||||
false => (*completion_handler).call((null_mut(),)),
|
||||
};
|
||||
} else {
|
||||
#[cfg(feature = "tracing")]
|
||||
tracing::warn!("WebView instance is dropped! This navigation handler shouldn't be called.");
|
||||
(*completion_handler).call((null_mut(),));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn download_did_finish(this: &WryDownloadDelegate, download: &WKDownload) {
|
||||
unsafe {
|
||||
let original_request = download.originalRequest().unwrap();
|
||||
let url = original_request.URL().unwrap().absoluteString().unwrap();
|
||||
if let Some(completed_fn) = this.ivars().completed.clone() {
|
||||
completed_fn(url.to_string(), None, true);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn download_did_fail(
|
||||
this: &WryDownloadDelegate,
|
||||
download: &WKDownload,
|
||||
error: &NSError,
|
||||
_resume_data: &NSData,
|
||||
) {
|
||||
unsafe {
|
||||
#[cfg(debug_assertions)]
|
||||
{
|
||||
let description = error.localizedDescription().to_string();
|
||||
eprintln!("Download failed with error: {description}");
|
||||
}
|
||||
|
||||
let original_request = download.originalRequest().unwrap();
|
||||
let url = original_request.URL().unwrap().absoluteString().unwrap();
|
||||
if let Some(completed_fn) = this.ivars().completed.clone() {
|
||||
completed_fn(url.to_string(), None, false);
|
||||
}
|
||||
}
|
||||
}
|
||||
+104
@@ -0,0 +1,104 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use std::{ffi::CStr, path::PathBuf};
|
||||
|
||||
use objc2::{
|
||||
runtime::{Bool, ProtocolObject},
|
||||
DeclaredClass,
|
||||
};
|
||||
use objc2_app_kit::{NSDragOperation, NSDraggingInfo, NSFilenamesPboardType};
|
||||
use objc2_foundation::{NSArray, NSPoint, NSRect, NSString};
|
||||
|
||||
use crate::DragDropEvent;
|
||||
|
||||
use super::WryWebView;
|
||||
|
||||
pub(crate) unsafe fn collect_paths(drag_info: &ProtocolObject<dyn NSDraggingInfo>) -> Vec<PathBuf> {
|
||||
let pb = drag_info.draggingPasteboard();
|
||||
let mut drag_drop_paths = Vec::new();
|
||||
let types = NSArray::arrayWithObject(NSFilenamesPboardType);
|
||||
|
||||
if pb.availableTypeFromArray(&types).is_some() {
|
||||
let paths = pb.propertyListForType(NSFilenamesPboardType).unwrap();
|
||||
let paths = paths.downcast::<NSArray>().unwrap();
|
||||
for path in paths {
|
||||
let path = path.downcast::<NSString>().unwrap();
|
||||
let path = CStr::from_ptr(path.UTF8String()).to_string_lossy();
|
||||
drag_drop_paths.push(PathBuf::from(path.into_owned()));
|
||||
}
|
||||
}
|
||||
drag_drop_paths
|
||||
}
|
||||
|
||||
pub(crate) fn dragging_entered(
|
||||
this: &WryWebView,
|
||||
drag_info: &ProtocolObject<dyn NSDraggingInfo>,
|
||||
) -> NSDragOperation {
|
||||
let paths = unsafe { collect_paths(drag_info) };
|
||||
let dl: NSPoint = unsafe { drag_info.draggingLocation() };
|
||||
let frame: NSRect = this.frame();
|
||||
let position = (dl.x as i32, (frame.size.height - dl.y) as i32);
|
||||
|
||||
let listener = &this.ivars().drag_drop_handler;
|
||||
if !listener(DragDropEvent::Enter { paths, position }) {
|
||||
// Reject the Wry file drop (invoke the OS default behaviour)
|
||||
unsafe { objc2::msg_send![super(this), draggingEntered: drag_info] }
|
||||
} else {
|
||||
NSDragOperation::Copy
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn dragging_updated(
|
||||
this: &WryWebView,
|
||||
drag_info: &ProtocolObject<dyn NSDraggingInfo>,
|
||||
) -> NSDragOperation {
|
||||
let dl: NSPoint = unsafe { drag_info.draggingLocation() };
|
||||
let frame: NSRect = this.frame();
|
||||
let position = (dl.x as i32, (frame.size.height - dl.y) as i32);
|
||||
|
||||
let listener = &this.ivars().drag_drop_handler;
|
||||
if !listener(DragDropEvent::Over { position }) {
|
||||
unsafe {
|
||||
let os_operation = objc2::msg_send![super(this), draggingUpdated: drag_info];
|
||||
if os_operation == NSDragOperation::None {
|
||||
// 0 will be returned for a drop on any arbitrary location on the webview.
|
||||
// We'll override that with NSDragOperationCopy.
|
||||
NSDragOperation::Copy
|
||||
} else {
|
||||
// A different NSDragOperation is returned when a file is hovered over something like
|
||||
// a <input type="file">, so we'll make sure to preserve that behaviour.
|
||||
os_operation
|
||||
}
|
||||
}
|
||||
} else {
|
||||
NSDragOperation::Copy
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn perform_drag_operation(
|
||||
this: &WryWebView,
|
||||
drag_info: &ProtocolObject<dyn NSDraggingInfo>,
|
||||
) -> Bool {
|
||||
let paths = unsafe { collect_paths(drag_info) };
|
||||
let dl: NSPoint = unsafe { drag_info.draggingLocation() };
|
||||
let frame: NSRect = this.frame();
|
||||
let position = (dl.x as i32, (frame.size.height - dl.y) as i32);
|
||||
|
||||
let listener = &this.ivars().drag_drop_handler;
|
||||
if !listener(DragDropEvent::Drop { paths, position }) {
|
||||
// Reject the Wry drop (invoke the OS default behaviour)
|
||||
unsafe { objc2::msg_send![super(this), performDragOperation: drag_info] }
|
||||
} else {
|
||||
Bool::YES
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn dragging_exited(this: &WryWebView, drag_info: &ProtocolObject<dyn NSDraggingInfo>) {
|
||||
let listener = &this.ivars().drag_drop_handler;
|
||||
if !listener(DragDropEvent::Leave) {
|
||||
// Reject the Wry drop (invoke the OS default behaviour)
|
||||
unsafe { objc2::msg_send![super(this), draggingExited: drag_info] }
|
||||
}
|
||||
}
|
||||
+625
@@ -0,0 +1,625 @@
|
||||
//! This file has been imported from `objc2-web-kit` and modified to match iOS.
|
||||
#![allow(warnings)]
|
||||
#![allow(clippy::all)]
|
||||
|
||||
use std::{ffi::c_double, ptr::NonNull};
|
||||
|
||||
use objc2::{
|
||||
encode::{Encode, Encoding, RefEncode},
|
||||
extern_class, extern_methods,
|
||||
rc::{Allocated, Retained},
|
||||
runtime::{AnyObject, ProtocolObject},
|
||||
MainThreadOnly,
|
||||
};
|
||||
use objc2_core_foundation::*;
|
||||
use objc2_foundation::*;
|
||||
use objc2_ui_kit::*;
|
||||
use objc2_web_kit::*;
|
||||
|
||||
use crate::*;
|
||||
|
||||
// NS_ENUM
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct WKMediaPlaybackState(pub NSInteger);
|
||||
impl WKMediaPlaybackState {
|
||||
#[doc(alias = "WKMediaPlaybackStateNone")]
|
||||
pub const None: Self = Self(0);
|
||||
#[doc(alias = "WKMediaPlaybackStatePlaying")]
|
||||
pub const Playing: Self = Self(1);
|
||||
#[doc(alias = "WKMediaPlaybackStatePaused")]
|
||||
pub const Paused: Self = Self(2);
|
||||
#[doc(alias = "WKMediaPlaybackStateSuspended")]
|
||||
pub const Suspended: Self = Self(3);
|
||||
}
|
||||
|
||||
unsafe impl Encode for WKMediaPlaybackState {
|
||||
const ENCODING: Encoding = NSInteger::ENCODING;
|
||||
}
|
||||
|
||||
unsafe impl RefEncode for WKMediaPlaybackState {
|
||||
const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
|
||||
}
|
||||
|
||||
// NS_ENUM
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct WKMediaCaptureState(pub NSInteger);
|
||||
impl WKMediaCaptureState {
|
||||
#[doc(alias = "WKMediaCaptureStateNone")]
|
||||
pub const None: Self = Self(0);
|
||||
#[doc(alias = "WKMediaCaptureStateActive")]
|
||||
pub const Active: Self = Self(1);
|
||||
#[doc(alias = "WKMediaCaptureStateMuted")]
|
||||
pub const Muted: Self = Self(2);
|
||||
}
|
||||
|
||||
unsafe impl Encode for WKMediaCaptureState {
|
||||
const ENCODING: Encoding = NSInteger::ENCODING;
|
||||
}
|
||||
|
||||
unsafe impl RefEncode for WKMediaCaptureState {
|
||||
const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
|
||||
}
|
||||
|
||||
// NS_ENUM
|
||||
#[repr(transparent)]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub struct WKFullscreenState(pub NSInteger);
|
||||
impl WKFullscreenState {
|
||||
#[doc(alias = "WKFullscreenStateNotInFullscreen")]
|
||||
pub const NotInFullscreen: Self = Self(0);
|
||||
#[doc(alias = "WKFullscreenStateEnteringFullscreen")]
|
||||
pub const EnteringFullscreen: Self = Self(1);
|
||||
#[doc(alias = "WKFullscreenStateInFullscreen")]
|
||||
pub const InFullscreen: Self = Self(2);
|
||||
#[doc(alias = "WKFullscreenStateExitingFullscreen")]
|
||||
pub const ExitingFullscreen: Self = Self(3);
|
||||
}
|
||||
|
||||
unsafe impl Encode for WKFullscreenState {
|
||||
const ENCODING: Encoding = NSInteger::ENCODING;
|
||||
}
|
||||
|
||||
unsafe impl RefEncode for WKFullscreenState {
|
||||
const ENCODING_REF: Encoding = Encoding::Pointer(&Self::ENCODING);
|
||||
}
|
||||
|
||||
extern_class!(
|
||||
#[unsafe(super(UIView, UIResponder, NSObject))]
|
||||
#[thread_kind = MainThreadOnly]
|
||||
#[derive(Debug, PartialEq, Eq, Hash)]
|
||||
pub struct WKWebView;
|
||||
);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe impl NSAccessibility for WKWebView {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe impl NSAccessibilityElementProtocol for WKWebView {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe impl NSAnimatablePropertyContainer for WKWebView {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe impl NSAppearanceCustomization for WKWebView {}
|
||||
|
||||
unsafe impl NSCoding for WKWebView {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe impl NSDraggingDestination for WKWebView {}
|
||||
|
||||
unsafe impl NSObjectProtocol for WKWebView {}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe impl NSUserInterfaceItemIdentification for WKWebView {}
|
||||
|
||||
impl WKWebView {
|
||||
extern_methods!(
|
||||
// #[cfg(feature = "WKWebViewConfiguration")]
|
||||
#[unsafe(method(configuration))]
|
||||
pub unsafe fn configuration(&self) -> Retained<WKWebViewConfiguration>;
|
||||
|
||||
// #[cfg(feature = "WKNavigationDelegate")]
|
||||
#[unsafe(method(navigationDelegate))]
|
||||
pub unsafe fn navigationDelegate(
|
||||
&self,
|
||||
) -> Option<Retained<ProtocolObject<dyn WKNavigationDelegate>>>;
|
||||
|
||||
// #[cfg(feature = "WKNavigationDelegate")]
|
||||
#[unsafe(method(setNavigationDelegate:))]
|
||||
pub unsafe fn setNavigationDelegate(
|
||||
&self,
|
||||
navigation_delegate: Option<&ProtocolObject<dyn WKNavigationDelegate>>,
|
||||
);
|
||||
|
||||
// #[cfg(feature = "WKUIDelegate")]
|
||||
#[unsafe(method(UIDelegate))]
|
||||
pub unsafe fn UIDelegate(&self) -> Option<Retained<ProtocolObject<dyn WKUIDelegate>>>;
|
||||
|
||||
// #[cfg(feature = "WKUIDelegate")]
|
||||
#[unsafe(method(setUIDelegate:))]
|
||||
pub unsafe fn setUIDelegate(&self, ui_delegate: Option<&ProtocolObject<dyn WKUIDelegate>>);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
// #[cfg(feature = "WKBackForwardList")]
|
||||
#[unsafe(method(backForwardList))]
|
||||
pub unsafe fn backForwardList(&self) -> Retained<WKBackForwardList>;
|
||||
|
||||
// #[cfg(feature = "WKWebViewConfiguration")]
|
||||
#[unsafe(method(initWithFrame:configuration:))]
|
||||
pub unsafe fn initWithFrame_configuration(
|
||||
this: Allocated<Self>,
|
||||
frame: CGRect,
|
||||
configuration: &WKWebViewConfiguration,
|
||||
) -> Retained<Self>;
|
||||
|
||||
#[unsafe(method(initWithCoder:))]
|
||||
pub unsafe fn initWithCoder(this: Allocated<Self>, coder: &NSCoder) -> Option<Retained<Self>>;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[unsafe(method(loadRequest:))]
|
||||
pub unsafe fn loadRequest(&self, request: &NSURLRequest) -> Option<Retained<WKNavigation>>;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[unsafe(method(loadFileURL:allowingReadAccessToURL:))]
|
||||
pub unsafe fn loadFileURL_allowingReadAccessToURL(
|
||||
&self,
|
||||
url: &NSURL,
|
||||
read_access_url: &NSURL,
|
||||
) -> Option<Retained<WKNavigation>>;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[unsafe(method(loadHTMLString:baseURL:))]
|
||||
pub unsafe fn loadHTMLString_baseURL(
|
||||
&self,
|
||||
string: &NSString,
|
||||
base_url: Option<&NSURL>,
|
||||
) -> Option<Retained<WKNavigation>>;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[unsafe(method(loadData:MIMEType:characterEncodingName:baseURL:))]
|
||||
pub unsafe fn loadData_MIMEType_characterEncodingName_baseURL(
|
||||
&self,
|
||||
data: &NSData,
|
||||
mime_type: &NSString,
|
||||
character_encoding_name: &NSString,
|
||||
base_url: &NSURL,
|
||||
) -> Option<Retained<WKNavigation>>;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
// #[cfg(all(feature = "WKBackForwardListItem", feature = "WKNavigation"))]
|
||||
#[unsafe(method(goToBackForwardListItem:))]
|
||||
pub unsafe fn goToBackForwardListItem(
|
||||
&self,
|
||||
item: &WKBackForwardListItem,
|
||||
) -> Option<Retained<WKNavigation>>;
|
||||
|
||||
#[unsafe(method(title))]
|
||||
pub unsafe fn title(&self) -> Option<Retained<NSString>>;
|
||||
|
||||
#[unsafe(method(URL))]
|
||||
pub unsafe fn URL(&self) -> Option<Retained<NSURL>>;
|
||||
|
||||
#[unsafe(method(isLoading))]
|
||||
pub unsafe fn isLoading(&self) -> bool;
|
||||
|
||||
#[unsafe(method(estimatedProgress))]
|
||||
pub unsafe fn estimatedProgress(&self) -> c_double;
|
||||
|
||||
#[unsafe(method(hasOnlySecureContent))]
|
||||
pub unsafe fn hasOnlySecureContent(&self) -> bool;
|
||||
|
||||
#[unsafe(method(canGoBack))]
|
||||
pub unsafe fn canGoBack(&self) -> bool;
|
||||
|
||||
#[unsafe(method(canGoForward))]
|
||||
pub unsafe fn canGoForward(&self) -> bool;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[unsafe(method(goBack))]
|
||||
pub unsafe fn goBack(&self) -> Option<Retained<WKNavigation>>;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[unsafe(method(goForward))]
|
||||
pub unsafe fn goForward(&self) -> Option<Retained<WKNavigation>>;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[unsafe(method(reload))]
|
||||
pub unsafe fn reload(&self) -> Option<Retained<WKNavigation>>;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[unsafe(method(reloadFromOrigin))]
|
||||
pub unsafe fn reloadFromOrigin(&self) -> Option<Retained<WKNavigation>>;
|
||||
|
||||
#[unsafe(method(stopLoading))]
|
||||
pub unsafe fn stopLoading(&self);
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[unsafe(method(evaluateJavaScript:completionHandler:))]
|
||||
pub unsafe fn evaluateJavaScript_completionHandler(
|
||||
&self,
|
||||
java_script_string: &NSString,
|
||||
completion_handler: Option<&block2::Block<dyn Fn(*mut AnyObject, *mut NSError)>>,
|
||||
);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
// #[cfg(all(
|
||||
// feature = "WKContentWorld",
|
||||
// feature = "WKFrameInfo",
|
||||
// feature = "block2"
|
||||
// ))]
|
||||
#[unsafe(method(evaluateJavaScript:inFrame:inContentWorld:completionHandler:))]
|
||||
pub unsafe fn evaluateJavaScript_inFrame_inContentWorld_completionHandler(
|
||||
&self,
|
||||
java_script_string: &NSString,
|
||||
frame: Option<&WKFrameInfo>,
|
||||
content_world: &WKContentWorld,
|
||||
completion_handler: Option<&block2::Block<dyn Fn(*mut AnyObject, *mut NSError)>>,
|
||||
);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
// #[cfg(all(
|
||||
// feature = "WKContentWorld",
|
||||
// feature = "WKFrameInfo",
|
||||
// feature = "block2"
|
||||
// ))]
|
||||
#[unsafe(method(callAsyncJavaScript:arguments:inFrame:inContentWorld:completionHandler:))]
|
||||
pub unsafe fn callAsyncJavaScript_arguments_inFrame_inContentWorld_completionHandler(
|
||||
&self,
|
||||
function_body: &NSString,
|
||||
arguments: Option<&NSDictionary<NSString, AnyObject>>,
|
||||
frame: Option<&WKFrameInfo>,
|
||||
content_world: &WKContentWorld,
|
||||
completion_handler: Option<&block2::Block<dyn Fn(*mut AnyObject, *mut NSError)>>,
|
||||
);
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[unsafe(method(closeAllMediaPresentationsWithCompletionHandler:))]
|
||||
pub unsafe fn closeAllMediaPresentationsWithCompletionHandler(
|
||||
&self,
|
||||
completion_handler: Option<&block2::Block<dyn Fn()>>,
|
||||
);
|
||||
|
||||
#[deprecated]
|
||||
#[unsafe(method(closeAllMediaPresentations))]
|
||||
pub unsafe fn closeAllMediaPresentations(&self);
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[unsafe(method(pauseAllMediaPlaybackWithCompletionHandler:))]
|
||||
pub unsafe fn pauseAllMediaPlaybackWithCompletionHandler(
|
||||
&self,
|
||||
completion_handler: Option<&block2::Block<dyn Fn()>>,
|
||||
);
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[deprecated]
|
||||
#[unsafe(method(pauseAllMediaPlayback:))]
|
||||
pub unsafe fn pauseAllMediaPlayback(
|
||||
&self,
|
||||
completion_handler: Option<&block2::Block<dyn Fn()>>,
|
||||
);
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[unsafe(method(setAllMediaPlaybackSuspended:completionHandler:))]
|
||||
pub unsafe fn setAllMediaPlaybackSuspended_completionHandler(
|
||||
&self,
|
||||
suspended: bool,
|
||||
completion_handler: Option<&block2::Block<dyn Fn()>>,
|
||||
);
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[deprecated]
|
||||
#[unsafe(method(resumeAllMediaPlayback:))]
|
||||
pub unsafe fn resumeAllMediaPlayback(
|
||||
&self,
|
||||
completion_handler: Option<&block2::Block<dyn Fn()>>,
|
||||
);
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[deprecated]
|
||||
#[unsafe(method(suspendAllMediaPlayback:))]
|
||||
pub unsafe fn suspendAllMediaPlayback(
|
||||
&self,
|
||||
completion_handler: Option<&block2::Block<dyn Fn()>>,
|
||||
);
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[unsafe(method(requestMediaPlaybackStateWithCompletionHandler:))]
|
||||
pub unsafe fn requestMediaPlaybackStateWithCompletionHandler(
|
||||
&self,
|
||||
completion_handler: &block2::Block<dyn Fn(WKMediaPlaybackState)>,
|
||||
);
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[deprecated]
|
||||
#[unsafe(method(requestMediaPlaybackState:))]
|
||||
pub unsafe fn requestMediaPlaybackState(
|
||||
&self,
|
||||
completion_handler: &block2::Block<dyn Fn(WKMediaPlaybackState)>,
|
||||
);
|
||||
|
||||
#[unsafe(method(cameraCaptureState))]
|
||||
pub unsafe fn cameraCaptureState(&self) -> WKMediaCaptureState;
|
||||
|
||||
#[unsafe(method(microphoneCaptureState))]
|
||||
pub unsafe fn microphoneCaptureState(&self) -> WKMediaCaptureState;
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[unsafe(method(setCameraCaptureState:completionHandler:))]
|
||||
pub unsafe fn setCameraCaptureState_completionHandler(
|
||||
&self,
|
||||
state: WKMediaCaptureState,
|
||||
completion_handler: Option<&block2::Block<dyn Fn()>>,
|
||||
);
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[unsafe(method(setMicrophoneCaptureState:completionHandler:))]
|
||||
pub unsafe fn setMicrophoneCaptureState_completionHandler(
|
||||
&self,
|
||||
state: WKMediaCaptureState,
|
||||
completion_handler: Option<&block2::Block<dyn Fn()>>,
|
||||
);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
// #[cfg(all(feature = "WKSnapshotConfiguration", feature = "block2"))]
|
||||
#[unsafe(method(takeSnapshotWithConfiguration:completionHandler:))]
|
||||
pub unsafe fn takeSnapshotWithConfiguration_completionHandler(
|
||||
&self,
|
||||
snapshot_configuration: Option<&WKSnapshotConfiguration>,
|
||||
completion_handler: &block2::Block<dyn Fn(*mut NSImage, *mut NSError)>,
|
||||
);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
// #[cfg(all(feature = "WKPDFConfiguration", feature = "block2"))]
|
||||
#[unsafe(method(createPDFWithConfiguration:completionHandler:))]
|
||||
pub unsafe fn createPDFWithConfiguration_completionHandler(
|
||||
&self,
|
||||
pdf_configuration: Option<&WKPDFConfiguration>,
|
||||
completion_handler: &block2::Block<dyn Fn(*mut NSData, *mut NSError)>,
|
||||
);
|
||||
|
||||
// #[cfg(feature = "block2")]
|
||||
#[unsafe(method(createWebArchiveDataWithCompletionHandler:))]
|
||||
pub unsafe fn createWebArchiveDataWithCompletionHandler(
|
||||
&self,
|
||||
completion_handler: &block2::Block<dyn Fn(NonNull<NSData>, NonNull<NSError>)>,
|
||||
);
|
||||
|
||||
#[unsafe(method(allowsBackForwardNavigationGestures))]
|
||||
pub unsafe fn allowsBackForwardNavigationGestures(&self) -> bool;
|
||||
|
||||
#[unsafe(method(setAllowsBackForwardNavigationGestures:))]
|
||||
pub unsafe fn setAllowsBackForwardNavigationGestures(
|
||||
&self,
|
||||
allows_back_forward_navigation_gestures: bool,
|
||||
);
|
||||
|
||||
#[unsafe(method(customUserAgent))]
|
||||
pub unsafe fn customUserAgent(&self) -> Option<Retained<NSString>>;
|
||||
|
||||
#[unsafe(method(setCustomUserAgent:))]
|
||||
pub unsafe fn setCustomUserAgent(&self, custom_user_agent: Option<&NSString>);
|
||||
|
||||
#[unsafe(method(allowsLinkPreview))]
|
||||
pub unsafe fn allowsLinkPreview(&self) -> bool;
|
||||
|
||||
#[unsafe(method(setAllowsLinkPreview:))]
|
||||
pub unsafe fn setAllowsLinkPreview(&self, allows_link_preview: bool);
|
||||
|
||||
#[unsafe(method(allowsMagnification))]
|
||||
pub unsafe fn allowsMagnification(&self) -> bool;
|
||||
|
||||
#[unsafe(method(setAllowsMagnification:))]
|
||||
pub unsafe fn setAllowsMagnification(&self, allows_magnification: bool);
|
||||
|
||||
#[unsafe(method(magnification))]
|
||||
pub unsafe fn magnification(&self) -> CGFloat;
|
||||
|
||||
#[unsafe(method(setMagnification:))]
|
||||
pub unsafe fn setMagnification(&self, magnification: CGFloat);
|
||||
|
||||
#[unsafe(method(setMagnification:centeredAtPoint:))]
|
||||
pub unsafe fn setMagnification_centeredAtPoint(&self, magnification: CGFloat, point: CGPoint);
|
||||
|
||||
#[unsafe(method(pageZoom))]
|
||||
pub unsafe fn pageZoom(&self) -> CGFloat;
|
||||
|
||||
#[unsafe(method(setPageZoom:))]
|
||||
pub unsafe fn setPageZoom(&self, page_zoom: CGFloat);
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
// #[cfg(all(
|
||||
// feature = "WKFindConfiguration",
|
||||
// feature = "WKFindResult",
|
||||
// feature = "block2"
|
||||
// ))]
|
||||
#[unsafe(method(findString:withConfiguration:completionHandler:))]
|
||||
pub unsafe fn findString_withConfiguration_completionHandler(
|
||||
&self,
|
||||
string: &NSString,
|
||||
configuration: Option<&WKFindConfiguration>,
|
||||
completion_handler: &block2::Block<dyn Fn(NonNull<WKFindResult>)>,
|
||||
);
|
||||
|
||||
#[unsafe(method(handlesURLScheme:))]
|
||||
pub unsafe fn handlesURLScheme(url_scheme: &NSString, mtm: MainThreadMarker) -> bool;
|
||||
|
||||
// #[cfg(all(feature = "WKDownload", feature = "block2"))]
|
||||
#[unsafe(method(startDownloadUsingRequest:completionHandler:))]
|
||||
pub unsafe fn startDownloadUsingRequest_completionHandler(
|
||||
&self,
|
||||
request: &NSURLRequest,
|
||||
completion_handler: &block2::Block<dyn Fn(NonNull<WKDownload>)>,
|
||||
);
|
||||
|
||||
// #[cfg(all(feature = "WKDownload", feature = "block2"))]
|
||||
#[unsafe(method(resumeDownloadFromResumeData:completionHandler:))]
|
||||
pub unsafe fn resumeDownloadFromResumeData_completionHandler(
|
||||
&self,
|
||||
resume_data: &NSData,
|
||||
completion_handler: &block2::Block<dyn Fn(NonNull<WKDownload>)>,
|
||||
);
|
||||
|
||||
#[unsafe(method(mediaType))]
|
||||
pub unsafe fn mediaType(&self) -> Option<Retained<NSString>>;
|
||||
|
||||
#[unsafe(method(setMediaType:))]
|
||||
pub unsafe fn setMediaType(&self, media_type: Option<&NSString>);
|
||||
|
||||
#[unsafe(method(interactionState))]
|
||||
pub unsafe fn interactionState(&self) -> Option<Retained<AnyObject>>;
|
||||
|
||||
#[unsafe(method(setInteractionState:))]
|
||||
pub unsafe fn setInteractionState(&self, interaction_state: Option<&AnyObject>);
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[unsafe(method(loadSimulatedRequest:response:responseData:))]
|
||||
pub unsafe fn loadSimulatedRequest_response_responseData(
|
||||
&self,
|
||||
request: &NSURLRequest,
|
||||
response: &NSURLResponse,
|
||||
data: &NSData,
|
||||
) -> Retained<WKNavigation>;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[deprecated]
|
||||
#[unsafe(method(loadSimulatedRequest:withResponse:responseData:))]
|
||||
pub unsafe fn loadSimulatedRequest_withResponse_responseData(
|
||||
&self,
|
||||
request: &NSURLRequest,
|
||||
response: &NSURLResponse,
|
||||
data: &NSData,
|
||||
) -> Retained<WKNavigation>;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[unsafe(method(loadFileRequest:allowingReadAccessToURL:))]
|
||||
pub unsafe fn loadFileRequest_allowingReadAccessToURL(
|
||||
&self,
|
||||
request: &NSURLRequest,
|
||||
read_access_url: &NSURL,
|
||||
) -> Retained<WKNavigation>;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[unsafe(method(loadSimulatedRequest:responseHTMLString:))]
|
||||
pub unsafe fn loadSimulatedRequest_responseHTMLString(
|
||||
&self,
|
||||
request: &NSURLRequest,
|
||||
string: &NSString,
|
||||
) -> Retained<WKNavigation>;
|
||||
|
||||
// #[cfg(feature = "WKNavigation")]
|
||||
#[deprecated]
|
||||
#[unsafe(method(loadSimulatedRequest:withResponseHTMLString:))]
|
||||
pub unsafe fn loadSimulatedRequest_withResponseHTMLString(
|
||||
&self,
|
||||
request: &NSURLRequest,
|
||||
string: &NSString,
|
||||
) -> Retained<WKNavigation>;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[unsafe(method(printOperationWithPrintInfo:))]
|
||||
pub unsafe fn printOperationWithPrintInfo(
|
||||
&self,
|
||||
print_info: &NSPrintInfo,
|
||||
) -> Retained<NSPrintOperation>;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[unsafe(method(themeColor))]
|
||||
pub unsafe fn themeColor(&self) -> Option<Retained<NSColor>>;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[unsafe(method(underPageBackgroundColor))]
|
||||
pub unsafe fn underPageBackgroundColor(&self) -> Retained<NSColor>;
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
#[unsafe(method(setUnderPageBackgroundColor:))]
|
||||
pub unsafe fn setUnderPageBackgroundColor(&self, under_page_background_color: Option<&NSColor>);
|
||||
|
||||
#[unsafe(method(fullscreenState))]
|
||||
pub unsafe fn fullscreenState(&self) -> WKFullscreenState;
|
||||
|
||||
#[unsafe(method(minimumViewportInset))]
|
||||
pub unsafe fn minimumViewportInset(&self) -> NSEdgeInsets;
|
||||
|
||||
#[unsafe(method(maximumViewportInset))]
|
||||
pub unsafe fn maximumViewportInset(&self) -> NSEdgeInsets;
|
||||
|
||||
#[unsafe(method(setMinimumViewportInset:maximumViewportInset:))]
|
||||
pub unsafe fn setMinimumViewportInset_maximumViewportInset(
|
||||
&self,
|
||||
minimum_viewport_inset: NSEdgeInsets,
|
||||
maximum_viewport_inset: NSEdgeInsets,
|
||||
);
|
||||
|
||||
#[unsafe(method(isInspectable))]
|
||||
pub unsafe fn isInspectable(&self) -> bool;
|
||||
|
||||
#[unsafe(method(setInspectable:))]
|
||||
pub unsafe fn setInspectable(&self, inspectable: bool);
|
||||
);
|
||||
}
|
||||
|
||||
/// Methods declared on superclass `UIView`
|
||||
impl WKWebView {
|
||||
extern_methods!(
|
||||
#[unsafe(method(initWithFrame:))]
|
||||
pub unsafe fn initWithFrame(this: Allocated<Self>, frame_rect: NSRect) -> Retained<Self>;
|
||||
);
|
||||
}
|
||||
|
||||
/// Methods declared on superclass `UIResponder`
|
||||
impl WKWebView {
|
||||
extern_methods!(
|
||||
#[unsafe(method(init))]
|
||||
pub unsafe fn init(this: Allocated<Self>) -> Retained<Self>;
|
||||
);
|
||||
}
|
||||
|
||||
/// Methods declared on superclass `NSObject`
|
||||
impl WKWebView {
|
||||
extern_methods!(
|
||||
#[unsafe(method(new))]
|
||||
pub unsafe fn new(mtm: MainThreadMarker) -> Retained<Self>;
|
||||
);
|
||||
}
|
||||
|
||||
/// WKIBActions
|
||||
impl WKWebView {
|
||||
extern_methods!(
|
||||
#[unsafe(method(goBack:))]
|
||||
pub unsafe fn goBack_(&self, sender: Option<&AnyObject>);
|
||||
|
||||
#[unsafe(method(goForward:))]
|
||||
pub unsafe fn goForward_(&self, sender: Option<&AnyObject>);
|
||||
|
||||
#[unsafe(method(reload:))]
|
||||
pub unsafe fn reload_(&self, sender: Option<&AnyObject>);
|
||||
|
||||
#[unsafe(method(reloadFromOrigin:))]
|
||||
pub unsafe fn reloadFromOrigin_(&self, sender: Option<&AnyObject>);
|
||||
|
||||
#[unsafe(method(stopLoading:))]
|
||||
pub unsafe fn stopLoading_(&self, sender: Option<&AnyObject>);
|
||||
);
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe impl NSUserInterfaceValidations for WKWebView {}
|
||||
|
||||
/// WKNSTextFinderClient
|
||||
impl WKWebView {
|
||||
extern_methods!();
|
||||
}
|
||||
|
||||
#[cfg(target_os = "macos")]
|
||||
unsafe impl NSTextFinderClient for WKWebView {}
|
||||
|
||||
/// WKDeprecated
|
||||
impl WKWebView {
|
||||
extern_methods!(
|
||||
#[deprecated]
|
||||
#[unsafe(method(certificateChain))]
|
||||
pub unsafe fn certificateChain(&self) -> Retained<NSArray>;
|
||||
);
|
||||
}
|
||||
Vendored
+1
@@ -0,0 +1 @@
|
||||
pub mod WKWebView;
|
||||
Vendored
+1472
File diff suppressed because it is too large.
Load diff
+116
@@ -0,0 +1,116 @@
|
||||
use objc2::DeclaredClass;
|
||||
use objc2_foundation::{NSObjectProtocol, NSString};
|
||||
use objc2_web_kit::{
|
||||
WKNavigation, WKNavigationAction, WKNavigationActionPolicy, WKNavigationResponse,
|
||||
WKNavigationResponsePolicy,
|
||||
};
|
||||
|
||||
#[cfg(target_os = "ios")]
|
||||
use crate::wkwebview::ios::WKWebView::WKWebView;
|
||||
#[cfg(target_os = "macos")]
|
||||
use objc2_web_kit::WKWebView;
|
||||
|
||||
use crate::PageLoadEvent;
|
||||
|
||||
use super::class::wry_navigation_delegate::WryNavigationDelegate;
|
||||
|
||||
pub(crate) fn did_commit_navigation(
|
||||
this: &WryNavigationDelegate,
|
||||
webview: &WKWebView,
|
||||
_navigation: &WKNavigation,
|
||||
) {
|
||||
unsafe {
|
||||
// Call on_load_handler
|
||||
if let Some(on_page_load) = &this.ivars().on_page_load_handler {
|
||||
on_page_load(PageLoadEvent::Started);
|
||||
}
|
||||
|
||||
// Inject scripts
|
||||
let mut pending_scripts = this.ivars().pending_scripts.lock().unwrap();
|
||||
if let Some(scripts) = &*pending_scripts {
|
||||
for script in scripts {
|
||||
webview.evaluateJavaScript_completionHandler(&NSString::from_str(script), None);
|
||||
}
|
||||
*pending_scripts = None;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn did_finish_navigation(
|
||||
this: &WryNavigationDelegate,
|
||||
_webview: &WKWebView,
|
||||
_navigation: &WKNavigation,
|
||||
) {
|
||||
if let Some(on_page_load) = &this.ivars().on_page_load_handler {
|
||||
on_page_load(PageLoadEvent::Finished);
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation handler
|
||||
pub(crate) fn navigation_policy(
|
||||
this: &WryNavigationDelegate,
|
||||
_webview: &WKWebView,
|
||||
action: &WKNavigationAction,
|
||||
handler: &block2::Block<dyn Fn(WKNavigationActionPolicy)>,
|
||||
) {
|
||||
unsafe {
|
||||
// <https://developer.apple.com/documentation/webkit/wknavigationaction/shouldperformdownload>
|
||||
// Available: macOS 11.3+, iOS 14.5+
|
||||
let can_download = action.respondsToSelector(objc2::sel!(shouldPerformDownload));
|
||||
let should_download: bool = if can_download {
|
||||
action.shouldPerformDownload()
|
||||
} else {
|
||||
false
|
||||
};
|
||||
let request = action.request();
|
||||
let url = request.URL().unwrap().absoluteString().unwrap();
|
||||
|
||||
if should_download {
|
||||
let has_download_handler = this.ivars().has_download_handler;
|
||||
if has_download_handler {
|
||||
(*handler).call((WKNavigationActionPolicy::Download,));
|
||||
} else {
|
||||
(*handler).call((WKNavigationActionPolicy::Cancel,));
|
||||
}
|
||||
} else {
|
||||
let function = &this.ivars().navigation_policy_function;
|
||||
match function(url.to_string()) {
|
||||
true => (*handler).call((WKNavigationActionPolicy::Allow,)),
|
||||
false => (*handler).call((WKNavigationActionPolicy::Cancel,)),
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation handler
|
||||
pub(crate) fn navigation_policy_response(
|
||||
this: &WryNavigationDelegate,
|
||||
_webview: &WKWebView,
|
||||
response: &WKNavigationResponse,
|
||||
handler: &block2::Block<dyn Fn(WKNavigationResponsePolicy)>,
|
||||
) {
|
||||
unsafe {
|
||||
let can_show_mime_type = response.canShowMIMEType();
|
||||
|
||||
if !can_show_mime_type {
|
||||
let has_download_handler = this.ivars().has_download_handler;
|
||||
if has_download_handler {
|
||||
(*handler).call((WKNavigationResponsePolicy::Download,));
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
(*handler).call((WKNavigationResponsePolicy::Allow,));
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn web_content_process_did_terminate(
|
||||
this: &WryNavigationDelegate,
|
||||
_webview: &WKWebView,
|
||||
) {
|
||||
if let Some(on_web_content_process_terminate) =
|
||||
&this.ivars().on_web_content_process_terminate_handler
|
||||
{
|
||||
on_web_content_process_terminate();
|
||||
}
|
||||
}
|
||||
Vendored
+44
@@ -0,0 +1,44 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use objc2_foundation::NSObject;
|
||||
use std::ffi::{c_char, CString};
|
||||
|
||||
use crate::{proxy::ProxyEndpoint, Error};
|
||||
|
||||
#[allow(non_camel_case_types)]
|
||||
pub type nw_endpoint_t = *mut NSObject;
|
||||
#[allow(non_camel_case_types)]
|
||||
pub type nw_protocol_options_t = *mut NSObject;
|
||||
#[allow(non_camel_case_types)]
|
||||
pub type nw_proxy_config_t = *mut NSObject;
|
||||
|
||||
#[link(name = "Network", kind = "framework")]
|
||||
extern "C" {
|
||||
fn nw_endpoint_create_host(host: *const c_char, port: *const c_char) -> nw_endpoint_t;
|
||||
pub fn nw_proxy_config_create_socksv5(proxy_endpoint: nw_endpoint_t) -> nw_proxy_config_t;
|
||||
pub fn nw_proxy_config_create_http_connect(
|
||||
proxy_endpoint: nw_endpoint_t,
|
||||
proxy_tls_options: nw_protocol_options_t,
|
||||
) -> nw_proxy_config_t;
|
||||
}
|
||||
|
||||
impl TryFrom<ProxyEndpoint> for nw_endpoint_t {
|
||||
type Error = Error;
|
||||
fn try_from(endpoint: ProxyEndpoint) -> Result<Self, Error> {
|
||||
unsafe {
|
||||
let endpoint_host =
|
||||
CString::new(endpoint.host).map_err(|_| Error::ProxyEndpointCreationFailed)?;
|
||||
let endpoint_port =
|
||||
CString::new(endpoint.port).map_err(|_| Error::ProxyEndpointCreationFailed)?;
|
||||
let endpoint = nw_endpoint_create_host(endpoint_host.as_ptr(), endpoint_port.as_ptr());
|
||||
|
||||
if endpoint.is_null() {
|
||||
Err(Error::ProxyEndpointCreationFailed)
|
||||
} else {
|
||||
Ok(endpoint)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
+123
@@ -0,0 +1,123 @@
|
||||
use objc2_app_kit::{
|
||||
NSAlternateKeyMask, NSCommandKeyMask, NSControlKeyMask, NSEvent, NSEventType, NSShiftKeyMask,
|
||||
NSView,
|
||||
};
|
||||
use objc2_foundation::NSString;
|
||||
|
||||
use super::WryWebView;
|
||||
|
||||
pub(crate) fn other_mouse_down(this: &WryWebView, event: &NSEvent) {
|
||||
unsafe {
|
||||
if event.r#type() == NSEventType::OtherMouseDown {
|
||||
let button_number = event.buttonNumber();
|
||||
match button_number {
|
||||
// back button
|
||||
3 => {
|
||||
let js = create_js_mouse_event(this, event, true, true);
|
||||
this.evaluateJavaScript_completionHandler(&NSString::from_str(&js), None);
|
||||
return;
|
||||
}
|
||||
// forward button
|
||||
4 => {
|
||||
let js = create_js_mouse_event(this, event, true, false);
|
||||
this.evaluateJavaScript_completionHandler(&NSString::from_str(&js), None);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
this.mouseDown(event);
|
||||
}
|
||||
}
|
||||
pub(crate) fn other_mouse_up(this: &WryWebView, event: &NSEvent) {
|
||||
unsafe {
|
||||
if event.r#type() == NSEventType::OtherMouseUp {
|
||||
let button_number = event.buttonNumber();
|
||||
match button_number {
|
||||
// back button
|
||||
3 => {
|
||||
let js = create_js_mouse_event(this, event, false, true);
|
||||
this.evaluateJavaScript_completionHandler(&NSString::from_str(&js), None);
|
||||
return;
|
||||
}
|
||||
// forward button
|
||||
4 => {
|
||||
let js = create_js_mouse_event(this, event, false, false);
|
||||
this.evaluateJavaScript_completionHandler(&NSString::from_str(&js), None);
|
||||
return;
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
|
||||
this.mouseUp(event);
|
||||
}
|
||||
}
|
||||
|
||||
unsafe fn create_js_mouse_event(
|
||||
view: &NSView,
|
||||
event: &NSEvent,
|
||||
down: bool,
|
||||
back_button: bool,
|
||||
) -> String {
|
||||
let event_name = if down { "mousedown" } else { "mouseup" };
|
||||
// js equivalent https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
|
||||
let button = if back_button { 3 } else { 4 };
|
||||
let mods_flags = event.modifierFlags();
|
||||
let window_point = event.locationInWindow();
|
||||
let view_point = view.convertPoint_fromView(window_point, None);
|
||||
let x = view_point.x as u32;
|
||||
let y = view_point.y as u32;
|
||||
// js equivalent https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
|
||||
let buttons = NSEvent::pressedMouseButtons();
|
||||
|
||||
format!(
|
||||
r#"(() => {{
|
||||
const el = document.elementFromPoint({x},{y});
|
||||
const ev = new MouseEvent('{event_name}', {{
|
||||
view: window,
|
||||
button: {button},
|
||||
buttons: {buttons},
|
||||
x: {x},
|
||||
y: {y},
|
||||
bubbles: true,
|
||||
detail: {detail},
|
||||
cancelBubble: false,
|
||||
cancelable: true,
|
||||
clientX: {x},
|
||||
clientY: {y},
|
||||
composed: true,
|
||||
layerX: {x},
|
||||
layerY: {y},
|
||||
pageX: {x},
|
||||
pageY: {y},
|
||||
screenX: window.screenX + {x},
|
||||
screenY: window.screenY + {y},
|
||||
ctrlKey: {ctrl_key},
|
||||
metaKey: {meta_key},
|
||||
shiftKey: {shift_key},
|
||||
altKey: {alt_key},
|
||||
}});
|
||||
el.dispatchEvent(ev)
|
||||
if (!ev.defaultPrevented && "{event_name}" === "mouseup") {{
|
||||
if (ev.button === 3) {{
|
||||
window.history.back();
|
||||
}}
|
||||
if (ev.button === 4) {{
|
||||
window.history.forward();
|
||||
}}
|
||||
}}
|
||||
}})()"#,
|
||||
event_name = event_name,
|
||||
x = x,
|
||||
y = y,
|
||||
detail = event.clickCount(),
|
||||
ctrl_key = mods_flags.contains(NSControlKeyMask),
|
||||
alt_key = mods_flags.contains(NSAlternateKeyMask),
|
||||
shift_key = mods_flags.contains(NSShiftKeyMask),
|
||||
meta_key = mods_flags.contains(NSCommandKeyMask),
|
||||
button = button,
|
||||
buttons = buttons,
|
||||
)
|
||||
}
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
// Copyright 2020-2023 Tauri Programme within The Commons Conservancy
|
||||
// SPDX-License-Identifier: Apache-2.0
|
||||
// SPDX-License-Identifier: MIT
|
||||
|
||||
use objc2_foundation::NSProcessInfo;
|
||||
|
||||
pub fn operating_system_version() -> (isize, isize, isize) {
|
||||
let process_info = NSProcessInfo::processInfo();
|
||||
let version = process_info.operatingSystemVersion();
|
||||
(
|
||||
version.majorVersion,
|
||||
version.minorVersion,
|
||||
version.patchVersion,
|
||||
)
|
||||
}
|
||||
Reference in new issue
Block a user