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