1
//! Native progress bar widget with customizable backgrounds, height, and
2
//! gradient styling. The main type is [`ProgressBar`], which is rendered
3
//! into a DOM via [`ProgressBar::dom()`].
4
//!
5
//! # The fast path: updating the bar without a relayout
6
//!
7
//! `dom()` wraps the bar in a **`VirtualView`** node whose private dataset
8
//! holds the [`ProgressBar`]. That makes the widget the reference
9
//! implementation of the *inter-widget fast path* (see
10
//! `doc/guide/*/architecture.md`): a callback on some OTHER node (say, a paint
11
//! area receiving pen pressure) can move this bar live - no app-data-model
12
//! write, no full `layout()`, no DOM diff - in three steps:
13
//!
14
//! 1. The app stamps a MARKER string on the widget's root during `layout()`
15
//!    (`ProgressBar::dom().with_marker(...)`) and keeps the same string in the RefAny of the
16
//!    callback that wants to drive the bar.
17
//! 2. The callback resolves the marker to the node: `CallbackInfo::get_node_id_by_marker`.
18
//! 3. It calls [`ProgressBar::update_progress`] with that node id - which downcasts the widget's
19
//!    PRIVATE dataset (the caller never sees the type), stores the new percentage, and triggers
20
//!    `CallbackInfo::trigger_virtual_view_rerender` on the node. The framework re-invokes ONLY this
21
//!    widget's `VirtualView` callback in place; the resulting DOM is restyled/relaid out inside the
22
//!    existing bounds and the damage rect covers just the bar.
23
//!
24
//! The heavy path stays valid: store the value in the app data model, return
25
//! `Update::RefreshDom`, and the full `layout()` + DOM diff repaints the bar
26
//! like any other widget.
27

            
28
use azul_core::{
29
    callbacks::{VirtualViewCallbackInfo, VirtualViewReturn},
30
    dom::{Dom, DomNodeId, IdOrClass, IdOrClass::Class, IdOrClassVec},
31
    geom::{LogicalPosition, LogicalRect},
32
    refany::RefAny,
33
};
34
use azul_css::css::BoxOrStatic;
35
#[allow(clippy::wildcard_imports)]
36
// widget/render module pulls in the css property/value types it builds with
37
use azul_css::{
38
    dynamic_selector::{CssPropertyWithConditions, CssPropertyWithConditionsVec},
39
    props::{
40
        basic::*,
41
        layout::*,
42
        property::{CssProperty, *},
43
        style::*,
44
    },
45
    *,
46
};
47

            
48
use crate::callbacks::CallbackInfo;
49

            
50
pub const STYLE_BACKGROUND_CONTENT_2688422633177340412_ITEMS: &[StyleBackgroundContent] =
51
    &[StyleBackgroundContent::LinearGradient(LinearGradient {
52
        direction: Direction::FromTo(DirectionCorners {
53
            dir_from: DirectionCorner::Top,
54
            dir_to: DirectionCorner::Bottom,
55
        }),
56
        extend_mode: ExtendMode::Clamp,
57
        stops: NormalizedLinearColorStopVec::from_const_slice(
58
            LINEAR_COLOR_STOP_12009347504665939_ITEMS,
59
        ),
60
    })];
61
pub const STYLE_BACKGROUND_CONTENT_14586281004485141058_ITEMS: &[StyleBackgroundContent] =
62
    &[StyleBackgroundContent::LinearGradient(LinearGradient {
63
        direction: Direction::FromTo(DirectionCorners {
64
            dir_from: DirectionCorner::Top,
65
            dir_to: DirectionCorner::Bottom,
66
        }),
67
        extend_mode: ExtendMode::Clamp,
68
        stops: NormalizedLinearColorStopVec::from_const_slice(
69
            LINEAR_COLOR_STOP_3104396762583413726_ITEMS,
70
        ),
71
    })];
72
pub const LINEAR_COLOR_STOP_12009347504665939_ITEMS: &[NormalizedLinearColorStop] = &[
73
    NormalizedLinearColorStop {
74
        offset: PercentageValue::const_new(0),
75
        color: ColorOrSystem::color(ColorU {
76
            r: 193,
77
            g: 255,
78
            b: 187,
79
            a: 255,
80
        }),
81
    },
82
    NormalizedLinearColorStop {
83
        offset: PercentageValue::const_new(10),
84
        color: ColorOrSystem::color(ColorU {
85
            r: 205,
86
            g: 255,
87
            b: 205,
88
            a: 255,
89
        }),
90
    },
91
    NormalizedLinearColorStop {
92
        offset: PercentageValue::const_new(15),
93
        color: ColorOrSystem::color(ColorU {
94
            r: 156,
95
            g: 238,
96
            b: 172,
97
            a: 255,
98
        }),
99
    },
100
    NormalizedLinearColorStop {
101
        offset: PercentageValue::const_new(20),
102
        color: ColorOrSystem::color(ColorU {
103
            r: 0,
104
            g: 211,
105
            b: 40,
106
            a: 255,
107
        }),
108
    },
109
    NormalizedLinearColorStop {
110
        offset: PercentageValue::const_new(30),
111
        color: ColorOrSystem::color(ColorU {
112
            r: 0,
113
            g: 211,
114
            b: 40,
115
            a: 255,
116
        }),
117
    },
118
    NormalizedLinearColorStop {
119
        offset: PercentageValue::const_new(70),
120
        color: ColorOrSystem::color(ColorU {
121
            r: 32,
122
            g: 219,
123
            b: 65,
124
            a: 255,
125
        }),
126
    },
127
    NormalizedLinearColorStop {
128
        offset: PercentageValue::const_new(100),
129
        color: ColorOrSystem::color(ColorU {
130
            r: 32,
131
            g: 219,
132
            b: 65,
133
            a: 255,
134
        }),
135
    },
136
];
137
pub const LINEAR_COLOR_STOP_3104396762583413726_ITEMS: &[NormalizedLinearColorStop] = &[
138
    NormalizedLinearColorStop {
139
        offset: PercentageValue::const_new(0),
140
        color: ColorOrSystem::color(ColorU {
141
            r: 243,
142
            g: 243,
143
            b: 243,
144
            a: 255,
145
        }),
146
    },
147
    NormalizedLinearColorStop {
148
        offset: PercentageValue::const_new(10),
149
        color: ColorOrSystem::color(ColorU {
150
            r: 252,
151
            g: 252,
152
            b: 252,
153
            a: 255,
154
        }),
155
    },
156
    NormalizedLinearColorStop {
157
        offset: PercentageValue::const_new(15),
158
        color: ColorOrSystem::color(ColorU {
159
            r: 218,
160
            g: 218,
161
            b: 218,
162
            a: 255,
163
        }),
164
    },
165
    NormalizedLinearColorStop {
166
        offset: PercentageValue::const_new(20),
167
        color: ColorOrSystem::color(ColorU {
168
            r: 201,
169
            g: 201,
170
            b: 201,
171
            a: 255,
172
        }),
173
    },
174
    NormalizedLinearColorStop {
175
        offset: PercentageValue::const_new(30),
176
        color: ColorOrSystem::color(ColorU {
177
            r: 218,
178
            g: 218,
179
            b: 218,
180
            a: 255,
181
        }),
182
    },
183
    NormalizedLinearColorStop {
184
        offset: PercentageValue::const_new(70),
185
        color: ColorOrSystem::color(ColorU {
186
            r: 203,
187
            g: 203,
188
            b: 203,
189
            a: 255,
190
        }),
191
    },
192
    NormalizedLinearColorStop {
193
        offset: PercentageValue::const_new(100),
194
        color: ColorOrSystem::color(ColorU {
195
            r: 203,
196
            g: 203,
197
            b: 203,
198
            a: 255,
199
        }),
200
    },
201
];
202

            
203
/// A native progress bar widget with customizable bar/container backgrounds and height.
204
#[derive(Debug, Clone)]
205
#[repr(C)]
206
pub struct ProgressBar {
207
    pub progressbar_state: ProgressBarState,
208
    pub height: PixelValue,
209
    pub bar_background: StyleBackgroundContentVec,
210
    pub container_background: StyleBackgroundContentVec,
211
    pub theme: crate::widgets::themes::OptionUiTheme,
212
}
213

            
214
/// Internal state for a [`ProgressBar`], tracking completion percentage.
215
#[derive(Copy, Debug, Clone)]
216
#[repr(C)]
217
pub struct ProgressBarState {
218
    pub percent_done: f32,
219
    pub display_percentage: bool,
220
}
221

            
222
/// The widget's PRIVATE `VirtualView` dataset: the whole [`ProgressBar`],
223
/// downcast only inside this module ([`ProgressBar::update_progress`] and the
224
/// `VirtualView` callback). Callers drive it exclusively through the public
225
/// API - the "`RefAny` datasets are private to the widget module" rule from
226
/// `architecture.md`.
227
#[derive(Debug)]
228
pub struct ProgressBarLocalDataset {
229
    pub bar: ProgressBar,
230
}
231

            
232
impl ProgressBar {
233
    /// Creates a new progress bar with the given completion percentage (0.0 to 100.0).
234
    #[inline]
235
    #[must_use]
236
11334
    pub const fn create(percent_done: f32) -> Self {
237
11334
        Self {
238
11334
            progressbar_state: ProgressBarState {
239
11334
                percent_done,
240
11334
                display_percentage: false,
241
11334
            },
242
11334
            height: PixelValue::const_px(15),
243
11334
            bar_background: StyleBackgroundContentVec::from_const_slice(
244
11334
                STYLE_BACKGROUND_CONTENT_2688422633177340412_ITEMS,
245
11334
            ),
246
11334
            container_background: StyleBackgroundContentVec::from_const_slice(
247
11334
                STYLE_BACKGROUND_CONTENT_14586281004485141058_ITEMS,
248
11334
            ),
249
11334
            theme: crate::widgets::themes::OptionUiTheme::Some(
250
11334
                crate::widgets::themes::UiTheme::Flat,
251
11334
            ),
252
11334
        }
253
11334
    }
254

            
255
    /// Replaces `self` with a default (0%) progress bar, returning the previous value.
256
    #[inline]
257
    #[must_use]
258
1017
    pub const fn swap_with_default(&mut self) -> Self {
259
1017
        let mut s = Self::create(0.0);
260
1017
        core::mem::swap(&mut s, self);
261
1017
        s
262
1017
    }
263

            
264
557
    pub fn set_container_background(&mut self, background: StyleBackgroundContentVec) {
265
557
        self.container_background = background;
266
557
    }
267

            
268
    #[must_use]
269
55
    pub fn with_container_background(mut self, background: StyleBackgroundContentVec) -> Self {
270
55
        self.set_container_background(background);
271
55
        self
272
55
    }
273

            
274
1562
    pub fn set_bar_background(&mut self, background: StyleBackgroundContentVec) {
275
1562
        self.bar_background = background;
276
1562
    }
277

            
278
    #[must_use]
279
60
    pub fn with_bar_background(mut self, background: StyleBackgroundContentVec) -> Self {
280
60
        self.set_bar_background(background);
281
60
        self
282
60
    }
283

            
284
132
    pub const fn set_height(&mut self, height: PixelValue) {
285
132
        self.height = height;
286
132
    }
287

            
288
    #[must_use]
289
97
    pub const fn with_height(mut self, height: PixelValue) -> Self {
290
97
        self.set_height(height);
291
97
        self
292
97
    }
293

            
294
    /// Build the widget: a `VirtualView` node (explicitly sized to
295
    /// [`height`](Self::height)) whose callback renders [`render_bar`]
296
    /// (`Self::render_bar`) into the node's bounds. The node carries the
297
    /// widget's private dataset so [`update_progress`](Self::update_progress)
298
    /// can find and mutate it later - see the module docs for the fast path.
299
    #[inline]
300
    pub const fn set_theme(&mut self, theme: crate::widgets::themes::UiTheme) {
301
        self.theme = crate::widgets::themes::OptionUiTheme::Some(theme);
302
    }
303

            
304
    #[inline]
305
    #[must_use]
306
    pub const fn with_theme(mut self, theme: crate::widgets::themes::UiTheme) -> Self {
307
        self.theme = crate::widgets::themes::OptionUiTheme::Some(theme);
308
        self
309
    }
310

            
311
    #[must_use]
312
9
    pub fn dom(self) -> Dom {
313
9
        let theme = self
314
9
            .theme
315
9
            .into_option()
316
9
            .unwrap_or(crate::widgets::themes::UiTheme::Flat);
317
9
        match theme {
318
            crate::widgets::themes::UiTheme::Flat => {
319
9
                crate::widgets::themes::flat::progressbar(self)
320
            }
321
            crate::widgets::themes::UiTheme::Flora => {
322
                crate::widgets::themes::flora::progressbar(self)
323
            }
324
        }
325
9
    }
326

            
327
    pub fn update_progress(info: &mut CallbackInfo, node_id: DomNodeId, percent_done: f32) -> bool {
328
        let Some(mut dataset) = info.get_dataset(node_id) else {
329
            return false;
330
        };
331
        {
332
            // Scoped: the downcast guard must drop before the re-render
333
            // trigger runs the queue drain path.
334
            let Some(mut state) = dataset.downcast_mut::<ProgressBarLocalDataset>() else {
335
                return false;
336
            };
337
            state.bar.progressbar_state.percent_done = percent_done;
338
        }
339
        let Some(node) = node_id.node.into_crate_internal() else {
340
            return false;
341
        };
342
        info.trigger_virtual_view_rerender(node_id.dom, node);
343
        true
344
    }
345

            
346
    /// Renders this progress bar into a [`Dom`] tree consisting of a container div
347
    /// with two children: the filled bar and the remaining empty space.
348
    ///
349
    /// This is the tree the `VirtualView` callback returns on every
350
    /// (re-)render; [`dom`](Self::dom) is the wrapper that mounts it. Calling
351
    /// it directly gives the bare bar with NO fast-path machinery - useful for
352
    /// embedding in a context that manages its own updates.
353
    #[must_use]
354
205
    pub fn render_bar(self) -> Dom {
355
205
        let theme = self
356
205
            .theme
357
205
            .into_option()
358
205
            .unwrap_or(crate::widgets::themes::UiTheme::Flat);
359
205
        match theme {
360
            crate::widgets::themes::UiTheme::Flat => {
361
205
                crate::widgets::themes::flat::progressbar_render_bar_impl(self, None)
362
            }
363
            crate::widgets::themes::UiTheme::Flora => {
364
                crate::widgets::themes::flora::progressbar_render_bar_impl(self, None)
365
            }
366
        }
367
205
    }
368
}
369

            
370
#[cfg(test)]
371
#[allow(
372
    clippy::float_cmp,
373
    clippy::cast_precision_loss,
374
    clippy::cast_possible_truncation,
375
    clippy::unreadable_literal,
376
    clippy::too_many_lines
377
)]
378
mod autotest_generated {
379
    use std::collections::HashSet;
380

            
381
    use azul_core::dom::NodeType;
382

            
383
    use super::*;
384

            
385
    // ------------------------------------------------------------------
386
    // Helpers
387
    // ------------------------------------------------------------------
388

            
389
    /// Every `f32` a caller can realistically hand to `ProgressBar::create`.
390
    /// The percentage is stored raw and only clamped inside `dom()`, where it is
391
    /// pushed through `PixelValue::percent` — which multiplies by 1000 and casts
392
    /// to `isize`. That cast saturates (NaN → 0, out of range → `isize::MIN/MAX`),
393
    /// so none of these may panic or wrap.
394
    ///
395
    /// `NAN` is deliberately absent: it is the one input that is unordered against
396
    /// the clamp bounds, so it gets its own test.
397
    const ADVERSARIAL_PERCENTS: [f32; 16] = [
398
        0.0,
399
        -0.0,
400
        1.0,
401
        50.0,
402
        100.0,
403
        -1.0,
404
        101.0,
405
        0.001,
406
        -0.001,
407
        f32::EPSILON,
408
        f32::MIN_POSITIVE,
409
        -f32::MIN_POSITIVE,
410
        f32::MAX,
411
        f32::MIN,
412
        f32::INFINITY,
413
        f32::NEG_INFINITY,
414
    ];
415

            
416
    /// Heights that stress the `f32 → isize` fixed-point encoding behind
417
    /// `PixelValue`: zero, both signed zeroes, the saturating extremes, NaN, and
418
    /// the relative metrics the widget is not supposed to reject.
419
    fn adversarial_heights() -> Vec<PixelValue> {
420
        vec![
421
            PixelValue::zero(),
422
            PixelValue::const_px(0),
423
            PixelValue::px(-0.0),
424
            PixelValue::px(-1.0),
425
            PixelValue::px(0.001),
426
            PixelValue::px(f32::MAX),
427
            PixelValue::px(f32::MIN),
428
            PixelValue::px(f32::INFINITY),
429
            PixelValue::px(f32::NEG_INFINITY),
430
            PixelValue::px(f32::NAN),
431
            PixelValue::percent(100.0),
432
            PixelValue::em(0.001),
433
            // The largest whole-pixel value `const_px` can scale by 1000 without
434
            // overflowing `isize` (one more would be a debug-build panic *inside
435
            // the argument*, not inside `set_height`).
436
            PixelValue::const_px(isize::MAX / 1000),
437
        ]
438
    }
439

            
440
    /// The raw fixed-point encoding of a length: `FloatValue` stores `value * 1000`
441
    /// as an `isize`, so this is what actually survives — comparing it avoids a
442
    /// second lossy float round-trip through `get()`.
443
    fn raw(pv: PixelValue) -> isize {
444
        pv.number.number()
445
    }
446

            
447
    /// The addresses `ProgressBar::create` hands out for the two static
448
    /// gradients — the reference every "is this still borrowed?" assertion below
449
    /// compares against.
450
    ///
451
    /// Deliberately NOT `STYLE_BACKGROUND_CONTENT_*_ITEMS.as_ptr()`. Those are
452
    /// `const` items, and every *use site* of a `const &[T]` gets its own
453
    /// promoted read-only allocation; two use sites share an address only if the
454
    /// optimizer merges them, which it does in an optimized build and does not
455
    /// in an unoptimized one. Comparing a `create()` pointer against the const
456
    /// was therefore an accidental green that held only because the suite had
457
    /// never been run on the dev profile. `create()` contains ONE use site of
458
    /// each const, so the address it returns is stable across calls — and that
459
    /// is exactly the property under test: a `create()` that copied the slice
460
    /// into a heap vec would hand out a fresh address every time.
461
    fn create_gradient_ptrs() -> (*const StyleBackgroundContent, *const StyleBackgroundContent) {
462
        let pb = ProgressBar::create(0.0);
463
        (pb.bar_background.as_ptr(), pb.container_background.as_ptr())
464
    }
465

            
466
    /// A heap-allocated background of `n` distinct solid colours. Heap-backed on
467
    /// purpose: it is the only case where the vec owns memory that can be
468
    /// double-freed or leaked.
469
    fn solid(n: usize) -> StyleBackgroundContentVec {
470
        StyleBackgroundContentVec::from_vec(
471
            (0..n)
472
                .map(|i| {
473
                    StyleBackgroundContent::Color(ColorU {
474
                        r: (i % 256) as u8,
475
                        g: 1,
476
                        b: 2,
477
                        a: 255,
478
                    })
479
                })
480
                .collect(),
481
        )
482
    }
483

            
484
    fn kids(dom: &Dom) -> &[Dom] {
485
        dom.children.as_ref()
486
    }
487

            
488
    /// The filled part (`.__azul-native-progress-bar-bar`).
489
    fn bar(dom: &Dom) -> &Dom {
490
        &kids(dom)[0]
491
    }
492

            
493
    /// The empty part (`.__azul-native-progress-bar-remaining`).
494
    fn remaining(dom: &Dom) -> &Dom {
495
        &kids(dom)[1]
496
    }
497

            
498
    /// The declared properties of a node's inline style, in declaration order.
499
    fn inline_props(dom: &Dom) -> Vec<CssProperty> {
500
        dom.root
501
            .style
502
            .iter_inline_properties()
503
            .map(|(p, _)| p.clone())
504
            .collect()
505
    }
506

            
507
    /// The CSS classes of a node, in declaration order.
508
    fn classes(dom: &Dom) -> Vec<String> {
509
        dom.root
510
            .get_ids_and_classes()
511
            .as_ref()
512
            .iter()
513
            .filter_map(|c| match c {
514
                Class(s) => Some(s.as_str().to_string()),
515
                IdOrClass::Id(_) => None,
516
            })
517
            .collect()
518
    }
519

            
520
    fn width_of(dom: &Dom) -> Option<PixelValue> {
521
        dom.root
522
            .style
523
            .iter_inline_properties()
524
            .find_map(|(p, _)| match p {
525
                CssProperty::Width(v) => match v.get_property() {
526
                    Some(LayoutWidth::Px(pv)) => Some(*pv),
527
                    Some(other) => panic!("the progress bar must size in lengths, got {other:?}"),
528
                    None => None,
529
                },
530
                _ => None,
531
            })
532
    }
533

            
534
    fn height_of(dom: &Dom) -> Option<PixelValue> {
535
        dom.root
536
            .style
537
            .iter_inline_properties()
538
            .find_map(|(p, _)| match p {
539
                CssProperty::Height(v) => match v.get_property() {
540
                    Some(LayoutHeight::Px(pv)) => Some(*pv),
541
                    Some(other) => panic!("the progress bar must size in lengths, got {other:?}"),
542
                    None => None,
543
                },
544
                _ => None,
545
            })
546
    }
547

            
548
    /// The background layers a node declares, cloned out of the DOM.
549
    fn background_of(dom: &Dom) -> Option<Vec<StyleBackgroundContent>> {
550
        dom.root
551
            .style
552
            .iter_inline_properties()
553
            .find_map(|(p, _)| match p {
554
                CssProperty::BackgroundContent(v) => v.get_property().map(|b| b.as_ref().to_vec()),
555
                _ => None,
556
            })
557
    }
558

            
559
    /// The *address* of a node's background buffer — the only way to tell a move
560
    /// from a copy, and a copy from a use-after-free.
561
    fn background_ptr(dom: &Dom) -> Option<*const StyleBackgroundContent> {
562
        dom.root
563
            .style
564
            .iter_inline_properties()
565
            .find_map(|(p, _)| match p {
566
                CssProperty::BackgroundContent(v) => {
567
                    v.get_property().map(StyleBackgroundContentVec::as_ptr)
568
                }
569
                _ => None,
570
            })
571
    }
572

            
573
    /// Every absolute length a chrome property declares (box shadows excluded —
574
    /// they carry `PixelValueNoPercent`, which cannot express a relative unit).
575
    fn lengths_of(p: &CssProperty) -> Vec<PixelValue> {
576
        let one = |pv: Option<PixelValue>| pv.into_iter().collect::<Vec<_>>();
577
        match p {
578
            CssProperty::BorderBottomWidth(v) => one(v.get_property().map(|x| x.inner)),
579
            CssProperty::BorderLeftWidth(v) => one(v.get_property().map(|x| x.inner)),
580
            CssProperty::BorderRightWidth(v) => one(v.get_property().map(|x| x.inner)),
581
            CssProperty::BorderTopWidth(v) => one(v.get_property().map(|x| x.inner)),
582
            CssProperty::BorderBottomRightRadius(v) => one(v.get_property().map(|x| x.inner)),
583
            CssProperty::BorderBottomLeftRadius(v) => one(v.get_property().map(|x| x.inner)),
584
            CssProperty::BorderTopRightRadius(v) => one(v.get_property().map(|x| x.inner)),
585
            CssProperty::BorderTopLeftRadius(v) => one(v.get_property().map(|x| x.inner)),
586
            _ => Vec::new(),
587
        }
588
    }
589

            
590
    // ------------------------------------------------------------------
591
    // ProgressBar::create
592
    // ------------------------------------------------------------------
593

            
594
    #[test]
595
    fn create_stores_the_percentage_bit_for_bit_and_never_normalises_it() {
596
        // `create` is documented as taking 0.0..=100.0 but performs no validation:
597
        // whatever comes in has to come back out untouched, sign of zero included.
598
        for p in ADVERSARIAL_PERCENTS {
599
            let pb = ProgressBar::create(p);
600
            assert_eq!(
601
                pb.progressbar_state.percent_done.to_bits(),
602
                p.to_bits(),
603
                "create() rewrote the percentage {p}",
604
            );
605
            assert!(
606
                !pb.progressbar_state.display_percentage,
607
                "a fresh progress bar must not opt into the percentage label",
608
            );
609
        }
610

            
611
        // NaN cannot be compared, only inspected.
612
        let nan = ProgressBar::create(f32::NAN);
613
        assert!(
614
            nan.progressbar_state.percent_done.is_nan(),
615
            "create() silently replaced a NaN percentage",
616
        );
617
    }
618

            
619
    #[test]
620
    fn create_defaults_to_a_15px_height() {
621
        let pb = ProgressBar::create(50.0);
622
        assert_eq!(
623
            pb.height.metric,
624
            SizeMetric::Px,
625
            "the default height must be absolute"
626
        );
627
        assert_eq!(
628
            raw(pb.height),
629
            15_000,
630
            "the default height is 15px in 1/1000 units"
631
        );
632
    }
633

            
634
    #[test]
635
    fn create_borrows_the_static_gradients_instead_of_allocating_them() {
636
        let pb = ProgressBar::create(50.0);
637
        let (bar_ptr, container_ptr) = create_gradient_ptrs();
638

            
639
        // Pointer identity, not just content equality: a `create()` that copied the
640
        // static slice into a heap vec would allocate on every frame, and one that
641
        // kept the static pointer but claimed ownership of it would free `&'static`
642
        // memory on drop.
643
        assert_eq!(
644
            pb.bar_background.as_ptr(),
645
            bar_ptr,
646
            "the bar gradient stopped being shared with the static slice",
647
        );
648
        assert_eq!(
649
            pb.container_background.as_ptr(),
650
            container_ptr,
651
            "the container gradient stopped being shared with the static slice",
652
        );
653
        // Content still pinned to the declared constants, so "shared" cannot
654
        // degrade into "shared with something else".
655
        assert_eq!(
656
            pb.bar_background.as_ref(),
657
            STYLE_BACKGROUND_CONTENT_2688422633177340412_ITEMS,
658
        );
659
        assert_eq!(
660
            pb.container_background.as_ref(),
661
            STYLE_BACKGROUND_CONTENT_14586281004485141058_ITEMS,
662
        );
663
        assert_eq!(pb.bar_background.len(), 1);
664
        assert_eq!(pb.container_background.len(), 1);
665
        assert_eq!(
666
            pb.bar_background.capacity(),
667
            pb.bar_background.len(),
668
            "a borrowed buffer must report capacity == len, or the free path over-reads",
669
        );
670

            
671
        // 10_000 bars built and dropped: if the destructor of a static-backed vec
672
        // were ever flipped to the owning one, this frees the same `&'static`
673
        // allocation 10_000 times.
674
        for i in 0..10_000 {
675
            let pb = ProgressBar::create(i as f32);
676
            assert_eq!(pb.bar_background.len(), 1);
677
            assert_eq!(pb.bar_background.as_ptr(), bar_ptr);
678
        }
679
    }
680

            
681
    #[test]
682
    fn create_backgrounds_are_the_declared_gradients_with_sorted_stops() {
683
        let pb = ProgressBar::create(0.0);
684
        assert_eq!(
685
            pb.bar_background.as_ref(),
686
            STYLE_BACKGROUND_CONTENT_2688422633177340412_ITEMS,
687
        );
688
        assert_eq!(
689
            pb.container_background.as_ref(),
690
            STYLE_BACKGROUND_CONTENT_14586281004485141058_ITEMS,
691
        );
692

            
693
        for bg in [&pb.bar_background, &pb.container_background] {
694
            match &bg.as_ref()[0] {
695
                StyleBackgroundContent::LinearGradient(g) => {
696
                    let stops = g.stops.as_ref();
697
                    assert_eq!(stops.len(), 7, "a gradient lost or gained a colour stop");
698

            
699
                    // Unsorted or out-of-range stops make the gradient renderer's
700
                    // interpolation run backwards over a segment.
701
                    let mut prev = f32::NEG_INFINITY;
702
                    for s in stops {
703
                        let offset = s.offset.normalized() * 100.0;
704
                        assert!(
705
                            (0.0..=100.0).contains(&offset),
706
                            "gradient stop outside 0%..100%: {offset}",
707
                        );
708
                        assert!(
709
                            offset >= prev,
710
                            "gradient stops are not sorted: {offset} follows {prev}",
711
                        );
712
                        prev = offset;
713
                    }
714
                }
715
                other => panic!("the progress bar gradients degraded to {other:?}"),
716
            }
717
        }
718
    }
719

            
720
    #[test]
721
    fn create_is_usable_in_const_context() {
722
        // `create` is `const fn`; a caller may therefore build a bar as a `const`
723
        // item. That only const-evaluates while the backgrounds stay
724
        // `from_const_slice` (a heap allocation would not be const-evaluable).
725
        const CONST_BAR: ProgressBar = ProgressBar::create(12.5);
726

            
727
        assert_eq!(CONST_BAR.progressbar_state.percent_done, 12.5);
728
        assert_eq!(raw(CONST_BAR.height), 15_000);
729
        assert_eq!(CONST_BAR.bar_background.len(), 1);
730
    }
731

            
732
    // ------------------------------------------------------------------
733
    // ProgressBar::swap_with_default
734
    // ------------------------------------------------------------------
735

            
736
    #[test]
737
    fn swap_with_default_returns_the_previous_bar_and_installs_a_pristine_one() {
738
        for p in ADVERSARIAL_PERCENTS {
739
            let mut pb = ProgressBar::create(p).with_height(PixelValue::const_px(99));
740
            let prev = pb.swap_with_default();
741

            
742
            assert_eq!(
743
                prev.progressbar_state.percent_done.to_bits(),
744
                p.to_bits(),
745
                "the returned bar is not the one that was there ({p})",
746
            );
747
            assert_eq!(raw(prev.height), 99_000, "the returned bar lost its height");
748

            
749
            assert_eq!(
750
                pb.progressbar_state.percent_done.to_bits(),
751
                0_u32,
752
                "the replacement must be +0.0 — a -0.0 would encode with the sign bit set",
753
            );
754
            assert_eq!(
755
                raw(pb.height),
756
                15_000,
757
                "the replacement must use the default height"
758
            );
759
            assert_eq!(
760
                pb.bar_background.as_ptr(),
761
                create_gradient_ptrs().0,
762
                "the replacement must borrow the static gradient again",
763
            );
764
        }
765
    }
766

            
767
    #[test]
768
    fn swap_with_default_keeps_a_nan_percentage_and_moves_owned_memory_out() {
769
        let owned = solid(4);
770
        let ptr = owned.as_ptr();
771
        let mut pb = ProgressBar::create(f32::NAN).with_bar_background(owned);
772

            
773
        let prev = pb.swap_with_default();
774

            
775
        assert!(
776
            prev.progressbar_state.percent_done.is_nan(),
777
            "a NaN percentage did not survive the swap",
778
        );
779
        assert_eq!(
780
            prev.bar_background.as_ptr(),
781
            ptr,
782
            "the heap buffer was copied instead of moved out",
783
        );
784
        assert_eq!(prev.bar_background.len(), 4);
785

            
786
        // Dropping the previous value frees that heap buffer. If `swap_with_default`
787
        // had left `self` pointing at it too, everything below would be a
788
        // use-after-free.
789
        drop(prev);
790
        assert_eq!(
791
            pb.bar_background.as_ref(),
792
            STYLE_BACKGROUND_CONTENT_2688422633177340412_ITEMS,
793
            "the swapped-in bar aliased the memory that was just freed",
794
        );
795
        assert_eq!(pb.progressbar_state.percent_done, 0.0);
796
    }
797

            
798
    #[test]
799
    fn repeated_swaps_never_alias_or_leak_the_backgrounds() {
800
        let mut pb = ProgressBar::create(1.0);
801
        let (bar_ptr, _) = create_gradient_ptrs();
802
        for i in 0..1_000_usize {
803
            let want = i % 8 + 1;
804
            pb.set_bar_background(solid(want));
805
            let prev = pb.swap_with_default();
806

            
807
            assert_eq!(
808
                prev.bar_background.len(),
809
                want,
810
                "round {i} handed back the wrong buffer"
811
            );
812
            assert_eq!(pb.progressbar_state.percent_done, 0.0);
813
            assert_eq!(pb.bar_background.as_ptr(), bar_ptr);
814
        }
815
    }
816

            
817
    // ------------------------------------------------------------------
818
    // set_/with_ background
819
    // ------------------------------------------------------------------
820

            
821
    #[test]
822
    fn each_background_setter_touches_exactly_one_field() {
823
        let mut pb = ProgressBar::create(50.0);
824
        let bar_ptr = pb.bar_background.as_ptr();
825
        pb.set_container_background(solid(3));
826
        assert_eq!(pb.container_background.len(), 3);
827
        assert_eq!(
828
            pb.bar_background.as_ptr(),
829
            bar_ptr,
830
            "set_container_background clobbered the bar background",
831
        );
832

            
833
        let mut pb = ProgressBar::create(50.0);
834
        let container_ptr = pb.container_background.as_ptr();
835
        pb.set_bar_background(solid(5));
836
        assert_eq!(pb.bar_background.len(), 5);
837
        assert_eq!(
838
            pb.container_background.as_ptr(),
839
            container_ptr,
840
            "set_bar_background clobbered the container background",
841
        );
842
        assert_eq!(pb.progressbar_state.percent_done, 50.0);
843
        assert_eq!(raw(pb.height), 15_000);
844
    }
845

            
846
    #[test]
847
    fn the_builder_forms_are_exactly_their_setters() {
848
        let a = ProgressBar::create(7.5)
849
            .with_bar_background(solid(3))
850
            .with_container_background(solid(2))
851
            .with_height(PixelValue::px(-4.5));
852

            
853
        let mut b = ProgressBar::create(7.5);
854
        b.set_bar_background(solid(3));
855
        b.set_container_background(solid(2));
856
        b.set_height(PixelValue::px(-4.5));
857

            
858
        assert_eq!(a.bar_background.as_ref(), b.bar_background.as_ref());
859
        assert_eq!(
860
            a.container_background.as_ref(),
861
            b.container_background.as_ref()
862
        );
863
        assert_eq!(a.height, b.height);
864
        assert_eq!(
865
            a.progressbar_state.percent_done,
866
            b.progressbar_state.percent_done,
867
        );
868
        assert_eq!(
869
            a.progressbar_state.display_percentage,
870
            b.progressbar_state.display_percentage,
871
        );
872
    }
873

            
874
    #[test]
875
    fn an_empty_background_stays_an_empty_declaration() {
876
        let pb = ProgressBar::create(0.0)
877
            .with_bar_background(StyleBackgroundContentVec::from_vec(Vec::new()))
878
            .with_container_background(StyleBackgroundContentVec::new());
879

            
880
        assert!(pb.bar_background.is_empty());
881
        assert_eq!(pb.bar_background.len(), 0);
882
        assert!(pb.container_background.is_empty());
883

            
884
        let dom = pb.render_bar();
885
        assert_eq!(
886
            background_of(bar(&dom)),
887
            Some(Vec::new()),
888
            "an empty background must reach the DOM as an empty layer list, not vanish",
889
        );
890
        assert_eq!(background_of(&dom), Some(Vec::new()));
891
    }
892

            
893
    #[test]
894
    fn a_background_with_spare_capacity_keeps_its_allocation_intact() {
895
        // The free path rebuilds a `Vec` from (ptr, len, cap); a `cap` that drifted
896
        // to `len` frees the wrong layout.
897
        let mut v = Vec::with_capacity(64);
898
        v.push(StyleBackgroundContent::Color(ColorU {
899
            r: 1,
900
            g: 2,
901
            b: 3,
902
            a: 4,
903
        }));
904
        let bg = StyleBackgroundContentVec::from_vec(v);
905
        assert_eq!(bg.len(), 1);
906
        assert!(
907
            bg.capacity() >= 64,
908
            "from_vec lost the spare capacity: {}",
909
            bg.capacity()
910
        );
911

            
912
        let pb = ProgressBar::create(0.0).with_container_background(bg);
913
        assert_eq!(pb.container_background.len(), 1);
914
        assert!(
915
            pb.container_background.capacity() >= 64,
916
            "the setter rewrote the buffer's capacity",
917
        );
918
    }
919

            
920
    #[test]
921
    fn a_very_large_background_is_neither_truncated_nor_copied() {
922
        let big = solid(10_000);
923
        let ptr = big.as_ptr();
924
        let pb = ProgressBar::create(50.0).with_bar_background(big);
925
        assert_eq!(pb.bar_background.len(), 10_000);
926
        assert_eq!(
927
            pb.bar_background.as_ptr(),
928
            ptr,
929
            "the setter deep-copied a 10k-layer background"
930
        );
931

            
932
        let dom = pb.render_bar();
933
        assert_eq!(
934
            background_of(bar(&dom)).map(|v| v.len()),
935
            Some(10_000),
936
            "the background was truncated on the way into the DOM",
937
        );
938
    }
939

            
940
    #[test]
941
    fn overwriting_a_background_releases_the_previous_one() {
942
        // 500 replacements of an owned buffer: a setter that forgot to drop the old
943
        // value leaks, and one that dropped it twice aborts.
944
        let n = 500_usize;
945
        let mut pb = ProgressBar::create(0.0);
946
        for i in 1..=n {
947
            pb.set_bar_background(solid(i % 16 + 1));
948
            pb.set_container_background(solid(i % 4 + 1));
949
        }
950
        // The surviving background is whatever the LAST iteration installed, so the
951
        // expected length is derived from `n` rather than hard-coded.
952
        assert_eq!(pb.bar_background.len(), n % 16 + 1);
953
        assert_eq!(pb.container_background.len(), n % 4 + 1);
954
    }
955

            
956
    #[test]
957
    fn cloning_deep_copies_owned_backgrounds_but_shares_static_ones() {
958
        let pb = ProgressBar::create(3.0).with_bar_background(solid(4));
959
        let copy = pb.clone();
960

            
961
        assert_ne!(
962
            copy.bar_background.as_ptr(),
963
            pb.bar_background.as_ptr(),
964
            "Clone shared an owned heap buffer — dropping both would double-free it",
965
        );
966
        assert_eq!(
967
            copy.container_background.as_ptr(),
968
            pb.container_background.as_ptr(),
969
            "the static gradient is never freed, so the clone should keep sharing it",
970
        );
971

            
972
        drop(pb);
973
        assert_eq!(copy.bar_background.len(), 4);
974
        assert_eq!(
975
            copy.bar_background.as_ref()[3],
976
            StyleBackgroundContent::Color(ColorU {
977
                r: 3,
978
                g: 1,
979
                b: 2,
980
                a: 255,
981
            }),
982
            "the clone read back garbage after the original was dropped",
983
        );
984
    }
985

            
986
    // ------------------------------------------------------------------
987
    // set_height / with_height
988
    // ------------------------------------------------------------------
989

            
990
    #[test]
991
    fn set_height_stores_every_pixel_value_verbatim() {
992
        for h in adversarial_heights() {
993
            let mut pb = ProgressBar::create(0.0);
994
            pb.set_height(h);
995
            assert_eq!(
996
                pb.height.metric, h.metric,
997
                "set_height changed the unit of {h:?}"
998
            );
999
            assert_eq!(raw(pb.height), raw(h), "set_height re-encoded {h:?}");
            // and nothing else moved
            assert_eq!(pb.progressbar_state.percent_done, 0.0);
            assert_eq!(pb.bar_background.len(), 1);
        }
    }
    #[test]
    fn an_out_of_range_height_saturates_instead_of_wrapping() {
        let mut pb = ProgressBar::create(0.0);
        // `FloatValue::new` computes `value * 1000.0` in `f32` (which overflows to
        // an infinity) and then casts to `isize` — a saturating cast, so the result
        // is a bound, never a wrapped negative.
        pb.set_height(PixelValue::px(f32::MAX));
        assert_eq!(
            raw(pb.height),
            isize::MAX,
            "an overflowing height wrapped instead of saturating"
        );
        assert!(
            pb.height.number.get().is_finite(),
            "the saturated height decoded to a non-finite f32"
        );
        pb.set_height(PixelValue::px(f32::INFINITY));
        assert_eq!(raw(pb.height), isize::MAX);
        pb.set_height(PixelValue::px(f32::MIN));
        assert_eq!(raw(pb.height), isize::MIN);
        pb.set_height(PixelValue::px(f32::NEG_INFINITY));
        assert_eq!(raw(pb.height), isize::MIN);
        pb.set_height(PixelValue::px(f32::NAN));
        assert_eq!(
            raw(pb.height),
            0,
            "a NaN height must land on 0, not on an arbitrary integer"
        );
        pb.set_height(PixelValue::px(-0.0));
        assert_eq!(raw(pb.height), 0, "-0.0 must encode to the same 0 as +0.0");
        // Below the 1/1000 resolution everything truncates to zero, deterministically.
        pb.set_height(PixelValue::px(0.0004));
        assert_eq!(raw(pb.height), 0);
        pb.set_height(PixelValue::px(f32::MIN_POSITIVE));
        assert_eq!(raw(pb.height), 0);
    }
    #[test]
    fn with_height_is_set_height_and_leaves_the_rest_alone() {
        for h in adversarial_heights() {
            let a = ProgressBar::create(42.0).with_height(h);
            let mut b = ProgressBar::create(42.0);
            b.set_height(h);
            assert_eq!(
                a.height, b.height,
                "with_height disagreed with set_height for {h:?}"
            );
            assert_eq!(raw(a.height), raw(h));
            assert_eq!(a.progressbar_state.percent_done, 42.0);
            assert_eq!(
                a.bar_background.as_ptr(),
                b.bar_background.as_ptr(),
                "with_height reallocated the background",
            );
        }
    }
    // ------------------------------------------------------------------
    // ProgressBar::dom
    // ------------------------------------------------------------------
    #[test]
    fn render_bar_is_a_container_div_with_exactly_two_leaf_children() {
        let dom = ProgressBar::create(50.0).render_bar();
        assert!(matches!(dom.root.get_node_type(), NodeType::Div));
        assert_eq!(
            kids(&dom).len(),
            2,
            "the progress bar must render bar + remaining"
        );
        assert!(kids(bar(&dom)).is_empty(), "the bar must stay a leaf");
        assert!(
            kids(remaining(&dom)).is_empty(),
            "the remaining space must stay a leaf"
        );
        // A cached child count that is too small makes `convert_dom_into_compact_dom`
        // under-allocate its arenas and panic on out-of-bounds writes.
        assert_eq!(dom.estimated_total_children, 2);
        assert_eq!(
            classes(&dom),
            vec!["__azul-native-progress-bar-container".to_string()]
        );
        assert_eq!(
            classes(bar(&dom)),
            vec!["__azul-native-progress-bar-bar".to_string()]
        );
        assert_eq!(
            classes(remaining(&dom)),
            vec!["__azul-native-progress-bar-remaining".to_string()],
        );
    }
    #[test]
    fn render_bar_clamps_every_out_of_range_percentage_into_zero_to_one_hundred() {
        // (input, bar width, remaining width) — widths in 1/1000 of a percent.
        const CASES: [(f32, isize, isize); 12] = [
            (0.0, 0, 100_000),
            (-0.0, 0, 100_000),
            (50.0, 50_000, 50_000),
            (100.0, 100_000, 0),
            (-1.0, 0, 100_000),
            (101.0, 100_000, 0),
            (-1e30, 0, 100_000),
            (1e30, 100_000, 0),
            (f32::MAX, 100_000, 0),
            (f32::MIN, 0, 100_000),
            (f32::INFINITY, 100_000, 0),
            (f32::NEG_INFINITY, 0, 100_000),
        ];
        for (input, bar_width, remaining_width) in CASES {
            let dom = ProgressBar::create(input).render_bar();
            let b = width_of(bar(&dom)).expect("the bar must declare a width");
            let r = width_of(remaining(&dom)).expect("the remaining space must declare a width");
            assert_eq!(
                b.metric,
                SizeMetric::Percent,
                "the bar must size in %, not {:?}",
                b.metric
            );
            assert_eq!(
                r.metric,
                SizeMetric::Percent,
                "the gap must size in %, not {:?}",
                r.metric
            );
            assert_eq!(raw(b), bar_width, "bar width for input {input}");
            assert_eq!(raw(r), remaining_width, "remaining width for input {input}");
            assert!(
                raw(b) >= 0 && raw(r) >= 0,
                "a negative width escaped for input {input}"
            );
        }
    }
    #[test]
    fn render_bar_collapses_a_nan_percentage_to_two_empty_children() {
        // `f32::clamp` propagates NaN rather than clamping it, and the `f32 -> isize`
        // cast inside `FloatValue::new` then turns it into 0. The documented result:
        // BOTH children get 0% — the bar renders as an empty container instead of
        // falling back to 0%/100%. It does not panic, and it is deterministic.
        let dom = ProgressBar::create(f32::NAN).render_bar();
        let b = width_of(bar(&dom)).expect("the bar must declare a width");
        let r = width_of(remaining(&dom)).expect("the remaining space must declare a width");
        assert_eq!(raw(b), 0);
        assert_eq!(raw(r), 0);
        assert_eq!(b.metric, SizeMetric::Percent);
        assert_eq!(r.metric, SizeMetric::Percent);
        assert_eq!(
            kids(&dom).len(),
            2,
            "a NaN percentage must not change the tree shape"
        );
    }
    #[test]
    fn render_bar_splits_the_container_exactly_for_whole_percentages() {
        for i in 0..=100_isize {
            let dom = ProgressBar::create(i as f32).render_bar();
            let b = raw(width_of(bar(&dom)).unwrap());
            let r = raw(width_of(remaining(&dom)).unwrap());
            assert_eq!(b, i * 1000, "the bar is not {i}% wide");
            assert_eq!(
                b + r,
                100_000,
                "the two halves do not add up to the container at {i}%",
            );
        }
    }
    #[test]
    fn render_bar_loses_at_most_the_encoding_truncation_for_fractional_percentages() {
        // Each side is truncated to 1/1000 of a percent independently, so the pair
        // may under-fill by two ticks — but never overflow the container, and never
        // go negative.
        for p in [
            0.0005_f32,
            0.5,
            1.0 / 3.0,
            33.333,
            66.667,
            99.999,
            99.9999,
            f32::EPSILON,
            f32::MIN_POSITIVE,
        ] {
            let dom = ProgressBar::create(p).render_bar();
            let b = raw(width_of(bar(&dom)).unwrap());
            let r = raw(width_of(remaining(&dom)).unwrap());
            assert!(
                (0..=100_000).contains(&b) && (0..=100_000).contains(&r),
                "a width left 0%..100% for {p}: {b} / {r}",
            );
            assert!(
                (b + r - 100_000).abs() <= 10,
                "the two halves drifted apart for {p}: {b} + {r}",
            );
        }
    }
    #[test]
    fn render_bar_routes_each_background_to_its_own_node() {
        let bar_bg = solid(3);
        let container_bg = solid(5);
        let bar_ptr = bar_bg.as_ptr();
        let container_ptr = container_bg.as_ptr();
        let dom = ProgressBar::create(25.0)
            .with_bar_background(bar_bg)
            .with_container_background(container_bg)
            .render_bar();
        assert_eq!(
            background_of(&dom).map(|v| v.len()),
            Some(5),
            "the container lost (or swapped) its background",
        );
        assert_eq!(
            background_of(bar(&dom)).map(|v| v.len()),
            Some(3),
            "the bar lost (or swapped) its background",
        );
        assert_eq!(
            background_of(remaining(&dom)),
            None,
            "the remaining space must not paint anything",
        );
        // The bar background is *moved* into the DOM — same allocation, no copy.
        assert_eq!(
            background_ptr(bar(&dom)),
            Some(bar_ptr),
            "the bar background was copied instead of moved",
        );
        // The container background is cloned, because `self` — and with it the
        // original buffer — is dropped at the end of `render_bar()`. Handing the DOM the
        // same pointer would be a use-after-free.
        assert_ne!(
            background_ptr(&dom),
            Some(container_ptr),
            "the DOM kept a pointer into a buffer that `dom()` then freed",
        );
    }
    #[test]
    fn render_bar_forwards_any_height_to_the_container_and_to_nobody_else() {
        for h in adversarial_heights() {
            let dom = ProgressBar::create(50.0).with_height(h).render_bar();
            let got = height_of(&dom).expect("the container must declare a height");
            assert_eq!(
                got.metric, h.metric,
                "the height unit changed on the way into the DOM"
            );
            assert_eq!(
                raw(got),
                raw(h),
                "the height was re-encoded on the way into the DOM"
            );
            assert_eq!(
                height_of(bar(&dom)),
                None,
                "the bar must not declare its own height"
            );
            assert_eq!(
                height_of(remaining(&dom)),
                None,
                "the remaining space must not declare its own height",
            );
            assert_eq!(
                width_of(&dom),
                None,
                "the container must not declare a width"
            );
        }
    }
    #[test]
    fn render_bar_declares_the_expected_style_blocks_and_no_property_twice() {
        let dom = ProgressBar::create(50.0)
            .with_bar_background(solid(1))
            .render_bar();
        // `render_bar()` is the percentage-sized entry point (`bounds_px: None`),
        // so the container declares no `width` — the VirtualView path, which
        // sizes in absolute pixels from known bounds, declares one more.
        assert_eq!(
            inline_props(&dom).len(),
            20,
            "the container style block drifted"
        );
        assert_eq!(
            inline_props(bar(&dom)).len(),
            10,
            "the bar style block drifted"
        );
        let props = inline_props(remaining(&dom));
        assert_eq!(
            props.len(),
            1,
            "the remaining space grew a style block: {props:?}"
        );
        assert!(
            matches!(&props[0], CssProperty::Width(_)),
            "the remaining space must only declare its width",
        );
        // A property declared twice means one of the two is silently dead, and which
        // one wins depends on cascade order.
        for node in [&dom, bar(&dom), remaining(&dom)] {
            let mut seen = HashSet::new();
            for p in inline_props(node) {
                assert!(
                    seen.insert(core::mem::discriminant(&p)),
                    "duplicate declaration of {p:?}",
                );
            }
        }
    }
    #[test]
    fn render_bar_chrome_lengths_are_all_absolute_pixels() {
        // Only the two child widths are relative. A border or radius that slipped
        // into `em`/`%` would resolve against the parent font or box and either
        // vanish or blow up.
        let dom = ProgressBar::create(50.0).render_bar();
        for node in [&dom, bar(&dom), remaining(&dom)] {
            for p in inline_props(node) {
                for length in lengths_of(&p) {
                    assert_eq!(
                        length.metric,
                        SizeMetric::Px,
                        "{p:?} declares a relative length: {length:?}",
                    );
                }
            }
        }
    }
    #[test]
    fn render_bar_ignores_display_percentage() {
        // The field is public and settable, but nothing in `render_bar()` reads it: the
        // rendered tree has to be byte-identical either way.
        let mut with_label = ProgressBar::create(40.0);
        with_label.progressbar_state.display_percentage = true;
        let without_label = ProgressBar::create(40.0);
        assert_eq!(
            with_label.render_bar(),
            without_label.render_bar(),
            "display_percentage started changing the tree",
        );
    }
    #[test]
    fn render_bar_is_deterministic_for_equal_inputs() {
        let a = ProgressBar::create(37.5)
            .with_bar_background(solid(2))
            .with_height(PixelValue::px(7.25))
            .render_bar();
        let b = ProgressBar::create(37.5)
            .with_bar_background(solid(2))
            .with_height(PixelValue::px(7.25))
            .render_bar();
        assert_eq!(
            a, b,
            "two identically-built progress bars rendered differently"
        );
    }
    /// The bar's percentage is its accessibility VALUE, on the container, as a
    /// `ProgressBar` role — so a screen reader announces "progress bar, 75%"
    /// instead of two anonymous divs. Out-of-range and NaN inputs announce
    /// what the bar draws (clamped / empty), never "NaN%".
    #[test]
    fn render_bar_publishes_its_percentage_as_the_accessibility_value() {
        use azul_core::a11y::AccessibilityRole;
        for (input, expected) in [
            (75.0_f32, "75%"),
            (0.0, "0%"),
            (100.0, "100%"),
            (33.3, "33%"),
            (-5.0, "0%"),
            (250.0, "100%"),
            (f32::NAN, "0%"),
            (f32::INFINITY, "100%"),
        ] {
            let dom = ProgressBar::create(input).render_bar();
            let info = dom
                .root
                .get_accessibility_info()
                .unwrap_or_else(|| panic!("{input}: the container carries accessibility info"));
            assert_eq!(info.role, AccessibilityRole::ProgressBar, "{input}");
            assert_eq!(
                info.accessibility_value.as_ref().map(AzString::as_str),
                Some(expected),
                "{input}: the percentage is the accessibility value"
            );
        }
    }
    #[test]
    fn render_bar_survives_every_extreme_percentage_and_background_size() {
        for p in ADVERSARIAL_PERCENTS.into_iter().chain([f32::NAN]) {
            for layers in [0_usize, 1, 64] {
                let dom = ProgressBar::create(p)
                    .with_bar_background(solid(layers))
                    .with_container_background(solid(layers))
                    .with_height(PixelValue::px(f32::MAX))
                    .render_bar();
                assert_eq!(
                    kids(&dom).len(),
                    2,
                    "shape changed for {p} / {layers} layers"
                );
                assert_eq!(dom.estimated_total_children, 2);
                assert_eq!(background_of(bar(&dom)).map(|v| v.len()), Some(layers));
                assert_eq!(background_of(&dom).map(|v| v.len()), Some(layers));
                let b = width_of(bar(&dom)).expect("the bar must declare a width");
                assert_eq!(b.metric, SizeMetric::Percent);
                assert!(
                    (0..=100_000).contains(&raw(b)),
                    "width out of range for {p}"
                );
            }
        }
    }
    // ------------------------------------------------------------------
    // ProgressBar::dom — the VirtualView wrapper (the fast path's mount)
    // ------------------------------------------------------------------
    /// Runs `f` against a `VirtualViewCallbackInfo` reporting `w x h` bounds
    /// (the same harness shape the map widget's VV tests use).
    fn with_virtual_view_info<R>(
        w: f32,
        h: f32,
        f: impl FnOnce(VirtualViewCallbackInfo) -> R,
    ) -> R {
        use azul_core::{
            callbacks::{HidpiAdjustedBounds, VirtualViewCallbackReason},
            geom::LogicalSize,
            resources::{DpiScaleFactor, ImageCache},
            window::WindowTheme,
        };
        use rust_fontconfig::FcFontCache;
        let fonts = FcFontCache::default();
        let images = ImageCache::default();
        let size = LogicalSize::new(w, h);
        let info = VirtualViewCallbackInfo::new(
            VirtualViewCallbackReason::InitialRender,
            &fonts,
            &images,
            WindowTheme::LightMode,
            azul_core::window::WindowFrame::Normal,
            HidpiAdjustedBounds {
                logical_size: size,
                hidpi_factor: DpiScaleFactor::new(1.0),
            },
            LogicalRect::new(LogicalPosition::zero(), size),
            LogicalRect::new(LogicalPosition::zero(), size),
            LogicalPosition::zero(),
        );
        f(info)
    }
    #[test]
    fn dom_mounts_a_virtual_view_leaf_carrying_the_private_dataset() {
        let dom = ProgressBar::create(30.0).dom();
        assert!(
            dom.root.is_virtual_view_node(),
            "dom() must mount the bar as a VirtualView, or update_progress has nothing to \
             re-render"
        );
        assert!(
            kids(&dom).is_empty(),
            "the wrapper is a LEAF - the bar's tree comes from the VV callback, never from the \
             outer DOM"
        );
        let mut ds = dom
            .root
            .get_dataset()
            .cloned()
            .expect("the wrapper must carry the dataset update_progress looks up");
        let state = ds
            .downcast_ref::<ProgressBarLocalDataset>()
            .expect("the dataset is the widget's private type");
        assert_eq!(state.bar.progressbar_state.percent_done, 30.0);
    }
    #[test]
    fn dom_wrapper_declares_its_height_and_hides_overflow_and_nothing_else() {
        // The VV node's box is what the callback renders INTO, so it must be
        // definitely sized by the wrapper itself - and only sized: all visual
        // chrome lives in the rendered tree where a re-render can change it.
        let dom = ProgressBar::create(50.0)
            .with_height(PixelValue::const_px(22))
            .dom();
        let h = height_of(&dom).expect("the wrapper must declare the height");
        assert_eq!(h.metric, SizeMetric::Px);
        assert_eq!(raw(h), 22_000);
        // Width 100%: a VirtualView is replaced-element-like and would take
        // the 300px intrinsic default instead of stretching to its parent.
        let w = width_of(&dom).expect("the wrapper must declare width: 100%");
        assert_eq!(w.metric, SizeMetric::Percent);
        assert_eq!(raw(w), 100_000);
        assert_eq!(
            inline_props(&dom).len(),
            4,
            "wrapper style must stay height + width + overflow-x/y: {:?}",
            inline_props(&dom)
        );
    }
    #[test]
    fn virtual_view_callback_renders_the_stored_bar_into_the_bounds() {
        let dom = ProgressBar::create(40.0).dom();
        let vv = dom
            .root
            .get_virtual_view_node_ref()
            .expect("a VirtualView node stores its callback + refany");
        let payload = vv.refany.clone();
        let ret = with_virtual_view_info(200.0, 15.0, |info| {
            crate::widgets::themes::flat::progressbar_render_virtual_view(payload, info)
        });
        let rendered = match &ret.dom {
            azul_core::dom::OptionDom::Some(d) => d,
            azul_core::dom::OptionDom::None => panic!("the callback must render the bar"),
        };
        assert_eq!(kids(rendered).len(), 2, "bar + remaining");
        // Inside the VV the callback renders PIXEL widths from its known
        // bounds (percent children do not resolve against VV bounds):
        // 200px - 2px borders = 198px content, 40% of that = 79.2px.
        let b = width_of(bar(rendered)).unwrap();
        assert_eq!(b.metric, SizeMetric::Px);
        assert_eq!(raw(b), 79_200);
        // The container is sized to bounds MINUS its 1px border ring, so the
        // borders land INSIDE the materialized area instead of overflowing
        // it and being clipped ("oddly cut off", user report 2026-08-29).
        assert_eq!(raw(width_of(rendered).unwrap()), 198_000);
        assert_eq!(raw(height_of(rendered).unwrap()), 13_000);
        // Not scrollable content: one rect, three names.
        let want = LogicalRect::new(
            LogicalPosition::zero(),
            azul_core::geom::LogicalSize::new(200.0, 15.0),
        );
        assert_eq!(ret.materialized, want, "materialized must be the bounds");
        assert_eq!(ret.virtual_rect, want, "virtual_rect must be the bounds");
    }
    #[test]
    fn virtual_view_callback_and_dataset_share_one_allocation() {
        // THE fast-path contract: `update_progress` writes through the NODE
        // dataset, the re-render reads through the VV refany - they must be
        // clones of one allocation or the bar re-renders its stale self.
        let dom = ProgressBar::create(10.0).dom();
        let mut ds = dom.root.get_dataset().cloned().expect("node dataset");
        ds.downcast_mut::<ProgressBarLocalDataset>()
            .expect("private type")
            .bar
            .progressbar_state
            .percent_done = 80.0;
        let payload = dom
            .root
            .get_virtual_view_node_ref()
            .expect("vv node")
            .refany
            .clone();
        let ret = with_virtual_view_info(100.0, 15.0, |info| {
            crate::widgets::themes::flat::progressbar_render_virtual_view(payload, info)
        });
        let rendered = match &ret.dom {
            azul_core::dom::OptionDom::Some(d) => d,
            azul_core::dom::OptionDom::None => panic!("the callback must render the bar"),
        };
        // 100px bounds - 2px borders = 98px content; 80% of that = 78.4px.
        assert_eq!(
            raw(width_of(bar(rendered)).unwrap()),
            78_400,
            "a write through the node dataset did not reach the VV re-render",
        );
    }
    #[test]
    fn virtual_view_callback_rejects_a_foreign_payload() {
        let ret = with_virtual_view_info(100.0, 15.0, |info| {
            crate::widgets::themes::flat::progressbar_render_virtual_view(RefAny::new(0_u8), info)
        });
        assert!(
            matches!(ret.dom, azul_core::dom::OptionDom::None),
            "a foreign payload must render nothing, not panic or invent a bar",
        );
        assert_eq!(ret.materialized, LogicalRect::zero());
        assert_eq!(ret.virtual_rect, LogicalRect::zero());
    }
}