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