Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

refactor(macos): migrate to objc2 #1316

Merged
merged 45 commits into from
Oct 11, 2024
Merged
Changes from 1 commit
Commits
Show all changes
45 commits
Select commit Hold shift + click to select a range
0da1952
migrate drag & drop
pewsheen Mar 27, 2024
73f0541
refactor: migrate to `dpi` crate (#1202)
amrbashir Mar 28, 2024
93f608f
fix(windows): avoid double-free the controller (#1206)
amrbashir Apr 1, 2024
990759f
fix(linux): Disable deprecated applicationCache web api. (#1207)
FabianLars Apr 1, 2024
7c2cbcd
fix(wkwebview): menu shortcuts (#1208)
thewh1teagle Apr 1, 2024
97ad528
Apply Version Updates From Current Changes (#1203)
github-actions[bot] Apr 1, 2024
4f445fa
migrate to `objc2`
pewsheen Apr 2, 2024
1bcbde0
fix(macos): response body being double freed
pewsheen Jul 8, 2024
ec9f3c3
fix(macos): eval callback NSStrgin convertion error
pewsheen Jul 8, 2024
8dbd6cf
chore: remove objc dependency
pewsheen Jul 8, 2024
cf2ac97
refactor(macos): migrate WebViewDelegate
pewsheen Jul 9, 2024
2e5d9fe
refactor(macos): migrate proxy to objc2
pewsheen Jul 9, 2024
f4309e7
refactor(macos): migrate document title change observer to objc2
pewsheen Jul 9, 2024
b4e51ed
refactor(macos): move drag&drop handler to delegate
pewsheen Jul 9, 2024
be6d74e
refactor(macos): move ipc_handler into WryWebViewDelegate
pewsheen Jul 9, 2024
e62e116
refactor(macos): migrate download handler
pewsheen Jul 9, 2024
986cecd
Merge branch 'dev' into refactor/migrate-to-objc2
pewsheen Jul 10, 2024
2fb6be9
fix(macos): prevent unsafe async custom protocol panic
pewsheen Jul 10, 2024
4eec6fb
chore: target os import
pewsheen Jul 10, 2024
78c5bf2
Merge branch 'dev' into refactor/migrate-to-objc2
pewsheen Jul 10, 2024
a6f7ce4
refactor(ios): migrate to objc2
pewsheen Jul 10, 2024
ce7b9d0
refactor(macos): migrate WebViewUIDelegate to objc2
pewsheen Jul 11, 2024
1abff79
refactor(macos): migrate WryWebViewParent to objc2
pewsheen Jul 11, 2024
e8d2c6e
refactor(macos): move custom class to individual files
pewsheen Jul 11, 2024
ab9804b
chore: fix clippy
pewsheen Jul 11, 2024
5f55c39
Merge branch 'dev' into refactor/migrate-to-objc2
pewsheen Jul 16, 2024
f889b7c
Merge branch 'dev' into refactor/migrate-to-objc2
pewsheen Jul 22, 2024
92a0242
Merge branch 'dev' into refactor/migrate-to-objc2
Aug 14, 2024
a769067
Merge branch 'dev' into refactor/migrate-to-objc2
Aug 23, 2024
a741fef
refector: use reference for task. use objc2::exception::catch.
Aug 24, 2024
47140fa
fix(dnd): use msg_send super and impl NSDraggingDestination
Aug 26, 2024
880e798
chore: call msg_send super
Aug 26, 2024
23444cb
fix: wrap Box<dyn FnMut(..)> with RefCell
Aug 29, 2024
7674bf3
chore(deps): update rust crate tao to 0.29 (#1343)
renovate[bot] Aug 26, 2024
796b6ec
refactor: use bitflags way to handle mask bit manipulation
Aug 29, 2024
a7919ca
Merge branch 'dev' into refactor/migrate-to-objc2
Sep 8, 2024
56a5616
WIP: refactor(ios): add wkwebview for ios
Sep 8, 2024
7f19a2f
Merge branch 'dev' into refactor/migrate-to-objc2
Sep 18, 2024
d0f6990
Update Cargo.toml
Sep 18, 2024
50c681f
Merge branch 'dev' into refactor/migrate-to-objc2
Oct 7, 2024
98372ef
fix: remove `.copy()` from RcBlock
Oct 8, 2024
abe4085
Merge branch 'dev' into refactor/migrate-to-objc2
lucasfernog Oct 11, 2024
34a3972
add change file
lucasfernog Oct 11, 2024
d09873c
lint
lucasfernog Oct 11, 2024
faef2eb
fmt
lucasfernog Oct 11, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
Next Next commit
refactor(macos): migrate WebViewDelegate
pewsheen committed Jul 9, 2024

Verified

This commit was signed with the committer’s verified signature.
paescuj Pascal Jufer
commit cf2ac973e78718e7756b074df66d41026aff51af
65 changes: 37 additions & 28 deletions src/wkwebview/drag_drop.rs
Original file line number Diff line number Diff line change
@@ -82,16 +82,19 @@ pub(crate) fn dragging_entered(
this: &WryWebView,
drag_info: &ProtocolObject<dyn NSDraggingInfo>,
) -> NSDragOperation {
let listener = this.ivars().drag_drop_handler.borrow();
let listener = this.ivars().drag_drop_handler;
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);
if !listener(DragDropEvent::Enter { paths, position }) {
// Reject the Wry file drop (invoke the OS default behaviour)
OBJC_DRAGGING_ENTERED(this, objc2::sel!(draggingEntered:), drag_info)
} else {
NSDragOperation::Copy

unsafe {
if !(*listener)(DragDropEvent::Enter { paths, position }) {
// Reject the Wry file drop (invoke the OS default behaviour)
OBJC_DRAGGING_ENTERED(this, objc2::sel!(draggingEntered:), drag_info)
} else {
NSDragOperation::Copy
}
}
}

@@ -102,20 +105,22 @@ pub(crate) fn dragging_updated(
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.borrow();
if !listener(DragDropEvent::Over { position }) {
let os_operation = OBJC_DRAGGING_UPDATED(this, objc2::sel!(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
let listener = this.ivars().drag_drop_handler;
unsafe {
if !(*listener)(DragDropEvent::Over { position }) {
let os_operation = OBJC_DRAGGING_UPDATED(this, objc2::sel!(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 {
// 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
NSDragOperation::Copy
}
} else {
NSDragOperation::Copy
}
}

@@ -127,19 +132,23 @@ pub(crate) fn perform_drag_operation(
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.borrow();
if !listener(DragDropEvent::Drop { paths, position }) {
// Reject the Wry drop (invoke the OS default behaviour)
OBJC_PERFORM_DRAG_OPERATION(this, objc2::sel!(performDragOperation:), drag_info)
} else {
Bool::YES
let listener = this.ivars().drag_drop_handler;
unsafe {
if !(*listener)(DragDropEvent::Drop { paths, position }) {
// Reject the Wry drop (invoke the OS default behaviour)
OBJC_PERFORM_DRAG_OPERATION(this, objc2::sel!(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.borrow();
if !listener(DragDropEvent::Leave) {
// Reject the Wry drop (invoke the OS default behaviour)
OBJC_DRAGGING_EXITED(this, objc2::sel!(draggingExited:), drag_info);
let listener = this.ivars().drag_drop_handler;
unsafe {
if !(*listener)(DragDropEvent::Leave) {
// Reject the Wry drop (invoke the OS default behaviour)
OBJC_DRAGGING_EXITED(this, objc2::sel!(draggingExited:), drag_info);
}
}
}
169 changes: 87 additions & 82 deletions src/wkwebview/mod.rs
Original file line number Diff line number Diff line change
@@ -19,6 +19,7 @@ use objc2::{
declare::ClassBuilder,
declare_class,
ffi::YES,
msg_send_id,
mutability::MainThreadOnly,
rc::{Allocated, Retained},
runtime::{AnyClass, AnyObject, Bool, NSObject, ProtocolObject},
@@ -47,7 +48,6 @@ use raw_window_handle::{HasWindowHandle, RawWindowHandle};

use std::{
borrow::Cow,
cell::RefCell,
ffi::{c_void, CStr},
os::raw::c_char,
ptr::{null_mut, NonNull},
@@ -162,48 +162,6 @@ impl InnerWebView {
) -> Result<Self> {
let mtm = MainThreadMarker::new().ok_or(Error::NotMainThread)?;

// Function for ipc handler
extern "C" fn did_receive(
this: &AnyObject,
_: objc2::runtime::Sel,
_: &AnyObject,
msg: &WKScriptMessage,
) {
// Safety: objc runtime calls are unsafe
unsafe {
#[cfg(feature = "tracing")]
let _span = tracing::info_span!("wry::ipc::handle").entered();

let function = this.get_ivar::<*mut c_void>("function");
if !function.is_null() {
let function = &mut *(*function as *mut Box<dyn Fn(Request<String>)>);
let body = msg.body();
let is_string = Retained::cast::<NSObject>(body.clone()).isKindOfClass(NSString::class());
if is_string {
let body = Retained::cast::<NSString>(body);
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(),
) {
(function)(Request::builder().uri(url).body(js.to_string()).unwrap());
return;
}
}
}

#[cfg(feature = "tracing")]
tracing::warn!("WebView received invalid IPC call.");
}
}

// Task handler for custom protocol
extern "C" fn start_task(
this: &AnyObject,
@@ -420,8 +378,8 @@ impl InnerWebView {
let webview = mtm.alloc::<WryWebView>().set_ivars(WryWebViewIvars {
#[cfg(target_os = "macos")]
drag_drop_handler: match attributes.drag_drop_handler {
Some(handler) => RefCell::new(handler),
None => RefCell::new(Box::new(|_| false)),
Some(handler) => Box::into_raw(Box::new(handler)),
None => Box::into_raw(Box::new(Box::new(|_| false))),
},
#[cfg(target_os = "macos")]
accept_first_mouse: Bool::new(attributes.accept_first_mouse),
@@ -448,7 +406,7 @@ impl InnerWebView {
let () = msg_send![data_store, setProxyConfigurations: proxies];
}

_preference.as_super().setValue_forKey(
_preference.setValue_forKey(
Some(&_yes),
ns_string!("allowsPictureInPictureMediaPlayback"),
);
@@ -470,9 +428,7 @@ impl InnerWebView {
#[cfg(feature = "fullscreen")]
// Equivalent Obj-C:
// [preference setValue:@YES forKey:@"fullScreenEnabled"];
_preference
.as_super()
.setValue_forKey(Some(&_yes), ns_string!("fullScreenEnabled"));
_preference.setValue_forKey(Some(&_yes), ns_string!("fullScreenEnabled"));

#[cfg(target_os = "macos")]
let webview = {
@@ -534,13 +490,10 @@ impl InnerWebView {
}

// allowsBackForwardNavigation
let value = attributes.back_forward_navigation_gestures;
webview.setAllowsBackForwardNavigationGestures(value);
webview.setAllowsBackForwardNavigationGestures(attributes.back_forward_navigation_gestures);

// tabFocusesLinks
_preference
.as_super()
.setValue_forKey(Some(&_yes), ns_string!("tabFocusesLinks"));
_preference.setValue_forKey(Some(&_yes), ns_string!("tabFocusesLinks"));
}
#[cfg(target_os = "ios")]
{
@@ -571,29 +524,12 @@ impl InnerWebView {

// Message handler
let ipc_handler_ptr = if let Some(ipc_handler) = attributes.ipc_handler {
let cls = ClassBuilder::new("WebViewDelegate", NSObject::class());
let cls = match cls {
Some(mut cls) => {
cls.add_ivar::<*mut c_void>("function");
cls.add_method(
objc2::sel!(userContentController:didReceiveScriptMessage:),
did_receive as extern "C" fn(_, _, _, _),
);
cls.register()
}
None => class!(WebViewDelegate),
};
let handler: *mut AnyObject = objc2::msg_send![cls, new];
let ipc_handler_ptr = Box::into_raw(Box::new(ipc_handler));

let ivar = (*handler).class().instance_variable("function").unwrap();
let ivar_delegate = ivar.load_mut(&mut *handler);
*ivar_delegate = ipc_handler_ptr as *mut _ as *mut c_void;

let ipc = NSString::from_str(IPC_MESSAGE_HANDLER_NAME);
let delegate = WryWebViewDelegate::new(ipc_handler_ptr, mtm);
let proto_delegate = ProtocolObject::from_ref(delegate.as_ref());
manager.addScriptMessageHandler_name(
&*(handler.cast::<ProtocolObject<dyn WKScriptMessageHandler>>()),
&ipc,
proto_delegate,
&NSString::from_str(IPC_MESSAGE_HANDLER_NAME),
);
ipc_handler_ptr
} else {
@@ -933,10 +869,6 @@ impl InnerWebView {
objc2::msg_send_id![ui_delegate, new];
webview.setUIDelegate(Some(&*ui_delegate));

// File drop handling
#[cfg(target_os = "macos")]
let drag_drop_ptr = webview.ivars().drag_drop_handler.as_ptr();

// ns window is required for the print operation
#[cfg(target_os = "macos")]
{
@@ -956,7 +888,7 @@ impl InnerWebView {
document_title_changed_handler,
navigation_decide_policy_ptr,
#[cfg(target_os = "macos")]
drag_drop_ptr,
drag_drop_ptr: webview.ivars().drag_drop_handler,
page_load_handler,
download_delegate,
protocol_ptrs,
@@ -1365,7 +1297,7 @@ impl Drop for InnerWebView {

#[cfg(target_os = "macos")]
if !self.drag_drop_ptr.is_null() {
drop(Rc::from_raw(self.drag_drop_ptr));
drop(Box::from_raw(self.drag_drop_ptr));
}

if !self.download_delegate.is_null() {
@@ -1396,7 +1328,7 @@ unsafe fn window_position(view: &NSView, x: i32, y: i32, height: f64) -> CGPoint

pub struct WryWebViewIvars {
#[cfg(target_os = "macos")]
drag_drop_handler: RefCell<Box<dyn Fn(DragDropEvent) -> bool>>,
drag_drop_handler: *mut Box<dyn Fn(DragDropEvent) -> bool>,
#[cfg(target_os = "macos")]
accept_first_mouse: objc2::runtime::Bool,
}
@@ -1488,3 +1420,76 @@ declare_class!(
}
}
);

struct WryWebViewDelegateIvars {
ipc_handler: *mut Box<dyn Fn(Request<String>)>,
}

declare_class!(
struct WryWebViewDelegate;

unsafe impl ClassType for WryWebViewDelegate {
type Super = NSObject;
type Mutability = MainThreadOnly;
const NAME: &'static str = "WryWebViewDelegate";
}

impl DeclaredClass for WryWebViewDelegate {
type Ivars = WryWebViewDelegateIvars;
}

unsafe impl NSObjectProtocol for WryWebViewDelegate {}

unsafe impl WKScriptMessageHandler for WryWebViewDelegate {
// Function for ipc handler
#[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!("wry::ipc::handle").entered();

let ipc_handler = this.ivars().ipc_handler;
if !ipc_handler.is_null() {
let body = msg.body();
let is_string = Retained::cast::<NSObject>(body.clone()).isKindOfClass(NSString::class());
if is_string {
let body = Retained::cast::<NSString>(body);
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(),
) {
(*ipc_handler)(Request::builder().uri(url).body(js.to_string()).unwrap());
return;
}
}
}

#[cfg(feature = "tracing")]
tracing::warn!("WebView received invalid IPC call.");
}
}
}
);

impl WryWebViewDelegate {
fn new(ipc_handler: *mut Box<dyn Fn(Request<String>)>, mtm: MainThreadMarker) -> Retained<Self> {
let this = mtm
.alloc::<WryWebViewDelegate>()
.set_ivars(WryWebViewDelegateIvars { ipc_handler });

unsafe { msg_send_id![super(this), init] }
}
}