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
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Dial (knob) widget.
use crate::core::{Color, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::widget::capability::coercion::{expect_bool, expect_f64, expect_i64};
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::numeric::ordered_clamp_i32;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// Dial (rotary knob) widget.
///
/// Holds an integer value in an inclusive `minimum ..= maximum` range and
/// renders it as a needle on a circle. The widget has no drag handling of its
/// own: it changes value in response to keyboard events and to explicit
/// [`Dial::set_value`] calls from the caller.
///
pub struct Dial {
base: BaseWidget,
minimum: i32,
maximum: i32,
value: i32,
single_step: i32,
page_step: i32,
notches_visible: bool,
notch_target: f64,
wrapping: bool,
/// Emitted with the new value whenever [`Dial::set_value`] actually changes
/// it. Redundant sets do not fire it.
pub value_changed: Signal1<i32>,
/// Emitted when the primary mouse button is pressed while the dial is
/// enabled. Purely a notification — the press does not change the value.
pub slider_pressed: GenericSignal,
/// Emitted when the primary mouse button is released while the dial is
/// enabled. Like `slider_pressed`, it does not change the value.
pub slider_released: GenericSignal,
}
impl Dial {
/// Creates a dial ranging over `0 ..= 99` with value `0`, a single step of
/// `1`, a page step of `10`, notches hidden, wrapping off, and a notch
/// target of `3.7`.
///
/// `geometry` is in parent-relative logical pixels; the size hint is 64x64.
pub fn new(geometry: Rect) -> Self {
Self {
base: BaseWidget::new(WidgetKind::Dial, geometry, "Dial"),
minimum: 0,
maximum: 99,
value: 0,
single_step: 1,
page_step: 10,
notches_visible: false,
notch_target: 3.7,
wrapping: false,
value_changed: Signal1::new(),
slider_pressed: GenericSignal::new(),
slider_released: GenericSignal::new(),
}
}
/// Returns the inclusive lower bound. Defaults to `0`.
pub fn minimum(&self) -> i32 {
self.minimum
}
/// Returns the inclusive upper bound. Defaults to `99`.
pub fn maximum(&self) -> i32 {
self.maximum
}
/// Returns the current value, always inside the configured range (modulo
/// wrapping, which is still range-mapped).
pub fn value(&self) -> i32 {
self.value
}
/// Returns the increment applied by one arrow-key press (in value units).
/// Always at least `1`; defaults to `1`.
pub fn single_step(&self) -> i32 {
self.single_step
}
/// Returns the increment applied by Page Up / Page Down (in value units).
/// Always at least `1`; defaults to `10`.
pub fn page_step(&self) -> i32 {
self.page_step
}
/// Returns whether notches are drawn. Defaults to `false`.
///
/// Note that [`Dial::draw`] currently paints only the body and needle, so
/// this flag has no visible effect yet.
pub fn notches_visible(&self) -> bool {
self.notches_visible
}
/// Returns the notch target angle, in **degrees**, used by the notch
/// geometry. Defaults to `3.7`.
///
/// The value is stored verbatim and currently not consumed by rendering.
pub fn notch_target(&self) -> f64 {
self.notch_target
}
/// Returns whether the value wraps around the range instead of clamping.
/// Defaults to `false`.
pub fn wrapping(&self) -> bool {
self.wrapping
}
/// Sets the lower bound and re-applies it to the current value through
/// [`Dial::set_value`], so the value will be clamped or wrapped into the
/// new range and `value_changed` may fire.
///
/// `min` above the current `maximum` leaves an inverted range in which the
/// clamp saturates unpredictably; use [`Dial::set_range`] instead, which
/// keeps `maximum >= minimum`.
pub fn set_minimum(&mut self, min: i32) {
self.minimum = min;
self.set_value(self.value);
self.base.request_redraw();
}
/// Sets the upper bound and re-applies it to the current value through
/// [`Dial::set_value`]. See [`Dial::set_minimum`] for range caveats.
pub fn set_maximum(&mut self, max: i32) {
self.maximum = max;
self.set_value(self.value);
self.base.request_redraw();
}
/// Sets both minimum and maximum in one call, raising `maximum` to `min`
/// if it is lower, so the range is never inverted. The current value is
/// then re-applied through [`Dial::set_value`].
///
/// This is a convenience writer; query bounds via `minimum()` and `maximum()`.
pub fn set_range(&mut self, min: i32, max: i32) {
self.minimum = min;
self.maximum = max.max(min);
self.set_value(self.value);
self.base.request_redraw();
}
/// Sets the value, clamping into `minimum ..= maximum` — or wrapping
/// modulo the range when [`Dial::wrapping`] is on, in which case the value
/// is mapped back into the range rather than rejected.
///
/// A no-op when the resulting value equals the current one: no signal and
/// no redraw.
pub fn set_value(&mut self, value: i32) {
let clamped = if self.wrapping {
// The span is computed in `i64`: `maximum - minimum + 1` overflows `i32`
// for a legal range such as `i32::MIN ..= i32::MAX`, and the overflow
// check panics in debug builds — aborting the host process on a property
// write (`write_property(w, "minimum", ..)` reaches this). Widening keeps
// the wrapping contract intact for every in-range span while making the
// extreme case saturate instead of panic.
let span = self.maximum as i64 - self.minimum as i64 + 1;
let offset = (value as i64 - self.minimum as i64).rem_euclid(span);
(self.minimum as i64 + offset) as i32
} else {
ordered_clamp_i32(value, self.minimum, self.maximum)
};
if self.value != clamped {
self.value = clamped;
self.value_changed.emit(clamped);
self.base.request_redraw();
}
}
/// Sets the arrow-key increment, floored at `1` so the value can always
/// move. Requests a redraw.
pub fn set_single_step(&mut self, step: i32) {
self.single_step = step.max(1);
self.base.request_redraw();
}
/// Sets the Page Up / Page Down increment, floored at `1`. Requests a
/// redraw.
pub fn set_page_step(&mut self, step: i32) {
self.page_step = step.max(1);
self.base.request_redraw();
}
/// Toggles notch rendering. See [`Dial::notches_visible`] — currently has
/// no visual effect. Requests a redraw.
pub fn set_notches_visible(&mut self, visible: bool) {
self.notches_visible = visible;
self.base.request_redraw();
}
/// Sets the notch target in degrees, stored verbatim. See
/// [`Dial::notch_target`]. Requests a redraw.
pub fn set_notch_target(&mut self, target: f64) {
self.notch_target = target;
self.base.request_redraw();
}
/// Enables or disables wrap-around behaviour.
///
/// Takes effect on the *next* call to [`Dial::set_value`]; the current
/// value is not re-mapped. Turning wrapping off therefore leaves a value
/// that was produced by wrapping in place, which is fine because wrapped
/// values are always inside the range. Requests a redraw.
pub fn set_wrapping(&mut self, wrapping: bool) {
self.wrapping = wrapping;
self.base.request_redraw();
}
/// Returns value as angle in radians (from -135° to +135°, or full circle if wrapping).
fn value_angle(&self) -> f64 {
let range = (self.maximum - self.minimum) as f64;
if range == 0.0 {
return -std::f64::consts::PI * 0.75;
}
let ratio = (self.value - self.minimum) as f64 / range;
if self.wrapping {
ratio * 2.0 * std::f64::consts::PI - std::f64::consts::PI
} else {
-std::f64::consts::PI * 0.75 + ratio * std::f64::consts::PI * 1.5
}
}
}
impl Widget for Dial {
fn base(&self) -> &BaseWidget {
&self.base
}
fn base_mut(&mut self) -> &mut BaseWidget {
&mut self.base
}
fn size_hint(&self) -> Size {
Size::new(64, 64)
}
impl_draw_bridge!();
impl_widget_property_hooks!();
}
/// `Dial`'s property contract.
impl WidgetProperties for Dial {
fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
match name {
"minimum" => Ok(CapabilityValue::Int(self.minimum() as i64)),
"maximum" => Ok(CapabilityValue::Int(self.maximum() as i64)),
"value" => Ok(CapabilityValue::Int(self.value() as i64)),
"single_step" => Ok(CapabilityValue::Int(self.single_step() as i64)),
"page_step" => Ok(CapabilityValue::Int(self.page_step() as i64)),
"notches_visible" => Ok(CapabilityValue::Bool(self.notches_visible())),
"notch_target" => Ok(CapabilityValue::Float(self.notch_target())),
"wrapping" => Ok(CapabilityValue::Bool(self.wrapping())),
_ => base_property_get(self, name),
}
}
fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
match name {
"minimum" => {
self.set_minimum(expect_i64(value)? as i32);
Ok(())
}
"maximum" => {
self.set_maximum(expect_i64(value)? as i32);
Ok(())
}
"value" => {
self.set_value(expect_i64(value)? as i32);
Ok(())
}
"single_step" => {
self.set_single_step(expect_i64(value)? as i32);
Ok(())
}
"page_step" => {
self.set_page_step(expect_i64(value)? as i32);
Ok(())
}
"notches_visible" => {
self.set_notches_visible(expect_bool(value)?);
Ok(())
}
"notch_target" => {
self.set_notch_target(expect_f64(value)?);
Ok(())
}
"wrapping" => {
self.set_wrapping(expect_bool(value)?);
Ok(())
}
_ => base_property_set(self, name, value),
}
}
fn property_names(&self) -> &'static [&'static str] {
// Mirrors `DIAL_PROPERTIES`.
property_names_of![
"minimum",
"maximum",
"value",
"single_step",
"page_step",
"notches_visible",
"notch_target",
"wrapping",
BASE_PROPERTY_NAMES
]
}
/// Reports the one published command that names no property.
///
/// `set_range` sets two properties at once (`minimum` and `maximum`) through the
/// control's own [`Self::set_range`], so neither property name alone stands for
/// it. The default `set_foo` convention would have resolved `range` against
/// `property_names` and, finding nothing, answered `UnknownCommand` for a command
/// the control really implements. Answering `OutOfRange` says what is true: the
/// command exists and needs the caller to supply a value.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"set_range" => Err(CapabilityAccessError::OutOfRange),
_ => self.default_command(name),
}
}
}
impl EventHandler for Dial {
fn handle_event(&mut self, event: &Event) {
self.base.handle_event(event);
if !self.base.is_enabled() {
return;
}
match event {
Event::MousePress { button, .. } if *button == 1 => {
self.slider_pressed.emit();
}
Event::MouseRelease { button, .. } if *button == 1 => {
self.slider_released.emit();
}
Event::KeyPress { key, .. } => match *key {
37 | 40 => self.set_value(self.value - self.single_step), // Left/Down
38 | 39 => self.set_value(self.value + self.single_step), // Up/Right
33 => self.set_value(self.value - self.page_step),
34 => self.set_value(self.value + self.page_step),
36 => self.set_value(self.minimum),
35 => self.set_value(self.maximum),
// Unknown key; ignore
_ => {}
},
// Other events are not relevant for this widget
_ => {}
}
}
}
impl Draw for Dial {
fn draw(&mut self, context: &mut RenderContext) {
let rect = self.geometry();
let center = Point {
x: rect.x + rect.width as f32 as i32 / 2,
y: rect.y + rect.height as f32 as i32 / 2,
};
let radius = (rect.width.min(rect.height) / 2).saturating_sub(4);
// 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 face, its rim, the needle and
// the hub were all fixed greys, which the rendering census reported 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().clone();
let theme = crate::style::resolved_theme_style("dial");
// Read as its own lock acquisition and copied out as values, so the guard is
// dropped before anything else touches the theme. The accent is the dial's value
// colour: the needle is a value indicator, the same role a progress bar's fill
// plays, and reading the token is what makes the indicator move with the theme.
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 face is one step from the window fill toward the text colour, so the dial reads
// as a raised disc in either appearance and is never byte-identical to the window
// behind it. 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 the resolved fill. A caller's own colour
// still wins.
let face_from_theme = window_fill.blend(&ink, 0.10);
let face = match style.background_color {
Some(resolved) if resolved != window_fill => resolved,
_ => face_from_theme,
};
// A dial is a `Surface`-role control: the resolver knows its background and text but
// has no border colour for it, so the rim is derived one visible step from the face.
let rim = style
.border_color
.or_else(|| theme.as_ref().and_then(|t| t.border_color))
.filter(|resolved| *resolved != face)
.unwrap_or_else(|| face.blend(&muted, 0.55));
context.fill_circle(center, radius, face);
context.draw_circle(center, radius, rim);
// Draw the value needle: an accent-coloured indicator, black hub beneath it.
let angle = self.value_angle();
let needle_len = (radius as f32 * 0.7) as i32;
let to = Point {
x: center.x + (needle_len as f32 * angle.cos() as f32) as i32,
y: center.y + (needle_len as f32 * angle.sin() as f32) as i32,
};
context.draw_line(center, to, accent);
context.fill_circle(center, 3, ink);
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::Rect;
#[test]
fn dial_creation_defaults() {
let d = Dial::new(Rect::new(0, 0, 64, 64));
assert_eq!(d.minimum(), 0);
assert_eq!(d.maximum(), 99);
assert_eq!(d.value(), 0);
assert_eq!(d.single_step(), 1);
assert_eq!(d.page_step(), 10);
assert!(!d.notches_visible());
assert!(!d.wrapping());
}
#[test]
fn dial_set_value_clamps() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
d.set_value(50);
assert_eq!(d.value(), 50);
d.set_value(200);
assert_eq!(d.value(), 99);
d.set_value(-10);
assert_eq!(d.value(), 0);
}
#[test]
fn dial_set_range_reclamps_value() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
d.set_value(50);
d.set_range(60, 80);
assert_eq!(d.value(), 60);
assert_eq!(d.minimum(), 60);
assert_eq!(d.maximum(), 80);
}
#[test]
fn dial_wrapping() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
d.set_range(0, 9);
d.set_wrapping(true);
assert!(d.wrapping());
d.set_value(9);
assert_eq!(d.value(), 9);
d.set_value(10);
// wrapping: 10 % 10 = 0
assert_eq!(d.value(), 0);
}
#[test]
fn dial_steps() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
d.set_single_step(5);
assert_eq!(d.single_step(), 5);
d.set_single_step(0);
assert_eq!(d.single_step(), 1); // floors at 1
d.set_page_step(25);
assert_eq!(d.page_step(), 25);
d.set_page_step(0);
assert_eq!(d.page_step(), 1); // floors at 1
}
#[test]
fn dial_notches_visible() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
assert!(!d.notches_visible());
d.set_notches_visible(true);
assert!(d.notches_visible());
d.set_notches_visible(false);
assert!(!d.notches_visible());
}
#[test]
fn dial_notch_target() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
assert!((d.notch_target() - 3.7).abs() < 1e-9);
d.set_notch_target(5.0);
assert!((d.notch_target() - 5.0).abs() < 1e-9);
}
#[test]
fn dial_keyboard_navigation() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
d.set_value(50);
// Left arrow (key 37) decreases by single step
d.handle_event(&Event::KeyPress { key: 37, modifiers: 0 });
assert_eq!(d.value(), 49);
// Right arrow (key 39) increases by single step
d.handle_event(&Event::KeyPress { key: 39, modifiers: 0 });
assert_eq!(d.value(), 50);
// PageUp (key 33) decreases by page step
d.handle_event(&Event::KeyPress { key: 33, modifiers: 0 });
assert_eq!(d.value(), 40);
// PageDown (key 34) increases by page step
d.handle_event(&Event::KeyPress { key: 34, modifiers: 0 });
assert_eq!(d.value(), 50);
// Home (key 36) goes to min
d.handle_event(&Event::KeyPress { key: 36, modifiers: 0 });
assert_eq!(d.value(), 0);
// End (key 35) goes to max
d.handle_event(&Event::KeyPress { key: 35, modifiers: 0 });
assert_eq!(d.value(), 99);
}
#[test]
fn dial_mouse_events() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
d.handle_event(&Event::MousePress { pos: Point::new(32, 32), button: 1 });
// value should not change; only signal emitted
assert_eq!(d.value(), 0);
d.handle_event(&Event::MouseRelease { pos: Point::new(32, 32), button: 1 });
assert_eq!(d.value(), 0);
}
#[test]
fn dial_signal_accessors() {
let d = Dial::new(Rect::new(0, 0, 64, 64));
let _ = &d.value_changed;
let _ = &d.slider_pressed;
let _ = &d.slider_released;
}
#[test]
fn dial_geometry_delegation() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
d.set_geometry(Rect::new(10, 10, 80, 80));
assert_eq!(d.geometry(), Rect::new(10, 10, 80, 80));
}
#[test]
fn dial_disabled_blocks_events() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
d.set_value(50);
d.set_enabled(false);
d.handle_event(&Event::KeyPress { key: 39, modifiers: 0 });
// Should stay unchanged because disabled
assert_eq!(d.value(), 50);
}
/// A wrapping dial over the full `i32` range must not overflow.
///
/// `maximum - minimum + 1` is `i32::MAX - i32::MIN + 1`, which does not fit in
/// `i32`; the previous implementation panicked with `attempt to add with
/// overflow` — killing the host process, since `set_minimum` is reachable from
/// `write_property(w, "minimum", ..)` (the JSON declarative layer, the C ABI and
/// every language binding all route through it).
#[test]
fn dial_wrapping_survives_full_i32_range() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
d.set_wrapping(true);
d.set_maximum(i32::MAX);
d.set_minimum(i32::MIN);
// Every value is in range, so the value is preserved exactly.
d.set_value(1234);
assert_eq!(d.value(), 1234);
d.set_value(i32::MIN);
assert_eq!(d.value(), i32::MIN);
d.set_value(i32::MAX);
assert_eq!(d.value(), i32::MAX);
}
/// Wrapping still maps out-of-range values modulo the span.
#[test]
fn dial_wrapping_maps_out_of_range_values() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
d.set_range(0, 9);
d.set_wrapping(true);
d.set_value(13);
assert_eq!(d.value(), 3);
d.set_value(-1);
assert_eq!(d.value(), 9);
}
/// A span wide enough to overflow `i32` when offset by one still wraps rather
/// than aborting: the span is computed in `i64` so the modulo is well-defined.
#[test]
fn dial_wrapping_handles_near_maximal_span() {
let mut d = Dial::new(Rect::new(0, 0, 64, 64));
d.set_wrapping(true);
d.set_range(-1, i32::MAX - 1);
d.set_value(0);
assert_eq!(d.value(), 0);
}
}