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
// SPDX-License-Identifier: MPL-2.0
// SPDX-FileCopyrightText: 2026 FernTech
//! Custom window title bar widget.
//!
//! `TitleBar` replaces a window's native chrome with a horizontal bar that
//! can host menus, tools, and the standard window controls (minimize /
//! maximize / close). The platform plumbing — beginning a window drag,
//! returning the right `WM_NCHITTEST` codes on Windows, repositioning the
//! macOS traffic lights — lives behind the
//! [`PlatformTitleBarHost`] trait in
//! `teksilo-platform`. The widget itself is platform-agnostic.
//!
//! Construct a `TitleBar` from inside the root-builder closure, fetching
//! the host from the widget tree:
//!
//! ```ignore
//! .root(|tree| {
//! let host = tree.title_bar_host().expect("custom_chrome enabled");
//! tree.add(
//! VStack::new()
//! .child(TitleBar::new(host)
//! .background(theme.colors.surface_raised)
//! .border(theme.colors.border, 1.0)
//! .leading(TextWidget::new(lit!("My App"))))
//! .child(Expand::new().child(/* body */)))
//! })
//! ```
use std::cell::Cell;
use std::rc::Rc;
use teksilo_canvas::{Canvas, Rect, Size, SizeProposal};
use teksilo_core::accessibility::AccessNodeBuilder;
use teksilo_core::color_prop::ColorProp;
use teksilo_core::signal::Prop;
use teksilo_core::widget::{
EventContext, LayoutContext, PaintContext, PendingChild, Widget, WidgetPlacement,
WidgetTreeView,
};
use teksilo_core::widget_id::WidgetId;
use teksilo_core::{HitRegions, PlatformTitleBarHost, Signal};
use teksilo_tokens::{Color, CornerRadius};
use crate::primitives::{FixedSize, HStack};
mod controls;
mod drag_region;
mod resize_strip;
mod window_frame;
mod window_menu;
pub use controls::{ControlAction, ControlButton, WindowControls, WindowControlsLayout};
pub use drag_region::DragRegion;
pub use resize_strip::ResizeStrip;
pub use window_frame::WindowFrame;
/// Type alias for the user-supplied close action that overrides
/// `host.close()` (which on Wayland is currently a no-op due to winit 0.30
/// lacking `Window::request_close`). Set via [`TitleBar::close_action`].
pub type CloseAction = Rc<dyn Fn(&mut EventContext)>;
/// A custom window title bar.
///
/// Layout (left to right):
///
/// ```text
/// [leading inset] [leading slot] [drag region (flexible)] [trailing slot] [trailing inset] [window controls]
/// ```
///
/// The leading inset reserves space for the OS-drawn traffic lights on
/// macOS. The drag region is a `Spacer`-style flex
/// child that absorbs all leftover horizontal space and forwards
/// pointer / drag / double-tap gestures to the platform host. The window
/// controls (minimize / maximize / close) are rendered only when the host
/// advertises [`PlatformTitleBarHost::renders_custom_controls`] — i.e. on
/// Windows and Wayland but not on macOS.
///
/// ## This widget builds exactly once
///
/// `build` consumes the leading / center / trailing slots with `take()`, so a
/// second pass finds them all `None` and produces a bar containing nothing but
/// window controls — no menu, no title, no tools. Nothing here may therefore
/// carry a [`BindingLevel::Rebuild`](teksilo_core::binding::BindingLevel)
/// binding. Reactive state on this widget is expressed either as a
/// `RepaintOnly` colour prop or, for structure, as dormancy via
/// [`teksilo_core::BuildContext::visible_when`] on an always-built child — which is how
/// [`controls_visible`](TitleBar::controls_visible) works. Memoising the
/// resolved slot ids is *not* a workaround: a rebuild replaces the inner row
/// and prunes its subtree, so the cached ids dangle and re-adding them yields
/// an empty bar just the same.
pub struct TitleBar {
host: Rc<dyn PlatformTitleBarHost>,
leading: Option<PendingChild>,
center: Option<PendingChild>,
trailing: Option<PendingChild>,
height: f32,
background: ColorProp,
border_color: ColorProp,
border_width: f32,
/// Optional override for the close button. When set, the close
/// button invokes this closure instead of `ctx.close_window()`.
close_action: Option<CloseAction>,
root_child_id: Option<WidgetId>,
/// `WidgetId` of the `DragRegion` we install. Memoised at build
/// time so `after_paint` can read its bounds via `WidgetTreeView`
/// without walking the subtree.
drag_region_id: Cell<Option<WidgetId>>,
/// Sink that the inner `WindowControls` populates with its
/// per-button ids during build. `None` when no controls are
/// rendered (macOS, where the OS draws traffic lights).
controls_layout: Rc<Cell<Option<WindowControlsLayout>>>,
/// Whether the minimize/maximize/close cluster is shown, statically or
/// reactively. Applied with [`teksilo_core::BuildContext::visible_when`] — **never** a
/// `Rebuild`-level binding. See [`TitleBar::controls_visible`] and
/// [`TitleBar`]'s own "builds once" note.
controls_visible: Prop<bool>,
}
impl std::fmt::Debug for TitleBar {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TitleBar")
.field("height", &self.height)
.field("has_leading", &self.leading.is_some())
.field("has_center", &self.center.is_some())
.field("has_trailing", &self.trailing.is_some())
.finish_non_exhaustive()
}
}
impl TitleBar {
/// Construct a `TitleBar` bound to the given platform host.
///
/// The maximize/restore glyph follows `WindowState::placement` via
/// `ctx.window()` at build time — the host no longer owns the
/// maximize signal.
pub fn new(host: Rc<dyn PlatformTitleBarHost>) -> Self {
Self {
host,
leading: None,
center: None,
trailing: None,
height: 40.0,
background: ColorProp::Static(Color::TRANSPARENT),
border_color: ColorProp::Static(Color::TRANSPARENT),
border_width: 0.0,
close_action: None,
root_child_id: None,
drag_region_id: Cell::new(None),
controls_layout: Rc::new(Cell::new(None)),
controls_visible: Prop::Static(true),
}
}
/// Show or hide the minimize / maximize / close cluster. Default `true`.
///
/// Accepts a plain `bool` or a `Signal<bool>`. Applied through the
/// framework's own dormancy ([`teksilo_core::BuildContext::visible_when`]), so a flip
/// costs a relayout and **never a rebuild** of the bar: a dormant node is
/// skipped by layout, hit-test, focus and paint, so a hidden cluster takes
/// no space and receives no input. A derived (`.map`) signal is fine —
/// binding resolves through to the mutable roots and never calls `observe`.
///
/// The case this exists for is **fullscreen**.
/// [`WindowPlacement::Fullscreen`](teksilo_core::WindowPlacement::Fullscreen)
/// is documented as "covers the entire display, title bar and all chrome
/// hidden", and every desktop convention agrees: macOS hides the traffic
/// lights, Windows fullscreen has no caption buttons, browsers and editors
/// hide their chrome outright. Minimize and maximize are meaningless for a
/// window with no frame. An app drawing custom chrome
/// ([`DecorationsMode::CustomChrome`](teksilo_core::DecorationsMode)) owns
/// that decision itself, because the framework cannot hide a title bar the
/// app composed — so it gates it here.
///
/// An app that hides these **must** keep some other visible way out of
/// fullscreen: a menu item, an on-screen button, or a documented shortcut.
pub fn controls_visible(mut self, visible: impl Into<Prop<bool>>) -> Self {
self.controls_visible = visible.into();
self
}
/// Set the title bar's logical-pixel height. Default: 40.
pub fn height(mut self, height: f32) -> Self {
self.height = height;
self
}
/// Fill the title bar with a solid background color. Default:
/// transparent (the window's clear color shows through).
///
/// Accepts a `Color`, a `Signal<Color>`, or any of the role types
/// (`SurfaceRole`, `TextRole`, `BorderRole`, or their `Signal<…>`
/// variants). Role values resolve at paint time, so the title bar
/// retints live across `ctx.set_theme(...)` switches.
pub fn background(mut self, color: impl Into<ColorProp>) -> Self {
self.background = color.into();
self
}
/// Draw a 1px-or-thicker bottom border separating the title bar from
/// the body.
///
/// Color accepts the same range as [`Self::background`]; pair with
/// `BorderRole::Default` for a theme-tracking divider.
pub fn border(mut self, color: impl Into<ColorProp>, width: f32) -> Self {
self.border_color = color.into();
self.border_width = width;
self
}
/// Set the leading-edge content (e.g. app icon, menus). Rendered to the
/// right of the macOS traffic-light inset.
pub fn leading(mut self, widget: impl Widget + 'static) -> Self {
self.leading = Some(PendingChild::Deferred(Box::new(widget)));
self
}
/// Set the leading-edge content by pre-registered ID.
pub fn leading_id(mut self, id: WidgetId) -> Self {
self.leading = Some(PendingChild::Id(id));
self
}
/// Set the center content (e.g. search box, breadcrumbs). Wrapped in a
/// flexible drag region: clicks that are not consumed by the child
/// initiate a window drag.
pub fn center(mut self, widget: impl Widget + 'static) -> Self {
self.center = Some(PendingChild::Deferred(Box::new(widget)));
self
}
/// Set the center content by pre-registered ID.
pub fn center_id(mut self, id: WidgetId) -> Self {
self.center = Some(PendingChild::Id(id));
self
}
/// Set the trailing-edge content (e.g. user avatar, notification bell).
/// Rendered before the window controls.
pub fn trailing(mut self, widget: impl Widget + 'static) -> Self {
self.trailing = Some(PendingChild::Deferred(Box::new(widget)));
self
}
/// Set the trailing-edge content by pre-registered ID.
pub fn trailing_id(mut self, id: WidgetId) -> Self {
self.trailing = Some(PendingChild::Id(id));
self
}
/// Override the close-button action. When set, the close button calls
/// this closure instead of `host.close()`. Required on Wayland where
/// the host's `close()` is a no-op (winit 0.30 has no
/// `Window::request_close`); the application typically wires this to
/// call `EventContext::close_window` directly, or to send an
/// `Intent` whose root-level `Action` handler calls it.
pub fn close_action(mut self, action: impl Fn(&mut EventContext) + 'static) -> Self {
self.close_action = Some(Rc::new(action));
self
}
}
impl Widget for TitleBar {
fn build(&mut self, ctx: &mut teksilo_core::build_context::BuildContext) -> Vec<WidgetId> {
// Register repaint-on-change for any signal-bearing ColorProp.
// Static + role-only variants need no registration — `set_theme`
// already mark-all-dirties the tree.
let self_id = ctx.self_id();
let registry = ctx.binding_registry();
self.background.register_if_bound(
self_id,
registry,
teksilo_core::binding::BindingLevel::RepaintOnly,
);
self.border_color.register_if_bound(
self_id,
registry,
teksilo_core::binding::BindingLevel::RepaintOnly,
);
let leading_inset = self.host.reserved_leading_inset();
let trailing_inset = self.host.reserved_trailing_inset();
let renders_controls = self.host.renders_custom_controls();
let height = self.height;
// The drag region is a spacer (claims all leftover horizontal space
// in the HStack) that forwards drag / double-tap / right-click to
// the host. Its child — if any — fills the spacer's full bounds.
let drag_region = match self.center.take() {
Some(PendingChild::Deferred(child)) => DragRegion::with_child(self.host.clone(), child),
Some(PendingChild::Id(id)) => DragRegion::with_child_id(self.host.clone(), id),
None => DragRegion::new(self.host.clone()),
}
// Only consulted when the platform has no OS window menu and the drag
// region therefore builds its own (X11); see `title_bar/window_menu.rs`.
.close_action(self.close_action.clone());
let drag_region_id = ctx.add(drag_region);
self.drag_region_id.set(Some(drag_region_id));
// Derive the restore signal from the hosting window's
// `WindowState::placement`. When no state is attached (standalone
// / tests) fall back to a static `false`.
//
// `is_maximized() || is_fullscreen()`, not `is_maximized()` alone: a
// fullscreen window is restorable and must not be offered "maximize",
// which is meaningless for a window with no frame. See
// `WindowControls::new`'s `show_restore` doc.
let show_restore_signal = ctx
.window()
.map(|w| w.placement().map(|p| p.is_maximized() || p.is_fullscreen()))
.unwrap_or_else(|| Signal::new(false));
// The cluster is always *built* when the platform renders custom
// controls; `controls_visible` gates its **activity**, via the
// framework's own dormancy (`visible_when`), not by rebuilding.
//
// This is deliberate and load-bearing: `build` consumes its slots with
// `take()`, so it can only ever run once — a second pass would find
// leading/center/trailing all `None` and silently produce a bar with
// nothing in it but window controls. A `Rebuild`-level binding here did
// exactly that. `visible_when` binds at `Relayout` instead: a dormant
// node is skipped by layout, hit-test, focus and paint, so the cluster
// takes no space and receives no input while hidden, and comes back
// without the bar ever being rebuilt.
let controls_id: Option<WidgetId> = if renders_controls {
let controls = WindowControls::new(
self.host.clone(),
show_restore_signal,
self.close_action.clone(),
)
.layout_sink(self.controls_layout.clone());
let id = ctx.add(controls);
ctx.visible_when(id, self.controls_visible.clone());
Some(id)
} else {
None
};
// The leading and trailing slots arrive as `Box<dyn Widget>`, which
// does not itself implement `Widget`, so we register them via
// `BuildContext::add_boxed` first and then attach them by id. The
// `add_child` and `child` calls on `HStack` push into the same
// ordered pending list, so interleaving is safe.
let mut row = HStack::new().spacing(0.0);
if leading_inset.width > 0.0 {
row = row.child(FixedSize::new().width(leading_inset.width).height(height));
}
if let Some(leading) = self.leading.take() {
let id = match leading {
PendingChild::Id(id) => id,
PendingChild::Deferred(w) => ctx.add_boxed(w),
};
row = row.add_child(id);
}
row = row.add_child(drag_region_id);
if let Some(trailing) = self.trailing.take() {
let id = match trailing {
PendingChild::Id(id) => id,
PendingChild::Deferred(w) => ctx.add_boxed(w),
};
row = row.add_child(id);
}
if trailing_inset.width > 0.0 {
row = row.child(FixedSize::new().width(trailing_inset.width).height(height));
}
if let Some(id) = controls_id {
row = row.add_child(id);
}
let root = ctx.add(row);
self.root_child_id = Some(root);
vec![root]
}
fn layout_response(
&self,
proposal: SizeProposal,
_ctx: &LayoutContext,
) -> teksilo_core::widget::LayoutResponse {
// Always claim the full width offered by the parent and the
// configured fixed height. Ignoring the child HStack's natural
// width is intentional: when the title bar is laid out by a
// shrink-to-fit container the inner HStack would otherwise
// collapse to the sum of its non-spacer children, leaving the
// drag region with zero pixels.
Size::new(proposal.width.unwrap_or(0.0), self.height).into()
}
fn place_children(
&self,
bounds: Rect,
_proposal: SizeProposal,
children: &mut [WidgetPlacement],
_ctx: &LayoutContext,
) {
for child in children.iter_mut() {
child.origin = bounds.origin();
child.size = bounds.size();
}
}
fn paint(&self, bounds: Rect, canvas: &mut Canvas, ctx: &PaintContext) {
let bg = self.background.resolve(ctx.theme, ctx.effective_enabled);
if bg.a() > 0.0 {
canvas.fill_rounded_rect(bounds, CornerRadius::ZERO, bg);
}
if self.border_width > 0.0 {
let border = self.border_color.resolve(ctx.theme, ctx.effective_enabled);
if border.a() > 0.0 {
canvas.draw_border_bottom(bounds, border, self.border_width);
}
}
}
fn wants_after_paint(&self) -> bool {
// We aggregate descendant rects (drag region + min/max/close
// buttons) into a single `HitRegions` payload for the host
// every frame. The Windows backend reads it from
// `WM_NCHITTEST`; Wayland and macOS backends ignore it.
true
}
fn after_paint(&self, view: &WidgetTreeView<'_>, _ctx: &PaintContext) {
// Build one complete `HitRegions` snapshot per frame. The
// widget tree publishes logical-pixel rects (its native
// coordinate system); platform backends that need physical
// pixels (Windows) convert internally.
let mut regions = HitRegions::new();
if let Some(drag_id) = self.drag_region_id.get() {
let drag_bounds = view.bounds(drag_id);
// A zero-size drag bounds (host doesn't render controls,
// tree not laid out yet, etc.) would still hit-test true
// for any point at the origin — skip it.
if drag_bounds.width > 0.0 && drag_bounds.height > 0.0 {
regions.drag.push(drag_bounds);
// Punch a hole for every `DeadZone` the app put inside the
// `center` slot. On Windows the drag rect becomes `HTCAPTION`,
// and the OS then owns those pixels outright — a button living
// there would never see a click, a hover or a cursor change; it
// would only drag the window. The dead-zone flag already means
// "not draggable chrome" to widget-land's drag arming, so it is
// the same declaration the OS needs. Wrap an interactive
// title-bar control in a `DeadZone` and it works on both layers.
collect_dead_zones(view, drag_id, drag_bounds, &mut regions.no_drag);
}
}
// Overlays float above every widget, chrome included — so wherever
// one covers the title bar, the OS must hand the pixels back to the
// client area or the overlay is unclickable there. `DeadZone` can't
// express this: the dead-zone walk above is scoped to the drag
// region's own subtree, and an overlay is anchored anywhere (the
// hamburger `MenuBar`'s revealed bar hangs off the leading slot; a
// tall modal hangs off nothing in here at all). The shipped bug:
// on Windows every revealed menu title over the caption returned
// `HTCAPTION` and dragged the window instead of opening its menu.
// Clip to the title bar's own strip — every rect this snapshot
// publishes lies inside it, so anything outside is already client
// area and would only bloat the per-message scan in the wndproc.
if let Some(strip_id) = self.root_child_id {
let strip = view.bounds(strip_id);
for &overlay in view.overlay_rects() {
if let Some(hole) = intersect(overlay, strip) {
regions.no_drag.push(hole);
}
}
}
// A hidden cluster publishes no control regions. The sink is populated
// at build time and survives the cluster going dormant, so without this
// guard Windows would keep returning `HTMINBUTTON`/`HTMAXBUTTON`/
// `HTCLOSE` for a strip of the caption that no longer has buttons in it
// — invisible controls, still clickable.
if !self.controls_visible.get() {
self.host.update_hit_regions(®ions);
return;
}
if let Some(layout) = self.controls_layout.take() {
regions.minimize = Some(view.bounds(layout.minimize_id));
regions.minimize_id = Some(layout.minimize_id);
// The maximize id is the Switcher's, not either glyph
// button's. The Switcher's bounds are always valid (the
// parent HStack lays it out regardless of which child is
// visible); a synthetic tap at the Switcher center routes
// through hit-testing to whichever child is currently
// visible — handles the floating ↔ maximized swap without
// the dormant-child-zero-bounds trap.
regions.maximize = Some(view.bounds(layout.maximize_id));
regions.maximize_id = Some(layout.maximize_id);
regions.close = Some(view.bounds(layout.close_id));
regions.close_id = Some(layout.close_id);
// Restore the layout cell so we don't have to rebuild it
// every frame.
self.controls_layout.set(Some(layout));
}
self.host.update_hit_regions(®ions);
}
fn accessibility(&self, builder: &mut AccessNodeBuilder) {
builder.set_role(teksilo_core::accesskit::Role::Banner);
builder.set_name(teksilo_i18n::tr_widget!(a11y_title_bar_name()).resolve_now());
}
fn children(&self) -> Vec<WidgetId> {
self.root_child_id.into_iter().collect()
}
}
/// Depth-first walk of `root`'s descendants collecting the bounds of every
/// gesture dead zone, clipped to `clip` (the drag rect). A dead zone is not
/// descended into — its whole subtree is already inside its bounds.
///
/// Two nodes are deliberately skipped: dormant ones (a `Switcher`'s hidden page
/// keeps stale bounds), and anything that does not overlap the drag rect — an
/// *open* popover is an arena descendant of its trigger but hangs below the
/// title bar, and its rect must not be mistaken for a hole in the caption.
fn collect_dead_zones(view: &WidgetTreeView<'_>, root: WidgetId, clip: Rect, out: &mut Vec<Rect>) {
for &child in view.children(root) {
if !view.is_active(child) {
continue;
}
let Some(hit) = intersect(view.bounds(child), clip) else {
continue;
};
if view.is_gesture_dead_zone(child) {
out.push(hit);
continue;
}
collect_dead_zones(view, child, clip, out);
}
}
/// Overlap of two rects, or `None` when they do not overlap — `Rect` has
/// `contains` but no intersection helper. Guards against publishing a
/// degenerate (zero-area) exclusion rect.
fn intersect(a: Rect, b: Rect) -> Option<Rect> {
let x0 = a.x.max(b.x);
let y0 = a.y.max(b.y);
let x1 = a.right().min(b.right());
let y1 = a.bottom().min(b.bottom());
(x1 > x0 && y1 > y0).then(|| Rect::new(x0, y0, x1 - x0, y1 - y0))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::primitives::{DeadZone, Expand};
use std::cell::{Cell, RefCell};
use teksilo_canvas::Point;
use teksilo_core::event::PointerButton;
use teksilo_core::widget_tree::WidgetTree;
use teksilo_core::{HitRegions, PlatformError, PlatformTitleBarHost, ResizeEdge};
/// A test host that records calls. Pretends the platform supports
/// custom controls (`renders_custom_controls = true`) and reports
/// zero macOS traffic-light insets.
struct TestHost {
minimized: Cell<u32>,
maximize_toggled: Cell<u32>,
closed: Cell<u32>,
drags_started: Cell<u32>,
is_max: Signal<bool>,
/// Last snapshot handed to `update_hit_regions` — what a real
/// platform backend would hit-test against.
last_regions: RefCell<HitRegions>,
}
impl Default for TestHost {
fn default() -> Self {
Self {
minimized: Cell::new(0),
maximize_toggled: Cell::new(0),
closed: Cell::new(0),
drags_started: Cell::new(0),
is_max: Signal::new(false),
last_regions: RefCell::new(HitRegions::default()),
}
}
}
impl PlatformTitleBarHost for TestHost {
fn reserved_leading_inset(&self) -> Size {
Size::ZERO
}
fn reserved_trailing_inset(&self) -> Size {
Size::ZERO
}
fn renders_custom_controls(&self) -> bool {
true
}
fn needs_custom_resize_handles(&self) -> bool {
true
}
fn begin_drag(&self) -> Result<(), PlatformError> {
self.drags_started.set(self.drags_started.get() + 1);
Ok(())
}
fn begin_resize(&self, _edge: ResizeEdge) -> Result<(), PlatformError> {
Ok(())
}
fn show_window_menu(&self, _at: Point) -> Result<(), PlatformError> {
Ok(())
}
fn update_hit_regions(&self, regions: &HitRegions) {
*self.last_regions.borrow_mut() = regions.clone();
}
}
/// Build a tree where the title bar is wrapped in the same VStack +
/// Expand body shape the demo uses. Returns the laid-out tree plus the
/// title-bar widget id.
fn build_realistic_tree(
host: Rc<TestHost>,
bar_setup: impl FnOnce(TitleBar) -> TitleBar,
) -> (WidgetTree, WidgetId) {
use crate::primitives::{Expand, VStack};
let bar_widget =
bar_setup(TitleBar::new(host as Rc<dyn PlatformTitleBarHost>).height(40.0));
// A theme + text backend so `render()` (and with it the `after_paint`
// pass that publishes `HitRegions`) can run: the control buttons carry
// glyphs, which need a typesetter.
let mut tree = WidgetTree::new()
.with_theme(teksilo_core::presets::intui::light())
.with_text_backend(Rc::new(std::cell::RefCell::new(
teksilo_canvas::MockTextBackend::new(),
)));
let bar_id = tree.add(bar_widget);
let body_id = tree.add(Expand::new());
let _root = tree.add(
VStack::new()
.spacing(0.0)
.add_child(bar_id)
.add_child(body_id),
);
tree.layout(SizeProposal::exact(900.0, 600.0));
(tree, bar_id)
}
/// Walk the title bar tree to find the trio of control button ids in
/// order: minimize, maximize, close. Layout-shape-aware — if the build
/// changes shape this test will tell us by panicking with a helpful
/// debug print of the children at each level.
///
/// The maximize slot is a `Switcher` whose two pages (`□` normal and
/// `❐` zoomed) are pre-mounted ControlButtons handed in via
/// `child_id`. With Switcher's lazy-mount semantics, `PreMounted`
/// entries become `Mounted` eagerly on first build, so the Switcher
/// reports both pages as direct children — this helper picks the
/// first (normal-state) since `TestHost::default()` reports
/// `is_maximized = false`.
fn locate_control_buttons(tree: &WidgetTree, bar: WidgetId) -> [WidgetId; 3] {
// bar -> [HStack root]
let bar_kids = tree.children(bar);
assert_eq!(
bar_kids.len(),
1,
"TitleBar should have a single root: {bar_kids:?}"
);
let row = bar_kids[0];
// row -> [DragRegion (spacer), WindowControls]
let row_kids = tree.children(row);
assert_eq!(
row_kids.len(),
2,
"row should have drag_region + controls, got {row_kids:?}"
);
let controls = row_kids[1];
// controls -> [inner HStack]
let controls_kids = tree.children(controls);
assert_eq!(controls_kids.len(), 1, "controls should wrap one HStack");
let inner_row = controls_kids[0];
// inner_row -> [minimize, max_switcher, close]
let inner_kids = tree.children(inner_row);
assert_eq!(
inner_kids.len(),
3,
"inner controls row should contain 3 items, got {inner_kids:?}"
);
// Switcher's direct children are its mounted pages — both
// pre-mounted ControlButtons (□ normal + ❐ zoomed) in
// declaration order.
let max_buttons = tree.children(inner_kids[1]);
assert_eq!(
max_buttons.len(),
2,
"maximize Switcher should expose 2 ControlButtons (□ + ❐), got {max_buttons:?}"
);
[inner_kids[0], max_buttons[0], inner_kids[2]]
}
/// Whether the control cluster is currently *live* — built and active.
///
/// Deliberately not a child count: the cluster is always built, and
/// `controls_visible` parks it dormant rather than removing it. Counting
/// children would report it present in both states.
fn controls_are_live(tree: &WidgetTree, bar: WidgetId) -> bool {
let row = tree.children(bar)[0];
tree.children(row)
.last()
.is_some_and(|&id| tree.is_active(id) && tree.bounds(id).width > 0.0)
}
/// Build a bar over a real `WindowState` at `placement`, so `ctx.window()`
/// resolves and the restore/maximize derivation is exercised for real
/// rather than falling back to its no-window `false`.
fn tree_at_placement(placement: teksilo_core::WindowPlacement) -> (WidgetTree, WidgetId) {
use crate::primitives::VStack;
use teksilo_core::window::WindowState;
use teksilo_core::{TeksiloWindowId, WindowStateInit};
let host = Rc::new(TestHost::default());
let mut tree = WidgetTree::new()
.with_theme(teksilo_core::presets::intui::light())
.with_text_backend(Rc::new(std::cell::RefCell::new(
teksilo_canvas::MockTextBackend::new(),
)));
tree.set_window_state(WindowState::new(WindowStateInit {
id: TeksiloWindowId::new(1),
string_id: Some("w1".to_string()),
placement,
title: "Test".to_string(),
size: (900, 600),
position: (0, 0),
focused: true,
resizable: true,
always_on_top: false,
}));
let bar_id = tree.add(TitleBar::new(host as Rc<dyn PlatformTitleBarHost>).height(40.0));
let body_id = tree.add(Expand::new());
let _root = tree.add(
VStack::new()
.spacing(0.0)
.add_child(bar_id)
.add_child(body_id),
);
tree.layout(SizeProposal::exact(900.0, 600.0));
(tree, bar_id)
}
/// The maximize slot's *visible* page: its index (0 = Maximize,
/// 1 = Restore) and its `WidgetId`. Read off which Switcher child is
/// active rather than off the glyph, since both pages deliberately draw
/// the same `□`.
///
/// The id matters as much as the index: `locate_control_buttons` always
/// returns page 0, so clicking *that* in a state where page 1 is showing
/// hits an inactive widget and silently does nothing.
fn visible_maximize_page(tree: &WidgetTree, bar: WidgetId) -> (usize, WidgetId) {
let row = tree.children(bar)[0];
let controls = tree.children(row)[1];
let inner = tree.children(controls)[0];
let switcher = tree.children(inner)[1];
let pages = tree.children(switcher);
pages
.iter()
.enumerate()
.find(|&(_, &p)| tree.is_active(p))
.map(|(i, &p)| (i, p))
.expect("one maximize page must be active")
}
/// **Rebuilding a `TitleBar` must not eat its slots.**
///
/// `build` used to `take()` leading/center/trailing, so it worked exactly
/// once. Nothing bound the bar at `Rebuild` level, so nothing ever rebuilt
/// it and the bug was unreachable — until `controls_visible` added the
/// first such binding, at which point the very first fullscreen toggle
/// emptied the bar of its menu, title and tools while leaving the window
/// controls (which *are* rebuilt each pass) in place.
///
/// Driven through the real `controls_visible` binding rather than a
/// synthetic rebuild: that is the path that broke, and a test that forced
/// a rebuild some other way could pass while the shipping one still ate
/// the slots.
#[test]
fn rebuilding_keeps_the_leading_and_trailing_slots() {
use crate::TextWidget;
use crate::primitives::VStack;
use teksilo_i18n::lit;
let host = Rc::new(TestHost::default());
let visible = Signal::new(true);
let mut tree = WidgetTree::new()
.with_theme(teksilo_core::presets::intui::light())
.with_text_backend(Rc::new(std::cell::RefCell::new(
teksilo_canvas::MockTextBackend::new(),
)));
let bar = tree.add(
TitleBar::new(host as Rc<dyn PlatformTitleBarHost>)
.height(40.0)
.leading(TextWidget::new(lit!("MENU")))
.center(TextWidget::new(lit!("TITLE")))
.trailing(TextWidget::new(lit!("TOOLS")))
.controls_visible(visible.clone()),
);
let body = tree.add(Expand::new());
let _root = tree.add(VStack::new().spacing(0.0).add_child(bar).add_child(body));
tree.layout(SizeProposal::exact(900.0, 600.0));
// row = [leading, drag_region, trailing, controls]. Asserted as a shape
// plus the drag region's width, because that is exactly what the real
// failure looked like: the row collapsed to the three 46 px control
// cells (138 px total), with the spacer and both slots gone, so the
// buttons ended up flush LEFT against an otherwise empty bar.
let shape = |t: &WidgetTree| {
let row = t.children(bar)[0];
let kids = t.children(row);
let drag_w = kids.get(1).map(|&id| t.bounds(id).width).unwrap_or(0.0);
(kids.len(), drag_w > 0.0, t.bounds(row).width)
};
let (n, drag_fills, row_w) = shape(&tree);
assert_eq!(n, 4, "leading + drag + trailing + controls");
assert!(
drag_fills,
"the drag region is a spacer and must have width"
);
assert!((row_w - 900.0).abs() < 1.0, "row spans the bar: {row_w}");
// Toggle the gate, twice, in both directions.
visible.set(false);
tree.layout(SizeProposal::exact(900.0, 600.0));
assert!(
!controls_are_live(&tree, bar),
"the cluster parks when the gate goes false"
);
let (n, drag_fills, row_w) = shape(&tree);
assert_eq!(n, 4, "the cluster parks, it is not removed");
assert!(drag_fills && (row_w - 900.0).abs() < 1.0, "slots intact");
visible.set(true);
tree.layout(SizeProposal::exact(900.0, 600.0));
assert!(controls_are_live(&tree, bar), "and comes back");
let (n, drag_fills, row_w) = shape(&tree);
assert_eq!(
n, 4,
"the leading/center/trailing slots must survive a gate flip — \
`build` consumes them, so anything that rebuilds this bar empties it"
);
assert!(
drag_fills && (row_w - 900.0).abs() < 1.0,
"slots still intact"
);
}
#[test]
fn controls_visible_false_parks_the_cluster() {
let host = Rc::new(TestHost::default());
let (tree, bar) = build_realistic_tree(host, |b| b.controls_visible(false));
assert!(
!controls_are_live(&tree, bar),
"controls_visible(false) must leave the cluster dormant and zero-width"
);
}
#[test]
fn controls_visible_defaults_to_showing_them() {
let host = Rc::new(TestHost::default());
let (tree, bar) = build_realistic_tree(host, |b| b);
assert!(controls_are_live(&tree, bar), "default is shown");
}
/// A bound gate flips a MOUNTED bar in both directions. The two tests above
/// each build a fresh bar, so they would pass even if the gate were read
/// once and frozen — this is the path an app takes when it enters and
/// leaves fullscreen with the bar already on screen.
#[test]
fn controls_visible_flips_a_mounted_bar_both_ways() {
use crate::primitives::VStack;
let host = Rc::new(TestHost::default());
let visible = Signal::new(true);
let mut tree = WidgetTree::new()
.with_theme(teksilo_core::presets::intui::light())
.with_text_backend(Rc::new(std::cell::RefCell::new(
teksilo_canvas::MockTextBackend::new(),
)));
let bar = tree.add(
TitleBar::new(host as Rc<dyn PlatformTitleBarHost>)
.height(40.0)
.controls_visible(visible.clone()),
);
let body = tree.add(Expand::new());
let _root = tree.add(VStack::new().spacing(0.0).add_child(bar).add_child(body));
tree.layout(SizeProposal::exact(900.0, 600.0));
assert!(controls_are_live(&tree, bar), "starts shown");
visible.set(false);
tree.layout(SizeProposal::exact(900.0, 600.0));
assert!(
!controls_are_live(&tree, bar),
"hiding must park the cluster on a mounted bar"
);
visible.set(true);
tree.layout(SizeProposal::exact(900.0, 600.0));
assert!(
controls_are_live(&tree, bar),
"and a hidden cluster must still learn to come back"
);
}
/// Fullscreen offers **Restore**, not Maximize. `WindowPlacement::is_maximized`
/// reports `false` in `Fullscreen`, so reading it alone used to render the
/// Maximize affordance over a window that has no frame to maximize.
#[test]
fn fullscreen_shows_the_restore_page_not_maximize() {
use teksilo_core::WindowPlacement as P;
let (tree, bar) = tree_at_placement(P::Floating);
assert_eq!(
visible_maximize_page(&tree, bar).0,
0,
"floating offers Maximize"
);
let (tree, bar) = tree_at_placement(P::Maximized);
assert_eq!(
visible_maximize_page(&tree, bar).0,
1,
"maximized offers Restore"
);
let (tree, bar) = tree_at_placement(P::Fullscreen);
assert_eq!(
visible_maximize_page(&tree, bar).0,
1,
"fullscreen must offer Restore — maximize is meaningless there"
);
}
/// ...and activating it from fullscreen restores, rather than sending the
/// window to `Maximized` — a state no command asked for, and one that
/// silently drops fullscreen while an app-level mode keyed off it stays on.
#[test]
fn activating_restore_from_fullscreen_leaves_fullscreen() {
use teksilo_core::WindowPlacement as P;
let (mut tree, bar) = tree_at_placement(P::Fullscreen);
let (_, restore) = visible_maximize_page(&tree, bar);
let b = tree.bounds(restore);
let centre = Point::new(b.x + b.width / 2.0, b.y + b.height / 2.0);
tree.pointer_down_button(centre, PointerButton::Primary);
tree.pointer_up_button(centre, PointerButton::Primary);
let placement = tree
.window_state()
.expect("window state attached")
.placement()
.get();
assert_eq!(
placement,
P::Floating,
"restore from fullscreen must not land on Maximized"
);
}
#[test]
fn title_bar_claims_full_width_and_configured_height() {
let host = Rc::new(TestHost::default());
let (tree, bar) = build_realistic_tree(host, |b| b);
let b = tree.bounds(bar);
assert!((b.width - 900.0).abs() < 0.01, "width = {}", b.width);
assert!((b.height - 40.0).abs() < 0.01, "height = {}", b.height);
}
#[test]
fn drag_region_is_a_spacer_so_controls_sit_flush_right() {
// Regression: in the first M2 cut DragRegion was not a spacer and
// collapsed to zero width, leaving the buttons clustered next to
// the leading text instead of at the trailing edge.
let host = Rc::new(TestHost::default());
let (tree, bar) = build_realistic_tree(host, |b| b);
let [_minimize, _maximize, close] = locate_control_buttons(&tree, bar);
let close_b = tree.bounds(close);
// 46 px wide cell, three of them, flush right against the 900 px
// window edge → close button right edge ≈ 900, left edge ≈ 854.
assert!(
(close_b.right() - 900.0).abs() < 1.0,
"close right edge = {}, expected ~900",
close_b.right()
);
assert!(
(close_b.width - 46.0).abs() < 1.0,
"close cell width = {}, expected 46",
close_b.width
);
}
#[test]
fn close_action_override_is_invoked_instead_of_host_close() {
let host = Rc::new(TestHost::default());
let close_calls = Rc::new(Cell::new(0u32));
let close_calls_clone = close_calls.clone();
let host_clone = host.clone();
let (mut tree, bar) = build_realistic_tree(host_clone, move |b| {
b.close_action(move |_ctx| {
close_calls_clone.set(close_calls_clone.get() + 1);
})
});
let [_min, _max, close] = locate_control_buttons(&tree, bar);
tree.click(close);
assert!(
close_calls.get() >= 1,
"close_action should have been called, got {}",
close_calls.get()
);
assert_eq!(
host.closed.get(),
0,
"host.close() must NOT be called when close_action override is set"
);
}
/// Attach a fresh `WindowState` to the tree so the title bar's
/// maximize/minimize actions have a target. Returns the state so
/// the test can assert against `placement().get()` after an action.
fn attach_window_state(tree: &mut WidgetTree) -> teksilo_core::WindowState {
let state = teksilo_core::WindowState::new(teksilo_core::WindowStateInit {
id: teksilo_core::TeksiloWindowId::new(1),
string_id: None,
placement: teksilo_core::WindowPlacement::Floating,
title: "Test".to_string(),
size: (800, 600),
position: (0, 0),
focused: true,
resizable: true,
always_on_top: false,
});
tree.set_window_state(state.clone());
state
}
#[test]
fn minimize_button_sets_placement_to_minimized() {
let host = Rc::new(TestHost::default());
let (mut tree, bar) = build_realistic_tree(host.clone(), |b| b);
let state = attach_window_state(&mut tree);
let [minimize, _max, _close] = locate_control_buttons(&tree, bar);
tree.click(minimize);
assert_eq!(
state.placement().get(),
teksilo_core::WindowPlacement::Minimized,
"minimize button should flip WindowState::placement to Minimized"
);
}
#[test]
fn maximize_button_toggles_placement() {
let host = Rc::new(TestHost::default());
let (mut tree, bar) = build_realistic_tree(host.clone(), |b| b);
let state = attach_window_state(&mut tree);
let [_min, maximize, _close] = locate_control_buttons(&tree, bar);
tree.click(maximize);
assert_eq!(
state.placement().get(),
teksilo_core::WindowPlacement::Maximized
);
tree.click(maximize);
assert_eq!(
state.placement().get(),
teksilo_core::WindowPlacement::Floating
);
}
/// Each control button advertises `Action::Click` — on macOS that is
/// precisely what makes VoiceOver offer a press (`is_clickable` ==
/// `supports_action(Click)`). Invoking it must actually drive the
/// window, or a screen-reader user cannot minimize / maximize /
/// close the window at all.
#[test]
fn access_click_drives_window_controls() {
let host = Rc::new(TestHost::default());
let (mut tree, bar) = build_realistic_tree(host.clone(), |b| b);
let state = attach_window_state(&mut tree);
let [minimize, maximize, _close] = locate_control_buttons(&tree, bar);
let at_click = |tree: &mut WidgetTree, id: WidgetId| {
tree.dispatch_event(teksilo_core::event::WidgetEvent::AccessAction {
action: teksilo_core::accesskit::Action::Click,
target: Some(id),
target_node: teksilo_core::accessibility::root_node_id(),
data: None,
});
};
at_click(&mut tree, minimize);
assert_eq!(
state.placement().get(),
teksilo_core::WindowPlacement::Minimized,
"AT click on minimize must flip placement to Minimized"
);
state
.placement()
.set(teksilo_core::WindowPlacement::Floating);
at_click(&mut tree, maximize);
assert_eq!(
state.placement().get(),
teksilo_core::WindowPlacement::Maximized,
"AT click on maximize must flip placement to Maximized"
);
}
/// The close button's AT click must run the same action a pointer tap
/// does — including a `close_action` override.
#[test]
fn access_click_invokes_close_action() {
let host = Rc::new(TestHost::default());
let close_calls = Rc::new(Cell::new(0u32));
let close_calls_clone = close_calls.clone();
let (mut tree, bar) = build_realistic_tree(host.clone(), move |b| {
b.close_action(move |_ctx| {
close_calls_clone.set(close_calls_clone.get() + 1);
})
});
let [_min, _max, close] = locate_control_buttons(&tree, bar);
tree.dispatch_event(teksilo_core::event::WidgetEvent::AccessAction {
action: teksilo_core::accesskit::Action::Click,
target: Some(close),
target_node: teksilo_core::accessibility::root_node_id(),
data: None,
});
assert_eq!(
close_calls.get(),
1,
"AT click on close must invoke the close action"
);
}
/// Locate the `DragRegion` widget id by walking the title-bar subtree.
/// Path: bar → HStack root → [drag_region, controls].
fn locate_drag_region(tree: &WidgetTree, bar: WidgetId) -> WidgetId {
let bar_kids = tree.children(bar);
let row = bar_kids[0];
let row_kids = tree.children(row);
row_kids[0]
}
#[test]
fn dragging_inside_drag_region_calls_host_begin_drag() {
// Regression for: in M2 the gesture-arena auto-wiring in teksilo-core
// only built a TapRecognizer when on_tap was set. DragRegion uses
// on_drag (no on_tap) and so was getting no arena at all → drag
// never fired. The fix in event_dispatch_impl::ensure_gesture_arena
// installs DragRecognizer whenever on_drag is set.
let host = Rc::new(TestHost::default());
let (mut tree, bar) = build_realistic_tree(host.clone(), |b| b);
let drag = locate_drag_region(&tree, bar);
let drag_b = tree.bounds(drag);
let from = Point::new(drag_b.x + 50.0, drag_b.y + drag_b.height / 2.0);
let to = Point::new(drag_b.x + 200.0, drag_b.y + drag_b.height / 2.0);
tree.drag(from, to);
assert!(
host.drags_started.get() >= 1,
"host.begin_drag() should be called on drag-start, got {}",
host.drags_started.get()
);
}
#[test]
fn title_bar_exposes_banner_landmark() {
let host = Rc::new(TestHost::default());
let (tree, bar) = build_realistic_tree(host, |b| b);
let info = tree.accessibility_node(bar);
assert_eq!(info.role(), teksilo_core::accesskit::Role::Banner);
assert!(
info.name().is_some(),
"TitleBar Banner landmark should have a localised name"
);
}
#[test]
fn window_control_glyphs_retint_on_theme_switch() {
// Regression: `WindowControls` froze `text_primary` / `surface_hover`
// / `status_error_bg` into `Color` snapshots at build time and relied
// on `mark_all_dirty` to "follow the theme" — but a static `Color` is
// a `ColorProp::Static` that always re-resolves to the same value, so
// the min/max/close glyphs kept the build-time theme's color after a
// `set_theme`. The fix hands the buttons `TextRole::Primary` /
// `SurfaceRole::*`, which resolve against the live theme at paint
// time. This test renders the control glyphs under light then dark
// and asserts they actually change color.
use crate::primitives::{Expand, VStack};
use std::cell::RefCell;
use teksilo_canvas::MockTextBackend;
let host = Rc::new(TestHost::default());
let bar_widget = TitleBar::new(host as Rc<dyn PlatformTitleBarHost>).height(40.0);
let mut tree = WidgetTree::new()
.with_theme(teksilo_core::presets::intui::light())
.with_text_backend(Rc::new(RefCell::new(MockTextBackend::new())));
let bar_id = tree.add(bar_widget);
let body_id = tree.add(Expand::new());
tree.add(
VStack::new()
.spacing(0.0)
.add_child(bar_id)
.add_child(body_id),
);
tree.layout(SizeProposal::exact(900.0, 600.0));
let light_glyphs: Vec<[f32; 4]> = tree.render().glyphs.iter().map(|g| g.color).collect();
assert!(
!light_glyphs.is_empty(),
"control glyphs (—, □, ×) should have rendered"
);
// Every control glyph uses TextRole::Primary; under light it must
// resolve to the light theme's primary text color.
let light_primary = teksilo_core::presets::intui::light()
.colors
.text_primary
.to_array();
assert!(
light_glyphs.iter().all(|c| *c == light_primary),
"control glyphs should paint with the light theme's text_primary, got {light_glyphs:?}"
);
tree.set_theme(teksilo_core::presets::intui::dark());
tree.layout(SizeProposal::exact(900.0, 600.0));
let dark_glyphs: Vec<[f32; 4]> = tree.render().glyphs.iter().map(|g| g.color).collect();
let dark_primary = teksilo_core::presets::intui::dark()
.colors
.text_primary
.to_array();
assert!(
dark_glyphs.iter().all(|c| *c == dark_primary),
"control glyphs should retint to the dark theme's text_primary, got {dark_glyphs:?}"
);
assert_ne!(
light_glyphs, dark_glyphs,
"control glyph colors must change across a theme switch"
);
}
#[test]
fn window_controls_have_semantic_names_not_glyphs() {
let host = Rc::new(TestHost::default());
let (tree, bar) = build_realistic_tree(host, |b| b);
let [minimize, maximize, close] = locate_control_buttons(&tree, bar);
let min_info = tree.accessibility_node(minimize);
let max_info = tree.accessibility_node(maximize);
let close_info = tree.accessibility_node(close);
// Screen readers must get a semantic verb, not the raw glyph
// character (`—`, `□`, `×`) which Unicode-aware AT pronounces
// as "em dash" / "white square" / "multiplication sign".
for info in [&min_info, &max_info, &close_info] {
let name = info.name().expect("control button must have a name");
assert!(!name.is_empty(), "name empty");
assert_ne!(name, "\u{2014}", "minimize reads glyph literal");
assert_ne!(name, "\u{25A1}", "maximize reads glyph literal");
assert_ne!(name, "\u{00D7}", "close reads glyph literal");
assert_eq!(info.role(), teksilo_core::accesskit::Role::Button);
}
}
#[test]
fn drag_region_is_hidden_from_a11y() {
let host = Rc::new(TestHost::default());
let (tree, bar) = build_realistic_tree(host, |b| b);
let drag = locate_drag_region(&tree, bar);
let info = tree.accessibility_node(drag);
assert!(
info.is_hidden(),
"DragRegion is pointer-only; should be hidden from AT"
);
}
/// Render one frame so `after_paint` runs and the host receives a
/// `HitRegions` snapshot. `WidgetTree::render` drives the paint pass.
fn paint_once(tree: &mut WidgetTree) {
tree.layout(SizeProposal::exact(900.0, 600.0));
let _ = tree.render();
}
#[test]
fn dead_zone_in_center_is_published_as_a_no_drag_hole() {
// Regression (Windows): the whole `center` slot is wrapped in a
// DragRegion whose rect goes out as `HitRegions::drag`, which the
// Windows backend answers with HTCAPTION. An interactive control
// living there was therefore unclickable — the OS took the press and
// started a window move instead. Wrapping it in a `DeadZone` must now
// punch a hole in the caption so the OS hands the pixels back.
let host = Rc::new(TestHost::default());
let host_for_bar = host.clone();
let (mut tree, _bar) = build_realistic_tree(host_for_bar, |b| {
b.center(
HStack::new()
.child(DeadZone::new().child(FixedSize::new().width(60.0).height(30.0)))
.child(Expand::new()),
)
});
paint_once(&mut tree);
let regions = host.last_regions.borrow();
assert_eq!(
regions.drag.len(),
1,
"the drag region should still be published"
);
assert_eq!(
regions.no_drag.len(),
1,
"the DeadZone in `center` must be published as one no_drag hole, got {:?}",
regions.no_drag
);
let hole = regions.no_drag[0];
let drag = regions.drag[0];
assert!(
(hole.width - 60.0).abs() < 1.0,
"the hole should match the dead zone's width, got {}",
hole.width
);
// The hole must lie inside the caption it is carving out of, or the
// Windows backend would test it against a region that never matches.
assert!(
hole.x >= drag.x - 0.01 && hole.right() <= drag.right() + 0.01,
"hole {hole:?} must be clipped to the drag rect {drag:?}"
);
}
#[test]
fn passive_center_content_punches_no_hole() {
// The inverse guard: a plain centred title must NOT become a no_drag
// hole, or the user could no longer drag the window by its title —
// which is the drag region's entire purpose.
let host = Rc::new(TestHost::default());
let host_for_bar = host.clone();
let (mut tree, _bar) = build_realistic_tree(host_for_bar, |b| {
b.center(crate::TextWidget::new(teksilo_i18n::lit!("My App")))
});
paint_once(&mut tree);
let regions = host.last_regions.borrow();
assert_eq!(regions.drag.len(), 1, "drag region still published");
assert!(
regions.no_drag.is_empty(),
"a passive centred title must not punch a hole in the caption, got {:?}",
regions.no_drag
);
}
#[test]
fn overlay_over_the_caption_is_published_as_a_no_drag_hole() {
// Regression (Windows): the hamburger `MenuBar`'s revealed bar is an
// *overlay* anchored in the leading slot — outside the drag region —
// so no `DeadZone` walk could ever reach it, and every menu title
// painted over the caption returned `HTCAPTION`: clicking a menu
// dragged the window instead of opening it (except where an
// unrelated dead-zoned control happened to sit beneath). Any
// interactive overlay must carve its caption overlap out of the
// published regions.
use teksilo_core::overlay::{
DismissBehavior, OverlayLayer, OverlayPlacement, OverlayRequest,
};
let host = Rc::new(TestHost::default());
let (mut tree, bar) = build_realistic_tree(host.clone(), |b| b);
// 200×60 content shown at (100, 20): its top half overlaps the
// 40 dp title bar strip, its bottom half hangs below into the
// client area.
let content = tree.add(FixedSize::new().width(200.0).height(60.0));
tree.show_overlay(OverlayRequest {
content_id: content,
anchor: bar,
placement: OverlayPlacement::AtPointer(Point::new(100.0, 20.0)),
dismiss: DismissBehavior::Manual,
layer: OverlayLayer::InTree,
parent_overlay: None,
on_dismiss: None,
fade_duration: None,
});
paint_once(&mut tree);
let regions = host.last_regions.borrow();
assert_eq!(regions.drag.len(), 1, "the drag region is still published");
assert_eq!(
regions.no_drag.len(),
1,
"the overlay's caption overlap must be published as one no_drag \
hole, got {:?}",
regions.no_drag
);
let hole = regions.no_drag[0];
assert!(
(hole.x - 100.0).abs() < 0.01 && (hole.width - 200.0).abs() < 0.01,
"the hole should span the overlay's width at its position, got {hole:?}"
);
// Clipped to the strip: the overlay reaches y=80 but the title bar
// ends at y=40, and everything below is client area already.
assert!(
(hole.y - 20.0).abs() < 0.01 && (hole.bottom() - 40.0).abs() < 0.01,
"the hole must be clipped to the title bar strip, got {hole:?}"
);
}
#[test]
fn overlay_below_the_caption_punches_no_hole() {
// The inverse guard: a dropdown, popover or toast that floats
// entirely below the title bar must NOT punch a hole — its rect
// never overlaps the published regions, and a spurious hole would
// eat the caption's drag under it.
use teksilo_core::overlay::{
DismissBehavior, OverlayLayer, OverlayPlacement, OverlayRequest,
};
let host = Rc::new(TestHost::default());
let (mut tree, bar) = build_realistic_tree(host.clone(), |b| b);
let content = tree.add(FixedSize::new().width(200.0).height(60.0));
tree.show_overlay(OverlayRequest {
content_id: content,
anchor: bar,
placement: OverlayPlacement::AtPointer(Point::new(100.0, 300.0)),
dismiss: DismissBehavior::Manual,
layer: OverlayLayer::InTree,
parent_overlay: None,
on_dismiss: None,
fade_duration: None,
});
paint_once(&mut tree);
let regions = host.last_regions.borrow();
assert!(
regions.no_drag.is_empty(),
"an overlay fully below the caption must not punch a hole, got {:?}",
regions.no_drag
);
}
#[test]
fn dead_zone_in_center_does_not_arm_the_window_drag() {
// The widget-land half of the same bug, live on every platform: a
// press on a control inside the drag region armed the DragRegion's
// `on_drag` via `arm_drag_observers`, so a few px of pointer jitter
// during an ordinary click started a window move and ate the tap.
// The `DeadZone` boundary must stop that arming.
let host = Rc::new(TestHost::default());
let host_for_bar = host.clone();
let (mut tree, _bar) = build_realistic_tree(host_for_bar, |b| {
b.center(
HStack::new()
.child(DeadZone::new().child(FixedSize::new().width(60.0).height(30.0)))
.child(Expand::new()),
)
});
paint_once(&mut tree);
let hole = host.last_regions.borrow().no_drag[0];
let (cx, cy) = (hole.x + hole.width / 2.0, hole.y + hole.height / 2.0);
// A jittery press on the dead-zoned control.
tree.pointer_down_button(Point::new(cx, cy), PointerButton::Primary);
for i in 1..=10 {
tree.pointer_move(Point::new(cx + (i as f32) * 3.0, cy + 1.0));
}
tree.pointer_up_button(Point::new(cx + 30.0, cy + 1.0), PointerButton::Primary);
assert_eq!(
host.drags_started.get(),
0,
"a jittery click on a DeadZone inside the title bar must not drag the window"
);
}
#[test]
fn dragging_the_bare_drag_region_still_works_with_a_dead_zone_present() {
// Guard the fix's blast radius: punching a hole must not disable the
// drag surface around it.
let host = Rc::new(TestHost::default());
let host_for_bar = host.clone();
let (mut tree, bar) = build_realistic_tree(host_for_bar, |b| {
b.center(
HStack::new()
.child(DeadZone::new().child(FixedSize::new().width(60.0).height(30.0)))
.child(Expand::new()),
)
});
paint_once(&mut tree);
// Drag from well to the right of the dead zone — still bare caption.
let drag_b = tree.bounds(locate_drag_region(&tree, bar));
let from = Point::new(drag_b.right() - 40.0, drag_b.y + drag_b.height / 2.0);
let to = Point::new(drag_b.right() - 200.0, drag_b.y + drag_b.height / 2.0);
tree.drag(from, to);
assert!(
host.drags_started.get() >= 1,
"the drag region outside the hole must still move the window"
);
}
#[test]
fn double_clicking_drag_region_toggles_placement() {
// Regression for: same auto-wiring gap. on_double_tap was wired in
// HandlerSet but the dispatch never installed a DoubleTapRecognizer
// unless on_tap was also set, so the handler was unreachable.
let host = Rc::new(TestHost::default());
let (mut tree, bar) = build_realistic_tree(host.clone(), |b| b);
let state = attach_window_state(&mut tree);
let drag = locate_drag_region(&tree, bar);
tree.click(drag);
tree.click(drag);
assert_eq!(
state.placement().get(),
teksilo_core::WindowPlacement::Maximized,
"double-tap on drag region should flip WindowState::placement to Maximized"
);
}
}