Visual Studio Code, rebuilt in Rust
Rust
refactor(webview): share the webview and its resource serving across backends
rokartur647352ec5c39
diff --git a/native/crates/app/src/webview.rs b/native/crates/app/src/webview.rsindex 7ff4a0ce811..23b19069709 100644--- a/native/crates/app/src/webview.rs+++ b/native/crates/app/src/webview.rs@@ -1,9 +1,13 @@//! platform/webview: the host page (src/vs/workbench/contrib/webview/browser/pre/index.html) and what the workbench//! answers it, shared by the native views: a WKWebView on macOS (`macos.rs`), a WebKitGTK view on Linux (`linux.rs`), a-//! WebView2 on Windows (`windows.rs`).+//! WebView2 on Windows (`windows.rs`). Each `Native` creates, places and focuses its view and hands requests and+//! messages to `Resources`; everything else is here.-use std::path::{Path, PathBuf};+use std::cell::RefCell;+use std::path::{Component, Path, PathBuf};+use std::rc::Rc;+use futures::channel::mpsc::UnboundedSender;use serde_json::{Value, json};use sha2::{Digest, Sha256};@@ -14,13 +18,19 @@ mod linux;#[cfg(target_os = "macos")]mod macos;#[cfg(target_os = "linux")]-pub use linux::{ClipView, Retained, Webview, gpui_x_window, pump_gtk, place, supported};+use linux::Native;+#[cfg(target_os = "linux")]+pub use linux::{ClipView, Retained, View, gpui_x_window, pump_gtk, place, supported};+#[cfg(target_os = "macos")]+use macos::Native;#[cfg(target_os = "macos")]-pub use macos::{ClipView, Retained, Webview, place, supported};+pub use macos::{ClipView, Retained, View, place, supported};#[cfg(target_os = "windows")]mod windows;#[cfg(target_os = "windows")]-pub use windows::{ClipView, Retained, Webview, place, supported};+use windows::Native;+#[cfg(target_os = "windows")]+pub use windows::{ClipView, Retained, View, place, supported};/// common/webview.ts `webviewRootResourceAuthority`.const RESOURCE_AUTHORITY: &str = "vscode-resource.vscode-cdn.net";@@ -65,6 +75,166 @@ impl std::fmt::Debug for ResourceRead {}}+pub struct Webview {+ native: Native,+ resources: Rc<Resources>,+ /// Messages for the host page before it posted `webview-ready`, sent in order once it has.+ pending: Option<Vec<String>>,+}++impl Webview {+ /// A hidden webview over `window` loading the host page; `origin` is the webview's `this.origin`, the salt of its host name.+ pub fn new(window: &gpui::Window, id: &str, origin: &str, extension_id: &str, pre_dir: PathBuf, roots: Vec<files::Resource>, events: UnboundedSender<WebviewEvent>) -> Self {+ let resources = Rc::new(Resources { id: id.to_string(), pre_dir, roots: RefCell::new(roots), events });+ let native = Native::new(window, resources.clone(), host_page_url(id, origin, extension_id));+ Webview { native, resources, pending: Some(Vec::new()) }+ }++ /// `webviewElement.ts` `_send`: posts `{ channel, args }` on the host page's port.+ pub fn send(&mut self, channel: &str, data: Value) {+ let script = format!("globalThis.__vscodeWebviewHost.post({}, {})", json!(channel), data);+ match &mut self.pending {+ Some(pending) => pending.push(script),+ None => self.native.evaluate(&script),+ }+ }++ /// The host page posted `webview-ready`: messages queued before go out now.+ pub fn did_become_ready(&mut self) {+ for script in self.pending.take().unwrap_or_default() {+ self.native.evaluate(&script);+ }+ }++ pub fn set_local_resource_roots(&self, roots: Vec<files::Resource>) {+ *self.resources.roots.borrow_mut() = roots;+ }++ /// The native view, for `place` from a paint callback.+ pub fn view(&self) -> View {+ self.native.view()+ }++ pub fn hide(&self) {+ self.native.hide();+ }++ /// `webviewElement.ts` `focus`: the view takes the keyboard and the host page focuses its content frame.+ pub fn focus(&mut self) {+ self.native.take_keyboard();+ self.send("focus", Value::Null);+ }++ /// `webviewElement.ts` `cut`, `copy`, `paste`. WebView2's Chromium runs the host page's `execCommand` as Electron's+ /// does; WebKit's needs clipboard access that every page in the webview would get, so it runs its own command.+ pub fn clipboard_command(&mut self, command: &str) {+ self.native.take_keyboard();+ #[cfg(target_os = "windows")]+ self.send("execCommand", json!(command));+ #[cfg(not(target_os = "windows"))]+ self.native.clipboard_command(command);+ }++ /// Gives the view the keyboard, as a click into it does.+ pub fn take_keyboard(&self) {+ self.native.take_keyboard();+ }++ /// Gives the keyboard back to GPUI's window.+ pub fn release_keyboard(&self) {+ self.native.release_keyboard();+ }++ pub fn has_keyboard(&self) -> bool {+ self.native.has_keyboard()+ }++ /// webviewFindWidget.ts `reveal`: the find widget over the host page's top right, its input focused. `styles` is+ /// `theme_data`; `icons` the arrow-up, arrow-down and close codicons as SVG markup.+ pub fn show_find(&self, styles: &Value, icons: [String; 3]) {+ self.native.take_keyboard();+ self.native.evaluate(&format!("({FIND_SCRIPT})({styles}, {}).show()", json!(icons)));+ }++ pub fn hide_find(&self) {+ self.native.evaluate("globalThis.__vscodeFind?.hide()");+ }++ /// `WebviewFindWidget.find`: the next or previous match of the widget's text.+ pub fn find(&self, previous: bool) {+ self.native.evaluate(&format!("globalThis.__vscodeFind?.find({previous})"));+ }++ /// The engine's own developer tools, as the Electron webview's.+ pub fn open_inspector(&self) {+ self.native.open_inspector();+ }+}++type Response = (u16, Vec<(&'static str, String)>, Vec<u8>);++/// What one webview's request and message handlers answer with.+struct Resources {+ id: String,+ /// src/vs/workbench/contrib/webview/browser/pre, the host page's files.+ pre_dir: PathBuf,+ roots: RefCell<Vec<files::Resource>>,+ /// Where host page messages go, and resources of extension file system providers are asked for.+ events: UnboundedSender<WebviewEvent>,+}++impl Resources {+ /// A `{ channel, data }` text the bridge script posted to the native message handler.+ fn receive(&self, text: &str) {+ if let Some(event) = host_message(&self.id, text) {+ let _ = self.events.unbounded_send(event);+ }+ }++ /// What the service worker answers upstream for an `https` request: the host page's files, and resources as+ /// webviewElement.ts `loadResource` with resourceLoading.ts `loadLocalResource` read them, a `file` one here,+ /// another scheme's through the workbench's file service, where extension file system providers answer. `respond`+ /// gets the answer now or once the file service read it; `false` for another host, which goes to the network.+ fn serve(&self, host: &str, path: &str, query: &str, range: Option<String>, respond: impl FnOnce(Response) + 'static) -> bool {+ if is_subdomain(host, HOST_SITE) {+ let name = path.trim_start_matches('/');+ // `join` puts a drive (`C:/`) or UNC path in place of pre_dir: only plain names stay inside it.+ let inside = Path::new(name).components().all(|component| matches!(component, Component::Normal(_)));+ let file = self.pre_dir.join(name);+ respond(match inside.then(|| std::fs::read(&file)) {+ Some(Ok(bytes)) => (200, vec![("Content-Type", mime_type(&file).to_string())], bytes),+ _ => (404, Vec::new(), Vec::new()),+ });+ return true;+ }+ if !is_subdomain(host, RESOURCE_AUTHORITY) {+ return false;+ }+ let Some(resource) = resource_uri(host, path, query) else {+ respond((404, Vec::new(), Vec::new()));+ return true;+ };+ if !is_contained(&resource, &self.roots.borrow()) {+ respond((401, Vec::new(), Vec::new()));+ return true;+ }+ if resource.scheme == "file" {+ let bytes = std::fs::read(crate::uri::fs_path(&resource.scheme, &resource.authority, &resource.path)).ok();+ respond(resource_response(&resource.path, bytes, range.as_deref()));+ return true;+ }+ let path = resource.path.clone();+ let respond = Box::new(move |bytes: Option<Vec<u8>>| respond(resource_response(&path, bytes, range.as_deref())));+ let read = ResourceRead { resource, respond };+ let _ = self.events.unbounded_send(WebviewEvent { id: self.id.clone(), channel: "load-resource".into(), data: Value::Null, read: Some(read) });+ true+ }+}++fn is_subdomain(host: &str, site: &str) -> bool {+ host.strip_suffix(site).is_some_and(|rest| rest.ends_with('.'))+}+/// base/browser/iframe.ts `parentOriginHash`: SHA-256 of `{"parentOrigin":…,"salt":…}` in base 32, 52 digits.pub fn parent_origin_hash(parent_origin: &str, salt: &str) -> String {let data = json!({ "parentOrigin": parent_origin, "salt": salt }).to_string();@@ -644,6 +814,44 @@ mod tests {assert!(!is_contained_on(&resource("file", "", "//host/share/a.png"), &roots, true));}+ #[test]+ fn serves_only_files_inside_pre_dir_and_the_roots() {+ let dir = std::env::temp_dir().join(format!("vsrustium-webview-serve-{}", std::process::id()));+ let (pre_dir, root, outside) = (dir.join("pre"), dir.join("root"), dir.join("outside"));+ for folder in [&pre_dir, &root, &outside] {+ std::fs::create_dir_all(folder).unwrap();+ }+ std::fs::write(pre_dir.join("index.html"), "host").unwrap();+ std::fs::write(pre_dir.join("a..b.js"), "dots").unwrap();+ std::fs::write(root.join("a.png"), "inside").unwrap();+ std::fs::write(outside.join("secret"), "secret").unwrap();+ #[cfg(unix)]+ std::os::unix::fs::symlink(outside.join("secret"), root.join("link")).unwrap();+ let (events, _receiver) = futures::channel::mpsc::unbounded();+ let resources = Resources { id: "1".into(), pre_dir, roots: RefCell::new(file_roots(std::slice::from_ref(&root))), events };+ let status = |host: &str, path: &str| {+ let answer = Rc::new(RefCell::new(None));+ let sink = answer.clone();+ let served = resources.serve(host, path, "", None, move |(status, _, body): Response| *sink.borrow_mut() = Some((status, String::from_utf8(body).unwrap())));+ served.then(|| answer.take().expect("a synchronous answer"))+ };+ let host = format!("x.{HOST_SITE}");+ assert_eq!(status(&host, "/index.html"), Some((200, "host".into())));+ assert_eq!(status(&host, "/a..b.js"), Some((200, "dots".into())), "a name with dots is no parent component");+ // NSURL, the proxy and `https_url_parts` percent-decode first, so `%2e%2e%2f` arrives as `../`.+ assert_eq!(status(&host, "/../outside/secret").map(|(status, _)| status), Some(404));+ assert_eq!(status(&host, &format!("/{}", outside.join("secret").display())).map(|(status, _)| status), Some(404));+ let resource_host = format!("file+.{RESOURCE_AUTHORITY}");+ let root_path = root.to_string_lossy().replace('\\', "/");+ assert_eq!(status(&resource_host, &format!("/{}/a.png", root_path.trim_start_matches('/'))), Some((200, "inside".into())));+ assert_eq!(status(&resource_host, &format!("/{}/../outside/secret", root_path.trim_start_matches('/'))).map(|(status, _)| status), Some(401));+ assert_eq!(status(&resource_host, &format!("/{}", outside.join("secret").to_string_lossy().replace('\\', "/").trim_start_matches('/'))).map(|(status, _)| status), Some(401));+ #[cfg(unix)]+ assert_eq!(status(&resource_host, &format!("/{}/link", root_path.trim_start_matches('/'))).map(|(status, _)| status), Some(401), "a link out of the root resolves outside it");+ assert_eq!(status("example.com", "/a"), None, "another host goes to the network");+ std::fs::remove_dir_all(&dir).unwrap();+ }+#[test]fn splits_https_urls_as_nsurl_does() {let parts = |url: &str| https_url_parts(url).map(|(host, path, query)| [host, path, query]);diff --git a/native/crates/app/src/webview/linux.rs b/native/crates/app/src/webview/linux.rsindex 1861aa9c9e6..69b1768b02f 100644--- a/native/crates/app/src/webview/linux.rs+++ b/native/crates/app/src/webview/linux.rs@@ -9,14 +9,13 @@ use std::cell::{OnceCell, RefCell};use std::collections::HashSet;use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};use std::os::unix::fs::MetadataExt;-use std::path::PathBuf;use std::pin::Pin;use std::rc::Rc;use std::sync::OnceLock;use std::time::Duration;use async_openssl::SslStream;-use futures::channel::{mpsc::UnboundedSender, oneshot};+use futures::channel::oneshot;use futures::io::{AsyncBufRead, AsyncBufReadExt, AsyncWriteExt, BufReader};use gpui::{App, Bounds, Pixels, Window};use gtk::glib::translate::{FromGlibPtrFull, ToGlibPtr};@@ -26,7 +25,6 @@ use openssl::pkey::PKey;use openssl::ssl::{Ssl, SslContext, SslMethod};use openssl::x509::X509;use raw_window_handle::{HasWindowHandle, RawWindowHandle};-use serde_json::{Value, json};pub use std::rc::Rc as Retained;use webkit2gtk::{NetworkProxyMode, NetworkProxySettings, SecurityManagerExt, SettingsExt, UserContentInjectedFrames, UserContentManager, UserContentManagerExt, UserScript, UserScriptInjectionTime, WebContext, WebContextExt, WebInspectorExt,@@ -34,7 +32,7 @@ use webkit2gtk::{};use x11::xlib;-use super::{BRIDGE_SCRIPT, FIND_SCRIPT, HOST_SITE, HTTP_LOOPBACK_ONLY_RULES, MESSAGE_HANDLER, RESOURCE_AUTHORITY, ResourceRead, WebviewEvent, host_message, host_page_url, is_contained, mime_type, resource_response, resource_uri};+use super::{BRIDGE_SCRIPT, HOST_SITE, HTTP_LOOPBACK_ONLY_RULES, MESSAGE_HANDLER, RESOURCE_AUTHORITY, Resources, Response, Webview, is_subdomain};/// The native view of a webview, which `place` shows.pub type View = webkit2gtk::WebView;@@ -64,30 +62,25 @@ pub fn pump_gtk(cx: &mut App) {.detach();}-pub struct Webview {+pub(super) struct Native {view: View,/// The GTK window the view sits in until a `ClipView` takes it.window: gtk::Window,content: UserContentManager,proxy: gio::SocketService,- roots: Rc<RefCell<Vec<files::Resource>>>,/// GPUI's X window, which gets the keyboard back.parent: xlib::Window,- /// Messages for the host page before it posted `webview-ready`, sent in order once it has.- pending: Option<Vec<String>>,}-impl Webview {- /// A hidden webview over `window` loading the host page; `origin` is the webview's `this.origin`, the salt of its host name.- pub fn new(window: &Window, id: &str, origin: &str, extension_id: &str, pre_dir: PathBuf, roots: Vec<files::Resource>, events: UnboundedSender<WebviewEvent>) -> Self {- let roots = Rc::new(RefCell::new(roots));+impl Native {+ pub(super) fn new(window: &Window, resources: Rc<Resources>, url: String) -> Self {let context = WebContext::new_ephemeral();let (certificate, tls) = proxy_certificate();let proxy = gio::SocketService::new();let address = gio::InetSocketAddress::new(&gio::InetAddress::new_loopback(gio::SocketFamily::Ipv4), 0);let address = proxy.add_address(&address, gio::SocketType::Stream, gio::SocketProtocol::Tcp, None::<&glib::Object>).expect("a loopback port");let port = address.downcast::<gio::InetSocketAddress>().expect("an inet address").port();- let state = Rc::new(ProxyState { id: id.to_string(), pre_dir, roots: roots.clone(), events: events.clone(), context: context.clone(), certificate, tls, trusted_hosts: RefCell::default(), port });+ let state = Rc::new(ProxyState { resources: resources.clone(), context: context.clone(), certificate, tls, trusted_hosts: RefCell::default(), port });proxy.connect_incoming(move |_, connection, _| {glib::MainContext::default().spawn_local(serve(connection.clone(), state.clone()));false@@ -101,12 +94,9 @@ impl Webview {let content = UserContentManager::new();content.register_script_message_handler(MESSAGE_HANDLER);- let id_for_messages = id.to_string();content.connect_script_message_received(Some(MESSAGE_HANDLER), move |_, result| {let Some(text) = result.js_value().map(|value| value.to_string()) else { return };- if let Some(event) = host_message(&id_for_messages, &text) {- let _ = events.unbounded_send(event);- }+ resources.receive(&text);});content.add_script(&UserScript::new(BRIDGE_SCRIPT, UserContentInjectedFrames::TopFrame, UserScriptInjectionTime::Start, &[], &[]));@@ -120,36 +110,15 @@ impl Webview {let parent = gpui_x_window(window);let gtk_window = embedded_window(parent);gtk_window.add(&view);- load_with_http_rules(&view, &content, host_page_url(id, origin, extension_id));- Webview { view, window: gtk_window, content, proxy, roots, parent, pending: Some(Vec::new()) }- }-- /// `webviewElement.ts` `_send`: posts `{ channel, args }` on the host page's port.- pub fn send(&mut self, channel: &str, data: Value) {- let script = format!("globalThis.__vscodeWebviewHost.post({}, {})", json!(channel), data);- match &mut self.pending {- Some(pending) => pending.push(script),- None => self.evaluate(&script),- }+ load_with_http_rules(&view, &content, url);+ Native { view, window: gtk_window, content, proxy, parent }}- /// The host page posted `webview-ready`: messages queued before go out now.- pub fn did_become_ready(&mut self) {- for script in self.pending.take().unwrap_or_default() {- self.evaluate(&script);- }- }-- pub fn set_local_resource_roots(&self, roots: Vec<files::Resource>) {- *self.roots.borrow_mut() = roots;- }-- /// The native view, for `place` from a paint callback.- pub fn view(&self) -> View {+ pub(super) fn view(&self) -> View {self.view.clone()}- pub fn hide(&self) {+ pub(super) fn hide(&self) {if !self.view.is_visible() {return;}@@ -158,16 +127,8 @@ impl Webview {self.window.hide();}- /// `webviewElement.ts` `focus`: the view takes the keyboard and the host page focuses its content frame.- pub fn focus(&mut self) {- self.take_keyboard();- self.send("focus", Value::Null);- }-- /// `webviewElement.ts` `cut`, `copy`, `paste`: WebKitGTK's editing commands in the page, as Ctrl+C runs them, for- /// the reason macos.rs gives.- pub fn clipboard_command(&mut self, command: &str) {- self.take_keyboard();+ /// WebKitGTK's editing commands in the page, as Ctrl+C runs them, for the reason macos.rs gives.+ pub(super) fn clipboard_command(&self, command: &str) {self.view.execute_editing_command(match command {"cut" => "Cut","copy" => "Copy",@@ -176,21 +137,21 @@ impl Webview {}/// Gives the view's X window the keyboard, as a click into it does.- pub fn take_keyboard(&self) {+ pub(super) fn take_keyboard(&self) {if !self.has_keyboard() {focus_x_window(&self.view);}}/// Gives the keyboard back to GPUI's X window.- pub fn release_keyboard(&self) {+ pub(super) fn release_keyboard(&self) {if self.has_keyboard() {set_input_focus(self.parent);}}/// Whether the X window holding the view has the keyboard.- pub fn has_keyboard(&self) -> bool {+ pub(super) fn has_keyboard(&self) -> bool {let Some(holder) = x_window_of(&self.view) else { return false };let (mut focused, mut revert) = (0, 0);// SAFETY: GTK's open X display; the out pointers are locals.@@ -198,24 +159,8 @@ impl Webview {focused == holder}- /// webviewFindWidget.ts `reveal`: the find widget over the host page's top right, its input focused. `styles` is- /// `theme_data`; `icons` the arrow-up, arrow-down and close codicons as SVG markup.- pub fn show_find(&self, styles: &Value, icons: [String; 3]) {- self.take_keyboard();- self.evaluate(&format!("({FIND_SCRIPT})({styles}, {}).show()", json!(icons)));- }-- pub fn hide_find(&self) {- self.evaluate("globalThis.__vscodeFind?.hide()");- }-- /// `WebviewFindWidget.find`: the next or previous match of the widget's text.- pub fn find(&self, previous: bool) {- self.evaluate(&format!("globalThis.__vscodeFind?.find({previous})"));- }-- /// The Web Inspector of the view, as the Electron webview's dev tools.- pub fn open_inspector(&self) {+ /// The Web Inspector of the view.+ pub(super) fn open_inspector(&self) {if let Some(settings) = WebViewExt::settings(&self.view) {settings.set_enable_developer_extras(true);}@@ -224,7 +169,7 @@ impl Webview {}}- fn evaluate(&self, script: &str) {+ pub(super) fn evaluate(&self, script: &str) {self.view.evaluate_javascript(script, None, None, None::<&gio::Cancellable>, |_| {});}}@@ -254,7 +199,7 @@ fn load_with_http_rules(view: &webkit2gtk::WebView, content: &UserContentManager}}-impl Drop for Webview {+impl Drop for Native {fn drop(&mut self) {self.content.unregister_script_message_handler(MESSAGE_HANDLER);self.release_keyboard();@@ -301,9 +246,10 @@ impl ClipView {let clip = embedded_window(gpui_x_window(window));let fixed = gtk::Fixed::new();clip.add(&fixed);- webview.window.remove(&webview.view);- fixed.put(&webview.view, 0, 0);- webview.view.show();+ let native = &webview.native;+ native.window.remove(&native.view);+ fixed.put(&native.view, 0, 0);+ native.view.show();fixed.show();Rc::new(ClipView { window: clip, fixed, shape: RefCell::default() })}@@ -429,12 +375,7 @@ fn proxy_certificate() -> (gio::TlsCertificate, SslContext) {}struct ProxyState {- id: String,- /// src/vs/workbench/contrib/webview/browser/pre, the host page's files.- pre_dir: PathBuf,- roots: Rc<RefCell<Vec<files::Resource>>>,- /// Where resources of extension file system providers are asked for.- events: UnboundedSender<WebviewEvent>,+ resources: Rc<Resources>,context: WebContext,certificate: gio::TlsCertificate,tls: SslContext,@@ -458,8 +399,7 @@ async fn serve(connection: gio::SocketConnection, state: Rc<ProxyState>) {let Some(target) = head.line.strip_prefix("CONNECT ").and_then(|rest| rest.split(' ').next()).map(str::to_string) else { return };let host = target.rsplit_once(':').map_or(target.as_str(), |(host, _)| host).to_ascii_lowercase();let output = connection.output_stream();- let is_subdomain = |site: &str| host.strip_suffix(site).is_some_and(|rest| rest.ends_with('.'));- if !is_subdomain(HOST_SITE) && !is_subdomain(RESOURCE_AUTHORITY) {+ if !is_subdomain(&host, HOST_SITE) && !is_subdomain(&host, RESOURCE_AUTHORITY) {let Ok(upstream) = gio::SocketClient::new().connect_to_host_future(&target, 443).await else {let _ = output.write_all_future(b"HTTP/1.1 502 Bad Gateway\r\n\r\n", glib::Priority::DEFAULT).await;return;@@ -529,39 +469,17 @@ async fn read_line(reader: &mut (impl AsyncBufRead + Unpin)) -> Option<String> {}}-/// What the service worker answers upstream: the host page's files, and resources as webviewElement.ts `loadResource`-/// with resourceLoading.ts `loadLocalResource` read them, a `file` one here, another scheme's through the workbench's-/// file service, where extension file system providers answer.-async fn answer(state: &ProxyState, host: &str, head: &Head) -> (u16, Vec<(&'static str, String)>, Vec<u8>) {+/// `Resources::serve` for a GET on a host the proxy terminates.+async fn answer(state: &ProxyState, host: &str, head: &Head) -> Response {let mut parts = head.line.split(' ');let (Some("GET"), Some(target)) = (parts.next(), parts.next()) else { return (405, Vec::new(), Vec::new()) };let (path, query) = target.split_once('?').unwrap_or((target, ""));- let path = crate::uri::percent_decode(path);- if host.ends_with(HOST_SITE) {- let name = path.trim_start_matches('/');- let file = state.pre_dir.join(name);- return match (name.contains(".."), std::fs::read(&file)) {- (false, Ok(bytes)) => (200, vec![("Content-Type", mime_type(&file).to_string())], bytes),- _ => (404, Vec::new(), Vec::new()),- };- }- let Some(resource) = resource_uri(host, &path, &crate::uri::percent_decode(query)) else { return (404, Vec::new(), Vec::new()) };- if !is_contained(&resource, &state.roots.borrow()) {- return (401, Vec::new(), Vec::new());- }- let range = head.range.as_deref();- if resource.scheme == "file" {- let bytes = std::fs::read(&resource.path).ok();- return resource_response(&resource.path, bytes, range);- }- let path = resource.path.clone();let (sender, receiver) = oneshot::channel();- let respond = Box::new(move |bytes: Option<Vec<u8>>| {- let _ = sender.send(bytes);+ state.resources.serve(host, &crate::uri::percent_decode(path), &crate::uri::percent_decode(query), head.range.clone(), move |response| {+ let _ = sender.send(response);});- let read = ResourceRead { resource, respond };- let _ = state.events.unbounded_send(WebviewEvent { id: state.id.clone(), channel: "load-resource".into(), data: Value::Null, read: Some(read) });- resource_response(&path, receiver.await.ok().flatten(), range)+ // The workbench dropped the read without an answer.+ receiver.await.unwrap_or((404, Vec::new(), Vec::new()))}fn reason(status: u16) -> &'static str {diff --git a/native/crates/app/src/webview/macos.rs b/native/crates/app/src/webview/macos.rsindex a24df85c5c9..9364ab9d391 100644--- a/native/crates/app/src/webview/macos.rs+++ b/native/crates/app/src/webview/macos.rs@@ -6,12 +6,10 @@use std::cell::RefCell;use std::collections::HashMap;-use std::path::PathBuf;use std::rc::Rc;use std::sync::OnceLock;use block2::RcBlock;-use futures::channel::mpsc::UnboundedSender;use gpui::{Bounds, Pixels, Window};pub use objc2::rc::Retained;use objc2::runtime::{AnyClass, Bool, Imp, NSObject, NSObjectProtocol, ProtocolObject, Sel};@@ -20,15 +18,14 @@ 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 serde_json::{Value, json};-use super::{BRIDGE_SCRIPT, FIND_SCRIPT, HOST_SITE, HTTP_LOOPBACK_ONLY_RULES, MESSAGE_HANDLER, RESOURCE_AUTHORITY, ResourceRead, WebviewEvent, host_message, host_page_url, is_contained, mime_type, resource_response, resource_uri};+use super::{BRIDGE_SCRIPT, HTTP_LOOPBACK_ONLY_RULES, MESSAGE_HANDLER, Resources, Response, Webview};-pub struct Webview {- view: Retained<WKWebView>,- roots: Rc<RefCell<Vec<files::Resource>>>,- /// Messages for the host page before it posted `webview-ready`, sent in order once it has.- pending: Option<Vec<String>>,+/// 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.@@ -36,14 +33,12 @@ pub fn supported() -> bool {MainThreadMarker::new().is_some()}-impl Webview {- /// A hidden webview over `window` loading the host page; `origin` is the webview's `this.origin`, the salt of its host name.- pub fn new(window: &Window, id: &str, origin: &str, extension_id: &str, pre_dir: PathBuf, roots: Vec<files::Resource>, events: UnboundedSender<WebviewEvent>) -> Self {+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();- let roots = Rc::new(RefCell::new(roots));let configuration = unsafe { WKWebViewConfiguration::new(mtm) };- let handler = SchemeHandler::new(mtm, SchemeState { id: id.to_string(), pre_dir, roots: roots.clone(), events: events.clone(), tasks: RefCell::default(), session: OnceLock::new() });+ let handler = SchemeHandler::new(mtm, SchemeState { resources: resources.clone(), tasks: RefCell::default(), session: OnceLock::new() });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 {@@ -51,7 +46,7 @@ impl Webview {let _: () = msg_send![pool, _registerURLSchemeAsSecure: &*NSString::from_str("http")];}let content = unsafe { configuration.userContentController() };- let bridge = MessageHandler::new(mtm, MessageState { id: id.to_string(), events });+ let bridge = MessageHandler::new(mtm, resources);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);@@ -68,7 +63,7 @@ impl Webview {view.setHidden(true);gpui_view(window).addSubview(&view);- let url = objc2_foundation::NSURL::URLWithString(&NSString::from_str(&host_page_url(id, origin, extension_id))).expect("host page URL");+ 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| {@@ -82,35 +77,14 @@ impl Webview {let store = unsafe { WKContentRuleListStore::defaultStore(mtm) }.expect("a default content rule list store");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.- Webview { view, roots, pending: Some(Vec::new()) }- }-- /// `webviewElement.ts` `_send`: posts `{ channel, args }` on the host page's port.- pub fn send(&mut self, channel: &str, data: Value) {- let script = format!("globalThis.__vscodeWebviewHost.post({}, {})", json!(channel), data);- match &mut self.pending {- Some(pending) => pending.push(script),- None => self.evaluate(&script),- }- }-- /// The host page posted `webview-ready`: messages queued before go out now.- pub fn did_become_ready(&mut self) {- for script in self.pending.take().unwrap_or_default() {- self.evaluate(&script);- }- }-- pub fn set_local_resource_roots(&self, roots: Vec<files::Resource>) {- *self.roots.borrow_mut() = roots;+ Native { view }}- /// The native view, for `place` from a paint callback.- pub fn view(&self) -> Retained<WKWebView> {+ pub(super) fn view(&self) -> View {self.view.clone()}- pub fn hide(&self) {+ pub(super) fn hide(&self) {if self.view.isHidden() {return;}@@ -118,17 +92,8 @@ impl Webview {self.view.setHidden(true);}- /// `webviewElement.ts` `focus`: the view takes the keyboard and the host page focuses its content frame.- pub fn focus(&mut self) {- self.take_keyboard();- self.send("focus", Value::Null);- }-- /// `webviewElement.ts` `cut`, `copy`, `paste`: WebKit's own editing commands in the page, as Cmd+C runs them.- /// The host page's `execCommand` needs `javaScriptCanAccessClipboard` and `DOMPasteAllowed` in WebKit, which would- /// let every page in the webview, a Simple Browser site too, read the clipboard.- pub fn clipboard_command(&mut self, command: &str) {- self.take_keyboard();+ /// 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 {@@ -141,14 +106,14 @@ impl Webview {}/// Makes the view the first responder, as a click into it does.- pub fn take_keyboard(&self) {+ 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 fn release_keyboard(&self) {+ 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>() {@@ -161,7 +126,7 @@ impl Webview {}/// Whether the view or one of its subviews is the window's first responder.- pub fn has_keyboard(&self) -> bool {+ pub(super) fn has_keyboard(&self) -> bool {self.view.window().is_some_and(|window| self.is_first_responder(&window))}@@ -172,24 +137,8 @@ impl Webview {view.isDescendantOf(&self.view)}- /// webviewFindWidget.ts `reveal`: the find widget over the host page's top right, its input focused. `styles` is- /// `theme_data`; `icons` the arrow-up, arrow-down and close codicons as SVG markup.- pub fn show_find(&self, styles: &Value, icons: [String; 3]) {- self.take_keyboard();- self.evaluate(&format!("({FIND_SCRIPT})({styles}, {}).show()", json!(icons)));- }-- pub fn hide_find(&self) {- self.evaluate("globalThis.__vscodeFind?.hide()");- }-- /// `WebviewFindWidget.find`: the next or previous match of the widget's text.- pub fn find(&self, previous: bool) {- self.evaluate(&format!("globalThis.__vscodeFind?.find({previous})"));- }-- /// The Web Inspector of the view, as the Electron webview's dev tools; WebKit has no public call to open it.- pub fn open_inspector(&self) {+ /// 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 {@@ -202,12 +151,12 @@ impl Webview {}}- fn evaluate(&self, script: &str) {+ pub(super) fn evaluate(&self, script: &str) {unsafe { self.view.evaluateJavaScript_completionHandler(&NSString::from_str(script), None) };}}-impl Drop for Webview {+impl Drop for Native {fn drop(&mut self) {let content = unsafe { self.view.configuration().userContentController() };unsafe { content.removeScriptMessageHandlerForName(&NSString::from_str(MESSAGE_HANDLER)) };@@ -283,9 +232,9 @@ impl ClipView {let this: Retained<Self> = unsafe { msg_send![super(this), initWithFrame: NSRect::ZERO] };this.setClipsToBounds(true);this.setHidden(true);- webview.view.removeFromSuperview();- this.addSubview(&webview.view);- webview.view.setHidden(false);+ webview.native.view.removeFromSuperview();+ this.addSubview(&webview.native.view);+ webview.native.view.setHidden(false);gpui_view(window).addSubview(&this);this}@@ -369,16 +318,11 @@ fn gpui_view(window: &Window) -> Retained<NSView> {view.retain()}-struct MessageState {- id: String,- events: UnboundedSender<WebviewEvent>,-}-define_class!(#[unsafe(super(NSObject))]#[thread_kind = MainThreadOnly]#[name = "CodeGpuiWebviewMessageHandler"]- #[ivars = MessageState]+ #[ivars = Rc<Resources>]struct MessageHandler;unsafe impl NSObjectProtocol for MessageHandler {}@@ -388,28 +332,20 @@ define_class!(fn did_receive(&self, _controller: &WKUserContentController, message: &WKScriptMessage) {let body = unsafe { message.body() };let Ok(text) = body.downcast::<NSString>() else { return };- let state = self.ivars();- if let Some(event) = host_message(&state.id, &text.to_string()) {- let _ = state.events.unbounded_send(event);- }+ self.ivars().receive(&text.to_string());}});impl MessageHandler {- fn new(mtm: MainThreadMarker, state: MessageState) -> Retained<Self> {- let this = Self::alloc(mtm).set_ivars(state);+ fn new(mtm: MainThreadMarker, resources: Rc<Resources>) -> Retained<Self> {+ let this = Self::alloc(mtm).set_ivars(resources);unsafe { msg_send![super(this), init] }}}struct SchemeState {- id: String,- /// src/vs/workbench/contrib/webview/browser/pre, the host page's files.- pre_dir: PathBuf,- roots: Rc<RefCell<Vec<files::Resource>>>,- /// Where resources of extension file system providers are asked for.- events: UnboundedSender<WebviewEvent>,+ 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>>,@@ -445,57 +381,30 @@ impl SchemeHandler {fn start(&self, task: &ProtocolObject<dyn WKURLSchemeTask>) {let request = unsafe { task.request() };- let Some(url) = request.URL() else { return respond(task, 404, &[], Vec::new()) };+ 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();- if host.ends_with(HOST_SITE) {- let name = path.trim_start_matches('/');- let file = state.pre_dir.join(name);- return match (name.contains(".."), std::fs::read(&file)) {- (false, Ok(bytes)) => respond(task, 200, &[("Content-Type", mime_type(&file))], bytes),- _ => respond(task, 404, &[], Vec::new()),- };- }- if host.ends_with(RESOURCE_AUTHORITY) {- let range = request.valueForHTTPHeaderField(&NSString::from_str("Range")).map(|range| range.to_string());- let query = url.query().map(|query| crate::uri::percent_decode(&query.to_string())).unwrap_or_default();- return self.load_resource(task, &host, &path, &query, range);- }- self.fetch(task);- }-- /// webviewElement.ts `loadResource` with resourceLoading.ts `loadLocalResource`: a `file` resource is read here,- /// another scheme's through the workbench's file service, where extension file system providers answer.- fn load_resource(&self, task: &ProtocolObject<dyn WKURLSchemeTask>, host: &str, path: &str, query: &str, range: Option<String>) {- let state = self.ivars();- let Some(resource) = resource_uri(host, path, query) else { return respond(task, 404, &[], Vec::new()) };- if !is_contained(&resource, &state.roots.borrow()) {- return respond(task, 401, &[], Vec::new());- }- if resource.scheme == "file" {- return respond_with_resource(task, &resource.path, std::fs::read(&resource.path).ok(), range.as_deref());- }let key = task as *const _ as usize;state.tasks.borrow_mut().insert(key, task.retain());let this = self.retain();- let path = resource.path.clone();- let respond = Box::new(move |bytes: Option<Vec<u8>>| {+ let answer = move |response: Response| {let Some(task) = this.ivars().tasks.borrow_mut().remove(&key) else { return };- respond_with_resource(&task, &path, bytes, range.as_deref());- });- let read = ResourceRead { resource, respond };- let _ = state.events.unbounded_send(WebviewEvent { id: state.id.clone(), channel: "load-resource".into(), data: Value::Null, read: Some(read) });+ 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>) {+ fn fetch(&self, task: &ProtocolObject<dyn WKURLSchemeTask>, key: usize) {let state = self.ivars();let session = state.session.get_or_init(|| unsafe {NSURLSession::sessionWithConfiguration_delegate_delegateQueue(&NSURLSessionConfiguration::defaultSessionConfiguration(), None, Some(&NSOperationQueue::mainQueue()))});- let key = task as *const _ as usize;- state.tasks.borrow_mut().insert(key, task.retain());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 };@@ -510,7 +419,7 @@ impl SchemeHandler {task.didFinish();}(_, Some(error)) => task.didFailWithError(error),- (None, None) => respond(&task, 502, &[], Vec::new()),+ (None, None) => respond(&task, (502, Vec::new(), Vec::new())),}}});@@ -520,20 +429,14 @@ impl SchemeHandler {}}-fn respond_with_resource(task: &ProtocolObject<dyn WKURLSchemeTask>, path: &str, bytes: Option<Vec<u8>>, range: Option<&str>) {- let (status, headers, body) = resource_response(path, bytes, range);- let headers: Vec<(&str, &str)> = headers.iter().map(|(key, value)| (*key, value.as_str())).collect();- respond(task, status as isize, &headers, body);-}--fn respond(task: &ProtocolObject<dyn WKURLSchemeTask>, status: isize, headers: &[(&str, &str)], body: Vec<u8>) {+fn respond(task: &ProtocolObject<dyn WKURLSchemeTask>, (status, headers, body): Response) {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, Some(&NSString::from_str("HTTP/1.1")), Some(&fields)).expect("an HTTP response");+ 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");unsafe {task.didReceiveResponse(&response);task.didReceiveData(&NSData::from_vec(body));diff --git a/native/crates/app/src/webview/windows.rs b/native/crates/app/src/webview/windows.rsindex 59e6bf97636..4bf1d20b34a 100644--- a/native/crates/app/src/webview/windows.rs+++ b/native/crates/app/src/webview/windows.rs@@ -6,14 +6,12 @@//! window holds the frame and visibility the controller takes on.use std::cell::{Cell, OnceCell, RefCell};-use std::path::{Component, Path, PathBuf};+use std::path::PathBuf;use std::rc::Rc;use std::sync::Once;-use futures::channel::mpsc::UnboundedSender;use gpui::{Bounds, Pixels, Window};use raw_window_handle::{HasWindowHandle, RawWindowHandle};-use serde_json::{Value, json};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,@@ -32,7 +30,7 @@ use windows::Win32::UI::WindowsAndMessaging::{};use windows::core::{HSTRING, Interface, PCWSTR, PWSTR, w};-use super::{BRIDGE_SCRIPT, FIND_SCRIPT, HOST_SITE, MESSAGE_HANDLER, RESOURCE_AUTHORITY, ResourceRead, WebviewEvent, host_message, host_page_url, https_url_parts, is_contained, mime_type, resource_response, resource_uri};+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>;@@ -105,81 +103,31 @@ fn fit(controller: &ICoreWebView2Controller, frame: RECT) {}}-pub struct Webview {+pub(super) struct Native {host: Rc<Host>,- roots: Rc<RefCell<Vec<files::Resource>>>,/// GPUI's window, which gets the keyboard back.parent: HWND,- /// Messages for the host page before it posted `webview-ready`, sent in order once it has.- pending: Option<Vec<String>>,}-/// What the resource and message handlers of one webview answer with.-struct Resources {- id: String,- /// src/vs/workbench/contrib/webview/browser/pre, the host page's files.- pre_dir: PathBuf,- roots: Rc<RefCell<Vec<files::Resource>>>,- /// Where host page messages go, and resources of extension file system providers are asked for.- events: UnboundedSender<WebviewEvent>,-}--impl Webview {- /// A hidden webview over `window` loading the host page; `origin` is the webview's `this.origin`, the salt of its host name.- pub fn new(window: &Window, id: &str, origin: &str, extension_id: &str, pre_dir: PathBuf, roots: Vec<files::Resource>, events: UnboundedSender<WebviewEvent>) -> Self {+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() });- let roots = Rc::new(RefCell::new(roots));- let resources = Rc::new(Resources { id: id.to_string(), pre_dir, roots: roots.clone(), events });- create(host.clone(), resources, host_page_url(id, origin, extension_id));- Webview { host, roots, parent, pending: Some(Vec::new()) }- }-- /// `webviewElement.ts` `_send`: posts `{ channel, args }` on the host page's port.- pub fn send(&mut self, channel: &str, data: Value) {- let script = format!("globalThis.__vscodeWebviewHost.post({}, {})", json!(channel), data);- match &mut self.pending {- Some(pending) => pending.push(script),- None => self.evaluate(&script),- }- }-- /// The host page posted `webview-ready`: messages queued before go out now.- pub fn did_become_ready(&mut self) {- for script in self.pending.take().unwrap_or_default() {- self.evaluate(&script);- }- }-- pub fn set_local_resource_roots(&self, roots: Vec<files::Resource>) {- *self.roots.borrow_mut() = roots;+ create(host.clone(), resources, url);+ Native { host, parent }}- /// The native view, for `place` from a paint callback.- pub fn view(&self) -> View {+ pub(super) fn view(&self) -> View {self.host.clone()}- pub fn hide(&self) {+ pub(super) fn hide(&self) {self.release_keyboard();self.host.set_visible(false);}- /// `webviewElement.ts` `focus`: the view takes the keyboard and the host page focuses its content frame.- pub fn focus(&mut self) {- self.take_keyboard();- self.send("focus", Value::Null);- }-- /// `webviewElement.ts` `cut`, `copy`, `paste`: the host page's `execCommand` in its content frame, as upstream; the- /// Chromium of WebView2 runs it as Electron's does.- pub fn clipboard_command(&mut self, command: &str) {- self.take_keyboard();- self.send("execCommand", json!(command));- }-/// Gives the WebView2 the keyboard, as a click into it does.- pub fn take_keyboard(&self) {+ pub(super) fn take_keyboard(&self) {if self.has_keyboard() {return;}@@ -190,7 +138,7 @@ impl Webview {}/// Gives the keyboard back to GPUI's window.- pub fn release_keyboard(&self) {+ 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)) };@@ -198,7 +146,7 @@ impl Webview {}/// Whether the host window or a window inside it, WebView2's, has the keyboard.- pub fn has_keyboard(&self) -> bool {+ pub(super) fn has_keyboard(&self) -> bool {// SAFETY: plain window queries.unsafe {let focused = GetFocus();@@ -206,24 +154,8 @@ impl Webview {}}- /// webviewFindWidget.ts `reveal`: the find widget over the host page's top right, its input focused. `styles` is- /// `theme_data`; `icons` the arrow-up, arrow-down and close codicons as SVG markup.- pub fn show_find(&self, styles: &Value, icons: [String; 3]) {- self.take_keyboard();- self.evaluate(&format!("({FIND_SCRIPT})({styles}, {}).show()", json!(icons)));- }-- pub fn hide_find(&self) {- self.evaluate("globalThis.__vscodeFind?.hide()");- }-- /// `WebviewFindWidget.find`: the next or previous match of the widget's text.- pub fn find(&self, previous: bool) {- self.evaluate(&format!("globalThis.__vscodeFind?.find({previous})"));- }-- /// WebView2's DevTools window, as the Electron webview's dev tools.- pub fn open_inspector(&self) {+ /// 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() };@@ -232,7 +164,7 @@ impl Webview {/// 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.- fn evaluate(&self, script: &str) {+ 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>) };@@ -240,7 +172,7 @@ impl Webview {}}-impl Drop for Webview {+impl Drop for Native {fn drop(&mut self) {self.release_keyboard();self.host.closed.set(true);@@ -333,9 +265,7 @@ fn attach(host: &Host, environment: &ICoreWebView2Environment, controller: ICoreif args.TryGetWebMessageAsString(&mut text).is_err() {return Ok(());}- if let Some(event) = host_message(&resources.id, &take_pwstr(text)) {- let _ = resources.events.unbounded_send(event);- }+ resources.receive(&take_pwstr(text));Ok(())})),&mut token,@@ -374,9 +304,7 @@ fn bridge_script() -> String {format!("if (window === window.top) {{ window.webkit = {{ messageHandlers: {{ {MESSAGE_HANDLER}: {{ postMessage: message => window.chrome.webview.postMessage(message) }} }} }}; {BRIDGE_SCRIPT} }}")}-/// What the service worker answers upstream: the host page's files, and resources as webviewElement.ts `loadResource`-/// with resourceLoading.ts `loadLocalResource` read them, a `file` one here, another scheme's through the workbench's-/// file service, where extension file system providers answer. Other hosts get no response and go to the network.+/// `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 {@@ -384,47 +312,24 @@ unsafe fn answer(environment: &ICoreWebView2Environment, resources: &Resources,let mut uri = PWSTR::null();request.Uri(&mut uri)?;let Some((host, path, query)) = https_url_parts(&take_pwstr(uri)) else { return Ok(()) };- if is_subdomain(&host, HOST_SITE) {- let name = path.trim_start_matches('/');- // `join` puts a drive (`C:/`) or UNC (`%5C%5Chost%5Cshare`) path in place of pre_dir: no read outside it.- let inside = Path::new(name).components().all(|component| matches!(component, Component::Normal(_)));- let file = resources.pre_dir.join(name);- let response = match inside.then(|| std::fs::read(&file)) {- Some(Ok(bytes)) => (200, vec![("Content-Type", mime_type(&file).to_string())], bytes),- _ => (404, Vec::new(), Vec::new()),- };- return respond(environment, &args, response);- }- if !is_subdomain(&host, RESOURCE_AUTHORITY) {+ // 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 Some(resource) = resource_uri(&host, &path, &query) else { return respond(environment, &args, (404, Vec::new(), Vec::new())) };- if !is_contained(&resource, &resources.roots.borrow()) {- return respond(environment, &args, (401, Vec::new(), Vec::new()));- }let mut range = PWSTR::null();let range = request.Headers()?.GetHeader(w!("Range"), &mut range).ok().map(|()| take_pwstr(range));- if resource.scheme == "file" {- return respond(environment, &args, resource_response(&resource.path, std::fs::read(crate::uri::fs_path(&resource.scheme, &resource.authority, &resource.path)).ok(), range.as_deref()));- }let deferral = args.GetDeferral()?;- let (environment, path) = (environment.clone(), resource.path.clone());- let done = Box::new(move |bytes: Option<Vec<u8>>| {- let _ = respond(&environment, &args, resource_response(&path, bytes, range.as_deref()));+ let environment = environment.clone();+ resources.serve(&host, &path, &query, range, move |response| {+ let _ = respond(&environment, &args, response);let _ = deferral.Complete();});- let read = ResourceRead { resource, respond: done };- let _ = resources.events.unbounded_send(WebviewEvent { id: resources.id.clone(), channel: "load-resource".into(), data: Value::Null, read: Some(read) });Ok(())}}-fn is_subdomain(host: &str, site: &str) -> bool {- host.strip_suffix(site).is_some_and(|rest| rest.ends_with('.'))-}-/// 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): (u16, Vec<(&'static str, String)>, Vec<u8>)) -> windows::core::Result<()> {+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 {@@ -473,11 +378,12 @@ impl ClipView {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(webview.host.hwnd, Some(hwnd)) };- webview.host.frame.set(None);- webview.host.set_visible(true);- Rc::new(ClipView { hwnd, parent, host: webview.host.clone(), shape: RefCell::default() })+ 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'sdiff --git a/port/notes.md b/port/notes.mdindex 3f98fc9561c..4d3c9e60391 100644--- a/port/notes.md+++ b/port/notes.md@@ -1019,6 +1019,7 @@ What to do (milestone 21, in order):- Cross build: the Studio has the `x86_64-pc-windows-msvc` and `aarch64-pc-windows-msvc` Rust targets, cargo-xwin (it downloads the MSVC CRT and Windows SDK headers on first use) and Homebrew `llvm` and `lld` (clang-cl, lld-link). It checks that the Windows build compiles; tests that need Windows run on the `windows.yml` runners.- Dialogs: file dialogs (`file_dialog/windows.rs`) follow Electron 43's file_dialog_win.cc (`ApplySettings`, `ConvertFilters`, the open and save `FOS_` options), message boxes (`dialog/windows.rs`) its message_box_win.cc with `noLink`, so custom buttons, not command links. Both use the `windows` crate at GPUI's version (0.61) for the COM interfaces. Difference: Electron runs both on its dialog thread (`dialog_thread::Run`); here they run on GPUI's main thread in the dialog's modal loop, as GPUI's own path prompts do, and the GPUI windows keep painting through it. TaskDialogIndirect needs Common Controls 6, which GPUI's embedded manifest (`windows-manifest` feature) declares; a second `/MANIFEST:EMBED` fails the link with a duplicate resource. The pure parts (filter specs, button ids and answers, `&` mnemonics, the main instruction) are host tests in file_dialog.rs and dialog.rs.- Webview: `webview/windows.rs` is a WebView2 (webview2-com 0.38, the last on `windows` 0.61) in a child window of GPUI's HWND, loading the same host page as macOS and Linux. A WebResourceRequested filter on `https://*.vscode-webview.vscode-cdn.net/*` and `https://*.vscode-resource.vscode-cdn.net/*` (with `COREWEBVIEW2_WEB_RESOURCE_REQUEST_SOURCE_KINDS_ALL` where `ICoreWebView2_22` exists, so the content iframe's loads reach it) answers what the service worker answers upstream; `file` resources are read in place, the rest through the workbench with a deferral. A `file` resource's path is the URI path (`/c:/proj/a.png`), which matches no root and reads nothing until the drive-letter row (app/src/editor_history.rs:59) gives one conversion to a disk path. The bridge script runs in the top frame only, with `window.webkit.messageHandlers.vscodeWebviewHost` mapped onto `chrome.webview.postMessage`; messages from any other origin are dropped. `window.open` is handled with no window, as WebKit without a UI delegate does. No HTTP_LOOPBACK_ONLY_RULES: WebView2 is Chromium, which blocks non-loopback http in the https page as Electron does. Profile in `%LOCALAPPDATA%\<nameShort>\WebView2`. GPUI's DirectComposition target was topmost (`CreateTargetForHwnd(hwnd, true)`), drawing over every child window; `native/vendor/wu/crates/gpui_windows` vendors the crate with that one argument `false`. The notebook back layer clip is one window region (hit rects minus the hole), where Linux has an input shape beside the drawn one. URL splitting (`https_url_parts`) is a host test in webview.rs; the rest needs the windows runner.+- Webview seam: `webview.rs` holds the one `Webview` (the message queue before `webview-ready`, focus, find, the clipboard choice) and `Resources` (`serve` answers the host page and resource hosts, `receive` the bridge messages); each backend is a `Native` with creation, keyboard, inspector and `evaluate`, plus its own request hook calling `serve`: WKURLSchemeHandler on `https`, the WebResourceRequested filter, the Linux TLS proxy. A `file` resource is read at its `fsPath` on every platform, the path `is_contained` checked. Rechecked against wry 0.58.2 (Tauri's webview crate): WebView2 custom protocols cover only `https://<name>.*` hosts, WKWebView takes an `https` handler only through our `allow_https_scheme_handler` swizzle, and WebKitGTK refuses an `https` handler, so the `https://*.vscode-cdn.net` hosts the host page and its CSP need would keep all three hooks beside wry, which also pins webview2-com 0.39 and windows 0.62 against our 0.38 and 0.61. The decision "Windows webview" stands.- Named pipes: `exthost/src/pipe.rs` carries both the extension host connection (`\\.\pipe\vscode-ipc-<uuid>-sock`) and the single instance (`\\.\pipe\<sha256(user data)[..8]>-<version>-main-sock`, launch.rs), as ipc.net.ts names them. Instances are made as libuv's `uv_pipe_bind` makes them (duplex, byte mode, 64 KiB buffers, default security descriptor) plus `PIPE_REJECT_REMOTE_CLIENTS` and `FILE_FLAG_FIRST_PIPE_INSTANCE`, so a second listener fails as Node's `listen` does with EADDRINUSE. The handles are overlapped: synchronous I/O on one pipe handle is serialized by Windows, and the extension host reader thread blocks in a read while the main thread writes. Clients connect with `SECURITY_IDENTIFICATION`, so a pipe server cannot act as the client. The single instance name is fixed per user data folder in the machine-wide pipe namespace, as upstream's: another local user who creates it first receives a later start's arguments and working directory. A second instance calls `AllowSetForegroundWindow` with the pipe server's pid (`GetNamedPipeServerProcessId`) where main.ts asks the first instance for its pid over IPC. `generateUuid` and the profile ids read the OS random source (getrandom), not `/dev/urandom`.- Console: the app is a GUI-subsystem binary, as Electron's, so a start from Explorer or the Start menu opens no console window; at start it attaches to the console of the process that started it unless the output is redirected or the CLI set `ELECTRON_NO_ATTACH_CONSOLE` (electron_main_win.cc, Chromium's `RouteStdioToConsole`), so `bin\<applicationName>.cmd --help` prints in the terminal.- Proxy: `request/windows.rs` sends through curl.exe as Linux does, with the proxy picked first: the session proxy, else the IE settings, auto-detect and the PAC URL through WinHTTP's resolver where Chromium runs the script in its own V8 (same answer, other engine), then the manual proxy. The rule and bypass parsing is Chromium's (`request/proxy_rules.rs`, built on every platform for its host tests). Difference: curl takes one proxy, so a PAC list's later entries are no fallback. `WinHttpGetProxyForUrl` runs without `fAutoLogonIfChallenged` first and with it only after `ERROR_WINHTTP_LOGIN_FAILURE`, as Chromium's proxy_resolver_winhttp.cc, so the logon credentials go to a WPAD or PAC server only when it asks.