rust_widgets 2.9.2

Pure Rust cross-platform native GUI library with hardware-adaptive rendering, 180 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
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
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
// SPDX-FileCopyrightText: Copyright (c) 2026 Mike Li/Mikewolfli/Wei Li(mikewolfli@163.com)
// SPDX-License-Identifier: MIT

//! Progress bar widget.
use core::fmt::Write as _;

use crate::compat::{String, ToString};
use crate::core::{Color, 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_i32_saturating, 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, effective_font, 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,
    /// The label's format string. `{}` is replaced by the rounded percentage.
    ///
    /// Only the **first** placeholder is substituted; any later `{}` is literal text, so a
    /// caller can print a template without the value being repeated into every slot. The
    /// default is `"{}%"`, which is byte-identical to the label this control drew before the
    /// format existed.
    format: String,
    /// The label shown when `minimum == maximum`.
    ///
    /// A zero-width range means the amount of work cannot be expressed as a percentage, so the
    /// bar shows a word instead of a fabricated number. This is a **label convention only**: it
    /// does not switch the control into the indeterminate sweep, and the fill geometry, the
    /// value, and [`ProgressBar::is_indeterminate`] are all unchanged.
    busy_text: String,
    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>,
    /// The rendered label, reused while its inputs are unchanged.
    label_cache: Option<LabelCache>,
}

/// The label text and the exact inputs that produced it.
///
/// The draw path used to rebuild the label through `write_text` on every frame — expanding the
/// caller's template, formatting the percentage and allocating a fresh `String` — while the value
/// and the range changed only when the host wrote them. Comparing these inputs is cheaper than
/// re-rendering, and it is the same "key unchanged → reuse" shape `badge` and `arc` use.
struct LabelCache {
    minimum: i32,
    maximum: i32,
    value: i32,
    format: String,
    busy_text: String,
    text_visible: bool,
    indeterminate: bool,
    text: String,
}
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,
            format: "{}%".to_string(),
            busy_text: "Busy".to_string(),
            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(),
            label_cache: None,
        }
    }
    /// Returns minimum value.
    pub fn minimum(&self) -> i32 {
        self.minimum
    }
    /// Sets minimum value.
    pub fn set_minimum(&mut self, minimum: i32) {
        if self.minimum == minimum {
            return;
        }
        self.minimum = minimum;
        if self.maximum < self.minimum {
            self.maximum = self.minimum;
        }
        self.set_value(self.value); // Re-clamp
                                    // The fill's proportion and the busy label both depend on the range, so a range change
                                    // is paint-worthy even when the value itself did not need re-clamping.
        self.base.request_redraw();
    }
    /// Returns maximum value.
    pub fn maximum(&self) -> i32 {
        self.maximum
    }
    /// Sets maximum value.
    pub fn set_maximum(&mut self, maximum: i32) {
        if self.maximum == maximum {
            return;
        }
        self.maximum = maximum;
        if self.minimum > self.maximum {
            self.minimum = self.maximum;
        }
        self.set_value(self.value); // Re-clamp
                                    // See `set_minimum`: the range is part of the painted state.
        self.base.request_redraw();
    }
    /// 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) {
        let maximum = maximum.max(minimum);
        if self.minimum == minimum && self.maximum == maximum {
            return;
        }
        self.minimum = minimum;
        self.maximum = maximum;
        self.set_value(self.value); // Re-clamp
                                    // See `set_minimum`: the range is part of the painted state.
        self.base.request_redraw();
    }
    /// 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.request_frame_repaint(None);
    }
    /// 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) {
        if self.text_visible == visible {
            return;
        }
        self.text_visible = visible;
        self.base.request_redraw();
    }
    /// Returns the label's format string.
    ///
    /// See [`ProgressBar::set_format`] for the supported placeholder convention.
    pub fn format(&self) -> &str {
        &self.format
    }

    /// Sets the label's format string and repaints.
    ///
    /// The first `{}` in the string is replaced by the rounded percentage; the rest of the
    /// string, including any further `{}` occurrences, is emitted unchanged. The default is
    /// `"{}%"`, so an untouched bar keeps its existing label exactly.
    pub fn set_format(&mut self, format: impl Into<String>) {
        let format = format.into();
        if self.format == format {
            return;
        }
        self.format = format;
        self.base.request_redraw();
    }

    /// Returns the label shown when `minimum == maximum`.
    pub fn busy_text(&self) -> &str {
        &self.busy_text
    }

    /// Sets the label shown when `minimum == maximum`, and repaints.
    ///
    /// The zero-width range is a label convention, not a mode switch: the bar stays
    /// determinate and its fill geometry is unchanged. The default is `"Busy"`.
    pub fn set_busy_text(&mut self, text: impl Into<String>) {
        let text = text.into();
        if self.busy_text == text {
            return;
        }
        self.busy_text = text;
        self.base.request_redraw();
    }

    /// Returns orientation.
    pub fn orientation(&self) -> Orientation {
        self.orientation
    }
    /// Sets orientation.
    pub fn set_orientation(&mut self, orientation: Orientation) {
        if self.orientation == orientation {
            return;
        }
        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) {
        if self.inverted_appearance == inverted {
            return;
        }
        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) {
        if self.direction == direction {
            return;
        }
        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.request_frame_repaint(None);
    }

    /// Submits one animated frame as damage bounded by the painted box plus the
    /// focus-ring and halo margin.
    ///
    /// `bounds` is supplied by [`Self::tick`], because the animation sweep calls `tick`
    /// while it holds the widget registry; passing the rectangle keeps that path from
    /// asking the runtime to read the geometry back. Event and setter paths pass `None`
    /// and let the runtime derive the box.
    ///
    /// A control that is unmounted falls back to [`BaseWidget::request_redraw`], which
    /// keeps the redraw signal contract for host-owned controls. An interaction frame in
    /// [`crate::widget::runtime::RepaintMode::Full`] still routes through
    /// [`crate::widget::runtime::request_repaint_rect`], whose documented fallback repaints
    /// the whole control; a tick frame keeps the base signal there because the animation
    /// sweep holds the registry across `tick`.
    fn request_frame_repaint(&self, bounds: Option<Rect>) {
        let _ = bounds;
        #[cfg(not(alloc_frugal))]
        {
            if let Some(id) = crate::widget::runtime::registry_id_of(self.id()) {
                let narrow = crate::widget::runtime::repaint_mode(id)
                    != crate::widget::runtime::RepaintMode::Full;
                // `bounds` is `Some` only from `tick`, which the animation sweep calls
                // while it holds the registry; the whole-control fallback would re-enter
                // that borrow, so `Full` stays on the base signal there. Interaction paths
                // may take the documented fallback.
                if narrow || bounds.is_none() {
                    let damage = bounds
                        .or_else(|| crate::widget::runtime::painted_box_with_damage_margin(id))
                        .unwrap_or_else(|| self.damage_bounds());
                    crate::widget::runtime::request_repaint_rect(id, damage);
                    // The replaced `request_redraw` emitted this signal; keep it.
                    self.base.redraw_requested.emit();
                    return;
                }
            }
        }
        self.base.request_redraw();
    }

    /// This control's own rectangle grown by
    /// [`crate::widget::metrics::DAMAGE_MARGIN`].
    ///
    /// The animation sweep holds the registry across `tick`, so the geometry lookup
    /// [`crate::widget::runtime::painted_box_with_damage_margin`] performs cannot run
    /// there. Deriving the rectangle from `Widget::geometry` yields the same answer the
    /// runtime returns for the mounted control.
    fn damage_bounds(&self) -> Rect {
        let rect = self.geometry();
        let margin = crate::widget::metrics::DAMAGE_MARGIN;
        let offset = margin as i32;
        Rect::new(
            rect.x.saturating_sub(offset),
            rect.y.saturating_sub(offset),
            rect.width.saturating_add(margin).saturating_add(margin),
            rect.height.saturating_add(margin).saturating_add(margin),
        )
    }

    /// 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.request_frame_repaint(Some(self.damage_bounds()));
        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))
    }

    /// Writes the display text into `out`: the percentage when the bar is determinate
    /// and its label visible, nothing otherwise.
    ///
    /// Into-style (the calendar-title arrangement): the draw pass renders into its own
    /// buffer, so a hidden or indeterminate bar costs no string at all and a shown one
    /// costs no intermediate `format!` copy.
    fn write_text(&self, out: &mut String) {
        if !self.text_visible {
            return;
        }
        // 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;
        }
        // A zero-width range has no meaningful percentage. Showing the caller's busy text is a
        // label decision only; the fill geometry and the indeterminate flag are untouched.
        if self.minimum == self.maximum {
            out.push_str(&self.busy_text);
            return;
        }
        let percentage = self.progress() * 100.0;
        self.write_formatted_value(out, percentage.round() as i32);
    }

    /// Writes `value` into `out` using the format string, replacing only the first `{}`.
    ///
    /// Written by hand rather than through `format!` because the format string is runtime
    /// data, not a literal: a caller-supplied template cannot be handed to the macro. Any
    /// placeholder after the first is preserved verbatim, which is what makes a template such
    /// as `"{} of {} tasks"` print one value rather than inventing a second.
    fn write_formatted_value(&self, out: &mut String, value: i32) {
        let mut rest = self.format.as_str();
        let mut substituted = false;
        while let Some(index) = rest.find("{}") {
            out.push_str(&rest[..index]);
            if substituted {
                out.push_str("{}");
            } else {
                let _ = write!(out, "{}", value);
                substituted = true;
            }
            rest = &rest[index + 2..];
        }
        out.push_str(rest);
    }

    /// The display text; see [`Self::write_text`].
    ///
    /// Test-only: the draw pass writes into its own buffer directly, so the owned-string
    /// convenience is kept for the test that pins the indeterminate contract.
    #[cfg(test)]
    fn format_text(&self) -> String {
        let mut out = String::new();
        self.write_text(&mut out);
        out
    }

    /// Rebuilds [`Self::label_cache`] only when one of the label's inputs changed.
    fn ensure_label_text(&mut self) {
        let fresh = self.label_cache.as_ref().is_some_and(|cache| {
            cache.minimum == self.minimum
                && cache.maximum == self.maximum
                && cache.value == self.value
                && cache.format == self.format
                && cache.busy_text == self.busy_text
                && cache.text_visible == self.text_visible
                && cache.indeterminate == self.indeterminate
        });
        if fresh {
            return;
        }
        let mut text = String::new();
        self.write_text(&mut text);
        self.label_cache = Some(LabelCache {
            minimum: self.minimum,
            maximum: self.maximum,
            value: self.value,
            format: self.format.clone(),
            busy_text: self.busy_text.clone(),
            text_visible: self.text_visible,
            indeterminate: self.indeterminate,
            text,
        });
    }
}
// Implement Widget trait
impl Widget for ProgressBar {
    fn base(&self) -> &BaseWidget {
        &self.base
    }
    fn set_state_theme_hook(&mut self) {
        crate::style::reapply_active_theme_state(self);
    }
    fn base_mut(&mut self) -> &mut BaseWidget {
        &mut self.base
    }

    fn size_hint(&self) -> Size {
        let extent = crate::widget::metrics::dimensions::BAR_DEFAULT_EXTENT;
        let thickness = crate::widget::metrics::dimensions::BAR_DEFAULT_THICKNESS;
        match self.orientation() {
            Orientation::Horizontal => Size::new(extent, thickness),
            Orientation::Vertical => Size::new(thickness, extent),
        }
    }
    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
    }
    /// Resolves a published event name to the control's own signal.
    ///
    /// # Why this is explicit per control
    ///
    /// `connect_event` validates a name against the capability table and registers a hub slot; only
    /// `event_signal_dyn` joins that name to the signal the control actually emits. Without it a name
    /// is valid and inert, which is the silent failure `tools/check_event_signal_dyn.sh` exists to
    /// make impossible. The arm set is checked against the capability's published names, so this
    /// list cannot drift from what the control advertises.
    fn event_signal_dyn(&self, name: &str) -> Option<crate::signal::EventSignalRef> {
        use crate::signal::EventSignalRef;
        #[allow(unused_imports)]
        use crate::widget::capability::CapabilityValue;
        match name {
            "value_changed" => {
                Some(EventSignalRef::mapped("value_changed", &self.value_changed, |v| {
                    CapabilityValue::Int(*v as i64)
                }))
            }
            _ => None,
        }
    }
}

/// `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())),
            "indeterminate" => Ok(CapabilityValue::Bool(self.is_indeterminate())),
            "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_i32_saturating(value)?);
                Ok(())
            }
            "maximum" => {
                self.set_maximum(expect_i32_saturating(value)?);
                Ok(())
            }
            "value" => {
                self.set_value(expect_i32_saturating(value)?);
                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(())
            }
            "indeterminate" => {
                self.set_indeterminate(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",
            "indeterminate",
            "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) {
        // Refresh the label before borrowing the resolved style: the cache rebuild mutates the
        // control, and the style reference below must not overlap it.
        self.ensure_label_text();
        // Draw base widget
        let rect = self.geometry();
        let progress = self.progress();
        let style = self.style();
        // 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`.
        // One shared palette read instead of a global theme-lock round trip per frame: the rest
        // of this draw already resolves through the `_shared` helpers, and a host painting
        // several bars concurrently no longer queues them on the manager mutex.
        let window_fill =
            crate::style::palette_shared().map(|colors| 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_shared("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, rounded like the pill groove so the outline closes at its ends.
        if let Some(border_color) = style.border_color {
            crate::widget::draw::stroke_surface_border(
                context,
                bar_rect,
                bar_height / 2,
                border_color,
                1,
            );
        }
        // 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
        };
        if let Some(text) = self.label_cache.as_ref().map(|cache| cache.text.as_str()) {
            if !text.is_empty() {
                // The value label takes the **effective font** — the resolved theme/caller font — so the
                // theme body font and the user's text scale reach it (D09-STYLE-01).
                context.draw_text_line_cow(
                    rect,
                    text,
                    effective_font(style),
                    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());
    }

    /// Only the first placeholder is substituted, and the default format is unchanged.
    #[test]
    fn the_format_string_replaces_only_the_first_placeholder() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        pb.set_value(50);

        assert_eq!(pb.format(), "{}%", "the default keeps the existing label");
        assert_eq!(pb.format_text(), "50%", "the default label is byte-identical");

        pb.set_format("{} of {}");
        assert_eq!(pb.format(), "{} of {}");
        assert_eq!(
            pb.format_text(),
            "50 of {}",
            "only the first placeholder takes the value; the second stays literal"
        );

        pb.set_format("done {}%");
        assert_eq!(pb.format_text(), "done 50%");
    }

    /// A zero-width range shows the busy label without becoming an indeterminate bar.
    #[test]
    fn a_zero_span_bar_shows_its_busy_label() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        pb.set_range(7, 7);

        assert_eq!(pb.busy_text(), "Busy");
        assert_eq!(pb.format_text(), "Busy", "a zero-width range has no percentage to show");

        pb.set_busy_text("Working");
        assert_eq!(pb.busy_text(), "Working");
        assert_eq!(pb.format_text(), "Working");

        // The label convention must not change the control's mode or its animation contract.
        assert!(!pb.is_indeterminate(), "busy text is not the indeterminate sweep");
        assert!(pb.indeterminate_band().is_none());
        assert!(!pb.tick(16), "a zero-width determinate bar owes no frames");
    }

    #[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_shared("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(&ltr_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(&ltr_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 Tier F) ────────────────────────────────

    /// The sweep band starts off the near end and **moves** across frames.
    ///
    /// This is the three-frame criterion for the Tier 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.
    #[cfg(device_profile)]
    #[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");
    }

    /// An animation frame submits damage bounded by the painted box and the margin.
    #[cfg(not(alloc_frugal))]
    #[test]
    fn a_sweep_frame_submits_the_painted_box_with_the_damage_margin() {
        use crate::widget::runtime;

        let mut bar = ProgressBar::new(Rect::new(4, 8, 120, 12));
        bar.set_indeterminate(true);
        let id = runtime::register(crate::compat::Box::new(bar)).expect("registry");
        assert!(runtime::set_repaint_mode(id, runtime::RepaintMode::Dirty));

        let moved = runtime::with_widget_mut(id, |widget| Widget::tick(widget, 16))
            .expect("mounted control");
        assert!(moved, "the indeterminate sweep owes a frame");

        let expected = runtime::painted_box_with_damage_margin(id).expect("painted box");
        assert_eq!(
            runtime::dirty_rects(id),
            vec![expected],
            "one animated frame must damage the painted box plus the margin"
        );
        runtime::unregister(id);
    }

    /// `Full` keeps the whole-control path and records no damage rectangle.
    #[cfg(not(alloc_frugal))]
    #[test]
    fn a_sweep_frame_in_full_mode_keeps_the_whole_control_repaint() {
        use crate::widget::runtime;

        let mut bar = ProgressBar::new(Rect::new(4, 8, 120, 12));
        bar.set_indeterminate(true);
        let id = runtime::register(crate::compat::Box::new(bar)).expect("registry");
        assert_eq!(runtime::repaint_mode(id), runtime::RepaintMode::Full);

        let moved = runtime::with_widget_mut(id, |widget| Widget::tick(widget, 16))
            .expect("mounted control");
        assert!(moved);
        assert!(
            runtime::dirty_rects(id).is_empty(),
            "Full mode records no damage, so the control repaints whole"
        );
        runtime::unregister(id);
    }

    /// The drawn label is rebuilt only when one of its inputs changes.
    #[test]
    fn the_label_is_cached_until_an_input_changes() {
        let mut pb = ProgressBar::new(Rect::new(0, 0, 200, 20));
        pb.ensure_label_text();
        let first = pb.label_cache.as_ref().expect("the label is cached").text.clone();
        assert_eq!(first, "0%");

        // A second frame with the same inputs reuses the same allocation.
        let ptr = pb.label_cache.as_ref().unwrap().text.as_ptr();
        pb.ensure_label_text();
        assert_eq!(pb.label_cache.as_ref().unwrap().text.as_ptr(), ptr);

        // A value change rebuilds it, and the text follows.
        pb.set_value(40);
        pb.ensure_label_text();
        assert_eq!(pb.label_cache.as_ref().unwrap().text, "40%");

        // A format change rebuilds it too.
        pb.set_format("{} of 100");
        pb.ensure_label_text();
        assert_eq!(pb.label_cache.as_ref().unwrap().text, "40 of 100");
    }
}