Skip to content

Visual Studio Code, rebuilt in Rust

Rust
21.7 KB
Raw Blame
//! platform/webview on Windows: a WebView2 (webview2-com) in a child window of GPUI's HWND, loading upstream's host
//! page (src/vs/workbench/contrib/webview/browser/pre/index.html) as macos.rs does. A WebResourceRequested handler
//! answers what the service worker answers there (the host page files and `https://*.vscode-resource.vscode-cdn.net`
//! resources), every other request goes to the network; `chrome.webview.postMessage` stands in for the window
//! `message` event. WebView2 makes its controller asynchronously on GPUI's message loop: until it arrives, the child
//! window holds the frame and visibility the controller takes on.

use std::cell::{Cell, OnceCell, RefCell};
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::Once;

use gpui::{Bounds, Pixels, Window};
use raw_window_handle::{HasWindowHandle, RawWindowHandle};
pub use std::rc::Rc as Retained;
use webview2_com::Microsoft::Web::WebView2::Win32::{
    COREWEBVIEW2_COLOR, COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC, COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL, COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_ALL, CreateCoreWebView2EnvironmentWithOptions,
    GetAvailableCoreWebView2BrowserVersionString, ICoreWebView2, ICoreWebView2_22, ICoreWebView2Controller, ICoreWebView2Controller2, ICoreWebView2Environment, ICoreWebView2EnvironmentOptions,
    ICoreWebView2ExecuteScriptCompletedHandler, ICoreWebView2Settings3, ICoreWebView2WebResourceRequestedEventArgs,
};
use webview2_com::{AddScriptToExecuteOnDocumentCreatedCompletedHandler, CreateCoreWebView2ControllerCompletedHandler, CreateCoreWebView2EnvironmentCompletedHandler, NewWindowRequestedEventHandler, WebMessageReceivedEventHandler, WebResourceRequestedEventHandler, take_pwstr};
use windows::Win32::Foundation::{E_POINTER, HWND, LPARAM, LRESULT, RECT, WPARAM};
use windows::Win32::Graphics::Gdi::{CombineRgn, CreateRectRgn, DeleteObject, RGN_DIFF, RGN_OR, SetWindowRgn};
use windows::Win32::System::LibraryLoader::GetModuleHandleW;
use windows::Win32::UI::Input::KeyboardAndMouse::{GetFocus, SetFocus};
use windows::Win32::UI::Shell::SHCreateMemStream;
use windows::Win32::UI::WindowsAndMessaging::{
    CreateWindowExW, DefWindowProcW, DestroyWindow, IsChild, IsWindowVisible, RegisterClassW, SW_HIDE, SW_SHOWNA, SWP_NOACTIVATE, SWP_NOZORDER, SetParent, SetWindowPos, ShowWindow, WINDOW_EX_STYLE, WNDCLASSW, WS_CHILD,
    WS_CLIPCHILDREN, WS_CLIPSIBLINGS,
};
use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};

use super::{BRIDGE_SCRIPT, HOST_SITE, MESSAGE_HANDLER, RESOURCE_AUTHORITY, Resources, Response, Webview, https_url_parts, is_subdomain};

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

thread_local! {
    static SUPPORTED: OnceCell<bool> = const { OnceCell::new() };
}

/// WebView2 calls back on the thread that made it, GPUI's main thread, which unit tests do not run on; the runtime
/// ships with Windows 10 and 11 but can be missing on an older or stripped install.
pub fn supported() -> bool {
    SUPPORTED.with(|supported| *supported.get_or_init(|| std::thread::current().name() == Some("main") && runtime_installed()))
}

fn runtime_installed() -> bool {
    let mut version = PWSTR::null();
    // SAFETY: the loader writes a CoTaskMem string or nothing; `take_pwstr` frees it.
    let found = unsafe { GetAvailableCoreWebView2BrowserVersionString(PCWSTR::null(), &mut version) }.is_ok() && !version.is_null();
    if !version.is_null() {
        take_pwstr(version);
    }
    found
}

/// The child window a WebView2 controller fills, and the controller once WebView2 made it.
pub struct Host {
    hwnd: HWND,
    controller: RefCell<Option<ICoreWebView2Controller>>,
    webview: RefCell<Option<ICoreWebView2>>,
    /// The frame last set, in the parent's physical pixels.
    frame: Cell<Option<RECT>>,
    /// The webview was dropped: a controller arriving later is closed at once.
    closed: Cell<bool>,
}

impl Host {
    fn move_to(&self, frame: RECT) {
        if self.frame.get() == Some(frame) {
            return;
        }
        self.frame.set(Some(frame));
        // SAFETY: the child window is this host's, alive until the webview drops.
        let _ = unsafe { SetWindowPos(self.hwnd, None, frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, SWP_NOACTIVATE | SWP_NOZORDER) };
        if let Some(controller) = &*self.controller.borrow() {
            fit(controller, frame);
        }
    }

    fn set_visible(&self, visible: bool) {
        // SAFETY: as in `move_to`.
        unsafe {
            if IsWindowVisible(self.hwnd).as_bool() == visible {
                return;
            }
            let _ = ShowWindow(self.hwnd, if visible { SW_SHOWNA } else { SW_HIDE });
        }
        if let Some(controller) = &*self.controller.borrow() {
            // SAFETY: a controller of this host, on its thread.
            let _ = unsafe { controller.SetIsVisible(visible) };
        }
    }
}

/// The controller over all of its host, whose origin `frame` is.
fn fit(controller: &ICoreWebView2Controller, frame: RECT) {
    // SAFETY: a live controller on its thread.
    unsafe {
        let _ = controller.SetBounds(RECT { left: 0, top: 0, right: frame.right - frame.left, bottom: frame.bottom - frame.top });
        let _ = controller.NotifyParentWindowPositionChanged();
    }
}

pub(super) struct Native {
    host: Rc<Host>,
    /// GPUI's window, which gets the keyboard back.
    parent: HWND,
}

impl Native {
    pub(super) fn new(window: &Window, resources: Rc<Resources>, url: String) -> Self {
        let parent = gpui_hwnd(window);
        let host = Rc::new(Host { hwnd: child_window(parent), controller: RefCell::default(), webview: RefCell::default(), frame: Cell::default(), closed: Cell::default() });
        create(host.clone(), resources, url);
        Native { host, parent }
    }

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

    pub(super) fn hide(&self) {
        self.release_keyboard();
        self.host.set_visible(false);
    }

    /// Gives the WebView2 the keyboard, as a click into it does.
    pub(super) fn take_keyboard(&self) {
        if self.has_keyboard() {
            return;
        }
        if let Some(controller) = &*self.host.controller.borrow() {
            // SAFETY: a live controller on its thread.
            let _ = unsafe { controller.MoveFocus(COREWEBVIEW2_MOVE_FOCUS_REASON_PROGRAMMATIC) };
        }
    }

    /// Gives the keyboard back to GPUI's window.
    pub(super) fn release_keyboard(&self) {
        if self.has_keyboard() {
            // SAFETY: GPUI's window, alive while its webviews are.
            let _ = unsafe { SetFocus(Some(self.parent)) };
        }
    }

    /// Whether the host window or a window inside it, WebView2's, has the keyboard.
    pub(super) fn has_keyboard(&self) -> bool {
        // SAFETY: plain window queries.
        unsafe {
            let focused = GetFocus();
            !focused.is_invalid() && (focused == self.host.hwnd || IsChild(self.host.hwnd, focused).as_bool())
        }
    }

    /// WebView2's DevTools window.
    pub(super) fn open_inspector(&self) {
        if let Some(webview) = &*self.host.webview.borrow() {
            // SAFETY: a live webview on its thread.
            let _ = unsafe { webview.OpenDevToolsWindow() };
        }
    }

    /// Runs `script` in the host page; before WebView2 made the webview there is no page to run it in, as on macOS
    /// before the host page loaded.
    pub(super) fn evaluate(&self, script: &str) {
        if let Some(webview) = &*self.host.webview.borrow() {
            // SAFETY: a live webview on its thread.
            let _ = unsafe { webview.ExecuteScript(&HSTRING::from(script), None::<&ICoreWebView2ExecuteScriptCompletedHandler>) };
        }
    }
}

impl Drop for Native {
    fn drop(&mut self) {
        self.release_keyboard();
        self.host.closed.set(true);
        self.host.webview.take();
        if let Some(controller) = self.host.controller.take() {
            // SAFETY: the controller is this webview's; Close releases its handlers and browser process share.
            let _ = unsafe { controller.Close() };
        }
        // SAFETY: the host window is this webview's; a clip view holding it gave it back on `remove`.
        let _ = unsafe { DestroyWindow(self.host.hwnd) };
    }
}

/// Makes the environment, then the controller in `host`, then loads `url` once the bridge script is in place.
fn create(host: Rc<Host>, resources: Rc<Resources>, url: String) {
    let folder = data_folder();
    let created = CreateCoreWebView2EnvironmentCompletedHandler::create(Box::new(move |result, environment| {
        result?;
        let environment = environment.ok_or_else(|| windows::core::Error::from(E_POINTER))?;
        if host.closed.get() {
            return Ok(());
        }
        let hwnd = host.hwnd;
        let controller_environment = environment.clone();
        let made = CreateCoreWebView2ControllerCompletedHandler::create(Box::new(move |result, controller| {
            result?;
            let controller = controller.ok_or_else(|| windows::core::Error::from(E_POINTER))?;
            attach(&host, &controller_environment, controller, resources, url).inspect_err(|error| eprintln!("[webview] WebView2: {error}"))
        }));
        // SAFETY: the host window is alive: `closed` is not set.
        unsafe { environment.CreateCoreWebView2Controller(hwnd, &made) }.inspect_err(|error| eprintln!("[webview] WebView2: {error}"))
    }));
    // SAFETY: the completion handler runs on this thread from GPUI's message loop.
    if let Err(error) = unsafe { CreateCoreWebView2EnvironmentWithOptions(PCWSTR::null(), &folder, None::<&ICoreWebView2EnvironmentOptions>, &created) } {
        eprintln!("[webview] WebView2: {error}");
    }
}

/// WebView2's profile, beside the app's other per-machine data: `%LOCALAPPDATA%\<nameShort>\WebView2`. Without
/// LOCALAPPDATA the empty folder is WebView2's own default, beside the executable.
fn data_folder() -> HSTRING {
    match std::env::var_os("LOCALAPPDATA") {
        Some(local) => HSTRING::from(PathBuf::from(local).join(crate::product::name_short()).join("WebView2").as_os_str()),
        None => HSTRING::new(),
    }
}

fn attach(host: &Host, environment: &ICoreWebView2Environment, controller: ICoreWebView2Controller, resources: Rc<Resources>, url: String) -> windows::core::Result<()> {
    // SAFETY: WebView2 calls on GPUI's main thread, the thread of every object here.
    unsafe {
        if host.closed.get() {
            return controller.Close();
        }
        // The page background shows until the host page paints, as the transparent iframe does upstream.
        controller.cast::<ICoreWebView2Controller2>()?.SetDefaultBackgroundColor(COREWEBVIEW2_COLOR { A: 0, R: 0, G: 0, B: 0 })?;
        let webview = controller.CoreWebView2()?;
        let settings = webview.Settings()?;
        settings.SetIsStatusBarEnabled(false)?;
        // Chromium's own keys (Ctrl+F, Ctrl+P, F5) stay off, as in Electron's webview; editing keys still work.
        settings.cast::<ICoreWebView2Settings3>()?.SetAreBrowserAcceleratorKeysEnabled(false)?;

        // A filter's `*` matches any text, `/` included: the handler checks the host itself.
        for filter in [format!("https://*.{HOST_SITE}/*"), format!("https://*.{RESOURCE_AUTHORITY}/*")] {
            // The resources load in the host page's content iframe, which only source kinds (ICoreWebView2_22) reach.
            match webview.cast::<ICoreWebView2_22>() {
                Ok(webview) => webview.AddWebResourceRequestedFilterWithRequestSourceKinds(&HSTRING::from(filter), COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL, COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_ALL)?,
                Err(_) => webview.AddWebResourceRequestedFilter(&HSTRING::from(filter), COREWEBVIEW2_WEB_RESOURCE_CONTEXT_ALL)?,
            }
        }
        let mut token = 0;
        let requested_environment = environment.clone();
        let requested_resources = resources.clone();
        webview.add_WebResourceRequested(
            &WebResourceRequestedEventHandler::create(Box::new(move |_, args| match args {
                Some(args) => answer(&requested_environment, &requested_resources, args),
                None => Ok(()),
            })),
            &mut token,
        )?;
        webview.add_WebMessageReceived(
            &WebMessageReceivedEventHandler::create(Box::new(move |_, args| {
                let Some(args) = args else { return Ok(()) };
                let mut source = PWSTR::null();
                args.Source(&mut source)?;
                // Only the host page talks to the workbench, not a site the top frame navigated to.
                if !https_url_parts(&take_pwstr(source)).is_some_and(|(host, ..)| is_subdomain(&host, HOST_SITE)) {
                    return Ok(());
                }
                let mut text = PWSTR::null();
                if args.TryGetWebMessageAsString(&mut text).is_err() {
                    return Ok(());
                }
                resources.receive(&take_pwstr(text));
                Ok(())
            })),
            &mut token,
        )?;

        // `window.open` gets no window, as WKWebView and WebKitGTK give none without a delegate; links go through the
        // host page's `did-click-link`.
        webview.add_NewWindowRequested(
            &NewWindowRequestedEventHandler::create(Box::new(|_, args| match args {
                Some(args) => args.SetHandled(true),
                None => Ok(()),
            })),
            &mut token,
        )?;

        let loading = webview.clone();
        let added = AddScriptToExecuteOnDocumentCreatedCompletedHandler::create(Box::new(move |result, _| {
            result?;
            loading.Navigate(&HSTRING::from(url))
        }));
        webview.AddScriptToExecuteOnDocumentCreated(&HSTRING::from(bridge_script()), &added)?;

        if let Some(frame) = host.frame.get() {
            fit(&controller, frame);
        }
        controller.SetIsVisible(IsWindowVisible(host.hwnd).as_bool())?;
        *host.webview.borrow_mut() = Some(webview);
        *host.controller.borrow_mut() = Some(controller);
    }
    Ok(())
}

/// BRIDGE_SCRIPT and FIND_SCRIPT post through WebKit's message handler; WebView2 runs document-created scripts in
/// every frame, and only the top one, the host page, gets `chrome.webview`.
fn bridge_script() -> String {
    format!("if (window === window.top) {{ window.webkit = {{ messageHandlers: {{ {MESSAGE_HANDLER}: {{ postMessage: message => window.chrome.webview.postMessage(message) }} }} }}; {BRIDGE_SCRIPT} }}")
}

/// `Resources::serve` for the filtered hosts; a deferral holds the request until its answer.
unsafe fn answer(environment: &ICoreWebView2Environment, resources: &Resources, args: ICoreWebView2WebResourceRequestedEventArgs) -> windows::core::Result<()> {
    // SAFETY: the event's objects on WebView2's thread.
    unsafe {
        let request = args.Request()?;
        let mut uri = PWSTR::null();
        request.Uri(&mut uri)?;
        let Some((host, path, query)) = https_url_parts(&take_pwstr(uri)) else { return Ok(()) };
        // Another host the filter's `*` matched gets no response and goes to the network.
        if !is_subdomain(&host, HOST_SITE) && !is_subdomain(&host, RESOURCE_AUTHORITY) {
            return Ok(());
        }
        let mut range = PWSTR::null();
        let range = request.Headers()?.GetHeader(w!("Range"), &mut range).ok().map(|()| take_pwstr(range));
        let deferral = args.GetDeferral()?;
        let environment = environment.clone();
        resources.serve(&host, &path, &query, range, move |response| {
            let _ = respond(&environment, &args, response);
            let _ = deferral.Complete();
        });
        Ok(())
    }
}

/// A response without a reason phrase, as service-worker.js's `new Response(body, { status, headers })`.
fn respond(environment: &ICoreWebView2Environment, args: &ICoreWebView2WebResourceRequestedEventArgs, (status, headers, body): Response) -> windows::core::Result<()> {
    let headers: String = headers.iter().map(|(key, value)| format!("{key}: {value}\r\n")).collect();
    // SAFETY: the event's objects on WebView2's thread; the stream copies `body`.
    unsafe {
        let stream = SHCreateMemStream(Some(&body));
        let response = environment.CreateWebResourceResponse(stream.as_ref(), status.into(), w!(""), &HSTRING::from(headers))?;
        args.SetResponse(&response)
    }
}

/// Shows `view` over `bounds`, in GPUI window coordinates.
pub fn place(view: &View, window: &Window, bounds: Bounds<Pixels>) {
    view.move_to(physical(window, bounds));
    view.set_visible(true);
}

/// The notebook's back layer webview (backLayerWebView.ts) lies behind the cells upstream; here it floats over GPUI's
/// layer, so a clip window holds it: it shows the webview inside the notebook list only, and over its outputs and
/// markdown previews only, where presses reach it; GPUI's cells show and take presses everywhere else. One window
/// region does both, where Linux has an input shape beside the drawn one.
pub struct ClipView {
    hwnd: HWND,
    /// GPUI's window, which gets the webview's host back on `remove`.
    parent: HWND,
    host: Rc<Host>,
    /// The region last set: the hit rects and the hole, in clip coordinates.
    shape: RefCell<Option<(Vec<RECT>, Option<RECT>)>>,
}

impl ClipView {
    pub fn hide(&self) {
        // SAFETY: the clip window is this clip view's.
        let _ = unsafe { ShowWindow(self.hwnd, SW_HIDE) };
    }

    pub fn remove(&self) {
        // SAFETY: the host and clip windows are alive; the host goes back to GPUI's window so destroying the clip
        // leaves it to its webview's drop.
        unsafe {
            self.host.set_visible(false);
            let _ = SetParent(self.host.hwnd, Some(self.parent));
            let _ = DestroyWindow(self.hwnd);
        }
    }

    /// A hidden clip window over `window` holding `webview`.
    pub fn new(window: &Window, webview: &Webview) -> Retained<Self> {
        let parent = gpui_hwnd(window);
        let hwnd = child_window(parent);
        let host = &webview.native.host;
        // SAFETY: both windows are alive and of this thread.
        let _ = unsafe { SetParent(host.hwnd, Some(hwnd)) };
        host.frame.set(None);
        host.set_visible(true);
        Rc::new(ClipView { hwnd, parent, host: host.clone(), shape: RefCell::default() })
    }

    /// 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: &View, window: &Window, bounds: Bounds<Pixels>, webview_frame: Bounds<Pixels>, hit_rects: Vec<Bounds<Pixels>>, hole: Option<Bounds<Pixels>>) {
        let frame = physical(window, bounds);
        // SAFETY: the clip window is this clip view's.
        unsafe {
            let _ = SetWindowPos(self.hwnd, None, frame.left, frame.top, frame.right - frame.left, frame.bottom - frame.top, SWP_NOACTIVATE | SWP_NOZORDER);
            let _ = ShowWindow(self.hwnd, SW_SHOWNA);
        }
        webview.move_to(physical(window, webview_frame));
        let rects: Vec<RECT> = hit_rects.into_iter().map(|rect| physical(window, rect)).collect();
        let hole = hole.map(|hole| physical(window, hole));
        if self.shape.borrow().as_ref() != Some(&(rects.clone(), hole)) {
            self.set_region(&rects, hole);
            *self.shape.borrow_mut() = Some((rects, hole));
        }
    }

    fn set_region(&self, rects: &[RECT], hole: Option<RECT>) {
        // SAFETY: GDI regions this function owns until SetWindowRgn takes the combined one.
        unsafe {
            let region = CreateRectRgn(0, 0, 0, 0);
            let combine = |rect: &RECT, mode| {
                let part = CreateRectRgn(rect.left, rect.top, rect.right, rect.bottom);
                CombineRgn(Some(region), Some(region), Some(part), mode);
                let _ = DeleteObject(part.into());
            };
            for rect in rects {
                combine(rect, RGN_OR);
            }
            if let Some(hole) = hole {
                combine(&hole, RGN_DIFF);
            }
            SetWindowRgn(self.hwnd, Some(region), true);
        }
    }
}

/// `bounds` in GPUI's logical pixels as the physical pixels Win32 places child windows in.
fn physical(window: &Window, bounds: Bounds<Pixels>) -> RECT {
    let scale = window.scale_factor();
    let value = |pixels: Pixels| (f32::from(pixels) * scale).round() as i32;
    let (left, top) = (value(bounds.origin.x), value(bounds.origin.y));
    RECT { left, top, right: left + value(bounds.size.width).max(1), bottom: top + value(bounds.size.height).max(1) }
}

/// A hidden child window of `parent`.
fn child_window(parent: HWND) -> HWND {
    static REGISTER: Once = Once::new();
    let class = w!("VSRustiumWebviewHost");
    // SAFETY: this module's window class with DefWindowProcW; GPUI's window is alive.
    unsafe {
        let instance = GetModuleHandleW(None).expect("the executable's module").into();
        REGISTER.call_once(|| {
            RegisterClassW(&WNDCLASSW { lpfnWndProc: Some(window_proc), hInstance: instance, lpszClassName: class, ..Default::default() });
        });
        CreateWindowExW(WINDOW_EX_STYLE::default(), class, PCWSTR::null(), WS_CHILD | WS_CLIPCHILDREN | WS_CLIPSIBLINGS, 0, 0, 0, 0, Some(parent), None, Some(instance), None).expect("a child window")
    }
}

unsafe extern "system" fn window_proc(hwnd: HWND, message: u32, wparam: WPARAM, lparam: LPARAM) -> LRESULT {
    // SAFETY: the arguments Windows passed this window procedure.
    unsafe { DefWindowProcW(hwnd, message, wparam, lparam) }
}

fn gpui_hwnd(window: &Window) -> HWND {
    let handle = HasWindowHandle::window_handle(window).expect("an open window has a handle");
    let RawWindowHandle::Win32(handle) = handle.as_raw() else { unreachable!("GPUI on Windows has Win32 handles") };
    HWND(handle.hwnd.get() as *mut std::ffi::c_void)
}