1use 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#[derive(Debug, Default)]
28pub struct TableCellParentData {
29 box_parent_data: BoxParentData,
30
31 pub vertical_alignment: Option<TableCellVerticalAlignment>,
36
37 pub x: Option<usize>,
39
40 pub y: Option<usize>,
42}
43
44impl TableCellParentData {
45 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
82pub type TableColumnWidthRef = Rc<dyn TableColumnWidth>;
85
86pub trait TableColumnWidth: fmt::Debug {
95 fn min_intrinsic_width(
104 &self,
105 app: &mut App,
106 cells: &[AnyRenderBox],
107 container_width: f64,
108 ) -> f64;
109
110 fn max_intrinsic_width(
122 &self,
123 app: &mut App,
124 cells: &[AnyRenderBox],
125 container_width: f64,
126 ) -> f64;
127
128 fn flex(&self, app: &mut App, cells: &[AnyRenderBox]) -> Option<f64> {
136 let _ = (app, cells);
137 None
138 }
139
140 fn as_any(&self) -> &dyn Any;
142}
143
144pub struct IntrinsicColumnWidth {
151 flex: Option<f64>,
152}
153
154impl IntrinsicColumnWidth {
155 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
218impl PartialEq for dyn TableColumnWidth {
220 fn eq(&self, other: &Self) -> bool {
221 std::ptr::eq(self, other)
222 }
223}
224
225pub struct FixedColumnWidth {
229 pub value: f64,
231}
232
233impl FixedColumnWidth {
234 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
270pub struct FractionColumnWidth {
274 pub value: f64,
276}
277
278impl FractionColumnWidth {
279 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
321pub struct FlexColumnWidth {
329 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 pub const fn new(value: f64) -> FlexColumnWidth {
342 FlexColumnWidth { value }
343 }
344
345 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#[derive(Debug)]
398pub struct MaxColumnWidth {
399 pub a: TableColumnWidthRef,
401 pub b: TableColumnWidthRef,
403}
404
405impl MaxColumnWidth {
406 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#[derive(Debug)]
462pub struct MinColumnWidth {
463 pub a: TableColumnWidthRef,
465 pub b: TableColumnWidthRef,
467}
468
469impl MinColumnWidth {
470 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#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
519pub enum TableCellVerticalAlignment {
520 #[default]
522 Top,
523
524 Middle,
526
527 Bottom,
529
530 Baseline,
538
539 Fill,
542
543 IntrinsicHeight,
546}
547
548pub struct RenderTable {
550 render_object: RenderObjectData,
551 render_box: RenderBoxData,
552 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: 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 row_tops: Vec<f64>,
570 column_lefts: Option<Vec<f64>>,
571 table_width: f64,
572 baseline_distance: Option<f64>,
573}
574
575impl RenderTable {
576 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 pub fn columns(self: RenderHandle<Self>, app: &App) -> usize {
621 self.get(app).columns
622 }
623
624 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 pub fn rows(self: RenderHandle<Self>, app: &App) -> usize {
659 self.get(app).rows
660 }
661
662 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 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 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 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 pub fn default_column_width(self: RenderHandle<Self>, app: &App) -> TableColumnWidthRef {
738 Rc::clone(&self.get(app).default_column_width)
739 }
740
741 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 pub fn text_direction(self: RenderHandle<Self>, app: &App) -> TextDirection {
756 self.get(app).text_direction
757 }
758
759 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 pub fn border(self: RenderHandle<Self>, app: &App) -> Option<TableBorder> {
770 self.get(app).border
771 }
772
773 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 pub fn row_decorations(self: RenderHandle<Self>, app: &App) -> &[Option<DecorationRef>] {
787 self.get(app).row_decorations.as_deref().unwrap_or(&[])
788 }
789
790 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 pub fn configuration(self: RenderHandle<Self>, app: &App) -> &ImageConfiguration {
812 &self.get(app).configuration
813 }
814
815 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 pub fn default_vertical_alignment(
826 self: RenderHandle<Self>,
827 app: &App,
828 ) -> TableCellVerticalAlignment {
829 self.get(app).default_vertical_alignment
830 }
831
832 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 pub fn text_baseline(self: RenderHandle<Self>, app: &App) -> Option<TextBaseline> {
848 self.get(app).text_baseline
849 }
850
851 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 pub fn set_flat_children(
868 self: RenderHandle<Self>,
869 app: &mut App,
870 columns: usize,
871 cells: Vec<Option<AnyRenderBox>>,
872 ) {
873 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 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 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 for child in lost_children {
925 self.drop_child(app, child.as_object());
926 }
927 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 pub fn set_children(
938 self: RenderHandle<Self>,
939 app: &mut App,
940 cells: Option<Vec<Vec<AnyRenderBox>>>,
941 ) {
942 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 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 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 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 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 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 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; let mut unflexed_table_width = 0.0; 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 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 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 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 if total_flex > 0.0 {
1101 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 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 if table_width > max_width_constraint {
1143 let mut deficit = table_width - max_width_constraint;
1144 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 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 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 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 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 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 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 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 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 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 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 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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 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 #[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}