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
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Progress bar widget.
use crate::core::{Color, Font, HorizontalAlignment, Orientation, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::RenderContext;
use crate::signal::Signal1;
use crate::widget::capability::coercion::{
    expect_bool, expect_i64, expect_orientation, orientation_to_str,
};
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};
/// Progress bar widget.
pub struct ProgressBar {
    base: BaseWidget,
    minimum: i32,
    maximum: i32,
    value: i32,
    text_visible: bool,
    orientation: Orientation,
    inverted_appearance: bool,
    pub value_changed: Signal1<i32>,
}
impl ProgressBar {
    /// Creates a progress bar with default range 0-100.
    pub fn new(geometry: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::ProgressBar, geometry, "ProgressBar"),
            minimum: 0,
            maximum: 100,
            value: 0,
            text_visible: true,
            orientation: Orientation::Horizontal,
            inverted_appearance: false,
            value_changed: Signal1::new(),
        }
    }
    /// Returns minimum value.
    pub fn minimum(&self) -> i32 {
        self.minimum
    }
    /// Sets minimum value.
    pub fn set_minimum(&mut self, minimum: i32) {
        self.minimum = minimum;
        if self.maximum < self.minimum {
            self.maximum = self.minimum;
        }
        self.set_value(self.value); // Re-clamp
    }
    /// Returns maximum value.
    pub fn maximum(&self) -> i32 {
        self.maximum
    }
    /// Sets maximum value.
    pub fn set_maximum(&mut self, maximum: i32) {
        self.maximum = maximum;
        if self.minimum > self.maximum {
            self.minimum = self.maximum;
        }
        self.set_value(self.value); // Re-clamp
    }
    /// Sets both minimum and maximum in one call.
    /// This is a convenience writer; query bounds via `minimum()` and `maximum()`.
    pub fn set_range(&mut self, minimum: i32, maximum: i32) {
        self.minimum = minimum;
        self.maximum = maximum.max(minimum);
        self.set_value(self.value); // Re-clamp
    }
    /// Returns current value.
    pub fn value(&self) -> i32 {
        self.value
    }
    /// Sets value, clamped to valid range.
    pub fn set_value(&mut self, value: i32) {
        let clamped = value.clamp(self.minimum, self.maximum);
        if self.value == clamped {
            return;
        }
        self.value = clamped;
        self.value_changed.emit(self.value);
        self.base.request_redraw();
    }
    /// Resets progress bar to minimum value.
    pub fn reset(&mut self) {
        self.set_value(self.minimum);
    }
    /// Returns whether text is visible.
    pub fn is_text_visible(&self) -> bool {
        self.text_visible
    }
    /// Sets text visibility.
    pub fn set_text_visible(&mut self, visible: bool) {
        self.text_visible = visible;
        self.base.request_redraw();
    }
    /// Returns orientation.
    pub fn orientation(&self) -> Orientation {
        self.orientation
    }
    /// Sets orientation.
    pub fn set_orientation(&mut self, orientation: Orientation) {
        self.orientation = orientation;
        self.base.request_redraw();
    }
    /// Returns whether appearance is inverted.
    pub fn is_inverted_appearance(&self) -> bool {
        self.inverted_appearance
    }
    /// Sets inverted appearance.
    pub fn set_inverted_appearance(&mut self, inverted: bool) {
        self.inverted_appearance = inverted;
        self.base.request_redraw();
    }
    /// Returns progress as percentage (0 to 1).
    pub fn progress(&self) -> f32 {
        if self.maximum == self.minimum {
            return 0.0;
        }
        // Use saturating_sub to prevent integer overflow.
        ((self.value.saturating_sub(self.minimum)) as f32)
            / ((self.maximum.saturating_sub(self.minimum)) as f32)
    }
    /// Returns formatted text for display.
    fn format_text(&self) -> String {
        if !self.text_visible {
            return String::new();
        }
        let percentage = self.progress() * 100.0;
        format!("{}%", percentage.round() as i32)
    }
}
// Implement Widget trait
impl Widget for ProgressBar {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        match self.orientation() {
            Orientation::Horizontal => Size::new(120, 20),
            Orientation::Vertical => Size::new(20, 120),
        }
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `ProgressBar`'s property contract.
///
/// `progress` is derived from `minimum`/`maximum`/`value`, so it is readable but
/// deliberately not writable — the same split the schema records, and the same
/// answer the previous centralised writer gave.
impl WidgetProperties for ProgressBar {
    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)),
            "text_visible" => Ok(CapabilityValue::Bool(self.is_text_visible())),
            "orientation" => {
                Ok(CapabilityValue::String(orientation_to_str(self.orientation()).to_string()))
            }
            "inverted_appearance" => Ok(CapabilityValue::Bool(self.is_inverted_appearance())),
            "progress" => Ok(CapabilityValue::Float(self.progress() as f64)),
            _ => 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(())
            }
            "text_visible" => {
                self.set_text_visible(expect_bool(value)?);
                Ok(())
            }
            "orientation" => {
                self.set_orientation(expect_orientation(value)?);
                Ok(())
            }
            "inverted_appearance" => {
                self.set_inverted_appearance(expect_bool(value)?);
                Ok(())
            }
            // `progress` has no setter: it is a function of the range. Reporting it
            // as unsupported keeps the read-only contract explicit.
            "progress" => Err(CapabilityAccessError::ReadOnlyProperty),
            _ => base_property_set(self, name, value),
        }
    }

    fn property_names(&self) -> &'static [&'static str] {
        // Mirrors `PROGRESS_BAR_PROPERTIES`.
        property_names_of![
            "minimum",
            "maximum",
            "value",
            "text_visible",
            "orientation",
            "inverted_appearance",
            "progress",
            BASE_PROPERTY_NAMES
        ]
    }
}

impl EventHandler for ProgressBar {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        // Progress bar is usually non-interactive
    }
}
impl Draw for ProgressBar {
    fn draw(&mut self, context: &mut RenderContext) {
        // Draw base widget
        let rect = self.geometry();
        let progress = self.progress();
        let style = self.style();
        let bg = style.background_color.unwrap_or(Color::rgb(240, 240, 240));
        let text_color = style.text_color.unwrap_or(Color::rgb(0, 0, 0));
        // Draw background
        context.fill_rect(Rect::new(rect.x, rect.y, rect.width, rect.height), bg);
        // Draw border
        if let Some(border_color) = style.border_color {
            context.draw_rect(Rect::new(rect.x, rect.y, rect.width, rect.height), border_color);
        }
        // Draw progress bar
        match self.orientation {
            Orientation::Horizontal => {
                let progress_width = (rect.width as f32 * progress) as u32;
                let x = if self.inverted_appearance {
                    rect.x + rect.width as i32 - progress_width as i32
                } else {
                    rect.x
                };
                context.fill_rect(
                    Rect::new(x, rect.y, progress_width, rect.height),
                    Color::rgb(0, 120, 215),
                );
            }
            Orientation::Vertical => {
                let progress_height = (rect.height as f32 * progress) as u32;
                let y = if self.inverted_appearance {
                    rect.y
                } else {
                    rect.y + rect.height as i32 - progress_height as i32
                };
                context.fill_rect(
                    Rect::new(rect.x, y, rect.width, progress_height),
                    Color::rgb(0, 120, 215),
                );
            }
        }
        // Draw text if visible
        let text = self.format_text();
        if !text.is_empty() {
            context.draw_text(
                Point::new(rect.x + rect.width as i32 / 2, rect.y + rect.height as i32 / 2),
                &text,
                &Font::default(),
                text_color,
                HorizontalAlignment::Center,
            );
        }
    }
}

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

    #[test]
    fn progressbar_creation_defaults() {
        let pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        assert_eq!(pb.value(), 0);
        assert_eq!(pb.minimum(), 0);
        assert_eq!(pb.maximum(), 100);
        assert!(pb.is_text_visible());
        assert_eq!(pb.orientation(), Orientation::Horizontal);
        assert!(!pb.is_inverted_appearance());
    }

    #[test]
    fn progressbar_set_value() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        pb.set_value(50);
        assert_eq!(pb.value(), 50);
        pb.set_value(200); // clamp to max
        assert_eq!(pb.value(), 100);
        pb.set_value(-10); // clamp to min
        assert_eq!(pb.value(), 0);
    }

    #[test]
    fn progressbar_set_range() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        pb.set_minimum(10);
        pb.set_maximum(200);
        assert_eq!(pb.minimum(), 10);
        assert_eq!(pb.maximum(), 200);
    }

    #[test]
    fn progressbar_set_range_reclamps_value() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        pb.set_value(50);
        pb.set_range(60, 100);
        assert_eq!(pb.value(), 60);
    }

    #[test]
    fn progressbar_orientation() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        pb.set_orientation(Orientation::Vertical);
        assert_eq!(pb.orientation(), Orientation::Vertical);
        pb.set_orientation(Orientation::Horizontal);
        assert_eq!(pb.orientation(), Orientation::Horizontal);
    }

    #[test]
    fn progressbar_text_visible() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        assert!(pb.is_text_visible());
        pb.set_text_visible(false);
        assert!(!pb.is_text_visible());
        pb.set_text_visible(true);
        assert!(pb.is_text_visible());
    }

    #[test]
    fn progressbar_inverted_appearance() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        assert!(!pb.is_inverted_appearance());
        pb.set_inverted_appearance(true);
        assert!(pb.is_inverted_appearance());
        pb.set_inverted_appearance(false);
        assert!(!pb.is_inverted_appearance());
    }

    #[test]
    fn progressbar_reset() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        pb.set_value(75);
        assert_eq!(pb.value(), 75);
        pb.reset();
        assert_eq!(pb.value(), 0);
    }

    #[test]
    fn progressbar_progress_percentage() {
        let pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        assert!((pb.progress() - 0.0).abs() < f32::EPSILON);

        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        pb.set_value(50);
        assert!((pb.progress() - 0.5).abs() < f32::EPSILON);

        pb.set_value(100);
        assert!((pb.progress() - 1.0).abs() < f32::EPSILON);
    }

    #[test]
    fn progressbar_geometry_delegation() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        pb.set_geometry(Rect::new(10, 10, 300, 30));
        assert_eq!(pb.geometry(), Rect::new(10, 10, 300, 30));
    }

    #[test]
    fn progressbar_visibility() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        assert!(pb.is_visible());
        pb.hide();
        assert!(!pb.is_visible());
        pb.show();
        assert!(pb.is_visible());
    }

    #[test]
    fn progressbar_enabled() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        assert!(pb.is_enabled());
        pb.set_enabled(false);
        assert!(!pb.is_enabled());
        pb.set_enabled(true);
        assert!(pb.is_enabled());
    }

    #[test]
    fn progressbar_tooltip_roundtrip() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        assert!(pb.tooltip().is_empty());
        pb.set_tooltip("Progress info".to_string());
        assert_eq!(pb.tooltip(), "Progress info");
        pb.set_tooltip(String::new());
        assert!(pb.tooltip().is_empty());
    }

    #[test]
    fn progressbar_style_roundtrip() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        assert_eq!(*pb.style(), WidgetStyle::default());
        let custom = WidgetStyle::default().with_background(Color::rgb(220, 220, 220));
        pb.set_style(custom.clone());
        assert_eq!(*pb.style(), custom);
    }

    #[test]
    fn progressbar_id_kind() {
        let pb_a = ProgressBar::new(Rect::new(0, 0, 100, 20));
        let pb_b = ProgressBar::new(Rect::new(0, 0, 100, 20));
        assert_ne!(pb_a.id(), pb_b.id());
        assert_eq!(pb_a.kind(), WidgetKind::ProgressBar);
        assert_eq!(pb_b.kind(), WidgetKind::ProgressBar);
    }

    #[test]
    fn progressbar_signal_accessors() {
        let pb = ProgressBar::new(Rect::new(0, 0, 100, 20));
        let _value_changed = &pb.value_changed;
    }

    #[test]
    fn progressbar_size_hint_horizontal() {
        let pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        let hint = pb.size_hint();
        assert_eq!(hint, Size::new(120, 20));
    }

    #[test]
    fn progressbar_size_hint_vertical() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        pb.set_orientation(Orientation::Vertical);
        let hint = pb.size_hint();
        assert_eq!(hint, Size::new(20, 120));
    }
}