Skip to main content

gpui/window/
native_view.rs

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