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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Roller widget — scroll-wheel style selector (BLUE13 R2.3).
//!
//! Displays a scroll-wheel list of options where one item is highlighted in the
//! center. Supports mouse wheel scrolling and click-to-select interaction.
use crate::compat::{String, Vec};
use crate::core::{Color, Font, HorizontalAlignment, Rect, Size};
use crate::event::{key_codes, Event, EventHandler, WheelScroll};
use crate::render::RenderContext;
use crate::signal::GenericSignal;
use crate::style::{MotionCurve, MotionSlot, PropertyDriver, SpringPreset};
use crate::widget::capability::coercion::{expect_string_list, expect_u32, expect_usize};
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::{dimensions, estimate_text_width, ControlMetrics};
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// Roller widget for selecting from a list via scroll-wheel interaction.
pub struct Roller {
base: BaseWidget,
/// List of option strings.
options: Vec<String>,
/// Currently selected index.
selected_index: usize,
/// Number of visible items (should be odd for symmetry).
visible_count: u32,
/// Font size for items.
font_size: f32,
/// Whether wheel and drag movement tween to the row target rather than jumping.
inertia: bool,
/// The drawn row position, in row units: `selected_index` while settled, and a
/// fractional row while a tween is running.
///
/// A driver rather than a bare float so the wheel slides rather than teleports, and so
/// the resting end is expressible: it is built exactly at index `0`, which is the row a
/// fresh roller shows.
scroll: PropertyDriver,
/// A pointer press that may become a drag: the press's y coordinate and the selection
/// it started from, in row terms.
drag_origin: Option<(i32, usize)>,
/// Signal emitted when selection changes.
pub changed_signal: GenericSignal,
}
impl Roller {
/// Creates a new `Roller` with the given options and geometry.
///
/// The initial selection is at index 0 and `visible_count` defaults to 5
/// (clamped to an odd value so the selected item sits in the center).
pub fn new(options: Vec<String>, rect: Rect) -> Self {
let visible_count = 5u32 | 1; // ensure odd, at least 3
Self {
base: BaseWidget::new(WidgetKind::Roller, rect, "Roller"),
options,
selected_index: 0,
visible_count,
font_size: 16.0,
inertia: false,
// A spring, not the easing curve: the driver's value is a **row index**, and the
// easing path normalises its target to `0.0..=1.0`, which would stop the wheel at
// the first row. The spring integrator works in the units it is given, so a row
// target of `3.0` is a real row.
scroll: PropertyDriver::with_curve(
0.0,
MotionSlot::Normal,
MotionCurve::Spring(SpringPreset::Settle),
),
drag_origin: None,
changed_signal: GenericSignal::new(),
}
}
/// Returns all option strings.
pub fn options(&self) -> &[String] {
&self.options
}
/// Replaces the option list and clamps the selected index to the new range.
pub fn set_options(&mut self, options: Vec<String>) {
self.options = options;
// The cached widths describe the replaced list, so they cannot be reused.
if !self.options.is_empty() {
self.selected_index = self.selected_index.min(self.options.len() - 1);
} else {
self.selected_index = 0;
}
// A replaced list is not a scroll: the wheel is placed at the surviving row rather
// than animating through options that no longer exist.
self.scroll.jump_to(self.selected_index as f32);
self.drag_origin = None;
self.changed_signal.emit();
self.base.request_redraw();
}
/// Returns the currently selected index.
pub fn selected_index(&self) -> Option<usize> {
self.options.get(self.selected_index).map(|_| self.selected_index)
}
/// Sets the selected index, clamped to the valid range.
///
/// Emits `changed_signal` only when the value actually changes. With inertia enabled the
/// *drawn* wheel tweens to the new row over the theme's motion token; without it the row
/// is placed immediately, which is the historical behaviour.
pub fn set_selected_index(&mut self, index: usize) {
let clamped = if self.options.is_empty() { 0 } else { index.min(self.options.len() - 1) };
if clamped != self.selected_index {
self.selected_index = clamped;
self.changed_signal.emit();
self.base.request_redraw();
}
if self.inertia {
self.scroll.set_target(self.selected_index as f32);
if crate::style::environment::environment().prefers_reduced_motion() {
self.scroll.jump_to(self.selected_index as f32);
}
} else {
self.scroll.jump_to(self.selected_index as f32);
}
}
/// Whether wheel and drag movement tween to the row target.
pub fn inertia(&self) -> bool {
self.inertia
}
/// Enables or disables the tween that carries the wheel to its target row.
///
/// Defaults to `false`, which is the historical behaviour: a wheel notch or a drag moves
/// the row immediately. When enabled, the wheel slides to the new row through
/// [`Roller::tick`], and the environment's reduced-motion preference collapses that slide
/// into a direct placement.
///
/// Switching inertia **off** lands the wheel on the selected row at once, so a picture
/// taken after the setter cannot show a tween that is no longer running.
pub fn set_inertia(&mut self, on: bool) {
if self.inertia == on {
return;
}
self.inertia = on;
if !on {
let target = self.selected_index as f32;
if (self.scroll.value() - target).abs() > f32::EPSILON {
self.scroll.jump_to(target);
self.base.request_redraw();
}
}
}
/// The drawn row position, in row units.
///
/// Exactly `selected_index` while the wheel is at rest; a fractional value between two
/// rows while an inertia tween is in flight. Exposed because it is the only way to assert
/// that the wheel slides rather than jumps.
pub fn visual_index(&self) -> f32 {
self.scroll.value()
}
/// Advances the wheel's inertia tween by `delta_ms`.
///
/// Returns `true` while the wheel is still travelling and `false` once it has settled.
/// With inertia disabled this is a still picture and owes nothing.
pub fn tick(&mut self, delta_ms: u32) -> bool {
if !self.inertia {
return false;
}
self.scroll.set_target(self.selected_index as f32);
self.scroll.tick(delta_ms)
}
/// Whether the wheel owes animation frames.
pub fn is_animating(&self) -> bool {
self.inertia && (self.scroll.value() - self.selected_index as f32).abs() > f32::EPSILON
}
/// Returns the text of the currently selected option, or `None` if the
/// options list is empty.
pub fn selected_text(&self) -> Option<&str> {
if self.selected_index < self.options.len() {
Some(self.options[self.selected_index].as_str())
} else {
None
}
}
/// Returns the number of visible items in the wheel.
pub fn visible_count(&self) -> u32 {
self.visible_count
}
/// Sets the number of visible items. The value is rounded up to the next
/// odd number (minimum 3) so that the selected item appears centered.
pub fn set_visible_count(&mut self, count: u32) {
let clamped = count.max(3);
let odd = if clamped.is_multiple_of(2) { clamped + 1 } else { clamped };
if odd != self.visible_count {
self.visible_count = odd;
self.base.request_redraw();
}
}
/// Sets the font size used to render option text.
pub fn set_font_size(&mut self, size: f32) {
let size = size.max(4.0);
if self.font_size == size {
return;
}
self.font_size = size;
self.base.request_redraw();
}
/// Returns the font size used to render option text.
pub fn font_size(&self) -> f32 {
self.font_size
}
/// The height of one row in the wheel.
///
/// # Why this is not a function of the control's rectangle
///
/// A row is a **fixed row**, like a picker's drum: the same control shows the same
/// row height in a short box and a tall one. Deriving it from `rect` — combined with
/// sizing the wheel from the same rectangle — made the census cell a 120 px surface
/// with one 24 px selection band in it, and made a wheel in a list slot a different
/// object from a wheel here. The base is [`dimensions::ROLLER_ROW_HEIGHT`], which is
/// the row the default 16 pt face needs; `font_size` still scales it, but as a
/// proportion of the type the control was told to draw, never of `rect`.
fn item_height(&self) -> u32 {
// The control's own default face, which is the type size `ROLLER_ROW_HEIGHT` was
// chosen for. Scaling from the *table's* base font instead made the default 16 pt
// face round 28 up to 32, so the drawn row disagreed with the named one on the one
// font size every default roller uses.
const DEFAULT_FONT_SIZE: f32 = 16.0;
// The row scales with the font the wheel actually **draws** with, not only with the
// caller-set `font_size`: `draw` prefers `style.font` when the theme or caller set one, so
// measuring the row from `font_size` alone let a styled font overflow its own row and be
// clipped by the wheel band (D09-STYLE-02).
let drawn_size = self.wheel_font().size();
if drawn_size <= DEFAULT_FONT_SIZE {
return dimensions::ROLLER_ROW_HEIGHT;
}
// A caller with a larger font gets a proportionally larger row. The base is the
// named row at the named font, and never `rect`: the two are unrelated facts.
// `font_size` is clamped to `>= 4.0` by the setter, so the divisor is never zero.
let scaled =
(drawn_size / DEFAULT_FONT_SIZE * dimensions::ROLLER_ROW_HEIGHT as f32).round() as u32;
scaled.max(dimensions::ROLLER_ROW_HEIGHT)
}
/// The font the wheel draws its rows with: the resolved `style.font` when set, otherwise the
/// caller-set `font_size` in the crate's default sans-serif face.
///
/// This is the same choice `draw` makes, named once so `size_hint` and `item_height` cannot
/// describe a different control from the one painted (D09-STYLE-02).
///
/// The fallback is constructed, not borrowed from a global default: the wheel's own
/// `font_size` decides the drawn size when no style font is set. Going through
/// `effective_font` here made `item_height` and `size_hint` measure the global default
/// face while `draw` painted `font_size` — a `set_font_size(24)` wheel drew 24 pt rows
/// inside a row height scaled for 16 pt and clipped them.
fn wheel_font(&self) -> Font {
self.base.style().font.clone().unwrap_or_else(|| Font::simple("sans-serif", self.font_size))
}
/// Measures every option once per face, scale and list, so the draw pass does not
/// repeat the same `measure_text` for each visible row every frame.
/// The total content height for all visible items.
///
/// Fixed at [`dimensions::ROLLER_WHEEL_HEIGHT`] for the default wheel — five rows —
/// rather than derived from the *current* row height, because the wheel's extent is
/// a chrome fact: a caller who changes the font changes the row's density inside the
/// wheel, not how tall the wheel is. Deriving it from `item_height()` coupled the
/// control's box to the type size, which is the same drift that made the drawn wheel
/// disagree with the height `size_hint` reported.
fn content_height(&self) -> u32 {
dimensions::ROLLER_WHEEL_HEIGHT * self.visible_count / dimensions::ROLLER_VISIBLE_ROWS
}
/// The band the wheel actually occupies: full width, its own height, centred.
///
/// # Why the wheel has its own height
///
/// A roller paints a **wheel of rows**, not a surface. The control used to fill its
/// whole rectangle (`fill_rect(rect, bg_color)`) and lay its items out around the
/// rectangle's middle, so the 240x120 census cell drew a 240x120 fill with a single
/// 24 px selection band at y 48 — a panel with one row in it rather than a wheel.
/// [`dimensions::ROLLER_WHEEL_HEIGHT`] is the wheel's own extent —
/// [`dimensions::ROLLER_VISIBLE_ROWS`] rows — and the shared
/// [`ControlMetrics::full_width_band`] centres it, so a wheel in a list slot and a
/// wheel in a census cell are the same object. When the caller's rectangle is
/// *shorter* than the wheel the band is clamped to it rather than painted outside,
/// which is the one case where the control legitimately fills its rectangle.
fn wheel_band(&self) -> Rect {
ControlMetrics::full_width_band(self.geometry(), dimensions::ROLLER_WHEEL_HEIGHT)
}
}
impl Widget for Roller {
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) -> Size {
// Estimate width from the longest option string, measured with the **effective font**
// through the shared estimate rather than a per-character `font_size * 0.6` guess: the
// drawn font may come from `style.font`, and a `len()` byte count over-measures non-ASCII
// (D09-STYLE-02).
let font = self.wheel_font();
let width = self
.options
.iter()
.map(|s| estimate_text_width(s, &font, 1.0))
.max()
.unwrap_or(80)
.max(80);
// The height is the wheel's own band, which `wheel_band` draws from, so the two
// cannot describe different controls: this is the `content_height` the control
// has always reported, now also the height it paints at.
Size::new(width, self.content_height())
}
/// One frame of the wheel's inertia tween.
fn tick(&mut self, delta_ms: u32) -> bool {
Roller::tick(self, delta_ms)
}
/// The wheel owes frames while it is still travelling.
fn is_animating(&self) -> bool {
Roller::is_animating(self)
}
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 {
"changed" => Some(EventSignalRef::unit("changed", &self.changed_signal)),
_ => None,
}
}
}
/// `Roller`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch.
impl WidgetProperties for Roller {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"selected_index" => {
Ok(CapabilityValue::UInt(self.selected_index().unwrap_or(0) as u64))
}
"visible_count" => Ok(CapabilityValue::UInt(self.visible_count() as u64)),
"item_count" => Ok(CapabilityValue::UInt(self.options().len() as u64)),
"options" => Ok(CapabilityValue::Tuple(
self.options().iter().map(|item| CapabilityValue::String(item.clone())).collect(),
)),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"selected_index" => {
self.set_selected_index(expect_usize(value)?);
Ok(())
}
"visible_count" => {
self.set_visible_count(expect_u32(value)?);
Ok(())
}
"item_count" => Err(CapabilityAccessError::ReadOnlyProperty),
"options" => {
self.set_options(expect_string_list(value)?);
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
property_names_of![
"options",
"selected_index",
"visible_count",
"item_count",
BASE_PROPERTY_NAMES
]
}
/// Runs one of the commands `roller` publishes.
///
/// All three assign state — the option list, the selected row and the number of
/// rows on screen — and each needs a payload, so the whole set is answered through
/// the property route rather than performed here.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"set_options" | "set_selected_index" | "set_visible_count" => {
Err(CapabilityAccessError::OutOfRange)
}
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
impl EventHandler for Roller {
fn handle_event(&mut self, event: &Event) {
self.base.handle_event(event);
if !self.base.is_enabled() || self.options.is_empty() {
return;
}
match event {
// Wheel / scroll: one notch is one option. A positive delta moves the
// content down and advances to the next option; a negative delta moves
// back. `set_selected_index` clamps at both ends.
Event::Wheel { delta, modifiers } => {
let scroll = WheelScroll::from_event(*delta, *modifiers, 1);
if scroll.lines_y != 0 {
let last = self.options.len().saturating_sub(1);
let next = (self.selected_index as i64 + scroll.lines_y as i64)
.clamp(0, last as i64) as usize;
self.set_selected_index(next);
}
}
// The wheel is keyboard-reachable through the same `set_selected_index` path the
// wheel notch and the drag use, so the inertia tween applies to all three.
Event::KeyPress { key, .. } => {
let last = self.options.len().saturating_sub(1);
let page = self.visible_count.max(1) as i64;
let target = match *key {
key_codes::UP => self.selected_index as i64 - 1,
key_codes::DOWN => self.selected_index as i64 + 1,
key_codes::PAGE_UP => self.selected_index as i64 - page,
key_codes::PAGE_DOWN => self.selected_index as i64 + page,
key_codes::HOME => 0,
key_codes::END => last as i64,
_ => return,
};
self.set_selected_index(target.clamp(0, last as i64) as usize);
}
// Mouse press: determine which item was clicked relative to the
// center of the visible wheel.
Event::MousePress { pos, .. } => {
let band = self.wheel_band();
let item_h = self.item_height() as i32;
let center_y = band.y + (band.height as i32) / 2;
let clicked_offset = pos.y - center_y;
// A press outside the wheel band selects nothing: the hit test is the
// **drawn** band, so the clickable rows and the painted rows are the same
// object. Reading the control's own rectangle here (as the old form did)
// made the empty space above and below the wheel live.
if pos.y < band.y || pos.y >= band.y + band.height as i32 {
return;
}
let half_visible = (self.visible_count / 2) as i32;
// Clamp the row offset to the visible range.
let row_offset = (clicked_offset / item_h).clamp(-half_visible, half_visible);
if row_offset == 0 {
// Clicked the center item — fire clicked signal.
self.base.clicked.emit();
} else {
let target = self.selected_index as i32 + row_offset;
let target =
target.clamp(0, self.options.len().saturating_sub(1) as i32) as usize;
self.set_selected_index(target);
}
// The press is also the anchor for a drag. The selection the press landed on
// is the origin, so the dragged distance is measured from what the user
// grabbed rather than from wherever a previous gesture ended.
self.drag_origin = Some((pos.y, self.selected_index));
}
// A drag moves the selection by the distance the pointer has travelled, in rows:
// dragging up walks the wheel toward later options, dragging down toward earlier
// ones. `set_selected_index` owns the tween (or the immediate placement) so a
// drag and a wheel notch take the same path.
Event::MouseMove { pos } => {
if let Some((origin_y, origin_index)) = self.drag_origin {
let item_h = self.item_height().max(1) as f32;
let rows = (origin_y - pos.y) as f32 / item_h;
let last = self.options.len().saturating_sub(1) as i64;
let target =
(origin_index as i64 + rows.round() as i64).clamp(0, last) as usize;
self.set_selected_index(target);
}
}
Event::MouseRelease { .. } => {
self.drag_origin = None;
}
Event::MouseLeave { .. } => {
// A release delivered outside the control never reaches this widget, so a
// departed pointer must abandon the drag rather than leave it armed.
self.drag_origin = None;
}
#[cfg(feature = "touch")]
Event::Tap { pos: _ } => {
self.base.clicked.emit();
}
_ => { /* Other events are not relevant */ }
}
}
}
impl Draw for Roller {
fn draw(&mut self, context: &mut RenderContext) {
let rect = self.geometry();
if rect.width == 0 || rect.height == 0 || self.options.is_empty() {
return;
}
// Chrome colours resolve explicit style first, then the theme's resolved
// style for this control, and only then a literal. The theme step is what
// makes an appearance switch visible; previously every colour below was a
// hardcoded literal, so light and dark rendered identically.
//
// `resolved_theme_style` takes and releases the global manager's lock
// internally, so no guard is held across the draw (the mutex is not
// re-entrant).
let style = self.base.style();
let theme = crate::style::resolved_theme_style_shared("roller")
.or_else(|| crate::style::resolved_theme_style_shared("list_box"));
// `roller` is not a control kind in the role table, so it classifies as
// `Surface`, whose background is `theme.colors.background` — byte-identical
// to the window behind it. The wheel's own fill is therefore a step toward the
// foreground, so it reads as a recessed surface of its own.
let resolved = style
.background_color
.or_else(|| theme.as_ref().and_then(|t| t.background_color))
.unwrap_or(Color::rgb(240, 240, 240));
let text_color = style
.text_color
.or_else(|| theme.as_ref().and_then(|t| t.text_color))
.unwrap_or(Color::rgb(50, 50, 50));
let bg_color = resolved.blend(&text_color, 0.08);
// The centre item is a *selection*, which is chrome rather than data, so it
// reads the theme's primary token instead of the previous literal blue.
let selected_bg = crate::style::resolved_theme_style_shared("button")
.and_then(|button| button.background_color)
.unwrap_or_else(|| bg_color.blend(&text_color, 0.6));
// Its label must be legible **on the selection band itself**, so it takes whichever
// of black/white contrasts with that band. The previous form blended the label 92% of
// the way toward the wheel's own surface, which is a light-theme assumption baked into
// arithmetic: on the light theme the band resolves to the theme's primary
// `rgb(33,150,243)` while the surface is `rgb(221,221,221)`, so the label came out
// `rgb(206,215,223)` — 2.14:1 against the band it sits on (below the 3:1 large-text
// floor, let alone the 4.5:1 body floor). Same rule as the theme's `Primary` role.
let selected_text_color = selected_bg.contrast_color();
let muted_color = text_color.blend(&bg_color, 0.47);
// One source of truth for the drawn face (`wheel_font`): the inline choice here
// could drift from the one `item_height` and `size_hint` measure with.
let font = self.wheel_font();
// `item_height` derives its row from the same font, so the wheel band cannot clip the
// glyphs it draws (D09-STYLE-02).
// The wheel actually painted ──
//
// `rect` is the area the control was *given*; a wheel's own chrome is its rows,
// `visible_count` of them at `ROLLER_ROW_HEIGHT` each. The band is the single
// derivation the surface fill, the selection band, every row and the hit test are
// placed from, so none of them can disagree about where the wheel is.
let band = self.wheel_band();
let item_h = self.item_height() as i32;
let half_visible = (self.visible_count / 2) as usize;
let center_y = band.y + (band.height as i32) / 2;
// Draw a background fill for the wheel's own band, not for the whole control.
context.fill_rect(band, bg_color);
// Clipping region to ensure items don't spill outside the wheel.
context.push_clip(band.x, band.y, band.width, band.height);
// How far the wheel has slid away from the selected row, in rows. Exactly zero while
// the inertia tween is at rest, so the default picture is untouched; fractional while
// a tween is in flight. The whole wheel is shifted by it, which is what makes the rows
// read as one surface moving rather than as labels being replaced.
let slide_rows = self.scroll.value() - self.selected_index as f32;
let slide = -(slide_rows * item_h as f32) as i32;
// One extra row on each side while sliding, so the band never shows a gap where the
// next row has not reached the clip edge yet. A resting wheel asks for the same rows
// it always did.
let extra = if slide_rows.abs() > f32::EPSILON { 1 } else { 0 };
// The selection band is fixed chrome: the rows slide *through* it. Drawing it at the
// moving row's position instead would make the highlight chase the text during a tween.
let highlight_rect = Rect::new(band.x, center_y - item_h / 2, band.width, item_h as u32);
// Draw each visible item around the center.
for offset in 0..=half_visible + extra {
for &sign in &[1i32, -1i32] {
if offset == 0 && sign == -1 {
continue; // center item only once
}
let idx = self.selected_index as i32 + sign * offset as i32;
if idx < 0 || idx >= self.options.len() as i32 {
continue;
}
let idx = idx as usize;
let y = center_y + sign * offset as i32 * item_h + slide;
let item_rect = Rect::new(band.x, y - item_h / 2, band.width, item_h as u32);
let is_selected = offset == 0;
if is_selected {
// Highlight the selected item in the center.
context.fill_rect(highlight_rect, selected_bg);
}
let color = if is_selected {
selected_text_color
} else {
// Items farther from center are more muted.
let fade = 1.0 - (offset as f32 / (half_visible.max(1)) as f32) * 0.5;
Color::rgba(
(muted_color.r as f32 * fade) as u8,
(muted_color.g as f32 * fade) as u8,
(muted_color.b as f32 * fade) as u8,
muted_color.a,
)
};
// Bounded text: a long option is fitted with an ellipsis inside the wheel band
// rather than cut at an arbitrary glyph by the clip. The same rule the tag's
// label uses, and the same for the selected row and its neighbours.
let text_band = Rect::new(
item_rect.x + 6,
item_rect.y,
item_rect.width.saturating_sub(12),
item_rect.height,
);
context.draw_text_line(
text_band,
&self.options[idx],
&font,
color,
HorizontalAlignment::Center,
);
}
}
context.pop_clip();
}
}
#[cfg(all(test, full_widgets))]
mod tests {
use super::*;
use crate::compat::MiniToString;
use crate::core::{Point, Size};
use crate::render::{PaintBackend, SoftwarePaintBackend};
fn make_roller() -> Roller {
let options = vec![
"Apple".to_string(),
"Banana".to_string(),
"Cherry".to_string(),
"Dragonfruit".to_string(),
"Elderberry".to_string(),
];
Roller::new(options, Rect::new(0, 0, 160, 120))
}
#[test]
fn options_property_round_trips_the_option_list() {
let mut roller = Roller::new(vec!["one".to_string()], Rect::new(0, 0, 160, 120));
let written = CapabilityValue::Tuple(vec![
CapabilityValue::String("Red".to_string()),
CapabilityValue::String("Green".to_string()),
CapabilityValue::String("Red".to_string()),
]);
roller.set("options", written).expect("options is writable");
assert_eq!(roller.options().len(), 3);
match roller.get("options").expect("options is readable") {
CapabilityValue::Tuple(items) => {
let texts: Vec<&str> = items.iter().filter_map(|value| value.as_str()).collect();
assert_eq!(texts, vec!["Red", "Green", "Red"]);
}
other => panic!("options should read back as a Tuple, got {other:?}"),
}
assert_eq!(
roller.set("options", CapabilityValue::UInt(3)),
Err(CapabilityAccessError::TypeMismatch)
);
}
#[test]
fn roller_creation_defaults() {
let roller = make_roller();
assert_eq!(roller.options.len(), 5);
assert_eq!(roller.selected_index().unwrap_or(0), 0);
assert_eq!(roller.selected_text(), Some("Apple"));
assert!(roller.visible_count() >= 3);
assert!(roller.visible_count() % 2 == 1);
assert_eq!(roller.kind(), WidgetKind::Roller);
}
#[test]
fn roller_set_selected_index() {
let mut roller = make_roller();
assert_eq!(roller.selected_index().unwrap_or(0), 0);
roller.set_selected_index(2);
assert_eq!(roller.selected_index().unwrap_or(0), 2);
assert_eq!(roller.selected_text(), Some("Cherry"));
// Clamp above max.
roller.set_selected_index(100);
assert_eq!(roller.selected_index().unwrap_or(0), 4);
assert_eq!(roller.selected_text(), Some("Elderberry"));
}
/// The canonical getter reports `None` until there is something to select (WDGT-13).
#[test]
fn selected_index_is_none_for_an_empty_roller() {
let empty = Roller::new(Vec::new(), Rect::new(0, 0, 100, 100));
assert_eq!(empty.selected_index(), None);
let filled = Roller::new(vec!["a".to_string()], Rect::new(0, 0, 100, 100));
assert_eq!(filled.selected_index(), Some(0));
}
#[test]
fn roller_selected_text() {
let mut roller = make_roller();
assert_eq!(roller.selected_text(), Some("Apple"));
roller.set_selected_index(3);
assert_eq!(roller.selected_text(), Some("Dragonfruit"));
// Empty options → no selected text.
let empty: Roller = Roller::new(Vec::new(), Rect::new(0, 0, 100, 100));
assert!(empty.selected_text().is_none());
}
#[test]
fn roller_mouse_wheel_changes_selection() {
let mut roller = make_roller();
assert_eq!(roller.selected_index().unwrap_or(0), 0);
// Scroll down (positive delta) should move to next item.
roller.handle_event(&Event::Wheel { delta: Point::new(0, 1), modifiers: 0 });
assert_eq!(roller.selected_index().unwrap_or(0), 1);
// Scroll down again.
roller.handle_event(&Event::Wheel { delta: Point::new(0, 1), modifiers: 0 });
assert_eq!(roller.selected_index().unwrap_or(0), 2);
// Scroll up (negative delta) should move to previous item.
roller.handle_event(&Event::Wheel { delta: Point::new(0, -1), modifiers: 0 });
assert_eq!(roller.selected_index().unwrap_or(0), 1);
// Scroll up past start clamps to 0.
roller.set_selected_index(0);
roller.handle_event(&Event::Wheel { delta: Point::new(0, -1), modifiers: 0 });
assert_eq!(roller.selected_index().unwrap_or(0), 0);
// Scroll down past end clamps to last.
roller.set_selected_index(roller.options.len() - 1);
roller.handle_event(&Event::Wheel { delta: Point::new(0, 1), modifiers: 0 });
assert_eq!(roller.selected_index().unwrap_or(0), roller.options.len() - 1);
}
#[test]
fn roller_draw_does_not_panic() {
let mut roller = make_roller();
// Create a minimal render context for testing.
let mut backend = SoftwarePaintBackend::new(Size::new(160, 120), 1.0);
backend.begin_frame(Color::WHITE);
let mut ctx = RenderContext::new(&mut backend);
roller.draw(&mut ctx);
backend.end_frame();
// Also test with empty options.
let mut empty: Roller = Roller::new(Vec::new(), Rect::new(0, 0, 100, 100));
let mut backend2 = SoftwarePaintBackend::new(Size::new(100, 100), 1.0);
backend2.begin_frame(Color::WHITE);
let mut ctx2 = RenderContext::new(&mut backend2);
empty.draw(&mut ctx2);
backend2.end_frame();
}
#[test]
fn roller_set_options_replaces_and_clamps() {
let mut roller = make_roller();
roller.set_selected_index(3);
assert_eq!(roller.selected_text(), Some("Dragonfruit"));
// Replace with fewer options; index should clamp.
roller.set_options(vec!["X".to_string(), "Y".to_string()]);
assert_eq!(roller.options.len(), 2);
assert_eq!(roller.selected_index().unwrap_or(0), 1);
assert_eq!(roller.selected_text(), Some("Y"));
// Replace with empty list.
roller.set_options(Vec::new());
assert!(roller.options.is_empty());
assert_eq!(roller.selected_index().unwrap_or(0), 0);
assert!(roller.selected_text().is_none());
}
#[test]
fn roller_visible_count_is_always_odd() {
let roller = make_roller();
assert!(roller.visible_count() % 2 == 1);
let mut roller = roller;
roller.set_visible_count(4);
assert!(roller.visible_count() % 2 == 1);
assert!(roller.visible_count() >= 3);
roller.set_visible_count(7);
assert_eq!(roller.visible_count(), 7);
}
#[test]
fn roller_font_size_accessors() {
let mut roller = make_roller();
assert!((roller.font_size() - 16.0).abs() < 0.01);
roller.set_font_size(20.0);
assert!((roller.font_size() - 20.0).abs() < 0.01);
// Clamp to minimum.
roller.set_font_size(0.0);
assert!((roller.font_size() - 4.0).abs() < 0.01);
}
#[test]
fn roller_mouse_press_selects_item() {
let mut roller = make_roller();
// The hit test is the **drawn** wheel band, not the control's rectangle. The
// wheel is `ROLLER_WHEEL_HEIGHT` (140 px) in this 120 px control, so the band is
// clamped to the control and its middle is the control's middle; each press is
// placed one *row* from that middle, using the row the painter uses.
let band = roller.wheel_band();
let item_h = roller.item_height() as i32;
assert!(item_h > 0, "a row is a drawable height");
let center_y = band.y + (band.height as i32) / 2;
// Click one item above center.
roller.handle_event(&Event::MousePress {
pos: Point::new(band.x + 10, center_y - item_h),
button: 1,
modifiers: 0,
});
// Should have moved one index up (if available).
assert_eq!(roller.selected_index().unwrap_or(0), 0); // already at 0, can't go up
roller.set_selected_index(2);
// Click one item below center → index 3.
roller.handle_event(&Event::MousePress {
pos: Point::new(band.x + 10, center_y + item_h),
button: 1,
modifiers: 0,
});
assert_eq!(roller.selected_index().unwrap_or(0), 3);
}
/// The wheel's rows are a fixed height, so the same control is the same object in
/// any rectangle.
///
/// This pins the defect the fix removes: `item_height` was `font_size * 1.5` and
/// the wheel's band was the control's own `rect`, so the census cell drew a 120 px
/// panel with one 24 px selection band in it while a 96 px list slot drew a
/// different wheel. The band is now the wheel's own extent — `visible_count` rows —
/// centred in the control and clamped only when the control is shorter than it.
#[test]
fn the_wheel_keeps_its_own_extent_in_any_rectangle() {
for height in [160u32, 240, 400] {
let roller = Roller::new(
vec!["a".to_string(), "b".to_string(), "c".to_string()],
Rect::new(0, 0, 200, height),
);
let band = roller.wheel_band();
// The band is the wheel's own height, not the caller's.
assert_eq!(band.height, roller.content_height(), "at control height {height}");
assert_eq!(
band.height,
dimensions::ROLLER_WHEEL_HEIGHT,
"a five-row wheel, whatever the control's height is"
);
// The row scales with the *type*, never with the box: at the default 16 pt
// face it is `ROLLER_ROW_HEIGHT`, and a taller control does not change it.
assert_eq!(
roller.item_height(),
dimensions::ROLLER_ROW_HEIGHT,
"a taller control must not stretch a row (at {height})"
);
assert_eq!(band.width, 200, "the wheel spans the control's width");
// Centred, so the wheel sits on the control's middle line.
assert_eq!(band.y, (height - band.height) as i32 / 2, "at control height {height}");
}
// A control shorter than the wheel clamps it rather than painting outside: this
// is the one case where the control legitimately fills its rectangle, and it is
// what the 240x120 census cell does.
let short = Roller::new(vec!["a".to_string()], Rect::new(0, 0, 200, 40));
assert_eq!(short.wheel_band().height, 40);
assert_eq!(short.wheel_band().y, 0, "a clamped band starts at the control's edge");
// And the census cell itself, which is shorter than the wheel.
let census = Roller::new(vec!["a".to_string()], crate::widget::census::CENSUS_RECT);
assert_eq!(census.wheel_band().height, 120);
}
/// A press outside the drawn wheel selects nothing.
///
/// The old handler tested the control's rectangle, so a click in the empty space
/// above or below the wheel moved the selection — a hit area larger than the ink.
#[test]
fn a_press_outside_the_wheel_band_changes_nothing() {
// A tall control with a much shorter wheel: the rows occupy only the middle.
let mut roller = Roller::new(
vec!["a".to_string(), "b".to_string(), "c".to_string()],
Rect::new(0, 0, 200, 400),
);
roller.set_selected_index(1);
let band = roller.wheel_band();
assert!(band.y > 0, "the wheel is centred, so there is empty space above it");
roller.handle_event(&Event::MousePress {
pos: Point::new(100, band.y - 10),
button: 1,
modifiers: 0,
});
assert_eq!(
roller.selected_index().unwrap_or(0),
1,
"a press above the wheel must not select"
);
roller.handle_event(&Event::MousePress {
pos: Point::new(100, band.y + band.height as i32 + 10),
button: 1,
modifiers: 0,
});
assert_eq!(
roller.selected_index().unwrap_or(0),
1,
"a press below the wheel must not select"
);
}
/// The emitted fill is the wheel band, not the control's whole rectangle.
#[test]
fn the_roller_paints_a_wheel_rather_than_a_panel() {
// 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();
// A 400 px control with a 140 px wheel: the fill must be the wheel, so the
// band's own rectangle is what the snapshot starts from rather than the cell.
let mut roller =
Roller::new(vec!["Apple".to_string(), "Banana".to_string()], Rect::new(0, 0, 240, 400));
let svg = crate::widget::svg::render_to_svg(&mut roller);
let band = roller.wheel_band();
assert_eq!(band.height, dimensions::ROLLER_WHEEL_HEIGHT);
assert!(band.y > 0, "the wheel is centred, not pinned to the control's top edge");
assert!(
svg.contains(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"",
band.x, band.y, band.width, band.height
)),
"the wheel's own band is what is painted: {svg}"
);
// The defect's signature: a fill spanning the control's whole height. The wheel
// is `visible_count` rows, so the control's own fill is the band — never the
// control's full height. (The `<rect x="0" y="0" … height="400">` above is the
// *exporter's* backdrop, painted before the control draws, which is why this
// asserts on the band's own rectangle rather than on the absence of a number.)
assert!(
!svg.contains(&format!(
"<rect x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\"",
band.x, band.y, band.width, 400
)),
"the control's own height would mean a panel fill: {svg}"
);
// The selection band is one row tall, not the whole wheel.
assert!(
svg.contains(&format!("height=\"{}\"", roller.item_height())),
"the centre row is a row, not the wheel: {svg}"
);
}
// ── D09-STYLE-02: the row and hint measure with the font the paint uses ──
/// A styled font larger than the caller-set `font_size` must grow the drawn row and the hint.
///
/// `draw` prefers `style.font`; `item_height` and `size_hint` must agree with it, or the wheel
/// band clips the taller glyphs it paints.
#[test]
fn a_styled_font_grows_the_roller_row_and_hint() {
let options = || vec!["one".to_string(), "two".to_string(), "three".to_string()];
let baseline = Roller::new(options(), Rect::new(0, 0, 200, 120));
let base_row = baseline.item_height();
let base_hint = baseline.size_hint();
let mut big = Roller::new(options(), Rect::new(0, 0, 200, 120));
big.set_style(
crate::style::WidgetStyle::default().with_font(crate::core::Font::simple("Test", 40.0)),
);
let big_row = big.item_height();
let big_hint = big.size_hint();
assert!(
big_row > base_row,
"a styled font must grow the drawn row: {big_row} vs {base_row}"
);
assert!(
big_hint.width > base_hint.width,
"a styled font must widen the hint: {} vs {}",
big_hint.width,
base_hint.width
);
}
/// With inertia on, a wheel notch aims the drawn wheel at the new row and it slides there.
///
/// The logical selection changes immediately, exactly as it always did; what changes is
/// that `visual_index` travels between rows over successive ticks instead of jumping. The
/// settle case is half the contract: once it arrives, the roller owes no more frames.
#[test]
fn inertia_tweens_the_wheel_to_the_target_row() {
let mut roller = make_roller();
assert!(!roller.inertia(), "a roller is direct by default");
roller.set_inertia(true);
assert!(roller.inertia());
roller.set_selected_index(3);
assert_eq!(roller.selected_index(), Some(3), "the logical row changes at once");
assert!(roller.is_animating(), "the drawn wheel owes frames");
assert!(roller.tick(30), "a short frame leaves the wheel travelling");
let mid = roller.visual_index();
assert!(mid > 0.0 && mid < 3.0, "the wheel is between rows: {mid}");
while roller.tick(1000) {}
assert_eq!(roller.visual_index(), 3.0, "the wheel arrives exactly");
assert!(!roller.is_animating());
assert!(!roller.tick(1000), "a settled wheel owes no more frames");
}
/// A drag moves the selection by the distance the pointer travelled, in rows.
#[test]
fn dragging_the_wheel_moves_the_selection_by_rows() {
let mut roller = make_roller();
let band = roller.wheel_band();
let item_h = roller.item_height() as i32;
let center_y = band.y + (band.height as i32) / 2;
let x = band.x + 10;
roller.set_selected_index(1);
roller.handle_event(&Event::MousePress {
pos: Point::new(x, center_y),
button: 1,
modifiers: 0,
});
// Dragging up by two rows walks two options forward.
roller.handle_event(&Event::MouseMove { pos: Point::new(x, center_y - 2 * item_h) });
assert_eq!(roller.selected_index(), Some(3));
// Dragging back down by one row walks back one option.
roller.handle_event(&Event::MouseMove { pos: Point::new(x, center_y - item_h) });
assert_eq!(roller.selected_index(), Some(2));
// The drag ends on release; a later move must not keep walking the wheel.
roller.handle_event(&Event::MouseRelease {
pos: Point::new(x, center_y - item_h),
button: 1,
});
roller.handle_event(&Event::MouseMove { pos: Point::new(x, center_y - 4 * item_h) });
assert_eq!(roller.selected_index(), Some(2), "a released drag must not stay armed");
}
/// The wheel is keyboard-reachable: arrows step one row, Page keys step a page and Home/End
/// jump to the ends, all through `set_selected_index`.
#[test]
fn the_keyboard_steps_the_wheel() {
let mut roller = make_roller();
roller.handle_event(&Event::KeyPress { key: crate::event::key_codes::DOWN, modifiers: 0 });
assert_eq!(roller.selected_index(), Some(1));
roller.handle_event(&Event::KeyPress { key: crate::event::key_codes::UP, modifiers: 0 });
assert_eq!(roller.selected_index(), Some(0));
roller.handle_event(&Event::KeyPress {
key: crate::event::key_codes::PAGE_DOWN,
modifiers: 0,
});
assert_eq!(
roller.selected_index(),
Some(roller.options().len() - 1),
"one page steps past the end and clamps"
);
roller.handle_event(&Event::KeyPress { key: crate::event::key_codes::END, modifiers: 0 });
assert_eq!(roller.selected_index(), Some(roller.options().len() - 1));
roller.handle_event(&Event::KeyPress { key: crate::event::key_codes::HOME, modifiers: 0 });
assert_eq!(roller.selected_index(), Some(0));
// An unrelated key is ignored rather than resetting the selection.
roller.handle_event(&Event::KeyPress { key: crate::event::key_codes::LEFT, modifiers: 0 });
assert_eq!(roller.selected_index(), Some(0));
}
}