gpui: Composite native views into the scene on macOS (#67311)

## 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 <noreply@anthropic.com>
Co-authored-by: zed-zippy[bot] <234243425+zed-zippy[bot]@users.noreply.github.com>
This commit is contained in:
Nathan Sobo
2026-11-22 03:18:59 +00:00
committed by GitHub
parent 8ad65dee1c
commit f4fe0be1f8
16 changed files with 3648 additions and 47 deletions
+11
View File
@@ -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"
+571
View File
@@ -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#"<!doctype html>
<html>
<body style="font: 15px -apple-system; margin: 24px; color: #eee; background: #204060">
<h2>Another page</h2>
<p><input placeholder="Type here" size="36" /></p>
</body>
</html>"#;
const PAGE: &CStr = cr#"<!doctype html>
<html>
<body style="font: 15px -apple-system; margin: 24px; color: #222; background: #fdf6e3">
<h2>A live WKWebView</h2>
<p>
<input placeholder="Type here, then press cmd-shift-p" size="36" autofocus />
</p>
<p><textarea rows="3" cols="38">A textarea with some text to select.</textarea></p>
<p contenteditable style="border: 1px solid #999; padding: 6px">An editable paragraph.</p>
<p><a href="https://example.com">A link, for the pointing-hand cursor</a></p>
<p id="kept">This page keeps cmd-k for itself.</p>
<button onclick="this.textContent = 'Clicked ' + (++window.clicks || (window.clicks = 1))">
A page button
</button>
<button onclick="document.body.style.background = window.dark ? '#fdf6e3' : '#30343a'; document.body.style.color = window.dark ? '#222' : '#ddd'; window.dark = !window.dark">
Toggle the page's colors
</button>
<script>
document.addEventListener("keydown", (event) => {
if (event.metaKey && event.key === "k") {
event.preventDefault();
window.keptCount = (window.keptCount || 0) + 1;
document.getElementById("kept").textContent =
"This page kept cmd-k " + window.keptCount + " times.";
}
});
for (let line = 1; line <= 60; line++) {
const paragraph = document.createElement("p");
paragraph.textContent = "Scrollable line " + line;
document.body.appendChild(paragraph);
}
</script>
</body>
</html>"#;
struct Example {
web_view: NativeView,
web_view_object: Retained<AnyObject>,
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<FocusHandle>,
keys_left_by_page: Vec<String>,
}
impl Example {
fn new(window: &mut Window, cx: &mut Context<Self>) -> 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<AnyObject> = msg_send![class!(WKWebView), alloc];
let web_view: Retained<AnyObject> = msg_send![web_view, init];
let configuration: Retained<AnyObject> = msg_send![&*web_view, configuration];
let content_controller: Retained<AnyObject> =
msg_send![&*configuration, userContentController];
const AT_DOCUMENT_END: isize = 1;
let script: Allocated<AnyObject> = msg_send![class!(WKUserScript), alloc];
let script: Retained<AnyObject> = 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<AnyObject> =
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::<TogglePalette>();
(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<Self>,
) {
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<Self>,
) {
if let Some(previous_focus) = self.focus_before_palette.take() {
window.focus(&previous_focus, cx);
cx.notify();
}
}
fn render_palette(&self, cx: &mut Context<Self>) -> 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<Self>) -> 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<AnyObject> {
// 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::<AnyObject>()
];
}
}
/// Creates the object the page's script posts its background color to.
fn background_reporter(sender: mpsc::UnboundedSender<String>) -> Retained<AnyObject> {
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::<mpsc::UnboundedSender<String>>();
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<AnyObject> = msg_send![*class, alloc];
let reporter: Retained<AnyObject> = 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<Rgba> {
let components = text.split_once('(')?.1.strip_suffix(')')?;
let mut components = components
.split(',')
.map(|component| component.trim().parse::<f32>().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.");
}
@@ -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#"<!doctype html>
<html>
<body style="font: 15px -apple-system; margin: 24px">
<p><input placeholder="A field in the page" size="36" autofocus /></p>
</body>
</html>"#;
#[derive(Clone, Copy, PartialEq)]
enum KeyboardInput {
AppKitField,
Page,
Gpui,
}
struct Example {
web_view: NativeView,
web_view_object: Retained<AnyObject>,
appkit_field: Retained<AnyObject>,
keyboard_input: KeyboardInput,
_watch: Task<()>,
}
impl Example {
fn new(window: &mut Window, cx: &mut Context<Self>) -> 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<AnyObject> = msg_send![class!(WKWebView), alloc];
let web_view: Retained<AnyObject> = msg_send![web_view, init];
let _: *mut AnyObject = msg_send![
&*web_view,
loadHTMLString: &*ns_string(PAGE),
baseURL: ptr::null::<AnyObject>()
];
// 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<AnyObject> = msg_send![class!(NSTextView), alloc];
let field: Retained<AnyObject> = 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::<c_void>(),
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<Self>) -> 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<AnyObject> {
// 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.");
}
+55 -9
View File
@@ -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<Self>,
) -> 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 {
+1 -1
View File
@@ -445,7 +445,7 @@ impl DispatchTree {
}
}
fn bindings_for_input(
pub(crate) fn bindings_for_input(
&self,
input: &[Keystroke],
dispatch_path: &SmallVec<[DispatchNodeId; 32]>,
+46
View File
@@ -1365,6 +1365,46 @@ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle {
fn on_should_close(&self, callback: Box<dyn FnMut() -> bool>);
fn on_hit_test_window_control(&self, callback: Box<dyn FnMut() -> Option<WindowControlArea>>);
fn on_close(&self, callback: Box<dyn FnOnce()>);
/// 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<std::ffi::c_void>,
) -> Option<Box<dyn std::any::Any>> {
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<crate::NativeViewId>) {}
/// 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<dyn FnMut(Point<Pixels>) -> Option<crate::NativeViewId>>,
) {
}
/// 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<dyn FnMut(crate::NativeViewId)>) {}
/// 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<dyn FnMut(crate::KeyDownEvent) -> bool>,
) {
}
fn on_appearance_changed(&self, callback: Box<dyn FnMut()>);
fn on_button_layout_changed(&self, _callback: Box<dyn FnMut()>) {}
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);
}
+95 -5
View File
@@ -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<Box<dyn FnMut() -> bool>>,
close_callback: Option<Box<dyn FnOnce()>>,
hit_test_window_control_callback: Option<Box<dyn FnMut() -> Option<WindowControlArea>>>,
attached_native_views: Rc<Cell<usize>>,
focused_native_view: Option<NativeViewId>,
hit_test_native_view_callback: Option<Box<dyn FnMut(Point<Pixels>) -> Option<NativeViewId>>>,
native_view_focused_callback: Option<Box<dyn FnMut(NativeViewId)>>,
key_down_before_native_view_callback: Option<Box<dyn FnMut(KeyDownEvent) -> bool>>,
input_callback: Option<Box<dyn FnMut(PlatformInput) -> DispatchEventResult>>,
active_status_change_callback: Option<Box<dyn FnMut(bool)>>,
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<NativeViewId> {
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<Pixels>) -> Option<NativeViewId> {
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<std::ffi::c_void>,
) -> Option<Box<dyn std::any::Any>> {
struct Attachment(Rc<Cell<usize>>);
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<NativeViewId>) {
self.0.lock().focused_native_view = id;
}
fn on_key_down_before_native_view(&self, callback: Box<dyn FnMut(KeyDownEvent) -> bool>) {
self.0.lock().key_down_before_native_view_callback = Some(callback);
}
fn on_hit_test_native_view(
&self,
callback: Box<dyn FnMut(Point<Pixels>) -> Option<NativeViewId>>,
) {
self.0.lock().hit_test_native_view_callback = Some(callback);
}
fn on_native_view_focused(&self, callback: Box<dyn FnMut(NativeViewId)>) {
self.0.lock().native_view_focused_callback = Some(callback);
}
fn on_appearance_changed(&self, callback: Box<dyn FnMut()>) {
self.0.lock().appearance_change_callback = Some(callback);
}
+155 -3
View File
@@ -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<ScaledPixels>,
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<SubpixelSprite>,
pub polychrome_sprites: Vec<PolychromeSprite>,
pub surfaces: Vec<PaintSurface>,
pub native_views: Vec<PaintNativeView>,
animations: Vec<SpriteAnimation>,
}
@@ -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<Primitive>) {
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<Primitive>) {
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<slice::Iter<'a, PolychromeSprite>>,
surfaces_start: usize,
surfaces_iter: Peekable<slice::Iter<'a, PaintSurface>>,
native_views_start: usize,
native_views_iter: Peekable<slice::Iter<'a, PaintNativeView>>,
}
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<usize>,
},
Surfaces(Range<usize>),
NativeViews(Range<usize>),
}
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<PaintSurface> 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<ScaledPixels>,
/// The clip applied to the view.
pub content_mask: ContentMask<ScaledPixels>,
/// 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<PaintNativeView> 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.
+44
View File
@@ -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<std::rc::Weak<NativeViewState>>,
next_native_view_id: u64,
pub(crate) next_tooltip_id: TooltipId,
pub(crate) tooltip_bounds: Option<TooltipBounds>,
pub(crate) next_frame_callbacks: Rc<RefCell<Vec<FrameCallback>>>,
@@ -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();
}
+815
View File
@@ -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<NativeViewState>);
pub(crate) struct NativeViewState {
id: NativeViewId,
window: AnyWindowHandle,
focus_handle: FocusHandle,
background: Cell<Hsla>,
reserved_actions: RefCell<HashSet<TypeId>>,
_attachment: Box<dyn Any>,
}
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<c_void>, window: &mut Window, cx: &mut App) -> Result<Self> {
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<Hsla>, 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<A: Action>(&self) {
self.0
.reserved_actions
.borrow_mut()
.insert(TypeId::of::<A>());
}
}
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<Hitbox>;
fn id(&self) -> Option<ElementId> {
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<Pixels>,
_request_layout: &mut Self::RequestLayoutState,
window: &mut Window,
_cx: &mut App,
) -> Option<Hitbox> {
(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<Pixels>,
_request_layout: &mut Self::RequestLayoutState,
hitbox: &mut Option<Hitbox>,
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<NativeViewId> {
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<Pixels>) -> Option<NativeViewId> {
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::<Reserved>();
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::<Vec<_>>();
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::<Vec<_>>();
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::<Vec<_>>();
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<Self>) -> 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<TestView>,
}
impl InputHandler for TestInput {
fn selected_text_range(
&mut self,
_: bool,
_: &mut Window,
_: &mut App,
) -> Option<UTF16Selection> {
None
}
fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<Range<usize>> {
None
}
fn text_for_range(
&mut self,
_: Range<usize>,
_: &mut Option<Range<usize>>,
_: &mut Window,
_: &mut App,
) -> Option<String> {
None
}
fn replace_text_in_range(
&mut self,
_: Option<Range<usize>>,
_: &str,
_: &mut Window,
_: &mut App,
) {
}
fn replace_and_mark_text_in_range(
&mut self,
_: Option<Range<usize>>,
_: &str,
_: Option<Range<usize>>,
_: &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<usize>,
_: &mut Window,
_: &mut App,
) -> Option<Bounds<Pixels>> {
None
}
fn character_index_for_point(
&mut self,
_: Point<Pixels>,
_: &mut Window,
_: &mut App,
) -> Option<usize> {
None
}
}
fn open_window(cx: &mut TestAppContext) -> WindowHandle<TestView> {
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")
}
}
+62 -1
View File
@@ -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<ProtocolObject<dyn MTLCommandQueue>>,
path_tiles_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
shadows_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
@@ -138,6 +140,7 @@ pub struct MetalRenderer {
monochrome_sprites_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
polychrome_sprites_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
surfaces_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
native_views_pipeline_state: Retained<ProtocolObject<dyn MTLRenderPipelineState>>,
depth_write_state: Retained<ProtocolObject<dyn MTLDepthStencilState>>,
depth_test_state: Retained<ProtocolObject<dyn MTLDepthStencilState>>,
depth_texture: Option<Retained<ProtocolObject<dyn MTLTexture>>>,
@@ -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<usize>,
instance_bindings: &InstanceBindings,
command_encoder: &ProtocolObject<dyn MTLRenderCommandEncoder>,
) {
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<usize>,
@@ -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<InstanceBindings> {
@@ -1443,6 +1498,12 @@ fn write_instances(scene: &Scene, writer: &mut InstanceBufferWriter) -> Result<I
bounds: surface.bounds,
content_mask: surface.content_mask,
}))?,
native_views: writer.write_iter(scene.native_views.iter().map(|native_view| {
SurfaceBounds {
bounds: native_view.bounds,
content_mask: native_view.content_mask,
}
}))?,
})
}
+22
View File
@@ -968,6 +968,28 @@ fragment float4 surface_fragment(SurfaceFragmentInput input [[stage_in]],
return ycbcrToRGBTransform * ycbcr;
}
struct NativeViewVertexOutput {
float4 position [[position]];
};
vertex NativeViewVertexOutput native_view_vertex(
uint vertex_id [[vertex_id]], uint native_view_id [[instance_id]],
constant SurfaceBounds *native_views [[buffer(SurfaceInputIndex_Surfaces)]],
constant Size_DevicePixels *viewport_size
[[buffer(GlobalInputIndex_ViewportSize)]]) {
float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u));
SurfaceBounds native_view = native_views[native_view_id];
ClippedVertex clipped = clip_to_mask(unit_vertex, native_view.bounds,
native_view.content_mask.bounds);
return NativeViewVertexOutput{
to_device_position_impl(clipped.position, viewport_size)};
}
// The pipeline does not blend, so this erases what was drawn beneath the view.
fragment float4 native_view_fragment(NativeViewVertexOutput input [[stage_in]]) {
return float4(0.);
}
float4 hsla_to_rgba(Hsla hsla) {
float h = hsla.h * 6.0; // Now, it's an angle but scaled in [0, 6) range
float s = hsla.s;
+117 -28
View File
@@ -73,6 +73,8 @@ use std::{
time::Duration,
};
mod native_views;
const WINDOW_STATE_IVAR: &CStr = c"windowState";
static RESTORES_WORKSPACE_AT_LAUNCH_DEFAULT: Once = Once::new();
@@ -269,6 +271,7 @@ unsafe fn build_classes() {
sel!(characterIndexForPoint:),
character_index_for_point as extern "C" fn(_, Sel, NSPoint) -> 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<accesskit_macos::SubclassingAdapter>,
// 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<c_void>,
) -> Option<Box<dyn std::any::Any>> {
// 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<gpui::NativeViewId>) {
native_views::set_focused(&self.0, id);
}
fn on_hit_test_native_view(
&self,
callback: Box<dyn FnMut(Point<Pixels>) -> Option<gpui::NativeViewId>>,
) {
self.0.lock().native_views.hit_test_callback = Some(callback);
}
fn on_native_view_focused(&self, callback: Box<dyn FnMut(gpui::NativeViewId)>) {
self.0.lock().native_views.focused_callback = Some(callback);
}
fn on_key_down_before_native_view(&self, callback: Box<dyn FnMut(KeyDownEvent) -> 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<Mutex<MacWindowState>> {
}
}
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<Rc<Mutex<MacWindowState>>> {
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<MacWindowState>);
if raw.is_null() {
return None;
}
let state = Rc::from_raw(raw as *mut Mutex<MacWindowState>);
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<MacWindowState>));
}
}
}
@@ -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 {
File diff suppressed because it is too large Load Diff
+2
View File
@@ -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(_) => {}
}
}
}
@@ -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!(