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
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT
//! Progress bar widget.
use crate::compat::{format, String, ToString};
use crate::core::{Color, Font, HorizontalAlignment, Orientation, 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, expect_text_direction, orientation_to_str,
text_direction_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::metrics::{dimensions, ControlMetrics};
use crate::widget::numeric::ordered_clamp_i32;
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,
/// The writing direction the value axis runs in.
///
/// # Why this is not `inverted_appearance`
///
/// `inverted_appearance` is a *presentational* choice — "anchor the fill to the far end" — and it
/// is what an indeterminate or a trailing-edge indicator wants. Direction is a *reading* fact: in
/// an Arabic or Hebrew interface the run begins at the right edge because that is where the user
/// starts reading, so the fill grows leftward and "a third of the way through" is measured from
/// the right. The two coincide for RTL — which is why one bool could stand in for both — but they
/// are different statements, and collapsing them would mean a control could not be right-anchored
/// in a left-to-right locale. BLUE22 §5.1 rejects a full `LayoutMirroring`; it does not reject
/// "a control knows which end its line begins at", which is what `TextDirection` is for.
///
/// Defaults to left-to-right, so a bar that never asks behaves exactly as it did.
direction: crate::core::TextDirection,
/// Whether the bar shows an unknown-progress sweep instead of a value.
///
/// An indeterminate bar is the honest state for "work is happening but the amount
/// cannot be quantified" — the alternative, showing a fabricated percentage, is worse
/// than showing none. When set, `value`/`progress` are ignored and a band sweeps the
/// track on a fixed period.
indeterminate: bool,
/// The sweep phase for the indeterminate state, in `0.0..1.0`.
///
/// A single looping value rather than a two-end property: the sweep is **periodic**, so
/// "half way" is a different concept from "ended" and a driver's settle-to-target model
/// does not describe it. `ProgressBar::tick` wraps it with
/// [`jump_to`](crate::style::PropertyDriver::jump_to), which is the driver's own spelling
/// of "and then restart" — the same operation, named at the one type that owns the value
/// (BLUE24 §2.3's "one animation state type" rule; the plan's own §2.2 text says this
/// control's loop is the case a driver *cannot* be aimed at, and `jump_to` is why it can
/// still be *held* by one).
sweep_phase: crate::style::PropertyDriver,
/// Emitted with the new value after any change to `value` — from
/// `set_value`, the steppers, or keyboard/wheel input. Not emitted when the
/// value is set to the value it already had.
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,
direction: crate::core::TextDirection::default(),
indeterminate: false,
// The sweep is a slow, steady loop; `slow` is the theme's longest token and matches
// the unhurried feel an indeterminate indicator should have.
sweep_phase: crate::style::PropertyDriver::at(0.0, crate::style::MotionSlot::Slow),
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()`.
///
/// Not gated by `enabled` for the same reason as [`ProgressBar::set_value`].
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.
///
/// `value_changed` is deliberately not gated by `enabled`: it reports the value the
/// host just wrote, and a disabled progress bar is still a data display its host
/// reads. The `enabled` contract exists to stop a disabled control from acting on
/// *user* input, which this path never involves.
pub fn set_value(&mut self, value: i32) {
let clamped = ordered_clamp_i32(value, 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 the writing direction the value axis runs in.
pub fn direction(&self) -> crate::core::TextDirection {
self.direction
}
/// Sets the writing direction the value axis runs in, and repaints.
///
/// A bar that runs right-to-left fills from the right edge, so its filled run is measured from
/// the beginning of the line — the edge the reader starts at — rather than from the left.
pub fn set_direction(&mut self, direction: crate::core::TextDirection) {
self.direction = direction;
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)
}
/// Whether the bar is showing an indeterminate sweep.
pub fn is_indeterminate(&self) -> bool {
self.indeterminate
}
/// Switches between the value bar and the indeterminate sweep.
///
/// Turning it on starts the sweep from the phase it is already at, so a bar that has
/// been indeterminate before resumes rather than jumping; turning it off simply stops
/// the frames and the bar returns to showing `value`.
pub fn set_indeterminate(&mut self, indeterminate: bool) {
if self.indeterminate == indeterminate {
return;
}
self.indeterminate = indeterminate;
self.base.request_redraw();
}
/// Advances the indeterminate sweep, reporting whether another frame is needed.
///
/// The sweep is a loop, so while indeterminate this always owes a frame; while showing
/// a value it owes none, which is why a determinate bar costs nothing per frame.
pub fn tick(&mut self, delta_ms: u32) -> bool {
if !self.indeterminate {
return false;
}
// Advance toward the far end, and when it arrives wrap straight back to the near end
// without a settle frame: a sweep that paused at each end would read as a stutter.
//
// # Why the test is `!moving` and not a named `arrived`
//
// The driver answers "has this not reached its target yet", which is `false` on the
// frame the value **lands** on the target — and that landing frame is the one to wrap. An
// earlier version of this read treated the return value as "arrived", so it wrapped on
// every frame *except* the one that arrived: the phase was reset to 0 on the first tick and
// then never wrapped again, making the first two samples of the band identical and the
// sweep appear to jump backwards. The flag now says what the value means.
self.sweep_phase.set_target(1.0);
let moving = self.sweep_phase.tick(delta_ms);
if !moving {
self.sweep_phase.jump_to(0.0);
}
self.base.request_redraw();
true
}
/// The band the indeterminate sweep is currently painting, as a half-open extent along
/// the bar's own axis, or `None` when the bar is determinate.
///
/// # Why the band is a fraction of the run, not a fixed width
///
/// A fixed-width band would be a huge fraction of a short bar and a sliver of a long one,
/// so the same indicator would read as two different things. Deriving it from the run
/// keeps "one third of the way through" meaning the same on every bar, which is the same
/// rule the scroll bar's minimum length follows.
pub fn indeterminate_band(&self) -> Option<(u32, u32)> {
if !self.indeterminate {
return None;
}
let rect = self.geometry();
let bar = ControlMetrics::centered_band(rect, dimensions::PROGRESS_HEIGHT);
let run = match self.orientation {
Orientation::Horizontal => bar.width,
Orientation::Vertical => bar.height,
};
if run == 0 {
return None;
}
// A third of the run travels from fully off the near end to fully off the far end, so the
// band enters, crosses and leaves rather than appearing in place.
let band = (run / 3).max(1);
let travel = run + band;
let lead = (travel as f32 * self.sweep_phase.value()) as u32;
// The band's **trailing** edge is what travels; its length is fixed.
//
// Deriving both edges from `lead` (a `lead.min(run)` end and a `lead - band` start) made the
// bar grow a band out of its near edge over the first third of the sweep and only then move
// it: the second frame of `the_indeterminate_band_sweeps_across_frames` read `(0, 0)` ->
// `(0, 16)`, i.e. the extent changed but the *position* did not, which is the one thing a
// sweep must not do. Clamping only the start — and taking the end from the start plus the
// band — makes the length (`run / 3`) an invariant of the whole cycle and puts the motion
// in the position, where the scroll bar's minimum-length rule already puts it: that rule
// extends a thumb until the visible extent is meaningful, while this one needs a *fixed*
// extent so an observer can read movement out of consecutive frames.
let start = lead.saturating_sub(band).min(run);
// Clipped to the run so a partly-arrived band paints only the part that is on the bar: the
// last third of the sweep has the band leaving, and a width that ran past `run` would paint
// outside the control, which nothing clips at this layer.
let visible = (start + band).min(run).saturating_sub(start);
Some((start, visible))
}
/// Returns formatted text for display.
fn format_text(&self) -> String {
if !self.text_visible {
return String::new();
}
// An indeterminate bar has no number to show, and printing a stale one would be a
// fabricated fact — the exact thing the state exists to avoid.
if self.indeterminate {
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!();
// The indeterminate sweep is the animation; a determinate bar owes no frames.
fn tick(&mut self, delta_ms: u32) -> bool {
ProgressBar::tick(self, delta_ms)
}
fn is_animating(&self) -> bool {
self.indeterminate
}
}
/// `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())),
"direction" => {
Ok(CapabilityValue::String(text_direction_to_str(self.direction()).to_string()))
}
"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(())
}
"direction" => {
self.set_direction(expect_text_direction(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",
"direction",
"progress",
BASE_PROPERTY_NAMES
]
}
/// Runs one of the commands `progress_bar` publishes.
///
/// Every published name carries a payload (`value`, `orientation`, or the
/// two-number range), so each is answered through the property route with a
/// value — `value` / `orientation` / `minimum` + `maximum`. Reporting
/// `OutOfRange` for a payload-less call is the same convention the sibling
/// display controls (`lcd_number`, `scrollbar`, `slider`) already use, and it
/// is what an absent `command` override cannot do: the trait default answers
/// `UnknownCommand`, which `invoke_command` reports as a registry/
/// implementation disagreement for a name the capability does publish.
fn command(&mut self, name: &str) -> Result<(), CapabilityAccessError> {
match name {
"set_value" | "set_orientation" | "set_range" => Err(CapabilityAccessError::OutOfRange),
_ => Err(CapabilityAccessError::UnknownCommand),
}
}
}
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().clone();
// The track is the bar's *groove*: the empty run behind the fill. It used to be
// `style.background_color` with a light-grey literal fallback, but `progress_bar`
// classifies as `WidgetRole::Accent` and `role_colors` writes the theme's **accent**
// colour there. The groove therefore painted the same saturated orange as the fill
// would, so `progress_bar.svg` was a solid slab in which the value was invisible —
// the control's whole purpose. A groove must be low-emphasis, so it is *derived*
// from the resolved surface rather than read from a field that carries the accent.
// The same derivation, for the same reason, is in `range_slider.rs`.
let window_fill = {
let manager = crate::style::theme_manager();
manager.current_theme().map(|active| active.colors.background).unwrap_or(Color::WHITE)
};
let ink = style.text_color.unwrap_or_else(|| window_fill.contrast_color());
// A caller-set background is the groove; a theme-derived one is the window fill
// (or the accent) and is replaced by one visible step from the surface. The filter
// is on the **resolved** value, not only on the provenance, because a control whose
// role resolves to the window fill paints an invisible groove either way.
let groove_from_surface = window_fill.blend(&ink, 0.14);
let track_color = match if style.theme_derived { None } else { style.background_color } {
Some(resolved) if resolved != window_fill => resolved,
_ => groove_from_surface,
};
// The fill resolves the explicit style first, then the theme's own resolved style
// for this control — the accent — and only then the literal, so a build without a
// theme renders exactly what it used to.
//
// The filled portion is **chrome**, not data: it expresses "how much of this task is
// done", and that reading is carried by its *extent*, not by its hue. Hardcoding it
// meant a light and a dark window showed the same blue bar, so the switch did
// nothing.
let themed = crate::style::resolved_theme_style("progress_bar");
let fill = style
.background_color
.filter(|_| !style.theme_derived)
.or_else(|| themed.as_ref().and_then(|resolved| resolved.background_color))
.or_else(|| crate::style::semantic_color(crate::style::SemanticColor::Info))
.unwrap_or(Color::rgb(0, 120, 215));
// The bar is a **fixed-height** rounded track centred in `rect`, not the whole of
// it. Using `rect.height` made a 240x120 census cell a 240x120 slab, which is a
// filled rectangle rather than a progress bar; Material's linear indicator is 4px
// tall with `height / 2` rounded ends. `rect` stays the widget's occupancy — its
// hit area and layout slot — and only the drawn chrome takes the constant.
//
// The height comes from the shared `dimensions` table and the box from
// `ControlMetrics::centered_band`, the derivation for "a line of this thickness
// across the middle of my area". A local `const BAR_HEIGHT: u32 = 4` was the same
// fact written a second time: the table already names it, so the two could drift
// and nothing would have connected a progress bar's thickness to its neighbour's.
let bar_rect = ControlMetrics::centered_band(rect, dimensions::PROGRESS_HEIGHT);
let bar_height = bar_rect.height;
// How much of the run is filled, in pixels along the bar's own axis.
let filled_len = match self.orientation {
Orientation::Horizontal => (bar_rect.width as f32 * progress) as u32,
Orientation::Vertical => (bar_rect.height as f32 * progress) as u32,
}
.min(match self.orientation {
Orientation::Horizontal => bar_rect.width,
Orientation::Vertical => bar_rect.height,
});
// Draw background (the groove).
//
// The groove is the control's *own chrome* — the empty run the fill is measured against — so
// it is drawn unconditionally, including at value 0. Only the fill below is conditional.
context.fill_rounded_rect(bar_rect, bar_height / 2, track_color);
// Draw border
if let Some(border_color) = style.border_color {
context.draw_rect(bar_rect, border_color);
}
// Draw the filled run — but only when there is one.
//
// A zero-extent rectangle is a *degenerate* element, not a small one. The SVG backend emits
// it faithfully (`<rect width="0" ...>`), where it paints nothing, so a bar at value 0
// claimed a fill and drew none: `snapshots/svg/progress_bar.svg` carried `width="0"` on the
// fill line. Worse, the two backends *disagreed* about the same command —
// `SoftwareSurface::fill_rounded_rect` returns early for a zero-extent rect — so the
// snapshot documented chrome no rasteriser ever produced. Guarding here fixes both: the
// emitted stream no longer contains an element that means nothing, and it now matches what
// the rasteriser does with the identical command.
//
// The guard is `filled_len > 0`, and the same for both arms. A guard on `progress > 0.0`
// alone would be wrong: a long bar at a *tiny* non-zero value floors to `filled_len == 0`
// too, and the degenerate rect would come straight back.
if filled_len > 0 {
match self.orientation {
Orientation::Horizontal => {
// `inverted_appearance` and the direction are two ways to reach the far end, and
// they compose: an inverted bar in an RTL locale anchors to the left, which is
// what XOR expresses and what a naive `||` would get wrong. The vertical arm is
// unaffected — the block axis is not mirrored in either direction, which is the
// same rule `slider` applies (its vertical run is top-to-bottom in every
// direction).
let from_far_end = self.inverted_appearance ^ self.direction.is_right_to_left();
let x = if from_far_end {
bar_rect.x + bar_rect.width as i32 - filled_len as i32
} else {
bar_rect.x
};
context.fill_rounded_rect(
Rect::new(x, bar_rect.y, filled_len, bar_height),
bar_height / 2,
fill,
);
}
Orientation::Vertical => {
let y = if self.inverted_appearance {
bar_rect.y
} else {
bar_rect.y + bar_rect.height as i32 - filled_len as i32
};
context.fill_rounded_rect(
Rect::new(bar_rect.x, y, bar_rect.width, filled_len),
bar_height / 2,
fill,
);
}
}
}
// Indeterminate sweep: one band travelling the track, drawn **instead of** the value
// fill. The band's position is `indeterminate_band`'s, so the animation test and the
// draw path cannot disagree about where it is.
if let Some((offset, extent)) = self.indeterminate_band() {
if extent > 0 {
match self.orientation {
Orientation::Horizontal => context.fill_rounded_rect(
Rect::new(bar_rect.x + offset as i32, bar_rect.y, extent, bar_height),
bar_height / 2,
fill,
),
Orientation::Vertical => context.fill_rounded_rect(
Rect::new(bar_rect.x, bar_rect.y + offset as i32, bar_rect.width, extent),
bar_height / 2,
fill,
),
}
}
}
// Draw text if visible
//
// The band is the whole control, not the 4px bar: a label centred on the bar alone
// would be clipped to four rows. `text_line` derives the glyph box from the band, so
// the label is centred rather than starting on the band's middle line.
//
// The ink is the contrast colour of the surface actually behind the label. The
// label is centred on the control, so the question is whether the filled run
// covers that centre: if it does, `fill.contrast_color()` is the legible choice;
// if it does not, the label sits on the groove and the groove's contrast colour is.
// It used to be a hardcoded `Color::rgb(0, 0, 0)`, which is 1.12:1 against the dark
// theme's background — the label was unreadable on exactly the appearance the
// census renders. Same rule, and the same mistake it removes, as `roller.rs`.
let text_color = if style.theme_derived || style.text_color.is_none() {
// The filled run, as a half-open interval along its own axis.
let (start, end) = match self.orientation {
Orientation::Horizontal if self.inverted_appearance => (
bar_rect.x + bar_rect.width as i32 - filled_len as i32,
bar_rect.x + bar_rect.width as i32,
),
Orientation::Horizontal => (bar_rect.x, bar_rect.x + filled_len as i32),
Orientation::Vertical if !self.inverted_appearance => (
bar_rect.y + bar_rect.height as i32 - filled_len as i32,
bar_rect.y + bar_rect.height as i32,
),
Orientation::Vertical => (bar_rect.y, bar_rect.y + filled_len as i32),
};
let label_centre = match self.orientation {
Orientation::Horizontal => rect.x + rect.width as i32 / 2,
Orientation::Vertical => rect.y + rect.height as i32 / 2,
};
if filled_len > 0 && label_centre >= start && label_centre < end {
fill.contrast_color()
} else {
track_color.contrast_color()
}
} else {
ink
};
let text = self.format_text();
if !text.is_empty() {
context.draw_text_line(
rect,
&text,
&Font::default(),
text_color,
HorizontalAlignment::Center,
);
}
}
}
#[cfg(test)]
mod tests {
use super::*;
// `Vec` comes from `crate::compat` rather than from `std`, because the `alloc_frugal`
// profile has no `std::vec` and a test that named it directly would not compile there.
use crate::compat::Vec;
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));
}
/// Returns the `(x, y, width, height)` of every `<rect>` whose `fill` is `fill`.
///
/// Parsed per line rather than with a regex so the test needs no extra dependency; the backend
/// emits exactly one element per line, so this is the whole element stream.
fn rects_with_fill(svg: &str, fill: &str) -> Vec<(i32, i32, i32, i32)> {
svg.lines()
.filter(|line| line.contains("<rect") && line.contains(fill))
.map(|line| {
let attr = |name: &str| -> i32 {
line.split(&std::format!("{name}=\""))
.nth(1)
.and_then(|rest| rest.split('"').next())
.and_then(|value| value.parse().ok())
.unwrap_or_else(|| panic!("no {name} on: {line}"))
};
(attr("x"), attr("y"), attr("width"), attr("height"))
})
.collect()
}
/// The colour `draw` resolves for the filled run, read the same way `draw` reads it.
///
/// Derived rather than hardcoded because the value is theme-dependent (the fill is chrome and
/// follows the resolved theme style). Asserting a literal here would make the test fail on a
/// theme change for a reason unrelated to what it pins.
/// The guard a theme-reading test must hold.
///
/// # Why this exists rather than each test calling the manager directly
///
/// `fill_color` below reads the **process-wide** theme manager, and libtest runs tests in
/// parallel: another test installing a theme between that read and the `render_to_svg` that
/// follows would make the resolved colour differ from the one the assertions search for, so
/// `rects_with_fill` would find nothing and the test would fail for a reason unrelated to the
/// bar. That is not hypothetical — it was observed as an intermittent red on
/// `a_vertical_bar_is_not_mirrored_by_direction` and `direction_and_inverted_appearance_compose`
/// while both passed in isolation.
///
/// # Why the guard is optional
///
/// The theme module exists only under `device_profile`, which is the same condition that makes
/// a theme manager exist to contend for. A `mini`/`embedded` build has neither, so there is
/// nothing to serialise against and the guard is `None` — the same shape `meter`'s test uses.
/// This is why the return is an `Option` rather than the guard itself: the caller holds it the
/// same way either way (`let _guard = theme_guard();`), so no test needs a `#[cfg]` of its own.
fn theme_guard() -> Option<crate::compat::MutexGuard<'static, ()>> {
#[cfg(device_profile)]
{
Some(crate::style::theme_test_guard())
}
#[cfg(not(device_profile))]
{
None
}
}
fn fill_color() -> Color {
crate::style::resolved_theme_style("progress_bar")
.and_then(|resolved| resolved.background_color)
.or_else(|| crate::style::semantic_color(crate::style::SemanticColor::Info))
.unwrap_or(Color::rgb(0, 120, 215))
}
/// A bar at value 0 must emit **nothing** for its fill, in either orientation.
///
/// A zero-extent `<rect>` is degenerate: it is present in the stream, it is not a drawing, and
/// the software rasteriser skips the identical command — so the snapshot showed an element the
/// raster never produced (`snapshots/svg/progress_bar.svg` carried `width="0"`). The groove
/// underneath is the control's own chrome and must still be there: "no fill" is the assertion,
/// "no drawing at all" is not.
#[test]
fn progressbar_at_zero_emits_no_fill_but_keeps_its_groove() {
let _guard = theme_guard();
let fill = fill_color();
for orientation in [Orientation::Horizontal, Orientation::Vertical] {
for inverted in [false, true] {
let mut pb = ProgressBar::new(Rect::new(0, 0, 240, 120));
pb.set_orientation(orientation);
pb.set_inverted_appearance(inverted);
pb.set_value(0);
assert_eq!(pb.value(), 0, "the precondition of this test is a 0 value");
let svg = crate::widget::svg::render_to_svg(&mut pb);
let filled =
rects_with_fill(&svg, &crate::render::svg::convert::color_to_rgba(&fill));
assert!(
filled.is_empty(),
"a 0-value {orientation:?} bar (inverted={inverted}) emitted a fill: {filled:?}\n{svg}"
);
// The groove is unconditional chrome, so it must survive the guard above. The
// window background is the only other rect, and it is the full control rect.
let drawn: Vec<_> = svg
.lines()
.filter(|line| line.contains("<rect") && line.contains("rx=\""))
.collect();
assert!(
!drawn.is_empty(),
"a 0-value bar still draws its own groove, not just the window background: {svg}"
);
// The groove is also a *fixed-height band* centred in the control, not the
// control itself: the 240x120 census cell used to be painted as a 240x120
// slab, which is a filled rectangle rather than a progress bar. This pins
// the shared `centered_band` derivation now that it supplies the geometry.
assert!(
svg.contains(&format!("height=\"{}\"", dimensions::PROGRESS_HEIGHT)),
"the groove is {0}px tall, not the whole cell: {svg}",
dimensions::PROGRESS_HEIGHT
);
}
}
}
/// The complement of the test above: a non-zero value that reaches a whole pixel of run **does**
/// emit a fill, and the emitted extent is the filled length, never zero.
#[test]
fn progressbar_above_zero_emits_a_non_degenerate_fill() {
let _guard = theme_guard();
let fill = fill_color();
let mut pb = ProgressBar::new(Rect::new(0, 0, 240, 120));
pb.set_value(50);
let svg = crate::widget::svg::render_to_svg(&mut pb);
let filled = rects_with_fill(&svg, &crate::render::svg::convert::color_to_rgba(&fill));
assert_eq!(filled.len(), 1, "half a bar is one filled run: {svg}");
let (_, _, width, height) = filled[0];
assert!(width > 0 && height > 0, "a drawn fill is never degenerate: {svg}");
assert_eq!(width, 120, "half of a 240-wide census cell is 120px: {svg}");
}
/// A right-to-left bar fills from the **right** edge, by the same length.
///
/// # What this pins
///
/// BLUE22 · F-4. A progress bar maps a value onto a line, and the line runs from where the reader
/// starts to where they finish — so in an Arabic or Hebrew interface a third of the way through a
/// task is a third of the way in from the *right*. Before this the control had no way to say so,
/// and the only knob was `inverted_appearance`, which is a presentational choice rather than a
/// reading fact.
///
/// The assertion is deliberately about the **length as well as the origin**: a mirrored bar that
/// also changed its length would look like it was at a different value, which is the "two
/// directions must share one inset" lesson of BLUE22 §4.3 in its simplest form. The horizontal
/// arm is the one that mirrors; the vertical arm must not.
#[test]
fn a_right_to_left_bar_fills_from_the_right_edge() {
let _guard = theme_guard();
let fill = fill_color();
let rgba = crate::render::svg::convert::color_to_rgba(&fill);
let mut ltr = ProgressBar::new(Rect::new(0, 0, 240, 120));
ltr.set_value(50);
let ltr_svg = crate::widget::svg::render_to_svg(&mut ltr);
let (ltr_x, _, ltr_w, _) = rects_with_fill(<r_svg, &rgba)[0];
let mut rtl = ProgressBar::new(Rect::new(0, 0, 240, 120));
rtl.set_value(50);
rtl.set_direction(crate::core::TextDirection::RightToLeft);
let rtl_svg = crate::widget::svg::render_to_svg(&mut rtl);
let (rtl_x, _, rtl_w, _) = rects_with_fill(&rtl_svg, &rgba)[0];
assert_eq!(rtl_w, ltr_w, "the fill's length is a fact about the value, not the direction");
assert_eq!(ltr_x, 0, "an LTR bar begins at its leading (left) edge");
assert_eq!(
rtl_x + rtl_w,
240,
"an RTL bar's fill ends at its leading (right) edge: x={rtl_x} w={rtl_w}"
);
}
/// A vertical bar is **not** mirrored by the direction.
///
/// The block axis is not a reading direction: text runs down the page the same way in Arabic and
/// in English, so a vertical progress bar fills bottom-to-top in both. `slider` states the same
/// rule in its own RTL arm, and the two controls must agree or a form would have one vertical
/// indicator that mirrors and one that does not.
#[test]
fn a_vertical_bar_is_not_mirrored_by_direction() {
let _guard = theme_guard();
let fill = fill_color();
let rgba = crate::render::svg::convert::color_to_rgba(&fill);
let mut ltr = ProgressBar::new(Rect::new(0, 0, 120, 240));
ltr.set_orientation(Orientation::Vertical);
ltr.set_value(50);
let ltr_svg = crate::widget::svg::render_to_svg(&mut ltr);
let (_, ltr_y, _, ltr_h) = rects_with_fill(<r_svg, &rgba)[0];
let mut rtl = ProgressBar::new(Rect::new(0, 0, 120, 240));
rtl.set_orientation(Orientation::Vertical);
rtl.set_value(50);
rtl.set_direction(crate::core::TextDirection::RightToLeft);
let rtl_svg = crate::widget::svg::render_to_svg(&mut rtl);
let (_, rtl_y, _, rtl_h) = rects_with_fill(&rtl_svg, &rgba)[0];
assert_eq!(ltr_y, rtl_y, "the vertical fill starts where it did");
assert_eq!(ltr_h, rtl_h, "and is the same length");
}
/// Direction and `inverted_appearance` compose rather than one winning.
///
/// They are two ways to reach the far end — one a reading fact, one a presentation choice — so a
/// bar that is *both* inverted and RTL must anchor to the **near** edge. Treating them as one flag
/// (`||`) would make the second setting undo the first, which is the kind of interaction that is
/// invisible until a locale is combined with an indeterminate indicator.
#[test]
fn direction_and_inverted_appearance_compose() {
let _guard = theme_guard();
let fill = fill_color();
let rgba = crate::render::svg::convert::color_to_rgba(&fill);
let mut both = ProgressBar::new(Rect::new(0, 0, 240, 120));
both.set_value(50);
both.set_inverted_appearance(true);
both.set_direction(crate::core::TextDirection::RightToLeft);
let svg = crate::widget::svg::render_to_svg(&mut both);
let (x, _, w, _) = rects_with_fill(&svg, &rgba)[0];
assert_eq!((x, w), (0, 120), "inverted and RTL cancel, anchoring to the near edge");
}
// ── Indeterminate sweep (BLUE23 §3.3 F 档) ────────────────────────────────
/// The sweep band starts off the near end and **moves** across frames.
///
/// This is the three-frame criterion for the F 档 control: the band's extent must be
/// somewhere different on each frame, and it must progress along the bar rather than
/// appear in place.
///
/// # Why the three frames are 16 ms apart
///
/// The criterion is about *consecutive frames*, so the step has to be a frame's worth of time —
/// 16 ms is the step a 60 Hz host uses and the step
/// [`crate::widget::draw_bridge::draw_of`] feeds a host-owned control. Sampling at 120 ms
/// instead asks for three positions inside a 300 ms sweep while each step is 40% of it, and the
/// sweep legitimately *finishes* on the second of those — which is a statement about how far
/// apart the samples are, not about whether the sweep moves. Measured at frame spacing the
/// property is the one the criterion describes: every frame is a new position, and the
/// positions increase.
/// # Why the first frames are skipped
///
/// The sweep begins with the band already a full `run / 3` wide and parked at the near end, so
/// the first step or two move it by less than one pixel of a 120 px run and the integer extent
/// is unchanged. That is the band *entering*, not a stall: sampling after a few frames is what
/// makes "every frame is a new position" a statement about the sweep rather than about
/// rounding. The whole cycle is swept inside one 300 ms token at a 16 ms step, so the samples
/// below are a small, fixed share of it.
#[test]
fn the_indeterminate_band_sweeps_across_frames() {
let mut bar = ProgressBar::new(Rect::new(0, 0, 120, 8));
bar.set_indeterminate(true);
assert!(bar.is_animating(), "an indeterminate bar owes frames");
// Get past the entry, where a sub-pixel step rounds to the same integer extent.
for _ in 0..4 {
assert!(bar.tick(16), "the sweep keeps going while indeterminate");
}
let start = bar.indeterminate_band().expect("indeterminate has a band");
assert!(bar.tick(16), "still sweeping");
let mid = bar.indeterminate_band().expect("band");
assert!(bar.tick(16), "and still");
let later = bar.indeterminate_band().expect("band");
assert_ne!(start.0, mid.0, "the band must have moved by the second frame");
assert_ne!(mid.0, later.0, "and again by the third");
assert!(
start.0 < mid.0 && mid.0 < later.0,
"the sweep must travel forward: {}/{}/{}",
start.0,
mid.0,
later.0
);
assert_eq!(
start.1, later.1,
"and its length must be an invariant, or it grows in place instead of moving"
);
}
/// A determinate bar owes no frames and shows no band.
#[test]
fn a_determinate_bar_has_no_sweep() {
let mut bar = ProgressBar::new(Rect::new(0, 0, 120, 8));
assert!(!bar.is_animating());
assert!(!bar.tick(120), "a value bar must not schedule frames");
assert!(bar.indeterminate_band().is_none());
}
/// An indeterminate bar shows no percentage: a fabricated number is worse than none.
#[test]
fn an_indeterminate_bar_shows_no_percentage() {
let mut bar = ProgressBar::new(Rect::new(0, 0, 120, 8));
bar.set_value(42);
bar.set_indeterminate(true);
assert_eq!(bar.format_text(), "", "no number when the amount is unknown");
}
}