1use std::any::{Any, TypeId};
8use std::fmt::{self, Debug};
9use std::hash::Hash;
10use std::panic::Location;
11use std::rc::Rc;
12
13use waft_foundation::{App, DiagnosticsNode, Handle, describe_enum};
14use waft_rendering::{
15 AnyRenderObject, ErasedRenderObject, PipelineOwner, RenderHandle, RenderObject,
16};
17
18use crate::framework::{
19 AnyElement, CreationLocation, Element, ElementData, IntoWidget, KeyRef, RenderObjectElement,
20 RenderObjectElementData, RenderObjectElementWidget, RenderObjectWidget, Slot, Widget,
21 WidgetKind, WidgetRef, downcast_widget, short_type_name,
22};
23
24pub trait SlotValue: Clone + Eq + Hash + Debug + 'static {}
27
28impl<T: Clone + Eq + Hash + Debug + 'static> SlotValue for T {}
29
30pub trait SlottedMultiChildRenderObjectWidget: RenderObjectWidget
46where
47 Self::RenderObject: SlottedContainerRenderObjectMixin<Self::Slot>,
48{
49 type Slot: SlotValue;
51
52 fn slots(&self) -> Vec<Self::Slot>;
56
57 fn child_for_slot(&self, slot: &Self::Slot) -> Option<WidgetRef>;
61}
62
63pub struct SlottedMultiChildRenderObjectKind;
65
66pub struct SlottedMultiChildRenderObject<W: SlottedMultiChildRenderObjectWidget>(
68 pub W,
69 pub(crate) CreationLocation,
70)
71where
72 W::RenderObject: SlottedContainerRenderObjectMixin<W::Slot>;
73
74impl<W: SlottedMultiChildRenderObjectWidget> IntoWidget<SlottedMultiChildRenderObjectKind> for W
75where
76 W::RenderObject: SlottedContainerRenderObjectMixin<W::Slot>,
77{
78 #[cfg_attr(debug_assertions, track_caller)]
79 fn into_widget(self) -> WidgetRef {
80 if cfg!(debug_assertions) {
81 RenderObjectWidget::debug_check_constructor(&self);
82 }
83 Rc::new(SlottedMultiChildRenderObject(
84 self,
85 CreationLocation::of_caller(),
86 ))
87 }
88}
89
90impl<W: SlottedMultiChildRenderObjectWidget> Widget for SlottedMultiChildRenderObject<W>
91where
92 W::RenderObject: SlottedContainerRenderObjectMixin<W::Slot>,
93{
94 fn key(&self) -> Option<&KeyRef> {
95 self.0.key()
96 }
97
98 fn creation_location(&self) -> Option<&'static Location<'static>> {
99 self.1.location()
100 }
101
102 fn create_element(&self, app: &mut App, this: WidgetRef) -> AnyElement {
103 SlottedRenderObjectElement::<W>::new(app, this).as_element()
104 }
105
106 fn as_any(&self) -> &dyn Any {
107 &self.0
108 }
109
110 fn widget_type(&self) -> TypeId {
111 TypeId::of::<W>()
112 }
113
114 fn type_name(&self) -> &'static str {
115 short_type_name::<W>()
116 }
117
118 fn kind(&self) -> WidgetKind {
119 WidgetKind::Other
120 }
121}
122
123impl<W: SlottedMultiChildRenderObjectWidget> Debug for SlottedMultiChildRenderObject<W>
124where
125 W::RenderObject: SlottedContainerRenderObjectMixin<W::Slot>,
126{
127 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
128 self.0.fmt(f)
129 }
130}
131
132pub struct SlottedContainerRenderObjectData<S, C> {
135 slot_to_child: Vec<(S, C)>,
136}
137
138impl<S, C> SlottedContainerRenderObjectData<S, C> {
139 pub fn new() -> SlottedContainerRenderObjectData<S, C> {
141 SlottedContainerRenderObjectData {
142 slot_to_child: Vec::new(),
143 }
144 }
145}
146
147impl<S, C> Default for SlottedContainerRenderObjectData<S, C> {
148 fn default() -> SlottedContainerRenderObjectData<S, C> {
149 SlottedContainerRenderObjectData::new()
150 }
151}
152
153fn slot_name(slot: &impl Debug) -> String {
157 let description = format!("{slot:?}");
158 let is_bare_name = description
159 .chars()
160 .all(|character| character.is_alphanumeric() || character == '_');
161 if is_bare_name {
162 describe_enum(slot)
163 } else {
164 description
165 }
166}
167
168pub trait SlottedContainerRenderObjectMixin<S: SlotValue>: RenderObject {
177 type ChildType: ErasedRenderObject;
179
180 fn slotted_container_data(
182 self: RenderHandle<Self>,
183 app: &App,
184 ) -> &SlottedContainerRenderObjectData<S, Self::ChildType>;
185
186 fn slotted_container_data_mut(
188 self: RenderHandle<Self>,
189 app: &mut App,
190 ) -> &mut SlottedContainerRenderObjectData<S, Self::ChildType>;
191
192 fn child_for_slot(self: RenderHandle<Self>, app: &App, slot: &S) -> Option<Self::ChildType> {
196 self.slotted_container_data(app)
197 .slot_to_child
198 .iter()
199 .find(|(child_slot, _)| child_slot == slot)
200 .map(|(_, child)| *child)
201 }
202
203 fn children(self: RenderHandle<Self>, app: &App) -> Vec<Self::ChildType> {
207 self.slotted_container_data(app)
208 .slot_to_child
209 .iter()
210 .map(|(_, child)| *child)
211 .collect()
212 }
213
214 fn debug_name_for_slot(&self, slot: &S) -> String {
219 slot_name(slot)
220 }
221
222 fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
224 for child in self.children(app) {
225 child.as_object().attach(app, owner);
226 }
227 }
228
229 fn did_detach(self: RenderHandle<Self>, app: &mut App) {
231 for child in self.children(app) {
232 child.as_object().detach(app);
233 }
234 }
235
236 fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
238 for child in self.children(app) {
239 self.as_render_object(app)
240 .redepth_child(app, child.as_object());
241 }
242 }
243
244 fn visit_children(
246 self: RenderHandle<Self>,
247 app: &App,
248 visitor: &mut dyn FnMut(AnyRenderObject),
249 ) {
250 for child in self.children(app) {
251 visitor(child.as_object());
252 }
253 }
254
255 fn debug_describe_children(
258 self: RenderHandle<Self>,
259 app: &App,
260 ) -> Vec<Rc<dyn DiagnosticsNode>> {
261 let mut nodes: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
262 for child in self.children(app) {
263 let slot = self
264 .slotted_container_data(app)
265 .slot_to_child
266 .iter()
267 .find(|(_, current)| *current == child)
268 .map(|(slot, _)| slot.clone())
269 .expect("every child occupies a slot");
270 let name = SlottedContainerRenderObjectMixin::debug_name_for_slot(self.get(app), &slot);
271 nodes.push(Rc::new(child.as_object().to_diagnostics_node(app, name)));
272 }
273 nodes
274 }
275
276 fn set_child(
278 self: RenderHandle<Self>,
279 app: &mut App,
280 child: Option<Self::ChildType>,
281 slot: &S,
282 ) {
283 let old_child = self.child_for_slot(app, slot);
284 if let Some(old_child) = old_child {
285 self.as_render_object(app)
286 .drop_child(app, old_child.as_object());
287 self.slotted_container_data_mut(app)
288 .slot_to_child
289 .retain(|(child_slot, _)| child_slot != slot);
290 }
291 if let Some(child) = child {
292 self.slotted_container_data_mut(app)
293 .slot_to_child
294 .push((slot.clone(), child));
295 self.as_render_object(app)
296 .adopt_child(app, child.as_object());
297 }
298 }
299
300 fn move_child(
302 self: RenderHandle<Self>,
303 app: &mut App,
304 child: Self::ChildType,
305 slot: &S,
306 old_slot: &S,
307 ) {
308 debug_assert!(slot != old_slot);
309 let old_child = self.child_for_slot(app, old_slot);
310 if old_child == Some(child) {
311 self.set_child(app, None, old_slot);
312 }
313 self.set_child(app, Some(child), slot);
314 }
315}
316
317pub struct SlottedRenderObjectElement<W: SlottedMultiChildRenderObjectWidget>
325where
326 W::RenderObject: SlottedContainerRenderObjectMixin<W::Slot>,
327{
328 element: ElementData,
329 render_object_element: RenderObjectElementData,
330 slot_to_child: Vec<(W::Slot, AnyElement)>,
331 keyed_children: Vec<(KeyRef, AnyElement)>,
332 slot_objects: Vec<(W::Slot, Rc<dyn Any>)>,
333 debug_previous_slots: Option<Vec<W::Slot>>,
334}
335
336impl<W: SlottedMultiChildRenderObjectWidget> SlottedRenderObjectElement<W>
337where
338 W::RenderObject: SlottedContainerRenderObjectMixin<W::Slot>,
339{
340 pub fn new(app: &mut App, widget: WidgetRef) -> Handle<Self> {
342 debug_assert!(downcast_widget::<W>(&*widget).is_some());
343 app.create(SlottedRenderObjectElement::<W> {
344 element: ElementData::new(widget),
345 render_object_element: RenderObjectElementData::default(),
346 slot_to_child: Vec::new(),
347 keyed_children: Vec::new(),
348 slot_objects: Vec::new(),
349 debug_previous_slots: None,
350 })
351 .into_tree_node(app)
352 }
353
354 fn element_slot(self: Handle<Self>, app: &mut App, slot: &W::Slot) -> Slot {
356 if let Some((_, object)) = app
357 .get(self)
358 .slot_objects
359 .iter()
360 .find(|(slot_value, _)| slot_value == slot)
361 {
362 return Slot::Custom(Rc::clone(object));
363 }
364 let object: Rc<dyn Any> = Rc::new(slot.clone());
365 app.get_mut(self)
366 .slot_objects
367 .push((slot.clone(), Rc::clone(&object)));
368 Slot::Custom(object)
369 }
370
371 fn slot_value(slot: Option<&Slot>) -> &W::Slot {
373 match slot {
374 Some(Slot::Custom(object)) => object
375 .downcast_ref::<W::Slot>()
376 .expect("a slotted element gives its children slots of its slot type"),
377 _ => unreachable!("a slotted element gives its children custom slots"),
378 }
379 }
380
381 fn typed(self: Handle<Self>, app: &App) -> RenderHandle<W::RenderObject> {
382 self.typed_render_object(app)
383 }
384
385 fn update_children(self: Handle<Self>, app: &mut App) {
387 let widget = self.as_element().widget(app).clone();
388 let slotted = Self::widget_of(&widget);
389 let slots = slotted.slots();
390 if cfg!(debug_assertions) {
391 let previous = app
392 .get_mut(self)
393 .debug_previous_slots
394 .get_or_insert_with(|| slots.clone());
395 assert!(
396 *previous == slots,
397 "{}.slots must not change.",
398 std::any::type_name::<W>()
399 );
400 }
401 debug_assert!(
402 slots.iter().collect::<std::collections::HashSet<_>>().len() == slots.len(),
403 "slots must be unique"
404 );
405
406 let old_keyed_elements = std::mem::take(&mut app.get_mut(self).keyed_children);
407 let mut old_slot_to_child = std::mem::take(&mut app.get_mut(self).slot_to_child);
408 let mut debug_duplicate_keys: Vec<(KeyRef, Vec<AnyElement>)> = Vec::new();
410
411 for slot in &slots {
412 let widget = slotted.child_for_slot(slot);
413 let new_widget_key = widget.as_ref().and_then(|widget| widget.key().cloned());
414 let old_slot_child = old_slot_to_child
415 .iter()
416 .find(|(old_slot, _)| old_slot == slot)
417 .map(|(_, child)| *child);
418 let old_key_child = new_widget_key.as_ref().and_then(|key| {
419 old_keyed_elements
420 .iter()
421 .find(|(old_key, _)| old_key == key)
422 .map(|(_, child)| *child)
423 });
424 let from_element = if let Some(old_key_child) = old_key_child {
427 let old_key_slot = Self::slot_value(old_key_child.slot(app).as_ref()).clone();
428 take_slot(&mut old_slot_to_child, &old_key_slot)
429 } else if old_slot_child.is_none_or(|child| child.widget(app).key().is_none()) {
430 take_slot(&mut old_slot_to_child, slot)
431 } else {
432 debug_assert!(!crate::framework::keys_equal(
434 old_slot_child.and_then(|child| child.widget(app).key()),
435 new_widget_key.as_ref()
436 ));
437 None
438 };
439 let element_slot = self.element_slot(app, slot);
440 let new_child =
441 self.as_element()
442 .update_child(app, from_element, widget, Some(element_slot));
443 if let Some(new_child) = new_child {
444 app.get_mut(self)
445 .slot_to_child
446 .push((slot.clone(), new_child));
447 if let Some(new_widget_key) = new_widget_key {
448 let keyed_children = &mut app.get_mut(self).keyed_children;
449 let existing = keyed_children
450 .iter()
451 .position(|(key, _)| *key == new_widget_key);
452 if cfg!(debug_assertions)
453 && let Some(index) = existing
454 {
455 let existing_element = keyed_children[index].1;
456 match debug_duplicate_keys
457 .iter_mut()
458 .find(|(key, _)| *key == new_widget_key)
459 {
460 Some((_, elements)) => elements.push(new_child),
461 None => debug_duplicate_keys
462 .push((new_widget_key.clone(), vec![existing_element, new_child])),
463 }
464 }
465 match existing {
467 Some(index) => keyed_children[index].1 = new_child,
468 None => keyed_children.push((new_widget_key, new_child)),
469 }
470 }
471 }
472 }
473 for (_, child) in old_slot_to_child {
474 self.as_element().deactivate_child(app, child);
475 }
476 Self::debug_duplicate_keys(&debug_duplicate_keys);
477 debug_assert!(
478 app.get(self).keyed_children.iter().all(|(_, keyed)| app
479 .get(self)
480 .slot_to_child
481 .iter()
482 .any(|(_, child)| child == keyed)),
483 "_keyedChildren should be a subset of _slotToChild"
484 );
485 }
486}
487
488impl<W: SlottedMultiChildRenderObjectWidget> SlottedRenderObjectElement<W>
489where
490 W::RenderObject: SlottedContainerRenderObjectMixin<W::Slot>,
491{
492 fn debug_duplicate_keys(debug_duplicate_keys: &[(KeyRef, Vec<AnyElement>)]) {
495 if let Some((key, elements)) = debug_duplicate_keys.first() {
496 let offending: String = elements
497 .iter()
498 .map(|element| format!(" - {element:?}\n"))
499 .collect();
500 panic!(
501 "Multiple widgets used the same key in {}.\nThe key {:?} was used by multiple \
502 widgets. The offending widgets were:\n{offending}A key can only be specified on \
503 one widget at a time in the same parent widget.",
504 std::any::type_name::<W>(),
505 key
506 );
507 }
508 }
509}
510
511fn take_slot<S: PartialEq>(slots: &mut Vec<(S, AnyElement)>, slot: &S) -> Option<AnyElement> {
513 let index = slots.iter().position(|(old_slot, _)| old_slot == slot)?;
514 Some(slots.remove(index).1)
515}
516
517impl<W: SlottedMultiChildRenderObjectWidget> RenderObjectElementWidget
518 for SlottedRenderObjectElement<W>
519where
520 W::RenderObject: SlottedContainerRenderObjectMixin<W::Slot>,
521{
522 type Widget = W;
523
524 fn widget_of(widget: &WidgetRef) -> &W {
525 downcast_widget::<W>(&**widget)
526 .expect("a SlottedRenderObjectElement holds its SlottedMultiChildRenderObjectWidget")
527 }
528}
529
530impl<W: SlottedMultiChildRenderObjectWidget> RenderObjectElement for SlottedRenderObjectElement<W>
531where
532 W::RenderObject: SlottedContainerRenderObjectMixin<W::Slot>,
533{
534 fn render_object_element_data(self: Handle<Self>, app: &App) -> &RenderObjectElementData {
535 &app.get(self).render_object_element
536 }
537
538 fn render_object_element_data_mut(
539 self: Handle<Self>,
540 app: &mut App,
541 ) -> &mut RenderObjectElementData {
542 &mut app.get_mut(self).render_object_element
543 }
544}
545
546impl<W: SlottedMultiChildRenderObjectWidget> Element for SlottedRenderObjectElement<W>
547where
548 W::RenderObject: SlottedContainerRenderObjectMixin<W::Slot>,
549{
550 crate::element_accessors!();
551
552 fn render_object(self: Handle<Self>, app: &App) -> Option<AnyRenderObject> {
553 self.render_object_element_data(app).render_object()
554 }
555
556 fn render_object_attaching_child(self: Handle<Self>, _app: &App) -> Option<AnyElement> {
557 None
558 }
559
560 fn debug_doing_build(self: Handle<Self>, app: &App) -> bool {
561 self.render_object_element_data(app).debug_doing_build()
562 }
563
564 const IS_RENDER_OBJECT_ELEMENT: bool = true;
565
566 fn perform_rebuild(self: Handle<Self>, app: &mut App) {
567 RenderObjectElement::perform_rebuild(self, app);
568 }
569
570 fn deactivate(self: Handle<Self>, app: &mut App) {
571 RenderObjectElement::deactivate(self, app);
572 }
573
574 fn unmount(self: Handle<Self>, app: &mut App) {
575 RenderObjectElement::unmount(self, app);
576 }
577
578 fn update_parent_data(self: Handle<Self>, app: &mut App, parent_data_element: AnyElement) {
579 RenderObjectElement::update_parent_data(self, app, parent_data_element);
580 }
581
582 fn update_slot(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
583 RenderObjectElement::update_slot(self, app, new_slot);
584 }
585
586 fn attach_render_object(self: Handle<Self>, app: &mut App, new_slot: Option<Slot>) {
587 RenderObjectElement::attach_render_object(self, app, new_slot);
588 }
589
590 fn detach_render_object(self: Handle<Self>, app: &mut App) {
591 RenderObjectElement::detach_render_object(self, app);
592 }
593
594 fn visit_children(self: Handle<Self>, app: &App, visitor: &mut dyn FnMut(AnyElement)) {
595 for (_, child) in &app.get(self).slot_to_child {
596 visitor(*child);
597 }
598 }
599
600 fn forget_child(self: Handle<Self>, app: &mut App, child: AnyElement) {
601 debug_assert!(app.get(self).slot_to_child.iter().any(|(_, c)| *c == child));
602 let slot = Self::slot_value(child.slot(app).as_ref()).clone();
603 let removed = take_slot(&mut app.get_mut(self).slot_to_child, &slot);
604 debug_assert!(removed.is_some());
605 }
606
607 fn mount(
608 self: Handle<Self>,
609 app: &mut App,
610 parent: Option<AnyElement>,
611 new_slot: Option<Slot>,
612 ) {
613 RenderObjectElement::mount(self, app, parent, new_slot);
614 self.update_children(app);
615 }
616
617 fn update(self: Handle<Self>, app: &mut App, new_widget: WidgetRef) {
618 RenderObjectElement::update(self, app, new_widget.clone());
619 debug_assert!(crate::framework::same_widget(
620 self.as_element().widget(app),
621 &new_widget
622 ));
623 self.update_children(app);
624 }
625
626 fn insert_render_object_child(
627 self: Handle<Self>,
628 app: &mut App,
629 child: AnyRenderObject,
630 slot: Option<Slot>,
631 ) {
632 let slot = Self::slot_value(slot.as_ref()).clone();
633 let render_object = self.typed(app);
634 let child = ErasedRenderObject::from_object(child);
635 render_object.set_child(app, Some(child), &slot);
636 debug_assert!(render_object.child_for_slot(app, &slot) == Some(child));
637 }
638
639 fn move_render_object_child(
640 self: Handle<Self>,
641 app: &mut App,
642 child: AnyRenderObject,
643 old_slot: Option<Slot>,
644 new_slot: Option<Slot>,
645 ) {
646 let old_slot = Self::slot_value(old_slot.as_ref()).clone();
647 let new_slot = Self::slot_value(new_slot.as_ref()).clone();
648 let render_object = self.typed(app);
649 render_object.move_child(
650 app,
651 ErasedRenderObject::from_object(child),
652 &new_slot,
653 &old_slot,
654 );
655 }
656
657 fn remove_render_object_child(
658 self: Handle<Self>,
659 app: &mut App,
660 child: AnyRenderObject,
661 slot: Option<Slot>,
662 ) {
663 let slot = Self::slot_value(slot.as_ref()).clone();
664 let render_object = self.typed(app);
665 if render_object.child_for_slot(app, &slot) == Some(ErasedRenderObject::from_object(child))
666 {
667 render_object.set_child(app, None, &slot);
668 debug_assert!(render_object.child_for_slot(app, &slot).is_none());
669 }
670 }
671}
672
673#[cfg(test)]
674mod tests {
675 use waft_embedder::{Offset, Size};
676 use waft_foundation::{AppCell, DiagnosticLevel, ValueKey};
677 use waft_rendering::{
678 AnyRenderBox, BoxConstraints, BoxParentData, PaintingContext, RenderBox, RenderBoxData,
679 RenderObjectData,
680 };
681
682 use super::*;
683 use crate::framework::BuildContext;
684 use crate::test_harness::Harness;
685 use crate::widgets::basic::{Center, SizedBox};
686
687 #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
689 enum DiagonalSlot {
690 Null,
691 TopLeft,
692 BottomRight,
693 }
694
695 #[derive(Debug, Default)]
697 struct Diagonal {
698 top_left: Option<WidgetRef>,
699 bottom_right: Option<WidgetRef>,
700 null_slot: Option<WidgetRef>,
701 }
702
703 impl RenderObjectWidget for Diagonal {
704 type RenderObject = RenderDiagonal;
705
706 fn create_render_object(&self, app: &mut App, _context: BuildContext) -> AnyRenderObject {
707 RenderHandle::new_box(
708 app,
709 RenderDiagonal {
710 render_object: RenderObjectData::new(),
711 render_box: RenderBoxData::new(),
712 slotted: SlottedContainerRenderObjectData::new(),
713 },
714 )
715 .as_object()
716 }
717 }
718
719 impl SlottedMultiChildRenderObjectWidget for Diagonal {
720 type Slot = DiagonalSlot;
721
722 fn slots(&self) -> Vec<DiagonalSlot> {
723 vec![
724 DiagonalSlot::Null,
725 DiagonalSlot::TopLeft,
726 DiagonalSlot::BottomRight,
727 ]
728 }
729
730 fn child_for_slot(&self, slot: &DiagonalSlot) -> Option<WidgetRef> {
731 match slot {
732 DiagonalSlot::Null => self.null_slot.clone(),
733 DiagonalSlot::TopLeft => self.top_left.clone(),
734 DiagonalSlot::BottomRight => self.bottom_right.clone(),
735 }
736 }
737 }
738
739 struct RenderDiagonal {
741 render_object: RenderObjectData,
742 render_box: RenderBoxData,
743 slotted: SlottedContainerRenderObjectData<DiagonalSlot, AnyRenderBox>,
744 }
745
746 impl SlottedContainerRenderObjectMixin<DiagonalSlot> for RenderDiagonal {
747 type ChildType = AnyRenderBox;
748
749 fn slotted_container_data(
750 self: RenderHandle<Self>,
751 app: &App,
752 ) -> &SlottedContainerRenderObjectData<DiagonalSlot, AnyRenderBox> {
753 &self.get(app).slotted
754 }
755
756 fn slotted_container_data_mut(
757 self: RenderHandle<Self>,
758 app: &mut App,
759 ) -> &mut SlottedContainerRenderObjectData<DiagonalSlot, AnyRenderBox> {
760 &mut self.get_mut(app).slotted
761 }
762 }
763
764 impl RenderDiagonal {
765 fn lay_out(app: &mut App, child: Option<AnyRenderBox>, offset: Offset) -> Size {
766 let Some(child) = child else {
767 return Size::ZERO;
768 };
769 child.layout(app, BoxConstraints::new(), true);
770 child
771 .as_object()
772 .parent_data_of_mut::<BoxParentData>(app)
773 .offset = offset;
774 child.size(app)
775 }
776 }
777
778 impl RenderObject for RenderDiagonal {
779 waft_rendering::render_object_accessors!();
780
781 fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
782 SlottedContainerRenderObjectMixin::did_attach(self, app, owner);
783 }
784
785 fn did_detach(self: RenderHandle<Self>, app: &mut App) {
786 SlottedContainerRenderObjectMixin::did_detach(self, app);
787 }
788
789 fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
790 SlottedContainerRenderObjectMixin::redepth_children(self, app);
791 }
792
793 fn visit_children(
794 self: RenderHandle<Self>,
795 app: &App,
796 visitor: &mut dyn FnMut(AnyRenderObject),
797 ) {
798 SlottedContainerRenderObjectMixin::visit_children(self, app, visitor);
799 }
800
801 fn debug_describe_children(
802 self: RenderHandle<Self>,
803 app: &App,
804 ) -> Vec<Rc<dyn DiagnosticsNode>> {
805 SlottedContainerRenderObjectMixin::debug_describe_children(self, app)
806 }
807
808 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
809 let top_left = self.child_for_slot(app, &DiagonalSlot::TopLeft);
810 let top_left_size = RenderDiagonal::lay_out(app, top_left, Offset::ZERO);
811 let bottom_right = self.child_for_slot(app, &DiagonalSlot::BottomRight);
812 let bottom_right_size = RenderDiagonal::lay_out(
813 app,
814 bottom_right,
815 Offset::new(top_left_size.width(), top_left_size.height()),
816 );
817 let null_slot = self.child_for_slot(app, &DiagonalSlot::Null);
818 let null_slot_size = RenderDiagonal::lay_out(app, null_slot, Offset::ZERO);
819 let size = self.constraints(app).constrain(Size::new(
820 top_left_size.width() + bottom_right_size.width() + null_slot_size.width(),
821 top_left_size.height() + bottom_right_size.height() + null_slot_size.height(),
822 ));
823 self.set_size(app, size);
824 }
825
826 fn paint(
827 self: RenderHandle<Self>,
828 app: &mut App,
829 context: &mut PaintingContext,
830 offset: Offset,
831 ) {
832 for slot in [DiagonalSlot::TopLeft, DiagonalSlot::BottomRight] {
833 if let Some(child) = self.child_for_slot(app, &slot) {
834 let child_offset = child
835 .as_object()
836 .parent_data_of::<BoxParentData>(app)
837 .offset;
838 context.paint_child(app, child.as_object(), child_offset + offset);
839 }
840 }
841 }
842 }
843
844 impl RenderBox for RenderDiagonal {
845 waft_rendering::render_box_accessors!();
846
847 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
848 if !child.parent_data_is::<BoxParentData>(app) {
849 child.set_parent_data(app, BoxParentData::new());
850 }
851 }
852 }
853
854 fn sized(width: f64, height: f64) -> WidgetRef {
855 SizedBox::new().width(width).height(height).into_widget()
856 }
857
858 fn keyed(key: &str, width: f64, height: f64) -> WidgetRef {
859 SizedBox::new()
860 .key(ValueKey::new(key.to_owned()).into())
861 .width(width)
862 .height(height)
863 .into_widget()
864 }
865
866 fn diagonal(app: &App, harness: &Harness) -> RenderHandle<RenderDiagonal> {
867 let center = harness.render_root(app).child(app).expect("the centre");
868 let mut found = None;
869 center
870 .as_object()
871 .visit_children(app, &mut |child| found = Some(child));
872 found
873 .expect("the diagonal")
874 .downcast::<RenderDiagonal>(app)
875 .expect("a RenderDiagonal")
876 }
877
878 fn mount_diagonal(
879 app: &mut App,
880 harness: Option<&Harness>,
881 widget: Diagonal,
882 ) -> Option<Harness> {
883 let tree = Center::new().child(widget).into_widget();
884 match harness {
885 Some(harness) => {
886 harness.set_child(app, tree);
887 harness.pump(app);
888 None
889 }
890 None => {
891 let harness = Harness::mount(app, tree);
892 harness.pump(app);
893 Some(harness)
894 }
895 }
896 }
897
898 #[test]
901 fn slotted_children_lay_out_update_and_leave_their_slots() {
902 let cell = AppCell::new();
903 let mut app = cell.borrow_mut();
904 let harness = mount_diagonal(
905 &mut app,
906 None,
907 Diagonal {
908 top_left: Some(sized(40.0, 50.0)),
909 bottom_right: Some(sized(55.0, 60.0)),
910 null_slot: None,
911 },
912 )
913 .expect("mounted");
914 let render = diagonal(&app, &harness);
915 assert_eq!(render.size(&app), Size::new(40.0 + 55.0, 50.0 + 60.0));
916 let bottom_right = render
917 .child_for_slot(&app, &DiagonalSlot::BottomRight)
918 .expect("a bottom right child");
919 assert_eq!(
920 bottom_right
921 .as_object()
922 .parent_data_of::<BoxParentData>(&app)
923 .offset,
924 Offset::new(40.0, 50.0)
925 );
926
927 mount_diagonal(
929 &mut app,
930 Some(&harness),
931 Diagonal {
932 top_left: Some(sized(50.0, 60.0)),
933 bottom_right: Some(sized(110.0, 70.0)),
934 null_slot: None,
935 },
936 );
937 assert_eq!(render.size(&app), Size::new(50.0 + 110.0, 60.0 + 70.0));
938 assert_eq!(
939 render.child_for_slot(&app, &DiagonalSlot::BottomRight),
940 Some(bottom_right)
941 );
942
943 mount_diagonal(
944 &mut app,
945 Some(&harness),
946 Diagonal {
947 top_left: Some(sized(50.0, 60.0)),
948 bottom_right: Some(keyed("new", 110.0, 70.0)),
949 null_slot: None,
950 },
951 );
952 assert_eq!(render.size(&app), Size::new(50.0 + 110.0, 60.0 + 70.0));
953 assert_ne!(
954 render.child_for_slot(&app, &DiagonalSlot::BottomRight),
955 Some(bottom_right),
956 "a newly keyed child replaces the unkeyed one"
957 );
958
959 mount_diagonal(
960 &mut app,
961 Some(&harness),
962 Diagonal {
963 top_left: Some(sized(50.0, 60.0)),
964 ..Diagonal::default()
965 },
966 );
967 assert_eq!(render.size(&app), Size::new(50.0, 60.0));
968 assert_eq!(render.children(&app).len(), 1);
969
970 mount_diagonal(&mut app, Some(&harness), Diagonal::default());
971 assert_eq!(render.size(&app), Size::ZERO);
972 assert!(render.children(&app).is_empty());
973 }
974
975 #[test]
977 fn an_enum_slot_is_named_as_darts_enum_name() {
978 let cell = AppCell::new();
979 let mut app = cell.borrow_mut();
980 let render = RenderHandle::new_box(
981 &mut app,
982 RenderDiagonal {
983 render_object: RenderObjectData::new(),
984 render_box: RenderBoxData::new(),
985 slotted: SlottedContainerRenderObjectData::new(),
986 },
987 );
988 let render = render.get(&app);
989 assert_eq!(
990 render.debug_name_for_slot(&DiagonalSlot::BottomRight),
991 "bottomRight"
992 );
993 assert_eq!(
994 render.debug_name_for_slot(&DiagonalSlot::TopLeft),
995 "topLeft"
996 );
997 }
998
999 #[test]
1002 fn a_slotted_dump_names_children_by_their_slots() {
1003 let cell = AppCell::new();
1004 let mut app = cell.borrow_mut();
1005 let harness = mount_diagonal(
1006 &mut app,
1007 None,
1008 Diagonal {
1009 top_left: Some(sized(80.0, 100.0)),
1010 bottom_right: Some(sized(110.0, 120.0)),
1011 null_slot: None,
1012 },
1013 )
1014 .expect("mounted");
1015 let render = diagonal(&app, &harness);
1016
1017 let dump = render
1018 .as_object()
1019 .to_string_deep_with(&app, DiagnosticLevel::Info);
1020 assert!(
1021 dump.lines()
1022 .any(|line| line.contains("topLeft: RenderConstrainedBox#")),
1023 "{dump}"
1024 );
1025 assert!(
1026 dump.lines()
1027 .any(|line| line.contains("bottomRight: RenderConstrainedBox#")),
1028 "{dump}"
1029 );
1030 assert!(!dump.contains("child 1"), "{dump}");
1031 }
1032
1033 #[test]
1035 fn keyed_children_move_between_slots_with_their_render_objects() {
1036 let cell = AppCell::new();
1037 let mut app = cell.borrow_mut();
1038 let (small, big, null) = (
1039 keyed("smol", 10.0, 10.0),
1040 keyed("big", 100.0, 100.0),
1041 keyed("null", 50.0, 50.0),
1042 );
1043 let harness = mount_diagonal(
1044 &mut app,
1045 None,
1046 Diagonal {
1047 top_left: Some(small.clone()),
1048 bottom_right: Some(big.clone()),
1049 null_slot: Some(null.clone()),
1050 },
1051 )
1052 .expect("mounted");
1053 let render = diagonal(&app, &harness);
1054 let small_box = render
1055 .child_for_slot(&app, &DiagonalSlot::TopLeft)
1056 .expect("small");
1057 let big_box = render
1058 .child_for_slot(&app, &DiagonalSlot::BottomRight)
1059 .expect("big");
1060 let null_box = render
1061 .child_for_slot(&app, &DiagonalSlot::Null)
1062 .expect("null");
1063 assert_eq!(small_box.size(&app), Size::new(10.0, 10.0));
1064 assert_eq!(render.size(&app), Size::new(160.0, 160.0));
1065
1066 mount_diagonal(
1067 &mut app,
1068 Some(&harness),
1069 Diagonal {
1070 top_left: Some(big.clone()),
1071 bottom_right: Some(small.clone()),
1072 null_slot: Some(null.clone()),
1073 },
1074 );
1075 assert_eq!(
1076 render.child_for_slot(&app, &DiagonalSlot::TopLeft),
1077 Some(big_box)
1078 );
1079 assert_eq!(
1080 render.child_for_slot(&app, &DiagonalSlot::BottomRight),
1081 Some(small_box)
1082 );
1083 assert_eq!(
1084 render.child_for_slot(&app, &DiagonalSlot::Null),
1085 Some(null_box)
1086 );
1087 assert_eq!(
1088 small_box
1089 .as_object()
1090 .parent_data_of::<BoxParentData>(&app)
1091 .offset,
1092 Offset::new(100.0, 100.0)
1093 );
1094 assert_eq!(render.size(&app), Size::new(160.0, 160.0));
1095 let small_element = element_in(&app, &harness, DiagonalSlot::BottomRight);
1096 let big_element = element_in(&app, &harness, DiagonalSlot::TopLeft);
1097 let null_element = element_in(&app, &harness, DiagonalSlot::Null);
1098
1099 mount_diagonal(
1101 &mut app,
1102 Some(&harness),
1103 Diagonal {
1104 top_left: Some(null.clone()),
1105 bottom_right: Some(big.clone()),
1106 null_slot: Some(small.clone()),
1107 },
1108 );
1109 assert_eq!(
1110 render.child_for_slot(&app, &DiagonalSlot::TopLeft),
1111 Some(null_box)
1112 );
1113 assert_eq!(
1114 render.child_for_slot(&app, &DiagonalSlot::BottomRight),
1115 Some(big_box)
1116 );
1117 assert_eq!(
1118 render.child_for_slot(&app, &DiagonalSlot::Null),
1119 Some(small_box)
1120 );
1121 assert_eq!(
1122 element_in(&app, &harness, DiagonalSlot::TopLeft),
1123 null_element
1124 );
1125 assert_eq!(
1126 element_in(&app, &harness, DiagonalSlot::BottomRight),
1127 big_element
1128 );
1129 assert_eq!(
1130 element_in(&app, &harness, DiagonalSlot::Null),
1131 small_element
1132 );
1133
1134 mount_diagonal(
1136 &mut app,
1137 Some(&harness),
1138 Diagonal {
1139 bottom_right: Some(big.clone()),
1140 ..Diagonal::default()
1141 },
1142 );
1143 assert_eq!(render.child_for_slot(&app, &DiagonalSlot::TopLeft), None);
1144 assert_eq!(
1145 render.child_for_slot(&app, &DiagonalSlot::BottomRight),
1146 Some(big_box)
1147 );
1148 assert_eq!(render.child_for_slot(&app, &DiagonalSlot::Null), None);
1149 assert!(is_defunct(&app, small_element));
1150 assert!(is_defunct(&app, null_element));
1151 assert_eq!(
1152 element_in(&app, &harness, DiagonalSlot::BottomRight),
1153 big_element
1154 );
1155
1156 mount_diagonal(
1158 &mut app,
1159 Some(&harness),
1160 Diagonal {
1161 top_left: Some(big),
1162 ..Diagonal::default()
1163 },
1164 );
1165 assert_eq!(
1166 render.child_for_slot(&app, &DiagonalSlot::TopLeft),
1167 Some(big_box)
1168 );
1169 assert_eq!(
1170 render.child_for_slot(&app, &DiagonalSlot::BottomRight),
1171 None
1172 );
1173 assert_eq!(
1174 element_in(&app, &harness, DiagonalSlot::TopLeft),
1175 big_element
1176 );
1177 }
1178
1179 fn element_in(app: &App, harness: &Harness, slot: DiagonalSlot) -> AnyElement {
1181 fn find_diagonal(app: &App, element: AnyElement) -> Option<AnyElement> {
1182 if element.widget(app).widget_type() == TypeId::of::<Diagonal>() {
1183 return Some(element);
1184 }
1185 let mut found = None;
1186 element.visit_children(app, &mut |child| {
1187 if found.is_none() {
1188 found = find_diagonal(app, child);
1189 }
1190 });
1191 found
1192 }
1193 let diagonal =
1194 find_diagonal(app, harness.root.as_element()).expect("the diagonal is mounted");
1195 let mut found = None;
1196 diagonal.visit_children(app, &mut |child| {
1197 let child_slot = match child.slot(app) {
1198 Some(Slot::Custom(object)) => object.downcast_ref::<DiagonalSlot>().copied(),
1199 _ => None,
1200 };
1201 if child_slot == Some(slot) {
1202 found = Some(child);
1203 }
1204 });
1205 found.expect("a child in the slot")
1206 }
1207
1208 fn is_defunct(app: &App, element: AnyElement) -> bool {
1210 app.is_disposed(element.id()) || element.debug_is_defunct(app)
1211 }
1212
1213 #[test]
1216 #[should_panic(expected = "The offending widgets were:")]
1217 fn a_duplicated_key_panics_naming_every_element_that_used_it() {
1218 let cell = AppCell::new();
1219 let mut app = cell.borrow_mut();
1220 mount_diagonal(
1221 &mut app,
1222 None,
1223 Diagonal {
1224 top_left: Some(keyed("widget 1", 10.0, 10.0)),
1225 bottom_right: Some(keyed("widget 1", 100.0, 100.0)),
1226 null_slot: Some(keyed("widget 1", 50.0, 50.0)),
1227 },
1228 );
1229 }
1230
1231 #[test]
1235 fn slotted_children_paint_at_their_offsets_and_the_element_unmounts() {
1236 use crate::widgets::basic::ColoredBox;
1237 use waft_embedder::Color;
1238 use waft_embedder::valo::Op;
1239
1240 let yellow = Color::new(0xFFFFFF00);
1241 let green = Color::new(0xFF00FF00);
1242 let colored = |color: Color, width: f64, height: f64| {
1243 SizedBox::new()
1244 .width(width)
1245 .height(height)
1246 .child(ColoredBox::new(color))
1247 .into_widget()
1248 };
1249 let cell = AppCell::new();
1250 let mut app = cell.borrow_mut();
1251 let harness = mount_diagonal(
1252 &mut app,
1253 None,
1254 Diagonal {
1255 top_left: Some(colored(yellow, 40.0, 50.0)),
1256 bottom_right: Some(colored(green, 55.0, 60.0)),
1257 null_slot: None,
1258 },
1259 )
1260 .expect("mounted");
1261 let ops = scene_ops(&mut app, &harness);
1262 let rects: Vec<_> = ops
1263 .iter()
1264 .filter_map(|op| match op {
1265 Op::DrawRect { rect, paint, .. } => Some((*rect, paint.color)),
1266 _ => None,
1267 })
1268 .collect();
1269 let origin = diagonal_origin(&app, &harness);
1270 assert_eq!(
1271 rects,
1272 vec![
1273 (
1274 waft_embedder::Rect::from_ltwh(origin.dx(), origin.dy(), 40.0, 50.0).into(),
1275 yellow.into()
1276 ),
1277 (
1278 waft_embedder::Rect::from_ltwh(
1279 origin.dx() + 40.0,
1280 origin.dy() + 50.0,
1281 55.0,
1282 60.0
1283 )
1284 .into(),
1285 green.into()
1286 ),
1287 ]
1288 );
1289
1290 mount_diagonal(&mut app, Some(&harness), Diagonal::default());
1291 assert!(
1292 !scene_ops(&mut app, &harness)
1293 .iter()
1294 .any(|op| matches!(op, Op::DrawRect { .. })),
1295 "an empty diagonal paints nothing"
1296 );
1297
1298 let element = {
1299 let render = diagonal(&app, &harness);
1300 let _ = render;
1301 element_of_diagonal(&app, &harness)
1302 };
1303 harness.set_child(&mut app, SizedBox::shrink().into_widget());
1304 harness.pump(&mut app);
1305 assert!(is_defunct(&app, element), "the slotted element unmounted");
1306 }
1307
1308 fn element_of_diagonal(app: &App, harness: &Harness) -> AnyElement {
1309 let mut found = None;
1310 fn walk(app: &App, element: AnyElement, found: &mut Option<AnyElement>) {
1311 if element.widget(app).widget_type() == TypeId::of::<Diagonal>() {
1312 *found = Some(element);
1313 return;
1314 }
1315 element.visit_children(app, &mut |child| {
1316 if found.is_none() {
1317 walk(app, child, found);
1318 }
1319 });
1320 }
1321 walk(app, harness.root.as_element(), &mut found);
1322 found.expect("the diagonal is mounted")
1323 }
1324
1325 fn diagonal_origin(app: &App, harness: &Harness) -> Offset {
1327 diagonal(app, harness)
1328 .as_box()
1329 .local_to_global(app, Offset::ZERO, None)
1330 }
1331
1332 fn scene_ops(app: &mut App, harness: &Harness) -> Vec<waft_embedder::valo::Op> {
1334 let layer = harness
1335 .render_root(app)
1336 .as_object()
1337 .debug_layer(app)
1338 .expect("painted");
1339 let scene = layer.build_scene(app, waft_embedder::SceneBuilder::new());
1340 waft_embedder::flattened_ops(&waft_embedder::slices(&scene, |_| None).picture_with_room())
1341 }
1342
1343 #[derive(Clone, Debug, PartialEq, Eq, Hash)]
1345 struct TestSlot(u32);
1346
1347 struct RenderTest {
1348 render_object: RenderObjectData,
1349 render_box: RenderBoxData,
1350 slotted: SlottedContainerRenderObjectData<TestSlot, AnyRenderBox>,
1351 }
1352
1353 impl SlottedContainerRenderObjectMixin<TestSlot> for RenderTest {
1354 type ChildType = AnyRenderBox;
1355
1356 fn slotted_container_data(
1357 self: RenderHandle<Self>,
1358 app: &App,
1359 ) -> &SlottedContainerRenderObjectData<TestSlot, AnyRenderBox> {
1360 &self.get(app).slotted
1361 }
1362
1363 fn slotted_container_data_mut(
1364 self: RenderHandle<Self>,
1365 app: &mut App,
1366 ) -> &mut SlottedContainerRenderObjectData<TestSlot, AnyRenderBox> {
1367 &mut self.get_mut(app).slotted
1368 }
1369 }
1370
1371 impl RenderObject for RenderTest {
1372 waft_rendering::render_object_accessors!();
1373
1374 fn debug_describe_children(
1375 self: RenderHandle<Self>,
1376 app: &App,
1377 ) -> Vec<Rc<dyn DiagnosticsNode>> {
1378 SlottedContainerRenderObjectMixin::debug_describe_children(self, app)
1379 }
1380
1381 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1382 let size = self.constraints(app).smallest();
1383 self.set_size(app, size);
1384 }
1385 }
1386
1387 impl RenderBox for RenderTest {
1388 waft_rendering::render_box_accessors!();
1389 }
1390
1391 #[test]
1393 fn a_slot_that_is_not_an_enum_is_named_by_its_debug_form() {
1394 let render = RenderTest {
1395 render_object: RenderObjectData::new(),
1396 render_box: RenderBoxData::new(),
1397 slotted: SlottedContainerRenderObjectData::new(),
1398 };
1399 assert_eq!(render.debug_name_for_slot(&TestSlot(3)), "TestSlot(3)");
1400 }
1401}