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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Switch/Toggle widget — a modern on/off binary state control.
//!
//! The Switch widget presents a sliding toggle that represents a boolean state,
//! similar to iOS UISwitch or Android Switch material widget. It supports
//! on/off toggling, animated transitions, and accessibility role mapping.
use crate::core::{Color, Rect};
// Gated exactly like the test module that uses it: `#[cfg(test)]` alone is true in a build where
// `full_widgets` is off, and the import would then be unused (a warning, which this crate's
// profile checks treat as a defect).
#[cfg(all(test, full_widgets))]
use crate::event::FocusReason;
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::style::{MotionSlot, PropertyDriver};
use crate::widget::capability::coercion::expect_bool;
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::metrics::{
focus_ring_color, ControlMetrics, FocusRing, SwitchGeometry, FOCUS_RING_WIDTH,
};
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// Switch/Toggle widget for binary on/off state selection.
pub struct Switch {
base: BaseWidget,
/// The **logical** state: the answer `is_checked` gives, changed by the user's action
/// the instant it happens. It is not what the thumb is drawn from — see `travel`.
checked: bool,
/// `true` between a pointer press that hit this control and the release that ends
/// it. The release is what commits the toggle, so a press that began elsewhere and
/// merely *ends* over the switch must not flip it — see `handle_event`.
///
/// Distinct from [`BaseWidget::is_pressed`], which is the paint flag the base keeps
/// for every control: this one is the *commit guard* the toggle needs, and it means
/// "a press landed on me and has not been released yet" rather than "paint pressed".
pressed: bool,
/// The **drawn** state: how far the thumb has travelled, `0.0` at the off end and
/// `1.0` at the on end.
/// # Why this is not `checked`
///
/// `checked` is the logical state, and a toggle must be answered immediately: a
/// caller that reads `is_checked` after a click has to see the new value the moment
/// the click happened. Drawing the thumb from `checked` would therefore *also* move
/// the thumb the instant the click arrived, with no transition — and a control whose
/// motion has to be observable cannot put its presentation into the value the caller
/// reads. The logical position and the drawn position are deliberately distinct,
/// as a slider's own `position` (logical) versus its
/// `visualPosition` are; this field is the crate's
/// drawn position. `travel = 0` renders exactly the old off-end appearance, so a
/// snapshot taken without a `tick` is unchanged.
travel: PropertyDriver,
/// The shape the track and thumb are drawn in.
///
/// Defaults to Material's `52x32`; `cupertino_switch` is this same control carrying
/// `SwitchGeometry::CUPERTINO`. One control, one gesture, one animation — and the two
/// presets cannot drift on the parts that are not about size, because there is only
/// one implementation of those parts.
geometry: SwitchGeometry,
/// The ON track's colour, when the caller wants to name it rather than take the
/// theme's accent.
///
/// # Why this is separate from `background_color`
///
/// `style.background_color` is the **off** track (the chrome the control sits on);
/// writing the active colour there paints an off switch in the on colour, which is
/// exactly the bug `cupertino_switch` had — its iOS green landed on the resting track.
/// The two ends are two facts and now have two fields.
on_track: Option<Color>,
/// Emitted when the checked state changes.
pub toggled: Signal1<bool>,
}
impl Switch {
/// Creates a new Switch widget with the given geometry.
/// Initial state is unchecked (off).
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::Switch, geometry, "Switch"),
checked: false,
pressed: false,
// A toggle travelling across its track is a *larger* movement than a direct
// reaction to the pointer, which is what the theme's `slow` token describes.
// Starting at rest (0.0) keeps a freshly built switch at the off end instead
// of fading *out* on its first frame.
travel: PropertyDriver::at(0.0, MotionSlot::Slow),
geometry: SwitchGeometry::MATERIAL,
on_track: None,
toggled: Signal1::new(),
}
}
/// Returns whether the switch is in the checked (on) state.
pub fn is_checked(&self) -> bool {
self.checked
}
/// Sets the checked state. Emits `toggled` signal if the state actually changes.
///
/// # Why this does **not** declare that the control drives its own frames
///
/// `checked` decides which end of the track the thumb travels toward, so the change is
/// paint-worthy — and the tempting move is to say so here, since a control that repaints itself
/// tells the frame bus to leave it alone. This one must not: the *drawn* state is `travel`,
/// `travel` only advances in [`Self::tick`], and [`Self::tick`] belongs to whoever owns the
/// control — the frame loop when it is mounted, [`crate::widget::draw_bridge::draw_of`] when the
/// host owns it. Declaring self-driving here would take the owned case away from the only
/// driver it has, leaving the thumb frozen at whichever end it was on when the caller toggled
/// it.
///
/// Asking for a repaint is not what makes the motion visible either, which is the second
/// reason there is nothing to do here:
///
/// * **mounted** — [`crate::widget::runtime::tick_animations`] reports `true` while any control
/// is in flight, and the frame loop paints again because of that;
/// * **host-owned** — the paint path advances the control and reports the result through
/// [`crate::widget::runtime::animation_bus_needs_another_frame`], the same answer by a
/// different route.
///
/// So the honest declaration is the one already in place: a `Switch` does not drive its own
/// frames. Everything that must re-read `checked` — the capability layer, the JSON loader, the
/// signal a host connected — is reached by the signal below.
pub fn set_checked(&mut self, checked: bool) {
if self.checked != checked {
self.checked = checked;
self.toggled.emit(checked);
}
}
/// Toggles the checked state.
pub fn toggle(&mut self) {
self.set_checked(!self.checked);
}
/// `true` while a pointer press that hit this control is still held.
pub fn is_pressed(&self) -> bool {
self.pressed
}
/// Returns whether this switch is the keyboard's current target, regardless of
/// whether a ring is drawn for it.
pub fn is_focused(&self) -> bool {
self.base.focus_reason().is_some()
}
/// Returns whether a focus ring should be painted right now.
///
/// The single question every draw site asks — [`BaseWidget::draws_focus_ring`] —
/// evaluated in one place so a control cannot accidentally implement "has focus"
/// as "draw the ring".
pub fn visual_focus(&self) -> bool {
self.base.draws_focus_ring()
}
/// Returns whether the pointer is currently over this switch.
///
/// Hover is recorded by [`BaseWidget`] from [`crate::event::Event::MouseEnter`] /
/// [`crate::event::Event::MouseLeave`], which the widget runtime synthesises as
/// the pointer moves between controls (no platform backend produces them).
pub fn is_hovered(&self) -> bool {
self.base.is_hovered()
}
/// Sets the hovered flag.
///
/// # Why this is public
///
/// The `MouseEnter`/`MouseLeave` arms set the flag from real pointer events, but a
/// host driving a control from its own input layer — a touch backend that has no
/// hover concept, a test, or a designer previewing a state — needs a way to say
/// "show me this control hovered". Without it the hovered appearance was reachable
/// only by synthesising an event.
///
/// Setting it also requests a redraw, because the flag changes what is painted.
pub fn set_hovered(&mut self, hovered: bool) {
if self.base.is_hovered() == hovered {
return;
}
self.base.set_hovered(hovered);
self.base.request_redraw();
}
/// How far the thumb has travelled, `0.0` at the off end and `1.0` at the on end.
///
/// This is the *drawn* position, not the logical state: it is what the draw site
/// reads to place the thumb and to blend the track colour, so the two cannot slide
/// out of step with each other.
pub fn travel_progress(&self) -> f32 {
self.travel.value()
}
/// The shape this switch's track and thumb are drawn in.
///
/// Named `drawn_shape` rather than `geometry` because `Widget::geometry()` already
/// answers a different question (the control's rectangle), and a same-named accessor
/// would silently shadow it at every call site.
pub fn drawn_shape(&self) -> SwitchGeometry {
self.geometry
}
/// Replaces the drawn shape.
///
/// # What this is for
///
/// `cupertino_switch` uses it to carry `SwitchGeometry::CUPERTINO`. It is public
/// rather than crate-private because a host that wants an iOS-shaped switch under
/// its own name — or a third preset — should not have to reimplement the gesture and
/// the animation to get it.
///
/// It also reports the change as paint-worthy: the thumb's rectangle and the
/// control's `size_hint` both read this field, so a silent assignment would leave a
/// laid-out switch painted at the old size.
pub fn set_geometry(&mut self, geometry: SwitchGeometry) {
if self.geometry == geometry {
return;
}
self.geometry = geometry;
self.base.request_redraw();
self.base.request_layout();
}
/// The ON track's explicitly named colour, if the caller named one.
pub fn on_track_color(&self) -> Option<Color> {
self.on_track
}
/// Names the ON track's colour, overriding the theme's accent.
///
/// `None` restores the theme-resolved behaviour. This is the *only* way to say
/// "this switch's active end is this colour": `set_style` with a `background_color`
/// sets the **off** track, because that field is the control's chrome.
pub fn set_on_track_color(&mut self, color: Option<Color>) {
if self.on_track == color {
return;
}
self.on_track = color;
self.base.request_redraw();
}
/// The thumb's rectangle for the current travel, or `None` when the track is too
/// small to hold a disc.
///
/// # Why this is an accessor and not an inline expression in `draw`
///
/// The thumb's position is the value an animation is *for*: the only way to assert
/// "the thumb slid rather than jumped" is to sample this at successive frames. Keeping
/// the derivation here means the geometry test and the draw path cannot disagree about
/// where the thumb is — the same "one derivation" rule the rest of the crate follows.
///
/// `None` for a degenerate track rather than a zero-size rectangle: a switch laid out
/// smaller than its own track has no thumb to point at, and the caller must be able to
/// tell that from a thumb at the origin.
pub fn thumb_rect(&self, rect: Rect) -> Option<Rect> {
let track_rect = ControlMetrics::center_in(rect, self.geometry.track);
let thumb_size = self.geometry.thumb_size();
let thumb_inset = self.geometry.thumb_inset;
let thumb_size = thumb_size.min(track_rect.height.saturating_sub(thumb_inset * 2));
if thumb_size == 0 {
return None;
}
// A disabled switch shows its logical state at rest; an enabled one follows the
// travel, which is what lets the thumb be seen crossing.
let travel = if self.base.is_enabled() {
self.travel.value()
} else if self.checked {
1.0
} else {
0.0
};
// A resting thumb is a disc; a held one stretches sideways into a capsule where
// the shape asks for it. The stretch is applied to the *span* the thumb travels
// over as well as to the thumb itself, so a stretched thumb still stops at the
// track's inner edge instead of overhanging it.
let held = self.base.is_pressed() && self.geometry.press_stretch > 0;
let stretch = if held { self.geometry.press_stretch } else { 0 };
let drawn_width = thumb_size + stretch * 2;
let travel_span = track_rect
.width
.saturating_sub(drawn_width + thumb_inset * 2)
.max(thumb_size.saturating_sub(drawn_width));
let travel_x = thumb_inset as i32 + (travel_span as f32 * travel) as i32;
// The centre travels; the rectangle grows around it. Placing the *left edge* at
// the travel offset would make a held thumb jump left by its own stretch, which
// reads as the control twitching on touch-down rather than responding.
let centre_x = track_rect.x + travel_x + thumb_size as i32 / 2;
let thumb_x = centre_x - drawn_width as i32 / 2;
let thumb_y = track_rect.y + thumb_inset as i32;
Some(Rect::new(thumb_x, thumb_y, drawn_width, thumb_size))
}
/// Advances the thumb's travel by `delta_ms` and reports whether another frame is
/// needed.
///
/// # The contract this implements
///
/// Return `true` while there is still movement and `false` once the thumb has
/// settled, so a host can stop scheduling frames for a control that is not moving. A
/// `tick` that always returned `true` would keep the whole application repainting
/// forever, which is why the boolean is part of the signature rather than something
/// the caller infers.
///
/// # Why the target is recomputed here
///
/// The target comes from the control's own logical state on every tick, so a toggle
/// that arrived without a `tick` in between is picked up rather than missed — and a
/// reversal mid-flight re-aims the travel from where it currently is instead of
/// restarting from the far end.
pub fn tick(&mut self, delta_ms: u32) -> bool {
// One place states which end `checked` means, so the tick and the "am I moving?" query
// cannot disagree about it (`Switch::travel_target`).
self.travel.set_target(self.travel_target());
self.travel.tick(delta_ms)
}
/// The travel the logical `checked` flag calls for.
///
/// Split out because two readers answer questions about the same fact -- the tick aims at
/// it and `is_animating` compares against it -- and a `if self.checked { 1.0 } else { 0.0 }`
/// written twice is exactly the kind of copy that drifts.
fn travel_target(&self) -> f32 {
if self.checked {
1.0
} else {
0.0
}
}
}
impl Widget for Switch {
fn base(&self) -> &BaseWidget {
&self.base
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn size_hint(&self) -> crate::core::Size {
// The hint describes the control's own floor rather than the drawn track: the track
// is `self.geometry.track`, but a switch that can show a focus ring needs room for the
// ring's inset on both sides. `SWITCH_TRACK.width` alone made the hint *narrower*
// than the width at which the ring is drawable, so `size_hint` described a control
// whose focus state could not be rendered. The height stays the track's own.
crate::core::Size::new(
self.geometry.track.width + FOCUS_RING_WIDTH * 2,
self.geometry.track.height,
)
}
impl_draw_bridge!();
impl_widget_property_hooks!();
/// Reports `Checked` for an on switch, so the preset's `switch:checked` override is reachable.
/// The same defect and the same fix as `CheckBox::widget_state` — the trait default knows the
/// four primitive flags and none of them means "latched", so the key was declared and
/// unreachable. This one is the most visible of the four: a switch's whole meaning is its
/// position.
fn widget_state(&self) -> crate::style::WidgetState {
use crate::style::WidgetState;
if !self.base.is_enabled() {
return WidgetState::Disabled;
}
if self.checked {
return WidgetState::Checked;
}
if self.base.is_pressed() {
WidgetState::Pressed
} else if self.base.is_hovered() {
WidgetState::Hover
} else if self.base.draws_focus_ring() {
WidgetState::Focused
} else {
WidgetState::Normal
}
}
// `Switch::tick` owns the thumb travel; the trait spelling is what the animation bus
// reaches through `&mut dyn Widget`, which is the only way the sliding actually happens.
fn tick(&mut self, delta_ms: u32) -> bool {
Switch::tick(self, delta_ms)
}
fn is_animating(&self) -> bool {
self.travel.value() != self.travel_target()
}
}
/// `Switch`'s property contract.
impl WidgetProperties for Switch {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"checked" => Ok(CapabilityValue::Bool(self.is_checked())),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"checked" => {
self.set_checked(expect_bool(value)?);
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
// Mirrors `SWITCH_PROPERTIES`.
property_names_of!["checked", BASE_PROPERTY_NAMES]
}
/// Runs one of the commands `switch` publishes.
///
/// `toggle` is the control's zero-argument action and flips the latch, emitting
/// `toggled` on the transition exactly as a pointer activation does.
/// `set_checked` assigns the same state but needs the boolean, so it is refused as
/// [`CapabilityAccessError::OutOfRange`] — use `set("checked", ..)` — rather than
/// reported unknown.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"toggle" => {
self.toggle();
Ok(())
}
"set_checked" => Err(CapabilityAccessError::OutOfRange),
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
impl Draw for Switch {
fn draw(&mut self, context: &mut RenderContext) {
let rect = self.geometry();
let is_enabled = self.base.is_enabled();
let style = self.style();
// Track geometry
//
// The track is a **fixed-size** stadium centred inside `rect`, not a scaling of
// it. Deriving the track from the geometry made the *control* the track: a
// 240x120 census cell drew a 240x120 stadium with a 116x116 thumb, which is a
// picture of a switch-shaped rectangle rather than a switch. The geometry is the
// widget's *occupancy* — its hit area and its layout slot — and the drawn chrome
// is a separate, fixed proportion of it. That is the same split a Material switch
// makes (a 52x32 track, a 14px thumb radius), and it is why `size_hint`
// describes the control without the drawn shape depending on the layout engine's
// answer.
//
// The values come from the shared `dimensions` table rather than being three
// independent literals. As literals they were `52`/`32`/`2` here and `50`/`28` in
// `size_hint` — four numbers describing one control, with nothing tying them
// together, so the hint and the ink could (and did) describe different switches.
// `ControlMetrics::center_in` is the shared derivation for "fixed-size chrome
// centred in the area I was given", and it clamps *down* rather than up: a control
// laid out smaller than the nominal track must not paint outside the rectangle it
// was given, since nothing clips a widget at this layer.
let track_rect = ControlMetrics::center_in(rect, self.geometry.track);
// The track's corner radius is half its height: a stadium. The thumb's own size and
// position come from `Switch::thumb_rect`, so the two derivations cannot disagree.
let track_height = track_rect.height;
// Draw track
//
// The track colour resolves **caller first, then the semantic token, then the
// literal**. The rung that used to sit here — the theme's *resolved* background —
// was dead code: `switch` classifies as `WidgetRole::Choice`, and `role_colors` in
// `src/theme/manager.rs` writes `Some(input_background())` into that role's
// background unconditionally. So `themed_background` was always `Some`, and the
// accent rung below it (the `Success` token, which is what makes an ON switch
// *green*) could never be reached: every switch drew the theme's field grey, and
// `switch.svg` showed a grey track for both the ON and the OFF state.
//
// `theme_derived` is what separates the two things that `background_color` was
// conflating. When the theme authored the style the value belongs to the theme,
// not the caller, and the control is free to substitute a more meaningful token;
// when the caller set a colour it must win. Same rule, and the same mechanism, as
// `banner.rs`.
let theme = crate::style::resolved_theme_style("switch");
let caller_background = if style.theme_derived { None } else { style.background_color };
// A stripped device build has no theme module, so the semantic token cannot be read
// and the literal below is the only rung. `#[cfg]` on the binding rather than on the
// call keeps the binding's type identical in both profiles.
#[cfg(device_profile)]
let themed_accent = crate::style::semantic_color(crate::style::SemanticColor::Success);
#[cfg(not(device_profile))]
let themed_accent: Option<Color> = None;
// The OFF track is *chrome*, so it descends from the theme's own resolved
// background — the field grey `Choice` resolves to — stepping one shade toward the
// ink when that colour would be the window's own fill. A track painted in the
// window colour is invisible against the surface the switch sits on.
#[cfg(device_profile)]
let themed_track = caller_background
.or_else(|| theme.as_ref().and_then(|resolved| resolved.background_color))
.map(|background| {
let window = crate::style::theme_manager()
.current_theme()
.map(|active| active.colors.background);
if window == Some(background) {
let ink = crate::style::theme_manager()
.current_theme()
.map(|active| active.colors.foreground)
.unwrap_or(Color::BLACK);
background.blend(&ink, 0.14)
} else {
background
}
});
#[cfg(not(device_profile))]
let themed_track = caller_background;
let off_track =
caller_background.or(themed_track).unwrap_or(Color::rgba(180, 180, 180, 200));
// The ON end resolves **caller-named colour first**, then the theme's accent. The
// literal is iOS's own on-tint, which is also what a stripped build falls back to.
let on_track = self.on_track.or(themed_accent).unwrap_or(Color::rgba(52, 199, 89, 200)); // iOS green
// The track's colour is a function of the *travel*, not of two discrete states.
// Blending the two endpoint colours by `travel.value()` is what makes the track
// change colour on the same frame as the thumb moves: a track that switched colour
// on `checked` while the thumb was still crossing would read as two separate
// actions, which is exactly the bug this control's `travel` exists to remove.
let travel = if is_enabled {
self.travel.value()
} else {
// A disabled switch shows its *logical* state at rest; there is no motion to
// follow, and leaving it at 0 would draw a grey track for a switch that is on.
if self.checked {
1.0
} else {
0.0
}
};
let track_color = if !is_enabled {
off_track.blend(&Color::rgba(200, 200, 200, 160), 1.0)
} else {
off_track.blend(&on_track, travel)
};
context.fill_rounded_rect(track_rect, track_height / 2, track_color);
// Draw thumb
//
// The thumb's x is derived from `travel.value()` and **not** from `checked`.
// Reading `checked` here is precisely the defect the transition exists to fix: the
// thumb would jump to the far end on the same frame the logical state changed, so
// the animation could never be seen and a "travelling" toggle was really a
// two-state image. `travel` is the crate's `visualPosition`.
let thumb_rect = match self.thumb_rect(rect) {
Some(thumb) => thumb,
None => return,
};
// The corner radius follows the thumb's own width, so a track too small for the
// nominal disc still draws a disc rather than a square: the size is read from the
// rectangle just derived, not recomputed here where it could disagree.
let thumb_radius = thumb_rect.width / 2;
let thumb_color = if !is_enabled {
Color::rgba(240, 240, 240, 200)
} else {
// The thumb reads the theme's foreground (a light thumb on a dark
// surface, a dark-ish thumb never — the thumb is always the lighter of
// the pair), falling back to white only when no theme is active.
theme
.as_ref()
.and_then(|resolved| resolved.text_color)
.map(|text| {
// Keep the thumb light: mix most of the way to white so it stays
// the highlight against the coloured track.
text.blend(&Color::WHITE, 0.85)
})
.unwrap_or(Color::WHITE)
};
// A hovered switch answers the pointer before it is pressed, so the thumb steps
// toward the ink: without it a switch that is under the cursor looks exactly like
// one that is not, which is the affordance the control was missing.
let thumb_color = if is_enabled && self.base.is_hovered() {
thumb_color.blend(&track_color.contrast_color(), 0.10)
} else {
thumb_color
};
context.fill_rounded_rect(thumb_rect, thumb_radius, thumb_color);
// Draw thumb shadow/border
let thumb_border_color = style.border_color.unwrap_or(Color::rgba(0, 0, 0, 30));
context.draw_rounded_rect_stroke(thumb_rect, thumb_radius, thumb_border_color, 1);
// ── Focus ring ──
//
// Drawn strictly inside the control's rectangle (see `ControlMetrics::focus_ring_rect`)
// and only when the *reason* focus arrived warrants it: a pointer press focuses without
// drawing a ring, Tab and Shortcut draw one. The reason is recorded by [`BaseWidget`] for
// every control, which is why the answer cannot differ between controls.
if self.visual_focus() {
let ring = FocusRing::for_control(rect, self.geometry.thumb_radius);
if ring.is_drawable() {
// The ring's colour is the contrast of the track it sits beside, so it reads
// on both the on and the off state rather than on one of them.
context.draw_rounded_rect_stroke(
ring.rect,
ring.radius,
focus_ring_color(track_color.contrast_color()),
FOCUS_RING_WIDTH,
);
}
}
}
}
impl EventHandler for Switch {
/// Toggles on a completed activation, not on a bare release.
///
/// # Why the press arm is load-bearing
///
/// This handler used to be `Event::MouseRelease => self.toggle()` with the position
/// discarded and no press tracking. Any release the host routed here flipped the
/// switch — including a drag that began outside it and merely ended on top, and
/// (since the control never takes pointer capture) any release a host delivered
/// without a preceding press inside the control.
///
/// [`Button`](crate::widget::base_widgets::button) and
/// [`CheckBox`](crate::widget::base_widgets::checkbox) both arm on
/// `MousePress`, which is the pattern the rest of the crate's binary controls
/// follow; a switch is the same interaction and now behaves identically. Touch,
/// `Tap` and the space bar are accepted for the same reason they are there:
/// the control is otherwise unreachable from a touch host or a keyboard.
fn handle_event(&mut self, event: &Event) {
self.base.handle_event(event);
let enabled = self.base.is_enabled();
match event {
Event::MousePress { pos, button: 1 } if enabled => {
// Arm only for a press that actually lands on the control; a press
// outside must not leave the latch armed for a later release.
self.pressed = self.base.contains_point_with_touch_expansion(*pos);
}
Event::MouseRelease { pos, button: 1 } if self.pressed => {
self.pressed = false;
// A release off the control cancels, matching the platform convention
// that dragging away from a toggle abandons the interaction.
if self.base.contains_point_with_touch_expansion(*pos) {
self.toggle();
}
}
Event::MouseRelease { button: 1, .. } => {
self.pressed = false;
}
#[cfg(feature = "touch")]
Event::TouchBegin { pos, .. } if enabled => {
self.pressed = self.base.contains_point_with_touch_expansion(*pos);
}
#[cfg(feature = "touch")]
Event::TouchEnd { pos, .. } if self.pressed => {
self.pressed = false;
if self.base.contains_point_with_touch_expansion(*pos) {
self.toggle();
}
}
#[cfg(feature = "touch")]
Event::Tap { .. } if enabled => {
self.toggle();
}
Event::KeyPress { key, .. } if *key == 32 && enabled => {
self.toggle();
}
// Focus entry carries the *reason*, and the reason is what decides whether a
// focus ring is painted; storing only a bool would make a click and a Tab
// indistinguishable and the ring would appear on click, which reads as a stuck
// highlight under the cursor. The base records it for every control.
Event::FocusGained { .. } => {
self.base.request_redraw();
}
// Focus loss abandons a held press, so the latch cannot survive a
// window switch and fire on an unrelated later release — and it also drops
// the ring, because the control is no longer the keyboard's target.
Event::FocusLost => {
self.pressed = false;
self.base.request_redraw();
}
Event::MouseEnter { .. } => {
self.set_hovered(true);
}
Event::MouseLeave { .. } => {
self.set_hovered(false);
}
_ => {}
}
}
}
#[cfg(all(test, full_widgets))]
mod tests {
use super::*;
use crate::core::Point;
use std::sync::{Arc, Mutex};
#[test]
fn switch_default_is_unchecked() {
let sw = Switch::new(Rect::new(0, 0, 60, 30));
assert!(!sw.is_checked());
assert_eq!(sw.kind(), WidgetKind::Switch);
}
#[test]
fn switch_set_checked_emits_signal() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
let captured = Arc::new(Mutex::new(None));
sw.toggled.connect({
let captured = Arc::clone(&captured);
move |val: Arc<bool>| {
*captured.lock().unwrap() = Some(*val);
}
});
sw.set_checked(true);
assert!(sw.is_checked());
assert_eq!(*captured.lock().unwrap(), Some(true));
}
#[test]
fn switch_toggle_flips_state() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
assert!(!sw.is_checked());
sw.toggle();
assert!(sw.is_checked());
sw.toggle();
assert!(!sw.is_checked());
}
/// A completed pointer activation toggles the switch.
///
/// The test used to dispatch a bare `MouseRelease`, which meant it asserted the
/// *defect*: the release position was discarded and no press was required, so any
/// release the host routed here flipped the control. The intent — "a pointer
/// activation toggles" — is unchanged; only the interaction it performs is now
/// the real one. The negative cases live in
/// `switch_release_without_press_does_not_toggle` and
/// `switch_press_outside_then_release_inside_does_not_toggle`.
#[test]
fn switch_mouse_press_toggles() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
let p = Point::new(10, 10);
sw.handle_event(&Event::MousePress { pos: p, button: 1 });
sw.handle_event(&Event::MouseRelease { pos: p, button: 1 });
assert!(sw.is_checked());
}
/// A release with no qualifying press must not toggle.
///
/// Reproduces the reported defect: the old handler toggled on *any* release, so a
/// bare `MouseRelease` — including one at a position far outside the geometry —
/// flipped the switch.
#[test]
fn switch_release_without_press_does_not_toggle() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
sw.handle_event(&Event::MouseRelease { pos: Point::new(10, 10), button: 1 });
assert!(!sw.is_checked(), "a release with no press must not toggle");
// The original reproduction: a release nowhere near the control.
sw.handle_event(&Event::MouseRelease { pos: Point::new(5000, 5000), button: 1 });
assert!(!sw.is_checked(), "a release far outside the geometry must not toggle");
}
/// A press outside the control must not arm the latch for a later release.
#[test]
fn switch_press_outside_then_release_inside_does_not_toggle() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
sw.handle_event(&Event::MousePress { pos: Point::new(5000, 5000), button: 1 });
sw.handle_event(&Event::MouseRelease { pos: Point::new(10, 10), button: 1 });
assert!(!sw.is_checked(), "a drag that began outside must not commit");
}
/// Pressing inside and releasing outside cancels, as it does for `Button`.
#[test]
fn switch_press_inside_then_release_outside_cancels() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
sw.handle_event(&Event::MousePress { pos: Point::new(10, 10), button: 1 });
sw.handle_event(&Event::MouseRelease { pos: Point::new(500, 500), button: 1 });
assert!(!sw.is_checked());
// The latch must also be clear, so the *next* stray release does not fire.
sw.handle_event(&Event::MouseRelease { pos: Point::new(10, 10), button: 1 });
assert!(!sw.is_checked(), "the cancelled press must not stay armed");
}
/// Losing focus abandons a held press.
#[test]
fn switch_focus_loss_cancels_a_held_press() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
sw.handle_event(&Event::MousePress { pos: Point::new(10, 10), button: 1 });
assert!(sw.is_pressed());
sw.handle_event(&Event::FocusLost);
assert!(!sw.is_pressed());
sw.handle_event(&Event::MouseRelease { pos: Point::new(10, 10), button: 1 });
assert!(!sw.is_checked());
}
/// The space bar toggles, matching `CheckBox`.
#[test]
fn switch_space_bar_toggles() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
sw.handle_event(&Event::KeyPress { key: 32, modifiers: 0 });
assert!(sw.is_checked());
}
#[test]
fn switch_disabled_blocks_events() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
sw.set_enabled(false);
sw.handle_event(&Event::MousePress { pos: Point::new(10, 10), button: 1 });
assert!(!sw.is_checked());
}
#[cfg(not(alloc_frugal))]
#[test]
fn switch_svg_output() {
let mut sw = Switch::new(Rect::new(0, 0, 60, 30));
let svg = crate::widget::svg::render_to_svg(&mut sw);
assert!(svg.starts_with("<svg"));
}
/// BLUE23 §3.3, judgement 3 — the thumb's geometry is distinct across frames and moves
/// monotonically. This is the plan's shared "three-frame" criterion: an animation cannot
/// be proved with one frame, only with the *difference* between frames.
#[test]
fn the_travel_takes_the_thumb_across_distinct_positions() {
let rect = crate::widget::census::CENSUS_RECT;
let mut sw = Switch::new(rect);
let at_rest = sw.thumb_rect(rect).expect("censused switch has a thumb").x;
sw.set_checked(true);
// Sample before any tick, then after two even steps of the travel.
let before = sw.thumb_rect(rect).expect("thumb").x;
assert_eq!(before, at_rest, "a state change alone must not teleport the thumb");
assert!(sw.tick(80), "the travel is still running after one step");
let mid = sw.thumb_rect(rect).expect("thumb").x;
// Drain the rest of the travel so the end position is sampled at rest.
let mut guard = 0;
while sw.tick(80) {
guard += 1;
assert!(guard < 100, "the travel must settle");
}
let end = sw.thumb_rect(rect).expect("thumb").x;
assert_ne!(mid, before, "the first frame must move the thumb");
assert_ne!(end, mid, "the last frame must reach a new position");
assert!(
before < mid && mid < end,
"the thumb must advance monotonically: {before}/{mid}/{end}"
);
}
/// The logical state and the drawn state are **two different facts**.
///
/// `checked` is what a caller reads after a click and must change the instant the
/// click lands; the thumb's position is a presentation that lags behind it. Drawing
/// the thumb from `checked` is the defect this pins against: the thumb jumped to the
/// far end on the same frame as the state change, so the travel could never be seen
/// and the "animation" was really a two-state image.
#[test]
fn the_logical_state_changes_before_the_thumb_arrives() {
let mut sw = Switch::new(crate::widget::census::CENSUS_RECT);
assert_eq!(sw.travel_progress(), 0.0, "a fresh switch is at the off end");
sw.toggle();
// The logical answer is immediate…
assert!(sw.is_checked(), "the caller must see the new state at once");
// …while the thumb has not moved yet, because no frame has been delivered.
assert_eq!(
sw.travel_progress(),
0.0,
"the thumb must not teleport to the far end on the frame the state changed"
);
}
/// Ticking moves the thumb toward the logical state and then **settles**.
///
/// The boolean return is the contract a host schedules frames from: `true` while
/// there is movement, `false` once there is none. A `tick` that always reported work
/// would keep the whole application repainting forever, so the settle case is half of
/// what this pins. A single long frame must arrive exactly, not approach forever.
#[test]
fn ticking_moves_the_thumb_toward_the_logical_state_and_settles() {
let mut sw = Switch::new(crate::widget::census::CENSUS_RECT);
sw.toggle();
// A short frame leaves the travel in flight and reports more work owed.
assert!(sw.tick(30), "a toggle must start a transition");
let partway = sw.travel_progress();
assert!(partway > 0.0 && partway < 1.0, "the thumb is mid-travel: {partway}");
// Ticking well past the theme's slow tempo lands it exactly…
while sw.tick(1000) {}
assert_eq!(sw.travel_progress(), 1.0, "the travel reaches its target exactly");
// …and then reports that there is nothing left to do.
assert!(!sw.tick(1000), "a settled switch owes no more frames");
// The reverse journey settles the same way.
sw.toggle();
while sw.tick(1000) {}
assert_eq!(sw.travel_progress(), 0.0);
assert!(!sw.tick(1000));
}
/// A freshly built switch must be at the **off end** of its travel, not the on end.
///
/// A transition that started at the interactive end of its range would make every new
/// switch fade *out* on its first frame — and, since the OFF track is drawn from the
/// travel, it would flash the ON colour before settling grey.
#[test]
fn a_freshly_built_switch_is_at_the_off_end_of_its_travel() {
let sw = Switch::new(crate::widget::census::CENSUS_RECT);
assert!(!sw.is_checked());
assert_eq!(sw.travel_progress(), 0.0);
}
/// A reversal mid-flight **re-aims from where the thumb is**, it does not restart.
///
/// The target is recomputed from the control's own state on every tick, so toggling
/// back while the thumb is still crossing turns it around from its current position.
/// Re-aiming is what makes a quick on-off read as one movement; restarting from the
/// far end would make the same gesture read as two fades.
#[test]
fn a_transition_in_flight_re_aims_rather_than_restarting() {
let mut sw = Switch::new(crate::widget::census::CENSUS_RECT);
sw.toggle();
sw.tick(50);
let forward = sw.travel_progress();
assert!(forward > 0.0 && forward < 1.0, "the toggle is in flight: {forward}");
// Reverse while the thumb is still travelling toward the on end.
sw.toggle();
assert!(!sw.is_checked());
// The reverse journey must start from where the thumb is, so the first frame of it
// is still *above* zero rather than having snapped back to the off end.
sw.tick(1);
let reversing = sw.travel_progress();
assert!(
reversing < forward,
"the thumb turns around instead of continuing: {reversing} < {forward}"
);
assert!(reversing > 0.0, "the reversal starts from the current position: {reversing}");
// And it settles back at the off end rather than oscillating.
while sw.tick(1000) {}
assert_eq!(sw.travel_progress(), 0.0);
}
/// Visual focus depends on the **reason** focus arrived, not merely on having it.
///
/// A pointer press focuses the control — it is the keyboard's target from then on —
/// but drawing a ring under the cursor reads as a stuck highlight, so only the
/// keyboard reasons draw one. This is the standard rule for visual focus, and the
/// reason the control stores a
/// `FocusReason` rather than a bare bool.
#[test]
fn switch_visual_focus_depends_on_the_reason() {
let mut sw = Switch::new(crate::widget::census::CENSUS_RECT);
sw.handle_event(&Event::FocusGained { reason: FocusReason::Pointer });
assert!(sw.is_focused(), "the control is the keyboard target");
assert!(!sw.visual_focus(), "but the user is on the pointer, so no ring is drawn");
for reason in [FocusReason::Tab, FocusReason::BackTab, FocusReason::Shortcut] {
let mut sw = Switch::new(crate::widget::census::CENSUS_RECT);
sw.handle_event(&Event::FocusGained { reason });
assert!(sw.is_focused());
assert!(sw.visual_focus(), "{reason:?} must draw the ring");
}
sw.handle_event(&Event::FocusLost);
assert!(!sw.is_focused());
assert!(!sw.visual_focus());
}
/// Hover is tracked from the pointer entering and leaving the control.
///
/// The control had no hover state at all, so a switch under the cursor looked
/// identical to one that was not — the affordance was simply missing. Both directions
/// are pinned: entering sets the flag and leaving clears it.
#[test]
fn switch_tracks_hover() {
let mut sw = Switch::new(crate::widget::census::CENSUS_RECT);
assert!(!sw.is_hovered(), "a fresh switch is not hovered");
sw.handle_event(&Event::MouseEnter { pos: Point::new(10, 10) });
assert!(sw.is_hovered());
sw.handle_event(&Event::MouseLeave { pos: Point::new(10, 10) });
assert!(!sw.is_hovered());
// The host-facing setter is the same fact, for a backend with no hover event.
sw.set_hovered(true);
assert!(sw.is_hovered());
}
/// An on switch reports `Checked`, so the preset's `switch:checked` key is reachable.
///
/// The same defect `CheckBox::widget_state` documents: the trait default knows the four
/// primitive flags and none of them means "latched", so the key resolved to `Normal` and the
/// accent fill the preset asks for was never painted. A switch is the most visible case — its
/// whole meaning is the position it reports.
#[test]
fn widget_state_reports_checked_for_an_on_switch() {
use crate::style::WidgetState;
let mut sw = Switch::new(crate::core::Rect::new(0, 0, 60, 30));
assert_eq!(sw.widget_state(), WidgetState::Normal);
sw.set_checked(true);
assert_eq!(sw.widget_state(), WidgetState::Checked);
sw.handle_event(&Event::MouseEnter { pos: Point::new(1, 1) });
assert_eq!(sw.widget_state(), WidgetState::Checked, "the latch outranks a hover");
sw.set_enabled(false);
assert_eq!(sw.widget_state(), WidgetState::Disabled, "disabled outranks the latch");
}
}