rust_widgets 2.8.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! MDI area widget.
use crate::core::{Color, Font, HorizontalAlignment, ObjectId, Point, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;

use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
#[cfg(feature = "image")]
use crate::widget::Image;
use crate::widget::{BaseWidget, Draw, SimpleRegistry, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
use std::cell::RefCell;
use std::rc::Rc;
/// MDI area widget.
pub struct MdiArea {
    base: BaseWidget,
    subwindows: Vec<MdiSubWindow>,
    active_subwindow: Option<usize>,
    view_mode: ViewMode,
    background: Background,
    activation_order: ActivationOrder,
    /// Emitted with the child `ObjectId` whenever a sub-window becomes active,
    /// including the automatic activation of the first sub-window on add and of
    /// a replacement sub-window after the active one is removed.
    pub subwindow_activated: Signal1<ObjectId>,
    /// Optional shared registry for child widget forwarding.
    registry: Option<Rc<RefCell<SimpleRegistry>>>,
}
/// MDI sub-window.
pub struct MdiSubWindow {
    widget: ObjectId,
    geometry: Rect,
    title: String,
    #[cfg(feature = "image")]
    icon: Option<Image>,
    minimized: bool,
    maximized: bool,
    closable: bool,
    movable: bool,
    resizable: bool,
    z_order: i32,
}
/// How an MDI area arranges its sub-windows.
///
/// # Not the same as [`crate::widget::view_widgets::list_view::ViewMode`]
///
/// Both types are called `ViewMode`, but they describe different axes and are
/// **not** interchangeable:
///
/// * this one — how an `MdiArea` lays its child windows out (free-floating
///   sub-windows vs. tabs inside the area);
/// * [`list_view::ViewMode`][lv] — how one `ListView` presents its *own items*
///   (list, icons, details, thumbnails).
///
/// They are deliberately left as two enums: merging them would create one type
/// whose variants are meaningless in the other's context, so a `match` could not
/// be exhaustive in either widget. See principle #49.
///
/// [lv]: crate::widget::view_widgets::list_view::ViewMode
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ViewMode {
    /// Sub-window mode
    #[default]
    SubWindowView,
    /// Tabbed view
    TabbedView,
}
/// MDI background.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Background {
    /// No background
    NoBackground,
    /// Plain color background
    #[default]
    Plain,
    /// Gradient background
    Gradient,
    /// Pattern background
    Pattern,
}
/// MDI activation order.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum ActivationOrder {
    /// Activation follows creation order
    CreationOrder,
    /// Activation follows stacking order
    #[default]
    StackingOrder,
    /// Activation follows history order
    HistoryOrder,
}
impl MdiSubWindow {
    /// Creates a new MDI sub-window.
    pub fn new(widget: ObjectId, geometry: Rect) -> Self {
        Self {
            widget,
            geometry,
            title: String::new(),
            #[cfg(feature = "image")]
            icon: None,
            minimized: false,
            maximized: false,
            closable: true,
            movable: true,
            resizable: true,
            z_order: 0,
        }
    }
    /// Returns widget.
    pub fn widget(&self) -> ObjectId {
        self.widget
    }
    /// Returns geometry.
    pub fn geometry(&self) -> Rect {
        self.geometry
    }
    /// Sets geometry.
    pub fn set_geometry(&mut self, geometry: Rect) {
        self.geometry = geometry;
    }
    /// Returns title.
    pub fn title(&self) -> &str {
        &self.title
    }
    /// Sets title.
    pub fn set_title(&mut self, title: String) {
        self.title = title;
    }
    #[cfg(feature = "image")]
    /// Returns icon.
    pub fn icon(&self) -> Option<&Image> {
        self.icon.as_ref()
    }
    #[cfg(feature = "image")]
    /// Sets icon.
    pub fn set_icon(&mut self, icon: Option<Image>) {
        self.icon = icon;
    }
    /// Returns whether sub-window is minimized.
    pub fn is_minimized(&self) -> bool {
        self.minimized
    }
    /// Sets minimized state.
    pub fn set_minimized(&mut self, minimized: bool) {
        self.minimized = minimized;
    }
    /// Returns whether sub-window is maximized.
    pub fn is_maximized(&self) -> bool {
        self.maximized
    }
    /// Sets maximized state.
    pub fn set_maximized(&mut self, maximized: bool) {
        self.maximized = maximized;
    }
    /// Returns whether sub-window is closable.
    pub fn is_closable(&self) -> bool {
        self.closable
    }
    /// Sets closable state.
    pub fn set_closable(&mut self, closable: bool) {
        self.closable = closable;
    }
    /// Returns whether sub-window is movable.
    pub fn is_movable(&self) -> bool {
        self.movable
    }
    /// Sets movable state.
    pub fn set_movable(&mut self, movable: bool) {
        self.movable = movable;
    }
    /// Returns whether sub-window is resizable.
    pub fn is_resizable(&self) -> bool {
        self.resizable
    }
    /// Sets resizable state.
    pub fn set_resizable(&mut self, resizable: bool) {
        self.resizable = resizable;
    }
    /// Returns z-order.
    pub fn z_order(&self) -> i32 {
        self.z_order
    }
    /// Sets z-order.
    pub fn set_z_order(&mut self, z_order: i32) {
        self.z_order = z_order;
    }
}
impl MdiArea {
    /// Creates an MDI area.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::MdiArea, geometry, "MdiArea"),
            subwindows: Vec::new(),
            active_subwindow: None,
            view_mode: ViewMode::SubWindowView,
            background: Background::Plain,
            activation_order: ActivationOrder::StackingOrder,
            subwindow_activated: Signal1::new(),
            registry: None,
        }
    }
    /// Sets the shared widget registry for child forwarding.
    pub fn set_registry(&mut self, registry: Rc<RefCell<SimpleRegistry>>) {
        self.registry = Some(registry);
        self.base.request_redraw();
    }
    /// Returns the shared widget registry, if set.
    pub fn registry(&self) -> Option<&Rc<RefCell<SimpleRegistry>>> {
        self.registry.as_ref()
    }
    /// Adds a sub-window.
    pub fn add_sub_window(&mut self, widget: ObjectId, geometry: Rect) -> usize {
        let mut subwindow = MdiSubWindow::new(widget, geometry);
        subwindow.z_order = self.subwindows.len() as i32;
        self.base.add_child(widget);
        self.subwindows.push(subwindow);
        let index = self.subwindows.len().saturating_sub(1);
        if self.active_subwindow.is_none() {
            self.active_subwindow = Some(index);
            self.subwindow_activated.emit(widget);
        }
        index
    }
    /// Removes a sub-window.
    pub fn remove_sub_window(&mut self, widget: ObjectId) {
        if let Some(index) = self.subwindows.iter().position(|sw| sw.widget == widget) {
            self.base.remove_child(widget);
            self.subwindows.remove(index);
            if self.active_subwindow == Some(index) {
                self.active_subwindow = None;
                // Try to activate another sub-window
                if !self.subwindows.is_empty() {
                    let new_index = index.min(self.subwindows.len() - 1);
                    self.active_subwindow = Some(new_index);
                    self.subwindow_activated.emit(self.subwindows[new_index].widget);
                }
            } else if let Some(active_index) = self.active_subwindow {
                if active_index > index {
                    self.active_subwindow = Some(active_index - 1);
                }
            }
        }
    }
    /// Returns number of sub-windows.
    pub fn sub_window_count(&self) -> usize {
        self.subwindows.len()
    }
    /// Returns active sub-window.
    pub fn active_sub_window(&self) -> Option<ObjectId> {
        self.active_subwindow.and_then(|index| self.subwindows.get(index).map(|sw| sw.widget))
    }
    /// Sets active sub-window.
    pub fn set_active_sub_window(&mut self, widget: ObjectId) {
        if let Some(index) = self.subwindows.iter().position(|sw| sw.widget == widget) {
            if self.active_subwindow != Some(index) {
                self.active_subwindow = Some(index);
                self.subwindow_activated.emit(widget);
                self.base.request_redraw();
            }
        }
    }
    /// Returns sub-window at index.
    pub fn sub_window(&self, index: usize) -> Option<&MdiSubWindow> {
        self.subwindows.get(index)
    }
    /// Returns mutable sub-window at index.
    pub fn sub_window_mut(&mut self, index: usize) -> Option<&mut MdiSubWindow> {
        self.subwindows.get_mut(index)
    }
    /// Returns view mode.
    pub fn view_mode(&self) -> ViewMode {
        self.view_mode
    }
    /// Sets view mode.
    pub fn set_view_mode(&mut self, mode: ViewMode) {
        self.view_mode = mode;
        self.base.request_redraw();
    }

    /// The box the tab strip occupies in [`ViewMode::TabbedView`].
    ///
    /// One derivation, read by the paint *and* by [`Self::tab_at_point`], because a strip whose
    /// clickable tabs are not the tabs it drew is the same class of defect the row height had in
    /// `list_view` -- two independent derivations that drift.
    fn tab_strip_rect(&self) -> Rect {
        let rect = self.geometry();
        Rect::new(
            rect.x,
            rect.y,
            rect.width,
            TAB_STRIP_HEIGHT.min(rect.height as i32).max(0) as u32,
        )
    }

    /// Tab `index`'s own box, or `None` when it is past the strip's trailing edge.
    ///
    /// Tabs are laid out end to end from the strip's leading edge at an equal width, capped at
    /// [`TAB_MAX_WIDTH`]: a strip holding two tabs must not stretch each across half the work area,
    /// because tabs and a toolbar are read differently. A tab that would cross the trailing edge is
    /// not returned at all rather than returned truncated -- a half-drawn tab reads as a rendering
    /// error, and the caller can draw an overflow affordance instead.
    fn tab_rect(&self, index: usize) -> Option<Rect> {
        let count = self.subwindows.len();
        if count == 0 || index >= count {
            return None;
        }
        let strip = self.tab_strip_rect();
        let width = (strip.width / count as u32).clamp(1, TAB_MAX_WIDTH);
        let x = strip.x + (width as usize * index) as i32;
        if x + width as i32 > strip.x + strip.width as i32 {
            return None;
        }
        Some(Rect::new(x, strip.y, width, strip.height))
    }

    /// The tab index a point falls on, if it falls on a drawn tab.
    ///
    /// The inverse of [`Self::tab_rect`], and deliberately built on it for the same reason
    /// `list_view` builds its own inverse on its forward geometry.
    fn tab_at_point(&self, point: Point) -> Option<usize> {
        let strip = self.tab_strip_rect();
        if !strip.contains_point(point) {
            return None;
        }
        (0..self.subwindows.len())
            .find(|index| self.tab_rect(*index).is_some_and(|tab| tab.contains_point(point)))
    }

    /// Where sub-window `index` is placed under the current [`ViewMode`].
    ///
    /// # Why one struct rather than a branch in the paint
    ///
    /// The two modes differ in **two** things: the frame's box and whether the frame draws its own
    /// title bar. A paint that read `self.view_mode` at each of those places would be two chances to
    /// update one of them, and the symptom would be a tab strip naming a window whose title bar is
    /// also drawn -- or, worse, a click that activates a tab whose body is not the one on screen.
    /// Resolving the mode once and reading the result everywhere is what makes that impossible.
    ///
    /// # The modes
    ///
    /// | mode | frame | title bar |
    /// |---|---|---|
    /// | `SubWindowView` | the sub-window's own stored geometry | drawn |
    /// | `TabbedView` | the work area below the tab strip | not drawn (the tab names it) |
    ///
    /// # Why a non-active sub-window has no placement in `TabbedView`
    ///
    /// The mode shows exactly one window, and which one is [`Self::active_sub_window`]'s answer.
    /// Handing every sub-window the whole body would paint them all on top of each other, and the
    /// last one drawn -- not the active one -- would be the one the user sees.
    fn subwindow_placement(&self, index: usize) -> Option<SubwindowPlacement> {
        let subwindow = self.subwindows.get(index)?;
        match self.view_mode {
            ViewMode::SubWindowView => {
                Some(SubwindowPlacement { frame: subwindow.geometry, title_bar: true })
            }
            ViewMode::TabbedView => {
                if self.active_subwindow != Some(index) {
                    return None;
                }
                let rect = self.geometry();
                let strip = self.tab_strip_rect();
                // The body is the work area below the strip. Both edges are taken from the same
                // `geometry()` the strip was, so a strip clamped to a short area cannot leave the
                // body starting *above* the strip's bottom edge.
                let top = strip.y + strip.height as i32;
                Some(SubwindowPlacement {
                    frame: Rect::new(
                        rect.x,
                        top,
                        rect.width,
                        (rect.y + rect.height as i32 - top).max(0) as u32,
                    ),
                    title_bar: false,
                })
            }
        }
    }

    /// Returns background.
    pub fn background(&self) -> Background {
        self.background
    }
    /// Sets background.
    pub fn set_background(&mut self, background: Background) {
        self.background = background;
        self.base.request_redraw();
    }
    /// Returns activation order.
    pub fn activation_order(&self) -> ActivationOrder {
        self.activation_order
    }
    /// Sets activation order.
    pub fn set_activation_order(&mut self, order: ActivationOrder) {
        self.activation_order = order;
        self.base.request_redraw();
    }
    /// Cascade sub-windows.
    pub fn cascade_sub_windows(&mut self) {
        let area_rect = self.geometry();
        let count = self.subwindows.len();
        if count == 0 {
            return;
        }
        let offset = 30;
        let max_width =
            (area_rect.width as f32 - offset as f32 * (count as f32 - 1.0)).max(0.0) as u32;
        let max_height =
            (area_rect.height as f32 - offset as f32 * (count as f32 - 1.0)).max(0.0) as u32;
        for (i, subwindow) in self.subwindows.iter_mut().enumerate() {
            let x = area_rect.x as f32 + offset as f32 * i as f32;
            let y = area_rect.y as f32 + offset as f32 * i as f32;
            subwindow.geometry = Rect::new(x as i32, y as i32, max_width, max_height);
        }
    }
    /// Tile sub-windows.
    pub fn tile_sub_windows(&mut self) {
        let area_rect = self.geometry();
        let count = self.subwindows.len();
        if count == 0 {
            return;
        }
        let cols = (count as f32).sqrt().ceil() as usize;
        let rows = (count as f32 / cols as f32).ceil() as usize;
        let cell_width = (area_rect.width as f32 / cols as f32).max(0.0) as u32;
        let cell_height = (area_rect.height as f32 / rows as f32).max(0.0) as u32;
        for (i, subwindow) in self.subwindows.iter_mut().enumerate() {
            let col = i % cols;
            let row = i / cols;
            let x = area_rect.x as f32 + cell_width as f32 * col as f32;
            let y = area_rect.y as f32 + cell_height as f32 * row as f32;
            subwindow.geometry = Rect::new(x as i32, y as i32, cell_width, cell_height);
        }
    }
    /// Arranges minimized sub-windows.
    pub fn arrange_icons(&mut self) {
        let area_rect = self.geometry();
        let mut minimized: Vec<_> = self.subwindows.iter_mut().filter(|sw| sw.minimized).collect();
        let count = minimized.len();
        if count == 0 {
            return;
        }
        let icon_width = 100;
        let icon_height = 80;
        let spacing = 10;
        let cols = ((area_rect.width as f32 - spacing as f32)
            / (icon_width as f32 + spacing as f32))
            .floor()
            .max(1.0) as usize;
        let _rows = count.div_ceil(cols);
        for (i, subwindow) in minimized.iter_mut().enumerate() {
            let col = i % cols;
            let row = i / cols;
            let x = area_rect.x + spacing + (icon_width as i32 + spacing) * col as i32;
            let y = area_rect.y + area_rect.height as i32
                - icon_height
                - spacing
                - (icon_height + spacing) * row as i32;
            subwindow.geometry = Rect::new(x, y, icon_width, icon_height as u32);
        }
    }
    /// Activates next sub-window.
    pub fn activate_next_sub_window(&mut self) {
        if self.subwindows.is_empty() {
            return;
        }
        let current = self.active_subwindow.unwrap_or(0);
        let next = (current + 1) % self.subwindows.len();
        self.set_active_sub_window(self.subwindows[next].widget);
    }
    /// Activates previous sub-window.
    pub fn activate_previous_sub_window(&mut self) {
        if self.subwindows.is_empty() {
            return;
        }
        let current = self.active_subwindow.unwrap_or(0);
        let prev = if current == 0 { self.subwindows.len() - 1 } else { current - 1 };
        self.set_active_sub_window(self.subwindows[prev].widget);
    }
    /// Returns sub-window at position.
    fn sub_window_at_position(&self, pos: Point) -> Option<usize> {
        // Check from top (highest z-order) to bottom
        let mut sorted_indices: Vec<usize> = (0..self.subwindows.len()).collect();
        sorted_indices.sort_by_key(|&i| -self.subwindows[i].z_order);
        for index in sorted_indices {
            let subwindow = &self.subwindows[index];
            if subwindow.geometry.contains(pos) {
                return Some(index);
            }
        }
        None
    }
}
// Implement Widget trait
impl Widget for MdiArea {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }

    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> crate::core::Size {
        crate::core::Size::new(
            crate::widget::metrics::dimensions::PANEL_DEFAULT_WIDTH,
            crate::widget::metrics::dimensions::PANEL_DEFAULT_HEIGHT,
        )
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `MdiArea`'s property contract.
///
/// `view_mode` uses this module's own [`ViewMode`] (sub-windows vs. tabs), not
/// `list_view::ViewMode`; the published tokens are the two this widget's reader
/// produced and nothing else.
impl WidgetProperties for MdiArea {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "subwindow_count" => Ok(CapabilityValue::UInt(self.sub_window_count() as u64)),
            "active_subwindow" => match self.active_sub_window() {
                Some(id) => Ok(CapabilityValue::UInt(id)),
                None => Ok(CapabilityValue::Null),
            },
            "view_mode" => {
                let token = match self.view_mode() {
                    ViewMode::SubWindowView => "sub_window_view",
                    ViewMode::TabbedView => "tabbed",
                };
                Ok(CapabilityValue::String(token.to_string()))
            }
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            // All three are read-only in the old dispatch: the reader serves them
            // and the writer has no arm, so the contract says so explicitly.
            "subwindow_count" | "active_subwindow" | "view_mode" => {
                Err(CapabilityAccessError::ReadOnlyProperty)
            }
            _ => base_property_set(self, name, value),
        }
    }

    /// Returns the names this control serves through the property contract.
    ///
    /// Only what `get` answers: `MDI_AREA_PROPERTIES` marks all three
    /// non-readable, and the old reader nevertheless served all three, so the
    /// readable set — not the schema flag — is what callers can actually use.
    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["subwindow_count", "active_subwindow", "view_mode", BASE_PROPERTY_NAMES]
    }

    /// Runs one of the commands `mdi_area` publishes.
    ///
    /// All three address a sub-window by its `ObjectId` (or, for `add_subwindow`, a
    /// `Rect` alongside it), so none can run on the bare name: there is no sub-window
    /// the control could pick that the caller did not name, and activating an
    /// arbitrary one would move focus the caller never asked to move. They are all
    /// [`CapabilityAccessError::OutOfRange`] — valid names whose arguments are what
    /// is missing. `set_view_mode` is a payload-carrying write published by the same
    /// capability and is refused the same way; an override that named only the
    /// non-`set_` commands dropped the trait default's `set_` acceptance, which is
    /// what the final arm restores.
    fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
        match name {
            "add_subwindow" | "remove_subwindow" | "activate_subwindow" => {
                Err(CapabilityAccessError::OutOfRange)
            }
            _ if name.starts_with("set_") => Err(CapabilityAccessError::OutOfRange),
            _ => Err(CapabilityAccessError::UnknownCommand),
        }
    }
}

impl EventHandler for MdiArea {
    /// Sub-window activation and event forwarding stop while the area is disabled.
    ///
    /// Without the guard a disabled MDI area still raised whichever sub-window was clicked and
    /// forwarded the event into it, so `set_enabled(false)` did not take the workspace out of play.
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }
        let mut hit_subwindow = false;
        if let Event::MousePress { pos, button } = event {
            if *button == 1 {
                // In `TabbedView` the tabs are the only clickable chrome, because the windows they
                // name carry no title bar of their own and all sit in the same body. Resolving the
                // tab first is what makes the strip interactive rather than decorative -- a mode
                // whose tabs cannot be clicked is the dead state this whole change closes.
                if self.view_mode == ViewMode::TabbedView {
                    if let Some(index) = self.tab_at_point(*pos) {
                        hit_subwindow = true;
                        self.set_active_sub_window(self.subwindows[index].widget);
                    }
                } else if let Some(index) = self.sub_window_at_position(*pos) {
                    hit_subwindow = true;
                    self.set_active_sub_window(self.subwindows[index].widget);
                }
            }
        }
        let should_forward = !matches!(event, Event::MousePress { .. }) || hit_subwindow;
        // Forward background-independent events, or pointer events that hit a subwindow.
        if should_forward {
            if let Some(widget_id) = self.active_sub_window() {
                if let Some(ref reg) = self.registry {
                    reg.borrow_mut().forward_event(widget_id, event);
                }
            }
        }
    }
}
/// Side of a sub-window's close button, in logical pixels.
///
/// A constant so the title's reserved width and the button's own geometry are derived from
/// one number rather than two literals that have to be kept in step.
const CLOSE_SIZE: i32 = 12;

/// Width reserved at the trailing edge of a sub-window's title bar for the close button
/// and its margins. Used to bound the title so the two cannot overlap.
const CLOSE_SIZE_SUM: u32 = 22;

/// Height of a sub-window's title bar, in logical pixels.
const TITLE_BAR_HEIGHT: i32 = 24;

/// The tab strip's height in `ViewMode::TabbedView`, in logical pixels.
///
/// Two pixels taller than a sub-window's own title bar: a tab carries the title *and* sits above
/// the body it names, so it is chrome twice over and reads as a strip rather than as a detached
/// title bar.
const TAB_STRIP_HEIGHT: i32 = TITLE_BAR_HEIGHT + 2;

/// The widest a single tab may grow in `ViewMode::TabbedView`, in logical pixels.
///
/// A strip of one or two tabs would otherwise stretch each to half the work area, which reads as
/// a toolbar rather than as tabs. Past this a tab stops growing and the free space is left at the
/// strip's trailing edge.
const TAB_MAX_WIDTH: u32 = 160;

/// How far a tab's label is inset from the tab's own edges, in logical pixels.
const TAB_TEXT_INSET: i32 = 6;

/// How a sub-window is *placed* under the current [`ViewMode`], independent of what it contains.
///
/// Produced by `MdiArea::subwindow_placement` and read by the paint, so the two modes cannot be
/// half-applied -- the defect `list_view`'s own `ViewMode` had, where four modes were stored,
/// published and read by nothing. See that method for what each mode does.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
struct SubwindowPlacement {
    /// The sub-window's frame, in the work area's coordinates.
    frame: Rect,
    /// Whether the frame's own title bar is drawn.
    ///
    /// False in `TabbedView`, where the tab strip names the sub-window: drawing both would name
    /// the same window twice, one above the other.
    title_bar: bool,
}

impl Draw for MdiArea {
    fn draw(&mut self, context: &mut RenderContext) {
        // Chrome colours resolve the explicit style first, then the theme's resolved style for
        // this control, and only then a literal. Every colour below used to be a literal, and the
        // plain background in particular was `rgb(240,240,240)` — byte-identical to the light
        // frame fill, so the area painted plenty of pixels and showed none of them. The census
        // reported it as both `ink = 0` and theme-blind.
        //
        // The theme read is a separate manager lock, taken and released inside
        // `resolved_theme_style`, so it is not held across the draw — the global manager's mutex
        // is not re-entrant.
        let style = self.base.style().clone();
        let theme = crate::style::resolved_theme_style("mdi_area");
        // Read as its own lock acquisition and copied out as values, so the guard is dropped
        // before anything else touches the theme.
        let (window_fill, foreground, secondary, primary) = {
            let manager = crate::style::theme_manager();
            match manager.current_theme() {
                Some(active) => (
                    active.colors.background,
                    active.colors.foreground,
                    active.colors.secondary,
                    active.colors.primary,
                ),
                None => (
                    Color::rgb(240, 240, 240),
                    Color::BLACK,
                    Color::rgb(158, 158, 158),
                    Color::rgb(33, 150, 243),
                ),
            }
        };
        let ink = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(foreground);
        // `mdi_area` is absent from `WidgetRole::for_kind_name`'s table, so it classifies as
        // `Surface` and the active theme writes the window fill into `style.background_color`. A
        // work area painted in that colour would be byte-identical to the frame behind it, so a
        // resolved surface equal to the window fill is re-derived a visible step away from it,
        // while a colour the caller set still wins.
        let area = match style.background_color {
            Some(resolved) if resolved != window_fill => resolved,
            _ => window_fill.blend(&ink, 0.08),
        };
        let border = style
            .border_color
            .or_else(|| theme.as_ref().and_then(|t| t.border_color))
            .filter(|resolved| *resolved != area)
            .unwrap_or_else(|| area.blend(&secondary, 0.45));

        // Draw base widget
        let rect = self.geometry();
        // Draw background
        match self.background {
            Background::NoBackground => {
                // No background
            }
            Background::Plain => {
                context.face(
                    rect,
                    area,
                    self.style().surface.unwrap_or_default(),
                    self.style().border_radius.unwrap_or(0),
                    Color::BLACK,
                );
            }
            Background::Gradient => {
                // Draw gradient background: the work area eased into its own border, so the ramp
                // is a shade of the themed surface rather than a fixed light grey.
                let top = area;
                let bottom = area.blend(&border, 0.55);
                for y in 0..rect.height as i32 {
                    let ratio = y as f32 / rect.height.max(1) as f32;
                    let color = top.blend(&bottom, ratio);
                    context.draw_line(
                        Point::new(rect.x, rect.y + y),
                        Point::new(rect.x + rect.width as i32, rect.y + y),
                        color,
                    );
                }
            }
            Background::Pattern => {
                // Draw pattern background: the checker alternates between the surface and one step
                // off it, so the weave reads on either appearance.
                let pattern_size = 20;
                let alt = area.blend(&ink, 0.06);
                for y in 0..(rect.height / pattern_size) as i32 {
                    for x in 0..(rect.width / pattern_size) as i32 {
                        let color = if (x + y) % 2 == 0 { area } else { alt };
                        context.fill_rect(
                            Rect::new(
                                (rect.x as f32 + x as f32 * pattern_size as f32) as i32,
                                (rect.y as f32 + y as f32 * pattern_size as f32) as i32,
                                pattern_size,
                                pattern_size,
                            ),
                            color,
                        );
                    }
                }
            }
        }
        // In `TabbedView` the tab strip is the mode's whole visible difference at rest, so it is
        // drawn before the body: the active tab is the one whose window is about to be painted
        // below it, and painting the strip first keeps the body's own frame from covering it.
        if self.view_mode == ViewMode::TabbedView {
            self.draw_tab_strip(context, &area, &border, &ink, &primary);
        }
        // Draw sub-windows
        // Sort by z-order (lowest first, so highest draws last)
        let mut sorted_indices: Vec<usize> = (0..self.subwindows.len()).collect();
        sorted_indices.sort_by_key(|&i| self.subwindows[i].z_order);
        for index in sorted_indices {
            let Some(placement) = self.subwindow_placement(index) else {
                continue;
            };
            let subwindow = &self.subwindows[index];
            let is_active = self.active_subwindow == Some(index);
            // Draw sub-window frame
            let frame_rect = placement.frame;
            // Draw frame background
            let bg_color = if is_active { area.blend(&ink, 0.22) } else { area.blend(&ink, 0.14) };
            context.fill_rect(frame_rect, bg_color);
            // Draw frame border
            let border_color = if is_active { primary } else { border };
            context.draw_rect(frame_rect, border_color);
            // Draw title bar. `TabbedView` places the window under a tab that already names it, so
            // the frame draws no title bar of its own -- and, crucially, its content gets the whole
            // frame rather than the frame minus a bar nobody drew.
            let title_bar_height = if placement.title_bar { TITLE_BAR_HEIGHT } else { 0 };
            if placement.title_bar {
                let title_bar_color =
                    if is_active { primary } else { area.blend(&secondary, 0.55) };
                context.fill_rect(
                    Rect::new(
                        frame_rect.x,
                        frame_rect.y,
                        frame_rect.width,
                        title_bar_height as u32,
                    ),
                    title_bar_color,
                );
                // Draw title text. Centred on the **title bar's own line box**, not on
                // `title_bar_height / 2`: the latter put the glyph box's top edge on the bar's
                // middle line, so a 14 px label occupied `12..26` inside a 24 px bar and the
                // descenders crossed the bottom border. The close button below already used the
                // correct `(bar - size) / 2` form — one bar, two rules — so both now share this
                // line box.
                let title_bar_rect = Rect::new(
                    frame_rect.x,
                    frame_rect.y,
                    frame_rect.width,
                    title_bar_height as u32,
                );
                let title_font = Font::default();
                let title_line = context.text_line(title_bar_rect, &title_font);
                let text_color = if is_active { primary.contrast_color() } else { ink };
                context.draw_text_fitted(
                    Rect {
                        x: frame_rect.x + 5,
                        y: title_line.y,
                        // Bounded so a long document title cannot run under the close button.
                        width: title_bar_rect.width.saturating_sub(5 + CLOSE_SIZE_SUM),
                        height: title_line.height,
                    },
                    &subwindow.title,
                    &title_font,
                    text_color,
                    HorizontalAlignment::Left,
                );
                // Draw close button if closable
                if subwindow.closable {
                    let close_size = CLOSE_SIZE;
                    let close_x = frame_rect.x + frame_rect.width as i32 - close_size - 5;
                    let close_y = title_line.y + (title_line.height as i32 - close_size) / 2;
                    let close_color = if is_active {
                        primary.contrast_color()
                    } else {
                        ink.blend(&title_bar_color, 0.35)
                    };
                    context.draw_line(
                        Point::new(close_x, close_y),
                        Point::new(close_x + close_size, close_y + close_size),
                        close_color,
                    );
                    context.draw_line(
                        Point::new(close_x + close_size, close_y),
                        Point::new(close_x, close_y + close_size),
                        close_color,
                    );
                }
            }
            // Draw widget content via registry
            let content_rect = Rect::new(
                frame_rect.x,
                frame_rect.y + title_bar_height,
                frame_rect.width,
                frame_rect.height.saturating_sub(title_bar_height as u32),
            );
            if let Some(ref reg) = self.registry {
                reg.borrow_mut().set_widget_geometry(subwindow.widget, content_rect);
                context.push_clip(
                    content_rect.x,
                    content_rect.y,
                    content_rect.width,
                    content_rect.height,
                );
                reg.borrow_mut().draw_widget(subwindow.widget, context);
                context.pop_clip();
            }
        }
    }
}

impl MdiArea {
    /// Paints the `TabbedView` tab strip: one tab per sub-window, the active one raised.
    ///
    /// Every tab's box comes from [`Self::tab_rect`], which is also what [`Self::tab_at_point`]
    /// resolves a click through, so the tab that is highlighted is the tab a click would activate.
    /// A tab past the strip's trailing edge is skipped by `tab_rect` returning `None`, and the loop
    /// stops rather than drawing a truncated tab.
    fn draw_tab_strip(
        &self,
        context: &mut RenderContext,
        area: &Color,
        border: &Color,
        ink: &Color,
        primary: &Color,
    ) {
        let strip = self.tab_strip_rect();
        context.fill_rect(strip, area.blend(ink, 0.06));
        context.draw_line(
            Point::new(strip.x, strip.y + strip.height as i32 - 1),
            Point::new(strip.x + strip.width as i32, strip.y + strip.height as i32 - 1),
            *border,
        );
        let font = Font::default();
        for index in 0..self.subwindows.len() {
            let Some(tab) = self.tab_rect(index) else { break };
            let is_active = self.active_subwindow == Some(index);
            // The active tab is drawn in the accent and the rest in the strip's own surface, which
            // is what makes "which window am I looking at" answerable without reading the title.
            let fill = if is_active { *primary } else { area.blend(ink, 0.12) };
            context.fill_rect(tab, fill);
            context.draw_rect(tab, *border);
            let text_color = if is_active { primary.contrast_color() } else { *ink };
            // The label's band is the tab minus its own padding, so a long title is ellipsised by
            // `draw_text_fitted` rather than running into the next tab.
            let inset = TAB_TEXT_INSET.min(tab.width as i32 / 2);
            let label = Rect::new(
                tab.x + inset,
                tab.y,
                tab.width.saturating_sub(inset as u32 * 2),
                tab.height,
            );
            context.draw_text_fitted(
                context.text_line(label, &font),
                &self.subwindows[index].title,
                &font,
                text_color,
                HorizontalAlignment::Center,
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{Point, Rect};
    use crate::event::Event;
    use crate::widget::svg::render_to_svg;
    use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
    use std::sync::Arc;

    // ── Helper constants ──────────────────────────────────────────────────

    fn widget_id_1() -> ObjectId {
        9201
    }
    fn widget_id_2() -> ObjectId {
        9202
    }
    fn widget_id_3() -> ObjectId {
        9203
    }

    // ── 1. Creation defaults ──────────────────────────────────────────────

    #[test]
    fn mdiarea_creation_defaults() {
        let area = MdiArea::new(Rect::new(0, 0, 600, 400));
        assert_eq!(area.sub_window_count(), 0, "should have no sub-windows");
        assert_eq!(area.active_sub_window(), None, "no active sub-window");
        assert_eq!(area.view_mode(), ViewMode::SubWindowView, "default view mode");
        assert_eq!(area.background(), Background::Plain, "default background");
        assert_eq!(
            area.activation_order(),
            ActivationOrder::StackingOrder,
            "default activation order"
        );
        assert!(area.is_visible(), "should be visible");
        assert!(area.is_enabled(), "should be enabled");
        assert_eq!(area.geometry(), Rect::new(0, 0, 600, 400));
        assert_eq!(area.kind(), WidgetKind::MdiArea);
        assert!(area.registry().is_none(), "registry should be None by default");
    }

    // ── 2. Adding sub-windows ─────────────────────────────────────────────

    #[test]
    fn mdiarea_add_sub_window() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        let idx = area.add_sub_window(widget_id_1(), Rect::new(10, 10, 200, 150));
        assert_eq!(idx, 0, "first sub-window index should be 0");
        assert_eq!(area.sub_window_count(), 1);
        assert_eq!(
            area.active_sub_window(),
            Some(widget_id_1()),
            "first sub-window becomes active"
        );

        let idx2 = area.add_sub_window(widget_id_2(), Rect::new(50, 50, 300, 200));
        assert_eq!(idx2, 1);
        assert_eq!(area.sub_window_count(), 2);

        // Children should include both widget IDs
        let children = area.children();
        assert!(children.contains(&widget_id_1()));
        assert!(children.contains(&widget_id_2()));
    }

    #[test]
    fn mdiarea_add_sub_window_sets_z_order() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_2(), Rect::new(0, 0, 100, 100));

        if let Some(sw) = area.sub_window(0) {
            assert_eq!(sw.z_order(), 0);
        }
        if let Some(sw) = area.sub_window(1) {
            assert_eq!(sw.z_order(), 1);
        }
    }

    // ── 3. Cascading / tiling ─────────────────────────────────────────────

    #[test]
    fn mdiarea_cascade_sub_windows() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 200, 150));
        area.add_sub_window(widget_id_2(), Rect::new(0, 0, 200, 150));
        area.add_sub_window(widget_id_3(), Rect::new(0, 0, 200, 150));

        area.cascade_sub_windows();

        // Each sub-window is offset by 30px
        if let Some(sw) = area.sub_window(0) {
            assert_eq!(sw.geometry().x, 0);
            assert_eq!(sw.geometry().y, 0);
        }
        if let Some(sw) = area.sub_window(1) {
            assert_eq!(sw.geometry().x, 30);
            assert_eq!(sw.geometry().y, 30);
        }
        if let Some(sw) = area.sub_window(2) {
            assert_eq!(sw.geometry().x, 60);
            assert_eq!(sw.geometry().y, 60);
        }
    }

    #[test]
    fn mdiarea_cascade_empty_is_noop() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.cascade_sub_windows(); // should not panic
        assert_eq!(area.sub_window_count(), 0);
    }

    #[test]
    fn mdiarea_tile_sub_windows() {
        let mut area = MdiArea::new(Rect::new(0, 0, 400, 300));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_2(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_3(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100)); // 4th

        area.tile_sub_windows();

        // 4 items -> 2 cols, 2 rows; cell width = 400/2 = 200, cell height = 300/2 = 150
        if let Some(sw) = area.sub_window(1) {
            assert_eq!(sw.geometry().x, 200, "item 1 should be in column 1");
            assert_eq!(sw.geometry().y, 0);
        }
        if let Some(sw) = area.sub_window(2) {
            assert_eq!(sw.geometry().x, 0, "item 2 should be in column 0");
            assert_eq!(sw.geometry().y, 150, "item 2 should be in row 1");
        }
        if let Some(sw) = area.sub_window(3) {
            assert_eq!(sw.geometry().x, 200);
            assert_eq!(sw.geometry().y, 150);
        }
    }

    #[test]
    fn mdiarea_tile_empty_is_noop() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.tile_sub_windows(); // should not panic
        assert_eq!(area.sub_window_count(), 0);
    }

    // ── 4. Removing sub-windows ───────────────────────────────────────────

    #[test]
    fn mdiarea_remove_sub_window() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(10, 10, 200, 150));
        area.add_sub_window(widget_id_2(), Rect::new(50, 50, 300, 200));

        area.remove_sub_window(widget_id_1());
        assert_eq!(area.sub_window_count(), 1);
        assert!(!area.children().contains(&widget_id_1()));
        // The remaining one becomes active
        assert_eq!(area.active_sub_window(), Some(widget_id_2()));
    }

    #[test]
    fn mdiarea_remove_sub_window_nonexistent_is_noop() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100));
        area.remove_sub_window(9999); // not present
        assert_eq!(area.sub_window_count(), 1);
    }

    #[test]
    fn mdiarea_remove_last_sub_window_clears_active() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100));
        area.remove_sub_window(widget_id_1());
        assert_eq!(area.sub_window_count(), 0);
        assert_eq!(area.active_sub_window(), None);
    }

    #[test]
    fn mdiarea_remove_sub_window_adjusts_active_index() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_2(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_3(), Rect::new(0, 0, 100, 100));
        area.set_active_sub_window(widget_id_3()); // active index = 2

        // Remove first sub-window (index 0 < active index 2) -> active shifts to 1
        area.remove_sub_window(widget_id_1());
        assert_eq!(area.active_sub_window(), Some(widget_id_3()), "active widget should stay same");

        // Now remove the widget at the new active index (widget_id_3 is now at index 1)
        area.remove_sub_window(widget_id_3());
        // active becomes 0 (widget_id_2)
        assert_eq!(area.active_sub_window(), Some(widget_id_2()));
    }

    // ── 5. Active sub-window management ───────────────────────────────────

    #[test]
    fn mdiarea_set_active_sub_window() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_2(), Rect::new(0, 0, 100, 100));

        assert_eq!(area.active_sub_window(), Some(widget_id_1()), "first added is active");

        area.set_active_sub_window(widget_id_2());
        assert_eq!(area.active_sub_window(), Some(widget_id_2()));

        // Activating non-existent widget is no-op
        area.set_active_sub_window(9999);
        assert_eq!(area.active_sub_window(), Some(widget_id_2()), "should not change");
    }

    #[test]
    fn mdiarea_activate_next_previous_sub_window() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_2(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_3(), Rect::new(0, 0, 100, 100));

        assert_eq!(area.active_sub_window(), Some(widget_id_1()));

        area.activate_next_sub_window();
        assert_eq!(area.active_sub_window(), Some(widget_id_2()));

        area.activate_next_sub_window();
        assert_eq!(area.active_sub_window(), Some(widget_id_3()));

        // Wrap around
        area.activate_next_sub_window();
        assert_eq!(area.active_sub_window(), Some(widget_id_1()));

        // Previous
        area.activate_previous_sub_window();
        assert_eq!(area.active_sub_window(), Some(widget_id_3()));

        area.activate_previous_sub_window();
        assert_eq!(area.active_sub_window(), Some(widget_id_2()));
    }

    #[test]
    fn mdiarea_activate_next_previous_empty_is_noop() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.activate_next_sub_window();
        area.activate_previous_sub_window();
        assert_eq!(area.active_sub_window(), None);
    }

    // ── 6. Geometry delegation ────────────────────────────────────────────

    #[test]
    fn mdiarea_geometry_delegation() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        assert_eq!(area.geometry(), Rect::new(0, 0, 600, 400));

        area.set_geometry(Rect::new(10, 20, 800, 600));
        assert_eq!(area.geometry(), Rect::new(10, 20, 800, 600));
        assert_eq!(area.base().geometry(), area.geometry());
    }

    #[test]
    fn mdiarea_position_and_size() {
        let mut area = MdiArea::new(Rect::new(5, 10, 600, 400));
        assert_eq!(area.position(), Point::new(5, 10));
        assert_eq!(area.size(), crate::core::Size::new(600, 400));

        area.set_position(Point::new(20, 30));
        assert_eq!(area.geometry(), Rect::new(20, 30, 600, 400));

        area.set_size(crate::core::Size::new(800, 600));
        assert_eq!(area.geometry(), Rect::new(20, 30, 800, 600));
    }

    // ── 7. Visibility ─────────────────────────────────────────────────────

    #[test]
    fn mdiarea_visibility() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        assert!(area.is_visible());

        area.hide();
        assert!(!area.is_visible());

        area.show();
        assert!(area.is_visible());

        area.set_visible(false);
        assert!(!area.is_visible());

        area.set_visible(true);
        assert!(area.is_visible());
    }

    #[test]
    fn mdiarea_enabled_state() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        assert!(area.is_enabled());

        area.set_enabled(false);
        assert!(!area.is_enabled());

        area.set_enabled(true);
        assert!(area.is_enabled());
    }

    // ── 8. ID / Kind ──────────────────────────────────────────────────────

    #[test]
    fn mdiarea_kind() {
        let area = MdiArea::new(Rect::new(0, 0, 600, 400));
        assert_eq!(area.kind(), WidgetKind::MdiArea);
    }

    #[test]
    fn mdiarea_id_is_unique() {
        let a1 = MdiArea::new(Rect::new(0, 0, 100, 100));
        let a2 = MdiArea::new(Rect::new(0, 0, 100, 100));
        assert_ne!(a1.id(), a2.id(), "each MdiArea must have a unique id");
    }

    // ── 9. SVG draw output ────────────────────────────────────────────────

    #[test]
    fn mdiarea_draw_produces_svg_output() {
        let mut area = MdiArea::new(Rect::new(0, 0, 400, 300));
        let svg = render_to_svg(&mut area);
        assert!(svg.starts_with("<svg"), "SVG must start with <svg");
        assert!(svg.ends_with("</svg>"), "SVG must end with </svg>");
        assert!(svg.contains("width=\"400\""), "SVG must contain correct width");
        assert!(svg.contains("height=\"300\""), "SVG must contain correct height");
        assert!(svg.contains("fill="), "SVG should contain fill attributes");
        assert!(svg.len() > 100, "SVG output should be substantial");
    }

    #[test]
    fn mdiarea_draw_with_subwindow_produces_svg() {
        let mut area = MdiArea::new(Rect::new(0, 0, 400, 300));
        area.add_sub_window(widget_id_1(), Rect::new(20, 30, 200, 150));
        area.set_background(Background::Gradient);
        let svg = render_to_svg(&mut area);
        assert!(svg.starts_with("<svg"));
        assert!(svg.contains("fill="));
        assert!(svg.len() > 200);
    }

    #[test]
    fn mdiarea_draw_with_pattern_background_produces_svg() {
        let mut area = MdiArea::new(Rect::new(0, 0, 60, 60));
        area.set_background(Background::Pattern);
        let svg = render_to_svg(&mut area);
        assert!(svg.starts_with("<svg"));
        assert!(svg.contains("fill="));
    }

    #[test]
    fn mdiarea_draw_no_background_produces_svg() {
        let mut area = MdiArea::new(Rect::new(0, 0, 100, 80));
        area.set_background(Background::NoBackground);
        let svg = render_to_svg(&mut area);
        assert!(svg.starts_with("<svg"));
        assert!(svg.len() > 50);
    }

    // ── 10. Signal accessors ─────────────────────────────────────────────

    #[test]
    fn mdiarea_subwindow_activated_signal_emits_on_set() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_2(), Rect::new(0, 0, 100, 100));

        let emitted = Arc::new(AtomicUsize::new(0));
        let last_id = Arc::new(AtomicU64::new(0));
        {
            let e = emitted.clone();
            let lid = last_id.clone();
            area.subwindow_activated.connect(move |id: Arc<ObjectId>| {
                e.fetch_add(1, Ordering::SeqCst);
                lid.store(*id, Ordering::SeqCst);
            });
        }

        // Emitted once on add (first sub-window becomes active)
        assert_eq!(emitted.load(Ordering::SeqCst), 0, "signal not connected during add");

        // Connect first, then set active
        let emitted2 = Arc::new(AtomicUsize::new(0));
        let e2 = emitted2.clone();
        area.subwindow_activated.connect(move |_: Arc<ObjectId>| {
            e2.fetch_add(1, Ordering::SeqCst);
        });

        area.set_active_sub_window(widget_id_2());
        assert_eq!(emitted2.load(Ordering::SeqCst), 1, "signal should emit on set_active");

        // Setting same value does not emit
        area.set_active_sub_window(widget_id_2());
        assert_eq!(emitted2.load(Ordering::SeqCst), 1, "same value should not emit");
    }

    #[test]
    fn mdiarea_subwindow_activated_on_remove_and_next() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_2(), Rect::new(0, 0, 100, 100));

        let hits = Arc::new(AtomicUsize::new(0));
        let h = hits.clone();
        area.subwindow_activated.connect(move |_: Arc<ObjectId>| {
            h.fetch_add(1, Ordering::SeqCst);
        });

        // Removing the active sub-window triggers activation of another
        let before = hits.load(Ordering::SeqCst);
        area.remove_sub_window(widget_id_1());
        assert!(
            hits.load(Ordering::SeqCst) > before,
            "removing active sub-window should emit activation signal"
        );
    }

    // ── View mode / Background / Activation order setters ─────────────────

    #[test]
    fn mdiarea_view_mode_enum() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        assert_eq!(area.view_mode(), ViewMode::SubWindowView);

        area.set_view_mode(ViewMode::TabbedView);
        assert_eq!(area.view_mode(), ViewMode::TabbedView);

        area.set_view_mode(ViewMode::SubWindowView);
        assert_eq!(area.view_mode(), ViewMode::SubWindowView);
    }

    #[test]
    fn mdiarea_background_enum() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        assert_eq!(area.background(), Background::Plain);

        area.set_background(Background::NoBackground);
        assert_eq!(area.background(), Background::NoBackground);

        area.set_background(Background::Gradient);
        assert_eq!(area.background(), Background::Gradient);

        area.set_background(Background::Pattern);
        assert_eq!(area.background(), Background::Pattern);
    }

    #[test]
    fn mdiarea_activation_order_enum() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        assert_eq!(area.activation_order(), ActivationOrder::StackingOrder);

        area.set_activation_order(ActivationOrder::CreationOrder);
        assert_eq!(area.activation_order(), ActivationOrder::CreationOrder);

        area.set_activation_order(ActivationOrder::HistoryOrder);
        assert_eq!(area.activation_order(), ActivationOrder::HistoryOrder);
    }

    // ── Sub-window property access ────────────────────────────────────────

    #[test]
    fn mdiarea_sub_window_accessors() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(10, 20, 200, 150));

        if let Some(sw) = area.sub_window(0) {
            assert_eq!(sw.widget(), widget_id_1());
            assert_eq!(sw.geometry(), Rect::new(10, 20, 200, 150));
            assert_eq!(sw.title(), "");
            assert!(sw.is_closable());
            assert!(sw.is_movable());
            assert!(sw.is_resizable());
            assert!(!sw.is_minimized());
            assert!(!sw.is_maximized());
            assert_eq!(sw.z_order(), 0);
        }

        // Mutable access
        if let Some(sw) = area.sub_window_mut(0) {
            sw.set_title("Doc".to_string());
            sw.set_minimized(true);
            sw.set_closable(false);
            sw.set_z_order(42);
        }

        if let Some(sw) = area.sub_window(0) {
            assert_eq!(sw.title(), "Doc");
            assert!(sw.is_minimized());
            assert!(!sw.is_closable());
            assert_eq!(sw.z_order(), 42);
        }

        // Out of bounds
        assert!(area.sub_window(5).is_none());
        assert!(area.sub_window_mut(5).is_none());
    }

    #[test]
    fn mdiarea_sub_window_set_geometry() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100));

        if let Some(sw) = area.sub_window_mut(0) {
            sw.set_geometry(Rect::new(50, 60, 300, 200));
        }

        if let Some(sw) = area.sub_window(0) {
            assert_eq!(sw.geometry(), Rect::new(50, 60, 300, 200));
        }
    }

    // ── Mouse event activates sub-window ─────────────────────────────────

    #[test]
    fn mdiarea_mouse_click_activates_sub_window() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(10, 10, 200, 150));
        area.add_sub_window(widget_id_2(), Rect::new(100, 100, 200, 150));

        // First sub-window is active by default
        assert_eq!(area.active_sub_window(), Some(widget_id_1()));

        // Click on second sub-window area
        area.handle_event(&Event::MousePress { pos: Point::new(150, 150), button: 1 });
        assert_eq!(area.active_sub_window(), Some(widget_id_2()));

        // Click back on first sub-window
        area.handle_event(&Event::MousePress { pos: Point::new(20, 20), button: 1 });
        assert_eq!(area.active_sub_window(), Some(widget_id_1()));
    }

    #[test]
    fn mdiarea_mouse_click_outside_sub_window_is_noop() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(10, 10, 200, 150));

        assert_eq!(area.active_sub_window(), Some(widget_id_1()));

        // Click outside all sub-windows
        area.handle_event(&Event::MousePress { pos: Point::new(500, 300), button: 1 });
        assert_eq!(area.active_sub_window(), Some(widget_id_1()), "should not change");
    }

    // ── Arrange icons ─────────────────────────────────────────────────────

    #[test]
    fn mdiarea_arrange_icons() {
        let mut area = MdiArea::new(Rect::new(0, 0, 400, 300));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 200, 150));
        area.add_sub_window(widget_id_2(), Rect::new(0, 0, 200, 150));

        // Mark both as minimized
        if let Some(sw) = area.sub_window_mut(0) {
            sw.set_minimized(true);
        }
        if let Some(sw) = area.sub_window_mut(1) {
            sw.set_minimized(true);
        }

        area.arrange_icons();
        // Both should now be placed at the bottom of the area
        if let Some(sw) = area.sub_window(0) {
            assert_eq!(sw.geometry().width, 100);
            assert_eq!(sw.geometry().height, 80);
            // Positioned at bottom
            assert_eq!(sw.geometry().y, 300 - 80 - 10);
        }
    }

    #[test]
    fn mdiarea_arrange_icons_empty_is_noop() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.arrange_icons(); // should not panic
        assert_eq!(area.sub_window_count(), 0);
    }

    #[test]
    fn mdiarea_arrange_icons_handles_narrow_area() {
        let mut area = MdiArea::new(Rect::new(0, 0, 50, 40));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 20, 20));
        area.sub_window_mut(0).expect("subwindow exists").set_minimized(true);
        area.arrange_icons();
        assert_eq!(area.sub_window(0).map(|window| window.geometry().width), Some(100));
    }

    // ── 11. `view_mode` decides where a sub-window is placed ────────────────

    /// A `TabbedView` area places its active window in the body below the tab strip, and only
    /// that one.
    ///
    /// # What was dead, and what proves it is alive now
    ///
    /// `view_mode` was stored, published (getter, `view_mode` property token, round-trip test) and
    /// read by nothing: `draw` painted the stored sub-window geometries and a title bar for each, so
    /// `TabbedView` rendered byte-identically to `SubWindowView`. Merely *branching* on the mode in
    /// `subwindow_placement` would leave the paint ignoring the result, so this asserts the numbers a
    /// paint has to obey: the frame starts below the strip, spans the work area, and the inactive
    /// windows have no placement at all rather than one under the active window.
    #[test]
    fn tabbed_view_stacks_every_window_in_one_body_below_the_strip() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(10, 10, 100, 80));
        area.add_sub_window(widget_id_2(), Rect::new(200, 200, 100, 80));
        area.set_active_sub_window(widget_id_2());
        area.set_view_mode(ViewMode::TabbedView);

        let strip = area.tab_strip_rect();
        assert_eq!(strip.y, 0);
        assert_eq!(strip.height, TAB_STRIP_HEIGHT as u32);
        assert_eq!(strip.width, 600);

        let active = area.subwindow_placement(1).expect("the active window is placed");
        assert_eq!(active.frame.x, 0, "the body spans the work area");
        assert_eq!(active.frame.width, 600);
        assert_eq!(
            active.frame.y,
            strip.y + strip.height as i32,
            "the body starts below the strip, not over it"
        );
        assert_eq!(
            active.frame.y + active.frame.height as i32,
            400,
            "and runs to the work area's bottom edge"
        );
        assert!(!active.title_bar, "the tab already names this window");

        // The window that is *not* active has no placement: two placements would paint both frames
        // over the same body and the later one would win, which is the wrong window on screen.
        assert!(area.subwindow_placement(0).is_none(), "only the active window occupies the body");

        // And the stored geometry is left alone, so switching back to `SubWindowView` restores it.
        area.set_view_mode(ViewMode::SubWindowView);
        let restored = area.subwindow_placement(0).expect("sub-window view places every window");
        assert_eq!(restored.frame, Rect::new(10, 10, 100, 80));
        assert!(restored.title_bar, "sub-window view draws its own title bar");
    }

    /// A tab is where the click says it is: the tab box the paint reads is the box the hit test
    /// resolves.
    ///
    /// `tab_rect` and `tab_at_point` are one derivation for the same reason `list_view`'s row
    /// geometry is: two independent calculations of "where is tab 3" drift, and the symptom is a
    /// click activating the tab next to the one that was clicked.
    #[test]
    fn a_tab_click_activates_the_tab_it_is_painted_on() {
        let mut area = MdiArea::new(Rect::new(0, 0, 600, 400));
        area.add_sub_window(widget_id_1(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_2(), Rect::new(0, 0, 100, 100));
        area.add_sub_window(widget_id_3(), Rect::new(0, 0, 100, 100));
        area.set_view_mode(ViewMode::TabbedView);

        for index in 0..3 {
            let tab = area.tab_rect(index).expect("three tabs fit");
            let centre = Point::new(tab.x + tab.width as i32 / 2, tab.y + tab.height as i32 / 2);
            assert_eq!(
                area.tab_at_point(centre),
                Some(index),
                "the centre of tab {index} at {tab:?} must hit-test back to it"
            );
        }
        // Tabs are capped rather than stretched: three tabs of 600 px each would each be 200 wide,
        // which is past the cap and reads as a toolbar.
        assert_eq!(area.tab_rect(0).map(|tab| tab.width), Some(TAB_MAX_WIDTH));
        // A click on the strip past the last tab is no tab, not a clamp onto the last one.
        assert_eq!(area.tab_at_point(Point::new(599, 2)), None);
        // And outside the strip entirely is no tab either.
        assert_eq!(area.tab_at_point(Point::new(5, TAB_STRIP_HEIGHT + 40)), None);
    }

    /// The mode reaches the pixels: a `TabbedView` snapshot is not a `SubWindowView` one.
    ///
    /// The geometry assertions above say where the frames go; this says the paint actually obeys
    /// them. Without it a `subwindow_placement` that nothing called would still pass every number.
    #[test]
    fn the_two_view_modes_render_differently() {
        let build = |mode: ViewMode| {
            let mut area = MdiArea::new(Rect::new(0, 0, 240, 160));
            area.add_sub_window(widget_id_1(), Rect::new(10, 10, 120, 90));
            area.add_sub_window(widget_id_2(), Rect::new(40, 40, 120, 90));
            area.set_active_sub_window(widget_id_2());
            area.sub_window_mut(0).expect("exists").set_title("First".to_string());
            area.sub_window_mut(1).expect("exists").set_title("Second".to_string());
            area.set_view_mode(mode);
            area
        };
        let windowed = render_to_svg(&mut build(ViewMode::SubWindowView));
        let tabbed = render_to_svg(&mut build(ViewMode::TabbedView));
        assert_ne!(
            windowed, tabbed,
            "the two view modes must not render identically -- that was the dead state"
        );
        // The tab strip sits on the top row and the sub-window view puts a frame there instead.
        let tabbed_strip = build(ViewMode::TabbedView);
        assert_eq!(tabbed_strip.tab_strip_rect().height, TAB_STRIP_HEIGHT as u32);

        // The *body* is what the mode is actually about, and "the strings differ" alone does not
        // pin it: a `TabbedView` that still painted every window at its stored geometry would differ
        // from the windowed one by the tab strip alone. So the placement is asserted through the
        // rendering's own numbers -- the active window's frame must start at the strip's bottom
        // edge, and the inactive one must not be drawn at its stored geometry.
        let tabbed_area = build(ViewMode::TabbedView);
        let active_frame =
            tabbed_area.subwindow_placement(1).expect("the active window is placed").frame;
        assert_eq!(active_frame.y, TAB_STRIP_HEIGHT, "the tabbed body begins where the strip ends");
        assert_eq!(active_frame.y + active_frame.height as i32, 160);
        assert!(
            tabbed_area.subwindow_placement(0).is_none(),
            "and the inactive window is not painted at its stored geometry"
        );
        // The windowed mode, by contrast, uses the stored geometry for both.
        let windowed_area = build(ViewMode::SubWindowView);
        assert_eq!(
            windowed_area.subwindow_placement(0).expect("placed").frame,
            Rect::new(10, 10, 120, 90)
        );
    }
}