Skip to main content

gpui/
element.rs

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