1#[cfg(any(feature = "inspector", debug_assertions))]
35use crate::InspectorElementPath;
36use crate::{
37 A11ySubtreeBuilder, App, ArenaBox, AvailableSpace, Bounds, Context, DispatchNodeId, ElementId,
38 FocusHandle, InspectorElementId, LayoutId, Pixels, Point, Size, Style, Window,
39 util::FluentBuilder, window::with_element_arena,
40};
41use std::{
42 any::Any,
43 fmt::{self, Debug, Display},
44 mem, panic,
45 sync::Arc,
46};
47
48pub trait Element: 'static + Sized {
53 type RequestLayoutState: 'static;
56
57 type PrepaintState: 'static;
60
61 fn id(&self) -> Option<ElementId>;
67
68 fn source_location(&self) -> Option<&'static panic::Location<'static>>;
71
72 fn request_layout(
75 &mut self,
76 id: Option<&GlobalElementId>,
77 inspector_id: Option<&InspectorElementId>,
78 window: &mut Window,
79 cx: &mut App,
80 ) -> (LayoutId, Self::RequestLayoutState);
81
82 fn prepaint(
85 &mut self,
86 id: Option<&GlobalElementId>,
87 inspector_id: Option<&InspectorElementId>,
88 bounds: Bounds<Pixels>,
89 request_layout: &mut Self::RequestLayoutState,
90 window: &mut Window,
91 cx: &mut App,
92 ) -> Self::PrepaintState;
93
94 fn paint(
97 &mut self,
98 id: Option<&GlobalElementId>,
99 inspector_id: Option<&InspectorElementId>,
100 bounds: Bounds<Pixels>,
101 request_layout: &mut Self::RequestLayoutState,
102 prepaint: &mut Self::PrepaintState,
103 window: &mut Window,
104 cx: &mut App,
105 );
106
107 fn a11y_role(&self) -> Option<accesskit::Role> {
114 None
115 }
116
117 fn write_a11y_info(&self, _node: &mut accesskit::Node) {}
122
123 fn a11y_synthetic_children(
133 &mut self,
134 _prepaint: &mut Self::PrepaintState,
135 _builder: &mut A11ySubtreeBuilder,
136 ) {
137 }
138
139 fn into_any(self) -> AnyElement {
141 AnyElement::new_please_call_into_any_to_avoid_double_box(self)
142 }
143}
144
145impl<T: Element> IntoElement for T {
146 type Element = Self;
147
148 fn into_element(self) -> Self::Element {
149 self
150 }
151}
152
153pub trait IntoElement: Sized {
155 type Element: Element;
158
159 fn into_element(self) -> Self::Element;
161
162 fn into_any_element(self) -> AnyElement {
164 self.into_element().into_any()
165 }
166}
167
168impl<T: IntoElement> FluentBuilder for T {}
169
170pub trait Render: 'static + Sized {
173 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement;
175}
176
177impl Render for Empty {
178 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
179 Empty
180 }
181}
182
183pub trait RenderOnce: 'static {
189 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
193}
194
195pub trait ParentElement {
198 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>);
200
201 fn child(mut self, child: impl IntoElement) -> Self
203 where
204 Self: Sized,
205 {
206 self.extend(std::iter::once(child.into_any_element()));
207 self
208 }
209
210 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self
212 where
213 Self: Sized,
214 {
215 self.extend(children.into_iter().map(|child| child.into_any_element()));
216 self
217 }
218}
219
220#[derive(Clone, Debug)]
228pub struct GlobalElementId {
229 ids: Arc<[ElementId]>,
230 hash: PathHash,
231}
232
233#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
237pub(crate) struct PathHash(u64);
238
239impl PathHash {
240 pub(crate) const EMPTY: Self = Self(0);
242
243 pub(crate) fn extend(self, id: &ElementId) -> Self {
245 use std::hash::{Hash, Hasher};
246 let mut hasher = collections::FxHasher::with_seed(self.0 as usize);
247 id.hash(&mut hasher);
248 Self(hasher.finish())
249 }
250}
251
252impl GlobalElementId {
253 pub(crate) fn new(ids: &[ElementId]) -> Self {
254 let hash = ids.iter().fold(PathHash::EMPTY, PathHash::extend);
255 Self::with_hash(ids, hash)
256 }
257
258 pub(crate) fn with_hash(ids: &[ElementId], hash: PathHash) -> Self {
260 debug_assert_eq!(hash, ids.iter().fold(PathHash::EMPTY, PathHash::extend));
261 Self {
262 ids: Arc::from(ids),
263 hash,
264 }
265 }
266
267 pub(crate) fn accesskit_node_id(&self) -> accesskit::NodeId {
268 accesskit::NodeId(self.hash.0)
269 }
270}
271
272impl Default for GlobalElementId {
273 fn default() -> Self {
274 Self::new(&[])
275 }
276}
277
278impl std::ops::Deref for GlobalElementId {
279 type Target = [ElementId];
280
281 fn deref(&self) -> &Self::Target {
282 &self.ids
283 }
284}
285
286impl PartialEq for GlobalElementId {
287 fn eq(&self, other: &Self) -> bool {
288 self.hash == other.hash && (Arc::ptr_eq(&self.ids, &other.ids) || self.ids == other.ids)
289 }
290}
291
292impl Eq for GlobalElementId {}
293
294impl std::hash::Hash for GlobalElementId {
295 fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
296 state.write_u64(self.hash.0);
297 }
298}
299
300impl Display for GlobalElementId {
301 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
302 for (i, element_id) in self.ids.iter().enumerate() {
303 if i > 0 {
304 write!(f, ".")?;
305 }
306 write!(f, "{}", element_id)?;
307 }
308 Ok(())
309 }
310}
311
312trait ElementObject {
313 fn inner_element(&mut self) -> &mut dyn Any;
314
315 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId;
316
317 fn prepaint(&mut self, window: &mut Window, cx: &mut App);
318
319 fn paint(&mut self, window: &mut Window, cx: &mut App);
320
321 fn layout_as_root(
322 &mut self,
323 available_space: Size<AvailableSpace>,
324 window: &mut Window,
325 cx: &mut App,
326 ) -> Size<Pixels>;
327}
328
329pub struct Drawable<E: Element> {
331 pub element: E,
333 phase: ElementDrawPhase<E::RequestLayoutState, E::PrepaintState>,
334}
335
336#[derive(Default)]
337enum ElementDrawPhase<RequestLayoutState, PrepaintState> {
338 #[default]
339 Start,
340 RequestLayout {
341 layout_id: LayoutId,
342 global_id: Option<GlobalElementId>,
343 inspector_id: Option<InspectorElementId>,
344 request_layout: RequestLayoutState,
345 },
346 LayoutComputed {
347 layout_id: LayoutId,
348 global_id: Option<GlobalElementId>,
349 inspector_id: Option<InspectorElementId>,
350 available_space: Size<AvailableSpace>,
351 request_layout: RequestLayoutState,
352 },
353 Prepaint {
354 node_id: DispatchNodeId,
355 global_id: Option<GlobalElementId>,
356 inspector_id: Option<InspectorElementId>,
357 bounds: Bounds<Pixels>,
358 request_layout: RequestLayoutState,
359 prepaint: PrepaintState,
360 },
361 Painted,
362}
363
364impl<E: Element> Drawable<E> {
366 pub(crate) fn new(element: E) -> Self {
367 Drawable {
368 element,
369 phase: ElementDrawPhase::Start,
370 }
371 }
372
373 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
374 match mem::take(&mut self.phase) {
375 ElementDrawPhase::Start => {
376 let global_id = self
377 .element
378 .id()
379 .map(|element_id| prepare_element_id(element_id, window));
380
381 let inspector_id;
382 #[cfg(any(feature = "inspector", debug_assertions))]
383 {
384 inspector_id = if window.inspector_enabled() {
385 self.element
386 .source_location()
387 .map(|source| prepare_inspector_id(source, window))
388 } else {
389 None
390 };
391 }
392 #[cfg(not(any(feature = "inspector", debug_assertions)))]
393 {
394 inspector_id = None;
395 }
396
397 let (layout_id, request_layout) = self.element.request_layout(
398 global_id.as_ref(),
399 inspector_id.as_ref(),
400 window,
401 cx,
402 );
403
404 if global_id.is_some() {
405 window.element_id_stack.pop();
406 }
407
408 self.phase = ElementDrawPhase::RequestLayout {
409 layout_id,
410 global_id,
411 inspector_id,
412 request_layout,
413 };
414 layout_id
415 }
416 _ => panic!("must call request_layout only once"),
417 }
418 }
419
420 pub(crate) fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
421 match mem::take(&mut self.phase) {
422 ElementDrawPhase::RequestLayout {
423 layout_id,
424 global_id,
425 inspector_id,
426 mut request_layout,
427 }
428 | ElementDrawPhase::LayoutComputed {
429 layout_id,
430 global_id,
431 inspector_id,
432 mut request_layout,
433 ..
434 } => {
435 if let Some(element_id) = self.element.id() {
436 window.element_id_stack.push(element_id);
437 debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);
438 }
439
440 let bounds = window.layout_bounds(layout_id);
441 let mut pushed_a11y_node = false;
442 if window.a11y.is_active() {
443 if let Some(global_id) = global_id.as_ref() {
444 if let Some(role) = self.element.a11y_role() {
445 let node_id = global_id.accesskit_node_id();
446 let mut node = accesskit::Node::new(role);
447 let scale = window.scale_factor();
448 node.set_bounds(accesskit::Rect {
449 x0: (bounds.origin.x.0 * scale) as f64,
450 y0: (bounds.origin.y.0 * scale) as f64,
451 x1: ((bounds.origin.x.0 + bounds.size.width.0) * scale) as f64,
452 y1: ((bounds.origin.y.0 + bounds.size.height.0) * scale) as f64,
453 });
454 self.element.write_a11y_info(&mut node);
455 window.a11y.node_bounds.insert(node_id, bounds);
456 pushed_a11y_node = window.a11y.nodes.push(node_id, node);
457 #[cfg(debug_assertions)]
458 if pushed_a11y_node {
459 let view = window
460 .a11y
461 .view_type_names
462 .get(&window.current_view())
463 .copied();
464 let source_location = self.element.source_location();
465 window.a11y.nodes.record_node_info(
466 node_id,
467 crate::window::a11y::debug::NodeDebugInfo {
468 synthetic: false,
469 view,
470 element_id: global_id.last().map(|id| format!("{id:?}")),
471 source_location,
472 },
473 );
474 }
475 }
476 }
477 }
478
479 let node_id = window.next_frame.dispatch_tree.push_node();
480 let mut prepaint = self.element.prepaint(
481 global_id.as_ref(),
482 inspector_id.as_ref(),
483 bounds,
484 &mut request_layout,
485 window,
486 cx,
487 );
488 window.next_frame.dispatch_tree.pop_node();
489
490 if pushed_a11y_node {
491 if let Some(global_id) = global_id.as_ref() {
492 #[cfg(debug_assertions)]
493 let creator = crate::window::a11y::debug::NodeCreator {
494 view: window
495 .a11y
496 .view_type_names
497 .get(&window.current_view())
498 .copied(),
499 element_id: global_id.last().map(|id| format!("{id:?}")),
500 source_location: self.element.source_location(),
501 };
502 let mut builder = A11ySubtreeBuilder::new(
503 global_id.accesskit_node_id(),
504 &mut window.a11y.nodes,
505 );
506 #[cfg(debug_assertions)]
507 {
508 builder = builder.with_creator(creator);
509 }
510 self.element
511 .a11y_synthetic_children(&mut prepaint, &mut builder);
512 }
513 window.a11y.nodes.pop();
514 }
515
516 if global_id.is_some() {
517 window.element_id_stack.pop();
518 }
519
520 self.phase = ElementDrawPhase::Prepaint {
521 node_id,
522 global_id,
523 inspector_id,
524 bounds,
525 request_layout,
526 prepaint,
527 };
528 }
529 _ => panic!("must call request_layout before prepaint"),
530 }
531 }
532
533 pub(crate) fn paint(
534 &mut self,
535 window: &mut Window,
536 cx: &mut App,
537 ) -> (E::RequestLayoutState, E::PrepaintState) {
538 match mem::take(&mut self.phase) {
539 ElementDrawPhase::Prepaint {
540 node_id,
541 global_id,
542 inspector_id,
543 bounds,
544 mut request_layout,
545 mut prepaint,
546 ..
547 } => {
548 if let Some(element_id) = self.element.id() {
549 window.element_id_stack.push(element_id);
550 debug_assert_eq!(&**global_id.as_ref().unwrap(), &*window.element_id_stack);
551 }
552
553 window.next_frame.dispatch_tree.set_active_node(node_id);
554 self.element.paint(
555 global_id.as_ref(),
556 inspector_id.as_ref(),
557 bounds,
558 &mut request_layout,
559 &mut prepaint,
560 window,
561 cx,
562 );
563
564 if global_id.is_some() {
565 window.element_id_stack.pop();
566 }
567
568 self.phase = ElementDrawPhase::Painted;
569 (request_layout, prepaint)
570 }
571 _ => panic!("must call prepaint before paint"),
572 }
573 }
574
575 pub(crate) fn layout_as_root(
576 &mut self,
577 available_space: Size<AvailableSpace>,
578 window: &mut Window,
579 cx: &mut App,
580 ) -> Size<Pixels> {
581 if matches!(&self.phase, ElementDrawPhase::Start) {
582 self.request_layout(window, cx);
583 }
584
585 let layout_id = match mem::take(&mut self.phase) {
586 ElementDrawPhase::RequestLayout {
587 layout_id,
588 global_id,
589 inspector_id,
590 request_layout,
591 } => {
592 window.compute_layout(layout_id, available_space, cx);
593 self.phase = ElementDrawPhase::LayoutComputed {
594 layout_id,
595 global_id,
596 inspector_id,
597 available_space,
598 request_layout,
599 };
600 layout_id
601 }
602 ElementDrawPhase::LayoutComputed {
603 layout_id,
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 global_id,
615 inspector_id,
616 available_space,
617 request_layout,
618 };
619 layout_id
620 }
621 _ => panic!("cannot measure after painting"),
622 };
623
624 window.layout_bounds(layout_id).size
625 }
626}
627
628impl<E> ElementObject for Drawable<E>
629where
630 E: Element,
631 E::RequestLayoutState: 'static,
632{
633 fn inner_element(&mut self) -> &mut dyn Any {
634 &mut self.element
635 }
636
637 #[inline]
638 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
639 Drawable::request_layout(self, window, cx)
640 }
641
642 #[inline]
643 fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
644 Drawable::prepaint(self, window, cx);
645 }
646
647 #[inline]
648 fn paint(&mut self, window: &mut Window, cx: &mut App) {
649 Drawable::paint(self, window, cx);
650 }
651
652 #[inline]
653 fn layout_as_root(
654 &mut self,
655 available_space: Size<AvailableSpace>,
656 window: &mut Window,
657 cx: &mut App,
658 ) -> Size<Pixels> {
659 Drawable::layout_as_root(self, available_space, window, cx)
660 }
661}
662
663pub struct AnyElement(ArenaBox<dyn ElementObject>);
665
666impl AnyElement {
667 fn new_please_call_into_any_to_avoid_double_box<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 pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
684 self.0.inner_element().downcast_mut::<T>()
685 }
686
687 pub fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
690 self.0.request_layout(window, cx)
691 }
692
693 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 pub fn paint(&mut self, window: &mut Window, cx: &mut App) {
709 self.0.paint(window, cx);
710 }
711
712 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 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 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 fn into_any(self) -> AnyElement {
796 self
797 }
798}
799
800pub struct Empty;
802
803impl Element for Empty {
804 type RequestLayoutState = ();
805 type PrepaintState = ();
806
807 fn id(&self) -> Option<ElementId> {
808 None
809 }
810
811 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
812 None
813 }
814
815 fn request_layout(
816 &mut self,
817 _id: Option<&GlobalElementId>,
818 _inspector_id: Option<&InspectorElementId>,
819 window: &mut Window,
820 cx: &mut App,
821 ) -> (LayoutId, Self::RequestLayoutState) {
822 (
823 window.request_layout(
824 Style {
825 display: crate::Display::None,
826 ..Default::default()
827 },
828 None,
829 cx,
830 ),
831 (),
832 )
833 }
834
835 fn prepaint(
836 &mut self,
837 _id: Option<&GlobalElementId>,
838 _inspector_id: Option<&InspectorElementId>,
839 _bounds: Bounds<Pixels>,
840 _state: &mut Self::RequestLayoutState,
841 _window: &mut Window,
842 _cx: &mut App,
843 ) {
844 }
845
846 fn paint(
847 &mut self,
848 _id: Option<&GlobalElementId>,
849 _inspector_id: Option<&InspectorElementId>,
850 _bounds: Bounds<Pixels>,
851 _request_layout: &mut Self::RequestLayoutState,
852 _prepaint: &mut Self::PrepaintState,
853 _window: &mut Window,
854 _cx: &mut App,
855 ) {
856 }
857}
858
859#[inline(never)]
860fn prepare_element_id(element_id: ElementId, window: &mut Window) -> GlobalElementId {
861 window.element_id_stack.push(element_id);
862 window.element_id_stack.global_id()
863}
864
865#[cfg(any(feature = "inspector", debug_assertions))]
866#[inline(never)]
867fn prepare_inspector_id(
868 source: &'static panic::Location<'static>,
869 window: &mut Window,
870) -> InspectorElementId {
871 let path = InspectorElementPath {
872 global_id: window.element_id_stack.global_id(),
873 source_location: source,
874 };
875 window.build_inspector_element_id(path)
876}
877
878#[cfg(test)]
879mod global_element_id_tests {
880 use super::*;
881 use std::hash::{Hash, Hasher};
882
883 fn path(depth: usize, leaf: u64) -> Vec<ElementId> {
884 let mut ids: Vec<ElementId> = (0..depth as u64)
885 .map(|level| ElementId::NamedInteger("some-container-element".into(), level))
886 .collect();
887 ids.push(ElementId::NamedInteger("leaf".into(), leaf));
888 ids
889 }
890
891 fn fx_hash(value: &impl Hash) -> u64 {
892 let mut hasher = collections::FxHasher::default();
893 value.hash(&mut hasher);
894 hasher.finish()
895 }
896
897 #[test]
898 fn equal_paths_are_equal_and_hash_alike() {
899 let a = GlobalElementId::new(&path(8, 1));
900 let b = GlobalElementId::new(&path(8, 1));
901 let c = GlobalElementId::new(&path(8, 2));
902 let shallower = GlobalElementId::new(&path(7, 1));
903 assert_eq!(a, b);
904 assert_eq!(fx_hash(&a), fx_hash(&b));
905 assert_eq!(a.accesskit_node_id(), b.accesskit_node_id());
906 assert_ne!(a, c);
907 assert_ne!(a, shallower);
908 assert_ne!(fx_hash(&a), fx_hash(&c));
909 assert_eq!(&*a, path(8, 1).as_slice());
910 assert_eq!(a.to_string(), b.to_string());
911 assert_eq!(GlobalElementId::default(), GlobalElementId::new(&[]));
912 }
913
914 struct DeepStatefulTree {
917 items: usize,
918 depth: usize,
919 }
920
921 impl crate::Render for DeepStatefulTree {
922 fn render(&mut self, _: &mut Window, _: &mut crate::Context<Self>) -> impl IntoElement {
923 use crate::{InteractiveElement as _, ParentElement as _, Styled as _, div, px};
924 let depth = self.depth;
925 div()
926 .flex()
927 .flex_wrap()
928 .size_full()
929 .children((0..self.items).map(move |item| {
930 let mut element = div().id(("leaf", item as u64)).size(px(2.));
931 for level in (0..depth).rev() {
932 element = div()
933 .id(("some-container-element", level as u64))
934 .child(element);
935 }
936 element.id(("item", item as u64)).size(px(4.))
937 }))
938 }
939 }
940
941 #[crate::test]
946 #[ignore = "prints timings; run by hand"]
947 fn frame_cost(cx: &mut crate::TestAppContext) {
948 use crate::AppContext as _;
949 for (items, depth) in [(500, 4), (500, 12), (2000, 12)] {
950 let window = cx.add_window(move |_, _| DeepStatefulTree { items, depth });
951 let window = crate::AnyWindowHandle::from(window);
952 let frame = |cx: &mut crate::TestAppContext| {
953 cx.update_window(window, |_, window, cx| {
954 window.refresh();
955 let started = std::time::Instant::now();
956 window.draw(cx).clear(cx);
957 started.elapsed()
958 })
959 .unwrap()
960 };
961 for _ in 0..5 {
962 frame(cx);
963 }
964 let mut samples: Vec<_> = (0..40).map(|_| frame(cx)).collect();
965 samples.sort();
966 let median = samples[samples.len() / 2];
967 let stateful = items * (depth + 2);
968 eprintln!(
969 "{items} items x {depth} deep ({stateful} stateful elements): median frame {:.2} ms, {:.0} ns per stateful element",
970 median.as_secs_f64() * 1e3,
971 median.as_nanos() as f64 / stateful as f64,
972 );
973 }
974 }
975
976 #[test]
978 #[ignore = "prints timings; run by hand"]
979 fn hash_cost() {
980 let ids = path(11, 7);
981 let id = GlobalElementId::new(&ids);
982 let n = 1_000_000u64;
983 let mut acc = 0u64;
984 let started = std::time::Instant::now();
985 for _ in 0..n {
986 acc ^= fx_hash(&std::hint::black_box(ids.as_slice()));
987 }
988 let walk = started.elapsed();
989 let started = std::time::Instant::now();
990 for _ in 0..n {
991 acc ^= fx_hash(std::hint::black_box(&id));
992 }
993 let cached = started.elapsed();
994 let started = std::time::Instant::now();
995 for _ in 0..n {
996 acc ^= GlobalElementId::new(std::hint::black_box(&ids)).hash.0;
997 }
998 let build = started.elapsed();
999 eprintln!(
1000 "12-deep path: hash by walking ids {:.1} ns, cached {:.1} ns, build (clone + hash once) {:.1} ns [{acc}]",
1001 walk.as_nanos() as f64 / n as f64,
1002 cached.as_nanos() as f64 / n as f64,
1003 build.as_nanos() as f64 / n as f64,
1004 );
1005 }
1006}