Skip to main content

waft_rendering/
custom_layout.rs

1//! Flutter counterpart: `rendering/custom_layout.dart` (`MultiChildLayoutParentData`,
2//! `MultiChildLayoutDelegate`, `RenderCustomMultiChildLayoutBox`).
3//!
4//! `SingleChildLayoutDelegate` and `RenderCustomSingleChildLayoutBox` live in
5//! `shifted_box.dart`.
6
7use 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
27/// An object representing the identity of a child of a [`RenderCustomMultiChildLayoutBox`].
28///
29/// Dart's `Object` id, which `LayoutId` also wraps in a `ValueKey` to key the widget.
30pub type ChildLayoutId = Rc<dyn Key>;
31
32/// [`ParentData`] used by [`RenderCustomMultiChildLayoutBox`].
33#[derive(Debug)]
34pub struct MultiChildLayoutParentData {
35    box_parent_data: BoxParentData,
36    container_parent_data: ContainerParentData<AnyRenderBox>,
37
38    /// An object representing the identity of this child.
39    pub id: Option<ChildLayoutId>,
40}
41
42impl MultiChildLayoutParentData {
43    /// Creates parent data for a child that has no id yet.
44    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
107/// The children a [`MultiChildLayoutDelegate`] lays out, keyed by their
108/// [`MultiChildLayoutParentData::id`].
109///
110/// Dart's `MultiChildLayoutDelegate._idToChild` and, in debug builds, its
111/// `_debugChildrenNeedingLayout`. [`RenderCustomMultiChildLayoutBox`] builds one from its child
112/// list and hands it to [`MultiChildLayoutDelegate::perform_layout`].
113pub 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    /// True if a non-`None` child was provided for the specified id.
121    ///
122    /// Call this from [`MultiChildLayoutDelegate::perform_layout`] to determine which children
123    /// are available, if the child list might vary.
124    ///
125    /// This cannot be called from [`MultiChildLayoutDelegate::get_size`] as the size is not
126    /// allowed to depend on the children.
127    pub fn has_child(&self, child_id: &ChildLayoutId) -> bool {
128        self.id_to_child.contains_key(child_id)
129    }
130
131    /// Ask the child to update its layout within the limits specified by the constraints
132    /// parameter. The child's size is returned.
133    ///
134    /// Call this from [`MultiChildLayoutDelegate::perform_layout`] to lay out each child. Every
135    /// child must be laid out using this function exactly once each time
136    /// [`MultiChildLayoutDelegate::perform_layout`] is called.
137    ///
138    /// # Panics
139    ///
140    /// If there is no child with `child_id`, or, in a debug build, if that child was already
141    /// laid out during this call.
142    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    /// Specify the child's origin relative to this origin.
173    ///
174    /// Call this from [`MultiChildLayoutDelegate::perform_layout`] to position each child. If
175    /// you do not call this for a child, its position will remain unchanged. Children initially
176    /// have their position set to (0,0), i.e. the top left of the
177    /// [`RenderCustomMultiChildLayoutBox`].
178    ///
179    /// # Panics
180    ///
181    /// If there is no child with `child_id`.
182    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
195/// A delegate that controls the layout of multiple children.
196///
197/// Used with `CustomMultiChildLayout` (in the widgets library) and
198/// [`RenderCustomMultiChildLayoutBox`] (in the rendering library).
199///
200/// Delegates must be idempotent. Specifically, if two delegates are equal, then they must
201/// produce the same layout. To change the layout, replace the delegate with a different
202/// instance whose [`should_relayout`](Self::should_relayout) returns true when given the
203/// previous instance.
204///
205/// Override [`get_size`](Self::get_size) to control the overall size of the layout. The size of
206/// the layout cannot depend on layout properties of the children. This was a design decision to
207/// simplify the delegate implementations: this way, the delegate implementations do not have to
208/// also handle various intrinsic sizing functions if the parent's size depended on the children.
209///
210/// Override [`perform_layout`](Self::perform_layout) to size and position the children. An
211/// implementation of [`perform_layout`](Self::perform_layout) must call
212/// [`MultiChildLayoutChildren::layout_child`] exactly once for each child, but it may lay out
213/// children in an arbitrary order.
214///
215/// Override [`should_relayout`](Self::should_relayout) to determine when the layout of the
216/// children needs to be recomputed when the delegate changes.
217///
218/// The most efficient way to trigger a relayout is to answer a [`relayout`](Self::relayout)
219/// listenable. The custom layout listens to that value and relays out whenever it notifies its
220/// listeners, such as when an animation ticks. This allows the custom layout to avoid the build
221/// phase of the pipeline.
222///
223/// Each child must be wrapped in a `LayoutId` widget to assign the id that identifies it to the
224/// delegate. The id needs to be unique among the children that the `CustomMultiChildLayout`
225/// manages.
226pub trait MultiChildLayoutDelegate: Debug + 'static {
227    /// The [`Listenable`] the layout will update on, Dart's `relayout` constructor argument.
228    ///
229    /// Defaults to `None`.
230    fn relayout(&self) -> Option<&Rc<dyn Listenable>> {
231        None
232    }
233
234    /// Override this method to return the size of this object given the incoming constraints.
235    ///
236    /// The size cannot reflect the sizes of the children. If this layout has a fixed width or
237    /// height the returned size can reflect that; the size will be constrained to the given
238    /// constraints.
239    ///
240    /// By default, attempts to size the box to the biggest size possible given the constraints.
241    fn get_size(&self, constraints: BoxConstraints) -> Size {
242        constraints.biggest()
243    }
244
245    /// Override this method to lay out and position all children given this widget's size.
246    ///
247    /// This method must call [`MultiChildLayoutChildren::layout_child`] for each child. It
248    /// should also specify the final position of each child with
249    /// [`MultiChildLayoutChildren::position_child`].
250    fn perform_layout(&self, app: &mut App, children: &mut MultiChildLayoutChildren, size: Size);
251
252    /// Override this method to return true when the children need to be laid out.
253    ///
254    /// This should compare the fields of the current delegate and the given `old_delegate` and
255    /// return true if the fields are such that the layout would be different. `old_delegate` is
256    /// of the same concrete type, Dart's `covariant`: narrow it with
257    /// [`as_any`](Self::as_any).
258    fn should_relayout(&self, old_delegate: &dyn MultiChildLayoutDelegate) -> bool;
259
260    /// The concrete delegate, for Dart's `runtimeType` comparison and its `covariant`
261    /// narrowing of [`should_relayout`](Self::should_relayout)'s argument.
262    fn as_any(&self) -> &dyn Any;
263}
264
265/// Defers the layout of multiple children to a delegate.
266///
267/// The delegate can determine the layout constraints for each child and can decide where to
268/// position each child. The delegate can also determine the size of the parent, but the size of
269/// the parent cannot depend on the sizes of the children.
270pub struct RenderCustomMultiChildLayoutBox {
271    render_object: RenderObjectData,
272    render_box: RenderBoxData,
273    container: ContainerRenderObjectData<AnyRenderBox>,
274    delegate: Rc<dyn MultiChildLayoutDelegate>,
275}
276
277impl RenderCustomMultiChildLayoutBox {
278    /// Creates a render object that customizes the layout of multiple children.
279    ///
280    /// Add children with [`add`](ContainerRenderObjectMixin::add) or
281    /// [`add_all`](ContainerRenderObjectMixin::add_all); Dart's constructor takes them.
282    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    /// The delegate that controls the layout of the children.
298    pub fn delegate(self: RenderHandle<Self>, app: &App) -> Rc<dyn MultiChildLayoutDelegate> {
299        Rc::clone(&self.get(app).delegate)
300    }
301
302    /// Sets [`delegate`](Self::delegate).
303    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    /// The `markNeedsLayout` tear-off, equal to itself across registrations.
329    fn relayout_listener(self: RenderHandle<Self>) -> Listener {
330        Listener::handle_method(self.handle(), mark_needs_layout)
331    }
332
333    /// Dart's `_getSize`.
334    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    /// Dart's `MultiChildLayoutDelegate._callPerformLayout`.
340    ///
341    /// Dart saves and restores the delegate's `_idToChild` because a delegate can be used by
342    /// both a parent and a child; here the map belongs to the call, so there is nothing to
343    /// restore.
344    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    // Dart's TODO stands: using the delegate's `getSize` for the intrinsic dimensions is a bit
465    // dubious.
466
467    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}