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

//! Toggle button widget.
use crate::core::{HorizontalAlignment, Rect, Size};
use crate::render::RenderContext;
use crate::signal::{GenericSignal, Signal1};
use crate::widget::capability::coercion::{expect_bool, expect_string};
use crate::widget::capability::properties_trait::{base_property_get, base_property_set};
use crate::widget::capability::types::{CapabilityAccessError, CapabilityValue};
use crate::widget::capability::WidgetProperties;
use crate::widget::{BaseWidget, Draw, Widget, WidgetKind};
use crate::{impl_widget_property_hooks, property_names_of};
/// Toggle button state enumeration.
///
/// Derived from the checked and enabled flags, never stored: see
/// [`ToggleButton::state`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ToggleButtonState {
    /// Enabled and not checked.
    Normal,
    /// Enabled and checked. Disabled always wins over checked, so an unchecked
    /// *and* disabled button also reports [`ToggleButtonState::Disabled`].
    Checked,
    /// Not enabled; reported regardless of the checked flag.
    Disabled,
}
/// Toggle button: a two-state push button that latches on click.
///
/// Also carries press tracking (`is_pressed`) so it can render a pressed
/// appearance between mouse-down and mouse-up.
pub struct ToggleButton {
    base: BaseWidget,
    text: String,
    checked: bool,
    auto_exclusive: bool,
    group_id: Option<String>,
    pressed: bool,
    /// Emitted with the new checked flag whenever it changes. Semantically a
    /// synonym for `checked_changed`, kept for callers using the checked-state
    /// terminology.
    pub toggled: Signal1<bool>,
    /// Emitted with the new checked flag whenever it changes.
    pub checked_changed: Signal1<bool>,
    /// Emitted on the rising edge of the pressed flag (mouse down).
    pub pressed_signal: GenericSignal,
    /// Emitted on the falling edge of the pressed flag (mouse up).
    pub released_signal: GenericSignal,
    /// Emitted with the recomputed [`ToggleButtonState`] whenever the checked
    /// flag changes. Not emitted when only the enabled flag changes, so a
    /// disabled button can still report a stale `Normal`. Reading
    /// [`ToggleButton::state`] after `set_enabled` gives the current value.
    pub state_changed: Signal1<ToggleButtonState>,
}
impl ToggleButton {
    /// Creates an unchecked, enabled toggle button with the given caption.
    ///
    /// `geometry` is in parent-relative logical pixels.
    pub fn new(text: String, geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::ToggleButton, geometry, "ToggleButton"),
            text,
            checked: false,
            auto_exclusive: false,
            group_id: None,
            pressed: false,
            toggled: Signal1::new(),
            checked_changed: Signal1::new(),
            pressed_signal: GenericSignal::new(),
            released_signal: GenericSignal::new(),
            state_changed: Signal1::new(),
        }
    }
    /// Returns the button caption, drawn centered. Empty by default only if
    /// constructed that way (`new` takes the text up front).
    pub fn text(&self) -> &str {
        &self.text
    }
    /// Replaces the caption. No-op (and no redraw) when the text is unchanged.
    pub fn set_text(&mut self, text: impl Into<String>) {
        let text = text.into();
        if self.text != text {
            self.text = text;
            self.base.request_redraw();
        }
    }
    /// Returns the latched checked flag.
    pub fn is_checked(&self) -> bool {
        self.checked
    }
    /// Sets the checked flag.
    ///
    /// A no-op when the value is unchanged, which means **no signals fire on a
    /// redundant set**. On an actual change this emits `checked_changed` and
    /// `toggled` (both with the new flag) followed by `state_changed`, and
    /// requests a redraw.
    pub fn set_checked(&mut self, checked: bool) {
        if self.checked == checked {
            return;
        }
        self.checked = checked;
        self.base.request_redraw();
        self.checked_changed.emit(checked);
        self.toggled.emit(checked);
        self.state_changed.emit(self.state());
    }
    /// Flips the checked flag through [`ToggleButton::set_checked`], so the
    /// usual signals fire.
    pub fn toggle(&mut self) {
        self.set_checked(!self.checked);
    }
    /// Returns the auto-exclusive intent flag. Defaults to `false`.
    pub fn is_auto_exclusive(&self) -> bool {
        self.auto_exclusive
    }
    /// Sets the auto-exclusive intent flag.
    ///
    /// This records intent only: the button does **not** enforce exclusivity
    /// itself. A group manager is expected to read this flag plus
    /// [`ToggleButton::group_id`] and uncheck the group's other members when
    /// one is checked. Setting it requests a redraw even though the flag is not
    /// drawn.
    pub fn set_auto_exclusive(&mut self, exclusive: bool) {
        self.auto_exclusive = exclusive;
        self.base.request_redraw();
    }
    /// Returns the group this button belongs to, or `None` when ungrouped.
    ///
    /// The id is an opaque caller-chosen string; the widget only stores and
    /// reports it. See [`ToggleButton::set_auto_exclusive`].
    pub fn group_id(&self) -> Option<&str> {
        self.group_id.as_deref()
    }
    /// Sets (or clears, with `None`) the group id. See
    /// [`ToggleButton::group_id`].
    pub fn set_group_id(&mut self, group_id: Option<String>) {
        self.group_id = group_id;
        self.base.request_redraw();
    }
    /// Returns whether the button is currently held down.
    pub fn is_pressed(&self) -> bool {
        self.pressed
    }
    /// Sets the pressed flag.
    ///
    /// No-op when unchanged, so the signals fire only on an actual edge: a
    /// rising edge emits `pressed_signal`, a falling edge emits
    /// `released_signal`. Unlike the checked flag, this does not request a
    /// redraw.
    pub fn set_pressed(&mut self, pressed: bool) {
        if self.pressed == pressed {
            return;
        }
        self.pressed = pressed;
        if pressed {
            self.pressed_signal.emit();
        } else {
            self.released_signal.emit();
        }
    }
    /// Returns the interaction state derived from the enabled and checked
    /// flags. Disabled takes precedence over checked.
    pub fn state(&self) -> ToggleButtonState {
        if !self.base.enabled {
            ToggleButtonState::Disabled
        } else if self.checked {
            ToggleButtonState::Checked
        } else {
            ToggleButtonState::Normal
        }
    }
}
impl Widget for ToggleButton {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        let text_w = self.text().len() as u32 * 8 + 20;
        Size::new(text_w.max(75), 28)
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `ToggleButton`'s property contract.
///
/// `state` is the derived interaction state ("normal"/"checked"/"disabled") and
/// is read-only, which is why it has a read arm but no write arm here — exactly
/// as the previous centralised dispatch behaved.
impl WidgetProperties for ToggleButton {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "text" => Ok(CapabilityValue::String(self.text().to_string())),
            "checked" => Ok(CapabilityValue::Bool(self.is_checked())),
            "state" => {
                let state = match self.state() {
                    ToggleButtonState::Normal => "normal",
                    ToggleButtonState::Checked => "checked",
                    ToggleButtonState::Disabled => "disabled",
                };
                Ok(CapabilityValue::String(state.to_string()))
            }
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "text" => {
                self.set_text(expect_string(value)?);
                Ok(())
            }
            "checked" => {
                self.set_checked(expect_bool(value)?);
                Ok(())
            }
            "state" => Err(CapabilityAccessError::ReadOnlyProperty),
            _ => base_property_set(self, name, value),
        }
    }

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

impl Draw for ToggleButton {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.base.geometry();
        let state = self.state();
        let style = self.style();
        use crate::core::Color;

        // ── Background ──
        let bg_color = style.background_color.unwrap_or_else(|| match state {
            ToggleButtonState::Disabled => Color::rgb(220, 220, 220),
            ToggleButtonState::Checked => Color::rgb(200, 220, 255),
            ToggleButtonState::Normal => Color::rgb(240, 240, 240),
        });
        context.fill_rect(rect, bg_color);

        // ── Border ──
        let border_color = style.border_color.unwrap_or_else(|| {
            if self.checked {
                Color::rgb(80, 120, 200)
            } else {
                Color::rgb(180, 180, 180)
            }
        });
        let bw = style.border_width.unwrap_or(0);
        let border_width = if bw > 0 { bw } else { 1 };
        context.draw_rect_stroke(rect, border_color, border_width);

        // ── Text ──
        if !self.text.is_empty() {
            let text_color = style.text_color.unwrap_or_else(|| {
                if state == ToggleButtonState::Disabled {
                    Color::rgb(150, 150, 150)
                } else {
                    Color::rgb(0, 0, 0)
                }
            });
            let default_font = crate::core::Font::default();
            let font = style.font.as_ref().unwrap_or(&default_font);
            context.draw_text(
                crate::core::Point::new(
                    rect.x + rect.width as i32 / 2,
                    rect.y + rect.height as i32 / 2,
                ),
                &self.text,
                font,
                text_color,
                HorizontalAlignment::Center,
            );
        }
    }
}
impl crate::event::EventHandler for ToggleButton {
    fn handle_event(&mut self, event: &crate::event::Event) {
        self.base.handle_event(event);
        if !self.base.is_enabled() {
            return;
        }
        match event {
            crate::event::Event::MousePress { pos: _, button } if *button == 1 => {
                self.set_pressed(true);
            }
            crate::event::Event::MouseRelease { pos: _, button } if *button == 1 => {
                if self.pressed {
                    self.toggle();
                }
                self.set_pressed(false);
            }
            _ => { /* Other events are not relevant */ }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{Color, ObjectId, Rect};
    use crate::style::WidgetStyle;

    #[test]
    fn toggle_creation_defaults() {
        let tb = ToggleButton::new("Toggle".to_string(), Rect::new(0, 0, 100, 30));
        assert!(!tb.is_checked());
        assert_eq!(tb.text(), "Toggle");
        assert!(!tb.is_auto_exclusive());
        assert!(tb.group_id().is_none());
        assert!(!tb.is_pressed());
        assert_eq!(tb.state(), ToggleButtonState::Normal);
    }

    #[test]
    fn toggle_set_checked() {
        let mut tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 50, 30));
        tb.set_checked(true);
        assert!(tb.is_checked());
        assert_eq!(tb.state(), ToggleButtonState::Checked);
        tb.set_checked(false);
        assert!(!tb.is_checked());
        assert_eq!(tb.state(), ToggleButtonState::Normal);
    }

    #[test]
    fn toggle_toggle_method() {
        let mut tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 50, 30));
        assert!(!tb.is_checked());
        tb.toggle();
        assert!(tb.is_checked());
        tb.toggle();
        assert!(!tb.is_checked());
    }

    #[test]
    fn toggle_set_text() {
        let mut tb = ToggleButton::new("Old".to_string(), Rect::new(0, 0, 100, 30));
        assert_eq!(tb.text(), "Old");
        tb.set_text("New".to_string());
        assert_eq!(tb.text(), "New");
    }

    #[test]
    fn toggle_auto_exclusive() {
        let mut tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 50, 30));
        assert!(!tb.is_auto_exclusive());
        tb.set_auto_exclusive(true);
        assert!(tb.is_auto_exclusive());
        tb.set_auto_exclusive(false);
        assert!(!tb.is_auto_exclusive());
    }

    #[test]
    fn toggle_group_id() {
        let mut tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 50, 30));
        assert!(tb.group_id().is_none());
        tb.set_group_id(Some("group1".to_string()));
        assert_eq!(tb.group_id(), Some("group1"));
        tb.set_group_id(None);
        assert!(tb.group_id().is_none());
    }

    #[test]
    fn toggle_pressed_state() {
        let mut tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 50, 30));
        assert!(!tb.is_pressed());
        tb.set_pressed(true);
        assert!(tb.is_pressed());
        tb.set_pressed(false);
        assert!(!tb.is_pressed());
    }

    #[test]
    fn toggle_geometry_delegation() {
        let mut tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 100, 30));
        tb.set_geometry(Rect::new(10, 10, 200, 50));
        assert_eq!(tb.geometry(), Rect::new(10, 10, 200, 50));
    }

    #[test]
    fn toggle_visibility_delegation() {
        let mut tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 100, 30));
        assert!(tb.is_visible());
        tb.hide();
        assert!(!tb.is_visible());
        tb.show();
        assert!(tb.is_visible());
    }

    #[test]
    fn toggle_enabled_delegation() {
        let mut tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 100, 30));
        assert!(tb.is_enabled());
        tb.set_enabled(false);
        assert!(!tb.is_enabled());
        assert_eq!(tb.state(), ToggleButtonState::Disabled);
        tb.set_enabled(true);
        assert!(tb.is_enabled());
    }

    #[test]
    fn toggle_parent_children() {
        let mut tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 100, 30));
        assert!(tb.parent().is_none());
        let pid: ObjectId = 42;
        tb.set_parent(Some(pid));
        assert_eq!(tb.parent(), Some(pid));
        tb.set_parent(None);
        assert!(tb.parent().is_none());

        let cid: ObjectId = 100;
        tb.add_child(cid);
        assert_eq!(tb.children().len(), 1);
        assert_eq!(tb.children()[0], cid);
        tb.remove_child(cid);
        assert!(tb.children().is_empty());
    }

    #[test]
    fn toggle_tooltip_roundtrip() {
        let mut tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 100, 30));
        assert!(tb.tooltip().is_empty());
        tb.set_tooltip("Helpful tip".to_string());
        assert_eq!(tb.tooltip(), "Helpful tip");
        tb.set_tooltip(String::new());
        assert!(tb.tooltip().is_empty());
    }

    #[test]
    fn toggle_style_roundtrip() {
        let mut tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 100, 30));
        assert_eq!(*tb.style(), WidgetStyle::default());
        let custom = WidgetStyle::default().with_background(Color::rgb(200, 200, 200));
        tb.set_style(custom.clone());
        assert_eq!(*tb.style(), custom);
    }

    #[test]
    fn toggle_id_kind() {
        let tb_a = ToggleButton::new("A".to_string(), Rect::new(0, 0, 50, 30));
        let tb_b = ToggleButton::new("B".to_string(), Rect::new(0, 0, 50, 30));
        assert_ne!(tb_a.id(), tb_b.id());
        assert_eq!(tb_a.kind(), WidgetKind::ToggleButton);
        assert_eq!(tb_b.kind(), WidgetKind::ToggleButton);
    }

    #[test]
    fn toggle_signal_accessors() {
        let tb = ToggleButton::new("T".to_string(), Rect::new(0, 0, 50, 30));
        // Signal1<bool>
        let _toggled = &tb.toggled;
        let _checked = &tb.checked_changed;
        let _state = &tb.state_changed;
        // GenericSignal
        let _pressed = &tb.pressed_signal;
        let _released = &tb.released_signal;
    }
}