1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
#![doc(html_favicon_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo-icon.png")]
#![doc(html_logo_url = "https://raw.githubusercontent.com/zng-ui/zng/main/examples/image/res/zng-logo.png")]
//!
//! Grid widgets, properties and nodes.
//!
//! # Crate
//!
#![doc = include_str!(concat!("../", std::env!("CARGO_PKG_README")))]
#![warn(unused_extern_crates)]
#![warn(missing_docs)]
use std::{fmt, mem};
use zng_layout::unit::{GridSpacing, PxGridSpacing};
use zng_wgt::prelude::*;
use zng_wgt_access::{access_role, AccessRole};
use zng_wgt_size_offset::*;
/// Grid layout with cells of variable sizes.
#[widget($crate::Grid)]
pub struct Grid(WidgetBase);
impl Grid {
fn widget_intrinsic(&mut self) {
self.widget_builder().push_build_action(|w| {
let child = node(
w.capture_ui_node_list_or_empty(property_id!(Self::cells)),
w.capture_ui_node_list_or_empty(property_id!(Self::columns)),
w.capture_ui_node_list_or_empty(property_id!(Self::rows)),
w.capture_var_or_else(property_id!(Self::auto_grow_fn), WidgetFn::nil),
w.capture_var_or_else(property_id!(Self::auto_grow_mode), AutoGrowMode::rows),
w.capture_var_or_default(property_id!(Self::spacing)),
);
w.set_child(child);
});
widget_set! {
self;
access_role = AccessRole::Grid;
}
}
}
/// Cell widget items.
///
/// Cells can select their own column, row, column-span and row-span using the properties in the [`Cell!`] widget.
/// Note that you don't need to use the cell widget, only the [`cell`] properties.
///
/// If the column or row index is set to [`usize::MAX`] the widget is positioned using the
/// logical index *i*, the column *i % columns* and the row *i / columns*.
///
/// [`Cell!`]: struct@Cell
#[property(CHILD, capture, widget_impl(Grid))]
pub fn cells(cells: impl UiNodeList) {}
/// Column definitions.
///
/// You can define columns with any widget, but the [`Column!`] widget is recommended. The column widget width defines
/// the width of the cells assigned to it, the [`Column::width`] property can be used to enforce a width, otherwise the
/// column is sized by the widest cell.
///
/// The grid uses the [`WIDGET_SIZE`] value to select one of three layout modes for columns:
///
/// * *Default*, used for columns that do not set width or set it to [`Length::Default`].
/// * *Exact*, used for columns that set the width to an unit that is exact or only depends on the grid context.
/// * *Leftover*, used for columns that set width to a [`lft`] value.
///
/// The column layout follows these steps:
///
/// 1 - All *Exact* column widgets are layout, their final width defines the column width.
/// 2 - All cell widgets with span `1` in *Default* columns are measured, the widest defines the fill width constrain,
/// the columns are layout using this constrain, the final width defines the column width.
/// 3 - All *Leftover* cells are layout with the leftover grid width divided among all columns in this mode.
///
/// So given the columns `200 | 1.lft() | 1.lft()` and grid width of `1000` with spacing `5` the final widths are `200 | 395 | 395`,
/// for `200 + 5 + 395 + 5 + 395 = 1000`.
///
/// Note that the column widget is not the parent of the cells that match it, the column widget is rendered under cell and row widgets.
/// Properties like `padding` and `align` only affect the column visual, not the cells, similarly contextual properties like `text_color`
/// don't affect the cells.
///
/// [`Column!`]: struct@Column
/// [`lft`]: zng_layout::unit::LengthUnits::lft
/// [`WIDGET_SIZE`]: zng_wgt_size_offset::WIDGET_SIZE
/// [`Length::Default`]: zng_layout::unit::Length::Default
#[property(CHILD, capture, widget_impl(Grid))]
pub fn columns(cells: impl UiNodeList) {}
/// Row definitions.
///
/// Same behavior as [`columns`], but in the ***y*** dimension.
///
/// [`columns`]: fn@columns
#[property(CHILD, capture, widget_impl(Grid))]
pub fn rows(cells: impl UiNodeList) {}
/// Widget function used when new rows or columns are needed to cover a cell placement.
///
/// The function is used according to the [`auto_grow_mode`]. Note that *imaginary* rows or columns are used if
/// the function is [`WidgetFn::nil`].
///
/// [`auto_grow_mode`]: fn@auto_grow_mode
/// [`WidgetFn::nil`]: zng_wgt::prelude::WidgetFn::nil
#[property(CONTEXT, capture, default(WidgetFn::nil()), widget_impl(Grid))]
pub fn auto_grow_fn(auto_grow: impl IntoVar<WidgetFn<AutoGrowFnArgs>>) {}
/// Defines the direction the grid auto-grows and the maximum inclusive index that can be covered by auto-generated columns or rows.
/// If a cell is outside this index and is not covered by predefined columns or rows a new one is auto generated for it, but if the
/// cell is also outside this max it is *collapsed*.
///
/// Is `AutoGrowMode::rows() by default.
#[property(CONTEXT, capture, default(AutoGrowMode::rows()), widget_impl(Grid))]
pub fn auto_grow_mode(mode: impl IntoVar<AutoGrowMode>) {}
/// Space in-between cells.
#[property(LAYOUT, capture, default(GridSpacing::default()), widget_impl(Grid))]
pub fn spacing(spacing: impl IntoVar<GridSpacing>) {}
/// Grid node.
///
/// Can be used directly to layout widgets without declaring a grid widget info. This node is the child
/// of the `Grid!` widget.
pub fn node(
cells: impl UiNodeList,
columns: impl UiNodeList,
rows: impl UiNodeList,
auto_grow_fn: impl IntoVar<WidgetFn<AutoGrowFnArgs>>,
auto_grow_mode: impl IntoVar<AutoGrowMode>,
spacing: impl IntoVar<GridSpacing>,
) -> impl UiNode {
let auto_columns: Vec<BoxedUiNode> = vec![];
let auto_rows: Vec<BoxedUiNode> = vec![];
let children = vec![
vec![columns.boxed(), auto_columns.boxed()].boxed(),
vec![rows.boxed(), auto_rows.boxed()].boxed(),
PanelList::new(cells).boxed(),
];
let spacing = spacing.into_var();
let auto_grow_fn = auto_grow_fn.into_var();
let auto_grow_mode = auto_grow_mode.into_var();
let mut grid = GridLayout::default();
let mut is_measured = false;
let mut last_layout = LayoutMetrics::new(1.fct(), PxSize::zero(), Px(0));
match_node_list(children, move |c, op| match op {
UiNodeOp::Init => {
WIDGET.sub_var(&auto_grow_fn).sub_var(&auto_grow_mode).sub_var_layout(&spacing);
c.init_all();
grid.update_entries(c.children(), auto_grow_mode.get(), &auto_grow_fn);
}
UiNodeOp::Deinit => {
c.deinit_all();
downcast_auto(&mut c.children()[0]).clear();
downcast_auto(&mut c.children()[1]).clear();
is_measured = false;
}
UiNodeOp::Update { updates } => {
let mut any = false;
c.update_all(updates, &mut any);
if auto_grow_fn.is_new() || auto_grow_mode.is_new() {
for mut auto in downcast_auto(&mut c.children()[0]).drain(..) {
auto.deinit();
}
for mut auto in downcast_auto(&mut c.children()[1]).drain(..) {
auto.deinit();
}
any = true;
}
if any {
grid.update_entries(c.children(), auto_grow_mode.get(), &auto_grow_fn);
WIDGET.layout();
}
}
UiNodeOp::Measure { wm, desired_size } => {
c.delegated();
*desired_size = if let Some(size) = LAYOUT.constraints().fill_or_exact() {
size
} else {
is_measured = true;
grid.grid_layout(wm, c.children(), &spacing).1
};
}
UiNodeOp::Layout { wl, final_size } => {
c.delegated();
is_measured = false;
last_layout = LAYOUT.metrics();
let (spacing, grid_size) = grid.grid_layout(&mut wl.to_measure(None), c.children(), &spacing);
let constraints = last_layout.constraints();
if grid.is_collapse() {
wl.collapse_descendants();
*final_size = constraints.fill_or_exact().unwrap_or_default();
return;
}
let mut children = c.children().iter_mut();
let columns = children.next().unwrap();
let rows = children.next().unwrap();
let cells = children.next().unwrap();
let cells: &mut PanelList = cells.as_any().downcast_mut().unwrap();
let grid = &grid;
// layout columns
let _ = columns.layout_each(
wl,
|ci, col, wl| {
let info = grid.columns[ci];
LAYOUT.with_constraints(constraints.with_exact(info.width, grid_size.height), || col.layout(wl))
},
|_, _| PxSize::zero(),
);
// layout rows
let _ = rows.layout_each(
wl,
|ri, row, wl| {
let info = grid.rows[ri];
LAYOUT.with_constraints(constraints.with_exact(grid_size.width, info.height), || row.layout(wl))
},
|_, _| PxSize::zero(),
);
// layout and translate cells
let cells_offset = columns.len() + rows.len();
cells.layout_each(
wl,
|i, cell, o, wl| {
let cell_info = cell::CellInfo::get_wgt(cell).actual(i, grid.columns.len());
if cell_info.column >= grid.columns.len() || cell_info.row >= grid.rows.len() {
wl.collapse_child(cells_offset + i);
return PxSize::zero(); // continue;
}
let cell_offset = PxVector::new(grid.columns[cell_info.column].x, grid.rows[cell_info.row].y);
let mut cell_size = PxSize::zero();
for col in cell_info.column..(cell_info.column + cell_info.column_span).min(grid.columns.len()) {
if grid.columns[col].width != Px(0) {
cell_size.width += grid.columns[col].width + spacing.column;
}
}
cell_size.width -= spacing.column;
for row in cell_info.row..(cell_info.row + cell_info.row_span).min(grid.rows.len()) {
if grid.rows[row].height != Px(0) {
cell_size.height += grid.rows[row].height + spacing.row;
}
}
cell_size.height -= spacing.row;
if cell_size.is_empty() {
wl.collapse_child(cells_offset + i);
return PxSize::zero(); // continue;
}
let (_, define_ref_frame) =
LAYOUT.with_constraints(constraints.with_exact_size(cell_size), || wl.with_child(|wl| cell.layout(wl)));
o.child_offset = cell_offset;
o.define_reference_frame = define_ref_frame;
cell_size
},
|_, _| PxSize::zero(),
);
cells.commit_data().request_render();
*final_size = constraints.fill_size_or(grid_size);
}
UiNodeOp::Render { frame } => {
c.delegated();
if mem::take(&mut is_measured) {
LAYOUT.with_context(last_layout.clone(), || {
let _ = grid.grid_layout(&mut WidgetMeasure::new_reuse(None), c.children(), &spacing);
});
}
let grid = &grid;
if grid.is_collapse() {
return;
}
let mut children = c.children().iter_mut();
let columns = children.next().unwrap();
let rows = children.next().unwrap();
let cells: &mut PanelList = children.next().unwrap().as_any().downcast_mut().unwrap();
let offset_key = cells.offset_key();
columns.for_each(|i, child| {
let offset = PxVector::new(grid.columns[i].x, Px(0));
frame.push_reference_frame(
(offset_key, i as u32).into(),
FrameValue::Value(offset.into()),
true,
true,
|frame| {
child.render(frame);
},
);
});
let i_extra = columns.len();
rows.for_each(|i, child| {
let offset = PxVector::new(Px(0), grid.rows[i].y);
frame.push_reference_frame(
(offset_key, (i + i_extra) as u32).into(),
FrameValue::Value(offset.into()),
true,
true,
|frame| {
child.render(frame);
},
);
});
let i_extra = i_extra + rows.len();
cells.for_each_z_sorted(|i, child, data| {
if data.define_reference_frame {
frame.push_reference_frame(
(offset_key, (i + i_extra) as u32).into(),
FrameValue::Value(data.child_offset.into()),
true,
true,
|frame| {
child.render(frame);
},
);
} else {
frame.push_child(data.child_offset, |frame| child.render(frame));
}
});
}
UiNodeOp::RenderUpdate { update } => {
c.delegated();
if mem::take(&mut is_measured) {
LAYOUT.with_context(last_layout.clone(), || {
let _ = grid.grid_layout(&mut WidgetMeasure::new_reuse(None), c.children(), &spacing);
});
}
let grid = &grid;
if grid.is_collapse() {
return;
}
let mut children = c.children().iter_mut();
let columns = children.next().unwrap();
let rows = children.next().unwrap();
let cells: &mut PanelList = children.next().unwrap().as_any().downcast_mut().unwrap();
columns.for_each(|i, child| {
let offset = PxVector::new(grid.columns[i].x, Px(0));
update.with_transform_value(&offset.into(), |update| {
child.render_update(update);
});
});
rows.for_each(|i, child| {
let offset = PxVector::new(Px(0), grid.rows[i].y);
update.with_transform_value(&offset.into(), |update| {
child.render_update(update);
});
});
cells.for_each(|_, child, data| {
if data.define_reference_frame {
update.with_transform_value(&data.child_offset.into(), |update| {
child.render_update(update);
});
} else {
update.with_child(data.child_offset, |update| {
child.render_update(update);
})
}
})
}
_ => {}
})
}
/// Arguments for [`auto_grow_fn`].
///
/// [`auto_grow_fn`]: fn@auto_grow_fn
#[derive(Clone, Debug)]
pub struct AutoGrowFnArgs {
/// Auto-grow direction.
pub mode: AutoGrowMode,
/// Column index.
pub index: usize,
}
/// Grid auto-grow direction.
///
/// The associated value is the maximum columns or rows that are allowed in the grid.
#[derive(Clone, Copy, PartialEq, Eq)]
pub enum AutoGrowMode {
/// Auto generate columns.
Columns(u32),
/// Auto generate rows.
Rows(u32),
}
impl AutoGrowMode {
/// Value that does not generate any new row or column.
pub const fn disabled() -> Self {
Self::Rows(0)
}
/// Columns, not specific maximum limit.
pub const fn columns() -> Self {
Self::Columns(u32::MAX)
}
/// Rows, not specific maximum limit.
pub const fn rows() -> Self {
Self::Rows(u32::MAX)
}
/// Set the maximum columns or rows allowed.
pub fn with_limit(self, limit: u32) -> Self {
match self {
AutoGrowMode::Columns(_) => AutoGrowMode::Columns(limit),
AutoGrowMode::Rows(_) => AutoGrowMode::Rows(limit),
}
}
}
impl fmt::Debug for AutoGrowMode {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if f.alternate() {
write!(f, "AutoGrowMode::")?;
}
match self {
AutoGrowMode::Rows(0) => write!(f, "disabled()"),
AutoGrowMode::Columns(u32::MAX) => write!(f, "Columns(MAX)"),
AutoGrowMode::Rows(u32::MAX) => write!(f, "Rows(MAX)"),
AutoGrowMode::Columns(l) => write!(f, "Columns({l})"),
AutoGrowMode::Rows(l) => write!(f, "Rows({l})"),
}
}
}
#[doc(inline)]
pub use column::Column;
/// Column widget and properties.
pub mod column {
use super::*;
/// Grid column definition.
///
/// This widget is layout to define the actual column width, it is not the parent
/// of the cells, only the `width` and `align` properties affect the cells.
///
/// See the [`Grid::columns`] property for more details.
///
/// # Shorthand
///
/// The `Column!` macro provides a shorthand init that sets the width, `grid::Column!(1.lft())` instantiates
/// a column with width of *1 leftover*.
#[widget($crate::Column {
($width:expr) => {
width = $width;
};
})]
pub struct Column(WidgetBase);
impl Column {
widget_impl! {
/// Column max width.
pub max_width(max: impl IntoVar<Length>);
/// Column min width.
pub min_width(min: impl IntoVar<Length>);
/// Column width.
pub width(width: impl IntoVar<Length>);
}
fn widget_intrinsic(&mut self) {
widget_set! {
self;
access_role = AccessRole::Column;
}
}
}
static_id! {
/// Column index, total in the parent widget set by the parent.
pub(super) static ref INDEX_ID: StateId<(usize, usize)>;
}
/// If the column index is even.
///
/// Column index is zero-based, so the first column is even, the next [`is_odd`].
///
/// [`is_odd`]: fn@is_odd
#[property(CONTEXT, widget_impl(Column))]
pub fn is_even(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
widget_state_is_state(child, |w| w.get(*INDEX_ID).copied().unwrap_or((0, 0)).0 % 2 == 0, |_| false, state)
}
/// If the column index is odd.
///
/// Column index is zero-based, so the first column [`is_even`], the next one is odd.
///
/// [`is_even`]: fn@is_even
#[property(CONTEXT, widget_impl(Column))]
pub fn is_odd(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
widget_state_is_state(child, |w| w.get(*INDEX_ID).copied().unwrap_or((0, 0)).0 % 2 != 0, |_| false, state)
}
/// If the column is the first.
#[property(CONTEXT, widget_impl(Column))]
pub fn is_first(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
widget_state_is_state(
child,
|w| {
let (i, l) = w.get(*INDEX_ID).copied().unwrap_or((0, 0));
i == 0 && l > 0
},
|_| false,
state,
)
}
/// If the column is the last.
#[property(CONTEXT, widget_impl(Column))]
pub fn is_last(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
widget_state_is_state(
child,
|w| {
let (i, l) = w.get(*INDEX_ID).copied().unwrap_or((0, 0));
i < l && i == l - 1
},
|_| false,
state,
)
}
/// Get the column index.
///
/// The column index is zero-based.
#[property(CONTEXT, widget_impl(Column))]
pub fn get_index(child: impl UiNode, state: impl IntoVar<usize>) -> impl UiNode {
widget_state_get_state(
child,
|w, &i| {
let a = w.get(*INDEX_ID).copied().unwrap_or((0, 0)).0;
if a != i {
Some(a)
} else {
None
}
},
|_, &i| if i != 0 { Some(0) } else { None },
state,
)
}
/// Get the column index and number of columns.
#[property(CONTEXT, widget_impl(Column))]
pub fn get_index_len(child: impl UiNode, state: impl IntoVar<(usize, usize)>) -> impl UiNode {
widget_state_get_state(
child,
|w, &i| {
let a = w.get(*INDEX_ID).copied().unwrap_or((0, 0));
if a != i {
Some(a)
} else {
None
}
},
|_, &i| if i != (0, 0) { Some((0, 0)) } else { None },
state,
)
}
/// Get the column index, starting from the last column at `0`.
#[property(CONTEXT, widget_impl(Column))]
pub fn get_rev_index(child: impl UiNode, state: impl IntoVar<usize>) -> impl UiNode {
widget_state_get_state(
child,
|w, &i| {
let a = w.get(*INDEX_ID).copied().unwrap_or((0, 0));
let a = a.1 - a.0;
if a != i {
Some(a)
} else {
None
}
},
|_, &i| if i != 0 { Some(0) } else { None },
state,
)
}
}
#[doc(inline)]
pub use row::Row;
/// Row widget and properties.
pub mod row {
use super::*;
/// Grid row definition.
///
/// This widget is layout to define the actual row height, it is not the parent
/// of the cells, only the `height` property affect the cells.
///
/// See the [`Grid::rows`] property for more details.
///
/// # Shorthand
///
/// The `Row!` macro provides a shorthand init that sets the height, `grid::Row!(1.lft())` instantiates
/// a row with height of *1 leftover*.
#[widget($crate::Row {
($height:expr) => {
height = $height;
};
})]
pub struct Row(WidgetBase);
impl Row {
widget_impl! {
/// Row max height.
pub max_height(max: impl IntoVar<Length>);
/// Row min height.
pub min_height(max: impl IntoVar<Length>);
/// Row height.
pub height(max: impl IntoVar<Length>);
}
fn widget_intrinsic(&mut self) {
widget_set! {
self;
access_role = AccessRole::Row;
}
}
}
static_id! {
/// Row index, total in the parent widget set by the parent.
pub(super) static ref INDEX_ID: StateId<(usize, usize)>;
}
/// If the row index is even.
///
/// Row index is zero-based, so the first row is even, the next [`is_odd`].
///
/// [`is_odd`]: fn@is_odd
#[property(CONTEXT, widget_impl(Row))]
pub fn is_even(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
widget_state_is_state(child, |w| w.get(*INDEX_ID).copied().unwrap_or((0, 0)).0 % 2 == 0, |_| false, state)
}
/// If the row index is odd.
///
/// Row index is zero-based, so the first row [`is_even`], the next one is odd.
///
/// [`is_even`]: fn@is_even
#[property(CONTEXT, widget_impl(Row))]
pub fn is_odd(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
widget_state_is_state(child, |w| w.get(*INDEX_ID).copied().unwrap_or((0, 0)).0 % 2 != 0, |_| false, state)
}
/// If the row is the first.
#[property(CONTEXT, widget_impl(Row))]
pub fn is_first(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
widget_state_is_state(
child,
|w| {
let (i, l) = w.get(*INDEX_ID).copied().unwrap_or((0, 0));
i == 0 && l > 0
},
|_| false,
state,
)
}
/// If the row is the last.
#[property(CONTEXT, widget_impl(Row))]
pub fn is_last(child: impl UiNode, state: impl IntoVar<bool>) -> impl UiNode {
widget_state_is_state(
child,
|w| {
let (i, l) = w.get(*INDEX_ID).copied().unwrap_or((0, 0));
i < l && i == l - 1
},
|_| false,
state,
)
}
/// Get the row index.
///
/// The row index is zero-based.
#[property(CONTEXT, widget_impl(Row))]
pub fn get_index(child: impl UiNode, state: impl IntoVar<usize>) -> impl UiNode {
widget_state_get_state(
child,
|w, &i| {
let a = w.get(*INDEX_ID).copied().unwrap_or((0, 0)).0;
if a != i {
Some(a)
} else {
None
}
},
|_, &i| if i != 0 { Some(0) } else { None },
state,
)
}
/// Get the row index and number of rows.
#[property(CONTEXT, widget_impl(Row))]
pub fn get_index_len(child: impl UiNode, state: impl IntoVar<(usize, usize)>) -> impl UiNode {
widget_state_get_state(
child,
|w, &i| {
let a = w.get(*INDEX_ID).copied().unwrap_or((0, 0));
if a != i {
Some(a)
} else {
None
}
},
|_, &i| if i != (0, 0) { Some((0, 0)) } else { None },
state,
)
}
/// Get the row index, starting from the last row at `0`.
#[property(CONTEXT, widget_impl(Row))]
pub fn get_rev_index(child: impl UiNode, state: impl IntoVar<usize>) -> impl UiNode {
widget_state_get_state(
child,
|w, &i| {
let a = w.get(*INDEX_ID).copied().unwrap_or((0, 0));
let a = a.1 - a.0;
if a != i {
Some(a)
} else {
None
}
},
|_, &i| if i != 0 { Some(0) } else { None },
state,
)
}
}
#[doc(inline)]
pub use cell::Cell;
/// Cell widget and properties.
pub mod cell {
use super::*;
/// Grid cell container.
///
/// This widget defines properties that position and size widgets in a [`Grid!`].
///
/// See the [`Grid::cells`] property for more details.
///
/// [`Grid!`]: struct@Grid
#[widget($crate::Cell)]
pub struct Cell(zng_wgt_container::Container);
impl Cell {
fn widget_intrinsic(&mut self) {
widget_set! {
self;
access_role = AccessRole::GridCell;
}
}
}
/// Represents values set by cell properties in a widget.
#[derive(Clone, Copy, Debug)]
pub struct CellInfo {
/// The [`column`] value.
///
/// [`column`]: fn@column
pub column: usize,
/// The [`column_span`] value.
///
/// [`column_span`]: fn@column_span
pub column_span: usize,
/// The [`row`] value.
///
/// [`row`]: fn@row
pub row: usize,
/// The [`row_span`] value.
///
/// [`row_span`]: fn@row_span
pub row_span: usize,
}
impl Default for CellInfo {
fn default() -> Self {
Self {
column: 0,
column_span: 1,
row: 0,
row_span: 1,
}
}
}
impl CellInfo {
/// Compute or correct the column and row of the cell.
///
/// The `logical_index` is the index of the cell widget in the cell node list.
pub fn actual(mut self, logical_index: usize, columns_len: usize) -> Self {
if self.column == usize::MAX {
self.column = logical_index % columns_len;
} else {
self.column = self.column.min(columns_len - 1);
}
if self.row == usize::MAX {
self.row = logical_index / columns_len
}
self
}
/// Get the cell info stored in the [`WIDGET`] state.
///
/// [`WIDGET`]: zng_wgt::prelude::WIDGET
pub fn get() -> Self {
WIDGET.get_state(*INFO_ID).unwrap_or_default()
}
/// Get the cell info stored in the `wgt` state.
pub fn get_wgt(wgt: &mut impl UiNode) -> Self {
wgt.with_context(WidgetUpdateMode::Ignore, Self::get).unwrap_or_default()
}
}
static_id! {
/// Id for widget state set by cell properties.
///
/// The parent grid uses this info to position and size the cell widget.
pub static ref INFO_ID: StateId<CellInfo>;
}
/// Cell column index.
///
/// If set to [`usize::MAX`] the cell is positioned based on the logical index.
///
/// Is `0` by default.
///
/// This property sets the [`INFO_ID`].
///
/// See also the [`at`] property to bind both indexes at the same time.
///
/// [`at`]: fn@at
#[property(CONTEXT, default(0), widget_impl(Cell))]
pub fn column(child: impl UiNode, col: impl IntoVar<usize>) -> impl UiNode {
with_widget_state_modify(child, *INFO_ID, col, CellInfo::default, |i, &c| {
if i.column != c {
i.column = c;
WIDGET.layout();
}
})
}
/// Cell row index.
///
/// If set to [`usize::MAX`] the cell is positioned based on the logical index.
///
/// Is `0` by default.
///
/// This property sets the [`INFO_ID`].
///
/// See also the [`at`] property to bind both indexes at the same time.
///
/// [`at`]: fn@at
#[property(CONTEXT, default(0), widget_impl(Cell))]
pub fn row(child: impl UiNode, row: impl IntoVar<usize>) -> impl UiNode {
with_widget_state_modify(child, *INFO_ID, row, CellInfo::default, |i, &r| {
if i.row != r {
i.row = r;
WIDGET.layout();
}
})
}
/// Cell column and row indexes.
///
/// If set to [`AT_AUTO`] the cell is positioned based on the logical index.
///
/// Is `(0, 0)` by default.
///
/// This property sets the [`INFO_ID`].
///
/// See also the [`column`] or [`row`] properties to bind each index individually.
///
/// [`column`]: fn@column
/// [`row`]: fn@row
#[property(CONTEXT, default((0, 0)), widget_impl(Cell))]
pub fn at(child: impl UiNode, column_row: impl IntoVar<(usize, usize)>) -> impl UiNode {
with_widget_state_modify(child, *INFO_ID, column_row, CellInfo::default, |i, &(col, row)| {
if i.column != col || i.row != row {
i.column = col;
i.row = row;
WIDGET.layout();
}
})
}
/// Cell column span.
///
/// Number of *cells* this one spans over horizontally, starting from the column index and spanning to the right.
///
/// Is `1` by default, the index is clamped between `1..max` where max is the maximum number of valid columns
/// to the right of the cell column index.
///
/// Note that the cell will not influence the column width if it spans over multiple columns.
///
/// This property sets the [`INFO_ID`].
///
/// See also the [`span`] property to bind both spans at the same time.
///
/// [`span`]: fn@span
#[property(CONTEXT, default(1), widget_impl(Cell))]
pub fn column_span(child: impl UiNode, span: impl IntoVar<usize>) -> impl UiNode {
with_widget_state_modify(child, *INFO_ID, span, CellInfo::default, |i, &s| {
if i.column_span != s {
i.column_span = s;
WIDGET.layout();
}
})
}
/// Cell row span.
///
/// Number of *cells* this one spans over vertically, starting from the row index and spanning down.
///
/// Is `1` by default, the index is clamped between `1..max` where max is the maximum number of valid rows
/// down from the cell column index.
///
/// Note that the cell will not influence the row height if it spans over multiple rows.
///
/// This property sets the [`INFO_ID`].
///
/// See also the [`span`] property to bind both spans at the same time.
///
/// [`span`]: fn@span
#[property(CONTEXT, default(1), widget_impl(Cell))]
pub fn row_span(child: impl UiNode, span: impl IntoVar<usize>) -> impl UiNode {
with_widget_state_modify(child, *INFO_ID, span, CellInfo::default, |i, &s| {
if i.row_span != s {
i.row_span = s;
WIDGET.layout();
}
})
}
/// Cell column and row span.
///
/// Is `(1, 1)` by default.
///
/// This property sets the [`INFO_ID`].
///
/// See also the [`column_span`] or [`row_span`] properties to bind each index individually.
///
/// [`column_span`]: fn@column_span
/// [`row_span`]: fn@row_span
#[property(CONTEXT, default((1, 1)), widget_impl(Cell))]
pub fn span(child: impl UiNode, span: impl IntoVar<(usize, usize)>) -> impl UiNode {
with_widget_state_modify(child, *INFO_ID, span, CellInfo::default, |i, &(cs, rs)| {
if i.column_span != rs || i.row_span != rs {
i.column_span = cs;
i.row_span = rs;
WIDGET.layout();
}
})
}
/// Value for [`at`] that causes the cell to be positioned based on the logical index *i*,
/// for columns *i % columns* and for rows *i / columns*.
///
/// [`at`]: fn@at
pub const AT_AUTO: (usize, usize) = (usize::MAX, usize::MAX);
}
#[derive(Clone, Copy)]
struct ColRowMeta(f32);
impl ColRowMeta {
/// `width` or `height` contains the largest cell or `Px::MIN` if cell measure is pending.
fn is_default(self) -> bool {
self.0.is_sign_negative() && self.0.is_infinite()
}
/// Return the leftover factor if the column or row must be measured on a fraction of the leftover space.
fn is_leftover(self) -> Option<Factor> {
if self.0 >= 0.0 {
Some(Factor(self.0))
} else {
None
}
}
/// `width` or `height` contains the final length or is pending layout `Px::MIN`.
fn is_exact(self) -> bool {
self.0.is_nan()
}
fn exact() -> Self {
Self(f32::NAN)
}
fn leftover(f: Factor) -> Self {
Self(f.0.max(0.0))
}
}
impl Default for ColRowMeta {
fn default() -> Self {
Self(f32::NEG_INFINITY)
}
}
impl fmt::Debug for ColRowMeta {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
if self.is_default() {
write!(f, "default")
} else if self.is_exact() {
write!(f, "exact")
} else if let Some(l) = self.is_leftover() {
write!(f, "leftover({l})")
} else {
write!(f, "ColRowMeta({})", self.0)
}
}
}
#[derive(Clone, Copy, Debug)]
struct ColumnLayout {
meta: ColRowMeta,
was_leftover: bool,
x: Px,
width: Px,
}
impl Default for ColumnLayout {
fn default() -> Self {
Self {
meta: ColRowMeta::default(),
was_leftover: false,
x: Px::MIN,
width: Px::MIN,
}
}
}
#[derive(Clone, Copy, Debug)]
struct RowLayout {
meta: ColRowMeta,
was_leftover: bool,
y: Px,
height: Px,
}
impl Default for RowLayout {
fn default() -> Self {
Self {
meta: ColRowMeta::default(),
was_leftover: false,
y: Px::MIN,
height: Px::MIN,
}
}
}
#[derive(Default)]
struct GridLayout {
columns: Vec<ColumnLayout>,
rows: Vec<RowLayout>,
}
impl GridLayout {
fn is_collapse(&self) -> bool {
self.columns.is_empty() || self.rows.is_empty()
}
fn collapse(&mut self) {
self.columns.clear();
self.rows.clear();
}
/// add/remove info entries, auto-grow/shrink
fn update_entries(&mut self, children: &mut GridChildren, auto_mode: AutoGrowMode, auto_grow_fn: &impl Var<WidgetFn<AutoGrowFnArgs>>) {
// max needed column or row in the auto_mode axis.
let mut max_custom = 0;
let mut max_auto_placed_i = 0;
children[2].for_each(|i, c| {
let info = c.with_context(WidgetUpdateMode::Ignore, cell::CellInfo::get).unwrap_or_default();
let n = match auto_mode {
AutoGrowMode::Rows(_) => info.row,
AutoGrowMode::Columns(_) => info.column,
};
if n == usize::MAX {
max_auto_placed_i = i;
} else {
max_custom = max_custom.max(n);
}
});
let mut imaginary_cols = 0;
let mut imaginary_rows = 0;
match auto_mode {
AutoGrowMode::Rows(max) => {
let columns_len = children[0].len();
if columns_len == 0 {
tracing::warn!(
"grid {} has no columns and auto_grow_mode={:?}, no cell will be visible",
WIDGET.id(),
auto_mode,
);
self.collapse();
return;
}
let max_auto_placed = max_auto_placed_i / columns_len;
let max_needed_len = max_auto_placed.max(max_custom).min(max as usize) + 1;
let rows_len = children[1].len();
#[expect(clippy::comparison_chain)]
if rows_len < max_needed_len {
let auto = downcast_auto(&mut children[1]);
let mut index = rows_len;
let view = auto_grow_fn.get();
if view.is_nil() {
imaginary_rows = max_needed_len - rows_len;
} else {
while index < max_needed_len {
let mut row = view(AutoGrowFnArgs { mode: auto_mode, index });
row.init();
auto.push(row);
index += 1;
}
}
} else if rows_len > max_needed_len {
let remove = rows_len - max_needed_len;
let auto = downcast_auto(&mut children[1]);
for mut auto in auto.drain(auto.len().saturating_sub(remove)..) {
auto.deinit();
}
}
}
AutoGrowMode::Columns(max) => {
let rows_len = children[1].len();
if rows_len == 0 {
tracing::warn!(
"grid {} has no rows and auto_grow_mode={:?}, no cell will be visible",
WIDGET.id(),
auto_mode,
);
self.collapse();
return;
}
let max_auto_placed = max_auto_placed_i / rows_len;
let max_needed_len = max_auto_placed.max(max_custom).min(max as usize) + 1;
let cols_len = children[0].len();
#[expect(clippy::comparison_chain)]
if cols_len < max_needed_len {
let auto = downcast_auto(&mut children[0]);
let mut index = cols_len;
let view = auto_grow_fn.get();
if view.is_nil() {
imaginary_cols = max_needed_len - cols_len;
} else {
while index < max_needed_len {
let mut column = view(AutoGrowFnArgs { mode: auto_mode, index });
column.init();
auto.push(column);
index += 1;
}
}
} else if cols_len > max_needed_len {
let remove = cols_len - max_needed_len;
let auto = downcast_auto(&mut children[0]);
for mut auto in auto.drain(auto.len().saturating_sub(remove)..) {
auto.deinit();
}
}
}
}
// Set index for column and row.
let columns_len = children[0].len() + imaginary_cols;
children[0].for_each(|i, c| {
c.with_context(WidgetUpdateMode::Bubble, || {
let prev = WIDGET.set_state(*column::INDEX_ID, (i, columns_len));
if prev != Some((i, columns_len)) {
WIDGET.update();
}
});
});
let rows_len = children[1].len() + imaginary_rows;
children[1].for_each(|i, r| {
r.with_context(WidgetUpdateMode::Bubble, || {
let prev = WIDGET.set_state(*row::INDEX_ID, (i, rows_len));
if prev != Some((i, rows_len)) {
WIDGET.update();
}
});
});
self.columns.resize(columns_len, ColumnLayout::default());
self.rows.resize(rows_len, RowLayout::default());
}
#[must_use]
fn grid_layout(
&mut self,
wm: &mut WidgetMeasure,
children: &mut GridChildren,
spacing: &impl Var<GridSpacing>,
) -> (PxGridSpacing, PxSize) {
if self.is_collapse() {
return (PxGridSpacing::zero(), PxSize::zero());
}
let spacing = spacing.layout();
let constraints = LAYOUT.constraints();
let fill_x = constraints.x.fill_or_exact();
let fill_y = constraints.y.fill_or_exact();
let mut children = children.iter_mut();
let columns = children.next().unwrap();
let rows = children.next().unwrap();
let cells = children.next().unwrap();
// layout exact columns&rows, mark others for next passes.
let mut has_default = false;
let mut has_leftover_cols = false;
let mut has_leftover_rows = false;
columns.for_each(|ci, col| {
let col_kind = WIDGET_SIZE.get_wgt(col).width;
let col_info = &mut self.columns[ci];
col_info.x = Px::MIN;
col_info.width = Px::MIN;
match col_kind {
WidgetLength::Default => {
col_info.meta = ColRowMeta::default();
has_default = true;
}
WidgetLength::Leftover(f) => {
col_info.meta = ColRowMeta::leftover(f);
col_info.was_leftover = true;
has_leftover_cols = true;
}
WidgetLength::Exact => {
col_info.width = col.measure(wm).width;
col_info.meta = ColRowMeta::exact();
}
}
});
rows.for_each(|ri, row| {
let row_kind = WIDGET_SIZE.get_wgt(row).height;
let row_info = &mut self.rows[ri];
row_info.y = Px::MIN;
row_info.height = Px::MIN;
match row_kind {
WidgetLength::Default => {
row_info.meta = ColRowMeta::default();
has_default = true;
}
WidgetLength::Leftover(f) => {
row_info.meta = ColRowMeta::leftover(f);
row_info.was_leftover = true;
has_leftover_rows = true;
}
WidgetLength::Exact => {
row_info.height = row.measure(wm).height;
row_info.meta = ColRowMeta::exact();
}
}
});
// reset imaginaries
for col in &mut self.columns[columns.len()..] {
col.meta = ColRowMeta::default();
col.x = Px::MIN;
col.width = Px::MIN;
has_default = true;
}
for row in &mut self.rows[rows.len()..] {
row.meta = ColRowMeta::default();
row.y = Px::MIN;
row.height = Px::MIN;
has_default = true;
}
// Measure cells when needed, collect widest/tallest.
// - For `Default` columns&rows to get their size.
// - For `leftover` columns&rows when the grid is not fill or exact size, to get the `1.lft()` length.
// - For leftover x default a second pass later in case the constrained leftover causes a different default.
let mut has_leftover_x_default = false;
let columns_len = self.columns.len();
if has_default || (fill_x.is_none() && has_leftover_cols) || (fill_y.is_none() && has_leftover_rows) {
let c = LAYOUT.constraints();
cells.for_each(|i, cell| {
let cell_info = cell::CellInfo::get_wgt(cell);
if cell_info.column_span > 1 || cell_info.row_span > 1 {
return; // continue;
}
let cell_info = cell_info.actual(i, columns_len);
let col = &mut self.columns[cell_info.column];
let row = &mut self.rows[cell_info.row];
let col_is_default = col.meta.is_default() || (fill_x.is_none() && col.meta.is_leftover().is_some());
let col_is_exact = !col_is_default && col.meta.is_exact();
let col_is_leftover = !col_is_default && col.meta.is_leftover().is_some();
let row_is_default = row.meta.is_default() || (fill_y.is_none() && row.meta.is_leftover().is_some());
let row_is_exact = !row_is_default && row.meta.is_exact();
let row_is_leftover = !row_is_default && row.meta.is_leftover().is_some();
if col_is_default {
if row_is_default {
// (default, default)
let size = LAYOUT.with_constraints(c.with_fill(false, false), || cell.measure(wm));
col.width = col.width.max(size.width);
row.height = row.height.max(size.height);
} else if row_is_exact {
// (default, exact)
let size = LAYOUT.with_constraints(c.with_exact_y(row.height).with_fill(false, false), || cell.measure(wm));
col.width = col.width.max(size.width);
} else {
debug_assert!(row_is_leftover);
// (default, leftover)
let size = LAYOUT.with_constraints(c.with_fill(false, false), || cell.measure(wm));
col.width = col.width.max(size.width);
has_leftover_x_default = true;
}
} else if col_is_exact {
if row_is_default {
// (exact, default)
let size = LAYOUT.with_constraints(c.with_exact_x(col.width).with_fill(false, false), || cell.measure(wm));
row.height = row.height.max(size.height);
}
} else if row_is_default {
debug_assert!(col_is_leftover);
// (leftover, default)
let size = LAYOUT.with_constraints(c.with_fill(false, false), || cell.measure(wm));
row.height = row.height.max(size.height);
has_leftover_x_default = true;
}
});
}
// distribute leftover grid space to columns
if has_leftover_cols {
let mut no_fill_1_lft = Px(0);
let mut used_width = Px(0);
let mut total_factor = Factor(0.0);
let mut leftover_count = 0;
let mut max_factor = 0.0_f32;
for col in &mut self.columns {
if let Some(f) = col.meta.is_leftover() {
if fill_x.is_none() {
no_fill_1_lft = no_fill_1_lft.max(col.width);
col.width = Px::MIN;
}
max_factor = max_factor.max(f.0);
total_factor += f;
leftover_count += 1;
} else if col.width > Px(0) {
used_width += col.width;
}
}
// handle big leftover factors
if total_factor.0.is_infinite() {
total_factor = Factor(0.0);
if max_factor.is_infinite() {
// +inf takes all space
for col in &mut self.columns {
if let Some(f) = col.meta.is_leftover() {
if f.0.is_infinite() {
col.meta = ColRowMeta::leftover(Factor(1.0));
total_factor.0 += 1.0;
} else {
col.meta = ColRowMeta::leftover(Factor(0.0));
}
}
}
} else {
// scale down every factor to fit
let scale = f32::MAX / max_factor / leftover_count as f32;
for col in &mut self.columns {
if let Some(f) = col.meta.is_leftover() {
let f = Factor(f.0 * scale);
col.meta = ColRowMeta::leftover(f);
total_factor += f;
}
}
}
}
// individual factors under `1.0` behave like `Length::Factor`.
if total_factor < Factor(1.0) {
total_factor = Factor(1.0);
}
let mut leftover_width = if let Some(w) = fill_x {
let vis_columns = self.columns.iter().filter(|c| c.width != Px(0)).count() as i32;
w - used_width - spacing.column * Px(vis_columns - 1).max(Px(0))
} else {
// grid has no width, so `1.lft()` is defined by the widest cell measured using `Default` constraints.
let mut unbounded_width = used_width;
for col in &self.columns {
if let Some(f) = col.meta.is_leftover() {
unbounded_width += no_fill_1_lft * f;
}
}
let bounded_width = constraints.x.clamp(unbounded_width);
bounded_width - used_width
};
leftover_width = leftover_width.max(Px(0));
let view_columns_len = columns.len();
// find extra leftover space from columns that can't fully fill their requested leftover length.
let mut settled_all = false;
while !settled_all && leftover_width > Px(0) {
settled_all = true;
for (i, col) in self.columns.iter_mut().enumerate() {
let lft = if let Some(lft) = col.meta.is_leftover() {
lft
} else {
continue;
};
let width = lft.0 * leftover_width.0 as f32 / total_factor.0;
col.width = Px(width as i32);
if i < view_columns_len {
let size = LAYOUT.with_constraints(LAYOUT.constraints().with_fill_x(true).with_max_x(col.width), || {
columns.with_node(i, |col| col.measure(wm))
});
if col.width != size.width {
// reached a max/min, convert this column to "exact" and remove it from
// the leftover pool.
settled_all = false;
col.width = size.width;
col.meta = ColRowMeta::exact();
if size.width != Px(0) {
leftover_width -= size.width + spacing.column;
total_factor -= lft;
if total_factor < Factor(1.0) {
total_factor = Factor(1.0);
}
}
}
}
}
}
leftover_width = leftover_width.max(Px(0));
// finish settled leftover columns that can fill the requested leftover length.
for col in &mut self.columns {
let lft = if let Some(lft) = col.meta.is_leftover() {
lft
} else {
continue;
};
let width = lft.0 * leftover_width.0 as f32 / total_factor.0;
col.width = Px(width as i32);
col.meta = ColRowMeta::exact();
}
}
// distribute leftover grid space to rows
if has_leftover_rows {
let mut no_fill_1_lft = Px(0);
let mut used_height = Px(0);
let mut total_factor = Factor(0.0);
let mut leftover_count = 0;
let mut max_factor = 0.0_f32;
for row in &mut self.rows {
if let Some(f) = row.meta.is_leftover() {
if fill_y.is_none() {
no_fill_1_lft = no_fill_1_lft.max(row.height);
row.height = Px::MIN;
}
max_factor = max_factor.max(f.0);
total_factor += f;
leftover_count += 1;
} else if row.height > Px(0) {
used_height += row.height;
}
}
// handle big leftover factors
if total_factor.0.is_infinite() {
total_factor = Factor(0.0);
if max_factor.is_infinite() {
// +inf takes all space
for row in &mut self.rows {
if let Some(f) = row.meta.is_leftover() {
if f.0.is_infinite() {
row.meta = ColRowMeta::leftover(Factor(1.0));
total_factor.0 += 1.0;
} else {
row.meta = ColRowMeta::leftover(Factor(0.0));
}
}
}
} else {
// scale down every factor to fit
let scale = f32::MAX / max_factor / leftover_count as f32;
for row in &mut self.rows {
if let Some(f) = row.meta.is_leftover() {
let f = Factor(f.0 * scale);
row.meta = ColRowMeta::leftover(f);
total_factor += f;
}
}
}
}
// individual factors under `1.0` behave like `Length::Factor`.
if total_factor < Factor(1.0) {
total_factor = Factor(1.0);
}
let mut leftover_height = if let Some(h) = fill_y {
let vis_rows = self.rows.iter().filter(|c| c.height != Px(0)).count() as i32;
h - used_height - spacing.row * Px(vis_rows - 1).max(Px(0))
} else {
// grid has no height, so `1.lft()` is defined by the tallest cell measured using `Default` constraints.
let mut unbounded_height = used_height;
for row in &self.rows {
if let Some(f) = row.meta.is_leftover() {
unbounded_height += no_fill_1_lft * f;
}
}
let bounded_height = constraints.x.clamp(unbounded_height);
bounded_height - used_height
};
leftover_height = leftover_height.max(Px(0));
let view_rows_len = rows.len();
// find extra leftover space from leftover that can't fully fill their requested leftover length.
let mut settled_all = false;
while !settled_all && leftover_height > Px(0) {
settled_all = true;
for (i, row) in self.rows.iter_mut().enumerate() {
let lft = if let Some(lft) = row.meta.is_leftover() {
lft
} else {
continue;
};
let height = lft.0 * leftover_height.0 as f32 / total_factor.0;
row.height = Px(height as i32);
if i < view_rows_len {
let size = LAYOUT.with_constraints(LAYOUT.constraints().with_fill_y(true).with_max_y(row.height), || {
rows.with_node(i, |row| row.measure(wm))
});
if row.height != size.height {
// reached a max/min, convert this row to "exact" and remove it from
// the leftover pool.
settled_all = false;
row.height = size.height;
row.meta = ColRowMeta::exact();
if size.height != Px(0) {
leftover_height -= size.height + spacing.row;
total_factor -= lft;
if total_factor < Factor(1.0) {
total_factor = Factor(1.0);
}
}
}
}
}
}
leftover_height = leftover_height.max(Px(0));
// finish settled leftover rows that can fill the requested leftover length.
for row in &mut self.rows {
let lft = if let Some(lft) = row.meta.is_leftover() {
lft
} else {
continue;
};
let height = lft.0 * leftover_height.0 as f32 / total_factor.0;
row.height = Px(height as i32);
row.meta = ColRowMeta::exact();
}
}
if has_leftover_x_default {
// second measure pass with constrained leftovers to get a more accurate default
let c = LAYOUT.constraints();
cells.for_each(|i, cell| {
let cell_info = cell::CellInfo::get_wgt(cell);
if cell_info.column_span > 1 || cell_info.row_span > 1 {
return; // continue;
}
let cell_info = cell_info.actual(i, columns_len);
let col = &mut self.columns[cell_info.column];
let row = &mut self.rows[cell_info.row];
let col_is_default = col.meta.is_default() || (fill_x.is_none() && col.was_leftover);
let col_is_leftover = col.was_leftover;
let row_is_default = row.meta.is_default() || (fill_y.is_none() && row.was_leftover);
let row_is_leftover = row.was_leftover;
if col_is_default {
if row_is_leftover {
// (default, leftover)
let size = LAYOUT.with_constraints(c.with_fill(false, false).with_exact_y(row.height), || cell.measure(wm));
col.width = col.width.max(size.width);
}
} else if row_is_default && col_is_leftover {
// (leftover, default)
let size = LAYOUT.with_constraints(c.with_fill(false, false).with_exact_x(col.width), || cell.measure(wm));
row.height = row.height.max(size.height);
}
});
}
// compute column&row offsets
let mut x = Px(0);
for col in &mut self.columns {
col.x = x;
if col.width > Px(0) {
x += col.width + spacing.column;
}
}
let mut y = Px(0);
for row in &mut self.rows {
row.y = y;
if row.height > Px(0) {
y += row.height + spacing.row;
}
}
(spacing, PxSize::new((x - spacing.column).max(Px(0)), (y - spacing.row).max(Px(0))))
}
}
/// Downcast auto-grow column or row list.
fn downcast_auto(cols_or_rows: &mut BoxedUiNodeList) -> &mut Vec<BoxedUiNode> {
cols_or_rows.as_any().downcast_mut::<Vec<BoxedUiNodeList>>().unwrap()[1]
.as_any()
.downcast_mut()
.unwrap()
}
/// [[columns, auto_columns], [rows, auto_rows], cells]
type GridChildren = Vec<BoxedUiNodeList>;