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 + IntoElement {
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(self)
143 }
144}
145
146pub trait IntoElement: Sized {
148 type Element: Element;
151
152 fn into_element(self) -> Self::Element;
154
155 fn into_any_element(self) -> AnyElement {
157 self.into_element().into_any()
158 }
159}
160
161impl<T: IntoElement> FluentBuilder for T {}
162
163pub trait Render: 'static + Sized {
166 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
176pub trait RenderOnce: 'static {
182 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
186}
187
188pub trait ParentElement {
191 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>);
193
194 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 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#[derive(Clone, Debug)]
221pub struct GlobalElementId {
222 pub(crate) ids: Arc<[ElementId]>,
223 pub(crate) hash: u64,
224}
225
226pub(crate) const EMPTY_PATH_HASH: u64 = 0;
230
231pub(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 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
318pub struct Drawable<E: Element> {
320 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
355impl<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 crate::fast::a11y::finish_synthetic_children(builder);
510 }
511 window.a11y.nodes.pop();
512 }
513
514 if global_id.is_some() {
515 window.element_id_stack.pop();
516 }
517
518 self.phase = ElementDrawPhase::Prepaint {
519 node_id,
520 global_id,
521 inspector_id,
522 bounds,
523 request_layout,
524 prepaint,
525 };
526 }
527 _ => panic!("must call request_layout before prepaint"),
528 }
529 }
530
531 pub(crate) fn paint(
532 &mut self,
533 window: &mut Window,
534 cx: &mut App,
535 ) -> (E::RequestLayoutState, E::PrepaintState) {
536 match mem::take(&mut self.phase) {
537 ElementDrawPhase::Prepaint {
538 node_id,
539 global_id,
540 inspector_id,
541 bounds,
542 mut request_layout,
543 mut prepaint,
544 ..
545 } => {
546 if let Some(element_id) = self.element.id() {
547 window.element_id_stack.push(element_id);
548 debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);
549 }
550
551 window.next_frame.dispatch_tree.set_active_node(node_id);
552 self.element.paint(
553 global_id.as_ref(),
554 inspector_id.as_ref(),
555 bounds,
556 &mut request_layout,
557 &mut prepaint,
558 window,
559 cx,
560 );
561
562 if global_id.is_some() {
563 window.element_id_stack.pop();
564 }
565
566 self.phase = ElementDrawPhase::Painted;
567 (request_layout, prepaint)
568 }
569 _ => panic!("must call prepaint before paint"),
570 }
571 }
572
573 pub(crate) fn layout_as_root(
574 &mut self,
575 available_space: Size<AvailableSpace>,
576 window: &mut Window,
577 cx: &mut App,
578 ) -> Size<Pixels> {
579 if matches!(&self.phase, ElementDrawPhase::Start) {
580 self.request_layout(window, cx);
581 }
582
583 let layout_id = match mem::take(&mut self.phase) {
584 ElementDrawPhase::RequestLayout {
585 layout_id,
586 fast_layout_key,
587 global_id,
588 inspector_id,
589 request_layout,
590 } => {
591 window.compute_layout(layout_id, available_space, cx);
592 self.phase = ElementDrawPhase::LayoutComputed {
593 layout_id,
594 fast_layout_key,
595 global_id,
596 inspector_id,
597 available_space,
598 request_layout,
599 };
600 layout_id
601 }
602 ElementDrawPhase::LayoutComputed {
603 layout_id,
604 fast_layout_key,
605 global_id,
606 inspector_id,
607 available_space: prev_available_space,
608 request_layout,
609 } => {
610 if available_space != prev_available_space {
611 window.compute_layout(layout_id, available_space, cx);
612 }
613 self.phase = ElementDrawPhase::LayoutComputed {
614 layout_id,
615 fast_layout_key,
616 global_id,
617 inspector_id,
618 available_space,
619 request_layout,
620 };
621 layout_id
622 }
623 _ => panic!("cannot measure after painting"),
624 };
625
626 window.layout_bounds(layout_id).size
627 }
628}
629
630impl<E> ElementObject for Drawable<E>
631where
632 E: Element,
633 E::RequestLayoutState: 'static,
634{
635 fn inner_element(&mut self) -> &mut dyn Any {
636 &mut self.element
637 }
638
639 fn fast_element_id(&self) -> Option<ElementId> {
640 self.element.id()
641 }
642
643 #[inline]
644 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
645 Drawable::request_layout(self, window, cx)
646 }
647
648 #[inline]
649 fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
650 Drawable::prepaint(self, window, cx);
651 }
652
653 #[inline]
654 fn paint(&mut self, window: &mut Window, cx: &mut App) {
655 Drawable::paint(self, window, cx);
656 }
657
658 #[inline]
659 fn layout_as_root(
660 &mut self,
661 available_space: Size<AvailableSpace>,
662 window: &mut Window,
663 cx: &mut App,
664 ) -> Size<Pixels> {
665 Drawable::layout_as_root(self, available_space, window, cx)
666 }
667}
668
669pub struct AnyElement(pub(crate) ArenaBox<dyn ElementObject>);
671
672impl AnyElement {
673 pub(crate) fn new<E>(element: E) -> Self
674 where
675 E: 'static + Element,
676 E::RequestLayoutState: Any,
677 {
678 let element = with_element_arena(|arena| arena.alloc(|| Drawable::new(element)))
679 .map(|element| element as &mut dyn ElementObject);
680 AnyElement(element)
681 }
682
683 pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
685 self.0.inner_element().downcast_mut::<T>()
686 }
687
688 pub fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
691 self.0.request_layout(window, cx)
692 }
693
694 pub fn prepaint(&mut self, window: &mut Window, cx: &mut App) -> Option<FocusHandle> {
697 let focus_assigned = window.next_frame.focus.is_some();
698
699 self.0.prepaint(window, cx);
700
701 if !focus_assigned && let Some(focus_id) = window.next_frame.focus {
702 return FocusHandle::for_id(focus_id, &cx.focus_handles);
703 }
704
705 None
706 }
707
708 pub fn paint(&mut self, window: &mut Window, cx: &mut App) {
710 self.0.paint(window, cx);
711 }
712
713 pub fn layout_as_root(
715 &mut self,
716 available_space: Size<AvailableSpace>,
717 window: &mut Window,
718 cx: &mut App,
719 ) -> Size<Pixels> {
720 self.0.layout_as_root(available_space, window, cx)
721 }
722
723 pub fn prepaint_at(
726 &mut self,
727 origin: Point<Pixels>,
728 window: &mut Window,
729 cx: &mut App,
730 ) -> Option<FocusHandle> {
731 window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
732 }
733
734 pub fn prepaint_as_root(
737 &mut self,
738 origin: Point<Pixels>,
739 available_space: Size<AvailableSpace>,
740 window: &mut Window,
741 cx: &mut App,
742 ) -> Option<FocusHandle> {
743 self.layout_as_root(available_space, window, cx);
744 window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
745 }
746}
747
748impl Element for AnyElement {
749 type RequestLayoutState = ();
750 type PrepaintState = ();
751
752 fn id(&self) -> Option<ElementId> {
753 None
754 }
755
756 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
757 None
758 }
759
760 fn request_layout(
761 &mut self,
762 _: Option<&GlobalElementId>,
763 _inspector_id: Option<&InspectorElementId>,
764 window: &mut Window,
765 cx: &mut App,
766 ) -> (LayoutId, Self::RequestLayoutState) {
767 let layout_id = self.request_layout(window, cx);
768 (layout_id, ())
769 }
770
771 fn prepaint(
772 &mut self,
773 _: Option<&GlobalElementId>,
774 _inspector_id: Option<&InspectorElementId>,
775 _: Bounds<Pixels>,
776 _: &mut Self::RequestLayoutState,
777 window: &mut Window,
778 cx: &mut App,
779 ) {
780 self.prepaint(window, cx);
781 }
782
783 fn paint(
784 &mut self,
785 _: Option<&GlobalElementId>,
786 _inspector_id: Option<&InspectorElementId>,
787 _: Bounds<Pixels>,
788 _: &mut Self::RequestLayoutState,
789 _: &mut Self::PrepaintState,
790 window: &mut Window,
791 cx: &mut App,
792 ) {
793 self.paint(window, cx);
794 }
795}
796
797impl IntoElement for AnyElement {
798 type Element = Self;
799
800 fn into_element(self) -> Self::Element {
801 self
802 }
803
804 fn into_any_element(self) -> AnyElement {
805 self
806 }
807}
808
809pub struct Empty;
811
812impl IntoElement for Empty {
813 type Element = Self;
814
815 fn into_element(self) -> Self::Element {
816 self
817 }
818}
819
820impl Element for Empty {
821 type RequestLayoutState = ();
822 type PrepaintState = ();
823
824 fn id(&self) -> Option<ElementId> {
825 None
826 }
827
828 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
829 None
830 }
831
832 fn request_layout(
833 &mut self,
834 _id: Option<&GlobalElementId>,
835 _inspector_id: Option<&InspectorElementId>,
836 window: &mut Window,
837 cx: &mut App,
838 ) -> (LayoutId, Self::RequestLayoutState) {
839 (
840 window.request_layout(
841 Style {
842 display: crate::Display::None,
843 ..Default::default()
844 },
845 None,
846 cx,
847 ),
848 (),
849 )
850 }
851
852 fn prepaint(
853 &mut self,
854 _id: Option<&GlobalElementId>,
855 _inspector_id: Option<&InspectorElementId>,
856 _bounds: Bounds<Pixels>,
857 _state: &mut Self::RequestLayoutState,
858 _window: &mut Window,
859 _cx: &mut App,
860 ) {
861 }
862
863 fn paint(
864 &mut self,
865 _id: Option<&GlobalElementId>,
866 _inspector_id: Option<&InspectorElementId>,
867 _bounds: Bounds<Pixels>,
868 _request_layout: &mut Self::RequestLayoutState,
869 _prepaint: &mut Self::PrepaintState,
870 _window: &mut Window,
871 _cx: &mut App,
872 ) {
873 }
874}
875
876#[inline(never)]
877fn prepare_element_id(element_id: ElementId, window: &mut Window) -> GlobalElementId {
878 window.element_id_stack.push(element_id);
879 crate::fast::global_id::current(window)
880}
881
882#[cfg(any(feature = "inspector", debug_assertions))]
883#[inline(never)]
884fn prepare_inspector_id(
885 source: &'static panic::Location<'static>,
886 window: &mut Window,
887) -> InspectorElementId {
888 let path = InspectorElementPath {
889 global_id: window.element_id_stack.global_id(),
890 source_location: source,
891 };
892 window.build_inspector_element_id(path)
893}
894
895#[cfg(test)]
896mod global_element_id_tests {
897 use super::*;
898 use std::hash::{Hash, Hasher};
899
900 fn path(depth: usize, leaf: u64) -> Vec<ElementId> {
901 let mut ids: Vec<ElementId> = (0..depth as u64)
902 .map(|level| ElementId::NamedInteger("some-container-element".into(), level))
903 .collect();
904 ids.push(ElementId::NamedInteger("leaf".into(), leaf));
905 ids
906 }
907
908 fn fx_hash(value: &impl Hash) -> u64 {
909 let mut hasher = collections::FxHasher::default();
910 value.hash(&mut hasher);
911 hasher.finish()
912 }
913
914 #[test]
915 fn equal_paths_are_equal_and_hash_alike() {
916 let a = GlobalElementId::new(&path(8, 1));
917 let b = GlobalElementId::new(&path(8, 1));
918 let c = GlobalElementId::new(&path(8, 2));
919 let shallower = GlobalElementId::new(&path(7, 1));
920 assert_eq!(a, b);
921 assert_eq!(fx_hash(&a), fx_hash(&b));
922 assert_eq!(a.accesskit_node_id(), b.accesskit_node_id());
923 assert_ne!(a, c);
924 assert_ne!(a, shallower);
925 assert_ne!(fx_hash(&a), fx_hash(&c));
926 assert_eq!(&*a, path(8, 1).as_slice());
927 assert_eq!(a.to_string(), b.to_string());
928 assert_eq!(GlobalElementId::default(), GlobalElementId::new(&[]));
929 }
930
931 struct DeepStatefulTree {
934 items: usize,
935 depth: usize,
936 }
937
938 impl crate::Render for DeepStatefulTree {
939 fn render(&mut self, _: &mut Window, _: &mut crate::Context<Self>) -> impl IntoElement {
940 use crate::{InteractiveElement as _, ParentElement as _, Styled as _, div, px};
941 let depth = self.depth;
942 div()
943 .flex()
944 .flex_wrap()
945 .size_full()
946 .children((0..self.items).map(move |item| {
947 let mut element = div().id(("leaf", item as u64)).size(px(2.));
948 for level in (0..depth).rev() {
949 element = div()
950 .id(("some-container-element", level as u64))
951 .child(element);
952 }
953 element.id(("item", item as u64)).size(px(4.))
954 }))
955 }
956 }
957
958 #[crate::test]
963 #[ignore = "prints timings; run by hand"]
964 fn frame_cost(cx: &mut crate::TestAppContext) {
965 use crate::AppContext as _;
966 for (items, depth) in [(500, 4), (500, 12), (2000, 12)] {
967 let window = cx.add_window(move |_, _| DeepStatefulTree { items, depth });
968 let window = crate::AnyWindowHandle::from(window);
969 let frame = |cx: &mut crate::TestAppContext| {
970 cx.update_window(window, |_, window, cx| {
971 window.refresh();
972 let started = std::time::Instant::now();
973 window.draw(cx).clear(cx);
974 started.elapsed()
975 })
976 .unwrap()
977 };
978 for _ in 0..5 {
979 frame(cx);
980 }
981 let mut samples: Vec<_> = (0..40).map(|_| frame(cx)).collect();
982 samples.sort();
983 let median = samples[samples.len() / 2];
984 let stateful = items * (depth + 2);
985 eprintln!(
986 "{items} items x {depth} deep ({stateful} stateful elements): median frame {:.2} ms, {:.0} ns per stateful element",
987 median.as_secs_f64() * 1e3,
988 median.as_nanos() as f64 / stateful as f64,
989 );
990 }
991 }
992
993 #[test]
995 #[ignore = "prints timings; run by hand"]
996 fn hash_cost() {
997 let ids = path(11, 7);
998 let id = GlobalElementId::new(&ids);
999 let n = 1_000_000u64;
1000 let mut acc = 0u64;
1001 let started = std::time::Instant::now();
1002 for _ in 0..n {
1003 acc ^= fx_hash(&std::hint::black_box(ids.as_slice()));
1004 }
1005 let walk = started.elapsed();
1006 let started = std::time::Instant::now();
1007 for _ in 0..n {
1008 acc ^= fx_hash(std::hint::black_box(&id));
1009 }
1010 let cached = started.elapsed();
1011 let started = std::time::Instant::now();
1012 for _ in 0..n {
1013 acc ^= GlobalElementId::new(std::hint::black_box(&ids)).hash;
1014 }
1015 let build = started.elapsed();
1016 eprintln!(
1017 "12-deep path: hash by walking ids {:.1} ns, cached {:.1} ns, build (clone + hash once) {:.1} ns [{acc}]",
1018 walk.as_nanos() as f64 / n as f64,
1019 cached.as_nanos() as f64 / n as f64,
1020 build.as_nanos() as f64 / n as f64,
1021 );
1022 }
1023}