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: u64,
231}
232
233/// The hash of an empty id path; every path hash is folded from it with
234/// [`extend_path_hash`], one id at a time, so the window can keep the hash
235/// of each prefix of its id stack and never re-hash a path.
236pub(crate) const EMPTY_PATH_HASH: u64 = 0;
237
238/// The hash of the path `prefix` + `id`, given the hash of `prefix`.
239pub(crate) fn extend_path_hash(prefix: u64, id: &ElementId) -> u64 {
240    use std::hash::{Hash, Hasher};
241    let mut hasher = collections::FxHasher::with_seed(prefix as usize);
242    id.hash(&mut hasher);
243    hasher.finish()
244}
245
246impl GlobalElementId {
247    pub(crate) fn new(ids: &[ElementId]) -> Self {
248        let hash = ids.iter().fold(EMPTY_PATH_HASH, extend_path_hash);
249        Self::with_hash(ids, hash)
250    }
251
252    /// `ids` with its hash already known, as the window's id stack keeps it.
253    pub(crate) fn with_hash(ids: &[ElementId], hash: u64) -> Self {
254        debug_assert_eq!(hash, ids.iter().fold(EMPTY_PATH_HASH, extend_path_hash));
255        Self {
256            ids: Arc::from(ids),
257            hash,
258        }
259    }
260
261    pub(crate) fn accesskit_node_id(&self) -> accesskit::NodeId {
262        accesskit::NodeId(self.hash)
263    }
264}
265
266impl Default for GlobalElementId {
267    fn default() -> Self {
268        Self::new(&[])
269    }
270}
271
272impl std::ops::Deref for GlobalElementId {
273    type Target = [ElementId];
274
275    fn deref(&self) -> &Self::Target {
276        &self.ids
277    }
278}
279
280impl PartialEq for GlobalElementId {
281    fn eq(&self, other: &Self) -> bool {
282        self.hash == other.hash && (Arc::ptr_eq(&self.ids, &other.ids) || self.ids == other.ids)
283    }
284}
285
286impl Eq for GlobalElementId {}
287
288impl std::hash::Hash for GlobalElementId {
289    fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
290        state.write_u64(self.hash);
291    }
292}
293
294impl Display for GlobalElementId {
295    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
296        for (i, element_id) in self.ids.iter().enumerate() {
297            if i > 0 {
298                write!(f, ".")?;
299            }
300            write!(f, "{}", element_id)?;
301        }
302        Ok(())
303    }
304}
305
306trait ElementObject {
307    fn inner_element(&mut self) -> &mut dyn Any;
308
309    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId;
310
311    fn prepaint(&mut self, window: &mut Window, cx: &mut App);
312
313    fn paint(&mut self, window: &mut Window, cx: &mut App);
314
315    fn layout_as_root(
316        &mut self,
317        available_space: Size<AvailableSpace>,
318        window: &mut Window,
319        cx: &mut App,
320    ) -> Size<Pixels>;
321}
322
323/// A wrapper around an implementer of [`Element`] that allows it to be drawn in a window.
324pub struct Drawable<E: Element> {
325    /// The drawn element.
326    pub element: E,
327    phase: ElementDrawPhase<E::RequestLayoutState, E::PrepaintState>,
328}
329
330#[derive(Default)]
331enum ElementDrawPhase<RequestLayoutState, PrepaintState> {
332    #[default]
333    Start,
334    RequestLayout {
335        layout_id: LayoutId,
336        global_id: Option<GlobalElementId>,
337        inspector_id: Option<InspectorElementId>,
338        request_layout: RequestLayoutState,
339    },
340    LayoutComputed {
341        layout_id: LayoutId,
342        global_id: Option<GlobalElementId>,
343        inspector_id: Option<InspectorElementId>,
344        available_space: Size<AvailableSpace>,
345        request_layout: RequestLayoutState,
346    },
347    Prepaint {
348        node_id: DispatchNodeId,
349        global_id: Option<GlobalElementId>,
350        inspector_id: Option<InspectorElementId>,
351        bounds: Bounds<Pixels>,
352        request_layout: RequestLayoutState,
353        prepaint: PrepaintState,
354    },
355    Painted,
356}
357
358/// A wrapper around an implementer of [`Element`] that allows it to be drawn in a window.
359impl<E: Element> Drawable<E> {
360    pub(crate) fn new(element: E) -> Self {
361        Drawable {
362            element,
363            phase: ElementDrawPhase::Start,
364        }
365    }
366
367    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
368        match mem::take(&mut self.phase) {
369            ElementDrawPhase::Start => {
370                let global_id = self
371                    .element
372                    .id()
373                    .map(|element_id| prepare_element_id(element_id, window));
374
375                let inspector_id;
376                #[cfg(any(feature = "inspector", debug_assertions))]
377                {
378                    inspector_id = if window.inspector_enabled() {
379                        self.element
380                            .source_location()
381                            .map(|source| prepare_inspector_id(source, window))
382                    } else {
383                        None
384                    };
385                }
386                #[cfg(not(any(feature = "inspector", debug_assertions)))]
387                {
388                    inspector_id = None;
389                }
390
391                let (layout_id, request_layout) = self.element.request_layout(
392                    global_id.as_ref(),
393                    inspector_id.as_ref(),
394                    window,
395                    cx,
396                );
397
398                if global_id.is_some() {
399                    window.element_id_stack.pop();
400                }
401
402                self.phase = ElementDrawPhase::RequestLayout {
403                    layout_id,
404                    global_id,
405                    inspector_id,
406                    request_layout,
407                };
408                layout_id
409            }
410            _ => panic!("must call request_layout only once"),
411        }
412    }
413
414    pub(crate) fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
415        match mem::take(&mut self.phase) {
416            ElementDrawPhase::RequestLayout {
417                layout_id,
418                global_id,
419                inspector_id,
420                mut request_layout,
421            }
422            | ElementDrawPhase::LayoutComputed {
423                layout_id,
424                global_id,
425                inspector_id,
426                mut request_layout,
427                ..
428            } => {
429                if let Some(element_id) = self.element.id() {
430                    window.element_id_stack.push(element_id);
431                    debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);
432                }
433
434                let bounds = window.layout_bounds(layout_id);
435                let mut pushed_a11y_node = false;
436                if window.a11y.is_active() {
437                    if let Some(global_id) = global_id.as_ref() {
438                        if let Some(role) = self.element.a11y_role() {
439                            let node_id = global_id.accesskit_node_id();
440                            let mut node = accesskit::Node::new(role);
441                            let scale = window.scale_factor();
442                            node.set_bounds(accesskit::Rect {
443                                x0: (bounds.origin.x.0 * scale) as f64,
444                                y0: (bounds.origin.y.0 * scale) as f64,
445                                x1: ((bounds.origin.x.0 + bounds.size.width.0) * scale) as f64,
446                                y1: ((bounds.origin.y.0 + bounds.size.height.0) * scale) as f64,
447                            });
448                            self.element.write_a11y_info(&mut node);
449                            window.a11y.node_bounds.insert(node_id, bounds);
450                            pushed_a11y_node = window.a11y.nodes.push(node_id, node);
451                            #[cfg(debug_assertions)]
452                            if pushed_a11y_node {
453                                let view = window
454                                    .a11y
455                                    .view_type_names
456                                    .get(&window.current_view())
457                                    .copied();
458                                let source_location = self.element.source_location();
459                                window.a11y.nodes.record_node_info(
460                                    node_id,
461                                    crate::window::a11y::debug::NodeDebugInfo {
462                                        synthetic: false,
463                                        view,
464                                        element_id: global_id.last().map(|id| format!("{id:?}")),
465                                        source_location,
466                                    },
467                                );
468                            }
469                        }
470                    }
471                }
472
473                let node_id = window.next_frame.dispatch_tree.push_node();
474                let mut prepaint = self.element.prepaint(
475                    global_id.as_ref(),
476                    inspector_id.as_ref(),
477                    bounds,
478                    &mut request_layout,
479                    window,
480                    cx,
481                );
482                window.next_frame.dispatch_tree.pop_node();
483
484                if pushed_a11y_node {
485                    if let Some(global_id) = global_id.as_ref() {
486                        #[cfg(debug_assertions)]
487                        let creator = crate::window::a11y::debug::NodeCreator {
488                            view: window
489                                .a11y
490                                .view_type_names
491                                .get(&window.current_view())
492                                .copied(),
493                            element_id: global_id.last().map(|id| format!("{id:?}")),
494                            source_location: self.element.source_location(),
495                        };
496                        let mut builder = A11ySubtreeBuilder::new(
497                            global_id.accesskit_node_id(),
498                            &mut window.a11y.nodes,
499                        );
500                        #[cfg(debug_assertions)]
501                        {
502                            builder = builder.with_creator(creator);
503                        }
504                        self.element
505                            .a11y_synthetic_children(&mut prepaint, &mut builder);
506                    }
507                    window.a11y.nodes.pop();
508                }
509
510                if global_id.is_some() {
511                    window.element_id_stack.pop();
512                }
513
514                self.phase = ElementDrawPhase::Prepaint {
515                    node_id,
516                    global_id,
517                    inspector_id,
518                    bounds,
519                    request_layout,
520                    prepaint,
521                };
522            }
523            _ => panic!("must call request_layout before prepaint"),
524        }
525    }
526
527    pub(crate) fn paint(
528        &mut self,
529        window: &mut Window,
530        cx: &mut App,
531    ) -> (E::RequestLayoutState, E::PrepaintState) {
532        match mem::take(&mut self.phase) {
533            ElementDrawPhase::Prepaint {
534                node_id,
535                global_id,
536                inspector_id,
537                bounds,
538                mut request_layout,
539                mut prepaint,
540                ..
541            } => {
542                if let Some(element_id) = self.element.id() {
543                    window.element_id_stack.push(element_id);
544                    debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);
545                }
546
547                window.next_frame.dispatch_tree.set_active_node(node_id);
548                self.element.paint(
549                    global_id.as_ref(),
550                    inspector_id.as_ref(),
551                    bounds,
552                    &mut request_layout,
553                    &mut prepaint,
554                    window,
555                    cx,
556                );
557
558                if global_id.is_some() {
559                    window.element_id_stack.pop();
560                }
561
562                self.phase = ElementDrawPhase::Painted;
563                (request_layout, prepaint)
564            }
565            _ => panic!("must call prepaint before paint"),
566        }
567    }
568
569    pub(crate) fn layout_as_root(
570        &mut self,
571        available_space: Size<AvailableSpace>,
572        window: &mut Window,
573        cx: &mut App,
574    ) -> Size<Pixels> {
575        if matches!(&self.phase, ElementDrawPhase::Start) {
576            self.request_layout(window, cx);
577        }
578
579        let layout_id = match mem::take(&mut self.phase) {
580            ElementDrawPhase::RequestLayout {
581                layout_id,
582                global_id,
583                inspector_id,
584                request_layout,
585            } => {
586                window.compute_layout(layout_id, available_space, cx);
587                self.phase = ElementDrawPhase::LayoutComputed {
588                    layout_id,
589                    global_id,
590                    inspector_id,
591                    available_space,
592                    request_layout,
593                };
594                layout_id
595            }
596            ElementDrawPhase::LayoutComputed {
597                layout_id,
598                global_id,
599                inspector_id,
600                available_space: prev_available_space,
601                request_layout,
602            } => {
603                if available_space != prev_available_space {
604                    window.compute_layout(layout_id, available_space, cx);
605                }
606                self.phase = ElementDrawPhase::LayoutComputed {
607                    layout_id,
608                    global_id,
609                    inspector_id,
610                    available_space,
611                    request_layout,
612                };
613                layout_id
614            }
615            _ => panic!("cannot measure after painting"),
616        };
617
618        window.layout_bounds(layout_id).size
619    }
620}
621
622impl<E> ElementObject for Drawable<E>
623where
624    E: Element,
625    E::RequestLayoutState: 'static,
626{
627    fn inner_element(&mut self) -> &mut dyn Any {
628        &mut self.element
629    }
630
631    #[inline]
632    fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
633        Drawable::request_layout(self, window, cx)
634    }
635
636    #[inline]
637    fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
638        Drawable::prepaint(self, window, cx);
639    }
640
641    #[inline]
642    fn paint(&mut self, window: &mut Window, cx: &mut App) {
643        Drawable::paint(self, window, cx);
644    }
645
646    #[inline]
647    fn layout_as_root(
648        &mut self,
649        available_space: Size<AvailableSpace>,
650        window: &mut Window,
651        cx: &mut App,
652    ) -> Size<Pixels> {
653        Drawable::layout_as_root(self, available_space, window, cx)
654    }
655}
656
657/// A dynamically typed element that can be used to store any element type.
658pub struct AnyElement(ArenaBox<dyn ElementObject>);
659
660impl AnyElement {
661    /// Boxes `element` into an `AnyElement`, erasing its concrete type.
662    ///
663    /// This always allocates and always adds a level of boxing, even when `element` is
664    /// already an [`AnyElement`], which would nest one `AnyElement` inside another. Call
665    /// [`Element::into_any`] instead; it skips the wrapper for `AnyElement` itself.
666    fn new_please_call_into_any_to_avoid_double_box<E>(element: E) -> Self
667    where
668        E: 'static + Element,
669        E::RequestLayoutState: Any,
670    {
671        let element = with_element_arena(|arena| arena.alloc(|| Drawable::new(element)))
672            .map(|element| element as &mut dyn ElementObject);
673        AnyElement(element)
674    }
675
676    /// Attempt to downcast a reference to the boxed element to a specific type.
677    pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
678        self.0.inner_element().downcast_mut::<T>()
679    }
680
681    /// Request the layout ID of the element stored in this `AnyElement`.
682    /// Used for laying out child elements in a parent element.
683    pub fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
684        self.0.request_layout(window, cx)
685    }
686
687    /// Prepares the element to be painted by storing its bounds, giving it a chance to draw hitboxes and
688    /// request autoscroll before the final paint pass is confirmed.
689    pub fn prepaint(&mut self, window: &mut Window, cx: &mut App) -> Option<FocusHandle> {
690        let focus_assigned = window.next_frame.focus.is_some();
691
692        self.0.prepaint(window, cx);
693
694        if !focus_assigned && let Some(focus_id) = window.next_frame.focus {
695            return FocusHandle::for_id(focus_id, &cx.focus_handles);
696        }
697
698        None
699    }
700
701    /// Paints the element stored in this `AnyElement`.
702    pub fn paint(&mut self, window: &mut Window, cx: &mut App) {
703        self.0.paint(window, cx);
704    }
705
706    /// Performs layout for this element within the given available space and returns its size.
707    pub fn layout_as_root(
708        &mut self,
709        available_space: Size<AvailableSpace>,
710        window: &mut Window,
711        cx: &mut App,
712    ) -> Size<Pixels> {
713        self.0.layout_as_root(available_space, window, cx)
714    }
715
716    /// Prepaints this element at the given absolute origin.
717    /// If any element in the subtree beneath this element is focused, its FocusHandle is returned.
718    pub fn prepaint_at(
719        &mut self,
720        origin: Point<Pixels>,
721        window: &mut Window,
722        cx: &mut App,
723    ) -> Option<FocusHandle> {
724        window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
725    }
726
727    /// Performs layout on this element in the available space, then prepaints it at the given absolute origin.
728    /// If any element in the subtree beneath this element is focused, its FocusHandle is returned.
729    pub fn prepaint_as_root(
730        &mut self,
731        origin: Point<Pixels>,
732        available_space: Size<AvailableSpace>,
733        window: &mut Window,
734        cx: &mut App,
735    ) -> Option<FocusHandle> {
736        self.layout_as_root(available_space, window, cx);
737        window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
738    }
739}
740
741impl Element for AnyElement {
742    type RequestLayoutState = ();
743    type PrepaintState = ();
744
745    fn id(&self) -> Option<ElementId> {
746        None
747    }
748
749    fn source_location(&self) -> Option<&'static panic::Location<'static>> {
750        None
751    }
752
753    fn request_layout(
754        &mut self,
755        _: Option<&GlobalElementId>,
756        _inspector_id: Option<&InspectorElementId>,
757        window: &mut Window,
758        cx: &mut App,
759    ) -> (LayoutId, Self::RequestLayoutState) {
760        let layout_id = self.request_layout(window, cx);
761        (layout_id, ())
762    }
763
764    fn prepaint(
765        &mut self,
766        _: Option<&GlobalElementId>,
767        _inspector_id: Option<&InspectorElementId>,
768        _: Bounds<Pixels>,
769        _: &mut Self::RequestLayoutState,
770        window: &mut Window,
771        cx: &mut App,
772    ) {
773        self.prepaint(window, cx);
774    }
775
776    fn paint(
777        &mut self,
778        _: Option<&GlobalElementId>,
779        _inspector_id: Option<&InspectorElementId>,
780        _: Bounds<Pixels>,
781        _: &mut Self::RequestLayoutState,
782        _: &mut Self::PrepaintState,
783        window: &mut Window,
784        cx: &mut App,
785    ) {
786        self.paint(window, cx);
787    }
788
789    fn into_any(self) -> AnyElement {
790        self
791    }
792}
793
794/// The empty element, which renders nothing.
795pub struct Empty;
796
797impl Element for Empty {
798    type RequestLayoutState = ();
799    type PrepaintState = ();
800
801    fn id(&self) -> Option<ElementId> {
802        None
803    }
804
805    fn source_location(&self) -> Option<&'static panic::Location<'static>> {
806        None
807    }
808
809    fn request_layout(
810        &mut self,
811        _id: Option<&GlobalElementId>,
812        _inspector_id: Option<&InspectorElementId>,
813        window: &mut Window,
814        cx: &mut App,
815    ) -> (LayoutId, Self::RequestLayoutState) {
816        (
817            window.request_layout(
818                Style {
819                    display: crate::Display::None,
820                    ..Default::default()
821                },
822                None,
823                cx,
824            ),
825            (),
826        )
827    }
828
829    fn prepaint(
830        &mut self,
831        _id: Option<&GlobalElementId>,
832        _inspector_id: Option<&InspectorElementId>,
833        _bounds: Bounds<Pixels>,
834        _state: &mut Self::RequestLayoutState,
835        _window: &mut Window,
836        _cx: &mut App,
837    ) {
838    }
839
840    fn paint(
841        &mut self,
842        _id: Option<&GlobalElementId>,
843        _inspector_id: Option<&InspectorElementId>,
844        _bounds: Bounds<Pixels>,
845        _request_layout: &mut Self::RequestLayoutState,
846        _prepaint: &mut Self::PrepaintState,
847        _window: &mut Window,
848        _cx: &mut App,
849    ) {
850    }
851}
852
853#[inline(never)]
854fn prepare_element_id(element_id: ElementId, window: &mut Window) -> GlobalElementId {
855    window.element_id_stack.push(element_id);
856    window.element_id_stack.global_id()
857}
858
859#[cfg(any(feature = "inspector", debug_assertions))]
860#[inline(never)]
861fn prepare_inspector_id(
862    source: &'static panic::Location<'static>,
863    window: &mut Window,
864) -> InspectorElementId {
865    let path = InspectorElementPath {
866        global_id: window.element_id_stack.global_id(),
867        source_location: source,
868    };
869    window.build_inspector_element_id(path)
870}
871
872#[cfg(test)]
873mod global_element_id_tests {
874    use super::*;
875    use std::hash::{Hash, Hasher};
876
877    fn path(depth: usize, leaf: u64) -> Vec<ElementId> {
878        let mut ids: Vec<ElementId> = (0..depth as u64)
879            .map(|level| ElementId::NamedInteger("some-container-element".into(), level))
880            .collect();
881        ids.push(ElementId::NamedInteger("leaf".into(), leaf));
882        ids
883    }
884
885    fn fx_hash(value: &impl Hash) -> u64 {
886        let mut hasher = collections::FxHasher::default();
887        value.hash(&mut hasher);
888        hasher.finish()
889    }
890
891    #[test]
892    fn equal_paths_are_equal_and_hash_alike() {
893        let a = GlobalElementId::new(&path(8, 1));
894        let b = GlobalElementId::new(&path(8, 1));
895        let c = GlobalElementId::new(&path(8, 2));
896        let shallower = GlobalElementId::new(&path(7, 1));
897        assert_eq!(a, b);
898        assert_eq!(fx_hash(&a), fx_hash(&b));
899        assert_eq!(a.accesskit_node_id(), b.accesskit_node_id());
900        assert_ne!(a, c);
901        assert_ne!(a, shallower);
902        assert_ne!(fx_hash(&a), fx_hash(&c));
903        assert_eq!(&*a, path(8, 1).as_slice());
904        assert_eq!(a.to_string(), b.to_string());
905        assert_eq!(GlobalElementId::default(), GlobalElementId::new(&[]));
906    }
907
908    /// A window of `items` columns of `depth` nested stateful divs — the
909    /// shape of a list of cards — drawn from scratch on every frame.
910    struct DeepStatefulTree {
911        items: usize,
912        depth: usize,
913    }
914
915    impl crate::Render for DeepStatefulTree {
916        fn render(&mut self, _: &mut Window, _: &mut crate::Context<Self>) -> impl IntoElement {
917            use crate::{InteractiveElement as _, ParentElement as _, Styled as _, div, px};
918            let depth = self.depth;
919            div()
920                .flex()
921                .flex_wrap()
922                .size_full()
923                .children((0..self.items).map(move |item| {
924                    let mut element = div().id(("leaf", item as u64)).size(px(2.));
925                    for level in (0..depth).rev() {
926                        element = div()
927                            .id(("some-container-element", level as u64))
928                            .child(element);
929                    }
930                    element.id(("item", item as u64)).size(px(4.))
931                }))
932        }
933    }
934
935    /// Frame cost of a tree of stateful elements: every one of them builds a
936    /// `GlobalElementId` and looks its state up in two frames' maps.
937    ///
938    /// `cargo test -p gpui --release --lib global_element_id_tests::frame_cost -- --ignored --nocapture`
939    #[crate::test]
940    #[ignore = "prints timings; run by hand"]
941    fn frame_cost(cx: &mut crate::TestAppContext) {
942        use crate::AppContext as _;
943        for (items, depth) in [(500, 4), (500, 12), (2000, 12)] {
944            let window = cx.add_window(move |_, _| DeepStatefulTree { items, depth });
945            let window = crate::AnyWindowHandle::from(window);
946            let frame = |cx: &mut crate::TestAppContext| {
947                cx.update_window(window, |_, window, cx| {
948                    window.refresh();
949                    let started = std::time::Instant::now();
950                    window.draw(cx).clear(cx);
951                    started.elapsed()
952                })
953                .unwrap()
954            };
955            for _ in 0..5 {
956                frame(cx);
957            }
958            let mut samples: Vec<_> = (0..40).map(|_| frame(cx)).collect();
959            samples.sort();
960            let median = samples[samples.len() / 2];
961            let stateful = items * (depth + 2);
962            eprintln!(
963                "{items} items x {depth} deep ({stateful} stateful elements): median frame {:.2} ms, {:.0} ns per stateful element",
964                median.as_secs_f64() * 1e3,
965                median.as_nanos() as f64 / stateful as f64,
966            );
967        }
968    }
969
970    /// `cargo test -p gpui --release --lib global_element_id_tests::hash_cost -- --ignored --nocapture`
971    #[test]
972    #[ignore = "prints timings; run by hand"]
973    fn hash_cost() {
974        let ids = path(11, 7);
975        let id = GlobalElementId::new(&ids);
976        let n = 1_000_000u64;
977        let mut acc = 0u64;
978        let started = std::time::Instant::now();
979        for _ in 0..n {
980            acc ^= fx_hash(&std::hint::black_box(ids.as_slice()));
981        }
982        let walk = started.elapsed();
983        let started = std::time::Instant::now();
984        for _ in 0..n {
985            acc ^= fx_hash(std::hint::black_box(&id));
986        }
987        let cached = started.elapsed();
988        let started = std::time::Instant::now();
989        for _ in 0..n {
990            acc ^= GlobalElementId::new(std::hint::black_box(&ids)).hash;
991        }
992        let build = started.elapsed();
993        eprintln!(
994            "12-deep path: hash by walking ids {:.1} ns, cached {:.1} ns, build (clone + hash once) {:.1} ns [{acc}]",
995            walk.as_nanos() as f64 / n as f64,
996            cached.as_nanos() as f64 / n as f64,
997            build.as_nanos() as f64 / n as f64,
998        );
999    }
1000}