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};
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 write!(f, "{}; id={:?}", self.box_parent_data, self.id)
104 }
105}
106
107pub struct MultiChildLayoutChildren {
114 id_to_child: HashMap<ChildLayoutId, AnyRenderBox>,
115 #[cfg(debug_assertions)]
116 children_needing_layout: std::collections::HashSet<AnyRenderBox>,
117}
118
119impl MultiChildLayoutChildren {
120 pub fn has_child(&self, child_id: &ChildLayoutId) -> bool {
128 self.id_to_child.contains_key(child_id)
129 }
130
131 pub fn layout_child(
143 &mut self,
144 app: &mut App,
145 child_id: &ChildLayoutId,
146 constraints: impl Into<AnyBoxConstraints>,
147 ) -> Size {
148 let constraints: AnyBoxConstraints = constraints.into();
149 let child = *self.id_to_child.get(child_id).unwrap_or_else(|| {
150 panic!(
151 "The custom multichild layout delegate tried to lay out a non-existent child. \
152 There is no child with the id {child_id:?}."
153 )
154 });
155 #[cfg(debug_assertions)]
156 assert!(
157 self.children_needing_layout.remove(&child),
158 "The custom multichild layout delegate tried to lay out the child with id \
159 {child_id:?} more than once. Each child must be laid out exactly once."
160 );
161 debug_assert!(
162 constraints.debug_assert_is_valid(true),
163 "The custom multichild layout delegate provided invalid box constraints for the \
164 child with id {child_id:?}. The minimum width and height must be greater than or \
165 equal to zero. The maximum width must be greater than or equal to the minimum \
166 width. The maximum height must be greater than or equal to the minimum height."
167 );
168 child.layout(app, constraints, true);
169 child.size(app)
170 }
171
172 pub fn position_child(&self, app: &mut App, child_id: &ChildLayoutId, offset: Offset) {
183 let child = *self.id_to_child.get(child_id).unwrap_or_else(|| {
184 panic!(
185 "The custom multichild layout delegate tried to position out a non-existent \
186 child: there is no child with the id {child_id:?}."
187 )
188 });
189 child
190 .parent_data_of_mut::<MultiChildLayoutParentData>(app)
191 .set_offset(offset);
192 }
193}
194
195pub trait MultiChildLayoutDelegate: Debug + 'static {
227 fn relayout(&self) -> Option<&Rc<dyn Listenable>> {
231 None
232 }
233
234 fn get_size(&self, constraints: BoxConstraints) -> Size {
242 constraints.biggest()
243 }
244
245 fn perform_layout(&self, app: &mut App, children: &mut MultiChildLayoutChildren, size: Size);
251
252 fn should_relayout(&self, old_delegate: &dyn MultiChildLayoutDelegate) -> bool;
259
260 fn as_any(&self) -> &dyn Any;
263}
264
265pub struct RenderCustomMultiChildLayoutBox {
271 render_object: RenderObjectData,
272 render_box: RenderBoxData,
273 container: ContainerRenderObjectData<AnyRenderBox>,
274 delegate: Rc<dyn MultiChildLayoutDelegate>,
275}
276
277impl RenderCustomMultiChildLayoutBox {
278 pub fn new(
283 app: &mut App,
284 delegate: Rc<dyn MultiChildLayoutDelegate>,
285 ) -> RenderHandle<RenderCustomMultiChildLayoutBox> {
286 RenderHandle::new_box(
287 app,
288 RenderCustomMultiChildLayoutBox {
289 render_object: RenderObjectData::new(),
290 render_box: RenderBoxData::new(),
291 container: ContainerRenderObjectData::new(),
292 delegate,
293 },
294 )
295 }
296
297 pub fn delegate(self: RenderHandle<Self>, app: &App) -> Rc<dyn MultiChildLayoutDelegate> {
299 Rc::clone(&self.get(app).delegate)
300 }
301
302 pub fn set_delegate(
304 self: RenderHandle<Self>,
305 app: &mut App,
306 new_delegate: Rc<dyn MultiChildLayoutDelegate>,
307 ) {
308 let old_delegate = Rc::clone(&self.get(app).delegate);
309 if Rc::ptr_eq(&old_delegate, &new_delegate) {
310 return;
311 }
312 if new_delegate.as_any().type_id() != old_delegate.as_any().type_id()
313 || new_delegate.should_relayout(&*old_delegate)
314 {
315 self.mark_needs_layout(app);
316 }
317 self.get_mut(app).delegate = Rc::clone(&new_delegate);
318 if self.attached(app) {
319 if let Some(relayout) = old_delegate.relayout() {
320 relayout.remove_listener(app, &self.relayout_listener());
321 }
322 if let Some(relayout) = new_delegate.relayout() {
323 relayout.add_listener(app, self.relayout_listener());
324 }
325 }
326 }
327
328 fn relayout_listener(self: RenderHandle<Self>) -> Listener {
330 Listener::handle_method(self.handle(), mark_needs_layout)
331 }
332
333 fn get_size(self: RenderHandle<Self>, app: &App, constraints: BoxConstraints) -> Size {
335 debug_assert!(constraints.debug_assert_is_valid(false));
336 constraints.constrain(self.get(app).delegate.get_size(constraints))
337 }
338
339 fn call_perform_layout(self: RenderHandle<Self>, app: &mut App, size: Size) {
345 let mut children = MultiChildLayoutChildren {
346 id_to_child: HashMap::new(),
347 #[cfg(debug_assertions)]
348 children_needing_layout: std::collections::HashSet::new(),
349 };
350 let mut child = self.first_child(app);
351 while let Some(current) = child {
352 let child_parent_data = current
353 .as_object()
354 .parent_data_of::<MultiChildLayoutParentData>(app);
355 let (id, next_sibling) = (
356 child_parent_data.id.clone(),
357 child_parent_data.next_sibling(),
358 );
359 let id = id.unwrap_or_else(|| {
360 panic!(
361 "Every child of a RenderCustomMultiChildLayoutBox must have an ID in its \
362 parent data. The following child has no ID: {current:?}"
363 )
364 });
365 children.id_to_child.insert(id, current);
366 #[cfg(debug_assertions)]
367 children.children_needing_layout.insert(current);
368 child = next_sibling;
369 }
370
371 let delegate = Rc::clone(&self.get(app).delegate);
372 delegate.perform_layout(app, &mut children, size);
373
374 #[cfg(debug_assertions)]
375 assert!(
376 children.children_needing_layout.is_empty(),
377 "Each child must be laid out exactly once. The custom multichild layout delegate \
378 forgot to lay out {:?}",
379 children.children_needing_layout
380 );
381 }
382}
383
384fn mark_needs_layout(this: Handle<RenderCustomMultiChildLayoutBox>, app: &mut App) {
385 RenderHandle::from_handle(this).mark_needs_layout(app);
386}
387
388impl ContainerRenderObjectMixin for RenderCustomMultiChildLayoutBox {
389 type ChildType = AnyRenderBox;
390 type ParentDataType = MultiChildLayoutParentData;
391
392 fn container_data(
393 self: RenderHandle<Self>,
394 app: &App,
395 ) -> &ContainerRenderObjectData<AnyRenderBox> {
396 &self.get(app).container
397 }
398
399 fn container_data_mut(
400 self: RenderHandle<Self>,
401 app: &mut App,
402 ) -> &mut ContainerRenderObjectData<AnyRenderBox> {
403 &mut self.get_mut(app).container
404 }
405}
406
407impl RenderBoxContainerDefaultsMixin for RenderCustomMultiChildLayoutBox {}
408
409impl RenderObject for RenderCustomMultiChildLayoutBox {
410 crate::render_object_accessors!();
411
412 fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
413 let constraints = self.constraints(app);
414 let size = self.get_size(app, constraints);
415 self.set_size(app, size);
416 self.call_perform_layout(app, size);
417 }
418
419 fn visit_children(
420 self: RenderHandle<Self>,
421 app: &App,
422 visitor: &mut dyn FnMut(AnyRenderObject),
423 ) {
424 ContainerRenderObjectMixin::visit_children(self, app, visitor)
425 }
426
427 fn did_attach(self: RenderHandle<Self>, app: &mut App, owner: Handle<PipelineOwner>) {
428 ContainerRenderObjectMixin::did_attach(self, app, owner);
429 if let Some(relayout) = self.delegate(app).relayout() {
430 relayout.add_listener(app, self.relayout_listener());
431 }
432 }
433
434 fn did_detach(self: RenderHandle<Self>, app: &mut App) {
435 if let Some(relayout) = self.delegate(app).relayout() {
436 relayout.remove_listener(app, &self.relayout_listener());
437 }
438 ContainerRenderObjectMixin::did_detach(self, app)
439 }
440
441 fn redepth_children(self: RenderHandle<Self>, app: &mut App) {
442 ContainerRenderObjectMixin::redepth_children(self, app)
443 }
444
445 fn paint(
446 self: RenderHandle<Self>,
447 app: &mut App,
448 context: &mut PaintingContext,
449 offset: Offset,
450 ) {
451 self.default_paint(app, context, offset);
452 }
453}
454
455impl RenderBox for RenderCustomMultiChildLayoutBox {
456 crate::render_box_accessors!();
457
458 fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
459 if !child.parent_data_is::<MultiChildLayoutParentData>(app) {
460 child.set_parent_data(app, MultiChildLayoutParentData::new());
461 }
462 }
463
464 fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
468 let width = self
469 .get_size(app, BoxConstraints::tight_for_finite(f64::INFINITY, height))
470 .width();
471 if width.is_finite() { width } else { 0.0 }
472 }
473
474 fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, height: f64) -> f64 {
475 let width = self
476 .get_size(app, BoxConstraints::tight_for_finite(f64::INFINITY, height))
477 .width();
478 if width.is_finite() { width } else { 0.0 }
479 }
480
481 fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
482 let height = self
483 .get_size(app, BoxConstraints::tight_for_finite(width, f64::INFINITY))
484 .height();
485 if height.is_finite() { height } else { 0.0 }
486 }
487
488 fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
489 let height = self
490 .get_size(app, BoxConstraints::tight_for_finite(width, f64::INFINITY))
491 .height();
492 if height.is_finite() { height } else { 0.0 }
493 }
494
495 fn compute_dry_layout(
496 self: RenderHandle<Self>,
497 app: &mut App,
498 constraints: BoxConstraints,
499 ) -> Size {
500 self.get_size(app, constraints)
501 }
502
503 fn hit_test_children(
504 self: RenderHandle<Self>,
505 app: &mut App,
506 result: &mut BoxHitTestResult<'_>,
507 position: Offset,
508 ) -> bool {
509 self.default_hit_test_children(app, result, position)
510 }
511}