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