From f4fe0be1f8c7974db07e01c5cd05bee0cf4eb8d9 Mon Sep 17 00:00:00 2001 From: Nathan Sobo Date: Sun, 22 Nov 2026 03:18:59 +0000 Subject: [PATCH] gpui: Composite native views into the scene on macOS (#67311) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit ## Summary Adds `NativeView` to GPUI: an element that places a platform view (an `NSView` on macOS) in a window and composites it with the rest of the scene, so that GPUI content can be drawn both under and over it. Delta uses this to show a `WKWebView` in a pane tab with GPUI dialogs and toolbars drawn over the page. What it covers on macOS: - **Compositing.** The native view sits behind the window's Metal layer, and the renderer cuts a hole in the scene where the view shows, so GPUI elements painted after it appear above it. The window's layer is non-opaque only while a scene shows a native view. - **Keyboard input.** Keys go to a focused native view first. An embedder can reserve actions that must keep working whatever the view does with keys, including the first key of a multi-key binding. AppKit controls beside a native view keep their own input. - **Pointer.** GPUI elements over a native view block clicks to it, and the native view chooses the cursor while the pointer is over an unobscured part of it. - **Accessibility.** VoiceOver can reach a native view that is shown. Other platforms get the element and a no-op implementation: `NativeView::new` reports that the window cannot show native views. Also included is a small `div` fix that the embedder needed: an item a scroll handle is asked to scroll to before the handle's first frame is now scrolled to once it has been laid out. ## Testing - Two examples: `cargo run -p gpui --example native_view` and `--example native_view_appkit_field`, which show native views with GPUI drawn over them. - The test platform's window records native view placement, with unit tests for the placement, input-routing policy and reserved-action logic. - Exercised through Delta's browser tabs on macOS 26: typing, shortcuts, splits, zoom, dialogs drawn over the page, and hiding and showing tabs. - Not exercised by hand: the black-flash, stale-cursor and VoiceOver fixes in the last two commits. ## Self-review - [x] I've reviewed my diff for quality, security, reliability, and performance. - [ ] UI changes follow the [checklist](https://zed.dev/docs/development/ui-checklist). - [x] Tests cover the new or changed behavior. Release Notes: - N/A - [GPUI] Added `NativeView`, an element that composites an `NSView` into a window's scene with GPUI content drawn over it. Only macOS supports it for now; `NativeView::new` returns an error on other platforms. - [GPUI] Fixed `ScrollHandle::scroll_to_item` being ignored when called before the handle's first frame. 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Co-authored-by: Claude Fable 5.2 Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com> --- crates/gpui/Cargo.toml | 11 + crates/gpui/examples/native_view.rs | 571 +++++++ .../gpui/examples/native_view_appkit_field.rs | 226 +++ crates/gpui/src/elements/div.rs | 64 +- crates/gpui/src/key_dispatch.rs | 2 +- crates/gpui/src/platform.rs | 46 + crates/gpui/src/platform/test/window.rs | 100 +- crates/gpui/src/scene.rs | 158 +- crates/gpui/src/window.rs | 44 + crates/gpui/src/window/native_view.rs | 815 ++++++++++ crates/gpui_apple/src/metal_renderer.rs | 63 +- crates/gpui_apple/src/shaders.metal | 22 + crates/gpui_macos/src/window.rs | 145 +- crates/gpui_macos/src/window/native_views.rs | 1424 +++++++++++++++++ crates/gpui_wgpu/src/wgpu_renderer.rs | 2 + crates/gpui_windows/src/directx_renderer.rs | 2 + 16 files changed, 3648 insertions(+), 47 deletions(-) create mode 100644 crates/gpui/examples/native_view.rs create mode 100644 crates/gpui/examples/native_view_appkit_field.rs create mode 100644 crates/gpui/src/window/native_view.rs create mode 100644 crates/gpui_macos/src/window/native_views.rs diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml index 3300a445059..5f6d01e07cc 100644 --- a/crates/gpui/Cargo.toml +++ b/crates/gpui/Cargo.toml @@ -192,6 +192,9 @@ http_client = { workspace = true, features = ["test-support"] } proptest.workspace = true reqwest_client = { workspace = true, features = ["test-support"] } +[target.'cfg(target_os = "macos")'.dev-dependencies] +objc2.workspace = true + [target.'cfg(target_family = "wasm")'.dev-dependencies] gpui_web.workspace = true wasm-bindgen.workspace = true @@ -208,6 +211,14 @@ ignored = [ ] ignored-paths = ["src/_ownership_and_data_flow.rs", "benches/focus_cleanup.rs"] +[[example]] +name = "native_view" +path = "examples/native_view.rs" + +[[example]] +name = "native_view_appkit_field" +path = "examples/native_view_appkit_field.rs" + [[example]] name = "hello_world" path = "examples/hello_world.rs" diff --git a/crates/gpui/examples/native_view.rs b/crates/gpui/examples/native_view.rs new file mode 100644 index 00000000000..81b95a0be3f --- /dev/null +++ b/crates/gpui/examples/native_view.rs @@ -0,0 +1,571 @@ +//! Shows a live `WKWebView` composited into a GPUI window on macOS. +//! +//! Things to try: +//! - Press `cmd-shift-p` while typing in the page. The palette opens across the page's +//! edge, takes keyboard input, and `escape` returns the caret to the same page field. +//! - Click the palette's button where it overlaps the page, then scroll the exposed page. +//! - Click the page while the palette is open, which dismisses the palette. +//! - Click the GPUI text box, type, then click back into the page. +//! - Click an empty part of the page and press some keys. The page sees every key first, +//! and the sidebar lists the ones it left for GPUI. It keeps `cmd-k` for itself, while +//! `cmd-shift-p` is reserved, so it opens the palette whatever the page does. +//! - Drag the divider, then load the other page or toggle the page's colors, and drag it +//! again. The strip that shows for a frame where the page is catching up takes the +//! page's own background color. + +#[cfg(target_os = "macos")] +#[path = "example_support/fonts.rs"] +mod example_support; + +#[cfg(target_os = "macos")] +mod example { + use futures::{StreamExt as _, channel::mpsc}; + use gpui::{ + App, Context, FocusHandle, KeyBinding, KeyDownEvent, MouseButton, MouseMoveEvent, + NativeView, Pixels, Rgba, Task, Window, WindowOptions, actions, anchored, deferred, div, + point, prelude::*, px, rgb, + }; + use objc2::{ + class, msg_send, + rc::{Allocated, Retained}, + runtime::{AnyClass, AnyObject, ClassBuilder, Sel}, + sel, + }; + use std::{ + ffi::{CStr, c_char, c_void}, + ptr::{self, NonNull}, + sync::OnceLock, + }; + + #[link(name = "WebKit", kind = "framework")] + unsafe extern "C" {} + + actions!(native_view_example, [TogglePalette, DismissPalette]); + + /// Runs in every page and reports its background color, so that GPUI can show + /// that color wherever the web view is still catching up with its element. + /// + /// It reports again when the color changes, which a page does by restyling + /// its root elements, changing its stylesheets, or following the system's + /// appearance. Checks are limited to one per frame, and only run after one + /// of those happens. + const REPORT_BACKGROUND: &CStr = cr#"(function () { + let reported = null; + let scheduled = false; + function report() { + scheduled = false; + const transparent = "rgba(0, 0, 0, 0)"; + let color = getComputedStyle(document.body).backgroundColor; + if (color === transparent) { + color = getComputedStyle(document.documentElement).backgroundColor; + } + if (color === transparent) { + color = "rgb(255, 255, 255)"; + } + if (color !== reported) { + reported = color; + window.webkit.messageHandlers.background.postMessage(color); + } + } + function schedule() { + if (!scheduled) { + scheduled = true; + requestAnimationFrame(report); + } + } + report(); + window.addEventListener("load", schedule); + const observer = new MutationObserver(schedule); + observer.observe(document.documentElement, { attributes: true }); + observer.observe(document.body, { attributes: true }); + observer.observe(document.head, { attributes: true, childList: true, subtree: true }); + matchMedia("(prefers-color-scheme: dark)").addEventListener("change", schedule); + for (const element of [document.documentElement, document.body]) { + element.addEventListener("transitionend", schedule); + } +})();"#; + + const OTHER_PAGE: &CStr = cr#" + + +

Another page

+

+ +"#; + + const PAGE: &CStr = cr#" + + +

A live WKWebView

+

+ +

+

+

An editable paragraph.

+

A link, for the pointing-hand cursor

+

This page keeps cmd-k for itself.

+ + + + +"#; + + struct Example { + web_view: NativeView, + web_view_object: Retained, + showing_other_page: bool, + _background_updates: Task<()>, + web_view_visible: bool, + sidebar_width: Pixels, + resizing_sidebar: bool, + text_box_focus: FocusHandle, + text_box_text: String, + palette_focus: FocusHandle, + palette_text: String, + palette_clicks: usize, + focus_before_palette: Option, + keys_left_by_page: Vec, + } + + impl Example { + fn new(window: &mut Window, cx: &mut Context) -> Self { + let (background_sender, mut backgrounds) = mpsc::unbounded(); + // SAFETY: `WKWebView` is a view class in the linked WebKit framework, and + // windows are opened on the main thread. + let (web_view, web_view_object) = unsafe { + let web_view: Allocated = msg_send![class!(WKWebView), alloc]; + let web_view: Retained = msg_send![web_view, init]; + + let configuration: Retained = msg_send![&*web_view, configuration]; + let content_controller: Retained = + msg_send![&*configuration, userContentController]; + const AT_DOCUMENT_END: isize = 1; + let script: Allocated = msg_send![class!(WKUserScript), alloc]; + let script: Retained = msg_send![ + script, + initWithSource: &*ns_string(REPORT_BACKGROUND), + injectionTime: AT_DOCUMENT_END, + forMainFrameOnly: true + ]; + let _: () = msg_send![&*content_controller, addUserScript: &*script]; + let _: () = msg_send![ + &*content_controller, + addScriptMessageHandler: &*background_reporter(background_sender), + name: &*ns_string(c"background") + ]; + + // A web view fills the area its page has not painted yet with the + // system's text background, which shows as a sliver while it grows. + // Without it, the window's native view background shows there instead. + let draws_background: Retained = + msg_send![class!(NSNumber), numberWithBool: false]; + let _: () = msg_send![ + &*web_view, + setValue: &*draws_background, + forKey: &*ns_string(c"drawsBackground") + ]; + load_page(&web_view, PAGE); + let native_view = NativeView::new(NonNull::from(&*web_view).cast(), window, cx) + .expect("macOS windows composite native views"); + // The page sees keys before GPUI does, so without this a page that + // handled this key itself would keep the palette from opening. + native_view.reserve_action::(); + (native_view, web_view) + }; + let background_updates = cx.spawn(async move |this, cx| { + while let Some(color) = backgrounds.next().await { + let Some(color) = parse_css_color(&color) else { + continue; + }; + let updated = this.update(cx, |this, cx| { + this.web_view.set_background(color, cx); + }); + if updated.is_err() { + break; + } + } + }); + Self { + web_view, + web_view_object, + showing_other_page: false, + _background_updates: background_updates, + web_view_visible: true, + sidebar_width: px(240.), + resizing_sidebar: false, + text_box_focus: cx.focus_handle(), + text_box_text: String::new(), + palette_focus: cx.focus_handle(), + palette_text: String::new(), + palette_clicks: 0, + focus_before_palette: None, + keys_left_by_page: Vec::new(), + } + } + + fn toggle_palette( + &mut self, + _: &TogglePalette, + window: &mut Window, + cx: &mut Context, + ) { + if self.focus_before_palette.is_some() { + self.dismiss_palette(&DismissPalette, window, cx); + return; + } + self.focus_before_palette = Some( + window + .focused(cx) + .unwrap_or_else(|| self.text_box_focus.clone()), + ); + window.focus(&self.palette_focus, cx); + cx.notify(); + } + + fn dismiss_palette( + &mut self, + _: &DismissPalette, + window: &mut Window, + cx: &mut Context, + ) { + if let Some(previous_focus) = self.focus_before_palette.take() { + window.focus(&previous_focus, cx); + cx.notify(); + } + } + + fn render_palette(&self, cx: &mut Context) -> impl IntoElement { + deferred( + anchored().position(point(px(170.), px(120.))).child( + div() + .id("palette") + .track_focus(&self.palette_focus) + .on_mouse_down_out(cx.listener(|this, _, window, cx| { + this.dismiss_palette(&DismissPalette, window, cx); + })) + .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { + if let Some(text) = &event.keystroke.key_char { + this.palette_text.push_str(text); + cx.notify(); + } + })) + .occlude() + .w(px(320.)) + .p_4() + .flex() + .flex_col() + .gap_3() + .rounded_lg() + .shadow_xl() + .bg(rgb(0x1f2933)) + .text_color(gpui::white()) + .child("A GPUI palette over the page") + .child( + div() + .p_2() + .rounded_md() + .bg(rgb(0x323f4b)) + .child(format!("Typed: {}", self.palette_text)), + ) + .child( + div() + .id("palette-button") + .p_2() + .rounded_md() + .bg(rgb(0x3e7bfa)) + .cursor_pointer() + .child(format!("Clicked {} times", self.palette_clicks)) + .on_click(cx.listener(|this, _, _, cx| { + this.palette_clicks += 1; + cx.notify(); + })), + ), + ), + ) + .with_priority(1) + } + } + + impl Render for Example { + fn render(&mut self, window: &mut Window, cx: &mut Context) -> impl IntoElement { + let text_box_focused = self.text_box_focus.is_focused(window); + div() + .size_full() + .flex() + .bg(rgb(0xf0f4f8)) + .text_color(rgb(0x1f2933)) + .on_action(cx.listener(Self::toggle_palette)) + .on_action(cx.listener(Self::dismiss_palette)) + .on_key_down(cx.listener(|this, event: &KeyDownEvent, window, cx| { + if gpui::Focusable::focus_handle(&this.web_view, cx).is_focused(window) { + this.keys_left_by_page + .push(event.keystroke.unparse(gpui::OperatingSystem::Mac)); + let excess = this.keys_left_by_page.len().saturating_sub(8); + this.keys_left_by_page.drain(..excess); + cx.notify(); + } + })) + .child( + div() + .flex_none() + .w(self.sidebar_width) + .p_4() + .flex() + .flex_col() + .gap_3() + .child("GPUI content") + .child( + div() + .id("text-box") + .track_focus(&self.text_box_focus) + .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, cx| { + if let Some(text) = &event.keystroke.key_char { + this.text_box_text.push_str(text); + cx.notify(); + } + })) + .on_click(cx.listener(|this, _, window, cx| { + window.focus(&this.text_box_focus, cx); + })) + .min_h(px(60.)) + .p_2() + .rounded_md() + .border_1() + .border_color(if text_box_focused { + rgb(0x3e7bfa) + } else { + rgb(0x9aa5b1) + }) + .bg(gpui::white()) + .child(format!("Click, then type: {}", self.text_box_text)), + ) + .child( + div() + .id("toggle-web-view") + .p_2() + .rounded_md() + .bg(rgb(0xd9e2ec)) + .cursor_pointer() + .child(if self.web_view_visible { + "Hide the web view" + } else { + "Show the web view" + }) + .on_click(cx.listener(|this, _, _, cx| { + this.web_view_visible = !this.web_view_visible; + cx.notify(); + })), + ) + .child( + div() + .id("load-other-page") + .p_2() + .rounded_md() + .bg(rgb(0xd9e2ec)) + .cursor_pointer() + .child("Load the other page") + .on_click(cx.listener(|this, _, _, _| { + this.showing_other_page = !this.showing_other_page; + let page = if this.showing_other_page { + OTHER_PAGE + } else { + PAGE + }; + // SAFETY: The web view is live, and listeners run on + // the main thread. + unsafe { load_page(&this.web_view_object, page) }; + })), + ) + .child("cmd-shift-p toggles the palette, escape dismisses it.") + .child(format!( + "Keys the page left for GPUI: {}", + self.keys_left_by_page.join(" ") + )), + ) + .child( + div() + .id("divider") + .flex_none() + .w(px(6.)) + .h_full() + .bg(rgb(0x9aa5b1)) + .cursor_col_resize() + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _, _, cx| { + this.resizing_sidebar = true; + cx.notify(); + }), + ), + ) + .child( + div() + .flex_1() + .min_w_0() + .h_full() + .when(self.web_view_visible, |this| { + this.child(self.web_view.clone()) + }), + ) + .when(self.focus_before_palette.is_some(), |this| { + this.child(self.render_palette(cx)) + }) + // The web view blocks the mouse from everything behind it, so the + // drag is followed by an element in front of it. + .when(self.resizing_sidebar, |this| { + this.child( + div() + .absolute() + .inset_0() + .occlude() + .cursor_col_resize() + .on_mouse_move(cx.listener(|this, event: &MouseMoveEvent, _, cx| { + this.sidebar_width = event.position.x.clamp(px(120.), px(600.)); + cx.notify(); + })) + .on_mouse_up( + MouseButton::Left, + cx.listener(|this, _, _, cx| { + this.resizing_sidebar = false; + cx.notify(); + }), + ), + ) + }) + } + } + + fn ns_string(text: &CStr) -> Retained { + // SAFETY: `text` is a valid, nul-terminated UTF-8 string. + unsafe { msg_send![class!(NSString), stringWithUTF8String: text.as_ptr()] } + } + + /// # Safety + /// + /// `web_view` must be a `WKWebView`, and this must be called on the main thread. + unsafe fn load_page(web_view: &AnyObject, page: &CStr) { + unsafe { + let _: *mut AnyObject = msg_send![ + web_view, + loadHTMLString: &*ns_string(page), + baseURL: ptr::null::() + ]; + } + } + + /// Creates the object the page's script posts its background color to. + fn background_reporter(sender: mpsc::UnboundedSender) -> Retained { + const SENDER: &CStr = c"sender"; + + extern "C" fn received( + this: &AnyObject, + _: Sel, + _: *mut AnyObject, + message: *mut AnyObject, + ) { + let Some(sender) = this.class().instance_variable(SENDER) else { + return; + }; + // SAFETY: The ivar holds the sender leaked below, WebKit passes a live + // `WKScriptMessage`, and the script only posts strings. + unsafe { + let sender = *sender.load::<*mut c_void>(this); + let sender = &*sender.cast::>(); + let body: *mut AnyObject = msg_send![message, body]; + let text: *const c_char = msg_send![body, UTF8String]; + if !text.is_null() { + let color = CStr::from_ptr(text).to_string_lossy().into_owned(); + // The example's window is gone if nothing is receiving. + sender.unbounded_send(color).ok(); + } + } + } + + static CLASS: OnceLock<&'static AnyClass> = OnceLock::new(); + let class = CLASS.get_or_init(|| { + let mut builder = + ClassBuilder::new(c"NativeViewExampleBackgroundReporter", class!(NSObject)) + .expect("the class is only registered here"); + builder.add_ivar::<*mut c_void>(SENDER); + // SAFETY: The function matches the signature of + // `-userContentController:didReceiveScriptMessage:`. + unsafe { + builder.add_method( + sel!(userContentController:didReceiveScriptMessage:), + received as extern "C" fn(_, _, _, _), + ); + } + builder.register() + }); + // SAFETY: The class was built from `NSObject` above. The web view keeps the + // reporter for as long as the example runs, so the sender is never freed. + unsafe { + let reporter: Allocated = msg_send![*class, alloc]; + let reporter: Retained = msg_send![reporter, init]; + if let Some(ivar) = class.instance_variable(SENDER) { + ivar.load_ptr::<*mut c_void>(&reporter) + .write(Box::into_raw(Box::new(sender)).cast()); + } + reporter + } + } + + /// Parses the `rgb(r, g, b)` and `rgba(r, g, b, a)` forms that computed styles use. + fn parse_css_color(text: &str) -> Option { + let components = text.split_once('(')?.1.strip_suffix(')')?; + let mut components = components + .split(',') + .map(|component| component.trim().parse::().ok()); + Some(Rgba { + r: components.next()?? / 255., + g: components.next()?? / 255., + b: components.next()?? / 255., + a: 1., + }) + } + + pub fn run() { + gpui_platform::application().run(|cx: &mut App| { + if !crate::example_support::load_fonts(cx) { + return; + } + cx.bind_keys([ + KeyBinding::new("cmd-shift-p", TogglePalette, None), + KeyBinding::new("escape", DismissPalette, None), + ]); + cx.open_window(WindowOptions::default(), |window, cx| { + cx.new(|cx| Example::new(window, cx)) + }) + .expect("opening the example window"); + cx.activate(true); + }); + } +} + +#[cfg(target_os = "macos")] +fn main() { + example::run(); +} + +#[cfg(not(target_os = "macos"))] +fn main() { + eprintln!("Native views are only composited on macOS."); +} diff --git a/crates/gpui/examples/native_view_appkit_field.rs b/crates/gpui/examples/native_view_appkit_field.rs new file mode 100644 index 00000000000..bb0721e7a4b --- /dev/null +++ b/crates/gpui/examples/native_view_appkit_field.rs @@ -0,0 +1,226 @@ +//! Shows that an AppKit control outside GPUI keeps keyboard input beside a native view. +//! +//! The window holds a `WKWebView` and, in its top right corner, an `NSTextView` +//! that GPUI knows nothing about. Click that field and type: the text goes into +//! it, and the line at the top says which of the three has keyboard input. +//! +//! A second after it opens, the example also gives the field keyboard input +//! itself and prints whether the field still had it half a second later. + +#[cfg(target_os = "macos")] +#[path = "example_support/fonts.rs"] +mod example_support; + +#[cfg(target_os = "macos")] +mod example { + use gpui::{ + App, Context, Focusable as _, NativeView, Task, Window, WindowOptions, div, prelude::*, px, + rgb, + }; + use objc2::{ + class, msg_send, + rc::{Allocated, Retained}, + runtime::{AnyObject, Bool}, + }; + use objc2_core_foundation::{CGPoint, CGRect, CGSize}; + use std::{ + ffi::{CStr, c_void}, + ptr::{self, NonNull}, + time::Duration, + }; + + #[link(name = "WebKit", kind = "framework")] + unsafe extern "C" {} + + const PAGE: &CStr = cr#" + + +

+ +"#; + + #[derive(Clone, Copy, PartialEq)] + enum KeyboardInput { + AppKitField, + Page, + Gpui, + } + + struct Example { + web_view: NativeView, + web_view_object: Retained, + appkit_field: Retained, + keyboard_input: KeyboardInput, + _watch: Task<()>, + } + + impl Example { + fn new(window: &mut Window, cx: &mut Context) -> Self { + // SAFETY: These are AppKit and WebKit classes used as documented, on + // the main thread. + let (web_view_object, appkit_field) = unsafe { + let web_view: Allocated = msg_send![class!(WKWebView), alloc]; + let web_view: Retained = msg_send![web_view, init]; + let _: *mut AnyObject = msg_send![ + &*web_view, + loadHTMLString: &*ns_string(PAGE), + baseURL: ptr::null::() + ]; + // A text view takes keyboard input itself, where a text field + // would pass it to an editor that AppKit manages. + let frame = CGRect::new(CGPoint::new(0., 0.), CGSize::new(220., 22.)); + let field: Allocated = msg_send![class!(NSTextView), alloc]; + let field: Retained = msg_send![field, initWithFrame: frame]; + let _: () = msg_send![&*field, setString: &*ns_string(c"An AppKit field")]; + (web_view, field) + }; + // SAFETY: The pointer is the live web view, which is in no view hierarchy. + let web_view = unsafe { + NativeView::new( + NonNull::from(&*web_view_object).cast::(), + window, + cx, + ) + } + .expect("this example only runs where native views are composited"); + // SAFETY: Attaching the web view put it in the GPUI window, whose + // content view is live, on the main thread. + unsafe { + let ns_window: *mut AnyObject = msg_send![&*web_view_object, window]; + let content_view: *mut AnyObject = msg_send![ns_window, contentView]; + let bounds: CGRect = msg_send![content_view, bounds]; + let is_flipped: bool = msg_send![content_view, isFlipped]; + let size = CGSize::new(220., 22.); + let top = if is_flipped { + 8. + } else { + bounds.size.height - size.height - 8. + }; + let origin = CGPoint::new(bounds.size.width - size.width - 8., top); + let _: () = msg_send![&*appkit_field, setFrame: CGRect::new(origin, size)]; + // Keeps the field in the corner as the window resizes: + // `NSViewMinXMargin`, with `NSViewMaxYMargin` or `NSViewMinYMargin`. + let mask: usize = if is_flipped { 1 | 32 } else { 1 | 8 }; + let _: () = msg_send![&*appkit_field, setAutoresizingMask: mask]; + let _: () = msg_send![content_view, addSubview: &*appkit_field]; + } + window.focus(&web_view.focus_handle(cx), cx); + + let watch = cx.spawn(async move |this, cx| { + let mut elapsed = Duration::ZERO; + let step = Duration::from_millis(250); + loop { + cx.background_executor().timer(step).await; + elapsed += step; + let updated = this.update(cx, |this, cx| { + if elapsed == Duration::from_millis(1000) { + this.focus_appkit_field(); + } + let keyboard_input = this.keyboard_input(); + if elapsed == Duration::from_millis(1500) { + println!( + "AppKit field kept keyboard input: {}", + keyboard_input == KeyboardInput::AppKitField + ); + } + if this.keyboard_input != keyboard_input { + this.keyboard_input = keyboard_input; + cx.notify(); + } + }); + if updated.is_err() { + break; + } + } + }); + + Self { + web_view, + web_view_object, + appkit_field, + keyboard_input: KeyboardInput::Gpui, + _watch: watch, + } + } + + fn focus_appkit_field(&self) { + // SAFETY: The field is live and in the window, on the main thread. + unsafe { + let ns_window: *mut AnyObject = msg_send![&*self.appkit_field, window]; + let accepted: Bool = msg_send![ns_window, makeFirstResponder: &*self.appkit_field]; + println!("AppKit field took keyboard input: {}", accepted.as_bool()); + } + } + + /// Which view the window's first responder is, or is inside. + fn keyboard_input(&self) -> KeyboardInput { + // SAFETY: The views are live and in the window, on the main thread. + unsafe { + let ns_window: *mut AnyObject = msg_send![&*self.appkit_field, window]; + let responder: *mut AnyObject = msg_send![ns_window, firstResponder]; + let is_view: bool = + !responder.is_null() && msg_send![responder, isKindOfClass: class!(NSView)]; + let inside = |view: &AnyObject| -> bool { + is_view && msg_send![responder, isDescendantOf: view] + }; + if inside(&self.appkit_field) { + KeyboardInput::AppKitField + } else if inside(&self.web_view_object) { + KeyboardInput::Page + } else { + KeyboardInput::Gpui + } + } + } + } + + impl Render for Example { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + let keyboard_input = match self.keyboard_input { + KeyboardInput::AppKitField => "the AppKit field", + KeyboardInput::Page => "the page", + KeyboardInput::Gpui => "GPUI", + }; + div() + .size_full() + .flex() + .flex_col() + .bg(rgb(0x202428)) + .text_color(rgb(0xdddddd)) + .child( + div() + .p(px(8.)) + .child(format!("Keyboard input is with {keyboard_input}.")), + ) + .child(div().flex_1().child(self.web_view.clone())) + } + } + + fn ns_string(text: &CStr) -> Retained { + // SAFETY: `text` is nul-terminated, and `NSString` copies it. + unsafe { msg_send![class!(NSString), stringWithUTF8String: text.as_ptr()] } + } + + pub fn run() { + gpui_platform::application().run(|cx: &mut App| { + if !crate::example_support::load_fonts(cx) { + return; + } + cx.open_window(WindowOptions::default(), |window, cx| { + cx.new(|cx| Example::new(window, cx)) + }) + .expect("opening the example window"); + cx.activate(true); + }); + } +} + +#[cfg(target_os = "macos")] +fn main() { + example::run(); +} + +#[cfg(not(target_os = "macos"))] +fn main() { + eprintln!("Native views are only composited on macOS."); +} diff --git a/crates/gpui/src/elements/div.rs b/crates/gpui/src/elements/div.rs index ce038047780..754a9754194 100644 --- a/crates/gpui/src/elements/div.rs +++ b/crates/gpui/src/elements/div.rs @@ -2114,10 +2114,6 @@ impl Element for Div { (child_max - child_min).into() }; - if let Some(scroll_handle) = self.interactivity.tracked_scroll_handle.as_ref() { - scroll_handle.scroll_to_active_item(); - } - self.interactivity.prepaint( global_id, inspector_id, @@ -2543,14 +2539,22 @@ impl Interactivity { if let Some(scroll_offset) = self.scroll_offset.as_ref() { let mut scroll_to_bottom = false; - let mut tracked_scroll_handle = self + if let Some(scroll_handle) = self.tracked_scroll_handle.as_ref() { + { + let mut scroll_handle_state = scroll_handle.0.borrow_mut(); + scroll_handle_state.overflow = style.overflow; + // Scrolling to an item needs this frame's bounds and overflow. + // What the handle remembers is from the last frame, and is + // empty the first time the element is drawn. + scroll_handle_state.bounds = bounds; + scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom); + } + scroll_handle.scroll_to_active_item(); + } + let tracked_scroll_handle = self .tracked_scroll_handle .as_ref() .map(|handle| handle.0.borrow_mut()); - if let Some(scroll_handle_state) = tracked_scroll_handle.as_deref_mut() { - scroll_handle_state.overflow = style.overflow; - scroll_to_bottom = mem::take(&mut scroll_handle_state.scroll_to_bottom); - } let rem_size = window.rem_size(); // Taffy lays the box out with the padding snapped to the device pixel @@ -5778,6 +5782,48 @@ mod tests { assert_eq!(scroll_handle.max_offset().y, px(0.)); } + #[gpui::test] + fn test_scrolls_to_an_item_requested_before_the_first_frame(cx: &mut TestAppContext) { + struct Strip { + scroll_handle: ScrollHandle, + } + + impl Render for Strip { + fn render( + &mut self, + _window: &mut Window, + _cx: &mut Context, + ) -> impl IntoElement { + div().size_full().child( + div() + .id("strip") + .flex() + .h(px(20.)) + .w(px(100.)) + .overflow_x_scroll() + .track_scroll(&self.scroll_handle) + .children((0..5).map(|_| div().flex_none().w(px(40.)).h_full())), + ) + } + } + + // The handle has never been drawn, so it knows neither its element's + // bounds nor that the element scrolls. + let scroll_handle = ScrollHandle::new(); + scroll_handle.scroll_to_item(4); + let window: AnyWindowHandle = cx + .add_window({ + let scroll_handle = scroll_handle.clone(); + move |_, _| Strip { scroll_handle } + }) + .into(); + cx.update_window(window, |_, window, cx| window.draw(cx).clear(cx)) + .unwrap(); + + // Five 40px items in a 100px strip: the last one ends at 200px. + assert_eq!(scroll_handle.offset().x, px(-100.)); + } + struct ContentSizedGrid; impl Render for ContentSizedGrid { diff --git a/crates/gpui/src/key_dispatch.rs b/crates/gpui/src/key_dispatch.rs index 764f31f7d4f..c273f160d1f 100644 --- a/crates/gpui/src/key_dispatch.rs +++ b/crates/gpui/src/key_dispatch.rs @@ -445,7 +445,7 @@ impl DispatchTree { } } - fn bindings_for_input( + pub(crate) fn bindings_for_input( &self, input: &[Keystroke], dispatch_path: &SmallVec<[DispatchNodeId; 32]>, diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs index 86520ab0498..154e5f62471 100644 --- a/crates/gpui/src/platform.rs +++ b/crates/gpui/src/platform.rs @@ -1365,6 +1365,46 @@ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle { fn on_should_close(&self, callback: Box bool>); fn on_hit_test_window_control(&self, callback: Box Option>); fn on_close(&self, callback: Box); + + /// Adds a platform view beneath the window's rendered content, hidden + /// until a drawn scene contains a [`PaintNativeView`](crate::PaintNativeView) + /// for it. Dropping the returned value removes the view from the window. + /// Returns `None` when the platform cannot composite native views. + /// + /// # Safety + /// + /// `view` must point to a live view of the kind this platform embeds, + /// which is not in another view hierarchy. + unsafe fn attach_native_view( + &self, + _id: crate::NativeViewId, + _view: std::ptr::NonNull, + ) -> Option> { + None + } + /// Gives keyboard input to the native view, or back to the window's own + /// content for `None`. + fn set_focused_native_view(&self, _id: Option) {} + /// Registers the callback that decides whether a mouse event at a + /// position belongs to a native view instead of the window's content. + fn on_hit_test_native_view( + &self, + _callback: Box) -> Option>, + ) { + } + /// Registers the callback invoked when the user moves keyboard input to + /// a native view through the platform, such as by clicking in it. + fn on_native_view_focused(&self, _callback: Box) {} + /// Registers the callback offered each key press before the native view + /// that has keyboard input, which returns whether it used the key. + /// + /// The native view receives the keys it doesn't use, and the ones the + /// view doesn't use either arrive afterwards as ordinary input. + fn on_key_down_before_native_view( + &self, + _callback: Box bool>, + ) { + } fn on_appearance_changed(&self, callback: Box); fn on_button_layout_changed(&self, _callback: Box) {} fn draw(&self, scene: &Scene); @@ -2211,6 +2251,12 @@ impl PlatformInputHandler { self.handler.apple_press_and_hold_enabled() } + /// Ends a composition from inside an update, where [`Self::unmark_text`] + /// cannot borrow the app. + pub(crate) fn unmark_text_during_update(&mut self, window: &mut Window, cx: &mut App) { + self.handler.unmark_text(window, cx); + } + pub fn dispatch_input(&mut self, input: &str, window: &mut Window, cx: &mut App) { self.handler.replace_text_in_range(None, input, window, cx); } diff --git a/crates/gpui/src/platform/test/window.rs b/crates/gpui/src/platform/test/window.rs index ff1c4cd3805..32b23043361 100644 --- a/crates/gpui/src/platform/test/window.rs +++ b/crates/gpui/src/platform/test/window.rs @@ -1,10 +1,10 @@ use crate::{ AnyWindowHandle, Bounds, Decorations, DevicePixels, DispatchEventResult, DisplayId, GpuSpecs, - HeadlessAtlas, Pixels, Platform, PlatformAtlas, PlatformDisplay, PlatformHeadlessRenderer, - PlatformInput, PlatformInputHandler, PlatformWindow, Point, PromptButton, RequestFrameOptions, - Scene, Size, TestDisplay, TestPlatform, TextInputConfiguration, TextInputStateChange, - WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowInsets, - WindowParams, WindowVisibility, + HeadlessAtlas, KeyDownEvent, NativeViewId, Pixels, Platform, PlatformAtlas, PlatformDisplay, + PlatformHeadlessRenderer, PlatformInput, PlatformInputHandler, PlatformWindow, Point, + PromptButton, RequestFrameOptions, Scene, Size, TestDisplay, TestPlatform, + TextInputConfiguration, TextInputStateChange, WindowAppearance, WindowBackgroundAppearance, + WindowBounds, WindowControlArea, WindowInsets, WindowParams, WindowVisibility, }; use gpui_util::ResultExt as _; #[cfg(any(test, feature = "test-support"))] @@ -32,6 +32,11 @@ pub(crate) struct TestWindowState { pub(crate) should_close_handler: Option bool>>, close_callback: Option>, hit_test_window_control_callback: Option Option>>, + attached_native_views: Rc>, + focused_native_view: Option, + hit_test_native_view_callback: Option) -> Option>>, + native_view_focused_callback: Option>, + key_down_before_native_view_callback: Option bool>>, input_callback: Option DispatchEventResult>>, active_status_change_callback: Option>, visibility: WindowVisibility, @@ -123,6 +128,11 @@ impl TestWindow { moved_callback: None, display_changed_callback: None, appearance_change_callback: None, + attached_native_views: Rc::new(Cell::new(0)), + focused_native_view: None, + hit_test_native_view_callback: None, + native_view_focused_callback: None, + key_down_before_native_view_callback: None, request_frame_callback: None, frame_wake_count: Rc::new(Cell::new(0)), frame_scheduled: false, @@ -258,6 +268,47 @@ impl TestWindow { self.simulate_resize(size); } + /// How many native views are attached to the window. + pub fn attached_native_view_count(&self) -> usize { + self.0.lock().attached_native_views.get() + } + + /// The native view the window last gave keyboard input to. + pub fn focused_native_view(&self) -> Option { + self.0.lock().focused_native_view + } + + /// Asks the window which native view a mouse event at `position` reaches. + pub fn hit_test_native_view(&self, position: Point) -> Option { + let mut callback = self.0.lock().hit_test_native_view_callback.take()?; + let id = callback(position); + self.0.lock().hit_test_native_view_callback = Some(callback); + id + } + + /// Acts as if the user pressed a key while a native view had keyboard input, + /// and returns whether the window used the key before the view saw it. + pub fn simulate_key_down_before_native_view(&self, event: KeyDownEvent) -> bool { + let Some(mut callback) = self.0.lock().key_down_before_native_view_callback.take() else { + return false; + }; + let handled = callback(event); + self.0.lock().key_down_before_native_view_callback = Some(callback); + handled + } + + /// Acts as if the user moved keyboard input to a native view through the platform. + pub fn simulate_native_view_focused(&self, id: NativeViewId) { + let mut lock = self.0.lock(); + lock.focused_native_view = Some(id); + let Some(mut callback) = lock.native_view_focused_callback.take() else { + return; + }; + drop(lock); + callback(id); + self.0.lock().native_view_focused_callback = Some(callback); + } + pub(crate) fn simulate_active_status_change(&self, active: bool) { let mut lock = self.0.lock(); let Some(mut callback) = lock.active_status_change_callback.take() else { @@ -577,6 +628,45 @@ impl PlatformWindow for TestWindow { self.0.lock().hit_test_window_control_callback = Some(callback); } + /// Counts the view as attached without ever reading `_view`, so tests may + /// pass a dangling pointer. + unsafe fn attach_native_view( + &self, + _id: NativeViewId, + _view: std::ptr::NonNull, + ) -> Option> { + struct Attachment(Rc>); + + impl Drop for Attachment { + fn drop(&mut self) { + self.0.set(self.0.get() - 1); + } + } + + let attached_native_views = self.0.lock().attached_native_views.clone(); + attached_native_views.set(attached_native_views.get() + 1); + Some(Box::new(Attachment(attached_native_views))) + } + + fn set_focused_native_view(&self, id: Option) { + self.0.lock().focused_native_view = id; + } + + fn on_key_down_before_native_view(&self, callback: Box bool>) { + self.0.lock().key_down_before_native_view_callback = Some(callback); + } + + fn on_hit_test_native_view( + &self, + callback: Box) -> Option>, + ) { + self.0.lock().hit_test_native_view_callback = Some(callback); + } + + fn on_native_view_focused(&self, callback: Box) { + self.0.lock().native_view_focused_callback = Some(callback); + } + fn on_appearance_changed(&self, callback: Box) { self.0.lock().appearance_change_callback = Some(callback); } diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs index b2104e5402a..f4f85f477c4 100644 --- a/crates/gpui/src/scene.rs +++ b/crates/gpui/src/scene.rs @@ -5,8 +5,8 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{ - AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Path, - PathTiles, Pixels, Point, Radians, ScaledPixels, Size, TimedTransformation, + AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, HitboxId, Hsla, + NativeViewId, Path, PathTiles, Pixels, Point, Radians, ScaledPixels, Size, TimedTransformation, bounds_tree::BoundsTree, }; use smallvec::SmallVec; @@ -43,6 +43,9 @@ struct Layer { bounds: Bounds, max_kind: PrimitiveKind, max_shared_kind: PrimitiveKind, + /// Whether a native view was painted in the layer, which then can't be + /// drawn as one: what was painted after the view has to cover it. + has_native_view: bool, } #[derive(Default)] @@ -60,6 +63,7 @@ pub struct Scene { pub subpixel_sprites: Vec, pub polychrome_sprites: Vec, pub surfaces: Vec, + pub native_views: Vec, animations: Vec, } @@ -78,6 +82,7 @@ impl Scene { self.subpixel_sprites.clear(); self.polychrome_sprites.clear(); self.surfaces.clear(); + self.native_views.clear(); self.animations.clear(); } @@ -133,7 +138,8 @@ impl Scene { primitives: SmallVec::new(), bounds: Bounds::default(), max_kind: PrimitiveKind::Shadow, - max_shared_kind: PrimitiveKind::Surface, + max_shared_kind: PrimitiveKind::NativeView, + has_native_view: false, }); self.paint_operations.push(PaintOperation::StartLayer); } @@ -152,6 +158,10 @@ impl Scene { if layer.primitives.is_empty() { return; } + if layer.has_native_view { + self.insert_layer_around_native_views(layer); + return; + } let order = self.primitive_bounds .insert(layer.bounds, layer.max_kind, layer.max_shared_kind); @@ -163,6 +173,50 @@ impl Scene { } } + /// Inserts a layer that a native view was painted in. + /// + /// A layer's primitives share one place in the drawing order, where they + /// are drawn by kind and not in the order they were painted. A native + /// view erases what is drawn before it, so the layer is inserted in parts: + /// what was painted before each view, the view, and what was painted after. + fn insert_layer_around_native_views(&mut self, layer: Layer) { + let mut part = Vec::new(); + for index in layer.primitives.into_iter().flatten() { + let PaintOperation::Primitive(primitive) = &self.paint_operations[index] else { + continue; + }; + let primitive = primitive.clone(); + if primitive.kind() == PrimitiveKind::NativeView { + self.insert_layer_part(std::mem::take(&mut part)); + self.insert_layer_part(vec![primitive]); + } else { + part.push(primitive); + } + } + self.insert_layer_part(part); + } + + fn insert_layer_part(&mut self, primitives: Vec) { + let Some(first) = primitives.first() else { + return; + }; + let mut bounds = first.clipped_bounds(); + let mut max_kind = PrimitiveKind::Shadow; + let mut max_shared_kind = PrimitiveKind::NativeView; + for primitive in &primitives { + let kind = primitive.kind(); + bounds = bounds.join(&primitive.clipped_bounds()); + max_kind = max_kind.max(kind); + max_shared_kind = max_shared_kind.min(kind.max_shared_kind()); + } + let order = self + .primitive_bounds + .insert(bounds, max_kind, max_shared_kind); + for primitive in primitives { + self.push_primitive(primitive, order); + } + } + pub fn insert_primitive(&mut self, primitive: impl Into) { self.try_insert_primitive(primitive.into()); } @@ -181,6 +235,7 @@ impl Scene { layer.bounds = layer.bounds.join(&clipped_bounds); layer.max_kind = layer.max_kind.max(kind); layer.max_shared_kind = layer.max_shared_kind.min(kind.max_shared_kind()); + layer.has_native_view |= kind == PrimitiveKind::NativeView; let index = self.paint_operations.len(); match layer.primitives.last_mut() { Some(range) if range.end == index => range.end += 1, @@ -221,6 +276,10 @@ impl Scene { surface.order = order; self.surfaces.push(surface); } + Primitive::NativeView(native_view) => self.native_views.push(PaintNativeView { + order, + ..native_view + }), } } @@ -261,6 +320,15 @@ impl Scene { (sprite.order, sprite.tile.texture_id.index) }); self.surfaces.sort_by_key(|surface| surface.order); + self.native_views + .sort_by_key(|native_view| native_view.order); + // A platform view can only be in one place, which is where it was painted first. + let mut shown = Vec::new(); + self.native_views.retain(|native_view| { + let is_first = !shown.contains(&native_view.id); + shown.push(native_view.id); + is_first + }); // Sorting moved the sprites, so animations learn where theirs ended up. if !self.animations.is_empty() { @@ -297,6 +365,8 @@ impl Scene { polychrome_sprites_iter: self.polychrome_sprites.iter().peekable(), surfaces_start: 0, surfaces_iter: self.surfaces.iter().peekable(), + native_views_start: 0, + native_views_iter: self.native_views.iter().peekable(), } } } @@ -370,6 +440,7 @@ pub(crate) enum PrimitiveKind { SubpixelSprite, PolychromeSprite, Surface, + NativeView, } impl PrimitiveKind { @@ -406,6 +477,7 @@ pub enum Primitive { SubpixelSprite(SubpixelSprite), PolychromeSprite(PolychromeSprite), Surface(PaintSurface), + NativeView(PaintNativeView), } #[expect(missing_docs)] @@ -420,6 +492,7 @@ impl Primitive { Primitive::SubpixelSprite(_) => PrimitiveKind::SubpixelSprite, Primitive::PolychromeSprite(_) => PrimitiveKind::PolychromeSprite, Primitive::Surface(_) => PrimitiveKind::Surface, + Primitive::NativeView(_) => PrimitiveKind::NativeView, } } @@ -433,6 +506,7 @@ impl Primitive { Primitive::SubpixelSprite(sprite) => &sprite.bounds, Primitive::PolychromeSprite(sprite) => &sprite.bounds, Primitive::Surface(surface) => &surface.bounds, + Primitive::NativeView(native_view) => &native_view.bounds, } } @@ -460,6 +534,7 @@ impl Primitive { Primitive::SubpixelSprite(sprite) => &sprite.content_mask, Primitive::PolychromeSprite(sprite) => &sprite.content_mask, Primitive::Surface(surface) => &surface.content_mask, + Primitive::NativeView(native_view) => &native_view.content_mask, } } } @@ -488,6 +563,8 @@ struct BatchIterator<'a> { polychrome_sprites_iter: Peekable>, surfaces_start: usize, surfaces_iter: Peekable>, + native_views_start: usize, + native_views_iter: Peekable>, } impl<'a> Iterator for BatchIterator<'a> { @@ -524,6 +601,12 @@ impl<'a> Iterator for BatchIterator<'a> { self.surfaces_iter.peek().map(|s| s.order), PrimitiveKind::Surface, ), + ( + self.native_views_iter + .peek() + .map(|native_view| native_view.order), + PrimitiveKind::NativeView, + ), ]; orders_and_kinds.sort_by_key(|(order, kind)| (order.unwrap_or(u32::MAX), *kind)); @@ -669,6 +752,22 @@ impl<'a> Iterator for BatchIterator<'a> { self.surfaces_start = surfaces_end; Some(PrimitiveBatch::Surfaces(surfaces_start..surfaces_end)) } + PrimitiveKind::NativeView => { + let native_views_start = self.native_views_start; + let mut native_views_end = native_views_start + 1; + self.native_views_iter.next(); + while self + .native_views_iter + .next_if(|native_view| (native_view.order, batch_kind) < max_order_and_kind) + .is_some() + { + native_views_end += 1; + } + self.native_views_start = native_views_end; + Some(PrimitiveBatch::NativeViews( + native_views_start..native_views_end, + )) + } } } } @@ -701,6 +800,7 @@ pub enum PrimitiveBatch { range: Range, }, Surfaces(Range), + NativeViews(Range), } impl PrimitiveBatch { @@ -733,6 +833,7 @@ impl PrimitiveBatch { ) } Self::Surfaces(range) => format!("surfaces ({})", range.len()), + Self::NativeViews(range) => format!("native views ({})", range.len()), } } } @@ -1057,6 +1158,34 @@ impl From for Primitive { } } +/// Where a platform view shows through the scene. +/// +/// The view sits beneath the window's rendered content, so the renderer +/// erases everything painted earlier within these bounds, and everything +/// painted later covers the view. The view is therefore treated as opaque. +#[derive(Clone, Copy, Debug)] +pub struct PaintNativeView { + /// The view's position among the scene's other primitives. + pub order: DrawOrder, + /// The view these bounds belong to. + pub id: NativeViewId, + /// The hitbox that decides whether a mouse position reaches the view. + pub hitbox_id: HitboxId, + /// Where the view is laid out, before clipping. + pub bounds: Bounds, + /// The clip applied to the view. + pub content_mask: ContentMask, + /// The color to show where the view has not caught up with these bounds, + /// or a transparent color for none. + pub background: Hsla, +} + +impl From for Primitive { + fn from(native_view: PaintNativeView) -> Self { + Primitive::NativeView(native_view) + } +} + #[derive(Clone, Copy, Debug, PartialEq)] #[repr(C)] #[expect(missing_docs)] @@ -1197,6 +1326,29 @@ mod tests { scene.batches().map(|batch| batch.label()).collect() } + #[test] + fn a_native_view_in_a_layer_is_covered_by_what_the_layer_paints_after_it() { + let mut scene = Scene::default(); + scene.push_layer(); + scene.insert_primitive(quad(0.)); + scene.insert_primitive(PaintNativeView { + order: 0, + id: NativeViewId::for_test(1), + hitbox_id: HitboxId::placeholder(), + bounds: square(0.), + content_mask: ContentMask { bounds: square(0.) }, + background: Hsla::default(), + }); + scene.insert_primitive(quad(0.)); + // A quad beside the view shares nothing with it, so it isn't held back. + scene.insert_primitive(quad(20.)); + scene.pop_layer(); + assert_eq!( + batch_labels(&mut scene), + ["quads (1)", "native views (1)", "quads (2)"] + ); + } + #[test] fn layers_are_drawn_in_paint_order() { // A quad painted after a layer goes above it. diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index 5b8f5deb86b..742891b5e87 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -68,9 +68,12 @@ use std::{ use uuid::Uuid; pub(crate) mod a11y; +mod native_view; mod prompts; pub use a11y::A11ySubtreeBuilder; +use native_view::NativeViewState; +pub use native_view::{NativeView, NativeViewId}; use self::a11y::A11y; #[cfg(not(target_family = "wasm"))] @@ -1264,6 +1267,8 @@ pub struct Window { pub(crate) rendered_frame: Frame, pub(crate) next_frame: Frame, next_hitbox_id: HitboxId, + native_views: Vec>, + next_native_view_id: u64, pub(crate) next_tooltip_id: TooltipId, pub(crate) tooltip_bounds: Option, pub(crate) next_frame_callbacks: Rc>>, @@ -2313,6 +2318,40 @@ impl Window { .unwrap_or(None) }) }); + platform_window.on_hit_test_native_view({ + let mut cx = cx.to_async(); + Box::new(move |position| { + // The platform can ask while this window is already being + // updated, in which case the event stays with GPUI. + handle + .update(&mut cx, |_, window, _| { + window.hit_test_native_view(position) + }) + .ok() + .flatten() + }) + }); + platform_window.on_key_down_before_native_view({ + let mut cx = cx.to_async(); + Box::new(move |event| { + handle + .update(&mut cx, |_, window, cx| { + window.dispatch_key_down_before_native_view(event, cx) + }) + .unwrap_or(false) + }) + }); + platform_window.on_native_view_focused({ + let mut cx = cx.to_async(); + Box::new(move |id| { + handle + .update(&mut cx, |_, window, cx| window.focus_native_view(id, cx)) + .with_context(|| { + format!("focusing a native view in window {:?}", handle.window_id()) + }) + .log_err(); + }) + }); platform_window.on_move_tab_to_new_window({ let mut cx = cx.to_async(); Box::new(move || { @@ -2420,6 +2459,8 @@ impl Window { next_frame: Frame::new(DispatchTree::new(cx.keymap.clone(), cx.actions.clone())), next_frame_callbacks, next_hitbox_id: HitboxId(0), + native_views: Vec::new(), + next_native_view_id: 0, next_tooltip_id: TooltipId::default(), tooltip_bounds: None, dirty_views: FxHashSet::default(), @@ -2725,7 +2766,9 @@ impl Window { return; } + self.end_composition_before_focusing_native_view(handle.id, cx); self.focus = Some(handle.id); + self.sync_native_view_focus(); self.focus_generation = self.focus_generation.wrapping_add(1); self.clear_pending_keystrokes(cx); @@ -2744,6 +2787,7 @@ impl Window { self.focus_generation = self.focus_generation.wrapping_add(1); } self.focus = None; + self.sync_native_view_focus(); self.refresh(); } diff --git a/crates/gpui/src/window/native_view.rs b/crates/gpui/src/window/native_view.rs new file mode 100644 index 00000000000..66282e30dc1 --- /dev/null +++ b/crates/gpui/src/window/native_view.rs @@ -0,0 +1,815 @@ +use crate::{Action, KeyBinding, KeyDownEvent, PlatformInput}; +use crate::{ + AnyWindowHandle, App, Bounds, Element, ElementId, FocusHandle, FocusId, Focusable, + GlobalElementId, Hitbox, HitboxBehavior, Hsla, InspectorElementId, InteractiveElement, + IntoElement, LayoutId, PaintNativeView, ParentElement, Pixels, Point, Style, Styled, Window, + div, +}; +use anyhow::{Context as _, Result}; +use collections::HashSet; +use std::{ + any::{Any, TypeId}, + cell::{Cell, RefCell}, + ffi::c_void, + ptr::NonNull, + rc::{Rc, Weak}, +}; + +/// Identifies a [`NativeView`] within its window. +#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +pub struct NativeViewId(u64); + +#[cfg(any(test, feature = "test-support"))] +impl NativeViewId { + /// Makes an ID for a test that needs one without a window to attach a view to. + pub fn for_test(id: u64) -> Self { + Self(id) + } +} + +/// A view owned by the platform's UI toolkit, shown inside a GPUI window. +/// +/// Only macOS shows native views so far, where the view is an `NSView`. +/// [`NativeView::new`] fails on every other platform. +/// +/// The view is composited beneath the window's GPUI content and shows through +/// wherever this handle is used as an element, so elements painted after it +/// cover it like they would cover any other element. The view is treated as +/// opaque, and is not affected by element opacity or transformations. +/// +/// Mouse input over the view goes to the view, and to nothing behind it, +/// wherever no element painted after the view takes mouse input. An element +/// that is only drawn over the view covers it without taking its mouse input. The window's own content is still told of a mouse press +/// there, as a press outside every element. An element behind the view hears +/// no mouse moves while the pointer is over it, so follow a drag that can cross +/// the view with `on_drag_move`, or with an element in front of the view. +/// +/// The view takes keyboard input directly from the platform while its +/// [`FocusHandle`] is focused, which a click on the view does, as can an +/// assistive technology such as VoiceOver moving its cursor into the view. +/// A key the view doesn't use is then dispatched from the view's element like +/// any other key press, so key bindings apply to what the view leaves. +/// +/// Two kinds of key reach key bindings before the view. Bindings for actions +/// passed to [`reserve_action`](Self::reserve_action) apply first, and their +/// keys never reach the view. A key held with Command or Control is offered to +/// the view as a key equivalent, which is how a web view takes it; a view that +/// only takes such keys as ordinary key presses, as AppKit's text views do, +/// gets one after key bindings have had it. +/// +/// The view may take a moment to leave a key, so the keys of any other +/// multi-key binding can reach the view when they are typed quickly. +/// +/// The view stays attached to the window it was created in, hidden when it +/// isn't painted, until the last clone of this handle is dropped. Painted more +/// than once in a frame, it shows only where it was painted first. It shows +/// nothing as an element of any other window, so showing the same platform +/// view in another window takes dropping this handle and creating one there. +#[derive(Clone)] +pub struct NativeView(Rc); + +pub(crate) struct NativeViewState { + id: NativeViewId, + window: AnyWindowHandle, + focus_handle: FocusHandle, + background: Cell, + reserved_actions: RefCell>, + _attachment: Box, +} + +impl NativeView { + /// Attaches a platform view to the window. + /// + /// # Errors + /// + /// Fails on platforms that cannot composite native views, which is every + /// platform but macOS for now. + /// + /// # Safety + /// + /// `view` must point to a live view of the kind the window's platform + /// embeds, which is an `NSView` on macOS, and that view must not be in + /// another view hierarchy. + /// + /// GPUI retains the view and puts it inside a view of its own, until the + /// last clone of the returned handle is dropped. Until then GPUI decides the + /// view's frame, whether it is hidden, and its order among the window's other + /// views, so the caller must leave those alone and must not move the view to + /// another superview. + pub unsafe fn new(view: NonNull, window: &mut Window, cx: &mut App) -> Result { + let id = NativeViewId(window.next_native_view_id); + // SAFETY: The caller upholds the platform's requirements for `view`. + let attachment = unsafe { window.platform_window.attach_native_view(id, view) } + .context("this platform cannot show native views")?; + window.next_native_view_id += 1; + let state = Rc::new(NativeViewState { + id, + window: window.handle, + focus_handle: cx.focus_handle(), + background: Cell::new(Hsla::transparent_black()), + reserved_actions: RefCell::default(), + _attachment: attachment, + }); + window.native_views.push(Rc::downgrade(&state)); + Ok(Self(state)) + } +} + +impl NativeView { + /// Sets the color shown where the view has not caught up with its element. + /// + /// The platform moves the view through its own compositor, so for a frame + /// or two after its element moves or resizes, part of the element can be + /// uncovered. A color close to the view's own background hides that. A + /// window showing several native views uses the color of the one painted + /// last. + pub fn set_background(&self, color: impl Into, cx: &mut App) { + let color = color.into(); + if self.0.background.replace(color) == color { + return; + } + // The color is part of what the element paints. + let window = self.0.window; + cx.defer(move |cx| { + window.update(cx, |_, window, _| window.refresh()).ok(); + }); + } + + /// Makes key bindings for `A` apply before the view sees the key. + /// + /// The view otherwise sees every key first and can keep any of them, so + /// this is for the few bindings that must work whatever the view shows. + /// The view never sees a key that such a binding starts with, even when the + /// rest of the binding's keys don't follow. + pub fn reserve_action(&self) { + self.0 + .reserved_actions + .borrow_mut() + .insert(TypeId::of::()); + } +} + +impl Focusable for NativeView { + fn focus_handle(&self, _: &App) -> FocusHandle { + self.0.focus_handle.clone() + } +} + +impl IntoElement for NativeView { + type Element = crate::Div; + + fn into_element(self) -> Self::Element { + div() + .track_focus(&self.0.focus_handle) + .size_full() + .child(NativeViewElement(self)) + } +} + +struct NativeViewElement(NativeView); + +impl Element for NativeViewElement { + type RequestLayoutState = (); + /// `None` in a window other than the one the view is attached to. + type PrepaintState = Option; + + fn id(&self) -> Option { + None + } + + fn source_location(&self) -> Option<&'static core::panic::Location<'static>> { + None + } + + fn request_layout( + &mut self, + _id: Option<&GlobalElementId>, + _inspector_id: Option<&InspectorElementId>, + window: &mut Window, + cx: &mut App, + ) -> (LayoutId, Self::RequestLayoutState) { + let mut style = Style::default(); + style.size.width = crate::relative(1.).into(); + style.size.height = crate::relative(1.).into(); + (window.request_layout(style, [], cx), ()) + } + + fn prepaint( + &mut self, + _id: Option<&GlobalElementId>, + _inspector_id: Option<&InspectorElementId>, + bounds: Bounds, + _request_layout: &mut Self::RequestLayoutState, + window: &mut Window, + _cx: &mut App, + ) -> Option { + (self.0.0.window == window.handle) + .then(|| window.insert_hitbox(bounds, HitboxBehavior::BlockMouse)) + } + + fn paint( + &mut self, + _id: Option<&GlobalElementId>, + _inspector_id: Option<&InspectorElementId>, + _bounds: Bounds, + _request_layout: &mut Self::RequestLayoutState, + hitbox: &mut Option, + window: &mut Window, + _cx: &mut App, + ) { + let Some(hitbox) = hitbox else { + return; + }; + let id = self.0.0.id; + let bounds = window.snap_bounds(hitbox.bounds); + let content_mask = window.snapped_content_mask(); + window.next_frame.scene.insert_primitive(PaintNativeView { + order: 0, + id, + hitbox_id: hitbox.id, + bounds, + content_mask, + background: self.0.0.background.get(), + }); + } +} + +impl Window { + /// Tells the platform which native view, if any, the focused handle belongs to. + pub(super) fn sync_native_view_focus(&mut self) { + self.native_views.retain(|view| view.strong_count() > 0); + if self.native_views.is_empty() { + return; + } + let focused = self + .focus + .and_then(|focus| self.native_view_for_focus(focus)); + self.platform_window.set_focused_native_view(focused); + } + + /// Ends an unfinished composition in the window's own content when keyboard + /// input is about to move to a native view. + /// + /// The platform also asks for this as its own view loses keyboard input, but + /// that request needs the app, which is already borrowed when focus is moved + /// from inside an update. The entity being updated may also be the one that + /// holds the composition, so this waits for the update to end. + pub(super) fn end_composition_before_focusing_native_view( + &mut self, + focus: FocusId, + cx: &mut App, + ) { + if self.native_view_for_focus(focus).is_none() { + return; + } + self.defer(cx, |window, cx| { + if let Some(mut input_handler) = window.platform_window.take_input_handler() { + input_handler.unmark_text_during_update(window, cx); + window.platform_window.set_input_handler(input_handler); + } + }); + } + + fn native_view_for_focus(&self, focus: FocusId) -> Option { + self.native_views + .iter() + .filter_map(Weak::upgrade) + .find(|view| view.focus_handle.id == focus) + .map(|view| view.id) + } + + /// The native view that a mouse event at this position reaches, if no + /// GPUI hitbox is above it there. + pub(super) fn hit_test_native_view(&self, position: Point) -> Option { + let hit_test = self.rendered_frame.hit_test(position); + let topmost = hit_test.ids.first()?; + self.rendered_frame + .scene + .native_views + .iter() + .find(|native_view| native_view.hitbox_id == *topmost) + .map(|native_view| native_view.id) + } + + /// Dispatches a key press that the focused native view has not seen yet, if + /// it continues a pending binding or is bound to an action the view reserved. + pub(super) fn dispatch_key_down_before_native_view( + &mut self, + event: KeyDownEvent, + cx: &mut App, + ) -> bool { + let Some(view) = self + .native_views + .iter() + .filter_map(Weak::upgrade) + .find(|view| Some(view.focus_handle.id) == self.focus) + else { + return false; + }; + let node_id = self.focus_node_id_in_rendered_frame(self.focus); + let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id); + let dispatch_tree = &self.rendered_frame.dispatch_tree; + // A key that doesn't continue what is pending is left for the view like + // any other. Dispatching it here as well would dispatch it twice when + // the view then leaves it. + let continues_pending = self.pending_input_keystrokes().is_some_and(|pending| { + let mut input = pending.to_vec(); + input.push(event.keystroke.clone()); + let (bindings, is_pending, _) = + dispatch_tree.bindings_for_input(&input, &dispatch_path); + is_pending || !bindings.is_empty() + }); + if !continues_pending { + let input = std::slice::from_ref(&event.keystroke); + let (bindings, _, context_stack) = + dispatch_tree.bindings_for_input(input, &dispatch_path); + let reserved_actions = view.reserved_actions.borrow(); + let is_reserved = |binding: &KeyBinding| { + reserved_actions.contains(&binding.action.as_any().type_id()) + }; + // The first key of a longer binding is reserved too, or the view + // could keep that key and the binding would never begin. + let is_reserved = bindings.first().is_some_and(is_reserved) + || dispatch_tree + .possible_next_bindings_for_input(input, &context_stack) + .iter() + .any(is_reserved); + if !is_reserved { + return false; + } + } + // The key is GPUI's whether or not anything acts on it. Leaving it to + // the view as well would have it dispatched again when the view left it. + self.dispatch_event(PlatformInput::KeyDown(event), cx); + true + } + + /// Focuses the handle of a native view that the platform gave keyboard input to. + pub(super) fn focus_native_view(&mut self, id: NativeViewId, cx: &mut App) { + let view = self + .native_views + .iter() + .filter_map(Weak::upgrade) + .find(|view| view.id == id); + if let Some(view) = view { + self.focus(&view.focus_handle, cx); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + Context, Entity, FocusHandle, InputHandler, KeyBinding, Keystroke, Modifiers, MouseButton, + Render, ScaledPixels, TestAppContext, UTF16Selection, VisualTestContext, WindowHandle, + canvas, point, prelude::*, px, rgb, + }; + use std::ops::Range; + + #[gpui::test] + fn focusing_a_native_view_gives_it_keyboard_input(cx: &mut TestAppContext) { + let window = open_window(cx); + let platform_window = cx.test_window(window.into()); + + let id = window + .update(cx, |view, window, cx| { + window.focus(&view.native_view.focus_handle(cx), cx); + view.native_view.0.id + }) + .unwrap(); + assert_eq!(platform_window.focused_native_view(), Some(id)); + + window + .update(cx, |view, window, cx| window.focus(&view.other_focus, cx)) + .unwrap(); + assert_eq!(platform_window.focused_native_view(), None); + + window + .update(cx, |view, window, cx| { + window.focus(&view.native_view.focus_handle(cx), cx); + window.blur(cx); + }) + .unwrap(); + assert_eq!(platform_window.focused_native_view(), None); + } + + #[gpui::test] + fn platform_focus_of_a_native_view_focuses_its_handle(cx: &mut TestAppContext) { + let window = open_window(cx); + let platform_window = cx.test_window(window.into()); + let id = window + .update(cx, |view, window, cx| { + window.focus(&view.other_focus, cx); + view.native_view.0.id + }) + .unwrap(); + + platform_window.simulate_native_view_focused(id); + + window + .update(cx, |view, window, cx| { + assert!(view.native_view.focus_handle(cx).is_focused(window)); + }) + .unwrap(); + assert_eq!(platform_window.focused_native_view(), Some(id)); + } + + #[gpui::test] + fn only_reserved_and_pending_bindings_apply_before_a_native_view(cx: &mut TestAppContext) { + cx.update(|cx| { + cx.bind_keys([ + KeyBinding::new("cmd-r", Reserved, None), + KeyBinding::new("cmd-o", Ordinary, None), + KeyBinding::new("cmd-k o", Ordinary, None), + KeyBinding::new("cmd-j r", Reserved, None), + ]); + }); + let window = open_window(cx); + let platform_window = cx.test_window(window.into()); + window + .update(cx, |view, window, cx| { + view.native_view.reserve_action::(); + window.focus(&view.native_view.focus_handle(cx), cx); + }) + .unwrap(); + cx.run_until_parked(); + let press = |keystroke: &'static str| KeyDownEvent { + keystroke: Keystroke::parse(keystroke).unwrap(), + is_held: false, + prefer_character_input: false, + }; + let actions = |cx: &mut TestAppContext| { + window + .update(cx, |view, _, _| std::mem::take(&mut view.actions)) + .unwrap() + }; + + assert!(platform_window.simulate_key_down_before_native_view(press("cmd-r"))); + assert_eq!(actions(cx), ["reserved"]); + + // The view gets to see an ordinary binding's key first. + assert!(!platform_window.simulate_key_down_before_native_view(press("cmd-o"))); + assert_eq!(actions(cx), [] as [&str; 0]); + + // Once the view has left the first key of a binding to GPUI, the rest + // of that binding's keys are GPUI's. + assert!(!platform_window.simulate_key_down_before_native_view(press("cmd-k"))); + cx.simulate_keystrokes(window.into(), "cmd-k"); + // A key that doesn't continue the binding is the view's to see first, + // and isn't dispatched here, which would dispatch it twice if the view + // then left it. + assert!(!platform_window.simulate_key_down_before_native_view(press("x"))); + assert!( + window + .update(cx, |_, window, _| window.has_pending_keystrokes()) + .unwrap() + ); + assert!(platform_window.simulate_key_down_before_native_view(press("o"))); + assert_eq!(actions(cx), ["ordinary"]); + + // The view never sees the first key of a reserved binding, which it + // could otherwise keep. + assert!(platform_window.simulate_key_down_before_native_view(press("cmd-j"))); + assert!(platform_window.simulate_key_down_before_native_view(press("r"))); + assert_eq!(actions(cx), ["reserved"]); + + // Nothing applies ahead of the window's own content. + window + .update(cx, |view, window, cx| window.focus(&view.other_focus, cx)) + .unwrap(); + assert!(!platform_window.simulate_key_down_before_native_view(press("cmd-r"))); + } + + #[gpui::test] + fn mouse_reaches_a_native_view_only_where_nothing_covers_it(cx: &mut TestAppContext) { + let window = open_window(cx); + let platform_window = cx.test_window(window.into()); + let id = window + .update(cx, |view, _, _| view.native_view.0.id) + .unwrap(); + cx.run_until_parked(); + + let uncovered = point(px(75.), px(75.)); + let covered = point(px(25.), px(25.)); + let outside = point(px(150.), px(150.)); + assert_eq!(platform_window.hit_test_native_view(uncovered), Some(id)); + assert_eq!(platform_window.hit_test_native_view(covered), None); + assert_eq!(platform_window.hit_test_native_view(outside), None); + } + + #[gpui::test] + fn mouse_press_on_a_native_view_reaches_nothing_behind_it(cx: &mut TestAppContext) { + let window = open_window(cx); + cx.run_until_parked(); + let mut cx = VisualTestContext::from_window(window.into(), cx); + + // The platform passes on a press that it gives to the view. + cx.simulate_mouse_down( + point(px(75.), px(75.)), + MouseButton::Left, + Modifiers::default(), + ); + + let presses = window + .update(&mut cx, |view, _, _| std::mem::take(&mut view.presses)) + .unwrap(); + assert_eq!(presses, ["outside cover"]); + } + + #[gpui::test] + fn changing_the_background_repaints_the_native_view(cx: &mut TestAppContext) { + let window = open_window(cx); + cx.run_until_parked(); + + window + .update(cx, |view, _, cx| { + view.native_view.set_background(rgb(0x00ff00), cx); + }) + .unwrap(); + cx.run_until_parked(); + + window + .update(cx, |_, window, _| { + let backgrounds = window + .rendered_frame + .scene + .native_views + .iter() + .map(|native_view| native_view.background) + .collect::>(); + assert_eq!(backgrounds, [Hsla::from(rgb(0x00ff00))]); + }) + .unwrap(); + } + + #[gpui::test] + fn native_view_painted_twice_shows_where_it_was_painted_first(cx: &mut TestAppContext) { + let window = open_window(cx); + window + .update(cx, |view, _, cx| { + view.paints_native_view_twice = true; + cx.notify(); + }) + .unwrap(); + cx.run_until_parked(); + + window + .update(cx, |_, window, _| { + let bounds = window + .rendered_frame + .scene + .native_views + .iter() + .map(|native_view| native_view.bounds.origin.x) + .collect::>(); + assert_eq!(bounds, [ScaledPixels::from(0.)]); + }) + .unwrap(); + } + + #[gpui::test] + fn native_view_is_drawn_in_paint_order(cx: &mut TestAppContext) { + let window = open_window(cx); + cx.run_until_parked(); + + // The view shows through its container's background, and the element + // painted after it covers it. + window + .update(cx, |_, window, _| { + let labels = window + .rendered_frame + .scene + .batches() + .map(|batch| batch.label()) + .collect::>(); + assert_eq!(labels, ["quads (1)", "native views (1)", "quads (1)"]); + }) + .unwrap(); + } + + #[gpui::test] + fn native_view_stays_attached_until_its_last_handle_is_dropped(cx: &mut TestAppContext) { + let window = open_window(cx); + let platform_window = cx.test_window(window.into()); + let other_handle = window + .update(cx, |view, _, _| view.native_view.clone()) + .unwrap(); + assert_eq!(platform_window.attached_native_view_count(), 1); + + window + .update(cx, |view, window, cx| { + view.native_view = new_native_view(window, cx); + }) + .unwrap(); + assert_eq!(platform_window.attached_native_view_count(), 2); + + drop(other_handle); + assert_eq!(platform_window.attached_native_view_count(), 1); + } + + #[gpui::test] + fn native_view_shows_nothing_in_another_window(cx: &mut TestAppContext) { + let window = open_window(cx); + let native_view = window + .update(cx, |view, _, _| view.native_view.clone()) + .unwrap(); + let other_window = cx.add_window(|_, cx| TestView { + native_view, + other_focus: cx.focus_handle(), + actions: Vec::new(), + presses: Vec::new(), + paints_native_view_twice: false, + unmark_count: 0, + }); + cx.run_until_parked(); + + other_window + .update(cx, |_, window, _| { + assert!(window.rendered_frame.scene.native_views.is_empty()); + }) + .unwrap(); + window + .update(cx, |_, window, _| { + assert_eq!(window.rendered_frame.scene.native_views.len(), 1); + }) + .unwrap(); + } + + #[gpui::test] + fn focusing_a_native_view_ends_a_composition(cx: &mut TestAppContext) { + let window = open_window(cx); + window + .update(cx, |view, window, cx| window.focus(&view.other_focus, cx)) + .unwrap(); + cx.run_until_parked(); + + // The view that holds the composition moves focus from inside its own + // update, so the composition can only be ended once that is over. + window + .update(cx, |view, window, cx| { + window.focus(&view.native_view.focus_handle(cx), cx); + }) + .unwrap(); + let unmark_count = window.update(cx, |view, _, _| view.unmark_count).unwrap(); + assert_eq!(unmark_count, 1); + } + + actions!(native_view_tests, [Reserved, Ordinary]); + + struct TestView { + native_view: NativeView, + other_focus: FocusHandle, + actions: Vec<&'static str>, + presses: Vec<&'static str>, + paints_native_view_twice: bool, + /// How many times the input handler of the "cover" element was told to + /// end its composition. + unmark_count: usize, + } + + impl Render for TestView { + fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + div() + .size_full() + .on_action(cx.listener(|this, _: &Reserved, _, _| this.actions.push("reserved"))) + .on_action(cx.listener(|this, _: &Ordinary, _, _| this.actions.push("ordinary"))) + .child( + div() + .absolute() + .top_0() + .left_0() + .size(px(100.)) + .bg(rgb(0xff0000)) + .on_mouse_down( + MouseButton::Left, + cx.listener(|this, _, _, _| this.presses.push("behind view")), + ) + .child(self.native_view.clone()), + ) + .when(self.paints_native_view_twice, |this| { + this.child( + div() + .absolute() + .top_0() + .left(px(200.)) + .size(px(100.)) + .child(self.native_view.clone()), + ) + }) + .child( + div() + .id("cover") + .track_focus(&self.other_focus) + .absolute() + .top_0() + .left_0() + .size(px(50.)) + .occlude() + .bg(rgb(0x0000ff)) + .on_mouse_down_out( + cx.listener(|this, _, _, _| this.presses.push("outside cover")), + ) + .child({ + let focus = self.other_focus.clone(); + let view = cx.entity(); + canvas( + |_, _, _| {}, + move |_, _, window, cx| { + window.handle_input(&focus, TestInput { view }, cx); + }, + ) + .size_full() + }), + ) + } + } + + /// Reaches its view as an element's input handler does, by updating it. + struct TestInput { + view: Entity, + } + + impl InputHandler for TestInput { + fn selected_text_range( + &mut self, + _: bool, + _: &mut Window, + _: &mut App, + ) -> Option { + None + } + + fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option> { + None + } + + fn text_for_range( + &mut self, + _: Range, + _: &mut Option>, + _: &mut Window, + _: &mut App, + ) -> Option { + None + } + + fn replace_text_in_range( + &mut self, + _: Option>, + _: &str, + _: &mut Window, + _: &mut App, + ) { + } + + fn replace_and_mark_text_in_range( + &mut self, + _: Option>, + _: &str, + _: Option>, + _: &mut Window, + _: &mut App, + ) { + } + + fn unmark_text(&mut self, _: &mut Window, cx: &mut App) { + self.view.update(cx, |view, _| view.unmark_count += 1); + } + + fn bounds_for_range( + &mut self, + _: Range, + _: &mut Window, + _: &mut App, + ) -> Option> { + None + } + + fn character_index_for_point( + &mut self, + _: Point, + _: &mut Window, + _: &mut App, + ) -> Option { + None + } + } + + fn open_window(cx: &mut TestAppContext) -> WindowHandle { + cx.add_window(|window, cx| TestView { + native_view: new_native_view(window, cx), + other_focus: cx.focus_handle(), + actions: Vec::new(), + presses: Vec::new(), + paints_native_view_twice: false, + unmark_count: 0, + }) + } + + fn new_native_view(window: &mut Window, cx: &mut App) -> NativeView { + // SAFETY: The test platform never reads the view it is given. + unsafe { NativeView::new(NonNull::dangling(), window, cx) } + .expect("the test platform attaches native views") + } +} diff --git a/crates/gpui_apple/src/metal_renderer.rs b/crates/gpui_apple/src/metal_renderer.rs index 86eff3d48b5..33c529972e1 100644 --- a/crates/gpui_apple/src/metal_renderer.rs +++ b/crates/gpui_apple/src/metal_renderer.rs @@ -129,6 +129,8 @@ pub struct MetalRenderer { display_link_mode: DisplayLinkMode, /// For headless rendering, tracks whether output should be opaque opaque: bool, + /// Whether the last scene drawn to the layer let native views show through it. + shows_native_views: bool, command_queue: Retained>, path_tiles_pipeline_state: Retained>, shadows_pipeline_state: Retained>, @@ -138,6 +140,7 @@ pub struct MetalRenderer { monochrome_sprites_pipeline_state: Retained>, polychrome_sprites_pipeline_state: Retained>, surfaces_pipeline_state: Retained>, + native_views_pipeline_state: Retained>, depth_write_state: Retained>, depth_test_state: Retained>, depth_texture: Option>>, @@ -354,6 +357,16 @@ impl MetalRenderer { MTLPixelFormat::BGRA8Unorm, true, )?; + // Blending is off so that the transparent output replaces what was drawn beneath it. + let native_views_pipeline_state = build_pipeline_state( + &device, + &library, + "native_views", + "native_view_vertex", + "native_view_fragment", + MTLPixelFormat::BGRA8Unorm, + false, + )?; let depth_write_state = build_depth_stencil_state(&device, true)?; let depth_test_state = build_depth_stencil_state(&device, false)?; @@ -386,6 +399,7 @@ impl MetalRenderer { is_apple_gpu, is_unified_memory, opaque, + shows_native_views: false, command_queue, path_tiles_pipeline_state, shadows_pipeline_state, @@ -395,6 +409,7 @@ impl MetalRenderer { monochrome_sprites_pipeline_state, polychrome_sprites_pipeline_state, surfaces_pipeline_state, + native_views_pipeline_state, depth_write_state, depth_test_state, depth_texture: None, @@ -485,7 +500,7 @@ impl MetalRenderer { pub fn update_transparency(&mut self, transparent: bool) { self.opaque = !transparent; if let Some(layer) = &self.layer { - layer.setOpaque(!transparent); + layer.setOpaque(self.opaque && !self.shows_native_views); } } @@ -503,6 +518,13 @@ impl MetalRenderer { return; } }; + // Native views sit beneath the layer, so it can only be opaque, and + // eligible for direct-to-display presentation, while none are showing. + let shows_native_views = !scene.native_views.is_empty(); + if shows_native_views != self.shows_native_views { + self.shows_native_views = shows_native_views; + layer.setOpaque(self.opaque && !shows_native_views); + } let drawable = match &mut self.display_link_mode { DisplayLinkMode::Attached { drawable } => { let Some(drawable) = drawable.take() else { @@ -849,6 +871,9 @@ impl MetalRenderer { return Err(error); } } + PrimitiveBatch::NativeViews(range) => { + self.draw_native_views(range, instance_bindings, &command_encoder) + } PrimitiveBatch::SubpixelSprites { .. } => unreachable!(), } } @@ -927,6 +952,35 @@ impl MetalRenderer { } } + fn draw_native_views( + &self, + native_views: Range, + instance_bindings: &InstanceBindings, + command_encoder: &ProtocolObject, + ) { + if native_views.is_empty() { + return; + } + + command_encoder.setRenderPipelineState(&self.native_views_pipeline_state); + // SAFETY: The SurfaceBounds instances match the shader layout and slot. + // Metal retains the buffer, and writer.finish publishes its writes. + unsafe { + command_encoder.setVertexBuffer_offset_atIndex( + Some(&instance_bindings.native_views.buffer), + instance_bindings.native_views.offset, + SurfaceInputIndex::Surfaces as usize, + ); + command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( + MTLPrimitiveType::TriangleStrip, + 0, + 4, + native_views.len(), + native_views.start, + ); + } + } + fn draw_path_tiles( &self, tiles: Range, @@ -1421,6 +1475,7 @@ struct InstanceBindings { monochrome_sprites: InstanceBinding, polychrome_sprites: InstanceBinding, surfaces: InstanceBinding, + native_views: InstanceBinding, } fn write_instances(scene: &Scene, writer: &mut InstanceBufferWriter) -> Result { @@ -1443,6 +1498,12 @@ fn write_instances(scene: &Scene, writer: &mut InstanceBufferWriter) -> Result NSUInteger, ); + native_views::add_view_methods(&mut decl); decl.register() }; BLURRED_VIEW_CLASS = { @@ -413,6 +416,7 @@ unsafe fn build_window_class(name: &CStr, superclass: &AnyClass) -> *const AnyCl let mut decl = ClassBuilder::new(name, superclass).unwrap(); decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR); decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(_, Sel)); + native_views::add_window_methods(&mut decl); decl.add_method( sel!(canBecomeMainWindow), @@ -709,6 +713,7 @@ struct MacWindowState { accesskit_adapter: Option, // The parent window if this window is a sheet (Dialog kind) sheet_parent: Option<*mut AnyObject>, + native_views: native_views::NativeViews, } impl MacWindowState { @@ -1215,6 +1220,7 @@ impl MacWindow { closed: Arc::new(AtomicBool::new(false)), accesskit_adapter: None, sheet_parent: None, + native_views: native_views::NativeViews::default(), })); let mut window = Self(state, marker, metal_frames); @@ -1749,33 +1755,11 @@ impl PlatformWindow for MacWindow { } fn modifiers(&self) -> Modifiers { - unsafe { - let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags]; - - let control = modifiers.contains(NSEventModifierFlags::Control); - let alt = modifiers.contains(NSEventModifierFlags::Option); - let shift = modifiers.contains(NSEventModifierFlags::Shift); - let command = modifiers.contains(NSEventModifierFlags::Command); - let function = modifiers.contains(NSEventModifierFlags::Function); - - Modifiers { - control, - alt, - shift, - platform: command, - function, - } - } + current_modifiers() } fn capslock(&self) -> Capslock { - unsafe { - let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags]; - - Capslock { - on: modifiers.contains(NSEventModifierFlags::CapsLock), - } - } + current_capslock() } fn set_input_handler(&mut self, input_handler: PlatformInputHandler) { @@ -1954,6 +1938,7 @@ impl PlatformWindow for MacWindow { NSColor::colorWithSRGBRed_green_blue_alpha(0f64, 0f64, 0f64, 0.0001) }; let _: () = msg_send![this.native_window, setBackgroundColor: &*background_color]; + this.native_views.background = None; if background_appearance != WindowBackgroundAppearance::Blurred { if let Some(blur_view) = this.blurred_view { @@ -2201,7 +2186,41 @@ impl PlatformWindow for MacWindow { fn draw(&self, scene: &gpui::Scene) { let mut this = self.0.lock(); + let native_view_layout = native_views::plan_layout(&this, scene); + native_views::update_background(&mut this, scene); + native_views::scene_drawn(&mut this, scene); this.renderer.draw(scene); + drop(this); + native_views::apply_layout(&self.0, native_view_layout); + } + + unsafe fn attach_native_view( + &self, + id: gpui::NativeViewId, + view: NonNull, + ) -> Option> { + // SAFETY: The caller guarantees `view` is a live `NSView` with no superview, and + // platform windows are only used on the main thread. + unsafe { native_views::attach(&self.0, id, view) } + } + + fn set_focused_native_view(&self, id: Option) { + native_views::set_focused(&self.0, id); + } + + fn on_hit_test_native_view( + &self, + callback: Box) -> Option>, + ) { + self.0.lock().native_views.hit_test_callback = Some(callback); + } + + fn on_native_view_focused(&self, callback: Box) { + self.0.lock().native_views.focused_callback = Some(callback); + } + + fn on_key_down_before_native_view(&self, callback: Box bool>) { + self.0.lock().native_views.key_down_before_callback = Some(callback); } // GPUI calls this without waking the frame waker when a window only needs @@ -2599,6 +2618,36 @@ fn get_scale_factor(native_window: *mut AnyObject) -> f32 { } /// Returns whether `window` is one of GPUI's managed windows. +fn current_modifiers() -> Modifiers { + unsafe { + let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags]; + + let control = modifiers.contains(NSEventModifierFlags::Control); + let alt = modifiers.contains(NSEventModifierFlags::Option); + let shift = modifiers.contains(NSEventModifierFlags::Shift); + let command = modifiers.contains(NSEventModifierFlags::Command); + let function = modifiers.contains(NSEventModifierFlags::Function); + + Modifiers { + control, + alt, + shift, + platform: command, + function, + } + } +} + +fn current_capslock() -> Capslock { + unsafe { + let modifiers: NSEventModifierFlags = msg_send![class!(NSEvent), modifierFlags]; + + Capslock { + on: modifiers.contains(NSEventModifierFlags::CapsLock), + } + } +} + unsafe fn is_gpui_window(window: *mut AnyObject) -> bool { unsafe { msg_send![window, isKindOfClass: WINDOW_CLASS] @@ -2620,14 +2669,39 @@ unsafe fn get_window_state(object: &AnyObject) -> Rc> { } } -unsafe fn drop_window_state(object: &AnyObject) { +/// Returns the window state, or `None` before it is set or after it is dropped. +/// +/// AppKit can call methods it defines on a window, unlike the delegate methods +/// GPUI adds, while the window is still being initialized or deallocated. +unsafe fn window_state_if_set(object: &AnyObject) -> Option>> { unsafe { let raw = *object .class() .instance_variable(WINDOW_STATE_IVAR) .expect("GPUI window state ivar") .load::<*mut c_void>(object); - Rc::from_raw(raw as *mut Mutex); + if raw.is_null() { + return None; + } + let state = Rc::from_raw(raw as *mut Mutex); + let clone = state.clone(); + mem::forget(state); + Some(clone) + } +} + +unsafe fn drop_window_state(object: &AnyObject) { + unsafe { + let ivar = object + .class() + .instance_variable(WINDOW_STATE_IVAR) + .expect("GPUI window state ivar"); + let raw = *ivar.load::<*mut c_void>(object); + // Cleared so that anything the superclass calls while deallocating sees no state. + *ivar.load_ptr::<*mut c_void>(object) = ptr::null_mut(); + if !raw.is_null() { + drop(Rc::from_raw(raw as *mut Mutex)); + } } } @@ -2723,7 +2797,13 @@ extern "C" fn reset_cursor_rects(this: &AnyObject, _: Sel) { let _: () = msg_send![super(this, class!(NSView)), resetCursorRects]; let window_state = get_window_state(this); - let cursor_style = window_state.lock().cursor_style; + let cursor_style = { + let lock = window_state.lock(); + if native_views::native_view_sets_cursor(&lock) { + return; + } + lock.cursor_style + }; let cursor = native_cursor(cursor_style); @@ -2737,6 +2817,9 @@ extern "C" fn handle_key_equivalent( _: Sel, native_event: *mut AnyObject, ) -> Bool { + if native_views::is_routing_key_equivalent(&unsafe { get_window_state(this) }) { + return Bool::NO; + } handle_key_event(this, native_event, true) } @@ -3350,9 +3433,10 @@ extern "C" fn window_did_change_key_status(this: &AnyObject, selector: Sel, _: * let a11y_events = { let mut lock = window_state.lock(); + let is_focused = is_active && native_views::gpui_view_is_focused(&lock); lock.accesskit_adapter .as_mut() - .and_then(|adapter| adapter.update_view_focus_state(is_active)) + .and_then(|adapter| adapter.update_view_focus_state(is_focused)) }; if let Some(events) = a11y_events { events.raise(); @@ -3509,6 +3593,8 @@ extern "C" fn display_layer(this: &AnyObject, _: Sel, _: *mut AnyObject) { lock.request_frame_callback = Some(callback); lock.renderer.set_presents_with_transaction(false); lock.start_display_link(&window_state); + drop(lock); + native_views::check_pointer_after_frame(&window_state); } } @@ -3533,6 +3619,7 @@ extern "C" fn step(view: *mut c_void) { ..Default::default() }); window_state.lock().request_frame_callback = Some(callback); + native_views::check_pointer_after_frame(&window_state); } } @@ -3563,6 +3650,8 @@ fn metal_frame( // lets the link hand it out again. let used_drawable = lock.renderer.set_frame_drawable(None).is_none(); metal_frames.end_frame(used_drawable); + drop(lock); + native_views::check_pointer_after_frame(window_state); } extern "C" fn valid_attributes_for_marked_text(_: &AnyObject, _: Sel) -> *mut AnyObject { diff --git a/crates/gpui_macos/src/window/native_views.rs b/crates/gpui_macos/src/window/native_views.rs new file mode 100644 index 00000000000..c6609b692b8 --- /dev/null +++ b/crates/gpui_macos/src/window/native_views.rs @@ -0,0 +1,1424 @@ +//! Composites platform views beneath a window's GPUI content. +//! +//! GPUI's focus decides which view receives keyboard input: the window's first +//! responder is the native view whose handle GPUI has focused, and GPUI's own +//! view otherwise. The overrides here keep AppKit from moving it anywhere else, +//! except when the user clicks into a native view. +//! +//! A native view with keyboard input sees each key press first. GPUI is only +//! offered a key ahead of it for a pending or reserved binding, and otherwise +//! receives the keys that no view used, as AppKit passes them back up. + +use super::{ + MacWindowState, convert_mouse_position, current_capslock, current_modifiers, + window_state_if_set, with_input_handler, +}; +use crate::events::platform_input_from_native; +use gpui::{ + Bounds, KeyDownEvent, ModifiersChangedEvent, NativeViewId, Pixels, PlatformInput, Point, Rgba, + ScaledPixels, Scene, WindowBackgroundAppearance, +}; +use objc2::{ + class, msg_send, + rc::Retained, + runtime::{AnyClass, AnyObject, Bool, ClassBuilder, Sel}, + sel, +}; +use objc2_app_kit::{NSColor, NSEventType, NSView, NSWindowOrderingMode, NSWorkspace}; +use objc2_foundation::{NSComparisonResult, NSPoint, NSRect, NSSize}; +use parking_lot::Mutex; +use std::{ + any::Any, + ffi::c_void, + ptr::{self, NonNull}, + rc::{Rc, Weak}, +}; + +type HitTestCallback = Box) -> Option>; + +#[derive(Default)] +pub(super) struct NativeViews { + views: Vec, + /// The view GPUI has focused, which is the one that should be first responder. + focused: Option, + /// The view a mouse-down event is being delivered to, which may take + /// first responder even though GPUI has not focused it yet. + clicked: Option, + /// Whether GPUI was told of a mouse press that went to a native view, and + /// is owed the release. + pressed_in_view: bool, + /// The keys, by key code, whose presses GPUI took ahead of a native view. + /// Their releases are GPUI's too, and not the view's, which never saw them + /// pressed. + keys_taken_before_view: Vec, + /// Whether the pointer is over a native view, which then sets the cursor. + pointer_over_view: bool, + /// Whether a scene has been drawn since the pointer was last looked for. + /// What is under a pointer that isn't moving can change with any scene. + drew_since_pointer_check: bool, + /// Set while the window routes a key equivalent between a native view and + /// GPUI itself, so the GPUI view doesn't also handle it. + routing_key_equivalent: bool, + /// Set while a key press is delivered to a native view, which can ask the + /// window to perform the same key as an equivalent before it has decided + /// whether to use it. + delivering_key_down: bool, + /// The key equivalent GPUI was already offered once no view performed it. + /// AppKit delivers it again as a key press, which must not reach GPUI twice. + passed_up_key_equivalent: Option>, + /// The views the last scene showed, from back to front. + stacking: Vec, + /// The color the window was last given behind its native views. + pub(super) background: Option, + pub(super) hit_test_callback: Option, + pub(super) focused_callback: Option>, + pub(super) key_down_before_callback: Option bool>>, +} + +struct AttachedView { + id: NativeViewId, + view: Retained, + /// The view's superview, which clips it to its element's content mask. + container: Retained, + /// Where the view was last placed, or `None` while it is hidden. + placement: Option, +} + +/// Where a native view is shown, as `[x, y, width, height]` frames in points. +#[derive(Clone, Copy, Debug, PartialEq)] +struct Placement { + /// The visible part of the view, in the window's content view. + container: [f64; 4], + /// The whole view, in its container. + view: [f64; 4], +} + +impl Placement { + /// Places a view with the given bounds and clip, both in device pixels + /// from the top left of the GPUI view, whose frame is `gpui_frame`. + /// Returns `None` if the clip leaves none of the view visible. + fn new( + bounds: Bounds, + content_mask: Bounds, + scale_factor: f64, + gpui_frame: [f64; 4], + ) -> Option { + let visible = bounds.intersect(&content_mask); + if visible.is_empty() { + return None; + } + // AppKit measures from the bottom left of the enclosing view. + let to_frame = |bounds: Bounds| { + let [gpui_x, gpui_y, _, gpui_height] = gpui_frame; + let to_points = |value: ScaledPixels| f64::from(value) / scale_factor; + let height = to_points(bounds.size.height); + [ + gpui_x + to_points(bounds.origin.x), + gpui_y + gpui_height - to_points(bounds.origin.y) - height, + to_points(bounds.size.width), + height, + ] + }; + let container = to_frame(visible); + let [x, y, width, height] = to_frame(bounds); + Some(Self { + container, + view: [x - container[0], y - container[1], width, height], + }) + } +} + +impl NativeViews { + fn shown(&self, id: NativeViewId) -> Option<&AttachedView> { + self.views + .iter() + .find(|attached| attached.id == id && attached.placement.is_some()) + } + + fn focused(&self) -> Option { + self.focused.map(|id| FocusedNativeView { + id, + shown: self.shown(id).is_some(), + }) + } + + fn is_showing_any(&self) -> bool { + self.views + .iter() + .any(|attached| attached.placement.is_some()) + } + + /// What `responder` is to the window whose own view is `gpui_view`. + fn holder( + &self, + responder: *mut AnyObject, + native_window: *mut AnyObject, + gpui_view: *mut AnyObject, + ) -> InputHolder { + if responder.is_null() || responder == native_window { + InputHolder::Window + } else if responder == gpui_view { + InputHolder::GpuiView + } else if let Some(id) = self.containing(responder) { + InputHolder::NativeView(id) + } else { + InputHolder::Other + } + } + + /// The attached view that contains `responder`, if it is a view inside one. + /// + /// Attached views are assumed not to contain one another, which holds + /// unless the app moves one after attaching it. + fn containing(&self, responder: *mut AnyObject) -> Option { + if responder.is_null() { + return None; + } + // SAFETY: `responder` is a live object AppKit passed as a responder, and the + // attached views are retained. + unsafe { + let is_view: bool = msg_send![responder, isKindOfClass: class!(NSView)]; + if !is_view { + return None; + } + self.views.iter().find_map(|attached| { + let inside: bool = msg_send![responder, isDescendantOf: &*attached.view]; + inside.then_some(attached.id) + }) + } + } +} + +struct Attachment { + window_state: Weak>, + id: NativeViewId, +} + +impl Drop for Attachment { + fn drop(&mut self) { + let Some(window_state) = self.window_state.upgrade() else { + return; + }; + let (attached, native_window, gpui_view) = { + let mut lock = window_state.lock(); + let Some(index) = lock + .native_views + .views + .iter() + .position(|attached| attached.id == self.id) + else { + return; + }; + if lock.native_views.focused == Some(self.id) { + lock.native_views.focused = None; + } + let attached = lock.native_views.views.remove(index); + (attached, lock.native_window, lock.native_view.as_ptr()) + }; + // SAFETY: The window and both views are live, and attachments are dropped on + // the main thread because `gpui::NativeView` is not `Send`. + unsafe { + // AppKit would otherwise hand first responder to the window itself. + give_up_first_responder(native_window, gpui_view, &attached.view); + attached.container.removeFromSuperview(); + attached.view.removeFromSuperview(); + } + } +} + +/// Adds `view` beneath the window's GPUI view, hidden until a scene shows it. +/// +/// # Safety +/// +/// `view` must point to a live `NSView` that is not in another view hierarchy, +/// and this must be called on the main thread. +pub(super) unsafe fn attach( + window_state: &Rc>, + id: NativeViewId, + view: NonNull, +) -> Option> { + // SAFETY: The caller guarantees `view` is a live `NSView`. + let view = unsafe { Retained::retain(view.as_ptr().cast::()) }?; + let gpui_view = window_state.lock().native_view.as_ptr(); + // SAFETY: The GPUI view is live and in the window's content view, and this + // runs on the main thread. The window state is unlocked because AppKit calls + // back into the window as its view hierarchy changes. + let container = unsafe { + let container: Retained = msg_send![class!(NSView), new]; + let _: () = msg_send![&*container, setClipsToBounds: true]; + container.setHidden(true); + container.addSubview(&view); + let content_view: *mut AnyObject = msg_send![gpui_view, superview]; + let _: () = msg_send![ + content_view, + addSubview: &*container, + positioned: NSWindowOrderingMode::Below, + relativeTo: gpui_view + ]; + container + }; + window_state.lock().native_views.views.push(AttachedView { + id, + view, + container, + placement: None, + }); + Some(Box::new(Attachment { + window_state: Rc::downgrade(window_state), + id, + })) +} + +/// Shows the scene's native view background behind the window's content. +/// +/// A view's frame change reaches the screen a frame or two before the scene +/// that moves its opening, so the opening briefly uncovers whatever is behind +/// the views. That is the window's background, which is given the color the +/// scene asks for. Presenting scenes in step with AppKit would close the gap, +/// but costs every frame of a window that shows a native view. +/// +/// The color stays until a scene without native views is drawn. The last +/// view's opening is still on screen when the view goes, and would show the +/// window's own black through it if the color went with the view. +pub(super) fn update_background(state: &mut MacWindowState, scene: &Scene) { + // The background of a transparent or blurred window is meant to show through. + if state.background_appearance != WindowBackgroundAppearance::Opaque { + return; + } + let background = scene + .native_views + .iter() + .rev() + .map(|native_view| Rgba::from(native_view.background)) + .find(|background| background.a > 0.); + if state.native_views.background == background { + return; + } + state.native_views.background = background; + // SAFETY: The window is live for as long as its state. + unsafe { + let _: () = msg_send![ + state.native_window, + setBackgroundColor: &*background_color(background) + ]; + } +} + +/// The background of an opaque window, which is black unless a native view asks for a color. +fn background_color(color: Option) -> Retained { + let Rgba { r, g, b, .. } = color.unwrap_or_default(); + NSColor::colorWithSRGBRed_green_blue_alpha(r as f64, g as f64, b as f64, 1.) +} + +/// What a scene changes about the window's attached views. +#[derive(Default)] +pub(super) struct Layout { + /// Views to place somewhere new, or to hide for `None`. + placements: Vec<(NativeViewId, Option)>, + /// The views the scene shows, from back to front, if that order changed. + stacking: Option>, +} + +/// Works out which attached views the scene moves, shows, hides, or restacks. +pub(super) fn plan_layout(state: &MacWindowState, scene: &Scene) -> Layout { + if state.native_views.views.is_empty() { + return Layout::default(); + } + let scale_factor = state.scale_factor() as f64; + // SAFETY: The GPUI view is live for as long as the window state. + let gpui_frame: NSRect = unsafe { msg_send![state.native_view.as_ptr(), frame] }; + let gpui_frame = [ + gpui_frame.origin.x, + gpui_frame.origin.y, + gpui_frame.size.width, + gpui_frame.size.height, + ]; + + let mut placements = Vec::new(); + for attached in &state.native_views.views { + let placement = scene + .native_views + .iter() + .find(|native_view| native_view.id == attached.id) + .and_then(|native_view| { + Placement::new( + native_view.bounds, + native_view.content_mask.bounds, + scale_factor, + gpui_frame, + ) + }); + if attached.placement != placement { + placements.push((attached.id, placement)); + } + } + + // The scene's native views are sorted by draw order, so the ones painted + // later, which belong in front, come last. + let mut stacking = Vec::new(); + for placement in &scene.native_views { + if !stacking.contains(&placement.id) { + stacking.push(placement.id); + } + } + let stacking = (stacking != state.native_views.stacking).then_some(stacking); + Layout { + placements, + stacking, + } +} + +/// Applies a planned layout. The window state must be unlocked, because AppKit +/// calls back into it when a view's frame or first responder changes. +pub(super) fn apply_layout(window_state: &Rc>, layout: Layout) { + if layout.placements.is_empty() && layout.stacking.is_none() { + return; + } + let (native_window, gpui_view, placements, stacking) = { + let mut lock = window_state.lock(); + let mut placements = Vec::new(); + for (id, placement) in layout.placements { + if let Some(attached) = lock + .native_views + .views + .iter_mut() + .find(|attached| attached.id == id) + { + attached.placement = placement; + placements.push((attached.view.clone(), attached.container.clone(), placement)); + } + } + let stacking = layout.stacking.map(|stacking| { + let current = Vec::new(); + let front_to_back = stacking + .iter() + .rev() + .filter_map(|id| lock.native_views.views.iter().find(|view| view.id == *id)) + .map(|attached| Retained::as_ptr(&attached.container)) + .collect(); + let attached = lock + .native_views + .views + .iter() + .map(|attached| Retained::as_ptr(&attached.container)) + .collect(); + lock.native_views.stacking = stacking; + Stacking { + gpui_view: lock.native_view.as_ptr().cast_const().cast(), + front_to_back, + attached, + current, + } + }); + ( + lock.native_window, + lock.native_view.as_ptr(), + placements, + stacking, + ) + }; + let to_rect = |[x, y, width, height]: [f64; 4]| { + NSRect::new(NSPoint::new(x, y), NSSize::new(width, height)) + }; + for (view, container, placement) in placements { + match placement { + Some(placement) => { + container.setFrame(to_rect(placement.container)); + view.setFrame(to_rect(placement.view)); + container.setHidden(false); + } + None => { + // SAFETY: The window and both views are live, and drawing runs on the main thread. + unsafe { give_up_first_responder(native_window, gpui_view, &view) }; + container.setHidden(true); + } + } + } + if let Some(mut stacking) = stacking + && stacking.front_to_back.len() > 1 + { + // SAFETY: The GPUI view is live and in the content view, the comparison + // function only reads `stacking`, which outlives the call, and sorting + // reorders the subviews in place, so none of them leaves the window. + unsafe { + let content_view: *mut NSView = msg_send![gpui_view, superview]; + if let Some(content_view) = content_view.as_ref() { + stacking.current = content_view + .subviews() + .iter() + .map(|subview| Retained::as_ptr(&subview)) + .collect(); + content_view.sortSubviewsUsingFunction_context( + compare_stacking, + (&raw mut stacking).cast(), + ); + } + } + } + // A view that GPUI focused while it was hidden can take keyboard input now. + reconcile_first_responder(window_state); +} + +/// The order to give the content view's subviews. +struct Stacking { + gpui_view: *const NSView, + /// The containers of the views the scene shows, starting with the one painted last. + front_to_back: Vec<*const NSView>, + attached: Vec<*const NSView>, + /// The subviews as they are ordered now, from the back. Those that aren't + /// native views keep their places among themselves and their side of the + /// GPUI view. + current: Vec<*const NSView>, +} + +impl Stacking { + /// How far forward a subview belongs, with greater values in front. + fn rank(&self, view: *const NSView) -> (u8, usize) { + let place = |view| self.current.iter().position(|current| *current == view); + if view == self.gpui_view { + (3, 0) + } else if let Some(index) = self.front_to_back.iter().position(|shown| *shown == view) { + // Shown views sit above hidden ones, in the scene's order. + (2, self.front_to_back.len() - index) + } else if self.attached.contains(&view) { + (1, 0) + } else if place(view) > place(self.gpui_view) { + // A view the app put in front of GPUI's content stays there. + (4, place(view).unwrap_or_default()) + } else { + // Other views, such as the blur behind a translucent window, stay + // at the back. + (0, place(view).unwrap_or_default()) + } + } +} + +unsafe extern "C-unwind" fn compare_stacking( + first: NonNull, + second: NonNull, + stacking: *mut c_void, +) -> NSComparisonResult { + // SAFETY: `apply_layout` passes a `Stacking` that outlives the sort. + let stacking = unsafe { &*stacking.cast::() }; + match stacking + .rank(first.as_ptr()) + .cmp(&stacking.rank(second.as_ptr())) + { + std::cmp::Ordering::Less => NSComparisonResult::Ascending, + std::cmp::Ordering::Equal => NSComparisonResult::Same, + std::cmp::Ordering::Greater => NSComparisonResult::Descending, + } +} + +/// What has, or is asking for, a window's keyboard input. +#[derive(Clone, Copy, Debug, PartialEq)] +enum InputHolder { + /// The window itself, which has it when no view does. + Window, + /// The view GPUI draws its own content in. + GpuiView, + /// An attached native view, or a view inside it. + NativeView(NativeViewId), + /// A view GPUI didn't attach, such as a control the app or AppKit put in + /// the titlebar. GPUI's focus says nothing about those. + Other, +} + +/// The native view GPUI has focused. +#[derive(Clone, Copy, Debug, PartialEq)] +struct FocusedNativeView { + id: NativeViewId, + /// Whether it is on screen. A view can be focused before it is shown, and + /// stays focused when it is hidden. + shown: bool, +} + +/// A view keyboard input is moved to so that it matches GPUI's focus. +#[derive(Clone, Copy, Debug, PartialEq)] +enum InputTarget { + GpuiView, + NativeView(NativeViewId), +} + +/// Where keyboard input should move so that it matches GPUI's focus, or `None` +/// to leave it with `current`. +fn input_target_for_focus( + focused: Option, + current: InputHolder, +) -> Option { + let (target, holder) = match focused { + Some(FocusedNativeView { id, shown: true }) => { + (InputTarget::NativeView(id), InputHolder::NativeView(id)) + } + // A hidden view can't take keyboard input until it is shown. + Some(FocusedNativeView { shown: false, .. }) | None => { + (InputTarget::GpuiView, InputHolder::GpuiView) + } + }; + (current != InputHolder::Other && current != holder).then_some(target) +} + +/// Whether `requested` may take keyboard input from `current` when AppKit or +/// the view itself asks. +/// +/// `clicked` is the native view a mouse press is being delivered to. +/// `voice_over_reaches_it` is whether VoiceOver is on and `requested` is a +/// native view on screen, which is where its cursor can go. A hidden view +/// asking for keyboard input is a page script, VoiceOver or not. +fn may_take_input( + requested: InputHolder, + current: InputHolder, + focused: Option, + clicked: Option, + voice_over_reaches_it: bool, +) -> bool { + match requested { + // AppKit offers the GPUI view keyboard input on every press inside it. + // While GPUI's focus stays on a native view, taking it and handing it + // straight back would make the native view lose and regain keyboard + // input, so it is refused. A press that moves GPUI's focus does so + // first, and is accepted. + InputHolder::GpuiView => !matches!( + focused, + Some(FocusedNativeView { id, shown: true }) if current == InputHolder::NativeView(id) + ), + // Web views ask for keyboard input on their own, such as when a page + // script focuses its window. Only GPUI's focus, a click, or VoiceOver's + // cursor may move it. + InputHolder::NativeView(requested) => { + focused.is_some_and(|focused| focused.id == requested) + || clicked == Some(requested) + || voice_over_reaches_it + } + InputHolder::Window | InputHolder::Other => true, + } +} + +/// Records the view GPUI has focused and gives it keyboard input. +pub(super) fn set_focused(window_state: &Rc>, id: Option) { + window_state.lock().native_views.focused = id; + reconcile_first_responder(window_state); +} + +/// Makes the window's first responder match the view GPUI has focused. +/// +/// A responder that is neither the window, the GPUI view, nor inside an +/// attached view is left with keyboard input, such as a control the app or +/// AppKit put in the titlebar. GPUI's focus says nothing about those. +pub(super) fn reconcile_first_responder(window_state: &Rc>) { + // SAFETY: The window and views are live, and this runs on the main thread. The + // window state is unlocked for `makeFirstResponder:` because AppKit calls back + // into it synchronously, and the target is retained in case that detaches it. + unsafe { + let (native_window, target) = { + let lock = window_state.lock(); + let native_window = lock.native_window; + let gpui_view = lock.native_view.as_ptr(); + let current: *mut AnyObject = msg_send![native_window, firstResponder]; + let views = &lock.native_views; + let current = views.holder(current, native_window, gpui_view); + let target = match input_target_for_focus(views.focused(), current) { + Some(InputTarget::NativeView(id)) => match views.shown(id) { + Some(attached) => Some(attached.view.clone()), + None => return, + }, + Some(InputTarget::GpuiView) => None, + None => return, + }; + (native_window, target.ok_or(gpui_view)) + }; + let _: Bool = match &target { + Ok(view) => msg_send![native_window, makeFirstResponder: &**view], + Err(gpui_view) => msg_send![native_window, makeFirstResponder: *gpui_view], + }; + } +} + +/// Returns first responder to the GPUI view if it is inside `view`. +/// +/// # Safety +/// +/// All three objects must be live, and this must be called on the main thread +/// without the window state locked. +unsafe fn give_up_first_responder( + native_window: *mut AnyObject, + gpui_view: *mut AnyObject, + view: &NSView, +) { + unsafe { + let current: *mut AnyObject = msg_send![native_window, firstResponder]; + let is_view: bool = !current.is_null() && msg_send![current, isKindOfClass: class!(NSView)]; + let inside: bool = is_view && msg_send![current, isDescendantOf: view]; + if inside { + let _: Bool = msg_send![native_window, makeFirstResponder: gpui_view]; + } + } +} + +pub(super) fn add_window_methods(decl: &mut ClassBuilder) { + // SAFETY: The function signatures match the selectors' Objective-C signatures. + unsafe { + decl.add_method( + sel!(makeFirstResponder:), + make_first_responder as extern "C" fn(_, Sel, *mut AnyObject) -> Bool, + ); + decl.add_method( + sel!(sendEvent:), + send_event as extern "C" fn(_, Sel, *mut AnyObject), + ); + decl.add_method( + sel!(performKeyEquivalent:), + window_perform_key_equivalent as extern "C" fn(_, Sel, *mut AnyObject) -> Bool, + ); + decl.add_method( + sel!(keyDown:), + window_key_down as extern "C" fn(_, Sel, *mut AnyObject), + ); + } +} + +pub(super) fn add_view_methods(decl: &mut ClassBuilder) { + // SAFETY: The function signatures match the selectors' Objective-C signatures. + unsafe { + decl.add_method( + sel!(hitTest:), + hit_test as extern "C" fn(_, Sel, NSPoint) -> *mut AnyObject, + ); + decl.add_method( + sel!(becomeFirstResponder), + become_first_responder as extern "C" fn(_, Sel) -> Bool, + ); + decl.add_method( + sel!(resignFirstResponder), + resign_first_responder as extern "C" fn(_, Sel) -> Bool, + ); + } +} + +/// GPUI windows subclass either `NSWindow` or `NSPanel`. +fn window_superclass(this: &AnyObject) -> &'static AnyClass { + // SAFETY: `this` is a live window. + let is_panel: bool = unsafe { msg_send![this, isKindOfClass: class!(NSPanel)] }; + if is_panel { + class!(NSPanel) + } else { + class!(NSWindow) + } +} + +/// Asks GPUI which native view, if any, a point in window coordinates reaches. +fn hit_test_native_view( + window_state: &Rc>, + position_in_window: NSPoint, +) -> Option { + // AppKit can hit-test while the state is locked for another call into it. + let mut lock = window_state.try_lock()?; + if !lock.native_views.is_showing_any() { + return None; + } + let position = convert_mouse_position(position_in_window, lock.content_size().height); + let mut callback = lock.native_views.hit_test_callback.take()?; + drop(lock); + let id = callback(position); + let mut lock = window_state.lock(); + lock.native_views.hit_test_callback = Some(callback); + id.filter(|id| lock.native_views.shown(*id).is_some()) +} + +/// Lets mouse events that GPUI routes to a native view fall through to it. +extern "C" fn hit_test(this: &AnyObject, _: Sel, point: NSPoint) -> *mut AnyObject { + // SAFETY: `this` is the live GPUI view, whose state outlives it. + unsafe { + // AppKit can ask while the view is being torn down, after its state + // has gone and it has left its superview. + let superview: *mut AnyObject = msg_send![this, superview]; + if let Some(window_state) = window_state_if_set(this) + && !superview.is_null() + { + let position_in_window: NSPoint = + msg_send![superview, convertPoint: point, toView: ptr::null::()]; + if hit_test_native_view(&window_state, position_in_window).is_some() { + return ptr::null_mut(); + } + } + msg_send![super(this, class!(NSView)), hitTest: point] + } +} + +/// Notes which native view a mouse-down is headed for while AppKit delivers it, +/// which is the only time a native view may take first responder on its own, and +/// offers GPUI a key press ahead of the native view that would receive it. +/// +/// GPUI is also given the mouse-down, which reaches nothing behind the view but +/// lets the window's own content notice a press outside it. +extern "C" fn send_event(this: &AnyObject, _: Sel, event: *mut AnyObject) { + // SAFETY: `this` is a live GPUI window and `event` a live `NSEvent`. + unsafe { + let superclass = window_superclass(this); + let Some(window_state) = window_state_if_set(this) else { + return msg_send![super(this, superclass), sendEvent: event]; + }; + if let Some(key_down) = key_down_for_native_view(&window_state, this, event) { + let key_code: u16 = msg_send![event, keyCode]; + if offer_key_down_before_native_view(&window_state, key_down) { + note_key_taken_before_view(&window_state, key_code, true); + return; + } + note_key_taken_before_view(&window_state, key_code, false); + window_state.lock().native_views.delivering_key_down = true; + let _: () = msg_send![super(this, superclass), sendEvent: event]; + window_state.lock().native_views.delivering_key_down = false; + return; + } + + let event_type: NSEventType = msg_send![event, type]; + if event_type == NSEventType::KeyUp { + let key_code: u16 = msg_send![event, keyCode]; + let was_taken = window_state.try_lock().is_some_and(|mut lock| { + let taken = &mut lock.native_views.keys_taken_before_view; + let count = taken.len(); + taken.retain(|taken| *taken != key_code); + taken.len() != count + }); + if was_taken { + if let Some(key_up) = platform_input_from_native(event, None) { + pass_input_to_gpui(&window_state, key_up); + } + return; + } + } + if event_type == NSEventType::FlagsChanged { + // The view with keyboard input is sent the change, and GPUI isn't, + // though what GPUI draws can depend on the modifiers held. + let _: () = msg_send![super(this, superclass), sendEvent: event]; + if let Some(modifiers_changed) = + modifiers_changed_beside_view(&window_state, this, event) + { + pass_input_to_gpui(&window_state, modifiers_changed); + } + return; + } + if event_type == NSEventType::MouseMoved { + let position: NSPoint = msg_send![event, locationInWindow]; + update_pointer_over_view(&window_state, position); + } + let clicked = if matches!( + event_type, + NSEventType::LeftMouseDown | NSEventType::RightMouseDown | NSEventType::OtherMouseDown + ) { + let position: NSPoint = msg_send![event, locationInWindow]; + hit_test_native_view(&window_state, position) + } else { + None + }; + if clicked.is_none() { + let is_release = matches!( + event_type, + NSEventType::LeftMouseUp | NSEventType::RightMouseUp | NSEventType::OtherMouseUp + ); + // GPUI was told of the press, so it is told of the release too, or + // it would go on treating the button as held. + let release = is_release + .then(|| { + let mut lock = window_state.try_lock()?; + std::mem::take(&mut lock.native_views.pressed_in_view) + .then(|| lock.content_size().height) + }) + .flatten() + .and_then(|window_height| platform_input_from_native(event, Some(window_height))); + let _: () = msg_send![super(this, superclass), sendEvent: event]; + if let Some(release) = release { + pass_input_to_gpui(&window_state, release); + } + return; + } + let window_height = { + let mut lock = window_state.lock(); + lock.native_views.clicked = clicked; + lock.native_views.pressed_in_view = true; + lock.content_size().height + }; + // GPUI goes first, so that focus it moves in response, such as a dismissed + // popover restoring focus, doesn't take keyboard input back from the view. + if let Some(mouse_down) = platform_input_from_native(event, Some(window_height)) { + pass_input_to_gpui(&window_state, mouse_down); + } + let _: () = msg_send![super(this, superclass), sendEvent: event]; + window_state.lock().native_views.clicked = None; + } +} + +/// Notes whether the pointer is over a native view, and has AppKit rebuild the +/// GPUI view's cursor rectangles when that changes. +fn update_pointer_over_view(window_state: &Rc>, position_in_window: NSPoint) { + let over_view = hit_test_native_view(window_state, position_in_window).is_some(); + let Some(mut lock) = window_state.try_lock() else { + return; + }; + if lock.native_views.pointer_over_view == over_view { + return; + } + lock.native_views.pointer_over_view = over_view; + let native_window = lock.native_window; + let gpui_view = lock.native_view.as_ptr(); + drop(lock); + // SAFETY: The window and the GPUI view are live, and events are sent on the main + // thread. The state is unlocked in case AppKit rebuilds the rectangles at once, + // which calls back into the view. + unsafe { + let _: () = msg_send![native_window, invalidateCursorRectsForView: gpui_view]; + } +} + +/// Notes that a scene was drawn, after which [`check_pointer_after_frame`] +/// looks for the pointer again. +pub(super) fn scene_drawn(state: &mut MacWindowState, scene: &Scene) { + let views = &mut state.native_views; + // A scene that shows no view can only take the pointer off one. + views.drew_since_pointer_check = views.pointer_over_view || !scene.native_views.is_empty(); +} + +/// Looks again for whether the pointer is over a native view, if a scene was +/// drawn since it last moved: something GPUI drew may now be under it, or +/// may have gone from over the view. +/// +/// This runs after a frame, not as its scene is drawn, because finding what +/// is under the pointer calls back into the window. +pub(super) fn check_pointer_after_frame(window_state: &Rc>) { + let native_window = { + let Some(mut lock) = window_state.try_lock() else { + return; + }; + if !std::mem::take(&mut lock.native_views.drew_since_pointer_check) { + return; + } + lock.native_window + }; + // SAFETY: The window is live for as long as its state, and frames are + // drawn on the main thread. + let position: NSPoint = unsafe { msg_send![native_window, mouseLocationOutsideOfEventStream] }; + update_pointer_over_view(window_state, position); +} + +/// Whether a native view sets the cursor, because the pointer is over it. +/// +/// The GPUI view lies over every native view, so its own cursor would +/// otherwise replace the one the native view chooses. +pub(super) fn native_view_sets_cursor(state: &MacWindowState) -> bool { + state.native_views.pointer_over_view && state.native_views.is_showing_any() +} + +extern "C" fn make_first_responder(this: &AnyObject, _: Sel, responder: *mut AnyObject) -> Bool { + // SAFETY: `this` is a live GPUI window and `responder` is null or a live responder. + unsafe { + let superclass = window_superclass(this); + let Some(window_state) = window_state_if_set(this) else { + return msg_send![super(this, superclass), makeFirstResponder: responder]; + }; + // The state is locked while a window is still being set up, before it has native views. + let Some(lock) = window_state.try_lock() else { + return msg_send![super(this, superclass), makeFirstResponder: responder]; + }; + if lock.native_views.views.is_empty() { + drop(lock); + return msg_send![super(this, superclass), makeFirstResponder: responder]; + } + let views = &lock.native_views; + let gpui_view = lock.native_view.as_ptr(); + let native_window = lock.native_window; + let current: *mut AnyObject = msg_send![this, firstResponder]; + let current = views.holder(current, native_window, gpui_view); + let requested = views.holder(responder, native_window, gpui_view); + let focused = views.focused(); + let clicked = views.clicked; + let requested_is_shown = + matches!(requested, InputHolder::NativeView(id) if views.shown(id).is_some()); + drop(lock); + + let voice_over_enabled: bool = + msg_send![&*NSWorkspace::sharedWorkspace(), isVoiceOverEnabled]; + let voice_over_reaches_it = voice_over_enabled && requested_is_shown; + if !may_take_input(requested, current, focused, clicked, voice_over_reaches_it) { + return Bool::NO; + } + + let accepted: Bool = msg_send![super(this, superclass), makeFirstResponder: responder]; + if !accepted.as_bool() { + return accepted; + } + + if let InputHolder::NativeView(requested) = requested + && focused.is_none_or(|focused| focused.id != requested) + { + let callback = window_state.lock().native_views.focused_callback.take(); + if let Some(mut callback) = callback { + callback(requested); + window_state.lock().native_views.focused_callback = Some(callback); + } + } + // GPUI records a view that took keyboard input as focused when it follows. + // If it could not, such as while the window's focus is disabled, this takes + // first responder back so the two never disagree. Anything else that moved + // first responder away from the view GPUI has focused is undone too, such as + // AppKit handing it to the window itself, or a full screen transition + // restoring it to the GPUI view. + reconcile_first_responder(&window_state); + accepted + } +} + +/// Returns the key press `event` describes, if a native view would receive it. +/// +/// # Safety +/// +/// `window` must be a live GPUI window and `event` a live `NSEvent`. +unsafe fn key_down_for_native_view( + window_state: &Rc>, + window: &AnyObject, + event: *mut AnyObject, +) -> Option { + // SAFETY: The caller guarantees that `window` and `event` are live. + unsafe { + let event_type: NSEventType = msg_send![event, type]; + if event_type != NSEventType::KeyDown { + return None; + } + let mut lock = window_state.try_lock()?; + if lock.native_views.views.is_empty() { + return None; + } + // AppKit can move first responder without asking the window, such as when + // the responder leaves the view hierarchy. The press belongs to the view + // GPUI has focused, so first responder is returned to it before routing. + if lock + .native_views + .focused + .is_some_and(|id| lock.native_views.shown(id).is_some()) + { + drop(lock); + reconcile_first_responder(window_state); + lock = window_state.try_lock()?; + } + let first_responder: *mut AnyObject = msg_send![window, firstResponder]; + lock.native_views.containing(first_responder)?; + let window_height = lock.content_size().height; + drop(lock); + match platform_input_from_native(event, Some(window_height))? { + PlatformInput::KeyDown(key_down) => Some(key_down), + _ => None, + } + } +} + +/// Records whether GPUI took the press of a key ahead of the native view, +/// which decides where the key's release goes. +fn note_key_taken_before_view( + window_state: &Rc>, + key_code: u16, + taken: bool, +) { + let mut lock = window_state.lock(); + let keys = &mut lock.native_views.keys_taken_before_view; + keys.retain(|key| *key != key_code); + if taken { + keys.push(key_code); + } +} + +/// Returns a change of modifiers for GPUI to hear of, if a native view has +/// keyboard input and GPUI hasn't heard of this change. +/// +/// # Safety +/// +/// `window` must be a live GPUI window and `event` a live `NSEvent`. +unsafe fn modifiers_changed_beside_view( + window_state: &Rc>, + window: &AnyObject, + event: *mut AnyObject, +) -> Option { + // SAFETY: The caller guarantees that `window` and `event` are live. + unsafe { + let mut lock = window_state.try_lock()?; + if lock.native_views.views.is_empty() { + return None; + } + let first_responder: *mut AnyObject = msg_send![window, firstResponder]; + lock.native_views.containing(first_responder)?; + let input = platform_input_from_native(event, None)?; + let PlatformInput::ModifiersChanged(current) = &input else { + return None; + }; + if let Some(PlatformInput::ModifiersChanged(previous)) = + &lock.previous_modifiers_changed_event + && previous.modifiers == current.modifiers + && previous.capslock == current.capslock + { + return None; + } + lock.previous_modifiers_changed_event = Some(input.clone()); + Some(input) + } +} + +/// Offers GPUI a key press that a native view has not seen, and returns whether GPUI used it. +fn offer_key_down_before_native_view( + window_state: &Rc>, + key_down: KeyDownEvent, +) -> bool { + let Some(mut callback) = window_state + .lock() + .native_views + .key_down_before_callback + .take() + else { + return false; + }; + let handled = callback(key_down); + window_state.lock().native_views.key_down_before_callback = Some(callback); + handled +} + +/// Dispatches a key press that no native view used, and returns whether GPUI used it. +/// +/// This skips the input method handling a key press gets when the GPUI view +/// has keyboard input, because the native view has already done its own. +fn pass_key_down_to_gpui(window_state: &Rc>, key_down: KeyDownEvent) -> bool { + pass_input_to_gpui(window_state, PlatformInput::KeyDown(key_down)) +} + +/// Dispatches input in GPUI, and returns whether GPUI used it. +fn pass_input_to_gpui(window_state: &Rc>, input: PlatformInput) -> bool { + let Some(mut callback) = window_state.lock().event_callback.take() else { + return false; + }; + let handled = !callback(input).propagate; + window_state.lock().event_callback = Some(callback); + handled +} + +/// Lets the native view with keyboard input perform a key equivalent before GPUI. +/// +/// AppKit otherwise asks the views in an order that doesn't depend on which +/// one has keyboard input. +extern "C" fn window_perform_key_equivalent( + this: &AnyObject, + _: Sel, + event: *mut AnyObject, +) -> Bool { + // SAFETY: `this` is a live GPUI window and `event` a live `NSEvent`. + unsafe { + let superclass = window_superclass(this); + let Some(window_state) = window_state_if_set(this) else { + return msg_send![super(this, superclass), performKeyEquivalent: event]; + }; + let Some(key_down) = key_down_for_native_view(&window_state, this, event) else { + return msg_send![super(this, superclass), performKeyEquivalent: event]; + }; + let delivering_key_down = window_state.lock().native_views.delivering_key_down; + if !delivering_key_down + && offer_key_down_before_native_view(&window_state, key_down.clone()) + { + let key_code: u16 = msg_send![event, keyCode]; + note_key_taken_before_view(&window_state, key_code, true); + return Bool::YES; + } + + window_state.lock().native_views.routing_key_equivalent = true; + let performed: Bool = msg_send![super(this, superclass), performKeyEquivalent: event]; + window_state.lock().native_views.routing_key_equivalent = false; + if performed.as_bool() || delivering_key_down { + return performed; + } + + // No view performed it. For a web view that means the page has already + // seen the key and left it, since a web view claims every key equivalent + // the first time and sends back the ones its page doesn't use. + window_state.lock().native_views.passed_up_key_equivalent = Retained::retain(event); + Bool::new(pass_key_down_to_gpui(&window_state, key_down)) + } +} + +/// Gives GPUI a key press that came back up the responder chain unused. +extern "C" fn window_key_down(this: &AnyObject, _: Sel, event: *mut AnyObject) { + // SAFETY: `this` is a live GPUI window and `event` a live `NSEvent`. + unsafe { + let superclass = window_superclass(this); + let Some(window_state) = window_state_if_set(this) else { + return msg_send![super(this, superclass), keyDown: event]; + }; + let Some(key_down) = key_down_for_native_view(&window_state, this, event) else { + return msg_send![super(this, superclass), keyDown: event]; + }; + let passed_up = window_state + .lock() + .native_views + .passed_up_key_equivalent + .take(); + let already_passed_up = + passed_up.is_some_and(|passed_up| ptr::eq(Retained::as_ptr(&passed_up), event)); + if !already_passed_up { + pass_key_down_to_gpui(&window_state, key_down); + } + // The window's own handling of an unused key press is to beep. + } +} + +/// Whether the window is routing the current key equivalent itself. +pub(super) fn is_routing_key_equivalent(window_state: &Rc>) -> bool { + window_state + .try_lock() + .is_some_and(|lock| lock.native_views.routing_key_equivalent) +} + +/// Whether assistive technology should treat the GPUI view as focused, which +/// it isn't while a native view has keyboard input. +pub(super) fn gpui_view_is_focused(state: &MacWindowState) -> bool { + let native_window = state.native_window(); + if !native_window.isKeyWindow() { + return false; + } + if state.native_views.views.is_empty() { + return true; + } + // SAFETY: The window is live for as long as its state. + let first_responder: *mut AnyObject = unsafe { msg_send![state.native_window, firstResponder] }; + first_responder == state.native_view.as_ptr() +} + +/// Tells the accessibility adapter whether the GPUI view is first responder, +/// which the window does not report correctly while that is changing. +fn update_accessibility_focus(window_state: &Rc>, is_first_responder: bool) { + let events = { + let Some(mut lock) = window_state.try_lock() else { + return; + }; + let is_focused = is_first_responder && lock.native_window().isKeyWindow(); + lock.accesskit_adapter + .as_mut() + .and_then(|adapter| adapter.update_view_focus_state(is_focused)) + }; + if let Some(events) = events { + events.raise(); + } +} + +extern "C" fn become_first_responder(this: &AnyObject, _: Sel) -> Bool { + // SAFETY: `this` is the live GPUI view, whose state outlives it. + unsafe { + let accepted: Bool = msg_send![super(this, class!(NSView)), becomeFirstResponder]; + let Some(window_state) = window_state_if_set(this) else { + return accepted; + }; + // The state is locked while the window is still being set up. + let Some(lock) = window_state.try_lock() else { + return accepted; + }; + if !accepted.as_bool() || lock.native_views.views.is_empty() { + return accepted; + } + // A native first responder consumes modifier changes, so GPUI may have missed + // some. GPUI can be in the middle of an update here, so report them afterwards. + let executor = lock.foreground_executor.clone(); + drop(lock); + update_accessibility_focus(&window_state, true); + executor + .spawn(async move { + let event = PlatformInput::ModifiersChanged(ModifiersChangedEvent { + modifiers: current_modifiers(), + capslock: current_capslock(), + }); + let mut lock = window_state.lock(); + let unchanged = matches!( + (&lock.previous_modifiers_changed_event, &event), + ( + Some(PlatformInput::ModifiersChanged(previous)), + PlatformInput::ModifiersChanged(current), + ) if previous.modifiers == current.modifiers + && previous.capslock == current.capslock + ); + if unchanged { + return; + } + lock.previous_modifiers_changed_event = Some(event.clone()); + if let Some(mut callback) = lock.event_callback.take() { + drop(lock); + callback(event); + window_state.lock().event_callback = Some(callback); + } + }) + .detach(); + accepted + } +} + +extern "C" fn resign_first_responder(this: &AnyObject, _: Sel) -> Bool { + // SAFETY: `this` is the live GPUI view, whose state outlives it. + unsafe { + let accepted: Bool = msg_send![super(this, class!(NSView)), resignFirstResponder]; + let Some(window_state) = window_state_if_set(this) else { + return accepted; + }; + let has_native_views = window_state + .try_lock() + .is_some_and(|lock| !lock.native_views.views.is_empty()); + if accepted.as_bool() && has_native_views { + // Keyboard input is leaving GPUI, so an unfinished composition ends here, + // as it would in a native text view. + with_input_handler(this, |input_handler| input_handler.unmark_text()); + let input_context: *mut AnyObject = msg_send![this, inputContext]; + let _: () = msg_send![input_context, discardMarkedText]; + update_accessibility_focus(&window_state, false); + } + accepted + } +} + +#[cfg(test)] +mod tests { + use super::*; + use gpui::{point, size}; + + #[test] + fn placement_clips_a_view_to_its_content_mask() { + let scaled = |x: f32, y: f32, width: f32, height: f32| Bounds { + origin: point(ScaledPixels::from(x), ScaledPixels::from(y)), + size: size(ScaledPixels::from(width), ScaledPixels::from(height)), + }; + // A 400 by 300 point GPUI view at twice the scale, 10 points above the + // bottom of the content view. + let gpui_frame = [0., 10., 400., 300.]; + let bounds = scaled(100., 40., 200., 400.); + + let unclipped = Placement::new(bounds, scaled(0., 0., 800., 600.), 2., gpui_frame); + assert_eq!( + unclipped, + Some(Placement { + container: [50., 90., 100., 200.], + view: [0., 0., 100., 200.], + }) + ); + + // Clipping the top 60 and left 20 pixels shrinks the container, and the + // view keeps its size and stays where it was in the window. + let clipped = Placement::new(bounds, scaled(120., 100., 800., 600.), 2., gpui_frame); + assert_eq!( + clipped, + Some(Placement { + container: [60., 90., 90., 170.], + view: [-10., 0., 100., 200.], + }) + ); + + let hidden = Placement::new(bounds, scaled(0., 500., 800., 100.), 2., gpui_frame); + assert_eq!(hidden, None); + } + + #[test] + fn keyboard_input_follows_gpui_focus_except_from_views_gpui_did_not_attach() { + use InputHolder::{GpuiView, NativeView, Other, Window}; + let shown = focused(1, true); + let hidden = focused(1, false); + let to_view = Some(InputTarget::NativeView(id(1))); + let to_gpui = Some(InputTarget::GpuiView); + for (focused, current, moves_to) in [ + // Focusing a native view gives it keyboard input, wherever that was. + (shown, GpuiView, to_view), + (shown, Window, to_view), + (shown, NativeView(id(2)), to_view), + (shown, NativeView(id(1)), None), + // Focusing GPUI's own content takes it back. + (None, NativeView(id(1)), to_gpui), + (None, Window, to_gpui), + (None, GpuiView, None), + // So does hiding the focused view. + (hidden, NativeView(id(1)), to_gpui), + (hidden, GpuiView, None), + // A control GPUI knows nothing about keeps it either way. + (shown, Other, None), + (None, Other, None), + ] { + assert_eq!( + input_target_for_focus(focused, current), + moves_to, + "focused: {focused:?}, current: {current:?}" + ); + } + } + + #[test] + fn views_take_keyboard_input_only_when_gpui_focus_a_click_or_voice_over_allows() { + use InputHolder::{GpuiView, NativeView, Other}; + let (view, view_2) = (NativeView(id(1)), NativeView(id(2))); + let (shown, hidden) = (focused(1, true), focused(1, false)); + let (click, click_2) = (Some(id(1)), Some(id(2))); + + // A page asking on its own is refused, as is a view other than the one + // GPUI focused or the one being clicked. + assert!(!may_take_input(view, GpuiView, None, None, false)); + assert!(!may_take_input(view_2, GpuiView, shown, None, false)); + assert!(!may_take_input(view, GpuiView, None, click_2, false)); + // GPUI's focus allows it, even before the view is shown. So do a click + // on the view and VoiceOver's cursor. + assert!(may_take_input(view, GpuiView, shown, None, false)); + assert!(may_take_input(view, GpuiView, hidden, None, false)); + assert!(may_take_input(view, GpuiView, None, click, false)); + assert!(may_take_input(view, GpuiView, None, None, true)); + + // AppKit offers the GPUI view every press inside it, which is refused + // while the focused native view is shown and has keyboard input. + assert!(!may_take_input(GpuiView, view, shown, None, false)); + // It is accepted once GPUI's focus has left the view, while the view is + // being hidden, and from a view that isn't the focused one. + assert!(may_take_input(GpuiView, view, None, None, false)); + assert!(may_take_input(GpuiView, view, hidden, None, false)); + assert!(may_take_input(GpuiView, view_2, shown, None, false)); + + // A control GPUI did not attach takes it freely. + assert!(may_take_input(Other, view, shown, None, false)); + } + + #[test] + fn stacking_puts_shown_views_between_the_gpui_view_and_everything_else() { + // The views are only compared by address. + let views = [0u8; 6]; + let [gpui_view, front, back, hidden, behind, above] = + [0, 1, 2, 3, 4, 5].map(|index| NonNull::from(&views[index]).cast::()); + // AppKit draws later subviews in front, and sorts ascending. + let mut back_to_front = [front, behind, gpui_view, hidden, above, back]; + let mut stacking = Stacking { + gpui_view: gpui_view.as_ptr(), + front_to_back: vec![front.as_ptr(), back.as_ptr()], + attached: vec![hidden.as_ptr(), back.as_ptr(), front.as_ptr()], + current: back_to_front + .iter() + .map(|view| view.as_ptr().cast_const()) + .collect(), + }; + + back_to_front.sort_by(|first, second| { + // SAFETY: `stacking` outlives the call, which never reads the views. + let order = unsafe { compare_stacking(*first, *second, (&raw mut stacking).cast()) }; + match order { + NSComparisonResult::Ascending => std::cmp::Ordering::Less, + NSComparisonResult::Same => std::cmp::Ordering::Equal, + NSComparisonResult::Descending => std::cmp::Ordering::Greater, + } + }); + // Views that aren't native views stay on their side of the GPUI view. + assert_eq!( + back_to_front, + [behind, hidden, back, front, gpui_view, above] + ); + } + + fn focused(view: u64, shown: bool) -> Option { + Some(FocusedNativeView { + id: id(view), + shown, + }) + } + + fn id(id: u64) -> NativeViewId { + NativeViewId::for_test(id) + } +} diff --git a/crates/gpui_wgpu/src/wgpu_renderer.rs b/crates/gpui_wgpu/src/wgpu_renderer.rs index 53af304a9f6..cd9d870be62 100644 --- a/crates/gpui_wgpu/src/wgpu_renderer.rs +++ b/crates/gpui_wgpu/src/wgpu_renderer.rs @@ -1543,6 +1543,8 @@ impl WgpuRendererCore { // Surfaces are macOS-only for video playback and are not // implemented by the WGPU renderer. PrimitiveBatch::Surfaces(_surfaces) => {} + // Native views are only composited by the Metal renderer. + PrimitiveBatch::NativeViews(_) => {} } } } diff --git a/crates/gpui_windows/src/directx_renderer.rs b/crates/gpui_windows/src/directx_renderer.rs index 8573fe40309..5ab916797fa 100644 --- a/crates/gpui_windows/src/directx_renderer.rs +++ b/crates/gpui_windows/src/directx_renderer.rs @@ -438,6 +438,8 @@ impl DirectXRenderer { self.draw_polychrome_sprites(texture_id, range.start, range.len()) } PrimitiveBatch::Surfaces(range) => self.draw_surfaces(&scene.surfaces[range]), + // Native views are only composited on macOS. + PrimitiveBatch::NativeViews(_) => Ok(()), } .with_context(|| { format!(