Skip to content

Visual Studio Code, rebuilt in Rust

Rust
25.1 KB
Raw Blame
//! platform/webview on macOS: a WKWebView added as a child of GPUI's NSView, loading upstream's host page
//! (src/vs/workbench/contrib/webview/browser/pre/index.html) the way webviewElement.ts loads it in an iframe.
//! Two seams differ from Electron: a WKURLSchemeHandler on `https` answers what the service worker answers there
//! (the host page files and `https://*.vscode-resource.vscode-cdn.net` resources, other https through NSURLSession),
//! and a WKScriptMessageHandler stands in for the window `message` event that hands the host the MessagePort.

use std::cell::RefCell;
use std::collections::HashMap;
use std::rc::Rc;
use std::sync::OnceLock;

use block2::RcBlock;
use gpui::{Bounds, Pixels, Window};
pub use objc2::rc::Retained;
use objc2::runtime::{AnyClass, Bool, Imp, NSObject, NSObjectProtocol, ProtocolObject, Sel};
use objc2::{AnyThread, ClassType, DefinedClass, MainThreadMarker, MainThreadOnly, Message, define_class, msg_send, sel};
use objc2_app_kit::{NSView, NSWindow};
use objc2_foundation::{NSData, NSDictionary, NSError, NSHTTPURLResponse, NSObjectNSKeyValueCoding, NSOperationQueue, NSPoint, NSRect, NSSize, NSString, NSURLResponse, NSURLSession, NSURLSessionConfiguration};
use objc2_web_kit::{WKContentRuleList, WKContentRuleListStore, WKScriptMessage, WKScriptMessageHandler, WKURLSchemeHandler, WKURLSchemeTask, WKUserContentController, WKUserScript, WKUserScriptInjectionTime, WKWebView, WKWebViewConfiguration};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};

use super::{BRIDGE_SCRIPT, HTTP_LOOPBACK_ONLY_RULES, MESSAGE_HANDLER, Resources, Response, Webview};

/// The native view of a webview, which `place` shows.
pub type View = Retained<WKWebView>;

pub(super) struct Native {
    view: View,
}

/// WebKit needs AppKit's main thread, which unit tests do not run on.
pub fn supported() -> bool {
    MainThreadMarker::new().is_some()
}

impl Native {
    pub(super) fn new(window: &Window, resources: Rc<Resources>, url: String) -> Self {
        let mtm = MainThreadMarker::new().expect("webviews live on the main thread");
        allow_https_scheme_handler();
        // SAFETY: `mtm` proves the main thread, where WebKit objects are made.
        let configuration = unsafe { WKWebViewConfiguration::new(mtm) };
        let handler = SchemeHandler::new(mtm, SchemeState { resources: resources.clone(), tasks: RefCell::default(), session: OnceLock::new() });
        // SAFETY: allow_https_scheme_handler ran, so WebKit takes a handler for https instead of raising; the configuration retains `handler`.
        unsafe { configuration.setURLSchemeHandler_forURLScheme(Some(ProtocolObject::from_ref(&*handler)), &NSString::from_str("https")) };
        // SAFETY: WKProcessPoolPrivate.h, macOS 10.13+. HTTP_LOOPBACK_ONLY_RULES keep http to loopback.
        unsafe {
            let pool: *mut objc2::runtime::AnyObject = msg_send![&*configuration, processPool];
            let _: () = msg_send![pool, _registerURLSchemeAsSecure: &*NSString::from_str("http")];
        }
        // SAFETY: a getter on the configuration made above, on the main thread.
        let content = unsafe { configuration.userContentController() };
        let bridge = MessageHandler::new(mtm, resources);
        // SAFETY: main thread; the controller retains `bridge` and the script, and MESSAGE_HANDLER is added once per configuration.
        unsafe {
            content.addScriptMessageHandler_name(ProtocolObject::from_ref(&*bridge), &NSString::from_str(MESSAGE_HANDLER));
            let script = WKUserScript::initWithSource_injectionTime_forMainFrameOnly(WKUserScript::alloc(mtm), &NSString::from_str(BRIDGE_SCRIPT), WKUserScriptInjectionTime::AtDocumentStart, true);
            content.addUserScript(&script);
        }
        // SAFETY: main thread; the view copies `configuration`.
        let view = unsafe { WKWebView::initWithFrame_configuration(WKWebView::alloc(mtm), NSRect::ZERO, &configuration) };
        let no = objc2_foundation::NSNumber::new_bool(false);
        let no: &objc2::runtime::AnyObject = &no;
        // SAFETY: `drawsBackground` is a key WKWebView answers (private, macOS 10.12+) with an NSNumber; main thread.
        unsafe {
            // The page background shows until the host page paints, as the transparent iframe does upstream.
            view.setValue_forKey(Some(no), &NSString::from_str("drawsBackground"));
            view.setInspectable(true);
        }
        view.setHidden(true);
        gpui_view(window).addSubview(&view);

        let url = objc2_foundation::NSURL::URLWithString(&NSString::from_str(&url)).expect("host page URL");
        let request = objc2_foundation::NSURLRequest::requestWithURL(&url);
        let loading = view.clone();
        let loaded = RcBlock::new(move |rules: *mut WKContentRuleList, error: *mut NSError| {
            // SAFETY: WebKit passes a rule list or an error.
            let rules = unsafe { rules.as_ref() }.unwrap_or_else(|| panic!("HTTP_LOOPBACK_ONLY_RULES: {:?}", unsafe { error.as_ref() }));
            // SAFETY: WebKit calls this on the main thread with `rules` non-null (checked above).
            unsafe {
                content.addContentRuleList(rules);
                loading.loadRequest(&request);
            }
        });
        // SAFETY: `mtm` proves the main thread.
        let store = unsafe { WKContentRuleListStore::defaultStore(mtm) }.expect("a default content rule list store");
        // SAFETY: the store copies the block; the strings are alive for the call.
        unsafe { store.compileContentRuleListForIdentifier_encodedContentRuleList_completionHandler(Some(&NSString::from_str("http-loopback-only")), Some(&NSString::from_str(HTTP_LOOPBACK_ONLY_RULES)), Some(&loaded)) };
        // The scheme and message handlers are retained by the configuration the view copied.
        Native { view }
    }

    pub(super) fn view(&self) -> View {
        self.view.clone()
    }

    pub(super) fn hide(&self) {
        if self.view.isHidden() {
            return;
        }
        self.release_keyboard();
        self.view.setHidden(true);
    }

    /// WebKit's own editing commands in the page, as Cmd+C runs them.
    pub(super) fn clipboard_command(&self, command: &str) {
        let nil = std::ptr::null::<objc2::runtime::AnyObject>();
        // SAFETY: WKWebView answers the NSResponder editing actions, whose sender may be nil.
        unsafe {
            match command {
                "cut" => msg_send![&*self.view, cut: nil],
                "copy" => msg_send![&*self.view, copy: nil],
                _ => msg_send![&*self.view, paste: nil],
            }
        }
    }

    /// Makes the view the first responder, as a click into it does.
    pub(super) fn take_keyboard(&self) {
        if let Some(window) = self.view.window().filter(|window| !self.is_first_responder(window)) {
            window.makeFirstResponder(Some(&self.view));
        }
    }

    /// Gives the keyboard back to GPUI's view, the view's superview.
    pub(super) fn release_keyboard(&self) {
        // SAFETY: the view is alive; its superview is GPUI's view or none.
        let (Some(window), Some(mut parent)) = (self.view.window(), unsafe { self.view.superview() }) else { return };
        if let Some(clip) = parent.downcast_ref::<ClipView>() {
            // SAFETY: the clip view is alive; its superview is GPUI's view or none.
            let Some(gpui) = (unsafe { clip.superview() }) else { return };
            parent = gpui;
        }
        if self.is_first_responder(&window) {
            window.makeFirstResponder(Some(&parent));
        }
    }

    /// Whether the view or one of its subviews is the window's first responder.
    pub(super) fn has_keyboard(&self) -> bool {
        self.view.window().is_some_and(|window| self.is_first_responder(&window))
    }

    fn is_first_responder(&self, window: &NSWindow) -> bool {
        // WKWebView hands first responder to an internal subview while editing; any descendant counts.
        let Some(responder) = window.firstResponder() else { return false };
        let Ok(view) = responder.downcast::<NSView>() else { return false };
        view.isDescendantOf(&self.view)
    }

    /// The Web Inspector of the view; WebKit has no public call to open it.
    pub(super) fn open_inspector(&self) {
        // SAFETY: `_setDeveloperExtrasEnabled:`, `_inspector` and its `show` exist since macOS 10.14. Without developer
        // extras `show` neither connects nor opens a window, `isInspectable` alone serves remote inspection only.
        unsafe {
            let preferences = self.view.configuration().preferences();
            let _: () = msg_send![&*preferences, _setDeveloperExtrasEnabled: true];
            let inspector: *mut objc2::runtime::AnyObject = msg_send![&*self.view, _inspector];
            if let Some(inspector) = inspector.as_ref() {
                let _: () = msg_send![inspector, show];
            }
        }
    }

    pub(super) fn evaluate(&self, script: &str) {
        // SAFETY: main thread (the view is MainThreadOnly); no completion handler to keep alive.
        unsafe { self.view.evaluateJavaScript_completionHandler(&NSString::from_str(script), None) };
    }
}

impl Drop for Native {
    fn drop(&mut self) {
        // SAFETY: the view is alive in its own drop, on the main thread.
        let content = unsafe { self.view.configuration().userContentController() };
        // SAFETY: removing a handler name is valid whether or not it is still registered.
        unsafe { content.removeScriptMessageHandlerForName(&NSString::from_str(MESSAGE_HANDLER)) };
        self.release_keyboard();
        self.view.removeFromSuperview();
    }
}

/// Shows `view` over `bounds`, in GPUI window coordinates.
pub fn place(view: &NSView, window: &Window, bounds: Bounds<Pixels>) {
    let parent = gpui_view(window);
    let (x, width, height) = (f64::from(f32::from(bounds.origin.x)), f64::from(f32::from(bounds.size.width)), f64::from(f32::from(bounds.size.height)));
    let top = f64::from(f32::from(bounds.origin.y));
    let y = if parent.isFlipped() { top } else { parent.bounds().size.height - top - height };
    let frame = NSRect::new(NSPoint::new(x, y), NSSize::new(width, height));
    if view.frame() != frame {
        view.setFrame(frame);
    }
    if view.isHidden() {
        view.setHidden(false);
    }
}

/// The notebook's back layer webview (backLayerWebView.ts) lies behind the cells upstream; here it floats over GPUI's
/// layer, so a clip view holds it: it shows the webview inside the notebook list only, and presses reach the
/// webview over its outputs and markdown previews only, GPUI's cells everywhere else.
pub struct ClipState {
    hit_rects: RefCell<Vec<NSRect>>,
    /// A GPUI widget over the clip (the notebook find widget): neither drawn over nor pressed, with the clip's size.
    hole: std::cell::Cell<Option<(NSRect, NSSize)>>,
}

define_class!(
    #[unsafe(super(NSView))]
    #[thread_kind = MainThreadOnly]
    #[name = "CodeGpuiWebviewClip"]
    #[ivars = ClipState]
    pub struct ClipView;

    impl ClipView {
        #[unsafe(method(isFlipped))]
        fn is_flipped(&self) -> bool {
            true
        }

        #[unsafe(method(hitTest:))]
        // The view `hitTest:` returns is not owned (+0), so it passes through as a pointer.
        fn hit_test(&self, point: NSPoint) -> *mut NSView {
            // SAFETY: the clip view is GPUI's view's subview while it is hit tested.
            let local = self.convertPoint_fromView(point, unsafe { self.superview() }.as_deref());
            let inside = |rect: &NSRect| local.x >= rect.origin.x && local.y >= rect.origin.y && local.x < rect.origin.x + rect.size.width && local.y < rect.origin.y + rect.size.height;
            if !self.ivars().hit_rects.borrow().iter().any(inside) || self.ivars().hole.get().is_some_and(|(hole, _)| inside(&hole)) {
                return std::ptr::null_mut();
            }
            // SAFETY: NSView implements hitTest:, and `point` is in the superview's coordinates, as it takes it.
            unsafe { msg_send![super(self), hitTest: point] }
        }
    }
);

impl ClipView {
    pub fn hide(&self) {
        self.setHidden(true);
    }

    pub fn remove(&self) {
        self.removeFromSuperview();
    }

    /// A hidden clip view over `window` holding `webview`.
    pub fn new(window: &Window, webview: &Webview) -> Retained<Self> {
        let mtm = MainThreadMarker::new().expect("webviews live on the main thread");
        let this = Self::alloc(mtm).set_ivars(ClipState { hit_rects: RefCell::default(), hole: std::cell::Cell::new(None) });
        // SAFETY: initWithFrame: is NSView's designated initializer, on the object allocated above with its ivars set.
        let this: Retained<Self> = unsafe { msg_send![super(this), initWithFrame: NSRect::ZERO] };
        this.setClipsToBounds(true);
        this.setHidden(true);
        webview.native.view.removeFromSuperview();
        this.addSubview(&webview.native.view);
        webview.native.view.setHidden(false);
        gpui_view(window).addSubview(&this);
        this
    }

    /// Shows the clip over `bounds` in GPUI window coordinates, its webview at `webview` (relative to the clip's
    /// origin, as `hit_rects` are).
    pub fn place(&self, webview: &WKWebView, window: &Window, bounds: Bounds<Pixels>, webview_frame: Bounds<Pixels>, hit_rects: Vec<Bounds<Pixels>>, hole: Option<Bounds<Pixels>>) {
        place(self, window, bounds);
        let frame = ns_rect(webview_frame);
        if webview.frame() != frame {
            webview.setFrame(frame);
        }
        *self.ivars().hit_rects.borrow_mut() = hit_rects.into_iter().map(ns_rect).collect();
        self.set_hole(hole.map(|hole| (ns_rect(hole), self.frame().size)));
    }

    /// Masks the clip's layer to all of it but `hole`: the part above the hole's bottom left and right of it, and the
    /// part below.
    fn set_hole(&self, hole: Option<(NSRect, NSSize)>) {
        if self.ivars().hole.get() == hole {
            return;
        }
        self.ivars().hole.set(hole);
        self.setWantsLayer(true);
        // SAFETY: CALayer and NSColor messages on the main thread; the view is layer-backed after `setWantsLayer`.
        unsafe {
            let layer: *mut objc2::runtime::AnyObject = msg_send![self, layer];
            let Some(layer) = layer.as_ref() else { return };
            let Some((hole, size)) = hole else {
                let _: () = msg_send![layer, setMask: std::ptr::null_mut::<objc2::runtime::AnyObject>()];
                return;
            };
            let flipped: Bool = msg_send![layer, isGeometryFlipped];
            let class = AnyClass::get(c"CALayer").expect("QuartzCore is loaded with AppKit");
            let mask: Retained<NSObject> = msg_send![class, layer];
            let _: () = msg_send![&*mask, setFrame: NSRect::new(NSPoint::new(0., 0.), size)];
            let black: *mut objc2::runtime::AnyObject = msg_send![AnyClass::get(c"NSColor").expect("AppKit"), blackColor];
            let color: CGColorRef = msg_send![black, CGColor];
            let bottom = hole.origin.y + hole.size.height;
            let right = hole.origin.x + hole.size.width;
            let parts = [
                NSRect::new(NSPoint::new(0., 0.), NSSize::new(hole.origin.x.max(0.), bottom)),
                NSRect::new(NSPoint::new(right, 0.), NSSize::new((size.width - right).max(0.), bottom)),
                NSRect::new(NSPoint::new(0., bottom), NSSize::new(size.width, (size.height - bottom).max(0.))),
            ];
            for part in parts {
                let part = match flipped.as_bool() {
                    true => part,
                    false => NSRect::new(NSPoint::new(part.origin.x, size.height - part.origin.y - part.size.height), part.size),
                };
                let sublayer: Retained<NSObject> = msg_send![class, layer];
                let _: () = msg_send![&*sublayer, setFrame: part];
                let _: () = msg_send![&*sublayer, setBackgroundColor: color];
                let _: () = msg_send![&*mask, addSublayer: &*sublayer];
            }
            let _: () = msg_send![layer, setMask: &*mask];
        }
    }
}

/// A `CGColorRef`, encoded as CALayer's `backgroundColor` expects.
#[repr(transparent)]
#[derive(Clone, Copy)]
struct CGColorRef(*const std::ffi::c_void);

// SAFETY: a pointer to the opaque `CGColor` struct, as `^{CGColor=}`.
unsafe impl objc2::Encode for CGColorRef {
    const ENCODING: objc2::Encoding = objc2::Encoding::Pointer(&objc2::Encoding::Struct("CGColor", &[]));
}

fn ns_rect(bounds: Bounds<Pixels>) -> NSRect {
    let value = |pixels: Pixels| f64::from(f32::from(pixels));
    NSRect::new(NSPoint::new(value(bounds.origin.x), value(bounds.origin.y)), NSSize::new(value(bounds.size.width), value(bounds.size.height)))
}

fn gpui_view(window: &Window) -> Retained<NSView> {
    let handle = HasWindowHandle::window_handle(window).expect("an open window has a handle");
    let RawWindowHandle::AppKit(handle) = handle.as_raw() else { unreachable!("GPUI on macOS has AppKit handles") };
    // SAFETY: GPUI's AppKit handle points at its NSView, alive while the window is.
    let view: &NSView = unsafe { handle.ns_view.cast().as_ref() };
    view.retain()
}

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "CodeGpuiWebviewMessageHandler"]
    #[ivars = Rc<Resources>]
    struct MessageHandler;

    // SAFETY: the superclass is NSObject, which implements NSObjectProtocol.
    unsafe impl NSObjectProtocol for MessageHandler {}

    // SAFETY: the method below has the selector and signature WKScriptMessageHandler declares.
    unsafe impl WKScriptMessageHandler for MessageHandler {
        #[unsafe(method(userContentController:didReceiveScriptMessage:))]
        fn did_receive(&self, _controller: &WKUserContentController, message: &WKScriptMessage) {
            // SAFETY: WebKit passes a valid message; `body` returns a retained object.
            let body = unsafe { message.body() };
            let Ok(text) = body.downcast::<NSString>() else { return };
            self.ivars().receive(&text.to_string());
        }
    }
);

impl MessageHandler {
    fn new(mtm: MainThreadMarker, resources: Rc<Resources>) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(resources);
        // SAFETY: `init` of NSObject on the object allocated above, whose ivars are set.
        unsafe { msg_send![super(this), init] }
    }
}

struct SchemeState {
    resources: Rc<Resources>,
    /// Loads in flight; a task WebKit stopped is dropped here and must get no more callbacks.
    tasks: RefCell<HashMap<usize, Retained<ProtocolObject<dyn WKURLSchemeTask>>>>,
    session: OnceLock<Retained<NSURLSession>>,
}

define_class!(
    #[unsafe(super(NSObject))]
    #[thread_kind = MainThreadOnly]
    #[name = "CodeGpuiWebviewSchemeHandler"]
    #[ivars = SchemeState]
    struct SchemeHandler;

    // SAFETY: the superclass is NSObject, which implements NSObjectProtocol.
    unsafe impl NSObjectProtocol for SchemeHandler {}

    // SAFETY: the methods below have the selectors and signatures WKURLSchemeHandler declares.
    unsafe impl WKURLSchemeHandler for SchemeHandler {
        #[unsafe(method(webView:startURLSchemeTask:))]
        fn start_task(&self, _web_view: &WKWebView, task: &ProtocolObject<dyn WKURLSchemeTask>) {
            self.start(task);
        }

        #[unsafe(method(webView:stopURLSchemeTask:))]
        fn stop_task(&self, _web_view: &WKWebView, task: &ProtocolObject<dyn WKURLSchemeTask>) {
            self.ivars().tasks.borrow_mut().remove(&(task as *const _ as usize));
        }
    }
);

impl SchemeHandler {
    fn new(mtm: MainThreadMarker, state: SchemeState) -> Retained<Self> {
        let this = Self::alloc(mtm).set_ivars(state);
        // SAFETY: `init` of NSObject on the object allocated above, whose ivars are set.
        unsafe { msg_send![super(this), init] }
    }

    fn start(&self, task: &ProtocolObject<dyn WKURLSchemeTask>) {
        // SAFETY: WebKit passes a valid task, on the main thread.
        let request = unsafe { task.request() };
        let Some(url) = request.URL() else { return respond(task, (404, Vec::new(), Vec::new())) };
        let host = url.host().map(|host| host.to_string().to_ascii_lowercase()).unwrap_or_default();
        let path = url.path().map(|path| path.to_string()).unwrap_or_default();
        let query = url.query().map(|query| crate::uri::percent_decode(&query.to_string())).unwrap_or_default();
        let range = request.valueForHTTPHeaderField(&NSString::from_str("Range")).map(|range| range.to_string());
        let state = self.ivars();
        let key = task as *const _ as usize;
        state.tasks.borrow_mut().insert(key, task.retain());
        let this = self.retain();
        let answer = move |response: Response| {
            let Some(task) = this.ivars().tasks.borrow_mut().remove(&key) else { return };
            respond(&task, response);
        };
        if !state.resources.serve(&host, &path, &query, range, answer) {
            self.fetch(task, key);
        }
    }

    /// Requests to the network, which the service worker leaves to the browser upstream.
    fn fetch(&self, task: &ProtocolObject<dyn WKURLSchemeTask>, key: usize) {
        let state = self.ivars();
        // SAFETY: main thread; the session retains the configuration and the main queue.
        let session = state.session.get_or_init(|| unsafe {
            NSURLSession::sessionWithConfiguration_delegate_delegateQueue(&NSURLSessionConfiguration::defaultSessionConfiguration(), None, Some(&NSOperationQueue::mainQueue()))
        });
        let this = self.retain();
        let completion = RcBlock::new(move |data: *mut NSData, response: *mut NSURLResponse, error: *mut NSError| {
            let Some(task) = this.ivars().tasks.borrow_mut().remove(&key) else { return };
            // SAFETY: NSURLSession passes valid objects or null, on the main queue it was given.
            unsafe {
                match (response.as_ref(), error.as_ref()) {
                    (Some(response), None) => {
                        task.didReceiveResponse(response);
                        if let Some(data) = data.as_ref() {
                            task.didReceiveData(data);
                        }
                        task.didFinish();
                    }
                    (_, Some(error)) => task.didFailWithError(error),
                    (None, None) => respond(&task, (502, Vec::new(), Vec::new())),
                }
            }
        });
        // SAFETY: `task` is still in `tasks`, so WebKit has not stopped it.
        let request = unsafe { task.request() };
        // SAFETY: the session copies `completion`; `request` is alive for the call.
        let data_task = unsafe { session.dataTaskWithRequest_completionHandler(&request, &completion) };
        data_task.resume();
    }
}

fn respond(task: &ProtocolObject<dyn WKURLSchemeTask>, (status, headers, body): Response) {
    // SAFETY: the caller holds a task WebKit has not stopped.
    let request = unsafe { task.request() };
    let url = request.URL().expect("a scheme task has a URL");
    let length = body.len().to_string();
    let keys: Vec<Retained<NSString>> = headers.iter().map(|(key, _)| NSString::from_str(key)).chain([NSString::from_str("Content-Length")]).collect();
    let values: Vec<Retained<NSString>> = headers.iter().map(|(_, value)| NSString::from_str(value)).chain([NSString::from_str(&length)]).collect();
    let fields = NSDictionary::from_slices(&keys.iter().map(|key| &**key).collect::<Vec<_>>(), &values.iter().map(|value| &**value).collect::<Vec<_>>());
    let response = NSHTTPURLResponse::initWithURL_statusCode_HTTPVersion_headerFields(NSHTTPURLResponse::alloc(), &url, status as isize, Some(&NSString::from_str("HTTP/1.1")), Some(&fields)).expect("an HTTP response");
    // SAFETY: response, data, finish in the order WKURLSchemeTask requires, on a task WebKit has not stopped (it raises on a stopped one).
    unsafe {
        task.didReceiveResponse(&response);
        task.didReceiveData(&NSData::from_vec(body));
        task.didFinish();
    }
}

static ORIGINAL_HANDLES_URL_SCHEME: OnceLock<Imp> = OnceLock::new();

/// `-[WKWebViewConfiguration setURLSchemeHandler:forURLScheme:]` refuses schemes `+[WKWebView handlesURLScheme:]`
/// claims; answering NO for https lets the handler stand in for the service worker on `https://*.vscode-cdn.net`.
fn allow_https_scheme_handler() {
    ORIGINAL_HANDLES_URL_SCHEME.get_or_init(|| {
        let method = WKWebView::class().class_method(sel!(handlesURLScheme:)).expect("+[WKWebView handlesURLScheme:]");
        let replacement: extern "C-unwind" fn(&AnyClass, Sel, &NSString) -> Bool = handles_url_scheme;
        // SAFETY: the replacement has the method's signature, `+ (BOOL)handlesURLScheme:(NSString *)`.
        unsafe { method.set_implementation(std::mem::transmute::<extern "C-unwind" fn(&AnyClass, Sel, &NSString) -> Bool, Imp>(replacement)) }
    });
}

extern "C-unwind" fn handles_url_scheme(class: &AnyClass, selector: Sel, scheme: &NSString) -> Bool {
    if scheme.to_string() == "https" {
        return Bool::NO;
    }
    let original = *ORIGINAL_HANDLES_URL_SCHEME.get().expect("swizzled");
    // SAFETY: the original implementation of the same method.
    let original: extern "C-unwind" fn(&AnyClass, Sel, &NSString) -> Bool = unsafe { std::mem::transmute(original) };
    original(class, selector, scheme)
}