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

//! Arc widget — circular progress/indicator (BLUE13 R2.1).
use crate::core::{deg_to_rad, Color, Font, HorizontalAlignment, Point, Rect, Size};
use crate::event::{Event, EventHandler};
use crate::render::{RenderCommand, RenderContext};
use crate::widget::capability::coercion::{expect_bool, expect_u32};
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};

/// Arc widget for displaying circular progress or angular values.
pub struct Arc {
    base: BaseWidget,
    /// Current value (0-100 range mapped to arc angle).
    value: u32,
    /// Minimum value.
    min: u32,
    /// Maximum value.
    max: u32,
    /// Start angle in degrees (0 = top, clockwise).
    start_angle: i16,
    /// Total sweep angle in degrees (default 360 for full circle, 270 for gauge).
    sweep_angle: u16,
    /// Arc thickness in pixels.
    thickness: u32,
    /// Whether the arc is rounded at ends.
    rounded: bool,
    /// Whether to show the value as text in the center.
    show_value: bool,
    /// Whether the arc is in indeterminate (spinning) mode.
    indeterminate: bool,
}

impl Arc {
    /// Creates a new arc widget with the given geometry and default settings.
    ///
    /// Default range is 0-100, sweep angle is 360 degrees (full circle),
    /// thickness is 10 pixels, start angle is 0 (top), and the value text
    /// is visible.
    pub fn new(rect: Rect) -> Self {
        Self {
            base: BaseWidget::new(WidgetKind::Arc, rect, "Arc"),
            value: 0,
            min: 0,
            max: 100,
            start_angle: 0,
            sweep_angle: 360,
            thickness: 10,
            rounded: false,
            show_value: true,
            indeterminate: false,
        }
    }

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

    /// Returns the minimum value of the range.
    pub fn minimum(&self) -> u32 {
        self.min
    }

    /// Returns the maximum value of the range.
    pub fn maximum(&self) -> u32 {
        self.max
    }

    /// Returns the total sweep angle in degrees.
    pub fn sweep_angle(&self) -> u16 {
        self.sweep_angle
    }

    /// Returns the arc thickness in pixels.
    pub fn thickness(&self) -> u32 {
        self.thickness
    }

    /// Returns whether the arc is drawn in indeterminate (spinning) mode.
    pub fn is_indeterminate(&self) -> bool {
        self.indeterminate
    }

    /// Sets the value, clamped between min and max.
    ///
    /// Emits the `changed` signal when the value actually changes.
    pub fn set_value(&mut self, value: u32) {
        let clamped = value.clamp(self.min, self.max);
        if self.value == clamped {
            return;
        }
        self.value = clamped;
        self.base.changed.emit();
        self.base.request_redraw();
    }

    /// Sets the minimum value of the range, re-clamping the current value.
    pub fn set_minimum(&mut self, minimum: u32) {
        self.set_range(minimum, self.max);
    }

    /// Sets the maximum value of the range, re-clamping the current value.
    pub fn set_maximum(&mut self, maximum: u32) {
        self.set_range(self.min, maximum);
    }

    /// Sets both minimum and maximum values in one call.
    ///
    /// The current value is re-clamped to the new range.
    pub fn set_range(&mut self, min: u32, max: u32) {
        self.min = min.min(max);
        self.max = max.max(min);
        let clamped = self.value.clamp(self.min, self.max);
        if self.value != clamped {
            self.value = clamped;
            self.base.changed.emit();
        }
        self.base.request_redraw();
    }

    /// Sets the total sweep angle in degrees (e.g., 360 for full circle, 270 for gauge).
    pub fn set_sweep_angle(&mut self, angle: u16) {
        self.sweep_angle = angle;
        self.base.request_redraw();
    }

    /// Sets the arc thickness in pixels.
    pub fn set_thickness(&mut self, thickness: u32) {
        self.thickness = thickness.max(1);
        self.base.request_redraw();
    }

    /// Sets whether the arc ends are rounded.
    pub fn set_rounded(&mut self, rounded: bool) {
        self.rounded = rounded;
        self.base.request_redraw();
    }

    /// Sets whether the value text is shown in the center of the arc.
    pub fn set_show_value(&mut self, show: bool) {
        self.show_value = show;
        self.base.request_redraw();
    }

    /// Sets whether the arc is in indeterminate (spinning indicator) mode.
    pub fn set_indeterminate(&mut self, indeterminate: bool) {
        self.indeterminate = indeterminate;
        self.base.request_redraw();
    }

    /// Normalizes the current value to a fraction in [0.0, 1.0].
    fn normalized_value(&self) -> f32 {
        if self.max <= self.min {
            return 0.0;
        }
        (self.value - self.min) as f32 / (self.max - self.min) as f32
    }

    /// Returns the start and end angles in radians for the progress arc.
    ///
    /// The widget API uses degrees with 0 = top, clockwise. Internally the
    /// angles are converted to radians offset by -PI/2 so that 0 radians
    /// corresponds to the 3 o'clock position (standard math convention for
    /// the rendering backend).
    fn arc_angles(&self) -> (f32, f32) {
        let start_deg = self.start_angle as f32;
        let sweep_deg = self.sweep_angle as f32;
        let progress = self.normalized_value();
        let end_deg = start_deg + sweep_deg * progress;
        // Offset by -90 degrees so that 0 (top) → 3 o'clock convention.
        let offset = -90.0_f32;
        (deg_to_rad(start_deg + offset), deg_to_rad(end_deg + offset))
    }

    /// Formats the current value as a percentage string for center display.
    fn format_value_text(&self) -> String {
        if !self.show_value {
            return String::new();
        }
        let pct = self.normalized_value() * 100.0;
        format!("{}%", pct.round() as u32)
    }
}

impl Widget for Arc {
    fn base(&self) -> &BaseWidget {
        &self.base
    }

    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        let diameter = self.thickness * 4;
        Size::new(diameter.max(60), diameter.max(60))
    }
    impl_draw_bridge!();
    impl_widget_property_hooks!();
}

/// `Arc`'s property contract.
///
/// Read/write semantics are carried over unchanged from the centralised
/// `access_read_other.in.rs` / `access_write_other.in.rs` dispatch. Every name the
/// `ARC_PROPERTIES` schema publishes as readable is answered here, so the schema
/// and the contract cannot disagree about what exists.
impl WidgetProperties for Arc {
    fn get(&self, name: &str) -> Result<CapabilityValue, CapabilityAccessError> {
        match name {
            "value" => Ok(CapabilityValue::UInt(self.value() as u64)),
            "minimum" => Ok(CapabilityValue::UInt(self.minimum() as u64)),
            "maximum" => Ok(CapabilityValue::UInt(self.maximum() as u64)),
            "thickness" => Ok(CapabilityValue::UInt(self.thickness() as u64)),
            "sweep_angle" => Ok(CapabilityValue::UInt(self.sweep_angle() as u64)),
            "indeterminate" => Ok(CapabilityValue::Bool(self.is_indeterminate())),
            _ => base_property_get(self, name),
        }
    }

    fn set(&mut self, name: &str, value: CapabilityValue) -> Result<(), CapabilityAccessError> {
        match name {
            "value" => {
                self.set_value(expect_u32(value)?);
                Ok(())
            }
            "minimum" => {
                self.set_minimum(expect_u32(value)?);
                Ok(())
            }
            "maximum" => {
                self.set_maximum(expect_u32(value)?);
                Ok(())
            }
            "thickness" => {
                self.set_thickness(expect_u32(value)?);
                Ok(())
            }
            "sweep_angle" => {
                self.set_sweep_angle(expect_u32(value)? as u16);
                Ok(())
            }
            "indeterminate" => {
                self.set_indeterminate(expect_bool(value)?);
                Ok(())
            }
            _ => base_property_set(self, name, value),
        }
    }

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

impl EventHandler for Arc {
    fn handle_event(&mut self, event: &Event) {
        self.base.handle_event(event);
        // Arc is non-interactive by default; subclasses can override.
    }
}

impl Draw for Arc {
    fn draw(&mut self, context: &mut RenderContext) {
        let rect = self.geometry();
        let center = Point::new(rect.x + rect.width as i32 / 2, rect.y + rect.height as i32 / 2);

        // Resolve colors from style overrides, falling back to defaults.
        let track_color = self.style().background_color.unwrap_or(Color::rgb(220, 220, 220));

        let arc_color = self.style().text_color.unwrap_or(Color::rgb(0, 120, 215));

        // Radius is half the smaller dimension minus a small inset.
        let outer_radius = rect.width.min(rect.height).saturating_sub(2) / 2;
        if outer_radius < self.thickness {
            // Not enough space to draw anything meaningful.
            return;
        }

        // Draw the background track as a filled circle (pancake style).
        context.fill_circle(center, outer_radius, track_color);

        // Draw the progress indicator arc.
        let (start_rad, end_rad) = self.arc_angles();
        let inner_radius = outer_radius.saturating_sub(self.thickness);

        if self.indeterminate {
            // In indeterminate mode, draw a quarter-circle arc as a spinning
            // indicator. The arc covers 90 degrees starting at the computed
            // start angle (which should be animated externally by advancing
            // start_angle over time).
            let indet_sweep = deg_to_rad(90.0);
            context.execute_command(RenderCommand::DrawArc {
                center,
                radius: outer_radius,
                start_angle: start_rad,
                end_angle: start_rad + indet_sweep,
                color: arc_color,
                filled: true,
            });
        } else {
            // Draw the progress arc from start_angle to start_angle + sweep * progress.
            if (end_rad - start_rad).abs() > 0.001 {
                context.execute_command(RenderCommand::DrawArc {
                    center,
                    radius: outer_radius,
                    start_angle: start_rad,
                    end_angle: end_rad,
                    color: arc_color,
                    filled: true,
                });
            }

            // When rounded ends are enabled, draw small filled circles at the
            // start and end of the arc to create a rounded cap appearance.
            if self.rounded && (end_rad - start_rad).abs() > 0.001 {
                let half_thick = (self.thickness as f32 / 2.0).max(1.0) as u32;
                let cap_radius = half_thick.max(2);

                // Cap at the start of the arc.
                let sx = center.x + (outer_radius as f32 * start_rad.cos()) as i32;
                let sy = center.y + (outer_radius as f32 * start_rad.sin()) as i32;
                context.fill_circle(Point::new(sx, sy), cap_radius, arc_color);

                // Cap at the end of the arc.
                let ex = center.x + (outer_radius as f32 * end_rad.cos()) as i32;
                let ey = center.y + (outer_radius as f32 * end_rad.sin()) as i32;
                context.fill_circle(Point::new(ex, ey), cap_radius, arc_color);
            }
        }

        // Draw the inner hole (clear center) so the arc looks like a ring.
        // We draw a filled circle in the background color over the center,
        // simulating a donut punch-out.
        if inner_radius > 0 {
            // Use the style background color, or fall back to the track color
            // (which was already drawn as the full background circle). This
            // creates a visible donut hole rather than relying on TRANSPARENT
            // which can't erase the filled circle behind it.
            let bg = self.style().background_color.unwrap_or(Color::WHITE);
            context.fill_circle(center, inner_radius, bg);
        }

        // Draw the value text in the center of the arc, if enabled.
        let text = self.format_value_text();
        if !text.is_empty() {
            let font = Font::default();
            let metrics = context.measure_text(&text, &font);
            let text_width = metrics.width;
            let text_height = metrics.height;

            let text_x = center.x - (text_width as i32 / 2);
            let text_y = center.y - (text_height as i32 / 2);

            let text_color = self.style().text_color.unwrap_or(Color::rgb(0, 0, 0));
            context.draw_text(
                Point::new(text_x, text_y),
                &text,
                &font,
                text_color,
                HorizontalAlignment::Left,
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::{Color, Rect, Size};
    use crate::render::{PaintBackend, SoftwarePaintBackend};

    #[test]
    fn arc_creation_defaults() {
        let arc = Arc::new(Rect::new(0, 0, 200, 200));
        assert_eq!(arc.value(), 0);
        assert_eq!(arc.min, 0);
        assert_eq!(arc.max, 100);
        assert_eq!(arc.sweep_angle, 360);
        assert_eq!(arc.thickness, 10);
        assert!(!arc.rounded);
        assert!(arc.show_value);
        assert!(!arc.indeterminate);
        assert_eq!(arc.start_angle, 0);
    }

    #[test]
    fn arc_set_value_clamps() {
        let mut arc = Arc::new(Rect::new(0, 0, 200, 200));
        arc.set_value(50);
        assert_eq!(arc.value(), 50);

        // Above max should clamp to 100.
        arc.set_value(200);
        assert_eq!(arc.value(), 100);

        // Below min should clamp to 0.
        arc.set_value(0);
        assert_eq!(arc.value(), 0);
    }

    #[test]
    fn arc_set_range() {
        let mut arc = Arc::new(Rect::new(0, 0, 200, 200));
        arc.set_range(10, 50);
        assert_eq!(arc.min, 10);
        assert_eq!(arc.max, 50);

        // Value should be re-clamped to the new range.
        arc.set_value(30);
        assert_eq!(arc.value(), 30);

        // Value below new min clamps up.
        arc.set_value(5);
        assert_eq!(arc.value(), 10);

        // Value above new max clamps down.
        arc.set_value(60);
        assert_eq!(arc.value(), 50);
    }

    #[test]
    fn arc_indeterminate_mode() {
        let mut arc = Arc::new(Rect::new(0, 0, 200, 200));
        assert!(!arc.indeterminate);

        arc.set_indeterminate(true);
        assert!(arc.indeterminate);

        arc.set_indeterminate(false);
        assert!(!arc.indeterminate);
    }

    #[test]
    fn arc_draw_does_not_panic() {
        let mut arc = Arc::new(Rect::new(0, 0, 200, 200));
        arc.set_value(65);

        let mut backend = SoftwarePaintBackend::new(Size::new(200, 200), 1.0);
        backend.begin_frame(Color::WHITE);
        let mut context = RenderContext::new(&mut backend);
        arc.draw(&mut context);
        backend.end_frame();
    }

    #[test]
    fn arc_normalized_value_returns_zero_for_empty_range() {
        let mut arc = Arc::new(Rect::new(0, 0, 100, 100));
        arc.set_range(50, 50);
        assert!((arc.normalized_value() - 0.0).abs() < f32::EPSILON);
    }

    #[test]
    fn arc_normalized_value_half() {
        let mut arc = Arc::new(Rect::new(0, 0, 100, 100));
        arc.set_value(50);
        assert!((arc.normalized_value() - 0.5).abs() < f32::EPSILON);
    }

    #[test]
    fn arc_set_sweep_angle() {
        let mut arc = Arc::new(Rect::new(0, 0, 100, 100));
        assert_eq!(arc.sweep_angle, 360);
        arc.set_sweep_angle(270);
        assert_eq!(arc.sweep_angle, 270);
    }

    #[test]
    fn arc_set_thickness() {
        let mut arc = Arc::new(Rect::new(0, 0, 100, 100));
        assert_eq!(arc.thickness, 10);
        arc.set_thickness(20);
        assert_eq!(arc.thickness, 20);
        // Thickness should not drop below 1.
        arc.set_thickness(0);
        assert_eq!(arc.thickness, 1);
    }

    #[test]
    fn arc_rounded_toggle() {
        let mut arc = Arc::new(Rect::new(0, 0, 100, 100));
        assert!(!arc.rounded);
        arc.set_rounded(true);
        assert!(arc.rounded);
    }

    #[test]
    fn arc_show_value_toggle() {
        let mut arc = Arc::new(Rect::new(0, 0, 100, 100));
        assert!(arc.show_value);
        arc.set_show_value(false);
        assert!(!arc.show_value);
    }

    #[test]
    fn arc_geometry_delegation() {
        let mut arc = Arc::new(Rect::new(0, 0, 200, 200));
        arc.set_geometry(Rect::new(10, 10, 150, 150));
        assert_eq!(arc.geometry(), Rect::new(10, 10, 150, 150));
    }

    #[test]
    fn arc_size_hint() {
        let arc = Arc::new(Rect::new(0, 0, 200, 200));
        let hint = arc.size_hint();
        assert_eq!(hint, Size::new(60, 60));
    }

    #[test]
    fn arc_draw_indeterminate_does_not_panic() {
        let mut arc = Arc::new(Rect::new(0, 0, 200, 200));
        arc.set_indeterminate(true);

        let mut backend = SoftwarePaintBackend::new(Size::new(200, 200), 1.0);
        backend.begin_frame(Color::WHITE);
        let mut context = RenderContext::new(&mut backend);
        arc.draw(&mut context);
        backend.end_frame();
    }
}