Skip to main content

waft_rendering/
table.rs

1//! Flutter counterpart: `rendering/table.dart`.
2//!
3//! The table's semantics (`describeSemanticsConfiguration`, `assembleSemanticsNode`) wait with
4//! the rest of accessibility.
5
6use std::any::{Any, TypeId};
7use std::collections::{HashMap, HashSet};
8use std::fmt;
9use std::rc::Rc;
10
11use waft_embedder::{Offset, Rect, Size, TextBaseline, TextDirection};
12use waft_foundation::{
13    App, DiagnosticLevel, DiagnosticPropertiesBuilder, DiagnosticsNode, DiagnosticsProperty,
14    IterableProperty, MessageProperty, PRECISION_ERROR_TOLERANCE, debug_format_double, message,
15};
16use waft_painting::{BoxPainter, ClipContext, DecorationRef, ImageConfiguration};
17
18use crate::box_::{
19    AnyRenderBox, BoxConstraints, BoxHitTestResult, BoxParentData, DryLayoutFailure, RenderBox,
20    RenderBoxData,
21};
22use crate::object::{AnyRenderObject, ParentData, RenderHandle, RenderObject, RenderObjectData};
23use crate::painting_context::PaintingContext;
24use crate::table_border::TableBorder;
25
26/// Parent data used by [`RenderTable`] for its children.
27#[derive(Debug, Default)]
28pub struct TableCellParentData {
29    box_parent_data: BoxParentData,
30
31    /// Where this cell should be placed vertically.
32    ///
33    /// When using [`TableCellVerticalAlignment::Baseline`], the text baseline must be set as
34    /// well.
35    pub vertical_alignment: Option<TableCellVerticalAlignment>,
36
37    /// The column that the child was in the last time it was laid out.
38    pub x: Option<usize>,
39
40    /// The row that the child was in the last time it was laid out.
41    pub y: Option<usize>,
42}
43
44impl TableCellParentData {
45    /// Creates table cell parent data at offset zero, with the default vertical alignment.
46    pub const fn new() -> TableCellParentData {
47        TableCellParentData {
48            box_parent_data: BoxParentData::new(),
49            vertical_alignment: None,
50            x: None,
51            y: None,
52        }
53    }
54}
55
56impl ParentData for TableCellParentData {
57    fn provide(&self, id: TypeId) -> Option<&dyn Any> {
58        if id == TypeId::of::<TableCellParentData>() {
59            return Some(self);
60        }
61        self.box_parent_data.provide(id)
62    }
63
64    fn provide_mut(&mut self, id: TypeId) -> Option<&mut dyn Any> {
65        if id == TypeId::of::<TableCellParentData>() {
66            return Some(self);
67        }
68        self.box_parent_data.provide_mut(id)
69    }
70}
71
72impl fmt::Display for TableCellParentData {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        fmt::Display::fmt(&self.box_parent_data, f)?;
75        match self.vertical_alignment {
76            None => f.write_str("; default vertical alignment"),
77            Some(vertical_alignment) => write!(f, "; {vertical_alignment:?}"),
78        }
79    }
80}
81
82/// A shared, immutable [`TableColumnWidth`] (a Dart object reference). Two references are the
83/// same column width only when they point at the same value, as Dart compares these objects.
84pub type TableColumnWidthRef = Rc<dyn TableColumnWidth>;
85
86/// Base class to describe how wide a column in a [`RenderTable`] should be.
87///
88/// To size a column to a specific number of pixels, use a [`FixedColumnWidth`]. This is the
89/// cheapest way to size a column.
90///
91/// Other algorithms that are relatively cheap include [`FlexColumnWidth`], which distributes
92/// the space equally among the flexible columns, [`FractionColumnWidth`], which sizes a column
93/// based on the size of the table's container.
94pub trait TableColumnWidth: fmt::Debug {
95    /// The smallest width that the column can have.
96    ///
97    /// The `cells` argument is an iterable that provides all the cells in the table for this
98    /// column. Walking the cells is by definition O(N), so algorithms that do that should be
99    /// considered expensive.
100    ///
101    /// The `container_width` argument is the `max_width` of the incoming constraints for the
102    /// table, and might be infinite.
103    fn min_intrinsic_width(
104        &self,
105        app: &mut App,
106        cells: &[AnyRenderBox],
107        container_width: f64,
108    ) -> f64;
109
110    /// The ideal width that the column should have. This must be equal to or greater than the
111    /// [`min_intrinsic_width`](Self::min_intrinsic_width). The column might be bigger than this
112    /// width, e.g. if the column is flexible or if the table's width ends up being forced to be
113    /// bigger than the sum of all the `max_intrinsic_width` values.
114    ///
115    /// The `cells` argument is an iterable that provides all the cells in the table for this
116    /// column. Walking the cells is by definition O(N), so algorithms that do that should be
117    /// considered expensive.
118    ///
119    /// The `container_width` argument is the `max_width` of the incoming constraints for the
120    /// table, and might be infinite.
121    fn max_intrinsic_width(
122        &self,
123        app: &mut App,
124        cells: &[AnyRenderBox],
125        container_width: f64,
126    ) -> f64;
127
128    /// The flex factor to apply to the cell if there is any room left over when laying out the
129    /// table. The remaining space is distributed to any columns with flex in proportion to
130    /// their flex value (higher values get more space).
131    ///
132    /// The `cells` argument is an iterable that provides all the cells in the table for this
133    /// column. Walking the cells is by definition O(N), so algorithms that do that should be
134    /// considered expensive.
135    fn flex(&self, app: &mut App, cells: &[AnyRenderBox]) -> Option<f64> {
136        let _ = (app, cells);
137        None
138    }
139
140    /// Downcast support for Dart's `is` checks on a column width.
141    fn as_any(&self) -> &dyn Any;
142}
143
144/// Sizes the column according to the intrinsic dimensions of all the cells in that column.
145///
146/// This is a very expensive way to size a column.
147///
148/// A flex value can be provided. If specified (and non-`None`), the column will participate in
149/// the distribution of remaining space once all the non-flexible columns have been sized.
150pub struct IntrinsicColumnWidth {
151    flex: Option<f64>,
152}
153
154impl IntrinsicColumnWidth {
155    /// Creates a column width based on intrinsic sizing.
156    ///
157    /// This sizing algorithm is very expensive.
158    ///
159    /// The `flex` argument specifies the flex factor to apply to the column if there is any
160    /// room left over when laying out the table. If `flex` is `None` (the default), the table
161    /// will not distribute any extra space to the column.
162    pub const fn new(flex: Option<f64>) -> IntrinsicColumnWidth {
163        IntrinsicColumnWidth { flex }
164    }
165}
166
167impl TableColumnWidth for IntrinsicColumnWidth {
168    fn min_intrinsic_width(
169        &self,
170        app: &mut App,
171        cells: &[AnyRenderBox],
172        _container_width: f64,
173    ) -> f64 {
174        let mut result: f64 = 0.0;
175        for cell in cells {
176            result = result.max(cell.get_min_intrinsic_width(app, f64::INFINITY));
177        }
178        result
179    }
180
181    fn max_intrinsic_width(
182        &self,
183        app: &mut App,
184        cells: &[AnyRenderBox],
185        _container_width: f64,
186    ) -> f64 {
187        let mut result: f64 = 0.0;
188        for cell in cells {
189            result = result.max(cell.get_max_intrinsic_width(app, f64::INFINITY));
190        }
191        result
192    }
193
194    fn flex(&self, _app: &mut App, _cells: &[AnyRenderBox]) -> Option<f64> {
195        self.flex
196    }
197
198    fn as_any(&self) -> &dyn Any {
199        self
200    }
201}
202
203impl fmt::Debug for IntrinsicColumnWidth {
204    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
205        match self.flex {
206            Some(flex) => write!(f, "IntrinsicColumnWidth(flex: {flex:.1})"),
207            None => f.write_str("IntrinsicColumnWidth(flex: null)"),
208        }
209    }
210}
211
212impl fmt::Display for dyn TableColumnWidth {
213    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
214        fmt::Debug::fmt(self, f)
215    }
216}
217
218/// Dart compares these objects by identity, which [`Rc`] shares.
219impl PartialEq for dyn TableColumnWidth {
220    fn eq(&self, other: &Self) -> bool {
221        std::ptr::eq(self, other)
222    }
223}
224
225/// Sizes the column to a specific number of pixels.
226///
227/// This is the cheapest way to size a column.
228pub struct FixedColumnWidth {
229    /// The width the column should occupy in logical pixels.
230    pub value: f64,
231}
232
233impl FixedColumnWidth {
234    /// Creates a column width based on a fixed number of logical pixels.
235    pub const fn new(value: f64) -> FixedColumnWidth {
236        FixedColumnWidth { value }
237    }
238}
239
240impl TableColumnWidth for FixedColumnWidth {
241    fn min_intrinsic_width(
242        &self,
243        _app: &mut App,
244        _cells: &[AnyRenderBox],
245        _container_width: f64,
246    ) -> f64 {
247        self.value
248    }
249
250    fn max_intrinsic_width(
251        &self,
252        _app: &mut App,
253        _cells: &[AnyRenderBox],
254        _container_width: f64,
255    ) -> f64 {
256        self.value
257    }
258
259    fn as_any(&self) -> &dyn Any {
260        self
261    }
262}
263
264impl fmt::Debug for FixedColumnWidth {
265    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
266        write!(f, "FixedColumnWidth({:.1})", self.value)
267    }
268}
269
270/// Sizes the column to a fraction of the table's constraints' `max_width`.
271///
272/// This is a cheap way to size a column.
273pub struct FractionColumnWidth {
274    /// The fraction of the table's constraints' `max_width` that this column should occupy.
275    pub value: f64,
276}
277
278impl FractionColumnWidth {
279    /// Creates a column width based on a fraction of the table's constraints' `max_width`.
280    pub const fn new(value: f64) -> FractionColumnWidth {
281        FractionColumnWidth { value }
282    }
283}
284
285impl TableColumnWidth for FractionColumnWidth {
286    fn min_intrinsic_width(
287        &self,
288        _app: &mut App,
289        _cells: &[AnyRenderBox],
290        container_width: f64,
291    ) -> f64 {
292        if !container_width.is_finite() {
293            return 0.0;
294        }
295        self.value * container_width
296    }
297
298    fn max_intrinsic_width(
299        &self,
300        _app: &mut App,
301        _cells: &[AnyRenderBox],
302        container_width: f64,
303    ) -> f64 {
304        if !container_width.is_finite() {
305            return 0.0;
306        }
307        self.value * container_width
308    }
309
310    fn as_any(&self) -> &dyn Any {
311        self
312    }
313}
314
315impl fmt::Debug for FractionColumnWidth {
316    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
317        write!(f, "FractionColumnWidth({})", self.value)
318    }
319}
320
321/// Sizes the column by taking a part of the remaining space once all the other columns have
322/// been laid out.
323///
324/// For example, if two columns have a [`FlexColumnWidth`], then half the space will go to one
325/// and half the space will go to the other.
326///
327/// This is a cheap way to size a column.
328pub struct FlexColumnWidth {
329    /// The fraction of the remaining space once all the other columns have been laid out that
330    /// this column should occupy.
331    pub value: f64,
332}
333
334thread_local! {
335    static DEFAULT_FLEX_COLUMN_WIDTH: TableColumnWidthRef = Rc::new(FlexColumnWidth::new(1.0));
336}
337
338impl FlexColumnWidth {
339    /// Creates a column width based on a fraction of the remaining space once all the other
340    /// columns have been laid out. Dart's default `value` is 1.0.
341    pub const fn new(value: f64) -> FlexColumnWidth {
342        FlexColumnWidth { value }
343    }
344
345    /// Dart's `const FlexColumnWidth()`, the default column width of a table: one shared value,
346    /// as Dart's constant is one object, so a table given the default again is unchanged.
347    pub fn default_width() -> TableColumnWidthRef {
348        DEFAULT_FLEX_COLUMN_WIDTH.with(Rc::clone)
349    }
350}
351
352impl TableColumnWidth for FlexColumnWidth {
353    fn min_intrinsic_width(
354        &self,
355        _app: &mut App,
356        _cells: &[AnyRenderBox],
357        _container_width: f64,
358    ) -> f64 {
359        0.0
360    }
361
362    fn max_intrinsic_width(
363        &self,
364        _app: &mut App,
365        _cells: &[AnyRenderBox],
366        _container_width: f64,
367    ) -> f64 {
368        0.0
369    }
370
371    fn flex(&self, _app: &mut App, _cells: &[AnyRenderBox]) -> Option<f64> {
372        Some(self.value)
373    }
374
375    fn as_any(&self) -> &dyn Any {
376        self
377    }
378}
379
380impl fmt::Debug for FlexColumnWidth {
381    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
382        write!(f, "FlexColumnWidth({:.1})", self.value)
383    }
384}
385
386/// Sizes the column such that it is the size that is the maximum of two column width
387/// specifications.
388///
389/// For example, to have a column be 10% of the container width or 100px, whichever is bigger,
390/// you could use:
391///
392/// ```ignore
393/// MaxColumnWidth::new(Rc::new(FixedColumnWidth::new(100.0)), Rc::new(FractionColumnWidth::new(0.1)))
394/// ```
395///
396/// Both specifications are evaluated, so if either specification is expensive, so is this.
397#[derive(Debug)]
398pub struct MaxColumnWidth {
399    /// A lower bound for the width of this column.
400    pub a: TableColumnWidthRef,
401    /// Another lower bound for the width of this column.
402    pub b: TableColumnWidthRef,
403}
404
405impl MaxColumnWidth {
406    /// Creates a column width that is the maximum of two other column widths.
407    pub fn new(a: TableColumnWidthRef, b: TableColumnWidthRef) -> MaxColumnWidth {
408        MaxColumnWidth { a, b }
409    }
410}
411
412impl TableColumnWidth for MaxColumnWidth {
413    fn min_intrinsic_width(
414        &self,
415        app: &mut App,
416        cells: &[AnyRenderBox],
417        container_width: f64,
418    ) -> f64 {
419        self.a
420            .min_intrinsic_width(app, cells, container_width)
421            .max(self.b.min_intrinsic_width(app, cells, container_width))
422    }
423
424    fn max_intrinsic_width(
425        &self,
426        app: &mut App,
427        cells: &[AnyRenderBox],
428        container_width: f64,
429    ) -> f64 {
430        self.a
431            .max_intrinsic_width(app, cells, container_width)
432            .max(self.b.max_intrinsic_width(app, cells, container_width))
433    }
434
435    fn flex(&self, app: &mut App, cells: &[AnyRenderBox]) -> Option<f64> {
436        let a_flex = self.a.flex(app, cells);
437        let b_flex = self.b.flex(app, cells);
438        match (a_flex, b_flex) {
439            (None, _) => b_flex,
440            (Some(_), None) => a_flex,
441            (Some(a_flex), Some(b_flex)) => Some(a_flex.max(b_flex)),
442        }
443    }
444
445    fn as_any(&self) -> &dyn Any {
446        self
447    }
448}
449
450/// Sizes the column such that it is the size that is the minimum of two column width
451/// specifications.
452///
453/// For example, to have a column be 10% of the container width but never bigger than 100px,
454/// you could use:
455///
456/// ```ignore
457/// MinColumnWidth::new(Rc::new(FixedColumnWidth::new(100.0)), Rc::new(FractionColumnWidth::new(0.1)))
458/// ```
459///
460/// Both specifications are evaluated, so if either specification is expensive, so is this.
461#[derive(Debug)]
462pub struct MinColumnWidth {
463    /// An upper bound for the width of this column.
464    pub a: TableColumnWidthRef,
465    /// Another upper bound for the width of this column.
466    pub b: TableColumnWidthRef,
467}
468
469impl MinColumnWidth {
470    /// Creates a column width that is the minimum of two other column widths.
471    pub fn new(a: TableColumnWidthRef, b: TableColumnWidthRef) -> MinColumnWidth {
472        MinColumnWidth { a, b }
473    }
474}
475
476impl TableColumnWidth for MinColumnWidth {
477    fn min_intrinsic_width(
478        &self,
479        app: &mut App,
480        cells: &[AnyRenderBox],
481        container_width: f64,
482    ) -> f64 {
483        self.a
484            .min_intrinsic_width(app, cells, container_width)
485            .min(self.b.min_intrinsic_width(app, cells, container_width))
486    }
487
488    fn max_intrinsic_width(
489        &self,
490        app: &mut App,
491        cells: &[AnyRenderBox],
492        container_width: f64,
493    ) -> f64 {
494        self.a
495            .max_intrinsic_width(app, cells, container_width)
496            .min(self.b.max_intrinsic_width(app, cells, container_width))
497    }
498
499    fn flex(&self, app: &mut App, cells: &[AnyRenderBox]) -> Option<f64> {
500        let a_flex = self.a.flex(app, cells);
501        let b_flex = self.b.flex(app, cells);
502        match (a_flex, b_flex) {
503            (None, _) => b_flex,
504            (Some(_), None) => a_flex,
505            (Some(a_flex), Some(b_flex)) => Some(a_flex.min(b_flex)),
506        }
507    }
508
509    fn as_any(&self) -> &dyn Any {
510        self
511    }
512}
513
514/// Vertical alignment options for cells in [`RenderTable`] objects.
515///
516/// This is specified using [`TableCellParentData`] objects on the parent data of the children
517/// of the [`RenderTable`].
518#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
519pub enum TableCellVerticalAlignment {
520    /// Cells with this alignment are placed with their top at the top of the row.
521    #[default]
522    Top,
523
524    /// Cells with this alignment are vertically centered in the row.
525    Middle,
526
527    /// Cells with this alignment are placed with their bottom at the bottom of the row.
528    Bottom,
529
530    /// Cells with this alignment are aligned such that they all share the same baseline. Cells
531    /// with no baseline are top-aligned instead. The baseline used is specified by
532    /// [`RenderTable::text_baseline`]. It is not valid to use the baseline value if
533    /// [`RenderTable::text_baseline`] is not specified.
534    ///
535    /// This vertical alignment is relatively expensive because it causes the table to compute
536    /// the baseline for each cell in the row.
537    Baseline,
538
539    /// Cells with this alignment are sized to be as tall as the row, then made to fit the row.
540    /// If all the cells have this alignment, then the row will have zero height.
541    Fill,
542
543    /// Cells with this alignment are sized to be the same height as the tallest cell in the
544    /// row.
545    IntrinsicHeight,
546}
547
548/// A table where the columns and rows are sized to fit the contents of the cells.
549pub struct RenderTable {
550    render_object: RenderObjectData,
551    render_box: RenderBoxData,
552    // Children are stored in row-major order.
553    // children.len() must be rows * columns
554    children: Vec<Option<AnyRenderBox>>,
555    columns: usize,
556    rows: usize,
557    column_widths: HashMap<usize, TableColumnWidthRef>,
558    default_column_width: TableColumnWidthRef,
559    text_direction: TextDirection,
560    border: Option<TableBorder>,
561    // row_decorations and row_decoration_painters need to be in sync. They have to either both
562    // be None or have same length.
563    row_decorations: Option<Vec<Option<DecorationRef>>>,
564    row_decoration_painters: Option<Vec<Option<Box<dyn BoxPainter>>>>,
565    configuration: ImageConfiguration,
566    default_vertical_alignment: TableCellVerticalAlignment,
567    text_baseline: Option<TextBaseline>,
568    // cache the table geometry for painting purposes
569    row_tops: Vec<f64>,
570    column_lefts: Option<Vec<f64>>,
571    table_width: f64,
572    baseline_distance: Option<f64>,
573}
574
575impl RenderTable {
576    /// Creates a table render object with no rows or columns.
577    ///
578    /// Dart's `columns`, `rows` and `children` arguments are [`set_columns`](Self::set_columns),
579    /// [`set_rows`](Self::set_rows) and [`set_children`](Self::set_children), and its other named
580    /// arguments are the setters: [`set_column_widths`](Self::set_column_widths) (empty),
581    /// [`set_default_column_width`](Self::set_default_column_width)
582    /// ([`FlexColumnWidth::default_width`]), [`set_border`](Self::set_border),
583    /// [`set_row_decorations`](Self::set_row_decorations),
584    /// [`set_configuration`](Self::set_configuration) ([`ImageConfiguration::EMPTY`]),
585    /// [`set_default_vertical_alignment`](Self::set_default_vertical_alignment)
586    /// ([`TableCellVerticalAlignment::Top`]) and [`set_text_baseline`](Self::set_text_baseline).
587    pub fn new(app: &mut App, text_direction: TextDirection) -> RenderHandle<RenderTable> {
588        RenderHandle::new_box(
589            app,
590            RenderTable {
591                render_object: RenderObjectData::new(),
592                render_box: RenderBoxData::new(),
593                children: Vec::new(),
594                columns: 0,
595                rows: 0,
596                column_widths: HashMap::new(),
597                default_column_width: FlexColumnWidth::default_width(),
598                text_direction,
599                border: None,
600                row_decorations: None,
601                row_decoration_painters: None,
602                configuration: ImageConfiguration::EMPTY,
603                default_vertical_alignment: TableCellVerticalAlignment::Top,
604                text_baseline: None,
605                row_tops: Vec::new(),
606                column_lefts: None,
607                table_width: 0.0,
608                baseline_distance: None,
609            },
610        )
611    }
612
613    /// The number of vertical alignment lines in this table.
614    ///
615    /// Changing the number of columns will remove any children that no longer fit in the
616    /// table.
617    ///
618    /// Changing the number of columns is an expensive operation because the table needs to
619    /// rearrange its internal representation.
620    pub fn columns(self: RenderHandle<Self>, app: &App) -> usize {
621        self.get(app).columns
622    }
623
624    /// Sets [`columns`](Self::columns).
625    pub fn set_columns(self: RenderHandle<Self>, app: &mut App, value: usize) {
626        if value == self.columns(app) {
627            return;
628        }
629        let old_columns = self.columns(app);
630        let rows = self.rows(app);
631        let this = self.get_mut(app);
632        let old_children = std::mem::take(&mut this.children);
633        this.columns = value;
634        let columns = value;
635        this.children = vec![None; columns * rows];
636        let columns_to_copy = columns.min(old_columns);
637        for y in 0..rows {
638            for x in 0..columns_to_copy {
639                this.children[x + y * columns] = old_children[x + y * old_columns];
640            }
641        }
642        if old_columns > columns {
643            for y in 0..rows {
644                for x in columns..old_columns {
645                    let xy = x + y * old_columns;
646                    if let Some(old_child) = old_children[xy] {
647                        self.drop_child(app, old_child.as_object());
648                    }
649                }
650            }
651        }
652        self.mark_needs_layout(app);
653    }
654
655    /// The number of horizontal alignment lines in this table.
656    ///
657    /// Changing the number of rows will remove any children that no longer fit in the table.
658    pub fn rows(self: RenderHandle<Self>, app: &App) -> usize {
659        self.get(app).rows
660    }
661
662    /// Sets [`rows`](Self::rows).
663    pub fn set_rows(self: RenderHandle<Self>, app: &mut App, value: usize) {
664        if value == self.rows(app) {
665            return;
666        }
667        let columns = self.columns(app);
668        if self.get(app).rows > value {
669            for xy in columns * value..self.get(app).children.len() {
670                if let Some(child) = self.get(app).children[xy] {
671                    self.drop_child(app, child.as_object());
672                }
673            }
674        }
675        let this = self.get_mut(app);
676        this.rows = value;
677        this.children.resize(columns * value, None);
678        self.mark_needs_layout(app);
679    }
680
681    /// How the horizontal extents of the columns of this table should be determined.
682    ///
683    /// If the map has no entry for a given column, the table uses the
684    /// [`default_column_width`](Self::default_column_width) instead.
685    ///
686    /// The layout performance of the table depends critically on which column sizing
687    /// algorithms are used here. In particular, [`IntrinsicColumnWidth`] is quite expensive
688    /// because it needs to measure each cell in the column to determine the intrinsic size of
689    /// the column.
690    ///
691    /// This property can never return `None`. If it is set to `None`, and the existing map is
692    /// not empty, then the value is replaced by an empty map. (If it is set to `None` while the
693    /// current value is an empty map, the value is not changed.)
694    pub fn column_widths(
695        self: RenderHandle<Self>,
696        app: &App,
697    ) -> HashMap<usize, TableColumnWidthRef> {
698        self.get(app).column_widths.clone()
699    }
700
701    /// Sets [`column_widths`](Self::column_widths).
702    pub fn set_column_widths(
703        self: RenderHandle<Self>,
704        app: &mut App,
705        value: Option<HashMap<usize, TableColumnWidthRef>>,
706    ) {
707        if self.get(app).column_widths.is_empty() && value.is_none() {
708            return;
709        }
710        self.get_mut(app).column_widths = value.unwrap_or_default();
711        self.mark_needs_layout(app);
712    }
713
714    /// Determines how the width of column with the given index is determined.
715    pub fn set_column_width(
716        self: RenderHandle<Self>,
717        app: &mut App,
718        column: usize,
719        value: TableColumnWidthRef,
720    ) {
721        if self
722            .get(app)
723            .column_widths
724            .get(&column)
725            .is_some_and(|current| Rc::ptr_eq(current, &value))
726        {
727            return;
728        }
729        self.get_mut(app).column_widths.insert(column, value);
730        self.mark_needs_layout(app);
731    }
732
733    /// How to determine with widths of columns that don't have an explicit sizing algorithm.
734    ///
735    /// Specifically, the [`default_column_width`](Self::default_column_width) is used for
736    /// column `i` if `column_widths[i]` is absent.
737    pub fn default_column_width(self: RenderHandle<Self>, app: &App) -> TableColumnWidthRef {
738        Rc::clone(&self.get(app).default_column_width)
739    }
740
741    /// Sets [`default_column_width`](Self::default_column_width).
742    pub fn set_default_column_width(
743        self: RenderHandle<Self>,
744        app: &mut App,
745        value: TableColumnWidthRef,
746    ) {
747        if Rc::ptr_eq(&self.get(app).default_column_width, &value) {
748            return;
749        }
750        self.get_mut(app).default_column_width = value;
751        self.mark_needs_layout(app);
752    }
753
754    /// The direction in which the columns are ordered.
755    pub fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
756        self.get(app).text_direction
757    }
758
759    /// Sets [`text_direction`](Self::text_direction).
760    pub fn set_text_direction(self: RenderHandle<Self>, app: &mut App, value: TextDirection) {
761        if self.get(app).text_direction == value {
762            return;
763        }
764        self.get_mut(app).text_direction = value;
765        self.mark_needs_layout(app);
766    }
767
768    /// The style to use when painting the boundary and interior divisions of the table.
769    pub fn border(self: RenderHandle<Self>, app: &App) -> Option<TableBorder> {
770        self.get(app).border
771    }
772
773    /// Sets [`border`](Self::border).
774    pub fn set_border(self: RenderHandle<Self>, app: &mut App, value: Option<TableBorder>) {
775        if self.border(app) == value {
776            return;
777        }
778        self.get_mut(app).border = value;
779        self.mark_needs_paint(app);
780    }
781
782    /// The decorations to use for each row of the table.
783    ///
784    /// Row decorations fill the horizontal and vertical extent of each row in the table, unlike
785    /// decorations for individual cells, which might not fill either.
786    pub fn row_decorations(self: RenderHandle<Self>, app: &App) -> &[Option<DecorationRef>] {
787        self.get(app).row_decorations.as_deref().unwrap_or(&[])
788    }
789
790    /// Sets [`row_decorations`](Self::row_decorations).
791    pub fn set_row_decorations(
792        self: RenderHandle<Self>,
793        app: &mut App,
794        value: Option<Vec<Option<DecorationRef>>>,
795    ) {
796        let this = self.get_mut(app);
797        this.row_decorations = value;
798        if let Some(painters) = this.row_decoration_painters.take() {
799            for mut painter in painters.into_iter().flatten() {
800                painter.dispose();
801            }
802        }
803        this.row_decoration_painters = this
804            .row_decorations
805            .as_ref()
806            .map(|decorations| decorations.iter().map(|_| None).collect());
807    }
808
809    /// The settings to pass to the [`row_decorations`](Self::row_decorations) when painting, so
810    /// that they can resolve images appropriately. See [`ImageConfiguration`].
811    pub fn configuration(self: RenderHandle<Self>, app: &App) -> &ImageConfiguration {
812        &self.get(app).configuration
813    }
814
815    /// Sets [`configuration`](Self::configuration).
816    pub fn set_configuration(self: RenderHandle<Self>, app: &mut App, value: ImageConfiguration) {
817        if value == self.get(app).configuration {
818            return;
819        }
820        self.get_mut(app).configuration = value;
821        self.mark_needs_paint(app);
822    }
823
824    /// How cells that do not explicitly specify a vertical alignment are aligned vertically.
825    pub fn default_vertical_alignment(
826        self: RenderHandle<Self>,
827        app: &App,
828    ) -> TableCellVerticalAlignment {
829        self.get(app).default_vertical_alignment
830    }
831
832    /// Sets [`default_vertical_alignment`](Self::default_vertical_alignment).
833    pub fn set_default_vertical_alignment(
834        self: RenderHandle<Self>,
835        app: &mut App,
836        value: TableCellVerticalAlignment,
837    ) {
838        if self.get(app).default_vertical_alignment == value {
839            return;
840        }
841        self.get_mut(app).default_vertical_alignment = value;
842        self.mark_needs_layout(app);
843    }
844
845    /// The text baseline to use when aligning rows using
846    /// [`TableCellVerticalAlignment::Baseline`].
847    pub fn text_baseline(self: RenderHandle<Self>, app: &App) -> Option<TextBaseline> {
848        self.get(app).text_baseline
849    }
850
851    /// Sets [`text_baseline`](Self::text_baseline).
852    pub fn set_text_baseline(self: RenderHandle<Self>, app: &mut App, value: Option<TextBaseline>) {
853        if self.get(app).text_baseline == value {
854            return;
855        }
856        self.get_mut(app).text_baseline = value;
857        self.mark_needs_layout(app);
858    }
859
860    /// Replaces the children of this table with the given cells.
861    ///
862    /// The cells are divided into the specified number of columns before replacing the
863    /// existing children.
864    ///
865    /// If the new cells contain any existing children of the table, those children are moved
866    /// to their new location in the table rather than removed from the table and re-added.
867    pub fn set_flat_children(
868        self: RenderHandle<Self>,
869        app: &mut App,
870        columns: usize,
871        cells: Vec<Option<AnyRenderBox>>,
872    ) {
873        // consider the case of a newly empty table
874        if columns == 0 || cells.is_empty() {
875            debug_assert!(cells.is_empty());
876            self.get_mut(app).columns = columns;
877            if self.get(app).children.is_empty() {
878                debug_assert_eq!(self.get(app).rows, 0);
879                return;
880            }
881            let old_children = std::mem::take(&mut self.get_mut(app).children);
882            for old_child in old_children.into_iter().flatten() {
883                self.drop_child(app, old_child.as_object());
884            }
885            self.get_mut(app).rows = 0;
886            self.mark_needs_layout(app);
887            return;
888        }
889        debug_assert!(cells.len().is_multiple_of(columns));
890        let (old_columns, old_rows) = (self.get(app).columns, self.get(app).rows);
891        // fill a set with the cells that are moving (it's important not to drop_child a child
892        // that's remaining with us, because that would clear their parent data field)
893        let mut lost_children: HashSet<AnyRenderBox> = HashSet::new();
894        for y in 0..old_rows {
895            for x in 0..old_columns {
896                let xy_old = x + y * old_columns;
897                let xy_new = x + y * columns;
898                if let Some(old_child) = self.get(app).children[xy_old]
899                    && (x >= columns || xy_new >= cells.len() || Some(old_child) != cells[xy_new])
900                {
901                    lost_children.insert(old_child);
902                }
903            }
904        }
905        // adopt cells that are arriving, and cross cells that are just moving off our list of
906        // lost_children
907        let mut y = 0;
908        while y * columns < cells.len() {
909            for x in 0..columns {
910                let xy_new = x + y * columns;
911                let xy_old = x + y * old_columns;
912                if let Some(cell) = cells[xy_new]
913                    && (x >= old_columns
914                        || y >= old_rows
915                        || self.get(app).children[xy_old] != Some(cell))
916                    && !lost_children.remove(&cell)
917                {
918                    self.adopt_child(app, cell.as_object());
919                }
920            }
921            y += 1;
922        }
923        // drop all the lost children
924        for child in lost_children {
925            self.drop_child(app, child.as_object());
926        }
927        // update our internal values
928        let this = self.get_mut(app);
929        this.columns = columns;
930        this.rows = cells.len() / columns;
931        this.children = cells;
932        debug_assert_eq!(this.children.len(), this.rows * this.columns);
933        self.mark_needs_layout(app);
934    }
935
936    /// Replaces the children of this table with the given cells.
937    pub fn set_children(
938        self: RenderHandle<Self>,
939        app: &mut App,
940        cells: Option<Vec<Vec<AnyRenderBox>>>,
941    ) {
942        // TODO(ianh): Make this smarter, like set_flat_children
943        let Some(cells) = cells else {
944            self.set_flat_children(app, 0, Vec::new());
945            return;
946        };
947        let old_children = std::mem::take(&mut self.get_mut(app).children);
948        for old_child in old_children.into_iter().flatten() {
949            self.drop_child(app, old_child.as_object());
950        }
951        let this = self.get_mut(app);
952        this.columns = cells.first().map_or(0, Vec::len);
953        this.rows = 0;
954        for row in cells {
955            self.add_row(app, row.into_iter().map(Some).collect());
956        }
957        debug_assert_eq!(
958            self.get(app).children.len(),
959            self.rows(app) * self.columns(app)
960        );
961    }
962
963    /// Adds a row to the end of the table.
964    ///
965    /// The newly added children must not already have parents.
966    pub fn add_row(self: RenderHandle<Self>, app: &mut App, cells: Vec<Option<AnyRenderBox>>) {
967        debug_assert_eq!(cells.len(), self.columns(app));
968        debug_assert_eq!(
969            self.get(app).children.len(),
970            self.rows(app) * self.columns(app)
971        );
972        let this = self.get_mut(app);
973        this.rows += 1;
974        this.children.extend(cells.iter().copied());
975        for cell in cells.into_iter().flatten() {
976            self.adopt_child(app, cell.as_object());
977        }
978        self.mark_needs_layout(app);
979    }
980
981    /// Replaces the child at the given position with the given child.
982    ///
983    /// If the given child is already located at the given position, this function does not
984    /// modify the table. Otherwise, the given child must not already have a parent.
985    pub fn set_child(
986        self: RenderHandle<Self>,
987        app: &mut App,
988        x: usize,
989        y: usize,
990        value: Option<AnyRenderBox>,
991    ) {
992        debug_assert!(x < self.columns(app) && y < self.rows(app));
993        debug_assert_eq!(
994            self.get(app).children.len(),
995            self.rows(app) * self.columns(app)
996        );
997        let xy = x + y * self.columns(app);
998        let old_child = self.get(app).children[xy];
999        if old_child == value {
1000            return;
1001        }
1002        if let Some(old_child) = old_child {
1003            self.drop_child(app, old_child.as_object());
1004        }
1005        self.get_mut(app).children[xy] = value;
1006        if let Some(value) = value {
1007            self.adopt_child(app, value.as_object());
1008        }
1009    }
1010
1011    /// Returns the list of [`RenderBox`] objects that are in the given column, in row order,
1012    /// starting from the first row.
1013    pub fn column(self: RenderHandle<Self>, app: &App, x: usize) -> Vec<AnyRenderBox> {
1014        let this = self.get(app);
1015        (0..this.rows)
1016            .filter_map(|y| this.children[x + y * this.columns])
1017            .collect()
1018    }
1019
1020    /// Returns the list of [`RenderBox`] objects that are on the given row, in column order,
1021    /// starting with the first column.
1022    pub fn row(self: RenderHandle<Self>, app: &App, y: usize) -> Vec<AnyRenderBox> {
1023        let this = self.get(app);
1024        let start = y * this.columns;
1025        let end = (y + 1) * this.columns;
1026        this.children[start..end]
1027            .iter()
1028            .flatten()
1029            .copied()
1030            .collect()
1031    }
1032
1033    /// The column width the table uses for column `x`.
1034    fn column_width_for(self: RenderHandle<Self>, app: &App, x: usize) -> TableColumnWidthRef {
1035        let this = self.get(app);
1036        Rc::clone(
1037            this.column_widths
1038                .get(&x)
1039                .unwrap_or(&this.default_column_width),
1040        )
1041    }
1042
1043    fn compute_column_widths(
1044        self: RenderHandle<Self>,
1045        app: &mut App,
1046        constraints: BoxConstraints,
1047    ) -> Vec<f64> {
1048        let columns = self.columns(app);
1049        debug_assert_eq!(self.get(app).children.len(), self.rows(app) * columns);
1050        // We apply the constraints to the column widths in the order of
1051        // least important to most important:
1052        // 1. apply the ideal widths (max_intrinsic_width)
1053        // 2. grow the flex columns so that the table has the max_width (if
1054        //    finite) or the min_width (if not)
1055        // 3. if there were no flex columns, then grow the table to the
1056        //    min_width.
1057        // 4. apply the maximum width of the table, shrinking columns as
1058        //    necessary, applying minimum column widths as we go
1059
1060        // 1. apply ideal widths, and collect information we'll need later
1061        let mut widths = vec![0.0; columns];
1062        let mut min_widths = vec![0.0; columns];
1063        let mut flexes: Vec<Option<f64>> = vec![None; columns];
1064        let mut table_width = 0.0; // running tally of the sum of widths[x] for all x
1065        let mut unflexed_table_width = 0.0; // sum of the max_intrinsic_widths of any column that has None flex
1066        let mut total_flex = 0.0;
1067        for x in 0..columns {
1068            let column_width = self.column_width_for(app, x);
1069            let column_cells = self.column(app, x);
1070            // apply ideal width (max_intrinsic_width)
1071            let max_intrinsic_width =
1072                column_width.max_intrinsic_width(app, &column_cells, constraints.max_width);
1073            debug_assert!(max_intrinsic_width.is_finite());
1074            debug_assert!(max_intrinsic_width >= 0.0);
1075            widths[x] = max_intrinsic_width;
1076            table_width += max_intrinsic_width;
1077            // collect min width information while we're at it
1078            let min_intrinsic_width =
1079                column_width.min_intrinsic_width(app, &column_cells, constraints.max_width);
1080            debug_assert!(min_intrinsic_width.is_finite());
1081            debug_assert!(min_intrinsic_width >= 0.0);
1082            min_widths[x] = min_intrinsic_width;
1083            debug_assert!(max_intrinsic_width >= min_intrinsic_width);
1084            // collect flex information while we're at it
1085            let flex = column_width.flex(app, &column_cells);
1086            if let Some(flex) = flex {
1087                debug_assert!(flex.is_finite());
1088                debug_assert!(flex > 0.0);
1089                flexes[x] = Some(flex);
1090                total_flex += flex;
1091            } else {
1092                unflexed_table_width += max_intrinsic_width;
1093            }
1094        }
1095        let max_width_constraint = constraints.max_width;
1096        let min_width_constraint = constraints.min_width;
1097
1098        // 2. grow the flex columns so that the table has the max_width (if
1099        //    finite) or the min_width (if not)
1100        if total_flex > 0.0 {
1101            // this can only grow the table, but it _will_ grow the table at
1102            // least as big as the target width.
1103            let target_width = if max_width_constraint.is_finite() {
1104                max_width_constraint
1105            } else {
1106                min_width_constraint
1107            };
1108            if table_width < target_width {
1109                let remaining_width = target_width - unflexed_table_width;
1110                debug_assert!(remaining_width.is_finite());
1111                debug_assert!(remaining_width >= 0.0);
1112                for x in 0..columns {
1113                    if let Some(flex) = flexes[x] {
1114                        let flexed_width = remaining_width * flex / total_flex;
1115                        debug_assert!(flexed_width.is_finite());
1116                        debug_assert!(flexed_width >= 0.0);
1117                        if widths[x] < flexed_width {
1118                            let delta = flexed_width - widths[x];
1119                            table_width += delta;
1120                            widths[x] = flexed_width;
1121                        }
1122                    }
1123                }
1124                debug_assert!(table_width + PRECISION_ERROR_TOLERANCE >= target_width);
1125            }
1126        }
1127        // step 2 and 3 are mutually exclusive
1128        // 3. if there were no flex columns, then grow the table to the
1129        //    min_width.
1130        else if table_width < min_width_constraint {
1131            let delta = (min_width_constraint - table_width) / columns as f64;
1132            for width in &mut widths {
1133                *width += delta;
1134            }
1135            table_width = min_width_constraint;
1136        }
1137
1138        // beyond this point, unflexed_table_width is no longer valid
1139
1140        // 4. apply the maximum width of the table, shrinking columns as
1141        //    necessary, applying minimum column widths as we go
1142        if table_width > max_width_constraint {
1143            let mut deficit = table_width - max_width_constraint;
1144            // Some columns may have low flex but have all the free space.
1145            // (Consider a case with a 1px wide column of flex 1000.0 and
1146            // a 1000px wide column of flex 1.0; the sizes coming from the
1147            // max_intrinsic_widths. If the maximum table width is 2px, then
1148            // just applying the flexes to the deficit would result in a
1149            // table with one column at -998px and one column at 990px,
1150            // which is wildly unhelpful.)
1151            // Similarly, some columns may be flexible, but not actually
1152            // be shrinkable due to a large minimum width. (Consider a
1153            // case with two columns, one is flex and one isn't, both have
1154            // 1000px max_intrinsic_widths, but the flex one has 1000px
1155            // min_intrinsic_width also. The whole deficit will have to come
1156            // from the non-flex column.)
1157            // So what we do is we repeatedly iterate through the flexible
1158            // columns shrinking them proportionally until we have no
1159            // available columns, then do the same to the non-flexible ones.
1160            let mut available_columns = columns;
1161            while deficit > PRECISION_ERROR_TOLERANCE && total_flex > PRECISION_ERROR_TOLERANCE {
1162                let mut new_total_flex = 0.0;
1163                for x in 0..columns {
1164                    if let Some(flex) = flexes[x] {
1165                        let new_width = widths[x] - deficit * flex / total_flex;
1166                        debug_assert!(new_width.is_finite());
1167                        if new_width <= min_widths[x] {
1168                            // shrank to minimum
1169                            deficit -= widths[x] - min_widths[x];
1170                            widths[x] = min_widths[x];
1171                            flexes[x] = None;
1172                            available_columns -= 1;
1173                        } else {
1174                            deficit -= widths[x] - new_width;
1175                            widths[x] = new_width;
1176                            new_total_flex += flex;
1177                        }
1178                        debug_assert!(widths[x] >= 0.0);
1179                    }
1180                }
1181                total_flex = new_total_flex;
1182            }
1183            while deficit > PRECISION_ERROR_TOLERANCE && available_columns > 0 {
1184                // Now we have to take out the remaining space from the
1185                // columns that aren't minimum sized.
1186                // To make this fair, we repeatedly remove equal amounts from
1187                // each column, clamped to the minimum width, until we run out
1188                // of columns that aren't at their min_width.
1189                let delta = deficit / available_columns as f64;
1190                debug_assert!(delta != 0.0);
1191                let mut new_available_columns = 0;
1192                for x in 0..columns {
1193                    let available_delta = widths[x] - min_widths[x];
1194                    if available_delta > 0.0 {
1195                        if available_delta <= delta {
1196                            // shrank to minimum
1197                            deficit -= widths[x] - min_widths[x];
1198                            widths[x] = min_widths[x];
1199                        } else {
1200                            deficit -= delta;
1201                            widths[x] -= delta;
1202                            new_available_columns += 1;
1203                        }
1204                    }
1205                }
1206                available_columns = new_available_columns;
1207            }
1208        }
1209        widths
1210    }
1211
1212    /// Returns the position and dimensions of the box that the given row covers, in this render
1213    /// object's coordinate space (so the left coordinate is always 0.0).
1214    ///
1215    /// The row being queried must exist.
1216    ///
1217    /// This is only valid after layout.
1218    pub fn get_row_box(self: RenderHandle<Self>, app: &App, row: usize) -> Rect {
1219        debug_assert!(row < self.rows(app));
1220        debug_assert!(!self.debug_needs_layout(app));
1221        let row_tops = &self.get(app).row_tops;
1222        Rect::from_ltrb(
1223            0.0,
1224            row_tops[row],
1225            self.size(app).width(),
1226            row_tops[row + 1],
1227        )
1228    }
1229
1230    /// The vertical alignment of `child`: its own, else the table's default.
1231    fn vertical_alignment_of(
1232        self: RenderHandle<Self>,
1233        app: &App,
1234        child: AnyRenderBox,
1235    ) -> TableCellVerticalAlignment {
1236        child
1237            .as_object()
1238            .parent_data_of::<TableCellParentData>(app)
1239            .vertical_alignment
1240            .unwrap_or(self.get(app).default_vertical_alignment)
1241    }
1242
1243    fn set_child_offset(app: &mut App, child: AnyRenderBox, offset: Offset) {
1244        child.parent_data_of_mut::<BoxParentData>(app).offset = offset;
1245    }
1246}
1247
1248impl RenderObject for RenderTable {
1249    crate::render_object_accessors!();
1250
1251    fn debug_fill_properties(
1252        self: RenderHandle<Self>,
1253        app: &App,
1254        properties: &mut DiagnosticPropertiesBuilder,
1255    ) {
1256        let this = self.get(app);
1257        properties.add(
1258            DiagnosticsProperty::<TableBorder>::new("border", this.border).default_value(None),
1259        );
1260        let column_widths = {
1261            let mut keys: Vec<&usize> = this.column_widths.keys().collect();
1262            keys.sort();
1263            format!(
1264                "{{{}}}",
1265                keys.into_iter()
1266                    .map(|key| format!("{key}: {}", this.column_widths[key]))
1267                    .collect::<Vec<_>>()
1268                    .join(", ")
1269            )
1270        };
1271        properties.add(
1272            DiagnosticsProperty::<String>::new("specified column widths", Some(column_widths))
1273                .with_level(if this.column_widths.is_empty() {
1274                    DiagnosticLevel::Hidden
1275                } else {
1276                    DiagnosticLevel::Info
1277                }),
1278        );
1279        properties.add(DiagnosticsProperty::<TableColumnWidthRef>::new(
1280            "default column width",
1281            Some(Rc::clone(&this.default_column_width)),
1282        ));
1283        properties.add(MessageProperty::new(
1284            "table size",
1285            format!("{}\u{00D7}{}", this.columns, this.rows),
1286        ));
1287        properties.add(
1288            IterableProperty::<String>::new(
1289                "column offsets",
1290                this.column_lefts.as_ref().map(|lefts| {
1291                    lefts
1292                        .iter()
1293                        .map(|left| debug_format_double(Some(*left)))
1294                        .collect()
1295                }),
1296            )
1297            .if_null("unknown"),
1298        );
1299        properties.add(
1300            IterableProperty::<String>::new(
1301                "row offsets",
1302                this.row_tops
1303                    .iter()
1304                    .map(|top| debug_format_double(Some(*top)))
1305                    .collect::<Vec<_>>(),
1306            )
1307            .if_null("unknown"),
1308        );
1309    }
1310
1311    fn debug_describe_children(
1312        self: RenderHandle<Self>,
1313        app: &App,
1314    ) -> Vec<Rc<dyn DiagnosticsNode>> {
1315        let this = self.get(app);
1316        if this.children.is_empty() {
1317            return vec![Rc::new(message("table is empty")) as Rc<dyn DiagnosticsNode>];
1318        }
1319        let mut children: Vec<Rc<dyn DiagnosticsNode>> = Vec::new();
1320        for y in 0..this.rows {
1321            for x in 0..this.columns {
1322                let name = format!("child ({x}, {y})");
1323                match this.children[x + y * this.columns] {
1324                    Some(child) => {
1325                        children.push(Rc::new(child.as_object().to_diagnostics_node(app, name)))
1326                    }
1327                    None => children.push(Rc::new(
1328                        DiagnosticsProperty::<String>::new(name, None)
1329                            .if_null("is null")
1330                            .with_show_separator(false),
1331                    )),
1332                }
1333            }
1334        }
1335        children
1336    }
1337
1338    fn did_detach(self: RenderHandle<Self>, app: &mut App) {
1339        let this = self.get_mut(app);
1340        if let Some(painters) = this.row_decoration_painters.take() {
1341            for mut painter in painters.into_iter().flatten() {
1342                painter.dispose();
1343            }
1344            let decorations = this.row_decorations.as_ref().map_or(0, Vec::len);
1345            this.row_decoration_painters = Some((0..decorations).map(|_| None).collect());
1346        }
1347        let children = self.get(app).children.clone();
1348        for child in children.into_iter().flatten() {
1349            child.as_object().detach(app);
1350        }
1351    }
1352
1353    fn visit_children(
1354        self: RenderHandle<Self>,
1355        app: &App,
1356        visitor: &mut dyn FnMut(AnyRenderObject),
1357    ) {
1358        let this = self.get(app);
1359        debug_assert_eq!(this.children.len(), this.rows * this.columns);
1360        for child in this.children.iter().flatten() {
1361            visitor(child.as_object());
1362        }
1363    }
1364
1365    fn perform_layout(self: RenderHandle<Self>, app: &mut App) {
1366        let constraints = self.constraints(app);
1367        let rows = self.rows(app);
1368        let columns = self.columns(app);
1369        debug_assert_eq!(self.get(app).children.len(), rows * columns);
1370        if rows * columns == 0 {
1371            // TODO(ianh): if columns is zero, this should be zero width
1372            // TODO(ianh): if columns is not zero, this should be based on the column width
1373            // specifications
1374            self.get_mut(app).table_width = 0.0;
1375            self.set_size(app, constraints.constrain(Size::ZERO));
1376            return;
1377        }
1378        let widths = self.compute_column_widths(app, constraints);
1379        let mut positions = vec![0.0; columns];
1380        let (column_lefts, table_width) = match self.text_direction(app) {
1381            TextDirection::Rtl => {
1382                positions[columns - 1] = 0.0;
1383                for x in (0..columns - 1).rev() {
1384                    positions[x] = positions[x + 1] + widths[x + 1];
1385                }
1386                let table_width = positions[0] + widths[0];
1387                (positions.iter().rev().copied().collect(), table_width)
1388            }
1389            TextDirection::Ltr => {
1390                positions[0] = 0.0;
1391                for x in 1..columns {
1392                    positions[x] = positions[x - 1] + widths[x - 1];
1393                }
1394                let table_width = positions[columns - 1] + widths[columns - 1];
1395                (positions.clone(), table_width)
1396            }
1397        };
1398        let this = self.get_mut(app);
1399        this.column_lefts = Some(column_lefts);
1400        this.table_width = table_width;
1401        this.row_tops.clear();
1402        this.baseline_distance = None;
1403        // then, lay out each row
1404        let mut row_top = 0.0;
1405        for y in 0..rows {
1406            self.get_mut(app).row_tops.push(row_top);
1407            let mut row_height: f64 = 0.0;
1408            let mut have_baseline = false;
1409            let mut before_baseline_distance: f64 = 0.0;
1410            let mut after_baseline_distance: f64 = 0.0;
1411            let mut baselines = vec![0.0; columns];
1412            for x in 0..columns {
1413                let xy = x + y * columns;
1414                let Some(child) = self.get(app).children[xy] else {
1415                    continue;
1416                };
1417                let child_parent_data = child
1418                    .as_object()
1419                    .parent_data_of_mut::<TableCellParentData>(app);
1420                child_parent_data.x = Some(x);
1421                child_parent_data.y = Some(y);
1422                match self.vertical_alignment_of(app, child) {
1423                    TableCellVerticalAlignment::Baseline => {
1424                        let text_baseline = self.text_baseline(app).expect(
1425                            "An explicit textBaseline is required when using baseline alignment.",
1426                        );
1427                        child.layout(app, BoxConstraints::tight_for(Some(widths[x]), None), true);
1428                        let child_baseline =
1429                            child.get_distance_to_baseline(app, text_baseline, true);
1430                        if let Some(child_baseline) = child_baseline {
1431                            before_baseline_distance = before_baseline_distance.max(child_baseline);
1432                            after_baseline_distance = after_baseline_distance
1433                                .max(child.size(app).height() - child_baseline);
1434                            baselines[x] = child_baseline;
1435                            have_baseline = true;
1436                        } else {
1437                            row_height = row_height.max(child.size(app).height());
1438                            RenderTable::set_child_offset(
1439                                app,
1440                                child,
1441                                Offset::new(positions[x], row_top),
1442                            );
1443                        }
1444                    }
1445                    TableCellVerticalAlignment::Top
1446                    | TableCellVerticalAlignment::Middle
1447                    | TableCellVerticalAlignment::Bottom
1448                    | TableCellVerticalAlignment::IntrinsicHeight => {
1449                        child.layout(app, BoxConstraints::tight_for(Some(widths[x]), None), true);
1450                        row_height = row_height.max(child.size(app).height());
1451                    }
1452                    TableCellVerticalAlignment::Fill => {}
1453                }
1454            }
1455            if have_baseline {
1456                if y == 0 {
1457                    self.get_mut(app).baseline_distance = Some(before_baseline_distance);
1458                }
1459                row_height = row_height.max(before_baseline_distance + after_baseline_distance);
1460            }
1461            for x in 0..columns {
1462                let xy = x + y * columns;
1463                let Some(child) = self.get(app).children[xy] else {
1464                    continue;
1465                };
1466                match self.vertical_alignment_of(app, child) {
1467                    TableCellVerticalAlignment::Baseline => {
1468                        RenderTable::set_child_offset(
1469                            app,
1470                            child,
1471                            Offset::new(
1472                                positions[x],
1473                                row_top + before_baseline_distance - baselines[x],
1474                            ),
1475                        );
1476                    }
1477                    TableCellVerticalAlignment::Top => {
1478                        RenderTable::set_child_offset(
1479                            app,
1480                            child,
1481                            Offset::new(positions[x], row_top),
1482                        );
1483                    }
1484                    TableCellVerticalAlignment::Middle => {
1485                        let offset = Offset::new(
1486                            positions[x],
1487                            row_top + (row_height - child.size(app).height()) / 2.0,
1488                        );
1489                        RenderTable::set_child_offset(app, child, offset);
1490                    }
1491                    TableCellVerticalAlignment::Bottom => {
1492                        let offset = Offset::new(
1493                            positions[x],
1494                            row_top + row_height - child.size(app).height(),
1495                        );
1496                        RenderTable::set_child_offset(app, child, offset);
1497                    }
1498                    TableCellVerticalAlignment::Fill
1499                    | TableCellVerticalAlignment::IntrinsicHeight => {
1500                        child.layout(
1501                            app,
1502                            BoxConstraints::tight_for(Some(widths[x]), Some(row_height)),
1503                            false,
1504                        );
1505                        RenderTable::set_child_offset(
1506                            app,
1507                            child,
1508                            Offset::new(positions[x], row_top),
1509                        );
1510                    }
1511                }
1512            }
1513            row_top += row_height;
1514        }
1515        self.get_mut(app).row_tops.push(row_top);
1516        let table_width = self.get(app).table_width;
1517        self.set_size(app, constraints.constrain(Size::new(table_width, row_top)));
1518        debug_assert_eq!(self.get(app).row_tops.len(), rows + 1);
1519    }
1520
1521    fn paint(
1522        self: RenderHandle<Self>,
1523        app: &mut App,
1524        context: &mut PaintingContext,
1525        offset: Offset,
1526    ) {
1527        let rows = self.rows(app);
1528        let columns = self.columns(app);
1529        debug_assert_eq!(self.get(app).children.len(), rows * columns);
1530        if rows * columns == 0 {
1531            if let Some(border) = self.border(app) {
1532                let border_rect =
1533                    Rect::from_ltwh(offset.dx(), offset.dy(), self.get(app).table_width, 0.0);
1534                border.paint(context.canvas(), border_rect, &[], &[]);
1535            }
1536            return;
1537        }
1538        debug_assert_eq!(self.get(app).row_tops.len(), rows + 1);
1539        if self.get(app).row_decorations.is_some() {
1540            let size = self.size(app);
1541            let this = self.get_mut(app);
1542            let decorations = this.row_decorations.as_ref().expect("checked above");
1543            let painters = this
1544                .row_decoration_painters
1545                .as_mut()
1546                .expect("in sync with the decorations");
1547            debug_assert_eq!(decorations.len(), painters.len());
1548            let canvas = context.canvas();
1549            for y in 0..rows {
1550                if decorations.len() <= y {
1551                    break;
1552                }
1553                if let Some(decoration) = &decorations[y] {
1554                    let painter = painters[y].get_or_insert_with(|| {
1555                        decoration.create_box_painter(Some(Rc::new(move |app| {
1556                            self.mark_needs_paint(app)
1557                        })))
1558                    });
1559                    let row_size = Size::new(size.width(), this.row_tops[y + 1] - this.row_tops[y]);
1560                    painter.paint(
1561                        canvas,
1562                        Offset::new(offset.dx(), offset.dy() + this.row_tops[y]),
1563                        &this
1564                            .configuration
1565                            .copy_with(None, None, None, None, Some(row_size), None),
1566                    );
1567                }
1568            }
1569        }
1570        let children = self.get(app).children.clone();
1571        for child in children.into_iter().flatten() {
1572            let child_offset = child.box_parent_data(app).offset;
1573            context.paint_child(app, child.as_object(), child_offset + offset);
1574        }
1575        debug_assert_eq!(rows, self.get(app).row_tops.len() - 1);
1576        debug_assert_eq!(
1577            Some(columns),
1578            self.get(app).column_lefts.as_ref().map(Vec::len)
1579        );
1580        if let Some(border) = self.border(app) {
1581            // The border rect might not fill the entire height of this render object
1582            // if the rows underflow. We always force the columns to fill the width of
1583            // the render object, which means the columns cannot underflow.
1584            let this = self.get(app);
1585            let row_tops = &this.row_tops;
1586            let border_rect = Rect::from_ltwh(
1587                offset.dx(),
1588                offset.dy(),
1589                this.table_width,
1590                row_tops[row_tops.len() - 1],
1591            );
1592            let rows = row_tops[1..row_tops.len() - 1].to_vec();
1593            let columns = this.column_lefts.as_ref().expect("laid out")[1..].to_vec();
1594            border.paint(context.canvas(), border_rect, &rows, &columns);
1595        }
1596    }
1597}
1598
1599impl RenderBox for RenderTable {
1600    crate::render_box_accessors!();
1601
1602    fn setup_parent_data(self: RenderHandle<Self>, app: &mut App, child: AnyRenderObject) {
1603        if !child.parent_data_is::<TableCellParentData>(app) {
1604            child.set_parent_data(app, TableCellParentData::new());
1605        }
1606    }
1607
1608    fn compute_min_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
1609        let (rows, columns) = (self.rows(app), self.columns(app));
1610        debug_assert_eq!(self.get(app).children.len(), rows * columns);
1611        if rows * columns == 0 {
1612            return 0.0;
1613        }
1614        let mut total_min_width = 0.0;
1615        for x in 0..columns {
1616            let column_width = self.column_width_for(app, x);
1617            let column_cells = self.column(app, x);
1618            total_min_width += column_width.min_intrinsic_width(app, &column_cells, f64::INFINITY);
1619        }
1620        total_min_width
1621    }
1622
1623    fn compute_max_intrinsic_width(self: RenderHandle<Self>, app: &mut App, _height: f64) -> f64 {
1624        let (rows, columns) = (self.rows(app), self.columns(app));
1625        debug_assert_eq!(self.get(app).children.len(), rows * columns);
1626        if rows * columns == 0 {
1627            return 0.0;
1628        }
1629        let mut total_max_width = 0.0;
1630        for x in 0..columns {
1631            let column_width = self.column_width_for(app, x);
1632            let column_cells = self.column(app, x);
1633            total_max_width += column_width.max_intrinsic_width(app, &column_cells, f64::INFINITY);
1634        }
1635        total_max_width
1636    }
1637
1638    fn compute_min_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1639        // winner of the 2016 world's most expensive intrinsic dimension function award
1640        // honorable mention, most likely to improve if taught about memoization award
1641        let (rows, columns) = (self.rows(app), self.columns(app));
1642        debug_assert_eq!(self.get(app).children.len(), rows * columns);
1643        if rows * columns == 0 {
1644            return 0.0;
1645        }
1646        let widths =
1647            self.compute_column_widths(app, BoxConstraints::tight_for_finite(width, f64::INFINITY));
1648        let mut row_top = 0.0;
1649        for y in 0..rows {
1650            let mut row_height: f64 = 0.0;
1651            for (x, &width) in widths.iter().enumerate() {
1652                let xy = x + y * columns;
1653                if let Some(child) = self.get(app).children[xy] {
1654                    row_height = row_height.max(child.get_max_intrinsic_height(app, width));
1655                }
1656            }
1657            row_top += row_height;
1658        }
1659        row_top
1660    }
1661
1662    fn compute_max_intrinsic_height(self: RenderHandle<Self>, app: &mut App, width: f64) -> f64 {
1663        self.as_box().get_min_intrinsic_height(app, width)
1664    }
1665
1666    /// Returns the baseline offset of the cell in the first row with the lowest baseline, and
1667    /// uses [`TableCellVerticalAlignment::Baseline`].
1668    fn compute_distance_to_actual_baseline(
1669        self: RenderHandle<Self>,
1670        app: &mut App,
1671        _baseline: TextBaseline,
1672    ) -> Option<f64> {
1673        debug_assert!(!self.debug_needs_layout(app));
1674        self.get(app).baseline_distance
1675    }
1676
1677    fn compute_dry_baseline(
1678        self: RenderHandle<Self>,
1679        app: &mut App,
1680        constraints: BoxConstraints,
1681        baseline: TextBaseline,
1682    ) -> Option<f64> {
1683        let columns = self.columns(app);
1684        if self.rows(app) * columns == 0 {
1685            return None;
1686        }
1687        let widths = self.compute_column_widths(app, constraints);
1688        let mut baseline_offset: Option<f64> = None;
1689        for (col, &width) in widths.iter().enumerate() {
1690            let Some(child) = self.get(app).children[col] else {
1691                continue;
1692            };
1693            let child_constraints = BoxConstraints::tight_for(Some(width), None);
1694            let child_baseline = match self.vertical_alignment_of(app, child) {
1695                TableCellVerticalAlignment::Baseline => {
1696                    child.get_dry_baseline(app, child_constraints, baseline)
1697                }
1698                TableCellVerticalAlignment::Top
1699                | TableCellVerticalAlignment::Middle
1700                | TableCellVerticalAlignment::Bottom
1701                | TableCellVerticalAlignment::Fill
1702                | TableCellVerticalAlignment::IntrinsicHeight => None,
1703            };
1704            if let Some(child_baseline) = child_baseline
1705                && baseline_offset.is_none_or(|offset| offset < child_baseline)
1706            {
1707                baseline_offset = Some(child_baseline);
1708            }
1709        }
1710        baseline_offset
1711    }
1712
1713    fn compute_dry_layout(
1714        self: RenderHandle<Self>,
1715        app: &mut App,
1716        constraints: BoxConstraints,
1717    ) -> Size {
1718        let (rows, columns) = (self.rows(app), self.columns(app));
1719        if rows * columns == 0 {
1720            return constraints.constrain(Size::ZERO);
1721        }
1722        let widths = self.compute_column_widths(app, constraints);
1723        let table_width: f64 = widths.iter().sum();
1724        let mut row_top = 0.0;
1725        for y in 0..rows {
1726            let mut row_height: f64 = 0.0;
1727            for (x, &width) in widths.iter().enumerate() {
1728                let xy = x + y * columns;
1729                let Some(child) = self.get(app).children[xy] else {
1730                    continue;
1731                };
1732                match self.vertical_alignment_of(app, child) {
1733                    TableCellVerticalAlignment::Baseline => {
1734                        self.debug_cannot_compute_dry_layout(DryLayoutFailure::Reason(
1735                            "TableCellVerticalAlignment.baseline requires a full layout for \
1736                             baseline metrics to be available.",
1737                        ));
1738                        return Size::ZERO;
1739                    }
1740                    TableCellVerticalAlignment::Top
1741                    | TableCellVerticalAlignment::Middle
1742                    | TableCellVerticalAlignment::Bottom
1743                    | TableCellVerticalAlignment::IntrinsicHeight => {
1744                        let child_size =
1745                            child.get_dry_layout(app, BoxConstraints::tight_for(Some(width), None));
1746                        row_height = row_height.max(child_size.height());
1747                    }
1748                    TableCellVerticalAlignment::Fill => {}
1749                }
1750            }
1751            row_top += row_height;
1752        }
1753        constraints.constrain(Size::new(table_width, row_top))
1754    }
1755
1756    fn hit_test_children(
1757        self: RenderHandle<Self>,
1758        app: &mut App,
1759        result: &mut BoxHitTestResult<'_>,
1760        position: Offset,
1761    ) -> bool {
1762        debug_assert_eq!(
1763            self.get(app).children.len(),
1764            self.rows(app) * self.columns(app)
1765        );
1766        let children = self.get(app).children.clone();
1767        for child in children.into_iter().rev().flatten() {
1768            let child_offset = child.box_parent_data(app).offset;
1769            let is_hit = result.add_with_paint_offset(
1770                Some(child_offset),
1771                position,
1772                |result, transformed| {
1773                    debug_assert_eq!(transformed, position - child_offset);
1774                    child.hit_test(app, result, transformed)
1775                },
1776            );
1777            if is_hit {
1778                return true;
1779            }
1780        }
1781        false
1782    }
1783}
1784
1785#[cfg(test)]
1786mod tests {
1787    use waft_embedder::valo::Op;
1788    use waft_embedder::{Color, Radius};
1789    use waft_foundation::AppCell;
1790    use waft_painting::{AlignmentGeometry, BorderRadius, BorderStyle};
1791
1792    use super::*;
1793    use crate::proxy_box::RenderConstrainedBox;
1794    use crate::shifted_box::RenderPositionedBox;
1795    use crate::testing::{
1796        EnginePhase, ignoring_hash_codes, layout, layout_with, painted_ops, pump_frame,
1797    };
1798
1799    fn sized_box(app: &mut App, width: f64, height: f64) -> AnyRenderBox {
1800        RenderConstrainedBox::new(app, BoxConstraints::tight(Size::new(width, height)), None)
1801            .as_box()
1802    }
1803
1804    fn positioned_box(app: &mut App) -> AnyRenderBox {
1805        RenderPositionedBox::new(app, AlignmentGeometry::CENTER, None, None, None, None).as_box()
1806    }
1807
1808    /// The paths `table` paints: Dart's `paints..path()` count over the table.
1809    fn paths_painted(app: &mut App, table: RenderHandle<RenderTable>) -> usize {
1810        painted_ops(app, table.as_object())
1811            .iter()
1812            .filter(|op| matches!(op, Op::DrawPath { .. }))
1813            .count()
1814    }
1815
1816    /// `table_test.dart`: "Table control test; tight".
1817    #[test]
1818    fn an_empty_table_fills_tight_constraints() {
1819        let cell = AppCell::new();
1820        let mut app = cell.borrow_mut();
1821        let table = RenderTable::new(&mut app, TextDirection::Ltr);
1822        layout(&mut app, table.as_box());
1823        assert_eq!(table.size(&app), Size::new(800.0, 600.0));
1824        assert_eq!(
1825            ignoring_hash_codes(&table.as_object().to_string_deep(&app)),
1826            "RenderTable#00000 NEEDS-PAINT\n\
1827             \u{20}│ parentData: <none> (can use size)\n\
1828             \u{20}│ constraints: BoxConstraints(w=800.0, h=600.0)\n\
1829             \u{20}│ size: Size(800.0, 600.0)\n\
1830             \u{20}│ default column width: FlexColumnWidth(1.0)\n\
1831             \u{20}│ table size: 0\u{00D7}0\n\
1832             \u{20}│ column offsets: unknown\n\
1833             \u{20}│ row offsets: []\n\
1834             \u{20}│\n\
1835             \u{20}└─table is empty\n"
1836        );
1837    }
1838
1839    /// `table_test.dart`: "Table control test; loose".
1840    #[test]
1841    fn an_empty_table_is_empty_in_loose_constraints() {
1842        let cell = AppCell::new();
1843        let mut app = cell.borrow_mut();
1844        let table = RenderTable::new(&mut app, TextDirection::Ltr);
1845        let center = RenderPositionedBox::new(
1846            &mut app,
1847            AlignmentGeometry::CENTER,
1848            None,
1849            None,
1850            None,
1851            Some(table.as_box()),
1852        );
1853        layout(&mut app, center.as_box());
1854        assert_eq!(table.size(&app), Size::ZERO);
1855    }
1856
1857    /// `table_test.dart`: "Table control test: constrained flex columns".
1858    #[test]
1859    fn flex_columns_share_the_width() {
1860        let cell = AppCell::new();
1861        let mut app = cell.borrow_mut();
1862        let table = RenderTable::new(&mut app, TextDirection::Ltr);
1863        let children: Vec<AnyRenderBox> = (0..6).map(|_| positioned_box(&mut app)).collect();
1864        table.set_flat_children(&mut app, 6, children.iter().copied().map(Some).collect());
1865        layout_with(
1866            &mut app,
1867            table.as_box(),
1868            Some(BoxConstraints::tight_for(Some(100.0), None)),
1869            AlignmentGeometry::CENTER,
1870            EnginePhase::Layout,
1871        );
1872        let expected_width = 100.0 / 6.0;
1873        for child in children {
1874            assert!((child.size(&app).width() - expected_width).abs() < 1e-10);
1875        }
1876    }
1877
1878    /// `table_test.dart`: "Table test: combinations". Boxes have no baseline, so a baseline
1879    /// row top-aligns them.
1880    #[test]
1881    fn intrinsic_columns_fit_their_widest_cell() {
1882        let cell = AppCell::new();
1883        let mut app = cell.borrow_mut();
1884        let table = RenderTable::new(&mut app, TextDirection::Ltr);
1885        table.set_columns(&mut app, 5);
1886        table.set_rows(&mut app, 5);
1887        table.set_default_column_width(&mut app, Rc::new(IntrinsicColumnWidth::new(None)));
1888        table.set_default_vertical_alignment(&mut app, TableCellVerticalAlignment::Baseline);
1889        table.set_text_baseline(&mut app, Some(TextBaseline::Alphabetic));
1890        let center = RenderPositionedBox::new(
1891            &mut app,
1892            AlignmentGeometry::CENTER,
1893            None,
1894            None,
1895            None,
1896            Some(table.as_box()),
1897        );
1898        layout(&mut app, center.as_box());
1899        assert_eq!(table.size(&app), Size::ZERO);
1900
1901        let tall = sized_box(&mut app, 100.0, 200.0);
1902        table.set_child(&mut app, 2, 4, Some(tall));
1903        pump_frame(&mut app, EnginePhase::Layout);
1904        assert_eq!(table.size(&app), Size::new(100.0, 200.0));
1905
1906        let first = sized_box(&mut app, 10.0, 30.0);
1907        let second = sized_box(&mut app, 20.0, 20.0);
1908        let third = sized_box(&mut app, 30.0, 10.0);
1909        table.set_child(&mut app, 0, 0, Some(first));
1910        table.set_child(&mut app, 1, 0, Some(second));
1911        table.set_child(&mut app, 2, 0, Some(third));
1912        pump_frame(&mut app, EnginePhase::Layout);
1913        assert_eq!(table.size(&app), Size::new(130.0, 230.0));
1914        assert_eq!(
1915            table.get(&app).column_lefts.as_deref(),
1916            Some(&[0.0, 10.0, 30.0, 130.0, 130.0][..])
1917        );
1918        assert_eq!(
1919            table.get(&app).row_tops,
1920            [0.0, 30.0, 30.0, 30.0, 30.0, 230.0]
1921        );
1922        assert_eq!(third.size(&app), Size::new(100.0, 10.0));
1923        assert_eq!(tall.box_parent_data(&app).offset, Offset::new(30.0, 30.0));
1924        let parent_data = third
1925            .as_object()
1926            .parent_data_of::<TableCellParentData>(&app);
1927        assert_eq!((parent_data.x, parent_data.y), (Some(2), Some(0)));
1928        assert_eq!(
1929            ignoring_hash_codes(&table.as_object().to_string_deep(&app)),
1930            "RenderTable#00000 relayoutBoundary=up1 NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE\n\
1931             \u{20}│ parentData: offset=Offset(335.0, 185.0) (can use size)\n\
1932             \u{20}│ constraints: BoxConstraints(0.0<=w<=800.0, 0.0<=h<=600.0)\n\
1933             \u{20}│ size: Size(130.0, 230.0)\n\
1934             \u{20}│ default column width: IntrinsicColumnWidth(flex: null)\n\
1935             \u{20}│ table size: 5\u{00D7}5\n\
1936             \u{20}│ column offsets: 0.0, 10.0, 30.0, 130.0, 130.0\n\
1937             \u{20}│ row offsets: 0.0, 30.0, 30.0, 30.0, 30.0, 230.0\n\
1938             \u{20}│\n\
1939             \u{20}├─child (0, 0): RenderConstrainedBox#00000 relayoutBoundary=up2 NEEDS-PAINT\n\
1940             \u{20}│   parentData: offset=Offset(0.0, 0.0); default vertical alignment\n\
1941             \u{20}│     (can use size)\n\
1942             \u{20}│   constraints: BoxConstraints(w=10.0, 0.0<=h<=Infinity)\n\
1943             \u{20}│   size: Size(10.0, 30.0)\n\
1944             \u{20}│   additionalConstraints: BoxConstraints(w=10.0, h=30.0)\n\
1945             \u{20}│\n\
1946             \u{20}├─child (1, 0): RenderConstrainedBox#00000 relayoutBoundary=up2 NEEDS-PAINT\n\
1947             \u{20}│   parentData: offset=Offset(10.0, 0.0); default vertical alignment\n\
1948             \u{20}│     (can use size)\n\
1949             \u{20}│   constraints: BoxConstraints(w=20.0, 0.0<=h<=Infinity)\n\
1950             \u{20}│   size: Size(20.0, 20.0)\n\
1951             \u{20}│   additionalConstraints: BoxConstraints(w=20.0, h=20.0)\n\
1952             \u{20}│\n\
1953             \u{20}├─child (2, 0): RenderConstrainedBox#00000 relayoutBoundary=up2 NEEDS-PAINT\n\
1954             \u{20}│   parentData: offset=Offset(30.0, 0.0); default vertical alignment\n\
1955             \u{20}│     (can use size)\n\
1956             \u{20}│   constraints: BoxConstraints(w=100.0, 0.0<=h<=Infinity)\n\
1957             \u{20}│   size: Size(100.0, 10.0)\n\
1958             \u{20}│   additionalConstraints: BoxConstraints(w=30.0, h=10.0)\n\
1959             \u{20}│\n\
1960             \u{20}├─child (3, 0) is null\n\
1961             \u{20}├─child (4, 0) is null\n\
1962             \u{20}├─child (0, 1) is null\n\
1963             \u{20}├─child (1, 1) is null\n\
1964             \u{20}├─child (2, 1) is null\n\
1965             \u{20}├─child (3, 1) is null\n\
1966             \u{20}├─child (4, 1) is null\n\
1967             \u{20}├─child (0, 2) is null\n\
1968             \u{20}├─child (1, 2) is null\n\
1969             \u{20}├─child (2, 2) is null\n\
1970             \u{20}├─child (3, 2) is null\n\
1971             \u{20}├─child (4, 2) is null\n\
1972             \u{20}├─child (0, 3) is null\n\
1973             \u{20}├─child (1, 3) is null\n\
1974             \u{20}├─child (2, 3) is null\n\
1975             \u{20}├─child (3, 3) is null\n\
1976             \u{20}├─child (4, 3) is null\n\
1977             \u{20}├─child (0, 4) is null\n\
1978             \u{20}├─child (1, 4) is null\n\
1979             \u{20}├─child (2, 4): RenderConstrainedBox#00000 relayoutBoundary=up2 NEEDS-PAINT\n\
1980             \u{20}│   parentData: offset=Offset(30.0, 30.0); default vertical alignment\n\
1981             \u{20}│     (can use size)\n\
1982             \u{20}│   constraints: BoxConstraints(w=100.0, 0.0<=h<=Infinity)\n\
1983             \u{20}│   size: Size(100.0, 200.0)\n\
1984             \u{20}│   additionalConstraints: BoxConstraints(w=100.0, h=200.0)\n\
1985             \u{20}│\n\
1986             \u{20}├─child (3, 4) is null\n\
1987             \u{20}└─child (4, 4) is null\n"
1988        );
1989    }
1990
1991    /// `table_test.dart`: "Table test: removing cells".
1992    #[test]
1993    fn fewer_rows_drop_the_cells_below() {
1994        let cell = AppCell::new();
1995        let mut app = cell.borrow_mut();
1996        let table = RenderTable::new(&mut app, TextDirection::Ltr);
1997        table.set_columns(&mut app, 5);
1998        table.set_rows(&mut app, 5);
1999        let child = sized_box(&mut app, 10.0, 10.0);
2000        table.set_child(&mut app, 4, 4, Some(child));
2001        layout(&mut app, table.as_box());
2002        assert!(child.as_object().attached(&app));
2003        table.set_rows(&mut app, 4);
2004        assert!(!child.as_object().attached(&app));
2005    }
2006
2007    /// `table_test.dart`: "Table test: replacing cells". A cell that moves keeps its parent.
2008    #[test]
2009    fn moving_cells_keeps_them_in_the_table() {
2010        let cell = AppCell::new();
2011        let mut app = cell.borrow_mut();
2012        let table = RenderTable::new(&mut app, TextDirection::Ltr);
2013        let moving: Vec<AnyRenderBox> = (0..3).map(|_| positioned_box(&mut app)).collect();
2014        let mut cells = Vec::new();
2015        for child in &moving {
2016            cells.push(Some(*child));
2017            cells.push(Some(positioned_box(&mut app)));
2018        }
2019        table.set_flat_children(&mut app, 3, cells);
2020        assert_eq!(table.rows(&app), 2);
2021        layout(&mut app, table.as_box());
2022        for _ in 0..2 {
2023            let mut cells = Vec::new();
2024            for child in &moving {
2025                cells.push(Some(positioned_box(&mut app)));
2026                cells.push(Some(*child));
2027            }
2028            table.set_flat_children(&mut app, 3, cells);
2029            pump_frame(&mut app, EnginePhase::Layout);
2030        }
2031        assert_eq!(table.columns(&app), 3);
2032        assert_eq!(table.rows(&app), 2);
2033        for child in moving {
2034            assert_eq!(child.as_object().parent(&app), Some(table.as_object()));
2035        }
2036    }
2037
2038    /// `table_test.dart`: "Table border painting": the inner lines are one path per direction,
2039    /// after which the outer border paints its four sides.
2040    #[test]
2041    fn a_border_paints_its_inner_lines_and_four_sides() {
2042        let cell = AppCell::new();
2043        let mut app = cell.borrow_mut();
2044        let table = RenderTable::new(&mut app, TextDirection::Rtl);
2045        table.set_border(
2046            &mut app,
2047            Some(TableBorder::all(
2048                Color::new(0xFF000000),
2049                1.0,
2050                BorderStyle::Solid,
2051                BorderRadius::ZERO,
2052            )),
2053        );
2054        layout(&mut app, table.as_box());
2055        for (columns, cells, paths) in [
2056            (1, 0, 4),
2057            (1, 1, 4),
2058            (1, 2, 5),
2059            (2, 2, 5),
2060            (2, 4, 6),
2061            (3, 6, 6),
2062        ] {
2063            let children = (0..cells).map(|_| Some(positioned_box(&mut app))).collect();
2064            table.set_flat_children(&mut app, columns, children);
2065            pump_frame(&mut app, EnginePhase::Layout);
2066            assert_eq!(
2067                paths_painted(&mut app, table),
2068                paths,
2069                "{columns} columns, {cells} cells"
2070            );
2071        }
2072    }
2073
2074    /// `table_test.dart`: "Table paints a borderRadius": a uniform rounded border is one ring
2075    /// after the two inner lines.
2076    #[test]
2077    fn a_rounded_uniform_border_paints_one_ring() {
2078        let cell = AppCell::new();
2079        let mut app = cell.borrow_mut();
2080        let table = RenderTable::new(&mut app, TextDirection::Ltr);
2081        table.set_border(
2082            &mut app,
2083            Some(TableBorder::all(
2084                Color::new(0xFF000000),
2085                1.0,
2086                BorderStyle::Solid,
2087                BorderRadius::all(Radius::circular(8.0)),
2088            )),
2089        );
2090        layout(&mut app, table.as_box());
2091        let children = (0..4).map(|_| Some(positioned_box(&mut app))).collect();
2092        table.set_flat_children(&mut app, 2, children);
2093        pump_frame(&mut app, EnginePhase::Layout);
2094        assert_eq!(paths_painted(&mut app, table), 3);
2095    }
2096
2097    /// Row decorations paint behind each row, filling it.
2098    #[test]
2099    fn row_decorations_paint_behind_their_rows() {
2100        let cell = AppCell::new();
2101        let mut app = cell.borrow_mut();
2102        let table = RenderTable::new(&mut app, TextDirection::Ltr);
2103        let rows = vec![
2104            vec![sized_box(&mut app, 10.0, 10.0)],
2105            vec![sized_box(&mut app, 10.0, 20.0)],
2106        ];
2107        table.set_children(&mut app, Some(rows));
2108        table.set_row_decorations(
2109            &mut app,
2110            Some(vec![
2111                None,
2112                Some(DecorationRef::new(
2113                    waft_painting::BoxDecoration::new().color(Color::new(0xFF0000FF)),
2114                )),
2115            ]),
2116        );
2117        layout_with(
2118            &mut app,
2119            table.as_box(),
2120            Some(BoxConstraints::tight_for(Some(100.0), None)),
2121            AlignmentGeometry::CENTER,
2122            EnginePhase::Layout,
2123        );
2124        let rects: Vec<_> = painted_ops(&mut app, table.as_object())
2125            .into_iter()
2126            .filter_map(|op| match op {
2127                Op::DrawRect { rect, .. } => Some(rect),
2128                _ => None,
2129            })
2130            .collect();
2131        assert_eq!(rects.len(), 1, "only the second row is decorated");
2132        assert_eq!(
2133            table.get_row_box(&app, 1),
2134            Rect::from_ltrb(0.0, 10.0, 100.0, 30.0)
2135        );
2136    }
2137
2138    /// `table_test.dart`: "MaxColumnWidth.flex returns the correct result" and
2139    /// "MinColumnWidth.flex returns the correct result".
2140    #[test]
2141    fn max_and_min_widths_take_the_flex_of_either() {
2142        let cell = AppCell::new();
2143        let mut app = cell.borrow_mut();
2144        let fixed: TableColumnWidthRef = Rc::new(FixedColumnWidth::new(100.0));
2145        let flex: TableColumnWidthRef = Rc::new(FlexColumnWidth::new(1.0));
2146        for width in [
2147            Rc::new(MaxColumnWidth::new(Rc::clone(&fixed), Rc::clone(&flex)))
2148                as TableColumnWidthRef,
2149            Rc::new(MaxColumnWidth::new(Rc::clone(&flex), Rc::clone(&fixed))),
2150            Rc::new(MinColumnWidth::new(Rc::clone(&fixed), Rc::clone(&flex))),
2151            Rc::new(MinColumnWidth::new(Rc::clone(&flex), Rc::clone(&fixed))),
2152        ] {
2153            assert_eq!(width.flex(&mut app, &[]), Some(1.0), "{width:?}");
2154        }
2155    }
2156
2157    /// Fixed and fractional columns take their width; a flexible one takes the rest.
2158    #[test]
2159    fn fixed_fraction_and_flex_columns_divide_the_width() {
2160        let cell = AppCell::new();
2161        let mut app = cell.borrow_mut();
2162        let table = RenderTable::new(&mut app, TextDirection::Ltr);
2163        let children: Vec<AnyRenderBox> = (0..3).map(|_| positioned_box(&mut app)).collect();
2164        table.set_flat_children(&mut app, 3, children.iter().copied().map(Some).collect());
2165        let mut widths: HashMap<usize, TableColumnWidthRef> = HashMap::new();
2166        widths.insert(0, Rc::new(FixedColumnWidth::new(50.0)));
2167        widths.insert(1, Rc::new(FractionColumnWidth::new(0.25)));
2168        table.set_column_widths(&mut app, Some(widths));
2169        layout_with(
2170            &mut app,
2171            table.as_box(),
2172            Some(BoxConstraints::tight_for(Some(400.0), None)),
2173            AlignmentGeometry::CENTER,
2174            EnginePhase::Layout,
2175        );
2176        let widths: Vec<f64> = children
2177            .iter()
2178            .map(|child| child.size(&app).width())
2179            .collect();
2180        assert_eq!(widths, [50.0, 100.0, 250.0]);
2181    }
2182
2183    /// Too little room shrinks no column below its minimum: the flexible column stops at its
2184    /// fixed lower bound, and the table is cut to its constraints.
2185    #[test]
2186    fn no_column_shrinks_below_its_minimum() {
2187        let cell = AppCell::new();
2188        let mut app = cell.borrow_mut();
2189        let table = RenderTable::new(&mut app, TextDirection::Ltr);
2190        let children: Vec<AnyRenderBox> = (0..2).map(|_| positioned_box(&mut app)).collect();
2191        table.set_flat_children(&mut app, 2, children.iter().copied().map(Some).collect());
2192        let mut widths: HashMap<usize, TableColumnWidthRef> = HashMap::new();
2193        widths.insert(0, Rc::new(FixedColumnWidth::new(150.0)));
2194        widths.insert(
2195            1,
2196            Rc::new(MaxColumnWidth::new(
2197                Rc::new(FixedColumnWidth::new(80.0)),
2198                Rc::new(FlexColumnWidth::new(1.0)),
2199            )),
2200        );
2201        table.set_column_widths(&mut app, Some(widths));
2202        layout_with(
2203            &mut app,
2204            table.as_box(),
2205            Some(BoxConstraints::tight_for(Some(200.0), None)),
2206            AlignmentGeometry::CENTER,
2207            EnginePhase::Layout,
2208        );
2209        let widths: Vec<f64> = children
2210            .iter()
2211            .map(|child| child.size(&app).width())
2212            .collect();
2213        assert_eq!(widths, [150.0, 80.0]);
2214        assert_eq!(table.size(&app).width(), 200.0);
2215    }
2216
2217    /// `table_test.dart`: "TableRows with different constraints, but vertically with
2218    /// intrinsicHeight": every cell takes the height of the tallest.
2219    #[test]
2220    fn intrinsic_height_cells_match_the_tallest() {
2221        let cell = AppCell::new();
2222        let mut app = cell.borrow_mut();
2223        let short = RenderConstrainedBox::new(
2224            &mut app,
2225            BoxConstraints::tight_for(Some(100.0), Some(100.0)),
2226            None,
2227        );
2228        let tall = RenderConstrainedBox::new(
2229            &mut app,
2230            BoxConstraints::tight_for(Some(200.0), Some(200.0)),
2231            None,
2232        );
2233        let table = RenderTable::new(&mut app, TextDirection::Rtl);
2234        table.set_default_vertical_alignment(&mut app, TableCellVerticalAlignment::IntrinsicHeight);
2235        table.set_children(&mut app, Some(vec![vec![short.as_box(), tall.as_box()]]));
2236        layout_with(
2237            &mut app,
2238            table.as_box(),
2239            Some(BoxConstraints::tight(Size::new(300.0, 300.0))),
2240            AlignmentGeometry::CENTER,
2241            EnginePhase::Layout,
2242        );
2243        assert_eq!(table.size(&app), Size::new(300.0, 300.0));
2244        assert_eq!(short.size(&app).height(), tall.size(&app).height());
2245    }
2246
2247    /// `table_test.dart`: "Empty table intrinsic dimensions should not crash".
2248    #[test]
2249    fn an_empty_table_has_no_intrinsic_size() {
2250        let cell = AppCell::new();
2251        let mut app = cell.borrow_mut();
2252        let table = RenderTable::new(&mut app, TextDirection::Ltr).as_box();
2253        for extent in [100.0, f64::INFINITY] {
2254            assert_eq!(table.get_min_intrinsic_width(&mut app, extent), 0.0);
2255            assert_eq!(table.get_max_intrinsic_width(&mut app, extent), 0.0);
2256            assert_eq!(table.get_min_intrinsic_height(&mut app, extent), 0.0);
2257            assert_eq!(table.get_max_intrinsic_height(&mut app, extent), 0.0);
2258        }
2259    }
2260
2261    /// The intrinsic widths sum the columns, and the intrinsic height at a width sums the
2262    /// tallest cell of each row; the dry layout matches the layout.
2263    #[test]
2264    fn intrinsics_and_dry_layout_follow_the_cells() {
2265        let cell = AppCell::new();
2266        let mut app = cell.borrow_mut();
2267        let table = RenderTable::new(&mut app, TextDirection::Ltr);
2268        table.set_default_column_width(&mut app, Rc::new(IntrinsicColumnWidth::new(None)));
2269        let rows = vec![
2270            vec![
2271                sized_box(&mut app, 10.0, 30.0),
2272                sized_box(&mut app, 40.0, 5.0),
2273            ],
2274            vec![
2275                sized_box(&mut app, 20.0, 10.0),
2276                sized_box(&mut app, 5.0, 15.0),
2277            ],
2278        ];
2279        table.set_children(&mut app, Some(rows));
2280        let table = table.as_box();
2281        assert_eq!(table.get_min_intrinsic_width(&mut app, f64::INFINITY), 60.0);
2282        assert_eq!(table.get_max_intrinsic_width(&mut app, f64::INFINITY), 60.0);
2283        assert_eq!(table.get_min_intrinsic_height(&mut app, 60.0), 45.0);
2284        assert_eq!(table.get_max_intrinsic_height(&mut app, 60.0), 45.0);
2285        let loose = BoxConstraints::new().max_width(500.0).max_height(500.0);
2286        let dry = table.get_dry_layout(&mut app, loose);
2287        layout_with(
2288            &mut app,
2289            table,
2290            Some(loose),
2291            AlignmentGeometry::CENTER,
2292            EnginePhase::Layout,
2293        );
2294        assert_eq!(dry, Size::new(60.0, 45.0));
2295        assert_eq!(table.size(&app), dry);
2296    }
2297
2298    /// What the shell does at start-up: the app-wide fonts, here the OS fonts.
2299    fn install_fonts(app: &mut App) {
2300        let binding = waft_painting::PaintingBinding::instance(app);
2301        if !binding.has_fonts(app) {
2302            binding.install_fonts(app, |fonts| {
2303                fonts.add_source(valo_system_fonts::SystemFonts::load());
2304            });
2305        }
2306    }
2307
2308    /// Baseline cells share the row's baseline, and the table's baseline is the first row's.
2309    #[test]
2310    fn baseline_cells_share_the_first_rows_baseline() {
2311        use waft_painting::{TextSpan, TextStyle};
2312
2313        use crate::paragraph::RenderParagraph;
2314
2315        let cell = AppCell::new();
2316        let mut app = cell.borrow_mut();
2317        install_fonts(&mut app);
2318        let paragraph = |app: &mut App, font_size: f64| {
2319            let text = TextSpan::new()
2320                .text("Hg")
2321                .style(TextStyle::new().font_size(font_size))
2322                .into_span();
2323            RenderParagraph::new(app, text, TextDirection::Ltr, None).as_box()
2324        };
2325        let small = paragraph(&mut app, 10.0);
2326        let large = paragraph(&mut app, 30.0);
2327        let table = RenderTable::new(&mut app, TextDirection::Ltr);
2328        table.set_default_vertical_alignment(&mut app, TableCellVerticalAlignment::Baseline);
2329        table.set_text_baseline(&mut app, Some(TextBaseline::Alphabetic));
2330        table.set_children(&mut app, Some(vec![vec![small, large]]));
2331        layout_with(
2332            &mut app,
2333            table.as_box(),
2334            Some(BoxConstraints::tight_for(Some(400.0), None)),
2335            AlignmentGeometry::CENTER,
2336            EnginePhase::Layout,
2337        );
2338
2339        let baseline_of = |app: &mut App, child: AnyRenderBox| {
2340            child.box_parent_data(app).offset.dy()
2341                + child
2342                    .get_distance_to_baseline(app, TextBaseline::Alphabetic, true)
2343                    .expect("text has a baseline")
2344        };
2345        let small_baseline = baseline_of(&mut app, small);
2346        let large_baseline = baseline_of(&mut app, large);
2347        assert!((small_baseline - large_baseline).abs() < 1e-9);
2348        assert!(
2349            small.box_parent_data(&app).offset.dy() > 0.0,
2350            "the small text is lowered"
2351        );
2352        assert_eq!(
2353            table
2354                .as_box()
2355                .get_distance_to_baseline(&mut app, TextBaseline::Alphabetic, true),
2356            Some(large_baseline)
2357        );
2358    }
2359}