use std::cell::{Cell, RefCell};
use std::path::PathBuf;
use std::rc::Rc;
use std::time::Duration;
use objc2::rc::Retained;
use objc2::runtime::{Bool, ProtocolObject};
use objc2::{define_class, msg_send, DefinedClass, MainThreadMarker, MainThreadOnly, Message};
use objc2_foundation::{
NSData, NSError, NSHTTPURLResponse, NSInteger, NSObject, NSObjectProtocol, NSRect, NSString,
NSURLAuthenticationChallenge, NSURLCredential, NSURLRequest, NSURLResponse, NSURL,
};
use objc2_web_kit::{
WKDownload, WKDownloadDelegate, WKFrameInfo, WKNavigation, WKNavigationAction,
WKNavigationDelegate, WKNavigationResponse, WKNavigationResponsePolicy, WKUIDelegate,
WKWebView, WKWebViewConfiguration, WKWindowFeatures,
};
use crate::backend::native_download::{
is_attachment, name_from_disposition, temp_path, SharedDownloads, MAX_BYTES,
};
use crate::engine::PageHandle;
#[derive(Debug, Default)]
pub(super) struct NavState {
pub started: bool,
pub committed: bool,
pub done: Option<Result<(), String>>,
}
impl NavState {
pub(super) fn reset(&mut self) {
*self = Self::default();
}
}
pub(super) type NavSlot = Rc<RefCell<NavState>>;
pub(super) struct NavDelegateIvars {
pub(super) slot: NavSlot,
pub(super) new_window: RefCell<Option<Retained<NSURLRequest>>>,
pub(super) downloads: SharedDownloads,
pub(super) in_flight: RefCell<Vec<(usize, u64, PathBuf)>>,
pub(super) main_became_download: Cell<bool>,
pub(super) main_response: RefCell<Option<crate::inspector::MainResponse>>,
pub(super) trust_anchor: RefCell<Option<Vec<u8>>>,
pub(super) popups: RefCell<Option<super::PopupQueue>>,
pub(super) page: Cell<Option<PageHandle>>,
}
fn ns_str(s: Option<Retained<NSString>>) -> String {
s.map(|s| s.to_string()).unwrap_or_default()
}
fn response_url(r: &NSURLResponse) -> String {
r.URL()
.and_then(|u| u.absoluteString())
.map(|s| s.to_string())
.unwrap_or_default()
}
fn disposition(r: &NSURLResponse) -> String {
let r: Retained<NSURLResponse> = r.retain();
r.downcast::<NSHTTPURLResponse>()
.ok()
.and_then(|h| h.valueForHTTPHeaderField(&NSString::from_str("Content-Disposition")))
.map(|s| s.to_string())
.unwrap_or_default()
}
fn http_response(r: &NSURLResponse) -> Option<crate::inspector::MainResponse> {
let url = response_url(r);
let h = r.retain().downcast::<NSHTTPURLResponse>().ok()?;
let status = u16::try_from(h.statusCode()).unwrap_or(0);
let (keys, values) = h.allHeaderFields().to_vecs();
let mut headers: Vec<(String, String)> = keys
.into_iter()
.zip(values)
.filter_map(|(k, v)| {
let k = k.downcast::<NSString>().ok()?.to_string();
let v = v.downcast::<NSString>().ok()?.to_string();
Some((k.to_ascii_lowercase(), v))
})
.collect();
headers.sort();
Some(crate::inspector::MainResponse {
url,
status,
status_text: crate::inspector::reason_phrase(status).to_string(),
headers,
})
}
fn wants_download(resp: &WKNavigationResponse) -> bool {
let r = unsafe { resp.response() };
let url = response_url(&r);
if !(url.starts_with("http:") || url.starts_with("https:")) {
return false;
}
is_attachment(&disposition(&r)) || !unsafe { resp.canShowMIMEType() }
}
define_class!(
#[unsafe(super = NSObject)]
#[thread_kind = MainThreadOnly]
#[name = "VsNavDelegate"]
#[ivars = NavDelegateIvars]
pub(super) struct NavDelegate;
impl NavDelegate {
#[unsafe(method(webView:didStartProvisionalNavigation:))]
fn did_start(&self, _web_view: &WKWebView, _nav: Option<&WKNavigation>) {
self.ivars().slot.borrow_mut().started = true;
self.ivars().main_response.borrow_mut().take();
}
#[unsafe(method(webView:didCommitNavigation:))]
fn did_commit(&self, _web_view: &WKWebView, _nav: Option<&WKNavigation>) {
let mut slot = self.ivars().slot.borrow_mut();
slot.started = true;
slot.committed = true;
}
#[unsafe(method(webView:didFinishNavigation:))]
fn did_finish(&self, _web_view: &WKWebView, _nav: Option<&WKNavigation>) {
let mut slot = self.ivars().slot.borrow_mut();
slot.started = true;
slot.committed = true;
slot.done = Some(Ok(()));
}
#[unsafe(method(webView:didFailNavigation:withError:))]
fn did_fail(
&self,
_web_view: &WKWebView,
_nav: Option<&WKNavigation>,
error: &NSError,
) {
let msg = error.localizedDescription().to_string();
self.ivars().slot.borrow_mut().done = Some(Err(msg));
}
#[unsafe(method(webView:didFailProvisionalNavigation:withError:))]
fn did_fail_provisional(
&self,
_web_view: &WKWebView,
_nav: Option<&WKNavigation>,
error: &NSError,
) {
if self.ivars().main_became_download.replace(false) {
self.ivars().slot.borrow_mut().done = Some(Ok(()));
return;
}
let msg = error.localizedDescription().to_string();
self.ivars().slot.borrow_mut().done = Some(Err(msg));
}
#[unsafe(method(webView:decidePolicyForNavigationResponse:decisionHandler:))]
fn decide_response(
&self,
_web_view: &WKWebView,
resp: &WKNavigationResponse,
handler: &block2::DynBlock<dyn Fn(WKNavigationResponsePolicy)>,
) {
let main = unsafe { resp.isForMainFrame() };
let policy = if wants_download(resp) {
if main {
self.ivars().main_became_download.set(true);
}
WKNavigationResponsePolicy::Download
} else {
if main {
let r = unsafe { resp.response() };
*self.ivars().main_response.borrow_mut() = http_response(&r);
}
WKNavigationResponsePolicy::Allow
};
handler.call((policy,));
}
#[unsafe(method(webView:didReceiveAuthenticationChallenge:completionHandler:))]
fn auth_challenge(
&self,
_web_view: &WKWebView,
challenge: &NSURLAuthenticationChallenge,
handler: &block2::DynBlock<dyn Fn(NSInteger, *mut NSURLCredential)>,
) {
let cred = self
.ivars()
.trust_anchor
.borrow()
.as_deref()
.and_then(|ca| super::trust::credential_for(challenge, ca));
match cred {
Some(c) => handler.call((0, Retained::as_ptr(&c).cast_mut())),
None => handler.call((1, std::ptr::null_mut())),
}
}
#[unsafe(method(webView:navigationResponse:didBecomeDownload:))]
fn response_became_download(
&self,
_web_view: &WKWebView,
resp: &WKNavigationResponse,
download: &WKDownload,
) {
let r = unsafe { resp.response() };
let name = name_from_disposition(&disposition(&r))
.unwrap_or_else(|| ns_str(r.suggestedFilename()));
let id = match self.ivars().downloads.lock() {
Ok(mut d) => d.begin(&response_url(&r), &name, &ns_str(r.MIMEType())),
Err(_) => return,
};
let key = std::ptr::from_ref(download) as usize;
self.ivars()
.in_flight
.borrow_mut()
.push((key, id, temp_path(id)));
unsafe { download.setDelegate(Some(ProtocolObject::from_ref(self))) };
}
#[unsafe(method(_webView:getWindowFrameWithCompletionHandler:))]
fn get_window_frame(
&self,
web_view: &WKWebView,
handler: &block2::DynBlock<dyn Fn(NSRect)>,
) {
let frame = web_view
.window()
.map_or_else(|| web_view.frame(), |w| w.frame());
handler.call((frame,));
}
#[unsafe(method(webView:createWebViewWithConfiguration:forNavigationAction:windowFeatures:))]
fn create_web_view(
&self,
web_view: &WKWebView,
config: &WKWebViewConfiguration,
action: &WKNavigationAction,
_features: &WKWindowFeatures,
) -> *mut WKWebView {
let request = unsafe { action.request() };
let queue = self.ivars().popups.borrow().clone();
if let Some(queue) = queue {
let url = request
.URL()
.and_then(|u| u.absoluteString())
.map(|s| s.to_string())
.unwrap_or_default();
let anchor = self.ivars().trust_anchor.borrow().clone();
let opener = self.ivars().page.get();
let view =
super::spawn_popup(self.mtm(), opener, web_view, config, url, anchor, &queue);
return Retained::as_ptr(&view).cast_mut();
}
*self.ivars().new_window.borrow_mut() = Some(request);
std::ptr::null_mut()
}
#[unsafe(method(webViewDidClose:))]
fn did_close(&self, _web_view: &WKWebView) {
let queue = self.ivars().popups.borrow().clone();
if let (Some(queue), Some(page)) = (queue, self.ivars().page.get()) {
super::popup_closed(&queue, page);
}
}
#[unsafe(method(webView:runJavaScriptAlertPanelWithMessage:initiatedByFrame:completionHandler:))]
fn alert(
&self,
_web_view: &WKWebView,
message: &NSString,
_frame: &WKFrameInfo,
handler: &block2::DynBlock<dyn Fn()>,
) {
let h = handler.copy();
let finish = Box::new(move |_: Option<crate::engine::DialogAnswer>| h.call(()));
if !self.report_dialog("alert", message, None, finish) {
handler.call(());
}
}
#[unsafe(method(webView:runJavaScriptConfirmPanelWithMessage:initiatedByFrame:completionHandler:))]
fn confirm(
&self,
_web_view: &WKWebView,
message: &NSString,
_frame: &WKFrameInfo,
handler: &block2::DynBlock<dyn Fn(Bool)>,
) {
let h = handler.copy();
let finish = Box::new(move |a: Option<crate::engine::DialogAnswer>| {
h.call((Bool::new(a.is_some_and(|a| a.accept)),));
});
if !self.report_dialog("confirm", message, None, finish) {
handler.call((Bool::NO,));
}
}
#[unsafe(method(webView:runJavaScriptTextInputPanelWithPrompt:defaultText:initiatedByFrame:completionHandler:))]
fn prompt(
&self,
_web_view: &WKWebView,
prompt: &NSString,
default_text: Option<&NSString>,
_frame: &WKFrameInfo,
handler: &block2::DynBlock<dyn Fn(*mut NSString)>,
) {
let default = default_text.map(ToString::to_string).unwrap_or_default();
let h = handler.copy();
let fallback = default.clone();
let finish = Box::new(move |a: Option<crate::engine::DialogAnswer>| match a {
Some(a) if a.accept => {
let text = NSString::from_str(&a.text.unwrap_or_else(|| fallback.clone()));
h.call((Retained::as_ptr(&text).cast_mut(),));
}
_ => h.call((std::ptr::null_mut(),)),
});
if !self.report_dialog("prompt", prompt, Some(default), finish) {
handler.call((std::ptr::null_mut(),));
}
}
}
unsafe impl NSObjectProtocol for NavDelegate {}
unsafe impl WKNavigationDelegate for NavDelegate {}
unsafe impl WKUIDelegate for NavDelegate {}
unsafe impl WKDownloadDelegate for NavDelegate {
#[unsafe(method(download:decideDestinationUsingResponse:suggestedFilename:completionHandler:))]
fn decide_destination(
&self,
download: &WKDownload,
response: &NSURLResponse,
suggested: &NSString,
handler: &block2::DynBlock<dyn Fn(*mut NSURL)>,
) {
let Some((id, path)) = self.in_flight_entry(download) else {
handler.call((std::ptr::null_mut(),));
return;
};
if let Ok(mut d) = self.ivars().downloads.lock() {
let header = name_from_disposition(&disposition(response));
if header.is_none() {
d.set_name(id, &suggested.to_string());
}
}
let expected = response.expectedContentLength();
if u64::try_from(expected).is_ok_and(|n| n > MAX_BYTES) {
self.settle(download, Err(format!(
"download exceeds {MAX_BYTES} bytes ({expected})"
)));
handler.call((std::ptr::null_mut(),));
return;
}
let _ = std::fs::remove_file(&path);
let url = NSURL::fileURLWithPath(&NSString::from_str(&path.to_string_lossy()));
handler.call((Retained::as_ptr(&url).cast_mut(),));
}
#[unsafe(method(downloadDidFinish:))]
fn download_did_finish(&self, download: &WKDownload) {
let Some((_, path)) = self.in_flight_entry(download) else {
return;
};
let bytes = std::fs::read(&path).map_err(|e| format!("read {}: {e}", path.display()));
let _ = std::fs::remove_file(&path);
self.settle(download, bytes);
}
#[unsafe(method(download:didFailWithError:resumeData:))]
fn download_did_fail(
&self,
download: &WKDownload,
error: &NSError,
_resume: Option<&NSData>,
) {
if let Some((_, path)) = self.in_flight_entry(download) {
let _ = std::fs::remove_file(&path);
}
self.settle(download, Err(error.localizedDescription().to_string()));
}
}
);
impl NavDelegate {
pub(super) fn new(
mtm: MainThreadMarker,
slot: NavSlot,
downloads: SharedDownloads,
) -> Retained<Self> {
let this = Self::alloc(mtm).set_ivars(NavDelegateIvars {
slot,
new_window: RefCell::new(None),
downloads,
in_flight: RefCell::new(Vec::new()),
main_became_download: Cell::new(false),
main_response: RefCell::new(None),
trust_anchor: RefCell::new(None),
popups: RefCell::new(None),
page: Cell::new(None),
});
unsafe { msg_send![super(this), init] }
}
pub(super) fn set_trust_anchor(&self, ca_der: Vec<u8>) {
*self.ivars().trust_anchor.borrow_mut() = Some(ca_der);
}
pub(super) fn set_popups(&self, queue: Option<super::PopupQueue>, page: Option<PageHandle>) {
*self.ivars().popups.borrow_mut() = queue;
self.ivars().page.set(page);
}
pub(super) fn popups(&self) -> bool {
self.ivars().popups.borrow().is_some()
}
fn report_dialog(
&self,
kind: &'static str,
message: &NSString,
default: Option<String>,
finish: Box<dyn Fn(Option<crate::engine::DialogAnswer>)>,
) -> bool {
let queue = self.ivars().popups.borrow().clone();
let (Some(queue), Some(page)) = (queue, self.ivars().page.get()) else {
return false;
};
let feed = queue.borrow().feed.clone();
let id = feed.next_dialog_id();
feed.push(crate::engine::PopupEvent::Dialog(crate::engine::Dialog {
page,
id,
kind,
message: message.to_string(),
default: default.unwrap_or_default(),
}));
super::dialogs::await_answer(feed, id, finish);
true
}
pub(super) fn slot(&self) -> NavSlot {
self.ivars().slot.clone()
}
pub(super) fn downloads(&self) -> SharedDownloads {
self.ivars().downloads.clone()
}
pub(super) fn main_response(&self) -> Option<crate::inspector::MainResponse> {
self.ivars().main_response.borrow().clone()
}
pub(super) fn has_new_window(&self) -> bool {
self.ivars().new_window.borrow().is_some()
}
fn in_flight_entry(&self, download: &WKDownload) -> Option<(u64, PathBuf)> {
let key = std::ptr::from_ref(download) as usize;
self.ivars()
.in_flight
.borrow()
.iter()
.find(|(k, _, _)| *k == key)
.map(|(_, id, p)| (*id, p.clone()))
}
fn settle(&self, download: &WKDownload, result: Result<Vec<u8>, String>) {
let key = std::ptr::from_ref(download) as usize;
let mut in_flight = self.ivars().in_flight.borrow_mut();
let Some(pos) = in_flight.iter().position(|(k, _, _)| *k == key) else {
return;
};
let (_, id, _) = in_flight.remove(pos);
if let Ok(mut d) = self.ivars().downloads.lock() {
d.finish(id, result);
}
}
pub(super) fn take_new_window(&self) -> Option<Retained<NSURLRequest>> {
self.ivars().new_window.borrow_mut().take()
}
}
const LAUNCH_BUDGET: Duration = Duration::from_secs(45);
pub(super) fn wait_for_navigation(
slot: &NavSlot,
load_budget: Duration,
primitive: &'static str,
) -> crate::engine::EngineResult<()> {
use crate::engine::EngineError;
use super::eval::run_loop_until;
let launched = run_loop_until(
|| {
let state = slot.borrow();
state.started || state.committed || state.done.is_some()
},
LAUNCH_BUDGET,
);
if !launched {
return Err(EngineError::Timeout {
budget: LAUNCH_BUDGET,
primitive,
detail: "web process did not start",
});
}
if let Some(result) = slot.borrow().done.clone() {
return result.map_err(|msg| EngineError::Other(format!("navigation failed: {msg}")));
}
let _finished = run_loop_until(|| slot.borrow().done.is_some(), load_budget);
let state = slot.borrow();
match &state.done {
Some(Ok(())) => Ok(()),
Some(Err(msg)) => Err(EngineError::Other(format!("navigation failed: {msg}"))),
None if state.committed => Ok(()),
None => Err(EngineError::Timeout {
budget: load_budget,
primitive,
detail: "navigation did not finish",
}),
}
}