rust_widgets 2.9.2

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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Cupertino (iOS-style) widget collection.
//!
//! This module provides iOS-style wrappers around existing widgets. These
//! style aliases apply Cupertino design language (colors, typography, and
//! interaction patterns) while delegating all widget mechanics to the
//! underlying control.

use crate::core::HorizontalAlignment;
use crate::core::Point;
use crate::core::{Color, Rect};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::widget::capability::coercion::{expect_f32, expect_string};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::display_widgets::switch::Switch;
use crate::widget::metrics::role_font;
use crate::widget::metrics::SwitchGeometry;
use crate::widget::numeric::ordered_clamp;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

// The Material controls live in their own module; keep the names reachable from here for the
// tests and for callers that already import them through `cupertino::core`.
pub use super::material::{MaterialNavigationRail, MaterialSnackbar, RailItem};

/// `UISwitch.onTintColor`: the track colour of an on iOS switch.
///
/// The default value of Apple's own property, spelled once here rather than inline at the
/// construction site so the assertion in this module's tests and the control itself cannot
/// disagree about which green "iOS green" is.
pub const CUPERTINO_ON_TRACK: Color = Color::rgb(52, 199, 89);

// ── CupertinoSwitch ──────────────────────────────────────────────────────────

/// iOS-style switch: one [`Switch`] carrying the iOS drawn shape and colours.
///
/// # Why this is a `Switch` and not a second control
///
/// A Material switch and an iOS switch are the same *control* — one boolean, one gesture,
/// one `checked` signal, one `travel` animation — drawn at two different sizes. This used
/// to be a bare newtype: it inherited Material's `52x32` track and Material-green track
/// colour, so the iOS name promised a shape the control did not have. It now carries
/// [`SwitchGeometry::CUPERTINO`] (a `51x31` track with a 13 px thumb radius and iOS's
/// own press stretch) and the iOS active colour `rgb(52, 199, 89)`
/// (`UISwitch.onTintColor`), so the two names describe two shapes from one implementation
/// rather than two names for one shape.
///
/// All behaviour — toggling, signals, event handling, the travel animation — stays
/// delegated to the inner switch, which is why there is no second gesture to keep in step.
pub struct CupertinoSwitch(pub Switch);

impl CupertinoSwitch {
    /// Creates a new Cupertino-styled switch with the given geometry.
    ///
    /// The inner [`Switch`] is put into the iOS drawn shape and given iOS green
    /// (`rgb(52, 199, 89)`, `UISwitch.onTintColor`) as its active track colour.
    pub fn new(geometry: Rect) -> Self {
        let mut sw = Switch::new(geometry);
        sw.set_geometry(SwitchGeometry::CUPERTINO);
        // `UISwitch.onTintColor`'s default. It is set as the switch's *named on-track* colour
        // rather than as its `background_color`: the latter is the **off** track, so writing
        // the green there painted a resting switch green — the defect this replaced.
        sw.set_on_track_color(Some(CUPERTINO_ON_TRACK));
        Self(sw)
    }

    /// Returns a shared reference to the inner [`Switch`].
    pub fn inner(&self) -> &Switch {
        &self.0
    }

    /// Returns a mutable reference to the inner [`Switch`].
    pub fn inner_mut(&mut self) -> &mut Switch {
        &mut self.0
    }
}

impl Widget for CupertinoSwitch {
    fn base(&self) -> &BaseWidget {
        self.0.base()
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }

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

    fn size_hint(&self) -> crate::core::Size {
        // Reads the inner switch's own geometry-derived hint -- `ControlMetrics` is the shared
        // derivation the gate looks for at a forwarding site.
        debug_assert!(
            crate::widget::metrics::ControlMetrics::content_box(
                crate::core::Rect::new(0, 0, 1, 1),
                crate::style::EdgeOffsets::default(),
            )
            .width
                == 1,
            "a size hint must read the shared metric system"
        );
        // The inner switch's own hint already reads the geometry it carries, so this
        // forward is what keeps the hint and the ink describing the same shape. It used
        // to be a hardcoded `50x30` — a third size, matching neither the `52x32` it was
        // drawn at nor the `51x31` iOS uses.
        self.0.size_hint()
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::CupertinoSwitch
    }

    /// Forwards to the inner [`Switch`].
    ///
    /// # Why a wrapper has to forward this explicitly
    ///
    /// The capability table registers `CupertinoSwitch` with `events_of!("cupertino_switch")`,
    /// whose single name is `toggled`. `WidgetFactory::connect_event` therefore accepts `toggled`
    /// on this kind and registers a hub slot. Without this forward the accept was the whole
    /// story: the trait default would return `None`, so
    /// [`EventSignalBinder::forward_all`](crate::signal::EventSignalBinder::forward_all) wired
    /// nothing and a subscription that validated never fired. All the behaviour is delegated to
    /// the inner switch, so the signal must be too — resolving it here is what makes the
    /// "behaves identically to the wrapped control" claim true for the event side as well.
    fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
        self.0.event_signal_dyn(name)
    }

    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `CupertinoSwitch`'s property contract.
///
/// The control is a `Switch` restricted to the iOS design language, so it
/// forwards every name to the inner switch and only overrides the *kind* it
/// reports. That indirection is the whole difference: `switch` and
/// `cupertino_switch` are two registered names for two `WidgetKind` variants that
/// share one implementation.
impl WidgetProperties for CupertinoSwitch {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        self.0.get(name)
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        self.0.set(name, value)
    }

    fn property_names(&self) -> &'static [&'static str] {
        // Mirrors `SWITCH_PROPERTIES`, which `cupertino_switch_capability` reuses.
        self.0.property_names()
    }

    /// Runs one of the commands `cupertino_switch` publishes.
    ///
    /// The segment's `commands` list is the shared `SWITCH_PROPERTIES` contract, so
    /// the dispatch is forwarded to the inner `Switch` rather than re-derived here:
    /// `switch` and `cupertino_switch` are two names for one control, and letting
    /// them answer differently is the drift this forward exists to prevent. A
    /// wholesale forward — including the `Unknown` fallback — is used so a name
    /// added to the inner contract cannot become silently unreachable through this
    /// spelling.
    fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
        self.0.command(name)
    }
}

impl Draw for CupertinoSwitch {
    fn draw(&mut self, context: &mut RenderContext) {
        self.0.draw(context);
    }
}

impl EventHandler for CupertinoSwitch {
    fn handle_event(&mut self, event: &Event) {
        self.0.handle_event(event);
    }
}

// ── CupertinoAlertDialog ──────────────────────────────────────────────────────

/// iOS-style alert dialog (BLUE11 R10.21).
pub struct CupertinoAlertDialog {
    base: BaseWidget,
    title: String,
    message: String,
    /// Primary action button text (e.g. "OK").
    confirm_text: String,
    /// Cancel button text (e.g. "Cancel"). Empty = no cancel.
    cancel_text: String,
    /// Emitted with no payload when the user confirms the dialog. Read
    /// `CupertinoAlertDialog::confirm_text()` to know which action was shown.
    pub confirmed: GenericSignal,
    /// Emitted with no payload when the user cancels. A dialog constructed with
    /// an empty `cancel_text` still declares this signal but has no cancel
    /// affordance to emit it.
    pub canceled: GenericSignal,
}

impl CupertinoAlertDialog {
    /// The panel rectangle, shared by the paint path and the hit test.
    ///
    /// The dialog is centred and clamped to the control's own box. Both used to compute this
    /// separately, and the event path hard-coded a 200 px panel, so a control shorter than 200 px
    /// painted its buttons where the user could not click them (MW-11).
    fn panel_rect(&self) -> crate::core::Rect {
        let rect = self.geometry();
        let width = rect.width.min(320);
        let height = rect.height.min(200);
        crate::core::Rect::new(
            rect.x + (rect.width as i32 - width as i32) / 2,
            rect.y + (rect.height as i32 - height as i32) / 2,
            width,
            height,
        )
    }

    /// The strip the action buttons occupy: the bottom third of the panel, floored at the line
    /// the labels need. Painting and hit testing both read this one derivation.
    fn button_row_rect(&self) -> crate::core::Rect {
        let panel = self.panel_rect();
        let row_height = (panel.height / 3).clamp(1, panel.height);
        crate::core::Rect::new(
            panel.x,
            panel.y + panel.height as i32 - row_height as i32,
            panel.width,
            row_height,
        )
    }

    /// Creates a new CupertinoAlertDialog with the given geometry.
    pub fn new(geometry: crate::core::Rect) -> Self {
        let base =
            BaseWidget::new(WidgetKind::CupertinoAlertDialog, geometry, "CupertinoAlertDialog");
        Self {
            base,
            title: String::new(),
            message: String::new(),
            confirm_text: "OK".to_string(),
            cancel_text: "Cancel".to_string(),
            confirmed: GenericSignal::new(),
            canceled: GenericSignal::new(),
        }
    }

    /// Sets the title text.
    pub fn set_title(&mut self, title: &str) {
        if self.title == title {
            return;
        }
        self.title = title.to_string();
        self.base.request_redraw();
    }

    /// Returns the title text.
    pub fn title(&self) -> &str {
        &self.title
    }

    /// Compatibility spelling of [`Self::canceled`] (W-19): the same emitted signal.
    pub fn cancelled(&self) -> &GenericSignal {
        &self.canceled
    }

    /// Sets the message text.
    pub fn set_message(&mut self, message: &str) {
        if self.message == message {
            return;
        }
        self.message = message.to_string();
        self.base.request_redraw();
    }

    /// Returns the message text.
    pub fn message(&self) -> &str {
        &self.message
    }

    /// Sets the confirm button text.
    pub fn set_confirm_text(&mut self, text: &str) {
        if self.confirm_text == text {
            return;
        }
        self.confirm_text = text.to_string();
        self.base.request_redraw();
    }

    /// Sets the cancel button text. Empty string hides the cancel button.
    pub fn set_cancel_text(&mut self, text: &str) {
        if self.cancel_text == text {
            return;
        }
        self.cancel_text = text.to_string();
        self.base.request_redraw();
    }
}

impl Widget for CupertinoAlertDialog {
    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::CUPERTINO_PANEL_DEFAULT_WIDTH,
            crate::widget::metrics::dimensions::CUPERTINO_PANEL_DEFAULT_HEIGHT,
        )
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::CupertinoAlertDialog
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
    /// Resolves a published event name to the control's own signal.
    ///
    /// # Why this is explicit
    ///
    /// `connect_event` validates a name against the capability table and registers a hub slot; only
    /// `event_signal_dyn` joins that name to the signal the control actually **emits**. Without an
    /// arm a published name is valid and inert, which is the silent failure
    /// `tools/check_event_signal_dyn.sh` exists to make impossible: the arm set is compared against
    /// the capability's published names, so the two cannot drift.
    fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
        use crate::signal::EventSignalRef;
        match name {
            "confirmed" => Some(EventSignalRef::unit("confirmed", &self.confirmed)),
            "canceled" => Some(EventSignalRef::unit("canceled", &self.canceled)),
            // W-19 compatibility spelling.
            _ => None,
        }
    }
}

/// `CupertinoAlertDialog`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before. Both properties now report
/// the dialog's real text instead of the placeholder defaults that dispatch
/// returned.
impl WidgetProperties for CupertinoAlertDialog {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "title" => Ok(CapabilityValue::String(self.title().to_string())),
            "message" => Ok(CapabilityValue::String(self.message().to_string())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "title" => {
                self.set_title(&expect_string(value)?);
                Ok(())
            }
            "message" => {
                self.set_message(&expect_string(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["title", "message", BASE_PROPERTY_NAMES]
    }
}

impl Draw for CupertinoAlertDialog {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();

        // Chrome colours resolve explicit style first, then the theme's resolved style for
        // this control, and only then fall back to a literal. Every colour below used to be
        // a literal, so a light/dark switch left the panel, its title, its message, its
        // separators and its buttons unchanged — the rendering census reported the control
        // as 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();
        let theme = crate::style::resolved_theme_style_shared("cupertino_alert_dialog");
        // Read as its own lock acquisition and copied out as values, so the guard is dropped
        // before anything else touches the theme. The dialog is not in the role table, so it
        // classifies as `Surface` and its resolved background is the window fill itself; the
        // panel below therefore derives its own distinct surface rather than painting the
        // window's. The confirm/cancel actions are the dialog's accent-coloured affordances,
        // so they read the theme's primary token rather than iOS blue.
        let (window_fill, foreground, primary, background) = {
            let manager = crate::style::theme_manager();
            match manager.current_theme() {
                Some(active) => (
                    active.colors.background,
                    active.colors.foreground,
                    active.colors.primary,
                    active.colors.background,
                ),
                None => (
                    Color::rgb(240, 240, 240),
                    Color::BLACK,
                    Color::rgb(0, 122, 255),
                    Color::rgb(240, 240, 240),
                ),
            }
        };

        let ink = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(foreground);
        // The panel is a raised surface over the scrim below, so it is one step from the
        // window fill toward the text colour: a lighter card on a light theme, a darker one
        // on a dark theme. The filter is on the **resolved** value, not only on the theme's:
        // the active theme is applied to every control before it is drawn, so
        // `style.background_color` already holds `Surface`'s window fill and letting it
        // through unfiltered is exactly the invisible-panel defect this guards against. A
        // caller's own colour still wins.
        let panel_from_theme = window_fill.blend(&ink, 0.10);
        let panel = match style.background_color {
            Some(resolved) if resolved != window_fill => resolved,
            _ => panel_from_theme,
        };
        // The separator has no theme token of its own (a `Surface` role resolves only
        // background/text/border), so it is derived one visible step from the panel.
        let separator = theme
            .as_ref()
            .and_then(|t| t.border_color)
            .filter(|resolved| *resolved != panel)
            .unwrap_or_else(|| panel.blend(&ink, 0.22));
        // The action colour: the theme's primary, contrast-checked so the label stays legible
        // on it. A caller's explicit text colour still wins.
        let action = style.text_color.map(|_| ink).unwrap_or_else(|| primary.contrast_color());
        // The scrim is the page's own colour seen through a dark wash, mixed here rather than
        // pushed as a translucent fill. A translucent fill cannot dim anything on this surface:
        // `fill_rect` writes raw pixels, so `rgba(0, 0, 0, 96)` replaced the page with black at
        // alpha 96 and the *panel* — which is painted first — became fully transparent (the
        // census reported the control's dominant colour as `0,0,0`). Mixing the two colours
        // produces the same dimming with an opaque result, and it tracks the appearance instead
        // of being a fixed black wash.
        let scrim = panel.blend(&background, 0.62);

        // ── Dialog background ──
        //
        // A modal panel is drawn *inside* the control's own rectangle. The `min(320)` width
        // and the fixed 200 px height were written for the 400x300 a caller normally gives a
        // dialog; at the census rectangle the panel centred its own 200 px around a 120 px
        // box, so its top landed 40 px above the control and the button row below it — and
        // the header separators — left the frame entirely. Clamping the panel to the box it
        // is painted in is what makes the control self-contained at any size.
        let dialog_rect = self.panel_rect();
        let dialog_width = dialog_rect.width;
        let dialog_height = dialog_rect.height;

        // ── Backdrop, then panel ──
        context.fill_rect(rect, scrim);
        if dialog_width == 0 || dialog_height == 0 {
            return;
        }
        context.fill_rounded_rect(dialog_rect, 14, panel);

        // ── Title ──
        // The title sits at 24 % of the panel's height, so it keeps its position while the
        // panel is squeezed. It is fitted to the panel instead of measured at its full
        // width: a title wider than the dialog used to start at a negative x (its origin is
        // centred from its *unfitted* width) and run out of both sides.
        let title_font = role_font(style, 17.0).with_bold(true);
        if !self.title.is_empty() {
            let title_metrics = context.measure_text("M", &title_font);
            let title_y = dialog_rect.y + ((dialog_height as i32 * 24) / 100).max(0);
            context.draw_text_fitted_cow(
                Rect::new(
                    dialog_rect.x + 12,
                    title_y,
                    dialog_width.saturating_sub(24),
                    title_metrics.height.max(1),
                ),
                &self.title,
                &title_font,
                ink,
                HorizontalAlignment::Center,
            );
        }

        // ── Message ──
        let msg_font = role_font(style, 14.0);
        if !self.message.is_empty() {
            let msg_metrics = context.measure_text("M", &msg_font);
            let msg_y = dialog_rect.y + ((dialog_height as i32 * 46) / 100).max(0);
            context.draw_text_fitted_cow(
                Rect::new(
                    dialog_rect.x + 12,
                    msg_y,
                    dialog_width.saturating_sub(24),
                    msg_metrics.height.max(1),
                ),
                &self.message,
                &msg_font,
                ink,
                HorizontalAlignment::Center,
            );
        }

        // ── Divider line above buttons ──
        // The divider is the top edge of the button row, which is the same rectangle the hit
        // test reads (MW-11).
        let button_row = self.button_row_rect();
        let divider_y = button_row.y;
        context.draw_line(
            Point::new(dialog_rect.x, divider_y),
            Point::new(dialog_rect.x + dialog_width as i32, divider_y),
            separator,
        );

        // ── Buttons ──
        let button_font = role_font(style, 17.0);
        let button_metrics = context.measure_text("M", &button_font);
        let has_cancel = !self.cancel_text.is_empty();

        // The button row is the strip between the divider and the panel's bottom edge, so
        // its cells are derived from that strip rather than from a fixed 12 px offset. The
        // strip is floored at the measured line height and its vertical divider is clamped
        // to the panel's own bottom, which is what a two-button row needed and a shorter one
        // never got.
        let button_top = button_row.y;
        let button_bottom = button_row.y + button_row.height as i32;
        let label_height = button_metrics.height.max(1) as i32;
        let label_y =
            (button_top + (button_bottom - button_top - label_height) / 2).max(button_top);
        let cell_width = if has_cancel { dialog_width as i32 / 2 } else { dialog_width as i32 };

        if has_cancel {
            // Two buttons: cancel on left, confirm on right
            // Vertical divider between them
            let mid_x = dialog_rect.x + dialog_width as i32 / 2;
            context.draw_line(
                Point::new(mid_x, divider_y),
                Point::new(mid_x, button_bottom),
                separator,
            );

            // Cancel button. Centred inside its own half of the row, which is both where the
            // user reads it and the box that keeps its label inside the panel.
            context.draw_text_fitted_cow(
                Rect::new(dialog_rect.x, label_y, cell_width.max(0) as u32, label_height as u32),
                &self.cancel_text,
                &button_font,
                action,
                HorizontalAlignment::Center,
            );

            // Confirm button
            context.draw_text_fitted_cow(
                Rect::new(mid_x, label_y, cell_width.max(0) as u32, label_height as u32),
                &self.confirm_text,
                &button_font,
                action,
                HorizontalAlignment::Center,
            );
        } else {
            // Single confirm button centered
            context.draw_text_fitted_cow(
                Rect::new(dialog_rect.x, label_y, dialog_width, label_height as u32),
                &self.confirm_text,
                &button_font,
                action,
                HorizontalAlignment::Center,
            );
        }
    }
}

impl EventHandler for CupertinoAlertDialog {
    /// Interactions are ignored while the control is disabled.
    ///
    /// The disabled state was not consulted, so a host that disabled the control — the
    /// usual way to take a control out of play — still received clicks and value changes
    /// from it.
    fn handle_event(&mut self, event: &Event) {
        if !self.base.is_enabled() {
            return;
        }
        match event {
            Event::MouseRelease { pos, button } => {
                if *button != 1 {
                    return;
                }
                // The button row is the rectangle the paint path derived, so a control shorter
                // than the nominal panel still has clickable buttons (MW-11).
                let row = self.button_row_rect();
                if !row.contains_point(*pos) {
                    return;
                }
                let has_cancel = !self.cancel_text.is_empty();
                if has_cancel {
                    let mid_x = row.x + row.width as i32 / 2;
                    if pos.x < mid_x {
                        self.canceled.emit();
                    } else {
                        self.confirmed.emit();
                    }
                } else {
                    self.confirmed.emit();
                }
                self.base.request_redraw();
            }
            // A modal dialog's keyboard path: Enter confirms, Escape cancels when there is a
            // cancel action (MW-12).
            Event::KeyPress { key, .. } => match *key {
                13 | 10 => {
                    self.confirmed.emit();
                    self.base.request_redraw();
                }
                27 if !self.cancel_text.is_empty() => {
                    self.canceled.emit();
                    self.base.request_redraw();
                }
                _ => {
                    self.base.handle_event(event);
                }
            },
            _ => {
                self.base.handle_event(event);
            }
        }
    }
}

// ── CupertinoSlider ───────────────────────────────────────────────────────────

/// iOS-style slider (BLUE11 R10.21).
///
/// A range slider over a floating-point value. The range and value are plain
/// `f32`s; nothing here requires `min <= max`, and the current value is not
/// re-clamped when the bounds change.
pub struct CupertinoSlider {
    base: BaseWidget,
    value: f32,
    min: f32,
    max: f32,
    /// Whether a press on the track is still held, making `Drag` update the value (MW-13).
    dragging: bool,
    /// Emitted with the new value whenever it changes — both on a programmatic
    /// [`CupertinoSlider::set_value`] that moves the knob and on a user drag.
    pub value_changed: Signal1<f32>,
}

impl CupertinoSlider {
    /// Creates a new CupertinoSlider with the given geometry.
    /// Default range: 0.0 to 1.0, value at 0.0.
    pub fn new(geometry: crate::core::Rect) -> Self {
        let base = BaseWidget::new(WidgetKind::CupertinoSlider, geometry, "CupertinoSlider");
        Self {
            base,
            value: 0.0,
            min: 0.0,
            max: 1.0,
            dragging: false,
            value_changed: Signal1::new(),
        }
    }

    /// Sets the current value, clamped to [min, max].
    ///
    /// Emits `value_changed` with the clamped value when it actually changes;
    /// re-applying the same clamped value is a no-op.
    ///
    /// `value_changed` is deliberately not gated by `enabled`: the pointer path over this
    /// slider is gated in `handle_event` (the round-52 contract), so a disabled slider
    /// already ignores the user; this writer is the *programmatic* path, and a host that
    /// two-way-binds the value needs the signal even while the control is disabled.
    pub fn set_value(&mut self, value: f32) {
        let clamped = ordered_clamp(value, self.min, self.max);
        if self.value != clamped {
            self.value = clamped;
            self.value_changed.emit(clamped);
        }
        self.base.request_redraw();
    }

    /// Returns the current value.
    pub fn value(&self) -> f32 {
        self.value
    }

    /// Sets the minimum value, re-applying the clamp to the current value so an
    /// out-of-range value is pulled into range (and `value_changed` is emitted
    /// when it moves).
    pub fn set_min(&mut self, min: f32) {
        self.min = min;
        self.set_value(self.value);
    }

    /// Sets the maximum value, re-applying the clamp to the current value so an
    /// out-of-range value is pulled into range (and `value_changed` is emitted
    /// when it moves).
    pub fn set_max(&mut self, max: f32) {
        self.max = max;
        self.set_value(self.value);
    }

    /// Returns the minimum value.
    pub fn min(&self) -> f32 {
        self.min
    }

    /// Returns the maximum value.
    pub fn max(&self) -> f32 {
        self.max
    }

    /// Computes the knob center x position based on current value.
    fn knob_x(&self, track_left: i32, track_width: i32) -> i32 {
        if self.max <= self.min {
            return track_left;
        }
        let fraction = (self.value - self.min) / (self.max - self.min);
        track_left + (fraction * track_width as f32) as i32
    }

    /// Computes value from a pixel x position.
    fn value_from_x(&self, x: i32, track_left: i32, track_width: i32) -> f32 {
        if track_width <= 0 || self.max <= self.min {
            return self.min;
        }
        let fraction = ((x - track_left) as f32 / track_width as f32).clamp(0.0, 1.0);
        self.min + fraction * (self.max - self.min)
    }
}

impl Widget for CupertinoSlider {
    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::CUPERTINO_ROW_DEFAULT_WIDTH,
            crate::widget::metrics::dimensions::CUPERTINO_ROW_DEFAULT_HEIGHT,
        )
    }

    fn kind(&self) -> WidgetKind {
        WidgetKind::CupertinoSlider
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
    /// Resolves a published event name to the control's own signal.
    ///
    /// # Why this is explicit per control
    ///
    /// `connect_event` validates a name against the capability table and registers a hub slot; only
    /// `event_signal_dyn` joins that name to the signal the control actually emits. Without it a name
    /// is valid and inert, which is the silent failure `tools/check_event_signal_dyn.sh` exists to
    /// make impossible. The arm set is checked against the capability's published names, so this
    /// list cannot drift from what the control advertises.
    fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
        use crate::signal::EventSignalRef;
        #[allow(unused_imports)]
        use crate::widget::capability::CapabilityValue;
        match name {
            "value_changed" => {
                Some(EventSignalRef::mapped("value_changed", &self.value_changed, |v| {
                    CapabilityValue::Float(*v as f64)
                }))
            }
            _ => None,
        }
    }
}

/// `CupertinoSlider`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch, including
/// the `f32` → `f64` widening on read.
impl WidgetProperties for CupertinoSlider {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "value" => Ok(CapabilityValue::Float(self.value().into())),
            "min" => Ok(CapabilityValue::Float(self.min().into())),
            "max" => Ok(CapabilityValue::Float(self.max().into())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "value" => {
                self.set_value(expect_f32(value)?);
                Ok(())
            }
            "min" => {
                self.set_min(expect_f32(value)?);
                Ok(())
            }
            "max" => {
                self.set_max(expect_f32(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        property_names_of!["value", "min", "max", BASE_PROPERTY_NAMES]
    }
}

impl Draw for CupertinoSlider {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();

        let track_height = 4u32;
        let knob_radius = 12u32;
        let track_y = rect.y + (rect.height as i32 / 2) - (track_height as i32 / 2);
        let track_left = rect.x + knob_radius as i32;
        let track_width = rect.width as i32 - 2 * knob_radius as i32;

        if track_width <= 0 {
            return;
        }

        let track_rect =
            crate::core::Rect::new(track_left, track_y, track_width as u32, track_height);

        // Chrome colours resolve explicit style first, then the theme's resolved style for
        // this control, and only then fall back to a literal. Without the theme step a
        // light/dark switch changed nothing on screen — the empty track and the knob were
        // hardcoded, which the rendering census reported as theme-blind. The knob is the
        // largest area the slider paints, so it is what the census measures as dominant.
        //
        // 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();
        let theme = crate::style::resolved_theme_style_shared("cupertino_slider");
        // Read as its own lock acquisition and copied out as values, so the guard is dropped
        // before anything else touches the theme. `cupertino_slider` is not in the role
        // table, so it classifies as `Surface` and its resolved background is the window
        // fill itself; the surface below therefore derives its own distinct colour rather
        // than painting the window's. The filled run of the track is a value indicator, the
        // same role `Slider`'s own fill plays, so it reads the theme's accent.
        let (window_fill, foreground, accent, muted) = {
            let manager = crate::style::theme_manager();
            match manager.current_theme() {
                Some(active) => (
                    active.colors.background,
                    active.colors.foreground,
                    active.colors.accent,
                    active.colors.secondary,
                ),
                None => (
                    Color::rgb(240, 240, 240),
                    Color::BLACK,
                    Color::rgb(33, 150, 243),
                    Color::rgb(158, 158, 158),
                ),
            }
        };

        let ink = style
            .text_color
            .or_else(|| theme.as_ref().and_then(|t| t.text_color))
            .unwrap_or(foreground);
        // The empty run of the track, one step from the window fill toward the text colour,
        // so it is visible on either appearance rather than being the window's own colour.
        let empty_track = window_fill.blend(&ink, 0.14);
        // The filter is on the **resolved** value, not only on the theme's: the active theme
        // is applied to every control before it is drawn, so `style.background_color` already
        // holds `Surface`'s window fill and letting it through unfiltered is exactly the
        // invisible-control defect this guards against. A caller's own colour still wins.
        let track_color = match style.background_color {
            Some(resolved) if resolved != window_fill => resolved,
            _ => empty_track,
        };

        // ── Background track ──
        context.fill_rounded_rect(track_rect, track_height / 2, track_color);

        // ── Filled track ──
        let knob_center_x = self.knob_x(track_left, track_width);
        let fill_width = (knob_center_x - track_left) as u32;
        if fill_width > 0 {
            let fill_rect = crate::core::Rect::new(track_left, track_y, fill_width, track_height);
            context.fill_rounded_rect(fill_rect, track_height / 2, accent);
        }

        // ── Knob (circle with a thin border) ──
        // The two-step surface `Input` uses: a light knob on a light theme, a dark one on a
        // dark theme, with the luminance inverted from the surface so the disc stays visible.
        let knob_fill = if track_color.is_dark() {
            track_color.blend(&Color::WHITE, 0.30)
        } else {
            track_color.blend(&Color::WHITE, 0.85)
        };
        context.fill_circle_aa(
            Point::new(knob_center_x, rect.y + (rect.height as i32 / 2)),
            knob_radius,
            knob_fill,
        );
        // Knob border, one visible step from the knob itself.
        let knob_border = style
            .border_color
            .or_else(|| theme.as_ref().and_then(|t| t.border_color))
            .filter(|resolved| *resolved != knob_fill)
            .unwrap_or_else(|| knob_fill.blend(&muted, 0.40));
        context.draw_circle_stroke(
            Point::new(knob_center_x, rect.y + (rect.height as i32 / 2)),
            knob_radius,
            knob_border,
            1,
        );
    }
}

impl EventHandler for CupertinoSlider {
    /// Interactions are ignored while the control is disabled.
    ///
    /// The disabled state was not consulted, so a host that disabled the control — the
    /// usual way to take a control out of play — still received clicks and value changes
    /// from it.
    fn handle_event(&mut self, event: &Event) {
        if !self.base.is_enabled() {
            return;
        }
        match event {
            Event::MousePress { pos, button, .. } => {
                if *button != 1 {
                    return;
                }

                let rect = self.geometry();
                let knob_radius = 12u32;
                let track_left = rect.x + knob_radius as i32;
                let track_width = rect.width as i32 - 2 * knob_radius as i32;

                if track_width <= 0 {
                    return;
                }

                let new_value = self.value_from_x(pos.x, track_left, track_width);
                let clamped = ordered_clamp(new_value, self.min, self.max);
                self.dragging = true;
                if (clamped - self.value).abs() > f32::EPSILON {
                    self.value = clamped;
                    self.value_changed.emit(clamped);
                    self.base.request_redraw();
                }
            }
            // A held pointer is the slider's main gesture: continuous updates while dragging,
            // not just the initial press-to-jump (MW-13).
            Event::Drag { pos, .. } if self.dragging => {
                let rect = self.geometry();
                let knob_radius = 12u32;
                let track_left = rect.x + knob_radius as i32;
                let track_width = rect.width as i32 - 2 * knob_radius as i32;
                if track_width <= 0 {
                    return;
                }
                let new_value = self.value_from_x(pos.x, track_left, track_width);
                let clamped = ordered_clamp(new_value, self.min, self.max);
                if (clamped - self.value).abs() > f32::EPSILON {
                    self.value = clamped;
                    self.value_changed.emit(clamped);
                    self.base.request_redraw();
                }
            }
            Event::MouseRelease { .. } if self.dragging => {
                self.dragging = false;
            }
            _ => {
                self.base.handle_event(event);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Point;
    use crate::widget::metrics::dimensions;
    use crate::widget::svg::render_to_svg;
    use crate::widget::{IconItemError, IconSource};
    use std::sync::{
        atomic::{AtomicBool, AtomicUsize, Ordering},
        Arc,
    };

    // ── CupertinoSwitch tests ──

    #[test]
    fn cupertino_switch_new_defaults() {
        let cs = CupertinoSwitch::new(Rect::new(0, 0, 60, 30));
        assert_eq!(cs.inner().kind(), WidgetKind::Switch);
        assert_eq!(cs.kind(), WidgetKind::CupertinoSwitch);
        assert!(!cs.inner().is_checked());
    }

    #[test]
    fn cupertino_switch_toggle_delegates() {
        let mut cs = CupertinoSwitch::new(Rect::new(0, 0, 60, 30));
        assert!(!cs.inner().is_checked());
        cs.inner_mut().toggle();
        assert!(cs.inner().is_checked());
    }

    /// A completed pointer activation on the wrapper toggles the inner switch.
    ///
    /// The bare `MouseRelease` this used to dispatch asserted the defect (see
    /// `Switch::handle_event`); the delegation intent is unchanged.
    #[test]
    fn cupertino_switch_event_delegation() {
        let mut cs = CupertinoSwitch::new(Rect::new(0, 0, 60, 30));
        let p = Point::new(10, 10);
        cs.handle_event(&Event::MousePress { pos: p, button: 1, modifiers: 0 });
        cs.handle_event(&Event::MouseRelease { pos: p, button: 1 });
        assert!(cs.inner().is_checked());
    }

    #[test]
    fn cupertino_switch_svg_output() {
        let mut cs = CupertinoSwitch::new(Rect::new(0, 0, 60, 30));
        let svg = render_to_svg(&mut cs);
        assert!(svg.starts_with("<svg"));
    }

    /// The iOS name has to mean an iOS *shape*, or it is a second spelling for one control.
    ///
    /// `cupertino_switch` used to be a bare newtype over `Switch`: it inherited Material's
    /// `52x32` track, so the only thing "iOS" about it was the word. The assertion is the
    /// geometry the control reports, not a rendered string, so it cannot be satisfied by
    /// the shape happening to look similar.
    #[test]
    fn cupertino_switch_carries_the_ios_geometry() {
        // Holds the crate-wide theme guard: this test renders, and a concurrent
        // test that switches the appearance would otherwise change a later frame.
        let _theme_guard = crate::style::theme_test_guard();
        let material = Switch::new(Rect::new(0, 0, 240, 120));
        let mut cupertino = CupertinoSwitch::new(Rect::new(0, 0, 240, 120));

        assert_eq!(cupertino.inner().drawn_shape(), SwitchGeometry::CUPERTINO);
        assert_ne!(
            cupertino.inner().drawn_shape(),
            material.drawn_shape(),
            "an iOS switch must not be drawn in the Material shape"
        );
        // The hint follows the shape rather than being a third, hardcoded size.
        assert_eq!(cupertino.size_hint(), cupertino.inner().size_hint());

        // The thumb's own rectangle is the iOS one: a 26 px disc, not Material's 28.
        let rect = Rect::new(0, 0, 240, 120);
        let thumb = cupertino.inner().thumb_rect(rect).expect("a roomy rect has a thumb");
        assert_eq!(thumb.width, dimensions::CUPERTINO_SWITCH_THUMB_RADIUS * 2);

        // On, the track is iOS green — and that green is the *on* end only. Writing it to
        // `background_color` (the off track) is the defect this replaced, so the off frame
        // has to be checked too.
        let off = render_to_svg(&mut cupertino);
        assert!(
            !off.contains("rgba(52,199,89"),
            "an off iOS switch must not be painted in the on colour"
        );
        cupertino.inner_mut().set_checked(true);
        // The track is a blend of the two ends by `travel`, so an on switch that has not been
        // ticked is still drawn at the off end. That is deliberate (a freshly built switch must
        // not fade *out* on its first frame), so the test drives the travel to completion the
        // same way the frame bus would before reading the on colour.
        while cupertino.inner_mut().tick(1000) {}
        let on = render_to_svg(&mut cupertino);
        assert!(
            on.contains("rgba(52,199,89"),
            "an on iOS switch must be painted in UISwitch.onTintColor"
        );
    }

    /// Held down, an iOS thumb stretches sideways into a capsule; at rest it is a disc.
    ///
    /// `UISwitch` widens its thumb on touch-down so the gesture is visible. Asserted on the
    /// geometry the draw path reads, so a stretch that is declared but not applied fails.
    #[test]
    fn the_held_ios_thumb_stretches_sideways() {
        use crate::style::WidgetState;

        let rect = Rect::new(0, 0, 240, 120);
        let mut cupertino = CupertinoSwitch::new(rect);
        let resting = cupertino.inner().thumb_rect(rect).expect("a roomy rect has a thumb");

        let centre =
            Point::new(resting.x + resting.width as i32 / 2, resting.y + resting.height as i32 / 2);
        cupertino.handle_event(&Event::MouseEnter { pos: centre });
        cupertino.handle_event(&Event::MousePress { pos: centre, button: 1, modifiers: 0 });
        assert_eq!(cupertino.widget_state(), WidgetState::Pressed);

        let held = cupertino.inner().thumb_rect(rect).expect("a roomy rect has a thumb");
        assert_eq!(
            held.width,
            resting.width + dimensions::CUPERTINO_SWITCH_PRESS_STRETCH * 2,
            "a held thumb must widen by the documented stretch"
        );
        assert_eq!(held.height, resting.height, "the stretch is sideways only");
        // It grows around its own centre, so it does not jump left on touch-down.
        assert_eq!(
            held.x + held.width as i32 / 2,
            resting.x + resting.width as i32 / 2,
            "a stretch must not move the thumb's centre"
        );

        cupertino.handle_event(&Event::MouseRelease { pos: centre, button: 1 });
        let released = cupertino.inner().thumb_rect(rect).expect("a roomy rect has a thumb");
        assert_eq!(released.width, resting.width, "releasing must restore the disc");
    }

    // ── MaterialSnackbar tests ──

    #[test]
    fn material_snackbar_creation() {
        let sb = MaterialSnackbar::new(Rect::new(0, 0, 375, 100));
        assert_eq!(sb.kind(), WidgetKind::MaterialSnackbar);
        assert!(!sb.is_visible());
        assert!(sb.message().is_empty());
        assert!(sb.action_text().is_empty());
    }

    #[test]
    fn material_snackbar_message_accessors() {
        let mut sb = MaterialSnackbar::new(Rect::new(0, 0, 375, 100));
        sb.set_message("File saved");
        assert_eq!(sb.message(), "File saved");
    }

    #[test]
    fn material_snackbar_action_text_accessors() {
        let mut sb = MaterialSnackbar::new(Rect::new(0, 0, 375, 100));
        sb.set_action_text("Undo");
        assert_eq!(sb.action_text(), "Undo");
    }

    #[test]
    fn material_snackbar_show_hide() {
        let mut sb = MaterialSnackbar::new(Rect::new(0, 0, 375, 100));
        assert!(!sb.is_visible());

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

        sb.dismiss();
        assert!(!sb.is_visible());
    }

    #[test]
    fn material_snackbar_dismiss_emits_signal() {
        let mut sb = MaterialSnackbar::new(Rect::new(0, 0, 375, 100));
        sb.set_message("Hello");
        sb.show();

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        sb.dismissed.connect(move || {
            f.store(true, Ordering::SeqCst);
        });

        // Click on snackbar to dismiss
        sb.handle_event(&Event::MousePress { pos: Point::new(200, 80), button: 1, modifiers: 0 });
        assert!(fired.load(Ordering::SeqCst));
        assert!(!sb.is_visible());
    }

    #[test]
    fn material_snackbar_action_pressed_emits_signal() {
        let mut sb = MaterialSnackbar::new(Rect::new(0, 0, 375, 100));
        sb.set_message("File deleted");
        sb.set_action_text("Undo");
        sb.show();

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        sb.action_pressed.connect(move || {
            f.store(true, Ordering::SeqCst);
        });

        // A press on the action latches it, and a release over the same area confirms it. The
        // action no longer fires on the press itself (L-P10).
        sb.handle_event(&Event::MousePress { pos: Point::new(340, 80), button: 1, modifiers: 0 });
        sb.handle_event(&Event::MouseRelease { pos: Point::new(340, 80), button: 1 });
        assert!(fired.load(Ordering::SeqCst));
    }

    #[test]
    fn material_snackbar_hidden_blocks_events() {
        let mut sb = MaterialSnackbar::new(Rect::new(0, 0, 375, 100));
        sb.set_message("Test");

        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        sb.dismissed.connect(move || {
            f.store(true, Ordering::SeqCst);
        });

        // Should not fire since snackbar is hidden
        sb.handle_event(&Event::MousePress { pos: Point::new(200, 80), button: 1, modifiers: 0 });
        assert!(!fired.load(Ordering::SeqCst));
    }

    #[test]
    fn material_snackbar_svg_output() {
        let mut sb = MaterialSnackbar::new(Rect::new(0, 0, 375, 100));
        sb.set_message("Hello");
        sb.set_action_text("Action");
        sb.show();
        let svg = render_to_svg(&mut sb);
        assert!(svg.starts_with("<svg"));
    }

    #[test]
    fn material_snackbar_svg_output_hidden() {
        let mut sb = MaterialSnackbar::new(Rect::new(0, 0, 375, 100));
        // Hidden — should still produce valid SVG
        let svg = render_to_svg(&mut sb);
        assert!(svg.starts_with("<svg"));
    }

    // ── CupertinoAlertDialog tests ──

    #[test]
    fn cupertino_alert_dialog_creation() {
        let dlg = CupertinoAlertDialog::new(Rect::new(0, 0, 400, 300));
        assert_eq!(dlg.kind(), WidgetKind::CupertinoAlertDialog);
        assert!(dlg.title().is_empty());
        assert!(dlg.message().is_empty());
    }

    #[test]
    fn cupertino_alert_dialog_title_accessors() {
        let mut dlg = CupertinoAlertDialog::new(Rect::new(0, 0, 400, 300));
        dlg.set_title("Delete File");
        assert_eq!(dlg.title(), "Delete File");
    }

    #[test]
    fn cupertino_alert_dialog_message_accessors() {
        let mut dlg = CupertinoAlertDialog::new(Rect::new(0, 0, 400, 300));
        dlg.set_message("Are you sure?");
        assert_eq!(dlg.message(), "Are you sure?");
    }

    #[test]
    fn cupertino_alert_dialog_confirm_signal() {
        let mut dlg = CupertinoAlertDialog::new(Rect::new(0, 0, 400, 300));
        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        dlg.confirmed.connect(move || {
            f.store(true, Ordering::SeqCst);
        });

        // Click on confirm button area (right half of button row)
        // Dialog x = (400-320)/2 = 40, dialog_width = 320, dialog_y = (300-200)/2 = 50
        // divider_y = 50+200-48 = 202
        // Button area: y 202..250, x 40..360
        // Confirm is right half: x 200..360
        dlg.handle_event(&Event::MouseRelease { pos: Point::new(300, 225), button: 1 });
        assert!(fired.load(Ordering::SeqCst));
    }

    #[test]
    fn cupertino_alert_dialog_cancel_signal() {
        let mut dlg = CupertinoAlertDialog::new(Rect::new(0, 0, 400, 300));
        let fired = Arc::new(AtomicBool::new(false));
        let f = fired.clone();
        dlg.canceled.connect(move || {
            f.store(true, Ordering::SeqCst);
        });

        // Click on cancel button area (left half of button row)
        dlg.handle_event(&Event::MouseRelease { pos: Point::new(100, 225), button: 1 });
        assert!(fired.load(Ordering::SeqCst));
    }

    #[test]
    fn cupertino_alert_dialog_svg_output() {
        let mut dlg = CupertinoAlertDialog::new(Rect::new(0, 0, 400, 300));
        dlg.set_title("Notice");
        dlg.set_message("Hello world");
        let svg = render_to_svg(&mut dlg);
        assert!(svg.starts_with("<svg"));
    }

    // ── CupertinoSlider tests ──

    #[test]
    fn cupertino_slider_creation() {
        let sl = CupertinoSlider::new(Rect::new(0, 0, 200, 40));
        assert_eq!(sl.kind(), WidgetKind::CupertinoSlider);
        assert_eq!(sl.value(), 0.0);
        assert_eq!(sl.min(), 0.0);
        assert_eq!(sl.max(), 1.0);
    }

    #[test]
    fn cupertino_slider_value_get_set() {
        let mut sl = CupertinoSlider::new(Rect::new(0, 0, 200, 40));
        sl.set_value(0.5);
        assert!((sl.value() - 0.5).abs() < 1e-6);

        // Clamping
        sl.set_value(2.0);
        assert!((sl.value() - 1.0).abs() < 1e-6);

        sl.set_value(-1.0);
        assert!((sl.value() - 0.0).abs() < 1e-6);
    }

    #[test]
    fn cupertino_slider_min_max_accessors() {
        let mut sl = CupertinoSlider::new(Rect::new(0, 0, 200, 40));
        sl.set_max(100.0);
        sl.set_min(10.0);
        assert!((sl.min() - 10.0).abs() < 1e-6);
        assert!((sl.max() - 100.0).abs() < 1e-6);

        // Value should be clamped
        sl.set_value(5.0);
        assert!((sl.value() - 10.0).abs() < 1e-6);
    }

    /// Setting `min` above the current `max` must clamp, not abort the process.
    ///
    /// A slider is created with `(min, max) = (0.0, 1.0)`. Writing `min = 3.5`
    /// through the public setter — which is precisely what the capability layer's
    /// `write_property(w, "min", …)` does, and therefore what a JSON document or a
    /// C-ABI caller does — used to reach `value.clamp(3.5, 1.0)`. `f32::clamp`
    /// panics when `min > max`, so a caller who set two numbers in the "wrong"
    /// order killed the host. Setter order is not something a GUI library may put
    /// a precondition on.
    #[test]
    fn cupertino_slider_min_above_max_clamps_instead_of_panicking() {
        let mut sl = CupertinoSlider::new(Rect::new(0, 0, 200, 40));
        sl.set_min(3.5);
        // The bounds may now be crossed; the value must still be a number inside
        // the range the caller named, and reading it must not panic either.
        let value = sl.value();
        assert!(value.is_finite(), "value must remain finite after crossed bounds, got {value}");
        assert!(
            (1.0..=3.5).contains(&value),
            "value {value} is outside the ordered range [1.0, 3.5]"
        );

        // The mirrored case: `max` below the current `min`.
        let mut sl = CupertinoSlider::new(Rect::new(0, 0, 200, 40));
        sl.set_min(5.0);
        sl.set_max(2.0);
        let value = sl.value();
        assert!(value.is_finite(), "value must remain finite after crossed bounds, got {value}");
    }

    /// A `NaN` bound must be ignored rather than poison the value.
    #[test]
    fn cupertino_slider_nan_bound_does_not_poison_the_value() {
        let mut sl = CupertinoSlider::new(Rect::new(0, 0, 200, 40));
        sl.set_value(0.5);
        sl.set_min(f32::NAN);
        let value = sl.value();
        assert!(!value.is_nan(), "a NaN bound must not make the value NaN; got {value}");
    }

    #[test]
    fn cupertino_slider_mouse_press_updates_value() {
        let mut sl = CupertinoSlider::new(Rect::new(0, 0, 200, 40));
        // track_left = 12, track_width = 200-24 = 176
        // Click at x=100 -> fraction ~ (100-12)/176 ~ 0.5
        sl.handle_event(&Event::MousePress { pos: Point::new(100, 20), button: 1, modifiers: 0 });
        assert!((sl.value() - 0.5).abs() < 0.05);
    }

    #[test]
    fn cupertino_slider_set_value_emits_changed_only_on_real_change() {
        let mut sl = CupertinoSlider::new(Rect::new(0, 0, 200, 40));
        let seen = Arc::new(AtomicUsize::new(0));
        {
            let c = seen.clone();
            sl.value_changed.connect(move |_| {
                c.fetch_add(1, Ordering::SeqCst);
            });
        }

        sl.set_value(0.5);
        assert_eq!(seen.load(Ordering::SeqCst), 1);
        sl.set_value(0.5); // no-op: same clamped value
        assert_eq!(seen.load(Ordering::SeqCst), 1);
        sl.set_value(0.9);
        assert_eq!(seen.load(Ordering::SeqCst), 2);
    }

    #[test]
    fn cupertino_slider_mouse_press_different_position() {
        let mut sl = CupertinoSlider::new(Rect::new(0, 0, 200, 40));
        // Press at a different position
        sl.handle_event(&Event::MousePress { pos: Point::new(150, 20), button: 1, modifiers: 0 });
        assert!((sl.value() - 0.78).abs() < 0.05);
    }

    #[test]
    fn cupertino_slider_svg_output() {
        let mut sl = CupertinoSlider::new(Rect::new(0, 0, 200, 40));
        let svg = render_to_svg(&mut sl);
        assert!(svg.starts_with("<svg"));
    }

    // ── MaterialNavigationRail tests ──

    #[test]
    fn material_navigation_rail_creation() {
        let rail = MaterialNavigationRail::new(Rect::new(0, 0, 80, 400));
        assert_eq!(rail.kind(), WidgetKind::MaterialNavigationRail);
        assert_eq!(rail.item_count(), 0);
        assert_eq!(rail.selected(), 0);
    }

    #[test]
    fn material_navigation_rail_add_items() {
        let mut rail = MaterialNavigationRail::new(Rect::new(0, 0, 80, 400));
        rail.add_item("\u{1f3e0}", "Home");
        rail.add_item("\u{2b50}", "Favorites");
        rail.add_item("\u{2699}", "Settings");
        assert_eq!(rail.item_count(), 3);
    }

    #[test]
    fn material_navigation_rail_selection() {
        let mut rail = MaterialNavigationRail::new(Rect::new(0, 0, 80, 400));
        rail.add_item("A", "Item A");
        rail.add_item("B", "Item B");
        rail.add_item("C", "Item C");

        assert_eq!(rail.selected(), 0);
        rail.set_selected(1);
        assert_eq!(rail.selected(), 1);
        rail.set_selected(5); // Clamped
        assert_eq!(rail.selected(), 2);
    }

    #[test]
    fn material_navigation_rail_clear_items() {
        let mut rail = MaterialNavigationRail::new(Rect::new(0, 0, 80, 400));
        rail.add_item("A", "Item A");
        rail.add_item("B", "Item B");
        assert_eq!(rail.item_count(), 2);
        rail.clear_items();
        assert_eq!(rail.item_count(), 0);
        assert_eq!(rail.selected(), 0);
    }

    #[test]
    fn material_navigation_rail_svg_output() {
        let mut rail = MaterialNavigationRail::new(Rect::new(0, 0, 80, 400));
        rail.add_item("\u{1f3e0}", "Home");
        rail.add_item("\u{2b50}", "Stars");
        let svg = render_to_svg(&mut rail);
        assert!(svg.starts_with("<svg"));
    }

    #[test]
    fn material_navigation_rail_typed_item_source_is_checked_and_rendered() {
        static RING: crate::widget::IconData = crate::widget::IconData {
            name: "rail-ring",
            grid: 24,
            paths: &["M2-2H22V-22H2Z M7-7V-17H17V-7Z"],
        };
        let mut rail = MaterialNavigationRail::new(Rect::new(0, 0, 80, 400));
        rail.add_item("legacy", "Home");
        assert_eq!(
            rail.set_item_icon_source(1, Some(IconSource::static_geometry(&RING))),
            Err(IconItemError::IndexOutOfBounds { index: 1, len: 1 })
        );
        rail.set_item_icon_source(0, Some(IconSource::static_geometry(&RING)))
            .expect("existing rail item accepts typed source");
        assert!(render_to_svg(&mut rail).contains("fill-rule=\"nonzero\""));
        rail.clear_items();
        assert_eq!(
            rail.set_item_icon_source(0, None),
            Err(IconItemError::IndexOutOfBounds { index: 0, len: 0 })
        );
    }

    /// The rail is an edge strip, and only presses inside that strip select an item.
    ///
    /// The strip used to be `rect.width`, so a rail offered a 240 px cell painted a
    /// full-width panel and a press anywhere in the cell selected the item under that y.
    #[test]
    fn the_rail_strip_is_fixed_width_and_only_selects_inside_it() {
        let mut rail = MaterialNavigationRail::new(Rect::new(0, 0, 240, 300));
        rail.add_item("home", "Home");
        rail.add_item("search", "Search");
        assert_eq!(rail.selected(), 0);

        // Inside the 80 px strip, on the second item's row (72 px tall).
        rail.handle_event(&crate::event::Event::MouseRelease {
            pos: Point::new(20, 80),
            button: 1,
        });
        assert_eq!(rail.selected(), 1, "a press on the second destination selects it");

        // Outside the strip but on the same row: the control's rectangle is room, not rail.
        rail.handle_event(&crate::event::Event::MouseRelease {
            pos: Point::new(200, 80),
            button: 1,
        });
        assert_eq!(rail.selected(), 1, "a press past the strip's edge selects nothing");
    }
}