Code at the speed of thought – Zed is a high-performance, multiplayer code editor from the creators of Atom and Tree-sitter.
gpui_web: Fix some bugs (#61707)
Lukas Wirthc97b7c0ea41a
diff --git a/Cargo.lock b/Cargo.lockindex 0bf1f8a61cf..ebc0bcebc8d 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -8032,7 +8032,6 @@ dependencies = ["log","parking_lot","raw-window-handle",- "smallvec","uuid","wasm-bindgen","wasm-bindgen-futures",diff --git a/Cargo.toml b/Cargo.tomlindex 4056f9d568a..6c1a3251abd 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -886,6 +886,9 @@ wasmtime-wasi = "36"wax = "0.7"which = "6.0.0"wasm-bindgen = "0.2.120"+wasm-bindgen-futures = "0.4"+js-sys = "0.3"+console_error_panic_hook = "0.1.7"web-time = "1.1.0"webrtc-sys = "0.3.23"wgpu = "29.0.4"diff --git a/crates/gpui_platform/Cargo.toml b/crates/gpui_platform/Cargo.tomlindex 22d44a96b21..a41cb176722 100644--- a/crates/gpui_platform/Cargo.toml+++ b/crates/gpui_platform/Cargo.toml@@ -35,4 +35,4 @@ gpui_linux.workspace = true[target.'cfg(target_family = "wasm")'.dependencies]gpui_web.workspace = true-console_error_panic_hook = "0.1.7"+console_error_panic_hook.workspace = truediff --git a/crates/gpui_web/Cargo.toml b/crates/gpui_web/Cargo.tomlindex 45420bf880f..a29ca340607 100644--- a/crates/gpui_web/Cargo.toml+++ b/crates/gpui_web/Cargo.toml@@ -24,13 +24,12 @@ http_client.workspace = trueanyhow.workspace = truefutures.workspace = truelog.workspace = true-smallvec.workspace = trueuuid.workspace = truewasm-bindgen.workspace = true-wasm-bindgen-futures = "0.4"+wasm-bindgen-futures.workspace = trueweb-time.workspace = true-console_error_panic_hook = "0.1.7"-js-sys = "0.3"+console_error_panic_hook.workspace = true+js-sys.workspace = trueraw-window-handle.workspace = truewasm_thread = { version = "0.3", features = ["es_modules"], optional = true }web-sys = { version = "0.3", features = [@@ -45,8 +44,6 @@ web-sys = { version = "0.3", features = ["DragEvent","Element","EventTarget",- "File",- "FileList","HtmlCanvasElement","HtmlElement","HtmlInputElement",diff --git a/crates/gpui_web/src/dispatcher.rs b/crates/gpui_web/src/dispatcher.rsindex 9bcacbdecb5..58b921dfbcb 100644--- a/crates/gpui_web/src/dispatcher.rs+++ b/crates/gpui_web/src/dispatcher.rs@@ -10,7 +10,6 @@ use web_time::Instant;#[cfg(feature = "multithreaded")]const MIN_BACKGROUND_THREADS: usize = 2;-#[cfg(feature = "multithreaded")]fn shared_memory_supported() -> bool {let global = js_sys::global();let has_shared_array_buffer =@@ -90,6 +89,11 @@ impl MainThreadMailbox {loop {js_sys::Atomics::store(&view, 0, 0).expect("Atomics.store failed");+ // Items posted between the previous drain and the store above+ // set the signal we just cleared, so their notify is lost.+ // Drain again after re-arming to avoid missing them.+ mailbox.drain(&window);+let result = match js_sys::Atomics::wait_async(&view, 0, 0) {Ok(result) => result,Err(error) => {@@ -103,17 +107,17 @@ impl MainThreadMailbox {.and_then(|v| v.as_bool()).unwrap_or(false);- if !is_async {- log::error!("Atomics.waitAsync returned synchronously; waker loop exiting");- break;- }-- let promise: js_sys::Promise =- js_sys::Reflect::get(&result, &JsValue::from_str("value"))- .expect("waitAsync result missing 'value'")- .unchecked_into();+ // `async: false` means the signal changed between the store and+ // the wait ("not-equal"): work has already arrived, so skip+ // waiting and drain immediately.+ if is_async {+ let promise: js_sys::Promise =+ js_sys::Reflect::get(&result, &JsValue::from_str("value"))+ .expect("waitAsync result missing 'value'")+ .unchecked_into();- let _ = wasm_bindgen_futures::JsFuture::from(promise).await;+ let _ = wasm_bindgen_futures::JsFuture::from(promise).await;+ }mailbox.drain(&window);}@@ -145,14 +149,12 @@ impl WebDispatcher {let main_thread_mailbox = Arc::new(MainThreadMailbox::new());- #[cfg(feature = "multithreaded")]- let supports_threads = allow_threads && shared_memory_supported();- #[cfg(not(feature = "multithreaded"))]- let supports_threads = false;+ let supports_threads =+ cfg!(feature = "multithreaded") && allow_threads && shared_memory_supported();if supports_threads {main_thread_mailbox.run_waker_loop(browser_window.clone());- } else {+ } else if cfg!(feature = "multithreaded") && allow_threads {log::warn!("SharedArrayBuffer not available; falling back to single-threaded dispatcher");diff --git a/crates/gpui_web/src/display.rs b/crates/gpui_web/src/display.rsindex 5023e7de33e..aaf70c67b5f 100644--- a/crates/gpui_web/src/display.rs+++ b/crates/gpui_web/src/display.rs@@ -8,7 +8,10 @@ pub struct WebDisplay {browser_window: web_sys::Window,}-// Safety: WASM is single-threaded — there is no concurrent access to `web_sys::Window`.+// Safety: `web_sys::Window` is only accessed from the main thread. Displays+// are handed out as `Rc<dyn PlatformDisplay>` and read by GPUI on the+// foreground thread; background worker threads (when the `multithreaded`+// feature is enabled) never touch them.unsafe impl Send for WebDisplay {}unsafe impl Sync for WebDisplay {}diff --git a/crates/gpui_web/src/events.rs b/crates/gpui_web/src/events.rsindex 08434aada41..471732671e1 100644--- a/crates/gpui_web/src/events.rs+++ b/crates/gpui_web/src/events.rs@@ -1,19 +1,86 @@use std::rc::Rc;use gpui::{- Capslock, DispatchEventResult, ExternalPaths, FileDropEvent, KeyDownEvent, KeyUpEvent,- Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseExitEvent,- MouseMoveEvent, MouseUpEvent, NavigationDirection, Pixels, PlatformInput, Point, ScrollDelta,- ScrollWheelEvent, TouchPhase, point, px,+ Capslock, DispatchEventResult, KeyDownEvent, KeyUpEvent, Keystroke, Modifiers,+ ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseExitEvent, MouseMoveEvent,+ MouseUpEvent, NavigationDirection, Pixels, PlatformInput, Point, ScrollDelta, ScrollWheelEvent,+ TouchPhase, point, px,};-use smallvec::smallvec;use wasm_bindgen::prelude::*;use crate::window::WebWindowInner;pub struct WebEventListeners {- #[allow(dead_code)]- closures: Vec<Closure<dyn FnMut(JsValue)>>,+ _handles: Vec<EventListenerHandle>,+}++/// A DOM event listener that is removed from its target when dropped.+///+/// Dropping the `Closure` alone would leave the listener attached to the DOM+/// pointing at a freed function; the next event would then throw "closure+/// invoked after being dropped". Keeping the target alongside the closure+/// lets `Drop` unregister the listener first.+pub(crate) struct EventListenerHandle {+ target: web_sys::EventTarget,+ event_name: &'static str,+ closure: Closure<dyn FnMut(JsValue)>,+}++impl EventListenerHandle {+ pub(crate) fn add(+ target: &web_sys::EventTarget,+ event_name: &'static str,+ handler: impl FnMut(JsValue) + 'static,+ ) -> Self {+ let closure = Closure::<dyn FnMut(JsValue)>::new(handler);+ target+ .add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())+ .ok();+ Self {+ target: target.clone(),+ event_name,+ closure,+ }+ }++ /// Registers with `{passive: false}` so that `preventDefault()` works.+ /// Needed for events like `wheel` which are passive by default in modern+ /// browsers. Removal does not need to match the `passive` option, so+ /// `Drop` works the same as for [`EventListenerHandle::add`].+ fn add_non_passive(+ target: &web_sys::EventTarget,+ event_name: &'static str,+ handler: impl FnMut(JsValue) + 'static,+ ) -> Self {+ let closure = Closure::<dyn FnMut(JsValue)>::new(handler);+ let target_js: &JsValue = target.as_ref();+ let callback_js: &JsValue = closure.as_ref();+ let options = js_sys::Object::new();+ js_sys::Reflect::set(&options, &"passive".into(), &false.into()).ok();+ if let Ok(add_fn_val) = js_sys::Reflect::get(target_js, &"addEventListener".into()) {+ if let Ok(add_fn) = add_fn_val.dyn_into::<js_sys::Function>() {+ add_fn+ .call3(target_js, &event_name.into(), callback_js, &options)+ .ok();+ }+ }+ Self {+ target: target.clone(),+ event_name,+ closure,+ }+ }+}++impl Drop for EventListenerHandle {+ fn drop(&mut self) {+ self.target+ .remove_event_listener_with_callback(+ self.event_name,+ self.closure.as_ref().unchecked_ref(),+ )+ .ok();+ }}pub(crate) struct ClickState {@@ -52,7 +119,7 @@ impl ClickState {impl WebWindowInner {pub fn register_event_listeners(self: &Rc<Self>) -> WebEventListeners {- let mut closures = vec![+ let mut handles = vec![self.register_pointer_down(),self.register_pointer_up(),self.register_pointer_move(),@@ -61,7 +128,6 @@ impl WebWindowInner {self.register_context_menu(),self.register_dragover(),self.register_drop(),- self.register_dragleave(),self.register_key_down(),self.register_key_up(),self.register_paste(),@@ -71,72 +137,66 @@ impl WebWindowInner {self.register_focus(),self.register_blur(),self.register_pointer_enter(),- self.register_pointer_leave_hover(),];- closures.extend(self.register_visibility_change());- closures.extend(self.register_appearance_change());+ handles.extend(self.register_visibility_change());+ handles.extend(self.register_appearance_change());+ handles.extend(self.register_fullscreen_change());- WebEventListeners { closures }+ WebEventListeners { _handles: handles }}fn listen(self: &Rc<Self>,- event_name: &str,+ event_name: &'static str,handler: impl FnMut(JsValue) + 'static,- ) -> Closure<dyn FnMut(JsValue)> {- let closure = Closure::<dyn FnMut(JsValue)>::new(handler);- self.canvas- .add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())- .ok();- closure+ ) -> EventListenerHandle {+ EventListenerHandle::add(self.canvas.as_ref(), event_name, handler)}fn listen_input(self: &Rc<Self>,- event_name: &str,+ event_name: &'static str,handler: impl FnMut(JsValue) + 'static,- ) -> Closure<dyn FnMut(JsValue)> {- let closure = Closure::<dyn FnMut(JsValue)>::new(handler);- self.input_element- .add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())- .ok();- closure+ ) -> EventListenerHandle {+ EventListenerHandle::add(self.input_element.as_ref(), event_name, handler)}- /// Registers a listener with `{passive: false}` so that `preventDefault()` works.- /// Needed for events like `wheel` which are passive by default in modern browsers.fn listen_non_passive(self: &Rc<Self>,- event_name: &str,+ event_name: &'static str,handler: impl FnMut(JsValue) + 'static,- ) -> Closure<dyn FnMut(JsValue)> {- let closure = Closure::<dyn FnMut(JsValue)>::new(handler);- let canvas_js: &JsValue = self.canvas.as_ref();- let callback_js: &JsValue = closure.as_ref();- let options = js_sys::Object::new();- js_sys::Reflect::set(&options, &"passive".into(), &false.into()).ok();- if let Ok(add_fn_val) = js_sys::Reflect::get(canvas_js, &"addEventListener".into()) {- if let Ok(add_fn) = add_fn_val.dyn_into::<js_sys::Function>() {- add_fn- .call3(canvas_js, &event_name.into(), callback_js, &options)- .ok();- }- }- closure+ ) -> EventListenerHandle {+ EventListenerHandle::add_non_passive(self.canvas.as_ref(), event_name, handler)}fn dispatch_input(&self, input: PlatformInput) -> Option<DispatchEventResult> {- let mut borrowed = self.callbacks.borrow_mut();- borrowed.input.as_mut().map(|callback| callback(input))+ self.with_callback(|callbacks| &mut callbacks.input, |callback| callback(input))+ }++ /// Records the latest modifier state and reports whether it changed, so+ /// that `ModifiersChanged` is only dispatched on actual transitions+ /// rather than for every key event.+ fn update_modifiers(&self, modifiers: Modifiers, capslock: Capslock) -> bool {+ let mut current_state = self.state.borrow_mut();+ let changed = current_state.modifiers != modifiers || current_state.capslock != capslock;+ current_state.modifiers = modifiers;+ current_state.capslock = capslock;+ changed}- fn register_pointer_down(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_pointer_down(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen("pointerdown", move |event: JsValue| {let event: web_sys::PointerEvent = event.unchecked_into();event.prevent_default();this.input_element.focus().ok();+ // Capture the pointer so drags that leave the canvas keep+ // delivering pointermove/pointerup here; otherwise a release+ // outside the canvas is never seen and `pressed_button` stays+ // stuck. The capture is released implicitly on pointerup.+ this.canvas.set_pointer_capture(event.pointer_id()).ok();+let button = dom_mouse_button_to_gpui(event.button());let position = pointer_position_in_element(&event);let modifiers = modifiers_from_mouse_event(&event, this.is_mac);@@ -161,7 +221,7 @@ impl WebWindowInner {})}- fn register_pointer_up(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_pointer_up(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen("pointerup", move |event: JsValue| {let event: web_sys::PointerEvent = event.unchecked_into();@@ -189,7 +249,7 @@ impl WebWindowInner {})}- fn register_pointer_move(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_pointer_move(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen("pointermove", move |event: JsValue| {let event: web_sys::PointerEvent = event.unchecked_into();@@ -213,7 +273,7 @@ impl WebWindowInner {})}- fn register_pointer_leave(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_pointer_leave(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen("pointerleave", move |event: JsValue| {let event: web_sys::PointerEvent = event.unchecked_into();@@ -226,6 +286,7 @@ impl WebWindowInner {let mut current_state = this.state.borrow_mut();current_state.mouse_position = position;current_state.modifiers = modifiers;+ current_state.is_hovered = false;}this.dispatch_input(PlatformInput::MouseExited(MouseExitEvent {@@ -233,10 +294,15 @@ impl WebWindowInner {pressed_button: current_pressed,modifiers,}));++ this.with_callback(+ |callbacks| &mut callbacks.hover_status_change,+ |callback| callback(false),+ );})}- fn register_wheel(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_wheel(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen_non_passive("wheel", move |event: JsValue| {let event: web_sys::WheelEvent = event.unchecked_into();@@ -270,64 +336,34 @@ impl WebWindowInner {})}- fn register_context_menu(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_context_menu(self: &Rc<Self>) -> EventListenerHandle {self.listen("contextmenu", move |event: JsValue| {let event: web_sys::Event = event.unchecked_into();event.prevent_default();})}- fn register_dragover(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {- let this = Rc::clone(self);+ /// Browsers only expose dropped files as `File` objects, never as+ /// filesystem paths, so no `FileDrop` input can be synthesized: GPUI's+ /// `ExternalPaths` consumers would try to read paths that don't exist.+ /// The events are still intercepted so the browser doesn't navigate to+ /// the dropped file. Delivering actual file drops would require plumbing+ /// `File` contents through a web-specific channel.+ fn register_dragover(self: &Rc<Self>) -> EventListenerHandle {self.listen("dragover", move |event: JsValue| {let event: web_sys::DragEvent = event.unchecked_into();event.prevent_default();-- let mouse_event: &web_sys::MouseEvent = event.as_ref();- let position = mouse_position_in_element(mouse_event);-- {- let mut current_state = this.state.borrow_mut();- current_state.mouse_position = position;- }-- this.dispatch_input(PlatformInput::FileDrop(FileDropEvent::Pending { position }));})}- fn register_drop(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {- let this = Rc::clone(self);+ fn register_drop(self: &Rc<Self>) -> EventListenerHandle {self.listen("drop", move |event: JsValue| {let event: web_sys::DragEvent = event.unchecked_into();event.prevent_default();-- let mouse_event: &web_sys::MouseEvent = event.as_ref();- let position = mouse_position_in_element(mouse_event);-- {- let mut current_state = this.state.borrow_mut();- current_state.mouse_position = position;- }-- let paths = extract_file_paths_from_drag(&event);-- this.dispatch_input(PlatformInput::FileDrop(FileDropEvent::Entered {- position,- paths: ExternalPaths(paths),- }));-- this.dispatch_input(PlatformInput::FileDrop(FileDropEvent::Submit { position }));- })- }-- fn register_dragleave(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {- let this = Rc::clone(self);- self.listen("dragleave", move |_event: JsValue| {- this.dispatch_input(PlatformInput::FileDrop(FileDropEvent::Exited));})}- fn register_key_down(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_key_down(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen_input("keydown", move |event: JsValue| {let event: web_sys::KeyboardEvent = event.unchecked_into();@@ -335,17 +371,13 @@ impl WebWindowInner {let modifiers = modifiers_from_keyboard_event(&event, this.is_mac);let capslock = capslock_from_keyboard_event(&event);- {- let mut current_state = this.state.borrow_mut();- current_state.modifiers = modifiers;- current_state.capslock = capslock;+ if this.update_modifiers(modifiers, capslock) {+ this.dispatch_input(PlatformInput::ModifiersChanged(ModifiersChangedEvent {+ modifiers,+ capslock,+ }));}- this.dispatch_input(PlatformInput::ModifiersChanged(ModifiersChangedEvent {- modifiers,- capslock,- }));-let key = dom_key_to_gpui_key(&event);if is_modifier_only_key(&key) {@@ -379,22 +411,22 @@ impl WebWindowInner {return;}- if modifiers.is_subset_of(&Modifiers::shift()) {- if let Some(text) = key_char {- this.with_input_handler(|handler| {- handler.replace_text_in_range(None, &text);- });- // The character went into the input handler; suppress browser- // side-effects for the same keystroke (space scrolling the- // page, quick-find, etc.). Everything not handled above falls- // through so browser shortcuts keep their defaults.- event.prevent_default();- }+ if keystroke_inserts_text(&modifiers, this.is_mac)+ && let Some(text) = key_char+ {+ this.with_input_handler(|handler| {+ handler.replace_text_in_range(None, &text);+ });+ // The character went into the input handler; suppress browser+ // side-effects for the same keystroke (space scrolling the+ // page, quick-find, etc.). Everything not handled above falls+ // through so browser shortcuts keep their defaults.+ event.prevent_default();}})}- fn register_key_up(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_key_up(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen_input("keyup", move |event: JsValue| {let event: web_sys::KeyboardEvent = event.unchecked_into();@@ -402,17 +434,13 @@ impl WebWindowInner {let modifiers = modifiers_from_keyboard_event(&event, this.is_mac);let capslock = capslock_from_keyboard_event(&event);- {- let mut current_state = this.state.borrow_mut();- current_state.modifiers = modifiers;- current_state.capslock = capslock;+ if this.update_modifiers(modifiers, capslock) {+ this.dispatch_input(PlatformInput::ModifiersChanged(ModifiersChangedEvent {+ modifiers,+ capslock,+ }));}- this.dispatch_input(PlatformInput::ModifiersChanged(ModifiersChangedEvent {- modifiers,- capslock,- }));-let key = dom_key_to_gpui_key(&event);if is_modifier_only_key(&key) {@@ -441,7 +469,7 @@ impl WebWindowInner {/// read API cannot fit that synchronous signature, while `ClipboardEvent`/// exposes `clipboardData` synchronously inside the event. It fires for/// any browser-initiated paste (keyboard, menu bar, context menu).- fn register_paste(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_paste(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen_input("paste", move |event: JsValue| {let event: web_sys::ClipboardEvent = event.unchecked_into();@@ -462,14 +490,14 @@ impl WebWindowInner {})}- fn register_composition_start(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_composition_start(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen_input("compositionstart", move |_event: JsValue| {this.is_composing.set(true);})}- fn register_composition_update(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_composition_update(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen_input("compositionupdate", move |event: JsValue| {let event: web_sys::CompositionEvent = event.unchecked_into();@@ -481,7 +509,7 @@ impl WebWindowInner {})}- fn register_composition_end(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_composition_end(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen_input("compositionend", move |event: JsValue| {let event: web_sys::CompositionEvent = event.unchecked_into();@@ -495,59 +523,45 @@ impl WebWindowInner {})}- fn register_focus(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_focus(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen_input("focus", move |_event: JsValue| {{let mut state = this.state.borrow_mut();state.is_active = true;}- let mut callbacks = this.callbacks.borrow_mut();- if let Some(ref mut callback) = callbacks.active_status_change {- callback(true);- }+ this.with_callback(+ |callbacks| &mut callbacks.active_status_change,+ |callback| callback(true),+ );})}- fn register_blur(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_blur(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen_input("blur", move |_event: JsValue| {{let mut state = this.state.borrow_mut();state.is_active = false;}- let mut callbacks = this.callbacks.borrow_mut();- if let Some(ref mut callback) = callbacks.active_status_change {- callback(false);- }+ this.with_callback(+ |callbacks| &mut callbacks.active_status_change,+ |callback| callback(false),+ );})}- fn register_pointer_enter(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {+ fn register_pointer_enter(self: &Rc<Self>) -> EventListenerHandle {let this = Rc::clone(self);self.listen("pointerenter", move |_event: JsValue| {{let mut state = this.state.borrow_mut();state.is_hovered = true;}- let mut callbacks = this.callbacks.borrow_mut();- if let Some(ref mut callback) = callbacks.hover_status_change {- callback(true);- }- })- }-- fn register_pointer_leave_hover(self: &Rc<Self>) -> Closure<dyn FnMut(JsValue)> {- let this = Rc::clone(self);- self.listen("pointerleave", move |_event: JsValue| {- {- let mut state = this.state.borrow_mut();- state.is_hovered = false;- }- let mut callbacks = this.callbacks.borrow_mut();- if let Some(ref mut callback) = callbacks.hover_status_change {- callback(false);- }+ this.with_callback(+ |callbacks| &mut callbacks.hover_status_change,+ |callback| callback(true),+ );})}}@@ -661,12 +675,28 @@ fn is_modifier_only_key(key: &str) -> bool {)}+/// Whether a keystroke with these modifiers produces text to insert.+///+/// On macOS, Option participates in text entry (e.g. option-n composes "~"+/// or accented characters), so only Command and Control disqualify. Elsewhere,+/// plain Alt is a shortcut modifier, but AltGr is reported by browsers as+/// control+alt and `event.key()` then carries the composed character.+fn keystroke_inserts_text(modifiers: &Modifiers, is_mac: bool) -> bool {+ if is_mac {+ !modifiers.platform && !modifiers.control+ } else {+ modifiers.is_subset_of(&Modifiers::shift()) || (modifiers.control && modifiers.alt)+ }+}+fn compute_key_char(event: &web_sys::KeyboardEvent,gpui_key: &str,modifiers: &Modifiers,) -> Option<String> {- if modifiers.platform || modifiers.control {+ // AltGr arrives as control+alt with the composed character in+ // `event.key()`; bare Command/Control combinations are not text.+ if (modifiers.platform || modifiers.control) && !(modifiers.control && modifiers.alt) {return None;}@@ -696,22 +726,3 @@ fn mouse_position_in_element(event: &web_sys::MouseEvent) -> Point<Pixels> {// offset_x/offset_y give position relative to the target element's padding edgepoint(px(event.offset_x() as f32), px(event.offset_y() as f32))}--fn extract_file_paths_from_drag(- event: &web_sys::DragEvent,-) -> smallvec::SmallVec<[std::path::PathBuf; 2]> {- let mut paths = smallvec![];- let Some(data_transfer) = event.data_transfer() else {- return paths;- };- let file_list = data_transfer.files();- let Some(files) = file_list else {- return paths;- };- for index in 0..files.length() {- if let Some(file) = files.get(index) {- paths.push(std::path::PathBuf::from(file.name()));- }- }- paths-}diff --git a/crates/gpui_web/src/http_client.rs b/crates/gpui_web/src/http_client.rsindex 2ea7a388d6b..f48746d088c 100644--- a/crates/gpui_web/src/http_client.rs+++ b/crates/gpui_web/src/http_client.rs@@ -30,16 +30,16 @@ pub enum FetchCredentials {Include,}-impl Default for FetchHttpClient {- fn default() -> Self {+impl FetchHttpClient {+ // Kept private so that all construction goes through the constructors+ // below, which are `unsafe` when background threads are enabled.+ fn build(user_agent: Option<http_client::http::header::HeaderValue>) -> Self {Self {- user_agent: None,+ user_agent,credentials: FetchCredentials::default(),}}-}-impl FetchHttpClient {pub fn with_credentials(mut self, credentials: FetchCredentials) -> Self {self.credentials = credentials;self@@ -50,46 +50,46 @@ impl FetchHttpClient {impl FetchHttpClient {/// # Safety///- /// The caller must ensure that the created `FetchHttpClient` is only used in a single thread environment.+ /// The caller must ensure the client is only used from the main thread:+ /// the futures returned by [`HttpClient::send`] call browser APIs that do+ /// not exist on worker threads, so they must never be polled from a task+ /// spawned on the background executor.pub unsafe fn new() -> Self {- Self::default()+ Self::build(None)}/// # Safety///- /// The caller must ensure that the created `FetchHttpClient` is only used in a single thread environment.+ /// The caller must ensure the client is only used from the main thread:+ /// the futures returned by [`HttpClient::send`] call browser APIs that do+ /// not exist on worker threads, so they must never be polled from a task+ /// spawned on the background executor.pub unsafe fn with_user_agent(user_agent: &str) -> anyhow::Result<Self> {- Ok(Self {- user_agent: Some(http_client::http::header::HeaderValue::from_str(- user_agent,- )?),- credentials: FetchCredentials::default(),- })+ Ok(Self::build(Some(+ http_client::http::header::HeaderValue::from_str(user_agent)?,+ )))}}#[cfg(not(feature = "multithreaded"))]impl FetchHttpClient {pub fn new() -> Self {- Self::default()+ Self::build(None)}pub fn with_user_agent(user_agent: &str) -> anyhow::Result<Self> {- Ok(Self {- user_agent: Some(http_client::http::header::HeaderValue::from_str(- user_agent,- )?),- credentials: FetchCredentials::default(),- })+ Ok(Self::build(Some(+ http_client::http::header::HeaderValue::from_str(user_agent)?,+ )))}}/// Wraps a `!Send` future to satisfy the `Send` bound on `BoxFuture`.///-/// Safety: only valid in WASM contexts where the `FetchHttpClient` is-/// confined to a single thread (guaranteed by the caller via unsafe-/// constructors when `multithreaded` is enabled, or by the absence of-/// threads when it is not).+/// Safety: only valid because the `FetchHttpClient` constructors confine the+/// client to the main thread (via their `unsafe` contract when+/// `multithreaded` is enabled, or by the absence of threads when it is not),+/// so the wrapped future is never actually sent across threads.struct AssertSend<F>(F);unsafe impl<F> Send for AssertSend<F> {}diff --git a/crates/gpui_web/src/keyboard.rs b/crates/gpui_web/src/keyboard.rsindex 0ab4f7aa4ac..51ed113c8c4 100644--- a/crates/gpui_web/src/keyboard.rs+++ b/crates/gpui_web/src/keyboard.rs@@ -2,12 +2,6 @@ use gpui::PlatformKeyboardLayout;pub struct WebKeyboardLayout;-impl WebKeyboardLayout {- pub fn new() -> Self {- WebKeyboardLayout- }-}-impl PlatformKeyboardLayout for WebKeyboardLayout {fn id(&self) -> &str {"us"diff --git a/crates/gpui_web/src/logging.rs b/crates/gpui_web/src/logging.rsindex 773118eeb25..09aaab08d51 100644--- a/crates/gpui_web/src/logging.rs+++ b/crates/gpui_web/src/logging.rs@@ -32,6 +32,14 @@ impl Log for ConsoleLogger {}pub fn init_logging() {+ // Without this hook, panics abort with an opaque "unreachable executed"+ // in the browser console instead of a message and backtrace.+ console_error_panic_hook::set_once();+log::set_logger(&ConsoleLogger).ok();- log::set_max_level(log::LevelFilter::Info);+ log::set_max_level(if cfg!(debug_assertions) {+ log::LevelFilter::Debug+ } else {+ log::LevelFilter::Info+ });}diff --git a/crates/gpui_web/src/platform.rs b/crates/gpui_web/src/platform.rsindex f70520d629d..bec68aaf6f0 100644--- a/crates/gpui_web/src/platform.rs+++ b/crates/gpui_web/src/platform.rs@@ -1,5 +1,6 @@use crate::dispatcher::WebDispatcher;use crate::display::WebDisplay;+use crate::events::EventListenerHandle;use crate::keyboard::WebKeyboardLayout;use crate::window::WebWindow;use anyhow::Result;@@ -120,6 +121,7 @@ impl Platform for WebPlatform {fn run(&self, on_finish_launching: Box<dyn 'static + FnOnce()>) {let wgpu_context = self.wgpu_context.clone();+ let browser_window = self.browser_window.clone();wasm_bindgen_futures::spawn_local(async move {match WgpuContext::new_web().await {Ok(context) => {@@ -128,8 +130,11 @@ impl Platform for WebPlatform {on_finish_launching();}Err(err) => {+ // Without a GPU context nothing can ever render, so+ // launching the app would only produce confusing+ // downstream errors. Leave a message in the page instead.log::error!("Failed to initialize WebGPU context: {err:#}");- on_finish_launching();+ show_webgpu_unavailable_message(&browser_window);}}});@@ -381,23 +386,6 @@ impl Platform for WebPlatform {}}-struct EventListenerHandle {- target: web_sys::EventTarget,- event_name: &'static str,- closure: Closure<dyn FnMut(JsValue)>,-}--impl Drop for EventListenerHandle {- fn drop(&mut self) {- self.target- .remove_event_listener_with_callback(- self.event_name,- self.closure.as_ref().unchecked_ref(),- )- .ok();- }-}-fn cursor_restore_listeners(browser_window: &web_sys::Window,cursor_visible: Rc<Cell<bool>>,@@ -408,26 +396,19 @@ fn cursor_restore_listeners(return handles;};- let make_restore_handler = |browser_window: web_sys::Window| {+ let mut add_listener = |target: &web_sys::EventTarget, event_name: &'static str| {+ let browser_window = browser_window.clone();let cursor_visible = cursor_visible.clone();let last_cursor_css = last_cursor_css.clone();- Closure::<dyn FnMut(JsValue)>::new(move |_event: JsValue| {- if !cursor_visible.replace(true) {- set_body_cursor(&browser_window, last_cursor_css.get());- }- })- };-- let mut add_listener = |target: &web_sys::EventTarget, event_name: &'static str| {- let closure = make_restore_handler(browser_window.clone());- target- .add_event_listener_with_callback(event_name, closure.as_ref().unchecked_ref())- .ok();- handles.push(EventListenerHandle {- target: target.clone(),+ handles.push(EventListenerHandle::add(+ target,event_name,- closure,- });+ move |_event: JsValue| {+ if !cursor_visible.replace(true) {+ set_body_cursor(&browser_window, last_cursor_css.get());+ }+ },+ ));};let document_target: &web_sys::EventTarget = document.as_ref();@@ -441,6 +422,22 @@ fn cursor_restore_listeners(handles}+fn show_webgpu_unavailable_message(browser_window: &web_sys::Window) {+ let Some(document) = browser_window.document() else {+ return;+ };+ let Some(body) = document.body() else {+ return;+ };+ let Ok(message) = document.create_element("p") else {+ return;+ };+ message.set_text_content(Some(+ "Failed to initialize WebGPU. This application requires a browser with WebGPU support.",+ ));+ body.append_child(&message).ok();+}+fn set_body_cursor(browser_window: &web_sys::Window, css_cursor: &str) {if let Some(document) = browser_window.document()&& let Some(body) = document.body()diff --git a/crates/gpui_web/src/window.rs b/crates/gpui_web/src/window.rsindex b9399d32e63..3dbf013a6fd 100644--- a/crates/gpui_web/src/window.rs+++ b/crates/gpui_web/src/window.rs@@ -1,5 +1,5 @@use crate::display::WebDisplay;-use crate::events::{ClickState, WebEventListeners, is_mac_platform};+use crate::events::{ClickState, EventListenerHandle, WebEventListeners, is_mac_platform};use std::sync::Arc;use std::{cell::Cell, cell::RefCell, rc::Rc};@@ -57,13 +57,12 @@ pub(crate) struct WebWindowInner {pub(crate) is_composing: Cell<bool>,mql_handle: RefCell<Option<MqlHandle>>,pending_physical_size: Cell<Option<(u32, u32)>>,+ raf_id: Cell<Option<i32>>,}pub struct WebWindow {inner: Rc<WebWindowInner>,display: Rc<dyn PlatformDisplay>,- #[allow(dead_code)]- handle: AnyWindowHandle,_raf_closure: Closure<dyn FnMut()>,_resize_observer: Option<web_sys::ResizeObserver>,_resize_observer_closure: Closure<dyn FnMut(js_sys::Array)>,@@ -72,7 +71,7 @@ pub struct WebWindow {impl WebWindow {pub fn new(- handle: AnyWindowHandle,+ _handle: AnyWindowHandle,_params: WindowParams,context: &WgpuContext,browser_window: web_sys::Window,@@ -184,6 +183,7 @@ impl WebWindow {is_composing: Cell::new(false),mql_handle: RefCell::new(None),pending_physical_size: Cell::new(None),+ raf_id: Cell::new(None),});let raf_closure = inner.create_raf_closure();@@ -203,7 +203,6 @@ impl WebWindow {Ok(Self {inner,display,- handle,_raf_closure: raf_closure,_resize_observer: resize_observer,_resize_observer_closure: resize_observer_closure,@@ -257,15 +256,16 @@ impl WebWindow {// Skip rendering to a zero-size canvas (e.g. display:none).if physical_width == 0 || physical_height == 0 {- let mut s = inner.state.borrow_mut();- s.bounds.size = Size::default();- s.scale_factor = dpr_f32;- // Still fire the callback so GPUI knows the window is gone.- drop(s);- let mut cbs = inner.callbacks.borrow_mut();- if let Some(ref mut callback) = cbs.resize {- callback(Size::default(), dpr_f32);+ {+ let mut s = inner.state.borrow_mut();+ s.bounds.size = Size::default();+ s.scale_factor = dpr_f32;}+ // Still fire the callback so GPUI knows the window is gone.+ inner.with_callback(+ |callbacks| &mut callbacks.resize,+ |callback| callback(Size::default(), dpr_f32),+ );return;}@@ -273,6 +273,20 @@ impl WebWindow {let clamped_width = physical_width.min(max_texture_dimension);let clamped_height = physical_height.min(max_texture_dimension);+ // Recompute the logical size from the clamped physical size so+ // that scale_factor still maps GPUI's logical bounds exactly onto+ // the surface; otherwise clamping would silently distort the+ // effective scale.+ let (logical_width, logical_height) =+ if (clamped_width, clamped_height) != (physical_width, physical_height) {+ (+ (clamped_width as f64 / dpr) as f32,+ (clamped_height as f64 / dpr) as f32,+ )+ } else {+ (logical_width, logical_height)+ };+inner.pending_physical_size.set(Some((clamped_width, clamped_height)));@@ -291,34 +305,53 @@ impl WebWindow {height: px(logical_height),};- let mut cbs = inner.callbacks.borrow_mut();- if let Some(ref mut callback) = cbs.resize {- callback(new_size, dpr_f32);- }+ inner.with_callback(+ |callbacks| &mut callbacks.resize,+ |callback| callback(new_size, dpr_f32),+ );})}}impl WebWindowInner {+ /// Invokes a registered callback with take/call/restore semantics.+ ///+ /// The callback is removed from the slot for the duration of the call, so+ /// the `RefCell` is not borrowed while user code runs: a callback that+ /// re-enters the platform window (dispatching input, registering+ /// handlers) would otherwise panic with a `BorrowMutError`. A re-entrant+ /// invocation of the same callback finds the slot empty and is a no-op.+ pub(crate) fn with_callback<C, R>(+ &self,+ select: impl Fn(&mut WebWindowCallbacks) -> &mut Option<C>,+ invoke: impl FnOnce(&mut C) -> R,+ ) -> Option<R> {+ let mut callback = select(&mut self.callbacks.borrow_mut()).take()?;+ let result = invoke(&mut callback);+ *select(&mut self.callbacks.borrow_mut()) = Some(callback);+ Some(result)+ }+fn create_raf_closure(self: &Rc<Self>) -> Closure<dyn FnMut()> {let raf_handle: Rc<RefCell<Option<js_sys::Function>>> = Rc::new(RefCell::new(None));let raf_handle_inner = Rc::clone(&raf_handle);let this = Rc::clone(self);let closure = Closure::new(move || {- {- let mut callbacks = this.callbacks.borrow_mut();- if let Some(ref mut callback) = callbacks.request_frame {+ this.with_callback(+ |callbacks| &mut callbacks.request_frame,+ |callback| {callback(RequestFrameOptions {require_presentation: true,force_render: false,- });- }- }+ })+ },+ );// Re-schedule for the next frameif let Some(ref func) = *raf_handle_inner.borrow() {- this.browser_window.request_animation_frame(func).ok();+ this.raf_id+ .set(this.browser_window.request_animation_frame(func).ok());}});@@ -330,9 +363,11 @@ impl WebWindowInner {}fn schedule_raf(&self, closure: &Closure<dyn FnMut()>) {- self.browser_window- .request_animation_frame(closure.as_ref().unchecked_ref())- .ok();+ self.raf_id.set(+ self.browser_window+ .request_animation_frame(closure.as_ref().unchecked_ref())+ .ok(),+ );}fn observe_canvas(&self, observer: &web_sys::ResizeObserver) {@@ -372,40 +407,57 @@ impl WebWindowInner {});}- pub(crate) fn register_visibility_change(- self: &Rc<Self>,- ) -> Option<Closure<dyn FnMut(JsValue)>> {+ pub(crate) fn register_visibility_change(self: &Rc<Self>) -> Option<EventListenerHandle> {let document = self.browser_window.document()?;let this = Rc::clone(self);- let closure = Closure::<dyn FnMut(JsValue)>::new(move |_event: JsValue| {- let is_visible = this- .browser_window- .document()- .map(|doc| {- let state_str: String = js_sys::Reflect::get(&doc, &"visibilityState".into())- .ok()- .and_then(|v| v.as_string())- .unwrap_or_default();- state_str == "visible"- })- .unwrap_or(true);-- {- let mut state = this.state.borrow_mut();- state.is_active = is_visible;- }- let mut callbacks = this.callbacks.borrow_mut();- if let Some(ref mut callback) = callbacks.active_status_change {- callback(is_visible);- }- });-- document- .add_event_listener_with_callback("visibilitychange", closure.as_ref().unchecked_ref())- .ok();+ Some(EventListenerHandle::add(+ document.as_ref(),+ "visibilitychange",+ move |_event: JsValue| {+ let is_visible = this+ .browser_window+ .document()+ .map(|doc| {+ let state_str: String =+ js_sys::Reflect::get(&doc, &"visibilityState".into())+ .ok()+ .and_then(|v| v.as_string())+ .unwrap_or_default();+ state_str == "visible"+ })+ .unwrap_or(true);++ {+ let mut state = this.state.borrow_mut();+ state.is_active = is_visible;+ }+ this.with_callback(+ |callbacks| &mut callbacks.active_status_change,+ |callback| callback(is_visible),+ );+ },+ ))+ }++ /// Tracks `fullscreenchange` instead of toggling a local flag: the user+ /// can exit fullscreen with Esc, and `requestFullscreen` can be rejected,+ /// so the document is the only reliable source of truth.+ pub(crate) fn register_fullscreen_change(self: &Rc<Self>) -> Option<EventListenerHandle> {+ let document = self.browser_window.document()?;+ let this = Rc::clone(self);- Some(closure)+ Some(EventListenerHandle::add(+ document.as_ref(),+ "fullscreenchange",+ move |_event: JsValue| {+ let is_fullscreen = this+ .browser_window+ .document()+ .is_some_and(|document| document.fullscreen_element().is_some());+ this.state.borrow_mut().is_fullscreen = is_fullscreen;+ },+ ))}pub(crate) fn with_input_handler<R>(@@ -418,26 +470,51 @@ impl WebWindowInner {Some(result)}- pub(crate) fn register_appearance_change(- self: &Rc<Self>,- ) -> Option<Closure<dyn FnMut(JsValue)>> {+ pub(crate) fn register_appearance_change(self: &Rc<Self>) -> Option<EventListenerHandle> {let mql = self.browser_window.match_media("(prefers-color-scheme: dark)").ok()??;let this = Rc::clone(self);- let closure = Closure::<dyn FnMut(JsValue)>::new(move |_event: JsValue| {- let mut callbacks = this.callbacks.borrow_mut();- if let Some(ref mut callback) = callbacks.appearance_changed {- callback();- }- });+ Some(EventListenerHandle::add(+ mql.as_ref(),+ "change",+ move |_event: JsValue| {+ this.with_callback(+ |callbacks| &mut callbacks.appearance_changed,+ |callback| callback(),+ );+ },+ ))+ }+}- mql.add_event_listener_with_callback("change", closure.as_ref().unchecked_ref())- .ok();+impl Drop for WebWindow {+ fn drop(&mut self) {+ // Cancel the pending requestAnimationFrame callback before+ // `_raf_closure` is freed, and disconnect the resize observer before+ // `_resize_observer_closure` is freed; a late invocation of either+ // would throw "closure invoked after being dropped".+ if let Some(raf_id) = self.inner.raf_id.take() {+ self.inner+ .browser_window+ .cancel_animation_frame(raf_id)+ .ok();+ }+ if let Some(ref observer) = self._resize_observer {+ observer.disconnect();+ }++ // The DPR media-query closure captures an `Rc<WebWindowInner>` and is+ // stored inside the inner itself, forming a reference cycle; take it+ // out so the inner can actually be freed.+ self.inner.mql_handle.borrow_mut().take();- Some(closure)+ let canvas: &web_sys::Element = self.inner.canvas.as_ref();+ canvas.remove();+ let input_element: &web_sys::Element = self.inner.input_element.as_ref();+ input_element.remove();}}@@ -607,16 +684,17 @@ impl PlatformWindow for WebWindow {}fn toggle_fullscreen(&self) {- let mut state = self.inner.state.borrow_mut();- state.is_fullscreen = !state.is_fullscreen;+ let Some(document) = self.inner.browser_window.document() else {+ return;+ };- if state.is_fullscreen {+ // `is_fullscreen` is updated by the `fullscreenchange` listener once+ // the transition actually happens (or not, if the request fails).+ if document.fullscreen_element().is_some() {+ document.exit_fullscreen();+ } else {let canvas: &web_sys::Element = self.inner.canvas.as_ref();canvas.request_fullscreen().ok();- } else {- if let Some(document) = self.inner.browser_window.document() {- document.exit_fullscreen();- }}}diff --git a/crates/gpui_wgpu/Cargo.toml b/crates/gpui_wgpu/Cargo.tomlindex b31614a78a5..03aea7f7d25 100644--- a/crates/gpui_wgpu/Cargo.toml+++ b/crates/gpui_wgpu/Cargo.toml@@ -43,9 +43,9 @@ pollster.workspace = true[target.'cfg(target_family = "wasm")'.dependencies]wasm-bindgen.workspace = true-wasm-bindgen-futures = "0.4"+wasm-bindgen-futures.workspace = trueweb-sys = { version = "0.3", features = ["HtmlCanvasElement"] }-js-sys = "0.3"+js-sys.workspace = true[dev-dependencies]criterion.workspace = true