quadraui 0.6.1

Cross-platform Rust UI toolkit: write one AppLogic and run it unmodified on TUI, GTK4 (Linux), macOS, and Windows backends
Documentation
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
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
//! `Toast` primitive: a transient corner notification with optional
//! severity tint and zero or more action buttons. Used for "File saved",
//! "LSP disconnected", "3 errors in src/foo.rs", "Install Markdown
//! Language Server?", etc.
//!
//! Toasts are ephemeral — the app owns their lifecycle (show, auto-dismiss
//! after a duration, manual dismiss) and passes the primitive the current
//! set of visible toasts each frame. The primitive itself does not tick
//! time or auto-dismiss; those are app concerns.
//!
//! # Backend contract
//!
//! **Declarative + overlay.** Render toasts stacked in the configured
//! `corner`, VS Code-style: title/body wrap across the box's
//! full width, growing its height up to a cap ([`MAX_BODY_LINES`])
//! before ellipsizing; the dismiss `×` sits alone near the top-right;
//! any [`Toast::actions`] sit on their own row at the bottom-right,
//! never inline with the title. Clicks resolve via
//! [`ToastStackLayout::hit_test`] / [`ToastHit`]: an action button hits
//! `ToastHit::Action`; the dismiss affordance hits `ToastHit::Dismiss`.
//!
//! Toast boxes take keyboard focus only when an app explicitly hands it
//! to them, via [`crate::compose::ToastStackController`] —
//! they're otherwise strictly a passive notification surface, and never
//! steal focus or block input on their own (unlike a modal
//! [`crate::primitives::dialog::Dialog`]). `ToastOverlay::focus`, set from
//! the controller, is what makes a backend paint a focus ring at all.
//!
//! Stacking direction: bottom-corner toasts grow upward (newest nearest
//! the corner); top-corner toasts grow downward. `ToastOverlay::layout()`
//! handles this based on `corner`.
//!
//! # Naming
//!
//! [`ToastOverlay`] (a corner's worth of toasts) holds [`Toast`]s, each
//! holding [`ToastButton`]s. Single-action counterparts were deprecated
//! and removed once known consumers migrated; see `CHANGELOG.md`'s
//! `Removed` entry.

use crate::event::Rect;
use crate::types::{Color, WidgetId};
use serde::{Deserialize, Serialize};

/// Declarative description of a toast stack for one corner.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToastOverlay {
    pub id: WidgetId,
    /// Which corner of the viewport the stack occupies.
    pub corner: ToastCorner,
    /// Toasts in temporal order — oldest first. Visual order depends on
    /// `corner` (bottom corners stack upward, top corners stack downward).
    pub toasts: Vec<Toast>,
    /// Which control (if any) currently has keyboard focus.
    /// `None` — the common case, since toasts are non-modal and never
    /// steal focus on their own — paints with no focus ring. Set this
    /// from [`crate::compose::ToastStackController::focus`] before
    /// calling [`crate::Backend::draw_toast_overlay`] to make the
    /// controller's cursor visible; the primitive itself never mutates
    /// this field (declarative, like every other field here).
    #[serde(default)]
    pub focus: Option<ToastFocus>,
}

/// Corner placement for a `ToastOverlay`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ToastCorner {
    #[default]
    BottomRight,
    BottomLeft,
    TopRight,
    TopLeft,
}

/// One toast notification.
///
/// # Examples
///
/// ```
/// use quadraui::{Toast, ToastHit, ToastMeasure, ToastOverlay, ToastSeverity, WidgetId};
///
/// let toast = Toast {
///     id: WidgetId::new("toast:saved"),
///     title: "File saved".to_string(),
///     body: String::new(),
///     severity: ToastSeverity::Success,
///     actions: vec![],
///     accent: None,
/// };
/// let overlay = ToastOverlay {
///     id: WidgetId::new("toasts:bottom_right"),
///     corner: Default::default(),
///     toasts: vec![toast.clone()],
///     focus: None,
/// };
///
/// let layout = overlay.layout(0.0, 0.0, 80.0, 24.0, 1.0, 1.0, |_| {
///     ToastMeasure::new(30.0, 3.0)
/// });
///
/// assert_eq!(layout.visible_toasts.len(), 1);
/// assert_eq!(layout.hit_test(60.0, 21.0), ToastHit::Body(toast.id));
/// ```
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Toast {
    pub id: WidgetId,
    pub title: String,
    /// Body text. Can be empty for minimal "File saved" style toasts.
    #[serde(default)]
    pub body: String,
    /// Visual severity — backends tint the box accordingly.
    #[serde(default)]
    pub severity: ToastSeverity,
    /// Ordered action buttons. Rendered on their own row at the bottom-right
    /// of the toast box, never inline with the title. Empty = no action row;
    /// just the dismiss affordance is clickable. At most one entry should set
    /// [`ToastButton::primary`] — see that field's doc.
    #[serde(default)]
    pub actions: Vec<ToastButton>,
    /// Override severity's default tint. Most toasts use `None` and let
    /// the theme decide.
    #[serde(default)]
    pub accent: Option<Color>,
}

/// Severity level of a `Toast`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
pub enum ToastSeverity {
    #[default]
    Info,
    Success,
    Warning,
    Error,
}

/// Action button on a toast.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToastButton {
    pub id: WidgetId,
    pub label: String,
    /// Styled with the theme's accent (filled background) instead of the
    /// plain secondary-button look. VS Code convention: at most
    /// one action per toast is primary — the "do the thing" button (e.g.
    /// "Install"), with the rest ("Don't ask again", …) staying
    /// secondary. Backends don't enforce the "at most one" rule; a
    /// caller that sets it on more than one action just gets more than
    /// one accent-filled button.
    #[serde(default)]
    pub primary: bool,
}

/// Keyboard-focus target within a [`ToastOverlay`] — set
/// [`ToastOverlay::focus`] to one of these so every backend's rasteriser
/// draws a visible focus ring around it. Produced by
/// [`crate::compose::ToastStackController`]; the primitive layer only
/// consumes it for painting, never computes it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ToastFocus {
    /// Which toast (by [`Toast::id`]) currently has keyboard focus.
    pub toast_id: WidgetId,
    /// Which control within that toast is focused.
    pub target: ToastFocusTarget,
}

/// Which control within a focused toast has keyboard focus — see
/// [`ToastFocus`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum ToastFocusTarget {
    /// The dismiss `×` affordance.
    Dismiss,
    /// One of the toast's action buttons, by index into
    /// [`Toast::actions`].
    Action(usize),
}

// ── Text wrapping ───────────────────────────────────────────────────────────
//
// Shared between every backend's toast rasteriser: the GUI paint
// (`native_surface_paint::paint`), its no-paint layout twin
// (`crate::primitives::layout_metrics::pixel_toast_stack_layout`), and
// `tui::toast`. Before this, none of them wrapped or truncated title/body
// text at all — a long title ran straight through the action button's
// reserved column, and a long body was drawn as one line that simply
// extended past the toast box (and, on GUI, past the window). Unit-
// agnostic (`width_of` is pixel width on GUI surfaces, character count on
// TUI cells) so one implementation covers both.

/// Max number of wrapped lines a toast body grows to before its last line
/// is ellipsized. Shared by the paint/layout pair on every pixel backend
/// and by `tui::toast`, so a no-paint layout call always predicts the same
/// box height the matching paint call actually drew.
pub(crate) const MAX_BODY_LINES: usize = 3;

/// Greedy word-wrap `text` into lines that each measure `<= max_width`
/// under `width_of`. Caps output at `max_lines`; if words remain past
/// that cap, the last line is trimmed and suffixed with `…` so the cut is
/// visible rather than silently dropped. A single word wider than
/// `max_width` on its own (a long URL/identifier with no spaces) is
/// hard-truncated with `…` instead of overflowing or looping forever
/// trying to fit it.
///
/// `max_lines == 1` is how callers get "truncate/ellipsize, never wrap"
/// behaviour for a title; `max_lines == `[`MAX_BODY_LINES`] is how the
/// body grows the toast's height instead.
pub(crate) fn wrap_text_lines(
    text: &str,
    max_width: f32,
    max_lines: usize,
    width_of: &dyn Fn(&str) -> f32,
) -> Vec<String> {
    if text.is_empty() || max_lines == 0 {
        return Vec::new();
    }
    if max_width <= 0.0 {
        return vec![text.to_string()];
    }

    let words: Vec<&str> = text.split_whitespace().collect();
    if words.is_empty() {
        return Vec::new();
    }

    let mut lines: Vec<String> = Vec::new();
    let mut idx = 0;
    while idx < words.len() && lines.len() < max_lines {
        let mut line = String::new();
        loop {
            if idx >= words.len() {
                break;
            }
            let word = words[idx];
            let candidate = if line.is_empty() {
                word.to_string()
            } else {
                format!("{line} {word}")
            };
            if width_of(&candidate) <= max_width {
                line = candidate;
                idx += 1;
                continue;
            }
            if line.is_empty() {
                // A single word wider than max_width on its own:
                // hard-truncate it with an ellipsis rather than looping
                // forever trying (and failing) to fit it whole.
                let mut piece = String::new();
                for ch in word.chars() {
                    let next = format!("{piece}{ch}…");
                    if width_of(&next) > max_width && !piece.is_empty() {
                        break;
                    }
                    piece.push(ch);
                }
                piece.push('…');
                line = piece;
                idx += 1;
            }
            break;
        }
        lines.push(line);
    }

    // Words remain past `max_lines`: ellipsize the last line so the cut
    // is visible rather than silently dropped.
    if idx < words.len() {
        if let Some(last) = lines.last_mut() {
            while !last.is_empty() && width_of(&format!("{last}…")) > max_width {
                last.pop();
            }
            last.push('…');
        }
    }

    lines
}

/// Truncate `text` to a single line that fits `max_width`, ellipsizing if
/// it doesn't — the title's shape (never wraps, unlike the body).
///
/// `#[cfg_attr(not(any(<every backend feature>)), allow(dead_code))]`: the
/// only callers are *rasterisers* — `tui::toast` and
/// `native_surface_paint::paint` (gtk/win/macos) — unlike its sibling
/// [`wrap_text_lines`], which `primitives::layout_metrics` also calls from
/// the ungated no-paint layout path (the title is always one line, so it
/// can't change a toast's height and layout never needs to truncate it).
/// A featureless `cargo check -p quadraui` therefore compiles no caller at
/// all. Kept compiled (rather than `#[cfg]`-ed out) on every leg so the
/// `wrap_tests` unit tests below cover it with no features enabled too.
#[cfg_attr(
    not(any(
        feature = "tui",
        feature = "gtk",
        feature = "win",
        all(feature = "macos", target_os = "macos")
    )),
    allow(dead_code)
)]
pub(crate) fn truncate_line(text: &str, max_width: f32, width_of: &dyn Fn(&str) -> f32) -> String {
    wrap_text_lines(text, max_width, 1, width_of)
        .into_iter()
        .next()
        .unwrap_or_default()
}

#[cfg(test)]
mod wrap_tests {
    use super::{truncate_line, wrap_text_lines};

    /// Character-count "pixel" metric — simplest deterministic `width_of`
    /// for these unit tests (matches how `tui::toast` measures).
    fn chars(s: &str) -> f32 {
        s.chars().count() as f32
    }

    #[test]
    fn short_text_is_one_line_unchanged() {
        let lines = wrap_text_lines("Hello", 20.0, 3, &chars);
        assert_eq!(lines, vec!["Hello".to_string()]);
    }

    #[test]
    fn wraps_on_word_boundaries() {
        let lines = wrap_text_lines("one two three four", 9.0, 3, &chars);
        // "one two" = 7 chars fits in 9; adding "three" (13) doesn't.
        assert_eq!(lines[0], "one two");
        for line in &lines {
            assert!(chars(line) <= 9.0, "line {line:?} exceeds max_width");
        }
    }

    #[test]
    fn ellipsizes_last_line_when_content_overflows_max_lines() {
        let lines = wrap_text_lines("a b c d e f g h", 3.0, 2, &chars);
        assert_eq!(lines.len(), 2);
        assert!(lines[1].ends_with('…'));
        for line in &lines {
            assert!(chars(line) <= 3.0, "line {line:?} exceeds max_width");
        }
    }

    #[test]
    fn truncate_line_never_wraps() {
        let line = truncate_line("Install Markdown Language Server?", 10.0, &chars);
        assert!(chars(&line) <= 10.0);
        assert!(line.ends_with('…'));
    }

    #[test]
    fn single_word_wider_than_max_width_is_hard_truncated() {
        let lines = wrap_text_lines("supercalifragilisticexpialidocious", 5.0, 1, &chars);
        assert_eq!(lines.len(), 1);
        assert!(
            chars(&lines[0]) <= 5.0,
            "line {:?} exceeds max_width",
            lines[0]
        );
        assert!(lines[0].ends_with('…'));
    }

    #[test]
    fn empty_text_yields_no_lines() {
        assert!(wrap_text_lines("", 20.0, 3, &chars).is_empty());
    }
}

// ── D6 Layout API ───────────────────────────────────────────────────────────
//
// First new B.3 primitive on D6. Toasts stack in a corner with uniform
// spacing; per-toast sizes are backend-supplied (a "body"-less toast is
// shorter than one with a multi-line body).

/// Per-toast measurement supplied by the backend.
///
/// `dismiss_rect` / `action_rects` are **toast-local** (relative to the
/// toast box's own top-left corner, not the viewport) — [`ToastOverlay::layout`]
/// translates them into absolute bounds itself, the same way it already
/// positions `width`/`height` into the stack. This lets each backend's
/// measure closure own its own padding/row-placement geometry (VS
/// Code-style: dismiss top-right, actions on their own row at the
/// bottom-right — see [`toast_button_rects`], the shared helper every
/// in-tree measure closure uses to compute both) without
/// `ToastOverlay::layout` itself needing to know any padding constant.
#[derive(Debug, Clone, PartialEq)]
pub struct ToastMeasure {
    /// Full width of the toast box in the backend's unit.
    pub width: f32,
    /// Full height of the toast box.
    pub height: f32,
    /// Toast-local dismiss-affordance rect. `None` if no dismiss UI is
    /// drawn.
    pub dismiss_rect: Option<Rect>,
    /// Toast-local action-button rects, one per [`Toast::actions`]
    /// entry, same order. Empty if the toast has no actions.
    pub action_rects: Vec<Rect>,
}

impl ToastMeasure {
    pub fn new(width: f32, height: f32) -> Self {
        Self {
            width,
            height,
            dismiss_rect: None,
            action_rects: Vec::new(),
        }
    }
}

/// Compute a toast's dismiss + action-button rects, toast-local (relative to
/// the toast box's own top-left) — shared by every backend's measure closure,
/// so the `×` affordance's top-right position and the action row's
/// right-aligned, bottom-edge placement are computed identically everywhere,
/// whether the caller's unit is pixels or terminal cells.
///
/// VS Code shape: `×` sits alone near the top-right, clear of the title
/// row below it in height so it never overlaps a wrapped multi-line
/// title/body; actions sit on their own row at the bottom-right,
/// right-to-left (`action_widths[0]` ends up leftmost in the row),
/// never inline with the title. `action_widths` is each action's
/// already-measured, already-padded button width, in [`Toast::actions`]
/// order; the returned `Vec` is aligned 1:1 with it. Both rects are
/// clamped to stay non-negative even if the box is smaller than the sum
/// of its own padding/button widths (a degenerate but non-panicking box,
/// matching this module's existing `.max(0.0)`-everywhere convention).
#[allow(clippy::too_many_arguments)]
pub(crate) fn toast_button_rects(
    width: f32,
    height: f32,
    padding: f32,
    dismiss_width: f32,
    dismiss_height: f32,
    action_widths: &[f32],
    action_height: f32,
    action_gap: f32,
) -> (Option<Rect>, Vec<Rect>) {
    let dismiss_rect = if dismiss_width > 0.0 && dismiss_height > 0.0 {
        Some(Rect::new(
            (width - padding - dismiss_width).max(0.0),
            padding,
            dismiss_width,
            dismiss_height,
        ))
    } else {
        None
    };

    let mut action_rects: Vec<Rect> = Vec::with_capacity(action_widths.len());
    if !action_widths.is_empty() && action_height > 0.0 {
        let row_y = (height - padding - action_height).max(0.0);
        let mut x_cursor = width - padding;
        for w in action_widths.iter().rev() {
            x_cursor -= w;
            action_rects.push(Rect::new(x_cursor.max(0.0), row_y, *w, action_height));
            x_cursor -= action_gap;
        }
        action_rects.reverse();
    }
    (dismiss_rect, action_rects)
}

/// Resolved position of one visible toast after layout.
#[derive(Debug, Clone, PartialEq)]
pub struct VisibleToast {
    /// Index into `ToastOverlay.toasts`.
    pub toast_idx: usize,
    pub id: WidgetId,
    /// Full toast box bounds.
    pub bounds: Rect,
    /// Dismiss affordance (if present).
    pub dismiss_bounds: Option<Rect>,
    /// Action-button bounds, one per [`Toast::actions`] entry, same order.
    /// Empty if the toast has no actions.
    pub action_rects: Vec<Rect>,
}

/// Classification of a hit-test result.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum ToastHit {
    /// Click landed on a toast's action button.
    Action(WidgetId),
    /// Click landed on a toast's dismiss affordance.
    Dismiss(WidgetId),
    /// Click landed on a toast's body (not action or dismiss).
    Body(WidgetId),
    /// Click landed outside any toast.
    Empty,
}

/// Fully-resolved toast-stack layout.
#[derive(Debug, Clone, PartialEq)]
pub struct ToastStackLayout {
    pub viewport_width: f32,
    pub viewport_height: f32,
    pub visible_toasts: Vec<VisibleToast>,
    pub hit_regions: Vec<(Rect, ToastHit)>,
}

/// Translate a `Rect` by `(dx, dy)`, keeping its size.
fn shift_rect(r: Rect, dx: f32, dy: f32) -> Rect {
    Rect::new(r.x + dx, r.y + dy, r.width, r.height)
}

impl ToastStackLayout {
    pub fn hit_test(&self, x: f32, y: f32) -> ToastHit {
        for (rect, hit) in &self.hit_regions {
            if x >= rect.x && x < rect.x + rect.width && y >= rect.y && y < rect.y + rect.height {
                return hit.clone();
            }
        }
        ToastHit::Empty
    }
}

impl ToastOverlay {
    /// Compute the rendering + hit-test layout for the stack.
    ///
    /// # Arguments
    ///
    /// - `origin_x`, `origin_y` — the top-left corner of the app's
    ///   overlay area, in the backend's absolute (screen/buffer) frame.
    ///   Returned `bounds` / `hit_regions` are absolute — callers pass
    ///   `hit_test` raw click coordinates in that same frame, matching
    ///   the `MenuBar`/`Panel` convention (unlike `TreeView`'s
    ///   viewport-local frame). Pass `(0.0, 0.0)` for an overlay
    ///   anchored at the buffer/window origin.
    /// - `viewport_width`, `viewport_height` — the app's overlay area
    ///   size. Toasts are positioned relative to this.
    /// - `margin` — spacing between the stack and the viewport edges.
    /// - `gap` — vertical gap between consecutive toasts.
    /// - `measure_toast(i)` — per-toast width/height/sub-region widths.
    ///
    /// # Stacking direction
    ///
    /// - `BottomRight` / `BottomLeft`: newest toast is nearest the
    ///   corner; older toasts stack upward.
    /// - `TopRight` / `TopLeft`: newest toast is nearest the corner;
    ///   older toasts stack downward.
    ///
    /// Toasts are iterated oldest-first (matching `self.toasts` order);
    /// the layout positions them in reverse of that for bottom corners
    /// so the newest stays pinned.
    #[allow(clippy::too_many_arguments)]
    pub fn layout<F>(
        &self,
        origin_x: f32,
        origin_y: f32,
        viewport_width: f32,
        viewport_height: f32,
        margin: f32,
        gap: f32,
        measure_toast: F,
    ) -> ToastStackLayout
    where
        F: Fn(usize) -> ToastMeasure,
    {
        let mut visible_toasts: Vec<VisibleToast> = Vec::new();
        let mut hit_regions: Vec<(Rect, ToastHit)> = Vec::new();

        if self.toasts.is_empty() {
            return ToastStackLayout {
                viewport_width,
                viewport_height,
                visible_toasts,
                hit_regions,
            };
        }

        let is_right = matches!(
            self.corner,
            ToastCorner::BottomRight | ToastCorner::TopRight
        );
        let is_bottom = matches!(
            self.corner,
            ToastCorner::BottomRight | ToastCorner::BottomLeft
        );

        // Iteration order: bottom corners show newest nearest the corner,
        // so we iterate newest-first and stack upward from the bottom.
        // Top corners show newest nearest the corner (top edge) and
        // stack downward.
        let ordered: Vec<(usize, ToastMeasure)> = if is_bottom {
            // Newest (highest index) nearest bottom — iterate in reverse.
            (0..self.toasts.len())
                .rev()
                .map(|i| (i, measure_toast(i)))
                .collect()
        } else {
            (0..self.toasts.len())
                .map(|i| (i, measure_toast(i)))
                .collect()
        };

        // Starting y: bottom edge - margin for bottom corners; margin for top.
        let mut y_cursor = if is_bottom {
            viewport_height - margin
        } else {
            margin
        };

        for (i, m) in ordered {
            if m.width <= 0.0 || m.height <= 0.0 {
                continue;
            }
            let x = if is_right {
                (viewport_width - margin - m.width).max(0.0)
            } else {
                margin
            };
            let y = if is_bottom {
                (y_cursor - m.height).max(0.0)
            } else {
                y_cursor
            };

            // Skip if the toast would render off-screen.
            if (is_bottom && y >= y_cursor) || (!is_bottom && y + m.height > viewport_height) {
                break;
            }

            let bounds = Rect::new(x, y, m.width, m.height);

            // Sub-regions come pre-computed toast-local by the measure
            let dismiss_bounds = m.dismiss_rect.map(|r| shift_rect(r, bounds.x, bounds.y));
            let action_rects: Vec<Rect> = m
                .action_rects
                .iter()
                .map(|r| shift_rect(*r, bounds.x, bounds.y))
                .collect();

            let toast_id = self.toasts[i].id;
            visible_toasts.push(VisibleToast {
                toast_idx: i,
                id: toast_id,
                bounds,
                dismiss_bounds,
                action_rects: action_rects.clone(),
            });

            // Register hit regions in specificity order: dismiss, actions, body.
            if let Some(db) = dismiss_bounds {
                hit_regions.push((db, ToastHit::Dismiss(toast_id)));
            }
            // Action hit regions carry the action's own id (not the
            // toast's) so the app can dispatch the intended action
            // directly from the hit result. Zipped by position with
            // `Toast::actions`, matching `action_rects`'s documented
            // 1:1 order.
            for (ab, act) in action_rects.iter().zip(self.toasts[i].actions.iter()) {
                hit_regions.push((*ab, ToastHit::Action(act.id)));
            }
            hit_regions.push((bounds, ToastHit::Body(toast_id)));

            // Advance the cursor for the next toast.
            if is_bottom {
                y_cursor = y - gap;
                if y_cursor <= 0.0 {
                    break;
                }
            } else {
                y_cursor = y + m.height + gap;
                if y_cursor >= viewport_height {
                    break;
                }
            }
        }

        // Shift from the viewport-local frame into the caller's absolute
        if origin_x != 0.0 || origin_y != 0.0 {
            for vt in &mut visible_toasts {
                vt.bounds = shift_rect(vt.bounds, origin_x, origin_y);
                vt.dismiss_bounds = vt.dismiss_bounds.map(|r| shift_rect(r, origin_x, origin_y));
                vt.action_rects = vt
                    .action_rects
                    .iter()
                    .map(|r| shift_rect(*r, origin_x, origin_y))
                    .collect();
            }
            for (rect, _) in &mut hit_regions {
                *rect = shift_rect(*rect, origin_x, origin_y);
            }
        }

        ToastStackLayout {
            viewport_width,
            viewport_height,
            visible_toasts,
            hit_regions,
        }
    }
}

// ── PaintSurface paint ────────────────────────────────────────────────
//
// This is the one shared implementation of toast painting, written against
// [`crate::paint_surface::PaintSurface`] instead of any one backend's
// drawing API.
//
// Each backend's own no-paint `*_toast_stack_layout` twin is untouched —
// it's layout-only, consumed by `Backend::toast_stack_layout` for
// hit-testing without a repaint. The margin/gap/dismiss-width/
// action-padding/box-width constants below match every pre-migration
// per-backend constant's value exactly.
//
// `severity_bg`'s colour formula (the `Success`/`Warning` hardcoded RGB,
// `Info`/`Error` theme fields) is unchanged.
//
// # Divergences found — reported, not silently resolved
//
// 1. **Win never took a live theme.** `win::toast::draw_toast_stack` had
//    no `theme: &Theme` parameter — it built `Theme::default()` internally
//    on every call. The shared `paint` requires a `theme: &Theme`
//    parameter (matching gtk/macos), so `WinBackend::draw_toast_stack`
//    now passes `&self.current_theme`.
//
// 2. **Dismiss/action glyph centring.** `gtk::toast::paint_toast` and
//    `macos::toast::paint_toast` centre the dismiss `×` and action-button
//    label horizontally within their reserved sub-region. `win::toast::
//    paint_toast` drew both directly via `DWrite::draw_text`, using
//    DirectWrite's default (leading/near) alignment — flush against the
//    sub-region's left edge. The shared `paint` adopts the 2-of-3
//    (gtk/macos) centred shape uniformly.
//
// 3. **Body-line vertical offset.** `gtk::toast::paint_toast` and
//    `macos::toast::paint_toast` positioned the body line at the title's
//    own *measured* pixel height. `win::toast::paint_toast` used the
//    nominal `line_height` argument instead. The shared `paint` adopts
//    the 2-of-3 (gtk/macos) measured-height shape uniformly.
//
// 4. **Toast-width clamp floor.** `gtk::toast::gtk_toast_stack_layout`
//    and `macos::toast::macos_toast_stack_layout` computed
//    `TOAST_WIDTH.min(viewport_width - TOAST_MARGIN * 2.0)` with no
//    floor. Only `win::toast::win_toast_stack_layout` clamped the
//    subtrahend to `.max(0.0)`. The shared `paint` adopts Win's
//    (safer) clamped form for all three.
//
// `#[allow(dead_code)]`: only called once a real pixel backend is
// compiled in, exercised by each backend's own `Backend::draw_toast_stack`
// call site plus this module's own `RecordingSurface` tests.
#[cfg(any(
    feature = "gtk",
    feature = "win",
    all(feature = "macos", target_os = "macos")
))]
#[allow(dead_code)]
pub(crate) mod native_surface_paint {
    use super::{
        shift_rect, toast_button_rects, truncate_line, wrap_text_lines, Toast, ToastFocus,
        ToastFocusTarget, ToastMeasure, ToastOverlay, ToastSeverity, ToastStackLayout,
        VisibleToast, MAX_BODY_LINES,
    };
    use crate::event::Rect;
    use crate::paint_surface::PaintSurface;
    use crate::style::Style;
    use crate::theme::Theme;
    use crate::types::{Color, WidgetId};

    const TOAST_WIDTH: f32 = 320.0;
    const TOAST_MARGIN: f32 = 12.0;
    const TOAST_GAP: f32 = 8.0;
    const DISMISS_WIDTH: f32 = 28.0;
    const ACTION_PADDING: f32 = 16.0;
    /// Horizontal gap between two adjacent action buttons on the button
    /// row.
    const ACTION_GAP: f32 = 8.0;
    const TOAST_PADDING: f32 = 8.0;

    /// Severity → fallback background tint, used when `Toast::accent` is
    /// `None`. Duplicated across `tui::toast` (out of scope for the
    /// `PaintSurface` migration).
    fn severity_bg(severity: ToastSeverity, theme: &Theme) -> Color {
        match severity {
            ToastSeverity::Info => theme.surface_bg,
            ToastSeverity::Success => Color::rgb(30, 80, 30),
            ToastSeverity::Warning => Color::rgb(100, 80, 20),
            ToastSeverity::Error => theme.error_fg,
        }
    }

    /// Compute a [`ToastOverlay`]'s layout and paint it onto `surface` in
    /// one pass, returning the resolved [`ToastStackLayout`] for the
    /// caller's click dispatch — same contract as
    /// [`crate::Backend::draw_toast_stack`]. `line_height` is the
    /// caller's current text-row height (surface-native units); action
    /// label width is measured directly against `surface`, so a no-paint
    /// hit-test caller (each backend's own `*_toast_stack_layout`) must
    /// keep using its own equivalent measurement to agree with what this
    /// painted. `style` supplies the corner radius/border
    /// width/shadow elevation every toast box paints with — callers pass
    /// `&self.style()`.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn paint(
        stack: &ToastOverlay,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        style: &Style,
        origin_x: f32,
        origin_y: f32,
        viewport_width: f32,
        viewport_height: f32,
        line_height: f32,
    ) -> ToastStackLayout {
        paint_with_x_offset(
            stack,
            surface,
            theme,
            style,
            origin_x,
            origin_y,
            viewport_width,
            viewport_height,
            line_height,
            |_| 0.0,
        )
    }

    /// Same contract as [`paint`], but shifts each toast box horizontally
    /// by `x_offset_for(id)` points before painting — the hook a backend's
    /// entrance-slide animation uses to paint a toast mid-flight without
    /// perturbing the returned [`ToastStackLayout`], which stays at the
    /// toast's resting position so hit-testing is unaffected by the
    /// in-flight visual offset.
    #[allow(clippy::too_many_arguments)]
    pub(crate) fn paint_with_x_offset<F>(
        stack: &ToastOverlay,
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        style: &Style,
        origin_x: f32,
        origin_y: f32,
        viewport_width: f32,
        viewport_height: f32,
        line_height: f32,
        x_offset_for: F,
    ) -> ToastStackLayout
    where
        F: Fn(&WidgetId) -> f32,
    {
        let layout = stack.layout(
            origin_x,
            origin_y,
            viewport_width,
            viewport_height,
            TOAST_MARGIN,
            TOAST_GAP,
            |i| {
                let toast = &stack.toasts[i];
                let width = TOAST_WIDTH.min((viewport_width - TOAST_MARGIN * 2.0).max(0.0));
                let body_avail = (width - TOAST_PADDING * 2.0).max(0.0);
                let body_lines = if toast.body.is_empty() {
                    0
                } else {
                    wrap_text_lines(&toast.body, body_avail, MAX_BODY_LINES, &|s| {
                        surface.surface_measure_text(s).0
                    })
                    .len()
                    .max(1)
                };
                // Button row: a separate row below the title/body, added
                let has_actions = !toast.actions.is_empty();
                let button_row_h = if has_actions {
                    TOAST_PADDING + line_height
                } else {
                    0.0
                };
                let h = line_height
                    + TOAST_PADDING * 2.0
                    + body_lines as f32 * line_height
                    + button_row_h;
                let action_widths: Vec<f32> = toast
                    .actions
                    .iter()
                    .map(|a| surface.surface_measure_text(&a.label).0 + ACTION_PADDING)
                    .collect();
                let (dismiss_rect, action_rects) = toast_button_rects(
                    width,
                    h,
                    TOAST_PADDING,
                    DISMISS_WIDTH,
                    // Height is a single text row, not `DISMISS_WIDTH`
                    // (a wide *click-target*, not a tall one) — a short,
                    // body-less, action-less toast is barely taller than
                    // one row plus padding, and a square dismiss target
                    // that tall would reach past the button row.
                    line_height,
                    &action_widths,
                    line_height,
                    ACTION_GAP,
                );
                ToastMeasure {
                    width,
                    height: h,
                    dismiss_rect,
                    action_rects,
                }
            },
        );

        for vt in &layout.visible_toasts {
            let toast = &stack.toasts[vt.toast_idx];
            let focus = stack.focus.as_ref().filter(|f| f.toast_id == toast.id);
            let dx = x_offset_for(&vt.id);
            if dx == 0.0 {
                paint_toast(surface, theme, style, vt, toast, line_height, focus);
            } else {
                let shifted = VisibleToast {
                    toast_idx: vt.toast_idx,
                    id: vt.id,
                    bounds: shift_rect(vt.bounds, dx, 0.0),
                    dismiss_bounds: vt.dismiss_bounds.map(|r| shift_rect(r, dx, 0.0)),
                    action_rects: vt
                        .action_rects
                        .iter()
                        .map(|r| shift_rect(*r, dx, 0.0))
                        .collect(),
                };
                paint_toast(surface, theme, style, &shifted, toast, line_height, focus);
            }
        }

        layout
    }

    /// Paint one resolved toast box: background tint, a theme border,
    /// title, optional body, a top-right dismiss `×`, and on their own row
    /// at the bottom-right (never inline with the title) zero or more action
    /// buttons: the one marked [`crate::primitives::toast::ToastButton::
    /// primary`] filled with `theme.accent_bg`/`theme.foreground` (matching
    /// `tui::toolbar`'s focused-action pairing), the rest plain text in
    /// `theme.link_fg` (a secondary/ghost-button look). `focus`, when it
    /// names a control on this toast, gets a `theme.link_fg` focus-ring
    /// stroke (every backend must draw one).
    ///
    /// The title is truncated/ellipsized to the space left of the dismiss
    /// button — never drawn under it. The body wraps across up to
    /// [`MAX_BODY_LINES`] lines at the box's full width, offset below the
    /// title by the title's own *measured* height, not the nominal
    /// `line_height`, each subsequent line advancing by `line_height`.
    fn paint_toast(
        surface: &mut dyn PaintSurface,
        theme: &Theme,
        style: &Style,
        vt: &VisibleToast,
        toast: &Toast,
        line_height: f32,
        focus: Option<&ToastFocus>,
    ) {
        let bg_color = toast
            .accent
            .unwrap_or_else(|| severity_bg(toast.severity, theme));
        // VS-Code-style elevated card: a shadow behind, then a rounded
        // fill and a rounded border.
        surface.surface_draw_shadow(
            vt.bounds,
            style.corner_radius,
            style.shadow_elevation,
            Color::rgba(0, 0, 0, 100),
        );
        surface.surface_fill_rounded_rect(vt.bounds, style.corner_radius, bg_color);
        surface.surface_stroke_rounded_rect(
            vt.bounds,
            style.corner_radius,
            theme.border_fg,
            style.border_width,
        );

        let dismiss_w = vt.dismiss_bounds.map(|d| d.width).unwrap_or(0.0);
        let title_avail_w = (vt.bounds.width - TOAST_PADDING * 2.0 - dismiss_w).max(0.0);
        let title_line = truncate_line(&toast.title, title_avail_w, &|s| {
            surface.surface_measure_text(s).0
        });

        let title_rect = Rect::new(
            vt.bounds.x + TOAST_PADDING,
            vt.bounds.y + TOAST_PADDING,
            title_avail_w,
            line_height,
        );
        surface.surface_draw_text_run(title_rect, &title_line, theme.foreground);

        if !toast.body.is_empty() {
            // Offset by the title's own measured pixel height, not the
            let (_, title_h) = surface.surface_measure_text(&toast.title);
            let body_avail_w = (vt.bounds.width - TOAST_PADDING * 2.0).max(0.0);
            let body_lines = wrap_text_lines(&toast.body, body_avail_w, MAX_BODY_LINES, &|s| {
                surface.surface_measure_text(s).0
            });
            for (i, line) in body_lines.iter().enumerate() {
                let body_rect = Rect::new(
                    title_rect.x,
                    title_rect.y + title_h + i as f32 * line_height,
                    body_avail_w,
                    line_height,
                );
                surface.surface_draw_text_run(body_rect, line, theme.foreground);
            }
        }

        if let Some(db) = vt.dismiss_bounds {
            let (tw, _) = surface.surface_measure_text("×");
            let rect = Rect::new(db.x + (db.width - tw) / 2.0, db.y, db.width, db.height);
            surface.surface_draw_text_run(rect, "×", theme.foreground);
            if matches!(focus, Some(f) if f.target == ToastFocusTarget::Dismiss) {
                surface.surface_stroke_rect(db, theme.link_fg, 2.0);
            }
        }

        for (i, (ab, action)) in vt.action_rects.iter().zip(toast.actions.iter()).enumerate() {
            if action.primary {
                surface.surface_fill_rect(*ab, theme.accent_bg);
            }
            let (tw, _) = surface.surface_measure_text(&action.label);
            let fg = if action.primary {
                theme.foreground
            } else {
                theme.link_fg
            };
            let rect = Rect::new(ab.x + (ab.width - tw) / 2.0, ab.y, ab.width, ab.height);
            surface.surface_draw_text_run(rect, &action.label, fg);
            if matches!(focus, Some(f) if f.target == ToastFocusTarget::Action(i)) {
                surface.surface_stroke_rect(*ab, theme.link_fg, 2.0);
            }
        }
    }

    #[cfg(test)]
    mod tests {
        use super::*;
        use crate::backend::ImagePaintResult;
        use crate::event::Viewport;
        use crate::primitives::toast::{ToastButton, ToastCorner, ToastFocusTarget};
        use crate::types::WidgetId;
        use crate::Image;

        /// Records every surface verb this primitive's paint uses —
        /// mirrors `primitives::status_bar`'s `RecordingSurface` test
        /// double, so this test runs on any host without Cairo/Core
        /// Graphics/Direct2D.
        #[derive(Default)]
        struct RecordingSurface {
            fills: Vec<(Rect, Color)>,
            text_runs: Vec<(Rect, String, Color)>,
            /// Records `surface_stroke_rect` calls so focus-ring tests can
            /// confirm one was drawn and where.
            strokes: Vec<(Rect, Color, f32)>,
            /// Overrides `surface_measure_text`'s returned height when
            /// set — lets a test make the "measured text height" and
            /// "nominal `line_height` passed into `paint`" conventions
            /// disagree, so it can tell which one `paint_toast` actually
            /// uses (regression for this module's divergence 3). `None`
            /// falls back to the fixed `16.0` every other test relies on.
            measured_text_height: Option<f32>,
        }

        impl PaintSurface for RecordingSurface {
            fn surface_begin_frame(&mut self, _viewport: Viewport) {}
            fn surface_end_frame(&mut self) {}
            fn surface_viewport(&self) -> Viewport {
                Viewport::new(400.0, 300.0, 1.0)
            }
            fn surface_line_height(&self) -> f32 {
                16.0
            }
            fn surface_char_width(&self) -> f32 {
                8.0
            }
            fn surface_measure_text(&self, text: &str) -> (f32, f32) {
                (
                    text.chars().count() as f32 * 8.0,
                    self.measured_text_height.unwrap_or(16.0),
                )
            }
            fn surface_fill_rect(&mut self, rect: Rect, color: Color) {
                self.fills.push((rect, color));
            }
            /// `paint_toast` now paints its box through this verb
            /// (radius dropped — same `fills` list `surface_fill_rect`
            /// above records into, so every existing `fills[..]`
            /// assertion still sees the toast's background fill here).
            fn surface_fill_rounded_rect(&mut self, rect: Rect, _radius: f32, color: Color) {
                self.fills.push((rect, color));
            }
            fn surface_stroke_rect(&mut self, rect: Rect, color: Color, stroke_width: f32) {
                self.strokes.push((rect, color, stroke_width));
            }
            /// `paint_toast`'s border, radius dropped — same
            /// `strokes` list `surface_stroke_rect` above records into.
            fn surface_stroke_rounded_rect(
                &mut self,
                rect: Rect,
                _radius: f32,
                color: Color,
                stroke_width: f32,
            ) {
                self.strokes.push((rect, color, stroke_width));
            }
            /// Deliberately does **not** forward to
            /// `PaintSurface`'s default (which would recurse into
            /// `surface_fill_rounded_rect` three times and pollute
            /// `fills` with shadow layers ahead of the real background
            /// fill every `fills[0]`-indexing test here relies on) — a
            /// no-op recorder, same posture as `surface_draw_line` below.
            fn surface_draw_shadow(
                &mut self,
                _rect: Rect,
                _radius: f32,
                _elevation: u8,
                _color: Color,
            ) {
            }
            fn surface_draw_text_run(&mut self, rect: Rect, text: &str, color: Color) {
                self.text_runs.push((rect, text.to_string(), color));
            }
            fn surface_draw_line(
                &mut self,
                _from: crate::Point,
                _to: crate::Point,
                _color: Color,
                _stroke_width: f32,
            ) {
            }
            fn surface_push_clip(&mut self, _rect: Rect) {}
            fn surface_pop_clip(&mut self) {}
            fn surface_draw_image(&mut self, _rect: Rect, _image: &Image) -> ImagePaintResult {
                ImagePaintResult::Unsupported
            }
        }

        fn toast(id: &str, title: &str) -> Toast {
            Toast {
                id: WidgetId::new(id),
                title: title.into(),
                body: String::new(),
                severity: ToastSeverity::Info,
                actions: Vec::new(),
                accent: None,
            }
        }

        fn stack_br(toasts: Vec<Toast>) -> ToastOverlay {
            ToastOverlay {
                id: WidgetId::new("toasts"),
                corner: ToastCorner::BottomRight,
                toasts,
                focus: None,
            }
        }

        #[test]
        fn empty_stack_paints_nothing() {
            let stack = stack_br(vec![]);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &stack,
                &mut surface,
                &theme,
                &Style::default(),
                0.0,
                0.0,
                400.0,
                300.0,
                16.0,
            );
            assert!(layout.visible_toasts.is_empty());
            assert!(surface.fills.is_empty());
            assert!(surface.text_runs.is_empty());
        }

        /// Background fill uses `accent` when present, else the
        /// severity's fallback tint.
        #[test]
        fn accent_overrides_severity_tint() {
            let accent = Color::rgb(10, 20, 30);
            let mut t = toast("t1", "Hello");
            t.accent = Some(accent);
            let stack = stack_br(vec![t]);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &stack,
                &mut surface,
                &theme,
                &Style::default(),
                0.0,
                0.0,
                400.0,
                300.0,
                16.0,
            );
            assert_eq!(surface.fills[0].1, accent);
        }

        #[test]
        fn severity_tint_used_when_no_accent() {
            let mut t = toast("t1", "Hello");
            t.severity = ToastSeverity::Error;
            let stack = stack_br(vec![t]);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &stack,
                &mut surface,
                &theme,
                &Style::default(),
                0.0,
                0.0,
                400.0,
                300.0,
                16.0,
            );
            assert_eq!(surface.fills[0].1, theme.error_fg);
        }

        /// Regression: the dismiss glyph and action label must be painted
        #[test]
        fn dismiss_and_action_are_centred_in_their_sub_region() {
            let mut t = toast("t1", "Build failed");
            t.actions = vec![ToastButton {
                id: WidgetId::new("open_log"),
                label: "Open log".into(),
                primary: false,
            }];
            let stack = stack_br(vec![t]);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &stack,
                &mut surface,
                &theme,
                &Style::default(),
                0.0,
                0.0,
                400.0,
                300.0,
                16.0,
            );
            let vt = &layout.visible_toasts[0];
            let db = vt.dismiss_bounds.expect("dismiss bounds present");
            let ab = vt.action_rects[0];

            let (dismiss_rect, _, _) = surface
                .text_runs
                .iter()
                .find(|(_, text, _)| text == "×")
                .expect("dismiss glyph painted");
            let dismiss_w = 8.0; // RecordingSurface: 1 char * 8.0
            assert!((dismiss_rect.x - (db.x + (db.width - dismiss_w) / 2.0)).abs() < 0.01);

            let (action_rect, _, _) = surface
                .text_runs
                .iter()
                .find(|(_, text, _)| text == "Open log")
                .expect("action label painted");
            let action_w = "Open log".chars().count() as f32 * 8.0;
            assert!((action_rect.x - (ab.x + (ab.width - action_w) / 2.0)).abs() < 0.01);
        }

        /// Acceptance: two actions sit on their own row at the bottom-right,
        #[test]
        fn multiple_actions_are_right_aligned_on_their_own_row() {
            let mut t = toast("t1", "Install Markdown Language Server?");
            t.actions = vec![
                ToastButton {
                    id: WidgetId::new("install"),
                    label: "Install".into(),
                    primary: true,
                },
                ToastButton {
                    id: WidgetId::new("dont-ask"),
                    label: "Don't ask again".into(),
                    primary: false,
                },
            ];
            let stack = stack_br(vec![t]);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &stack,
                &mut surface,
                &theme,
                &Style::default(),
                0.0,
                0.0,
                400.0,
                300.0,
                16.0,
            );
            let vt = &layout.visible_toasts[0];
            let db = vt.dismiss_bounds.expect("dismiss bounds present");
            assert_eq!(vt.action_rects.len(), 2);
            let install = vt.action_rects[0];
            let dont_ask = vt.action_rects[1];

            // Same row, both below the dismiss button.
            assert_eq!(install.y, dont_ask.y);
            assert!(install.y > db.y + db.height - 0.01);

            // `install` (first action) sits left of `dont_ask`, no overlap.
            assert!(install.x + install.width <= dont_ask.x + 0.01);

            // Row is right-aligned: the rightmost button's edge is at the
            // toast's own trailing-edge padding.
            assert!(
                (dont_ask.x + dont_ask.width - (vt.bounds.x + vt.bounds.width - 8.0)).abs() < 0.01
            );
        }

        /// The action marked `primary` gets a `theme.accent_bg` fill
        /// (VS Code's "do the thing" button); a non-primary action gets
        /// no fill of its own.
        #[test]
        fn primary_action_gets_accent_fill() {
            let mut t = toast("t1", "Install?");
            t.actions = vec![
                ToastButton {
                    id: WidgetId::new("install"),
                    label: "Install".into(),
                    primary: true,
                },
                ToastButton {
                    id: WidgetId::new("skip"),
                    label: "Skip".into(),
                    primary: false,
                },
            ];
            let stack = stack_br(vec![t]);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &stack,
                &mut surface,
                &theme,
                &Style::default(),
                0.0,
                0.0,
                400.0,
                300.0,
                16.0,
            );
            let vt = &layout.visible_toasts[0];
            let install_bounds = vt.action_rects[0];
            let skip_bounds = vt.action_rects[1];

            assert!(surface
                .fills
                .iter()
                .any(|(r, c)| *r == install_bounds && *c == theme.accent_bg));
            assert!(!surface.fills.iter().any(|(r, _)| *r == skip_bounds));
        }

        /// A focused dismiss button gets a `theme.link_fg` stroke
        /// around its own bounds.
        #[test]
        fn focused_dismiss_gets_a_focus_ring() {
            let t = toast("t1", "Saved");
            let mut stack = stack_br(vec![t]);
            stack.focus = Some(ToastFocus {
                toast_id: WidgetId::new("t1"),
                target: ToastFocusTarget::Dismiss,
            });
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &stack,
                &mut surface,
                &theme,
                &Style::default(),
                0.0,
                0.0,
                400.0,
                300.0,
                16.0,
            );
            let db = layout.visible_toasts[0]
                .dismiss_bounds
                .expect("dismiss bounds present");
            assert!(surface
                .strokes
                .iter()
                .any(|(r, c, w)| *r == db && *c == theme.link_fg && *w > 1.0));
        }

        /// A focused action button gets a `theme.link_fg` stroke
        /// around its own bounds — a different toast/action combination
        /// than the dismiss ring, confirming the focus target is looked
        /// up per-toast (`ToastFocus::toast_id`), not just "the first
        /// toast".
        #[test]
        fn focused_action_gets_a_focus_ring() {
            let t1 = toast("t1", "Saved");
            let mut t2 = toast("t2", "Install?");
            t2.actions = vec![ToastButton {
                id: WidgetId::new("install"),
                label: "Install".into(),
                primary: true,
            }];
            let mut stack = stack_br(vec![t1, t2]);
            stack.focus = Some(ToastFocus {
                toast_id: WidgetId::new("t2"),
                target: ToastFocusTarget::Action(0),
            });
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &stack,
                &mut surface,
                &theme,
                &Style::default(),
                0.0,
                0.0,
                400.0,
                300.0,
                16.0,
            );
            let t2_visible = layout
                .visible_toasts
                .iter()
                .find(|vt| vt.id == WidgetId::new("t2"))
                .expect("t2 visible");
            let ab = t2_visible.action_rects[0];
            assert!(surface
                .strokes
                .iter()
                .any(|(r, c, w)| *r == ab && *c == theme.link_fg && *w > 1.0));

            // The unfocused toast's own dismiss must not get a ring.
            let t1_visible = layout
                .visible_toasts
                .iter()
                .find(|vt| vt.id == WidgetId::new("t1"))
                .expect("t1 visible");
            let t1_db = t1_visible.dismiss_bounds.expect("dismiss bounds present");
            assert!(!surface
                .strokes
                .iter()
                .any(|(r, c, w)| *r == t1_db && *c == theme.link_fg && *w > 1.0));
        }

        #[test]
        fn body_line_painted_below_title() {
            let mut t = toast("t1", "Title");
            t.body = "Body text".into();
            let stack = stack_br(vec![t]);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            paint(
                &stack,
                &mut surface,
                &theme,
                &Style::default(),
                0.0,
                0.0,
                400.0,
                300.0,
                16.0,
            );
            let title_run = surface
                .text_runs
                .iter()
                .find(|(_, text, _)| text == "Title")
                .expect("title painted");
            let body_run = surface
                .text_runs
                .iter()
                .find(|(_, text, _)| text == "Body text")
                .expect("body painted");
            assert_eq!(body_run.0.y, title_run.0.y + 16.0);
        }

        /// Regression: the body line must be offset by the title's own
        #[test]
        fn body_offset_uses_measured_title_height_not_nominal_line_height() {
            let mut t = toast("t1", "Title");
            t.body = "Body text".into();
            let stack = stack_br(vec![t]);
            let theme = Theme::default();
            let mut surface = RecordingSurface {
                measured_text_height: Some(20.0),
                ..Default::default()
            };
            paint(
                &stack,
                &mut surface,
                &theme,
                &Style::default(),
                0.0,
                0.0,
                400.0,
                300.0,
                16.0,
            );
            let title_run = surface
                .text_runs
                .iter()
                .find(|(_, text, _)| text == "Title")
                .expect("title painted");
            let body_run = surface
                .text_runs
                .iter()
                .find(|(_, text, _)| text == "Body text")
                .expect("body painted");
            assert_eq!(body_run.0.y, title_run.0.y + 20.0);
        }

        /// Acceptance regression: a toast with a long title, an action
        #[test]
        fn long_title_and_body_stay_inside_bounds_and_dont_overlap_action() {
            let mut t = toast("t1", "Install Markdown Language Server?");
            t.actions = vec![ToastButton {
                id: WidgetId::new("install"),
                label: "Install".into(),
                primary: true,
            }];
            t.body =
                "N: don't ask again · :ExtInstall markdown-language-server for full details".into();
            let stack = stack_br(vec![t]);
            let theme = Theme::default();
            let mut surface = RecordingSurface::default();
            let layout = paint(
                &stack,
                &mut surface,
                &theme,
                &Style::default(),
                0.0,
                0.0,
                400.0,
                300.0,
                16.0,
            );

            let vt = &layout.visible_toasts[0];
            let ab = vt.action_rects[0];
            let db = vt.dismiss_bounds.expect("dismiss bounds present");

            // Every text run must stay within the toast's own bounds,
            // both horizontally (x + measured width) and vertically
            // (y + line height, allowing for wrapped body lines).
            for (rect, text, _) in &surface.text_runs {
                if text == "×" {
                    continue;
                }
                let (w, _) = surface.surface_measure_text(text);
                assert!(
                    rect.x >= vt.bounds.x - 0.01,
                    "{text:?} starts left of the toast bounds"
                );
                assert!(
                    rect.x + w <= vt.bounds.x + vt.bounds.width + 0.01,
                    "{text:?} (rect {rect:?}, measured width {w}) overflows the toast's right edge"
                );
                assert!(
                    rect.y + 16.0 <= vt.bounds.y + vt.bounds.height + 0.01,
                    "{text:?} overflows the toast's bottom edge"
                );
            }

            // The title run must end at or before the dismiss
            // button's left edge (never drawn under `×`) — the action
            // row moved off the title line entirely, so it no longer
            // constrains the title at all, unlike pre-#1185.
            let title_run = surface
                .text_runs
                .iter()
                .find(|(_, text, _)| text.starts_with("Install Markdown"))
                .expect("truncated title painted");
            let (title_w, _) = surface.surface_measure_text(&title_run.1);
            assert!(
                title_run.0.x + title_w <= db.x + 0.01,
                "title run {:?} overlaps the dismiss button at {:?}",
                title_run,
                db
            );

            // The action row sits on its own line, strictly below both
            // the title row and the dismiss button — never inline with
            // either.
            assert!(
                ab.y > db.y + db.height - 0.01,
                "action row overlaps dismiss's row"
            );

            // The long body needed more than one line, so the box grew
            // taller than the single-body-line default, and the button
            // row adds further height on top of that.
            let single_line_height = 16.0 + 8.0 * 2.0 + 16.0; // line_height + 2*padding + 1 body line
            assert!(
                vt.bounds.height > single_line_height,
                "box should have grown to fit the wrapped body: height={}",
                vt.bounds.height
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // ── Toast primitive tests (D6 shape, new B.3 primitive) ───────────

    fn make_toast(id: &str, title: &str) -> Toast {
        Toast {
            id: WidgetId::new(id),
            title: title.to_string(),
            body: String::new(),
            severity: ToastSeverity::Info,
            actions: Vec::new(),
            accent: None,
        }
    }

    fn make_toast_stack(corner: ToastCorner, toasts: Vec<Toast>) -> ToastOverlay {
        ToastOverlay {
            id: WidgetId::new("toasts"),
            corner,
            toasts,
            focus: None,
        }
    }

    #[test]
    fn toast_layout_empty() {
        let stack = make_toast_stack(ToastCorner::BottomRight, vec![]);
        let layout = stack.layout(0.0, 0.0, 800.0, 600.0, 16.0, 8.0, |_| {
            ToastMeasure::new(300.0, 64.0)
        });
        assert_eq!(layout.visible_toasts.len(), 0);
        assert_eq!(layout.hit_test(100.0, 100.0), ToastHit::Empty);
    }

    #[test]
    fn toast_layout_bottom_right_newest_at_bottom() {
        let stack = make_toast_stack(
            ToastCorner::BottomRight,
            vec![
                make_toast("first", "First"),
                make_toast("second", "Second"),
                make_toast("third", "Third"),
            ],
        );
        let layout = stack.layout(0.0, 0.0, 800.0, 600.0, 16.0, 8.0, |_| {
            ToastMeasure::new(300.0, 64.0)
        });
        assert_eq!(layout.visible_toasts.len(), 3);
        // Newest (idx=2, "third") pinned at the bottom.
        let newest = &layout.visible_toasts[0];
        assert_eq!(newest.toast_idx, 2);
        assert_eq!(newest.id.as_str(), "third");
        // Newest bottom = viewport_height (600) - margin (16) - toast_height (64) = 520
        assert_eq!(newest.bounds.y, 520.0);
        // Right-aligned: x = 800 - 16 - 300 = 484
        assert_eq!(newest.bounds.x, 484.0);
        // Second-newest above with gap.
        assert_eq!(layout.visible_toasts[1].id.as_str(), "second");
        assert_eq!(layout.visible_toasts[1].bounds.y, 520.0 - 8.0 - 64.0);
    }

    #[test]
    fn toast_layout_top_left_newest_at_top() {
        let stack = make_toast_stack(
            ToastCorner::TopLeft,
            vec![make_toast("a", "A"), make_toast("b", "B")],
        );
        let layout = stack.layout(0.0, 0.0, 800.0, 600.0, 10.0, 5.0, |_| {
            ToastMeasure::new(200.0, 50.0)
        });
        assert_eq!(layout.visible_toasts.len(), 2);
        // Iteration is oldest-first for top corners.
        let first = &layout.visible_toasts[0];
        assert_eq!(first.id.as_str(), "a");
        assert_eq!(first.bounds.x, 10.0);
        assert_eq!(first.bounds.y, 10.0);
        let second = &layout.visible_toasts[1];
        assert_eq!(second.bounds.y, 10.0 + 50.0 + 5.0);
    }

    #[test]
    fn toast_layout_action_and_dismiss_regions() {
        let mut toast = make_toast("t1", "Build failed");
        toast.actions = vec![ToastButton {
            id: WidgetId::new("open_log"),
            label: "Open log".to_string(),
            primary: false,
        }];
        let stack = make_toast_stack(ToastCorner::BottomRight, vec![toast]);
        let layout = stack.layout(0.0, 0.0, 800.0, 600.0, 16.0, 8.0, |_| ToastMeasure {
            width: 300.0,
            height: 64.0,
            dismiss_rect: Some(Rect::new(300.0 - 24.0, 0.0, 24.0, 24.0)),
            action_rects: vec![Rect::new(300.0 - 80.0, 64.0 - 20.0, 80.0, 20.0)],
        });
        let v = &layout.visible_toasts[0];
        assert!(v.dismiss_bounds.is_some());
        assert_eq!(v.action_rects.len(), 1);
        let db = v.dismiss_bounds.unwrap();
        let ab = v.action_rects[0];
        // Dismiss at the trailing (top) edge.
        assert_eq!(db.x + db.width, v.bounds.x + v.bounds.width);
        // Action row sits on its own, lower row — below the dismiss row,
        // not inline with it.
        assert!(ab.y >= db.y + db.height);

        // Hit-test on dismiss.
        match layout.hit_test(db.x + 5.0, db.y + 10.0) {
            ToastHit::Dismiss(id) => assert_eq!(id.as_str(), "t1"),
            _ => panic!("expected Dismiss hit"),
        }
        // Hit-test on action.
        match layout.hit_test(ab.x + 5.0, ab.y + 10.0) {
            ToastHit::Action(id) => assert_eq!(id.as_str(), "open_log"),
            _ => panic!("expected Action hit"),
        }
        // Hit-test on body (left part of toast, not on action/dismiss).
        match layout.hit_test(v.bounds.x + 5.0, v.bounds.y + 10.0) {
            ToastHit::Body(id) => assert_eq!(id.as_str(), "t1"),
            _ => panic!("expected Body hit"),
        }
    }

    /// A toast with two actions produces two, non-overlapping
    /// `action_rects` entries, aligned 1:1 with `Toast::actions`.
    #[test]
    fn toast_layout_multiple_action_regions() {
        let mut toast = make_toast("t1", "Install Markdown Language Server?");
        toast.actions = vec![
            ToastButton {
                id: WidgetId::new("install"),
                label: "Install".to_string(),
                primary: true,
            },
            ToastButton {
                id: WidgetId::new("dont-ask"),
                label: "Don't ask again".to_string(),
                primary: false,
            },
        ];
        let stack = make_toast_stack(ToastCorner::BottomRight, vec![toast]);
        let layout = stack.layout(0.0, 0.0, 800.0, 600.0, 16.0, 8.0, |_| ToastMeasure {
            width: 300.0,
            height: 80.0,
            dismiss_rect: Some(Rect::new(276.0, 0.0, 24.0, 24.0)),
            action_rects: vec![
                Rect::new(120.0, 60.0, 70.0, 20.0),
                Rect::new(198.0, 60.0, 90.0, 20.0),
            ],
        });
        let v = &layout.visible_toasts[0];
        assert_eq!(v.action_rects.len(), 2);
        let install = v.action_rects[0];
        let dont_ask = v.action_rects[1];
        // No overlap between the two buttons.
        assert!(install.x + install.width <= dont_ask.x);

        match layout.hit_test(install.x + 1.0, install.y + 1.0) {
            ToastHit::Action(id) => assert_eq!(id.as_str(), "install"),
            other => panic!("expected Action(install), got {other:?}"),
        }
        match layout.hit_test(dont_ask.x + 1.0, dont_ask.y + 1.0) {
            ToastHit::Action(id) => assert_eq!(id.as_str(), "dont-ask"),
            other => panic!("expected Action(dont-ask), got {other:?}"),
        }
    }

    #[test]
    fn toast_layout_stack_clips_when_out_of_room() {
        // 5 toasts of 64px each, but viewport only has 200 px from margin
        // to top. Should render as many as fit.
        let stack = make_toast_stack(
            ToastCorner::BottomRight,
            (0..5)
                .map(|i| make_toast(&format!("t{i}"), &format!("T{i}")))
                .collect(),
        );
        let layout = stack.layout(0.0, 0.0, 800.0, 200.0, 10.0, 8.0, |_| {
            ToastMeasure::new(300.0, 64.0)
        });
        // Bottom stack. Newest at y = 200 - 10 - 64 = 126. Each subsequent
        // goes up 64+8=72. Next: 126-72=54. Next: 54-72=-18 (would be off-top).
        // So only 2-3 fit. Specifically we break when y_cursor <= 0.
        assert!(layout.visible_toasts.len() >= 2);
        assert!(layout.visible_toasts.len() <= 3);
    }

    /// Non-zero-origin regression guard: `ToastOverlay::layout` previously
    #[test]
    fn toast_layout_nonzero_origin_shifts_every_bound() {
        let mut toast = make_toast("t1", "Build failed");
        toast.actions = vec![ToastButton {
            id: WidgetId::new("open_log"),
            label: "Open log".to_string(),
            primary: false,
        }];
        let stack = make_toast_stack(ToastCorner::BottomRight, vec![toast]);
        let measure = |_: usize| ToastMeasure {
            width: 300.0,
            height: 64.0,
            dismiss_rect: Some(Rect::new(276.0, 0.0, 24.0, 24.0)),
            action_rects: vec![Rect::new(220.0, 44.0, 80.0, 20.0)],
        };
        let origin = stack.layout(0.0, 0.0, 800.0, 600.0, 16.0, 8.0, measure);
        let shifted = stack.layout(7.0, 13.0, 800.0, 600.0, 16.0, 8.0, measure);

        let o = &origin.visible_toasts[0];
        let s = &shifted.visible_toasts[0];
        assert_eq!(s.bounds.x, o.bounds.x + 7.0);
        assert_eq!(s.bounds.y, o.bounds.y + 13.0);
        assert_eq!(s.bounds.width, o.bounds.width);
        assert_eq!(
            s.dismiss_bounds.unwrap().x,
            o.dismiss_bounds.unwrap().x + 7.0
        );
        assert_eq!(s.action_rects[0].y, o.action_rects[0].y + 13.0);

        // Round trip: an absolute hit against the shifted layout must
        // resolve the same way the origin layout resolves its local hit.
        let db = s.dismiss_bounds.unwrap();
        assert_eq!(
            shifted.hit_test(db.x + 5.0, db.y + 10.0),
            ToastHit::Dismiss(WidgetId::new("t1")),
        );
    }
}