1use crate::{
35 App, ArenaBox, AvailableSpace, Bounds, Context, DispatchNodeId, ELEMENT_ARENA, ElementId,
36 FocusHandle, InspectorElementId, LayoutId, Pixels, Point, Size, Style, Window,
37 util::FluentBuilder,
38};
39use derive_more::{Deref, DerefMut};
40use std::{
41 any::{Any, type_name},
42 fmt::{self, Debug, Display},
43 mem, panic,
44 sync::Arc,
45};
46
47pub trait Element: 'static + IntoElement {
52 type RequestLayoutState: 'static;
55
56 type PrepaintState: 'static;
59
60 fn id(&self) -> Option<ElementId>;
66
67 fn source_location(&self) -> Option<&'static panic::Location<'static>>;
70
71 fn request_layout(
74 &mut self,
75 id: Option<&GlobalElementId>,
76 inspector_id: Option<&InspectorElementId>,
77 window: &mut Window,
78 cx: &mut App,
79 ) -> (LayoutId, Self::RequestLayoutState);
80
81 fn prepaint(
84 &mut self,
85 id: Option<&GlobalElementId>,
86 inspector_id: Option<&InspectorElementId>,
87 bounds: Bounds<Pixels>,
88 request_layout: &mut Self::RequestLayoutState,
89 window: &mut Window,
90 cx: &mut App,
91 ) -> Self::PrepaintState;
92
93 fn paint(
96 &mut self,
97 id: Option<&GlobalElementId>,
98 inspector_id: Option<&InspectorElementId>,
99 bounds: Bounds<Pixels>,
100 request_layout: &mut Self::RequestLayoutState,
101 prepaint: &mut Self::PrepaintState,
102 window: &mut Window,
103 cx: &mut App,
104 );
105
106 fn a11y_role(&self) -> Option<accesskit::Role> {
108 None
109 }
110
111 fn write_a11y_info(&self, _node: &mut accesskit::Node) {}
113
114 fn take_a11y_actions(&mut self) -> Vec<(accesskit::Action, crate::A11yActionListener)> {
116 Vec::new()
117 }
118
119 fn a11y_focus_handle(&self) -> Option<crate::FocusHandle> {
121 None
122 }
123
124 fn a11y_reports_active_descendant(&self) -> bool {
126 false
127 }
128
129 fn a11y_synthetic_children(
131 &mut self,
132 _prepaint: &mut Self::PrepaintState,
133 _builder: &mut crate::A11ySubtreeBuilder,
134 ) {
135 }
136
137 fn into_any(self) -> AnyElement {
139 AnyElement::new(self)
140 }
141}
142
143pub trait IntoElement: Sized {
145 type Element: Element;
148
149 fn into_element(self) -> Self::Element;
151
152 fn into_any_element(self) -> AnyElement {
154 self.into_element().into_any()
155 }
156}
157
158impl<T: IntoElement> FluentBuilder for T {}
159
160pub trait Render: 'static + Sized {
163 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement;
165}
166
167impl Render for Empty {
168 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
169 Empty
170 }
171}
172
173pub trait RenderOnce: 'static {
179 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
183}
184
185pub trait ParentElement {
188 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>);
190
191 fn child(mut self, child: impl IntoElement) -> Self
193 where
194 Self: Sized,
195 {
196 self.extend(std::iter::once(child.into_element().into_any()));
197 self
198 }
199
200 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self
202 where
203 Self: Sized,
204 {
205 self.extend(children.into_iter().map(|child| child.into_any_element()));
206 self
207 }
208}
209
210#[doc(hidden)]
213pub struct Component<C: RenderOnce> {
214 component: Option<C>,
215 #[cfg(debug_assertions)]
216 source: &'static core::panic::Location<'static>,
217}
218
219impl<C: RenderOnce> Component<C> {
220 #[track_caller]
222 pub fn new(component: C) -> Self {
223 Component {
224 component: Some(component),
225 #[cfg(debug_assertions)]
226 source: core::panic::Location::caller(),
227 }
228 }
229}
230
231impl<C: RenderOnce> Element for Component<C> {
232 type RequestLayoutState = AnyElement;
233 type PrepaintState = ();
234
235 fn id(&self) -> Option<ElementId> {
236 None
237 }
238
239 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
240 #[cfg(debug_assertions)]
241 return Some(self.source);
242
243 #[cfg(not(debug_assertions))]
244 return None;
245 }
246
247 fn request_layout(
248 &mut self,
249 _id: Option<&GlobalElementId>,
250 _inspector_id: Option<&InspectorElementId>,
251 window: &mut Window,
252 cx: &mut App,
253 ) -> (LayoutId, Self::RequestLayoutState) {
254 window.with_global_id(ElementId::Name(type_name::<C>().into()), |_, window| {
255 let mut element = self
256 .component
257 .take()
258 .unwrap()
259 .render(window, cx)
260 .into_any_element();
261
262 let layout_id = element.request_layout(window, cx);
263 (layout_id, element)
264 })
265 }
266
267 fn prepaint(
268 &mut self,
269 _id: Option<&GlobalElementId>,
270 _inspector_id: Option<&InspectorElementId>,
271 _: Bounds<Pixels>,
272 element: &mut AnyElement,
273 window: &mut Window,
274 cx: &mut App,
275 ) {
276 window.with_global_id(ElementId::Name(type_name::<C>().into()), |_, window| {
277 element.prepaint(window, cx);
278 })
279 }
280
281 fn paint(
282 &mut self,
283 _id: Option<&GlobalElementId>,
284 _inspector_id: Option<&InspectorElementId>,
285 _: Bounds<Pixels>,
286 element: &mut Self::RequestLayoutState,
287 _: &mut Self::PrepaintState,
288 window: &mut Window,
289 cx: &mut App,
290 ) {
291 window.with_global_id(ElementId::Name(type_name::<C>().into()), |_, window| {
292 element.paint(window, cx);
293 })
294 }
295}
296
297impl<C: RenderOnce> IntoElement for Component<C> {
298 type Element = Self;
299
300 fn into_element(self) -> Self::Element {
301 self
302 }
303}
304
305#[derive(Deref, DerefMut, Clone, Default, Debug, Eq, PartialEq, Hash)]
307pub struct GlobalElementId(pub(crate) Arc<[ElementId]>);
308
309impl Display for GlobalElementId {
310 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311 for (i, element_id) in self.0.iter().enumerate() {
312 if i > 0 {
313 write!(f, ".")?;
314 }
315 write!(f, "{}", element_id)?;
316 }
317 Ok(())
318 }
319}
320
321trait ElementObject {
322 fn inner_element(&mut self) -> &mut dyn Any;
323
324 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId;
325
326 fn prepaint(&mut self, window: &mut Window, cx: &mut App);
327
328 fn paint(&mut self, window: &mut Window, cx: &mut App);
329
330 fn layout_as_root(
331 &mut self,
332 available_space: Size<AvailableSpace>,
333 window: &mut Window,
334 cx: &mut App,
335 ) -> Size<Pixels>;
336}
337
338pub type ViewElement<V> = Component<V>;
340
341pub struct Drawable<E: Element> {
343 pub element: E,
345 phase: ElementDrawPhase<E::RequestLayoutState, E::PrepaintState>,
346}
347
348#[derive(Default)]
349enum ElementDrawPhase<RequestLayoutState, PrepaintState> {
350 #[default]
351 Start,
352 RequestLayout {
353 layout_id: LayoutId,
354 global_id: Option<GlobalElementId>,
355 inspector_id: Option<InspectorElementId>,
356 request_layout: RequestLayoutState,
357 },
358 LayoutComputed {
359 layout_id: LayoutId,
360 global_id: Option<GlobalElementId>,
361 inspector_id: Option<InspectorElementId>,
362 available_space: Size<AvailableSpace>,
363 request_layout: RequestLayoutState,
364 },
365 Prepaint {
366 node_id: DispatchNodeId,
367 global_id: Option<GlobalElementId>,
368 inspector_id: Option<InspectorElementId>,
369 bounds: Bounds<Pixels>,
370 request_layout: RequestLayoutState,
371 prepaint: PrepaintState,
372 },
373 Painted,
374}
375
376impl<E: Element> Drawable<E> {
378 pub(crate) fn new(element: E) -> Self {
379 Drawable {
380 element,
381 phase: ElementDrawPhase::Start,
382 }
383 }
384
385 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
386 match mem::take(&mut self.phase) {
387 ElementDrawPhase::Start => {
388 let global_id = self.element.id().map(|element_id| {
389 window.element_id_stack.push(element_id);
390 GlobalElementId(Arc::from(&*window.element_id_stack))
391 });
392
393 let inspector_id;
394 #[cfg(any(feature = "inspector", debug_assertions))]
395 {
396 inspector_id = self.element.source_location().map(|source| {
397 let path = crate::InspectorElementPath {
398 global_id: GlobalElementId(Arc::from(&*window.element_id_stack)),
399 source_location: source,
400 };
401 window.build_inspector_element_id(path)
402 });
403 }
404 #[cfg(not(any(feature = "inspector", debug_assertions)))]
405 {
406 inspector_id = None;
407 }
408
409 let (layout_id, request_layout) = self.element.request_layout(
410 global_id.as_ref(),
411 inspector_id.as_ref(),
412 window,
413 cx,
414 );
415
416 if global_id.is_some() {
417 window.element_id_stack.pop();
418 }
419
420 self.phase = ElementDrawPhase::RequestLayout {
421 layout_id,
422 global_id,
423 inspector_id,
424 request_layout,
425 };
426 layout_id
427 }
428 _ => panic!("must call request_layout only once"),
429 }
430 }
431
432 pub(crate) fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
433 match mem::take(&mut self.phase) {
434 ElementDrawPhase::RequestLayout {
435 layout_id,
436 global_id,
437 inspector_id,
438 mut request_layout,
439 }
440 | ElementDrawPhase::LayoutComputed {
441 layout_id,
442 global_id,
443 inspector_id,
444 mut request_layout,
445 ..
446 } => {
447 if let Some(element_id) = self.element.id() {
448 window.element_id_stack.push(element_id);
449 debug_assert_eq!(&*global_id.as_ref().unwrap().0, &*window.element_id_stack);
450 }
451
452 let bounds = window.layout_bounds(layout_id);
453 let node_id = window.next_frame.dispatch_tree.push_node();
454 let prepaint = self.element.prepaint(
455 global_id.as_ref(),
456 inspector_id.as_ref(),
457 bounds,
458 &mut request_layout,
459 window,
460 cx,
461 );
462 window.next_frame.dispatch_tree.pop_node();
463
464 if global_id.is_some() {
465 window.element_id_stack.pop();
466 }
467
468 self.phase = ElementDrawPhase::Prepaint {
469 node_id,
470 global_id,
471 inspector_id,
472 bounds,
473 request_layout,
474 prepaint,
475 };
476 }
477 _ => panic!("must call request_layout before prepaint"),
478 }
479 }
480
481 pub(crate) fn paint(
482 &mut self,
483 window: &mut Window,
484 cx: &mut App,
485 ) -> (E::RequestLayoutState, E::PrepaintState) {
486 match mem::take(&mut self.phase) {
487 ElementDrawPhase::Prepaint {
488 node_id,
489 global_id,
490 inspector_id,
491 bounds,
492 mut request_layout,
493 mut prepaint,
494 ..
495 } => {
496 if let Some(element_id) = self.element.id() {
497 window.element_id_stack.push(element_id);
498 debug_assert_eq!(&*global_id.as_ref().unwrap().0, &*window.element_id_stack);
499 }
500
501 window.next_frame.dispatch_tree.set_active_node(node_id);
502 let a11y_id = window.begin_a11y_node(&mut self.element, global_id.as_ref(), bounds);
503 self.element.paint(
504 global_id.as_ref(),
505 inspector_id.as_ref(),
506 bounds,
507 &mut request_layout,
508 &mut prepaint,
509 window,
510 cx,
511 );
512
513 if let Some(a11y_id) = a11y_id {
514 if let Some(mut builder) =
515 crate::A11ySubtreeBuilder::new(a11y_id, &mut window.a11y_nodes)
516 {
517 self.element
518 .a11y_synthetic_children(&mut prepaint, &mut builder);
519 }
520 window.a11y_nodes.pop();
521 }
522
523 if global_id.is_some() {
524 window.element_id_stack.pop();
525 }
526
527 self.phase = ElementDrawPhase::Painted;
528 (request_layout, prepaint)
529 }
530 _ => panic!("must call prepaint before paint"),
531 }
532 }
533
534 pub(crate) fn layout_as_root(
535 &mut self,
536 available_space: Size<AvailableSpace>,
537 window: &mut Window,
538 cx: &mut App,
539 ) -> Size<Pixels> {
540 if matches!(&self.phase, ElementDrawPhase::Start) {
541 window.with_profiled_request_layout(|window| self.request_layout(window, cx));
542 }
543
544 let layout_id = match mem::take(&mut self.phase) {
545 ElementDrawPhase::RequestLayout {
546 layout_id,
547 global_id,
548 inspector_id,
549 request_layout,
550 } => {
551 window.compute_layout(layout_id, available_space, cx);
552 self.phase = ElementDrawPhase::LayoutComputed {
553 layout_id,
554 global_id,
555 inspector_id,
556 available_space,
557 request_layout,
558 };
559 layout_id
560 }
561 ElementDrawPhase::LayoutComputed {
562 layout_id,
563 global_id,
564 inspector_id,
565 available_space: prev_available_space,
566 request_layout,
567 } => {
568 if available_space != prev_available_space {
569 window.compute_layout(layout_id, available_space, cx);
570 }
571 self.phase = ElementDrawPhase::LayoutComputed {
572 layout_id,
573 global_id,
574 inspector_id,
575 available_space,
576 request_layout,
577 };
578 layout_id
579 }
580 _ => panic!("cannot measure after painting"),
581 };
582
583 window.layout_bounds(layout_id).size
584 }
585}
586
587impl<E> ElementObject for Drawable<E>
588where
589 E: Element,
590 E::RequestLayoutState: 'static,
591{
592 fn inner_element(&mut self) -> &mut dyn Any {
593 &mut self.element
594 }
595
596 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
597 Drawable::request_layout(self, window, cx)
598 }
599
600 fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
601 Drawable::prepaint(self, window, cx);
602 }
603
604 fn paint(&mut self, window: &mut Window, cx: &mut App) {
605 Drawable::paint(self, window, cx);
606 }
607
608 fn layout_as_root(
609 &mut self,
610 available_space: Size<AvailableSpace>,
611 window: &mut Window,
612 cx: &mut App,
613 ) -> Size<Pixels> {
614 Drawable::layout_as_root(self, available_space, window, cx)
615 }
616}
617
618pub struct AnyElement(ArenaBox<dyn ElementObject>);
620
621impl AnyElement {
622 pub(crate) fn new<E>(element: E) -> Self
623 where
624 E: 'static + Element,
625 E::RequestLayoutState: Any,
626 {
627 let element = ELEMENT_ARENA
628 .with_borrow_mut(|arena| arena.alloc(|| Drawable::new(element)))
629 .map(|element| element as &mut dyn ElementObject);
630 AnyElement(element)
631 }
632
633 pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
635 self.0.inner_element().downcast_mut::<T>()
636 }
637
638 pub fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
641 self.0.request_layout(window, cx)
642 }
643
644 pub fn prepaint(&mut self, window: &mut Window, cx: &mut App) -> Option<FocusHandle> {
647 let focus_assigned = window.next_frame.focus.is_some();
648
649 self.0.prepaint(window, cx);
650
651 if !focus_assigned && let Some(focus_id) = window.next_frame.focus {
652 return FocusHandle::for_id(focus_id, &cx.focus_handles);
653 }
654
655 None
656 }
657
658 pub fn paint(&mut self, window: &mut Window, cx: &mut App) {
660 self.0.paint(window, cx);
661 }
662
663 pub fn layout_as_root(
665 &mut self,
666 available_space: Size<AvailableSpace>,
667 window: &mut Window,
668 cx: &mut App,
669 ) -> Size<Pixels> {
670 self.0.layout_as_root(available_space, window, cx)
671 }
672
673 pub fn prepaint_at(
676 &mut self,
677 origin: Point<Pixels>,
678 window: &mut Window,
679 cx: &mut App,
680 ) -> Option<FocusHandle> {
681 window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
682 }
683
684 pub fn prepaint_as_root(
687 &mut self,
688 origin: Point<Pixels>,
689 available_space: Size<AvailableSpace>,
690 window: &mut Window,
691 cx: &mut App,
692 ) -> Option<FocusHandle> {
693 self.layout_as_root(available_space, window, cx);
694 window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
695 }
696}
697
698impl Element for AnyElement {
699 type RequestLayoutState = ();
700 type PrepaintState = ();
701
702 fn id(&self) -> Option<ElementId> {
703 None
704 }
705
706 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
707 None
708 }
709
710 fn request_layout(
711 &mut self,
712 _: Option<&GlobalElementId>,
713 _inspector_id: Option<&InspectorElementId>,
714 window: &mut Window,
715 cx: &mut App,
716 ) -> (LayoutId, Self::RequestLayoutState) {
717 let layout_id = self.request_layout(window, cx);
718 (layout_id, ())
719 }
720
721 fn prepaint(
722 &mut self,
723 _: Option<&GlobalElementId>,
724 _inspector_id: Option<&InspectorElementId>,
725 _: Bounds<Pixels>,
726 _: &mut Self::RequestLayoutState,
727 window: &mut Window,
728 cx: &mut App,
729 ) {
730 self.prepaint(window, cx);
731 }
732
733 fn paint(
734 &mut self,
735 _: Option<&GlobalElementId>,
736 _inspector_id: Option<&InspectorElementId>,
737 _: Bounds<Pixels>,
738 _: &mut Self::RequestLayoutState,
739 _: &mut Self::PrepaintState,
740 window: &mut Window,
741 cx: &mut App,
742 ) {
743 self.paint(window, cx);
744 }
745}
746
747impl IntoElement for AnyElement {
748 type Element = Self;
749
750 fn into_element(self) -> Self::Element {
751 self
752 }
753
754 fn into_any_element(self) -> AnyElement {
755 self
756 }
757}
758
759pub struct Empty;
761
762impl IntoElement for Empty {
763 type Element = Self;
764
765 fn into_element(self) -> Self::Element {
766 self
767 }
768}
769
770impl Element for Empty {
771 type RequestLayoutState = ();
772 type PrepaintState = ();
773
774 fn id(&self) -> Option<ElementId> {
775 None
776 }
777
778 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
779 None
780 }
781
782 fn request_layout(
783 &mut self,
784 _id: Option<&GlobalElementId>,
785 _inspector_id: Option<&InspectorElementId>,
786 window: &mut Window,
787 cx: &mut App,
788 ) -> (LayoutId, Self::RequestLayoutState) {
789 (
790 window.request_layout(
791 Style {
792 display: crate::Display::None,
793 ..Default::default()
794 },
795 None,
796 cx,
797 ),
798 (),
799 )
800 }
801
802 fn prepaint(
803 &mut self,
804 _id: Option<&GlobalElementId>,
805 _inspector_id: Option<&InspectorElementId>,
806 _bounds: Bounds<Pixels>,
807 _state: &mut Self::RequestLayoutState,
808 _window: &mut Window,
809 _cx: &mut App,
810 ) {
811 }
812
813 fn paint(
814 &mut self,
815 _id: Option<&GlobalElementId>,
816 _inspector_id: Option<&InspectorElementId>,
817 _bounds: Bounds<Pixels>,
818 _request_layout: &mut Self::RequestLayoutState,
819 _prepaint: &mut Self::PrepaintState,
820 _window: &mut Window,
821 _cx: &mut App,
822 ) {
823 }
824}