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