Visual Studio Code, rebuilt in Rust
Rust
feat(windows): show webviews through WebView2
rokartur79733748cce8
diff --git a/native/Cargo.lock b/native/Cargo.lockindex 4a7c8f4c45f..931c85e62fd 100644--- a/native/Cargo.lock+++ b/native/Cargo.lock@@ -271,6 +271,7 @@ dependencies = ["ttf-parser","url","webkit2gtk",+ "webview2-com","windows 0.61.3","windows-sys 0.61.2","wuff",@@ -2848,7 +2849,6 @@ dependencies = [[[package]]name = "gpui_windows"version = "0.1.0"-source = "git+https://github.com/dstrml/wu?rev=a3ced2864abd933055b0d0afc5821e6cd9b0db2a#a3ced2864abd933055b0d0afc5821e6cd9b0db2a"dependencies = ["accesskit","accesskit_windows",@@ -7368,6 +7368,42 @@ dependencies = ["system-deps",]+[[package]]+name = "webview2-com"+version = "0.38.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a"+dependencies = [+ "webview2-com-macros",+ "webview2-com-sys",+ "windows 0.61.3",+ "windows-core 0.61.2",+ "windows-implement",+ "windows-interface",+]++[[package]]+name = "webview2-com-macros"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "webview2-com-sys"+version = "0.38.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c"+dependencies = [+ "thiserror 2.0.21",+ "windows 0.61.3",+ "windows-core 0.61.2",+]+[[package]]name = "weezl"version = "0.1.12"diff --git a/native/Cargo.toml b/native/Cargo.tomlindex 0adb67b3d6c..64031f261ef 100644--- a/native/Cargo.toml+++ b/native/Cargo.toml@@ -20,6 +20,7 @@ gpui_platform = { git = "https://github.com/dstrml/wu", rev = "a3ced2864abd93305[patch."https://github.com/dstrml/wu"]gpui = { path = "vendor/wu/crates/gpui" }gpui_apple = { path = "vendor/wu/crates/gpui_apple" }+gpui_windows = { path = "vendor/wu/crates/gpui_windows" }# Dependencies (GPUI included) at opt-level 1, the port's crates at 0: settings_editor tests 21.5 s -> 4.3 s (port/notes.md "Build speed").[profile.dev.package."*"]diff --git a/native/crates/app/Cargo.toml b/native/crates/app/Cargo.tomlindex 5d8fa9a56de..64c57bb6589 100644--- a/native/crates/app/Cargo.toml+++ b/native/crates/app/Cargo.toml@@ -54,13 +54,17 @@ security-framework = "3"# GPUI's version, for the COM interfaces windows-sys lacks.windows = { version = "0.61", features = ["Win32_Foundation",+ "Win32_Graphics_Gdi","Win32_System_Com","Win32_System_LibraryLoader","Win32_UI_Controls","Win32_UI_Input_KeyboardAndMouse","Win32_UI_Shell","Win32_UI_Shell_Common",+ "Win32_UI_WindowsAndMessaging",] }+# 0.38 is the last on windows 0.61, GPUI's.+webview2-com = "0.38"windows-sys = { version = "0.61", features = ["Win32_Foundation","Win32_Security",diff --git a/native/crates/app/src/webview.rs b/native/crates/app/src/webview.rsindex ee41e4383f6..3deee8ba9fd 100644--- a/native/crates/app/src/webview.rs+++ b/native/crates/app/src/webview.rs@@ -1,5 +1,6 @@//! 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`).+//! 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`).use std::path::{Component, Path, PathBuf};@@ -30,7 +31,8 @@ const PARENT_ORIGIN: &str = "vscode-file://vscode-app";const MESSAGE_HANDLER: &str = "vscodeWebviewHost";/// WebKit blocks every http load in the https host page, loopback included, where Chromium lets loopback through (the/// Simple Browser's dev servers). With `http` registered secure, these content rules block the rest: http stays loopback-/// only. A rule ends at `(:port)?/` so `http://localhost:[email protected]/` (a user name) does not match.+/// only. A rule ends at `(:port)?/` so `http://localhost:[email protected]/` (a user name) does not match. WebView2 is Chromium.+#[cfg(not(target_os = "windows"))]const HTTP_LOOPBACK_ONLY_RULES: &str = r#"[{ "trigger": { "url-filter": "^http:" }, "action": { "type": "block" } },{ "trigger": { "url-filter": "^http://localhost(:[0-9]+)?/" }, "action": { "type": "ignore-previous-rules" } },@@ -94,6 +96,18 @@ fn query_escape(value: &str) -> String {out}+/// The lowercase host and the percent-decoded path and query of an `https` URL, as NSURL's `host`, `path` and `query`+/// give them to macos.rs.+#[cfg(any(target_os = "windows", test))]+fn https_url_parts(url: &str) -> Option<(String, String, String)> {+ let rest = url.strip_prefix("https://")?;+ let rest = rest.split_once('#').map_or(rest, |(rest, _)| rest);+ let (host, target) = rest.find(['/', '?']).map_or((rest, ""), |index| rest.split_at(index));+ let (path, query) = target.split_once('?').unwrap_or((target, ""));+ let path = if path.is_empty() { "/" } else { path };+ Some((host.to_ascii_lowercase(), crate::uri::percent_decode(path), crate::uri::percent_decode(query)))+}+/// The resource an `asWebviewUri` URL names, `https://{scheme}+{authority}.vscode-resource.vscode-cdn.net{path}`,/// with the authority as webview.ts `decodeAuthority` restores it.pub fn resource_uri(host: &str, decoded_path: &str, decoded_query: &str) -> Option<files::Resource> {@@ -601,6 +615,16 @@ mod tests {assert!(!is_contained(&resource("vscode-remote", "wsl+x", "/media/a.png"), &[resource("vscode-remote", "wsl+x", "/media")]));}+ #[test]+ fn splits_https_urls_as_nsurl_does() {+ let parts = |url: &str| https_url_parts(url).map(|(host, path, query)| [host, path, query]);+ assert_eq!(parts("https://File+.VSCODE-resource.vscode-cdn.net/c%3A/a%20b.png?v=%31#top"), Some(["file+.vscode-resource.vscode-cdn.net".into(), "/c:/a b.png".into(), "v=1".into()]));+ assert_eq!(parts("https://x.vscode-webview.vscode-cdn.net?id=1"), Some(["x.vscode-webview.vscode-cdn.net".into(), "/".into(), "id=1".into()]));+ // A wildcard filter matches this URL; its host is example.com.+ assert_eq!(parts("https://example.com/.vscode-resource.vscode-cdn.net/a").map(|[host, ..]| host), Some("example.com".into()));+ assert_eq!(parts("http://x.vscode-webview.vscode-cdn.net/"), None);+ }+#[test]fn answers_byte_ranges_and_mime_types() {assert_eq!(byte_range("bytes=0-", 10), Some((0, 9)));diff --git a/native/crates/app/src/webview/windows.rs b/native/crates/app/src/webview/windows.rsindex 222c7e70137..9bc4380cefd 100644--- a/native/crates/app/src/webview/windows.rs+++ b/native/crates/app/src/webview/windows.rs@@ -1,106 +1,552 @@-//! shortcut: no WebView2 yet, so `supported` is false and the views show their fallback; port/ledger.md M24 row-//! app/src/webview.rs:11 (webview2-com).+//! 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::path::PathBuf;+use std::cell::{Cell, OnceCell, RefCell};+use std::path::{Component, Path, PathBuf};+use std::rc::Rc;+use std::sync::Once;use futures::channel::mpsc::UnboundedSender;use gpui::{Bounds, Pixels, Window};-use serde_json::Value;-+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,+ 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::WebviewEvent;--pub enum View {}+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};-pub enum Webview {}+/// The native view of a webview, which `place` shows.+pub type View = Rc<Host>;-pub enum ClipView {}+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 {- false+ 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 struct Webview {+ 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 {- pub fn new(_window: &Window, _id: &str, _origin: &str, _extension_id: &str, _pre_dir: PathBuf, _roots: Vec<files::Resource>, _events: UnboundedSender<WebviewEvent>) -> Self {- unreachable!("webview::supported() is false on Windows")+ /// 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 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()) }}- pub fn send(&mut self, _channel: &str, _data: Value) {- match *self {}+ /// `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) {- match *self {}+ for script in self.pending.take().unwrap_or_default() {+ self.evaluate(&script);+ }}- pub fn set_local_resource_roots(&self, _roots: Vec<files::Resource>) {- match *self {}+ 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 {- match *self {}+ self.host.clone()}pub fn hide(&self) {- match *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) {- match *self {}+ self.take_keyboard();+ self.send("focus", Value::Null);}- pub fn clipboard_command(&mut self, _command: &str) {- match *self {}+ /// `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) {- match *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 fn release_keyboard(&self) {- match *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 fn has_keyboard(&self) -> bool {- match *self {}+ // SAFETY: plain window queries.+ unsafe {+ let focused = GetFocus();+ !focused.is_invalid() && (focused == self.host.hwnd || IsChild(self.host.hwnd, focused).as_bool())+ }}- pub fn show_find(&self, _styles: &Value, _icons: [String; 3]) {- match *self {}+ /// 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) {- match *self {}+ self.evaluate("globalThis.__vscodeFind?.hide()");}- pub fn find(&self, _previous: bool) {- match *self {}+ /// `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) {- match *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.+ 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>) };+ }}}-pub fn place(view: &View, _window: &Window, _bounds: Bounds<Pixels>) {- match *view {}+impl Drop for Webview {+ 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(());+ }+ if let Some(event) = host_message(&resources.id, &take_pwstr(text)) {+ let _ = resources.events.unbounded_send(event);+ }+ 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} }}")+}++/// 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.+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(()) };+ 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) {+ 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(&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 _ = 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<()> {+ 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) {- match *self {}+ // SAFETY: the clip window is this clip view's.+ let _ = unsafe { ShowWindow(self.hwnd, SW_HIDE) };}pub fn remove(&self) {- match *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);+ }}- pub fn new(_window: &Window, webview: &Webview) -> Retained<Self> {- match *webview {}+ /// 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);+ // 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() })}- pub fn place(&self, _webview: &View, _window: &Window, _bounds: Bounds<Pixels>, _webview_frame: Bounds<Pixels>, _hit_rects: Vec<Bounds<Pixels>>, _hole: Option<Bounds<Pixels>>) {- match *self {}+ /// 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)}diff --git a/native/vendor/wu/Cargo.toml b/native/vendor/wu/Cargo.tomlindex 925f72abbc2..90ec4862bcf 100644--- a/native/vendor/wu/Cargo.toml+++ b/native/vendor/wu/Cargo.toml@@ -2,7 +2,7 @@# vendored crates inherit from. Members are the vendored crates; every other wu crate stays the git dependency.[workspace]resolver = "2"-members = ["crates/gpui", "crates/gpui_apple"]+members = ["crates/gpui", "crates/gpui_apple", "crates/gpui_windows"][workspace.package]publish = false@@ -70,7 +70,7 @@ gpui_tokio = { git = "https://github.com/dstrml/wu", rev = "a3ced2864abd933055b0gpui_util = { git = "https://github.com/dstrml/wu", rev = "a3ced2864abd933055b0d0afc5821e6cd9b0db2a" }gpui_web = { git = "https://github.com/dstrml/wu", rev = "a3ced2864abd933055b0d0afc5821e6cd9b0db2a" }gpui_wgpu = { git = "https://github.com/dstrml/wu", rev = "a3ced2864abd933055b0d0afc5821e6cd9b0db2a" }-gpui_windows = { git = "https://github.com/dstrml/wu", rev = "a3ced2864abd933055b0d0afc5821e6cd9b0db2a", default-features = false }+gpui_windows = { path = "crates/gpui_windows", default-features = false }grammars = { git = "https://github.com/dstrml/wu", rev = "a3ced2864abd933055b0d0afc5821e6cd9b0db2a" }http_client = { git = "https://github.com/dstrml/wu", rev = "a3ced2864abd933055b0d0afc5821e6cd9b0db2a" }http_client_tls = { git = "https://github.com/dstrml/wu", rev = "a3ced2864abd933055b0d0afc5821e6cd9b0db2a" }diff --git a/native/vendor/wu/crates/gpui_windows/Cargo.toml b/native/vendor/wu/crates/gpui_windows/Cargo.tomlnew file mode 100644index 00000000000..3157f05ed20--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/Cargo.toml@@ -0,0 +1,45 @@+[package]+name = "gpui_windows"+version = "0.1.0"+edition.workspace = true+publish.workspace = true+license = "Apache-2.0"++[lints]+workspace = true++[lib]+path = "src/gpui_windows.rs"++[features]+default = ["gpui/default"]+test-support = ["gpui/test-support"]++[dependencies]+gpui.workspace = true+i18n.workspace = true++[target.'cfg(target_os = "windows")'.dependencies]+accesskit.workspace = true+accesskit_windows.workspace = true+anyhow.workspace = true+collections.workspace = true+dunce.workspace = true+etagere.workspace = true+futures.workspace = true+gpui_util.workspace = true+image.workspace = true+itertools.workspace = true+log.workspace = true+parking_lot.workspace = true+rand.workspace = true+raw-window-handle.workspace = true+smallvec.workspace = true+uuid.workspace = true+windows.workspace = true+windows-core.workspace = true+windows-numerics = "0.2"+windows-registry = "0.5"++[target.'cfg(target_os = "windows")'.build-dependencies]+windows-registry = "0.5"diff --git a/native/vendor/wu/crates/gpui_windows/LICENSE-APACHE b/native/vendor/wu/crates/gpui_windows/LICENSE-APACHEnew file mode 120000index 00000000000..1cd601d0a3a--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/LICENSE-APACHE@@ -0,0 +1 @@+../../LICENSE-APACHE\ No newline at end of filediff --git a/native/vendor/wu/crates/gpui_windows/build.rs b/native/vendor/wu/crates/gpui_windows/build.rsnew file mode 100644index 00000000000..1b364388e8e--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/build.rs@@ -0,0 +1,244 @@+#![allow(clippy::disallowed_methods, reason = "build scripts are exempt")]++fn main() {+ #[cfg(target_os = "windows")]+ {+ // Compile HLSL shaders+ #[cfg(not(debug_assertions))]+ compile_shaders();+ }+}++#[cfg(all(target_os = "windows", not(debug_assertions)))]+mod shader_compilation {+ use std::{+ fs,+ io::Write,+ path::{Path, PathBuf},+ process::{self, Command},+ };++ pub fn compile_shaders() {+ let shader_path =+ PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap()).join("src/shaders.hlsl");+ let out_dir = std::env::var("OUT_DIR").unwrap();++ println!("cargo:rerun-if-changed={}", shader_path.display());++ // Check if fxc.exe is available+ let fxc_path = find_fxc_compiler();++ // Define all modules+ let modules = [+ "backdrop_pass",+ "backdrop_composite",+ "quad",+ "shadow",+ "path_rasterization",+ "path_sprite",+ "underline",+ "monochrome_sprite",+ "subpixel_sprite",+ "polychrome_sprite",+ ];++ let rust_binding_path = format!("{}/shaders_bytes.rs", out_dir);+ if Path::new(&rust_binding_path).exists() {+ fs::remove_file(&rust_binding_path)+ .expect("Failed to remove existing Rust binding file");+ }+ for module in modules {+ compile_shader_for_module(+ module,+ &out_dir,+ &fxc_path,+ shader_path.to_str().unwrap(),+ &rust_binding_path,+ );+ }++ {+ let shader_path = PathBuf::from(std::env::var("CARGO_MANIFEST_DIR").unwrap())+ .join("src/color_text_raster.hlsl");+ compile_shader_for_module(+ "emoji_rasterization",+ &out_dir,+ &fxc_path,+ shader_path.to_str().unwrap(),+ &rust_binding_path,+ );+ }+ }++ /// Locate `binary` in the newest installed Windows SDK.+ pub fn find_latest_windows_sdk_binary(+ binary: &str,+ ) -> Result<Option<PathBuf>, Box<dyn std::error::Error>> {+ let key = windows_registry::LOCAL_MACHINE+ .open("SOFTWARE\\WOW6432Node\\Microsoft\\Microsoft SDKs\\Windows\\v10.0")?;++ let install_folder: String = key.get_string("InstallationFolder")?; // "C:\Program Files (x86)\Windows Kits\10\"+ let install_folder_bin = Path::new(&install_folder).join("bin");++ let mut versions: Vec<_> = std::fs::read_dir(&install_folder_bin)?+ .flatten()+ .filter(|entry| entry.path().is_dir())+ .filter_map(|entry| entry.file_name().into_string().ok())+ .collect();++ versions.sort_by_key(|s| {+ s.split('.')+ .filter_map(|p| p.parse().ok())+ .collect::<Vec<u32>>()+ });++ let arch = match std::env::consts::ARCH {+ "x86_64" => "x64",+ "aarch64" => "arm64",+ _ => Err(format!(+ "Unsupported architecture: {}",+ std::env::consts::ARCH+ ))?,+ };++ if let Some(highest_version) = versions.last() {+ return Ok(Some(+ install_folder_bin+ .join(highest_version)+ .join(arch)+ .join(binary),+ ));+ }++ Ok(None)+ }++ /// You can set the `GPUI_FXC_PATH` environment variable to specify the path to the fxc.exe compiler.+ fn find_fxc_compiler() -> String {+ // Check environment variable+ if let Ok(path) = std::env::var("GPUI_FXC_PATH")+ && Path::new(&path).exists()+ {+ return path;+ }++ // Try to find in PATH+ // NOTE: This has to be `where.exe` on Windows, not `where`, it must be ended with `.exe`+ if let Ok(output) = std::process::Command::new("where.exe")+ .arg("fxc.exe")+ .output()+ && output.status.success()+ {+ let path = String::from_utf8_lossy(&output.stdout);+ return path.trim().to_string();+ }++ if let Ok(Some(path)) = find_latest_windows_sdk_binary("fxc.exe") {+ return path.to_string_lossy().into_owned();+ }++ panic!("Failed to find fxc.exe");+ }++ fn compile_shader_for_module(+ module: &str,+ out_dir: &str,+ fxc_path: &str,+ shader_path: &str,+ rust_binding_path: &str,+ ) {+ // Compile vertex shader+ let output_file = format!("{}/{}_vs.h", out_dir, module);+ let const_name = format!("{}_VERTEX_BYTES", module.to_uppercase());+ compile_shader_impl(+ fxc_path,+ &format!("{module}_vertex"),+ &output_file,+ &const_name,+ shader_path,+ "vs_4_1",+ );+ generate_rust_binding(&const_name, &output_file, rust_binding_path);++ // Compile fragment shader+ let output_file = format!("{}/{}_ps.h", out_dir, module);+ let const_name = format!("{}_FRAGMENT_BYTES", module.to_uppercase());+ compile_shader_impl(+ fxc_path,+ &format!("{module}_fragment"),+ &output_file,+ &const_name,+ shader_path,+ "ps_4_1",+ );+ generate_rust_binding(&const_name, &output_file, rust_binding_path);+ }++ fn compile_shader_impl(+ fxc_path: &str,+ entry_point: &str,+ output_path: &str,+ var_name: &str,+ shader_path: &str,+ target: &str,+ ) {+ let output = Command::new(fxc_path)+ .args([+ "/T",+ target,+ "/E",+ entry_point,+ "/Fh",+ output_path,+ "/Vn",+ var_name,+ "/O3",+ shader_path,+ ])+ .output();++ match output {+ Ok(result) => {+ if result.status.success() {+ return;+ }+ println!(+ "cargo::error=Shader compilation failed for {}:\n{}",+ entry_point,+ String::from_utf8_lossy(&result.stderr)+ );+ process::exit(1);+ }+ Err(e) => {+ println!("cargo::error=Failed to run fxc for {}: {}", entry_point, e);+ process::exit(1);+ }+ }+ }++ fn generate_rust_binding(const_name: &str, head_file: &str, output_path: &str) {+ let header_content = fs::read_to_string(head_file).expect("Failed to read header file");+ let const_definition = {+ let global_var_start = header_content.find("const BYTE").unwrap();+ let global_var = &header_content[global_var_start..];+ let equal = global_var.find('=').unwrap();+ global_var[equal + 1..].trim()+ };+ let rust_binding = format!(+ "const {}: &[u8] = &{}\n",+ const_name,+ const_definition.replace('{', "[").replace('}', "]")+ );+ let mut options = fs::OpenOptions::new()+ .create(true)+ .append(true)+ .open(output_path)+ .expect("Failed to open Rust binding file");+ options+ .write_all(rust_binding.as_bytes())+ .expect("Failed to write Rust binding file");+ }+}++#[cfg(all(target_os = "windows", not(debug_assertions)))]+use shader_compilation::compile_shaders;diff --git a/native/vendor/wu/crates/gpui_windows/src/alpha_correction.hlsl b/native/vendor/wu/crates/gpui_windows/src/alpha_correction.hlslnew file mode 100644index 00000000000..5a34a4ebf28--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/alpha_correction.hlsl@@ -0,0 +1,49 @@+// Adapted from https://github.com/microsoft/terminal/blob/1283c0f5b99a2961673249fa77c6b986efb5086c/src/renderer/atlas/dwrite.hlsl+// Copyright (c) Microsoft Corporation.+// Licensed under the MIT license.++float color_brightness(float3 color) {+ // REC. 601 luminance coefficients for perceived brightness+ return dot(color, float3(0.30f, 0.59f, 0.11f));+}++float light_on_dark_contrast(float enhancedContrast, float3 color) {+ float brightness = color_brightness(color);+ float multiplier = saturate(4.0f * (0.75f - brightness));+ return enhancedContrast * multiplier;+}++float enhance_contrast(float alpha, float k) {+ return alpha * (k + 1.0f) / (alpha * k + 1.0f);+}++float3 enhance_contrast3(float3 alpha, float k) {+ return alpha * (k + 1.0f) / (alpha * k + 1.0f);+}++float apply_alpha_correction(float a, float b, float4 g) {+ float brightness_adjustment = g.x * b + g.y;+ float correction = brightness_adjustment * a + (g.z * b + g.w);+ return a + a * (1.0f - a) * correction;+}++float3 apply_alpha_correction3(float3 a, float3 b, float4 g) {+ float3 brightness_adjustment = g.x * b + g.y;+ float3 correction = brightness_adjustment * a + (g.z * b + g.w);+ return a + a * (1.0f - a) * correction;+}++float apply_contrast_and_gamma_correction(float sample, float3 color, float enhanced_contrast_factor, float4 gamma_ratios) {+ float enhanced_contrast = light_on_dark_contrast(enhanced_contrast_factor, color);+ float brightness = color_brightness(color);++ float contrasted = enhance_contrast(sample, enhanced_contrast);+ return apply_alpha_correction(contrasted, brightness, gamma_ratios);+}++float3 apply_contrast_and_gamma_correction3(float3 sample, float3 color, float enhanced_contrast_factor, float4 gamma_ratios) {+ float enhanced_contrast = light_on_dark_contrast(enhanced_contrast_factor, color);++ float3 contrasted = enhance_contrast3(sample, enhanced_contrast);+ return apply_alpha_correction3(contrasted, color, gamma_ratios);+}diff --git a/native/vendor/wu/crates/gpui_windows/src/clipboard.rs b/native/vendor/wu/crates/gpui_windows/src/clipboard.rsnew file mode 100644index 00000000000..2036b6a6592--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/clipboard.rs@@ -0,0 +1,415 @@+use std::sync::LazyLock;++use anyhow::Result;+use collections::FxHashMap;+use itertools::Itertools;+use std::os::windows::ffi::OsStrExt;+use windows::Win32::{+ Foundation::{HANDLE, HGLOBAL, POINT},+ System::{+ DataExchange::{+ CloseClipboard, CountClipboardFormats, EmptyClipboard, EnumClipboardFormats,+ GetClipboardData, GetClipboardFormatNameW, OpenClipboard, RegisterClipboardFormatW,+ SetClipboardData,+ },+ Memory::{GMEM_MOVEABLE, GlobalAlloc, GlobalLock, GlobalSize, GlobalUnlock},+ Ole::{CF_DIB, CF_HDROP, CF_UNICODETEXT},+ },+ UI::Shell::{DROPFILES, DragQueryFileW, HDROP},+};+use windows::core::{BOOL, Owned, PCWSTR};++use gpui::{+ ClipboardEntry, ClipboardItem, ClipboardString, ExternalPaths, Image, ImageFormat, hash,+};++const DRAGDROP_GET_FILES_COUNT: u32 = 0xFFFFFFFF;++static CLIPBOARD_HASH_FORMAT: LazyLock<u32> =+ LazyLock::new(|| register_clipboard_format(windows::core::w!("GPUI internal text hash")));+static CLIPBOARD_METADATA_FORMAT: LazyLock<u32> =+ LazyLock::new(|| register_clipboard_format(windows::core::w!("GPUI internal metadata")));+static CLIPBOARD_SVG_FORMAT: LazyLock<u32> =+ LazyLock::new(|| register_clipboard_format(windows::core::w!("image/svg+xml")));+static CLIPBOARD_GIF_FORMAT: LazyLock<u32> =+ LazyLock::new(|| register_clipboard_format(windows::core::w!("GIF")));+static CLIPBOARD_PNG_FORMAT: LazyLock<u32> =+ LazyLock::new(|| register_clipboard_format(windows::core::w!("PNG")));+static CLIPBOARD_JPG_FORMAT: LazyLock<u32> =+ LazyLock::new(|| register_clipboard_format(windows::core::w!("JFIF")));++static IMAGE_FORMATS_MAP: LazyLock<FxHashMap<u32, ImageFormat>> = LazyLock::new(|| {+ let mut map = FxHashMap::default();+ map.insert(*CLIPBOARD_PNG_FORMAT, ImageFormat::Png);+ map.insert(*CLIPBOARD_GIF_FORMAT, ImageFormat::Gif);+ map.insert(*CLIPBOARD_JPG_FORMAT, ImageFormat::Jpeg);+ map.insert(*CLIPBOARD_SVG_FORMAT, ImageFormat::Svg);+ map+});++fn register_clipboard_format(format: PCWSTR) -> u32 {+ let ret = unsafe { RegisterClipboardFormatW(format) };+ if ret == 0 {+ panic!(+ "Error when registering clipboard format: {}",+ std::io::Error::last_os_error()+ );+ }+ log::debug!(+ "Registered clipboard format {} as {}",+ unsafe { format.display() },+ ret+ );+ ret+}++fn get_clipboard_data(format: u32) -> Option<LockedGlobal> {+ let global = HGLOBAL(unsafe { GetClipboardData(format).ok() }?.0);+ LockedGlobal::lock(global)+}++pub(crate) fn write_to_clipboard(item: ClipboardItem) {+ let Some(_clip) = ClipboardGuard::open() else {+ return;+ };++ let result: Result<()> = (|| {+ unsafe { EmptyClipboard()? };+ for entry in item.entries() {+ match entry {+ ClipboardEntry::String(string) => write_string(string)?,+ ClipboardEntry::Image(image) => write_image(image)?,+ ClipboardEntry::ExternalPaths(paths) => write_files(paths)?,+ }+ }+ Ok(())+ })();++ if let Err(e) = result {+ log::error!("Failed to write to clipboard: {e}");+ }+}++pub(crate) fn read_from_clipboard() -> Option<ClipboardItem> {+ let _clip = ClipboardGuard::open()?;++ let mut entries = Vec::new();+ let mut have_text = false;+ let mut have_image = false;+ let mut have_files = false;++ let count = unsafe { CountClipboardFormats() };+ let mut format = 0;+ for _ in 0..count {+ format = unsafe { EnumClipboardFormats(format) };++ if !have_text && format == CF_UNICODETEXT.0 as u32 {+ if let Some(entry) = read_string() {+ entries.push(entry);+ have_text = true;+ }+ } else if !have_image && is_image_format(format) {+ if let Some(entry) = read_image(format) {+ entries.push(entry);+ have_image = true;+ }+ } else if !have_files && format == CF_HDROP.0 as u32 {+ if let Some(entry) = read_files() {+ entries.push(entry);+ have_files = true;+ }+ }+ }++ if entries.is_empty() {+ log_unsupported_clipboard_formats();+ return None;+ }+ Some(ClipboardItem { entries })+}++pub(crate) fn with_file_names<F>(hdrop: HDROP, mut f: F)+where+ F: FnMut(String),+{+ let file_count = unsafe { DragQueryFileW(hdrop, DRAGDROP_GET_FILES_COUNT, None) };+ for file_index in 0..file_count {+ let filename_length = unsafe { DragQueryFileW(hdrop, file_index, None) } as usize;+ let mut buffer = vec![0u16; filename_length + 1];+ let ret = unsafe { DragQueryFileW(hdrop, file_index, Some(buffer.as_mut_slice())) };+ if ret == 0 {+ log::error!("unable to read file name of dragged file");+ continue;+ }+ match String::from_utf16(&buffer[0..filename_length]) {+ Ok(file_name) => f(file_name),+ Err(e) => log::error!("dragged file name is not UTF-16: {}", e),+ }+ }+}++fn set_clipboard_bytes<T>(data: &[T], format: u32) -> Result<()> {+ unsafe {+ let global = Owned::new(GlobalAlloc(GMEM_MOVEABLE, std::mem::size_of_val(data))?);+ let ptr = GlobalLock(*global);+ anyhow::ensure!(!ptr.is_null(), "GlobalLock returned null");+ std::ptr::copy_nonoverlapping(data.as_ptr(), ptr as _, data.len());+ GlobalUnlock(*global).ok();+ SetClipboardData(format, Some(HANDLE(global.0)))?;+ // SetClipboardData succeeded — the system now owns the memory.+ std::mem::forget(global);+ }+ Ok(())+}++fn get_clipboard_string(format: u32) -> Option<String> {+ let locked = get_clipboard_data(format)?;+ let bytes = locked.as_bytes();+ let words_len = bytes.len() / std::mem::size_of::<u16>();+ if words_len == 0 {+ return Some(String::new());+ }+ let slice = unsafe { std::slice::from_raw_parts(bytes.as_ptr() as *const u16, words_len) };+ let actual_len = slice.iter().position(|&c| c == 0).unwrap_or(words_len);+ Some(String::from_utf16_lossy(&slice[..actual_len]))+}++fn is_image_format(format: u32) -> bool {+ IMAGE_FORMATS_MAP.contains_key(&format) || format == CF_DIB.0 as u32+}++fn write_string(item: &ClipboardString) -> Result<()> {+ let wide: Vec<u16> = item.text.encode_utf16().chain(Some(0)).collect_vec();+ set_clipboard_bytes(&wide, CF_UNICODETEXT.0 as u32)?;++ if let Some(metadata) = item.metadata.as_ref() {+ let hash_bytes = ClipboardString::text_hash(&item.text).to_ne_bytes();+ set_clipboard_bytes(&hash_bytes, *CLIPBOARD_HASH_FORMAT)?;++ let wide: Vec<u16> = metadata.encode_utf16().chain(Some(0)).collect_vec();+ set_clipboard_bytes(&wide, *CLIPBOARD_METADATA_FORMAT)?;+ }+ Ok(())+}++fn write_image(item: &Image) -> Result<()> {+ let native_format = match item.format {+ ImageFormat::Svg => Some(*CLIPBOARD_SVG_FORMAT),+ ImageFormat::Gif => Some(*CLIPBOARD_GIF_FORMAT),+ ImageFormat::Png => Some(*CLIPBOARD_PNG_FORMAT),+ ImageFormat::Jpeg => Some(*CLIPBOARD_JPG_FORMAT),+ _ => None,+ };+ if let Some(format) = native_format {+ set_clipboard_bytes(item.bytes(), format)?;+ }++ // Also provide a PNG copy for broad compatibility.+ // SVG can't be rasterized by the image crate, so skip it.+ if item.format != ImageFormat::Svg && native_format != Some(*CLIPBOARD_PNG_FORMAT) {+ if let Some(png_bytes) = convert_to_png(item.bytes(), item.format) {+ set_clipboard_bytes(&png_bytes, *CLIPBOARD_PNG_FORMAT)?;+ }+ }+ Ok(())+}++fn write_files(paths: &ExternalPaths) -> Result<()> {+ let mut names: Vec<u16> = Vec::new();+ for path in paths.paths() {+ names.extend(path.as_os_str().encode_wide());+ names.push(0);+ }+ names.push(0);++ let header = DROPFILES {+ pFiles: std::mem::size_of::<DROPFILES>() as u32,+ pt: POINT::default(),+ fNC: BOOL(0),+ fWide: BOOL(1),+ };+ let header_bytes = unsafe {+ std::slice::from_raw_parts(+ &header as *const DROPFILES as *const u8,+ std::mem::size_of::<DROPFILES>(),+ )+ };+ let mut bytes = Vec::with_capacity(header_bytes.len() + names.len() * 2);+ bytes.extend_from_slice(header_bytes);+ bytes.extend(names.iter().flat_map(|unit| unit.to_ne_bytes()));+ set_clipboard_bytes(&bytes, CF_HDROP.0 as u32)+}++fn convert_to_png(bytes: &[u8], format: ImageFormat) -> Option<Vec<u8>> {+ let img_format = gpui_to_image_format(format)?;+ let image = image::load_from_memory_with_format(bytes, img_format)+ .map_err(|e| log::warn!("Failed to decode image for PNG conversion: {e}"))+ .ok()?;+ let mut buf = Vec::new();+ image+ .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)+ .map_err(|e| log::warn!("Failed to encode PNG: {e}"))+ .ok()?;+ Some(buf)+}++fn read_string() -> Option<ClipboardEntry> {+ let text = get_clipboard_string(CF_UNICODETEXT.0 as u32)?;+ let metadata = read_clipboard_metadata(&text);+ Some(ClipboardEntry::String(ClipboardString { text, metadata }))+}++fn read_clipboard_metadata(text: &str) -> Option<String> {+ let locked = get_clipboard_data(*CLIPBOARD_HASH_FORMAT)?;+ let hash_bytes: [u8; 8] = locked.as_bytes().get(..8)?.try_into().ok()?;+ let hash = u64::from_ne_bytes(hash_bytes);+ if hash != ClipboardString::text_hash(text) {+ return None;+ }+ get_clipboard_string(*CLIPBOARD_METADATA_FORMAT)+}++fn read_image(format: u32) -> Option<ClipboardEntry> {+ let locked = get_clipboard_data(format)?;+ let (bytes, image_format) = if format == CF_DIB.0 as u32 {+ (convert_dib_to_bmp(locked.as_bytes())?, ImageFormat::Bmp)+ } else {+ let image_format = *IMAGE_FORMATS_MAP.get(&format)?;+ (locked.as_bytes().to_vec(), image_format)+ };+ let id = hash(&bytes);+ Some(ClipboardEntry::Image(Image {+ format: image_format,+ bytes,+ id,+ }))+}++fn read_files() -> Option<ClipboardEntry> {+ let locked = get_clipboard_data(CF_HDROP.0 as u32)?;+ let hdrop = HDROP(locked.ptr as *mut _);+ let mut filenames = Vec::new();+ with_file_names(hdrop, |name| filenames.push(std::path::PathBuf::from(name)));+ Some(ClipboardEntry::ExternalPaths(ExternalPaths(+ filenames.into(),+ )))+}++/// DIB is BMP without the 14-byte BITMAPFILEHEADER. Prepend one.+fn convert_dib_to_bmp(dib: &[u8]) -> Option<Vec<u8>> {+ if dib.len() < 40 {+ return None;+ }++ let header_size = u32::from_le_bytes(dib[0..4].try_into().ok()?);+ let bit_count = u16::from_le_bytes(dib[14..16].try_into().ok()?);+ let compression = u32::from_le_bytes(dib[16..20].try_into().ok()?);++ let color_table_size = if bit_count <= 8 {+ let colors_used = u32::from_le_bytes(dib[32..36].try_into().ok()?);+ (if colors_used == 0 {+ 1u32 << bit_count+ } else {+ colors_used+ }) * 4+ } else if compression == 3 {+ 12 // BI_BITFIELDS+ } else {+ 0+ };++ let pixel_offset = 14 + header_size + color_table_size;+ let file_size = 14 + dib.len() as u32;++ let mut bmp = Vec::with_capacity(file_size as usize);+ bmp.extend_from_slice(b"BM");+ bmp.extend_from_slice(&file_size.to_le_bytes());+ bmp.extend_from_slice(&[0u8; 4]); // reserved+ bmp.extend_from_slice(&pixel_offset.to_le_bytes());+ bmp.extend_from_slice(dib);+ Some(bmp)+}++fn log_unsupported_clipboard_formats() {+ let count = unsafe { CountClipboardFormats() };+ let mut format = 0;+ for _ in 0..count {+ format = unsafe { EnumClipboardFormats(format) };+ let mut buffer = [0u16; 64];+ unsafe { GetClipboardFormatNameW(format, &mut buffer) };+ let format_name = String::from_utf16_lossy(&buffer);+ log::warn!(+ "Try to paste with unsupported clipboard format: {}, {}.",+ format,+ format_name+ );+ }+}++fn gpui_to_image_format(value: ImageFormat) -> Option<image::ImageFormat> {+ match value {+ ImageFormat::Png => Some(image::ImageFormat::Png),+ ImageFormat::Jpeg => Some(image::ImageFormat::Jpeg),+ ImageFormat::Webp => Some(image::ImageFormat::WebP),+ ImageFormat::Gif => Some(image::ImageFormat::Gif),+ ImageFormat::Bmp => Some(image::ImageFormat::Bmp),+ ImageFormat::Tiff => Some(image::ImageFormat::Tiff),+ other => {+ log::warn!("No image crate equivalent for format: {other:?}");+ None+ }+ }+}++struct ClipboardGuard;++impl ClipboardGuard {+ fn open() -> Option<Self> {+ match unsafe { OpenClipboard(None) } {+ Ok(()) => Some(Self),+ Err(e) => {+ log::error!("Failed to open clipboard: {e}");+ None+ }+ }+ }+}++impl Drop for ClipboardGuard {+ fn drop(&mut self) {+ if let Err(e) = unsafe { CloseClipboard() } {+ log::error!("Failed to close clipboard: {e}");+ }+ }+}++struct LockedGlobal {+ global: HGLOBAL,+ ptr: *const u8,+ size: usize,+}++impl LockedGlobal {+ fn lock(global: HGLOBAL) -> Option<Self> {+ let size = unsafe { GlobalSize(global) };+ let ptr = unsafe { GlobalLock(global) };+ if ptr.is_null() {+ return None;+ }+ Some(Self {+ global,+ ptr: ptr as *const u8,+ size,+ })+ }++ fn as_bytes(&self) -> &[u8] {+ unsafe { std::slice::from_raw_parts(self.ptr, self.size) }+ }+}++impl Drop for LockedGlobal {+ fn drop(&mut self) {+ unsafe { GlobalUnlock(self.global).ok() };+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/color_text_raster.hlsl b/native/vendor/wu/crates/gpui_windows/src/color_text_raster.hlslnew file mode 100644index 00000000000..2fbc156ba5e--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/color_text_raster.hlsl@@ -0,0 +1,44 @@+#include "alpha_correction.hlsl"++struct RasterVertexOutput {+ float4 position : SV_Position;+ float2 texcoord : TEXCOORD0;+};++RasterVertexOutput emoji_rasterization_vertex(uint vertexID : SV_VERTEXID)+{+ RasterVertexOutput output;+ output.texcoord = float2((vertexID << 1) & 2, vertexID & 2);+ output.position = float4(output.texcoord * 2.0f - 1.0f, 0.0f, 1.0f);+ output.position.y = -output.position.y;++ return output;+}++struct PixelInput {+ float4 position: SV_Position;+ float2 texcoord : TEXCOORD0;+};++struct Bounds {+ int2 origin;+ int2 size;+};++Texture2D<float> t_layer : register(t0);+SamplerState s_layer : register(s0);++cbuffer GlyphLayerTextureParams : register(b0) {+ Bounds bounds;+ float4 run_color;+ float4 gamma_ratios;+ float grayscale_enhanced_contrast;+ float3 _pad;+};++float4 emoji_rasterization_fragment(PixelInput input): SV_Target {+ float sample = t_layer.Sample(s_layer, input.texcoord.xy).r;+ float alpha_corrected = apply_contrast_and_gamma_correction(sample, run_color.rgb, grayscale_enhanced_contrast, gamma_ratios);+ float alpha = alpha_corrected * run_color.a;+ return float4(run_color.rgb * alpha, alpha);+}diff --git a/native/vendor/wu/crates/gpui_windows/src/destination_list.rs b/native/vendor/wu/crates/gpui_windows/src/destination_list.rsnew file mode 100644index 00000000000..51ba137995e--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/destination_list.rs@@ -0,0 +1,207 @@+use std::{path::PathBuf, sync::Arc};++use itertools::Itertools;+use smallvec::SmallVec;+use windows::{+ Win32::{+ Foundation::PROPERTYKEY,+ Globalization::u_strlen,+ System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance, StructuredStorage::PROPVARIANT},+ UI::{+ Controls::INFOTIPSIZE,+ Shell::{+ Common::{IObjectArray, IObjectCollection},+ DestinationList, EnumerableObjectCollection, ICustomDestinationList, IShellLinkW,+ PropertiesSystem::IPropertyStore,+ ShellLink,+ },+ },+ },+ core::{GUID, HSTRING, Interface},+};++use gpui::{Action, MenuItem, SharedString};++pub(crate) struct JumpList {+ pub(crate) dock_menus: Vec<DockMenuItem>,+ pub(crate) recent_workspaces: Arc<[SmallVec<[PathBuf; 2]>]>,+}++impl JumpList {+ pub(crate) fn new() -> Self {+ Self {+ dock_menus: Vec::default(),+ recent_workspaces: Arc::default(),+ }+ }+}++pub(crate) struct DockMenuItem {+ pub(crate) name: SharedString,+ pub(crate) description: SharedString,+ pub(crate) action: Box<dyn Action>,+}++impl DockMenuItem {+ pub(crate) fn new(item: MenuItem) -> anyhow::Result<Self> {+ match item {+ MenuItem::Action { name, action, .. } => Ok(Self {+ name: name.clone(),+ description: if action.name() == "workspace::NewWindow" {+ i18n::t!("Opens a new window")+ } else {+ name+ },+ action,+ }),+ _ => anyhow::bail!("Only `MenuItem::Action` is supported for dock menu on Windows."),+ }+ }+}++// This code is based on the example from Microsoft:+// https://github.com/microsoft/Windows-classic-samples/blob/main/Samples/Win7Samples/winui/shell/appshellintegration/RecipePropertyHandler/RecipePropertyHandler.cpp+pub(crate) fn update_jump_list(+ recent_workspaces: &[SmallVec<[PathBuf; 2]>],+ dock_menus: &[(SharedString, SharedString)],+) -> anyhow::Result<Vec<SmallVec<[PathBuf; 2]>>> {+ let (list, removed) = create_destination_list()?;+ add_recent_folders(&list, recent_workspaces, removed.as_ref())?;+ add_dock_menu(&list, dock_menus)?;+ unsafe { list.CommitList() }?;+ Ok(removed)+}++// Copied from:+// https://github.com/microsoft/windows-rs/blob/0fc3c2e5a13d4316d242bdeb0a52af611eba8bd4/crates/libs/windows/src/Windows/Win32/Storage/EnhancedStorage/mod.rs#L1881+const PKEY_TITLE: PROPERTYKEY = PROPERTYKEY {+ fmtid: GUID::from_u128(0xf29f85e0_4ff9_1068_ab91_08002b27b3d9),+ pid: 2,+};++fn create_destination_list() -> anyhow::Result<(ICustomDestinationList, Vec<SmallVec<[PathBuf; 2]>>)>+{+ let list: ICustomDestinationList =+ unsafe { CoCreateInstance(&DestinationList, None, CLSCTX_INPROC_SERVER) }?;++ let mut slots = 0;+ let user_removed: IObjectArray = unsafe { list.BeginList(&mut slots) }?;++ let count = unsafe { user_removed.GetCount() }?;+ if count == 0 {+ return Ok((list, Vec::new()));+ }++ let mut removed = Vec::with_capacity(count as usize);+ for i in 0..count {+ let shell_link: IShellLinkW = unsafe { user_removed.GetAt(i)? };+ let description = {+ // INFOTIPSIZE is the maximum size of the buffer+ // see https://learn.microsoft.com/en-us/windows/win32/api/shobjidl_core/nf-shobjidl_core-ishelllinkw-getdescription+ let mut buffer = [0u16; INFOTIPSIZE as usize];+ unsafe { shell_link.GetDescription(&mut buffer)? };+ let len = unsafe { u_strlen(buffer.as_ptr()) };+ String::from_utf16_lossy(&buffer[..len as usize])+ };+ let args = description.split('\n').map(PathBuf::from).collect();++ removed.push(args);+ }++ Ok((list, removed))+}++fn add_dock_menu(+ list: &ICustomDestinationList,+ dock_menus: &[(SharedString, SharedString)],+) -> anyhow::Result<()> {+ unsafe {+ let tasks: IObjectCollection =+ CoCreateInstance(&EnumerableObjectCollection, None, CLSCTX_INPROC_SERVER)?;+ for (idx, (name, description)) in dock_menus.iter().enumerate() {+ let argument = HSTRING::from(format!("--dock-action {}", idx));+ let description = HSTRING::from(description.as_str());+ let display = name.as_str();+ let task = create_shell_link(argument, description, None, display)?;+ tasks.AddObject(&task)?;+ }+ list.AddUserTasks(&tasks)?;+ Ok(())+ }+}++fn add_recent_folders(+ list: &ICustomDestinationList,+ entries: &[SmallVec<[PathBuf; 2]>],+ removed: &Vec<SmallVec<[PathBuf; 2]>>,+) -> anyhow::Result<()> {+ unsafe {+ let tasks: IObjectCollection =+ CoCreateInstance(&EnumerableObjectCollection, None, CLSCTX_INPROC_SERVER)?;++ for folder_path in entries.iter().filter(|path| !removed.contains(path)) {+ let argument = HSTRING::from(+ folder_path+ .iter()+ .map(|path| format!("\"{}\"", path.display()))+ .join(" "),+ );++ let description = HSTRING::from(+ folder_path+ .iter()+ .map(|path| path.to_string_lossy())+ .collect::<Vec<_>>()+ .join("\n"),+ );+ // simulate folder icon+ // https://github.com/microsoft/vscode/blob/7a5dc239516a8953105da34f84bae152421a8886/src/vs/platform/workspaces/electron-main/workspacesHistoryMainService.ts#L380+ let icon = HSTRING::from("explorer.exe");++ let display = folder_path+ .iter()+ .map(|p| {+ p.file_name()+ .map(|name| name.to_string_lossy())+ .unwrap_or_else(|| p.to_string_lossy())+ })+ .join(", ");++ tasks.AddObject(&create_shell_link(+ argument,+ description,+ Some(icon),+ &display,+ )?)?;+ }++ if tasks.GetCount().unwrap_or(0) > 0 {+ list.AppendCategory(&HSTRING::from("Recent Folders"), &tasks)?;+ }+ Ok(())+ }+}++fn create_shell_link(+ argument: HSTRING,+ description: HSTRING,+ icon: Option<HSTRING>,+ display: &str,+) -> anyhow::Result<IShellLinkW> {+ unsafe {+ let link: IShellLinkW = CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER)?;+ let exe_path = HSTRING::from(std::env::current_exe()?.as_os_str());+ link.SetPath(&exe_path)?;+ link.SetArguments(&argument)?;+ link.SetDescription(&description)?;+ if let Some(icon) = icon {+ link.SetIconLocation(&icon, 0)?;+ }+ let store: IPropertyStore = link.cast()?;+ let title = PROPVARIANT::from(display);+ store.SetValue(&PKEY_TITLE, &title)?;+ store.Commit()?;++ Ok(link)+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/direct_manipulation.rs b/native/vendor/wu/crates/gpui_windows/src/direct_manipulation.rsnew file mode 100644index 00000000000..9adcbed343b--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/direct_manipulation.rs@@ -0,0 +1,359 @@+use std::cell::{Cell, RefCell};+use std::rc::Rc;++use anyhow::Result;+use gpui::*;+use gpui_util::ResultExt;+use windows::Win32::{+ Foundation::*,+ Graphics::{DirectManipulation::*, Gdi::*},+ System::Com::*,+ UI::{Input::Pointer::*, WindowsAndMessaging::*},+};++use crate::*;++/// Default viewport size in pixels. The actual content size doesn't matter+/// because we're using the viewport only for gesture recognition, not for+/// visual output.+const DEFAULT_VIEWPORT_SIZE: i32 = 1000;++pub(crate) struct DirectManipulationHandler {+ manager: IDirectManipulationManager,+ update_manager: IDirectManipulationUpdateManager,+ viewport: IDirectManipulationViewport,+ _handler_cookie: u32,+ window: HWND,+ scale_factor: Rc<Cell<f32>>,+ pending_events: Rc<RefCell<Vec<PlatformInput>>>,+}++impl DirectManipulationHandler {+ pub fn new(window: HWND, scale_factor: f32) -> Result<Self> {+ unsafe {+ let manager: IDirectManipulationManager =+ CoCreateInstance(&DirectManipulationManager, None, CLSCTX_INPROC_SERVER)?;++ let update_manager: IDirectManipulationUpdateManager = manager.GetUpdateManager()?;++ let viewport: IDirectManipulationViewport = manager.CreateViewport(None, window)?;++ let configuration = DIRECTMANIPULATION_CONFIGURATION_INTERACTION+ | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_X+ | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_Y+ | DIRECTMANIPULATION_CONFIGURATION_TRANSLATION_INERTIA+ | DIRECTMANIPULATION_CONFIGURATION_RAILS_X+ | DIRECTMANIPULATION_CONFIGURATION_RAILS_Y+ | DIRECTMANIPULATION_CONFIGURATION_SCALING;+ viewport.ActivateConfiguration(configuration)?;++ viewport.SetViewportOptions(+ DIRECTMANIPULATION_VIEWPORT_OPTIONS_MANUALUPDATE+ | DIRECTMANIPULATION_VIEWPORT_OPTIONS_DISABLEPIXELSNAPPING,+ )?;++ let mut rect = RECT {+ left: 0,+ top: 0,+ right: DEFAULT_VIEWPORT_SIZE,+ bottom: DEFAULT_VIEWPORT_SIZE,+ };+ viewport.SetViewportRect(&mut rect)?;++ manager.Activate(window)?;+ viewport.Enable()?;++ let scale_factor = Rc::new(Cell::new(scale_factor));+ let pending_events = Rc::new(RefCell::new(Vec::new()));++ let event_handler: IDirectManipulationViewportEventHandler =+ DirectManipulationEventHandler::new(+ window,+ Rc::clone(&scale_factor),+ Rc::clone(&pending_events),+ )+ .into();++ let handler_cookie = viewport.AddEventHandler(Some(window), &event_handler)?;++ update_manager.Update(None)?;++ Ok(Self {+ manager,+ update_manager,+ viewport,+ _handler_cookie: handler_cookie,+ window,+ scale_factor,+ pending_events,+ })+ }+ }++ pub fn set_scale_factor(&self, scale_factor: f32) {+ self.scale_factor.set(scale_factor);+ }++ pub fn on_pointer_hit_test(&self, wparam: WPARAM) {+ unsafe {+ let pointer_id = wparam.loword() as u32;+ let mut pointer_type = POINTER_INPUT_TYPE::default();+ if GetPointerType(pointer_id, &mut pointer_type).is_ok() && pointer_type == PT_TOUCHPAD+ {+ self.viewport.SetContact(pointer_id).log_err();+ }+ }+ }++ pub fn update(&self) {+ unsafe {+ self.update_manager.Update(None).log_err();+ }+ }++ pub fn drain_events(&self) -> Vec<PlatformInput> {+ std::mem::take(&mut *self.pending_events.borrow_mut())+ }+}++impl Drop for DirectManipulationHandler {+ fn drop(&mut self) {+ unsafe {+ self.viewport.Stop().log_err();+ self.viewport.Abandon().log_err();+ self.manager.Deactivate(self.window).log_err();+ }+ }+}++#[derive(Debug, Clone, Copy, PartialEq, Eq)]+enum GestureKind {+ None,+ Scroll,+ Pinch,+}++#[windows_core::implement(IDirectManipulationViewportEventHandler)]+struct DirectManipulationEventHandler {+ window: HWND,+ scale_factor: Rc<Cell<f32>>,+ gesture_kind: Cell<GestureKind>,+ last_scale: Cell<f32>,+ last_x_offset: Cell<f32>,+ last_y_offset: Cell<f32>,+ scroll_phase: Cell<TouchPhase>,+ pending_events: Rc<RefCell<Vec<PlatformInput>>>,+}++impl DirectManipulationEventHandler {+ fn new(+ window: HWND,+ scale_factor: Rc<Cell<f32>>,+ pending_events: Rc<RefCell<Vec<PlatformInput>>>,+ ) -> Self {+ Self {+ window,+ scale_factor,+ gesture_kind: Cell::new(GestureKind::None),+ last_scale: Cell::new(1.0),+ last_x_offset: Cell::new(0.0),+ last_y_offset: Cell::new(0.0),+ scroll_phase: Cell::new(TouchPhase::Started),+ pending_events,+ }+ }++ fn end_gesture(&self) {+ let position = self.mouse_position();+ let modifiers = current_modifiers();+ match self.gesture_kind.get() {+ GestureKind::Scroll => {+ self.pending_events+ .borrow_mut()+ .push(PlatformInput::ScrollWheel(ScrollWheelEvent {+ position,+ delta: ScrollDelta::Pixels(point(px(0.0), px(0.0))),+ modifiers,+ touch_phase: TouchPhase::Ended,+ }));+ }+ GestureKind::Pinch => {+ self.pending_events+ .borrow_mut()+ .push(PlatformInput::Pinch(PinchEvent {+ position,+ delta: 0.0,+ modifiers,+ phase: TouchPhase::Ended,+ }));+ }+ GestureKind::None => {}+ }+ self.gesture_kind.set(GestureKind::None);+ }++ fn mouse_position(&self) -> Point<Pixels> {+ let scale_factor = self.scale_factor.get();+ unsafe {+ let mut point: POINT = std::mem::zeroed();+ let _ = GetCursorPos(&mut point);+ let _ = ScreenToClient(self.window, &mut point);+ logical_point(point.x as f32, point.y as f32, scale_factor)+ }+ }+}++impl IDirectManipulationViewportEventHandler_Impl for DirectManipulationEventHandler_Impl {+ fn OnViewportStatusChanged(+ &self,+ viewport: windows_core::Ref<'_, IDirectManipulationViewport>,+ current: DIRECTMANIPULATION_STATUS,+ previous: DIRECTMANIPULATION_STATUS,+ ) -> windows_core::Result<()> {+ if current == previous {+ return Ok(());+ }++ // A new gesture interrupted inertia, so end the old sequence.+ if current == DIRECTMANIPULATION_RUNNING && previous == DIRECTMANIPULATION_INERTIA {+ self.end_gesture();+ }++ if current == DIRECTMANIPULATION_READY {+ self.end_gesture();++ // Reset the content transform so the viewport is ready for the next gesture.+ // ZoomToRect triggers a second RUNNING -> READY cycle, so prevent an infinite loop here.+ if self.last_scale.get() != 1.0+ || self.last_x_offset.get() != 0.0+ || self.last_y_offset.get() != 0.0+ {+ if let Some(viewport) = viewport.as_ref() {+ unsafe {+ viewport+ .ZoomToRect(+ 0.0,+ 0.0,+ DEFAULT_VIEWPORT_SIZE as f32,+ DEFAULT_VIEWPORT_SIZE as f32,+ false,+ )+ .log_err();+ }+ }+ }++ self.last_scale.set(1.0);+ self.last_x_offset.set(0.0);+ self.last_y_offset.set(0.0);+ }++ Ok(())+ }++ fn OnViewportUpdated(+ &self,+ _viewport: windows_core::Ref<'_, IDirectManipulationViewport>,+ ) -> windows_core::Result<()> {+ Ok(())+ }++ fn OnContentUpdated(+ &self,+ _viewport: windows_core::Ref<'_, IDirectManipulationViewport>,+ content: windows_core::Ref<'_, IDirectManipulationContent>,+ ) -> windows_core::Result<()> {+ let content = content.as_ref().ok_or(E_POINTER)?;++ // Get the 6-element content transform: [scale, 0, 0, scale, tx, ty]+ let mut xform = [0.0f32; 6];+ unsafe {+ content.GetContentTransform(&mut xform)?;+ }++ let scale = xform[0];+ let scale_factor = self.scale_factor.get();+ let x_offset = xform[4] / scale_factor;+ let y_offset = xform[5] / scale_factor;++ if scale == 0.0 {+ return Ok(());+ }++ let last_scale = self.last_scale.get();+ let last_x = self.last_x_offset.get();+ let last_y = self.last_y_offset.get();++ if float_equals(scale, last_scale)+ && float_equals(x_offset, last_x)+ && float_equals(y_offset, last_y)+ {+ return Ok(());+ }++ let position = self.mouse_position();+ let modifiers = current_modifiers();++ // Direct Manipulation reports both translation and scale in every content update.+ // Translation values can shift during a pinch due to the zoom center shifting.+ // We classify each gesture as either scroll or pinch and only emit one type of event.+ // We allow Scroll -> Pinch (a pinch can start with a small pan) but not the reverse.+ if !float_equals(scale, 1.0) {+ if self.gesture_kind.get() != GestureKind::Pinch {+ self.end_gesture();+ self.gesture_kind.set(GestureKind::Pinch);+ self.pending_events+ .borrow_mut()+ .push(PlatformInput::Pinch(PinchEvent {+ position,+ delta: 0.0,+ modifiers,+ phase: TouchPhase::Started,+ }));+ }+ } else if self.gesture_kind.get() == GestureKind::None {+ self.gesture_kind.set(GestureKind::Scroll);+ self.scroll_phase.set(TouchPhase::Started);+ }++ match self.gesture_kind.get() {+ GestureKind::Scroll => {+ let dx = x_offset - last_x;+ let dy = y_offset - last_y;+ let touch_phase = self.scroll_phase.get();+ self.scroll_phase.set(TouchPhase::Moved);+ self.pending_events+ .borrow_mut()+ .push(PlatformInput::ScrollWheel(ScrollWheelEvent {+ position,+ delta: ScrollDelta::Pixels(point(px(dx), px(dy))),+ modifiers,+ touch_phase,+ }));+ }+ GestureKind::Pinch => {+ let scale_delta = scale / last_scale;+ self.pending_events+ .borrow_mut()+ .push(PlatformInput::Pinch(PinchEvent {+ position,+ delta: scale_delta - 1.0,+ modifiers,+ phase: TouchPhase::Moved,+ }));+ }+ GestureKind::None => {}+ }++ self.last_scale.set(scale);+ self.last_x_offset.set(x_offset);+ self.last_y_offset.set(y_offset);++ Ok(())+ }+}++fn float_equals(f1: f32, f2: f32) -> bool {+ const EPSILON_SCALE: f32 = 0.00001;+ (f1 - f2).abs() < EPSILON_SCALE * f1.abs().max(f2.abs()).max(EPSILON_SCALE)+}diff --git a/native/vendor/wu/crates/gpui_windows/src/direct_write.rs b/native/vendor/wu/crates/gpui_windows/src/direct_write.rsnew file mode 100644index 00000000000..dfe98a76be1--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/direct_write.rs@@ -0,0 +1,2158 @@+use std::{+ borrow::Cow,+ ffi::{c_uint, c_void},+ mem::ManuallyDrop,+};++use anyhow::{Context, Result};+use collections::HashMap;+use gpui_util::{ResultExt, maybe};+use parking_lot::{RwLock, RwLockUpgradableReadGuard};+use windows::{+ Win32::{+ Foundation::*,+ Globalization::GetUserDefaultLocaleName,+ Graphics::{+ Direct3D::D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, Direct3D11::*, DirectWrite::*,+ Dxgi::Common::*, Gdi::LOGFONTW,+ },+ System::SystemServices::LOCALE_NAME_MAX_LENGTH,+ UI::WindowsAndMessaging::*,+ },+ core::*,+};+use windows_numerics::Vector2;++use crate::*;+use gpui::*;++#[derive(Debug)]+struct FontInfo {+ font_family_h: HSTRING,+ font_face: IDWriteFontFace3,+ features: IDWriteTypography,+ fallbacks: Option<IDWriteFontFallback>,+ font_collection: IDWriteFontCollection1,+}++pub(crate) struct DirectWriteTextSystem {+ components: DirectWriteComponents,+ state: RwLock<DirectWriteState>,+}++struct DirectWriteComponents {+ locale: HSTRING,+ factory: IDWriteFactory5,+ in_memory_loader: IDWriteInMemoryFontFileLoader,+ builder: IDWriteFontSetBuilder1,+ text_renderer: TextRendererWrapper,+ system_ui_font_name: SharedString,+ system_subpixel_rendering: bool,+}++impl Drop for DirectWriteComponents {+ fn drop(&mut self) {+ unsafe {+ let _ = self+ .factory+ .UnregisterFontFileLoader(&self.in_memory_loader);+ }+ }+}++struct GPUState {+ device: ID3D11Device,+ device_context: ID3D11DeviceContext,+ sampler: Option<ID3D11SamplerState>,+ blend_state: ID3D11BlendState,+ vertex_shader: ID3D11VertexShader,+ pixel_shader: ID3D11PixelShader,+}++struct DirectWriteState {+ gpu_state: GPUState,+ system_font_collection: IDWriteFontCollection1,+ custom_font_collection: IDWriteFontCollection1,+ fonts: Vec<FontInfo>,+ font_to_font_id: HashMap<Font, FontId>,+ font_info_cache: HashMap<usize, FontId>,+ layout_line_scratch: Vec<u16>,+}++impl GPUState {+ fn new(directx_devices: &DirectXDevices) -> Result<Self> {+ let device = directx_devices.device.clone();+ let device_context = directx_devices.device_context.clone();++ let blend_state = {+ let mut blend_state = None;+ let desc = D3D11_BLEND_DESC {+ AlphaToCoverageEnable: false.into(),+ IndependentBlendEnable: false.into(),+ RenderTarget: [+ D3D11_RENDER_TARGET_BLEND_DESC {+ BlendEnable: true.into(),+ SrcBlend: D3D11_BLEND_ONE,+ DestBlend: D3D11_BLEND_INV_SRC_ALPHA,+ BlendOp: D3D11_BLEND_OP_ADD,+ SrcBlendAlpha: D3D11_BLEND_ONE,+ DestBlendAlpha: D3D11_BLEND_INV_SRC_ALPHA,+ BlendOpAlpha: D3D11_BLEND_OP_ADD,+ RenderTargetWriteMask: D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8,+ },+ Default::default(),+ Default::default(),+ Default::default(),+ Default::default(),+ Default::default(),+ Default::default(),+ Default::default(),+ ],+ };+ unsafe { device.CreateBlendState(&desc, Some(&mut blend_state)) }?;+ blend_state.unwrap()+ };++ let sampler = {+ let mut sampler = None;+ let desc = D3D11_SAMPLER_DESC {+ Filter: D3D11_FILTER_MIN_MAG_MIP_POINT,+ AddressU: D3D11_TEXTURE_ADDRESS_BORDER,+ AddressV: D3D11_TEXTURE_ADDRESS_BORDER,+ AddressW: D3D11_TEXTURE_ADDRESS_BORDER,+ MipLODBias: 0.0,+ MaxAnisotropy: 1,+ ComparisonFunc: D3D11_COMPARISON_ALWAYS,+ BorderColor: [0.0, 0.0, 0.0, 0.0],+ MinLOD: 0.0,+ MaxLOD: 0.0,+ };+ unsafe { device.CreateSamplerState(&desc, Some(&mut sampler)) }?;+ sampler+ };++ let vertex_shader = {+ let source = shader_resources::RawShaderBytes::new(+ shader_resources::ShaderModule::EmojiRasterization,+ shader_resources::ShaderTarget::Vertex,+ )?;+ let mut shader = None;+ unsafe { device.CreateVertexShader(source.as_bytes(), None, Some(&mut shader)) }?;+ shader.unwrap()+ };++ let pixel_shader = {+ let source = shader_resources::RawShaderBytes::new(+ shader_resources::ShaderModule::EmojiRasterization,+ shader_resources::ShaderTarget::Fragment,+ )?;+ let mut shader = None;+ unsafe { device.CreatePixelShader(source.as_bytes(), None, Some(&mut shader)) }?;+ shader.unwrap()+ };++ Ok(Self {+ device,+ device_context,+ sampler,+ blend_state,+ vertex_shader,+ pixel_shader,+ })+ }+}++impl DirectWriteTextSystem {+ pub(crate) fn new(directx_devices: &DirectXDevices) -> Result<Self> {+ let factory: IDWriteFactory5 = unsafe { DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)? };+ // The `IDWriteInMemoryFontFileLoader` here is supported starting from+ // Windows 10 Creators Update, which consequently requires the entire+ // `DirectWriteTextSystem` to run on `win10 1703`+.+ let in_memory_loader = unsafe { factory.CreateInMemoryFontFileLoader()? };+ unsafe { factory.RegisterFontFileLoader(&in_memory_loader)? };+ let builder = unsafe { factory.CreateFontSetBuilder()? };+ let mut locale = [0u16; LOCALE_NAME_MAX_LENGTH as usize];+ unsafe { GetUserDefaultLocaleName(&mut locale) };+ let locale = HSTRING::from_wide(&locale);+ let text_renderer = TextRendererWrapper::new(locale.clone());++ let gpu_state = GPUState::new(directx_devices)?;++ let system_subpixel_rendering = get_system_subpixel_rendering();+ let system_ui_font_name = get_system_ui_font_name();+ let components = DirectWriteComponents {+ locale,+ factory,+ in_memory_loader,+ builder,+ text_renderer,+ system_ui_font_name,+ system_subpixel_rendering,+ };++ let system_font_collection = unsafe {+ let mut result = None;+ components+ .factory+ .GetSystemFontCollection(false, &mut result, true)?;+ result.context("Failed to get system font collection")?+ };+ let custom_font_set = unsafe { components.builder.CreateFontSet()? };+ let custom_font_collection = unsafe {+ components+ .factory+ .CreateFontCollectionFromFontSet(&custom_font_set)?+ };++ Ok(Self {+ components,+ state: RwLock::new(DirectWriteState {+ gpu_state,+ system_font_collection,+ custom_font_collection,+ fonts: Vec::new(),+ font_to_font_id: HashMap::default(),+ font_info_cache: HashMap::default(),+ layout_line_scratch: Vec::new(),+ }),+ })+ }++ pub(crate) fn handle_gpu_lost(&self, directx_devices: &DirectXDevices) -> Result<()> {+ self.state.write().handle_gpu_lost(directx_devices)+ }+}++impl PlatformTextSystem for DirectWriteTextSystem {+ fn add_fonts(&self, fonts: Vec<Cow<'static, [u8]>>) -> Result<()> {+ self.state.write().add_fonts(&self.components, fonts)+ }++ fn all_font_names(&self) -> Vec<String> {+ self.state.read().all_font_names(&self.components)+ }++ fn font_id(&self, font: &Font) -> Result<FontId> {+ let lock = self.state.upgradable_read();+ if let Some(font_id) = lock.font_to_font_id.get(font) {+ Ok(*font_id)+ } else {+ RwLockUpgradableReadGuard::upgrade(lock)+ .select_and_cache_font(&self.components, font)+ .with_context(|| format!("Failed to select font: {:?}", font))+ }+ }++ fn font_metrics(&self, font_id: FontId) -> FontMetrics {+ self.state.read().font_metrics(font_id)+ }++ fn typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {+ self.state.read().get_typographic_bounds(font_id, glyph_id)+ }++ fn advance(&self, font_id: FontId, glyph_id: GlyphId) -> anyhow::Result<Size<f32>> {+ self.state.read().get_advance(font_id, glyph_id)+ }++ fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {+ self.state.read().glyph_for_char(font_id, ch)+ }++ fn glyph_raster_bounds(+ &self,+ params: &RenderGlyphParams,+ ) -> anyhow::Result<Bounds<DevicePixels>> {+ self.state.read().raster_bounds(&self.components, params)+ }++ fn rasterize_glyph(+ &self,+ params: &RenderGlyphParams,+ raster_bounds: Bounds<DevicePixels>,+ ) -> anyhow::Result<(Size<DevicePixels>, Vec<u8>)> {+ self.state+ .read()+ .rasterize_glyph(&self.components, params, raster_bounds)+ }++ fn layout_line(&self, text: &str, font_size: Pixels, runs: &[FontRun]) -> LineLayout {+ self.state+ .write()+ .layout_line(&self.components, text, font_size, runs)+ .log_err()+ .unwrap_or(LineLayout {+ font_size,+ ..Default::default()+ })+ }++ fn recommended_rendering_mode(+ &self,+ _font_id: FontId,+ _font_size: Pixels,+ ) -> TextRenderingMode {+ if self.components.system_subpixel_rendering {+ TextRenderingMode::Subpixel+ } else {+ TextRenderingMode::Grayscale+ }+ }+}++impl DirectWriteState {+ fn select_and_cache_font(+ &mut self,+ components: &DirectWriteComponents,+ font: &Font,+ ) -> Option<FontId> {+ let select_font = |this: &mut DirectWriteState, font: &Font| -> Option<FontId> {+ let info = [&this.custom_font_collection, &this.system_font_collection]+ .into_iter()+ .find_map(|font_collection| unsafe {+ DirectWriteState::make_font_from_font_collection(+ font,+ font_collection,+ &components.factory,+ &this.system_font_collection,+ &components.system_ui_font_name,+ )+ })?;++ let font_id = FontId(this.fonts.len());+ let font_face_key = info.font_face.cast::<IUnknown>().unwrap().as_raw().addr();+ this.fonts.push(info);+ this.font_info_cache.insert(font_face_key, font_id);+ Some(font_id)+ };++ let mut font_id = select_font(self, font);+ if font_id.is_none() {+ // try updating system fonts and reselect+ let mut collection = None;+ let font_collection_updated = unsafe {+ components+ .factory+ .GetSystemFontCollection(false, &mut collection, true)+ }+ .log_err()+ .is_some();+ if font_collection_updated && let Some(collection) = collection {+ self.system_font_collection = collection;+ }+ font_id = select_font(self, font);+ };+ let font_id = font_id?;+ self.font_to_font_id.insert(font.clone(), font_id);+ Some(font_id)+ }++ fn add_fonts(+ &mut self,+ components: &DirectWriteComponents,+ fonts: Vec<Cow<'static, [u8]>>,+ ) -> Result<()> {+ for font_data in fonts {+ match font_data {+ Cow::Borrowed(data) => unsafe {+ let font_file = components+ .in_memory_loader+ .CreateInMemoryFontFileReference(+ &components.factory,+ data.as_ptr().cast(),+ data.len() as _,+ None,+ )?;+ components.builder.AddFontFile(&font_file)?;+ },+ Cow::Owned(data) => unsafe {+ let font_file = components+ .in_memory_loader+ .CreateInMemoryFontFileReference(+ &components.factory,+ data.as_ptr().cast(),+ data.len() as _,+ None,+ )?;+ components.builder.AddFontFile(&font_file)?;+ },+ }+ }+ let set = unsafe { components.builder.CreateFontSet()? };+ let collection = unsafe { components.factory.CreateFontCollectionFromFontSet(&set)? };+ self.custom_font_collection = collection;++ Ok(())+ }++ fn generate_font_fallbacks(+ fallbacks: &FontFallbacks,+ factory: &IDWriteFactory5,+ system_font_collection: &IDWriteFontCollection1,+ ) -> Result<Option<IDWriteFontFallback>> {+ let fallback_list = fallbacks.fallback_list();+ if fallback_list.is_empty() {+ return Ok(None);+ }+ unsafe {+ let builder = factory.CreateFontFallbackBuilder()?;+ let font_set = &system_font_collection.GetFontSet()?;+ let mut unicode_ranges = Vec::new();+ for family_name in fallback_list {+ let family_name = HSTRING::from(family_name);+ let Some(fonts) = font_set+ .GetMatchingFonts(+ &family_name,+ DWRITE_FONT_WEIGHT_NORMAL,+ DWRITE_FONT_STRETCH_NORMAL,+ DWRITE_FONT_STYLE_NORMAL,+ )+ .log_err()+ else {+ continue;+ };+ let Ok(font_face) = fonts.GetFontFaceReference(0) else {+ continue;+ };+ let font = font_face.CreateFontFace()?;+ let mut count = 0;+ font.GetUnicodeRanges(None, &mut count).ok();+ if count == 0 {+ continue;+ }+ unicode_ranges.clear();+ unicode_ranges.resize_with(count as usize, DWRITE_UNICODE_RANGE::default);+ let Some(_) = font+ .GetUnicodeRanges(Some(&mut unicode_ranges), &mut count)+ .log_err()+ else {+ continue;+ };+ builder.AddMapping(+ &unicode_ranges,+ &[family_name.as_ptr()],+ None,+ None,+ None,+ 1.0,+ )?;+ }+ let system_fallbacks = factory.GetSystemFontFallback()?;+ builder.AddMappings(&system_fallbacks)?;+ Ok(Some(builder.CreateFontFallback()?))+ }+ }++ unsafe fn generate_font_features(+ factory: &IDWriteFactory5,+ font_features: &FontFeatures,+ ) -> Result<IDWriteTypography> {+ let direct_write_features = unsafe { factory.CreateTypography()? };+ apply_font_features(&direct_write_features, font_features)?;+ Ok(direct_write_features)+ }++ unsafe fn make_font_from_font_collection(+ &Font {+ ref family,+ ref features,+ ref fallbacks,+ weight,+ style,+ }: &Font,+ collection: &IDWriteFontCollection1,+ factory: &IDWriteFactory5,+ system_font_collection: &IDWriteFontCollection1,+ system_ui_font_name: &SharedString,+ ) -> Option<FontInfo> {+ const SYSTEM_UI_FONT_NAME: &str = ".SystemUIFont";+ let family = if family == SYSTEM_UI_FONT_NAME {+ system_ui_font_name+ } else {+ gpui::font_name_with_fallbacks_shared(&family, &system_ui_font_name)+ };+ let fontset = unsafe { collection.GetFontSet().log_err()? };+ let font_family_h = HSTRING::from(family.as_str());+ let font = unsafe {+ fontset+ .GetMatchingFonts(+ &font_family_h,+ font_weight_to_dwrite(weight),+ DWRITE_FONT_STRETCH_NORMAL,+ font_style_to_dwrite(style),+ )+ .log_err()?+ };+ let total_number = unsafe { font.GetFontCount() };+ for index in 0..total_number {+ let res = maybe!({+ let font_face_ref = unsafe { font.GetFontFaceReference(index).log_err()? };+ let font_face = unsafe { font_face_ref.CreateFontFace().log_err()? };+ let direct_write_features =+ unsafe { Self::generate_font_features(factory, features).log_err()? };+ let fallbacks = fallbacks.as_ref().and_then(|fallbacks| {+ Self::generate_font_fallbacks(fallbacks, factory, system_font_collection)+ .log_err()+ .flatten()+ });+ let font_info = FontInfo {+ font_family_h: font_family_h.clone(),+ font_face,+ features: direct_write_features,+ fallbacks,+ font_collection: collection.clone(),+ };+ Some(font_info)+ });+ if res.is_some() {+ return res;+ }+ }+ None+ }++ fn layout_line(+ &mut self,+ components: &DirectWriteComponents,+ text: &str,+ font_size: Pixels,+ font_runs: &[FontRun],+ ) -> Result<LineLayout> {+ if font_runs.is_empty() {+ return Ok(LineLayout {+ font_size,+ ..Default::default()+ });+ }+ unsafe {+ self.layout_line_scratch.clear();+ self.layout_line_scratch.extend(text.encode_utf16());+ let text_wide = &*self.layout_line_scratch;++ let mut utf8_offset = 0usize;+ let mut utf16_offset = 0u32;+ let text_layout = {+ let first_run = &font_runs[0];+ let font_info = &self.fonts[first_run.font_id.0];+ let collection = &font_info.font_collection;+ let format: IDWriteTextFormat1 = components+ .factory+ .CreateTextFormat(+ &font_info.font_family_h,+ collection,+ font_info.font_face.GetWeight(),+ font_info.font_face.GetStyle(),+ DWRITE_FONT_STRETCH_NORMAL,+ font_size.as_f32(),+ &components.locale,+ )?+ .cast()?;+ if let Some(ref fallbacks) = font_info.fallbacks {+ format.SetFontFallback(fallbacks)?;+ }++ let layout = components.factory.CreateTextLayout(+ text_wide,+ &format,+ f32::INFINITY,+ f32::INFINITY,+ )?;+ let current_text = &text[utf8_offset..(utf8_offset + first_run.len)];+ utf8_offset += first_run.len;+ let current_text_utf16_length = current_text.encode_utf16().count() as u32;+ let text_range = DWRITE_TEXT_RANGE {+ startPosition: utf16_offset,+ length: current_text_utf16_length,+ };+ layout.SetTypography(&font_info.features, text_range)?;+ utf16_offset += current_text_utf16_length;++ layout+ };++ let (ascent, descent) = {+ let mut first_metrics = [DWRITE_LINE_METRICS::default(); 4];+ let mut line_count = 0u32;+ text_layout.GetLineMetrics(Some(&mut first_metrics), &mut line_count)?;+ (+ px(first_metrics[0].baseline),+ px(first_metrics[0].height - first_metrics[0].baseline),+ )+ };+ let mut break_ligatures = true;+ for run in &font_runs[1..] {+ let font_info = &self.fonts[run.font_id.0];+ let current_text = &text[utf8_offset..(utf8_offset + run.len)];+ utf8_offset += run.len;+ let current_text_utf16_length = current_text.encode_utf16().count() as u32;++ let collection = &font_info.font_collection;+ let text_range = DWRITE_TEXT_RANGE {+ startPosition: utf16_offset,+ length: current_text_utf16_length,+ };+ utf16_offset += current_text_utf16_length;+ text_layout.SetFontCollection(collection, text_range)?;+ text_layout.SetFontFamilyName(&font_info.font_family_h, text_range)?;+ let font_size = if break_ligatures {+ font_size.as_f32().next_up()+ } else {+ font_size.as_f32()+ };+ text_layout.SetFontSize(font_size, text_range)?;+ text_layout.SetFontStyle(font_info.font_face.GetStyle(), text_range)?;+ text_layout.SetFontWeight(font_info.font_face.GetWeight(), text_range)?;+ text_layout.SetTypography(&font_info.features, text_range)?;++ break_ligatures = !break_ligatures;+ }++ let mut runs = Vec::new();+ let mut renderer_context = RendererContext {+ text_system: self,+ components,+ index_converter: StringIndexConverter::new(text),+ runs: &mut runs,+ width: 0.0,+ };+ text_layout.Draw(+ Some((&raw mut renderer_context).cast::<c_void>().cast_const()),+ &components.text_renderer.0,+ 0.0,+ 0.0,+ )?;+ let width = px(renderer_context.width);++ Ok(LineLayout {+ font_size,+ width,+ ascent,+ descent,+ runs,+ len: text.len(),+ })+ }+ }++ fn font_metrics(&self, font_id: FontId) -> FontMetrics {+ unsafe {+ let font_info = &self.fonts[font_id.0];+ let mut metrics = std::mem::zeroed();+ font_info.font_face.GetMetrics(&mut metrics);++ FontMetrics {+ units_per_em: metrics.Base.designUnitsPerEm as _,+ ascent: metrics.Base.ascent as _,+ descent: -(metrics.Base.descent as f32),+ line_gap: metrics.Base.lineGap as _,+ underline_position: metrics.Base.underlinePosition as _,+ underline_thickness: metrics.Base.underlineThickness as _,+ cap_height: metrics.Base.capHeight as _,+ x_height: metrics.Base.xHeight as _,+ bounding_box: Bounds {+ origin: Point {+ x: metrics.glyphBoxLeft as _,+ y: metrics.glyphBoxBottom as _,+ },+ size: Size {+ width: (metrics.glyphBoxRight - metrics.glyphBoxLeft) as _,+ height: (metrics.glyphBoxTop - metrics.glyphBoxBottom) as _,+ },+ },+ }+ }+ }++ fn create_glyph_run_analysis(+ &self,+ components: &DirectWriteComponents,+ params: &RenderGlyphParams,+ ) -> Result<IDWriteGlyphRunAnalysis> {+ let font = &self.fonts[params.font_id.0];+ let glyph_id = [params.glyph_id.0 as u16];+ let advance = [0.0];+ let offset = [DWRITE_GLYPH_OFFSET::default()];+ let glyph_run = DWRITE_GLYPH_RUN {+ fontFace: ManuallyDrop::new(Some(unsafe { std::ptr::read(&***font.font_face) })),+ fontEmSize: params.font_size.as_f32(),+ glyphCount: 1,+ glyphIndices: glyph_id.as_ptr(),+ glyphAdvances: advance.as_ptr(),+ glyphOffsets: offset.as_ptr(),+ isSideways: BOOL(0),+ bidiLevel: 0,+ };+ let transform = DWRITE_MATRIX {+ m11: params.scale_factor,+ m12: 0.0,+ m21: 0.0,+ m22: params.scale_factor,+ dx: 0.0,+ dy: 0.0,+ };+ let baseline_origin_x =+ params.subpixel_variant.x as f32 / SUBPIXEL_VARIANTS_X as f32 / params.scale_factor;+ let baseline_origin_y = params.subpixel_variant.y as f32+ / gpui::SUBPIXEL_VARIANTS_Y as f32+ / params.scale_factor;++ let mut rendering_mode = DWRITE_RENDERING_MODE1::default();+ let mut grid_fit_mode = DWRITE_GRID_FIT_MODE::default();+ unsafe {+ font.font_face.GetRecommendedRenderingMode(+ params.font_size.as_f32(),+ // Using 96 as scale is applied by the transform+ 96.0,+ 96.0,+ Some(&transform),+ false,+ DWRITE_OUTLINE_THRESHOLD_ANTIALIASED,+ DWRITE_MEASURING_MODE_NATURAL,+ None,+ &mut rendering_mode,+ &mut grid_fit_mode,+ )?;+ }+ let rendering_mode = match rendering_mode {+ DWRITE_RENDERING_MODE1_OUTLINE => DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,+ m => m,+ };++ let antialias_mode = if params.subpixel_rendering {+ DWRITE_TEXT_ANTIALIAS_MODE_CLEARTYPE+ } else {+ DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE+ };++ let glyph_analysis = unsafe {+ components.factory.CreateGlyphRunAnalysis(+ &glyph_run,+ Some(&transform),+ rendering_mode,+ DWRITE_MEASURING_MODE_NATURAL,+ grid_fit_mode,+ antialias_mode,+ baseline_origin_x,+ baseline_origin_y,+ )+ }?;+ Ok(glyph_analysis)+ }++ fn raster_bounds(+ &self,+ components: &DirectWriteComponents,+ params: &RenderGlyphParams,+ ) -> Result<Bounds<DevicePixels>> {+ let glyph_analysis = self.create_glyph_run_analysis(components, params)?;++ let texture_type = if params.subpixel_rendering {+ DWRITE_TEXTURE_CLEARTYPE_3x1+ } else {+ DWRITE_TEXTURE_ALIASED_1x1+ };++ let bounds = unsafe { glyph_analysis.GetAlphaTextureBounds(texture_type)? };++ if bounds.right < bounds.left {+ Ok(Bounds {+ origin: point(0.into(), 0.into()),+ size: size(0.into(), 0.into()),+ })+ } else {+ Ok(Bounds {+ origin: point(bounds.left.into(), bounds.top.into()),+ size: size(+ (bounds.right - bounds.left).into(),+ (bounds.bottom - bounds.top).into(),+ ),+ })+ }+ }++ fn glyph_for_char(&self, font_id: FontId, ch: char) -> Option<GlyphId> {+ let font_info = &self.fonts[font_id.0];+ let codepoints = ch as u32;+ let mut glyph_indices = 0u16;+ unsafe {+ font_info+ .font_face+ .GetGlyphIndices(&raw const codepoints, 1, &raw mut glyph_indices)+ .log_err()+ }+ .map(|_| GlyphId(glyph_indices as u32))+ }++ fn rasterize_glyph(+ &self,+ components: &DirectWriteComponents,+ params: &RenderGlyphParams,+ glyph_bounds: Bounds<DevicePixels>,+ ) -> Result<(Size<DevicePixels>, Vec<u8>)> {+ if glyph_bounds.size.width.0 == 0 || glyph_bounds.size.height.0 == 0 {+ anyhow::bail!("glyph bounds are empty");+ }++ let bitmap_data = if params.is_emoji {+ if let Ok(color) = self.rasterize_color(components, params, glyph_bounds) {+ color+ } else {+ let monochrome = self.rasterize_monochrome(components, params, glyph_bounds)?;+ monochrome+ .into_iter()+ .flat_map(|pixel| [0, 0, 0, pixel])+ .collect::<Vec<_>>()+ }+ } else {+ self.rasterize_monochrome(components, params, glyph_bounds)?+ };++ Ok((glyph_bounds.size, bitmap_data))+ }++ fn rasterize_monochrome(+ &self,+ components: &DirectWriteComponents,+ params: &RenderGlyphParams,+ glyph_bounds: Bounds<DevicePixels>,+ ) -> Result<Vec<u8>> {+ let glyph_analysis = self.create_glyph_run_analysis(components, params)?;+ if !params.subpixel_rendering {+ let mut bitmap_data =+ vec![0u8; glyph_bounds.size.width.0 as usize * glyph_bounds.size.height.0 as usize];+ unsafe {+ glyph_analysis.CreateAlphaTexture(+ DWRITE_TEXTURE_ALIASED_1x1,+ &RECT {+ left: glyph_bounds.origin.x.0,+ top: glyph_bounds.origin.y.0,+ right: glyph_bounds.size.width.0 + glyph_bounds.origin.x.0,+ bottom: glyph_bounds.size.height.0 + glyph_bounds.origin.y.0,+ },+ &mut bitmap_data,+ )?;+ }++ return Ok(bitmap_data);+ }++ let width = glyph_bounds.size.width.0 as usize;+ let height = glyph_bounds.size.height.0 as usize;+ let pixel_count = width * height;++ let mut bitmap_data = vec![0u8; pixel_count * 4];++ unsafe {+ glyph_analysis.CreateAlphaTexture(+ DWRITE_TEXTURE_CLEARTYPE_3x1,+ &RECT {+ left: glyph_bounds.origin.x.0,+ top: glyph_bounds.origin.y.0,+ right: glyph_bounds.size.width.0 + glyph_bounds.origin.x.0,+ bottom: glyph_bounds.size.height.0 + glyph_bounds.origin.y.0,+ },+ &mut bitmap_data[..pixel_count * 3],+ )?;+ }++ // The output buffer expects RGBA data, so pad the alpha channel with zeros.+ for pixel_ix in (0..pixel_count).rev() {+ let src = pixel_ix * 3;+ let dst = pixel_ix * 4;+ (+ bitmap_data[dst],+ bitmap_data[dst + 1],+ bitmap_data[dst + 2],+ bitmap_data[dst + 3],+ ) = (+ bitmap_data[src],+ bitmap_data[src + 1],+ bitmap_data[src + 2],+ 0,+ );+ }++ Ok(bitmap_data)+ }++ fn rasterize_color(+ &self,+ components: &DirectWriteComponents,+ params: &RenderGlyphParams,+ glyph_bounds: Bounds<DevicePixels>,+ ) -> Result<Vec<u8>> {+ // INVARIANT: the code below drives the *shared* D3D11 immediate context+ // (`Map`/`Unmap`/`Draw`/`CopyResource`), which `DirectXRenderer` and `DirectXAtlas` also+ // touch. An immediate `ID3D11DeviceContext` is not thread-safe, so this must only run on+ // the main UI thread (which it always is; text rasterization never leaves that thread).+ let bitmap_size = glyph_bounds.size;+ let subpixel_shift = params+ .subpixel_variant+ .map(|v| v as f32 / SUBPIXEL_VARIANTS_X as f32);+ let baseline_origin_x = subpixel_shift.x / params.scale_factor;+ let baseline_origin_y = subpixel_shift.y / params.scale_factor;++ let transform = DWRITE_MATRIX {+ m11: params.scale_factor,+ m12: 0.0,+ m21: 0.0,+ m22: params.scale_factor,+ dx: 0.0,+ dy: 0.0,+ };++ let font = &self.fonts[params.font_id.0];+ let glyph_id = [params.glyph_id.0 as u16];+ let advance = [glyph_bounds.size.width.0 as f32];+ let offset = [DWRITE_GLYPH_OFFSET {+ advanceOffset: -glyph_bounds.origin.x.0 as f32 / params.scale_factor,+ ascenderOffset: glyph_bounds.origin.y.0 as f32 / params.scale_factor,+ }];+ let glyph_run = DWRITE_GLYPH_RUN {+ fontFace: ManuallyDrop::new(Some(unsafe { std::ptr::read(&***font.font_face) })),+ fontEmSize: params.font_size.as_f32(),+ glyphCount: 1,+ glyphIndices: glyph_id.as_ptr(),+ glyphAdvances: advance.as_ptr(),+ glyphOffsets: offset.as_ptr(),+ isSideways: BOOL(0),+ bidiLevel: 0,+ };++ // todo: support formats other than COLR+ let color_enumerator = unsafe {+ components.factory.TranslateColorGlyphRun(+ Vector2::new(baseline_origin_x, baseline_origin_y),+ &glyph_run,+ None,+ DWRITE_GLYPH_IMAGE_FORMATS_COLR,+ DWRITE_MEASURING_MODE_NATURAL,+ Some(&transform),+ 0,+ )+ }?;++ let mut glyph_layers = Vec::new();+ let mut alpha_data = Vec::new();+ loop {+ let color_run = unsafe { color_enumerator.GetCurrentRun() }?;+ let color_run = unsafe { &*color_run };+ let image_format = color_run.glyphImageFormat & !DWRITE_GLYPH_IMAGE_FORMATS_TRUETYPE;+ if image_format == DWRITE_GLYPH_IMAGE_FORMATS_COLR {+ let color_analysis = unsafe {+ components.factory.CreateGlyphRunAnalysis(+ &color_run.Base.glyphRun as *const _,+ Some(&transform),+ DWRITE_RENDERING_MODE1_NATURAL_SYMMETRIC,+ DWRITE_MEASURING_MODE_NATURAL,+ DWRITE_GRID_FIT_MODE_DEFAULT,+ DWRITE_TEXT_ANTIALIAS_MODE_GRAYSCALE,+ baseline_origin_x,+ baseline_origin_y,+ )+ }?;++ let color_bounds =+ unsafe { color_analysis.GetAlphaTextureBounds(DWRITE_TEXTURE_ALIASED_1x1) }?;++ let color_size = size(+ color_bounds.right - color_bounds.left,+ color_bounds.bottom - color_bounds.top,+ );+ if color_size.width > 0 && color_size.height > 0 {+ alpha_data.clear();+ alpha_data.resize((color_size.width * color_size.height) as usize, 0);+ unsafe {+ color_analysis.CreateAlphaTexture(+ DWRITE_TEXTURE_ALIASED_1x1,+ &color_bounds,+ &mut alpha_data,+ )+ }?;++ let run_color = {+ let run_color = color_run.Base.runColor;+ Rgba {+ r: run_color.r,+ g: run_color.g,+ b: run_color.b,+ a: run_color.a,+ }+ };+ let bounds = bounds(point(color_bounds.left, color_bounds.top), color_size);+ glyph_layers.push(GlyphLayerTexture::new(+ &self.gpu_state,+ run_color,+ bounds,+ &alpha_data,+ )?);+ }+ }++ let has_next = unsafe { color_enumerator.MoveNext() }+ .map(|e| e.as_bool())+ .unwrap_or(false);+ if !has_next {+ break;+ }+ }++ let gpu_state = &self.gpu_state;++ let render_target_texture = {+ let mut texture = None;+ let desc = D3D11_TEXTURE2D_DESC {+ Width: bitmap_size.width.0 as u32,+ Height: bitmap_size.height.0 as u32,+ MipLevels: 1,+ ArraySize: 1,+ Format: DXGI_FORMAT_B8G8R8A8_UNORM,+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ Usage: D3D11_USAGE_DEFAULT,+ BindFlags: D3D11_BIND_RENDER_TARGET.0 as u32,+ CPUAccessFlags: 0,+ MiscFlags: 0,+ };+ unsafe {+ gpu_state+ .device+ .CreateTexture2D(&desc, None, Some(&mut texture))+ }?;+ texture.unwrap()+ };++ let render_target_view = {+ let desc = D3D11_RENDER_TARGET_VIEW_DESC {+ Format: DXGI_FORMAT_B8G8R8A8_UNORM,+ ViewDimension: D3D11_RTV_DIMENSION_TEXTURE2D,+ Anonymous: D3D11_RENDER_TARGET_VIEW_DESC_0 {+ Texture2D: D3D11_TEX2D_RTV { MipSlice: 0 },+ },+ };+ let mut rtv = None;+ unsafe {+ gpu_state.device.CreateRenderTargetView(+ &render_target_texture,+ Some(&desc),+ Some(&mut rtv),+ )+ }?;+ rtv+ };++ Self::composite_color_layers(+ gpu_state,+ &glyph_layers,+ bitmap_size,+ &render_target_texture,+ &render_target_view,+ )+ }++ fn composite_color_layers(+ gpu_state: &GPUState,+ glyph_layers: &[GlyphLayerTexture],+ bitmap_size: Size<DevicePixels>,+ render_target_texture: &ID3D11Texture2D,+ render_target_view: &Option<ID3D11RenderTargetView>,+ ) -> Result<Vec<u8>> {+ let params_buffer = {+ let desc = D3D11_BUFFER_DESC {+ ByteWidth: std::mem::size_of::<GlyphLayerTextureParams>() as u32,+ Usage: D3D11_USAGE_DYNAMIC,+ BindFlags: D3D11_BIND_CONSTANT_BUFFER.0 as u32,+ CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32,+ MiscFlags: 0,+ StructureByteStride: 0,+ };++ let mut buffer = None;+ unsafe {+ gpu_state+ .device+ .CreateBuffer(&desc, None, Some(&mut buffer))+ }?;+ buffer+ };++ let staging_texture = {+ let mut texture = None;+ let desc = D3D11_TEXTURE2D_DESC {+ Width: bitmap_size.width.0 as u32,+ Height: bitmap_size.height.0 as u32,+ MipLevels: 1,+ ArraySize: 1,+ Format: DXGI_FORMAT_B8G8R8A8_UNORM,+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ Usage: D3D11_USAGE_STAGING,+ BindFlags: 0,+ CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,+ MiscFlags: 0,+ };+ unsafe {+ gpu_state+ .device+ .CreateTexture2D(&desc, None, Some(&mut texture))+ }?;+ texture.unwrap()+ };++ let device_context = &gpu_state.device_context;+ unsafe { device_context.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP) };+ unsafe { device_context.VSSetShader(&gpu_state.vertex_shader, None) };+ unsafe { device_context.PSSetShader(&gpu_state.pixel_shader, None) };+ unsafe {+ device_context.VSSetConstantBuffers(0, Some(std::slice::from_ref(¶ms_buffer)))+ };+ unsafe {+ device_context.PSSetConstantBuffers(0, Some(std::slice::from_ref(¶ms_buffer)))+ };+ unsafe {+ device_context.OMSetRenderTargets(Some(std::slice::from_ref(render_target_view)), None)+ };+ unsafe {+ if let Some(render_target_view) = render_target_view.as_ref() {+ device_context.ClearRenderTargetView(render_target_view, &[0.0, 0.0, 0.0, 0.0]);+ }+ }+ unsafe { device_context.PSSetSamplers(0, Some(std::slice::from_ref(&gpu_state.sampler))) };+ unsafe { device_context.OMSetBlendState(&gpu_state.blend_state, None, 0xffffffff) };++ let crate::FontInfo {+ gamma_ratios,+ grayscale_enhanced_contrast,+ ..+ } = DirectXRenderer::get_font_info();++ for layer in glyph_layers {+ let params = GlyphLayerTextureParams {+ run_color: layer.run_color,+ bounds: layer.bounds,+ gamma_ratios: *gamma_ratios,+ grayscale_enhanced_contrast: *grayscale_enhanced_contrast,+ _pad: [0f32; 3],+ };+ unsafe {+ let mut dest = std::mem::zeroed();+ gpu_state.device_context.Map(+ params_buffer.as_ref().unwrap(),+ 0,+ D3D11_MAP_WRITE_DISCARD,+ 0,+ Some(&mut dest),+ )?;+ std::ptr::copy_nonoverlapping(¶ms as *const _, dest.pData as *mut _, 1);+ gpu_state+ .device_context+ .Unmap(params_buffer.as_ref().unwrap(), 0);+ };++ let texture = [Some(layer.texture_view.clone())];+ unsafe { device_context.PSSetShaderResources(0, Some(&texture)) };++ let viewport = [D3D11_VIEWPORT {+ TopLeftX: layer.bounds.origin.x as f32,+ TopLeftY: layer.bounds.origin.y as f32,+ Width: layer.bounds.size.width as f32,+ Height: layer.bounds.size.height as f32,+ MinDepth: 0.0,+ MaxDepth: 1.0,+ }];+ unsafe { device_context.RSSetViewports(Some(&viewport)) };++ unsafe { device_context.Draw(4, 0) };+ }++ unsafe { device_context.CopyResource(&staging_texture, render_target_texture) };++ let mapped_data = {+ let mut mapped_data = D3D11_MAPPED_SUBRESOURCE::default();+ unsafe {+ device_context.Map(+ &staging_texture,+ 0,+ D3D11_MAP_READ,+ 0,+ Some(&mut mapped_data),+ )+ }?;+ mapped_data+ };+ let mut rasterized =+ vec![0u8; (bitmap_size.width.0 as u32 * bitmap_size.height.0 as u32 * 4) as usize];++ for y in 0..bitmap_size.height.0 as usize {+ let width = bitmap_size.width.0 as usize;+ unsafe {+ std::ptr::copy_nonoverlapping::<u8>(+ (mapped_data.pData as *const u8).byte_add(mapped_data.RowPitch as usize * y),+ rasterized+ .as_mut_ptr()+ .byte_add(width * y * std::mem::size_of::<u32>()),+ width * std::mem::size_of::<u32>(),+ )+ };+ }++ // Release the mapping now that the rows have been copied out; leaving `staging_texture`+ // mapped would leak the mapping and keep the resource pinned for later reuse.+ unsafe { device_context.Unmap(&staging_texture, 0) };++ // Convert from premultiplied to straight alpha+ for chunk in rasterized.chunks_exact_mut(4) {+ let b = chunk[0] as f32;+ let g = chunk[1] as f32;+ let r = chunk[2] as f32;+ let a = chunk[3] as f32;+ if a > 0.0 {+ let inv_a = 255.0 / a;+ chunk[0] = (b * inv_a).clamp(0.0, 255.0) as u8;+ chunk[1] = (g * inv_a).clamp(0.0, 255.0) as u8;+ chunk[2] = (r * inv_a).clamp(0.0, 255.0) as u8;+ }+ }++ Ok(rasterized)+ }++ fn get_typographic_bounds(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Bounds<f32>> {+ unsafe {+ let font = &self.fonts[font_id.0].font_face;+ let glyph_indices = [glyph_id.0 as u16];+ let mut metrics = [DWRITE_GLYPH_METRICS::default()];+ font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;++ let metrics = &metrics[0];+ let advance_width = metrics.advanceWidth as i32;+ let advance_height = metrics.advanceHeight as i32;+ let left_side_bearing = metrics.leftSideBearing;+ let right_side_bearing = metrics.rightSideBearing;+ let top_side_bearing = metrics.topSideBearing;+ let bottom_side_bearing = metrics.bottomSideBearing;+ let vertical_origin_y = metrics.verticalOriginY;++ let y_offset = vertical_origin_y + bottom_side_bearing - advance_height;+ let width = advance_width - (left_side_bearing + right_side_bearing);+ let height = advance_height - (top_side_bearing + bottom_side_bearing);++ Ok(Bounds {+ origin: Point {+ x: left_side_bearing as f32,+ y: y_offset as f32,+ },+ size: Size {+ width: width as f32,+ height: height as f32,+ },+ })+ }+ }++ fn get_advance(&self, font_id: FontId, glyph_id: GlyphId) -> Result<Size<f32>> {+ unsafe {+ let font = &self.fonts[font_id.0].font_face;+ let glyph_indices = [glyph_id.0 as u16];+ let mut metrics = [DWRITE_GLYPH_METRICS::default()];+ font.GetDesignGlyphMetrics(glyph_indices.as_ptr(), 1, metrics.as_mut_ptr(), false)?;++ let metrics = &metrics[0];++ Ok(Size {+ width: metrics.advanceWidth as f32,+ height: 0.0,+ })+ }+ }++ fn all_font_names(&self, components: &DirectWriteComponents) -> Vec<String> {+ let mut result =+ get_font_names_from_collection(&self.system_font_collection, &components.locale);+ result.extend(get_font_names_from_collection(+ &self.custom_font_collection,+ &components.locale,+ ));+ result+ }++ fn handle_gpu_lost(&mut self, directx_devices: &DirectXDevices) -> Result<()> {+ try_to_recover_from_device_lost(|| {+ GPUState::new(directx_devices).context("Recreating GPU state for DirectWrite")+ })+ .map(|gpu_state| self.gpu_state = gpu_state)+ }+}++struct GlyphLayerTexture {+ run_color: Rgba,+ bounds: Bounds<i32>,+ texture_view: ID3D11ShaderResourceView,+ // holding on to the texture to not RAII drop it+ _texture: ID3D11Texture2D,+}++impl GlyphLayerTexture {+ fn new(+ gpu_state: &GPUState,+ run_color: Rgba,+ bounds: Bounds<i32>,+ alpha_data: &[u8],+ ) -> Result<Self> {+ let texture_size = bounds.size;++ let desc = D3D11_TEXTURE2D_DESC {+ Width: texture_size.width as u32,+ Height: texture_size.height as u32,+ MipLevels: 1,+ ArraySize: 1,+ Format: DXGI_FORMAT_R8_UNORM,+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ Usage: D3D11_USAGE_DEFAULT,+ BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,+ CPUAccessFlags: 0,+ MiscFlags: 0,+ };++ let texture = {+ let mut texture: Option<ID3D11Texture2D> = None;+ unsafe {+ gpu_state+ .device+ .CreateTexture2D(&desc, None, Some(&mut texture))?+ };+ texture.unwrap()+ };+ let texture_view = {+ let mut view: Option<ID3D11ShaderResourceView> = None;+ unsafe {+ gpu_state+ .device+ .CreateShaderResourceView(&texture, None, Some(&mut view))?+ };+ view.unwrap()+ };++ unsafe {+ gpu_state.device_context.UpdateSubresource(+ &texture,+ 0,+ None,+ alpha_data.as_ptr() as _,+ texture_size.width as u32,+ 0,+ )+ };++ Ok(GlyphLayerTexture {+ run_color,+ bounds,+ texture_view,+ _texture: texture,+ })+ }+}++#[repr(C)]+struct GlyphLayerTextureParams {+ bounds: Bounds<i32>,+ run_color: Rgba,+ gamma_ratios: [f32; 4],+ grayscale_enhanced_contrast: f32,+ _pad: [f32; 3],+}++struct TextRendererWrapper(IDWriteTextRenderer);++impl TextRendererWrapper {+ fn new(locale_str: HSTRING) -> Self {+ let inner = TextRenderer::new(locale_str);+ TextRendererWrapper(inner.into())+ }+}++#[implement(IDWriteTextRenderer)]+struct TextRenderer {+ locale: HSTRING,+}++impl TextRenderer {+ fn new(locale: HSTRING) -> Self {+ TextRenderer { locale }+ }+}++struct RendererContext<'t, 'a, 'b> {+ text_system: &'t mut DirectWriteState,+ components: &'a DirectWriteComponents,+ index_converter: StringIndexConverter<'a>,+ runs: &'b mut Vec<ShapedRun>,+ width: f32,+}++#[derive(Debug)]+struct ClusterAnalyzer<'t> {+ utf16_idx: usize,+ glyph_idx: usize,+ glyph_count: usize,+ cluster_map: &'t [u16],+}++impl<'t> ClusterAnalyzer<'t> {+ fn new(cluster_map: &'t [u16], glyph_count: usize) -> Self {+ ClusterAnalyzer {+ utf16_idx: 0,+ glyph_idx: 0,+ glyph_count,+ cluster_map,+ }+ }+}++impl Iterator for ClusterAnalyzer<'_> {+ type Item = (usize, usize);++ fn next(&mut self) -> Option<(usize, usize)> {+ if self.utf16_idx >= self.cluster_map.len() {+ return None; // No more clusters+ }+ let start_utf16_idx = self.utf16_idx;+ let current_glyph = self.cluster_map[start_utf16_idx] as usize;++ // Find the end of current cluster (where glyph index changes)+ let mut end_utf16_idx = start_utf16_idx + 1;+ while end_utf16_idx < self.cluster_map.len()+ && self.cluster_map[end_utf16_idx] as usize == current_glyph+ {+ end_utf16_idx += 1;+ }++ let utf16_len = end_utf16_idx - start_utf16_idx;++ // Calculate glyph count for this cluster+ let next_glyph = if end_utf16_idx < self.cluster_map.len() {+ self.cluster_map[end_utf16_idx] as usize+ } else {+ self.glyph_count+ };++ let glyph_count = next_glyph - current_glyph;++ // Update state for next call+ self.utf16_idx = end_utf16_idx;+ self.glyph_idx = next_glyph;++ Some((utf16_len, glyph_count))+ }+}++#[allow(non_snake_case)]+impl IDWritePixelSnapping_Impl for TextRenderer_Impl {+ fn IsPixelSnappingDisabled(+ &self,+ _clientdrawingcontext: *const ::core::ffi::c_void,+ ) -> windows::core::Result<BOOL> {+ Ok(BOOL(0))+ }++ fn GetCurrentTransform(+ &self,+ _clientdrawingcontext: *const ::core::ffi::c_void,+ transform: *mut DWRITE_MATRIX,+ ) -> windows::core::Result<()> {+ unsafe {+ *transform = DWRITE_MATRIX {+ m11: 1.0,+ m12: 0.0,+ m21: 0.0,+ m22: 1.0,+ dx: 0.0,+ dy: 0.0,+ };+ }+ Ok(())+ }++ fn GetPixelsPerDip(+ &self,+ _clientdrawingcontext: *const ::core::ffi::c_void,+ ) -> windows::core::Result<f32> {+ Ok(1.0)+ }+}++#[allow(non_snake_case)]+impl IDWriteTextRenderer_Impl for TextRenderer_Impl {+ fn DrawGlyphRun(+ &self,+ clientdrawingcontext: *const ::core::ffi::c_void,+ _baselineoriginx: f32,+ _baselineoriginy: f32,+ _measuringmode: DWRITE_MEASURING_MODE,+ glyphrun: *const DWRITE_GLYPH_RUN,+ glyphrundescription: *const DWRITE_GLYPH_RUN_DESCRIPTION,+ _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,+ ) -> windows::core::Result<()> {+ let glyphrun = unsafe { &*glyphrun };+ let glyph_count = glyphrun.glyphCount as usize;+ if glyph_count == 0 {+ return Ok(());+ }+ let desc = unsafe { &*glyphrundescription };+ let context = unsafe { &mut *(clientdrawingcontext.cast::<RendererContext>().cast_mut()) };+ let Some(font_face) = glyphrun.fontFace.as_ref() else {+ return Ok(());+ };+ // This `cast()` action here should never fail since we are running on Win10+, and+ // `IDWriteFontFace3` requires Win10+ let Ok(font_face) = &font_face.cast::<IDWriteFontFace3>() else {+ return Err(Error::new(+ DWRITE_E_UNSUPPORTEDOPERATION,+ "Failed to cast font face",+ ));+ };++ let font_face_key = font_face.cast::<IUnknown>().unwrap().as_raw().addr();+ let font_id = context+ .text_system+ .font_info_cache+ .get(&font_face_key)+ .copied()+ // in some circumstances, we might be getting served a FontFace that we did not create ourselves+ // so create a new font from it and cache it accordingly. The usual culprit here seems to be Segoe UI Symbol+ .map_or_else(+ || {+ let font = font_face_to_font(font_face, &self.locale)+ .ok_or_else(|| Error::new(DWRITE_E_NOFONT, "Failed to create font"))?;+ let font_id = match context.text_system.font_to_font_id.get(&font) {+ Some(&font_id) => font_id,+ None => context+ .text_system+ .select_and_cache_font(context.components, &font)+ .ok_or_else(|| Error::new(DWRITE_E_NOFONT, "Failed to create font"))?,+ };+ context+ .text_system+ .font_info_cache+ .insert(font_face_key, font_id);+ windows::core::Result::Ok(font_id)+ },+ Ok,+ )?;++ let color_font = unsafe { font_face.IsColorFont().as_bool() };++ let glyph_ids = unsafe {+ slice_from_nullable(+ glyphrun.glyphIndices,+ glyph_count,+ "DirectWrite returned a null glyph indices array",+ )?+ };+ let glyph_advances = unsafe {+ slice_from_nullable(+ glyphrun.glyphAdvances,+ glyph_count,+ "DirectWrite returned a null glyph advances array",+ )?+ };+ let glyph_offsets = unsafe {+ slice_from_nullable(+ glyphrun.glyphOffsets,+ glyph_count,+ "DirectWrite returned a null glyph offsets array",+ )?+ };+ let cluster_map = unsafe {+ slice_from_nullable(+ desc.clusterMap,+ desc.stringLength as usize,+ "DirectWrite returned a null cluster map",+ )?+ };++ let cluster_analyzer = ClusterAnalyzer::new(cluster_map, glyph_count);+ let mut utf16_idx = desc.textPosition as usize;+ let mut glyph_idx = 0;+ let mut glyphs = Vec::with_capacity(glyph_count);+ for (cluster_utf16_len, cluster_glyph_count) in cluster_analyzer {+ context.index_converter.advance_to_utf16_ix(utf16_idx);+ utf16_idx += cluster_utf16_len;+ for (cluster_glyph_idx, glyph_id) in glyph_ids+ [glyph_idx..(glyph_idx + cluster_glyph_count)]+ .iter()+ .enumerate()+ {+ let id = GlyphId(*glyph_id as u32);+ let is_emoji =+ color_font && is_color_glyph(font_face, id, &context.components.factory);+ let this_glyph_idx = glyph_idx + cluster_glyph_idx;+ glyphs.push(ShapedGlyph {+ id,+ position: point(+ px(context.width + glyph_offsets[this_glyph_idx].advanceOffset),+ px(-glyph_offsets[this_glyph_idx].ascenderOffset),+ ),+ index: context.index_converter.utf8_ix,+ is_emoji,+ });+ context.width += glyph_advances[this_glyph_idx];+ }+ glyph_idx += cluster_glyph_count;+ }+ context.runs.push(ShapedRun { font_id, glyphs });+ Ok(())+ }++ fn DrawUnderline(+ &self,+ _clientdrawingcontext: *const ::core::ffi::c_void,+ _baselineoriginx: f32,+ _baselineoriginy: f32,+ _underline: *const DWRITE_UNDERLINE,+ _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,+ ) -> windows::core::Result<()> {+ Err(windows::core::Error::new(+ E_NOTIMPL,+ "DrawUnderline unimplemented",+ ))+ }++ fn DrawStrikethrough(+ &self,+ _clientdrawingcontext: *const ::core::ffi::c_void,+ _baselineoriginx: f32,+ _baselineoriginy: f32,+ _strikethrough: *const DWRITE_STRIKETHROUGH,+ _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,+ ) -> windows::core::Result<()> {+ Err(windows::core::Error::new(+ E_NOTIMPL,+ "DrawStrikethrough unimplemented",+ ))+ }++ fn DrawInlineObject(+ &self,+ _clientdrawingcontext: *const ::core::ffi::c_void,+ _originx: f32,+ _originy: f32,+ _inlineobject: windows::core::Ref<IDWriteInlineObject>,+ _issideways: BOOL,+ _isrighttoleft: BOOL,+ _clientdrawingeffect: windows::core::Ref<windows::core::IUnknown>,+ ) -> windows::core::Result<()> {+ Err(windows::core::Error::new(+ E_NOTIMPL,+ "DrawInlineObject unimplemented",+ ))+ }+}++/// Interprets an optional DirectWrite array pointer as a slice, treating a+/// null pointer with a zero length as an empty slice. A null pointer with a+/// nonzero length fails with `null_error_message`.+///+/// # Safety+///+/// When `ptr` is non-null, the caller must guarantee that it points to a valid+/// array of at least `len` elements that outlives the returned slice.+unsafe fn slice_from_nullable<'a, T>(+ ptr: *const T,+ len: usize,+ null_error_message: &str,+) -> windows::core::Result<&'a [T]> {+ if ptr.is_null() {+ if len != 0 {+ return Err(Error::new(E_INVALIDARG, null_error_message));+ }+ Ok(&[])+ } else {+ Ok(unsafe { std::slice::from_raw_parts(ptr, len) })+ }+}++struct StringIndexConverter<'a> {+ text: &'a str,+ utf8_ix: usize,+ utf16_ix: usize,+}++impl<'a> StringIndexConverter<'a> {+ fn new(text: &'a str) -> Self {+ Self {+ text,+ utf8_ix: 0,+ utf16_ix: 0,+ }+ }++ #[allow(dead_code)]+ fn advance_to_utf8_ix(&mut self, utf8_target: usize) {+ for (ix, c) in self.text[self.utf8_ix..].char_indices() {+ if self.utf8_ix + ix >= utf8_target {+ self.utf8_ix += ix;+ return;+ }+ self.utf16_ix += c.len_utf16();+ }+ self.utf8_ix = self.text.len();+ }++ fn advance_to_utf16_ix(&mut self, utf16_target: usize) {+ for (ix, c) in self.text[self.utf8_ix..].char_indices() {+ if self.utf16_ix >= utf16_target {+ self.utf8_ix += ix;+ return;+ }+ self.utf16_ix += c.len_utf16();+ }+ self.utf8_ix = self.text.len();+ }+}++fn font_style_to_dwrite(style: FontStyle) -> DWRITE_FONT_STYLE {+ match style {+ FontStyle::Normal => DWRITE_FONT_STYLE_NORMAL,+ FontStyle::Italic => DWRITE_FONT_STYLE_ITALIC,+ FontStyle::Oblique => DWRITE_FONT_STYLE_OBLIQUE,+ }+}++fn font_style_from_dwrite(value: DWRITE_FONT_STYLE) -> FontStyle {+ match value.0 {+ 0 => FontStyle::Normal,+ 1 => FontStyle::Italic,+ 2 => FontStyle::Oblique,+ _ => unreachable!(),+ }+}++fn font_weight_to_dwrite(weight: FontWeight) -> DWRITE_FONT_WEIGHT {+ DWRITE_FONT_WEIGHT(weight.0 as i32)+}++fn font_weight_from_dwrite(value: DWRITE_FONT_WEIGHT) -> FontWeight {+ FontWeight(value.0 as f32)+}++fn get_font_names_from_collection(+ collection: &IDWriteFontCollection1,+ locale: &HSTRING,+) -> Vec<String> {+ unsafe {+ let mut result = Vec::new();+ let family_count = collection.GetFontFamilyCount();+ for index in 0..family_count {+ let Some(font_family) = collection.GetFontFamily(index).log_err() else {+ continue;+ };+ let Some(localized_family_name) = font_family.GetFamilyNames().log_err() else {+ continue;+ };+ let Some(family_name) = get_name(localized_family_name, locale).log_err() else {+ continue;+ };+ result.push(family_name);+ }++ result+ }+}++fn font_face_to_font(font_face: &IDWriteFontFace3, locale: &HSTRING) -> Option<Font> {+ let localized_family_name = unsafe { font_face.GetFamilyNames().log_err() }?;+ let family_name = get_name(localized_family_name, locale).log_err()?;+ let weight = unsafe { font_face.GetWeight() };+ let style = unsafe { font_face.GetStyle() };+ Some(Font {+ family: family_name.into(),+ features: FontFeatures::default(),+ weight: font_weight_from_dwrite(weight),+ style: font_style_from_dwrite(style),+ fallbacks: None,+ })+}++// https://learn.microsoft.com/en-us/windows/win32/api/dwrite/ne-dwrite-dwrite_font_feature_tag+fn apply_font_features(+ direct_write_features: &IDWriteTypography,+ features: &FontFeatures,+) -> Result<()> {+ let tag_values = features.tag_value_list();++ // All of these features are enabled by default by DirectWrite.+ // If you want to (and can) peek into the source of DirectWrite+ let mut feature_liga = make_direct_write_feature("liga", 1);+ let mut feature_clig = make_direct_write_feature("clig", 1);+ let mut feature_calt = make_direct_write_feature("calt", 1);++ for (tag, value) in tag_values {+ if tag.as_str() == "liga" && *value == 0 {+ feature_liga.parameter = 0;+ continue;+ }+ if tag.as_str() == "clig" && *value == 0 {+ feature_clig.parameter = 0;+ continue;+ }+ if tag.as_str() == "calt" && *value == 0 {+ feature_calt.parameter = 0;+ continue;+ }++ unsafe {+ direct_write_features.AddFontFeature(make_direct_write_feature(tag, *value))?;+ }+ }+ unsafe {+ direct_write_features.AddFontFeature(feature_liga)?;+ direct_write_features.AddFontFeature(feature_clig)?;+ direct_write_features.AddFontFeature(feature_calt)?;+ }++ Ok(())+}++#[inline]+const fn make_direct_write_feature(feature_name: &str, parameter: u32) -> DWRITE_FONT_FEATURE {+ let tag = make_direct_write_tag(feature_name);+ DWRITE_FONT_FEATURE {+ nameTag: tag,+ parameter,+ }+}++#[inline]+const fn make_open_type_tag(tag_name: &str) -> u32 {+ let bytes = tag_name.as_bytes();+ debug_assert!(bytes.len() == 4);+ u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]])+}++#[inline]+const fn make_direct_write_tag(tag_name: &str) -> DWRITE_FONT_FEATURE_TAG {+ DWRITE_FONT_FEATURE_TAG(make_open_type_tag(tag_name))+}++#[inline]+fn get_name(string: IDWriteLocalizedStrings, locale: &HSTRING) -> Result<String> {+ let mut locale_name_index = 0u32;+ let mut exists = BOOL(0);+ unsafe { string.FindLocaleName(locale, &mut locale_name_index, &mut exists as _)? };+ if !exists.as_bool() {+ unsafe {+ string.FindLocaleName(+ DEFAULT_LOCALE_NAME,+ &mut locale_name_index as _,+ &mut exists as _,+ )?+ };+ anyhow::ensure!(exists.as_bool(), "No localised string for {locale}");+ }++ let name_length = unsafe { string.GetStringLength(locale_name_index) }? as usize;+ let mut name_vec = vec![0u16; name_length + 1];+ unsafe {+ string.GetString(locale_name_index, &mut name_vec)?;+ }++ Ok(String::from_utf16_lossy(&name_vec[..name_length]))+}++fn get_system_subpixel_rendering() -> bool {+ let mut value = c_uint::default();+ let result = unsafe {+ SystemParametersInfoW(+ SPI_GETFONTSMOOTHINGTYPE,+ 0,+ Some((&mut value) as *mut c_uint as *mut c_void),+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),+ )+ };+ if result.log_err().is_some() {+ value == FE_FONTSMOOTHINGCLEARTYPE+ } else {+ true+ }+}++fn get_system_ui_font_name() -> SharedString {+ unsafe {+ let mut info: LOGFONTW = std::mem::zeroed();+ let font_family = if SystemParametersInfoW(+ SPI_GETICONTITLELOGFONT,+ std::mem::size_of::<LOGFONTW>() as u32,+ Some(&mut info as *mut _ as _),+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS(0),+ )+ .log_err()+ .is_none()+ {+ // https://learn.microsoft.com/en-us/windows/win32/uxguide/vis-fonts+ // Segoe UI is the Windows font intended for user interface text strings.+ "Segoe UI".into()+ } else {+ let font_name = String::from_utf16_lossy(&info.lfFaceName);+ font_name.trim_matches(char::from(0)).to_owned().into()+ };+ log::info!("Use {} as UI font.", font_family);+ font_family+ }+}++// One would think that with newer DirectWrite method: IDWriteFontFace4::GetGlyphImageFormats+// but that doesn't seem to work for some glyphs, say ❤+fn is_color_glyph(+ font_face: &IDWriteFontFace3,+ glyph_id: GlyphId,+ factory: &IDWriteFactory5,+) -> bool {+ let glyph_run = DWRITE_GLYPH_RUN {+ fontFace: ManuallyDrop::new(Some(unsafe { std::ptr::read(&****font_face) })),+ fontEmSize: 14.0,+ glyphCount: 1,+ glyphIndices: &(glyph_id.0 as u16),+ glyphAdvances: &0.0,+ glyphOffsets: &DWRITE_GLYPH_OFFSET {+ advanceOffset: 0.0,+ ascenderOffset: 0.0,+ },+ isSideways: BOOL(0),+ bidiLevel: 0,+ };+ unsafe {+ factory.TranslateColorGlyphRun(+ Vector2::default(),+ &glyph_run as _,+ None,+ DWRITE_GLYPH_IMAGE_FORMATS_COLR+ | DWRITE_GLYPH_IMAGE_FORMATS_SVG+ | DWRITE_GLYPH_IMAGE_FORMATS_PNG+ | DWRITE_GLYPH_IMAGE_FORMATS_JPEG+ | DWRITE_GLYPH_IMAGE_FORMATS_PREMULTIPLIED_B8G8R8A8,+ DWRITE_MEASURING_MODE_NATURAL,+ None,+ 0,+ )+ }+ .is_ok()+}++const DEFAULT_LOCALE_NAME: PCWSTR = windows::core::w!("en-US");++#[cfg(test)]+mod tests {+ use super::{DirectWriteState, DirectWriteTextSystem, GPUState, GlyphLayerTexture};+ use crate::direct_write::ClusterAnalyzer;+ use crate::directx_devices::DirectXDevices;+ use anyhow::Result;+ use gpui::{+ DevicePixels, Font, PlatformTextSystem, RenderGlyphParams, Rgba, bounds, point, px, size,+ };+ use std::ffi::c_void;+ use windows::Win32::Graphics::Direct3D11::{+ D3D11_BIND_RENDER_TARGET, D3D11_RENDER_TARGET_VIEW_DESC, D3D11_RENDER_TARGET_VIEW_DESC_0,+ D3D11_RTV_DIMENSION_TEXTURE2D, D3D11_SUBRESOURCE_DATA, D3D11_TEX2D_RTV,+ D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT,+ };+ use windows::Win32::Graphics::Dxgi::Common::{DXGI_FORMAT_B8G8R8A8_UNORM, DXGI_SAMPLE_DESC};++ #[test]+ fn test_cluster_map() {+ let cluster_map = [0];+ let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);+ let next = analyzer.next();+ assert_eq!(next, Some((1, 1)));+ let next = analyzer.next();+ assert_eq!(next, None);++ let cluster_map = [0, 1, 2];+ let mut analyzer = ClusterAnalyzer::new(&cluster_map, 3);+ let next = analyzer.next();+ assert_eq!(next, Some((1, 1)));+ let next = analyzer.next();+ assert_eq!(next, Some((1, 1)));+ let next = analyzer.next();+ assert_eq!(next, Some((1, 1)));+ let next = analyzer.next();+ assert_eq!(next, None);+ // 👨👩👧👦👩💻+ let cluster_map = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 4, 4, 4, 4];+ let mut analyzer = ClusterAnalyzer::new(&cluster_map, 5);+ let next = analyzer.next();+ assert_eq!(next, Some((11, 4)));+ let next = analyzer.next();+ assert_eq!(next, Some((5, 1)));+ let next = analyzer.next();+ assert_eq!(next, None);+ // 👩💻+ let cluster_map = [0, 0, 0, 0, 0];+ let mut analyzer = ClusterAnalyzer::new(&cluster_map, 1);+ let next = analyzer.next();+ assert_eq!(next, Some((5, 1)));+ let next = analyzer.next();+ assert_eq!(next, None);+ }++ #[test]+ fn color_emoji_rasterization_is_stable_across_batches() -> Result<()> {+ let devices = DirectXDevices::new()?;+ let text_system = DirectWriteTextSystem::new(&devices)?;++ let font = Font {+ family: "Segoe UI Emoji".into(),+ ..Default::default()+ };+ let font_id = text_system.font_id(&font)?;++ let mut params_list = Vec::new();+ for ch in ['🫠', '🥹', '🧗', '🏋', '🚀', '🥺'] {+ let Some(glyph_id) = text_system.glyph_for_char(font_id, ch) else {+ log::info!("no glyph found for {ch}");+ continue;+ };+ let params = RenderGlyphParams {+ font_id,+ glyph_id,+ font_size: px(48.0),+ subpixel_variant: point(0u8, 0u8),+ scale_factor: 1.0,+ is_emoji: true,+ subpixel_rendering: false,+ dilation: 0,+ };+ let raster_bounds = text_system.glyph_raster_bounds(¶ms)?;+ if raster_bounds.size.width.0 == 0 || raster_bounds.size.height.0 == 0 {+ log::info!("raster bounds are empty for {ch}");+ continue;+ }+ params_list.push((params, raster_bounds));+ }+ assert!(!params_list.is_empty());++ let first: Vec<_> = params_list+ .iter()+ .map(|(params, bounds)| text_system.rasterize_glyph(params, *bounds))+ .collect::<Result<_>>()?;++ // Churn the texture heap with further rasterization passes. If the color+ // compositing leaks leftover texture data (the render target is not cleared),+ // the second batch can pick up different contents and differ from the first.+ // With an explicit clear both batches are deterministic and identical.+ for _ in 0..3 {+ for (params, bounds) in ¶ms_list {+ text_system.rasterize_glyph(params, *bounds)?;+ }+ }+ let second: Vec<_> = params_list+ .iter()+ .map(|(params, bounds)| text_system.rasterize_glyph(params, *bounds))+ .collect::<Result<_>>()?;++ assert_eq!(+ first, second,+ "color glyph rasterization changed between batches; \+ render target contents are leaking into the glyph bitmaps"+ );+ Ok(())+ }++ #[test]+ fn color_emoji_composites_over_cleared_texture() -> Result<()> {+ let devices = DirectXDevices::new()?;+ let gpu_state = GPUState::new(&devices)?;++ const SIZE: u32 = 32;+ // Seed the render target with solid red so that any texel which the+ // compositing pass fails to clear/overwrite remains identifiable after+ // the readback.+ let poison = {+ let mut v = vec![0u8; (SIZE * SIZE * 4) as usize];+ for pixel in v.chunks_exact_mut(4) {+ pixel[2] = 255;+ pixel[3] = 255;+ }+ v+ };+ let desc = D3D11_TEXTURE2D_DESC {+ Width: SIZE,+ Height: SIZE,+ MipLevels: 1,+ ArraySize: 1,+ Format: DXGI_FORMAT_B8G8R8A8_UNORM,+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ Usage: D3D11_USAGE_DEFAULT,+ BindFlags: D3D11_BIND_RENDER_TARGET.0 as u32,+ CPUAccessFlags: 0,+ MiscFlags: 0,+ };+ let initial_data = D3D11_SUBRESOURCE_DATA {+ pSysMem: poison.as_ptr() as *const c_void,+ SysMemPitch: SIZE * 4,+ SysMemSlicePitch: 0,+ };+ let texture = unsafe {+ let mut texture = None;+ gpu_state+ .device+ .CreateTexture2D(&desc, Some(&initial_data), Some(&mut texture))?;+ texture.unwrap()+ };+ let render_target_view = unsafe {+ let desc = D3D11_RENDER_TARGET_VIEW_DESC {+ Format: DXGI_FORMAT_B8G8R8A8_UNORM,+ ViewDimension: D3D11_RTV_DIMENSION_TEXTURE2D,+ Anonymous: D3D11_RENDER_TARGET_VIEW_DESC_0 {+ Texture2D: D3D11_TEX2D_RTV { MipSlice: 0 },+ },+ };+ let mut rtv = None;+ gpu_state+ .device+ .CreateRenderTargetView(&texture, Some(&desc), Some(&mut rtv))?;+ rtv.unwrap()+ };++ // A single opaque layer in the top-left corner; the bottom-right corner+ // of the texture is covered by no layer at all.+ let layer_alpha = vec![255u8; 4 * 4];+ let layer = GlyphLayerTexture::new(+ &gpu_state,+ Rgba {+ r: 1.0,+ g: 1.0,+ b: 1.0,+ a: 1.0,+ },+ bounds(point(0, 0), size(4, 4)),+ &layer_alpha,+ )?;++ let rasterized = DirectWriteState::composite_color_layers(+ &gpu_state,+ std::slice::from_ref(&layer),+ size(DevicePixels(SIZE as i32), DevicePixels(SIZE as i32)),+ &texture,+ &Some(render_target_view),+ )?;++ let corner = (SIZE as usize - 1 + (SIZE as usize - 1) * SIZE as usize) * 4;+ assert_eq!(+ &rasterized[corner..corner + 4],+ &[0, 0, 0, 0],+ "uncovered texel retained the poison from the uninitialized render target"+ );+ Ok(())+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/directx_atlas.rs b/native/vendor/wu/crates/gpui_windows/src/directx_atlas.rsnew file mode 100644index 00000000000..84160cb21fd--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/directx_atlas.rs@@ -0,0 +1,421 @@+use collections::FxHashMap;+use etagere::BucketedAtlasAllocator;+use parking_lot::Mutex;+use windows::Win32::Graphics::{+ Direct3D11::{+ D3D11_BIND_SHADER_RESOURCE, D3D11_BOX, D3D11_TEXTURE2D_DESC, D3D11_USAGE_DEFAULT,+ ID3D11Device, ID3D11DeviceContext, ID3D11ShaderResourceView, ID3D11Texture2D,+ },+ Dxgi::Common::*,+};++use gpui::{+ AtlasKey, AtlasTextureId, AtlasTextureKind, AtlasTextureList, AtlasTile, Bounds, DevicePixels,+ PlatformAtlas, Point, Size,+};++pub(crate) struct DirectXAtlas(Mutex<DirectXAtlasState>);++struct DirectXAtlasState {+ device: ID3D11Device,+ device_context: ID3D11DeviceContext,+ monochrome_textures: AtlasTextureList<DirectXAtlasTexture>,+ polychrome_textures: AtlasTextureList<DirectXAtlasTexture>,+ subpixel_textures: AtlasTextureList<DirectXAtlasTexture>,+ tiles_by_key: FxHashMap<AtlasKey, AtlasTile>,+}++struct DirectXAtlasTexture {+ id: AtlasTextureId,+ bytes_per_pixel: u32,+ allocator: BucketedAtlasAllocator,+ texture: ID3D11Texture2D,+ view: [Option<ID3D11ShaderResourceView>; 1],+ live_atlas_keys: u32,+}++impl DirectXAtlas {+ pub(crate) fn new(device: &ID3D11Device, device_context: &ID3D11DeviceContext) -> Self {+ DirectXAtlas(Mutex::new(DirectXAtlasState {+ device: device.clone(),+ device_context: device_context.clone(),+ monochrome_textures: Default::default(),+ polychrome_textures: Default::default(),+ subpixel_textures: Default::default(),+ tiles_by_key: Default::default(),+ }))+ }++ /// Returns the view backing `id`, or `None` once every tile in it has been+ /// removed. A scene can still reference such a texture when a cached view+ /// replays a paint from before the image was dropped, so callers must skip+ /// those sprites rather than assume the texture exists.+ pub(crate) fn get_texture_view(+ &self,+ id: AtlasTextureId,+ ) -> Option<[Option<ID3D11ShaderResourceView>; 1]> {+ let lock = self.0.lock();+ let texture = lock.texture(id)?;+ Some(texture.view.clone())+ }++ pub(crate) fn handle_device_lost(+ &self,+ device: &ID3D11Device,+ device_context: &ID3D11DeviceContext,+ ) {+ let mut lock = self.0.lock();+ lock.device = device.clone();+ lock.device_context = device_context.clone();+ lock.monochrome_textures = AtlasTextureList::default();+ lock.polychrome_textures = AtlasTextureList::default();+ lock.subpixel_textures = AtlasTextureList::default();+ lock.tiles_by_key.clear();+ }+}++impl PlatformAtlas for DirectXAtlas {+ fn get_or_insert_with<'a>(+ &self,+ key: &AtlasKey,+ build: &mut dyn FnMut() -> anyhow::Result<+ Option<(Size<DevicePixels>, std::borrow::Cow<'a, [u8]>)>,+ >,+ ) -> anyhow::Result<Option<AtlasTile>> {+ let mut lock = self.0.lock();+ if let Some(tile) = lock.tiles_by_key.get(key) {+ Ok(Some(*tile))+ } else {+ let Some((size, bytes)) = build()? else {+ return Ok(None);+ };+ let tile = lock+ .allocate(size, key.texture_kind())+ .ok_or_else(|| anyhow::anyhow!("failed to allocate"))?;+ let texture = lock+ .texture(tile.texture_id)+ .ok_or_else(|| anyhow::anyhow!("allocated tile refers to a missing texture"))?;+ texture.upload(&lock.device_context, tile.bounds, &bytes);+ lock.tiles_by_key.insert(key.clone(), tile);+ Ok(Some(tile))+ }+ }++ fn remove(&self, key: &AtlasKey) {+ let mut lock = self.0.lock();++ let Some(tile) = lock.tiles_by_key.remove(key) else {+ return;+ };+ let id = tile.texture_id;++ let textures = match id.kind {+ AtlasTextureKind::Monochrome => &mut lock.monochrome_textures,+ AtlasTextureKind::Polychrome => &mut lock.polychrome_textures,+ AtlasTextureKind::Subpixel => &mut lock.subpixel_textures,+ };++ let Some(texture_slot) = textures.textures.get_mut(id.index as usize) else {+ return;+ };++ if let Some(mut texture) = texture_slot.take() {+ texture.allocator.deallocate(tile.tile_id.into());+ texture.decrement_ref_count();+ if texture.is_unreferenced() {+ textures.free_list.push(texture.id.index as usize);+ } else {+ *texture_slot = Some(texture);+ }+ }+ }+}++impl DirectXAtlasState {+ fn allocate(+ &mut self,+ size: Size<DevicePixels>,+ texture_kind: AtlasTextureKind,+ ) -> Option<AtlasTile> {+ {+ let textures = match texture_kind {+ AtlasTextureKind::Monochrome => &mut self.monochrome_textures,+ AtlasTextureKind::Polychrome => &mut self.polychrome_textures,+ AtlasTextureKind::Subpixel => &mut self.subpixel_textures,+ };++ if let Some(tile) = textures+ .iter_mut()+ .rev()+ .find_map(|texture| texture.allocate(size))+ {+ return Some(tile);+ }+ }++ let texture = self.push_texture(size, texture_kind)?;+ texture.allocate(size)+ }++ fn push_texture(+ &mut self,+ min_size: Size<DevicePixels>,+ kind: AtlasTextureKind,+ ) -> Option<&mut DirectXAtlasTexture> {+ const DEFAULT_ATLAS_SIZE: Size<DevicePixels> = Size {+ width: DevicePixels(1024),+ height: DevicePixels(1024),+ };+ // Max texture size for DirectX. See:+ // https://learn.microsoft.com/en-us/windows/win32/direct3d11/overviews-direct3d-11-resources-limits+ const MAX_ATLAS_SIZE: Size<DevicePixels> = Size {+ width: DevicePixels(16384),+ height: DevicePixels(16384),+ };+ let size = min_size.min(&MAX_ATLAS_SIZE).max(&DEFAULT_ATLAS_SIZE);+ let pixel_format;+ let bind_flag;+ let bytes_per_pixel;+ match kind {+ AtlasTextureKind::Monochrome => {+ pixel_format = DXGI_FORMAT_R8_UNORM;+ bind_flag = D3D11_BIND_SHADER_RESOURCE;+ bytes_per_pixel = 1;+ }+ AtlasTextureKind::Polychrome => {+ pixel_format = DXGI_FORMAT_B8G8R8A8_UNORM;+ bind_flag = D3D11_BIND_SHADER_RESOURCE;+ bytes_per_pixel = 4;+ }+ AtlasTextureKind::Subpixel => {+ pixel_format = DXGI_FORMAT_R8G8B8A8_UNORM;+ bind_flag = D3D11_BIND_SHADER_RESOURCE;+ bytes_per_pixel = 4;+ }+ }+ let texture_desc = D3D11_TEXTURE2D_DESC {+ Width: size.width.0 as u32,+ Height: size.height.0 as u32,+ MipLevels: 1,+ ArraySize: 1,+ Format: pixel_format,+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ Usage: D3D11_USAGE_DEFAULT,+ BindFlags: bind_flag.0 as u32,+ CPUAccessFlags: 0,+ MiscFlags: 0,+ };+ let mut texture: Option<ID3D11Texture2D> = None;+ unsafe {+ // This only returns None if the device is lost, which we will recreate later.+ // So it's ok to return None here.+ self.device+ .CreateTexture2D(&texture_desc, None, Some(&mut texture))+ .ok()?;+ }+ let texture = texture.unwrap();++ let texture_list = match kind {+ AtlasTextureKind::Monochrome => &mut self.monochrome_textures,+ AtlasTextureKind::Polychrome => &mut self.polychrome_textures,+ AtlasTextureKind::Subpixel => &mut self.subpixel_textures,+ };+ let index = texture_list.free_list.pop();+ let view = unsafe {+ let mut view = None;+ self.device+ .CreateShaderResourceView(&texture, None, Some(&mut view))+ .ok()?;+ [view]+ };+ let atlas_texture = DirectXAtlasTexture {+ id: AtlasTextureId {+ index: index.unwrap_or(texture_list.textures.len()) as u32,+ kind,+ },+ bytes_per_pixel,+ allocator: etagere::BucketedAtlasAllocator::new(device_size_to_etagere(size)),+ texture,+ view,+ live_atlas_keys: 0,+ };+ if let Some(ix) = index {+ texture_list.textures[ix] = Some(atlas_texture);+ texture_list.textures.get_mut(ix).unwrap().as_mut()+ } else {+ texture_list.textures.push(Some(atlas_texture));+ texture_list.textures.last_mut().unwrap().as_mut()+ }+ }++ fn texture(&self, id: AtlasTextureId) -> Option<&DirectXAtlasTexture> {+ let textures = match id.kind {+ AtlasTextureKind::Monochrome => &self.monochrome_textures,+ AtlasTextureKind::Polychrome => &self.polychrome_textures,+ AtlasTextureKind::Subpixel => &self.subpixel_textures,+ };+ textures.textures.get(id.index as usize)?.as_ref()+ }+}++impl DirectXAtlasTexture {+ fn allocate(&mut self, size: Size<DevicePixels>) -> Option<AtlasTile> {+ let allocation = self.allocator.allocate(device_size_to_etagere(size))?;+ let tile = AtlasTile {+ texture_id: self.id,+ tile_id: allocation.id.into(),+ bounds: Bounds {+ origin: etagere_point_to_device(allocation.rectangle.min),+ size,+ },+ padding: 0,+ };+ self.live_atlas_keys += 1;+ Some(tile)+ }++ fn upload(+ &self,+ device_context: &ID3D11DeviceContext,+ bounds: Bounds<DevicePixels>,+ bytes: &[u8],+ ) {+ // `UpdateSubresource` reads `row_pitch * height` bytes from `bytes` based on the+ // `D3D11_BOX` below. If the caller hands us a slice shorter than that, the driver would+ // over-read past the end of the source buffer (potentially by multiple megabytes), so bail+ // out instead. This is a first-insert path rather than a per-frame one, so the check is+ // effectively free.+ let row_bytes = bounds.size.width.to_bytes(self.bytes_per_pixel as u8) as usize;+ let expected = row_bytes * bounds.size.height.0.max(0) as usize;+ if bytes.len() < expected {+ log::error!(+ "DirectXAtlasTexture::upload: source slice is {} bytes but the {}x{} region \+ requires {} bytes; skipping upload to avoid a driver over-read",+ bytes.len(),+ bounds.size.width.0,+ bounds.size.height.0,+ expected,+ );+ return;+ }+ unsafe {+ device_context.UpdateSubresource(+ &self.texture,+ 0,+ Some(&D3D11_BOX {+ left: bounds.left().0 as u32,+ top: bounds.top().0 as u32,+ front: 0,+ right: bounds.right().0 as u32,+ bottom: bounds.bottom().0 as u32,+ back: 1,+ }),+ bytes.as_ptr() as _,+ bounds.size.width.to_bytes(self.bytes_per_pixel as u8),+ 0,+ );+ }+ }++ fn decrement_ref_count(&mut self) {+ self.live_atlas_keys -= 1;+ }++ fn is_unreferenced(&mut self) -> bool {+ self.live_atlas_keys == 0+ }+}++fn device_size_to_etagere(size: Size<DevicePixels>) -> etagere::Size {+ etagere::Size::new(size.width.into(), size.height.into())+}++fn etagere_point_to_device(value: etagere::Point) -> Point<DevicePixels> {+ Point {+ x: DevicePixels::from(value.x),+ y: DevicePixels::from(value.y),+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use gpui::{ImageId, RenderImageParams};+ use std::borrow::Cow;+ use windows::Win32::{+ Foundation::HMODULE,+ Graphics::{+ Direct3D::D3D_DRIVER_TYPE_WARP,+ Direct3D11::{D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_SDK_VERSION, D3D11CreateDevice},+ },+ };++ fn create_atlas() -> Option<DirectXAtlas> {+ let mut device: Option<ID3D11Device> = None;+ let mut device_context: Option<ID3D11DeviceContext> = None;+ unsafe {+ D3D11CreateDevice(+ None,+ D3D_DRIVER_TYPE_WARP,+ HMODULE::default(),+ D3D11_CREATE_DEVICE_BGRA_SUPPORT,+ None,+ D3D11_SDK_VERSION,+ Some(&mut device),+ None,+ Some(&mut device_context),+ )+ }+ .ok()?;+ Some(DirectXAtlas::new(&device?, &device_context?))+ }++ fn make_image_key(image_id: usize) -> AtlasKey {+ AtlasKey::Image(RenderImageParams {+ image_id: ImageId(image_id),+ frame_index: 0,+ })+ }++ fn insert_tile(atlas: &DirectXAtlas, key: &AtlasKey, size: Size<DevicePixels>) -> AtlasTile {+ atlas+ .get_or_insert_with(key, &mut || {+ let byte_count = (size.width.0 as usize) * (size.height.0 as usize) * 4;+ Ok(Some((size, Cow::Owned(vec![0u8; byte_count]))))+ })+ .expect("allocation should succeed")+ .expect("callback returns Some")+ }++ #[test]+ fn test_remove_deallocates_tile_space_for_reuse() {+ let Some(atlas) = create_atlas() else {+ return;+ };++ let small = Size {+ width: DevicePixels(64),+ height: DevicePixels(64),+ };+ let big = Size {+ width: DevicePixels(700),+ height: DevicePixels(700),+ };++ let keeper_key = make_image_key(1);+ let big_key_a = make_image_key(2);+ let big_key_b = make_image_key(3);++ let keeper_tile = insert_tile(&atlas, &keeper_key, small);+ let tile_a = insert_tile(&atlas, &big_key_a, big);+ assert_eq!(keeper_tile.texture_id, tile_a.texture_id);++ atlas.remove(&big_key_a);++ let tile_b = insert_tile(&atlas, &big_key_b, big);+ assert_eq!(tile_b.texture_id, keeper_tile.texture_id);+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/directx_devices.rs b/native/vendor/wu/crates/gpui_windows/src/directx_devices.rsnew file mode 100644index 00000000000..8e65e6e626a--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/directx_devices.rs@@ -0,0 +1,194 @@+use anyhow::{Context, Result};+use gpui_util::ResultExt;+use itertools::Itertools;+use windows::Win32::{+ Foundation::HMODULE,+ Graphics::{+ Direct3D::{+ D3D_DRIVER_TYPE_UNKNOWN, D3D_FEATURE_LEVEL, D3D_FEATURE_LEVEL_10_1,+ D3D_FEATURE_LEVEL_11_0, D3D_FEATURE_LEVEL_11_1,+ },+ Direct3D11::{+ D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_CREATE_DEVICE_DEBUG,+ D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS, D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS,+ D3D11_SDK_VERSION, D3D11CreateDevice, ID3D11Device, ID3D11DeviceContext,+ },+ Dxgi::{+ CreateDXGIFactory2, DXGI_CREATE_FACTORY_DEBUG, DXGI_CREATE_FACTORY_FLAGS,+ IDXGIAdapter1, IDXGIFactory6,+ },+ },+};+use windows::core::Interface;++pub(crate) fn try_to_recover_from_device_lost<T>(mut f: impl FnMut() -> Result<T>) -> Result<T> {+ (0..5)+ .map(|i| {+ if i > 0 {+ // Add a small delay before retrying+ std::thread::sleep(std::time::Duration::from_millis(100 + i * 10));+ }+ f()+ })+ .find_or_last(Result::is_ok)+ .unwrap()+ .context("DirectXRenderer failed to recover from lost device after multiple attempts")+}++#[derive(Clone)]+pub(crate) struct DirectXDevices {+ pub(crate) adapter: IDXGIAdapter1,+ pub(crate) dxgi_factory: IDXGIFactory6,+ pub(crate) device: ID3D11Device,+ pub(crate) device_context: ID3D11DeviceContext,+}++impl DirectXDevices {+ pub(crate) fn new() -> Result<Self> {+ let debug_layer_available = check_debug_layer_available();+ let dxgi_factory =+ get_dxgi_factory(debug_layer_available).context("Creating DXGI factory")?;+ let (adapter, device, device_context, feature_level) =+ get_adapter(&dxgi_factory, debug_layer_available).context("Getting DXGI adapter")?;+ match feature_level {+ D3D_FEATURE_LEVEL_11_1 => {+ log::info!("Created device with Direct3D 11.1 feature level.")+ }+ D3D_FEATURE_LEVEL_11_0 => {+ log::info!("Created device with Direct3D 11.0 feature level.")+ }+ D3D_FEATURE_LEVEL_10_1 => {+ log::info!("Created device with Direct3D 10.1 feature level.")+ }+ _ => unreachable!(),+ }++ Ok(Self {+ adapter,+ dxgi_factory,+ device,+ device_context,+ })+ }+}++#[inline]+fn check_debug_layer_available() -> bool {+ #[cfg(debug_assertions)]+ {+ use windows::Win32::Graphics::Dxgi::{DXGIGetDebugInterface1, IDXGIInfoQueue};++ unsafe { DXGIGetDebugInterface1::<IDXGIInfoQueue>(0) }+ .log_err()+ .is_some()+ }+ #[cfg(not(debug_assertions))]+ {+ false+ }+}++#[inline]+fn get_dxgi_factory(debug_layer_available: bool) -> Result<IDXGIFactory6> {+ let factory_flag = if debug_layer_available {+ DXGI_CREATE_FACTORY_DEBUG+ } else {+ #[cfg(debug_assertions)]+ log::warn!(+ "Failed to get DXGI debug interface. DirectX debugging features will be disabled."+ );+ DXGI_CREATE_FACTORY_FLAGS::default()+ };+ unsafe { Ok(CreateDXGIFactory2(factory_flag)?) }+}++#[inline]+fn get_adapter(+ dxgi_factory: &IDXGIFactory6,+ debug_layer_available: bool,+) -> Result<(+ IDXGIAdapter1,+ ID3D11Device,+ ID3D11DeviceContext,+ D3D_FEATURE_LEVEL,+)> {+ for adapter_index in 0.. {+ let adapter: IDXGIAdapter1 = unsafe { dxgi_factory.EnumAdapters(adapter_index)?.cast()? };+ if let Ok(desc) = unsafe { adapter.GetDesc1() } {+ let gpu_name = String::from_utf16_lossy(&desc.Description)+ .trim_matches(char::from(0))+ .to_string();+ log::info!("Using GPU: {}", gpu_name);+ }+ // Check to see whether the adapter supports Direct3D 11 and create+ // the device if it does.+ let mut context: Option<ID3D11DeviceContext> = None;+ let mut feature_level = D3D_FEATURE_LEVEL::default();+ if let Some(device) = get_device(+ &adapter,+ Some(&mut context),+ Some(&mut feature_level),+ debug_layer_available,+ )+ .log_err()+ {+ return Ok((adapter, device, context.unwrap(), feature_level));+ }+ }++ unreachable!()+}++#[inline]+fn get_device(+ adapter: &IDXGIAdapter1,+ context: Option<*mut Option<ID3D11DeviceContext>>,+ feature_level: Option<*mut D3D_FEATURE_LEVEL>,+ debug_layer_available: bool,+) -> Result<ID3D11Device> {+ let mut device: Option<ID3D11Device> = None;+ let device_flags = if debug_layer_available {+ D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_DEBUG+ } else {+ D3D11_CREATE_DEVICE_BGRA_SUPPORT+ };+ unsafe {+ D3D11CreateDevice(+ adapter,+ D3D_DRIVER_TYPE_UNKNOWN,+ HMODULE::default(),+ device_flags,+ // 4x MSAA is required for Direct3D Feature Level 10.1 or better+ Some(&[+ D3D_FEATURE_LEVEL_11_1,+ D3D_FEATURE_LEVEL_11_0,+ D3D_FEATURE_LEVEL_10_1,+ ]),+ D3D11_SDK_VERSION,+ Some(&mut device),+ feature_level,+ context,+ )?;+ }+ let device = device.unwrap();+ let mut data = D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS::default();+ unsafe {+ device+ .CheckFeatureSupport(+ D3D11_FEATURE_D3D10_X_HARDWARE_OPTIONS,+ &mut data as *mut _ as _,+ std::mem::size_of::<D3D11_FEATURE_DATA_D3D10_X_HARDWARE_OPTIONS>() as u32,+ )+ .context("Checking GPU device feature support")?;+ }+ if data+ .ComputeShaders_Plus_RawAndStructuredBuffers_Via_Shader_4_x+ .as_bool()+ {+ Ok(device)+ } else {+ Err(anyhow::anyhow!(+ "Required feature StructuredBuffer is not supported by GPU/driver"+ ))+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/directx_renderer.rs b/native/vendor/wu/crates/gpui_windows/src/directx_renderer.rsnew file mode 100644index 00000000000..fadaf0a2dda--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/directx_renderer.rs@@ -0,0 +1,2124 @@+use std::{+ slice,+ sync::{Arc, OnceLock},+};++use anyhow::{Context, Result};+use gpui_util::ResultExt;+use windows::{+ Win32::{+ Foundation::HWND,+ Graphics::{+ Direct3D::*,+ Direct3D11::*,+ DirectComposition::*,+ DirectWrite::*,+ Dxgi::{Common::*, *},+ },+ },+ core::{HSTRING, Interface},+};++use crate::directx_renderer::shader_resources::{RawShaderBytes, ShaderModule, ShaderTarget};+use crate::*;+use gpui::*;++pub(crate) const DISABLE_DIRECT_COMPOSITION: &str = "GPUI_DISABLE_DIRECT_COMPOSITION";+const RENDER_TARGET_FORMAT: DXGI_FORMAT = DXGI_FORMAT_B8G8R8A8_UNORM;+// This configuration is used for MSAA rendering on paths only, and it's guaranteed to be supported by DirectX 11.+const PATH_MULTISAMPLE_COUNT: u32 = 4;+const MAX_INSTANCE_BUFFER_SIZE: usize = 256 * 1024 * 1024;++mod backdrop;+use backdrop::BackdropResources;++#[cfg(test)]+mod backdrop_tests;++pub(crate) struct FontInfo {+ pub gamma_ratios: [f32; 4],+ pub grayscale_enhanced_contrast: f32,+ pub subpixel_enhanced_contrast: f32,+ pub is_bgr: bool,+}++pub(crate) struct DirectXRenderer {+ hwnd: HWND,+ atlas: Arc<DirectXAtlas>,+ devices: Option<DirectXRendererDevices>,+ resources: Option<DirectXResources>,+ globals: DirectXGlobalElements,+ pipelines: DirectXRenderPipelines,+ direct_composition: Option<DirectComposition>,+ font_info: &'static FontInfo,++ width: u32,+ height: u32,++ /// Whether we want to skip drwaing due to device lost events.+ ///+ /// In that case we want to discard the first frame that we draw as we got reset in the middle of a frame+ /// meaning we lost all the allocated gpu textures and scene resources.+ skip_draws: bool,+}++/// Direct3D objects+#[derive(Clone)]+pub(crate) struct DirectXRendererDevices {+ pub(crate) adapter: IDXGIAdapter1,+ pub(crate) dxgi_factory: IDXGIFactory6,+ pub(crate) device: ID3D11Device,+ pub(crate) device_context: ID3D11DeviceContext,+ dxgi_device: Option<IDXGIDevice>,+ annotation: Option<ID3DUserDefinedAnnotation>,+}++struct DirectXResources {+ backdrop: Option<BackdropResources>,+ // Direct3D rendering objects+ swap_chain: IDXGISwapChain1,+ render_target: Option<ID3D11Texture2D>,+ render_target_view: Option<ID3D11RenderTargetView>,++ // Path intermediate textures (with MSAA)+ path_intermediate_texture: ID3D11Texture2D,+ path_intermediate_srv: Option<ID3D11ShaderResourceView>,+ path_intermediate_msaa_texture: ID3D11Texture2D,+ path_intermediate_msaa_view: Option<ID3D11RenderTargetView>,++ // Cached viewport+ viewport: D3D11_VIEWPORT,+}++struct DirectXRenderPipelines {+ shadow_pipeline: PipelineState<Shadow>,+ quad_pipeline: PipelineState<Quad>,+ path_rasterization_pipeline: PipelineState<PathRasterizationSprite>,+ path_sprite_pipeline: PipelineState<PathSprite>,+ underline_pipeline: PipelineState<Underline>,+ mono_sprites: PipelineState<MonochromeSprite>,+ subpixel_sprites: PipelineState<SubpixelSprite>,+ poly_sprites: PipelineState<PolychromeSprite>,+}++struct DirectXGlobalElements {+ global_params_buffer: Option<ID3D11Buffer>,+ batch_params_buffer: Option<ID3D11Buffer>,+ sampler: Option<ID3D11SamplerState>,+}++struct Annotation<'a>(&'a ID3DUserDefinedAnnotation);++impl<'a> Annotation<'a> {+ fn new(annotation: &'a ID3DUserDefinedAnnotation, label: HSTRING) -> Self {+ unsafe { annotation.BeginEvent(&label) };+ Self(annotation)+ }+}++impl Drop for Annotation<'_> {+ fn drop(&mut self) {+ unsafe { self.0.EndEvent() };+ }+}++struct DirectComposition {+ comp_device: IDCompositionDevice,+ comp_target: IDCompositionTarget,+ comp_visual: IDCompositionVisual,+}++impl DirectXRendererDevices {+ pub(crate) fn new(+ directx_devices: &DirectXDevices,+ disable_direct_composition: bool,+ ) -> Result<Self> {+ let DirectXDevices {+ adapter,+ dxgi_factory,+ device,+ device_context,+ } = directx_devices;+ let dxgi_device = if disable_direct_composition {+ None+ } else {+ Some(device.cast().context("Creating DXGI device")?)+ };+ let annotation = device_context.cast().ok();++ Ok(Self {+ adapter: adapter.clone(),+ dxgi_factory: dxgi_factory.clone(),+ device: device.clone(),+ device_context: device_context.clone(),+ dxgi_device,+ annotation,+ })+ }+}++impl DirectXRenderer {+ pub(crate) fn new(+ hwnd: HWND,+ directx_devices: &DirectXDevices,+ disable_direct_composition: bool,+ ) -> Result<Self> {+ if disable_direct_composition {+ log::info!("Direct Composition is disabled.");+ }++ let devices = DirectXRendererDevices::new(directx_devices, disable_direct_composition)+ .context("Creating DirectX devices")?;+ let atlas = Arc::new(DirectXAtlas::new(&devices.device, &devices.device_context));++ let resources = DirectXResources::new(&devices, 1, 1, hwnd, disable_direct_composition)+ .context("Creating DirectX resources")?;+ let globals = DirectXGlobalElements::new(&devices.device)+ .context("Creating DirectX global elements")?;+ let pipelines = DirectXRenderPipelines::new(&devices.device)+ .context("Creating DirectX render pipelines")?;++ let direct_composition = if disable_direct_composition {+ None+ } else {+ let composition = DirectComposition::new(devices.dxgi_device.as_ref().unwrap(), hwnd)+ .context("Creating DirectComposition")?;+ composition+ .set_swap_chain(&resources.swap_chain)+ .context("Setting swap chain for DirectComposition")?;+ Some(composition)+ };++ Ok(DirectXRenderer {+ hwnd,+ atlas,+ devices: Some(devices),+ resources: Some(resources),+ globals,+ pipelines,+ direct_composition,+ font_info: Self::get_font_info(),+ width: 1,+ height: 1,+ skip_draws: false,+ })+ }++ pub(crate) fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {+ self.atlas.clone()+ }++ fn pre_draw(&self, clear_color: &[f32; 4]) -> Result<()> {+ let resources = self.resources.as_ref().expect("resources missing");+ let device_context = &self+ .devices+ .as_ref()+ .expect("devices missing")+ .device_context;+ update_buffer(+ device_context,+ self.globals.global_params_buffer.as_ref().unwrap(),+ &[GlobalParams {+ gamma_ratios: self.font_info.gamma_ratios,+ viewport_size: [resources.viewport.Width, resources.viewport.Height],+ grayscale_enhanced_contrast: self.font_info.grayscale_enhanced_contrast,+ subpixel_enhanced_contrast: self.font_info.subpixel_enhanced_contrast,+ is_bgr: self.font_info.is_bgr as u32,+ _pad: [0; 3],+ }],+ )?;+ unsafe {+ device_context.ClearRenderTargetView(+ resources+ .render_target_view+ .as_ref()+ .context("missing render target view")?,+ clear_color,+ );+ device_context+ .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None);+ device_context.RSSetViewports(Some(slice::from_ref(&resources.viewport)));+ device_context+ .VSSetConstantBuffers(0, Some(slice::from_ref(&self.globals.global_params_buffer)));+ device_context+ .VSSetConstantBuffers(1, Some(slice::from_ref(&self.globals.batch_params_buffer)));+ device_context+ .PSSetConstantBuffers(0, Some(slice::from_ref(&self.globals.global_params_buffer)));+ }+ Ok(())+ }++ #[inline]+ fn present(&mut self) -> Result<()> {+ let result = unsafe {+ self.resources+ .as_ref()+ .expect("resources missing")+ .swap_chain+ .Present(0, DXGI_PRESENT(0))+ };+ result.ok().context("Presenting swap chain failed")+ }++ pub(crate) fn handle_device_lost(&mut self, directx_devices: &DirectXDevices) -> Result<()> {+ try_to_recover_from_device_lost(|| {+ self.handle_device_lost_impl(directx_devices)+ .context("DirectXRenderer handling device lost")+ })+ }++ fn handle_device_lost_impl(&mut self, directx_devices: &DirectXDevices) -> Result<()> {+ let disable_direct_composition = self.direct_composition.is_none();++ unsafe {+ #[cfg(debug_assertions)]+ if let Some(devices) = &self.devices {+ report_live_objects(&devices.device)+ .context("Failed to report live objects after device lost")+ .log_err();+ }++ self.resources.take();+ if let Some(devices) = &self.devices {+ devices.device_context.OMSetRenderTargets(None, None);+ devices.device_context.ClearState();+ devices.device_context.Flush();+ #[cfg(debug_assertions)]+ report_live_objects(&devices.device)+ .context("Failed to report live objects after device lost")+ .log_err();+ }++ self.direct_composition.take();+ self.devices.take();+ }++ let devices = DirectXRendererDevices::new(directx_devices, disable_direct_composition)+ .context("Recreating DirectX devices")?;+ let resources = DirectXResources::new(+ &devices,+ self.width,+ self.height,+ self.hwnd,+ disable_direct_composition,+ )+ .context("Creating DirectX resources")?;+ let globals = DirectXGlobalElements::new(&devices.device)+ .context("Creating DirectXGlobalElements")?;+ let pipelines = DirectXRenderPipelines::new(&devices.device)+ .context("Creating DirectXRenderPipelines")?;++ let direct_composition = if disable_direct_composition {+ None+ } else {+ let composition =+ DirectComposition::new(devices.dxgi_device.as_ref().unwrap(), self.hwnd)?;+ composition.set_swap_chain(&resources.swap_chain)?;+ Some(composition)+ };++ self.atlas+ .handle_device_lost(&devices.device, &devices.device_context);++ unsafe {+ devices+ .device_context+ .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None);+ }+ self.devices = Some(devices);+ self.resources = Some(resources);+ self.globals = globals;+ self.pipelines = pipelines;+ self.direct_composition = direct_composition;+ self.skip_draws = true;+ Ok(())+ }++ pub(crate) fn draw(+ &mut self,+ scene: &Scene,+ background_appearance: WindowBackgroundAppearance,+ ) -> Result<()> {+ if self.skip_draws {+ // skip drawing this frame, we just recovered from a device lost event+ // and so likely do not have the textures anymore that are required for drawing+ return Ok(());+ }+ self.render(scene, background_appearance)?;+ self.present()+ }++ #[cfg(test)]+ fn draw_scene(+ &mut self,+ scene: &Scene,+ background_appearance: WindowBackgroundAppearance,+ ) -> Result<()> {+ if self.skip_draws {+ return Ok(());+ }+ self.render(scene, background_appearance)+ }++ /// Clear the render target for `background_appearance` and encode every+ /// primitive batch of `scene` into it, without presenting. Shared by+ /// [`draw`](Self::draw) (which then presents) and+ /// [`render_to_image`](Self::render_to_image) (which reads the target back+ /// instead), so the two cannot drift.+ fn render(+ &mut self,+ scene: &Scene,+ background_appearance: WindowBackgroundAppearance,+ ) -> Result<()> {+ self.pre_draw(&match background_appearance {+ WindowBackgroundAppearance::Opaque => [1.0f32; 4],+ _ => [0.0f32; 4],+ })?;+ self.upload_scene_buffers(scene)?;++ {+ let resources = self.resources.as_mut().context("resources missing")?;+ if let Some(backdrop) = resources.backdrop.as_mut() {+ backdrop.release_idle_scratch();+ }+ }+ let mut blurs = scene.backdrop_blurs.iter().peekable();++ let annotation = self+ .devices+ .as_ref()+ .and_then(|devices| devices.annotation.clone())+ .filter(|annotation| unsafe { annotation.GetStatus().as_bool() });+ for batch in scene.batches() {+ // Relies on Scene::batches splitting at every blur order.+ if blurs.peek().is_some() {+ let order = batch.first_order(scene);+ while let Some(blur) = blurs.next_if(|blur| blur.order <= order) {+ self.draw_backdrop_blur(blur)?;+ }+ }+ let _annotation = annotation+ .as_ref()+ .map(|annotation| Annotation::new(annotation, HSTRING::from(batch.label())));+ match batch {+ PrimitiveBatch::Shadows(range) => self.draw_shadows(range.start, range.len()),+ PrimitiveBatch::Quads(range) => self.draw_quads(range.start, range.len()),+ PrimitiveBatch::Paths(range) => {+ let paths = &scene.paths[range];+ self.draw_paths_to_intermediate(paths)?;+ self.draw_paths_from_intermediate(paths)+ }+ PrimitiveBatch::Underlines(range) => self.draw_underlines(range.start, range.len()),+ PrimitiveBatch::MonochromeSprites { texture_id, range } => {+ self.draw_monochrome_sprites(texture_id, range.start, range.len())+ }+ PrimitiveBatch::SubpixelSprites { texture_id, range } => {+ self.draw_subpixel_sprites(texture_id, range.start, range.len())+ }+ PrimitiveBatch::PolychromeSprites { texture_id, range } => {+ self.draw_polychrome_sprites(texture_id, range.start, range.len())+ }+ PrimitiveBatch::Surfaces(range) => self.draw_surfaces(&scene.surfaces[range]),+ }+ .with_context(|| {+ format!(+ "scene too large:\+ {} paths, {} shadows, {} quads, {} underlines, {} mono, {} subpixel, {} poly, {} surfaces",+ scene.paths.len(),+ scene.shadows.len(),+ scene.quads.len(),+ scene.underlines.len(),+ scene.monochrome_sprites.len(),+ scene.subpixel_sprites.len(),+ scene.polychrome_sprites.len(),+ scene.surfaces.len(),+ )+ })?;+ }+ for blur in blurs {+ self.draw_backdrop_blur(blur)?;+ }+ Ok(())+ }++ /// Render `scene` to an offscreen CPU image **without presenting** so+ /// the window need never be shown or visible (the macOS headless path+ /// goes through MetalRenderer; this is the Windows analogue). Draws into+ /// the existing render target, copies it into a `D3D11_USAGE_STAGING`+ /// texture, maps it, and converts BGRA to RGBA.+ #[cfg(any(test, feature = "test-support"))]+ pub(crate) fn render_to_image(+ &mut self,+ scene: &Scene,+ background_appearance: WindowBackgroundAppearance,+ ) -> Result<image::RgbaImage> {+ // A pending device-lost recovery (`skip_draws`) leaves the atlas holding+ // tile references from the previous device; drawing before the forced+ // re-render rebuilds them panics in `DirectXAtlasState::texture`.+ anyhow::ensure!(+ !self.skip_draws,+ "render_to_image unavailable while recovering from a lost device"+ );+ self.render(scene, background_appearance)?;++ let devices = self.devices.as_ref().context("devices missing")?;+ let device = &devices.device;+ let context = &devices.device_context;+ let resources = self.resources.as_ref().context("resources missing")?;+ let render_target = resources+ .render_target+ .as_ref()+ .context("render target missing")?;++ // A CPU-readable copy of the render target.+ let mut desc = D3D11_TEXTURE2D_DESC::default();+ unsafe { render_target.GetDesc(&mut desc) };+ let width = desc.Width;+ let height = desc.Height;+ let staging_desc = D3D11_TEXTURE2D_DESC {+ Usage: D3D11_USAGE_STAGING,+ BindFlags: 0,+ CPUAccessFlags: D3D11_CPU_ACCESS_READ.0 as u32,+ MiscFlags: 0,+ MipLevels: 1,+ ArraySize: 1,+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ ..desc+ };+ let mut staging: Option<ID3D11Texture2D> = None;+ unsafe { device.CreateTexture2D(&staging_desc, None, Some(&mut staging))? };+ let staging = staging.context("creating staging texture")?;+ unsafe { context.CopyResource(&staging, render_target) };++ let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();+ unsafe { context.Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))? };+ let row_bytes = (width as usize) * 4;+ let mut pixels = vec![0u8; row_bytes * height as usize];+ // SAFETY: `Map` succeeded, so `pData` points at `RowPitch * height`+ // readable bytes for as long as the mapping is held, and `RowPitch >=+ // row_bytes` (it only ever adds trailing padding). `pixels` is sized+ // `row_bytes * height`, so every copy stays in bounds on both sides,+ // and the regions cannot overlap (`pixels` is a fresh allocation).+ unsafe {+ let src = mapped.pData as *const u8;+ for row in 0..height as usize {+ let s = src.add(row * mapped.RowPitch as usize);+ let d = pixels.as_mut_ptr().add(row * row_bytes);+ std::ptr::copy_nonoverlapping(s, d, row_bytes);+ }+ context.Unmap(&staging, 0);+ }+ // The render target is BGRA; image::RgbaImage expects RGBA.+ for px in pixels.chunks_exact_mut(4) {+ px.swap(0, 2);+ }+ image::RgbaImage::from_raw(width, height, pixels)+ .context("Failed to build RgbaImage from staging readback")+ }++ pub(crate) fn resize(&mut self, new_size: Size<DevicePixels>) -> Result<()> {+ let width = new_size.width.0.max(1) as u32;+ let height = new_size.height.0.max(1) as u32;+ if self.width == width && self.height == height {+ return Ok(());+ }+ self.width = width;+ self.height = height;++ // Clear the render target before resizing+ let devices = self.devices.as_ref().context("devices missing")?;+ unsafe { devices.device_context.OMSetRenderTargets(None, None) };+ let resources = self.resources.as_mut().context("resources missing")?;+ if let Some(backdrop) = resources.backdrop.as_mut() {+ backdrop.release_scratch();+ }+ resources.render_target.take();+ resources.render_target_view.take();++ // Resizing the swap chain requires a call to the underlying DXGI adapter, which can return the device removed error.+ // The app might have moved to a monitor that's attached to a different graphics device.+ // When a graphics device is removed or reset, the desktop resolution often changes, resulting in a window size change.+ // But here we just return the error, because we are handling device lost scenarios elsewhere.+ unsafe {+ resources+ .swap_chain+ .ResizeBuffers(+ BUFFER_COUNT as u32,+ width,+ height,+ RENDER_TARGET_FORMAT,+ DXGI_SWAP_CHAIN_FLAG(0),+ )+ .context("Failed to resize swap chain")?;+ }++ resources.recreate_resources(devices, width, height)?;++ unsafe {+ devices+ .device_context+ .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None);+ }++ Ok(())+ }++ fn upload_scene_buffers(&mut self, scene: &Scene) -> Result<()> {+ let devices = self.devices.as_ref().context("devices missing")?;++ if !scene.shadows.is_empty() {+ self.pipelines.shadow_pipeline.update_buffer(+ &devices.device,+ &devices.device_context,+ &scene.shadows,+ )?;+ }++ if !scene.quads.is_empty() {+ self.pipelines.quad_pipeline.update_buffer(+ &devices.device,+ &devices.device_context,+ &scene.quads,+ )?;+ }++ if !scene.underlines.is_empty() {+ self.pipelines.underline_pipeline.update_buffer(+ &devices.device,+ &devices.device_context,+ &scene.underlines,+ )?;+ }++ if !scene.monochrome_sprites.is_empty() {+ self.pipelines.mono_sprites.update_buffer(+ &devices.device,+ &devices.device_context,+ &scene.monochrome_sprites,+ )?;+ }++ if !scene.subpixel_sprites.is_empty() {+ self.pipelines.subpixel_sprites.update_buffer(+ &devices.device,+ &devices.device_context,+ &scene.subpixel_sprites,+ )?;+ }++ if !scene.polychrome_sprites.is_empty() {+ self.pipelines.poly_sprites.update_buffer(+ &devices.device,+ &devices.device_context,+ &scene.polychrome_sprites,+ )?;+ }++ Ok(())+ }++ fn draw_shadows(&mut self, start: usize, len: usize) -> Result<()> {+ if len == 0 {+ return Ok(());+ }+ let devices = self.devices.as_ref().context("devices missing")?;+ self.pipelines.shadow_pipeline.draw_range(+ &devices.device_context,+ self.globals+ .batch_params_buffer+ .as_ref()+ .context("batch params buffer missing")?,+ start as u32,+ len as u32,+ )+ }++ fn draw_quads(&mut self, start: usize, len: usize) -> Result<()> {+ if len == 0 {+ return Ok(());+ }+ let devices = self.devices.as_ref().context("devices missing")?;+ self.pipelines.quad_pipeline.draw_range(+ &devices.device_context,+ self.globals+ .batch_params_buffer+ .as_ref()+ .context("batch params buffer missing")?,+ start as u32,+ len as u32,+ )+ }++ fn draw_paths_to_intermediate(&mut self, paths: &[Path<ScaledPixels>]) -> Result<()> {+ if paths.is_empty() {+ return Ok(());+ }++ let devices = self.devices.as_ref().context("devices missing")?;+ let resources = self.resources.as_ref().context("resources missing")?;+ // Clear intermediate MSAA texture+ unsafe {+ devices.device_context.ClearRenderTargetView(+ resources.path_intermediate_msaa_view.as_ref().unwrap(),+ &[0.0; 4],+ );+ // Set intermediate MSAA texture as render target+ devices.device_context.OMSetRenderTargets(+ Some(slice::from_ref(&resources.path_intermediate_msaa_view)),+ None,+ );+ }++ // Collect all vertices and sprites for a single draw call+ let mut vertices = Vec::new();++ for path in paths {+ vertices.extend(path.vertices.iter().map(|v| PathRasterizationSprite {+ xy_position: v.xy_position,+ st_position: v.st_position,+ color: path.color,+ bounds: path.clipped_bounds(),+ }));+ }++ self.pipelines.path_rasterization_pipeline.update_buffer(+ &devices.device,+ &devices.device_context,+ &vertices,+ )?;++ self.pipelines.path_rasterization_pipeline.draw(+ &devices.device_context,+ D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST,+ vertices.len() as u32,+ 1,+ )?;++ // Resolve MSAA to non-MSAA intermediate texture+ unsafe {+ devices.device_context.ResolveSubresource(+ &resources.path_intermediate_texture,+ 0,+ &resources.path_intermediate_msaa_texture,+ 0,+ RENDER_TARGET_FORMAT,+ );+ // Restore main render target+ devices+ .device_context+ .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None);+ }++ Ok(())+ }++ fn draw_paths_from_intermediate(&mut self, paths: &[Path<ScaledPixels>]) -> Result<()> {+ let Some(first_path) = paths.first() else {+ return Ok(());+ };++ // When copying paths from the intermediate texture to the drawable,+ // each pixel must only be copied once, in case of transparent paths.+ //+ // If all paths have the same draw order, then their bounds are all+ // disjoint, so we can copy each path's bounds individually. If this+ // batch combines different draw orders, we perform a single copy+ // for a minimal spanning rect.+ let sprites = if paths.last().unwrap().order == first_path.order {+ paths+ .iter()+ .map(|path| PathSprite {+ bounds: path.clipped_bounds(),+ })+ .collect::<Vec<_>>()+ } else {+ let mut bounds = first_path.clipped_bounds();+ for path in paths.iter().skip(1) {+ bounds = bounds.union(&path.clipped_bounds());+ }+ vec![PathSprite { bounds }]+ };++ let devices = self.devices.as_ref().context("devices missing")?;+ let resources = self.resources.as_ref().context("resources missing")?;+ self.pipelines.path_sprite_pipeline.update_buffer(+ &devices.device,+ &devices.device_context,+ &sprites,+ )?;++ // Draw the sprites with the path texture+ self.pipelines.path_sprite_pipeline.draw_with_texture(+ &devices.device_context,+ slice::from_ref(&resources.path_intermediate_srv),+ slice::from_ref(&self.globals.sampler),+ sprites.len() as u32,+ )+ }++ fn draw_underlines(&mut self, start: usize, len: usize) -> Result<()> {+ if len == 0 {+ return Ok(());+ }+ let devices = self.devices.as_ref().context("devices missing")?;+ self.pipelines.underline_pipeline.draw_range(+ &devices.device_context,+ self.globals+ .batch_params_buffer+ .as_ref()+ .context("batch params buffer missing")?,+ start as u32,+ len as u32,+ )+ }++ fn draw_monochrome_sprites(+ &mut self,+ texture_id: AtlasTextureId,+ start: usize,+ len: usize,+ ) -> Result<()> {+ if len == 0 {+ return Ok(());+ }+ let devices = self.devices.as_ref().context("devices missing")?;+ let Some(texture_view) = self.atlas.get_texture_view(texture_id) else {+ return Ok(());+ };+ self.pipelines.mono_sprites.draw_range_with_texture(+ &devices.device_context,+ &texture_view,+ self.globals+ .batch_params_buffer+ .as_ref()+ .context("batch params buffer missing")?,+ slice::from_ref(&self.globals.sampler),+ start as u32,+ len as u32,+ )+ }++ fn draw_subpixel_sprites(+ &mut self,+ texture_id: AtlasTextureId,+ start: usize,+ len: usize,+ ) -> Result<()> {+ if len == 0 {+ return Ok(());+ }+ let devices = self.devices.as_ref().context("devices missing")?;+ let Some(texture_view) = self.atlas.get_texture_view(texture_id) else {+ return Ok(());+ };+ self.pipelines.subpixel_sprites.draw_range_with_texture(+ &devices.device_context,+ &texture_view,+ self.globals+ .batch_params_buffer+ .as_ref()+ .context("batch params buffer missing")?,+ slice::from_ref(&self.globals.sampler),+ start as u32,+ len as u32,+ )+ }++ fn draw_polychrome_sprites(+ &mut self,+ texture_id: AtlasTextureId,+ start: usize,+ len: usize,+ ) -> Result<()> {+ if len == 0 {+ return Ok(());+ }+ let devices = self.devices.as_ref().context("devices missing")?;+ let Some(texture_view) = self.atlas.get_texture_view(texture_id) else {+ return Ok(());+ };+ self.pipelines.poly_sprites.draw_range_with_texture(+ &devices.device_context,+ &texture_view,+ self.globals+ .batch_params_buffer+ .as_ref()+ .context("batch params buffer missing")?,+ slice::from_ref(&self.globals.sampler),+ start as u32,+ len as u32,+ )+ }++ fn draw_surfaces(&mut self, surfaces: &[PaintSurface]) -> Result<()> {+ if surfaces.is_empty() {+ return Ok(());+ }+ Ok(())+ }++ pub(crate) fn gpu_specs(&self) -> Result<GpuSpecs> {+ let devices = self.devices.as_ref().context("devices missing")?;+ let desc = unsafe { devices.adapter.GetDesc1() }?;+ let is_software_emulated = (desc.Flags & DXGI_ADAPTER_FLAG_SOFTWARE.0 as u32) != 0;+ let device_name = String::from_utf16_lossy(&desc.Description)+ .trim_matches(char::from(0))+ .to_string();+ let driver_name = match desc.VendorId {+ 0x10DE => "NVIDIA Corporation".to_string(),+ 0x1002 => "AMD Corporation".to_string(),+ 0x8086 => "Intel Corporation".to_string(),+ id => format!("Unknown Vendor (ID: {:#X})", id),+ };+ let driver_version = match desc.VendorId {+ 0x10DE => nvidia::get_driver_version(),+ 0x1002 => amd::get_driver_version(),+ // For Intel and other vendors, we use the DXGI API to get the driver version.+ _ => dxgi::get_driver_version(&devices.adapter),+ }+ .context("Failed to get gpu driver info")+ .log_err()+ .unwrap_or("Unknown Driver".to_string());+ Ok(GpuSpecs {+ is_software_emulated,+ device_name,+ driver_name,+ driver_info: driver_version,+ })+ }++ pub(crate) fn get_font_info() -> &'static FontInfo {+ static CACHED_FONT_INFO: OnceLock<FontInfo> = OnceLock::new();+ CACHED_FONT_INFO.get_or_init(|| unsafe {+ let factory: IDWriteFactory5 = DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED).unwrap();+ let render_params: IDWriteRenderingParams1 =+ factory.CreateRenderingParams().unwrap().cast().unwrap();+ FontInfo {+ gamma_ratios: gpui::get_gamma_correction_ratios(render_params.GetGamma()),+ grayscale_enhanced_contrast: render_params.GetGrayscaleEnhancedContrast(),+ subpixel_enhanced_contrast: render_params.GetEnhancedContrast(),+ is_bgr: render_params.GetPixelGeometry() == DWRITE_PIXEL_GEOMETRY_BGR,+ }+ })+ }++ pub(crate) fn mark_drawable(&mut self) {+ self.skip_draws = false;+ }+}++impl DirectXResources {+ pub fn new(+ devices: &DirectXRendererDevices,+ width: u32,+ height: u32,+ hwnd: HWND,+ disable_direct_composition: bool,+ ) -> Result<Self> {+ let swap_chain = if disable_direct_composition {+ create_swap_chain(&devices.dxgi_factory, &devices.device, hwnd, width, height)?+ } else {+ create_swap_chain_for_composition(+ &devices.dxgi_factory,+ &devices.device,+ width,+ height,+ )?+ };++ let (+ render_target,+ render_target_view,+ path_intermediate_texture,+ path_intermediate_srv,+ path_intermediate_msaa_texture,+ path_intermediate_msaa_view,+ viewport,+ ) = create_resources(devices, &swap_chain, width, height)?;+ set_rasterizer_state(&devices.device, &devices.device_context)?;++ Ok(Self {+ backdrop: None,+ swap_chain,+ render_target: Some(render_target),+ render_target_view,+ path_intermediate_texture,+ path_intermediate_msaa_texture,+ path_intermediate_msaa_view,+ path_intermediate_srv,+ viewport,+ })+ }++ #[inline]+ fn recreate_resources(+ &mut self,+ devices: &DirectXRendererDevices,+ width: u32,+ height: u32,+ ) -> Result<()> {+ let (+ render_target,+ render_target_view,+ path_intermediate_texture,+ path_intermediate_srv,+ path_intermediate_msaa_texture,+ path_intermediate_msaa_view,+ viewport,+ ) = create_resources(devices, &self.swap_chain, width, height)?;+ self.render_target = Some(render_target);+ self.render_target_view = render_target_view;+ self.path_intermediate_texture = path_intermediate_texture;+ self.path_intermediate_msaa_texture = path_intermediate_msaa_texture;+ self.path_intermediate_msaa_view = path_intermediate_msaa_view;+ self.path_intermediate_srv = path_intermediate_srv;+ self.viewport = viewport;+ Ok(())+ }+}++impl DirectXRenderPipelines {+ pub fn new(device: &ID3D11Device) -> Result<Self> {+ let shadow_pipeline = PipelineState::new(+ device,+ "shadow_pipeline",+ ShaderModule::Shadow,+ 4,+ create_blend_state(device)?,+ )?;+ let quad_pipeline = PipelineState::new(+ device,+ "quad_pipeline",+ ShaderModule::Quad,+ 64,+ create_blend_state(device)?,+ )?;+ let path_rasterization_pipeline = PipelineState::new(+ device,+ "path_rasterization_pipeline",+ ShaderModule::PathRasterization,+ 32,+ create_blend_state_for_path_rasterization(device)?,+ )?;+ let path_sprite_pipeline = PipelineState::new(+ device,+ "path_sprite_pipeline",+ ShaderModule::PathSprite,+ 4,+ create_blend_state_for_path_sprite(device)?,+ )?;+ let underline_pipeline = PipelineState::new(+ device,+ "underline_pipeline",+ ShaderModule::Underline,+ 4,+ create_blend_state(device)?,+ )?;+ let mono_sprites = PipelineState::new(+ device,+ "monochrome_sprite_pipeline",+ ShaderModule::MonochromeSprite,+ 512,+ create_blend_state(device)?,+ )?;+ let subpixel_sprites = PipelineState::new(+ device,+ "subpixel_sprite_pipeline",+ ShaderModule::SubpixelSprite,+ 512,+ create_blend_state_for_subpixel_rendering(device)?,+ )?;+ let poly_sprites = PipelineState::new(+ device,+ "polychrome_sprite_pipeline",+ ShaderModule::PolychromeSprite,+ 16,+ create_blend_state(device)?,+ )?;++ Ok(Self {+ shadow_pipeline,+ quad_pipeline,+ path_rasterization_pipeline,+ path_sprite_pipeline,+ underline_pipeline,+ mono_sprites,+ subpixel_sprites,+ poly_sprites,+ })+ }+}++impl DirectComposition {+ pub fn new(dxgi_device: &IDXGIDevice, hwnd: HWND) -> Result<Self> {+ let comp_device = get_comp_device(dxgi_device)?;+ // VSRustium: behind child windows, so the WebView2 child HWNDs of app/src/webview/windows.rs draw over GPUI.+ let comp_target = unsafe { comp_device.CreateTargetForHwnd(hwnd, false) }?;+ let comp_visual = unsafe { comp_device.CreateVisual() }?;++ Ok(Self {+ comp_device,+ comp_target,+ comp_visual,+ })+ }++ pub fn set_swap_chain(&self, swap_chain: &IDXGISwapChain1) -> Result<()> {+ unsafe {+ self.comp_visual.SetContent(swap_chain)?;+ self.comp_target.SetRoot(&self.comp_visual)?;+ self.comp_device.Commit()?;+ }+ Ok(())+ }+}++impl DirectXGlobalElements {+ pub fn new(device: &ID3D11Device) -> Result<Self> {+ let global_params_buffer = create_constant_buffer::<GlobalParams>(device)?;+ let batch_params_buffer = create_constant_buffer::<BatchParams>(device)?;++ let sampler = unsafe {+ let desc = D3D11_SAMPLER_DESC {+ Filter: D3D11_FILTER_MIN_MAG_MIP_LINEAR,+ AddressU: D3D11_TEXTURE_ADDRESS_WRAP,+ AddressV: D3D11_TEXTURE_ADDRESS_WRAP,+ AddressW: D3D11_TEXTURE_ADDRESS_WRAP,+ MipLODBias: 0.0,+ MaxAnisotropy: 1,+ ComparisonFunc: D3D11_COMPARISON_ALWAYS,+ BorderColor: [0.0; 4],+ MinLOD: 0.0,+ MaxLOD: D3D11_FLOAT32_MAX,+ };+ let mut output = None;+ device.CreateSamplerState(&desc, Some(&mut output))?;+ output+ };++ Ok(Self {+ global_params_buffer,+ batch_params_buffer,+ sampler,+ })+ }+}++#[derive(Debug, Default)]+#[repr(C)]+struct GlobalParams {+ gamma_ratios: [f32; 4],+ viewport_size: [f32; 2],+ grayscale_enhanced_contrast: f32,+ subpixel_enhanced_contrast: f32,+ is_bgr: u32,+ _pad: [u32; 3],+}++#[derive(Clone, Copy, Debug, Default)]+#[repr(C, align(16))]+struct BatchParams {+ start_index: u32,+ _padding: [u32; 3],+}++const _: () = assert!(std::mem::size_of::<BatchParams>() == 16);++struct PipelineState<T> {+ label: &'static str,+ vertex: ID3D11VertexShader,+ fragment: ID3D11PixelShader,+ buffer: ID3D11Buffer,+ buffer_size: usize,+ view: Option<ID3D11ShaderResourceView>,+ blend_state: ID3D11BlendState,+ _marker: std::marker::PhantomData<T>,+}++impl<T> PipelineState<T> {+ fn new(+ device: &ID3D11Device,+ label: &'static str,+ shader_module: ShaderModule,+ buffer_size: usize,+ blend_state: ID3D11BlendState,+ ) -> Result<Self> {+ let vertex = {+ let raw_shader = RawShaderBytes::new(shader_module, ShaderTarget::Vertex)?;+ create_vertex_shader(device, raw_shader.as_bytes())?+ };+ let fragment = {+ let raw_shader = RawShaderBytes::new(shader_module, ShaderTarget::Fragment)?;+ create_fragment_shader(device, raw_shader.as_bytes())?+ };+ let buffer = create_buffer(device, std::mem::size_of::<T>(), buffer_size)?;+ let view = create_buffer_view(device, &buffer)?;++ Ok(PipelineState {+ label,+ vertex,+ fragment,+ buffer,+ buffer_size,+ view,+ blend_state,+ _marker: std::marker::PhantomData,+ })+ }++ fn update_buffer(+ &mut self,+ device: &ID3D11Device,+ device_context: &ID3D11DeviceContext,+ data: &[T],+ ) -> Result<()> {+ if self.buffer_size < data.len() {+ let element_size = std::mem::size_of::<T>();+ let required_size = std::mem::size_of_val(data);+ anyhow::ensure!(+ required_size <= MAX_INSTANCE_BUFFER_SIZE,+ "{} buffer needs {required_size} bytes, above the maximum of {MAX_INSTANCE_BUFFER_SIZE}",+ self.label+ );+ let new_buffer_size = data+ .len()+ .next_power_of_two()+ .min(MAX_INSTANCE_BUFFER_SIZE / element_size);+ log::debug!(+ "Updating {} buffer size from {} to {}",+ self.label,+ self.buffer_size,+ new_buffer_size+ );+ let buffer = create_buffer(device, std::mem::size_of::<T>(), new_buffer_size)?;+ let view = create_buffer_view(device, &buffer)?;+ self.buffer = buffer;+ self.view = view;+ self.buffer_size = new_buffer_size;+ }+ update_buffer(device_context, &self.buffer, data)+ }++ fn draw(+ &self,+ device_context: &ID3D11DeviceContext,+ topology: D3D_PRIMITIVE_TOPOLOGY,+ vertex_count: u32,+ instance_count: u32,+ ) -> Result<()> {+ set_pipeline_state(+ device_context,+ slice::from_ref(&self.view),+ topology,+ &self.vertex,+ &self.fragment,+ &self.blend_state,+ );+ unsafe {+ device_context.DrawInstanced(vertex_count, instance_count, 0, 0);+ }+ Ok(())+ }++ fn draw_with_texture(+ &self,+ device_context: &ID3D11DeviceContext,+ texture: &[Option<ID3D11ShaderResourceView>],+ sampler: &[Option<ID3D11SamplerState>],+ instance_count: u32,+ ) -> Result<()> {+ set_pipeline_state(+ device_context,+ slice::from_ref(&self.view),+ D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,+ &self.vertex,+ &self.fragment,+ &self.blend_state,+ );+ unsafe {+ device_context.PSSetSamplers(0, Some(sampler));+ device_context.VSSetShaderResources(0, Some(texture));+ device_context.PSSetShaderResources(0, Some(texture));++ device_context.DrawInstanced(4, instance_count, 0, 0);+ }+ Ok(())+ }++ fn draw_range(+ &self,+ device_context: &ID3D11DeviceContext,+ batch_params_buffer: &ID3D11Buffer,+ first_instance: u32,+ instance_count: u32,+ ) -> Result<()> {+ anyhow::ensure!(+ first_instance as usize + instance_count as usize <= self.buffer_size,+ "DirectX instance range exceeds the {} buffer",+ self.label+ );+ update_batch_start(device_context, batch_params_buffer, first_instance)?;+ set_pipeline_state(+ device_context,+ slice::from_ref(&self.view),+ D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,+ &self.vertex,+ &self.fragment,+ &self.blend_state,+ );+ unsafe {+ device_context.DrawInstanced(4, instance_count, 0, 0);+ }+ Ok(())+ }++ fn draw_range_with_texture(+ &self,+ device_context: &ID3D11DeviceContext,+ texture: &[Option<ID3D11ShaderResourceView>],+ batch_params_buffer: &ID3D11Buffer,+ sampler: &[Option<ID3D11SamplerState>],+ first_instance: u32,+ instance_count: u32,+ ) -> Result<()> {+ anyhow::ensure!(+ first_instance as usize + instance_count as usize <= self.buffer_size,+ "DirectX instance range exceeds the {} buffer",+ self.label+ );+ update_batch_start(device_context, batch_params_buffer, first_instance)?;+ set_pipeline_state(+ device_context,+ slice::from_ref(&self.view),+ D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP,+ &self.vertex,+ &self.fragment,+ &self.blend_state,+ );+ unsafe {+ device_context.PSSetSamplers(0, Some(sampler));+ device_context.VSSetShaderResources(0, Some(texture));+ device_context.PSSetShaderResources(0, Some(texture));+ device_context.DrawInstanced(4, instance_count, 0, 0);+ }+ Ok(())+ }+}++#[derive(Clone, Copy)]+#[repr(C)]+struct PathRasterizationSprite {+ xy_position: Point<ScaledPixels>,+ st_position: Point<f32>,+ color: Background,+ bounds: Bounds<ScaledPixels>,+}++#[derive(Clone, Copy)]+#[repr(C)]+struct PathSprite {+ bounds: Bounds<ScaledPixels>,+}++impl Drop for DirectXRenderer {+ fn drop(&mut self) {+ #[cfg(debug_assertions)]+ if let Some(devices) = &self.devices {+ report_live_objects(&devices.device).ok();+ }+ }+}++#[inline]+fn get_comp_device(dxgi_device: &IDXGIDevice) -> Result<IDCompositionDevice> {+ Ok(unsafe { DCompositionCreateDevice(dxgi_device)? })+}++fn create_swap_chain_for_composition(+ dxgi_factory: &IDXGIFactory6,+ device: &ID3D11Device,+ width: u32,+ height: u32,+) -> Result<IDXGISwapChain1> {+ let desc = DXGI_SWAP_CHAIN_DESC1 {+ Width: width,+ Height: height,+ Format: RENDER_TARGET_FORMAT,+ Stereo: false.into(),+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,+ BufferCount: BUFFER_COUNT as u32,+ // Composition SwapChains only support the DXGI_SCALING_STRETCH Scaling.+ Scaling: DXGI_SCALING_STRETCH,+ SwapEffect: DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL,+ AlphaMode: DXGI_ALPHA_MODE_PREMULTIPLIED,+ Flags: 0,+ };+ Ok(unsafe { dxgi_factory.CreateSwapChainForComposition(device, &desc, None)? })+}++fn create_swap_chain(+ dxgi_factory: &IDXGIFactory6,+ device: &ID3D11Device,+ hwnd: HWND,+ width: u32,+ height: u32,+) -> Result<IDXGISwapChain1> {+ use windows::Win32::Graphics::Dxgi::DXGI_MWA_NO_ALT_ENTER;++ let desc = DXGI_SWAP_CHAIN_DESC1 {+ Width: width,+ Height: height,+ Format: RENDER_TARGET_FORMAT,+ Stereo: false.into(),+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ BufferUsage: DXGI_USAGE_RENDER_TARGET_OUTPUT,+ BufferCount: BUFFER_COUNT as u32,+ Scaling: DXGI_SCALING_NONE,+ SwapEffect: DXGI_SWAP_EFFECT_FLIP_SEQUENTIAL,+ AlphaMode: DXGI_ALPHA_MODE_IGNORE,+ Flags: 0,+ };+ let swap_chain =+ unsafe { dxgi_factory.CreateSwapChainForHwnd(device, hwnd, &desc, None, None) }?;+ unsafe { dxgi_factory.MakeWindowAssociation(hwnd, DXGI_MWA_NO_ALT_ENTER) }?;+ Ok(swap_chain)+}++#[inline]+fn create_resources(+ devices: &DirectXRendererDevices,+ swap_chain: &IDXGISwapChain1,+ width: u32,+ height: u32,+) -> Result<(+ ID3D11Texture2D,+ Option<ID3D11RenderTargetView>,+ ID3D11Texture2D,+ Option<ID3D11ShaderResourceView>,+ ID3D11Texture2D,+ Option<ID3D11RenderTargetView>,+ D3D11_VIEWPORT,+)> {+ let (render_target, render_target_view) =+ create_render_target_and_its_view(swap_chain, &devices.device)?;+ let (path_intermediate_texture, path_intermediate_srv) =+ create_path_intermediate_texture(&devices.device, width, height)?;+ let (path_intermediate_msaa_texture, path_intermediate_msaa_view) =+ create_path_intermediate_msaa_texture_and_view(&devices.device, width, height)?;+ let viewport = D3D11_VIEWPORT {+ TopLeftX: 0.0,+ TopLeftY: 0.0,+ Width: width as f32,+ Height: height as f32,+ MinDepth: 0.0,+ MaxDepth: 1.0,+ };+ Ok((+ render_target,+ render_target_view,+ path_intermediate_texture,+ path_intermediate_srv,+ path_intermediate_msaa_texture,+ path_intermediate_msaa_view,+ viewport,+ ))+}++#[inline]+fn create_render_target_and_its_view(+ swap_chain: &IDXGISwapChain1,+ device: &ID3D11Device,+) -> Result<(ID3D11Texture2D, Option<ID3D11RenderTargetView>)> {+ let render_target: ID3D11Texture2D = unsafe { swap_chain.GetBuffer(0) }?;+ let mut render_target_view = None;+ unsafe { device.CreateRenderTargetView(&render_target, None, Some(&mut render_target_view))? };+ Ok((render_target, render_target_view))+}++#[inline]+fn create_path_intermediate_texture(+ device: &ID3D11Device,+ width: u32,+ height: u32,+) -> Result<(ID3D11Texture2D, Option<ID3D11ShaderResourceView>)> {+ let texture = unsafe {+ let mut output = None;+ let desc = D3D11_TEXTURE2D_DESC {+ Width: width,+ Height: height,+ MipLevels: 1,+ ArraySize: 1,+ Format: RENDER_TARGET_FORMAT,+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ Usage: D3D11_USAGE_DEFAULT,+ BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32,+ CPUAccessFlags: 0,+ MiscFlags: 0,+ };+ device.CreateTexture2D(&desc, None, Some(&mut output))?;+ output.unwrap()+ };++ let mut shader_resource_view = None;+ unsafe { device.CreateShaderResourceView(&texture, None, Some(&mut shader_resource_view))? };++ Ok((texture, Some(shader_resource_view.unwrap())))+}++#[inline]+fn create_path_intermediate_msaa_texture_and_view(+ device: &ID3D11Device,+ width: u32,+ height: u32,+) -> Result<(ID3D11Texture2D, Option<ID3D11RenderTargetView>)> {+ let msaa_texture = unsafe {+ let mut output = None;+ let desc = D3D11_TEXTURE2D_DESC {+ Width: width,+ Height: height,+ MipLevels: 1,+ ArraySize: 1,+ Format: RENDER_TARGET_FORMAT,+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: PATH_MULTISAMPLE_COUNT,+ Quality: D3D11_STANDARD_MULTISAMPLE_PATTERN.0 as u32,+ },+ Usage: D3D11_USAGE_DEFAULT,+ BindFlags: D3D11_BIND_RENDER_TARGET.0 as u32,+ CPUAccessFlags: 0,+ MiscFlags: 0,+ };+ device.CreateTexture2D(&desc, None, Some(&mut output))?;+ output.unwrap()+ };+ let mut msaa_view = None;+ unsafe { device.CreateRenderTargetView(&msaa_texture, None, Some(&mut msaa_view))? };+ Ok((msaa_texture, Some(msaa_view.unwrap())))+}++#[inline]+fn set_rasterizer_state(device: &ID3D11Device, device_context: &ID3D11DeviceContext) -> Result<()> {+ let desc = D3D11_RASTERIZER_DESC {+ FillMode: D3D11_FILL_SOLID,+ CullMode: D3D11_CULL_NONE,+ FrontCounterClockwise: false.into(),+ DepthBias: 0,+ DepthBiasClamp: 0.0,+ SlopeScaledDepthBias: 0.0,+ DepthClipEnable: true.into(),+ ScissorEnable: false.into(),+ MultisampleEnable: true.into(),+ AntialiasedLineEnable: false.into(),+ };+ let rasterizer_state = unsafe {+ let mut state = None;+ device.CreateRasterizerState(&desc, Some(&mut state))?;+ state.unwrap()+ };+ unsafe { device_context.RSSetState(&rasterizer_state) };+ Ok(())+}++// https://learn.microsoft.com/en-us/windows/win32/api/d3d11/ns-d3d11-d3d11_blend_desc+#[inline]+fn create_blend_state(device: &ID3D11Device) -> Result<ID3D11BlendState> {+ let mut desc = D3D11_BLEND_DESC::default();+ desc.RenderTarget[0].BlendEnable = true.into();+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC_ALPHA;+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;+ desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8;+ unsafe {+ let mut state = None;+ device.CreateBlendState(&desc, Some(&mut state))?;+ Ok(state.unwrap())+ }+}++#[inline]+fn create_blend_state_for_subpixel_rendering(device: &ID3D11Device) -> Result<ID3D11BlendState> {+ let mut desc = D3D11_BLEND_DESC::default();+ desc.RenderTarget[0].BlendEnable = true.into();+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_SRC1_COLOR;+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC1_COLOR;+ // It does not make sense to draw transparent subpixel-rendered text, since it cannot be meaningfully alpha-blended onto anything else.+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO;+ desc.RenderTarget[0].RenderTargetWriteMask =+ D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8 & !D3D11_COLOR_WRITE_ENABLE_ALPHA.0 as u8;++ unsafe {+ let mut state = None;+ device.CreateBlendState(&desc, Some(&mut state))?;+ Ok(state.unwrap())+ }+}++#[inline]+fn create_blend_state_for_path_rasterization(device: &ID3D11Device) -> Result<ID3D11BlendState> {+ // If the feature level is set to greater than D3D_FEATURE_LEVEL_9_3, the display+ // device performs the blend in linear space, which is ideal.+ let mut desc = D3D11_BLEND_DESC::default();+ desc.RenderTarget[0].BlendEnable = true.into();+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;+ desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8;+ unsafe {+ let mut state = None;+ device.CreateBlendState(&desc, Some(&mut state))?;+ Ok(state.unwrap())+ }+}++#[inline]+fn create_blend_state_for_path_sprite(device: &ID3D11Device) -> Result<ID3D11BlendState> {+ // If the feature level is set to greater than D3D_FEATURE_LEVEL_9_3, the display+ // device performs the blend in linear space, which is ideal.+ let mut desc = D3D11_BLEND_DESC::default();+ desc.RenderTarget[0].BlendEnable = true.into();+ desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD;+ desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD;+ desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE;+ desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE;+ desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA;+ desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA;+ desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8;+ unsafe {+ let mut state = None;+ device.CreateBlendState(&desc, Some(&mut state))?;+ Ok(state.unwrap())+ }+}++#[inline]+fn create_vertex_shader(device: &ID3D11Device, bytes: &[u8]) -> Result<ID3D11VertexShader> {+ unsafe {+ let mut shader = None;+ device.CreateVertexShader(bytes, None, Some(&mut shader))?;+ Ok(shader.unwrap())+ }+}++#[inline]+fn create_fragment_shader(device: &ID3D11Device, bytes: &[u8]) -> Result<ID3D11PixelShader> {+ unsafe {+ let mut shader = None;+ device.CreatePixelShader(bytes, None, Some(&mut shader))?;+ Ok(shader.unwrap())+ }+}++#[inline]+fn create_constant_buffer<T>(device: &ID3D11Device) -> Result<Option<ID3D11Buffer>> {+ const { assert!(std::mem::size_of::<T>() != 0 && std::mem::size_of::<T>().is_multiple_of(16)) };+ let desc = D3D11_BUFFER_DESC {+ ByteWidth: std::mem::size_of::<T>() as u32,+ Usage: D3D11_USAGE_DYNAMIC,+ BindFlags: D3D11_BIND_CONSTANT_BUFFER.0 as u32,+ CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32,+ MiscFlags: 0,+ StructureByteStride: 0,+ };+ let mut buffer = None;+ unsafe { device.CreateBuffer(&desc, None, Some(&mut buffer)) }?;+ Ok(buffer)+}++#[inline]+fn create_buffer(+ device: &ID3D11Device,+ element_size: usize,+ buffer_size: usize,+) -> Result<ID3D11Buffer> {+ let desc = D3D11_BUFFER_DESC {+ ByteWidth: (element_size * buffer_size) as u32,+ Usage: D3D11_USAGE_DYNAMIC,+ BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32,+ CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32,+ MiscFlags: D3D11_RESOURCE_MISC_BUFFER_STRUCTURED.0 as u32,+ StructureByteStride: element_size as u32,+ };+ let mut buffer = None;+ unsafe { device.CreateBuffer(&desc, None, Some(&mut buffer)) }?;+ Ok(buffer.unwrap())+}++#[inline]+fn create_buffer_view(+ device: &ID3D11Device,+ buffer: &ID3D11Buffer,+) -> Result<Option<ID3D11ShaderResourceView>> {+ let mut view = None;+ unsafe { device.CreateShaderResourceView(buffer, None, Some(&mut view)) }?;+ Ok(view)+}++#[inline]+fn update_buffer<T>(+ device_context: &ID3D11DeviceContext,+ buffer: &ID3D11Buffer,+ data: &[T],+) -> Result<()> {+ unsafe {+ let mut dest = std::mem::zeroed();+ device_context.Map(buffer, 0, D3D11_MAP_WRITE_DISCARD, 0, Some(&mut dest))?;+ std::ptr::copy_nonoverlapping(data.as_ptr(), dest.pData as _, data.len());+ device_context.Unmap(buffer, 0);+ }+ Ok(())+}++#[inline]+fn update_batch_start(+ device_context: &ID3D11DeviceContext,+ buffer: &ID3D11Buffer,+ first_instance: u32,+) -> Result<()> {+ update_buffer(+ device_context,+ buffer,+ &[BatchParams {+ start_index: first_instance,+ _padding: [0; 3],+ }],+ )+}++#[inline]+fn set_pipeline_state(+ device_context: &ID3D11DeviceContext,+ buffer_view: &[Option<ID3D11ShaderResourceView>],+ topology: D3D_PRIMITIVE_TOPOLOGY,+ vertex_shader: &ID3D11VertexShader,+ fragment_shader: &ID3D11PixelShader,+ blend_state: &ID3D11BlendState,+) {+ unsafe {+ device_context.VSSetShaderResources(1, Some(buffer_view));+ device_context.PSSetShaderResources(1, Some(buffer_view));+ device_context.IASetPrimitiveTopology(topology);+ device_context.VSSetShader(vertex_shader, None);+ device_context.PSSetShader(fragment_shader, None);+ device_context.OMSetBlendState(blend_state, None, 0xFFFFFFFF);+ }+}++#[cfg(debug_assertions)]+fn report_live_objects(device: &ID3D11Device) -> Result<()> {+ let debug_device: ID3D11Debug = device.cast()?;+ unsafe {+ debug_device.ReportLiveDeviceObjects(D3D11_RLDO_DETAIL)?;+ }+ Ok(())+}++const BUFFER_COUNT: usize = 3;++pub(crate) mod shader_resources {+ use anyhow::Result;++ #[cfg(debug_assertions)]+ use windows::{+ Win32::Graphics::Direct3D::{+ Fxc::{D3DCOMPILE_DEBUG, D3DCOMPILE_SKIP_OPTIMIZATION, D3DCompileFromFile},+ ID3DBlob,+ },+ core::{HSTRING, PCSTR},+ };++ #[derive(Copy, Clone, Debug, Eq, PartialEq)]+ pub(crate) enum ShaderModule {+ BackdropPass,+ BackdropComposite,+ Quad,+ Shadow,+ Underline,+ PathRasterization,+ PathSprite,+ MonochromeSprite,+ SubpixelSprite,+ PolychromeSprite,+ EmojiRasterization,+ }++ #[derive(Copy, Clone, Debug, Eq, PartialEq)]+ pub(crate) enum ShaderTarget {+ Vertex,+ Fragment,+ }++ pub(crate) struct RawShaderBytes<'t> {+ inner: &'t [u8],++ #[cfg(debug_assertions)]+ _blob: ID3DBlob,+ }++ impl<'t> RawShaderBytes<'t> {+ pub(crate) fn new(module: ShaderModule, target: ShaderTarget) -> Result<Self> {+ #[cfg(not(debug_assertions))]+ {+ Ok(Self::from_bytes(module, target))+ }+ #[cfg(debug_assertions)]+ {+ let blob = build_shader_blob(module, target)?;+ let inner = unsafe {+ std::slice::from_raw_parts(+ blob.GetBufferPointer() as *const u8,+ blob.GetBufferSize(),+ )+ };+ Ok(Self { inner, _blob: blob })+ }+ }++ pub(crate) fn as_bytes(&'t self) -> &'t [u8] {+ self.inner+ }++ #[cfg(not(debug_assertions))]+ fn from_bytes(module: ShaderModule, target: ShaderTarget) -> Self {+ let bytes = match module {+ ShaderModule::BackdropPass => match target {+ ShaderTarget::Vertex => BACKDROP_PASS_VERTEX_BYTES,+ ShaderTarget::Fragment => BACKDROP_PASS_FRAGMENT_BYTES,+ },+ ShaderModule::BackdropComposite => match target {+ ShaderTarget::Vertex => BACKDROP_COMPOSITE_VERTEX_BYTES,+ ShaderTarget::Fragment => BACKDROP_COMPOSITE_FRAGMENT_BYTES,+ },+ ShaderModule::Quad => match target {+ ShaderTarget::Vertex => QUAD_VERTEX_BYTES,+ ShaderTarget::Fragment => QUAD_FRAGMENT_BYTES,+ },+ ShaderModule::Shadow => match target {+ ShaderTarget::Vertex => SHADOW_VERTEX_BYTES,+ ShaderTarget::Fragment => SHADOW_FRAGMENT_BYTES,+ },+ ShaderModule::Underline => match target {+ ShaderTarget::Vertex => UNDERLINE_VERTEX_BYTES,+ ShaderTarget::Fragment => UNDERLINE_FRAGMENT_BYTES,+ },+ ShaderModule::PathRasterization => match target {+ ShaderTarget::Vertex => PATH_RASTERIZATION_VERTEX_BYTES,+ ShaderTarget::Fragment => PATH_RASTERIZATION_FRAGMENT_BYTES,+ },+ ShaderModule::PathSprite => match target {+ ShaderTarget::Vertex => PATH_SPRITE_VERTEX_BYTES,+ ShaderTarget::Fragment => PATH_SPRITE_FRAGMENT_BYTES,+ },+ ShaderModule::MonochromeSprite => match target {+ ShaderTarget::Vertex => MONOCHROME_SPRITE_VERTEX_BYTES,+ ShaderTarget::Fragment => MONOCHROME_SPRITE_FRAGMENT_BYTES,+ },+ ShaderModule::SubpixelSprite => match target {+ ShaderTarget::Vertex => SUBPIXEL_SPRITE_VERTEX_BYTES,+ ShaderTarget::Fragment => SUBPIXEL_SPRITE_FRAGMENT_BYTES,+ },+ ShaderModule::PolychromeSprite => match target {+ ShaderTarget::Vertex => POLYCHROME_SPRITE_VERTEX_BYTES,+ ShaderTarget::Fragment => POLYCHROME_SPRITE_FRAGMENT_BYTES,+ },+ ShaderModule::EmojiRasterization => match target {+ ShaderTarget::Vertex => EMOJI_RASTERIZATION_VERTEX_BYTES,+ ShaderTarget::Fragment => EMOJI_RASTERIZATION_FRAGMENT_BYTES,+ },+ };+ Self { inner: bytes }+ }+ }++ #[cfg(debug_assertions)]+ pub(super) fn build_shader_blob(entry: ShaderModule, target: ShaderTarget) -> Result<ID3DBlob> {+ unsafe {+ use windows::Win32::Graphics::{+ Direct3D::ID3DInclude, Hlsl::D3D_COMPILE_STANDARD_FILE_INCLUDE,+ };++ let shader_name = if matches!(entry, ShaderModule::EmojiRasterization) {+ "color_text_raster.hlsl"+ } else {+ "shaders.hlsl"+ };++ let entry = format!(+ "{}_{}\0",+ entry.as_str(),+ match target {+ ShaderTarget::Vertex => "vertex",+ ShaderTarget::Fragment => "fragment",+ }+ );+ let target = match target {+ ShaderTarget::Vertex => "vs_4_1\0",+ ShaderTarget::Fragment => "ps_4_1\0",+ };++ let mut compile_blob = None;+ let mut error_blob = None;+ let shader_path = std::path::PathBuf::from(env!("CARGO_MANIFEST_DIR"))+ .join(&format!("src/{}", shader_name))+ .canonicalize()?;++ let entry_point = PCSTR::from_raw(entry.as_ptr());+ let target_cstr = PCSTR::from_raw(target.as_ptr());++ // really dirty trick because winapi bindings are unhappy otherwise+ let include_handler = &std::mem::transmute::<usize, ID3DInclude>(+ D3D_COMPILE_STANDARD_FILE_INCLUDE as usize,+ );++ let ret = D3DCompileFromFile(+ &HSTRING::from(shader_path.to_str().unwrap()),+ None,+ include_handler,+ entry_point,+ target_cstr,+ D3DCOMPILE_DEBUG | D3DCOMPILE_SKIP_OPTIMIZATION,+ 0,+ &mut compile_blob,+ Some(&mut error_blob),+ );+ if ret.is_err() {+ let Some(error_blob) = error_blob else {+ return Err(anyhow::anyhow!("{ret:?}"));+ };++ let error_string =+ std::ffi::CStr::from_ptr(error_blob.GetBufferPointer() as *const i8)+ .to_string_lossy();+ log::error!("Shader compile error: {}", error_string);+ return Err(anyhow::anyhow!("Compile error: {}", error_string));+ }+ Ok(compile_blob.unwrap())+ }+ }++ #[cfg(not(debug_assertions))]+ include!(concat!(env!("OUT_DIR"), "/shaders_bytes.rs"));++ #[cfg(debug_assertions)]+ impl ShaderModule {+ pub fn as_str(self) -> &'static str {+ match self {+ ShaderModule::BackdropPass => "backdrop_pass",+ ShaderModule::BackdropComposite => "backdrop_composite",+ ShaderModule::Quad => "quad",+ ShaderModule::Shadow => "shadow",+ ShaderModule::Underline => "underline",+ ShaderModule::PathRasterization => "path_rasterization",+ ShaderModule::PathSprite => "path_sprite",+ ShaderModule::MonochromeSprite => "monochrome_sprite",+ ShaderModule::SubpixelSprite => "subpixel_sprite",+ ShaderModule::PolychromeSprite => "polychrome_sprite",+ ShaderModule::EmojiRasterization => "emoji_rasterization",+ }+ }+ }+}++mod nvidia {+ use std::{+ ffi::CStr,+ os::raw::{c_char, c_int, c_uint},+ };++ use anyhow::Result;+ use windows::{Win32::System::LibraryLoader::GetProcAddress, core::s};++ use crate::with_dll_library;++ // https://github.com/NVIDIA/nvapi/blob/7cb76fce2f52de818b3da497af646af1ec16ce27/nvapi_lite_common.h#L180+ const NVAPI_SHORT_STRING_MAX: usize = 64;++ // https://github.com/NVIDIA/nvapi/blob/7cb76fce2f52de818b3da497af646af1ec16ce27/nvapi_lite_common.h#L235+ #[allow(non_camel_case_types)]+ type NvAPI_ShortString = [c_char; NVAPI_SHORT_STRING_MAX];++ // https://github.com/NVIDIA/nvapi/blob/7cb76fce2f52de818b3da497af646af1ec16ce27/nvapi_lite_common.h#L447+ #[allow(non_camel_case_types)]+ type NvAPI_SYS_GetDriverAndBranchVersion_t = unsafe extern "C" fn(+ driver_version: *mut c_uint,+ build_branch_string: *mut NvAPI_ShortString,+ ) -> c_int;++ pub(super) fn get_driver_version() -> Result<String> {+ #[cfg(target_pointer_width = "64")]+ let nvidia_dll_name = s!("nvapi64.dll");+ #[cfg(target_pointer_width = "32")]+ let nvidia_dll_name = s!("nvapi.dll");++ with_dll_library(nvidia_dll_name, |nvidia_dll| unsafe {+ let nvapi_query_addr = GetProcAddress(nvidia_dll, s!("nvapi_QueryInterface"))+ .ok_or_else(|| anyhow::anyhow!("Failed to get nvapi_QueryInterface address"))?;+ let nvapi_query: extern "C" fn(u32) -> *mut () = std::mem::transmute(nvapi_query_addr);++ // https://github.com/NVIDIA/nvapi/blob/7cb76fce2f52de818b3da497af646af1ec16ce27/nvapi_interface.h#L41+ let nvapi_get_driver_version_ptr = nvapi_query(0x2926aaad);+ if nvapi_get_driver_version_ptr.is_null() {+ anyhow::bail!("Failed to get NVIDIA driver version function pointer");+ }+ let nvapi_get_driver_version: NvAPI_SYS_GetDriverAndBranchVersion_t =+ std::mem::transmute(nvapi_get_driver_version_ptr);++ let mut driver_version: c_uint = 0;+ let mut build_branch_string: NvAPI_ShortString = [0; NVAPI_SHORT_STRING_MAX];+ let result = nvapi_get_driver_version(+ &mut driver_version as *mut c_uint,+ &mut build_branch_string as *mut NvAPI_ShortString,+ );++ if result != 0 {+ anyhow::bail!(+ "Failed to get NVIDIA driver version, error code: {}",+ result+ );+ }+ let major = driver_version / 100;+ let minor = driver_version % 100;+ let branch_string = CStr::from_ptr(build_branch_string.as_ptr());+ Ok(format!(+ "{}.{} {}",+ major,+ minor,+ branch_string.to_string_lossy()+ ))+ })+ }+}++mod amd {+ use std::os::raw::{c_char, c_int, c_void};++ use anyhow::Result;+ use windows::{Win32::System::LibraryLoader::GetProcAddress, core::s};++ use crate::with_dll_library;++ // https://github.com/GPUOpen-LibrariesAndSDKs/AGS_SDK/blob/5d8812d703d0335741b6f7ffc37838eeb8b967f7/ags_lib/inc/amd_ags.h#L145+ const AGS_CURRENT_VERSION: i32 = (6 << 22) | (3 << 12);++ // https://github.com/GPUOpen-LibrariesAndSDKs/AGS_SDK/blob/5d8812d703d0335741b6f7ffc37838eeb8b967f7/ags_lib/inc/amd_ags.h#L204+ // This is an opaque type, using struct to represent it properly for FFI+ #[repr(C)]+ struct AGSContext {+ _private: [u8; 0],+ }++ #[repr(C)]+ pub struct AGSGPUInfo {+ pub driver_version: *const c_char,+ pub radeon_software_version: *const c_char,+ pub num_devices: c_int,+ pub devices: *mut c_void,+ }++ // https://github.com/GPUOpen-LibrariesAndSDKs/AGS_SDK/blob/5d8812d703d0335741b6f7ffc37838eeb8b967f7/ags_lib/inc/amd_ags.h#L429+ #[allow(non_camel_case_types)]+ type agsInitialize_t = unsafe extern "C" fn(+ version: c_int,+ config: *const c_void,+ context: *mut *mut AGSContext,+ gpu_info: *mut AGSGPUInfo,+ ) -> c_int;++ // https://github.com/GPUOpen-LibrariesAndSDKs/AGS_SDK/blob/5d8812d703d0335741b6f7ffc37838eeb8b967f7/ags_lib/inc/amd_ags.h#L436+ #[allow(non_camel_case_types)]+ type agsDeInitialize_t = unsafe extern "C" fn(context: *mut AGSContext) -> c_int;++ pub(super) fn get_driver_version() -> Result<String> {+ #[cfg(target_pointer_width = "64")]+ let amd_dll_name = s!("amd_ags_x64.dll");+ #[cfg(target_pointer_width = "32")]+ let amd_dll_name = s!("amd_ags_x86.dll");++ with_dll_library(amd_dll_name, |amd_dll| unsafe {+ let ags_initialize_addr = GetProcAddress(amd_dll, s!("agsInitialize"))+ .ok_or_else(|| anyhow::anyhow!("Failed to get agsInitialize address"))?;+ let ags_deinitialize_addr = GetProcAddress(amd_dll, s!("agsDeInitialize"))+ .ok_or_else(|| anyhow::anyhow!("Failed to get agsDeInitialize address"))?;++ let ags_initialize: agsInitialize_t = std::mem::transmute(ags_initialize_addr);+ let ags_deinitialize: agsDeInitialize_t = std::mem::transmute(ags_deinitialize_addr);++ let mut context: *mut AGSContext = std::ptr::null_mut();+ let mut gpu_info: AGSGPUInfo = AGSGPUInfo {+ driver_version: std::ptr::null(),+ radeon_software_version: std::ptr::null(),+ num_devices: 0,+ devices: std::ptr::null_mut(),+ };++ let result = ags_initialize(+ AGS_CURRENT_VERSION,+ std::ptr::null(),+ &mut context,+ &mut gpu_info,+ );+ if result != 0 {+ anyhow::bail!("Failed to initialize AMD AGS, error code: {}", result);+ }++ // Vulkan actually returns this as the driver version+ let software_version = if !gpu_info.radeon_software_version.is_null() {+ std::ffi::CStr::from_ptr(gpu_info.radeon_software_version)+ .to_string_lossy()+ .into_owned()+ } else {+ "Unknown Radeon Software Version".to_string()+ };++ let driver_version = if !gpu_info.driver_version.is_null() {+ std::ffi::CStr::from_ptr(gpu_info.driver_version)+ .to_string_lossy()+ .into_owned()+ } else {+ "Unknown Radeon Driver Version".to_string()+ };++ ags_deinitialize(context);+ Ok(format!("{} ({})", software_version, driver_version))+ })+ }+}++mod dxgi {+ use windows::{+ Win32::Graphics::Dxgi::{IDXGIAdapter1, IDXGIDevice},+ core::Interface,+ };++ pub(super) fn get_driver_version(adapter: &IDXGIAdapter1) -> anyhow::Result<String> {+ let number = unsafe { adapter.CheckInterfaceSupport(&IDXGIDevice::IID as _) }?;+ Ok(format!(+ "{}.{}.{}.{}",+ number >> 48,+ (number >> 32) & 0xFFFF,+ (number >> 16) & 0xFFFF,+ number & 0xFFFF+ ))+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/directx_renderer/backdrop.rs b/native/vendor/wu/crates/gpui_windows/src/directx_renderer/backdrop.rsnew file mode 100644index 00000000000..f595d9ae6f8--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/directx_renderer/backdrop.rs@@ -0,0 +1,443 @@+use super::*;++const IDLE_FRAMES: u32 = 120;+const KERNEL_VECTORS: usize = 33;+// Keep in sync with backdrop_pass_fragment in shaders.hlsl.+const MAX_SIGMA: f32 = 64.;+const PARAMS_SLOT: u32 = 2;++// Layout must match cbuffer BackdropParams in shaders.hlsl.+#[repr(C)]+#[derive(Clone, Copy)]+struct Params {+ bounds: [f32; 4],+ corners: [f32; 4],+ clip: [f32; 4],+ source: [f32; 4],+ kernel: [f32; 4],+ weights: [[f32; 4]; KERNEL_VECTORS],+}++struct Texture {+ texture: ID3D11Texture2D,+ srv: Option<ID3D11ShaderResourceView>,+ rtv: Option<ID3D11RenderTargetView>,+}++impl Texture {+ fn new(device: &ID3D11Device, width: u32, height: u32, renderable: bool) -> Result<Self> {+ let desc = D3D11_TEXTURE2D_DESC {+ Width: width,+ Height: height,+ MipLevels: 1,+ ArraySize: 1,+ Format: RENDER_TARGET_FORMAT,+ SampleDesc: DXGI_SAMPLE_DESC {+ Count: 1,+ Quality: 0,+ },+ Usage: D3D11_USAGE_DEFAULT,+ BindFlags: (D3D11_BIND_SHADER_RESOURCE.0+ | if renderable {+ D3D11_BIND_RENDER_TARGET.0+ } else {+ 0+ }) as u32,+ ..Default::default()+ };+ unsafe {+ let mut texture = None;+ device.CreateTexture2D(&desc, None, Some(&mut texture))?;+ let texture = texture.context("creating backdrop texture")?;+ let mut srv = None;+ device.CreateShaderResourceView(&texture, None, Some(&mut srv))?;+ let mut rtv = None;+ if renderable {+ device.CreateRenderTargetView(&texture, None, Some(&mut rtv))?;+ }+ Ok(Self { texture, srv, rtv })+ }+ }+}++struct Scratch {+ width: u32,+ height: u32,+ downsample: u32,+ snapshot: Texture,+ horizontal: Texture,+ vertical: Texture,+}++struct Shaders {+ vertex: ID3D11VertexShader,+ fragment: ID3D11PixelShader,+}++impl Shaders {+ fn new(device: &ID3D11Device, module: ShaderModule) -> Result<Self> {+ Ok(Self {+ vertex: create_vertex_shader(+ device,+ RawShaderBytes::new(module, ShaderTarget::Vertex)?.as_bytes(),+ )?,+ fragment: create_fragment_shader(+ device,+ RawShaderBytes::new(module, ShaderTarget::Fragment)?.as_bytes(),+ )?,+ })+ }+}++pub(super) struct BackdropResources {+ pass: Shaders,+ composite: Shaders,+ params: Option<ID3D11Buffer>,+ sampler: Option<ID3D11SamplerState>,+ scratch: Option<Scratch>,+ idle_frames: u32,+}++impl BackdropResources {+ #[cfg(test)]+ pub(super) fn snapshot(&self) -> &ID3D11Texture2D {+ &self.scratch.as_ref().unwrap().snapshot.texture+ }++ #[cfg(test)]+ pub(super) fn has_scratch(&self) -> bool {+ self.scratch.is_some()+ }++ fn new(device: &ID3D11Device) -> Result<Self> {+ let pass = Shaders::new(device, ShaderModule::BackdropPass)?;+ let composite = Shaders::new(device, ShaderModule::BackdropComposite)?;+ unsafe {+ let mut params = None;+ device.CreateBuffer(+ &D3D11_BUFFER_DESC {+ ByteWidth: std::mem::size_of::<Params>() as u32,+ Usage: D3D11_USAGE_DYNAMIC,+ BindFlags: D3D11_BIND_CONSTANT_BUFFER.0 as u32,+ CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32,+ ..Default::default()+ },+ None,+ Some(&mut params),+ )?;+ let mut sampler = None;+ device.CreateSamplerState(+ &D3D11_SAMPLER_DESC {+ Filter: D3D11_FILTER_MIN_MAG_MIP_LINEAR,+ AddressU: D3D11_TEXTURE_ADDRESS_CLAMP,+ AddressV: D3D11_TEXTURE_ADDRESS_CLAMP,+ AddressW: D3D11_TEXTURE_ADDRESS_CLAMP,+ MaxLOD: D3D11_FLOAT32_MAX,+ MaxAnisotropy: 1,+ ComparisonFunc: D3D11_COMPARISON_ALWAYS,+ ..Default::default()+ },+ Some(&mut sampler),+ )?;+ Ok(Self {+ pass,+ composite,+ params,+ sampler,+ scratch: None,+ idle_frames: 0,+ })+ }+ }++ pub(super) fn release_idle_scratch(&mut self) {+ self.idle_frames = self.idle_frames.saturating_add(1);+ if self.idle_frames >= IDLE_FRAMES {+ self.scratch = None;+ }+ }++ pub(super) fn release_scratch(&mut self) {+ self.scratch = None;+ }++ fn ensure_scratch(+ &mut self,+ device: &ID3D11Device,+ width: u32,+ height: u32,+ downsample: u32,+ viewport: [u32; 2],+ ) -> Result<()> {+ self.idle_frames = 0;+ if self+ .scratch+ .as_ref()+ .is_some_and(|s| s.width >= width && s.height >= height && s.downsample == downsample)+ {+ return Ok(());+ }+ // Clamped to the drawable so every cached texel holds real pixels.+ let previous = self.scratch.as_ref();+ let width = width+ .max(previous.map_or(0, |s| s.width))+ .div_ceil(64)+ .saturating_mul(64)+ .min(viewport[0]);+ let height = height+ .max(previous.map_or(0, |s| s.height))+ .div_ceil(64)+ .saturating_mul(64)+ .min(viewport[1]);+ self.scratch = Some(Scratch {+ width,+ height,+ downsample,+ snapshot: Texture::new(device, width, height, false)?,+ horizontal: Texture::new(device, width.div_ceil(downsample), height, true)?,+ vertical: Texture::new(+ device,+ width.div_ceil(downsample),+ height.div_ceil(downsample),+ true,+ )?,+ });+ Ok(())+ }++ fn draw_pass(+ &self,+ context: &ID3D11DeviceContext,+ shaders: &Shaders,+ source: &Texture,+ target: &Option<ID3D11RenderTargetView>,+ viewport: D3D11_VIEWPORT,+ params: Params,+ ) -> Result<()> {+ update_buffer(+ context,+ self.params+ .as_ref()+ .context("backdrop params buffer missing")?,+ &[params],+ )?;+ unsafe {+ context.PSSetShaderResources(0, Some(&[None]));+ context.OMSetRenderTargets(Some(slice::from_ref(target)), None);+ context.PSSetShaderResources(0, Some(slice::from_ref(&source.srv)));+ context.VSSetConstantBuffers(PARAMS_SLOT, Some(slice::from_ref(&self.params)));+ context.PSSetConstantBuffers(PARAMS_SLOT, Some(slice::from_ref(&self.params)));+ context.PSSetSamplers(0, Some(slice::from_ref(&self.sampler)));+ context.RSSetViewports(Some(&[viewport]));+ context.IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP);+ context.VSSetShader(&shaders.vertex, None);+ context.PSSetShader(&shaders.fragment, None);+ // The premultiplied result must replace the target, not blend over it.+ context.OMSetBlendState(None, None, u32::MAX);+ context.Draw(4, 0);+ }+ Ok(())+ }+}++impl DirectXRenderer {+ pub(super) fn draw_backdrop_blur(&mut self, blur: &BackdropBlur) -> Result<()> {+ if !blur.blur_radius.0.is_finite()+ || !valid_bounds(blur.bounds)+ || !valid_bounds(blur.content_mask.bounds)+ || ![+ blur.corner_radii.top_left.0,+ blur.corner_radii.top_right.0,+ blur.corner_radii.bottom_right.0,+ blur.corner_radii.bottom_left.0,+ ]+ .iter()+ .all(|value| value.is_finite() && *value >= 0.)+ {+ return Ok(());+ }+ let visible = blur+ .bounds+ .intersect(&blur.content_mask.bounds)+ .intersect(&Bounds::new(+ point(ScaledPixels(0.), ScaledPixels(0.)),+ size(+ ScaledPixels(self.width as f32),+ ScaledPixels(self.height as f32),+ ),+ ));+ if visible.size.width.0 <= 0. || visible.size.height.0 <= 0. {+ return Ok(());+ }+ let sigma = blur.blur_radius.0.clamp(1., MAX_SIGMA);+ let padding = (sigma * 3.).ceil() + 2.;+ let x0 = (visible.origin.x.0 - padding).floor().max(0.) as u32;+ let y0 = (visible.origin.y.0 - padding).floor().max(0.) as u32;+ let x1 = (visible.origin.x.0 + visible.size.width.0 + padding)+ .ceil()+ .min(self.width as f32) as u32;+ let y1 = (visible.origin.y.0 + visible.size.height.0 + padding)+ .ceil()+ .min(self.height as f32) as u32;+ if x1 <= x0 || y1 <= y0 {+ return Ok(());+ }+ let downsample = ((sigma / 8.) as u32).clamp(1, 4);+ let devices = self.devices.as_ref().context("devices missing")?;+ let resources = self.resources.as_mut().context("resources missing")?;+ if resources.backdrop.is_none() {+ resources.backdrop = Some(BackdropResources::new(&devices.device)?);+ }+ let backdrop = resources+ .backdrop+ .as_mut()+ .context("backdrop resources missing")?;+ backdrop.ensure_scratch(+ &devices.device,+ x1 - x0,+ y1 - y0,+ downsample,+ [self.width, self.height],+ )?;+ let scratch = backdrop+ .scratch+ .as_ref()+ .context("backdrop scratch missing")?;+ let copy_x = x0.min(self.width - scratch.width);+ let copy_y = y0.min(self.height - scratch.height);+ let context = &devices.device_context;+ unsafe {+ context+ .VSSetConstantBuffers(0, Some(slice::from_ref(&self.globals.global_params_buffer)));+ context+ .PSSetConstantBuffers(0, Some(slice::from_ref(&self.globals.global_params_buffer)));+ // D3D11 silently nulls SRVs that conflict with a bound render target.+ context.VSSetShaderResources(0, Some(&[None]));+ context.PSSetShaderResources(0, Some(&[None]));+ context.OMSetRenderTargets(None, None);+ context.CopySubresourceRegion(+ &scratch.snapshot.texture,+ 0,+ 0,+ 0,+ 0,+ resources+ .render_target+ .as_ref()+ .context("missing render target")?,+ 0,+ Some(&D3D11_BOX {+ left: copy_x,+ top: copy_y,+ front: 0,+ right: copy_x + scratch.width,+ bottom: copy_y + scratch.height,+ back: 1,+ }),+ );+ }+ let mut params = Params {+ bounds: rect(blur.bounds),+ corners: [+ blur.corner_radii.top_left.0,+ blur.corner_radii.top_right.0,+ blur.corner_radii.bottom_right.0,+ blur.corner_radii.bottom_left.0,+ ],+ clip: rect(blur.content_mask.bounds),+ source: [+ copy_x as f32,+ copy_y as f32,+ scratch.width as f32,+ scratch.height as f32,+ ],+ kernel: [1. / scratch.width as f32, 0., sigma, downsample as f32],+ weights: gaussian_weights(sigma),+ };+ let viewport = D3D11_VIEWPORT {+ Width: scratch.width.div_ceil(downsample) as f32,+ Height: scratch.height as f32,+ MaxDepth: 1.,+ ..Default::default()+ };+ // Restore state even on failure so the context never holds expired scratch textures.+ let result = (|| {+ backdrop.draw_pass(+ context,+ &backdrop.pass,+ &scratch.snapshot,+ &scratch.horizontal.rtv,+ viewport,+ params,+ )?;+ params.kernel = [0., 1. / viewport.Height, sigma, downsample as f32];+ let viewport = D3D11_VIEWPORT {+ Height: scratch.height.div_ceil(downsample) as f32,+ ..viewport+ };+ backdrop.draw_pass(+ context,+ &backdrop.pass,+ &scratch.horizontal,+ &scratch.vertical.rtv,+ viewport,+ params,+ )?;+ backdrop.draw_pass(+ context,+ &backdrop.composite,+ &scratch.vertical,+ &resources.render_target_view,+ resources.viewport,+ params,+ )+ })();+ unsafe {+ context.PSSetShaderResources(0, Some(&[None]));+ context.VSSetConstantBuffers(PARAMS_SLOT, Some(&[None]));+ context.PSSetConstantBuffers(PARAMS_SLOT, Some(&[None]));+ context.PSSetSamplers(0, Some(&[None]));+ context.VSSetShader(None, None);+ context.PSSetShader(None, None);+ context.OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None);+ context.RSSetViewports(Some(&[resources.viewport]));+ }+ result.context("Drawing backdrop blur")+ }+}++fn rect(bounds: Bounds<ScaledPixels>) -> [f32; 4] {+ [+ bounds.origin.x.0,+ bounds.origin.y.0,+ bounds.size.width.0,+ bounds.size.height.0,+ ]+}++fn valid_bounds(bounds: Bounds<ScaledPixels>) -> bool {+ rect(bounds).iter().all(|value| value.is_finite())+ && bounds.size.width.0 >= 0.+ && bounds.size.height.0 >= 0.+ && bounds.right().0.is_finite()+ && bounds.bottom().0.is_finite()+}++fn gaussian_weights(sigma: f32) -> [[f32; 4]; KERNEL_VECTORS] {+ let mut weights = [[0.; 4]; KERNEL_VECTORS];+ let radius = (sigma * 3.).ceil() as usize;+ if radius > 128 {+ return weights;+ }+ let mut total = 0.;+ for k in -(radius as i32)..=radius as i32 {+ let weight = (-(k as f32) * k as f32 / (2. * sigma * sigma)).exp();+ total += weight;+ let k = k.unsigned_abs() as usize;+ weights[k / 4][k % 4] = weight;+ }+ for weight in weights.iter_mut().flatten() {+ *weight /= total;+ }+ weights+}diff --git a/native/vendor/wu/crates/gpui_windows/src/directx_renderer/backdrop_tests.rs b/native/vendor/wu/crates/gpui_windows/src/directx_renderer/backdrop_tests.rsnew file mode 100644index 00000000000..54d3561639d--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/directx_renderer/backdrop_tests.rs@@ -0,0 +1,1006 @@+use super::*;+use windows::{+ Win32::{Foundation::HMODULE, UI::WindowsAndMessaging::*},+ core::w,+};++struct TestWindow(HWND);++impl Drop for TestWindow {+ fn drop(&mut self) {+ unsafe { DestroyWindow(self.0).unwrap() };+ }+}++fn warp_devices() -> Result<DirectXDevices> {+ unsafe {+ let mut device = None;+ let mut context = None;+ let debug_result = D3D11CreateDevice(+ None,+ D3D_DRIVER_TYPE_WARP,+ HMODULE::default(),+ D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_DEBUG,+ Some(&[D3D_FEATURE_LEVEL_11_0]),+ D3D11_SDK_VERSION,+ Some(&mut device),+ None,+ Some(&mut context),+ );+ if let Err(error) = debug_result {+ if error.code() != DXGI_ERROR_SDK_COMPONENT_MISSING {+ return Err(error.into());+ }+ D3D11CreateDevice(+ None,+ D3D_DRIVER_TYPE_WARP,+ HMODULE::default(),+ D3D11_CREATE_DEVICE_BGRA_SUPPORT,+ Some(&[D3D_FEATURE_LEVEL_11_0]),+ D3D11_SDK_VERSION,+ Some(&mut device),+ None,+ Some(&mut context),+ )?;+ }+ let device = device.unwrap();+ let dxgi: IDXGIDevice = device.cast()?;+ Ok(DirectXDevices {+ adapter: dxgi.GetAdapter()?.cast()?,+ dxgi_factory: CreateDXGIFactory2(DXGI_CREATE_FACTORY_FLAGS(0))?,+ device,+ device_context: context.unwrap(),+ })+ }+}++fn warp_renderer() -> Result<(DirectXRenderer, TestWindow)> {+ unsafe {+ let devices = warp_devices()?;+ let window = TestWindow(CreateWindowExW(+ WINDOW_EX_STYLE::default(),+ w!("STATIC"),+ w!("GPUI WARP regression"),+ WS_OVERLAPPED,+ 0,+ 0,+ 64,+ 64,+ None,+ None,+ None,+ None,+ )?);+ let mut renderer = DirectXRenderer::new(window.0, &devices, true)?;+ renderer.resize(size(DevicePixels(64), DevicePixels(64)))?;+ Ok((renderer, window))+ }+}++fn bounds(x: f32, y: f32, width: f32, height: f32) -> Bounds<ScaledPixels> {+ Bounds::new(+ point(ScaledPixels(x), ScaledPixels(y)),+ size(ScaledPixels(width), ScaledPixels(height)),+ )+}++fn quad(order: u32, rect: Bounds<ScaledPixels>, color: Hsla) -> Quad {+ Quad {+ order,+ bounds: rect,+ content_mask: ContentMask {+ bounds: bounds(0., 0., 64., 64.),+ },+ background: color.into(),+ ..Default::default()+ }+}++fn blur(order: u32) -> BackdropBlur {+ BackdropBlur {+ order,+ blur_radius: ScaledPixels(3.),+ bounds: bounds(8., 8., 48., 48.),+ content_mask: ContentMask {+ bounds: bounds(0., 0., 64., 64.),+ },+ corner_radii: Corners::all(ScaledPixels(8.)),+ }+}++fn pixels(renderer: &DirectXRenderer) -> Result<Vec<[u8; 4]>> {+ let devices = renderer.devices.as_ref().unwrap();+ let target = renderer+ .resources+ .as_ref()+ .unwrap()+ .render_target+ .as_ref()+ .unwrap();+ unsafe {+ let mut desc = D3D11_TEXTURE2D_DESC::default();+ target.GetDesc(&mut desc);+ desc.Usage = D3D11_USAGE_STAGING;+ desc.BindFlags = 0;+ desc.CPUAccessFlags = D3D11_CPU_ACCESS_READ.0 as u32;+ let mut staging = None;+ devices+ .device+ .CreateTexture2D(&desc, None, Some(&mut staging))?;+ let staging = staging.unwrap();+ devices.device_context.OMSetRenderTargets(None, None);+ devices.device_context.CopyResource(&staging, target);+ let mut mapped = D3D11_MAPPED_SUBRESOURCE::default();+ devices+ .device_context+ .Map(&staging, 0, D3D11_MAP_READ, 0, Some(&mut mapped))?;+ let mut result = Vec::new();+ for y in 0..desc.Height {+ let row = slice::from_raw_parts(+ (mapped.pData as *const u8).add((y * mapped.RowPitch) as usize) as *const [u8; 4],+ desc.Width as usize,+ );+ result.extend_from_slice(row);+ }+ devices.device_context.Unmap(&staging, 0);+ assert_no_gpu_errors(&devices.device)?;+ Ok(result)+ }+}++fn assert_no_gpu_errors(device: &ID3D11Device) -> Result<()> {+ let Ok(queue) = device.cast::<ID3D11InfoQueue>() else {+ return Ok(());+ };+ unsafe {+ for index in 0..queue.GetNumStoredMessagesAllowedByRetrievalFilter() {+ let mut length = 0;+ queue.GetMessage(index, None, &mut length)?;+ // usize storage guarantees the alignment required by D3D11_MESSAGE.+ let mut buffer = vec![0usize; length.div_ceil(std::mem::size_of::<usize>())];+ let message = buffer.as_mut_ptr().cast::<D3D11_MESSAGE>();+ queue.GetMessage(index, Some(message), &mut length)?;+ let message = &*message;+ assert!(+ !matches!(+ message.Severity,+ D3D11_MESSAGE_SEVERITY_CORRUPTION+ | D3D11_MESSAGE_SEVERITY_ERROR+ | D3D11_MESSAGE_SEVERITY_WARNING+ ),+ "D3D11 validation: {}",+ std::ffi::CStr::from_ptr(message.pDescription.cast()).to_string_lossy()+ );+ }+ queue.ClearStoredMessages();+ }+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_backdrop_blurs_pixels() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ let mut scene = Scene::default();+ scene+ .quads+ .push(quad(0, bounds(0., 0., 32., 64.), hsla(0., 0., 0., 1.)));+ scene+ .quads+ .push(quad(0, bounds(32., 0., 32., 64.), hsla(0., 0., 1., 1.)));+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ let sharp = pixels(&renderer)?;+ scene.backdrop_blurs.push(blur(1));+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ let blurred = pixels(&renderer)?;+ assert_eq!(sharp[32 * 64 + 31][0], 0);+ assert!(+ blurred[32 * 64 + 31][0] > 50,+ "backdrop should soften black/white boundary: {:?}",+ blurred[32 * 64 + 31]+ );+ assert!(blurred[32 * 64 + 32][0] < 205);+ assert_eq!(+ blurred[2 * 64 + 31],+ sharp[2 * 64 + 31],+ "outside blur remains untouched"+ );+ Ok(())+}++fn sample(image: &[[u8; 4]], width: usize, height: usize, x: f32, y: f32) -> [f32; 4] {+ let x = x.clamp(0., (width - 1) as f32);+ let y = y.clamp(0., (height - 1) as f32);+ let x0 = x.floor() as usize;+ let y0 = y.floor() as usize;+ let x1 = (x0 + 1).min(width - 1);+ let y1 = (y0 + 1).min(height - 1);+ let tx = x - x0 as f32;+ let ty = y - y0 as f32;+ std::array::from_fn(|c| {+ let top =+ image[y0 * width + x0][c] as f32 * (1. - tx) + image[y0 * width + x1][c] as f32 * tx;+ let bottom =+ image[y1 * width + x0][c] as f32 * (1. - tx) + image[y1 * width + x1][c] as f32 * tx;+ top * (1. - ty) + bottom * ty+ })+}++fn cpu_blur(image: &[[u8; 4]], width: usize, height: usize, blur: BackdropBlur) -> Vec<[u8; 4]> {+ let sigma = blur.blur_radius.0.clamp(1., 64.);+ let stride = ((sigma / 8.) as usize).clamp(1, 4);+ let bw = width.div_ceil(stride);+ let bh = height.div_ceil(stride);+ let radius = (sigma * 3.).ceil() as i32;+ let weights: Vec<f32> = (-radius..=radius)+ .map(|k| (-(k * k) as f32 / (2. * sigma * sigma)).exp())+ .collect();+ let total: f32 = weights.iter().sum();+ let mut horizontal = Vec::with_capacity(bw * bh);+ let mut vertical = Vec::with_capacity(bw * bh);+ for y in 0..height {+ for x in 0..bw {+ let mut sum = [0.; 4];+ for (k, weight) in (-radius..=radius).zip(&weights) {+ let value = sample(+ image,+ width,+ height,+ (x as f32 + 0.5) * width as f32 / bw as f32 - 0.5 + k as f32,+ y as f32,+ );+ for c in 0..4 {+ sum[c] += value[c] * weight / total;+ }+ }+ horizontal.push(sum.map(|v| v.round() as u8));+ }+ }+ for y in 0..bh {+ for x in 0..bw {+ let mut sum = [0.; 4];+ for (k, weight) in (-radius..=radius).zip(&weights) {+ let value = sample(+ &horizontal,+ bw,+ height,+ x as f32,+ (y as f32 + 0.5) * height as f32 / bh as f32 - 0.5 + k as f32,+ );+ for c in 0..4 {+ sum[c] += value[c] * weight / total;+ }+ }+ vertical.push(sum.map(|v| v.round() as u8));+ }+ }+ let mut result = image.to_vec();+ let rect = blur.bounds;+ let clip = rect.intersect(&blur.content_mask.bounds);+ for y in 0..height {+ for x in 0..width {+ let px = x as f32 + 0.5;+ let py = y as f32 + 0.5;+ if px < clip.origin.x.0+ || px > clip.right().0+ || py < clip.origin.y.0+ || py > clip.bottom().0+ {+ continue;+ }+ let left = px < rect.center().x.0;+ let top = py < rect.center().y.0;+ let radius = match (left, top) {+ (true, true) => blur.corner_radii.top_left.0,+ (false, true) => blur.corner_radii.top_right.0,+ (false, false) => blur.corner_radii.bottom_right.0,+ (true, false) => blur.corner_radii.bottom_left.0,+ };+ let cx = if left {+ rect.left().0 + radius+ } else {+ rect.right().0 - radius+ };+ let cy = if top {+ rect.top().0 + radius+ } else {+ rect.bottom().0 - radius+ };+ if (left && px < cx || !left && px > cx)+ && (top && py < cy || !top && py > cy)+ && (px - cx).hypot(py - cy) > radius+ {+ continue;+ }+ result[y * width + x] = sample(+ &vertical,+ bw,+ bh,+ px * bw as f32 / width as f32 - 0.5,+ py * bh as f32 / height as f32 - 0.5,+ )+ .map(|v| v.round() as u8);+ }+ }+ result+}++fn assert_pixels(actual: &[[u8; 4]], expected: &[[u8; 4]], tolerance: u8) {+ assert_eq!(actual.len(), expected.len());+ for (index, (actual, expected)) in actual.iter().zip(expected).enumerate() {+ for c in 0..4 {+ assert!(+ actual[c].abs_diff(expected[c]) <= tolerance,+ "pixel {index} channel {c}: actual {actual:?}, expected {expected:?}"+ );+ }+ }+}++fn checkerboard() -> Scene {+ let mut scene = Scene::default();+ for y in 0..16 {+ for x in 0..16 {+ scene.quads.push(quad(+ 0,+ bounds((x * 4) as f32, (y * 4) as f32, 4., 4.),+ hsla(0., 0., ((x + y) % 2) as f32, 1.),+ ));+ }+ }+ scene+}++#[::core::prelude::v1::test]+fn warp_nested_backdrops_match_sequential_reference() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ let mut scene = checkerboard();+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ let original = pixels(&renderer)?;+ let parent = blur(1);+ let child = BackdropBlur {+ order: 3,+ bounds: bounds(16., 16., 32., 32.),+ content_mask: ContentMask {+ bounds: bounds(20., 18., 24., 28.),+ },+ corner_radii: Corners::all(ScaledPixels(9.)),+ ..blur(3)+ };+ let mut expected = cpu_blur(&original, 64, 64, parent);+ for y in 0..64 {+ for x in 30..34 {+ expected[y * 64 + x] = [0, 0, 255, 255];+ }+ }+ expected = cpu_blur(&expected, 64, 64, child);+ for y in 28..36 {+ for x in 28..36 {+ expected[y * 64 + x] = [0, 255, 0, 255];+ }+ }+ scene+ .quads+ .push(quad(2, bounds(30., 0., 4., 64.), hsla(0., 1., 0.5, 1.)));+ scene.quads.push(quad(+ 3,+ bounds(28., 28., 8., 8.),+ hsla(1. / 3., 1., 0.5, 1.),+ ));+ scene.backdrop_blurs = vec![parent, child];+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ assert_pixels(&pixels(&renderer)?, &expected, 2);+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_backdrop_preserves_premultiplied_alpha() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ let mut scene = Scene::default();+ scene+ .quads+ .push(quad(0, bounds(0., 0., 32., 64.), hsla(0., 1., 0.5, 0.5)));+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let original = pixels(&renderer)?;+ let expected = cpu_blur(&original, 64, 64, blur(1));+ scene.backdrop_blurs = vec![blur(1)];+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let actual = pixels(&renderer)?;+ assert_pixels(&actual, &expected, 2);+ assert_eq!(+ actual[32 * 64 + 16][3],+ original[32 * 64 + 16][3],+ "replacement must not accumulate alpha"+ );+ for pixel in actual {+ assert!(+ pixel[2] <= pixel[3] + 1,+ "premultiplied red cannot exceed alpha"+ );+ }+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_backdrop_downsampling_and_large_kernel() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ renderer.resize(size(DevicePixels(65), DevicePixels(67)))?;+ let original: Vec<[u8; 4]> = (0..67)+ .flat_map(|y| {+ (0..65).map(move |x| {+ [+ (x * 3) as u8,+ (y * 3) as u8,+ if x < 32 { 0 } else { 255 },+ 255,+ ]+ })+ })+ .collect();+ for sigma in [0., 2.5, 16., 24., 32., 64., 180., f32::MAX] {+ renderer.pre_draw(&[0.; 4])?;+ let context = &renderer.devices.as_ref().unwrap().device_context;+ unsafe {+ context.VSSetConstantBuffers(0, Some(&[None]));+ context.PSSetConstantBuffers(0, Some(&[None]));+ context.OMSetRenderTargets(None, None);+ context.UpdateSubresource(+ renderer+ .resources+ .as_ref()+ .unwrap()+ .render_target+ .as_ref()+ .unwrap(),+ 0,+ None,+ original.as_ptr().cast(),+ 65 * 4,+ 0,+ );+ }+ let blur = BackdropBlur {+ blur_radius: ScaledPixels(sigma),+ bounds: bounds(0., 0., 65., 67.),+ content_mask: ContentMask {+ bounds: bounds(0., 0., 65., 67.),+ },+ corner_radii: Corners::default(),+ ..blur(0)+ };+ renderer.draw_backdrop_blur(&blur)?;+ assert_pixels(&pixels(&renderer)?, &cpu_blur(&original, 65, 67, blur), 2);+ }+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_backdrop_cache_lifecycle() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ let empty = Scene::default();+ renderer.draw_scene(&empty, WindowBackgroundAppearance::Opaque)?;+ assert!(renderer.resources.as_ref().unwrap().backdrop.is_none());+ let mut scene = checkerboard();+ scene.backdrop_blurs = vec![blur(1)];+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ let expected = pixels(&renderer)?;+ let snapshot = renderer+ .resources+ .as_ref()+ .unwrap()+ .backdrop+ .as_ref()+ .unwrap()+ .snapshot()+ .clone();+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ assert_eq!(+ &snapshot,+ renderer+ .resources+ .as_ref()+ .unwrap()+ .backdrop+ .as_ref()+ .unwrap()+ .snapshot(),+ "stable blur reuses GPU scratch"+ );+ assert_pixels(&pixels(&renderer)?, &expected, 0);+ drop(snapshot);+ for _ in 0..119 {+ renderer.draw_scene(&empty, WindowBackgroundAppearance::Opaque)?;+ }+ assert!(+ renderer+ .resources+ .as_ref()+ .unwrap()+ .backdrop+ .as_ref()+ .unwrap()+ .has_scratch()+ );+ renderer.draw_scene(&empty, WindowBackgroundAppearance::Opaque)?;+ assert!(+ renderer+ .resources+ .as_ref()+ .unwrap()+ .backdrop+ .as_ref()+ .is_some_and(|backdrop| !backdrop.has_scratch()),+ "idle scratch must be released while shaders stay cached"+ );+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ assert_pixels(&pixels(&renderer)?, &expected, 0);+ renderer.resize(size(DevicePixels(81), DevicePixels(73)))?;+ assert!(+ renderer+ .resources+ .as_ref()+ .unwrap()+ .backdrop+ .as_ref()+ .is_some_and(|backdrop| !backdrop.has_scratch()),+ "resize releases scratch while shaders stay cached"+ );+ renderer.resize(size(DevicePixels(64), DevicePixels(64)))?;+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ assert_pixels(&pixels(&renderer)?, &expected, 0);+ let new_devices = warp_devices()?;+ renderer.handle_device_lost(&new_devices)?;+ assert!(+ renderer.resources.as_ref().unwrap().backdrop.is_none(),+ "recovery releases all old-device blur state"+ );+ renderer.draw(&scene, WindowBackgroundAppearance::Opaque)?;+ assert!(renderer.resources.as_ref().unwrap().backdrop.is_none());+ renderer.mark_drawable();+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ assert_pixels(&pixels(&renderer)?, &expected, 0);+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_backdrop_clipped_and_blur_only_frames() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ let mut scene = Scene::default();+ scene.backdrop_blurs = vec![BackdropBlur {+ bounds: bounds(-100., -100., 8., 8.),+ ..blur(0)+ }];+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ assert!(+ renderer.resources.as_ref().unwrap().backdrop.is_none(),+ "offscreen blur allocates nothing"+ );+ for sigma in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {+ scene.backdrop_blurs = vec![BackdropBlur {+ blur_radius: ScaledPixels(sigma),+ ..blur(0)+ }];+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ assert!(renderer.resources.as_ref().unwrap().backdrop.is_none());+ }+ scene.backdrop_blurs = (0..40).map(blur).collect();+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ assert!(pixels(&renderer)?.iter().all(|pixel| *pixel == [255; 4]));+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_backdrop_reuses_cropped_snapshot_at_window_edges() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ renderer.resize(size(DevicePixels(193), DevicePixels(131)))?;+ let original: Vec<[u8; 4]> = (0..131)+ .flat_map(|y| {+ (0..193).map(move |x| {+ [+ (x % 256) as u8,+ (y % 256) as u8,+ if (x / 4 + y / 4) % 2 == 0 { 0 } else { 255 },+ 255,+ ]+ })+ })+ .collect();+ renderer.pre_draw(&[0.; 4])?;+ unsafe {+ let context = &renderer.devices.as_ref().unwrap().device_context;+ context.OMSetRenderTargets(None, None);+ context.UpdateSubresource(+ renderer+ .resources+ .as_ref()+ .unwrap()+ .render_target+ .as_ref()+ .unwrap(),+ 0,+ None,+ original.as_ptr().cast(),+ 193 * 4,+ 0,+ );+ }+ let mut expected = original;+ for rect in [+ bounds(166., 108., 24., 20.),+ bounds(0., 0., 21., 18.),+ bounds(80., 60., 8., 9.),+ ] {+ let region = BackdropBlur {+ bounds: rect,+ content_mask: ContentMask {+ bounds: bounds(0., 0., 193., 131.),+ },+ corner_radii: Corners::all(ScaledPixels(4.)),+ ..blur(0)+ };+ renderer.draw_backdrop_blur(®ion)?;+ expected = cpu_blur(&expected, 193, 131, region);+ assert_pixels(&pixels(&renderer)?, &expected, 2);+ }+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_composer_tint_preserves_translucent_backdrop() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ for shell_alpha in [0.8, 1.0] {+ for with_blur in [true, false] {+ let mut scene = Scene::default();+ scene.quads.push(quad(+ 0,+ bounds(0., 0., 64., 64.),+ hsla(0., 0., 0.2, shell_alpha),+ ));+ if with_blur {+ scene.backdrop_blurs = vec![blur(1)];+ }+ scene+ .quads+ .push(quad(1, bounds(8., 8., 48., 48.), hsla(0., 0., 0.1, 0.15)));+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let actual = pixels(&renderer)?;+ let pixel = actual[32 * 64 + 32];+ let expected_alpha = 0.15 + shell_alpha * 0.85;+ assert!(+ (pixel[3] as f32 / 255. - expected_alpha).abs() < 0.01,+ "shell={shell_alpha}, blur={with_blur}: alpha {:?}, expected {expected_alpha}",+ pixel+ );+ let expected_rgb = 0.1 * 0.15 + 0.2 * shell_alpha * 0.85 + 1. - expected_alpha;+ for channel in &pixel[..3] {+ let over_white = *channel as f32 / 255. + 1. - pixel[3] as f32 / 255.;+ assert!(+ (over_white - expected_rgb).abs() < 0.02,+ "composer must retain desktop contribution: {over_white} vs {expected_rgb}"+ );+ }+ assert!((actual[0][3] as f32 / 255. - shell_alpha).abs() < 0.01);+ if with_blur {+ let mut child = blur(2);+ child.bounds = bounds(20., 20., 24., 24.);+ scene.backdrop_blurs.push(child);+ scene+ .quads+ .push(quad(2, child.bounds, hsla(0., 0., 0.1, 0.15)));+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let nested = pixels(&renderer)?[32 * 64 + 32];+ let nested_alpha = 0.15 + expected_alpha * 0.85;+ assert!(+ (nested[3] as f32 / 255. - nested_alpha).abs() < 0.01,+ "nested tint must retain backdrop alpha: {nested:?}, expected {nested_alpha}"+ );+ }+ }+ }+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_path_tint_preserves_translucent_backdrop() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ let mut scene = Scene::default();+ scene+ .quads+ .push(quad(0, bounds(0., 0., 64., 64.), hsla(0., 0., 0.2, 0.8)));+ scene.backdrop_blurs = vec![blur(1)];+ let mut path = gpui::Path::new(point(gpui::px(8.), gpui::px(8.)));+ path.line_to(point(gpui::px(56.), gpui::px(8.)));+ path.line_to(point(gpui::px(56.), gpui::px(56.)));+ let mut path = path.scale(1.);+ path.order = 1;+ path.color = hsla(0., 0., 0.1, 0.15).into();+ path.content_mask.bounds = bounds(0., 0., 64., 64.);+ for vertex in &mut path.vertices {+ vertex.content_mask = path.content_mask;+ }+ scene.paths.push(path);+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let actual = pixels(&renderer)?;+ let pixel = actual[24 * 64 + 40];+ assert!(+ (pixel[3] as f32 / 255. - 0.83).abs() < 0.01,+ "path tint must retain backdrop alpha: {pixel:?}"+ );+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_fractional_blur_clip_matches_primitive_clip() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ for scale in [1.0, 1.25, 1.5, 2.0] {+ let mut scene = Scene::default();+ for x in 0..64 {+ scene.quads.push(quad(+ 0,+ bounds(x as f32, 0., 1., 64.),+ hsla(0., 0., if x % 2 == 0 { 0. } else { 1. }, 0.8),+ ));+ }+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let original = pixels(&renderer)?;+ let mut region = blur(1);+ region.corner_radii = Corners::default();+ scene.backdrop_blurs = vec![region];+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let filtered = pixels(&renderer)?;++ let clip = bounds(10.5 * scale, 11.5 * scale, 12. * scale, 13. * scale);+ let mut mask = quad(0, bounds(0., 0., 64., 64.), hsla(0., 0., 1., 1.));+ mask.content_mask.bounds = clip;+ let mut mask_scene = Scene::default();+ mask_scene.quads.push(mask);+ renderer.draw_scene(&mask_scene, WindowBackgroundAppearance::Transparent)?;+ let mask_pixels = pixels(&renderer)?;+ region.content_mask.bounds = clip;+ scene.backdrop_blurs = vec![region];+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let actual = pixels(&renderer)?;+ let expected: Vec<_> = original+ .iter()+ .zip(&filtered)+ .zip(&mask_pixels)+ .map(|((before, after), mask)| if mask[3] > 0 { *after } else { *before })+ .collect();+ assert_pixels(&actual, &expected, 2);+ }+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_translucent_sprites_keep_backdrop_at_scaled_edges() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ let tile_size = size(DevicePixels(8), DevicePixels(8));+ for monochrome in [true, false] {+ let key = if monochrome {+ AtlasKey::Svg(RenderSvgParams {+ path: "coverage-fixture".into(),+ size: tile_size,+ })+ } else {+ AtlasKey::Image(RenderImageParams {+ image_id: ImageId(1001),+ frame_index: 0,+ })+ };+ let coverage = [0, 16, 64, 128, 192, 255, 128, 0];+ let bytes: Vec<u8> = (0..64)+ .flat_map(|i| {+ if monochrome {+ vec![coverage[i % 8]]+ } else {+ vec![40, 90, 180, coverage[i % 8]]+ }+ })+ .collect();+ let tile = renderer+ .atlas+ .get_or_insert_with(&key, &mut || {+ Ok(Some((tile_size, std::borrow::Cow::Borrowed(&bytes))))+ })?+ .unwrap();+ for scale in [1.0, 1.25, 1.5, 2.0] {+ let sprite_bounds = bounds(16.25, 16.5, 8. * scale, 8. * scale);+ let content_mask = ContentMask {+ bounds: bounds(0., 0., 64., 64.),+ };+ let mut scene = Scene::default();+ if monochrome {+ scene.monochrome_sprites.push(MonochromeSprite {+ order: 1,+ pad: 0,+ bounds: sprite_bounds,+ content_mask,+ color: hsla(0.1, 0.6, 0.8, 0.6),+ fade: EdgeFadeParams::default(),+ tile,+ transformation: TransformationMatrix::default(),+ });+ } else {+ scene.polychrome_sprites.push(PolychromeSprite {+ order: 1,+ pad: 0,+ grayscale: false.into(),+ opacity: 0.6,+ bounds: sprite_bounds,+ content_mask,+ corner_radii: Corners::all(ScaledPixels(2. * scale)),+ fade: EdgeFadeParams::default(),+ alpha_mask: ImageAlphaMaskParams::default(),+ tile,+ });+ }+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let foreground = pixels(&renderer)?;+ assert!(+ foreground+ .iter()+ .any(|pixel| pixel[3] > 0 && pixel[3] < 150),+ "fixture must exercise partial glyph/image coverage"+ );+ scene+ .quads+ .push(quad(0, bounds(0., 0., 64., 64.), hsla(0., 0., 0.3, 0.8)));+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let actual = pixels(&renderer)?;+ for (src, actual) in foreground.iter().zip(actual) {+ let a = src[3] as f32 / 255.;+ let expected = [+ src[0] as f32 + 255. * 0.3 * 0.8 * (1. - a),+ src[1] as f32 + 255. * 0.3 * 0.8 * (1. - a),+ src[2] as f32 + 255. * 0.3 * 0.8 * (1. - a),+ 255. * (a + 0.8 * (1. - a)),+ ];+ for channel in 0..4 {+ assert!(+ (actual[channel] as f32 - expected[channel]).abs() <= 2.,+ "mono={monochrome} scale={scale} channel={channel}: {actual:?} vs {expected:?}"+ );+ }+ }+ }+ }+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_animated_nested_blur_matches_fresh_resources() -> Result<()> {+ let (mut cached, _cached_window) = warp_renderer()?;+ let (mut fresh, _fresh_window) = warp_renderer()?;+ for (width, height) in [(193, 131), (137, 99), (211, 143)] {+ cached.resize(size(DevicePixels(width), DevicePixels(height)))?;+ fresh.resize(size(DevicePixels(width), DevicePixels(height)))?;+ for frame in 0..12 {+ let viewport = bounds(0., 0., width as f32, height as f32);+ let mut scene = Scene::default();+ for x in 0..width {+ let mut stripe = quad(+ 0,+ bounds(x as f32, 0., 1., height as f32),+ hsla(0.1, 0.5, if (x + frame) % 7 < 3 { 0.2 } else { 0.8 }, 0.7),+ );+ stripe.content_mask.bounds = viewport;+ scene.quads.push(stripe);+ }+ let offset = frame as f32 * 7.25;+ let parent = BackdropBlur {+ bounds: bounds(offset - 12., 4.25, 100., 80.),+ content_mask: ContentMask { bounds: viewport },+ blur_radius: ScaledPixels(if frame % 3 == 0 { 16. } else { 3. }),+ ..blur(1)+ };+ let mut tint = quad(2, parent.bounds, hsla(0., 0., 0.1, 0.15));+ tint.content_mask.bounds = viewport;+ scene.quads.push(tint);+ scene.backdrop_blurs = vec![+ parent,+ BackdropBlur {+ bounds: bounds(offset + 9.5, 21.25, 41.5, 39.5),+ content_mask: ContentMask {+ bounds: parent.bounds.intersect(&viewport),+ },+ ..blur(3)+ },+ ];+ cached.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let actual = pixels(&cached)?;+ fresh.resources.as_mut().unwrap().backdrop = None;+ fresh.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ assert_pixels(&actual, &pixels(&fresh)?, 2);+ }+ }+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_large_blur_removes_fine_stripes() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ renderer.resize(size(DevicePixels(256), DevicePixels(256)))?;+ for phase in 0..4 {+ for horizontal in [false, true] {+ let mut scene = Scene::default();+ for n in 0..256 {+ let rect = if horizontal {+ bounds(0., n as f32, 256., 1.)+ } else {+ bounds(n as f32, 0., 1., 256.)+ };+ let mut stripe = quad(+ 0,+ rect,+ hsla(0., 0., if (n + phase) % 4 < 2 { 0. } else { 1. }, 1.),+ );+ stripe.content_mask.bounds = bounds(0., 0., 256., 256.);+ scene.quads.push(stripe);+ }+ scene.backdrop_blurs.push(BackdropBlur {+ bounds: bounds(0., 0., 256., 256.),+ content_mask: ContentMask {+ bounds: bounds(0., 0., 256., 256.),+ },+ blur_radius: ScaledPixels(32.),+ corner_radii: Corners::default(),+ ..blur(1)+ });+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Transparent)?;+ let image = pixels(&renderer)?;++ assert!(+ (image[128 * 256 + 128][0] as i32 - 128).abs() <= 3,+ "fine stripes should average to gray: orientation={horizontal}, center={:?}",+ image[128 * 256 + 128]+ );+ }+ }+ Ok(())+}++#[::core::prelude::v1::test]+fn warp_invalid_geometry_allocates_nothing_and_idle_cache_expires() -> Result<()> {+ let (mut renderer, _window) = warp_renderer()?;+ let mut scene = Scene::default();+ for value in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, -1.] {+ for field in 0..4 {+ let mut region = blur(0);+ match field {+ 0 => region.bounds.size.width = ScaledPixels(value),+ 1 => region.content_mask.bounds.size.height = ScaledPixels(value),+ 2 => region.corner_radii.top_left = ScaledPixels(value),+ _ => {+ region.bounds.origin.x =+ ScaledPixels(if value == -1. { f32::INFINITY } else { value })+ }+ }+ scene.backdrop_blurs = vec![region];+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ assert!(renderer.resources.as_ref().unwrap().backdrop.is_none());+ assert!(pixels(&renderer)?.iter().all(|pixel| *pixel == [255; 4]));+ }+ }+ scene.backdrop_blurs = vec![BackdropBlur {+ bounds: bounds(f32::MAX, 0., f32::MAX, 10.),+ ..blur(0)+ }];+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ assert!(renderer.resources.as_ref().unwrap().backdrop.is_none());+ scene.backdrop_blurs = vec![blur(0)];+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ assert!(renderer.resources.as_ref().unwrap().backdrop.is_some());+ scene.backdrop_blurs[0].bounds = bounds(-100., -100., 8., 8.);+ for _ in 0..120 {+ renderer.draw_scene(&scene, WindowBackgroundAppearance::Opaque)?;+ }+ assert!(+ renderer+ .resources+ .as_ref()+ .unwrap()+ .backdrop+ .as_ref()+ .is_some_and(|backdrop| !backdrop.has_scratch())+ );+ Ok(())+}diff --git a/native/vendor/wu/crates/gpui_windows/src/dispatcher.rs b/native/vendor/wu/crates/gpui_windows/src/dispatcher.rsnew file mode 100644index 00000000000..55f18b50c07--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/dispatcher.rs@@ -0,0 +1,191 @@+use std::{+ ffi::c_void,+ ptr::NonNull,+ sync::atomic::{AtomicBool, Ordering},+ thread::{ThreadId, current},+ time::Duration,+};++use anyhow::Context;+use gpui_util::ResultExt;+use windows::Win32::{+ Foundation::{FILETIME, LPARAM, WPARAM},+ Media::{timeBeginPeriod, timeEndPeriod},+ System::Threading::{+ CloseThreadpoolTimer, CreateThreadpoolTimer, GetCurrentThread, PTP_CALLBACK_INSTANCE,+ PTP_TIMER, SetThreadPriority, SetThreadpoolTimer, THREAD_PRIORITY_TIME_CRITICAL,+ TP_CALLBACK_ENVIRON_V3, TP_CALLBACK_PRIORITY, TP_CALLBACK_PRIORITY_HIGH,+ TP_CALLBACK_PRIORITY_LOW, TP_CALLBACK_PRIORITY_NORMAL, TrySubmitThreadpoolCallback,+ },+ UI::WindowsAndMessaging::PostMessageW,+};++use crate::{HWND, SafeHwnd, WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD};+use gpui::{+ PlatformDispatcher, Priority, PriorityQueueSender, RunnableVariant, TimerResolutionGuard,+};++pub(crate) struct WindowsDispatcher {+ pub(crate) wake_posted: AtomicBool,+ main_sender: PriorityQueueSender<RunnableVariant>,+ main_thread_id: ThreadId,+ pub(crate) platform_window_handle: SafeHwnd,+ validation_number: usize,+}++impl WindowsDispatcher {+ pub(crate) fn new(+ main_sender: PriorityQueueSender<RunnableVariant>,+ platform_window_handle: HWND,+ validation_number: usize,+ ) -> Self {+ let main_thread_id = current().id();+ let platform_window_handle = platform_window_handle.into();++ WindowsDispatcher {+ main_sender,+ main_thread_id,+ platform_window_handle,+ validation_number,+ wake_posted: AtomicBool::new(false),+ }+ }++ fn dispatch_on_threadpool(&self, priority: TP_CALLBACK_PRIORITY, runnable: RunnableVariant) {+ let environ = TP_CALLBACK_ENVIRON_V3 {+ Version: 3,+ CallbackPriority: priority,+ Size: size_of::<TP_CALLBACK_ENVIRON_V3>() as u32,+ ..Default::default()+ };++ // If the thread pool never runs our callback, the matching `from_raw` is never called, which leaks the runnable.+ // Dropping the scheduled runnable would cancel its task and make the next poll of any awaiter panic. Since we expect+ // the scenario to usually happen during shutdown, this leak is acceptable.+ let context = runnable.into_raw().as_ptr() as *mut c_void;++ unsafe {+ TrySubmitThreadpoolCallback(Some(run_work_callback), Some(context), Some(&environ))+ .log_err();+ }+ }++ fn dispatch_on_threadpool_after(&self, runnable: RunnableVariant, duration: Duration) {+ let context = runnable.into_raw().as_ptr() as *mut c_void;++ unsafe {+ if let Ok(timer) = CreateThreadpoolTimer(Some(run_timer_callback), Some(context), None)+ {+ // Negative FILETIME expresses a relative delay in 100ns ticks+ let ticks = (duration.as_nanos() / 100).min(i64::MAX as u128) as i64;+ let due = (-ticks) as u64;+ let due_time = FILETIME {+ dwLowDateTime: due as u32,+ dwHighDateTime: (due >> 32) as u32,+ };+ SetThreadpoolTimer(timer, Some(&due_time), 0, None);+ }+ }+ }++ #[inline(always)]+ pub(crate) fn execute_runnable(runnable: RunnableVariant) {+ let location = runnable.metadata().location;+ let spawned = runnable.metadata().spawned;+ gpui::profiler::update_running_task(spawned, location);+ runnable.run();+ gpui::profiler::save_task_timing();+ }+}++impl PlatformDispatcher for WindowsDispatcher {+ fn is_main_thread(&self) -> bool {+ current().id() == self.main_thread_id+ }++ fn dispatch(&self, runnable: RunnableVariant, priority: Priority) {+ let priority = match priority {+ Priority::RealtimeAudio => {+ panic!("RealtimeAudio priority should use spawn_realtime, not dispatch")+ }+ Priority::High => TP_CALLBACK_PRIORITY_HIGH,+ Priority::Medium => TP_CALLBACK_PRIORITY_NORMAL,+ Priority::Low => TP_CALLBACK_PRIORITY_LOW,+ };+ self.dispatch_on_threadpool(priority, runnable);+ }++ fn dispatch_on_main_thread(&self, runnable: RunnableVariant, priority: Priority) {+ match self.main_sender.send(priority, runnable) {+ Ok(_) => {+ if !self.wake_posted.swap(true, Ordering::AcqRel) {+ unsafe {+ PostMessageW(+ Some(self.platform_window_handle.as_raw()),+ WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD,+ WPARAM(self.validation_number),+ LPARAM(0),+ )+ .log_err();+ }+ }+ }+ Err(runnable) => {+ // NOTE: Runnable may wrap a Future that is !Send.+ //+ // This is usually safe because we only poll it on the main thread.+ // However if the send fails, we know that:+ // 1. main_receiver has been dropped (which implies the app is shutting down)+ // 2. we are on a background thread.+ // It is not safe to drop something !Send on the wrong thread, and+ // the app will exit soon anyway, so we must forget the runnable.+ std::mem::forget(runnable);+ }+ }+ }++ fn dispatch_after(&self, duration: Duration, runnable: RunnableVariant) {+ self.dispatch_on_threadpool_after(runnable, duration);+ }++ fn spawn_realtime(&self, f: Box<dyn FnOnce() + Send>) {+ std::thread::spawn(move || {+ // SAFETY: always safe to call+ let thread_handle = unsafe { GetCurrentThread() };++ // SAFETY: thread_handle is a valid handle to the current thread+ unsafe { SetThreadPriority(thread_handle, THREAD_PRIORITY_TIME_CRITICAL) }+ .context("thread priority")+ .log_err();++ f();+ });+ }++ fn increase_timer_resolution(&self) -> TimerResolutionGuard {+ unsafe {+ timeBeginPeriod(1);+ }+ gpui_util::defer(Box::new(|| unsafe {+ timeEndPeriod(1);+ }))+ }+}++unsafe extern "system" fn run_work_callback(+ _instance: PTP_CALLBACK_INSTANCE,+ context: *mut c_void,+) {+ let runnable = unsafe { RunnableVariant::from_raw(NonNull::new_unchecked(context as *mut ())) };+ WindowsDispatcher::execute_runnable(runnable);+}++unsafe extern "system" fn run_timer_callback(+ _instance: PTP_CALLBACK_INSTANCE,+ context: *mut c_void,+ timer: PTP_TIMER,+) {+ let runnable = unsafe { RunnableVariant::from_raw(NonNull::new_unchecked(context as *mut ())) };+ WindowsDispatcher::execute_runnable(runnable);+ unsafe { CloseThreadpoolTimer(timer) };+}diff --git a/native/vendor/wu/crates/gpui_windows/src/display.rs b/native/vendor/wu/crates/gpui_windows/src/display.rsnew file mode 100644index 00000000000..ee02309d8c7--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/display.rs@@ -0,0 +1,210 @@+use gpui_util::ResultExt;+use itertools::Itertools;+use smallvec::SmallVec;+use std::rc::Rc;+use uuid::Uuid;+use windows::{+ Win32::{+ Foundation::*,+ Graphics::Gdi::*,+ UI::{+ HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI},+ WindowsAndMessaging::USER_DEFAULT_SCREEN_DPI,+ },+ },+ core::*,+};++use crate::logical_point;+use gpui::{Bounds, DevicePixels, DisplayId, Pixels, PlatformDisplay, point, size};++#[derive(Debug, Clone, Copy)]+pub(crate) struct WindowsDisplay {+ pub handle: HMONITOR,+ pub display_id: DisplayId,+ scale_factor: f32,+ bounds: Bounds<Pixels>,+ visible_bounds: Bounds<Pixels>,+ physical_bounds: Bounds<DevicePixels>,+ uuid: Uuid,+}++// The `HMONITOR` is thread-safe.+unsafe impl Send for WindowsDisplay {}+unsafe impl Sync for WindowsDisplay {}++impl WindowsDisplay {+ pub(crate) fn new(display_id: DisplayId) -> Option<Self> {+ let handle = HMONITOR(u64::from(display_id) as _);+ let info = get_monitor_info(handle).log_err()?;+ let monitor_size = info.monitorInfo.rcMonitor;+ let work_area = info.monitorInfo.rcWork;+ let uuid = generate_uuid(&info.szDevice);+ let scale_factor = get_scale_factor_for_monitor(handle).log_err()?;+ let physical_size = size(+ (monitor_size.right - monitor_size.left).into(),+ (monitor_size.bottom - monitor_size.top).into(),+ );++ Some(WindowsDisplay {+ handle,+ display_id,+ scale_factor,+ bounds: Bounds {+ origin: logical_point(+ monitor_size.left as f32,+ monitor_size.top as f32,+ scale_factor,+ ),+ size: physical_size.to_pixels(scale_factor),+ },+ visible_bounds: Bounds {+ origin: logical_point(work_area.left as f32, work_area.top as f32, scale_factor),+ size: size(+ (work_area.right - work_area.left) as f32 / scale_factor,+ (work_area.bottom - work_area.top) as f32 / scale_factor,+ )+ .map(gpui::px),+ },+ physical_bounds: Bounds {+ origin: point(monitor_size.left.into(), monitor_size.top.into()),+ size: physical_size,+ },+ uuid,+ })+ }++ pub(crate) fn display_id_for_monitor(monitor: HMONITOR) -> DisplayId {+ DisplayId::new(monitor.0 as u64)+ }++ pub fn primary_monitor() -> Option<Self> {+ // https://devblogs.microsoft.com/oldnewthing/20070809-00/?p=25643+ const POINT_ZERO: POINT = POINT { x: 0, y: 0 };+ let monitor = unsafe { MonitorFromPoint(POINT_ZERO, MONITOR_DEFAULTTOPRIMARY) };+ if monitor.is_invalid() {+ log::error!(+ "can not find the primary monitor: {}",+ std::io::Error::last_os_error()+ );+ return None;+ }+ WindowsDisplay::new(Self::display_id_for_monitor(monitor))+ }++ /// The DPI scale factor of this monitor, independent of whatever monitor+ /// a not-yet-positioned window currently happens to be on.+ pub(crate) fn scale_factor(&self) -> f32 {+ self.scale_factor+ }++ /// Check if the center point of given bounds is inside this monitor+ pub fn check_given_bounds(&self, bounds: Bounds<Pixels>) -> bool {+ let center = bounds.center();+ let center = POINT {+ x: (center.x.as_f32() * self.scale_factor) as i32,+ y: (center.y.as_f32() * self.scale_factor) as i32,+ };+ let monitor = unsafe { MonitorFromPoint(center, MONITOR_DEFAULTTONULL) };+ if monitor.is_invalid() {+ false+ } else {+ let Some(display) = WindowsDisplay::new(Self::display_id_for_monitor(monitor)) else {+ return false;+ };+ display.uuid == self.uuid+ }+ }++ pub fn displays() -> Vec<Rc<dyn PlatformDisplay>> {+ available_monitors()+ .into_iter()+ .filter_map(|handle| {+ Some(+ Rc::new(WindowsDisplay::new(Self::display_id_for_monitor(handle))?)+ as Rc<dyn PlatformDisplay>,+ )+ })+ .collect()+ }++ pub fn physical_bounds(&self) -> Bounds<DevicePixels> {+ self.physical_bounds+ }+}++impl PlatformDisplay for WindowsDisplay {+ fn id(&self) -> DisplayId {+ self.display_id+ }++ fn uuid(&self) -> anyhow::Result<Uuid> {+ Ok(self.uuid)+ }++ fn bounds(&self) -> Bounds<Pixels> {+ self.bounds+ }++ fn visible_bounds(&self) -> Bounds<Pixels> {+ self.visible_bounds+ }+}++fn available_monitors() -> SmallVec<[HMONITOR; 4]> {+ let mut monitors: SmallVec<[HMONITOR; 4]> = SmallVec::new();+ unsafe {+ EnumDisplayMonitors(+ None,+ None,+ Some(monitor_enum_proc),+ LPARAM(&mut monitors as *mut _ as _),+ )+ .ok()+ .log_err();+ }+ monitors+}++unsafe extern "system" fn monitor_enum_proc(+ hmonitor: HMONITOR,+ _hdc: HDC,+ _place: *mut RECT,+ data: LPARAM,+) -> BOOL {+ let monitors = data.0 as *mut SmallVec<[HMONITOR; 4]>;+ unsafe { (*monitors).push(hmonitor) };+ BOOL(1)+}++fn get_monitor_info(hmonitor: HMONITOR) -> anyhow::Result<MONITORINFOEXW> {+ let mut monitor_info: MONITORINFOEXW = unsafe { std::mem::zeroed() };+ monitor_info.monitorInfo.cbSize = std::mem::size_of::<MONITORINFOEXW>() as u32;+ let status = unsafe {+ GetMonitorInfoW(+ hmonitor,+ &mut monitor_info as *mut MONITORINFOEXW as *mut MONITORINFO,+ )+ };+ if status.as_bool() {+ Ok(monitor_info)+ } else {+ Err(anyhow::anyhow!(std::io::Error::last_os_error()))+ }+}++fn generate_uuid(device_name: &[u16]) -> Uuid {+ let name = device_name+ .iter()+ .flat_map(|&a| a.to_be_bytes())+ .collect_vec();+ Uuid::new_v5(&Uuid::NAMESPACE_DNS, &name)+}++fn get_scale_factor_for_monitor(monitor: HMONITOR) -> Result<f32> {+ let mut dpi_x = 0;+ let mut dpi_y = 0;+ unsafe { GetDpiForMonitor(monitor, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y) }?;+ assert_eq!(dpi_x, dpi_y);+ Ok(dpi_x as f32 / USER_DEFAULT_SCREEN_DPI as f32)+}diff --git a/native/vendor/wu/crates/gpui_windows/src/events.rs b/native/vendor/wu/crates/gpui_windows/src/events.rsnew file mode 100644index 00000000000..186a03df08f--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/events.rs@@ -0,0 +1,1841 @@+use std::{cell::Cell, rc::Rc, sync::atomic::Ordering};++use anyhow::Context as _;+use gpui_util::ResultExt;+use windows::{+ Win32::{+ Foundation::*,+ Graphics::Gdi::*,+ System::SystemServices::*,+ UI::{+ Controls::*,+ HiDpi::*,+ Input::{Ime::*, KeyboardAndMouse::*, Pointer::*},+ WindowsAndMessaging::*,+ },+ },+ core::PCWSTR,+};++use crate::*;+use gpui::*;++pub(crate) const WM_GPUI_CURSOR_STYLE_CHANGED: u32 = WM_USER + 1;+pub(crate) const WM_GPUI_CLOSE_ONE_WINDOW: u32 = WM_USER + 2;+pub(crate) const WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD: u32 = WM_USER + 3;+pub(crate) const WM_GPUI_DOCK_MENU_ACTION: u32 = WM_USER + 4;+pub(crate) const WM_GPUI_FORCE_UPDATE_WINDOW: u32 = WM_USER + 5;+pub(crate) const WM_GPUI_KEYBOARD_LAYOUT_CHANGED: u32 = WM_USER + 6;+pub(crate) const WM_GPUI_GPU_DEVICE_LOST: u32 = WM_USER + 7;+pub(crate) const WM_GPUI_KEYDOWN: u32 = WM_USER + 8;+pub(crate) const WM_GPUI_END_SESSION: u32 = WM_USER + 9;++const SIZE_MOVE_LOOP_TIMER_ID: usize = 1;++/// Coordinates window draws on the UI thread. Owned by the platform and+/// shared with every window (like `WindowsPlatformState::cursor_visible`),+/// because the coordination is inherently cross-window: while window A is+/// drawing, a re-entrant paint request for window B must be deferred.+pub(crate) struct DrawCoordinator {+ /// Whether some window is currently inside `draw_window`. Win32 can+ /// re-enter the window procedure while a draw is in progress (e.g.+ /// cross-thread `SendMessage` dispatch during message pumping, or modal+ /// message loops entered by COM calls), and drawing re-entrantly would+ /// nest GPUI draws. Nested draws are wasted work whose output is+ /// immediately redrawn, so we defer them instead.+ drawing: Cell<bool>,+}++impl DrawCoordinator {+ pub(crate) fn new() -> Self {+ Self {+ drawing: Cell::new(false),+ }+ }++ fn try_begin_draw(&self) -> Option<DrawWindowGuard<'_>> {+ // This only covers the `draw_window` span (which extends past the GPUI+ // draw, through presentation and IME updates). Requests that arrive+ // re-entrantly during GPUI-initiated draws (e.g. key dispatch or+ // opening a window draws synchronously) are deferred by GPUI's+ // `on_request_frame` callback itself, which no-ops in that case.+ if self.drawing.get() {+ None+ } else {+ self.drawing.set(true);+ Some(DrawWindowGuard { coordinator: self })+ }+ }+}++struct DrawWindowGuard<'a> {+ coordinator: &'a DrawCoordinator,+}++impl Drop for DrawWindowGuard<'_> {+ fn drop(&mut self) {+ self.coordinator.drawing.set(false);+ }+}++impl WindowsWindowInner {+ pub(crate) fn handle_msg(+ self: &Rc<Self>,+ handle: HWND,+ msg: u32,+ wparam: WPARAM,+ lparam: LPARAM,+ ) -> LRESULT {+ let handled = match msg {+ // `DefWindowProc` answers `MA_NOACTIVATE` for a left click on `HTCAPTION`.+ // The activation is only triggered when `DefWindowProc` handles the following `WM_NCLBUTTONDOWN`.+ // The GPUI event is dispatched in between, so a click handler runs while `active_window` is still+ // whichever window was active before the click. If that handler consumes the+ // press, `DefWindowProc` never sees it, so the window is never activated at all.+ // So, let's eagerly activate the window.+ WM_MOUSEACTIVATE => Some(MA_ACTIVATE as isize),+ WM_ACTIVATE => self.handle_activate_msg(wparam),+ WM_CREATE => self.handle_create_msg(handle),+ WM_MOVE => self.handle_move_msg(handle, lparam),+ WM_SIZE => self.handle_size_msg(wparam, lparam),+ WM_GETMINMAXINFO => self.handle_get_min_max_info_msg(lparam),+ WM_ENTERSIZEMOVE | WM_ENTERMENULOOP => self.handle_size_move_loop(handle),+ WM_EXITSIZEMOVE | WM_EXITMENULOOP => self.handle_size_move_loop_exit(handle),+ WM_TIMER => self.handle_timer_msg(handle, wparam),+ WM_NCCALCSIZE => self.handle_calc_client_size(handle, wparam, lparam),+ WM_DPICHANGED => self.handle_dpi_changed_msg(handle, wparam, lparam),+ WM_DISPLAYCHANGE => self.handle_display_change_msg(handle),+ WM_NCHITTEST => self.handle_hit_test_msg(handle, lparam),+ WM_PAINT => self.handle_paint_msg(handle),+ WM_CLOSE => self.handle_close_msg(),+ WM_DESTROY => self.handle_destroy_msg(handle),+ WM_QUERYENDSESSION => Some(1),+ WM_ENDSESSION => self.handle_end_session_msg(wparam),+ WM_MOUSEMOVE => self.handle_mouse_move_msg(handle, lparam, wparam),+ WM_MOUSELEAVE | WM_NCMOUSELEAVE => self.handle_mouse_leave_msg(),+ WM_NCMOUSEMOVE => self.handle_nc_mouse_move_msg(handle, lparam),+ // Treat double click as a second single click, since we track the double clicks ourselves.+ // If you don't interact with any elements, this will fall through to the windows default+ // behavior of toggling whether the window is maximized.+ WM_NCLBUTTONDBLCLK | WM_NCLBUTTONDOWN => {+ self.handle_nc_mouse_down_msg(handle, MouseButton::Left, wparam, lparam)+ }+ WM_NCRBUTTONDOWN => {+ self.handle_nc_mouse_down_msg(handle, MouseButton::Right, wparam, lparam)+ }+ WM_NCMBUTTONDOWN => {+ self.handle_nc_mouse_down_msg(handle, MouseButton::Middle, wparam, lparam)+ }+ WM_NCLBUTTONUP => {+ self.handle_nc_mouse_up_msg(handle, MouseButton::Left, wparam, lparam)+ }+ WM_NCRBUTTONUP => {+ self.handle_nc_mouse_up_msg(handle, MouseButton::Right, wparam, lparam)+ }+ WM_NCMBUTTONUP => {+ self.handle_nc_mouse_up_msg(handle, MouseButton::Middle, wparam, lparam)+ }+ WM_LBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Left, lparam),+ WM_RBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Right, lparam),+ WM_MBUTTONDOWN => self.handle_mouse_down_msg(handle, MouseButton::Middle, lparam),+ WM_XBUTTONDOWN => {+ self.handle_xbutton_msg(handle, wparam, lparam, Self::handle_mouse_down_msg)+ }+ WM_LBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Left, lparam),+ WM_RBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Right, lparam),+ WM_MBUTTONUP => self.handle_mouse_up_msg(handle, MouseButton::Middle, lparam),+ WM_XBUTTONUP => {+ self.handle_xbutton_msg(handle, wparam, lparam, Self::handle_mouse_up_msg)+ }+ WM_POINTERDOWN | WM_POINTERUPDATE | WM_POINTERUP => {+ self.handle_pointer_msg(handle, msg, wparam)+ }+ WM_POINTERCAPTURECHANGED => self.handle_pointer_capture_changed_msg(wparam),+ WM_MOUSEWHEEL => self.handle_mouse_wheel_msg(handle, wparam, lparam),+ WM_MOUSEHWHEEL => self.handle_mouse_horizontal_wheel_msg(handle, wparam, lparam),+ WM_SYSKEYUP => self.handle_syskeyup_msg(wparam, lparam),+ WM_KEYUP => self.handle_keyup_msg(wparam, lparam),+ WM_GPUI_KEYDOWN => self.handle_keydown_msg(wparam, lparam),+ WM_CHAR => self.handle_char_msg(wparam),+ WM_IME_STARTCOMPOSITION => self.handle_ime_position(handle),+ WM_IME_COMPOSITION => self.handle_ime_composition(handle, lparam),+ WM_SETCURSOR => self.handle_set_cursor(handle, lparam),+ WM_SETTINGCHANGE => self.handle_system_settings_changed(handle, wparam, lparam),+ WM_INPUTLANGCHANGE => self.handle_input_language_changed(),+ WM_SHOWWINDOW => self.handle_window_visibility_changed(handle, wparam),+ WM_GPUI_CURSOR_STYLE_CHANGED => self.handle_cursor_changed(lparam),+ WM_GPUI_FORCE_UPDATE_WINDOW => self.draw_window(handle, true),+ WM_GPUI_GPU_DEVICE_LOST => self.handle_device_lost(lparam),+ DM_POINTERHITTEST => self.handle_dm_pointer_hit_test(wparam),+ WM_GETOBJECT => self.handle_wm_getobject(wparam, lparam),+ _ => None,+ };+ if let Some(n) = handled {+ LRESULT(n)+ } else {+ unsafe { DefWindowProcW(handle, msg, wparam, lparam) }+ }+ }++ fn handle_end_session_msg(&self, wparam: WPARAM) -> Option<isize> {+ if wparam.0 != 0 {+ unsafe {+ SendMessageW(+ self.platform_window_handle,+ WM_GPUI_END_SESSION,+ Some(WPARAM(self.validation_number)),+ None,+ );+ }+ }+ Some(0)+ }++ fn handle_move_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {+ let origin = logical_point(+ lparam.signed_loword() as f32,+ lparam.signed_hiword() as f32,+ self.state.scale_factor.get(),+ );+ self.state.origin.set(origin);+ let size = self.state.logical_size.get();+ let center_x = origin.x.as_f32() + size.width.as_f32() / 2.;+ let center_y = origin.y.as_f32() + size.height.as_f32() / 2.;+ let monitor_bounds = self.state.display.get().bounds();+ if center_x < monitor_bounds.left().as_f32()+ || center_x > monitor_bounds.right().as_f32()+ || center_y < monitor_bounds.top().as_f32()+ || center_y > monitor_bounds.bottom().as_f32()+ {+ // center of the window may have moved to another monitor+ let monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };+ // minimize the window can trigger this event too, in this case,+ // monitor is invalid, we do nothing.+ if !monitor.is_invalid() && self.state.display.get().handle != monitor {+ // we will get the same monitor if we only have one+ self.state.display.set(WindowsDisplay::new(+ WindowsDisplay::display_id_for_monitor(monitor),+ )?);+ }+ }+ if let Some(mut callback) = self.state.callbacks.moved.take() {+ callback();+ self.state.callbacks.moved.set(Some(callback));+ }+ Some(0)+ }++ fn handle_get_min_max_info_msg(&self, lparam: LPARAM) -> Option<isize> {+ let min_size = self.state.min_size?;+ let scale_factor = self.state.scale_factor.get();+ let boarder_offset = &self.state.border_offset;++ unsafe {+ let minmax_info = &mut *(lparam.0 as *mut MINMAXINFO);+ minmax_info.ptMinTrackSize.x = min_size.width.scale(scale_factor).as_f32() as i32+ + boarder_offset.width_offset.get();+ minmax_info.ptMinTrackSize.y = min_size.height.scale(scale_factor).as_f32() as i32+ + boarder_offset.height_offset.get();+ }+ Some(0)+ }++ fn handle_size_msg(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {+ // Don't resize the renderer when the window is minimized, but record that it was minimized so+ // that on restore the swap chain can be recreated via `update_drawable_size_even_if_unchanged`.+ if wparam.0 == SIZE_MINIMIZED as usize {+ self.state+ .restore_from_minimized+ .set(self.state.callbacks.request_frame.take());+ return Some(0);+ }++ let width = lparam.loword().max(1) as i32;+ let height = lparam.hiword().max(1) as i32;+ let new_size = size(DevicePixels(width), DevicePixels(height));++ let scale_factor = self.state.scale_factor.get();+ let mut should_resize_renderer = false;+ if let Some(restore_from_minimized) = self.state.restore_from_minimized.take() {+ self.state+ .callbacks+ .request_frame+ .set(Some(restore_from_minimized));+ } else {+ should_resize_renderer = true;+ }++ self.handle_size_change(new_size, scale_factor, should_resize_renderer);+ Some(0)+ }++ fn handle_size_change(+ &self,+ device_size: Size<DevicePixels>,+ scale_factor: f32,+ should_resize_renderer: bool,+ ) {+ let new_logical_size = device_size.to_pixels(scale_factor);++ self.state.logical_size.set(new_logical_size);+ if should_resize_renderer+ && let Err(e) = self.state.renderer.borrow_mut().resize(device_size)+ {+ log::error!("Failed to resize renderer, invalidating devices: {}", e);+ self.state+ .invalidate_devices+ .store(true, std::sync::atomic::Ordering::Release);+ }+ if let Some(mut callback) = self.state.callbacks.resize.take() {+ callback(new_logical_size, scale_factor);+ self.state.callbacks.resize.set(Some(callback));+ }+ }++ fn handle_size_move_loop(&self, handle: HWND) -> Option<isize> {+ unsafe {+ let ret = SetTimer(+ Some(handle),+ SIZE_MOVE_LOOP_TIMER_ID,+ USER_TIMER_MINIMUM,+ None,+ );+ if ret == 0 {+ log::error!(+ "unable to create timer: {}",+ std::io::Error::last_os_error()+ );+ }+ }+ None+ }++ fn handle_size_move_loop_exit(&self, handle: HWND) -> Option<isize> {+ unsafe {+ KillTimer(Some(handle), SIZE_MOVE_LOOP_TIMER_ID).log_err();+ }+ None+ }++ fn handle_timer_msg(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {+ if wparam.0 == SIZE_MOVE_LOOP_TIMER_ID {+ let mut runnables = self.main_receiver.clone().try_iter();+ while let Some(Ok(runnable)) = runnables.next() {+ WindowsDispatcher::execute_runnable(runnable);+ }+ self.handle_paint_msg(handle)+ } else {+ None+ }+ }++ fn handle_paint_msg(&self, handle: HWND) -> Option<isize> {+ self.draw_window(handle, false)+ }++ fn handle_close_msg(&self) -> Option<isize> {+ let mut callback = self.state.callbacks.should_close.take()?;+ let should_close = callback();+ self.state.callbacks.should_close.set(Some(callback));+ if should_close { None } else { Some(0) }+ }++ fn handle_destroy_msg(&self, handle: HWND) -> Option<isize> {+ let callback = { self.state.callbacks.close.take() };+ // Re-enable parent window if this was a modal dialog+ if let Some(parent_hwnd) = self.parent_hwnd {+ unsafe {+ let _ = EnableWindow(parent_hwnd, true);+ let _ = SetForegroundWindow(parent_hwnd);+ }+ }++ if let Some(callback) = callback {+ callback();+ }+ unsafe {+ PostMessageW(+ Some(self.platform_window_handle),+ WM_GPUI_CLOSE_ONE_WINDOW,+ WPARAM(self.validation_number),+ LPARAM(handle.0 as isize),+ )+ .log_err();+ }+ Some(0)+ }++ fn handle_mouse_move_msg(&self, handle: HWND, lparam: LPARAM, wparam: WPARAM) -> Option<isize> {+ self.start_tracking_mouse(handle, TME_LEAVE);+ self.restore_cursor_after_hide();++ let Some(mut func) = self.state.callbacks.input.take() else {+ return Some(1);+ };+ let scale_factor = self.state.scale_factor.get();++ let pressed_button = match MODIFIERKEYS_FLAGS(wparam.loword() as u32) {+ flags if flags.contains(MK_LBUTTON) => Some(MouseButton::Left),+ flags if flags.contains(MK_RBUTTON) => Some(MouseButton::Right),+ flags if flags.contains(MK_MBUTTON) => Some(MouseButton::Middle),+ flags if flags.contains(MK_XBUTTON1) => {+ Some(MouseButton::Navigate(NavigationDirection::Back))+ }+ flags if flags.contains(MK_XBUTTON2) => {+ Some(MouseButton::Navigate(NavigationDirection::Forward))+ }+ _ => None,+ };+ let x = lparam.signed_loword() as f32;+ let y = lparam.signed_hiword() as f32;+ let input = PlatformInput::MouseMove(MouseMoveEvent {+ position: logical_point(x, y, scale_factor),+ pressed_button,+ modifiers: current_modifiers(),+ });+ let handled = !func(input).propagate;+ self.state.callbacks.input.set(Some(func));++ if handled { Some(0) } else { Some(1) }+ }++ fn handle_mouse_leave_msg(&self) -> Option<isize> {+ self.state.hovered.set(false);+ // The next window's `WM_SETCURSOR` picks its own cursor, so we just clear+ // the flag for tight `is_cursor_visible()` semantics.+ self.state.cursor_visible.store(true, Ordering::Relaxed);+ if let Some(mut callback) = self.state.callbacks.hovered_status_change.take() {+ callback(false);+ self.state+ .callbacks+ .hovered_status_change+ .set(Some(callback));+ }++ Some(0)+ }++ fn handle_syskeyup_msg(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {+ let input = handle_key_event(wparam, lparam, &self.state, |keystroke, _| {+ PlatformInput::KeyUp(KeyUpEvent { keystroke })+ })?;+ let mut func = self.state.callbacks.input.take()?;++ func(input);+ self.state.callbacks.input.set(Some(func));++ // Always return 0 to indicate that the message was handled, so we could properly handle `ModifiersChanged` event.+ Some(0)+ }++ // It's a known bug that you can't trigger `ctrl-shift-0`. See:+ // https://superuser.com/questions/1455762/ctrl-shift-number-key-combination-has-stopped-working-for-a-few-numbers+ fn handle_keydown_msg(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {+ let Some(input) = handle_key_event(+ wparam,+ lparam,+ &self.state,+ |keystroke, prefer_character_input| {+ PlatformInput::KeyDown(KeyDownEvent {+ keystroke,+ is_held: lparam.0 & (0x1 << 30) > 0,+ prefer_character_input,+ })+ },+ ) else {+ return Some(1);+ };++ let Some(mut func) = self.state.callbacks.input.take() else {+ return Some(1);+ };++ let handled = !func(input).propagate;++ self.state.callbacks.input.set(Some(func));++ if handled { Some(0) } else { Some(1) }+ }++ fn handle_keyup_msg(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {+ let Some(input) = handle_key_event(wparam, lparam, &self.state, |keystroke, _| {+ PlatformInput::KeyUp(KeyUpEvent { keystroke })+ }) else {+ return Some(1);+ };++ let Some(mut func) = self.state.callbacks.input.take() else {+ return Some(1);+ };++ let handled = !func(input).propagate;+ self.state.callbacks.input.set(Some(func));++ if handled { Some(0) } else { Some(1) }+ }++ fn handle_char_msg(&self, wparam: WPARAM) -> Option<isize> {+ let input = self.parse_char_message(wparam)?;+ self.with_input_handler(|input_handler| {+ input_handler.replace_text_in_range(None, &input);+ });++ Some(0)+ }++ fn handle_mouse_down_msg(+ &self,+ handle: HWND,+ button: MouseButton,+ lparam: LPARAM,+ ) -> Option<isize> {+ unsafe { SetCapture(handle) };++ let Some(mut func) = self.state.callbacks.input.take() else {+ return Some(1);+ };+ let x = lparam.signed_loword();+ let y = lparam.signed_hiword();+ let physical_point = point(DevicePixels(x as i32), DevicePixels(y as i32));+ let click_count = self.state.click_state.update(button, physical_point);+ let scale_factor = self.state.scale_factor.get();++ let input = PlatformInput::MouseDown(MouseDownEvent {+ button,+ position: logical_point(x as f32, y as f32, scale_factor),+ modifiers: current_modifiers(),+ click_count,+ first_mouse: false,+ });+ let handled = !func(input).propagate;+ self.state.callbacks.input.set(Some(func));++ if handled { Some(0) } else { Some(1) }+ }++ fn handle_mouse_up_msg(+ &self,+ _handle: HWND,+ button: MouseButton,+ lparam: LPARAM,+ ) -> Option<isize> {+ unsafe { ReleaseCapture().log_err() };++ let Some(mut func) = self.state.callbacks.input.take() else {+ return Some(1);+ };+ let x = lparam.signed_loword() as f32;+ let y = lparam.signed_hiword() as f32;+ let click_count = self.state.click_state.current_count.get();+ let scale_factor = self.state.scale_factor.get();++ let input = PlatformInput::MouseUp(MouseUpEvent {+ button,+ position: logical_point(x, y, scale_factor),+ modifiers: current_modifiers(),+ click_count,+ });+ let handled = !func(input).propagate;+ self.state.callbacks.input.set(Some(func));++ if handled { Some(0) } else { Some(1) }+ }++ /// Touches must not reach `DefWindowProc`, which would also turn them into mouse clicks.+ fn handle_pointer_msg(&self, handle: HWND, msg: u32, wparam: WPARAM) -> Option<isize> {+ let pointer_id = wparam.loword() as u32;+ let mut info = POINTER_INFO::default();+ if unsafe { GetPointerInfo(pointer_id, &mut info) }+ .log_err()+ .is_none()+ {+ return self.cancel_touch(pointer_id);+ }+ if info.pointerType != PT_TOUCH {+ return None;+ }+ let mut location = info.ptPixelLocation;+ if !unsafe { ScreenToClient(handle, &mut location) }.as_bool() {+ self.cancel_touch(pointer_id);+ return Some(0);+ }+ let position = logical_point(+ location.x as f32,+ location.y as f32,+ self.state.scale_factor.get(),+ );+ let mut touches = self.state.touches.borrow_mut();+ let events: Vec<_> = match msg {+ WM_POINTERDOWN => touches.start(pointer_id, (), position),+ WM_POINTERUPDATE => touches.moved(&pointer_id, position).into_iter().collect(),+ _ if info.pointerFlags.contains(POINTER_FLAG_CANCELED) => {+ touches.cancelled(&pointer_id).into_iter().collect()+ }+ _ => {+ let moved = touches.moved(&pointer_id, position);+ moved+ .into_iter()+ .chain(touches.ended(&pointer_id))+ .collect()+ }+ };+ drop(touches);+ self.dispatch_touches(events);+ Some(0)+ }++ fn handle_pointer_capture_changed_msg(&self, wparam: WPARAM) -> Option<isize> {+ self.cancel_touch(wparam.loword() as u32)+ }++ /// Returns `Some(0)` if the pointer was a touch, so the message is kept from `DefWindowProc`.+ fn cancel_touch(&self, pointer_id: u32) -> Option<isize> {+ let cancelled = self.state.touches.borrow_mut().cancelled(&pointer_id)?;+ self.dispatch_touches([cancelled]);+ Some(0)+ }++ fn dispatch_touches(&self, events: impl IntoIterator<Item = ((), TouchEvent)>) {+ let Some(mut func) = self.state.callbacks.input.take() else {+ return;+ };+ for ((), event) in events {+ func(PlatformInput::Touch(event));+ }+ self.state.callbacks.input.set(Some(func));+ }++ fn handle_xbutton_msg(+ &self,+ handle: HWND,+ wparam: WPARAM,+ lparam: LPARAM,+ handler: impl Fn(&Self, HWND, MouseButton, LPARAM) -> Option<isize>,+ ) -> Option<isize> {+ let nav_dir = match wparam.hiword() {+ XBUTTON1 => NavigationDirection::Back,+ XBUTTON2 => NavigationDirection::Forward,+ _ => return Some(1),+ };+ handler(self, handle, MouseButton::Navigate(nav_dir), lparam)+ }++ fn handle_mouse_wheel_msg(+ &self,+ handle: HWND,+ wparam: WPARAM,+ lparam: LPARAM,+ ) -> Option<isize> {+ let modifiers = current_modifiers();++ let Some(mut func) = self.state.callbacks.input.take() else {+ return Some(1);+ };+ let scale_factor = self.state.scale_factor.get();+ let wheel_scroll_amount = match modifiers.shift {+ true => self+ .system_settings()+ .mouse_wheel_settings+ .wheel_scroll_chars+ .get(),+ false => self+ .system_settings()+ .mouse_wheel_settings+ .wheel_scroll_lines+ .get(),+ };++ let wheel_distance =+ (wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_amount as f32;+ let mut cursor_point = POINT {+ x: lparam.signed_loword().into(),+ y: lparam.signed_hiword().into(),+ };+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };+ let input = PlatformInput::ScrollWheel(ScrollWheelEvent {+ position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),+ delta: ScrollDelta::Lines(match modifiers.shift {+ true => Point {+ x: wheel_distance,+ y: 0.0,+ },+ false => Point {+ y: wheel_distance,+ x: 0.0,+ },+ }),+ modifiers,+ touch_phase: TouchPhase::Moved,+ });+ let handled = !func(input).propagate;+ self.state.callbacks.input.set(Some(func));++ if handled { Some(0) } else { Some(1) }+ }++ fn handle_mouse_horizontal_wheel_msg(+ &self,+ handle: HWND,+ wparam: WPARAM,+ lparam: LPARAM,+ ) -> Option<isize> {+ let Some(mut func) = self.state.callbacks.input.take() else {+ return Some(1);+ };+ let scale_factor = self.state.scale_factor.get();+ let wheel_scroll_chars = self+ .system_settings()+ .mouse_wheel_settings+ .wheel_scroll_chars+ .get();++ let wheel_distance =+ (-wparam.signed_hiword() as f32 / WHEEL_DELTA as f32) * wheel_scroll_chars as f32;+ let mut cursor_point = POINT {+ x: lparam.signed_loword().into(),+ y: lparam.signed_hiword().into(),+ };+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };+ let event = PlatformInput::ScrollWheel(ScrollWheelEvent {+ position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),+ delta: ScrollDelta::Lines(Point {+ x: wheel_distance,+ y: 0.0,+ }),+ modifiers: current_modifiers(),+ touch_phase: TouchPhase::Moved,+ });+ let handled = !func(event).propagate;+ self.state.callbacks.input.set(Some(func));++ if handled { Some(0) } else { Some(1) }+ }++ fn retrieve_caret_position(&self) -> Option<POINT> {+ self.with_input_handler_and_scale_factor(|input_handler, scale_factor| {+ let caret_range = input_handler.selected_text_range(false)?;+ let caret_position = input_handler.bounds_for_range(caret_range.range)?;+ Some(POINT {+ // logical to physical+ x: (caret_position.origin.x.as_f32() * scale_factor) as i32,+ y: (caret_position.origin.y.as_f32() * scale_factor) as i32+ + ((caret_position.size.height.as_f32() * scale_factor) as i32 / 2),+ })+ })+ }++ fn handle_ime_position(&self, handle: HWND) -> Option<isize> {+ if let Some(caret_position) = self.retrieve_caret_position() {+ self.update_ime_position(handle, caret_position);+ }+ Some(0)+ }++ pub(crate) fn update_ime_position(&self, handle: HWND, caret_position: POINT) {+ let Some(ctx) = ImeContext::get(handle) else {+ return;+ };+ unsafe {+ ImmSetCompositionWindow(+ *ctx,+ &COMPOSITIONFORM {+ dwStyle: CFS_POINT,+ ptCurrentPos: caret_position,+ ..Default::default()+ },+ )+ .ok()+ .log_err();++ ImmSetCandidateWindow(+ *ctx,+ &CANDIDATEFORM {+ dwStyle: CFS_CANDIDATEPOS,+ ptCurrentPos: caret_position,+ ..Default::default()+ },+ )+ .ok()+ .log_err();+ }+ }++ fn update_ime_enabled(&self, handle: HWND) {+ let ime_enabled = self+ .with_input_handler(|input_handler| input_handler.query_accepts_text_input())+ .unwrap_or(false);+ if ime_enabled == self.state.ime_enabled.get() {+ return;+ }+ self.state.ime_enabled.set(ime_enabled);+ unsafe {+ if ime_enabled {+ ImmAssociateContextEx(handle, HIMC::default(), IACE_DEFAULT)+ .ok()+ .log_err();+ } else {+ // The IME context is per-thread, so without this check a change in this+ // window's text input state could commit an IME composition happening in another window.+ if GetFocus() == handle+ && let Some(ctx) = ImeContext::get(handle)+ {+ ImmNotifyIME(*ctx, NI_COMPOSITIONSTR, CPS_COMPLETE, 0)+ .ok()+ .log_err();+ }+ ImmAssociateContextEx(handle, HIMC::default(), 0)+ .ok()+ .log_err();+ }+ }+ }++ fn handle_ime_composition(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {+ let ctx = ImeContext::get(handle)?;+ self.handle_ime_composition_inner(*ctx, lparam)+ }++ fn handle_ime_composition_inner(&self, ctx: HIMC, lparam: LPARAM) -> Option<isize> {+ let lparam = lparam.0 as u32;+ if lparam == 0 {+ // Japanese IME may send this message with lparam = 0, which indicates that+ // there is no composition string.+ self.with_input_handler(|input_handler| {+ input_handler.replace_text_in_range(None, "");+ })?;+ Some(0)+ } else {+ if lparam & GCS_RESULTSTR.0 > 0 {+ let comp_result = parse_ime_composition_string(ctx, GCS_RESULTSTR)?;+ self.with_input_handler(|input_handler| {+ input_handler+ .replace_text_in_range(None, &String::from_utf16_lossy(&comp_result));+ })?;+ }+ if lparam & GCS_COMPSTR.0 > 0 {+ let comp_string = parse_ime_composition_string(ctx, GCS_COMPSTR)?;+ let caret_pos =+ (!comp_string.is_empty() && lparam & GCS_CURSORPOS.0 > 0).then(|| {+ let cursor_pos = retrieve_composition_cursor_position(ctx);+ let pos = if should_use_ime_cursor_position(ctx, cursor_pos) {+ cursor_pos+ } else {+ comp_string.len()+ };+ pos..pos+ });+ self.with_input_handler(|input_handler| {+ input_handler.replace_and_mark_text_in_range(+ None,+ &String::from_utf16_lossy(&comp_string),+ caret_pos,+ );+ })?;+ }+ if lparam & (GCS_RESULTSTR.0 | GCS_COMPSTR.0) > 0 {+ return Some(0);+ }++ // currently, we don't care other stuff+ None+ }+ }++ fn handle_calc_client_size(+ &self,+ handle: HWND,+ wparam: WPARAM,+ lparam: LPARAM,+ ) -> Option<isize> {+ if !self.hide_title_bar || self.state.is_fullscreen() || wparam.0 == 0 {+ return None;+ }++ unsafe {+ let params = lparam.0 as *mut NCCALCSIZE_PARAMS;+ let saved_top = (*params).rgrc[0].top;+ let result = DefWindowProcW(handle, WM_NCCALCSIZE, wparam, lparam);+ (*params).rgrc[0].top = saved_top;+ if self.state.is_maximized() {+ let dpi = GetDpiForWindow(handle);+ (*params).rgrc[0].top += get_frame_thicknessx(dpi);+ }+ Some(result.0 as isize)+ }+ }++ fn handle_activate_msg(self: &Rc<Self>, wparam: WPARAM) -> Option<isize> {+ let activated = wparam.loword() > 0;++ let events = self+ .state+ .a11y+ .try_borrow_mut()+ .ok()+ .and_then(|mut a11y| a11y.as_mut()?.adapter.update_window_focus_state(activated));+ if let Some(events) = events {+ events.raise();+ }++ let this = self.clone();++ if !activated {+ this.state.cursor_visible.store(true, Ordering::Relaxed);+ }++ // When the window is activated (gains focus), reset the modifier tracking state.+ // This fixes the issue where Alt-Tab away and back leaves stale modifier state+ // (especially the Alt key) because Windows doesn't always send key-up events to+ // windows that have lost focus.+ if activated {+ this.state.last_reported_modifiers.set(None);+ this.state.last_reported_capslock.set(None);++ if let Some(mut func) = this.state.callbacks.input.take() {+ let input = PlatformInput::ModifiersChanged(ModifiersChangedEvent {+ modifiers: current_modifiers(),+ capslock: current_capslock(),+ });+ func(input);+ this.state.callbacks.input.set(Some(func));+ }+ }++ self.executor+ .spawn(async move {+ if let Some(mut func) = this.state.callbacks.active_status_change.take() {+ func(activated);+ this.state.callbacks.active_status_change.set(Some(func));+ }+ })+ .detach();++ None+ }++ fn handle_wm_getobject(&self, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {+ let result = {+ let mut a11y = self.state.a11y.borrow_mut();+ let a11y = a11y.as_mut()?;+ a11y.adapter.handle_wm_getobject(+ accesskit_windows::WPARAM(wparam.0),+ accesskit_windows::LPARAM(lparam.0),+ &mut a11y.activation_handler,+ )?+ };+ // The borrow above must be dropped before calling `.into()`, because+ // it calls `UiaReturnRawElementProvider` which may send a nested+ // `WM_GETOBJECT` back into this window procedure.+ let lresult: accesskit_windows::LRESULT = result.into();+ Some(lresult.0)+ }++ fn handle_create_msg(&self, handle: HWND) -> Option<isize> {+ if self.hide_title_bar {+ notify_frame_changed(handle);+ Some(0)+ } else {+ None+ }+ }++ fn handle_dpi_changed_msg(+ &self,+ handle: HWND,+ wparam: WPARAM,+ lparam: LPARAM,+ ) -> Option<isize> {+ let new_dpi = wparam.loword() as f32;++ let is_maximized = self.state.is_maximized();+ let new_scale_factor = new_dpi / USER_DEFAULT_SCREEN_DPI as f32;+ self.state.scale_factor.set(new_scale_factor);+ self.state.border_offset.update(handle).log_err();++ self.state+ .direct_manipulation+ .set_scale_factor(new_scale_factor);++ if is_maximized {+ // Get the monitor and its work area at the new DPI+ let monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONEAREST) };+ let mut monitor_info: MONITORINFO = unsafe { std::mem::zeroed() };+ monitor_info.cbSize = std::mem::size_of::<MONITORINFO>() as u32;+ if unsafe { GetMonitorInfoW(monitor, &mut monitor_info) }.as_bool() {+ let work_area = monitor_info.rcWork;+ let width = work_area.right - work_area.left;+ let height = work_area.bottom - work_area.top;++ // Update the window size to match the new monitor work area+ // This will trigger WM_SIZE which will handle the size change+ unsafe {+ SetWindowPos(+ handle,+ None,+ work_area.left,+ work_area.top,+ width,+ height,+ SWP_NOZORDER | SWP_NOACTIVATE | SWP_FRAMECHANGED,+ )+ .context("unable to set maximized window position after dpi has changed")+ .log_err();+ }++ // SetWindowPos may not send WM_SIZE for maximized windows in some cases,+ // so we manually update the size to ensure proper rendering+ let device_size = size(DevicePixels(width), DevicePixels(height));+ self.handle_size_change(device_size, new_scale_factor, true);+ }+ } else {+ // For non-maximized windows, use the suggested RECT from the system+ let rect = unsafe { &*(lparam.0 as *const RECT) };+ let width = rect.right - rect.left;+ let height = rect.bottom - rect.top;+ // this will emit `WM_SIZE` and `WM_MOVE` right here+ // even before this function returns+ // the new size is handled in `WM_SIZE`+ unsafe {+ SetWindowPos(+ handle,+ None,+ rect.left,+ rect.top,+ width,+ height,+ SWP_NOZORDER | SWP_NOACTIVATE,+ )+ .context("unable to set window position after dpi has changed")+ .log_err();+ }+ }++ Some(0)+ }++ fn handle_display_change_msg(&self, handle: HWND) -> Option<isize> {+ let new_monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) };+ if new_monitor.is_invalid() {+ log::error!("No monitor detected!");+ return None;+ }+ let new_display = WindowsDisplay::new(WindowsDisplay::display_id_for_monitor(new_monitor))?;+ self.state.display.set(new_display);+ Some(0)+ }++ fn handle_hit_test_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {+ if self.state.is_fullscreen() {+ return None;+ }++ let callback = self.state.callbacks.hit_test_window_control.take();+ let drag_area = if let Some(mut callback) = callback {+ let area = callback();+ self.state+ .callbacks+ .hit_test_window_control+ .set(Some(callback));+ area.and_then(|area| match area {+ WindowControlArea::Drag if self.is_movable => Some(HTCAPTION as _),+ WindowControlArea::Drag => None,+ WindowControlArea::Close => Some(HTCLOSE as _),+ WindowControlArea::Max if self.is_resizable => Some(HTMAXBUTTON as _),+ WindowControlArea::Max if self.is_movable => Some(HTCAPTION as _),+ WindowControlArea::Max => Some(HTNOWHERE as _),+ WindowControlArea::Min if self.is_minimizable => Some(HTMINBUTTON as _),+ WindowControlArea::Min if self.is_movable => Some(HTCAPTION as _),+ WindowControlArea::Min => Some(HTNOWHERE as _),+ })+ } else {+ None+ };++ if !self.hide_title_bar {+ // If the OS draws the title bar, we don't need to handle hit test messages.+ return drag_area;+ }++ let dpi = unsafe { GetDpiForWindow(handle) };+ // We do not use the OS title bar, so the default `DefWindowProcW` will only register a 1px edge for resizes+ // We need to calculate the frame thickness ourselves and do the hit test manually.+ let frame_y = get_frame_thicknessx(dpi);+ let frame_x = get_frame_thicknessy(dpi);+ let mut cursor_point = POINT {+ x: lparam.signed_loword().into(),+ y: lparam.signed_hiword().into(),+ };++ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };+ if self.is_resizable+ && !self.state.is_maximized()+ && 0 <= cursor_point.y+ && cursor_point.y <= frame_y+ {+ // x-axis actually goes from -frame_x to 0+ return Some(if cursor_point.x <= 0 {+ HTTOPLEFT+ } else {+ let mut rect = Default::default();+ unsafe { GetWindowRect(handle, &mut rect) }.log_err();+ // right and bottom bounds of RECT are exclusive, thus `-1`+ let right = rect.right - rect.left - 1;+ // the bounds include the padding frames, so accommodate for both of them+ if right - 2 * frame_x <= cursor_point.x {+ HTTOPRIGHT+ } else {+ HTTOP+ }+ } as _);+ }++ drag_area+ }++ fn handle_nc_mouse_move_msg(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {+ self.start_tracking_mouse(handle, TME_LEAVE | TME_NONCLIENT);+ self.restore_cursor_after_hide();++ let mut func = self.state.callbacks.input.take()?;+ let scale_factor = self.state.scale_factor.get();++ let mut cursor_point = POINT {+ x: lparam.signed_loword().into(),+ y: lparam.signed_hiword().into(),+ };+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };+ let input = PlatformInput::MouseMove(MouseMoveEvent {+ position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),+ pressed_button: None,+ modifiers: current_modifiers(),+ });+ let handled = !func(input).propagate;+ self.state.callbacks.input.set(Some(func));++ if handled { Some(0) } else { None }+ }++ fn handle_nc_mouse_down_msg(+ &self,+ handle: HWND,+ button: MouseButton,+ wparam: WPARAM,+ lparam: LPARAM,+ ) -> Option<isize> {+ if let Some(mut func) = self.state.callbacks.input.take() {+ let scale_factor = self.state.scale_factor.get();+ let mut cursor_point = POINT {+ x: lparam.signed_loword().into(),+ y: lparam.signed_hiword().into(),+ };+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };+ let physical_point = point(DevicePixels(cursor_point.x), DevicePixels(cursor_point.y));+ let click_count = self.state.click_state.update(button, physical_point);++ let input = PlatformInput::MouseDown(MouseDownEvent {+ button,+ position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),+ modifiers: current_modifiers(),+ click_count,+ first_mouse: false,+ });+ let handled = !func(input).propagate;+ self.state.callbacks.input.set(Some(func));++ if handled {+ return Some(0);+ }+ } else {+ };++ // Since these are handled in handle_nc_mouse_up_msg we must prevent the default window proc+ if button == MouseButton::Left {+ match wparam.0 as u32 {+ HTMINBUTTON => self.state.nc_button_pressed.set(Some(HTMINBUTTON)),+ HTMAXBUTTON => self.state.nc_button_pressed.set(Some(HTMAXBUTTON)),+ HTCLOSE => self.state.nc_button_pressed.set(Some(HTCLOSE)),+ _ => return None,+ };+ Some(0)+ } else {+ None+ }+ }++ fn handle_nc_mouse_up_msg(+ &self,+ handle: HWND,+ button: MouseButton,+ wparam: WPARAM,+ lparam: LPARAM,+ ) -> Option<isize> {+ if let Some(mut func) = self.state.callbacks.input.take() {+ let scale_factor = self.state.scale_factor.get();++ let mut cursor_point = POINT {+ x: lparam.signed_loword().into(),+ y: lparam.signed_hiword().into(),+ };+ unsafe { ScreenToClient(handle, &mut cursor_point).ok().log_err() };+ let input = PlatformInput::MouseUp(MouseUpEvent {+ button,+ position: logical_point(cursor_point.x as f32, cursor_point.y as f32, scale_factor),+ modifiers: current_modifiers(),+ click_count: 1,+ });+ let handled = !func(input).propagate;+ self.state.callbacks.input.set(Some(func));++ if handled {+ return Some(0);+ }+ } else {+ }++ let last_pressed = self.state.nc_button_pressed.take();+ if button == MouseButton::Left+ && let Some(last_pressed) = last_pressed+ {+ let handled = match (wparam.0 as u32, last_pressed) {+ (HTMINBUTTON, HTMINBUTTON) if self.is_minimizable => {+ unsafe { ShowWindowAsync(handle, SW_MINIMIZE).ok().log_err() };+ true+ }+ (HTMINBUTTON, HTMINBUTTON) => true,+ (HTMAXBUTTON, HTMAXBUTTON) if self.is_resizable => {+ if self.state.is_maximized() {+ unsafe { ShowWindowAsync(handle, SW_NORMAL).ok().log_err() };+ } else {+ unsafe { ShowWindowAsync(handle, SW_MAXIMIZE).ok().log_err() };+ }+ true+ }+ (HTMAXBUTTON, HTMAXBUTTON) => true,+ (HTCLOSE, HTCLOSE) => {+ unsafe {+ PostMessageW(Some(handle), WM_CLOSE, WPARAM::default(), LPARAM::default())+ .log_err()+ };+ true+ }+ _ => false,+ };+ if handled {+ return Some(0);+ }+ }++ None+ }++ fn handle_cursor_changed(&self, lparam: LPARAM) -> Option<isize> {+ let had_cursor = self.state.current_cursor.get().is_some();++ self.state.current_cursor.set(if lparam.0 == 0 {+ None+ } else {+ Some(HCURSOR(lparam.0 as _))+ });++ if had_cursor != self.state.current_cursor.get().is_some() {+ unsafe { SetCursor(self.state.current_cursor.get()) };+ }++ Some(0)+ }++ fn handle_set_cursor(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {+ if unsafe { !IsWindowEnabled(handle).as_bool() }+ || matches!(+ lparam.loword() as u32,+ HTLEFT+ | HTRIGHT+ | HTTOP+ | HTTOPLEFT+ | HTTOPRIGHT+ | HTBOTTOM+ | HTBOTTOMLEFT+ | HTBOTTOMRIGHT+ )+ {+ return None;+ }+ let cursor = if self.state.cursor_visible.load(Ordering::Relaxed) {+ self.state.current_cursor.get()+ } else {+ None+ };+ unsafe {+ SetCursor(cursor);+ };+ Some(0)+ }++ fn handle_system_settings_changed(+ &self,+ handle: HWND,+ wparam: WPARAM,+ lparam: LPARAM,+ ) -> Option<isize> {+ if wparam.0 != 0 {+ self.state.click_state.system_update(wparam.0);+ self.state.border_offset.update(handle).log_err();+ // system settings may emit a window message which wants to take the refcell self.state, so drop it++ self.system_settings().update(wparam.0);+ } else {+ self.handle_system_theme_changed(handle, lparam)?;+ };++ Some(0)+ }++ fn handle_system_theme_changed(&self, handle: HWND, lparam: LPARAM) -> Option<isize> {+ // lParam is a pointer to a string that indicates the area containing the system parameter+ // that was changed.+ let parameter = PCWSTR::from_raw(lparam.0 as _);+ if unsafe { !parameter.is_null() && !parameter.is_empty() }+ && let Some(parameter_string) = unsafe { parameter.to_string() }.log_err()+ {+ log::info!("System settings changed: {}", parameter_string);+ if parameter_string.as_str() == "ImmersiveColorSet" {+ let new_appearance = system_appearance()+ .context("unable to get system appearance when handling ImmersiveColorSet")+ .log_err()?;++ if new_appearance != self.state.appearance.get() {+ self.state.appearance.set(new_appearance);+ let mut callback = self.state.callbacks.appearance_changed.take()?;++ callback();+ self.state.callbacks.appearance_changed.set(Some(callback));+ configure_dwm_dark_mode(handle, new_appearance);+ }+ }+ }+ Some(0)+ }++ fn handle_input_language_changed(&self) -> Option<isize> {+ unsafe {+ PostMessageW(+ Some(self.platform_window_handle),+ WM_GPUI_KEYBOARD_LAYOUT_CHANGED,+ WPARAM(self.validation_number),+ LPARAM(0),+ )+ .log_err();+ }+ Some(0)+ }++ fn handle_window_visibility_changed(&self, handle: HWND, wparam: WPARAM) -> Option<isize> {+ if wparam.0 == 1 {+ self.draw_window(handle, false);+ }+ None+ }++ fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {+ let devices = lparam.0 as *const DirectXDevices;+ let devices = unsafe { &*devices };+ if let Err(err) = self+ .state+ .renderer+ .borrow_mut()+ .handle_device_lost(&devices)+ {+ panic!("Device lost: {err}");+ }+ // Make sure the first `draw_window` after recovery (whether it comes+ // from the forced WM_GPUI_FORCE_UPDATE_WINDOW or a stray WM_PAINT in+ // between) is treated as a forced render so it both clears+ // `skip_draws` and bypasses the view cache.+ self.state.force_render_pending.set(true);+ Some(0)+ }++ fn handle_dm_pointer_hit_test(&self, wparam: WPARAM) -> Option<isize> {+ self.state.direct_manipulation.on_pointer_hit_test(wparam);+ None+ }++ #[inline]+ fn draw_window(&self, handle: HWND, force_render: bool) -> Option<isize> {+ let Some(_guard) = self.state.draw_coordinator.try_begin_draw() else {+ log::debug!("deferring re-entrant draw of window {handle:?}");+ if force_render {+ self.state.force_render_pending.set(true);+ }+ // Validate the region so a nested message pump doesn't keep+ // re-dispatching WM_PAINT for the still-invalid region in a busy+ // loop until the in-progress draw unwinds. The vsync thread+ // re-invalidates every window on each vsync (see+ // `begin_vsync_thread`), so the deferred frame still gets drawn,+ // at most one vsync late.+ unsafe { ValidateRect(Some(handle), None).ok().log_err() };+ return Some(0);+ };+ let mut request_frame = self.state.callbacks.request_frame.take()?;++ self.state.direct_manipulation.update();++ let events = self.state.direct_manipulation.drain_events();+ if !events.is_empty() {+ if let Some(mut func) = self.state.callbacks.input.take() {+ for event in events {+ func(event);+ }+ self.state.callbacks.input.set(Some(func));+ }+ }++ let force_render = force_render || self.state.force_render_pending.take();+ if force_render {+ // Re-enable drawing after a device loss recovery. The forced render+ // will rebuild the scene with fresh atlas textures.+ self.state.renderer.borrow_mut().mark_drawable();+ }+ request_frame(RequestFrameOptions {+ require_presentation: false,+ force_render,+ });++ self.state.callbacks.request_frame.set(Some(request_frame));+ self.update_ime_enabled(handle);+ unsafe { ValidateRect(Some(handle), None).ok().log_err() };++ Some(0)+ }++ #[inline]+ fn parse_char_message(&self, wparam: WPARAM) -> Option<String> {+ let code_point = wparam.loword();++ // https://www.unicode.org/versions/Unicode16.0.0/core-spec/chapter-3/#G2630+ match code_point {+ 0xD800..=0xDBFF => {+ // High surrogate, wait for low surrogate+ self.state.pending_surrogate.set(Some(code_point));+ None+ }+ 0xDC00..=0xDFFF => {+ if let Some(high_surrogate) = self.state.pending_surrogate.take() {+ // Low surrogate, combine with pending high surrogate+ String::from_utf16(&[high_surrogate, code_point]).ok()+ } else {+ // Invalid low surrogate without a preceding high surrogate+ log::warn!(+ "Received low surrogate without a preceding high surrogate: {code_point:x}"+ );+ None+ }+ }+ _ => {+ self.state.pending_surrogate.set(None);+ char::from_u32(code_point as u32)+ .filter(|c| !c.is_control())+ .map(|c| c.to_string())+ }+ }+ }++ /// Clear the hidden flag and restore the cursor immediately+ fn restore_cursor_after_hide(&self) {+ if !self.state.cursor_visible.swap(true, Ordering::Relaxed) {+ unsafe {+ SetCursor(self.state.current_cursor.get());+ }+ }+ }++ fn start_tracking_mouse(&self, handle: HWND, flags: TRACKMOUSEEVENT_FLAGS) {+ if !self.state.hovered.get() {+ self.state.hovered.set(true);+ unsafe {+ TrackMouseEvent(&mut TRACKMOUSEEVENT {+ cbSize: std::mem::size_of::<TRACKMOUSEEVENT>() as u32,+ dwFlags: flags,+ hwndTrack: handle,+ dwHoverTime: HOVER_DEFAULT,+ })+ .log_err()+ };+ if let Some(mut callback) = self.state.callbacks.hovered_status_change.take() {+ callback(true);+ self.state+ .callbacks+ .hovered_status_change+ .set(Some(callback));+ }+ }+ }++ fn with_input_handler<F, R>(&self, f: F) -> Option<R>+ where+ F: FnOnce(&mut PlatformInputHandler) -> R,+ {+ let mut input_handler = self.state.input_handler.take()?;+ let result = f(&mut input_handler);+ self.state.input_handler.set(Some(input_handler));+ Some(result)+ }++ fn with_input_handler_and_scale_factor<F, R>(&self, f: F) -> Option<R>+ where+ F: FnOnce(&mut PlatformInputHandler, f32) -> Option<R>,+ {+ let mut input_handler = self.state.input_handler.take()?;+ let scale_factor = self.state.scale_factor.get();++ let result = f(&mut input_handler, scale_factor);+ self.state.input_handler.set(Some(input_handler));+ result+ }+}++struct ImeContext {+ hwnd: HWND,+ himc: HIMC,+}++impl ImeContext {+ fn get(hwnd: HWND) -> Option<Self> {+ let himc = unsafe { ImmGetContext(hwnd) };+ if himc.is_invalid() {+ return None;+ }+ Some(Self { hwnd, himc })+ }+}++impl std::ops::Deref for ImeContext {+ type Target = HIMC;+ fn deref(&self) -> &HIMC {+ &self.himc+ }+}++impl Drop for ImeContext {+ fn drop(&mut self) {+ unsafe {+ ImmReleaseContext(self.hwnd, self.himc).ok().log_err();+ }+ }+}++fn handle_key_event<F>(+ wparam: WPARAM,+ lparam: LPARAM,+ state: &WindowsWindowState,+ f: F,+) -> Option<PlatformInput>+where+ F: FnOnce(Keystroke, bool) -> PlatformInput,+{+ let virtual_key = VIRTUAL_KEY(wparam.loword());+ let modifiers = current_modifiers();++ match virtual_key {+ VK_SHIFT | VK_CONTROL | VK_MENU | VK_LMENU | VK_RMENU | VK_LWIN | VK_RWIN => {+ if state+ .last_reported_modifiers+ .get()+ .is_some_and(|prev_modifiers| prev_modifiers == modifiers)+ {+ return None;+ }+ state.last_reported_modifiers.set(Some(modifiers));+ Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {+ modifiers,+ capslock: current_capslock(),+ }))+ }+ VK_PACKET => None,+ VK_CAPITAL => {+ let capslock = current_capslock();+ if state+ .last_reported_capslock+ .get()+ .is_some_and(|prev_capslock| prev_capslock == capslock)+ {+ return None;+ }+ state.last_reported_capslock.set(Some(capslock));+ Some(PlatformInput::ModifiersChanged(ModifiersChangedEvent {+ modifiers,+ capslock,+ }))+ }+ vkey => {+ let keystroke = parse_normal_key(vkey, lparam, modifiers)?;+ Some(f(keystroke.0, keystroke.1))+ }+ }+}++fn parse_immutable(vkey: VIRTUAL_KEY) -> Option<String> {+ Some(+ match vkey {+ VK_SPACE => "space",+ VK_BACK => "backspace",+ VK_RETURN => "enter",+ VK_TAB => "tab",+ VK_UP => "up",+ VK_DOWN => "down",+ VK_RIGHT => "right",+ VK_LEFT => "left",+ VK_HOME => "home",+ VK_END => "end",+ VK_PRIOR => "pageup",+ VK_NEXT => "pagedown",+ VK_BROWSER_BACK => "back",+ VK_BROWSER_FORWARD => "forward",+ VK_ESCAPE => "escape",+ VK_INSERT => "insert",+ VK_DELETE => "delete",+ VK_APPS => "menu",+ VK_F1 => "f1",+ VK_F2 => "f2",+ VK_F3 => "f3",+ VK_F4 => "f4",+ VK_F5 => "f5",+ VK_F6 => "f6",+ VK_F7 => "f7",+ VK_F8 => "f8",+ VK_F9 => "f9",+ VK_F10 => "f10",+ VK_F11 => "f11",+ VK_F12 => "f12",+ VK_F13 => "f13",+ VK_F14 => "f14",+ VK_F15 => "f15",+ VK_F16 => "f16",+ VK_F17 => "f17",+ VK_F18 => "f18",+ VK_F19 => "f19",+ VK_F20 => "f20",+ VK_F21 => "f21",+ VK_F22 => "f22",+ VK_F23 => "f23",+ VK_F24 => "f24",+ _ => return None,+ }+ .to_string(),+ )+}++fn parse_normal_key(+ vkey: VIRTUAL_KEY,+ lparam: LPARAM,+ mut modifiers: Modifiers,+) -> Option<(Keystroke, bool)> {+ let (key_char, prefer_character_input) = process_key(vkey, lparam.hiword());++ let key = parse_immutable(vkey).or_else(|| {+ let scan_code = lparam.hiword() & 0xFF;+ get_keystroke_key(vkey, scan_code as u32, &mut modifiers)+ })?;++ Some((+ Keystroke {+ modifiers,+ key,+ key_char,+ },+ prefer_character_input,+ ))+}++fn process_key(vkey: VIRTUAL_KEY, scan_code: u16) -> (Option<String>, bool) {+ let mut keyboard_state = [0u8; 256];+ unsafe {+ if GetKeyboardState(&mut keyboard_state).is_err() {+ return (None, false);+ }+ }++ let mut buffer_c = [0u16; 8];+ let result_c = unsafe {+ ToUnicode(+ vkey.0 as u32,+ scan_code as u32,+ Some(&keyboard_state),+ &mut buffer_c,+ 0x4,+ )+ };++ if result_c == 0 {+ return (None, false);+ }++ let c = &buffer_c[..result_c.unsigned_abs() as usize];+ let key_char = String::from_utf16(c)+ .ok()+ .filter(|s| !s.is_empty() && !s.chars().next().unwrap().is_control());++ if result_c < 0 {+ return (key_char, true);+ }++ if key_char.is_none() {+ return (None, false);+ }++ // Workaround for some bug that makes the compiler think keyboard_state is still zeroed out+ let keyboard_state = std::hint::black_box(keyboard_state);+ let ctrl_down = (keyboard_state[VK_CONTROL.0 as usize] & 0x80) != 0;+ let alt_down = (keyboard_state[VK_MENU.0 as usize] & 0x80) != 0;+ let win_down = (keyboard_state[VK_LWIN.0 as usize] & 0x80) != 0+ || (keyboard_state[VK_RWIN.0 as usize] & 0x80) != 0;++ let has_modifiers = ctrl_down || alt_down || win_down;+ if !has_modifiers {+ return (key_char, false);+ }++ let mut state_no_modifiers = keyboard_state;+ state_no_modifiers[VK_CONTROL.0 as usize] = 0;+ state_no_modifiers[VK_LCONTROL.0 as usize] = 0;+ state_no_modifiers[VK_RCONTROL.0 as usize] = 0;+ state_no_modifiers[VK_MENU.0 as usize] = 0;+ state_no_modifiers[VK_LMENU.0 as usize] = 0;+ state_no_modifiers[VK_RMENU.0 as usize] = 0;+ state_no_modifiers[VK_LWIN.0 as usize] = 0;+ state_no_modifiers[VK_RWIN.0 as usize] = 0;++ let mut buffer_c_no_modifiers = [0u16; 8];+ let result_c_no_modifiers = unsafe {+ ToUnicode(+ vkey.0 as u32,+ scan_code as u32,+ Some(&state_no_modifiers),+ &mut buffer_c_no_modifiers,+ 0x4,+ )+ };++ let c_no_modifiers = &buffer_c_no_modifiers[..result_c_no_modifiers.unsigned_abs() as usize];+ (+ key_char,+ result_c != result_c_no_modifiers || c != c_no_modifiers,+ )+}++fn parse_ime_composition_string(ctx: HIMC, comp_type: IME_COMPOSITION_STRING) -> Option<Vec<u16>> {+ unsafe {+ let string_len = ImmGetCompositionStringW(ctx, comp_type, None, 0);+ if string_len >= 0 {+ let mut buffer = vec![0u8; string_len as usize + 2];+ ImmGetCompositionStringW(+ ctx,+ comp_type,+ Some(buffer.as_mut_ptr() as _),+ string_len as _,+ );+ let wstring = std::slice::from_raw_parts::<u16>(+ buffer.as_mut_ptr().cast::<u16>(),+ string_len as usize / 2,+ );+ Some(wstring.to_vec())+ } else {+ None+ }+ }+}++#[inline]+fn retrieve_composition_cursor_position(ctx: HIMC) -> usize {+ unsafe { ImmGetCompositionStringW(ctx, GCS_CURSORPOS, None, 0) as usize }+}++fn should_use_ime_cursor_position(ctx: HIMC, cursor_pos: usize) -> bool {+ let attrs_size = unsafe { ImmGetCompositionStringW(ctx, GCS_COMPATTR, None, 0) } as usize;+ if attrs_size == 0 {+ return false;+ }++ let mut attrs = vec![0u8; attrs_size];+ let result = unsafe {+ ImmGetCompositionStringW(+ ctx,+ GCS_COMPATTR,+ Some(attrs.as_mut_ptr() as *mut _),+ attrs_size as u32,+ )+ };+ if result <= 0 {+ return false;+ }++ // Keep the cursor adjacent to the inserted text by only using the suggested position+ // if it's adjacent to unconverted text.+ let at_cursor_is_input = cursor_pos < attrs.len() && attrs[cursor_pos] == (ATTR_INPUT as u8);+ let before_cursor_is_input = cursor_pos > 0+ && (cursor_pos - 1) < attrs.len()+ && attrs[cursor_pos - 1] == (ATTR_INPUT as u8);++ at_cursor_is_input || before_cursor_is_input+}++#[inline]+fn is_virtual_key_pressed(vkey: VIRTUAL_KEY) -> bool {+ unsafe { GetKeyState(vkey.0 as i32) < 0 }+}++#[inline]+pub(crate) fn current_modifiers() -> Modifiers {+ Modifiers {+ control: is_virtual_key_pressed(VK_CONTROL),+ alt: is_virtual_key_pressed(VK_MENU),+ shift: is_virtual_key_pressed(VK_SHIFT),+ platform: is_virtual_key_pressed(VK_LWIN) || is_virtual_key_pressed(VK_RWIN),+ function: false,+ }+}++#[inline]+pub(crate) fn current_capslock() -> Capslock {+ let on = unsafe { GetKeyState(VK_CAPITAL.0 as i32) & 1 } > 0;+ Capslock { on }+}++// there is some additional non-visible space when talking about window+// borders on Windows:+// - SM_CXSIZEFRAME: The resize handle.+// - SM_CXPADDEDBORDER: Additional border space that isn't part of the resize handle.+fn get_frame_thicknessx(dpi: u32) -> i32 {+ let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CXSIZEFRAME, dpi) };+ let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };+ resize_frame_thickness + padding_thickness+}++fn get_frame_thicknessy(dpi: u32) -> i32 {+ let resize_frame_thickness = unsafe { GetSystemMetricsForDpi(SM_CYSIZEFRAME, dpi) };+ let padding_thickness = unsafe { GetSystemMetricsForDpi(SM_CXPADDEDBORDER, dpi) };+ resize_frame_thickness + padding_thickness+}++fn notify_frame_changed(handle: HWND) {+ unsafe {+ SetWindowPos(+ handle,+ None,+ 0,+ 0,+ 0,+ 0,+ SWP_FRAMECHANGED+ | SWP_NOACTIVATE+ | SWP_NOCOPYBITS+ | SWP_NOMOVE+ | SWP_NOOWNERZORDER+ | SWP_NOREPOSITION+ | SWP_NOSENDCHANGING+ | SWP_NOSIZE+ | SWP_NOZORDER,+ )+ .log_err();+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/gpui_windows.rs b/native/vendor/wu/crates/gpui_windows/src/gpui_windows.rsnew file mode 100644index 00000000000..79b99e27965--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/gpui_windows.rs@@ -0,0 +1,155 @@+#![cfg(target_os = "windows")]++mod clipboard;+mod destination_list;+mod direct_manipulation;+mod direct_write;+mod directx_atlas;+mod directx_devices;+mod directx_renderer;+mod dispatcher;+mod display;+mod events;+mod keyboard;+mod platform;+mod system_notifications;+mod system_settings;+mod util;+mod vsync;+mod window;+mod wrapper;++pub(crate) use clipboard::*;+pub(crate) use destination_list::*;+pub(crate) use direct_write::*;+pub(crate) use directx_atlas::*;+pub(crate) use directx_devices::*;+pub(crate) use directx_renderer::*;+pub(crate) use dispatcher::*;+pub(crate) use display::*;+pub(crate) use events::*;+pub(crate) use keyboard::*;+pub(crate) use platform::*;+pub(crate) use system_notifications::*;+pub(crate) use system_settings::*;+pub(crate) use util::*;+pub(crate) use vsync::*;+pub(crate) use window::*;+pub(crate) use wrapper::*;++pub use platform::WindowsPlatform;++pub(crate) use windows::Win32::Foundation::HWND;++#[cfg(test)]+mod tests {+ use gpui::{AtlasTile, EdgeFadeParams, ImageAlphaMaskParams, PolychromeSprite, Quad};+ use std::mem::{align_of, offset_of, size_of};++ const SHADERS: &str = include_str!("shaders.hlsl");++ fn hlsl_struct(name: &str) -> &str {+ let declaration = format!("struct {name} {{");+ SHADERS+ .split_once(&declaration)+ .unwrap_or_else(|| panic!("missing HLSL {name} declaration"))+ .1+ .split_once("};")+ .unwrap_or_else(|| panic!("unterminated HLSL {name} declaration"))+ .0+ }++ fn assert_fields_in_order(body: &str, fields: &[&str]) {+ let mut remainder = body;+ for field in fields {+ remainder = remainder+ .split_once(field)+ .unwrap_or_else(|| {+ panic!("missing or out-of-order HLSL field `{field}` in:\n{body}")+ })+ .1;+ }+ }++ #[test]+ fn edge_fade_layout_is_eight_packed_floats() {+ assert_eq!(align_of::<EdgeFadeParams>(), align_of::<f32>());+ assert_eq!(size_of::<EdgeFadeParams>(), 32);+ assert_fields_in_order(+ hlsl_struct("EdgeFadeParams"),+ &[+ "float top_y;",+ "float bottom_y;",+ "float band_top;",+ "float band_bottom;",+ "float left_x;",+ "float right_x;",+ "float band_left;",+ "float band_right;",+ ],+ );+ }++ #[test]+ fn quad_hlsl_layout_includes_trailing_edge_fade() {+ assert_eq!(offset_of!(Quad, fade), 160);+ assert_eq!(size_of::<Quad>(), 192);+ assert_fields_in_order(+ hlsl_struct("Quad"),+ &[+ "uint order;",+ "uint border_style;",+ "Bounds bounds;",+ "Bounds content_mask;",+ "Background background;",+ "Hsla border_color;",+ "Corners corner_radii;",+ "Edges border_widths;",+ "EdgeFadeParams fade;",+ ],+ );+ }++ #[test]+ fn polychrome_hlsl_layout_keeps_fade_before_atlas_tile() {+ assert_eq!(offset_of!(PolychromeSprite, fade), 64);+ assert_eq!(offset_of!(PolychromeSprite, alpha_mask), 96);+ assert_eq!(offset_of!(PolychromeSprite, tile), 136);+ assert_eq!(size_of::<AtlasTile>(), 32);+ assert_eq!(size_of::<PolychromeSprite>(), 168);+ assert_fields_in_order(+ hlsl_struct("PolychromeSprite"),+ &[+ "uint order;",+ "uint pad;",+ "uint grayscale;",+ "float opacity;",+ "Bounds bounds;",+ "Bounds content_mask;",+ "Corners corner_radii;",+ "EdgeFadeParams fade;",+ "ImageAlphaMaskParams alpha_mask;",+ "AtlasTile tile;",+ ],+ );+ }++ #[test]+ fn image_alpha_mask_hlsl_layout_matches_host() {+ assert_eq!(size_of::<ImageAlphaMaskParams>(), 40);+ assert_eq!(offset_of!(ImageAlphaMaskParams, radius), 16);+ assert_eq!(offset_of!(ImageAlphaMaskParams, bottom_feather), 32);+ assert_fields_in_order(+ hlsl_struct("ImageAlphaMaskParams"),+ &[+ "Bounds bounds;",+ "float radius;",+ "float feather;",+ "float clearance;",+ "float bottom_y;",+ "float bottom_feather;",+ "float pad;",+ ],+ );+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/keyboard.rs b/native/vendor/wu/crates/gpui_windows/src/keyboard.rsnew file mode 100644index 00000000000..8164bc1564d--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/keyboard.rs@@ -0,0 +1,371 @@+use anyhow::Result;+use collections::HashMap;+use windows::Win32::UI::{+ Input::KeyboardAndMouse::{+ GetKeyboardLayoutNameW, MAPVK_VK_TO_CHAR, MAPVK_VK_TO_VSC, MapVirtualKeyW, ToUnicode,+ VIRTUAL_KEY, VK_0, VK_1, VK_2, VK_3, VK_4, VK_5, VK_6, VK_7, VK_8, VK_9, VK_ABNT_C1,+ VK_CONTROL, VK_MENU, VK_OEM_1, VK_OEM_2, VK_OEM_3, VK_OEM_4, VK_OEM_5, VK_OEM_6, VK_OEM_7,+ VK_OEM_8, VK_OEM_102, VK_OEM_COMMA, VK_OEM_MINUS, VK_OEM_PERIOD, VK_OEM_PLUS, VK_SHIFT,+ },+ WindowsAndMessaging::KL_NAMELENGTH,+};++use gpui::{+ KeybindingKeystroke, Keystroke, Modifiers, PlatformKeyboardLayout, PlatformKeyboardMapper,+};++pub(crate) struct WindowsKeyboardLayout {+ id: String,+ name: String,+}++pub(crate) struct WindowsKeyboardMapper {+ key_to_vkey: HashMap<String, (u16, bool)>,+ vkey_to_key: HashMap<u16, String>,+ vkey_to_shifted: HashMap<u16, String>,+}++impl PlatformKeyboardLayout for WindowsKeyboardLayout {+ fn id(&self) -> &str {+ &self.id+ }++ fn name(&self) -> &str {+ &self.name+ }+}++impl PlatformKeyboardMapper for WindowsKeyboardMapper {+ fn map_key_equivalent(+ &self,+ mut keystroke: Keystroke,+ use_key_equivalents: bool,+ ) -> KeybindingKeystroke {+ let Some((vkey, shifted_key)) = self.get_vkey_from_key(&keystroke.key, use_key_equivalents)+ else {+ return KeybindingKeystroke::from_keystroke(keystroke);+ };+ if shifted_key && keystroke.modifiers.shift {+ log::warn!(+ "Keystroke '{}' has both shift and a shifted key, this is likely a bug",+ keystroke.key+ );+ }++ let shift = shifted_key || keystroke.modifiers.shift;+ keystroke.modifiers.shift = false;++ let Some(key) = self.vkey_to_key.get(&vkey).cloned() else {+ log::error!(+ "Failed to map key equivalent '{:?}' to a valid key",+ keystroke+ );+ return KeybindingKeystroke::from_keystroke(keystroke);+ };++ keystroke.key = if shift {+ let Some(shifted_key) = self.vkey_to_shifted.get(&vkey).cloned() else {+ log::error!(+ "Failed to map keystroke {:?} with virtual key '{:?}' to a shifted key",+ keystroke,+ vkey+ );+ return KeybindingKeystroke::from_keystroke(keystroke);+ };+ shifted_key+ } else {+ key.clone()+ };++ let modifiers = Modifiers {+ shift,+ ..keystroke.modifiers+ };++ KeybindingKeystroke::new(keystroke, modifiers, key)+ }++ fn get_key_equivalents(&self) -> Option<&HashMap<char, char>> {+ None+ }+}++impl WindowsKeyboardLayout {+ pub(crate) fn new() -> Result<Self> {+ let mut buffer = [0u16; KL_NAMELENGTH as usize]; // KL_NAMELENGTH includes the null terminator+ unsafe { GetKeyboardLayoutNameW(&mut buffer)? };+ let id = String::from_utf16_lossy(&buffer[..buffer.len() - 1]); // Remove the null terminator+ let entry = windows_registry::LOCAL_MACHINE.open(format!(+ "System\\CurrentControlSet\\Control\\Keyboard Layouts\\{id}"+ ))?;+ let name = entry.get_string("Layout Text")?;+ Ok(Self { id, name })+ }++ pub(crate) fn unknown() -> Self {+ Self {+ id: "unknown".to_string(),+ name: "unknown".to_string(),+ }+ }+}++impl WindowsKeyboardMapper {+ pub(crate) fn new() -> Self {+ let mut key_to_vkey = HashMap::default();+ let mut vkey_to_key = HashMap::default();+ let mut vkey_to_shifted = HashMap::default();+ for vkey in CANDIDATE_VKEYS {+ if let Some(key) = get_key_from_vkey(*vkey) {+ key_to_vkey.insert(key.clone(), (vkey.0, false));+ vkey_to_key.insert(vkey.0, key);+ }+ let scan_code = unsafe { MapVirtualKeyW(vkey.0 as u32, MAPVK_VK_TO_VSC) };+ if scan_code == 0 {+ continue;+ }+ if let Some(shifted_key) = get_shifted_key(*vkey, scan_code) {+ key_to_vkey.insert(shifted_key.clone(), (vkey.0, true));+ vkey_to_shifted.insert(vkey.0, shifted_key);+ }+ }+ Self {+ key_to_vkey,+ vkey_to_key,+ vkey_to_shifted,+ }+ }++ fn get_vkey_from_key(&self, key: &str, use_key_equivalents: bool) -> Option<(u16, bool)> {+ if use_key_equivalents {+ get_vkey_from_key_with_us_layout(key)+ } else {+ self.key_to_vkey.get(key).cloned()+ }+ }+}++pub(crate) fn get_keystroke_key(+ vkey: VIRTUAL_KEY,+ scan_code: u32,+ modifiers: &mut Modifiers,+) -> Option<String> {+ if modifiers.shift && need_to_convert_to_shifted_key(vkey) {+ get_shifted_key(vkey, scan_code).inspect(|_| {+ modifiers.shift = false;+ })+ } else {+ get_key_from_vkey(vkey)+ }+}++fn get_key_from_vkey(vkey: VIRTUAL_KEY) -> Option<String> {+ let key_data = unsafe { MapVirtualKeyW(vkey.0 as u32, MAPVK_VK_TO_CHAR) };+ if key_data == 0 {+ return None;+ }++ // The high word contains dead key flag, the low word contains the character+ let key = char::from_u32(key_data & 0xFFFF)?;++ Some(key.to_ascii_lowercase().to_string())+}++#[inline]+fn need_to_convert_to_shifted_key(vkey: VIRTUAL_KEY) -> bool {+ matches!(+ vkey,+ VK_OEM_3+ | VK_OEM_MINUS+ | VK_OEM_PLUS+ | VK_OEM_4+ | VK_OEM_5+ | VK_OEM_6+ | VK_OEM_1+ | VK_OEM_7+ | VK_OEM_COMMA+ | VK_OEM_PERIOD+ | VK_OEM_2+ | VK_OEM_102+ | VK_OEM_8+ | VK_ABNT_C1+ | VK_0+ | VK_1+ | VK_2+ | VK_3+ | VK_4+ | VK_5+ | VK_6+ | VK_7+ | VK_8+ | VK_9+ )+}++fn get_shifted_key(vkey: VIRTUAL_KEY, scan_code: u32) -> Option<String> {+ generate_key_char(vkey, scan_code, false, true, false)+}++pub(crate) fn generate_key_char(+ vkey: VIRTUAL_KEY,+ scan_code: u32,+ control: bool,+ shift: bool,+ alt: bool,+) -> Option<String> {+ let mut state = [0; 256];+ if control {+ state[VK_CONTROL.0 as usize] = 0x80;+ }+ if shift {+ state[VK_SHIFT.0 as usize] = 0x80;+ }+ if alt {+ state[VK_MENU.0 as usize] = 0x80;+ }++ let mut buffer = [0; 8];+ let len = unsafe { ToUnicode(vkey.0 as u32, scan_code, Some(&state), &mut buffer, 0x5) };++ match len {+ len if len > 0 => String::from_utf16(&buffer[..len as usize])+ .ok()+ .filter(|candidate| {+ !candidate.is_empty() && !candidate.chars().next().unwrap().is_control()+ }),+ len if len < 0 => String::from_utf16(&buffer[..(-len as usize)]).ok(),+ _ => None,+ }+}++fn get_vkey_from_key_with_us_layout(key: &str) -> Option<(u16, bool)> {+ match key {+ // ` => VK_OEM_3+ "`" => Some((VK_OEM_3.0, false)),+ "~" => Some((VK_OEM_3.0, true)),+ "1" => Some((VK_1.0, false)),+ "!" => Some((VK_1.0, true)),+ "2" => Some((VK_2.0, false)),+ "@" => Some((VK_2.0, true)),+ "3" => Some((VK_3.0, false)),+ "#" => Some((VK_3.0, true)),+ "4" => Some((VK_4.0, false)),+ "$" => Some((VK_4.0, true)),+ "5" => Some((VK_5.0, false)),+ "%" => Some((VK_5.0, true)),+ "6" => Some((VK_6.0, false)),+ "^" => Some((VK_6.0, true)),+ "7" => Some((VK_7.0, false)),+ "&" => Some((VK_7.0, true)),+ "8" => Some((VK_8.0, false)),+ "*" => Some((VK_8.0, true)),+ "9" => Some((VK_9.0, false)),+ "(" => Some((VK_9.0, true)),+ "0" => Some((VK_0.0, false)),+ ")" => Some((VK_0.0, true)),+ "-" => Some((VK_OEM_MINUS.0, false)),+ "_" => Some((VK_OEM_MINUS.0, true)),+ "=" => Some((VK_OEM_PLUS.0, false)),+ "+" => Some((VK_OEM_PLUS.0, true)),+ "[" => Some((VK_OEM_4.0, false)),+ "{" => Some((VK_OEM_4.0, true)),+ "]" => Some((VK_OEM_6.0, false)),+ "}" => Some((VK_OEM_6.0, true)),+ "\\" => Some((VK_OEM_5.0, false)),+ "|" => Some((VK_OEM_5.0, true)),+ ";" => Some((VK_OEM_1.0, false)),+ ":" => Some((VK_OEM_1.0, true)),+ "'" => Some((VK_OEM_7.0, false)),+ "\"" => Some((VK_OEM_7.0, true)),+ "," => Some((VK_OEM_COMMA.0, false)),+ "<" => Some((VK_OEM_COMMA.0, true)),+ "." => Some((VK_OEM_PERIOD.0, false)),+ ">" => Some((VK_OEM_PERIOD.0, true)),+ "/" => Some((VK_OEM_2.0, false)),+ "?" => Some((VK_OEM_2.0, true)),+ _ => None,+ }+}++const CANDIDATE_VKEYS: &[VIRTUAL_KEY] = &[+ VK_OEM_3,+ VK_OEM_MINUS,+ VK_OEM_PLUS,+ VK_OEM_4,+ VK_OEM_5,+ VK_OEM_6,+ VK_OEM_1,+ VK_OEM_7,+ VK_OEM_COMMA,+ VK_OEM_PERIOD,+ VK_OEM_2,+ VK_OEM_102,+ VK_OEM_8,+ VK_ABNT_C1,+ VK_0,+ VK_1,+ VK_2,+ VK_3,+ VK_4,+ VK_5,+ VK_6,+ VK_7,+ VK_8,+ VK_9,+];++#[cfg(test)]+mod tests {+ use crate::WindowsKeyboardMapper;+ use gpui::{Keystroke, Modifiers, PlatformKeyboardMapper};++ #[test]+ fn test_keyboard_mapper() {+ let mapper = WindowsKeyboardMapper::new();++ // Normal case+ let keystroke = Keystroke {+ modifiers: Modifiers::control(),+ key: "a".to_string(),+ key_char: None,+ };+ let mapped = mapper.map_key_equivalent(keystroke.clone(), true);+ assert_eq!(*mapped.inner(), keystroke);+ assert_eq!(mapped.key(), "a");+ assert_eq!(*mapped.modifiers(), Modifiers::control());++ // Shifted case, ctrl-$+ let keystroke = Keystroke {+ modifiers: Modifiers::control(),+ key: "$".to_string(),+ key_char: None,+ };+ let mapped = mapper.map_key_equivalent(keystroke.clone(), true);+ assert_eq!(*mapped.inner(), keystroke);+ assert_eq!(mapped.key(), "4");+ assert_eq!(*mapped.modifiers(), Modifiers::control_shift());++ // Shifted case, but shift is true+ let keystroke = Keystroke {+ modifiers: Modifiers::control_shift(),+ key: "$".to_string(),+ key_char: None,+ };+ let mapped = mapper.map_key_equivalent(keystroke, true);+ assert_eq!(mapped.inner().modifiers, Modifiers::control());+ assert_eq!(mapped.key(), "4");+ assert_eq!(*mapped.modifiers(), Modifiers::control_shift());++ // Windows style+ let keystroke = Keystroke {+ modifiers: Modifiers::control_shift(),+ key: "4".to_string(),+ key_char: None,+ };+ let mapped = mapper.map_key_equivalent(keystroke, true);+ assert_eq!(mapped.inner().modifiers, Modifiers::control());+ assert_eq!(mapped.inner().key, "$");+ assert_eq!(mapped.key(), "4");+ assert_eq!(*mapped.modifiers(), Modifiers::control_shift());+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/platform.rs b/native/vendor/wu/crates/gpui_windows/src/platform.rsnew file mode 100644index 00000000000..059ce1fe4a6--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/platform.rs@@ -0,0 +1,1646 @@+use std::{+ cell::{Cell, RefCell},+ ffi::{OsStr, OsString},+ os::windows::ffi::{OsStrExt as _, OsStringExt as _},+ path::{Path, PathBuf},+ rc::{Rc, Weak},+ sync::{+ Arc,+ atomic::{AtomicBool, Ordering},+ },+};++use anyhow::{Context as _, Result, anyhow};+use futures::channel::oneshot::{self, Receiver};+use gpui_util::{ResultExt, get_powershell, new_std_command};+use itertools::Itertools;+use parking_lot::RwLock;+use smallvec::SmallVec;+use windows::{+ UI::ViewManagement::UISettings,+ Win32::{+ Foundation::*,+ Graphics::{Direct3D11::ID3D11Device, Gdi::*},+ Security::Credentials::*,+ System::{+ Com::*,+ LibraryLoader::*,+ Ole::*,+ Power::*,+ SystemInformation::*,+ SystemServices::POWER_REQUEST_CONTEXT_VERSION,+ Threading::{POWER_REQUEST_CONTEXT_SIMPLE_STRING, REASON_CONTEXT, REASON_CONTEXT_0},+ },+ UI::{Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},+ },+ core::*,+};++use crate::*;+use gpui::*;++pub struct WindowsPlatform {+ inner: Rc<WindowsPlatformInner>,+ raw_window_handles: Arc<RwLock<SmallVec<[SafeHwnd; 4]>>>,+ // The below members will never change throughout the entire lifecycle of the app.+ headless: bool,+ icon: HICON,+ background_executor: BackgroundExecutor,+ foreground_executor: ForegroundExecutor,+ text_system: Arc<dyn PlatformTextSystem>,+ direct_write_text_system: Option<Arc<DirectWriteTextSystem>>,+ drop_target_helper: Option<IDropTargetHelper>,+ /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices+ /// as resizing them has failed, causing us to have lost at least the render target.+ invalidate_devices: Arc<AtomicBool>,+ handle: HWND,+ suspend_resume_notification: RefCell<Option<HPOWERNOTIFY>>,+ disable_direct_composition: bool,+ has_package_identity: bool,+ app_identity: RefCell<Option<(String, String)>>,+ system_notifications: RefCell<SystemNotificationState>,+}++struct WindowsPlatformInner {+ state: WindowsPlatformState,+ raw_window_handles: std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,+ // The below members will never change throughout the entire lifecycle of the app.+ validation_number: usize,+ main_receiver: PriorityQueueReceiver<RunnableVariant>,+ dispatcher: Arc<WindowsDispatcher>,+}++pub(crate) struct WindowsPlatformState {+ callbacks: PlatformCallbacks,+ menus: RefCell<Vec<OwnedMenu>>,+ jump_list: RefCell<JumpList>,+ // NOTE: standard cursor handles don't need to close.+ pub(crate) current_cursor: Cell<Option<HCURSOR>>,+ /// Shared with each window so `WM_SETCURSOR` can read it directly.+ pub(crate) cursor_visible: Arc<AtomicBool>,+ /// Shared with each window to coordinate draws across windows on the UI+ /// thread; see [`DrawCoordinator`].+ pub(crate) draw_coordinator: Rc<DrawCoordinator>,+ directx_devices: RefCell<Option<DirectXDevices>>,+}++#[derive(Default)]+struct PlatformCallbacks {+ open_urls: Cell<Option<Box<dyn FnMut(Vec<String>)>>>,+ quit: Cell<Option<Box<dyn FnMut() -> bool>>>,+ reopen: Cell<Option<Box<dyn FnMut()>>>,+ app_menu_action: Cell<Option<Box<dyn FnMut(&dyn Action)>>>,+ will_open_app_menu: Cell<Option<Box<dyn FnMut()>>>,+ validate_app_menu_command: Cell<Option<Box<dyn FnMut(&dyn Action) -> bool>>>,+ keyboard_layout_change: Cell<Option<Box<dyn FnMut()>>>,+ system_wake: Cell<Option<Box<dyn FnMut()>>>,+}++impl WindowsPlatformState {+ fn new(directx_devices: Option<DirectXDevices>) -> Self {+ let callbacks = PlatformCallbacks::default();+ let jump_list = JumpList::new();+ let current_cursor = load_cursor(CursorStyle::Arrow);++ Self {+ callbacks,+ jump_list: RefCell::new(jump_list),+ current_cursor: Cell::new(current_cursor),+ cursor_visible: Arc::new(AtomicBool::new(true)),+ draw_coordinator: Rc::new(DrawCoordinator::new()),+ directx_devices: RefCell::new(directx_devices),+ menus: RefCell::new(Vec::new()),+ }+ }+}++struct PowerRequest {+ handle: HANDLE,+}++unsafe impl Send for PowerRequest {}++impl PowerRequest {+ fn prevent_idle_sleep(reason: &str) -> Result<Self> {+ let mut reason = reason.encode_utf16().chain([0]).collect::<Vec<_>>();+ let context = REASON_CONTEXT {+ Version: POWER_REQUEST_CONTEXT_VERSION,+ Flags: POWER_REQUEST_CONTEXT_SIMPLE_STRING,+ Reason: REASON_CONTEXT_0 {+ SimpleReasonString: PWSTR(reason.as_mut_ptr()),+ },+ };+ let handle = unsafe { PowerCreateRequest(&context) }+ .context("Failed to create a Windows power request")?;+ if let Err(error) = unsafe { PowerSetRequest(handle, PowerRequestSystemRequired) } {+ unsafe { CloseHandle(handle) }+ .context("Failed to close the Windows power request")+ .log_err();+ return Err(error).context("Failed to set the Windows power request");+ }+ Ok(Self { handle })+ }+}++impl Drop for PowerRequest {+ fn drop(&mut self) {+ unsafe { PowerClearRequest(self.handle, PowerRequestSystemRequired) }+ .context("Failed to clear the Windows power request")+ .log_err();+ unsafe { CloseHandle(self.handle) }+ .context("Failed to close the Windows power request")+ .log_err();+ }+}++impl WindowsPlatform {+ pub fn new(headless: bool) -> Result<Self> {+ unsafe {+ OleInitialize(None).context("unable to initialize Windows OLE")?;+ }+ let (directx_devices, text_system, direct_write_text_system) = if !headless {+ let devices = DirectXDevices::new().context("Creating DirectX devices")?;+ let dw_text_system = Arc::new(+ DirectWriteTextSystem::new(&devices)+ .context("Error creating DirectWriteTextSystem")?,+ );+ (+ Some(devices),+ dw_text_system.clone() as Arc<dyn PlatformTextSystem>,+ Some(dw_text_system),+ )+ } else {+ (+ None,+ Arc::new(gpui::NoopTextSystem::new()) as Arc<dyn PlatformTextSystem>,+ None,+ )+ };++ let (main_sender, main_receiver) = PriorityQueueReceiver::new();+ let validation_number = if usize::BITS == 64 {+ rand::random::<u64>() as usize+ } else {+ rand::random::<u32>() as usize+ };+ let raw_window_handles = Arc::new(RwLock::new(SmallVec::new()));++ register_platform_window_class();+ let mut context = PlatformWindowCreateContext {+ inner: None,+ raw_window_handles: Arc::downgrade(&raw_window_handles),+ validation_number,+ main_sender: Some(main_sender),+ main_receiver: Some(main_receiver),+ directx_devices,+ dispatcher: None,+ };+ let result = unsafe {+ CreateWindowExW(+ WINDOW_EX_STYLE(0),+ PLATFORM_WINDOW_CLASS_NAME,+ None,+ WINDOW_STYLE(0),+ 0,+ 0,+ 0,+ 0,+ Some(HWND_MESSAGE),+ None,+ None,+ Some(&raw const context as *const _),+ )+ };+ let inner = context+ .inner+ .take()+ .context("CreateWindowExW did not run correctly")??;+ let dispatcher = context+ .dispatcher+ .take()+ .context("CreateWindowExW did not run correctly")?;+ let handle = result?;++ let disable_direct_composition = std::env::var(DISABLE_DIRECT_COMPOSITION)+ .is_ok_and(|value| value == "true" || value == "1");+ let background_executor = BackgroundExecutor::new(dispatcher.clone());+ let foreground_executor = ForegroundExecutor::new(dispatcher);++ let drop_target_helper: Option<IDropTargetHelper> = if !headless {+ Some(unsafe {+ CoCreateInstance(&CLSID_DragDropHelper, None, CLSCTX_INPROC_SERVER)+ .context("Error creating drop target helper.")?+ })+ } else {+ None+ };+ let icon = if !headless {+ load_icon().unwrap_or_default()+ } else {+ HICON::default()+ };++ Ok(Self {+ inner,+ handle,+ raw_window_handles,+ headless,+ icon,+ background_executor,+ foreground_executor,+ text_system,+ direct_write_text_system,+ suspend_resume_notification: RefCell::new(None),+ disable_direct_composition,+ has_package_identity: has_package_identity(),+ drop_target_helper,+ invalidate_devices: Arc::new(AtomicBool::new(false)),+ app_identity: RefCell::new(None),+ system_notifications: RefCell::new(SystemNotificationState::new()),+ })+ }++ pub(crate) fn window_from_hwnd(&self, hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {+ self.raw_window_handles+ .read()+ .iter()+ .find(|entry| entry.as_raw() == hwnd)+ .and_then(|hwnd| window_from_hwnd(hwnd.as_raw()))+ }++ #[inline]+ fn post_message(&self, message: u32, wparam: WPARAM, lparam: LPARAM) {+ self.raw_window_handles+ .read()+ .iter()+ .for_each(|handle| unsafe {+ PostMessageW(Some(handle.as_raw()), message, wparam, lparam).log_err();+ });+ }++ fn generate_creation_info(&self) -> WindowCreationInfo {+ WindowCreationInfo {+ icon: self.icon,+ executor: self.foreground_executor.clone(),+ current_cursor: self.inner.state.current_cursor.get(),+ cursor_visible: self.inner.state.cursor_visible.clone(),+ drop_target_helper: self.drop_target_helper.clone().unwrap(),+ validation_number: self.inner.validation_number,+ main_receiver: self.inner.main_receiver.clone(),+ platform_window_handle: self.handle,+ disable_direct_composition: self.disable_direct_composition,+ directx_devices: self.inner.state.directx_devices.borrow().clone().unwrap(),+ invalidate_devices: self.invalidate_devices.clone(),+ draw_coordinator: self.inner.state.draw_coordinator.clone(),+ }+ }++ fn set_dock_menus(&self, menus: Vec<MenuItem>) {+ let mut actions = Vec::new();+ menus.into_iter().for_each(|menu| {+ if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {+ actions.push(dock_menu);+ }+ });+ self.inner.state.jump_list.borrow_mut().dock_menus = actions;+ let borrow = self.inner.state.jump_list.borrow();+ let dock_menus = borrow+ .dock_menus+ .iter()+ .map(|menu| (menu.name.clone(), menu.description.clone()))+ .collect::<Vec<_>>();+ let recent_workspaces = borrow.recent_workspaces.clone();+ self.background_executor+ .spawn(async move {+ update_jump_list(&recent_workspaces, &dock_menus).log_err();+ })+ .detach();+ }++ fn update_jump_list(+ &self,+ menus: Vec<MenuItem>,+ entries: Vec<SmallVec<[PathBuf; 2]>>,+ ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {+ let mut actions = Vec::new();+ menus.into_iter().for_each(|menu| {+ if let Some(dock_menu) = DockMenuItem::new(menu).log_err() {+ actions.push(dock_menu);+ }+ });+ let mut jump_list = self.inner.state.jump_list.borrow_mut();+ jump_list.dock_menus = actions;+ jump_list.recent_workspaces = entries.into();+ let dock_menus = jump_list+ .dock_menus+ .iter()+ .map(|menu| (menu.name.clone(), menu.description.clone()))+ .collect::<Vec<_>>();+ let recent_workspaces = jump_list.recent_workspaces.clone();+ self.background_executor.spawn(async move {+ update_jump_list(&recent_workspaces, &dock_menus)+ .log_err()+ .unwrap_or_default()+ })+ }++ fn find_current_active_window(&self) -> Option<HWND> {+ let active_window_hwnd = unsafe { GetActiveWindow() };+ if active_window_hwnd.is_invalid() {+ return None;+ }+ self.raw_window_handles+ .read()+ .iter()+ .find(|hwnd| hwnd.as_raw() == active_window_hwnd)+ .map(|hwnd| hwnd.as_raw())+ }++ fn begin_vsync_thread(&self) {+ let Some(directx_devices) = self.inner.state.directx_devices.borrow().clone() else {+ return;+ };+ let Some(direct_write_text_system) = &self.direct_write_text_system else {+ return;+ };+ let mut directx_device = directx_devices;+ let platform_window: SafeHwnd = self.handle.into();+ let validation_number = self.inner.validation_number;+ let all_windows = Arc::downgrade(&self.raw_window_handles);+ let text_system = Arc::downgrade(direct_write_text_system);+ let invalidate_devices = self.invalidate_devices.clone();++ std::thread::Builder::new()+ .name("VSyncProvider".to_owned())+ .spawn(move || {+ let vsync_provider = VSyncProvider::new();+ loop {+ vsync_provider.wait_for_vsync();+ if check_device_lost(&directx_device.device)+ || invalidate_devices.fetch_and(false, Ordering::Acquire)+ {+ if let Err(err) = handle_gpu_device_lost(+ &mut directx_device,+ platform_window.as_raw(),+ validation_number,+ &all_windows,+ &text_system,+ ) {+ panic!("Device lost: {err}");+ }+ }+ let Some(all_windows) = all_windows.upgrade() else {+ break;+ };+ for hwnd in all_windows.read().iter() {+ unsafe {+ let _ = RedrawWindow(Some(hwnd.as_raw()), None, None, RDW_INVALIDATE);+ }+ }+ }+ })+ .unwrap();+ }+}++fn translate_accelerator(msg: &MSG) -> Option<()> {+ if msg.message != WM_KEYDOWN && msg.message != WM_SYSKEYDOWN {+ return None;+ }++ let result = unsafe {+ SendMessageW(+ msg.hwnd,+ WM_GPUI_KEYDOWN,+ Some(msg.wParam),+ Some(msg.lParam),+ )+ };+ (result.0 == 0).then_some(())+}++fn encode_restart_arguments(arguments: &[OsString]) -> OsString {+ // `Start-Process` accepts a single native command line, so quote each argument according to+ // the Windows argv parsing rules before passing the complete string through the environment.+ let mut encoded = Vec::new();++ for (index, argument) in arguments.iter().enumerate() {+ if index > 0 {+ encoded.push(b' ' as u16);+ }+ encoded.push(b'"' as u16);++ let mut backslash_count = 0;+ for code_unit in argument.encode_wide() {+ if code_unit == b'\\' as u16 {+ backslash_count += 1;+ } else {+ if code_unit == b'"' as u16 {+ encoded.extend(std::iter::repeat_n(b'\\' as u16, backslash_count * 2 + 1));+ } else {+ encoded.extend(std::iter::repeat_n(b'\\' as u16, backslash_count));+ }+ backslash_count = 0;+ encoded.push(code_unit);+ }+ }++ encoded.extend(std::iter::repeat_n(b'\\' as u16, backslash_count * 2));+ encoded.push(b'"' as u16);+ }++ OsString::from_wide(&encoded)+}++impl Platform for WindowsPlatform {+ fn background_executor(&self) -> BackgroundExecutor {+ self.background_executor.clone()+ }++ fn foreground_executor(&self) -> ForegroundExecutor {+ self.foreground_executor.clone()+ }++ fn text_system(&self) -> Arc<dyn PlatformTextSystem> {+ self.text_system.clone()+ }++ fn keyboard_layout(&self) -> Box<dyn PlatformKeyboardLayout> {+ Box::new(+ WindowsKeyboardLayout::new()+ .log_err()+ .unwrap_or(WindowsKeyboardLayout::unknown()),+ )+ }++ fn keyboard_mapper(&self) -> Rc<dyn PlatformKeyboardMapper> {+ Rc::new(WindowsKeyboardMapper::new())+ }++ fn on_keyboard_layout_change(&self, callback: Box<dyn FnMut()>) {+ self.inner+ .state+ .callbacks+ .keyboard_layout_change+ .set(Some(callback));+ }++ fn on_thermal_state_change(&self, _callback: Box<dyn FnMut()>) {}++ fn thermal_state(&self) -> ThermalState {+ ThermalState::Nominal+ }++ fn prevent_idle_sleep(&self, reason: &str) -> Task<Result<ActivityGuard>> {+ Task::ready(+ PowerRequest::prevent_idle_sleep(reason)+ .map(|request| ActivityGuard::new(move || drop(request))),+ )+ }++ fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {+ on_finish_launching();+ if !self.headless {+ self.begin_vsync_thread();+ }++ let mut msg = MSG::default();+ unsafe {+ while GetMessageW(&mut msg, None, 0, 0).as_bool() {+ if translate_accelerator(&msg).is_none() {+ _ = TranslateMessage(&msg);+ DispatchMessageW(&msg);+ }+ }+ }++ self.inner.with_callback(+ |callbacks| &callbacks.quit,+ |callback| {+ callback();+ },+ );+ }++ fn quit(&self) {+ self.foreground_executor()+ .spawn(async { unsafe { PostQuitMessage(0) } })+ .detach();+ }++ fn restart(+ &self,+ binary_path: Option<PathBuf>,+ arguments: Vec<OsString>,+ ) -> anyhow::Result<()> {+ let pid = std::process::id();+ let app_path = match binary_path {+ Some(path) => path,+ None => self.app_path().context("failed to get app path")?,+ };+ let script = r#"+ $pidToWaitFor = $env:ZED_RESTART_PID+ $exePath = $env:ZED_RESTART_EXECUTABLE+ $argumentList = $env:ZED_RESTART_ARGUMENTS++ [Environment]::SetEnvironmentVariable("ZED_RESTART_PID", $null)+ [Environment]::SetEnvironmentVariable("ZED_RESTART_EXECUTABLE", $null)+ [Environment]::SetEnvironmentVariable("ZED_RESTART_ARGUMENTS", $null)++ while ($true) {+ $process = Get-Process -Id $pidToWaitFor -ErrorAction SilentlyContinue+ if (-not $process) {+ if ([string]::IsNullOrEmpty($argumentList)) {+ Start-Process -FilePath $exePath+ } else {+ Start-Process -FilePath $exePath -ArgumentList $argumentList+ }+ break+ }+ Start-Sleep -Seconds 0.1+ }+ "#;++ // Defer spawning to the foreground executor so it runs after the+ // current `AppCell` borrow is released. On Windows, `Command::spawn()`+ // can pump the Win32 message loop (via `CreateProcessW`), which+ // re-enters message handling possibly resulting in another mutable+ // borrow of the `AppCell` ending up with a double borrow panic+ let powershell =+ get_powershell().context("failed to restart: PowerShell is unavailable")?;+ self.foreground_executor+ .spawn(async move {+ let mut command = new_std_command(powershell);+ let arguments = encode_restart_arguments(&arguments);+ command+ .arg("-command")+ .arg(script)+ .env("ZED_RESTART_PID", pid.to_string())+ .env("ZED_RESTART_EXECUTABLE", app_path)+ .env("ZED_RESTART_ARGUMENTS", arguments);+ #[allow(+ clippy::disallowed_methods,+ reason = "We are restarting ourselves, using std command thus is fine"+ )]+ let restart_process = command.spawn();++ match restart_process {+ Ok(_) => unsafe { PostQuitMessage(0) },+ Err(e) => log::error!("failed to spawn restart script: {:?}", e),+ }+ })+ .detach();+ Ok(())+ }++ fn activate(&self, _ignoring_other_apps: bool) {}++ fn hide(&self) {}++ // Hiding other apps is a macOS concept; there is no Windows equivalent.+ fn hide_other_apps(&self) {}++ fn unhide_other_apps(&self) {}++ fn displays(&self) -> Vec<Rc<dyn PlatformDisplay>> {+ WindowsDisplay::displays()+ }++ fn primary_display(&self) -> Option<Rc<dyn PlatformDisplay>> {+ WindowsDisplay::primary_monitor().map(|display| Rc::new(display) as Rc<dyn PlatformDisplay>)+ }++ fn active_window(&self) -> Option<AnyWindowHandle> {+ let active_window_hwnd = unsafe { GetActiveWindow() };+ self.window_from_hwnd(active_window_hwnd)+ .map(|inner| inner.handle)+ }++ fn open_window(+ &self,+ handle: AnyWindowHandle,+ options: WindowParams,+ ) -> Result<Box<dyn PlatformWindow>> {+ let window = WindowsWindow::new(handle, options, self.generate_creation_info())?;+ let handle = window.get_raw_handle();+ self.raw_window_handles.write().push(handle.into());++ Ok(Box::new(window))+ }++ fn window_appearance(&self) -> WindowAppearance {+ system_appearance().log_err().unwrap_or_default()+ }++ fn open_url(&self, url: &str) {+ if url.is_empty() {+ return;+ }+ let url_string = url.to_string();+ self.background_executor()+ .spawn(async move {+ open_target(&url_string)+ .with_context(|| format!("Opening url: {}", url_string))+ .log_err();+ })+ .detach();+ }++ fn on_open_urls(&self, callback: Box<dyn FnMut(Vec<String>)>) {+ self.inner.state.callbacks.open_urls.set(Some(callback));+ }++ fn prompt_for_paths(+ &self,+ options: PathPromptOptions,+ ) -> Receiver<Result<Option<Vec<PathBuf>>>> {+ let (tx, rx) = oneshot::channel();+ let window = self.find_current_active_window();+ self.foreground_executor()+ .spawn(async move {+ let _ = tx.send(file_open_dialog(options, window));+ })+ .detach();++ rx+ }++ fn prompt_for_new_path(+ &self,+ directory: &Path,+ suggested_name: Option<&str>,+ ) -> Receiver<Result<Option<PathBuf>>> {+ let directory = directory.to_owned();+ let suggested_name = suggested_name.map(|s| s.to_owned());+ let (tx, rx) = oneshot::channel();+ let window = self.find_current_active_window();+ self.foreground_executor()+ .spawn(async move {+ let _ = tx.send(file_save_dialog(directory, suggested_name, window));+ })+ .detach();++ rx+ }++ fn can_select_mixed_files_and_dirs(&self) -> bool {+ // The FOS_PICKFOLDERS flag toggles between "only files" and "only folders".+ false+ }++ fn reveal_path(&self, path: &Path) {+ if path.as_os_str().is_empty() {+ return;+ }+ let path = path.to_path_buf();+ self.background_executor()+ .spawn(async move {+ open_target_in_explorer(&path)+ .with_context(|| format!("Revealing path {} in explorer", path.display()))+ .log_err();+ })+ .detach();+ }++ fn open_with_system(&self, path: &Path) {+ if path.as_os_str().is_empty() {+ return;+ }+ let path = path.to_path_buf();+ self.background_executor()+ .spawn(async move {+ open_target(&path)+ .with_context(|| format!("Opening {} with system", path.display()))+ .log_err();+ })+ .detach();+ }++ fn on_quit(&self, callback: Box<dyn FnMut() -> bool>) {+ self.inner.state.callbacks.quit.set(Some(callback));+ }++ fn on_reopen(&self, callback: Box<dyn FnMut()>) {+ self.inner.state.callbacks.reopen.set(Some(callback));+ }++ fn on_system_wake(&self, callback: Box<dyn FnMut()>) {+ self.inner.state.callbacks.system_wake.set(Some(callback));+ let mut notification = self.suspend_resume_notification.borrow_mut();+ if notification.is_none() {+ *notification = unsafe {+ // SAFETY: self.handle is the platform window receiving WM_POWERBROADCAST.+ RegisterSuspendResumeNotification(+ HANDLE(self.handle.0),+ DEVICE_NOTIFY_WINDOW_HANDLE,+ )+ .log_err()+ };+ }+ }++ fn set_app_identity(&self, identifier: &str, name: &str) {+ // If the process has package identity, it's automatally granted an AUMID by the system.+ if self.has_package_identity {+ return;+ }++ let identifier_utf16 = windows::core::HSTRING::from(identifier);+ // SAFETY: `identifier_utf16` outlives the call and is null-terminated.+ if let Err(error) = unsafe {+ windows::Win32::UI::Shell::SetCurrentProcessExplicitAppUserModelID(+ windows::core::PCWSTR(identifier_utf16.as_ptr()),+ )+ } {+ log::warn!("failed to set the process AppUserModelID: {error}");+ }+ *self.app_identity.borrow_mut() = Some((identifier.to_string(), name.to_string()));+ }++ fn show_system_notification(&self, notification: gpui::SystemNotification) {+ let app_identity = self.app_identity.borrow().clone();+ self.system_notifications+ .borrow_mut()+ .show(+ self.has_package_identity,+ app_identity+ .as_ref()+ .map(|(identifier, name)| (identifier.as_str(), name.as_str())),+ notification,+ )+ .log_err();+ }++ fn dismiss_system_notification(&self, tag: &str) {+ self.system_notifications.borrow_mut().dismiss(tag);+ }++ fn on_system_notification_response(+ &self,+ callback: Box<dyn FnMut(gpui::SystemNotificationResponse)>,+ ) {+ self.system_notifications+ .borrow_mut()+ .on_response(&self.foreground_executor, callback);+ }++ fn set_menus(&self, menus: Vec<Menu>, _keymap: &Keymap) {+ *self.inner.state.menus.borrow_mut() = menus.into_iter().map(|menu| menu.owned()).collect();+ }++ fn get_menus(&self) -> Option<Vec<OwnedMenu>> {+ Some(self.inner.state.menus.borrow().clone())+ }++ fn set_dock_menu(&self, menus: Vec<MenuItem>, _keymap: &Keymap) {+ self.set_dock_menus(menus);+ }++ fn on_app_menu_action(&self, callback: Box<dyn FnMut(&dyn Action)>) {+ self.inner+ .state+ .callbacks+ .app_menu_action+ .set(Some(callback));+ }++ fn on_will_open_app_menu(&self, callback: Box<dyn FnMut()>) {+ self.inner+ .state+ .callbacks+ .will_open_app_menu+ .set(Some(callback));+ }++ fn on_validate_app_menu_command(&self, callback: Box<dyn FnMut(&dyn Action) -> bool>) {+ self.inner+ .state+ .callbacks+ .validate_app_menu_command+ .set(Some(callback));+ }++ fn app_path(&self) -> Result<PathBuf> {+ Ok(std::env::current_exe()?)+ }++ // todo(windows)+ fn path_for_auxiliary_executable(&self, _name: &str) -> Result<PathBuf> {+ anyhow::bail!("not yet implemented");+ }++ fn set_cursor_style(&self, style: CursorStyle) {+ let hcursor = load_cursor(style);+ if self.inner.state.current_cursor.get().map(|c| c.0) != hcursor.map(|c| c.0) {+ self.post_message(+ WM_GPUI_CURSOR_STYLE_CHANGED,+ WPARAM(0),+ LPARAM(hcursor.map_or(0, |c| c.0 as isize)),+ );+ self.inner.state.current_cursor.set(hcursor);+ }+ }++ fn hide_cursor_until_mouse_moves(&self) {+ if !self+ .inner+ .state+ .cursor_visible+ .swap(false, Ordering::Relaxed)+ {+ return;+ }++ for handle in self.raw_window_handles.read().iter() {+ let Some(window) = window_from_hwnd(handle.as_raw()) else {+ continue;+ };+ if window.state.hovered.get() {+ unsafe { SetCursor(None) };+ break;+ }+ }+ }++ fn is_cursor_visible(&self) -> bool {+ self.inner.state.cursor_visible.load(Ordering::Relaxed)+ }++ fn should_auto_hide_scrollbars(&self) -> bool {+ should_auto_hide_scrollbars().log_err().unwrap_or(false)+ }++ fn write_to_clipboard(&self, item: ClipboardItem) {+ write_to_clipboard(item);+ }++ fn read_from_clipboard(&self) -> Option<ClipboardItem> {+ read_from_clipboard()+ }++ fn write_credentials(&self, url: &str, username: &str, password: &[u8]) -> Task<Result<()>> {+ // CredWriteW rejects larger blobs with the opaque RPC error+ // 0x800706F7 "The stub received bad data", so fail with a clear+ // message instead.+ if password.len() > CRED_MAX_CREDENTIAL_BLOB_SIZE as usize {+ return Task::ready(Err(anyhow!(+ "credential for {url} is {} bytes, which exceeds the Windows Credential Manager limit of {CRED_MAX_CREDENTIAL_BLOB_SIZE} bytes",+ password.len()+ )));+ }+ let password = password.to_vec();+ let mut username = username.encode_utf16().chain(Some(0)).collect_vec();+ let mut target_name = windows_credentials_target_name(url)+ .encode_utf16()+ .chain(Some(0))+ .collect_vec();+ self.foreground_executor().spawn(async move {+ let credentials = CREDENTIALW {+ LastWritten: unsafe { GetSystemTimeAsFileTime() },+ Flags: CRED_FLAGS(0),+ Type: CRED_TYPE_GENERIC,+ TargetName: PWSTR::from_raw(target_name.as_mut_ptr()),+ CredentialBlobSize: password.len() as u32,+ CredentialBlob: password.as_ptr() as *mut _,+ Persist: CRED_PERSIST_LOCAL_MACHINE,+ UserName: PWSTR::from_raw(username.as_mut_ptr()),+ ..CREDENTIALW::default()+ };+ unsafe {+ CredWriteW(&credentials, 0).map_err(|err| {+ anyhow!(+ "Failed to write credentials to Windows Credential Manager: {}",+ err,+ )+ })?;+ }+ Ok(())+ })+ }++ fn read_credentials(&self, url: &str) -> Task<Result<Option<(String, Vec<u8>)>>> {+ let target_name = windows_credentials_target_name(url)+ .encode_utf16()+ .chain(Some(0))+ .collect_vec();+ self.foreground_executor().spawn(async move {+ let mut credentials: *mut CREDENTIALW = std::ptr::null_mut();+ let result = unsafe {+ CredReadW(+ PCWSTR::from_raw(target_name.as_ptr()),+ CRED_TYPE_GENERIC,+ None,+ &mut credentials,+ )+ };++ if let Err(err) = result {+ // ERROR_NOT_FOUND means the credential doesn't exist.+ // Return Ok(None) to match macOS and Linux behavior.+ if err.code() == ERROR_NOT_FOUND.to_hresult() {+ return Ok(None);+ }+ return Err(err.into());+ }++ if credentials.is_null() {+ Ok(None)+ } else {+ let username: String = unsafe { (*credentials).UserName.to_string()? };+ let credential_blob = unsafe {+ std::slice::from_raw_parts(+ (*credentials).CredentialBlob,+ (*credentials).CredentialBlobSize as usize,+ )+ };+ let password = credential_blob.to_vec();+ unsafe { CredFree(credentials as *const _ as _) };+ Ok(Some((username, password)))+ }+ })+ }++ fn delete_credentials(&self, url: &str) -> Task<Result<()>> {+ let target_name = windows_credentials_target_name(url)+ .encode_utf16()+ .chain(Some(0))+ .collect_vec();+ self.foreground_executor().spawn(async move {+ unsafe {+ CredDeleteW(+ PCWSTR::from_raw(target_name.as_ptr()),+ CRED_TYPE_GENERIC,+ None,+ )?+ };+ Ok(())+ })+ }++ fn register_url_scheme(&self, _: &str) -> Task<anyhow::Result<()>> {+ Task::ready(Err(anyhow!("register_url_scheme unimplemented")))+ }++ fn perform_dock_menu_action(&self, action: usize) {+ unsafe {+ PostMessageW(+ Some(self.handle),+ WM_GPUI_DOCK_MENU_ACTION,+ WPARAM(self.inner.validation_number),+ LPARAM(action as isize),+ )+ .log_err();+ }+ }++ fn update_jump_list(+ &self,+ menus: Vec<MenuItem>,+ entries: Vec<SmallVec<[PathBuf; 2]>>,+ ) -> Task<Vec<SmallVec<[PathBuf; 2]>>> {+ self.update_jump_list(menus, entries)+ }+}++impl WindowsPlatformInner {+ fn new(context: &mut PlatformWindowCreateContext) -> Result<Rc<Self>> {+ let state = WindowsPlatformState::new(context.directx_devices.take());+ Ok(Rc::new(Self {+ state,+ raw_window_handles: context.raw_window_handles.clone(),+ dispatcher: context+ .dispatcher+ .as_ref()+ .context("missing dispatcher")?+ .clone(),+ validation_number: context.validation_number,+ main_receiver: context+ .main_receiver+ .take()+ .context("missing main receiver")?,+ }))+ }++ /// Calls `project` to project to the corresponding callback field, removes it from callbacks, calls `f` with the callback and then puts the callback back.+ fn with_callback<T>(+ &self,+ project: impl Fn(&PlatformCallbacks) -> &Cell<Option<T>>,+ f: impl FnOnce(&mut T),+ ) {+ let callback = project(&self.state.callbacks).take();+ if let Some(mut callback) = callback {+ f(&mut callback);+ project(&self.state.callbacks).set(Some(callback));+ }+ }++ fn handle_msg(+ self: &Rc<Self>,+ handle: HWND,+ msg: u32,+ wparam: WPARAM,+ lparam: LPARAM,+ ) -> LRESULT {+ let handled = match msg {+ WM_GPUI_CLOSE_ONE_WINDOW+ | WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD+ | WM_GPUI_DOCK_MENU_ACTION+ | WM_GPUI_KEYBOARD_LAYOUT_CHANGED+ | WM_GPUI_GPU_DEVICE_LOST+ | WM_GPUI_END_SESSION => self.handle_gpui_events(msg, wparam, lparam),+ WM_POWERBROADCAST => self.handle_power_broadcast(wparam),+ _ => None,+ };+ if let Some(result) = handled {+ LRESULT(result)+ } else {+ unsafe { DefWindowProcW(handle, msg, wparam, lparam) }+ }+ }++ fn handle_gpui_events(&self, message: u32, wparam: WPARAM, lparam: LPARAM) -> Option<isize> {+ if wparam.0 != self.validation_number {+ log::error!("Wrong validation number while processing message: {message}");+ return None;+ }+ match message {+ WM_GPUI_CLOSE_ONE_WINDOW => {+ self.close_one_window(HWND(lparam.0 as _));+ Some(0)+ }+ WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD => self.run_foreground_task(),+ WM_GPUI_DOCK_MENU_ACTION => self.handle_dock_action_event(lparam.0 as _),+ WM_GPUI_KEYBOARD_LAYOUT_CHANGED => self.handle_keyboard_layout_change(),+ WM_GPUI_GPU_DEVICE_LOST => self.handle_device_lost(lparam),+ WM_GPUI_END_SESSION => self.handle_end_session(),+ _ => unreachable!(),+ }+ }++ fn handle_end_session(&self) -> Option<isize> {+ let mut shutdown_completed = false;+ self.with_callback(+ |callbacks| &callbacks.quit,+ |callback| shutdown_completed = callback(),+ );+ log::logger().flush();+ if shutdown_completed {+ std::process::exit(0);+ }++ // Shutdown couldn't run synchronously, since the AppCell is already borrowed.+ // Windows may terminate the application as soon as we return from this handler, but if we post a WM_QUIT message now,+ // we may get to gracefully shut down the app before we're terminated by the OS.+ unsafe { PostQuitMessage(0) };+ Some(0)+ }++ fn close_one_window(&self, target_window: HWND) -> bool {+ let Some(all_windows) = self.raw_window_handles.upgrade() else {+ log::error!("Failed to upgrade raw window handles");+ return false;+ };+ let mut lock = all_windows.write();+ let index = lock+ .iter()+ .position(|handle| handle.as_raw() == target_window)+ .unwrap();+ lock.remove(index);++ lock.is_empty()+ }++ #[inline]+ fn run_foreground_task(&self) -> Option<isize> {+ const MAIN_TASK_TIMEOUT: u128 = 10;++ let start = std::time::Instant::now();+ 'tasks: loop {+ 'timeout_loop: loop {+ if start.elapsed().as_millis() >= MAIN_TASK_TIMEOUT {+ log::debug!("foreground task timeout reached");+ // we spent our budget on gpui tasks, we likely have a lot of work queued so drain system events first to stay responsive+ // then quit out of foreground work to allow us to process other gpui events first before returning back to foreground task work+ // if we don't we might not for example process window quit events+ let mut msg = MSG::default();+ let process_message = |msg: &_| {+ if translate_accelerator(msg).is_none() {+ _ = unsafe { TranslateMessage(msg) };+ unsafe { DispatchMessageW(msg) };+ }+ };+ let peek_msg = |msg: &mut _, msg_kind| unsafe {+ PeekMessageW(msg, None, 0, 0, PM_REMOVE | msg_kind).as_bool()+ };+ // We need to process a paint message here as otherwise we will re-enter `run_foreground_task` before painting if we have work remaining.+ // The reason for this is that windows prefers custom application message processing over system messages.+ if peek_msg(&mut msg, PM_QS_PAINT) {+ process_message(&msg);+ }+ while peek_msg(&mut msg, PM_QS_INPUT) {+ process_message(&msg);+ }+ // Allow the main loop to process other gpui events before going back into `run_foreground_task`+ unsafe {+ if let Err(_) = PostMessageW(+ Some(self.dispatcher.platform_window_handle.as_raw()),+ WM_GPUI_TASK_DISPATCHED_ON_MAIN_THREAD,+ WPARAM(self.validation_number),+ LPARAM(0),+ ) {+ self.dispatcher.wake_posted.store(false, Ordering::Release);+ };+ }+ break 'tasks;+ }+ let mut main_receiver = self.main_receiver.clone();+ match main_receiver.try_pop() {+ Ok(Some(runnable)) => WindowsDispatcher::execute_runnable(runnable),+ _ => break 'timeout_loop,+ }+ }++ // Someone could enqueue a Runnable here. The flag is still true, so they will not PostMessage.+ // We need to check for those Runnables after we clear the flag.+ self.dispatcher.wake_posted.store(false, Ordering::Release);+ let mut main_receiver = self.main_receiver.clone();+ match main_receiver.try_pop() {+ Ok(Some(runnable)) => {+ self.dispatcher.wake_posted.store(true, Ordering::Release);++ WindowsDispatcher::execute_runnable(runnable);+ }+ _ => break 'tasks,+ }+ }++ Some(0)+ }++ fn handle_dock_action_event(&self, action_idx: usize) -> Option<isize> {+ let Some(action) = self+ .state+ .jump_list+ .borrow()+ .dock_menus+ .get(action_idx)+ .map(|dock_menu| dock_menu.action.boxed_clone())+ else {+ log::error!("Dock menu for index {action_idx} not found");+ return Some(1);+ };+ self.with_callback(+ |callbacks| &callbacks.app_menu_action,+ |callback| callback(&*action),+ );+ Some(0)+ }++ fn handle_keyboard_layout_change(&self) -> Option<isize> {+ self.with_callback(+ |callbacks| &callbacks.keyboard_layout_change,+ |callback| callback(),+ );+ Some(0)+ }++ fn handle_power_broadcast(&self, wparam: WPARAM) -> Option<isize> {+ if wparam.0 as u32 == PBT_APMRESUMEAUTOMATIC {+ self.with_callback(|callbacks| &callbacks.system_wake, |callback| callback());+ }+ Some(1)+ }++ fn handle_device_lost(&self, lparam: LPARAM) -> Option<isize> {+ let directx_devices = lparam.0 as *const DirectXDevices;+ let directx_devices = unsafe { &*directx_devices };+ self.state.directx_devices.borrow_mut().take();+ *self.state.directx_devices.borrow_mut() = Some(directx_devices.clone());++ Some(0)+ }+}++impl Drop for WindowsPlatform {+ fn drop(&mut self) {+ unsafe {+ if let Some(notification) = self.suspend_resume_notification.borrow_mut().take() {+ // SAFETY: notification was returned by RegisterSuspendResumeNotification.+ UnregisterSuspendResumeNotification(notification).log_err();+ }+ DestroyWindow(self.handle)+ .context("Destroying platform window")+ .log_err();+ OleUninitialize();+ }+ }+}++pub(crate) struct WindowCreationInfo {+ pub(crate) icon: HICON,+ pub(crate) executor: ForegroundExecutor,+ pub(crate) current_cursor: Option<HCURSOR>,+ pub(crate) cursor_visible: Arc<AtomicBool>,+ pub(crate) drop_target_helper: IDropTargetHelper,+ pub(crate) validation_number: usize,+ pub(crate) main_receiver: PriorityQueueReceiver<RunnableVariant>,+ pub(crate) platform_window_handle: HWND,+ pub(crate) disable_direct_composition: bool,+ pub(crate) directx_devices: DirectXDevices,+ /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices+ /// as resizing them has failed, causing us to have lost at least the render target.+ pub(crate) invalidate_devices: Arc<AtomicBool>,+ /// Shared with [`WindowsPlatformState::draw_coordinator`] and every other window.+ pub(crate) draw_coordinator: Rc<DrawCoordinator>,+}++struct PlatformWindowCreateContext {+ inner: Option<Result<Rc<WindowsPlatformInner>>>,+ raw_window_handles: std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,+ validation_number: usize,+ main_sender: Option<PriorityQueueSender<RunnableVariant>>,+ main_receiver: Option<PriorityQueueReceiver<RunnableVariant>>,+ directx_devices: Option<DirectXDevices>,+ dispatcher: Option<Arc<WindowsDispatcher>>,+}++fn has_package_identity() -> bool {+ let mut package_full_name_length = 0;+ let result = unsafe {+ windows::Win32::Storage::Packaging::Appx::GetCurrentPackageFullName(+ &mut package_full_name_length,+ None,+ )+ };+ if result == ERROR_INSUFFICIENT_BUFFER {+ true+ } else if result == APPMODEL_ERROR_NO_PACKAGE {+ false+ } else {+ log::warn!("failed to determine whether the process has package identity: {result:?}");+ false+ }+}++fn open_target(target: impl AsRef<OsStr>) -> Result<()> {+ let target = target.as_ref();+ let ret = unsafe {+ ShellExecuteW(+ None,+ windows::core::w!("open"),+ &HSTRING::from(target),+ None,+ None,+ SW_SHOWDEFAULT,+ )+ };+ if ret.0 as isize <= 32 {+ Err(anyhow::anyhow!(+ "Unable to open target: {}",+ std::io::Error::last_os_error()+ ))+ } else {+ Ok(())+ }+}++fn open_target_in_explorer(target: &Path) -> Result<()> {+ let dir = target.parent().context("No parent folder found")?;+ let desktop = unsafe { SHGetDesktopFolder()? };++ let mut dir_item = std::ptr::null_mut();+ unsafe {+ desktop.ParseDisplayName(+ HWND::default(),+ None,+ &HSTRING::from(dir),+ None,+ &mut dir_item,+ std::ptr::null_mut(),+ )?;+ }++ let mut file_item = std::ptr::null_mut();+ unsafe {+ desktop.ParseDisplayName(+ HWND::default(),+ None,+ &HSTRING::from(target),+ None,+ &mut file_item,+ std::ptr::null_mut(),+ )?;+ }++ let highlight = [file_item as *const _];+ unsafe { SHOpenFolderAndSelectItems(dir_item as _, Some(&highlight), 0) }.or_else(|err| {+ if err.code().0 == ERROR_FILE_NOT_FOUND.0 as i32 {+ // On some systems, the above call mysteriously fails with "file not+ // found" even though the file is there. In these cases, ShellExecute()+ // seems to work as a fallback (although it won't select the file).+ open_target(dir).context("Opening target parent folder")+ } else {+ Err(anyhow::anyhow!("Can not open target path: {}", err))+ }+ })+}++fn file_open_dialog(+ options: PathPromptOptions,+ window: Option<HWND>,+) -> Result<Option<Vec<PathBuf>>> {+ let folder_dialog: IFileOpenDialog =+ unsafe { CoCreateInstance(&FileOpenDialog, None, CLSCTX_ALL)? };++ let mut dialog_options = FOS_FILEMUSTEXIST;+ if options.multiple {+ dialog_options |= FOS_ALLOWMULTISELECT;+ }+ if options.directories {+ dialog_options |= FOS_PICKFOLDERS;+ }++ unsafe {+ folder_dialog.SetOptions(dialog_options)?;++ if let Some(prompt) = options.prompt {+ let prompt: &str = &prompt;+ folder_dialog.SetOkButtonLabel(&HSTRING::from(prompt))?;+ }++ if folder_dialog.Show(window).is_err() {+ // User cancelled+ return Ok(None);+ }+ }++ let results = unsafe { folder_dialog.GetResults()? };+ let file_count = unsafe { results.GetCount()? };+ if file_count == 0 {+ return Ok(None);+ }++ let mut paths = Vec::with_capacity(file_count as usize);+ for i in 0..file_count {+ let item = unsafe { results.GetItemAt(i)? };+ let path = unsafe { item.GetDisplayName(SIGDN_FILESYSPATH)?.to_string()? };+ paths.push(PathBuf::from(path));+ }++ Ok(Some(paths))+}++fn file_save_dialog(+ directory: PathBuf,+ suggested_name: Option<String>,+ window: Option<HWND>,+) -> Result<Option<PathBuf>> {+ let dialog: IFileSaveDialog = unsafe { CoCreateInstance(&FileSaveDialog, None, CLSCTX_ALL)? };+ if !directory.to_string_lossy().is_empty()+ && let Some(full_path) = directory+ .canonicalize()+ .context("failed to canonicalize directory")+ .log_err()+ {+ let full_path = dunce::simplified(&full_path);+ let full_path_string = full_path.display().to_string();+ let path_item: IShellItem =+ unsafe { SHCreateItemFromParsingName(&HSTRING::from(full_path_string), None)? };+ unsafe {+ dialog+ .SetFolder(&path_item)+ .context("failed to set dialog folder")+ .log_err()+ };+ }++ if let Some(suggested_name) = suggested_name {+ unsafe {+ dialog+ .SetFileName(&HSTRING::from(suggested_name))+ .context("failed to set file name")+ .log_err()+ };+ }++ unsafe {+ dialog.SetFileTypes(&[Common::COMDLG_FILTERSPEC {+ pszName: windows::core::w!("All files"),+ pszSpec: windows::core::w!("*.*"),+ }])?;+ if dialog.Show(window).is_err() {+ // User cancelled+ return Ok(None);+ }+ }+ let shell_item = unsafe { dialog.GetResult()? };+ let file_path_string = unsafe {+ let pwstr = shell_item.GetDisplayName(SIGDN_FILESYSPATH)?;+ let string = pwstr.to_string()?;+ CoTaskMemFree(Some(pwstr.0 as _));+ string+ };+ Ok(Some(PathBuf::from(file_path_string)))+}++fn load_icon() -> Result<HICON> {+ let module = unsafe { GetModuleHandleW(None).context("unable to get module handle")? };+ let handle = unsafe {+ LoadImageW(+ Some(module.into()),+ windows::core::PCWSTR(1 as _),+ IMAGE_ICON,+ 0,+ 0,+ LR_DEFAULTSIZE | LR_SHARED,+ )+ .context("unable to load icon file")?+ };+ Ok(HICON(handle.0))+}++#[inline]+fn should_auto_hide_scrollbars() -> Result<bool> {+ let ui_settings = UISettings::new()?;+ Ok(ui_settings.AutoHideScrollBars()?)+}++fn check_device_lost(device: &ID3D11Device) -> bool {+ let device_state = unsafe { device.GetDeviceRemovedReason() };+ match device_state {+ Ok(_) => false,+ Err(err) => {+ log::error!("DirectX device lost detected: {:?}", err);+ true+ }+ }+}++fn handle_gpu_device_lost(+ directx_devices: &mut DirectXDevices,+ platform_window: HWND,+ validation_number: usize,+ all_windows: &std::sync::Weak<RwLock<SmallVec<[SafeHwnd; 4]>>>,+ text_system: &std::sync::Weak<DirectWriteTextSystem>,+) -> Result<()> {+ // Here we wait a bit to ensure the system has time to recover from the device lost state.+ // If we don't wait, the final drawing result will be blank.+ std::thread::sleep(std::time::Duration::from_millis(350));++ *directx_devices = try_to_recover_from_device_lost(|| {+ DirectXDevices::new().context("Failed to recreate new DirectX devices after device lost")+ })?;+ log::info!("DirectX devices successfully recreated.");++ let lparam = LPARAM(directx_devices as *const _ as _);+ unsafe {+ SendMessageW(+ platform_window,+ WM_GPUI_GPU_DEVICE_LOST,+ Some(WPARAM(validation_number)),+ Some(lparam),+ );+ }++ if let Some(text_system) = text_system.upgrade() {+ text_system.handle_gpu_lost(&directx_devices)?;+ }+ if let Some(all_windows) = all_windows.upgrade() {+ for window in all_windows.read().iter() {+ unsafe {+ SendMessageW(+ window.as_raw(),+ WM_GPUI_GPU_DEVICE_LOST,+ Some(WPARAM(validation_number)),+ Some(lparam),+ );+ }+ }+ std::thread::sleep(std::time::Duration::from_millis(200));+ for window in all_windows.read().iter() {+ unsafe {+ SendMessageW(+ window.as_raw(),+ WM_GPUI_FORCE_UPDATE_WINDOW,+ Some(WPARAM(validation_number)),+ None,+ );+ }+ }+ }+ Ok(())+}++const PLATFORM_WINDOW_CLASS_NAME: PCWSTR = w!("Wu::PlatformWindow");++fn register_platform_window_class() {+ let wc = WNDCLASSW {+ lpfnWndProc: Some(window_procedure),+ lpszClassName: PCWSTR(PLATFORM_WINDOW_CLASS_NAME.as_ptr()),+ ..Default::default()+ };+ unsafe { RegisterClassW(&wc) };+}++unsafe extern "system" fn window_procedure(+ hwnd: HWND,+ msg: u32,+ wparam: WPARAM,+ lparam: LPARAM,+) -> LRESULT {+ if msg == WM_NCCREATE {+ let params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };+ let creation_context = params.lpCreateParams as *mut PlatformWindowCreateContext;+ let creation_context = unsafe { &mut *creation_context };++ let Some(main_sender) = creation_context.main_sender.take() else {+ creation_context.inner = Some(Err(anyhow!("missing main sender")));+ return LRESULT(0);+ };+ creation_context.dispatcher = Some(Arc::new(WindowsDispatcher::new(+ main_sender,+ hwnd,+ creation_context.validation_number,+ )));++ return match WindowsPlatformInner::new(creation_context) {+ Ok(inner) => {+ let weak = Box::new(Rc::downgrade(&inner));+ unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };+ creation_context.inner = Some(Ok(inner));+ unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }+ }+ Err(error) => {+ creation_context.inner = Some(Err(error));+ LRESULT(0)+ }+ };+ }++ let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsPlatformInner>;+ if ptr.is_null() {+ return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };+ }+ let inner = unsafe { &*ptr };+ let result = if let Some(inner) = inner.upgrade() {+ if cfg!(debug_assertions) {+ let inner = std::panic::AssertUnwindSafe(inner);+ match std::panic::catch_unwind(|| { inner }.handle_msg(hwnd, msg, wparam, lparam)) {+ Ok(result) => result,+ Err(_) => std::process::abort(),+ }+ } else {+ inner.handle_msg(hwnd, msg, wparam, lparam)+ }+ } else {+ unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }+ };++ if msg == WM_NCDESTROY {+ unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };+ unsafe { drop(Box::from_raw(ptr)) };+ }++ result+}++#[cfg(test)]+mod tests {+ use std::ffi::{OsStr, OsString};++ use crate::{read_from_clipboard, write_to_clipboard};+ use gpui::ClipboardItem;++ use super::encode_restart_arguments;++ #[test]+ fn test_encode_restart_arguments() {+ assert_eq!(encode_restart_arguments(&[]), OsStr::new(""));+ assert_eq!(+ encode_restart_arguments(&[+ OsString::from("--user-data-dir"),+ OsString::from(r"C:\Zed Data"),+ ]),+ OsStr::new(r#""--user-data-dir" "C:\Zed Data""#)+ );+ assert_eq!(+ encode_restart_arguments(&[OsString::from(r"C:\")]),+ OsStr::new(r#""C:\\""#)+ );+ }++ #[test]+ fn test_clipboard() {+ let item = ClipboardItem::new_string("你好,我是张小白".to_string());+ write_to_clipboard(item.clone());+ assert_eq!(read_from_clipboard(), Some(item));++ let item = ClipboardItem::new_string("12345".to_string());+ write_to_clipboard(item.clone());+ assert_eq!(read_from_clipboard(), Some(item));++ let item = ClipboardItem::new_string_with_json_metadata("abcdef".to_string(), vec![3, 4]);+ write_to_clipboard(item.clone());+ assert_eq!(read_from_clipboard(), Some(item));+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/shaders.hlsl b/native/vendor/wu/crates/gpui_windows/src/shaders.hlslnew file mode 100644index 00000000000..55b1ddc5ea6--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/shaders.hlsl@@ -0,0 +1,1413 @@+#include "alpha_correction.hlsl"++cbuffer GlobalParams: register(b0) {+ float4 gamma_ratios;+ float2 global_viewport_size;+ float grayscale_enhanced_contrast;+ float subpixel_enhanced_contrast;+ uint is_bgr;+ uint3 global_pad;+};++cbuffer BatchParams: register(b1) {+ uint batch_start_index;+ uint3 batch_pad;+};++Texture2D<float4> t_sprite: register(t0);+SamplerState s_sprite: register(s0);++struct SubpixelSpriteFragmentOutput {+ float4 foreground : SV_Target0;+ float4 alpha : SV_Target1;+};++struct Bounds {+ float2 origin;+ float2 size;+};++struct Corners {+ float top_left;+ float top_right;+ float bottom_right;+ float bottom_left;+};++struct Edges {+ float top;+ float right;+ float bottom;+ float left;+};++struct EdgeFadeParams {+ float top_y;+ float bottom_y;+ float band_top;+ float band_bottom;+ float left_x;+ float right_x;+ float band_left;+ float band_right;+};++struct Hsla {+ float h;+ float s;+ float l;+ float a;+};++struct LinearColorStop {+ Hsla color;+ float percentage;+};++struct Background {+ // 0u is Solid+ // 1u is LinearGradient+ // 2u is PatternSlash+ uint tag;+ // 0u is sRGB linear color+ // 1u is Oklab color+ uint color_space;+ Hsla solid;+ float gradient_angle_or_pattern_height;+ LinearColorStop colors[2];+ uint pad;+};++struct GradientColor {+ float4 solid;+ float4 color0;+ float4 color1;+};++struct AtlasTextureId {+ uint index;+ uint kind;+};++struct AtlasBounds {+ int2 origin;+ int2 size;+};++struct AtlasTile {+ AtlasTextureId texture_id;+ uint tile_id;+ uint padding;+ AtlasBounds bounds;+};++struct TransformationMatrix {+ float2x2 rotation_scale;+ float2 translation;+};++static const float M_PI_F = 3.141592653f;+static const float3 GRAYSCALE_FACTORS = float3(0.2126f, 0.7152f, 0.0722f);++float4 to_device_position_impl(float2 position) {+ float2 device_position = position / global_viewport_size * float2(2.0, -2.0) + float2(-1.0, 1.0);+ return float4(device_position, 0., 1.);+}++float4 to_device_position(float2 unit_vertex, Bounds bounds) {+ float2 position = unit_vertex * bounds.size + bounds.origin;+ return to_device_position_impl(position);+}++float4 distance_from_clip_rect_impl(float2 position, Bounds clip_bounds) {+ float2 tl = position - clip_bounds.origin;+ float2 br = clip_bounds.origin + clip_bounds.size - position;+ return float4(tl.x, br.x, tl.y, br.y);+}++float4 distance_from_clip_rect(float2 unit_vertex, Bounds bounds, Bounds clip_bounds) {+ float2 position = unit_vertex * bounds.size + bounds.origin;+ return distance_from_clip_rect_impl(position, clip_bounds);+}++float4 distance_from_clip_rect_transformed(float2 unit_vertex, Bounds bounds, Bounds clip_bounds, TransformationMatrix transformation) {+ float2 position = unit_vertex * bounds.size + bounds.origin;+ float2 transformed = mul(position, transformation.rotation_scale) + transformation.translation;+ return distance_from_clip_rect_impl(transformed, clip_bounds);+}++// Squared to match the fade curve of the other renderers.+float edge_fade_alpha(float2 position, EdgeFadeParams fade) {+ float ramp = 1.0;+ if (fade.band_top > 0.0) {+ ramp = min(ramp, clamp((position.y - fade.top_y) / fade.band_top, 0.0, 1.0));+ }+ if (fade.band_bottom > 0.0) {+ ramp = min(ramp, clamp((fade.bottom_y - position.y) / fade.band_bottom, 0.0, 1.0));+ }+ if (fade.band_left > 0.0) {+ ramp = min(ramp, clamp((position.x - fade.left_x) / fade.band_left, 0.0, 1.0));+ }+ if (fade.band_right > 0.0) {+ ramp = min(ramp, clamp((fade.right_x - position.x) / fade.band_right, 0.0, 1.0));+ }+ return ramp * ramp;+}++// Convert linear RGB to sRGB+float3 linear_to_srgb(float3 color) {+ return pow(color, float3(1.0 / 2.2, 1.0 / 2.2, 1.0 / 2.2));+}++// Convert sRGB to linear RGB+float3 srgb_to_linear(float3 color) {+ return pow(color, float3(2.2, 2.2, 2.2));+}++/// Hsla to linear RGBA conversion.+float4 hsla_to_rgba(Hsla hsla) {+ float h = hsla.h * 6.0; // Now, it's an angle but scaled in [0, 6) range+ float s = hsla.s;+ float l = hsla.l;+ float a = hsla.a;++ float c = (1.0 - abs(2.0 * l - 1.0)) * s;+ float x = c * (1.0 - abs(fmod(h, 2.0) - 1.0));+ float m = l - c / 2.0;++ float r = 0.0;+ float g = 0.0;+ float b = 0.0;++ if (h >= 0.0 && h < 1.0) {+ r = c;+ g = x;+ b = 0.0;+ } else if (h >= 1.0 && h < 2.0) {+ r = x;+ g = c;+ b = 0.0;+ } else if (h >= 2.0 && h < 3.0) {+ r = 0.0;+ g = c;+ b = x;+ } else if (h >= 3.0 && h < 4.0) {+ r = 0.0;+ g = x;+ b = c;+ } else if (h >= 4.0 && h < 5.0) {+ r = x;+ g = 0.0;+ b = c;+ } else {+ r = c;+ g = 0.0;+ b = x;+ }++ float4 rgba;+ rgba.x = (r + m);+ rgba.y = (g + m);+ rgba.z = (b + m);+ rgba.w = a;+ return rgba;+}++// Converts a sRGB color to the Oklab color space.+// Reference: https://bottosson.github.io/posts/oklab/#converting-from-linear-srgb-to-oklab+float4 srgb_to_oklab(float4 color) {+ // Convert non-linear sRGB to linear sRGB+ color = float4(srgb_to_linear(color.rgb), color.a);++ float l = 0.4122214708 * color.r + 0.5363325363 * color.g + 0.0514459929 * color.b;+ float m = 0.2119034982 * color.r + 0.6806995451 * color.g + 0.1073969566 * color.b;+ float s = 0.0883024619 * color.r + 0.2817188376 * color.g + 0.6299787005 * color.b;++ float l_ = pow(l, 1.0/3.0);+ float m_ = pow(m, 1.0/3.0);+ float s_ = pow(s, 1.0/3.0);++ return float4(+ 0.2104542553 * l_ + 0.7936177850 * m_ - 0.0040720468 * s_,+ 1.9779984951 * l_ - 2.4285922050 * m_ + 0.4505937099 * s_,+ 0.0259040371 * l_ + 0.7827717662 * m_ - 0.8086757660 * s_,+ color.a+ );+}++// Converts an Oklab color to the sRGB color space.+float4 oklab_to_srgb(float4 color) {+ float l_ = color.r + 0.3963377774 * color.g + 0.2158037573 * color.b;+ float m_ = color.r - 0.1055613458 * color.g - 0.0638541728 * color.b;+ float s_ = color.r - 0.0894841775 * color.g - 1.2914855480 * color.b;++ float l = l_ * l_ * l_;+ float m = m_ * m_ * m_;+ float s = s_ * s_ * s_;++ float3 linear_rgb = float3(+ 4.0767416621 * l - 3.3077115913 * m + 0.2309699292 * s,+ -1.2684380046 * l + 2.6097574011 * m - 0.3413193965 * s,+ -0.0041960863 * l - 0.7034186147 * m + 1.7076147010 * s+ );++ // Convert linear sRGB to non-linear sRGB+ return float4(linear_to_srgb(linear_rgb), color.a);+}++// This approximates the error function, needed for the gaussian integral+float2 erf(float2 x) {+ float2 s = sign(x);+ float2 a = abs(x);+ x = 1. + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a;+ x *= x;+ return s - s / (x * x);+}++float blur_along_x(float x, float y, float sigma, float corner, float2 half_size) {+ float delta = min(half_size.y - corner - abs(y), 0.);+ float curved = half_size.x - corner + sqrt(max(0., corner * corner - delta * delta));+ float2 integral = 0.5 + 0.5 * erf((x + float2(-curved, curved)) * (sqrt(0.5) / sigma));+ return integral.y - integral.x;+}++// A standard gaussian function, used for weighting samples+float gaussian(float x, float sigma) {+ return exp(-(x * x) / (2. * sigma * sigma)) / (sqrt(2. * M_PI_F) * sigma);+}++float4 over(float4 below, float4 above) {+ float4 result;+ float alpha = above.a + below.a * (1.0 - above.a);+ result.rgb = (above.rgb * above.a + below.rgb * below.a * (1.0 - above.a)) / alpha;+ result.a = alpha;+ return result;+}++float2 to_tile_position(float2 unit_vertex, AtlasTile tile) {+ float2 atlas_size;+ t_sprite.GetDimensions(atlas_size.x, atlas_size.y);+ return (float2(tile.bounds.origin) + unit_vertex * float2(tile.bounds.size)) / atlas_size;+}++// Selects corner radius based on quadrant.+float pick_corner_radius(float2 center_to_point, Corners corner_radii) {+ if (center_to_point.x < 0.) {+ if (center_to_point.y < 0.) {+ return corner_radii.top_left;+ } else {+ return corner_radii.bottom_left;+ }+ } else {+ if (center_to_point.y < 0.) {+ return corner_radii.top_right;+ } else {+ return corner_radii.bottom_right;+ }+ }+}++float4 to_device_position_transformed(float2 unit_vertex, Bounds bounds,+ TransformationMatrix transformation) {+ float2 position = unit_vertex * bounds.size + bounds.origin;+ float2 transformed = mul(position, transformation.rotation_scale) + transformation.translation;+ float2 device_position = transformed / global_viewport_size * float2(2.0, -2.0) + float2(-1.0, 1.0);+ return float4(device_position, 0.0, 1.0);+}++// Implementation of quad signed distance field+float quad_sdf_impl(float2 corner_center_to_point, float corner_radius) {+ if (corner_radius == 0.0) {+ // Fast path for unrounded corners+ return max(corner_center_to_point.x, corner_center_to_point.y);+ } else {+ // Signed distance of the point from a quad that is inset by corner_radius+ // It is negative inside this quad, and positive outside+ float signed_distance_to_inset_quad =+ // 0 inside the inset quad, and positive outside+ length(max(float2(0.0, 0.0), corner_center_to_point)) ++ // 0 outside the inset quad, and negative inside+ min(0.0, max(corner_center_to_point.x, corner_center_to_point.y));++ return signed_distance_to_inset_quad - corner_radius;+ }+}++float quad_sdf(float2 pt, Bounds bounds, Corners corner_radii) {+ float2 half_size = bounds.size / 2.;+ float2 center = bounds.origin + half_size;+ float2 center_to_point = pt - center;+ float corner_radius = pick_corner_radius(center_to_point, corner_radii);+ float2 corner_to_point = abs(center_to_point) - half_size;+ float2 corner_center_to_point = corner_to_point + corner_radius;+ return quad_sdf_impl(corner_center_to_point, corner_radius);+}++GradientColor prepare_gradient_color(uint tag, uint color_space, Hsla solid, LinearColorStop colors[2]) {+ GradientColor output;+ if (tag == 0 || tag == 2 || tag == 3) {+ output.solid = hsla_to_rgba(solid);+ } else if (tag == 1) {+ output.color0 = hsla_to_rgba(colors[0].color);+ output.color1 = hsla_to_rgba(colors[1].color);++ // Prepare color space in vertex for avoid conversion+ // in fragment shader for performance reasons+ if (color_space == 1) {+ // Oklab+ output.color0 = srgb_to_oklab(output.color0);+ output.color1 = srgb_to_oklab(output.color1);+ }+ }++ return output;+}++float2x2 rotate2d(float angle) {+ float s = sin(angle);+ float c = cos(angle);+ return float2x2(c, -s, s, c);+}++float4 gradient_color(Background background,+ float2 position,+ Bounds bounds,+ float4 solid_color, float4 color0, float4 color1) {+ float4 color;++ switch (background.tag) {+ case 0:+ color = solid_color;+ break;+ case 1: {+ // -90 degrees to match the CSS gradient angle.+ float gradient_angle = background.gradient_angle_or_pattern_height;+ float radians = (fmod(gradient_angle, 360.0) - 90.0) * (M_PI_F / 180.0);+ float2 direction = float2(cos(radians), sin(radians));++ // Expand the short side to be the same as the long side+ if (bounds.size.x > bounds.size.y) {+ direction.y *= bounds.size.y / bounds.size.x;+ } else {+ direction.x *= bounds.size.x / bounds.size.y;+ }++ // Get the t value for the linear gradient with the color stop percentages.+ float2 half_size = bounds.size * 0.5;+ float2 center = bounds.origin + half_size;+ float2 center_to_point = position - center;+ float t = dot(center_to_point, direction) / length(direction);+ // Check the direct to determine the use x or y+ if (abs(direction.x) > abs(direction.y)) {+ t = (t + half_size.x) / bounds.size.x;+ } else {+ t = (t + half_size.y) / bounds.size.y;+ }++ // Adjust t based on the stop percentages+ t = (t - background.colors[0].percentage)+ / (background.colors[1].percentage+ - background.colors[0].percentage);+ t = clamp(t, 0.0, 1.0);++ switch (background.color_space) {+ case 0:+ color = lerp(color0, color1, t);+ break;+ case 1: {+ float4 oklab_color = lerp(color0, color1, t);+ color = oklab_to_srgb(oklab_color);+ break;+ }+ }++ // Dither to reduce banding in gradients (especially dark/alpha).+ // Triangular-distributed noise breaks up 8-bit quantization steps.+ // ±2/255 for RGB (enough for dark-on-dark compositing),+ // ±3/255 for alpha (needs more because alpha × dark color = tiny steps).+ {+ float2 seed = position * 0.6180339887; // golden ratio spread+ float r1 = frac(sin(dot(seed, float2(12.9898, 78.233))) * 43758.5453);+ float r2 = frac(sin(dot(seed, float2(39.3460, 11.135))) * 24634.6345);+ float tri = r1 + r2 - 1.0; // triangular PDF, range [-1, +1]+ color.rgb += tri * 2.0 / 255.0;+ color.a += tri * 3.0 / 255.0;+ }++ break;+ }+ case 2: {+ float gradient_angle_or_pattern_height = background.gradient_angle_or_pattern_height;+ float pattern_width = (gradient_angle_or_pattern_height / 65535.0f) / 255.0f;+ float pattern_interval = fmod(gradient_angle_or_pattern_height, 65535.0f) / 255.0f;+ float pattern_height = pattern_width + pattern_interval;+ float stripe_angle = M_PI_F / 4.0;+ float pattern_period = pattern_height * sin(stripe_angle);+ float2x2 rotation = rotate2d(stripe_angle);+ float2 relative_position = position - bounds.origin;+ float2 rotated_point = mul(relative_position, rotation);+ float pattern = fmod(rotated_point.x, pattern_period);+ float distance = min(pattern, pattern_period - pattern) - pattern_period * (pattern_width / pattern_height) / 2.0f;+ color = solid_color;+ color.a *= saturate(0.5 - distance);+ break;+ }+ case 3: {+ // checkerboard+ float size = background.gradient_angle_or_pattern_height;+ float2 relative_position = position - bounds.origin;++ float x_index = floor(relative_position.x / size);+ float y_index = floor(relative_position.y / size);+ float should_be_colored = (x_index + y_index) % 2.0;++ color = solid_color;+ color.a *= saturate(should_be_colored);+ break;+ }+ }++ return color;+}++// Returns the dash velocity of a corner given the dash velocity of the two+// sides, by returning the slower velocity (larger dashes).+//+// Since 0 is used for dash velocity when the border width is 0 (instead of+// +inf), this returns the other dash velocity in that case.+//+// An alternative to this might be to appropriately interpolate the dash+// velocity around the corner, but that seems overcomplicated.+float corner_dash_velocity(float dv1, float dv2) {+ if (dv1 == 0.0) {+ return dv2;+ } else if (dv2 == 0.0) {+ return dv1;+ } else {+ return min(dv1, dv2);+ }+}++// Returns alpha used to render antialiased dashes.+// `t` is within the dash when `fmod(t, period) < length`.+float dash_alpha(+ float t, float period, float length, float dash_velocity,+ float antialias_threshold+) {+ float half_period = period / 2.0;+ float half_length = length / 2.0;+ // Value in [-half_period, half_period]+ // The dash is in [-half_length, half_length]+ float centered = fmod(t + half_period - half_length, period) - half_period;+ // Signed distance for the dash, negative values are inside the dash+ float signed_distance = abs(centered) - half_length;+ // Antialiased alpha based on the signed distance+ return saturate(antialias_threshold - signed_distance / dash_velocity);+}++// This approximates distance to the nearest point to a quarter ellipse in a way+// that is sufficient for anti-aliasing when the ellipse is not very eccentric.+// The components of `point` are expected to be positive.+//+// Negative on the outside and positive on the inside.+float quarter_ellipse_sdf(float2 pt, float2 radii) {+ // Scale the space to treat the ellipse like a unit circle+ float2 circle_vec = pt / radii;+ float unit_circle_sdf = length(circle_vec) - 1.0;+ // Approximate up-scaling of the length by using the average of the radii.+ //+ // TODO: A better solution would be to use the gradient of the implicit+ // function for an ellipse to approximate a scaling factor.+ return unit_circle_sdf * (radii.x + radii.y) * -0.5;+}++/*+**+** Quads+**+*/++struct Quad {+ uint order;+ uint border_style;+ Bounds bounds;+ Bounds content_mask;+ Background background;+ Hsla border_color;+ Corners corner_radii;+ Edges border_widths;+ EdgeFadeParams fade;+};++struct QuadVertexOutput {+ nointerpolation uint quad_id: TEXCOORD0;+ float4 position: SV_Position;+ nointerpolation float4 border_color: COLOR0;+ nointerpolation float4 background_solid: COLOR1;+ nointerpolation float4 background_color0: COLOR2;+ nointerpolation float4 background_color1: COLOR3;+ float4 clip_distance: SV_ClipDistance;+};++struct QuadFragmentInput {+ nointerpolation uint quad_id: TEXCOORD0;+ float4 position: SV_Position;+ nointerpolation float4 border_color: COLOR0;+ nointerpolation float4 background_solid: COLOR1;+ nointerpolation float4 background_color0: COLOR2;+ nointerpolation float4 background_color1: COLOR3;+};++StructuredBuffer<Quad> quads: register(t1);++QuadVertexOutput quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));+ uint quad_id = batch_start_index + instance_id;+ Quad quad = quads[quad_id];+ float4 device_position = to_device_position(unit_vertex, quad.bounds);++ GradientColor gradient = prepare_gradient_color(+ quad.background.tag,+ quad.background.color_space,+ quad.background.solid,+ quad.background.colors+ );+ float4 clip_distance = distance_from_clip_rect(unit_vertex, quad.bounds, quad.content_mask);+ float4 border_color = hsla_to_rgba(quad.border_color);++ QuadVertexOutput output;+ output.position = device_position;+ output.border_color = border_color;+ output.quad_id = quad_id;+ output.background_solid = gradient.solid;+ output.background_color0 = gradient.color0;+ output.background_color1 = gradient.color1;+ output.clip_distance = clip_distance;+ return output;+}++float4 quad_fragment(QuadFragmentInput input): SV_Target {+ Quad quad = quads[input.quad_id];+ float4 background_color = gradient_color(quad.background, input.position.xy, quad.bounds,+ input.background_solid, input.background_color0, input.background_color1);++ float edge_fade = edge_fade_alpha(input.position.xy, quad.fade);+ background_color.a *= edge_fade;++ bool unrounded = quad.corner_radii.top_left == 0.0 &&+ quad.corner_radii.top_right == 0.0 &&+ quad.corner_radii.bottom_left == 0.0 &&+ quad.corner_radii.bottom_right == 0.0;++ // Fast path when the quad is not rounded and doesn't have any border+ if (quad.border_widths.top == 0.0 &&+ quad.border_widths.left == 0.0 &&+ quad.border_widths.right == 0.0 &&+ quad.border_widths.bottom == 0.0 &&+ unrounded) {+ return background_color;+ }++ float2 size = quad.bounds.size;+ float2 half_size = size / 2.;+ float2 the_point = input.position.xy - quad.bounds.origin;+ float2 center_to_point = the_point - half_size;++ // Signed distance field threshold for inclusion of pixels. 0.5 is the+ // minimum distance between the center of the pixel and the edge.+ const float antialias_threshold = 0.5;++ // Radius of the nearest corner+ float corner_radius = pick_corner_radius(center_to_point, quad.corner_radii);++ float2 border = float2(+ center_to_point.x < 0.0 ? quad.border_widths.left : quad.border_widths.right,+ center_to_point.y < 0.0 ? quad.border_widths.top : quad.border_widths.bottom+ );++ // 0-width borders are reduced so that `inner_sdf >= antialias_threshold`.+ // The purpose of this is to not draw antialiasing pixels in this case.+ float2 reduced_border = float2(+ border.x == 0.0 ? -antialias_threshold : border.x,+ border.y == 0.0 ? -antialias_threshold : border.y+ );++ // Vector from the corner of the quad bounds to the point, after mirroring+ // the point into the bottom right quadrant. Both components are <= 0.+ float2 corner_to_point = abs(center_to_point) - half_size;++ // Vector from the point to the center of the rounded corner's circle, also+ // mirrored into bottom right quadrant.+ float2 corner_center_to_point = corner_to_point + corner_radius;++ // Whether the nearest point on the border is rounded+ bool is_near_rounded_corner =+ corner_center_to_point.x >= 0.0 &&+ corner_center_to_point.y >= 0.0;++ // Vector from straight border inner corner to point.+ //+ // 0-width borders are turned into width -1 so that inner_sdf is > 1.0 near+ // the border. Without this, antialiasing pixels would be drawn.+ float2 straight_border_inner_corner_to_point = corner_to_point + reduced_border;++ // Whether the point is beyond the inner edge of the straight border+ bool is_beyond_inner_straight_border =+ straight_border_inner_corner_to_point.x > 0.0 ||+ straight_border_inner_corner_to_point.y > 0.0;++ // Whether the point is far enough inside the quad, such that the pixels are+ // not affected by the straight border.+ bool is_within_inner_straight_border =+ straight_border_inner_corner_to_point.x < -antialias_threshold &&+ straight_border_inner_corner_to_point.y < -antialias_threshold;++ // Fast path for points that must be part of the background+ if (is_within_inner_straight_border && !is_near_rounded_corner) {+ return background_color;+ }++ // Signed distance of the point to the outside edge of the quad's border+ float outer_sdf = quad_sdf_impl(corner_center_to_point, corner_radius);++ // Approximate signed distance of the point to the inside edge of the quad's+ // border. It is negative outside this edge (within the border), and+ // positive inside.+ //+ // This is not always an accurate signed distance:+ // * The rounded portions with varying border width use an approximation of+ // nearest-point-on-ellipse.+ // * When it is quickly known to be outside the edge, -1.0 is used.+ float inner_sdf = 0.0;+ if (corner_center_to_point.x <= 0.0 || corner_center_to_point.y <= 0.0) {+ // Fast paths for straight borders+ inner_sdf = -max(straight_border_inner_corner_to_point.x,+ straight_border_inner_corner_to_point.y);+ } else if (is_beyond_inner_straight_border) {+ // Fast path for points that must be outside the inner edge+ inner_sdf = -1.0;+ } else if (reduced_border.x == reduced_border.y) {+ // Fast path for circular inner edge.+ inner_sdf = -(outer_sdf + reduced_border.x);+ } else {+ float2 ellipse_radii = max(float2(0.0, 0.0), float2(corner_radius, corner_radius) - reduced_border);+ inner_sdf = quarter_ellipse_sdf(corner_center_to_point, ellipse_radii);+ }++ // Negative when inside the border+ float border_sdf = max(inner_sdf, outer_sdf);++ float4 color = background_color;+ if (border_sdf < antialias_threshold) {+ float4 border_color = input.border_color;+ border_color.a *= edge_fade;+ // Dashed border logic when border_style == 1+ if (quad.border_style == 1) {+ // Position along the perimeter in "dash space", where each dash+ // period has length 1+ float t = 0.0;++ // Total number of dash periods, so that the dash spacing can be+ // adjusted to evenly divide it+ float max_t = 0.0;++ // Border width is proportional to dash size. This is the behavior+ // used by browsers, but also avoids dashes from different segments+ // overlapping when dash size is smaller than the border width.+ //+ // Dash pattern: (2 * border width) dash, (1 * border width) gap+ const float dash_length_per_width = 2.0;+ const float dash_gap_per_width = 1.0;+ const float dash_period_per_width = dash_length_per_width + dash_gap_per_width;++ // Since the dash size is determined by border width, the density of+ // dashes varies. Multiplying a pixel distance by this returns a+ // position in dash space - it has units (dash period / pixels). So+ // a dash velocity of (1 / 10) is 1 dash every 10 pixels.+ float dash_velocity = 0.0;++ // Dividing this by the border width gives the dash velocity+ const float dv_numerator = 1.0 / dash_period_per_width;++ if (unrounded) {+ // When corners aren't rounded, the dashes are separately laid+ // out on each straight line, rather than around the whole+ // perimeter. This way each line starts and ends with a dash.+ bool is_horizontal = corner_center_to_point.x < corner_center_to_point.y;+ // Choosing the right border width for dashed borders.+ // TODO: A better solution exists taking a look at the whole file.+ // this does not fix single dashed borders at the corners+ float2 dashed_border = float2(+ max(quad.border_widths.bottom, quad.border_widths.top),+ max(quad.border_widths.right, quad.border_widths.left)+ );+ float border_width = is_horizontal ? dashed_border.x : dashed_border.y;+ dash_velocity = dv_numerator / border_width;+ t = is_horizontal ? the_point.x : the_point.y;+ t *= dash_velocity;+ max_t = is_horizontal ? size.x : size.y;+ max_t *= dash_velocity;+ } else {+ // When corners are rounded, the dashes are laid out clockwise+ // around the whole perimeter.++ float r_tr = quad.corner_radii.top_right;+ float r_br = quad.corner_radii.bottom_right;+ float r_bl = quad.corner_radii.bottom_left;+ float r_tl = quad.corner_radii.top_left;++ float w_t = quad.border_widths.top;+ float w_r = quad.border_widths.right;+ float w_b = quad.border_widths.bottom;+ float w_l = quad.border_widths.left;++ // Straight side dash velocities+ float dv_t = w_t <= 0.0 ? 0.0 : dv_numerator / w_t;+ float dv_r = w_r <= 0.0 ? 0.0 : dv_numerator / w_r;+ float dv_b = w_b <= 0.0 ? 0.0 : dv_numerator / w_b;+ float dv_l = w_l <= 0.0 ? 0.0 : dv_numerator / w_l;++ // Straight side lengths in dash space+ float s_t = (size.x - r_tl - r_tr) * dv_t;+ float s_r = (size.y - r_tr - r_br) * dv_r;+ float s_b = (size.x - r_br - r_bl) * dv_b;+ float s_l = (size.y - r_bl - r_tl) * dv_l;++ float corner_dash_velocity_tr = corner_dash_velocity(dv_t, dv_r);+ float corner_dash_velocity_br = corner_dash_velocity(dv_b, dv_r);+ float corner_dash_velocity_bl = corner_dash_velocity(dv_b, dv_l);+ float corner_dash_velocity_tl = corner_dash_velocity(dv_t, dv_l);++ // Corner lengths in dash space+ float c_tr = r_tr * (M_PI_F / 2.0) * corner_dash_velocity_tr;+ float c_br = r_br * (M_PI_F / 2.0) * corner_dash_velocity_br;+ float c_bl = r_bl * (M_PI_F / 2.0) * corner_dash_velocity_bl;+ float c_tl = r_tl * (M_PI_F / 2.0) * corner_dash_velocity_tl;++ // Cumulative dash space upto each segment+ float upto_tr = s_t;+ float upto_r = upto_tr + c_tr;+ float upto_br = upto_r + s_r;+ float upto_b = upto_br + c_br;+ float upto_bl = upto_b + s_b;+ float upto_l = upto_bl + c_bl;+ float upto_tl = upto_l + s_l;+ max_t = upto_tl + c_tl;++ if (is_near_rounded_corner) {+ float radians = atan2(corner_center_to_point.y, corner_center_to_point.x);+ float corner_t = radians * corner_radius;++ if (center_to_point.x >= 0.0) {+ if (center_to_point.y < 0.0) {+ dash_velocity = corner_dash_velocity_tr;+ // Subtracted because radians is pi/2 to 0 when+ // going clockwise around the top right corner,+ // since the y axis has been flipped+ t = upto_r - corner_t * dash_velocity;+ } else {+ dash_velocity = corner_dash_velocity_br;+ // Added because radians is 0 to pi/2 when going+ // clockwise around the bottom-right corner+ t = upto_br + corner_t * dash_velocity;+ }+ } else {+ if (center_to_point.y >= 0.0) {+ dash_velocity = corner_dash_velocity_bl;+ // Subtracted because radians is pi/1 to 0 when+ // going clockwise around the bottom-left corner,+ // since the x axis has been flipped+ t = upto_l - corner_t * dash_velocity;+ } else {+ dash_velocity = corner_dash_velocity_tl;+ // Added because radians is 0 to pi/2 when going+ // clockwise around the top-left corner, since both+ // axis were flipped+ t = upto_tl + corner_t * dash_velocity;+ }+ }+ } else {+ // Straight borders+ bool is_horizontal = corner_center_to_point.x < corner_center_to_point.y;+ if (is_horizontal) {+ if (center_to_point.y < 0.0) {+ dash_velocity = dv_t;+ t = (the_point.x - r_tl) * dash_velocity;+ } else {+ dash_velocity = dv_b;+ t = upto_bl - (the_point.x - r_bl) * dash_velocity;+ }+ } else {+ if (center_to_point.x < 0.0) {+ dash_velocity = dv_l;+ t = upto_tl - (the_point.y - r_tl) * dash_velocity;+ } else {+ dash_velocity = dv_r;+ t = upto_r + (the_point.y - r_tr) * dash_velocity;+ }+ }+ }+ }+ float dash_length = dash_length_per_width / dash_period_per_width;+ float desired_dash_gap = dash_gap_per_width / dash_period_per_width;++ // Straight borders should start and end with a dash, so max_t is+ // reduced to cause this.+ max_t -= unrounded ? dash_length : 0.0;+ if (max_t >= 1.0) {+ // Adjust dash gap to evenly divide max_t+ float dash_count = floor(max_t);+ float dash_period = max_t / dash_count;+ border_color.a *= dash_alpha(t, dash_period, dash_length, dash_velocity, antialias_threshold);+ } else if (unrounded) {+ // When there isn't enough space for the full gap between the+ // two start / end dashes of a straight border, reduce gap to+ // make them fit.+ float dash_gap = max_t - dash_length;+ if (dash_gap > 0.0) {+ float dash_period = dash_length + dash_gap;+ border_color.a *= dash_alpha(t, dash_period, dash_length, dash_velocity, antialias_threshold);+ }+ }+ }++ // Blend the border on top of the background and then linearly interpolate+ // between the two as we slide inside the background.+ float4 blended_border = over(background_color, border_color);+ color = lerp(background_color, blended_border,+ saturate(antialias_threshold - inner_sdf));+ }++ return color * float4(1.0, 1.0, 1.0, saturate(antialias_threshold - outer_sdf));+}++/*+**+** Shadows+**+*/++struct Shadow {+ uint order;+ float blur_radius;+ Bounds bounds;+ Corners corner_radii;+ Bounds content_mask;+ Hsla color;+ Bounds element_bounds;+ Corners element_corner_radii;+ uint inset;+ uint pad; // align to 8 bytes+};++struct ShadowVertexOutput {+ nointerpolation uint shadow_id: TEXCOORD0;+ float4 position: SV_Position;+ nointerpolation float4 color: COLOR;+ float4 clip_distance: SV_ClipDistance;+};++struct ShadowFragmentInput {+ nointerpolation uint shadow_id: TEXCOORD0;+ float4 position: SV_Position;+ nointerpolation float4 color: COLOR;+};++StructuredBuffer<Shadow> shadows: register(t1);++ShadowVertexOutput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));+ uint shadow_id = batch_start_index + instance_id;+ Shadow shadow = shadows[shadow_id];++ Bounds bounds;+ if (shadow.inset != 0u) {+ bounds = shadow.element_bounds;+ } else {+ // Leave room for the gaussian tail outside the shadow rect.+ float margin = 3.0 * shadow.blur_radius;+ bounds = shadow.bounds;+ bounds.origin -= margin;+ bounds.size += 2.0 * margin;+ }++ float4 device_position = to_device_position(unit_vertex, bounds);+ float4 clip_distance = distance_from_clip_rect(unit_vertex, bounds, shadow.content_mask);+ float4 color = hsla_to_rgba(shadow.color);++ ShadowVertexOutput output;+ output.position = device_position;+ output.color = color;+ output.shadow_id = shadow_id;+ output.clip_distance = clip_distance;++ return output;+}++float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET {+ Shadow shadow = shadows[input.shadow_id];++ float2 half_size = shadow.bounds.size / 2.;+ float2 center = shadow.bounds.origin + half_size;+ float2 point0 = input.position.xy - center;+ float corner_radius = pick_corner_radius(point0, shadow.corner_radii);++ float alpha;+ if (shadow.blur_radius == 0.) {+ float distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii);+ alpha = saturate(0.5 - distance);+ } else {+ // The signal is only non-zero in a limited range, so don't waste samples+ float low = point0.y - half_size.y;+ float high = point0.y + half_size.y;+ float start = clamp(-3. * shadow.blur_radius, low, high);+ float end = clamp(3. * shadow.blur_radius, low, high);++ // Accumulate samples (we can get away with surprisingly few samples)+ float step = (end - start) / 4.;+ float y = start + step * 0.5;+ alpha = 0.;+ for (int i = 0; i < 4; i++) {+ alpha += blur_along_x(point0.x, point0.y - y, shadow.blur_radius,+ corner_radius, half_size) *+ gaussian(y, shadow.blur_radius) * step;+ y += step;+ }+ }++ if (shadow.inset != 0u) {+ // The inset shadow is the complement of the (blurred) hole rect, clipped to the element.+ // `saturate(0.5 - d)` gives a 1-pixel antialiased edge: d <= -0.5 -> 1, d >= 0.5 -> 0.+ alpha = 1.0 - alpha;+ float element_distance = quad_sdf(input.position.xy, shadow.element_bounds,+ shadow.element_corner_radii);+ alpha *= saturate(0.5 - element_distance);+ }++ return input.color * float4(1., 1., 1., alpha);+}++/*+**+** Path Rasterization+**+*/++struct PathRasterizationSprite {+ float2 xy_position;+ float2 st_position;+ Background color;+ Bounds bounds;+};++StructuredBuffer<PathRasterizationSprite> path_rasterization_sprites: register(t1);++struct PathVertexOutput {+ float4 position: SV_Position;+ float2 st_position: TEXCOORD0;+ nointerpolation uint vertex_id: TEXCOORD1;+ float4 clip_distance: SV_ClipDistance;+};++struct PathFragmentInput {+ float4 position: SV_Position;+ float2 st_position: TEXCOORD0;+ nointerpolation uint vertex_id: TEXCOORD1;+};++PathVertexOutput path_rasterization_vertex(uint vertex_id: SV_VertexID) {+ PathRasterizationSprite sprite = path_rasterization_sprites[vertex_id];++ PathVertexOutput output;+ output.position = to_device_position_impl(sprite.xy_position);+ output.st_position = sprite.st_position;+ output.vertex_id = vertex_id;+ output.clip_distance = distance_from_clip_rect_impl(sprite.xy_position, sprite.bounds);++ return output;+}++float4 path_rasterization_fragment(PathFragmentInput input): SV_Target {+ float2 dx = ddx(input.st_position);+ float2 dy = ddy(input.st_position);+ PathRasterizationSprite sprite = path_rasterization_sprites[input.vertex_id];++ Background background = sprite.color;+ Bounds bounds = sprite.bounds;++ float alpha;+ if (length(float2(dx.x, dy.x))) {+ alpha = 1.0;+ } else {+ float2 gradient = 2.0 * input.st_position.xx * float2(dx.x, dy.x) - float2(dx.y, dy.y);+ float f = input.st_position.x * input.st_position.x - input.st_position.y;+ float distance = f / length(gradient);+ alpha = saturate(0.5 - distance);+ }++ GradientColor gradient = prepare_gradient_color(+ background.tag, background.color_space, background.solid, background.colors);++ float4 color = gradient_color(background, input.position.xy, bounds,+ gradient.solid, gradient.color0, gradient.color1);+ return float4(color.rgb * color.a * alpha, alpha * color.a);+}++/*+**+** Path Sprites+**+*/++struct PathSprite {+ Bounds bounds;+};++struct PathSpriteVertexOutput {+ float4 position: SV_Position;+ float2 texture_coords: TEXCOORD0;+};++StructuredBuffer<PathSprite> path_sprites: register(t1);++PathSpriteVertexOutput path_sprite_vertex(uint vertex_id: SV_VertexID, uint sprite_id: SV_InstanceID) {+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));+ PathSprite sprite = path_sprites[sprite_id];++ // Don't apply content mask because it was already accounted for when rasterizing the path+ float4 device_position = to_device_position(unit_vertex, sprite.bounds);++ float2 screen_position = sprite.bounds.origin + unit_vertex * sprite.bounds.size;+ float2 texture_coords = screen_position / global_viewport_size;++ PathSpriteVertexOutput output;+ output.position = device_position;+ output.texture_coords = texture_coords;+ return output;+}++float4 path_sprite_fragment(PathSpriteVertexOutput input): SV_Target {+ return t_sprite.Sample(s_sprite, input.texture_coords);+}++/*+**+** Underlines+**+*/++struct Underline {+ uint order;+ uint pad;+ Bounds bounds;+ Bounds content_mask;+ Hsla color;+ float thickness;+ uint wavy;+};++struct UnderlineVertexOutput {+ nointerpolation uint underline_id: TEXCOORD0;+ float4 position: SV_Position;+ nointerpolation float4 color: COLOR;+ float4 clip_distance: SV_ClipDistance;+};++struct UnderlineFragmentInput {+ nointerpolation uint underline_id: TEXCOORD0;+ float4 position: SV_Position;+ nointerpolation float4 color: COLOR;+};++StructuredBuffer<Underline> underlines: register(t1);++UnderlineVertexOutput underline_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));+ uint underline_id = batch_start_index + instance_id;+ Underline underline = underlines[underline_id];+ float4 device_position = to_device_position(unit_vertex, underline.bounds);+ float4 clip_distance = distance_from_clip_rect(unit_vertex, underline.bounds,+ underline.content_mask);+ float4 color = hsla_to_rgba(underline.color);++ UnderlineVertexOutput output;+ output.position = device_position;+ output.color = color;+ output.underline_id = underline_id;+ output.clip_distance = clip_distance;+ return output;+}++float4 underline_fragment(UnderlineFragmentInput input): SV_Target {+ const float WAVE_FREQUENCY = 2.0;+ const float WAVE_HEIGHT_RATIO = 0.8;++ Underline underline = underlines[input.underline_id];+ if (underline.wavy) {+ float half_thickness = underline.thickness * 0.5;+ float2 origin = underline.bounds.origin;++ float2 st = ((input.position.xy - origin) / underline.bounds.size.y) - float2(0., 0.5);+ float frequency = (M_PI_F * WAVE_FREQUENCY * underline.thickness) / underline.bounds.size.y;+ float amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.y;++ float sine = sin(st.x * frequency) * amplitude;+ float dSine = cos(st.x * frequency) * amplitude * frequency;+ float distance = (st.y - sine) / sqrt(1. + dSine * dSine);+ float distance_in_pixels = distance * underline.bounds.size.y;+ float distance_from_top_border = distance_in_pixels - half_thickness;+ float distance_from_bottom_border = distance_in_pixels + half_thickness;+ float alpha = saturate(+ 0.5 - max(-distance_from_bottom_border, distance_from_top_border));+ return input.color * float4(1., 1., 1., alpha);+ } else {+ return input.color;+ }+}++/*+**+** Monochrome sprites+**+*/++struct MonochromeSprite {+ uint order;+ uint pad;+ Bounds bounds;+ Bounds content_mask;+ Hsla color;+ AtlasTile tile;+ TransformationMatrix transformation;+ EdgeFadeParams fade;+};++struct MonochromeSpriteVertexOutput {+ float4 position: SV_Position;+ float2 tile_position: POSITION;+ nointerpolation float4 color: COLOR;+ nointerpolation uint sprite_id: TEXCOORD1;+ float4 clip_distance: SV_ClipDistance;+};++struct MonochromeSpriteFragmentInput {+ float4 position: SV_Position;+ float2 tile_position: POSITION;+ nointerpolation float4 color: COLOR;+ nointerpolation uint sprite_id: TEXCOORD1;+ float4 clip_distance: SV_ClipDistance;+};++StructuredBuffer<MonochromeSprite> mono_sprites: register(t1);++MonochromeSpriteVertexOutput monochrome_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));+ uint sprite_id = batch_start_index + instance_id;+ MonochromeSprite sprite = mono_sprites[sprite_id];+ float4 device_position =+ to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation);+ float4 clip_distance = distance_from_clip_rect_transformed(unit_vertex, sprite.bounds, sprite.content_mask, sprite.transformation);+ float2 tile_position = to_tile_position(unit_vertex, sprite.tile);+ float4 color = hsla_to_rgba(sprite.color);++ MonochromeSpriteVertexOutput output;+ output.position = device_position;+ output.tile_position = tile_position;+ output.color = color;+ output.sprite_id = sprite_id;+ output.clip_distance = clip_distance;+ return output;+}++float4 monochrome_sprite_fragment(MonochromeSpriteFragmentInput input): SV_Target {+ float sample = t_sprite.Sample(s_sprite, input.tile_position).r;+ float alpha_corrected = apply_contrast_and_gamma_correction(sample, input.color.rgb, grayscale_enhanced_contrast, gamma_ratios);+ return float4(input.color.rgb, input.color.a * alpha_corrected * edge_fade_alpha(input.position.xy, mono_sprites[input.sprite_id].fade));+}++MonochromeSpriteVertexOutput subpixel_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {+ return monochrome_sprite_vertex(vertex_id, instance_id);+}++SubpixelSpriteFragmentOutput subpixel_sprite_fragment(MonochromeSpriteFragmentInput input) {+ float3 sample = t_sprite.Sample(s_sprite, input.tile_position).rgb;+ if (is_bgr) {+ sample = sample.bgr;+ }+ float3 alpha_corrected = apply_contrast_and_gamma_correction3(sample, input.color.rgb, subpixel_enhanced_contrast, gamma_ratios);++ SubpixelSpriteFragmentOutput output;+ output.foreground = float4(input.color.rgb, 1.0f);+ output.alpha = float4(input.color.a * alpha_corrected * edge_fade_alpha(input.position.xy, mono_sprites[input.sprite_id].fade), 1.0f);+ return output;+}++/*+**+** Polychrome sprites+**+*/++struct ImageAlphaMaskParams {+ Bounds bounds;+ float radius;+ float feather;+ float clearance;+ float bottom_y;+ float bottom_feather;+ float pad;+};++float image_mask_alpha(float2 position, ImageAlphaMaskParams mask) {+ if (mask.feather <= 0.0) return 1.0;+ float2 half_size = mask.bounds.size * 0.5;+ float2 center = mask.bounds.origin + half_size;+ float2 q = abs(position - center) - half_size + mask.radius;+ float distance = length(max(q, float2(0.0, 0.0))) + min(max(q.x, q.y), 0.0) - mask.radius;+ float alpha = smoothstep(0.0, mask.feather, distance - mask.clearance);+ if (mask.bottom_feather > 0.0)+ alpha = min(alpha, smoothstep(0.0, mask.bottom_feather, mask.bottom_y - position.y));+ return alpha;+}++struct PolychromeSprite {+ uint order;+ uint pad;+ uint grayscale;+ float opacity;+ Bounds bounds;+ Bounds content_mask;+ Corners corner_radii;+ EdgeFadeParams fade;+ ImageAlphaMaskParams alpha_mask;+ AtlasTile tile;+};++struct PolychromeSpriteVertexOutput {+ nointerpolation uint sprite_id: TEXCOORD0;+ float4 position: SV_Position;+ float2 tile_position: POSITION;+ float4 clip_distance: SV_ClipDistance;+};++struct PolychromeSpriteFragmentInput {+ nointerpolation uint sprite_id: TEXCOORD0;+ float4 position: SV_Position;+ float2 tile_position: POSITION;+};++StructuredBuffer<PolychromeSprite> poly_sprites: register(t1);++PolychromeSpriteVertexOutput polychrome_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) {+ float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));+ uint sprite_id = batch_start_index + instance_id;+ PolychromeSprite sprite = poly_sprites[sprite_id];+ float4 device_position = to_device_position(unit_vertex, sprite.bounds);+ float4 clip_distance = distance_from_clip_rect(unit_vertex, sprite.bounds,+ sprite.content_mask);+ float2 tile_position = to_tile_position(unit_vertex, sprite.tile);++ PolychromeSpriteVertexOutput output;+ output.position = device_position;+ output.tile_position = tile_position;+ output.sprite_id = sprite_id;+ output.clip_distance = clip_distance;+ return output;+}++float4 polychrome_sprite_fragment(PolychromeSpriteFragmentInput input): SV_Target {+ PolychromeSprite sprite = poly_sprites[input.sprite_id];+ float4 sample = t_sprite.Sample(s_sprite, input.tile_position);+ float distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii);++ float4 color = sample;+ if (sprite.grayscale != 0u) {+ float3 grayscale = dot(color.rgb, GRAYSCALE_FACTORS);+ color = float4(grayscale, sample.a);+ }+ color.a *= sprite.opacity * saturate(0.5 - distance)+ * edge_fade_alpha(input.position.xy, sprite.fade)+ * image_mask_alpha(input.position.xy, sprite.alpha_mask);+ return color;+}++// Layout must match `Params` in directx_renderer/backdrop.rs.+cbuffer BackdropParams: register(b2) {+ Bounds backdrop_bounds;+ Corners backdrop_corners;+ Bounds backdrop_clip;+ float4 backdrop_source;+ float4 backdrop_kernel;+ float4 backdrop_weights[33];+};++struct BackdropVertex {+ float4 position: SV_Position;+ float2 uv: TEXCOORD0;+};++BackdropVertex backdrop_pass_vertex(uint vertex_id: SV_VertexID) {+ float2 uv = float2(vertex_id & 1u, (vertex_id >> 1u) & 1u);+ BackdropVertex output;+ output.position = float4(uv * float2(2., -2.) + float2(-1., 1.), 0., 1.);+ output.uv = uv;+ return output;+}++float4 backdrop_pass_fragment(BackdropVertex input): SV_Target {+ // Keep in sync with MAX_SIGMA in directx_renderer/backdrop.rs.+ float sigma = clamp(backdrop_kernel.z, 1., 64.);+ int radius = min(int(ceil(3. * sigma)), 192);+ float2 step_uv = backdrop_kernel.xy;+ float4 sum = 0.;+ if (radius <= 128) {+ if (backdrop_kernel.w == 1.) {+ // Each bilinear sample covers two adjacent taps.+ sum = t_sprite.SampleLevel(s_sprite, input.uv, 0.) * backdrop_weights[0].x;+ [loop] for (int k = 1; k <= radius; k += 2) {+ uint index = uint(k);+ float a = backdrop_weights[index >> 2u][index & 3u];+ float b = backdrop_weights[(index + 1u) >> 2u][(index + 1u) & 3u];+ float weight = a + b;+ float2 offset = (float(k) + b / weight) * step_uv;+ sum += t_sprite.SampleLevel(s_sprite, input.uv + offset, 0.) * weight;+ sum += t_sprite.SampleLevel(s_sprite, input.uv - offset, 0.) * weight;+ }+ } else {+ [loop] for (int k = -radius; k <= radius; ++k) {+ uint index = uint(abs(k));+ float weight = backdrop_weights[index >> 2u][index & 3u];+ sum += t_sprite.SampleLevel(s_sprite, input.uv + float(k) * step_uv, 0.) * weight;+ }+ }+ return sum;+ }+ // Radii above 128 do not fit in backdrop_weights.+ float total_weight = 0.;+ [loop] for (int k = -radius; k <= radius; ++k) {+ float weight = exp(-float(k) * float(k) / (2. * sigma * sigma));+ sum += t_sprite.SampleLevel(s_sprite, input.uv + float(k) * step_uv, 0.) * weight;+ total_weight += weight;+ }+ return sum / total_weight;+}++BackdropVertex backdrop_composite_vertex(uint vertex_id: SV_VertexID) {+ float2 uv = float2(vertex_id & 1u, (vertex_id >> 1u) & 1u);+ BackdropVertex output;+ float2 position = backdrop_bounds.origin + uv * backdrop_bounds.size;+ output.position = float4(position / global_viewport_size * float2(2., -2.) + float2(-1., 1.), 0., 1.);+ output.uv = uv;+ return output;+}++float4 backdrop_composite_fragment(BackdropVertex input): SV_Target {+ float2 position = input.position.xy;+ // Blending is off, so returning transparent black would erase the frame.+ if (any(position < backdrop_clip.origin) || any(position >= backdrop_clip.origin + backdrop_clip.size)+ || quad_sdf(position, backdrop_bounds, backdrop_corners) > 0.) {+ discard;+ }+ float2 uv = (position - backdrop_source.xy) / backdrop_source.zw;+ return t_sprite.SampleLevel(s_sprite, uv, 0.);+}diff --git a/native/vendor/wu/crates/gpui_windows/src/system_notifications.rs b/native/vendor/wu/crates/gpui_windows/src/system_notifications.rsnew file mode 100644index 00000000000..b0075f0e39d--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/system_notifications.rs@@ -0,0 +1,198 @@+//! System notifications as Windows toast notifications.++use std::cell::RefCell;+use std::collections::{HashMap, hash_map::DefaultHasher};+use std::hash::{Hash as _, Hasher as _};+use std::rc::Rc;++use futures::StreamExt as _;+use futures::channel::mpsc;+use gpui::{+ ForegroundExecutor, SharedString, SystemNotification, SystemNotificationResponse, Task,+};+use windows::Data::Xml::Dom::XmlDocument;+use windows::Foundation::TypedEventHandler;+use windows::UI::Notifications::{+ ToastActivatedEventArgs, ToastNotification, ToastNotificationManager, ToastNotifier,+};+use windows::core::{IInspectable, Interface as _, h};++type ResponseCallback = Rc<RefCell<Option<Box<dyn FnMut(SystemNotificationResponse)>>>>;++pub(crate) struct SystemNotificationState {+ notifier: Option<ToastNotifier>,+ active_toasts: HashMap<SharedString, ToastNotification>,+ response_sender: mpsc::UnboundedSender<SystemNotificationResponse>,+ response_receiver: Option<mpsc::UnboundedReceiver<SystemNotificationResponse>>,+ callback: ResponseCallback,+ _response_task: Option<Task<()>>,+}++impl SystemNotificationState {+ pub(crate) fn new() -> Self {+ let (response_sender, response_receiver) = mpsc::unbounded();+ Self {+ notifier: None,+ active_toasts: HashMap::new(),+ response_sender,+ response_receiver: Some(response_receiver),+ callback: Rc::new(RefCell::new(None)),+ _response_task: None,+ }+ }++ pub(crate) fn show(+ &mut self,+ has_package_identity: bool,+ app_identity: Option<(&str, &str)>,+ notification: SystemNotification,+ ) -> windows::core::Result<()> {+ let Some(notifier) = self.notifier(has_package_identity, app_identity)? else {+ return Ok(());+ };++ let document = toast_document(¬ification)?;+ let toast = ToastNotification::CreateToastNotification(&document)?;+ // Windows caps toast tags at 64 characters (post-Creators Update),+ // so hash the arbitrary GPUI tag down to a fixed-width value.+ let tag = {+ let mut hasher = DefaultHasher::new();+ notification.tag.hash(&mut hasher);+ format!("{:016x}", hasher.finish())+ };+ toast.SetTag(&tag.into())?;++ let sender = self.response_sender.clone();+ let response_tag = notification.tag.clone();+ toast.Activated(&TypedEventHandler::<ToastNotification, IInspectable>::new(+ move |_sender, arguments| {+ let action_id = arguments+ .as_ref()+ .and_then(|arguments| arguments.cast::<ToastActivatedEventArgs>().ok())+ .and_then(|arguments| arguments.Arguments().ok())+ .filter(|arguments| !arguments.is_empty())+ .map(|arguments| SharedString::from(arguments.to_string()));+ sender+ .unbounded_send(SystemNotificationResponse {+ tag: response_tag.clone(),+ action_id,+ })+ .ok();+ Ok(())+ },+ ))?;++ if let Some(previous) = self.active_toasts.remove(¬ification.tag) {+ notifier.Hide(&previous)?;+ }+ notifier.Show(&toast)?;+ self.active_toasts.insert(notification.tag, toast);+ Ok(())+ }++ pub(crate) fn dismiss(&mut self, tag: &str) {+ let Some(toast) = self.active_toasts.remove(tag) else {+ return;+ };+ let Some(notifier) = &self.notifier else {+ return;+ };+ if let Err(error) = notifier.Hide(&toast) {+ log::warn!("failed to dismiss system notification: {error}");+ }+ }++ pub(crate) fn on_response(+ &mut self,+ executor: &ForegroundExecutor,+ callback: Box<dyn FnMut(SystemNotificationResponse)>,+ ) {+ *self.callback.borrow_mut() = Some(callback);++ if let Some(mut receiver) = self.response_receiver.take() {+ let callback = self.callback.clone();+ self._response_task = Some(executor.spawn(async move {+ while let Some(response) = receiver.next().await {+ // Take the callback out for the call: it may re-enter the+ // platform (e.g. to dismiss the notification it was told+ // about) or replace itself.+ let taken = callback.borrow_mut().take();+ if let Some(mut taken) = taken {+ taken(response);+ callback.borrow_mut().get_or_insert(taken);+ }+ }+ }));+ }+ }++ fn notifier(+ &mut self,+ has_package_identity: bool,+ app_identity: Option<(&str, &str)>,+ ) -> windows::core::Result<Option<ToastNotifier>> {+ if let Some(notifier) = &self.notifier {+ return Ok(Some(notifier.clone()));+ }++ let notifier = if has_package_identity {+ ToastNotificationManager::CreateToastNotifier()?+ } else {+ let Some((app_identifier, app_name)) = app_identity else {+ log::warn!(+ "cannot show a system notification without an app identity; \+ call `App::set_app_identity` during startup"+ );+ return Ok(None);+ };+ register_app_user_model_id(app_identifier, app_name);+ ToastNotificationManager::CreateToastNotifierWithId(&app_identifier.into())?+ };++ self.notifier = Some(notifier.clone());+ Ok(Some(notifier))+ }+}++fn toast_document(notification: &SystemNotification) -> windows::core::Result<XmlDocument> {+ let document = XmlDocument::new()?;+ let toast = document.CreateElement(h!("toast"))?;+ document.AppendChild(&toast)?;++ let visual = document.CreateElement(h!("visual"))?;+ toast.AppendChild(&visual)?;+ let binding = document.CreateElement(h!("binding"))?;+ binding.SetAttribute(h!("template"), h!("ToastGeneric"))?;+ visual.AppendChild(&binding)?;+ for text in [¬ification.title, ¬ification.body] {+ let element = document.CreateElement(h!("text"))?;+ element.SetInnerText(&text.as_ref().into())?;+ binding.AppendChild(&element)?;+ }++ if !notification.actions.is_empty() {+ let actions = document.CreateElement(h!("actions"))?;+ toast.AppendChild(&actions)?;+ for action in ¬ification.actions {+ let action_element = document.CreateElement(h!("action"))?;+ action_element.SetAttribute(h!("content"), &action.label.as_ref().into())?;+ action_element.SetAttribute(h!("arguments"), &action.id.as_ref().into())?;+ actions.AppendChild(&action_element)?;+ }+ }++ let audio = document.CreateElement(h!("audio"))?;+ audio.SetAttribute(h!("silent"), h!("true"))?;+ toast.AppendChild(&audio)?;+ Ok(document)+}++/// Registers the app's AUMID so toasts display correctly for an unpackaged app without a Start Menu shortcut.+fn register_app_user_model_id(app_identifier: &str, app_name: &str) {+ let result = windows_registry::CURRENT_USER+ .create(format!(r"Software\Classes\AppUserModelId\{app_identifier}"))+ .and_then(|key| key.set_string("DisplayName", app_name));+ if let Err(error) = result {+ log::warn!("failed to register AppUserModelID; notifications may not display: {error}");+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/system_settings.rs b/native/vendor/wu/crates/gpui_windows/src/system_settings.rsnew file mode 100644index 00000000000..8cce544be1b--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/system_settings.rs@@ -0,0 +1,87 @@+use std::{+ cell::Cell,+ ffi::{c_uint, c_void},+};++use gpui_util::ResultExt;+use windows::Win32::UI::WindowsAndMessaging::{+ SPI_GETWHEELSCROLLCHARS, SPI_GETWHEELSCROLLLINES, SYSTEM_PARAMETERS_INFO_ACTION,+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS, SystemParametersInfoW,+};++/// Windows settings pulled from SystemParametersInfo+/// https://learn.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-systemparametersinfow+#[derive(Default, Debug, Clone)]+pub(crate) struct WindowsSystemSettings {+ pub(crate) mouse_wheel_settings: MouseWheelSettings,+}++#[derive(Default, Debug, Clone)]+pub(crate) struct MouseWheelSettings {+ /// SEE: SPI_GETWHEELSCROLLCHARS+ pub(crate) wheel_scroll_chars: Cell<u32>,+ /// SEE: SPI_GETWHEELSCROLLLINES+ pub(crate) wheel_scroll_lines: Cell<u32>,+}++impl WindowsSystemSettings {+ pub(crate) fn new() -> Self {+ let mut settings = Self::default();+ settings.init();+ settings+ }++ fn init(&mut self) {+ self.mouse_wheel_settings.update();+ }++ pub(crate) fn update(&self, wparam: usize) {+ match SYSTEM_PARAMETERS_INFO_ACTION(wparam as u32) {+ SPI_GETWHEELSCROLLLINES | SPI_GETWHEELSCROLLCHARS => self.update_mouse_wheel_settings(),+ _ => {}+ }+ }++ fn update_mouse_wheel_settings(&self) {+ self.mouse_wheel_settings.update();+ }+}++impl MouseWheelSettings {+ fn update(&self) {+ self.update_wheel_scroll_chars();+ self.update_wheel_scroll_lines();+ }++ fn update_wheel_scroll_chars(&self) {+ let mut value = c_uint::default();+ let result = unsafe {+ SystemParametersInfoW(+ SPI_GETWHEELSCROLLCHARS,+ 0,+ Some((&mut value) as *mut c_uint as *mut c_void),+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),+ )+ };++ if result.log_err() != None && self.wheel_scroll_chars.get() != value {+ self.wheel_scroll_chars.set(value);+ }+ }++ fn update_wheel_scroll_lines(&self) {+ let mut value = c_uint::default();+ let result = unsafe {+ SystemParametersInfoW(+ SPI_GETWHEELSCROLLLINES,+ 0,+ Some((&mut value) as *mut c_uint as *mut c_void),+ SYSTEM_PARAMETERS_INFO_UPDATE_FLAGS::default(),+ )+ };++ if result.log_err() != None && self.wheel_scroll_lines.get() != value {+ self.wheel_scroll_lines.set(value);+ }+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/util.rs b/native/vendor/wu/crates/gpui_windows/src/util.rsnew file mode 100644index 00000000000..b3badd84d10--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/util.rs@@ -0,0 +1,191 @@+use std::sync::OnceLock;++use anyhow::Context;+use gpui_util::ResultExt;+use windows::{+ UI::{+ Color,+ ViewManagement::{UIColorType, UISettings},+ },+ Win32::{+ Foundation::*, Graphics::Dwm::*, System::LibraryLoader::LoadLibraryA,+ UI::WindowsAndMessaging::*,+ },+ core::{BOOL, PCSTR},+};++use crate::*;+use gpui::*;++pub(crate) trait HiLoWord {+ fn hiword(&self) -> u16;+ fn loword(&self) -> u16;+ fn signed_hiword(&self) -> i16;+ fn signed_loword(&self) -> i16;+}++impl HiLoWord for WPARAM {+ fn hiword(&self) -> u16 {+ ((self.0 >> 16) & 0xFFFF) as u16+ }++ fn loword(&self) -> u16 {+ (self.0 & 0xFFFF) as u16+ }++ fn signed_hiword(&self) -> i16 {+ ((self.0 >> 16) & 0xFFFF) as i16+ }++ fn signed_loword(&self) -> i16 {+ (self.0 & 0xFFFF) as i16+ }+}++impl HiLoWord for LPARAM {+ fn hiword(&self) -> u16 {+ ((self.0 >> 16) & 0xFFFF) as u16+ }++ fn loword(&self) -> u16 {+ (self.0 & 0xFFFF) as u16+ }++ fn signed_hiword(&self) -> i16 {+ ((self.0 >> 16) & 0xFFFF) as i16+ }++ fn signed_loword(&self) -> i16 {+ (self.0 & 0xFFFF) as i16+ }+}++pub(crate) unsafe fn get_window_long(hwnd: HWND, nindex: WINDOW_LONG_PTR_INDEX) -> isize {+ #[cfg(target_pointer_width = "64")]+ unsafe {+ GetWindowLongPtrW(hwnd, nindex)+ }+ #[cfg(target_pointer_width = "32")]+ unsafe {+ GetWindowLongW(hwnd, nindex) as isize+ }+}++pub(crate) unsafe fn set_window_long(+ hwnd: HWND,+ nindex: WINDOW_LONG_PTR_INDEX,+ dwnewlong: isize,+) -> isize {+ #[cfg(target_pointer_width = "64")]+ unsafe {+ SetWindowLongPtrW(hwnd, nindex, dwnewlong)+ }+ #[cfg(target_pointer_width = "32")]+ unsafe {+ SetWindowLongW(hwnd, nindex, dwnewlong as i32) as isize+ }+}++pub(crate) fn windows_credentials_target_name(url: &str) -> String {+ format!("zed:url={}", url)+}++pub(crate) fn load_cursor(style: CursorStyle) -> Option<HCURSOR> {+ static ARROW: OnceLock<SafeCursor> = OnceLock::new();+ static IBEAM: OnceLock<SafeCursor> = OnceLock::new();+ static CROSS: OnceLock<SafeCursor> = OnceLock::new();+ static HAND: OnceLock<SafeCursor> = OnceLock::new();+ static SIZEWE: OnceLock<SafeCursor> = OnceLock::new();+ static SIZENS: OnceLock<SafeCursor> = OnceLock::new();+ static SIZENWSE: OnceLock<SafeCursor> = OnceLock::new();+ static SIZENESW: OnceLock<SafeCursor> = OnceLock::new();+ static NO: OnceLock<SafeCursor> = OnceLock::new();+ let (lock, name) = match style {+ CursorStyle::IBeam | CursorStyle::IBeamCursorForVerticalLayout => (&IBEAM, IDC_IBEAM),+ CursorStyle::Crosshair => (&CROSS, IDC_CROSS),+ CursorStyle::PointingHand | CursorStyle::DragLink => (&HAND, IDC_HAND),+ CursorStyle::ResizeLeft+ | CursorStyle::ResizeRight+ | CursorStyle::ResizeLeftRight+ | CursorStyle::ResizeColumn => (&SIZEWE, IDC_SIZEWE),+ CursorStyle::ResizeUp+ | CursorStyle::ResizeDown+ | CursorStyle::ResizeUpDown+ | CursorStyle::ResizeRow => (&SIZENS, IDC_SIZENS),+ CursorStyle::ResizeUpLeftDownRight => (&SIZENWSE, IDC_SIZENWSE),+ CursorStyle::ResizeUpRightDownLeft => (&SIZENESW, IDC_SIZENESW),+ CursorStyle::OperationNotAllowed => (&NO, IDC_NO),+ _ => (&ARROW, IDC_ARROW),+ };+ Some(+ *(*lock.get_or_init(|| {+ HCURSOR(+ unsafe { LoadImageW(None, name, IMAGE_CURSOR, 0, 0, LR_DEFAULTSIZE | LR_SHARED) }+ .log_err()+ .unwrap_or_default()+ .0,+ )+ .into()+ })),+ )+}++/// This function is used to configure the dark mode for the window built-in title bar.+pub(crate) fn configure_dwm_dark_mode(hwnd: HWND, appearance: WindowAppearance) {+ let dark_mode_enabled: BOOL = match appearance {+ WindowAppearance::Dark | WindowAppearance::VibrantDark => true.into(),+ WindowAppearance::Light | WindowAppearance::VibrantLight => false.into(),+ };+ unsafe {+ DwmSetWindowAttribute(+ hwnd,+ DWMWA_USE_IMMERSIVE_DARK_MODE,+ &dark_mode_enabled as *const _ as _,+ std::mem::size_of::<BOOL>() as u32,+ )+ .log_err();+ }+}++#[inline]+pub(crate) fn logical_point(x: f32, y: f32, scale_factor: f32) -> Point<Pixels> {+ Point {+ x: px(x / scale_factor),+ y: px(y / scale_factor),+ }+}++// https://learn.microsoft.com/en-us/windows/apps/desktop/modernize/apply-windows-themes+#[inline]+pub(crate) fn system_appearance() -> Result<WindowAppearance> {+ let ui_settings = UISettings::new()?;+ let foreground_color = ui_settings.GetColorValue(UIColorType::Foreground)?;+ // If the foreground is light, then is_color_light will evaluate to true,+ // meaning Dark mode is enabled.+ if is_color_light(&foreground_color) {+ Ok(WindowAppearance::Dark)+ } else {+ Ok(WindowAppearance::Light)+ }+}++#[inline(always)]+fn is_color_light(color: &Color) -> bool {+ ((5 * color.G as u32) + (2 * color.R as u32) + color.B as u32) > (8 * 128)+}++pub(crate) fn with_dll_library<R, F>(dll_name: PCSTR, f: F) -> Result<R>+where+ F: FnOnce(HMODULE) -> Result<R>,+{+ let library = unsafe {+ LoadLibraryA(dll_name).with_context(|| format!("Loading dll: {}", dll_name.display()))?+ };+ let result = f(library);+ unsafe {+ FreeLibrary(library)+ .with_context(|| format!("Freeing dll: {}", dll_name.display()))+ .log_err();+ }+ result+}diff --git a/native/vendor/wu/crates/gpui_windows/src/vsync.rs b/native/vendor/wu/crates/gpui_windows/src/vsync.rsnew file mode 100644index 00000000000..51fbdf6c500--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/vsync.rs@@ -0,0 +1,81 @@+use std::{+ sync::LazyLock,+ time::{Duration, Instant},+};++use anyhow::{Context, Result};+use gpui_util::ResultExt;+use windows::Win32::{+ Foundation::HWND,+ Graphics::Dwm::{DWM_TIMING_INFO, DwmFlush, DwmGetCompositionTimingInfo},+ System::Performance::QueryPerformanceFrequency,+};++static QPC_TICKS_PER_SECOND: LazyLock<u64> = LazyLock::new(|| {+ let mut frequency = 0;+ // On systems that run Windows XP or later, the function will always succeed and+ // will thus never return zero.+ unsafe { QueryPerformanceFrequency(&mut frequency).unwrap() };+ frequency as u64+});++const VSYNC_INTERVAL_THRESHOLD: Duration = Duration::from_millis(1);+const DEFAULT_VSYNC_INTERVAL: Duration = Duration::from_micros(16_666); // ~60Hz++pub(crate) struct VSyncProvider {+ interval: Duration,+ f: Box<dyn Fn() -> bool>,+}++impl VSyncProvider {+ pub(crate) fn new() -> Self {+ let interval = get_dwm_interval()+ .context("Failed to get DWM interval")+ .log_err()+ .unwrap_or(DEFAULT_VSYNC_INTERVAL);+ let f = Box::new(|| unsafe { DwmFlush().is_ok() });+ Self { interval, f }+ }++ pub(crate) fn wait_for_vsync(&self) {+ let vsync_start = Instant::now();+ let wait_succeeded = (self.f)();+ let elapsed = vsync_start.elapsed();+ // DwmFlush and DCompositionWaitForCompositorClock returns very early+ // instead of waiting until vblank when the monitor goes to sleep or is+ // unplugged (nothing to present due to desktop occlusion). We use 1ms as+ // a threshold for the duration of the wait functions and fallback to+ // Sleep() if it returns before that. This could happen during normal+ // operation for the first call after the vsync thread becomes non-idle,+ // but it shouldn't happen often.+ if !wait_succeeded || elapsed < VSYNC_INTERVAL_THRESHOLD {+ log::trace!("VSyncProvider::wait_for_vsync() took less time than expected");+ std::thread::sleep(self.interval);+ }+ }+}++fn get_dwm_interval() -> Result<Duration> {+ let mut timing_info = DWM_TIMING_INFO {+ cbSize: std::mem::size_of::<DWM_TIMING_INFO>() as u32,+ ..Default::default()+ };+ unsafe { DwmGetCompositionTimingInfo(HWND::default(), &mut timing_info) }?;+ let interval = retrieve_duration(timing_info.qpcRefreshPeriod, *QPC_TICKS_PER_SECOND);+ // Check for interval values that are impossibly low. A 29 microsecond+ // interval was seen (from a qpcRefreshPeriod of 60).+ if interval < VSYNC_INTERVAL_THRESHOLD {+ Ok(retrieve_duration(+ timing_info.rateRefresh.uiDenominator as u64,+ timing_info.rateRefresh.uiNumerator as u64,+ ))+ } else {+ Ok(interval)+ }+}++#[inline]+fn retrieve_duration(counts: u64, ticks_per_second: u64) -> Duration {+ let ticks_per_microsecond = ticks_per_second / 1_000_000;+ Duration::from_micros(counts / ticks_per_microsecond)+}diff --git a/native/vendor/wu/crates/gpui_windows/src/window.rs b/native/vendor/wu/crates/gpui_windows/src/window.rsnew file mode 100644index 00000000000..3ee19ae095d--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/window.rs@@ -0,0 +1,1703 @@+#![deny(unsafe_op_in_unsafe_fn)]++use std::{+ cell::{Cell, RefCell},+ num::NonZeroIsize,+ path::PathBuf,+ rc::{Rc, Weak},+ str::FromStr,+ sync::{Arc, Once, atomic::AtomicBool},+ time::{Duration, Instant},+};++use anyhow::{Context as _, Result};+use futures::channel::oneshot::{self, Receiver};+use gpui_util::ResultExt;+use raw_window_handle as rwh;+use smallvec::SmallVec;+use windows::{+ Win32::{+ Foundation::*,+ Graphics::Dwm::*,+ Graphics::Gdi::*,+ System::{+ Com::*, Diagnostics::Debug::MessageBeep, LibraryLoader::*, Ole::*, SystemServices::*,+ },+ UI::{Controls::*, HiDpi::*, Input::KeyboardAndMouse::*, Shell::*, WindowsAndMessaging::*},+ },+ core::*,+};++use crate::direct_manipulation::DirectManipulationHandler;+use crate::*;+use gpui::*;++pub(crate) struct WindowsWindow(pub Rc<WindowsWindowInner>);++impl std::ops::Deref for WindowsWindow {+ type Target = WindowsWindowInner;++ fn deref(&self) -> &Self::Target {+ &self.0+ }+}++pub struct WindowsWindowState {+ pub origin: Cell<Point<Pixels>>,+ pub logical_size: Cell<Size<Pixels>>,+ pub min_size: Option<Size<Pixels>>,+ pub fullscreen_restore_bounds: Cell<Bounds<Pixels>>,+ pub border_offset: WindowBorderOffset,+ pub appearance: Cell<WindowAppearance>,+ pub background_appearance: Cell<WindowBackgroundAppearance>,+ pub scale_factor: Cell<f32>,+ pub restore_from_minimized: Cell<Option<Box<dyn FnMut(RequestFrameOptions)>>>,++ pub callbacks: Callbacks,+ pub input_handler: Cell<Option<PlatformInputHandler>>,+ pub ime_enabled: Cell<bool>,+ pub pending_surrogate: Cell<Option<u16>>,+ pub last_reported_modifiers: Cell<Option<Modifiers>>,+ pub last_reported_capslock: Cell<Option<Capslock>>,+ pub hovered: Cell<bool>,+ pub direct_manipulation: DirectManipulationHandler,+ pub touches: RefCell<ActiveTouches<u32, ()>>,++ pub renderer: RefCell<DirectXRenderer>,+ /// Set when the next `draw_window` call must be treated as a forced+ /// render. Used after a GPU device-lost recovery, where the next frame+ /// must both re-enable drawing (via `mark_drawable`) and bypass the GPUI+ /// view cache (which would otherwise replay stale atlas tile references+ /// from the previous frame and panic in `DirectXAtlasState::texture`),+ /// and when a forced render was requested while another draw was in+ /// progress and had to be deferred.+ pub force_render_pending: Cell<bool>,++ pub click_state: ClickState,+ pub current_cursor: Cell<Option<HCURSOR>>,+ /// Shared with [`WindowsPlatformState::cursor_visible`].+ pub cursor_visible: Arc<AtomicBool>,+ pub nc_button_pressed: Cell<Option<u32>>,++ pub display: Cell<WindowsDisplay>,+ /// Flag to instruct the `VSyncProvider` thread to invalidate the directx devices+ /// as resizing them has failed, causing us to have lost at least the render target.+ pub invalidate_devices: Arc<AtomicBool>,+ /// Shared with [`WindowsPlatformState::draw_coordinator`] and every other window.+ pub(crate) draw_coordinator: Rc<DrawCoordinator>,+ fullscreen: Cell<Option<StyleAndBounds>>,+ initial_placement: Cell<Option<WindowOpenStatus>>,+ hwnd: HWND,+ pub(crate) a11y: RefCell<Option<A11yState>>,+}++pub(crate) struct WindowsWindowInner {+ hwnd: HWND,+ drop_target_helper: IDropTargetHelper,+ pub(crate) state: WindowsWindowState,+ system_settings: WindowsSystemSettings,+ pub(crate) handle: AnyWindowHandle,+ pub(crate) hide_title_bar: bool,+ pub(crate) is_movable: bool,+ pub(crate) is_resizable: bool,+ pub(crate) is_minimizable: bool,+ pub(crate) executor: ForegroundExecutor,+ pub(crate) validation_number: usize,+ pub(crate) main_receiver: PriorityQueueReceiver<RunnableVariant>,+ pub(crate) platform_window_handle: HWND,+ pub(crate) parent_hwnd: Option<HWND>,+}++impl WindowsWindowState {+ fn new(+ hwnd: HWND,+ directx_devices: &DirectXDevices,+ window_params: &CREATESTRUCTW,+ current_cursor: Option<HCURSOR>,+ cursor_visible: Arc<AtomicBool>,+ display: WindowsDisplay,+ min_size: Option<Size<Pixels>>,+ appearance: WindowAppearance,+ disable_direct_composition: bool,+ invalidate_devices: Arc<AtomicBool>,+ draw_coordinator: Rc<DrawCoordinator>,+ ) -> Result<Self> {+ let scale_factor = {+ let monitor_dpi = unsafe { GetDpiForWindow(hwnd) } as f32;+ monitor_dpi / USER_DEFAULT_SCREEN_DPI as f32+ };+ let origin = logical_point(window_params.x as f32, window_params.y as f32, scale_factor);+ let logical_size = {+ let physical_size = size(+ DevicePixels(window_params.cx),+ DevicePixels(window_params.cy),+ );+ physical_size.to_pixels(scale_factor)+ };+ let fullscreen_restore_bounds = Bounds {+ origin,+ size: logical_size,+ };+ let border_offset = WindowBorderOffset::default();+ let restore_from_minimized = None;+ let renderer = DirectXRenderer::new(hwnd, directx_devices, disable_direct_composition)+ .context("Creating DirectX renderer")?;+ let callbacks = Callbacks::default();+ let input_handler = None;+ let pending_surrogate = None;+ let last_reported_modifiers = None;+ let last_reported_capslock = None;+ let hovered = false;+ let click_state = ClickState::new();+ let nc_button_pressed = None;+ let fullscreen = None;+ let initial_placement = None;++ let direct_manipulation = DirectManipulationHandler::new(hwnd, scale_factor)+ .context("initializing Direct Manipulation")?;++ Ok(Self {+ origin: Cell::new(origin),+ logical_size: Cell::new(logical_size),+ fullscreen_restore_bounds: Cell::new(fullscreen_restore_bounds),+ border_offset,+ appearance: Cell::new(appearance),+ background_appearance: Cell::new(WindowBackgroundAppearance::Opaque),+ scale_factor: Cell::new(scale_factor),+ restore_from_minimized: Cell::new(restore_from_minimized),+ min_size,+ callbacks,+ input_handler: Cell::new(input_handler),+ ime_enabled: Cell::new(true),+ pending_surrogate: Cell::new(pending_surrogate),+ last_reported_modifiers: Cell::new(last_reported_modifiers),+ last_reported_capslock: Cell::new(last_reported_capslock),+ hovered: Cell::new(hovered),+ renderer: RefCell::new(renderer),+ force_render_pending: Cell::new(false),+ click_state,+ current_cursor: Cell::new(current_cursor),+ cursor_visible,+ nc_button_pressed: Cell::new(nc_button_pressed),+ display: Cell::new(display),+ fullscreen: Cell::new(fullscreen),+ initial_placement: Cell::new(initial_placement),+ hwnd,+ invalidate_devices,+ draw_coordinator,+ direct_manipulation,+ touches: RefCell::default(),+ a11y: RefCell::new(None),+ })+ }++ #[inline]+ pub(crate) fn is_fullscreen(&self) -> bool {+ self.fullscreen.get().is_some()+ }++ pub(crate) fn is_maximized(&self) -> bool {+ !self.is_fullscreen() && unsafe { IsZoomed(self.hwnd) }.as_bool()+ }++ fn bounds(&self) -> Bounds<Pixels> {+ Bounds {+ origin: self.origin.get(),+ size: self.logical_size.get(),+ }+ }++ // Calculate the bounds used for saving and whether the window is maximized.+ fn calculate_window_bounds(&self) -> (Bounds<Pixels>, bool) {+ let placement = unsafe {+ let mut placement = WINDOWPLACEMENT {+ length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,+ ..Default::default()+ };+ GetWindowPlacement(self.hwnd, &mut placement)+ .context("failed to get window placement")+ .log_err();+ placement+ };+ (+ calculate_client_rect(+ placement.rcNormalPosition,+ &self.border_offset,+ self.scale_factor.get(),+ ),+ placement.showCmd == SW_SHOWMAXIMIZED.0 as u32,+ )+ }++ fn window_bounds(&self) -> WindowBounds {+ let (bounds, maximized) = self.calculate_window_bounds();++ if self.is_fullscreen() {+ WindowBounds::Fullscreen(self.fullscreen_restore_bounds.get())+ } else if maximized {+ WindowBounds::Maximized(bounds)+ } else {+ WindowBounds::Windowed(bounds)+ }+ }++ /// get the logical size of the app's drawable area.+ ///+ /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as+ /// whether the mouse collides with other elements of GPUI).+ fn content_size(&self) -> Size<Pixels> {+ self.logical_size.get()+ }+}++impl WindowsWindowInner {+ fn new(context: &mut WindowCreateContext, hwnd: HWND, cs: &CREATESTRUCTW) -> Result<Rc<Self>> {+ let state = WindowsWindowState::new(+ hwnd,+ &context.directx_devices,+ cs,+ context.current_cursor,+ context.cursor_visible.clone(),+ context.display,+ context.min_size,+ context.appearance,+ context.disable_direct_composition,+ context.invalidate_devices.clone(),+ context.draw_coordinator.clone(),+ )?;++ Ok(Rc::new(Self {+ hwnd,+ drop_target_helper: context.drop_target_helper.clone(),+ state,+ handle: context.handle,+ hide_title_bar: context.hide_title_bar,+ is_movable: context.is_movable,+ is_resizable: context.is_resizable,+ is_minimizable: context.is_minimizable,+ executor: context.executor.clone(),+ validation_number: context.validation_number,+ main_receiver: context.main_receiver.clone(),+ platform_window_handle: context.platform_window_handle,+ system_settings: WindowsSystemSettings::new(),+ parent_hwnd: context.parent_hwnd,+ }))+ }++ fn toggle_fullscreen(self: &Rc<Self>) {+ let this = self.clone();+ self.executor+ .spawn(async move {+ let StyleAndBounds {+ style,+ x,+ y,+ cx,+ cy,+ } = match this.state.fullscreen.take() {+ Some(state) => state,+ None => {+ let (window_bounds, _) = this.state.calculate_window_bounds();+ this.state.fullscreen_restore_bounds.set(window_bounds);++ let style =+ WINDOW_STYLE(unsafe { get_window_long(this.hwnd, GWL_STYLE) } as _);+ let mut rc = RECT::default();+ unsafe { GetWindowRect(this.hwnd, &mut rc) }+ .context("failed to get window rect")+ .log_err();+ let _ = this.state.fullscreen.set(Some(StyleAndBounds {+ style,+ x: rc.left,+ y: rc.top,+ cx: rc.right - rc.left,+ cy: rc.bottom - rc.top,+ }));+ let style = style+ & !(WS_THICKFRAME+ | WS_SYSMENU+ | WS_MAXIMIZEBOX+ | WS_MINIMIZEBOX+ | WS_CAPTION);+ let physical_bounds = this.state.display.get().physical_bounds();+ StyleAndBounds {+ style,+ x: physical_bounds.left().0,+ y: physical_bounds.top().0,+ cx: physical_bounds.size.width.0,+ cy: physical_bounds.size.height.0,+ }+ }+ };+ set_non_rude_hwnd(this.hwnd, !this.state.is_fullscreen());+ unsafe { set_window_long(this.hwnd, GWL_STYLE, style.0 as isize) };+ unsafe {+ SetWindowPos(+ this.hwnd,+ None,+ x,+ y,+ cx,+ cy,+ SWP_FRAMECHANGED | SWP_NOACTIVATE | SWP_NOZORDER,+ )+ }+ .log_err();+ })+ .detach();+ }++ fn set_window_placement(self: &Rc<Self>) -> Result<()> {+ let Some(open_status) = self.state.initial_placement.take() else {+ return Ok(());+ };+ match open_status.state {+ WindowOpenState::Maximized => unsafe {+ SetWindowPlacement(self.hwnd, &open_status.placement)+ .context("failed to set window placement")?;+ ShowWindowAsync(self.hwnd, SW_MAXIMIZE).ok()?;+ },+ WindowOpenState::Fullscreen => {+ unsafe {+ SetWindowPlacement(self.hwnd, &open_status.placement)+ .context("failed to set window placement")?+ };+ self.toggle_fullscreen();+ }+ WindowOpenState::Windowed => unsafe {+ SetWindowPlacement(self.hwnd, &open_status.placement)+ .context("failed to set window placement")?;+ },+ }+ Ok(())+ }++ pub(crate) fn system_settings(&self) -> &WindowsSystemSettings {+ &self.system_settings+ }+}++#[derive(Default)]+pub(crate) struct Callbacks {+ pub(crate) request_frame: Cell<Option<Box<dyn FnMut(RequestFrameOptions)>>>,+ pub(crate) input: Cell<Option<Box<dyn FnMut(PlatformInput) -> DispatchEventResult>>>,+ pub(crate) active_status_change: Cell<Option<Box<dyn FnMut(bool)>>>,+ pub(crate) hovered_status_change: Cell<Option<Box<dyn FnMut(bool)>>>,+ pub(crate) resize: Cell<Option<Box<dyn FnMut(Size<Pixels>, f32)>>>,+ pub(crate) moved: Cell<Option<Box<dyn FnMut()>>>,+ pub(crate) should_close: Cell<Option<Box<dyn FnMut() -> bool>>>,+ pub(crate) close: Cell<Option<Box<dyn FnOnce()>>>,+ pub(crate) hit_test_window_control: Cell<Option<Box<dyn FnMut() -> Option<WindowControlArea>>>>,+ pub(crate) appearance_changed: Cell<Option<Box<dyn FnMut()>>>,+}++struct WindowCreateContext {+ inner: Option<Result<Rc<WindowsWindowInner>>>,+ handle: AnyWindowHandle,+ hide_title_bar: bool,+ display: WindowsDisplay,+ is_movable: bool,+ is_resizable: bool,+ is_minimizable: bool,+ min_size: Option<Size<Pixels>>,+ executor: ForegroundExecutor,+ current_cursor: Option<HCURSOR>,+ cursor_visible: Arc<AtomicBool>,+ drop_target_helper: IDropTargetHelper,+ validation_number: usize,+ main_receiver: PriorityQueueReceiver<RunnableVariant>,+ platform_window_handle: HWND,+ appearance: WindowAppearance,+ disable_direct_composition: bool,+ directx_devices: DirectXDevices,+ invalidate_devices: Arc<AtomicBool>,+ draw_coordinator: Rc<DrawCoordinator>,+ parent_hwnd: Option<HWND>,+}++impl WindowsWindow {+ pub(crate) fn new(+ handle: AnyWindowHandle,+ params: WindowParams,+ creation_info: WindowCreationInfo,+ ) -> Result<Self> {+ // Native popups are not implemented on Windows yet. Rejecting lets callers fall back to+ // gpui's in-window popovers.+ if let WindowKind::AnchoredPopup(_) = params.kind {+ return Err(popup::PopupNotSupportedError.into());+ }++ let WindowCreationInfo {+ icon,+ executor,+ current_cursor,+ cursor_visible,+ drop_target_helper,+ validation_number,+ main_receiver,+ platform_window_handle,+ disable_direct_composition,+ directx_devices,+ invalidate_devices,+ draw_coordinator,+ } = creation_info;+ register_window_class(icon);+ let parent_hwnd = if params.kind == WindowKind::Dialog {+ let parent_window = unsafe { GetActiveWindow() };+ if parent_window.is_invalid() {+ None+ } else {+ // Disable the parent window to make this dialog modal+ unsafe {+ EnableWindow(parent_window, false).as_bool();+ };+ Some(parent_window)+ }+ } else {+ None+ };+ let hide_title_bar = params+ .titlebar+ .as_ref()+ .map(|titlebar| titlebar.appears_transparent)+ .unwrap_or(true);+ let window_name = HSTRING::from(+ params+ .titlebar+ .as_ref()+ .and_then(|titlebar| titlebar.title.as_ref())+ .map(|title| title.as_ref())+ .unwrap_or(""),+ );++ let (mut dwexstyle, dwstyle) = if params.kind == WindowKind::PopUp {+ (WS_EX_TOOLWINDOW | WS_EX_TOPMOST, WINDOW_STYLE(0x0))+ } else {+ let mut dwstyle = WS_SYSMENU;++ if params.is_resizable {+ dwstyle |= WS_THICKFRAME | WS_MAXIMIZEBOX;+ }++ if params.is_minimizable {+ dwstyle |= WS_MINIMIZEBOX;+ }+ let dwexstyle = if params.kind == WindowKind::Dialog {+ dwstyle |= WS_POPUP | WS_CAPTION;+ WS_EX_DLGMODALFRAME+ } else {+ WS_EX_APPWINDOW+ };++ (dwexstyle, dwstyle)+ };+ if !disable_direct_composition {+ dwexstyle |= WS_EX_NOREDIRECTIONBITMAP;+ }++ let hinstance = get_module_handle();+ let display = if let Some(display_id) = params.display_id {+ WindowsDisplay::new(display_id)+ } else {+ None+ }+ .or_else(WindowsDisplay::primary_monitor)+ .context("failed to find any monitor")?;+ let appearance = system_appearance().unwrap_or_default();+ let mut context = WindowCreateContext {+ inner: None,+ handle,+ hide_title_bar,+ display,+ is_movable: params.is_movable,+ is_resizable: params.is_resizable,+ is_minimizable: params.is_minimizable,+ min_size: params.window_min_size,+ executor,+ current_cursor,+ cursor_visible,+ drop_target_helper,+ validation_number,+ main_receiver,+ platform_window_handle,+ appearance,+ disable_direct_composition,+ directx_devices,+ invalidate_devices,+ draw_coordinator,+ parent_hwnd,+ };+ let creation_result = unsafe {+ CreateWindowExW(+ dwexstyle,+ WINDOW_CLASS_NAME,+ &window_name,+ dwstyle,+ CW_USEDEFAULT,+ CW_USEDEFAULT,+ CW_USEDEFAULT,+ CW_USEDEFAULT,+ parent_hwnd,+ None,+ Some(hinstance.into()),+ Some(&context as *const _ as *const _),+ )+ };++ // Failure to create a `WindowsWindowState` can cause window creation to fail,+ // so check the inner result first.+ let created = context+ .inner+ .take()+ .transpose()+ .and_then(|this| Ok((this, creation_result?)));+ let (this, hwnd) = match created {+ Ok(created) => created,+ Err(error) => {+ if let Some(parent_hwnd) = parent_hwnd {+ unsafe {+ EnableWindow(parent_hwnd, true).as_bool();+ }+ }+ return Err(error);+ }+ };+ let this = this.unwrap();++ register_drag_drop(&this)?;+ set_non_rude_hwnd(hwnd, true);+ configure_dwm_dark_mode(hwnd, appearance);+ this.state.border_offset.update(hwnd)?;+ let placement =+ retrieve_window_placement(hwnd, display, params.bounds, &this.state.border_offset)?;+ if params.show {+ let mut placement = placement;+ if !params.focus {+ placement.showCmd = SW_SHOWNOACTIVATE.0 as u32;+ }+ unsafe { SetWindowPlacement(hwnd, &placement)? };+ } else {+ this.state.initial_placement.set(Some(WindowOpenStatus {+ placement,+ state: WindowOpenState::Windowed,+ }));+ }++ Ok(Self(this))+ }+}++impl rwh::HasWindowHandle for WindowsWindow {+ fn window_handle(&self) -> std::result::Result<rwh::WindowHandle<'_>, rwh::HandleError> {+ let raw = rwh::Win32WindowHandle::new(unsafe {+ NonZeroIsize::new_unchecked(self.0.hwnd.0 as isize)+ })+ .into();+ Ok(unsafe { rwh::WindowHandle::borrow_raw(raw) })+ }+}++impl rwh::HasDisplayHandle for WindowsWindow {+ fn display_handle(&self) -> std::result::Result<rwh::DisplayHandle<'_>, rwh::HandleError> {+ Ok(rwh::DisplayHandle::windows())+ }+}++impl Drop for WindowsWindow {+ fn drop(&mut self) {+ // clone this `Rc` to prevent early release of the pointer+ let this = self.0.clone();+ self.0+ .executor+ .spawn(async move {+ let handle = this.hwnd;+ unsafe {+ RevokeDragDrop(handle).log_err();+ DestroyWindow(handle).log_err();+ }+ })+ .detach();+ }+}++impl PlatformWindow for WindowsWindow {+ fn bounds(&self) -> Bounds<Pixels> {+ self.state.bounds()+ }++ fn is_maximized(&self) -> bool {+ self.state.is_maximized()+ }++ fn window_bounds(&self) -> WindowBounds {+ self.state.window_bounds()+ }++ /// get the logical size of the app's drawable area.+ ///+ /// Currently, GPUI uses the logical size of the app to handle mouse interactions (such as+ /// whether the mouse collides with other elements of GPUI).+ fn content_size(&self) -> Size<Pixels> {+ self.state.content_size()+ }++ fn resize(&mut self, size: Size<Pixels>) {+ let hwnd = self.0.hwnd;+ let bounds = gpui::bounds(self.bounds().origin, size).to_device_pixels(self.scale_factor());+ let rect = calculate_window_rect(bounds, &self.state.border_offset);++ self.0+ .executor+ .spawn(async move {+ unsafe {+ SetWindowPos(+ hwnd,+ None,+ bounds.origin.x.0,+ bounds.origin.y.0,+ rect.right - rect.left,+ rect.bottom - rect.top,+ SWP_NOMOVE,+ )+ .context("unable to set window content size")+ .log_err();+ }+ })+ .detach();+ }++ fn scale_factor(&self) -> f32 {+ self.state.scale_factor.get()+ }++ fn appearance(&self) -> WindowAppearance {+ self.state.appearance.get()+ }++ fn display(&self) -> Option<Rc<dyn PlatformDisplay>> {+ Some(Rc::new(self.state.display.get()))+ }++ fn mouse_position(&self) -> Point<Pixels> {+ let scale_factor = self.scale_factor();+ let point = unsafe {+ let mut point: POINT = std::mem::zeroed();+ GetCursorPos(&mut point)+ .context("unable to get cursor position")+ .log_err();+ ScreenToClient(self.0.hwnd, &mut point).ok().log_err();+ point+ };+ logical_point(point.x as f32, point.y as f32, scale_factor)+ }++ fn modifiers(&self) -> Modifiers {+ current_modifiers()+ }++ fn capslock(&self) -> Capslock {+ current_capslock()+ }++ fn set_input_handler(&mut self, input_handler: PlatformInputHandler) {+ self.state.input_handler.set(Some(input_handler));+ }++ fn take_input_handler(&mut self) -> Option<PlatformInputHandler> {+ self.state.input_handler.take()+ }++ fn prompt(+ &self,+ level: PromptLevel,+ msg: &str,+ detail: Option<&str>,+ answers: &[PromptButton],+ ) -> Option<Receiver<usize>> {+ let (done_tx, done_rx) = oneshot::channel();+ let msg = msg.to_string();+ let detail_string = detail.map(|detail| detail.to_string());+ let handle = self.0.hwnd;+ let answers = answers.to_vec();+ self.0+ .executor+ .spawn(async move {+ unsafe {+ let mut config = TASKDIALOGCONFIG::default();+ config.cbSize = std::mem::size_of::<TASKDIALOGCONFIG>() as _;+ config.hwndParent = handle;+ let title;+ let main_icon;+ match level {+ PromptLevel::Info => {+ title = windows::core::w!("Info");+ main_icon = TD_INFORMATION_ICON;+ }+ PromptLevel::Warning => {+ title = windows::core::w!("Warning");+ main_icon = TD_WARNING_ICON;+ }+ PromptLevel::Critical => {+ title = windows::core::w!("Critical");+ main_icon = TD_ERROR_ICON;+ }+ };+ config.pszWindowTitle = title;+ config.Anonymous1.pszMainIcon = main_icon;+ let instruction = HSTRING::from(msg);+ config.pszMainInstruction = PCWSTR::from_raw(instruction.as_ptr());+ let hints_encoded;+ if let Some(ref hints) = detail_string {+ hints_encoded = HSTRING::from(hints);+ config.pszContent = PCWSTR::from_raw(hints_encoded.as_ptr());+ };+ let mut button_id_map = Vec::with_capacity(answers.len());+ let mut buttons = Vec::new();+ let mut btn_encoded = Vec::new();+ for (index, btn) in answers.iter().enumerate() {+ let encoded = HSTRING::from(btn.label().as_ref());+ let button_id = match btn {+ PromptButton::Ok(_) => IDOK.0,+ PromptButton::Cancel(_) => IDCANCEL.0,+ // the first few low integer values are reserved for known buttons+ // so for simplicity we just go backwards from -1+ PromptButton::Other(_) => -(index as i32) - 1,+ };+ button_id_map.push(button_id);+ buttons.push(TASKDIALOG_BUTTON {+ nButtonID: button_id,+ pszButtonText: PCWSTR::from_raw(encoded.as_ptr()),+ });+ btn_encoded.push(encoded);+ }+ config.cButtons = buttons.len() as _;+ config.pButtons = buttons.as_ptr();++ config.pfCallback = None;+ let mut res = std::mem::zeroed();+ let _ = TaskDialogIndirect(&config, Some(&mut res), None, None)+ .context("unable to create task dialog")+ .log_err();++ if let Some(clicked) =+ button_id_map.iter().position(|&button_id| button_id == res)+ {+ let _ = done_tx.send(clicked);+ }+ }+ })+ .detach();++ Some(done_rx)+ }++ fn activate(&self) {+ let hwnd = self.0.hwnd;+ let this = self.0.clone();+ self.0+ .executor+ .spawn(async move {+ this.set_window_placement().log_err();++ unsafe {+ // If the window is minimized, restore it.+ if IsIconic(hwnd).as_bool() {+ ShowWindowAsync(hwnd, SW_RESTORE).ok().log_err();+ }++ SetActiveWindow(hwnd).ok();+ SetFocus(Some(hwnd)).ok();+ }++ // premium ragebait by windows, this is needed because the window+ // must have received an input event to be able to set itself to foreground+ // so let's just simulate user input as that seems to be the most reliable way+ // some more info: https://gist.github.com/Aetopia/1581b40f00cc0cadc93a0e8ccb65dc8c+ // bonus: this bug also doesn't manifest if you have vs attached to the process+ let inputs = [+ INPUT {+ r#type: INPUT_KEYBOARD,+ Anonymous: INPUT_0 {+ ki: KEYBDINPUT {+ wVk: VK_MENU,+ dwFlags: KEYBD_EVENT_FLAGS(0),+ ..Default::default()+ },+ },+ },+ INPUT {+ r#type: INPUT_KEYBOARD,+ Anonymous: INPUT_0 {+ ki: KEYBDINPUT {+ wVk: VK_MENU,+ dwFlags: KEYEVENTF_KEYUP,+ ..Default::default()+ },+ },+ },+ ];+ unsafe { SendInput(&inputs, std::mem::size_of::<INPUT>() as i32) };++ // todo(windows)+ // crate `windows 0.56` reports true as Err+ unsafe { SetForegroundWindow(hwnd).as_bool() };+ })+ .detach();+ }++ fn request_attention(&self) {+ if self.is_active() {+ return;+ }++ let hwnd = self.0.hwnd;+ self.0+ .executor+ .spawn(async move {+ let info = FLASHWINFO {+ cbSize: std::mem::size_of::<FLASHWINFO>() as u32,+ hwnd,+ dwFlags: FLASHW_ALL,+ uCount: 1,+ dwTimeout: 0,+ };+ unsafe { FlashWindowEx(&info).ok().log_err() };+ })+ .detach();+ }++ fn is_active(&self) -> bool {+ self.0.hwnd == unsafe { GetActiveWindow() }+ }++ fn is_hovered(&self) -> bool {+ self.state.hovered.get()+ }++ fn background_appearance(&self) -> WindowBackgroundAppearance {+ self.state.background_appearance.get()+ }++ fn is_subpixel_rendering_supported(&self) -> bool {+ true+ }++ fn set_title(&mut self, title: &str) {+ unsafe { SetWindowTextW(self.0.hwnd, &HSTRING::from(title)) }+ .inspect_err(|e| log::error!("Set title failed: {e}"))+ .ok();+ }++ fn set_background_appearance(&self, background_appearance: WindowBackgroundAppearance) {+ self.state.background_appearance.set(background_appearance);+ let hwnd = self.0.hwnd;++ // using Dwm APIs for Mica and MicaAlt backdrops.+ // others follow the set_window_composition_attribute approach+ match background_appearance {+ WindowBackgroundAppearance::Opaque => {+ set_window_composition_attribute(hwnd, None, 0);+ }+ WindowBackgroundAppearance::Transparent => {+ set_window_composition_attribute(hwnd, None, 2);+ }+ WindowBackgroundAppearance::Blurred => {+ set_window_composition_attribute(hwnd, Some((0, 0, 0, 0)), 4);+ }+ WindowBackgroundAppearance::MicaBackdrop => {+ // DWMSBT_MAINWINDOW => MicaBase+ dwm_set_window_composition_attribute(hwnd, 2);+ }+ WindowBackgroundAppearance::MicaAltBackdrop => {+ // DWMSBT_TABBEDWINDOW => MicaAlt+ dwm_set_window_composition_attribute(hwnd, 4);+ }+ }+ }++ fn minimize(&self) {+ unsafe { ShowWindowAsync(self.0.hwnd, SW_MINIMIZE).ok().log_err() };+ }++ fn zoom(&self) {+ unsafe {+ if IsWindowVisible(self.0.hwnd).as_bool() {+ ShowWindowAsync(self.0.hwnd, SW_MAXIMIZE).ok().log_err();+ } else if let Some(mut status) = self.state.initial_placement.take() {+ status.state = WindowOpenState::Maximized;+ self.state.initial_placement.set(Some(status));+ }+ }+ }++ fn toggle_fullscreen(&self) {+ if unsafe { IsWindowVisible(self.0.hwnd).as_bool() } {+ self.0.toggle_fullscreen();+ } else if let Some(mut status) = self.state.initial_placement.take() {+ status.state = WindowOpenState::Fullscreen;+ self.state.initial_placement.set(Some(status));+ }+ }++ fn is_fullscreen(&self) -> bool {+ self.state.is_fullscreen()+ }++ fn on_request_frame(&self, callback: Box<dyn FnMut(RequestFrameOptions)>) {+ self.state.callbacks.request_frame.set(Some(callback));+ }++ fn on_input(&self, callback: Box<dyn FnMut(PlatformInput) -> DispatchEventResult>) {+ self.state.callbacks.input.set(Some(callback));+ }++ fn on_active_status_change(&self, callback: Box<dyn FnMut(bool)>) {+ self.0+ .state+ .callbacks+ .active_status_change+ .set(Some(callback));+ }++ fn on_hover_status_change(&self, callback: Box<dyn FnMut(bool)>) {+ self.0+ .state+ .callbacks+ .hovered_status_change+ .set(Some(callback));+ }++ fn on_resize(&self, callback: Box<dyn FnMut(Size<Pixels>, f32)>) {+ self.state.callbacks.resize.set(Some(callback));+ }++ fn on_moved(&self, callback: Box<dyn FnMut()>) {+ self.state.callbacks.moved.set(Some(callback));+ }++ fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>) {+ self.state.callbacks.should_close.set(Some(callback));+ }++ fn on_close(&self, callback: Box<dyn FnOnce()>) {+ self.state.callbacks.close.set(Some(callback));+ }++ fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>) {+ self.0+ .state+ .callbacks+ .hit_test_window_control+ .set(Some(callback));+ }++ fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {+ self.0+ .state+ .callbacks+ .appearance_changed+ .set(Some(callback));+ }++ fn draw(&self, scene: &Scene) {+ self.state+ .renderer+ .borrow_mut()+ .draw(scene, self.state.background_appearance.get())+ .log_err();+ }++ #[cfg(any(test, feature = "test-support"))]+ fn render_to_image(&self, scene: &Scene) -> anyhow::Result<image::RgbaImage> {+ self.state+ .renderer+ .borrow_mut()+ .render_to_image(scene, self.state.background_appearance.get())+ }++ fn sprite_atlas(&self) -> Arc<dyn PlatformAtlas> {+ self.state.renderer.borrow().sprite_atlas()+ }++ fn get_raw_handle(&self) -> HWND {+ self.0.hwnd+ }++ fn gpu_specs(&self) -> Option<GpuSpecs> {+ self.state.renderer.borrow().gpu_specs().log_err()+ }++ fn update_ime_position(&self, bounds: Bounds<Pixels>) {+ let scale_factor = self.state.scale_factor.get();+ let caret_position = POINT {+ x: (bounds.origin.x.as_f32() * scale_factor) as i32,+ y: (bounds.origin.y.as_f32() * scale_factor) as i32+ + ((bounds.size.height.as_f32() * scale_factor) as i32 / 2),+ };++ self.0.update_ime_position(self.0.hwnd, caret_position);+ }++ fn play_system_bell(&self) {+ // MB_OK: The sound specified as the Windows Default Beep sound.+ let _ = unsafe { MessageBeep(MB_OK) };+ }++ fn a11y_init(&self, callbacks: gpui::A11yCallbacks) {+ let action_handler = A11yActionHandler(callbacks.action);+ let is_focused = unsafe { GetForegroundWindow() } == self.0.hwnd;++ let adapter = accesskit_windows::Adapter::new(+ accesskit_windows::HWND(self.0.hwnd.0),+ is_focused,+ action_handler,+ );++ let activation_handler = A11yActivationHandler {+ callback: callbacks.activation,+ };++ *self.state.a11y.borrow_mut() = Some(A11yState {+ adapter,+ activation_handler,+ });+ }++ fn a11y_tree_update(&self, tree_update: accesskit::TreeUpdate) {+ let events = {+ let mut a11y = self.state.a11y.borrow_mut();+ a11y.as_mut()+ .and_then(|a11y| a11y.adapter.update_if_active(|| tree_update))+ };+ // The borrow must be dropped before raising events, because+ // `events.raise()` calls `UiaRaiseAutomationPropertyChangedEvent`+ // which may send a nested `WM_GETOBJECT` back into this window+ // procedure, re-entering `handle_wm_getobject` which also borrows+ // `self.state.a11y`.+ if let Some(events) = events {+ events.raise();+ }+ }++ fn a11y_update_window_bounds(&self) {+ // Windows UIA handles window bounds tracking automatically.+ }+}++pub(crate) struct A11yState {+ pub(crate) adapter: accesskit_windows::Adapter,+ pub(crate) activation_handler: A11yActivationHandler,+}++pub(crate) struct A11yActivationHandler {+ callback: Box<dyn Fn() -> Option<accesskit::TreeUpdate> + Send + 'static>,+}++impl accesskit::ActivationHandler for A11yActivationHandler {+ fn request_initial_tree(&mut self) -> Option<accesskit::TreeUpdate> {+ (self.callback)()+ }+}++struct A11yActionHandler(Box<dyn Fn(accesskit::ActionRequest) + Send + 'static>);++impl accesskit::ActionHandler for A11yActionHandler {+ fn do_action(&mut self, request: accesskit::ActionRequest) {+ (self.0)(request);+ }+}++#[implement(IDropTarget)]+struct WindowsDragDropHandler(pub Rc<WindowsWindowInner>);++impl WindowsDragDropHandler {+ fn handle_drag_drop(&self, input: PlatformInput) {+ if let Some(mut func) = self.0.state.callbacks.input.take() {+ func(input);+ self.0.state.callbacks.input.set(Some(func));+ }+ }+}++#[allow(non_snake_case)]+impl IDropTarget_Impl for WindowsDragDropHandler_Impl {+ fn DragEnter(+ &self,+ pdataobj: windows::core::Ref<IDataObject>,+ _grfkeystate: MODIFIERKEYS_FLAGS,+ pt: &POINTL,+ pdweffect: *mut DROPEFFECT,+ ) -> windows::core::Result<()> {+ unsafe {+ let idata_obj = pdataobj.ok()?;+ let config = FORMATETC {+ cfFormat: CF_HDROP.0,+ ptd: std::ptr::null_mut() as _,+ dwAspect: DVASPECT_CONTENT.0,+ lindex: -1,+ tymed: TYMED_HGLOBAL.0 as _,+ };+ let cursor_position = POINT { x: pt.x, y: pt.y };+ if idata_obj.QueryGetData(&config as _) == S_OK {+ *pdweffect = DROPEFFECT_COPY;+ let Some(mut idata) = idata_obj.GetData(&config as _).log_err() else {+ return Ok(());+ };+ if idata.u.hGlobal.is_invalid() {+ return Ok(());+ }+ let hdrop = HDROP(idata.u.hGlobal.0);+ let mut paths = SmallVec::<[PathBuf; 2]>::new();+ with_file_names(hdrop, |file_name| {+ if let Some(path) = PathBuf::from_str(&file_name).log_err() {+ paths.push(path);+ }+ });+ ReleaseStgMedium(&mut idata);+ let mut cursor_position = cursor_position;+ ScreenToClient(self.0.hwnd, &mut cursor_position)+ .ok()+ .log_err();+ let scale_factor = self.0.state.scale_factor.get();+ let input = PlatformInput::FileDrop(FileDropEvent::Entered {+ position: logical_point(+ cursor_position.x as f32,+ cursor_position.y as f32,+ scale_factor,+ ),+ paths: ExternalPaths(paths),+ });+ self.handle_drag_drop(input);+ } else {+ *pdweffect = DROPEFFECT_NONE;+ }+ self.0+ .drop_target_helper+ .DragEnter(self.0.hwnd, idata_obj, &cursor_position, *pdweffect)+ .log_err();+ }+ Ok(())+ }++ fn DragOver(+ &self,+ _grfkeystate: MODIFIERKEYS_FLAGS,+ pt: &POINTL,+ pdweffect: *mut DROPEFFECT,+ ) -> windows::core::Result<()> {+ let mut cursor_position = POINT { x: pt.x, y: pt.y };+ unsafe {+ *pdweffect = DROPEFFECT_COPY;+ self.0+ .drop_target_helper+ .DragOver(&cursor_position, *pdweffect)+ .log_err();+ ScreenToClient(self.0.hwnd, &mut cursor_position)+ .ok()+ .log_err();+ }+ let scale_factor = self.0.state.scale_factor.get();+ let input = PlatformInput::FileDrop(FileDropEvent::Pending {+ position: logical_point(+ cursor_position.x as f32,+ cursor_position.y as f32,+ scale_factor,+ ),+ });+ self.handle_drag_drop(input);++ Ok(())+ }++ fn DragLeave(&self) -> windows::core::Result<()> {+ unsafe {+ self.0.drop_target_helper.DragLeave().log_err();+ }+ let input = PlatformInput::FileDrop(FileDropEvent::Exited);+ self.handle_drag_drop(input);++ Ok(())+ }++ fn Drop(+ &self,+ pdataobj: windows::core::Ref<IDataObject>,+ _grfkeystate: MODIFIERKEYS_FLAGS,+ pt: &POINTL,+ pdweffect: *mut DROPEFFECT,+ ) -> windows::core::Result<()> {+ let idata_obj = pdataobj.ok()?;+ let mut cursor_position = POINT { x: pt.x, y: pt.y };+ unsafe {+ *pdweffect = DROPEFFECT_COPY;+ self.0+ .drop_target_helper+ .Drop(idata_obj, &cursor_position, *pdweffect)+ .log_err();+ ScreenToClient(self.0.hwnd, &mut cursor_position)+ .ok()+ .log_err();+ }+ let scale_factor = self.0.state.scale_factor.get();+ let input = PlatformInput::FileDrop(FileDropEvent::Submit {+ position: logical_point(+ cursor_position.x as f32,+ cursor_position.y as f32,+ scale_factor,+ ),+ });+ self.handle_drag_drop(input);++ Ok(())+ }+}++#[derive(Debug, Clone)]+pub(crate) struct ClickState {+ button: Cell<MouseButton>,+ last_click: Cell<Instant>,+ last_position: Cell<Point<DevicePixels>>,+ double_click_spatial_tolerance_width: Cell<i32>,+ double_click_spatial_tolerance_height: Cell<i32>,+ double_click_interval: Cell<Duration>,+ pub(crate) current_count: Cell<usize>,+}++impl ClickState {+ pub fn new() -> Self {+ let double_click_spatial_tolerance_width = unsafe { GetSystemMetrics(SM_CXDOUBLECLK) };+ let double_click_spatial_tolerance_height = unsafe { GetSystemMetrics(SM_CYDOUBLECLK) };+ let double_click_interval = Duration::from_millis(unsafe { GetDoubleClickTime() } as u64);++ ClickState {+ button: Cell::new(MouseButton::Left),+ last_click: Cell::new(Instant::now()),+ last_position: Cell::new(Point::default()),+ double_click_spatial_tolerance_width: Cell::new(double_click_spatial_tolerance_width),+ double_click_spatial_tolerance_height: Cell::new(double_click_spatial_tolerance_height),+ double_click_interval: Cell::new(double_click_interval),+ current_count: Cell::new(0),+ }+ }++ /// update self and return the needed click count+ pub fn update(&self, button: MouseButton, new_position: Point<DevicePixels>) -> usize {+ if self.button.get() == button && self.is_double_click(new_position) {+ self.current_count.update(|it| it + 1);+ } else {+ self.current_count.set(1);+ }+ self.last_click.set(Instant::now());+ self.last_position.set(new_position);+ self.button.set(button);++ self.current_count.get()+ }++ pub fn system_update(&self, wparam: usize) {+ match wparam {+ // SPI_SETDOUBLECLKWIDTH+ 29 => self+ .double_click_spatial_tolerance_width+ .set(unsafe { GetSystemMetrics(SM_CXDOUBLECLK) }),+ // SPI_SETDOUBLECLKHEIGHT+ 30 => self+ .double_click_spatial_tolerance_height+ .set(unsafe { GetSystemMetrics(SM_CYDOUBLECLK) }),+ // SPI_SETDOUBLECLICKTIME+ 32 => self+ .double_click_interval+ .set(Duration::from_millis(unsafe { GetDoubleClickTime() } as u64)),+ _ => {}+ }+ }++ #[inline]+ fn is_double_click(&self, new_position: Point<DevicePixels>) -> bool {+ let diff = self.last_position.get() - new_position;++ self.last_click.get().elapsed() < self.double_click_interval.get()+ && diff.x.0.abs() <= self.double_click_spatial_tolerance_width.get()+ && diff.y.0.abs() <= self.double_click_spatial_tolerance_height.get()+ }+}++#[derive(Copy, Clone)]+struct StyleAndBounds {+ style: WINDOW_STYLE,+ x: i32,+ y: i32,+ cx: i32,+ cy: i32,+}++#[repr(C)]+struct WINDOWCOMPOSITIONATTRIBDATA {+ attrib: u32,+ pv_data: *mut std::ffi::c_void,+ cb_data: usize,+}++#[repr(C)]+struct AccentPolicy {+ accent_state: u32,+ accent_flags: u32,+ gradient_color: u32,+ animation_id: u32,+}++type Color = (u8, u8, u8, u8);++#[derive(Debug, Default, Clone)]+pub(crate) struct WindowBorderOffset {+ pub(crate) width_offset: Cell<i32>,+ pub(crate) height_offset: Cell<i32>,+}++impl WindowBorderOffset {+ pub(crate) fn update(&self, hwnd: HWND) -> anyhow::Result<()> {+ let window_rect = unsafe {+ let mut rect = std::mem::zeroed();+ GetWindowRect(hwnd, &mut rect)?;+ rect+ };+ let client_rect = unsafe {+ let mut rect = std::mem::zeroed();+ GetClientRect(hwnd, &mut rect)?;+ rect+ };+ self.width_offset+ .set((window_rect.right - window_rect.left) - (client_rect.right - client_rect.left));+ self.height_offset+ .set((window_rect.bottom - window_rect.top) - (client_rect.bottom - client_rect.top));+ Ok(())+ }+}++#[derive(Clone)]+struct WindowOpenStatus {+ placement: WINDOWPLACEMENT,+ state: WindowOpenState,+}++#[derive(Clone, Copy)]+enum WindowOpenState {+ Maximized,+ Fullscreen,+ Windowed,+}++const WINDOW_CLASS_NAME: PCWSTR = w!("Wu::Window");++fn register_window_class(icon_handle: HICON) {+ static ONCE: Once = Once::new();+ ONCE.call_once(|| {+ let wc = WNDCLASSW {+ lpfnWndProc: Some(window_procedure),+ hIcon: icon_handle,+ lpszClassName: PCWSTR(WINDOW_CLASS_NAME.as_ptr()),+ style: CS_HREDRAW | CS_VREDRAW,+ hInstance: get_module_handle().into(),+ hbrBackground: unsafe { CreateSolidBrush(COLORREF(0x00000000)) },+ ..Default::default()+ };+ unsafe { RegisterClassW(&wc) };+ });+}++unsafe extern "system" fn window_procedure(+ hwnd: HWND,+ msg: u32,+ wparam: WPARAM,+ lparam: LPARAM,+) -> LRESULT {+ if msg == WM_NCCREATE {+ let window_params = unsafe { &*(lparam.0 as *const CREATESTRUCTW) };+ let window_creation_context = window_params.lpCreateParams as *mut WindowCreateContext;+ let window_creation_context = unsafe { &mut *window_creation_context };+ return match WindowsWindowInner::new(window_creation_context, hwnd, window_params) {+ Ok(window_state) => {+ let weak = Box::new(Rc::downgrade(&window_state));+ unsafe { set_window_long(hwnd, GWLP_USERDATA, Box::into_raw(weak) as isize) };+ window_creation_context.inner = Some(Ok(window_state));+ unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }+ }+ Err(error) => {+ window_creation_context.inner = Some(Err(error));+ LRESULT(0)+ }+ };+ }++ let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;+ if ptr.is_null() {+ return unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) };+ }+ let inner = unsafe { &*ptr };+ let result = if let Some(inner) = inner.upgrade() {+ inner.handle_msg(hwnd, msg, wparam, lparam)+ } else {+ unsafe { DefWindowProcW(hwnd, msg, wparam, lparam) }+ };++ if msg == WM_NCDESTROY {+ unsafe { set_window_long(hwnd, GWLP_USERDATA, 0) };+ unsafe { drop(Box::from_raw(ptr)) };+ }++ result+}++pub(crate) fn window_from_hwnd(hwnd: HWND) -> Option<Rc<WindowsWindowInner>> {+ if hwnd.is_invalid() {+ return None;+ }++ let ptr = unsafe { get_window_long(hwnd, GWLP_USERDATA) } as *mut Weak<WindowsWindowInner>;+ if !ptr.is_null() {+ let inner = unsafe { &*ptr };+ inner.upgrade()+ } else {+ None+ }+}++fn get_module_handle() -> HMODULE {+ unsafe {+ let mut h_module = std::mem::zeroed();+ GetModuleHandleExW(+ GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT,+ windows::core::w!("ZedModule"),+ &mut h_module,+ )+ .expect("Unable to get module handle"); // this should never fail++ h_module+ }+}++fn register_drag_drop(window: &Rc<WindowsWindowInner>) -> Result<()> {+ let window_handle = window.hwnd;+ let handler = WindowsDragDropHandler(window.clone());+ // The lifetime of `IDropTarget` is handled by Windows, it won't release until+ // we call `RevokeDragDrop`.+ // So, it's safe to drop it here.+ let drag_drop_handler: IDropTarget = handler.into();+ unsafe {+ RegisterDragDrop(window_handle, &drag_drop_handler)+ .context("unable to register drag-drop event")?;+ }+ Ok(())+}++fn calculate_window_rect(bounds: Bounds<DevicePixels>, border_offset: &WindowBorderOffset) -> RECT {+ // NOTE:+ // The reason we're not using `AdjustWindowRectEx()` here is+ // that the size reported by this function is incorrect.+ // You can test it, and there are similar discussions online.+ // See: https://stackoverflow.com/questions/12423584/how-to-set-exact-client-size-for-overlapped-window-winapi+ //+ // So we manually calculate these values here.+ let mut rect = RECT {+ left: bounds.left().0,+ top: bounds.top().0,+ right: bounds.right().0,+ bottom: bounds.bottom().0,+ };+ let left_offset = border_offset.width_offset.get() / 2;+ let top_offset = border_offset.height_offset.get() / 2;+ let right_offset = border_offset.width_offset.get() - left_offset;+ let bottom_offset = border_offset.height_offset.get() - top_offset;+ rect.left -= left_offset;+ rect.top -= top_offset;+ rect.right += right_offset;+ rect.bottom += bottom_offset;+ rect+}++fn calculate_client_rect(+ rect: RECT,+ border_offset: &WindowBorderOffset,+ scale_factor: f32,+) -> Bounds<Pixels> {+ let left_offset = border_offset.width_offset.get() / 2;+ let top_offset = border_offset.height_offset.get() / 2;+ let right_offset = border_offset.width_offset.get() - left_offset;+ let bottom_offset = border_offset.height_offset.get() - top_offset;+ let left = rect.left + left_offset;+ let top = rect.top + top_offset;+ let right = rect.right - right_offset;+ let bottom = rect.bottom - bottom_offset;+ let physical_size = size(DevicePixels(right - left), DevicePixels(bottom - top));+ Bounds {+ origin: logical_point(left as f32, top as f32, scale_factor),+ size: physical_size.to_pixels(scale_factor),+ }+}++fn retrieve_window_placement(+ hwnd: HWND,+ display: WindowsDisplay,+ initial_bounds: Bounds<Pixels>,+ border_offset: &WindowBorderOffset,+) -> Result<WINDOWPLACEMENT> {+ let mut placement = WINDOWPLACEMENT {+ length: std::mem::size_of::<WINDOWPLACEMENT>() as u32,+ ..Default::default()+ };+ unsafe { GetWindowPlacement(hwnd, &mut placement)? };+ // the bounds may be not inside the display+ let bounds = if display.check_given_bounds(initial_bounds) {+ initial_bounds+ } else {+ display.default_bounds()+ };+ // `bounds` is expressed in logical pixels for `display`, so it must be converted+ // to device pixels using that display's own scale factor. The window's current+ // scale factor can't be used here: `CreateWindowExW` was called with+ // `CW_USEDEFAULT`, so at this point the window may still be sitting on whichever+ // monitor Windows picked by default, which can have a different DPI than `display`+ // and would otherwise throw off the physical position (e.g. leaving the window+ // partially off-screen when moved to a monitor with a different scale factor).+ let bounds = bounds.to_device_pixels(display.scale_factor());+ placement.rcNormalPosition = calculate_window_rect(bounds, border_offset);+ Ok(placement)+}++fn dwm_set_window_composition_attribute(hwnd: HWND, backdrop_type: u32) {+ let mut version = unsafe { std::mem::zeroed() };+ let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };++ // DWMWA_SYSTEMBACKDROP_TYPE is available only on version 22621 or later+ // using SetWindowCompositionAttributeType as a fallback+ if !status.is_ok() || version.dwBuildNumber < 22621 {+ return;+ }++ unsafe {+ let result = DwmSetWindowAttribute(+ hwnd,+ DWMWA_SYSTEMBACKDROP_TYPE,+ &backdrop_type as *const _ as *const _,+ std::mem::size_of_val(&backdrop_type) as u32,+ );++ if !result.is_ok() {+ return;+ }+ }+}++fn set_window_composition_attribute(hwnd: HWND, color: Option<Color>, state: u32) {+ let mut version = unsafe { std::mem::zeroed() };+ let status = unsafe { windows::Wdk::System::SystemServices::RtlGetVersion(&mut version) };++ if !status.is_ok() || version.dwBuildNumber < 17763 {+ return;+ }++ unsafe {+ type SetWindowCompositionAttributeType =+ unsafe extern "system" fn(HWND, *mut WINDOWCOMPOSITIONATTRIBDATA) -> BOOL;+ let module_name = PCSTR::from_raw(c"user32.dll".as_ptr() as *const u8);+ if let Some(user32) = GetModuleHandleA(module_name)+ .context("Unable to get user32.dll handle")+ .log_err()+ {+ let func_name = PCSTR::from_raw(c"SetWindowCompositionAttribute".as_ptr() as *const u8);+ let Some(raw_set_window_composition_attribute) = GetProcAddress(user32, func_name)+ else {+ return;+ };+ let set_window_composition_attribute: SetWindowCompositionAttributeType =+ std::mem::transmute(raw_set_window_composition_attribute);+ let mut color = color.unwrap_or_default();+ let is_acrylic = state == 4;+ if is_acrylic && color.3 == 0 {+ color.3 = 1;+ }+ let accent = AccentPolicy {+ accent_state: state,+ accent_flags: if is_acrylic { 0 } else { 2 },+ gradient_color: (color.0 as u32)+ | ((color.1 as u32) << 8)+ | ((color.2 as u32) << 16)+ | ((color.3 as u32) << 24),+ animation_id: 0,+ };+ let mut data = WINDOWCOMPOSITIONATTRIBDATA {+ attrib: 0x13,+ pv_data: &accent as *const _ as *mut _,+ cb_data: std::mem::size_of::<AccentPolicy>(),+ };+ let _ = set_window_composition_attribute(hwnd, &mut data as *mut _ as _);+ }+ }+}++// When the platform title bar is hidden, Windows may think that our application is meant to appear 'fullscreen'+// and will stop the taskbar from appearing on top of our window. Prevent this.+// https://devblogs.microsoft.com/oldnewthing/20250522-00/?p=111211+fn set_non_rude_hwnd(hwnd: HWND, non_rude: bool) {+ if non_rude {+ unsafe { SetPropW(hwnd, w!("NonRudeHWND"), Some(HANDLE(1 as _))) }.log_err();+ } else {+ unsafe { RemovePropW(hwnd, w!("NonRudeHWND")) }.log_err();+ }+}++#[cfg(test)]+mod tests {+ use super::ClickState;+ use gpui::{DevicePixels, MouseButton, point};+ use std::time::Duration;++ #[test]+ fn test_double_click_interval() {+ let state = ClickState::new();+ assert_eq!(+ state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),+ 1+ );+ assert_eq!(+ state.update(MouseButton::Right, point(DevicePixels(0), DevicePixels(0))),+ 1+ );+ assert_eq!(+ state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),+ 1+ );+ assert_eq!(+ state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),+ 2+ );+ state+ .last_click+ .update(|it| it - Duration::from_millis(700));+ assert_eq!(+ state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(0))),+ 1+ );+ }++ #[test]+ fn test_double_click_spatial_tolerance() {+ let state = ClickState::new();+ assert_eq!(+ state.update(MouseButton::Left, point(DevicePixels(-3), DevicePixels(0))),+ 1+ );+ assert_eq!(+ state.update(MouseButton::Left, point(DevicePixels(0), DevicePixels(3))),+ 2+ );+ assert_eq!(+ state.update(MouseButton::Right, point(DevicePixels(3), DevicePixels(2))),+ 1+ );+ assert_eq!(+ state.update(MouseButton::Right, point(DevicePixels(10), DevicePixels(0))),+ 1+ );+ }+}diff --git a/native/vendor/wu/crates/gpui_windows/src/wrapper.rs b/native/vendor/wu/crates/gpui_windows/src/wrapper.rsnew file mode 100644index 00000000000..60bbc433cab--- /dev/null+++ b/native/vendor/wu/crates/gpui_windows/src/wrapper.rs@@ -0,0 +1,53 @@+use std::ops::Deref;++use windows::Win32::{Foundation::HWND, UI::WindowsAndMessaging::HCURSOR};++#[derive(Debug, Clone, Copy)]+pub(crate) struct SafeCursor {+ raw: HCURSOR,+}++unsafe impl Send for SafeCursor {}+unsafe impl Sync for SafeCursor {}++impl From<HCURSOR> for SafeCursor {+ fn from(value: HCURSOR) -> Self {+ SafeCursor { raw: value }+ }+}++impl Deref for SafeCursor {+ type Target = HCURSOR;++ fn deref(&self) -> &Self::Target {+ &self.raw+ }+}++#[derive(Debug, Clone, Copy)]+pub(crate) struct SafeHwnd {+ raw: HWND,+}++impl SafeHwnd {+ pub(crate) fn as_raw(&self) -> HWND {+ self.raw+ }+}++unsafe impl Send for SafeHwnd {}+unsafe impl Sync for SafeHwnd {}++impl From<HWND> for SafeHwnd {+ fn from(value: HWND) -> Self {+ SafeHwnd { raw: value }+ }+}++impl Deref for SafeHwnd {+ type Target = HWND;++ fn deref(&self) -> &Self::Target {+ &self.raw+ }+}diff --git a/port/ledger.md b/port/ledger.mdindex 7f88d1d464b..9d3c178edb2 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -71,7 +71,7 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,| M24 Windows | app/src/terminal/profiles.rs:133 | open | [windows M] Windows terminal profiles (terminalProfiles.ts `detectAvailableWindowsProfiles`): PowerShell (pwsh, then Windows PowerShell), Command Prompt, Git Bash, WSL distributions; `terminal.integrated.defaultProfile.windows`; shell integration for pwsh (shellIntegration.ps1). | `cargo gc test -p app terminal::profiles` on the windows runner || M24 Windows | app/src/file_dialog.rs:9 | in progress | [windows M] Win32 open and save dialogs (file_dialog/windows.rs, IFileOpenDialog, IFileSaveDialog) with title, button label (`&` mnemonic), filters, default path, folder pick and multi-select, as Electron's file_dialog_win.cc `ApplySettings` and `ConvertFilters` (filter specs `*.ts;*.js`, `All Files (*.*)`, the first specific filter selected), owned by the active window, with dialogMainService.ts's lock (shared with macOS). Built, not yet run on Windows. | `cargo gc test -p app file_dialog` on the host: `windows_filters_become_semicolon_specs_and_the_first_specific_one_is_selected`, `one_dialog_of_the_same_options_per_window`; [windows] the dialog on the windows runner || M24 Windows | app/src/dialog.rs:5 | in progress | [windows M] native message box through TaskDialogIndirect (dialog/windows.rs), as Electron's message_box_win.cc with `noLink`: buttons in the order dialogs.ts `massageMessageBoxOptions` gives Windows (the caller's, cancel last) with `&` mnemonics, the message as main instruction above a detail, the checkbox as the verification text, owner window modal, Esc and the close button answer cancel. Common Controls 6 comes from GPUI's manifest (`windows-manifest`). Built, not yet run on Windows. | `cargo gc test -p app dialog::tests` on the host: `windows_labels_take_ampersand_mnemonics`, `windows_task_dialog_keeps_the_callers_button_order_with_cancel_last`, `windows_task_dialog_message_is_the_main_instruction_only_with_a_detail`; [windows] the dialog on the windows runner |-| M24 Windows | app/src/webview.rs:11 | open | [windows L] webviews through WebView2 (webview2-com, decision "Windows webview") as child windows of GPUI's HWND, with the host page, resource scheme and message bridge `webview.rs` shares with macOS and Linux: panels and views, editor insets, notebook outputs, extension details, release notes. The WebView2 runtime ships with Windows 10 and 11. | `FIXTURE=webview-tests` smoke on the windows runner; `cargo gc test -p app webview` there |+| M24 Windows | app/src/webview.rs:11 | in progress | [windows L] webviews through WebView2 (webview2-com, decision "Windows webview") as child windows of GPUI's HWND (webview/windows.rs), with the host page, resource scheme and message bridge `webview.rs` shares with macOS and Linux: panels and views, editor insets, notebook outputs, extension details, release notes. The WebView2 runtime ships with Windows 10 and 11. GPUI's DirectComposition target is not topmost (vendored `gpui_windows`, port/notes.md milestone 24 "Webview"). Built, not yet run on Windows. | `cargo gc test -p app splits_https_urls` on the host; [windows] `FIXTURE=webview-tests` smoke on the windows runner; `cargo gc test -p app webview` there || M24 Windows | exthost/src/lib.rs:31 | open | [windows L] extension host connection over a named pipe (`\\.\pipe\vscode-ipc-<uuid>-sock`, ipc.net.ts `createRandomIPCHandle` on Windows) instead of a Unix socket; Bun's `net.connect` takes the pipe path. | `cargo gc test -p exthost` on the windows runner: the handshake test || M24 Windows | app/src/launch.rs:5 | open | [windows M] single instance and second-instance arguments over a named pipe (main.ts `mainIPCHandle` on Windows). | `cargo gc test -p app launch` on the windows runner || M24 Windows | app/src/cli.rs:7 | in progress | [windows M] the command line on Windows: `bin\<applicationName>.cmd` from resources/win32/bin/code.cmd, stdin read and terminal width through the console API. | `cargo gc test -p app cli` on the windows runner |diff --git a/port/notes.md b/port/notes.mdindex 4f837173403..a3a80b63081 100644--- a/port/notes.md+++ b/port/notes.md@@ -1012,6 +1012,7 @@ What to do (milestone 21, in order):- Layout: as milestone 23, with `cfg(target_os = "windows")` beside the macOS and Linux code and a `windows.rs` beside `macos.rs` and `linux.rs` where the split is large; Windows gaps are the "M24 Windows" rows of the Work table in port/ledger.md, sized `[windows S|M|L]`.- 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.## Accepted platform differences