1use crate::{
35 App, ArenaBox, AvailableSpace, Bounds, Context, DispatchNodeId, ElementId, FocusHandle,
36 InspectorElementId, LayoutId, Pixels, Point, SharedString, Size, Style, Window,
37 util::FluentBuilder, window::with_element_arena,
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> {
113 None
114 }
115
116 fn write_a11y_info(&self, _node: &mut accesskit::Node) {}
121
122 fn into_any(self) -> AnyElement {
124 AnyElement::new(self)
125 }
126}
127
128pub trait IntoElement: Sized {
130 type Element: Element;
133
134 fn into_element(self) -> Self::Element;
136
137 fn into_any_element(self) -> AnyElement {
139 self.into_element().into_any()
140 }
141}
142
143impl<T: IntoElement> FluentBuilder for T {}
144
145pub trait Render: 'static + Sized {
148 fn render(&mut self, window: &mut Window, cx: &mut Context<Self>) -> impl IntoElement;
150}
151
152impl Render for Empty {
153 fn render(&mut self, _window: &mut Window, _cx: &mut Context<Self>) -> impl IntoElement {
154 Empty
155 }
156}
157
158pub trait RenderOnce: 'static {
164 fn render(self, window: &mut Window, cx: &mut App) -> impl IntoElement;
168}
169
170pub trait ParentElement {
173 fn extend(&mut self, elements: impl IntoIterator<Item = AnyElement>);
175
176 fn child(mut self, child: impl IntoElement) -> Self
178 where
179 Self: Sized,
180 {
181 self.extend(std::iter::once(child.into_element().into_any()));
182 self
183 }
184
185 fn children(mut self, children: impl IntoIterator<Item = impl IntoElement>) -> Self
187 where
188 Self: Sized,
189 {
190 self.extend(children.into_iter().map(|child| child.into_any_element()));
191 self
192 }
193}
194
195#[doc(hidden)]
198pub struct Component<C: RenderOnce> {
199 component: Option<C>,
200 #[cfg(debug_assertions)]
201 source: &'static core::panic::Location<'static>,
202}
203
204impl<C: RenderOnce> Component<C> {
205 #[track_caller]
207 pub fn new(component: C) -> Self {
208 Component {
209 component: Some(component),
210 #[cfg(debug_assertions)]
211 source: core::panic::Location::caller(),
212 }
213 }
214}
215
216fn prepaint_component(
217 (element, name): &mut (AnyElement, &'static str),
218 window: &mut Window,
219 cx: &mut App,
220) {
221 window.with_id(ElementId::Name(SharedString::new_static(name)), |window| {
222 element.prepaint(window, cx);
223 })
224}
225
226fn paint_component(
227 (element, name): &mut (AnyElement, &'static str),
228 window: &mut Window,
229 cx: &mut App,
230) {
231 window.with_id(ElementId::Name(SharedString::new_static(name)), |window| {
232 element.paint(window, cx);
233 })
234}
235impl<C: RenderOnce> Element for Component<C> {
236 type RequestLayoutState = (AnyElement, &'static str);
237 type PrepaintState = ();
238
239 fn id(&self) -> Option<ElementId> {
240 None
241 }
242
243 fn source_location(&self) -> Option<&'static core::panic::Location<'static>> {
244 #[cfg(debug_assertions)]
245 return Some(self.source);
246
247 #[cfg(not(debug_assertions))]
248 return None;
249 }
250
251 fn request_layout(
252 &mut self,
253 _id: Option<&GlobalElementId>,
254 _inspector_id: Option<&InspectorElementId>,
255 window: &mut Window,
256 cx: &mut App,
257 ) -> (LayoutId, Self::RequestLayoutState) {
258 window.with_id(ElementId::Name(type_name::<C>().into()), |window| {
259 let mut element = self
260 .component
261 .take()
262 .unwrap()
263 .render(window, cx)
264 .into_any_element();
265
266 let layout_id = element.request_layout(window, cx);
267 (layout_id, (element, type_name::<C>()))
268 })
269 }
270
271 fn prepaint(
272 &mut self,
273 _id: Option<&GlobalElementId>,
274 _inspector_id: Option<&InspectorElementId>,
275 _: Bounds<Pixels>,
276 state: &mut Self::RequestLayoutState,
277 window: &mut Window,
278 cx: &mut App,
279 ) {
280 prepaint_component(state, window, cx);
281 }
282
283 fn paint(
284 &mut self,
285 _id: Option<&GlobalElementId>,
286 _inspector_id: Option<&InspectorElementId>,
287 _: Bounds<Pixels>,
288 state: &mut Self::RequestLayoutState,
289 _: &mut Self::PrepaintState,
290 window: &mut Window,
291 cx: &mut App,
292 ) {
293 paint_component(state, window, cx);
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
321impl GlobalElementId {
322 pub fn accesskit_node_id(&self) -> accesskit::NodeId {
324 use std::hash::{Hash, Hasher};
325 let mut hasher = std::hash::DefaultHasher::default();
326 self.hash(&mut hasher);
327 accesskit::NodeId(hasher.finish())
328 }
329}
330
331trait ElementObject {
332 fn inner_element(&mut self) -> &mut dyn Any;
333
334 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId;
335
336 fn prepaint(&mut self, window: &mut Window, cx: &mut App);
337
338 fn paint(&mut self, window: &mut Window, cx: &mut App);
339
340 fn layout_as_root(
341 &mut self,
342 available_space: Size<AvailableSpace>,
343 window: &mut Window,
344 cx: &mut App,
345 ) -> Size<Pixels>;
346}
347
348pub struct Drawable<E: Element> {
350 pub element: E,
352 phase: ElementDrawPhase<E::RequestLayoutState, E::PrepaintState>,
353}
354
355#[derive(Default)]
356enum ElementDrawPhase<RequestLayoutState, PrepaintState> {
357 #[default]
358 Start,
359 RequestLayout {
360 layout_id: LayoutId,
361 global_id: Option<GlobalElementId>,
362 inspector_id: Option<InspectorElementId>,
363 request_layout: RequestLayoutState,
364 },
365 LayoutComputed {
366 layout_id: LayoutId,
367 global_id: Option<GlobalElementId>,
368 inspector_id: Option<InspectorElementId>,
369 available_space: Size<AvailableSpace>,
370 request_layout: RequestLayoutState,
371 },
372 Prepaint {
373 node_id: DispatchNodeId,
374 global_id: Option<GlobalElementId>,
375 inspector_id: Option<InspectorElementId>,
376 bounds: Bounds<Pixels>,
377 request_layout: RequestLayoutState,
378 prepaint: PrepaintState,
379 },
380 Painted,
381}
382
383impl<E: Element> Drawable<E> {
385 pub(crate) fn new(element: E) -> Self {
386 Drawable {
387 element,
388 phase: ElementDrawPhase::Start,
389 }
390 }
391
392 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
393 match mem::take(&mut self.phase) {
394 ElementDrawPhase::Start => {
395 let global_id = self.element.id().map(|element_id| {
396 window.element_id_stack.push(element_id);
397 GlobalElementId(Arc::from(&*window.element_id_stack))
398 });
399
400 let inspector_id;
401 #[cfg(any(feature = "inspector", debug_assertions))]
402 {
403 inspector_id = self.element.source_location().map(|source| {
404 let path = crate::InspectorElementPath {
405 global_id: GlobalElementId(Arc::from(&*window.element_id_stack)),
406 source_location: source,
407 };
408 window.build_inspector_element_id(path)
409 });
410 }
411 #[cfg(not(any(feature = "inspector", debug_assertions)))]
412 {
413 inspector_id = None;
414 }
415
416 let (layout_id, request_layout) = self.element.request_layout(
417 global_id.as_ref(),
418 inspector_id.as_ref(),
419 window,
420 cx,
421 );
422
423 if global_id.is_some() {
424 window.element_id_stack.pop();
425 }
426
427 self.phase = ElementDrawPhase::RequestLayout {
428 layout_id,
429 global_id,
430 inspector_id,
431 request_layout,
432 };
433 layout_id
434 }
435 _ => panic!("must call request_layout only once"),
436 }
437 }
438
439 pub(crate) fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
440 match mem::take(&mut self.phase) {
441 ElementDrawPhase::RequestLayout {
442 layout_id,
443 global_id,
444 inspector_id,
445 mut request_layout,
446 }
447 | ElementDrawPhase::LayoutComputed {
448 layout_id,
449 global_id,
450 inspector_id,
451 mut request_layout,
452 ..
453 } => {
454 if let Some(element_id) = self.element.id() {
455 window.element_id_stack.push(element_id);
456 debug_assert_eq!(&*global_id.as_ref().unwrap().0, &*window.element_id_stack);
457 }
458
459 let bounds = window.layout_bounds(layout_id);
460 let mut pushed_a11y_node = false;
461 if window.a11y.is_active() {
462 if let Some(global_id) = global_id.as_ref() {
463 if let Some(role) = self.element.a11y_role() {
464 let node_id = global_id.accesskit_node_id();
465 let mut node = accesskit::Node::new(role);
466 let scale = window.scale_factor();
467 node.set_bounds(accesskit::Rect {
468 x0: (bounds.origin.x.0 * scale) as f64,
469 y0: (bounds.origin.y.0 * scale) as f64,
470 x1: ((bounds.origin.x.0 + bounds.size.width.0) * scale) as f64,
471 y1: ((bounds.origin.y.0 + bounds.size.height.0) * scale) as f64,
472 });
473 self.element.write_a11y_info(&mut node);
474 window.a11y.node_bounds.insert(node_id, bounds);
475 pushed_a11y_node = window.a11y.nodes.push(node_id, node);
476 }
477 }
478 }
479
480 let node_id = window.next_frame.dispatch_tree.push_node();
481 let prepaint = self.element.prepaint(
482 global_id.as_ref(),
483 inspector_id.as_ref(),
484 bounds,
485 &mut request_layout,
486 window,
487 cx,
488 );
489 window.next_frame.dispatch_tree.pop_node();
490
491 if pushed_a11y_node {
492 window.a11y.nodes.pop();
493 }
494
495 if global_id.is_some() {
496 window.element_id_stack.pop();
497 }
498
499 self.phase = ElementDrawPhase::Prepaint {
500 node_id,
501 global_id,
502 inspector_id,
503 bounds,
504 request_layout,
505 prepaint,
506 };
507 }
508 _ => panic!("must call request_layout before prepaint"),
509 }
510 }
511
512 pub(crate) fn paint(
513 &mut self,
514 window: &mut Window,
515 cx: &mut App,
516 ) -> (E::RequestLayoutState, E::PrepaintState) {
517 match mem::take(&mut self.phase) {
518 ElementDrawPhase::Prepaint {
519 node_id,
520 global_id,
521 inspector_id,
522 bounds,
523 mut request_layout,
524 mut prepaint,
525 ..
526 } => {
527 if let Some(element_id) = self.element.id() {
528 window.element_id_stack.push(element_id);
529 debug_assert_eq!(&*global_id.as_ref().unwrap().0, &*window.element_id_stack);
530 }
531
532 window.next_frame.dispatch_tree.set_active_node(node_id);
533 self.element.paint(
534 global_id.as_ref(),
535 inspector_id.as_ref(),
536 bounds,
537 &mut request_layout,
538 &mut prepaint,
539 window,
540 cx,
541 );
542
543 if global_id.is_some() {
544 window.element_id_stack.pop();
545 }
546
547 self.phase = ElementDrawPhase::Painted;
548 (request_layout, prepaint)
549 }
550 _ => panic!("must call prepaint before paint"),
551 }
552 }
553
554 pub(crate) fn layout_as_root(
555 &mut self,
556 available_space: Size<AvailableSpace>,
557 window: &mut Window,
558 cx: &mut App,
559 ) -> Size<Pixels> {
560 if matches!(&self.phase, ElementDrawPhase::Start) {
561 self.request_layout(window, cx);
562 }
563
564 let layout_id = match mem::take(&mut self.phase) {
565 ElementDrawPhase::RequestLayout {
566 layout_id,
567 global_id,
568 inspector_id,
569 request_layout,
570 } => {
571 window.compute_layout(layout_id, available_space, cx);
572 self.phase = ElementDrawPhase::LayoutComputed {
573 layout_id,
574 global_id,
575 inspector_id,
576 available_space,
577 request_layout,
578 };
579 layout_id
580 }
581 ElementDrawPhase::LayoutComputed {
582 layout_id,
583 global_id,
584 inspector_id,
585 available_space: prev_available_space,
586 request_layout,
587 } => {
588 if available_space != prev_available_space {
589 window.compute_layout(layout_id, available_space, cx);
590 }
591 self.phase = ElementDrawPhase::LayoutComputed {
592 layout_id,
593 global_id,
594 inspector_id,
595 available_space,
596 request_layout,
597 };
598 layout_id
599 }
600 _ => panic!("cannot measure after painting"),
601 };
602
603 window.layout_bounds(layout_id).size
604 }
605}
606
607impl<E> ElementObject for Drawable<E>
608where
609 E: Element,
610 E::RequestLayoutState: 'static,
611{
612 fn inner_element(&mut self) -> &mut dyn Any {
613 &mut self.element
614 }
615
616 #[inline]
617 fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
618 Drawable::request_layout(self, window, cx)
619 }
620
621 #[inline]
622 fn prepaint(&mut self, window: &mut Window, cx: &mut App) {
623 Drawable::prepaint(self, window, cx);
624 }
625
626 #[inline]
627 fn paint(&mut self, window: &mut Window, cx: &mut App) {
628 Drawable::paint(self, window, cx);
629 }
630
631 #[inline]
632 fn layout_as_root(
633 &mut self,
634 available_space: Size<AvailableSpace>,
635 window: &mut Window,
636 cx: &mut App,
637 ) -> Size<Pixels> {
638 Drawable::layout_as_root(self, available_space, window, cx)
639 }
640}
641
642pub struct AnyElement(ArenaBox<dyn ElementObject>);
644
645impl AnyElement {
646 pub(crate) fn new<E>(element: E) -> Self
647 where
648 E: 'static + Element,
649 E::RequestLayoutState: Any,
650 {
651 let element = with_element_arena(|arena| arena.alloc(|| Drawable::new(element)))
652 .map(|element| element as &mut dyn ElementObject);
653 AnyElement(element)
654 }
655
656 pub fn downcast_mut<T: 'static>(&mut self) -> Option<&mut T> {
658 self.0.inner_element().downcast_mut::<T>()
659 }
660
661 pub fn request_layout(&mut self, window: &mut Window, cx: &mut App) -> LayoutId {
664 self.0.request_layout(window, cx)
665 }
666
667 pub fn prepaint(&mut self, window: &mut Window, cx: &mut App) -> Option<FocusHandle> {
670 let focus_assigned = window.next_frame.focus.is_some();
671
672 self.0.prepaint(window, cx);
673
674 if !focus_assigned && let Some(focus_id) = window.next_frame.focus {
675 return FocusHandle::for_id(focus_id, &cx.focus_handles);
676 }
677
678 None
679 }
680
681 pub fn paint(&mut self, window: &mut Window, cx: &mut App) {
683 self.0.paint(window, cx);
684 }
685
686 pub fn layout_as_root(
688 &mut self,
689 available_space: Size<AvailableSpace>,
690 window: &mut Window,
691 cx: &mut App,
692 ) -> Size<Pixels> {
693 self.0.layout_as_root(available_space, window, cx)
694 }
695
696 pub fn prepaint_at(
699 &mut self,
700 origin: Point<Pixels>,
701 window: &mut Window,
702 cx: &mut App,
703 ) -> Option<FocusHandle> {
704 window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
705 }
706
707 pub fn prepaint_as_root(
710 &mut self,
711 origin: Point<Pixels>,
712 available_space: Size<AvailableSpace>,
713 window: &mut Window,
714 cx: &mut App,
715 ) -> Option<FocusHandle> {
716 self.layout_as_root(available_space, window, cx);
717 window.with_absolute_element_offset(origin, |window| self.prepaint(window, cx))
718 }
719}
720
721impl Element for AnyElement {
722 type RequestLayoutState = ();
723 type PrepaintState = ();
724
725 fn id(&self) -> Option<ElementId> {
726 None
727 }
728
729 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
730 None
731 }
732
733 fn request_layout(
734 &mut self,
735 _: Option<&GlobalElementId>,
736 _inspector_id: Option<&InspectorElementId>,
737 window: &mut Window,
738 cx: &mut App,
739 ) -> (LayoutId, Self::RequestLayoutState) {
740 let layout_id = self.request_layout(window, cx);
741 (layout_id, ())
742 }
743
744 fn prepaint(
745 &mut self,
746 _: Option<&GlobalElementId>,
747 _inspector_id: Option<&InspectorElementId>,
748 _: Bounds<Pixels>,
749 _: &mut Self::RequestLayoutState,
750 window: &mut Window,
751 cx: &mut App,
752 ) {
753 self.prepaint(window, cx);
754 }
755
756 fn paint(
757 &mut self,
758 _: Option<&GlobalElementId>,
759 _inspector_id: Option<&InspectorElementId>,
760 _: Bounds<Pixels>,
761 _: &mut Self::RequestLayoutState,
762 _: &mut Self::PrepaintState,
763 window: &mut Window,
764 cx: &mut App,
765 ) {
766 self.paint(window, cx);
767 }
768}
769
770impl IntoElement for AnyElement {
771 type Element = Self;
772
773 fn into_element(self) -> Self::Element {
774 self
775 }
776
777 fn into_any_element(self) -> AnyElement {
778 self
779 }
780}
781
782pub struct Empty;
784
785impl IntoElement for Empty {
786 type Element = Self;
787
788 fn into_element(self) -> Self::Element {
789 self
790 }
791}
792
793impl Element for Empty {
794 type RequestLayoutState = ();
795 type PrepaintState = ();
796
797 fn id(&self) -> Option<ElementId> {
798 None
799 }
800
801 fn source_location(&self) -> Option<&'static panic::Location<'static>> {
802 None
803 }
804
805 fn request_layout(
806 &mut self,
807 _id: Option<&GlobalElementId>,
808 _inspector_id: Option<&InspectorElementId>,
809 window: &mut Window,
810 cx: &mut App,
811 ) -> (LayoutId, Self::RequestLayoutState) {
812 (
813 window.request_layout(
814 Style {
815 display: crate::Display::None,
816 ..Default::default()
817 },
818 None,
819 cx,
820 ),
821 (),
822 )
823 }
824
825 fn prepaint(
826 &mut self,
827 _id: Option<&GlobalElementId>,
828 _inspector_id: Option<&InspectorElementId>,
829 _bounds: Bounds<Pixels>,
830 _state: &mut Self::RequestLayoutState,
831 _window: &mut Window,
832 _cx: &mut App,
833 ) {
834 }
835
836 fn paint(
837 &mut self,
838 _id: Option<&GlobalElementId>,
839 _inspector_id: Option<&InspectorElementId>,
840 _bounds: Bounds<Pixels>,
841 _request_layout: &mut Self::RequestLayoutState,
842 _prepaint: &mut Self::PrepaintState,
843 _window: &mut Window,
844 _cx: &mut App,
845 ) {
846 }
847}