rust_widgets 2.0.0

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 60+ widgets, touch/gesture support, i18n, and SVG-pipeline-accurate output
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Stepper widget — a numeric increment/decrement control with +/- buttons.
//!
//! The Stepper widget displays a numeric value with minus (-) and plus (+)
//! buttons on either side for incrementing or decrementing the value.
//! It supports configurable minimum, maximum, step size, and emits a
//! `value_changed` signal whenever the value changes.

use crate::core::{Color, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::widget::capability::coercion::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::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};

/// Stepper widget for numeric increment/decrement with +/- buttons.
pub struct Stepper {
    base: BaseWidget,
    value: i32,
    min: i32,
    max: i32,
    step: i32,
    /// Emitted when the value changes.
    pub value_changed: Signal1<i32>,
}

impl Stepper {
    /// Creates a new Stepper widget with the given geometry.
    /// Default value is 0, min=0, max=100, step=1.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Stepper, geometry, "Stepper"),
            value: 0,
            min: 0,
            max: 100,
            step: 1,
            value_changed: Signal1::new(),
        }
    }

    /// Sets the current value, clamped to [min, max].
    /// Emits `value_changed` signal if the value actually changes.
    pub fn set_value(&mut self, value: i32) {
        let clamped = value.clamp(self.min, self.max);
        if self.value != clamped {
            self.value = clamped;
            self.value_changed.emit(clamped);
            self.base.request_redraw();
        }
    }

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

    /// Sets the minimum value (inclusive).
    pub fn set_min(&mut self, min: i32) {
        self.min = min.min(self.max);
        // Re-clamp current value to new bounds
        self.set_value(self.value);
    }

    /// Sets the maximum value (inclusive).
    pub fn set_max(&mut self, max: i32) {
        self.max = max.max(self.min);
        // Re-clamp current value to new bounds
        self.set_value(self.value);
    }

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

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

    /// Sets the step increment/decrement amount.
    pub fn set_step(&mut self, step: i32) {
        self.step = step.max(1);
    }

    /// Returns the step increment/decrement amount.
    pub fn step(&self) -> i32 {
        self.step
    }

    /// Increments the value by the step amount, clamped to max.
    pub fn increment(&mut self) {
        self.set_value(self.value.saturating_add(self.step));
    }

    /// Decrements the value by the step amount, clamped to min.
    pub fn decrement(&mut self) {
        self.set_value(self.value.saturating_sub(self.step));
    }
}

impl Widget for Stepper {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        crate::core::Size::new(120, 30)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `Stepper`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_dialog.in.rs` / `access_write_dialog.in.rs` dispatch, so callers see
/// the same coercions and the same errors as before, including the `i32`
/// truncation and the `min`/`max` clamping the setters perform.
impl WidgetProperties for Stepper {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "value" => Ok(CapabilityValue::Int(self.value() as i64)),
            "minimum" => Ok(CapabilityValue::Int(self.min() as i64)),
            "maximum" => Ok(CapabilityValue::Int(self.max() as i64)),
            "step" => Ok(CapabilityValue::Int(self.step() as i64)),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "value" => {
                self.set_value(expect_i64(value)? as i32);
                Ok(())
            }
            "minimum" => {
                self.set_min(expect_i64(value)? as i32);
                Ok(())
            }
            "maximum" => {
                self.set_max(expect_i64(value)? as i32);
                Ok(())
            }
            "step" => {
                self.set_step(expect_i64(value)? as i32);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

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

impl Draw for Stepper {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        let is_enabled = self.base.is_enabled();
        let btn_width = rect.height.min(rect.width / 3).max(20);
        let value_text = self.value.to_string();
        let font = crate::core::Font::default_ui();
        let text_metrics = context.measure_text(&value_text, &font);

        // Background
        let bg_color = if !is_enabled {
            Color::rgba(230, 230, 230, 200)
        } else {
            Color::rgba(240, 240, 240, 255)
        };
        context.fill_rounded_rect(rect, 4, bg_color);
        context.draw_rounded_rect_stroke(rect, 4, Color::rgba(180, 180, 180, 200), 1);

        // --- Minus button (left) ---
        let inner_height = rect.height.saturating_sub(2);
        let minus_rect = Rect::new(rect.x + 1, rect.y + 1, btn_width, inner_height);
        let minus_color = if !is_enabled {
            Color::rgba(200, 200, 200, 200)
        } else {
            Color::rgba(220, 220, 220, 255)
        };
        context.fill_rounded_rect(minus_rect, 3, minus_color);
        context.draw_rounded_rect_stroke(minus_rect, 3, Color::rgba(160, 160, 160, 200), 1);
        // Draw "-" symbol centered in the minus button
        let minus_label = "\u{2212}";
        let minus_font = crate::core::Font::bold("Arial", 16.0);
        let minus_metrics = context.measure_text(minus_label, &minus_font);
        let minus_x = minus_rect.x + (minus_rect.width as i32 - minus_metrics.width as i32) / 2;
        let minus_y = minus_rect.y + (minus_rect.height as i32 + minus_metrics.height as i32) / 2
            - minus_metrics.descent as i32;
        context.draw_text(
            Point::new(minus_x, minus_y),
            minus_label,
            &minus_font,
            if !is_enabled {
                Color::rgba(150, 150, 150, 200)
            } else {
                Color::rgba(60, 60, 60, 255)
            },
            HorizontalAlignment::Left,
        );

        // --- Plus button (right) ---
        let plus_rect = Rect::new(
            rect.x + rect.width as i32 - btn_width as i32 - 1,
            rect.y + 1,
            btn_width,
            inner_height,
        );
        let plus_color = if !is_enabled {
            Color::rgba(200, 200, 200, 200)
        } else {
            Color::rgba(220, 220, 220, 255)
        };
        context.fill_rounded_rect(plus_rect, 3, plus_color);
        context.draw_rounded_rect_stroke(plus_rect, 3, Color::rgba(160, 160, 160, 200), 1);
        // Draw "+" symbol centered in the plus button
        let plus_label = "+";
        let plus_font = crate::core::Font::bold("Arial", 16.0);
        let plus_metrics = context.measure_text(plus_label, &plus_font);
        let plus_x = plus_rect.x + (plus_rect.width as i32 - plus_metrics.width as i32) / 2;
        let plus_y = plus_rect.y + (plus_rect.height as i32 + plus_metrics.height as i32) / 2
            - plus_metrics.descent as i32;
        context.draw_text(
            Point::new(plus_x, plus_y),
            plus_label,
            &plus_font,
            if !is_enabled {
                Color::rgba(150, 150, 150, 200)
            } else {
                Color::rgba(60, 60, 60, 255)
            },
            HorizontalAlignment::Left,
        );

        // --- Value text (center) ---
        let text_x = rect.x + (rect.width as i32 - text_metrics.width as i32) / 2;
        let text_y = rect.y + (rect.height as i32 + text_metrics.height as i32) / 2
            - text_metrics.descent as i32;
        let text_color = if !is_enabled {
            Color::rgba(150, 150, 150, 200)
        } else {
            Color::rgba(30, 30, 30, 255)
        };
        context.draw_text(
            Point::new(text_x, text_y),
            &value_text,
            &font,
            text_color,
            HorizontalAlignment::Left,
        );
    }
}

impl EventHandler for Stepper {
    fn handle_event(&mut self, event: &Event) {
        if !self.base.is_enabled() {
            return;
        }
        match event {
            Event::MousePress { pos, button } => {
                if *button != 1 {
                    return;
                }
                let rect = self.geometry();
                let btn_width = rect.height.min(rect.width / 3).max(20);

                // Minus button area (left)
                let inner_height = rect.height.saturating_sub(2);
                let minus_rect = Rect::new(rect.x + 1, rect.y + 1, btn_width, inner_height);
                // Plus button area (right)
                let plus_rect = Rect::new(
                    rect.x + rect.width as i32 - btn_width as i32 - 1,
                    rect.y + 1,
                    btn_width,
                    inner_height,
                );

                if minus_rect.contains(*pos) {
                    self.decrement();
                } else if plus_rect.contains(*pos) {
                    self.increment();
                }
            }
            _ => {
                self.base.handle_event(event);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::Point;
    use std::sync::{Arc, Mutex};

    #[test]
    fn stepper_default_values() {
        let s = Stepper::new(Rect::new(0, 0, 120, 30));
        assert_eq!(s.value(), 0);
        assert_eq!(s.kind(), WidgetKind::Stepper);
    }

    #[test]
    fn stepper_set_value_clamps_to_min() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        s.set_value(-10);
        assert_eq!(s.value(), 0); // clamped to min=0
    }

    #[test]
    fn stepper_set_value_clamps_to_max() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        s.set_value(200);
        assert_eq!(s.value(), 100); // clamped to max=100
    }

    #[test]
    fn stepper_set_value_emits_signal() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        let captured = Arc::new(Mutex::new(None));
        s.value_changed.connect({
            let captured = Arc::clone(&captured);
            move |val: Arc<i32>| {
                *captured.lock().unwrap() = Some(*val);
            }
        });

        s.set_value(42);
        assert_eq!(s.value(), 42);
        assert_eq!(*captured.lock().unwrap(), Some(42));
    }

    #[test]
    fn stepper_increment_decrement() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        s.increment();
        assert_eq!(s.value(), 1);
        s.increment();
        assert_eq!(s.value(), 2);
        s.decrement();
        assert_eq!(s.value(), 1);
    }

    #[test]
    fn stepper_increment_clamped_to_max() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        s.set_value(100);
        s.increment();
        assert_eq!(s.value(), 100);
    }

    #[test]
    fn stepper_decrement_clamped_to_min() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        s.set_value(0);
        s.decrement();
        assert_eq!(s.value(), 0);
    }

    #[test]
    fn stepper_set_min_max() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        s.set_min(10);
        s.set_max(50);
        // Current value should be re-clamped
        assert_eq!(s.value(), 10);
        s.set_value(30);
        assert_eq!(s.value(), 30);
        s.set_value(5);
        assert_eq!(s.value(), 10);
        s.set_value(100);
        assert_eq!(s.value(), 50);
    }

    #[test]
    fn stepper_set_step() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        s.set_step(5);
        s.increment();
        assert_eq!(s.value(), 5);
        s.increment();
        assert_eq!(s.value(), 10);
        s.decrement();
        assert_eq!(s.value(), 5);
    }

    #[test]
    fn stepper_mouse_press_minus_decrements() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        // Set value to 5 first, then click in minus area (left side)
        s.set_value(5);
        // The minus button is btn_width wide, starting at x=0
        s.handle_event(&Event::MousePress { pos: Point::new(2, 15), button: 1 });
        assert_eq!(s.value(), 4);
    }

    #[test]
    fn stepper_mouse_press_plus_increments() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        // The plus button is btn_width wide on the right side
        // btn_width = min(30, 120/3).max(20) = min(30, 40).max(20) = 30
        // plus_rect starts at x = 0 + 120 - 30 - 1 = 89
        s.handle_event(&Event::MousePress { pos: Point::new(100, 15), button: 1 });
        assert_eq!(s.value(), 1);
    }

    #[test]
    fn stepper_disabled_blocks_events() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        s.set_enabled(false);
        s.handle_event(&Event::MousePress { pos: Point::new(100, 15), button: 1 });
        assert_eq!(s.value(), 0);
    }

    #[test]
    fn stepper_svg_output() {
        let mut s = Stepper::new(Rect::new(0, 0, 120, 30));
        let svg = crate::widget::svg::render_to_svg(&mut s);
        assert!(svg.starts_with("<svg"));
    }
}