1use std::any::{Any, TypeId};
8use std::collections::HashMap;
9use std::fmt::{self, Debug};
10use std::rc::Rc;
11
12use waft_embedder::{Offset, Size};
13use waft_foundation::{App, Handle, Key, Listenable, Listener, display_or_null};
14
15use crate::box_::{
16 AnyBoxConstraints, AnyRenderBox, BoxConstraints, BoxHitTestResult, BoxParentData,
17 ContainerBoxParentData, RenderBox, RenderBoxContainerDefaultsMixin, RenderBoxData,
18};
19use crate::object::{
20 AnyRenderObject, Constraints, ContainerParentData, ContainerParentDataMixin,
21 ContainerRenderObjectData, ContainerRenderObjectMixin, ParentData, RenderHandle, RenderObject,
22 RenderObjectData,
23};
24use crate::painting_context::PaintingContext;
25use crate::pipeline_owner::PipelineOwner;
26
27pub type ChildLayoutId = Rc<dyn Key>;
31
32#[derive(Debug)]
34pub struct MultiChildLayoutParentData {
35 box_parent_data: BoxParentData,
36 container_parent_data: ContainerParentData<AnyRenderBox>,
37
38 pub id: Option<ChildLayoutId>,
40}
41
42impl MultiChildLayoutParentData {
43 pub const fn new() -> MultiChildLayoutParentData {
45 MultiChildLayoutParentData {
46 box_parent_data: BoxParentData::new(),
47 container_parent_data: ContainerParentData::new(),
48 id: None,
49 }
50 }
51}
52
53impl Default for MultiChildLayoutParentData {
54 fn default() -> MultiChildLayoutParentData {
55 MultiChildLayoutParentData::new()
56 }
57}
58
59impl ParentData for MultiChildLayoutParentData {
60 fn detach(&mut self) {
61 ContainerParentDataMixin::detach(self);
62 }
63
64 fn provide(&self, id: TypeId) -> Option<&dyn Any> {
65 if id == TypeId::of::<MultiChildLayoutParentData>() {
66 return Some(self);
67 }
68 self.box_parent_data.provide(id)
69 }
70
71 fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
72 if id == TypeId::of::<MultiChildLayoutParentData>() {
73 return Some(self);
74 }
75 self.box_parent_data.provide_mut(id)
76 }
77}
78
79impl ContainerParentDataMixin for MultiChildLayoutParentData {
80 type ChildType = AnyRenderBox;
81
82 fn container_parent_data(&self) -> &ContainerParentData<AnyRenderBox> {
83 &self.container_parent_data
84 }
85
86 fn container_parent_data_mut(&mut self) -> &mut ContainerParentData<AnyRenderBox> {
87 &mut self.container_parent_data
88 }
89}
90
91impl ContainerBoxParentData for MultiChildLayoutParentData {
92 fn box_parent_data(&self) -> &BoxParentData {
93 &self.box_parent_data
94 }
95
96 fn box_parent_data_mut(&mut self) -> &mut BoxParentData {
97 &mut self.box_parent_data
98 }
99}
100
101impl fmt::Display for MultiChildLayoutParentData {
102 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
103 let id = self.id.as_ref().map(|id| format!("{id:?}"));
105 write!(f, "{}; id={}", self.box_parent_data, display_or_null(&id))
106 }
107}
108
109pub struct MultiChildLayoutChildren {
116 id_to_child: HashMap<ChildLayoutId, AnyRenderBox>,
117 #[cfg(debug_assertions)]
118 children_needing_layout: std::collections::HashSet<AnyRenderBox>,
119}
120
121impl MultiChildLayoutChildren {
122 pub fn has_child(&self, child_id: &ChildLayoutId) -> bool {
130 self.id_to_child.contains_key(child_id)
131 }
132
133 pub fn layout_child(
145 &mut self,
146 app: &mut App,
147 child_id: &ChildLayoutId,
148 constraints: impl Into<AnyBoxConstraints>,
149 ) -> Size {
150 let constraints: AnyBoxConstraints = constraints.into();
151 let child = *self.id_to_child.get(child_id).unwrap_or_else(|| {
152 panic!(
153 "The custom multichild layout delegate tried to lay out a non-existent child. \
154 There is no child with the id {child_id:?}."
155 )
156 });
157 #[cfg(debug_assertions)]
158 assert!(
159 self.children_needing_layout.remove(&child),
160 "The custom multichild layout delegate tried to lay out the child with id \
161 {child_id:?} more than once. Each child must be laid out exactly once."
162 );
163 debug_assert!(
164 constraints.debug_assert_is_valid(true),
165 "The custom multichild layout delegate provided invalid box constraints for the \
166 child with id {child_id:?}. The minimum width and height must be greater than or \
167 equal to zero. The maximum width must be greater than or equal to the minimum \
168 width. The maximum height must be greater than or equal to the minimum height."
169 );
170 child.layout(app, constraints, true);
171 child.size(app)
172 }
173
174 pub fn position_child(&self, app: &mut App, child_id: &ChildLayoutId, offset: Offset) {
185 let child = *self.id_to_child.get(child_id).unwrap_or_else(|| {
186 panic!(
187 "The custom multichild layout delegate tried to position out a non-existent \
188 child: there is no child with the id {child_id:?}."
189 )
190 });
191 child
192 .parent_data_of_mut::<MultiChildLayoutParentData>(app)
193 .set_offset(offset);
194 }
195}
196
197pub trait MultiChildLayoutDelegate: Debug + 'static {
229 fn relayout(&self) -> Option<&Rc<dyn Listenable>> {
233 None
234 }
235
236 fn get_size(&self, constraints: BoxConstraints) -> Size {
244 constraints.biggest()
245 }
246
247 fn perform_layout(&self, app: &mut App, children: &mut MultiChildLayoutChildren, size: Size);
253
254 fn should_relayout(&self, old_delegate: &dyn MultiChildLayoutDelegate) -> bool;
261
262 fn as_any(&self) -> &dyn Any;
265}
266
267pub struct RenderCustomMultiChildLayoutBox {
273 render_object: RenderObjectData,
274 render_box: RenderBoxData,
275 container: ContainerRenderObjectData<AnyRenderBox>,
276 delegate: Rc<dyn MultiChildLayoutDelegate>,
277}
278
279impl RenderCustomMultiChildLayoutBox {
280 pub fn new(
285 app: &mut App,
286 delegate: Rc<dyn MultiChildLayoutDelegate>,
287 ) -> RenderHandle<RenderCustomMultiChildLayoutBox> {
288 RenderHandle::new_box(
289 app,
290 RenderCustomMultiChildLayoutBox {
291 render_object: RenderObjectData::new(),
292 render_box: RenderBoxData::new(),
293 container: ContainerRenderObjectData::new(),
294 delegate,
295 },
296 )
297 }
298
299 pub fn delegate(self: RenderHandle<Self>, app: &App) -> Rc<dyn MultiChildLayoutDelegate> {
301 Rc::clone(&self.get(app).delegate)
302 }
303
304 pub fn set_delegate(
306 self: RenderHandle<Self>,
307 app: &mut App,
308 new_delegate: Rc<dyn MultiChildLayoutDelegate>,
309 ) {
310 let old_delegate = Rc::clone(&self.get(app).delegate);
311 if Rc::ptr_eq(&old_delegate, &new_delegate) {
312 return;
313 }
314 if new_delegate.as_any().type_id() != old_delegate.as_any().type_id()
315 || new_delegate.should_relayout(&*old_delegate)
316 {
317 self.mark_needs_layout(app);
318 }
319 self.get_mut(app).delegate = Rc::clone(&new_delegate);
320 if self.attached(app) {
321 if let Some(relayout) = old_delegate.relayout() {
322 relayout.remove_listener(app, &self.relayout_listener());
323 }
324 if let Some(relayout) = new_delegate.relayout() {
325 relayout.add_listener(app, self.relayout_listener());
326 }
327 }
328 }
329
330 fn relayout_listener(self: RenderHandle<Self>) -> Listener {
332 Listener::handle_method(self.handle(), mark_needs_layout)
333 }
334
335 fn get_size(self: RenderHandle<Self>, app: &App, constraints: BoxConstraints) -> Size {
337 debug_assert!(constraints.debug_assert_is_valid(false));
338 constraints.constrain(self.get(app).delegate.get_size(constraints))
339 }
340
341 fn call_perform_layout(self: RenderHandle<Self>, app: &mut App, size: Size) {
347 let mut children = MultiChildLayoutChildren {
348 id_to_child: HashMap::new(),
349 #[cfg(debug_assertions)]
350 children_needing_layout: std::collections::HashSet::new(),
351 };
352 let mut child = self.first_child(app);
353 while let Some(current) = child {
354 let child_parent_data = current
355 .as_object()
356 .parent_data_of::<MultiChildLayoutParentData>(app);
357 let (id, next_sibling) = (
358 child_parent_data.id.clone(),
359 child_parent_data.next_sibling(),
360 );
361 let id = id.unwrap_or_else(|| {
362 panic!(
363 "Every child of a RenderCustomMultiChildLayoutBox must have an ID in its \
364 parent data. The following child has no ID: {current:?}"
365 )
366 });
367 children.id_to_child.insert(id, current);
368 #[cfg(debug_assertions)]
369 children.children_needing_layout.insert(current);
370 child = next_sibling;
371 }
372
373 let delegate = Rc::clone(&self.get(app).delegate);
374 delegate.perform_layout(app, &mut children, size);
375
376 #[cfg(debug_assertions)]
377 assert!(
378 children.children_needing_layout.is_empty(),
379 "Each child must be laid out exactly once. The custom multichild layout delegate \
380 forgot to lay out {:?}",
381 children.children_needing_layout
382 );
383 }
384}
385
386fn mark_needs_layout(this: Handle<RenderCustomMultiChildLayoutBox>, app: &mut App) {
387 RenderHandle::from_handle(this).mark_needs_layout(app);
388}
389
390impl ContainerRenderObjectMixin for RenderCustomMultiChildLayoutBox {
391 type ChildType = AnyRenderBox;
392 type ParentDataType = MultiChildLayoutParentData;
393
394 fn container_data(
395 self: RenderHandle<Self>,
396 app: &App,
397 ) -> &ContainerRenderObjectData<AnyRenderBox> {
398 &self.get(app).container
399 }
400
401 fn container_data_mut(
402 self: RenderHandle<Self>,
403 app: &mut App,
404 ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
405 &mut self.get_mut(app).container
406 }
407}
408
409impl RenderBoxContainerDefaultsMixin for RenderCustomMultiChildLayoutBox {}
410
411impl RenderObject for RenderCustomMultiChildLayoutBox {
412 crate::render_object_accessors!();
413
414 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
415 let constraints = self.constraints(app);
416 let size = self.get_size(app, constraints);
417 self.set_size(app, size);
418 self.call_perform_layout(app, size);
419 }
420
421 fn visit_children(
422 self: RenderHandle<Self>,
423 app: &App,
424 visitor: &mut dyn FnMut(AnyRenderObject),
425 ) {
426 ContainerRenderObjectMixin::visit_children(self, app, visitor)
427 }
428
429 fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
430 ContainerRenderObjectMixin::did_attach(self, app, owner);
431 if let Some(relayout) = self.delegate(app).relayout() {
432 relayout.add_listener(app, self.relayout_listener());
433 }
434 }
435
436 fn did_detach(self: RenderHandle<Self>, app: &mut App) {
437 if let Some(relayout) = self.delegate(app).relayout() {
438 relayout.remove_listener(app, &self.relayout_listener());
439 }
440 ContainerRenderObjectMixin::did_detach(self, app)
441 }
442
443 fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
444 ContainerRenderObjectMixin::redepth_children(self, app)
445 }
446
447 fn paint(
448 self: RenderHandle<Self>,
449 app: &mut App,
450 context: &mut PaintingContext,
451 offset: Offset,
452 ) {
453 self.default_paint(app, context, offset);
454 }
455}
456
457impl RenderBox for RenderCustomMultiChildLayoutBox {
458 crate::render_box_accessors!();
459
460 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
461 if !child.parent_data_is::<MultiChildLayoutParentData>(app) {
462 child.set_parent_data(app, MultiChildLayoutParentData::new());
463 }
464 }
465
466 fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
470 let width = self
471 .get_size(app, BoxConstraints::tight_for_finite(f64::INFINITY, height))
472 .width();
473 if width.is_finite() { width } else { 0.0 }
474 }
475
476 fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
477 let width = self
478 .get_size(app, BoxConstraints::tight_for_finite(f64::INFINITY, height))
479 .width();
480 if width.is_finite() { width } else { 0.0 }
481 }
482
483 fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
484 let height = self
485 .get_size(app, BoxConstraints::tight_for_finite(width, f64::INFINITY))
486 .height();
487 if height.is_finite() { height } else { 0.0 }
488 }
489
490 fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
491 let height = self
492 .get_size(app, BoxConstraints::tight_for_finite(width, f64::INFINITY))
493 .height();
494 if height.is_finite() { height } else { 0.0 }
495 }
496
497 fn compute_dry_layout(
498 self: RenderHandle<Self>,
499 app: &mut App,
500 constraints: BoxConstraints,
501 ) -> Size {
502 self.get_size(app, constraints)
503 }
504
505 fn hit_test_children(
506 self: RenderHandle<Self>,
507 app: &mut App,
508 result: &mut BoxHitTestResult<'_>,
509 position: Offset,
510 ) -> bool {
511 self.default_hit_test_children(app, result, position)
512 }
513}