Skip to main content

gpui/window/
native_view.rs

1use crate::{Action, KeyBinding, KeyDownEvent, PlatformInput};
2use crate::{
3    AnyWindowHandle, App, Bounds, Element, ElementId, FocusHandle, FocusId, Focusable,
4    GlobalElementId, Hitbox, HitboxBehavior, HitboxId, Hsla, InspectorElementId,
5    InteractiveElement, IntoElement, LayoutId, PaintNativeView, ParentElement, Pixels, Point,
6    Style, Styled, Window, div,
7};
8use anyhow::{Context as _, Result};
9use collections::HashSet;
10use std::{
11    any::{Any, TypeId},
12    cell::{Cell, RefCell},
13    ffi::c_void,
14    ptr::NonNull,
15    rc::{Rc, Weak},
16};
17
18/// Identifies a [`NativeView`] within its window.
19#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)]
20pub struct NativeViewId(u64);
21
22#[cfg(any(test, feature = "test-support"))]
23impl NativeViewId {
24    /// Makes an ID for a test that needs one without a window to attach a view to.
25    pub fn for_test(id: u64) -> Self {
26        Self(id)
27    }
28}
29
30/// A view owned by the platform's UI toolkit, shown inside a GPUI window.
31///
32/// Only macOS shows native views so far, where the view is an `NSView`.
33/// [`NativeView::new`] fails on every other platform.
34///
35/// The view is composited beneath the window's GPUI content and shows through
36/// wherever this handle is used as an element, so elements painted after it
37/// cover it like they would cover any other element. The view is treated as
38/// opaque, and is not affected by element opacity or transformations.
39///
40/// Mouse input over the view goes to the view, and to nothing behind it,
41/// wherever no element painted after the view takes mouse input. An element
42/// 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
43/// there, as a press outside every element. An element behind the view hears
44/// no mouse moves while the pointer is over it, so follow a drag that can cross
45/// the view with `on_drag_move`, or with an element in front of the view.
46///
47/// The view takes keyboard input directly from the platform while its
48/// [`FocusHandle`] is focused, which a click on the view does, as can an
49/// assistive technology such as VoiceOver moving its cursor into the view.
50/// A key the view doesn't use is then dispatched from the view's element like
51/// any other key press, so key bindings apply to what the view leaves.
52///
53/// Two kinds of key reach key bindings before the view. Bindings for actions
54/// passed to [`reserve_action`](Self::reserve_action) apply first, and their
55/// keys never reach the view. A key held with Command or Control is offered to
56/// the view as a key equivalent, which is how a web view takes it; a view that
57/// only takes such keys as ordinary key presses, as AppKit's text views do,
58/// gets one after key bindings have had it.
59///
60/// The view may take a moment to leave a key, so the keys of any other
61/// multi-key binding can reach the view when they are typed quickly.
62///
63/// The view stays attached to the window it was created in, hidden when it
64/// isn't painted, until the last clone of this handle is dropped. Painted more
65/// than once in a frame, it shows only where it was painted first. It shows
66/// nothing as an element of any other window, so showing the same platform
67/// view in another window takes dropping this handle and creating one there.
68#[derive(Clone)]
69pub struct NativeView(Rc<NativeViewState>);
70
71pub(crate) struct NativeViewState {
72    id: NativeViewId,
73    window: AnyWindowHandle,
74    focus_handle: FocusHandle,
75    background: Cell<Hsla>,
76    /// The hitbox of the occurrence that shows the view, which is the one
77    /// painted first in a frame that paints the view more than once.
78    shown_hitbox: Cell<Option<HitboxId>>,
79    reserved_actions: RefCell<HashSet<TypeId>>,
80    _attachment: Box<dyn Any>,
81}
82
83impl NativeView {
84    /// Attaches a platform view to the window.
85    ///
86    /// # Errors
87    ///
88    /// Fails on platforms that cannot composite native views, which is every
89    /// platform but macOS for now.
90    ///
91    /// # Safety
92    ///
93    /// `view` must point to a live view of the kind the window's platform
94    /// embeds, which is an `NSView` on macOS, and that view must not be in
95    /// another view hierarchy.
96    ///
97    /// GPUI retains the view and puts it inside a view of its own, until the
98    /// last clone of the returned handle is dropped. Until then GPUI decides the
99    /// view's frame, whether it is hidden, and its order among the window's other
100    /// views, so the caller must leave those alone and must not move the view to
101    /// another superview.
102    pub unsafe fn new(view: NonNull<c_void>, window: &mut Window, cx: &mut App) -> Result<Self> {
103        let id = NativeViewId(window.next_native_view_id);
104        // SAFETY: The caller upholds the platform's requirements for `view`.
105        let attachment = unsafe { window.platform_window.attach_native_view(id, view) }
106            .context("this platform cannot show native views")?;
107        window.next_native_view_id += 1;
108        let state = Rc::new(NativeViewState {
109            id,
110            window: window.handle,
111            focus_handle: cx.focus_handle(),
112            background: Cell::new(Hsla::transparent_black()),
113            shown_hitbox: Cell::new(None),
114            reserved_actions: RefCell::default(),
115            _attachment: attachment,
116        });
117        window.native_views.push(Rc::downgrade(&state));
118        Ok(Self(state))
119    }
120}
121
122impl NativeView {
123    /// Sets the color shown where the view has not caught up with its element.
124    ///
125    /// The platform moves the view through its own compositor, so for a frame
126    /// or two after its element moves or resizes, part of the element can be
127    /// uncovered. A color close to the view's own background hides that. A
128    /// window showing several native views uses the color of the one painted
129    /// last.
130    pub fn set_background(&self, color: impl Into<Hsla>, cx: &mut App) {
131        let color = color.into();
132        if self.0.background.replace(color) == color {
133            return;
134        }
135        // The color is part of what the element paints.
136        let window = self.0.window;
137        cx.defer(move |cx| {
138            window.update(cx, |_, window, _| window.refresh()).ok();
139        });
140    }
141
142    /// Makes key bindings for `A` apply before the view sees the key.
143    ///
144    /// The view otherwise sees every key first and can keep any of them, so
145    /// this is for the few bindings that must work whatever the view shows.
146    /// The view never sees a key that such a binding starts with, even when the
147    /// rest of the binding's keys don't follow.
148    pub fn reserve_action<A: Action>(&self) {
149        self.0
150            .reserved_actions
151            .borrow_mut()
152            .insert(TypeId::of::<A>());
153    }
154}
155
156impl Focusable for NativeView {
157    fn focus_handle(&self, _: &App) -> FocusHandle {
158        self.0.focus_handle.clone()
159    }
160}
161
162impl IntoElement for NativeView {
163    type Element = crate::Div;
164
165    fn into_element(self) -> Self::Element {
166        div()
167            .track_focus(&self.0.focus_handle)
168            .size_full()
169            .child(NativeViewElement(self))
170    }
171}
172
173struct NativeViewElement(NativeView);
174
175impl Element for NativeViewElement {
176    type RequestLayoutState = ();
177    /// `None` in a window other than the one the view is attached to.
178    type PrepaintState = Option<Hitbox>;
179
180    fn id(&self) -> Option<ElementId> {
181        None
182    }
183
184    fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
185        None
186    }
187
188    fn request_layout(
189        &mut self,
190        _id: Option<&GlobalElementId>,
191        _inspector_id: Option<&InspectorElementId>,
192        window: &mut Window,
193        cx: &mut App,
194    ) -> (LayoutId, Self::RequestLayoutState) {
195        let mut style = Style::default();
196        style.size.width = crate::relative(1.).into();
197        style.size.height = crate::relative(1.).into();
198        (window.request_layout(style, [], cx), ())
199    }
200
201    fn prepaint(
202        &mut self,
203        _id: Option<&GlobalElementId>,
204        _inspector_id: Option<&InspectorElementId>,
205        bounds: Bounds<Pixels>,
206        _request_layout: &mut Self::RequestLayoutState,
207        window: &mut Window,
208        _cx: &mut App,
209    ) -> Option<Hitbox> {
210        let state = &self.0.0;
211        if state.window != window.handle {
212            return None;
213        }
214        // The view is only where it is painted first, so a later occurrence
215        // must not keep mouse input from what is behind it. It still has a
216        // hitbox, which becomes the view's if a frame reuses this occurrence
217        // after the first one has gone. An occurrence that is clipped away
218        // paints nothing, and doesn't count as the first.
219        let is_visible = !bounds.intersect(&window.content_mask().bounds).is_empty();
220        let is_shown_elsewhere = state.shown_hitbox.get().is_some_and(|shown| {
221            window
222                .next_frame
223                .hitboxes
224                .iter()
225                .any(|hitbox| hitbox.id == shown)
226        });
227        let shows_view = is_visible && !is_shown_elsewhere;
228        let behavior = if shows_view {
229            HitboxBehavior::BlockMouse
230        } else {
231            HitboxBehavior::Normal
232        };
233        let hitbox = window.insert_hitbox(bounds, behavior);
234        if shows_view {
235            state.shown_hitbox.set(Some(hitbox.id));
236        }
237        Some(hitbox)
238    }
239
240    fn paint(
241        &mut self,
242        _id: Option<&GlobalElementId>,
243        _inspector_id: Option<&InspectorElementId>,
244        _bounds: Bounds<Pixels>,
245        _request_layout: &mut Self::RequestLayoutState,
246        hitbox: &mut Option<Hitbox>,
247        window: &mut Window,
248        _cx: &mut App,
249    ) {
250        let Some(hitbox) = hitbox else {
251            return;
252        };
253        let id = self.0.0.id;
254        let bounds = window.snap_bounds(hitbox.bounds);
255        let content_mask = window.snapped_content_mask();
256        window.next_frame.scene.insert_primitive(PaintNativeView {
257            order: 0,
258            id,
259            hitbox_id: hitbox.id,
260            bounds,
261            content_mask,
262            background: self.0.0.background.get(),
263        });
264    }
265}
266
267impl Window {
268    /// Tells the platform which native view, if any, the focused handle belongs to.
269    pub(super) fn sync_native_view_focus(&mut self) {
270        self.native_views.retain(|view| view.strong_count() > 0);
271        if self.native_views.is_empty() {
272            return;
273        }
274        let focused = self
275            .focus
276            .and_then(|focus| self.native_view_for_focus(focus));
277        self.platform_window.set_focused_native_view(focused);
278    }
279
280    /// Ends an unfinished composition in the window's own content when keyboard
281    /// input is about to move to a native view.
282    ///
283    /// The platform also asks for this as its own view loses keyboard input, but
284    /// that request needs the app, which is already borrowed when focus is moved
285    /// from inside an update. The entity being updated may also be the one that
286    /// holds the composition, so this waits for the update to end.
287    pub(super) fn end_composition_before_focusing_native_view(
288        &mut self,
289        focus: FocusId,
290        cx: &mut App,
291    ) {
292        if self.native_view_for_focus(focus).is_none() {
293            return;
294        }
295        self.defer(cx, |window, cx| {
296            if let Some(mut input_handler) = window.platform_window.take_input_handler() {
297                input_handler.unmark_text_during_update(window, cx);
298                window.platform_window.set_input_handler(input_handler);
299            }
300        });
301    }
302
303    fn native_view_for_focus(&self, focus: FocusId) -> Option<NativeViewId> {
304        self.native_views
305            .iter()
306            .filter_map(Weak::upgrade)
307            .find(|view| view.focus_handle.id == focus)
308            .map(|view| view.id)
309    }
310
311    /// The native view that a mouse event at this position reaches, if no
312    /// GPUI hitbox is above it there.
313    pub(super) fn hit_test_native_view(&self, position: Point<Pixels>) -> Option<NativeViewId> {
314        let hit_test = self.rendered_frame.hit_test(position);
315        let topmost = hit_test.ids.first()?;
316        self.rendered_frame
317            .scene
318            .native_views
319            .iter()
320            .find(|native_view| native_view.hitbox_id == *topmost)
321            .map(|native_view| native_view.id)
322    }
323
324    /// Dispatches a key press that the focused native view has not seen yet, if
325    /// it continues a pending binding or is bound to an action the view reserved.
326    pub(super) fn dispatch_key_down_before_native_view(
327        &mut self,
328        event: KeyDownEvent,
329        cx: &mut App,
330    ) -> bool {
331        let Some(view) = self
332            .native_views
333            .iter()
334            .filter_map(Weak::upgrade)
335            .find(|view| Some(view.focus_handle.id) == self.focus)
336        else {
337            return false;
338        };
339        let node_id = self.focus_node_id_in_rendered_frame(self.focus);
340        let dispatch_path = self.rendered_frame.dispatch_tree.dispatch_path(node_id);
341        let dispatch_tree = &self.rendered_frame.dispatch_tree;
342        let pending = self.pending_input_keystrokes();
343        let is_pending = pending.is_some();
344        let continues_pending = pending.is_some_and(|pending| {
345            let mut input = pending.to_vec();
346            input.push(event.keystroke.clone());
347            let (bindings, is_pending, _) =
348                dispatch_tree.bindings_for_input(&input, &dispatch_path);
349            is_pending || !bindings.is_empty()
350        });
351        let is_reserved = !continues_pending && {
352            let input = std::slice::from_ref(&event.keystroke);
353            let (bindings, _, context_stack) =
354                dispatch_tree.bindings_for_input(input, &dispatch_path);
355            let reserved_actions = view.reserved_actions.borrow();
356            let is_reserved = |binding: &KeyBinding| {
357                reserved_actions.contains(&binding.action.as_any().type_id())
358            };
359            // The first key of a longer binding is reserved too, or the view
360            // could keep that key and the binding would never begin.
361            bindings.first().is_some_and(is_reserved)
362                || dispatch_tree
363                    .possible_next_bindings_for_input(input, &context_stack)
364                    .iter()
365                    .any(is_reserved)
366        };
367        if is_pending && !continues_pending {
368            // The pending binding ends here, as it would in the window's own
369            // content. Left pending, it would be completed by a later key even
370            // after the view had used this one.
371            self.flush_pending_input(cx);
372        }
373        if !continues_pending && !is_reserved {
374            // The key is left for the view like any other. Dispatching it here
375            // as well would dispatch it twice when the view then leaves it.
376            return false;
377        }
378        // The key is GPUI's whether or not anything acts on it. Leaving it to
379        // the view as well would have it dispatched again when the view left it.
380        self.dispatch_event(PlatformInput::KeyDown(event), cx);
381        true
382    }
383
384    /// Focuses the handle of a native view that the platform gave keyboard input to.
385    pub(super) fn focus_native_view(&mut self, id: NativeViewId, cx: &mut App) {
386        let view = self
387            .native_views
388            .iter()
389            .filter_map(Weak::upgrade)
390            .find(|view| view.id == id);
391        if let Some(view) = view {
392            self.focus(&view.focus_handle, cx);
393        }
394    }
395}
396
397#[cfg(test)]
398mod tests {
399    use super::*;
400    use crate::{
401        Context, Entity, FocusHandle, InputHandler, KeyBinding, Keystroke, Modifiers, MouseButton,
402        Render, ScaledPixels, TestAppContext, UTF16Selection, VisualTestContext, WindowHandle,
403        canvas, point, prelude::*, px, rgb,
404    };
405    use std::ops::Range;
406
407    #[gpui::test]
408    fn focusing_a_native_view_gives_it_keyboard_input(cx: &mut TestAppContext) {
409        let window = open_window(cx);
410        let platform_window = cx.test_window(window.into());
411
412        let id = window
413            .update(cx, |view, window, cx| {
414                window.focus(&view.native_view.focus_handle(cx), cx);
415                view.native_view.0.id
416            })
417            .unwrap();
418        assert_eq!(platform_window.focused_native_view(), Some(id));
419
420        window
421            .update(cx, |view, window, cx| window.focus(&view.other_focus, cx))
422            .unwrap();
423        assert_eq!(platform_window.focused_native_view(), None);
424
425        window
426            .update(cx, |view, window, cx| {
427                window.focus(&view.native_view.focus_handle(cx), cx);
428                window.blur(cx);
429            })
430            .unwrap();
431        assert_eq!(platform_window.focused_native_view(), None);
432    }
433
434    #[gpui::test]
435    fn platform_focus_of_a_native_view_focuses_its_handle(cx: &mut TestAppContext) {
436        let window = open_window(cx);
437        let platform_window = cx.test_window(window.into());
438        let id = window
439            .update(cx, |view, window, cx| {
440                window.focus(&view.other_focus, cx);
441                view.native_view.0.id
442            })
443            .unwrap();
444
445        platform_window.simulate_native_view_focused(id);
446
447        window
448            .update(cx, |view, window, cx| {
449                assert!(view.native_view.focus_handle(cx).is_focused(window));
450            })
451            .unwrap();
452        assert_eq!(platform_window.focused_native_view(), Some(id));
453    }
454
455    #[gpui::test]
456    fn only_reserved_and_pending_bindings_apply_before_a_native_view(cx: &mut TestAppContext) {
457        cx.update(|cx| {
458            cx.bind_keys([
459                KeyBinding::new("cmd-r", Reserved, None),
460                KeyBinding::new("cmd-o", Ordinary, None),
461                KeyBinding::new("cmd-k o", Ordinary, None),
462                KeyBinding::new("cmd-j r", Reserved, None),
463            ]);
464        });
465        let window = open_window(cx);
466        let platform_window = cx.test_window(window.into());
467        window
468            .update(cx, |view, window, cx| {
469                view.native_view.reserve_action::<Reserved>();
470                window.focus(&view.native_view.focus_handle(cx), cx);
471            })
472            .unwrap();
473        cx.run_until_parked();
474        let press = |keystroke: &'static str| KeyDownEvent {
475            keystroke: Keystroke::parse(keystroke).unwrap(),
476            is_held: false,
477            prefer_character_input: false,
478        };
479        let actions = |cx: &mut TestAppContext| {
480            window
481                .update(cx, |view, _, _| std::mem::take(&mut view.actions))
482                .unwrap()
483        };
484
485        assert!(platform_window.simulate_key_down_before_native_view(press("cmd-r")));
486        assert_eq!(actions(cx), ["reserved"]);
487
488        // The view gets to see an ordinary binding's key first.
489        assert!(!platform_window.simulate_key_down_before_native_view(press("cmd-o")));
490        assert_eq!(actions(cx), [] as [&str; 0]);
491
492        // Once the view has left the first key of a binding to GPUI, the rest
493        // of that binding's keys are GPUI's.
494        assert!(!platform_window.simulate_key_down_before_native_view(press("cmd-k")));
495        cx.simulate_keystrokes(window.into(), "cmd-k");
496        // A key that doesn't continue the binding ends it. The key is the
497        // view's to see first, and isn't dispatched here, which would dispatch
498        // it twice if the view then left it.
499        assert!(!platform_window.simulate_key_down_before_native_view(press("x")));
500        assert!(
501            !window
502                .update(cx, |_, window, _| window.has_pending_keystrokes())
503                .unwrap()
504        );
505        let keys = |cx: &mut TestAppContext| {
506            window
507                .update(cx, |view, _, _| std::mem::take(&mut view.keys))
508                .unwrap()
509        };
510        // The binding's first key is dispatched on its own, as it is when
511        // the binding times out.
512        assert_eq!(keys(cx), ["k"]);
513        cx.simulate_keystrokes(window.into(), "x");
514        assert_eq!(keys(cx), ["x"]);
515        // Whether or not the view used that key, the rest of the binding's
516        // keys no longer complete it, and are the view's again.
517        assert!(!platform_window.simulate_key_down_before_native_view(press("o")));
518        assert_eq!(actions(cx), [] as [&str; 0]);
519
520        // The view never sees the first key of a reserved binding, which it
521        // could otherwise keep.
522        assert!(platform_window.simulate_key_down_before_native_view(press("cmd-j")));
523        assert!(platform_window.simulate_key_down_before_native_view(press("r")));
524        assert_eq!(actions(cx), ["reserved"]);
525
526        // Nothing applies ahead of the window's own content.
527        window
528            .update(cx, |view, window, cx| window.focus(&view.other_focus, cx))
529            .unwrap();
530        assert!(!platform_window.simulate_key_down_before_native_view(press("cmd-r")));
531    }
532
533    #[gpui::test]
534    fn mouse_reaches_a_native_view_only_where_nothing_covers_it(cx: &mut TestAppContext) {
535        let window = open_window(cx);
536        let platform_window = cx.test_window(window.into());
537        let id = window
538            .update(cx, |view, _, _| view.native_view.0.id)
539            .unwrap();
540        cx.run_until_parked();
541
542        let uncovered = point(px(75.), px(75.));
543        let covered = point(px(25.), px(25.));
544        let outside = point(px(150.), px(150.));
545        assert_eq!(platform_window.hit_test_native_view(uncovered), Some(id));
546        assert_eq!(platform_window.hit_test_native_view(covered), None);
547        assert_eq!(platform_window.hit_test_native_view(outside), None);
548    }
549
550    #[gpui::test]
551    fn mouse_press_on_a_native_view_reaches_nothing_behind_it(cx: &mut TestAppContext) {
552        let window = open_window(cx);
553        cx.run_until_parked();
554        let mut cx = VisualTestContext::from_window(window.into(), cx);
555
556        // The platform passes on a press that it gives to the view.
557        cx.simulate_mouse_down(
558            point(px(75.), px(75.)),
559            MouseButton::Left,
560            Modifiers::default(),
561        );
562
563        let presses = window
564            .update(&mut cx, |view, _, _| std::mem::take(&mut view.presses))
565            .unwrap();
566        assert_eq!(presses, ["outside cover"]);
567    }
568
569    #[gpui::test]
570    fn changing_the_background_repaints_the_native_view(cx: &mut TestAppContext) {
571        let window = open_window(cx);
572        cx.run_until_parked();
573
574        window
575            .update(cx, |view, _, cx| {
576                view.native_view.set_background(rgb(0x00ff00), cx);
577            })
578            .unwrap();
579        cx.run_until_parked();
580
581        window
582            .update(cx, |_, window, _| {
583                let backgrounds = window
584                    .rendered_frame
585                    .scene
586                    .native_views
587                    .iter()
588                    .map(|native_view| native_view.background)
589                    .collect::<Vec<_>>();
590                assert_eq!(backgrounds, [Hsla::from(rgb(0x00ff00))]);
591            })
592            .unwrap();
593    }
594
595    #[gpui::test]
596    fn native_view_painted_twice_shows_where_it_was_painted_first(cx: &mut TestAppContext) {
597        let window = open_window(cx);
598        window
599            .update(cx, |view, _, cx| {
600                view.paints_native_view_twice = true;
601                cx.notify();
602            })
603            .unwrap();
604        cx.run_until_parked();
605
606        window
607            .update(cx, |_, window, _| {
608                let bounds = window
609                    .rendered_frame
610                    .scene
611                    .native_views
612                    .iter()
613                    .map(|native_view| native_view.bounds.origin.x)
614                    .collect::<Vec<_>>();
615                assert_eq!(bounds, [ScaledPixels::from(0.)]);
616            })
617            .unwrap();
618
619        // Where the view was painted again, it isn't shown and takes no mouse
620        // input, so what is behind it there gets the press.
621        let id = window
622            .update(cx, |view, _, _| view.native_view.0.id)
623            .unwrap();
624        let platform_window = cx.test_window(window.into());
625        let painted_first = point(px(75.), px(75.));
626        let painted_again = point(px(250.), px(50.));
627        assert_eq!(
628            platform_window.hit_test_native_view(painted_first),
629            Some(id)
630        );
631        assert_eq!(platform_window.hit_test_native_view(painted_again), None);
632        let mut cx = VisualTestContext::from_window(window.into(), cx);
633        cx.simulate_mouse_down(painted_again, MouseButton::Left, Modifiers::default());
634        let presses = window
635            .update(&mut cx, |view, _, _| std::mem::take(&mut view.presses))
636            .unwrap();
637        assert_eq!(presses, ["outside cover", "behind second occurrence"]);
638    }
639
640    #[gpui::test]
641    fn native_view_is_drawn_in_paint_order(cx: &mut TestAppContext) {
642        let window = open_window(cx);
643        cx.run_until_parked();
644
645        // The view shows through its container's background, and the element
646        // painted after it covers it.
647        window
648            .update(cx, |_, window, _| {
649                let labels = window
650                    .rendered_frame
651                    .scene
652                    .batches()
653                    .map(|batch| batch.label())
654                    .collect::<Vec<_>>();
655                assert_eq!(labels, ["quads (1)", "native views (1)", "quads (1)"]);
656            })
657            .unwrap();
658    }
659
660    #[gpui::test]
661    fn native_view_stays_attached_until_its_last_handle_is_dropped(cx: &mut TestAppContext) {
662        let window = open_window(cx);
663        let platform_window = cx.test_window(window.into());
664        let other_handle = window
665            .update(cx, |view, _, _| view.native_view.clone())
666            .unwrap();
667        assert_eq!(platform_window.attached_native_view_count(), 1);
668
669        window
670            .update(cx, |view, window, cx| {
671                view.native_view = new_native_view(window, cx);
672            })
673            .unwrap();
674        assert_eq!(platform_window.attached_native_view_count(), 2);
675
676        drop(other_handle);
677        assert_eq!(platform_window.attached_native_view_count(), 1);
678    }
679
680    #[gpui::test]
681    fn native_view_shows_nothing_in_another_window(cx: &mut TestAppContext) {
682        let window = open_window(cx);
683        let native_view = window
684            .update(cx, |view, _, _| view.native_view.clone())
685            .unwrap();
686        let other_window = cx.add_window(|_, cx| TestView {
687            native_view,
688            other_focus: cx.focus_handle(),
689            actions: Vec::new(),
690            keys: Vec::new(),
691            presses: Vec::new(),
692            paints_native_view_twice: false,
693            unmark_count: 0,
694        });
695        cx.run_until_parked();
696
697        other_window
698            .update(cx, |_, window, _| {
699                assert!(window.rendered_frame.scene.native_views.is_empty());
700            })
701            .unwrap();
702        window
703            .update(cx, |_, window, _| {
704                assert_eq!(window.rendered_frame.scene.native_views.len(), 1);
705            })
706            .unwrap();
707    }
708
709    #[gpui::test]
710    fn focusing_a_native_view_ends_a_composition(cx: &mut TestAppContext) {
711        let window = open_window(cx);
712        window
713            .update(cx, |view, window, cx| window.focus(&view.other_focus, cx))
714            .unwrap();
715        cx.run_until_parked();
716
717        // The view that holds the composition moves focus from inside its own
718        // update, so the composition can only be ended once that is over.
719        window
720            .update(cx, |view, window, cx| {
721                window.focus(&view.native_view.focus_handle(cx), cx);
722            })
723            .unwrap();
724        let unmark_count = window.update(cx, |view, _, _| view.unmark_count).unwrap();
725        assert_eq!(unmark_count, 1);
726    }
727
728    actions!(native_view_tests, [Reserved, Ordinary]);
729
730    struct TestView {
731        native_view: NativeView,
732        other_focus: FocusHandle,
733        actions: Vec<&'static str>,
734        /// The key presses dispatched to the window's content.
735        keys: Vec<String>,
736        presses: Vec<&'static str>,
737        paints_native_view_twice: bool,
738        /// How many times the input handler of the "cover" element was told to
739        /// end its composition.
740        unmark_count: usize,
741    }
742
743    impl Render for TestView {
744        fn render(&mut self, _: &mut Window, cx: &mut Context<Self>) -> impl IntoElement {
745            div()
746                .size_full()
747                .on_action(cx.listener(|this, _: &Reserved, _, _| this.actions.push("reserved")))
748                .on_action(cx.listener(|this, _: &Ordinary, _, _| this.actions.push("ordinary")))
749                .on_key_down(cx.listener(|this, event: &KeyDownEvent, _, _| {
750                    this.keys.push(event.keystroke.key.clone())
751                }))
752                .child(
753                    div()
754                        .absolute()
755                        .top_0()
756                        .left_0()
757                        .size(px(100.))
758                        .bg(rgb(0xff0000))
759                        .on_mouse_down(
760                            MouseButton::Left,
761                            cx.listener(|this, _, _, _| this.presses.push("behind view")),
762                        )
763                        .child(self.native_view.clone()),
764                )
765                .when(self.paints_native_view_twice, |this| {
766                    this.child(
767                        div()
768                            .absolute()
769                            .top_0()
770                            .left(px(200.))
771                            .size(px(100.))
772                            .on_mouse_down(
773                                MouseButton::Left,
774                                cx.listener(|this, _, _, _| {
775                                    this.presses.push("behind second occurrence")
776                                }),
777                            )
778                            .child(self.native_view.clone()),
779                    )
780                })
781                .child(
782                    div()
783                        .id("cover")
784                        .track_focus(&self.other_focus)
785                        .absolute()
786                        .top_0()
787                        .left_0()
788                        .size(px(50.))
789                        .occlude()
790                        .bg(rgb(0x0000ff))
791                        .on_mouse_down_out(
792                            cx.listener(|this, _, _, _| this.presses.push("outside cover")),
793                        )
794                        .child({
795                            let focus = self.other_focus.clone();
796                            let view = cx.entity();
797                            canvas(
798                                |_, _, _| {},
799                                move |_, _, window, cx| {
800                                    window.handle_input(&focus, TestInput { view }, cx);
801                                },
802                            )
803                            .size_full()
804                        }),
805                )
806        }
807    }
808
809    /// Reaches its view as an element's input handler does, by updating it.
810    struct TestInput {
811        view: Entity<TestView>,
812    }
813
814    impl InputHandler for TestInput {
815        fn selected_text_range(
816            &mut self,
817            _: bool,
818            _: &mut Window,
819            _: &mut App,
820        ) -> Option<UTF16Selection> {
821            None
822        }
823
824        fn marked_text_range(&mut self, _: &mut Window, _: &mut App) -> Option<Range<usize>> {
825            None
826        }
827
828        fn text_for_range(
829            &mut self,
830            _: Range<usize>,
831            _: &mut Option<Range<usize>>,
832            _: &mut Window,
833            _: &mut App,
834        ) -> Option<String> {
835            None
836        }
837
838        fn replace_text_in_range(
839            &mut self,
840            _: Option<Range<usize>>,
841            _: &str,
842            _: &mut Window,
843            _: &mut App,
844        ) {
845        }
846
847        fn replace_and_mark_text_in_range(
848            &mut self,
849            _: Option<Range<usize>>,
850            _: &str,
851            _: Option<Range<usize>>,
852            _: &mut Window,
853            _: &mut App,
854        ) {
855        }
856
857        fn unmark_text(&mut self, _: &mut Window, cx: &mut App) {
858            self.view.update(cx, |view, _| view.unmark_count += 1);
859        }
860
861        fn bounds_for_range(
862            &mut self,
863            _: Range<usize>,
864            _: &mut Window,
865            _: &mut App,
866        ) -> Option<Bounds<Pixels>> {
867            None
868        }
869
870        fn character_index_for_point(
871            &mut self,
872            _: Point<Pixels>,
873            _: &mut Window,
874            _: &mut App,
875        ) -> Option<usize> {
876            None
877        }
878    }
879
880    fn open_window(cx: &mut TestAppContext) -> WindowHandle<TestView> {
881        cx.add_window(|window, cx| TestView {
882            native_view: new_native_view(window, cx),
883            other_focus: cx.focus_handle(),
884            actions: Vec::new(),
885            keys: Vec::new(),
886            presses: Vec::new(),
887            paints_native_view_twice: false,
888            unmark_count: 0,
889        })
890    }
891
892    fn new_native_view(window: &mut Window, cx: &mut App) -> NativeView {
893        // SAFETY: The test platform never reads the view it is given.
894        unsafe { NativeView::new(NonNull::dangling(), window, cx) }
895            .expect("the test platform attaches native views")
896    }
897}