Skip to main content

gpui/
element.rs

1//! Elements are the workhorses of GPUI. They are responsible for laying out and painting all of
2//! the contents of a window. Elements form a tree and are laid out according to the web layout
3//! standards as implemented by [taffy](https://github.com/DioxusLabs/taffy). Most of the time,
4//! you won't need to interact with this module or these APIs directly. Elements provide their
5//! own APIs and GPUI, or other element implementation, uses the APIs in this module to convert
6//! that element tree into the pixels you see on the screen.
7//!
8//! # Element Basics
9//!
10//! Elements are constructed by calling [`Render::render()`] on the root view of the window,
11//! which recursively constructs the element tree from the current state of the application,.
12//! These elements are then laid out by Taffy, and painted to the screen according to their own
13//! implementation of [`Element::paint()`]. Before the start of the next frame, the entire element
14//! tree and any callbacks they have registered with GPUI are dropped and the process repeats.
15//!
16//! But some state is too simple and voluminous to store in every view that needs it, e.g.
17//! whether a hover has been started or not. For this, GPUI provides the [`Element::PrepaintState`], associated type.
18//!
19//! # Implementing your own elements
20//!
21//! Elements are intended to be the low level, imperative API to GPUI. They are responsible for upholding,
22//! or breaking, GPUI's features as they deem necessary. As an example, most GPUI elements are expected
23//! to stay in the bounds that their parent element gives them. But with [`Window::with_content_mask`],
24//! you can ignore this restriction and paint anywhere inside of the window's bounds. This is useful for overlays
25//! and popups and anything else that shows up 'on top' of other elements.
26//! With great power, comes great responsibility.
27//!
28//! However, most of the time, you won't need to implement your own elements. GPUI provides a number of
29//! elements that should cover most common use cases out of the box and it's recommended that you use those
30//! to construct `components`, using the [`RenderOnce`] trait and the `#[derive(IntoElement)]` macro. Only implement
31//! elements when you need to take manual control of the layout and painting process, such as when using
32//! your own custom layout algorithm or rendering a code editor.
33
34#[cfg(any(feature = "inspector", debug_assertions))]
35use crate::InspectorElementPath;
36use crate::{
37    A11ySubtreeBuilder, App, ArenaBox, AvailableSpace, Bounds, Context, DispatchNodeId, ElementId,
38    FocusHandle, InspectorElementId, LayoutId, Pixels, Point, Size, Style, Window,
39    util::FluentBuilder, window::with_element_arena,
40};
41use std::{
42    any::Any,
43    fmt::{self, Debug, Display},
44    mem, panic,
45    sync::Arc,
46};
47
48/// Implemented by types that participate in laying out and painting the contents of a window.
49/// Elements form a tree and are laid out according to web-based layout rules, as implemented by Taffy.
50/// You can create custom elements by implementing this trait, see the module-level documentation
51/// for more details.
52pub trait Element: 'static + Sized {
53    /// The type of state returned from [`Element::request_layout`]. A mutable reference to this state is subsequently
54    /// provided to [`Element::prepaint`] and [`Element::paint`].
55    type RequestLayoutState: 'static;
56
57    /// The type of state returned from [`Element::prepaint`]. A mutable reference to this state is subsequently
58    /// provided to [`Element::paint`].
59    type PrepaintState: 'static;
60
61    /// If this element has a unique identifier, return it here. This is used to track elements across frames, and
62    /// will cause a GlobalElementId to be passed to the request_layout, prepaint, and paint methods.
63    ///
64    /// The global id can in turn be used to access state that's connected to an element with the same id across
65    /// frames. This id must be unique among children of the first containing element with an id.
66    fn id(&self) -> Option<ElementId>;
67
68    /// Source location where this element was constructed, used to disambiguate elements in the
69    /// inspector and navigate to their source code.
70    fn source_location(&self) -> Option<&'static panic::Location<'static>>;
71
72    /// Before an element can be painted, we need to know where it's going to be and how big it is.
73    /// Use this method to request a layout from Taffy and initialize the element's state.
74    fn request_layout(
75        &mut self,
76        id: Option<&GlobalElementId>,
77        inspector_id: Option<&InspectorElementId>,
78        window: &mut Window,
79        cx: &mut App,
80    ) -> (LayoutId, Self::RequestLayoutState);
81
82    /// After laying out an element, we need to commit its bounds to the current frame for hitbox
83    /// purposes. The state argument is the same state that was returned from [`Element::request_layout()`].
84    fn prepaint(
85        &mut self,
86        id: Option<&GlobalElementId>,
87        inspector_id: Option<&InspectorElementId>,
88        bounds: Bounds<Pixels>,
89        request_layout: &mut Self::RequestLayoutState,
90        window: &mut Window,
91        cx: &mut App,
92    ) -> Self::PrepaintState;
93
94    /// Once layout has been completed, this method will be called to paint the element to the screen.
95    /// The state argument is the same state that was returned from [`Element::request_layout()`].
96    fn paint(
97        &mut self,
98        id: Option<&GlobalElementId>,
99        inspector_id: Option<&InspectorElementId>,
100        bounds: Bounds<Pixels>,
101        request_layout: &mut Self::RequestLayoutState,
102        prepaint: &mut Self::PrepaintState,
103        window: &mut Window,
104        cx: &mut App,
105    );
106
107    /// Returns the accessible role for this element, if any.
108    /// Elements that return `None` are not included in the accessibility tree.
109    ///
110    /// Note: inclusion in accessibility tree requires non-`None` [`id`][Element::id].
111    ///
112    /// See the [accessibility guide](crate::_accessibility) for an overview.
113    fn a11y_role(&self) -> Option<accesskit::Role> {
114        None
115    }
116
117    /// Write accessibility properties to the given node.
118    /// Called only when `a11y_role()` returns `Some`.
119    ///
120    /// See the [accessibility guide](crate::_accessibility) for an overview.
121    fn write_a11y_info(&self, _node: &mut accesskit::Node) {}
122
123    /// Add synthetic child nodes to an [`Element`] that has an
124    /// [`.id()`][Element::id] and a [`.role()`][Element::a11y_role].
125    ///
126    /// Some elements may want to inject accessibility nodes that do not
127    /// correspond to any GPUI element. For example, a custom text field element
128    /// may want to inject synthetic child nodes for the text content.
129    ///
130    /// See [Synthetic children](crate::_accessibility#synthetic-children) in
131    /// the accessibility guide for more detail.
132    fn a11y_synthetic_children(
133        &mut self,
134        _prepaint: &mut Self::PrepaintState,
135        _builder: &mut A11ySubtreeBuilder,
136    ) {
137    }
138
139    /// Convert this element into a dynamically-typed [`AnyElement`].
140    fn into_any(self) -> AnyElement {
141        AnyElement::new_please_call_into_any_to_avoid_double_box(self)
142    }
143}
144
145impl<T: Element> IntoElement for T {
146    type Element = Self;
147
148    fn into_element(self) -> Self::Element {
149        self
150    }
151}
152
153/// Implemented by any type that can be converted into an element.
154pub trait IntoElement: Sized {
155    /// The specific type of element into which the implementing type is converted.
156    /// Useful for converting other types into elements automatically, like Strings
157    type Element: Element;
158
159    /// Convert self into a type that implements [`Element`].
160    fn into_element(self) -> Self::Element;
161
162    /// Convert self into a dynamically-typed [`AnyElement`].
163    fn into_any_element(self) -> AnyElement {
164        self.into_element().into_any()
165    }
166}
167
168impl<T: IntoElement> FluentBuilder for T {}
169
170/// An object that can be drawn to the screen. This is the trait that distinguishes "views" from
171/// other entities. Views are `Entity`'s which `impl Render` and drawn to the screen.
172pub trait Render: 'static + Sized {
173    /// Render this view into an element tree.
174    fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement;
175}
176
177impl Render for Empty {
178    fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
179        Empty
180    }
181}
182
183/// You can derive [`IntoElement`] on any type that implements this trait.
184/// It is used to construct reusable `components` out of plain data. Think of
185/// components as a recipe for a certain pattern of elements. RenderOnce allows
186/// you to invoke this pattern, without breaking the fluent builder pattern of
187/// the element APIs.
188pub trait RenderOnce: 'static {
189    /// Render this component into an element tree. Note that this method
190    /// takes ownership of self, as compared to [`Render::render()`] method
191    /// which takes a mutable reference.
192    fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
193}
194
195/// This is a helper trait to provide a uniform interface for constructing elements that
196/// can accept any number of any kind of child elements
197pub trait ParentElement {
198    /// Extend this element's children with the given child elements.
199    fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>);
200
201    /// Add a single child element to this element.
202    fn child(mut self, child: impl IntoElement) -> Self
203    where
204        Self: Sized,
205    {
206        self.extend(std::iter::once(child.into_any_element()));
207        self
208    }
209
210    /// Add multiple child elements to this element.
211    fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self
212    where
213        Self: Sized,
214    {
215        self.extend(children.into_iter().map(|child| child.into_any_element()));
216        self
217    }
218}
219
220/// A globally unique identifier for an element, used to track state across frames.
221///
222/// The hash of the id path is computed once, when the id is built. Every
223/// element with an id is looked up in the element-state maps of two frames
224/// and recorded as accessed on every frame it is drawn, and each of those
225/// hashes the whole path — every ancestor's id, string names byte by byte —
226/// so on a deep tree the hashing alone was a visible share of a frame.
227#[derive(Clone, Debug)]
228pub struct GlobalElementId {
229    ids: Arc<[ElementId]>,
230    hash: PathHash,
231}
232
233/// The hash of an element id path. Every path hash is folded from [`PathHash::EMPTY`] with
234/// [`PathHash::extend`], one id at a time, so the window can keep the hash of each prefix
235/// of its id stack and never re-hash a path.
236#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
237pub(crate) struct PathHash(u64);
238
239impl PathHash {
240    /// The hash of an empty id path.
241    pub(crate) const EMPTY: Self = Self(0);
242
243    /// The hash of this path with `id` appended.
244    pub(crate) fn extend(self, id: &ElementId) -> Self {
245        use std::hash::{Hash, Hasher};
246        let mut hasher = collections::FxHasher::with_seed(self.0 as usize);
247        id.hash(&mut hasher);
248        Self(hasher.finish())
249    }
250}
251
252impl GlobalElementId {
253    pub(crate) fn new(ids: &[ElementId]) -> Self {
254        let hash = ids.iter().fold(PathHash::EMPTY, PathHash::extend);
255        Self::with_hash(ids, hash)
256    }
257
258    /// `ids` with its hash already known, as the window's id stack keeps it.
259    pub(crate) fn with_hash(ids: &[ElementId], hash: PathHash) -> Self {
260        debug_assert_eq!(hash, ids.iter().fold(PathHash::EMPTY, PathHash::extend));
261        Self {
262            ids: Arc::from(ids),
263            hash,
264        }
265    }
266
267    pub(crate) fn accesskit_node_id(&self) -> accesskit::NodeId {
268        accesskit::NodeId(self.hash.0)
269    }
270}
271
272impl Default for GlobalElementId {
273    fn default() -> Self {
274        Self::new(&[])
275    }
276}
277
278impl std::ops::Deref for GlobalElementId {
279    type Target = [ElementId];
280
281    fn deref(&self) -> &Self::Target {
282        &self.ids
283    }
284}
285
286impl PartialEq for GlobalElementId {
287    fn eq(&self, other: &Self) -> bool {
288        self.hash == other.hash && (Arc::ptr_eq(&self.ids, &other.ids) || self.ids == other.ids)
289    }
290}
291
292impl Eq for GlobalElementId {}
293
294impl std::hash::Hash for GlobalElementId {
295    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
296        state.write_u64(self.hash.0);
297    }
298}
299
300impl Display for GlobalElementId {
301    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302        for (i, element_id) in self.ids.iter().enumerate() {
303            if i > 0 {
304                write!(f, ".")?;
305            }
306            write!(f, "{}", element_id)?;
307        }
308        Ok(())
309    }
310}
311
312trait ElementObject {
313    fn inner_element(&mut self) -> &mut dyn Any;
314
315    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId;
316
317    fn prepaint(&mut self, window: &mut Window, cx: &mut App);
318
319    fn paint(&mut self, window: &mut Window, cx: &mut App);
320
321    fn layout_as_root(
322        &mut self,
323        available_space: Size<AvailableSpace>,
324        window: &mut Window,
325        cx: &mut App,
326    ) -> Size<Pixels>;
327}
328
329/// A wrapper around an implementer of [`Element`] that allows it to be drawn in a window.
330pub struct Drawable<E: Element> {
331    /// The drawn element.
332    pub element: E,
333    phase: ElementDrawPhase<E::RequestLayoutState, E::PrepaintState>,
334}
335
336#[derive(Default)]
337enum ElementDrawPhase<RequestLayoutState, PrepaintState> {
338    #[default]
339    Start,
340    RequestLayout {
341        layout_id: LayoutId,
342        global_id: Option<GlobalElementId>,
343        inspector_id: Option<InspectorElementId>,
344        request_layout: RequestLayoutState,
345    },
346    LayoutComputed {
347        layout_id: LayoutId,
348        global_id: Option<GlobalElementId>,
349        inspector_id: Option<InspectorElementId>,
350        available_space: Size<AvailableSpace>,
351        request_layout: RequestLayoutState,
352    },
353    Prepaint {
354        node_id: DispatchNodeId,
355        global_id: Option<GlobalElementId>,
356        inspector_id: Option<InspectorElementId>,
357        bounds: Bounds<Pixels>,
358        request_layout: RequestLayoutState,
359        prepaint: PrepaintState,
360    },
361    Painted,
362}
363
364/// A wrapper around an implementer of [`Element`] that allows it to be drawn in a window.
365impl<E: Element> Drawable<E> {
366    pub(crate) fn new(element: E) -> Self {
367        Drawable {
368            element,
369            phase: ElementDrawPhase::Start,
370        }
371    }
372
373    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
374        match mem::take(&mut self.phase) {
375            ElementDrawPhase::Start => {
376                let global_id = self
377                    .element
378                    .id()
379                    .map(|element_id| prepare_element_id(element_id, window));
380
381                let inspector_id;
382                #[cfg(any(feature = "inspector", debug_assertions))]
383                {
384                    inspector_id = if window.inspector_enabled() {
385                        self.element
386                            .source_location()
387                            .map(|source| prepare_inspector_id(source, window))
388                    } else {
389                        None
390                    };
391                }
392                #[cfg(not(any(feature = "inspector", debug_assertions)))]
393                {
394                    inspector_id = None;
395                }
396
397                let (layout_id, request_layout) = self.element.request_layout(
398                    global_id.as_ref(),
399                    inspector_id.as_ref(),
400                    window,
401                    cx,
402                );
403
404                if global_id.is_some() {
405                    window.element_id_stack.pop();
406                }
407
408                self.phase = ElementDrawPhase::RequestLayout {
409                    layout_id,
410                    global_id,
411                    inspector_id,
412                    request_layout,
413                };
414                layout_id
415            }
416            _ => panic!("must call request_layout only once"),
417        }
418    }
419
420    pub(crate) fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
421        match mem::take(&mut self.phase) {
422            ElementDrawPhase::RequestLayout {
423                layout_id,
424                global_id,
425                inspector_id,
426                mut request_layout,
427            }
428            | ElementDrawPhase::LayoutComputed {
429                layout_id,
430                global_id,
431                inspector_id,
432                mut request_layout,
433                ..
434            } => {
435                if let Some(element_id) = self.element.id() {
436                    window.element_id_stack.push(element_id);
437                    debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);
438                }
439
440                let bounds = window.layout_bounds(layout_id);
441                let mut pushed_a11y_node = false;
442                if window.a11y.is_active() {
443                    if let Some(global_id) = global_id.as_ref() {
444                        if let Some(role) = self.element.a11y_role() {
445                            let node_id = global_id.accesskit_node_id();
446                            let mut node = accesskit::Node::new(role);
447                            let scale = window.scale_factor();
448                            node.set_bounds(accesskit::Rect {
449                                x0: (bounds.origin.x.0 * scale) as f64,
450                                y0: (bounds.origin.y.0 * scale) as f64,
451                                x1: ((bounds.origin.x.0 + bounds.size.width.0) * scale) as f64,
452                                y1: ((bounds.origin.y.0 + bounds.size.height.0) * scale) as f64,
453                            });
454                            self.element.write_a11y_info(&mut node);
455                            window.a11y.node_bounds.insert(node_id, bounds);
456                            pushed_a11y_node = window.a11y.nodes.push(node_id, node);
457                            #[cfg(debug_assertions)]
458                            if pushed_a11y_node {
459                                let view = window
460                                    .a11y
461                                    .view_type_names
462                                    .get(&window.current_view())
463                                    .copied();
464                                let source_location = self.element.source_location();
465                                window.a11y.nodes.record_node_info(
466                                    node_id,
467                                    crate::window::a11y::debug::NodeDebugInfo {
468                                        synthetic: false,
469                                        view,
470                                        element_id: global_id.last().map(|id| format!("{id:?}")),
471                                        source_location,
472                                    },
473                                );
474                            }
475                        }
476                    }
477                }
478
479                let node_id = window.next_frame.dispatch_tree.push_node();
480                let mut prepaint = self.element.prepaint(
481                    global_id.as_ref(),
482                    inspector_id.as_ref(),
483                    bounds,
484                    &mut request_layout,
485                    window,
486                    cx,
487                );
488                window.next_frame.dispatch_tree.pop_node();
489
490                if pushed_a11y_node {
491                    if let Some(global_id) = global_id.as_ref() {
492                        #[cfg(debug_assertions)]
493                        let creator = crate::window::a11y::debug::NodeCreator {
494                            view: window
495                                .a11y
496                                .view_type_names
497                                .get(&window.current_view())
498                                .copied(),
499                            element_id: global_id.last().map(|id| format!("{id:?}")),
500                            source_location: self.element.source_location(),
501                        };
502                        let mut builder = A11ySubtreeBuilder::new(
503                            global_id.accesskit_node_id(),
504                            &mut window.a11y.nodes,
505                        );
506                        #[cfg(debug_assertions)]
507                        {
508                            builder = builder.with_creator(creator);
509                        }
510                        self.element
511                            .a11y_synthetic_children(&mut prepaint, &mut builder);
512                    }
513                    window.a11y.nodes.pop();
514                }
515
516                if global_id.is_some() {
517                    window.element_id_stack.pop();
518                }
519
520                self.phase = ElementDrawPhase::Prepaint {
521                    node_id,
522                    global_id,
523                    inspector_id,
524                    bounds,
525                    request_layout,
526                    prepaint,
527                };
528            }
529            _ => panic!("must call request_layout before prepaint"),
530        }
531    }
532
533    pub(crate) fn paint(
534        &mut self,
535        window: &mut Window,
536        cx: &mut App,
537    ) -> (E::RequestLayoutState, E::PrepaintState) {
538        match mem::take(&mut self.phase) {
539            ElementDrawPhase::Prepaint {
540                node_id,
541                global_id,
542                inspector_id,
543                bounds,
544                mut request_layout,
545                mut prepaint,
546                ..
547            } => {
548                if let Some(element_id) = self.element.id() {
549                    window.element_id_stack.push(element_id);
550                    debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);
551                }
552
553                window.next_frame.dispatch_tree.set_active_node(node_id);
554                self.element.paint(
555                    global_id.as_ref(),
556                    inspector_id.as_ref(),
557                    bounds,
558                    &mut request_layout,
559                    &mut prepaint,
560                    window,
561                    cx,
562                );
563
564                if global_id.is_some() {
565                    window.element_id_stack.pop();
566                }
567
568                self.phase = ElementDrawPhase::Painted;
569                (request_layout, prepaint)
570            }
571            _ => panic!("must call prepaint before paint"),
572        }
573    }
574
575    pub(crate) fn layout_as_root(
576        &mut self,
577        available_space: Size<AvailableSpace>,
578        window: &mut Window,
579        cx: &mut App,
580    ) -> Size<Pixels> {
581        if matches!(&self.phase, ElementDrawPhase::Start) {
582            self.request_layout(window, cx);
583        }
584
585        let layout_id = match mem::take(&mut self.phase) {
586            ElementDrawPhase::RequestLayout {
587                layout_id,
588                global_id,
589                inspector_id,
590                request_layout,
591            } => {
592                window.compute_layout(layout_id, available_space, cx);
593                self.phase = ElementDrawPhase::LayoutComputed {
594                    layout_id,
595                    global_id,
596                    inspector_id,
597                    available_space,
598                    request_layout,
599                };
600                layout_id
601            }
602            ElementDrawPhase::LayoutComputed {
603                layout_id,
604                global_id,
605                inspector_id,
606                available_space: prev_available_space,
607                request_layout,
608            } => {
609                if available_space != prev_available_space {
610                    window.compute_layout(layout_id, available_space, cx);
611                }
612                self.phase = ElementDrawPhase::LayoutComputed {
613                    layout_id,
614                    global_id,
615                    inspector_id,
616                    available_space,
617                    request_layout,
618                };
619                layout_id
620            }
621            _ => panic!("cannot measure after painting"),
622        };
623
624        window.layout_bounds(layout_id).size
625    }
626}
627
628impl<E> ElementObject for Drawable<E>
629where
630    E: Element,
631    E::RequestLayoutState: 'static,
632{
633    fn inner_element(&mut self) -> &mut dyn Any {
634        &mut self.element
635    }
636
637    #[inline]
638    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
639        Drawable::request_layout(self, window, cx)
640    }
641
642    #[inline]
643    fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
644        Drawable::prepaint(self, window, cx);
645    }
646
647    #[inline]
648    fn paint(&mut self, window: &mut Window, cx: &mut App) {
649        Drawable::paint(self, window, cx);
650    }
651
652    #[inline]
653    fn layout_as_root(
654        &mut self,
655        available_space: Size<AvailableSpace>,
656        window: &mut Window,
657        cx: &mut App,
658    ) -> Size<Pixels> {
659        Drawable::layout_as_root(self, available_space, window, cx)
660    }
661}
662
663/// A dynamically typed element that can be used to store any element type.
664pub struct AnyElement(ArenaBox<dyn ElementObject>);
665
666impl AnyElement {
667    /// Boxes `element` into an `AnyElement`, erasing its concrete type.
668    ///
669    /// This always allocates and always adds a level of boxing, even when `element` is
670    /// already an [`AnyElement`], which would nest one `AnyElement` inside another. Call
671    /// [`Element::into_any`] instead; it skips the wrapper for `AnyElement` itself.
672    fn new_please_call_into_any_to_avoid_double_box<E>(element: E) -> Self
673    where
674        E: 'static + Element,
675        E::RequestLayoutState: Any,
676    {
677        let element = with_element_arena(|arena| arena.alloc(|| Drawable::new(element)))
678            .map(|element| element as &mut dyn ElementObject);
679        AnyElement(element)
680    }
681
682    /// Attempt to downcast a reference to the boxed element to a specific type.
683    pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
684        self.0.inner_element().downcast_mut::<T>()
685    }
686
687    /// Request the layout ID of the element stored in this `AnyElement`.
688    /// Used for laying out child elements in a parent element.
689    pub fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
690        self.0.request_layout(window, cx)
691    }
692
693    /// Prepares the element to be painted by storing its bounds, giving it a chance to draw hitboxes and
694    /// request autoscroll before the final paint pass is confirmed.
695    pub fn prepaint(&mut self, window: &mut Window, cx: &mut App) -> Option<FocusHandle> {
696        let focus_assigned = window.next_frame.focus.is_some();
697
698        self.0.prepaint(window, cx);
699
700        if !focus_assigned && let Some(focus_id) = window.next_frame.focus {
701            return FocusHandle::for_id(focus_id, &cx.focus_handles);
702        }
703
704        None
705    }
706
707    /// Paints the element stored in this `AnyElement`.
708    pub fn paint(&mut self, window: &mut Window, cx: &mut App) {
709        self.0.paint(window, cx);
710    }
711
712    /// Performs layout for this element within the given available space and returns its size.
713    pub fn layout_as_root(
714        &mut self,
715        available_space: Size<AvailableSpace>,
716        window: &mut Window,
717        cx: &mut App,
718    ) -> Size<Pixels> {
719        self.0.layout_as_root(available_space, window, cx)
720    }
721
722    /// Prepaints this element at the given absolute origin.
723    /// If any element in the subtree beneath this element is focused, its FocusHandle is returned.
724    pub fn prepaint_at(
725        &mut self,
726        origin: Point<Pixels>,
727        window: &mut Window,
728        cx: &mut App,
729    ) -> Option<FocusHandle> {
730        window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
731    }
732
733    /// Performs layout on this element in the available space, then prepaints it at the given absolute origin.
734    /// If any element in the subtree beneath this element is focused, its FocusHandle is returned.
735    pub fn prepaint_as_root(
736        &mut self,
737        origin: Point<Pixels>,
738        available_space: Size<AvailableSpace>,
739        window: &mut Window,
740        cx: &mut App,
741    ) -> Option<FocusHandle> {
742        self.layout_as_root(available_space, window, cx);
743        window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
744    }
745}
746
747impl Element for AnyElement {
748    type RequestLayoutState = ();
749    type PrepaintState = ();
750
751    fn id(&self) -> Option<ElementId> {
752        None
753    }
754
755    fn source_location(&self) -> Option<&'static panic::Location<'static>> {
756        None
757    }
758
759    fn request_layout(
760        &mut self,
761        _: Option<&GlobalElementId>,
762        _inspector_id: Option<&InspectorElementId>,
763        window: &mut Window,
764        cx: &mut App,
765    ) -> (LayoutId, Self::RequestLayoutState) {
766        let layout_id = self.request_layout(window, cx);
767        (layout_id, ())
768    }
769
770    fn prepaint(
771        &mut self,
772        _: Option<&GlobalElementId>,
773        _inspector_id: Option<&InspectorElementId>,
774        _: Bounds<Pixels>,
775        _: &mut Self::RequestLayoutState,
776        window: &mut Window,
777        cx: &mut App,
778    ) {
779        self.prepaint(window, cx);
780    }
781
782    fn paint(
783        &mut self,
784        _: Option<&GlobalElementId>,
785        _inspector_id: Option<&InspectorElementId>,
786        _: Bounds<Pixels>,
787        _: &mut Self::RequestLayoutState,
788        _: &mut Self::PrepaintState,
789        window: &mut Window,
790        cx: &mut App,
791    ) {
792        self.paint(window, cx);
793    }
794
795    fn into_any(self) -> AnyElement {
796        self
797    }
798}
799
800/// The empty element, which renders nothing.
801pub struct Empty;
802
803impl Element for Empty {
804    type RequestLayoutState = ();
805    type PrepaintState = ();
806
807    fn id(&self) -> Option<ElementId> {
808        None
809    }
810
811    fn source_location(&self) -> Option<&'static panic::Location<'static>> {
812        None
813    }
814
815    fn request_layout(
816        &mut self,
817        _id: Option<&GlobalElementId>,
818        _inspector_id: Option<&InspectorElementId>,
819        window: &mut Window,
820        cx: &mut App,
821    ) -> (LayoutId, Self::RequestLayoutState) {
822        (
823            window.request_layout(
824                Style {
825                    display: crate::Display::None,
826                    ..Default::default()
827                },
828                None,
829                cx,
830            ),
831            (),
832        )
833    }
834
835    fn prepaint(
836        &mut self,
837        _id: Option<&GlobalElementId>,
838        _inspector_id: Option<&InspectorElementId>,
839        _bounds: Bounds<Pixels>,
840        _state: &mut Self::RequestLayoutState,
841        _window: &mut Window,
842        _cx: &mut App,
843    ) {
844    }
845
846    fn paint(
847        &mut self,
848        _id: Option<&GlobalElementId>,
849        _inspector_id: Option<&InspectorElementId>,
850        _bounds: Bounds<Pixels>,
851        _request_layout: &mut Self::RequestLayoutState,
852        _prepaint: &mut Self::PrepaintState,
853        _window: &mut Window,
854        _cx: &mut App,
855    ) {
856    }
857}
858
859#[inline(never)]
860fn prepare_element_id(element_id: ElementId, window: &mut Window) -> GlobalElementId {
861    window.element_id_stack.push(element_id);
862    window.element_id_stack.global_id()
863}
864
865#[cfg(any(feature = "inspector", debug_assertions))]
866#[inline(never)]
867fn prepare_inspector_id(
868    source: &'static panic::Location<'static>,
869    window: &mut Window,
870) -> InspectorElementId {
871    let path = InspectorElementPath {
872        global_id: window.element_id_stack.global_id(),
873        source_location: source,
874    };
875    window.build_inspector_element_id(path)
876}
877
878#[cfg(test)]
879mod global_element_id_tests {
880    use super::*;
881    use std::hash::{Hash, Hasher};
882
883    fn path(depth: usize, leaf: u64) -> Vec<ElementId> {
884        let mut ids: Vec<ElementId> = (0..depth as u64)
885            .map(|level| ElementId::NamedInteger("some-container-element".into(), level))
886            .collect();
887        ids.push(ElementId::NamedInteger("leaf".into(), leaf));
888        ids
889    }
890
891    fn fx_hash(value: &impl Hash) -> u64 {
892        let mut hasher = collections::FxHasher::default();
893        value.hash(&mut hasher);
894        hasher.finish()
895    }
896
897    #[test]
898    fn equal_paths_are_equal_and_hash_alike() {
899        let a = GlobalElementId::new(&path(8, 1));
900        let b = GlobalElementId::new(&path(8, 1));
901        let c = GlobalElementId::new(&path(8, 2));
902        let shallower = GlobalElementId::new(&path(7, 1));
903        assert_eq!(a, b);
904        assert_eq!(fx_hash(&a), fx_hash(&b));
905        assert_eq!(a.accesskit_node_id(), b.accesskit_node_id());
906        assert_ne!(a, c);
907        assert_ne!(a, shallower);
908        assert_ne!(fx_hash(&a), fx_hash(&c));
909        assert_eq!(&*a, path(8, 1).as_slice());
910        assert_eq!(a.to_string(), b.to_string());
911        assert_eq!(GlobalElementId::default(), GlobalElementId::new(&[]));
912    }
913
914    /// A window of `items` columns of `depth` nested stateful divs — the
915    /// shape of a list of cards — drawn from scratch on every frame.
916    struct DeepStatefulTree {
917        items: usize,
918        depth: usize,
919    }
920
921    impl crate::Render for DeepStatefulTree {
922        fn render(&mut self, _: &mut Window, _: &mut crate::Context<Self>) -> impl IntoElement {
923            use crate::{InteractiveElement as _, ParentElement as _, Styled as _, div, px};
924            let depth = self.depth;
925            div()
926                .flex()
927                .flex_wrap()
928                .size_full()
929                .children((0..self.items).map(move |item| {
930                    let mut element = div().id(("leaf", item as u64)).size(px(2.));
931                    for level in (0..depth).rev() {
932                        element = div()
933                            .id(("some-container-element", level as u64))
934                            .child(element);
935                    }
936                    element.id(("item", item as u64)).size(px(4.))
937                }))
938        }
939    }
940
941    /// Frame cost of a tree of stateful elements: every one of them builds a
942    /// `GlobalElementId` and looks its state up in two frames' maps.
943    ///
944    /// `cargo test -p gpui --release --lib global_element_id_tests::frame_cost -- --ignored --nocapture`
945    #[crate::test]
946    #[ignore = "prints timings; run by hand"]
947    fn frame_cost(cx: &mut crate::TestAppContext) {
948        use crate::AppContext as _;
949        for (items, depth) in [(500, 4), (500, 12), (2000, 12)] {
950            let window = cx.add_window(move |_, _| DeepStatefulTree { items, depth });
951            let window = crate::AnyWindowHandle::from(window);
952            let frame = |cx: &mut crate::TestAppContext| {
953                cx.update_window(window, |_, window, cx| {
954                    window.refresh();
955                    let started = std::time::Instant::now();
956                    window.draw(cx).clear(cx);
957                    started.elapsed()
958                })
959                .unwrap()
960            };
961            for _ in 0..5 {
962                frame(cx);
963            }
964            let mut samples: Vec<_> = (0..40).map(|_| frame(cx)).collect();
965            samples.sort();
966            let median = samples[samples.len() / 2];
967            let stateful = items * (depth + 2);
968            eprintln!(
969                "{items} items x {depth} deep ({stateful} stateful elements): median frame {:.2} ms, {:.0} ns per stateful element",
970                median.as_secs_f64() * 1e3,
971                median.as_nanos() as f64 / stateful as f64,
972            );
973        }
974    }
975
976    /// `cargo test -p gpui --release --lib global_element_id_tests::hash_cost -- --ignored --nocapture`
977    #[test]
978    #[ignore = "prints timings; run by hand"]
979    fn hash_cost() {
980        let ids = path(11, 7);
981        let id = GlobalElementId::new(&ids);
982        let n = 1_000_000u64;
983        let mut acc = 0u64;
984        let started = std::time::Instant::now();
985        for _ in 0..n {
986            acc ^= fx_hash(&std::hint::black_box(ids.as_slice()));
987        }
988        let walk = started.elapsed();
989        let started = std::time::Instant::now();
990        for _ in 0..n {
991            acc ^= fx_hash(std::hint::black_box(&id));
992        }
993        let cached = started.elapsed();
994        let started = std::time::Instant::now();
995        for _ in 0..n {
996            acc ^= GlobalElementId::new(std::hint::black_box(&ids)).hash.0;
997        }
998        let build = started.elapsed();
999        eprintln!(
1000            "12-deep path: hash by walking ids {:.1} ns, cached {:.1} ns, build (clone + hash once) {:.1} ns [{acc}]",
1001            walk.as_nanos() as f64 / n as f64,
1002            cached.as_nanos() as f64 / n as f64,
1003            build.as_nanos() as f64 / n as f64,
1004        );
1005    }
1006}