ailloli_ui_widgets/controls/
progress.rs

1//! Non-interactive linear and circular determinate progress indicators.
2
3use crate::layout::layout_ext::{apply_layout_size, finish_view_sized};
4use ailloli_ui_core::event::Event;
5use ailloli_ui_core::geometry::{Constraints, Rect, Size};
6use ailloli_ui_core::style::{Border, FlexItemStyle, LayoutSizeHint, LayoutStyle, Radius};
7use ailloli_ui_core::{Color, FontId, ProgressSpec, TextStyle, Theme};
8use ailloli_ui_runtime::component::{Binding, IntoView, Memo, View, Widget};
9use ailloli_ui_runtime::input::{EventCtx, FocusPolicy};
10use ailloli_ui_runtime::layout::{LayoutChild, LayoutCtx, LayoutResult};
11use ailloli_ui_runtime::scene::PaintCtx;
12use ailloli_ui_runtime::{DrawBorder, DrawCmd, DrawRRect, DrawRect, DrawRingProgress, DrawText};
13use ailloli_ui_text::{TextLayoutParams, WrapMode};
14
15#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
16/// Built-in geometry and typography choices for progress indicators.
17///
18/// # Examples
19///
20/// ```
21/// use ailloli_ui_widgets::controls::ProgressSize;
22/// assert_eq!(ProgressSize::default(), ProgressSize::Default);
23/// ```
24pub enum ProgressSize {
25    /// 180 × 6 bar and 44-pixel ring with 11-pixel label text.
26    Compact,
27    /// 220 × 8 bar and 58-pixel ring with 12-pixel label text.
28    #[default]
29    Default,
30    /// 280 × 12 bar and 72-pixel ring with 14-pixel label text.
31    Large,
32}
33
34#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
35/// Fill treatment for a [`ProgressBar`].
36///
37/// # Examples
38///
39/// ```
40/// use ailloli_ui_widgets::controls::ProgressVariant;
41/// assert_eq!(ProgressVariant::default(), ProgressVariant::Solid);
42/// ```
43pub enum ProgressVariant {
44    /// Uniform fill.
45    #[default]
46    Solid,
47    /// Repeating clipped rectangular stripes over enabled fill.
48    Striped,
49}
50
51#[derive(Clone, Debug, PartialEq)]
52/// Resolved colors, typography, and logical-pixel progress geometry.
53///
54/// `focus_neutral` is reserved for compatibility; progress widgets are not
55/// focusable and do not currently paint it.
56///
57/// # Examples
58///
59/// ```
60/// use ailloli_ui_core::Theme;
61/// use ailloli_ui_widgets::controls::{ProgressSize, ProgressStyle};
62/// let style = ProgressStyle::from_theme(Theme::dark(), ProgressSize::Large);
63/// assert_eq!((style.bar_width, style.bar_height), (280.0, 12.0));
64/// assert_eq!(style.circular_size, 72.0);
65/// ```
66pub struct ProgressStyle {
67    /// Enabled track fill.
68    pub track: Color,
69    /// Enabled active fill/ring color.
70    pub fill: Color,
71    /// Enabled striped-overlay color.
72    pub stripe: Color,
73    /// Disabled track color before opacity multiplication.
74    pub disabled_track: Color,
75    /// Disabled fill color before opacity multiplication.
76    pub disabled_fill: Color,
77    /// Linear bar border; circular progress does not paint it.
78    pub border: Border,
79    /// Enabled circular label style.
80    pub text: TextStyle,
81    /// Disabled circular label style.
82    pub muted_text: TextStyle,
83    /// Reserved focus color; currently unused.
84    pub focus_neutral: Color,
85    /// Linear intrinsic width.
86    pub bar_width: f32,
87    /// Linear intrinsic height.
88    pub bar_height: f32,
89    /// Circular intrinsic width and height.
90    pub circular_size: f32,
91    /// Circular ring thickness, later fitted to the resolved side.
92    pub circular_thickness: f32,
93    /// Alpha multiplier for disabled track, fill, label, and border.
94    pub disabled_opacity: f32,
95}
96
97impl Default for ProgressStyle {
98    fn default() -> Self {
99        Self::from_theme(Theme::default(), ProgressSize::Default)
100    }
101}
102
103impl ProgressStyle {
104    /// Resolves progress colors, metrics, and typography from `theme` and `size`.
105    ///
106    /// # Examples
107    ///
108    /// ```
109    /// use ailloli_ui_core::Theme;
110    /// use ailloli_ui_widgets::controls::{ProgressSize, ProgressStyle};
111    /// let style = ProgressStyle::from_theme(Theme::dark(), ProgressSize::Compact);
112    /// assert_eq!(style.circular_thickness, 5.0);
113    /// assert_eq!(style.text.px_size, 11);
114    /// ```
115    pub fn from_theme(theme: Theme, size: ProgressSize) -> Self {
116        let palette = theme.palette();
117        let (bar_width, bar_height, circular_size, circular_thickness, text_px) = match size {
118            ProgressSize::Compact => (180.0, 6.0, 44.0, 5.0, 11),
119            ProgressSize::Default => (220.0, 8.0, 58.0, 6.0, 12),
120            ProgressSize::Large => (280.0, 12.0, 72.0, 8.0, 14),
121        };
122        Self {
123            track: palette.surface_elevated,
124            fill: palette.accent,
125            stripe: Color::WHITE.with_alpha(0.20),
126            disabled_track: palette.surface.with_alpha(0.58),
127            disabled_fill: palette.accent.with_alpha(0.38),
128            border: Border::new(1.0, palette.border.with_alpha(0.72)),
129            text: TextStyle::new(FontId::Ui, text_px, palette.text),
130            muted_text: TextStyle::new(FontId::Ui, text_px, palette.text_muted),
131            focus_neutral: palette.focus,
132            bar_width,
133            bar_height,
134            circular_size,
135            circular_thickness,
136            disabled_opacity: 0.48,
137        }
138    }
139
140    /// Returns configured linear width and height without clamping.
141    fn bar_intrinsic_size(&self) -> Size {
142        Size::new(self.bar_width, self.bar_height)
143    }
144
145    /// Returns a square using configured circular size without clamping.
146    fn circular_intrinsic_size(&self) -> Size {
147        Size::new(self.circular_size, self.circular_size)
148    }
149}
150
151/// A non-focusable determinate linear progress bar.
152///
153/// Values are mapped and clamped through [`ProgressSpec`]. Non-finite values
154/// select the range minimum. Extreme finite domains may still yield a non-finite
155/// fraction as documented by `ProgressSpec`; normal domains paint `0.0..=1.0`.
156/// Disabled striped bars omit stripes and paint disabled colors/opacities.
157///
158/// # Examples
159///
160/// ```
161/// use ailloli_ui_widgets::controls::ProgressBar;
162/// let bar = ProgressBar::new().range(0.0, 100.0).value(42.0);
163/// let _ = bar;
164/// ```
165pub struct ProgressBar {
166    /// Layout configuration used to resolve intrinsic geometry.
167    pub(crate) layout: LayoutStyle,
168    /// Flex-item behavior used by the parent layout.
169    pub(crate) flex_item: FlexItemStyle,
170    /// Live value in the configured numeric domain.
171    value: Binding<f32>,
172    /// Live disabled state.
173    disabled: Binding<bool>,
174    /// Sanitized value domain.
175    spec: ProgressSpec,
176    /// Solid or striped enabled fill.
177    variant: ProgressVariant,
178    /// Resolved colors and geometry.
179    style: ProgressStyle,
180}
181
182crate::impl_layout_builders_unit!(ProgressBar);
183
184impl Default for ProgressBar {
185    fn default() -> Self {
186        Self::new()
187    }
188}
189
190impl ProgressBar {
191    /// Creates an enabled, empty solid bar over the `0.0..=1.0` domain.
192    ///
193    /// # Examples
194    ///
195    /// ```
196    /// use ailloli_ui_widgets::controls::ProgressBar;
197    /// let bar = ProgressBar::new();
198    /// let _ = bar;
199    /// ```
200    pub fn new() -> Self {
201        Self {
202            layout: LayoutStyle::default(),
203            flex_item: FlexItemStyle::default(),
204            value: Binding::Static(0.0),
205            disabled: Binding::Static(false),
206            spec: ProgressSpec::default(),
207            variant: ProgressVariant::Solid,
208            style: ProgressStyle::default(),
209        }
210    }
211
212    /// Sets a static or reactive value.
213    ///
214    /// Values outside the domain are visually clamped. NaN and infinities select
215    /// the minimum through [`ProgressSpec::clamp_value`].
216    ///
217    /// # Examples
218    ///
219    /// ```
220    /// use ailloli_ui_widgets::controls::ProgressBar;
221    /// let bar = ProgressBar::new().value(0.5);
222    /// let _ = bar;
223    /// ```
224    pub fn value(mut self, value: impl Into<Binding<f32>>) -> Self {
225        self.value = value.into();
226        self
227    }
228
229    /// Sets static or reactive disabled state.
230    ///
231    /// Progress remains visible but uses disabled colors/opacities and suppresses
232    /// stripes. These widgets are non-interactive regardless of disabled state.
233    ///
234    /// # Examples
235    ///
236    /// ```
237    /// use ailloli_ui_widgets::controls::ProgressBar;
238    /// let bar = ProgressBar::new().disabled(true);
239    /// let _ = bar;
240    /// ```
241    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
242        self.disabled = disabled.into();
243        self
244    }
245
246    /// Convenience alias for [`Self::disabled`] with a reactive memo.
247    ///
248    /// # Examples
249    ///
250    /// ```
251    /// use ailloli_ui_runtime::component::Memo;
252    /// use ailloli_ui_widgets::controls::ProgressBar;
253    /// let bar = ProgressBar::new().disabled_signal(Memo::new(|| false));
254    /// let _ = bar;
255    /// ```
256    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
257        self.disabled(disabled)
258    }
259
260    /// Replaces range bounds and immediately sanitizes them.
261    ///
262    /// Reversed bounds swap, equal finite bounds try to expand max by `1.0`, and
263    /// any non-finite bound resets the range to `0.0..=1.0`.
264    ///
265    /// # Examples
266    ///
267    /// ```
268    /// use ailloli_ui_widgets::controls::ProgressBar;
269    /// let bar = ProgressBar::new().range(100.0, 0.0).value(25.0);
270    /// let _ = bar; // sanitized domain is 0..=100
271    /// ```
272    pub fn range(mut self, min: f32, max: f32) -> Self {
273        self.spec.min = min;
274        self.spec.max = max;
275        self.spec = self.spec.sanitized();
276        self
277    }
278
279    /// Replaces and sanitizes the complete numeric domain.
280    ///
281    /// # Examples
282    ///
283    /// ```
284    /// use ailloli_ui_core::ProgressSpec;
285    /// use ailloli_ui_widgets::controls::ProgressBar;
286    /// let bar = ProgressBar::new().progress_spec(ProgressSpec::new(10.0, 20.0));
287    /// let _ = bar;
288    /// ```
289    pub fn progress_spec(mut self, spec: ProgressSpec) -> Self {
290        self.spec = spec.sanitized();
291        self
292    }
293
294    /// Selects solid or striped enabled fill.
295    ///
296    /// # Examples
297    ///
298    /// ```
299    /// use ailloli_ui_widgets::controls::{ProgressBar, ProgressVariant};
300    /// let bar = ProgressBar::new().variant(ProgressVariant::Striped);
301    /// let _ = bar;
302    /// ```
303    pub fn variant(mut self, variant: ProgressVariant) -> Self {
304        self.variant = variant;
305        self
306    }
307
308    /// Replaces complete resolved style without clamping its values.
309    ///
310    /// A later [`Self::progress_size`] call discards this custom style.
311    ///
312    /// # Examples
313    ///
314    /// ```
315    /// use ailloli_ui_core::Theme;
316    /// use ailloli_ui_widgets::controls::{ProgressBar, ProgressSize, ProgressStyle};
317    /// let style = ProgressStyle::from_theme(Theme::dark(), ProgressSize::Compact);
318    /// let bar = ProgressBar::new().progress_style(style);
319    /// let _ = bar;
320    /// ```
321    pub fn progress_style(mut self, style: ProgressStyle) -> Self {
322        self.style = style;
323        self
324    }
325
326    /// Replaces complete style with the default-theme built-in size.
327    ///
328    /// # Examples
329    ///
330    /// ```
331    /// use ailloli_ui_widgets::controls::{ProgressBar, ProgressSize};
332    /// let bar = ProgressBar::new().progress_size(ProgressSize::Large);
333    /// let _ = bar;
334    /// ```
335    pub fn progress_size(mut self, size: ProgressSize) -> Self {
336        self.style = ProgressStyle::from_theme(Theme::default(), size);
337        self
338    }
339}
340
341/// A non-focusable determinate circular progress ring with an optional label.
342///
343/// The ring is centered in the shortest resolved side and begins at 12 o'clock.
344/// With `show_label(true)` and no custom label, a rounded whole percentage is
345/// generated. A stored custom label is painted even after `show_label(false)`;
346/// there is no builder that clears it.
347///
348/// # Examples
349///
350/// ```
351/// use ailloli_ui_widgets::controls::CircularProgress;
352/// let progress = CircularProgress::new().value(0.75).show_label(true);
353/// let _ = progress;
354/// ```
355pub struct CircularProgress {
356    /// Layout configuration used to resolve intrinsic square geometry.
357    pub(crate) layout: LayoutStyle,
358    /// Flex-item behavior used by the parent layout.
359    pub(crate) flex_item: FlexItemStyle,
360    /// Live value in the configured numeric domain.
361    value: Binding<f32>,
362    /// Live disabled state.
363    disabled: Binding<bool>,
364    /// Sanitized value domain.
365    spec: ProgressSpec,
366    /// Resolved colors, typography, size, and ring thickness.
367    style: ProgressStyle,
368    /// Whether to generate a percentage when no custom label exists.
369    show_label: bool,
370    /// Optional static or reactive custom center label.
371    label: Option<Binding<String>>,
372}
373
374crate::impl_layout_builders_unit!(CircularProgress);
375
376impl Default for CircularProgress {
377    fn default() -> Self {
378        Self::new()
379    }
380}
381
382impl CircularProgress {
383    /// Creates an enabled, empty unlabeled ring over `0.0..=1.0`.
384    ///
385    /// # Examples
386    ///
387    /// ```
388    /// use ailloli_ui_widgets::controls::CircularProgress;
389    /// let progress = CircularProgress::new();
390    /// let _ = progress;
391    /// ```
392    pub fn new() -> Self {
393        Self {
394            layout: LayoutStyle::default(),
395            flex_item: FlexItemStyle::default(),
396            value: Binding::Static(0.0),
397            disabled: Binding::Static(false),
398            spec: ProgressSpec::default(),
399            style: ProgressStyle::default(),
400            show_label: false,
401            label: None,
402        }
403    }
404
405    /// Sets a static or reactive value, visually clamped through the domain.
406    ///
407    /// # Examples
408    ///
409    /// ```
410    /// use ailloli_ui_widgets::controls::CircularProgress;
411    /// let progress = CircularProgress::new().value(0.25);
412    /// let _ = progress;
413    /// ```
414    pub fn value(mut self, value: impl Into<Binding<f32>>) -> Self {
415        self.value = value.into();
416        self
417    }
418
419    /// Sets static or reactive disabled state.
420    ///
421    /// Disabled state changes colors and label style; the ring is non-interactive
422    /// in either state.
423    ///
424    /// # Examples
425    ///
426    /// ```
427    /// use ailloli_ui_widgets::controls::CircularProgress;
428    /// let progress = CircularProgress::new().disabled(true);
429    /// let _ = progress;
430    /// ```
431    pub fn disabled(mut self, disabled: impl Into<Binding<bool>>) -> Self {
432        self.disabled = disabled.into();
433        self
434    }
435
436    /// Convenience alias for [`Self::disabled`] with a reactive memo.
437    ///
438    /// # Examples
439    ///
440    /// ```
441    /// use ailloli_ui_runtime::component::Memo;
442    /// use ailloli_ui_widgets::controls::CircularProgress;
443    /// let progress = CircularProgress::new().disabled_signal(Memo::new(|| false));
444    /// let _ = progress;
445    /// ```
446    pub fn disabled_signal(self, disabled: Memo<bool>) -> Self {
447        self.disabled(disabled)
448    }
449
450    /// Replaces range bounds and immediately sanitizes them.
451    ///
452    /// Reversed bounds swap, equal finite bounds try to expand max by `1.0`, and
453    /// any non-finite bound resets the domain to `0.0..=1.0`.
454    ///
455    /// # Examples
456    ///
457    /// ```
458    /// use ailloli_ui_widgets::controls::CircularProgress;
459    /// let progress = CircularProgress::new().range(0.0, 100.0).value(75.0);
460    /// let _ = progress;
461    /// ```
462    pub fn range(mut self, min: f32, max: f32) -> Self {
463        self.spec.min = min;
464        self.spec.max = max;
465        self.spec = self.spec.sanitized();
466        self
467    }
468
469    /// Replaces and sanitizes the complete numeric domain.
470    ///
471    /// # Examples
472    ///
473    /// ```
474    /// use ailloli_ui_core::ProgressSpec;
475    /// use ailloli_ui_widgets::controls::CircularProgress;
476    /// let progress = CircularProgress::new().progress_spec(ProgressSpec::new(10.0, 20.0));
477    /// let _ = progress;
478    /// ```
479    pub fn progress_spec(mut self, spec: ProgressSpec) -> Self {
480        self.spec = spec.sanitized();
481        self
482    }
483
484    /// Replaces complete resolved style without clamping its values.
485    ///
486    /// # Examples
487    ///
488    /// ```
489    /// use ailloli_ui_core::Theme;
490    /// use ailloli_ui_widgets::controls::{CircularProgress, ProgressSize, ProgressStyle};
491    /// let style = ProgressStyle::from_theme(Theme::dark(), ProgressSize::Large);
492    /// let progress = CircularProgress::new().progress_style(style);
493    /// let _ = progress;
494    /// ```
495    pub fn progress_style(mut self, style: ProgressStyle) -> Self {
496        self.style = style;
497        self
498    }
499
500    /// Replaces complete style with the default-theme built-in size.
501    ///
502    /// # Examples
503    ///
504    /// ```
505    /// use ailloli_ui_widgets::controls::{CircularProgress, ProgressSize};
506    /// let progress = CircularProgress::new().progress_size(ProgressSize::Compact);
507    /// let _ = progress;
508    /// ```
509    pub fn progress_size(mut self, size: ProgressSize) -> Self {
510        self.style = ProgressStyle::from_theme(Theme::default(), size);
511        self
512    }
513
514    /// Controls generated percentage visibility when no custom label exists.
515    ///
516    /// A custom label remains visible regardless of `show`; call this before
517    /// [`Self::label`] only to document intent, because `label` sets it true.
518    ///
519    /// # Examples
520    ///
521    /// ```
522    /// use ailloli_ui_widgets::controls::CircularProgress;
523    /// let progress = CircularProgress::new().value(0.5).show_label(true);
524    /// let _ = progress; // generated label is "50%"
525    /// ```
526    pub fn show_label(mut self, show: bool) -> Self {
527        self.show_label = show;
528        self
529    }
530
531    /// Sets static or reactive custom center text and enables label painting.
532    ///
533    /// Empty text remains a custom label and suppresses generated percentage.
534    /// There is no builder to return to `None`.
535    ///
536    /// # Examples
537    ///
538    /// ```
539    /// use ailloli_ui_widgets::controls::CircularProgress;
540    /// let progress = CircularProgress::new().value(3.0).range(0.0, 10.0).label("3 / 10");
541    /// let _ = progress;
542    /// ```
543    pub fn label(mut self, label: impl Into<Binding<String>>) -> Self {
544        self.label = Some(label.into());
545        self.show_label = true;
546        self
547    }
548}
549
550/// Retained non-interactive leaf for a linear bar.
551struct ProgressBarWidget {
552    /// Outer logical sizing policy.
553    layout: LayoutStyle,
554    /// Reactive progress value interpreted by `spec`.
555    value: Binding<f32>,
556    /// Reactive disabled-state source affecting opacity.
557    disabled: Binding<bool>,
558    /// Determinate/indeterminate range and normalization policy.
559    spec: ProgressSpec,
560    /// Linear progress visual variant.
561    variant: ProgressVariant,
562    /// Track/fill colors and logical-pixel geometry.
563    style: ProgressStyle,
564}
565
566/// Retained non-interactive leaf for a circular ring and optional label.
567struct CircularProgressWidget {
568    /// Outer logical sizing policy.
569    layout: LayoutStyle,
570    /// Reactive progress value interpreted by `spec`.
571    value: Binding<f32>,
572    /// Reactive disabled-state source affecting opacity.
573    disabled: Binding<bool>,
574    /// Determinate/indeterminate range and normalization policy.
575    spec: ProgressSpec,
576    /// Arc colors and logical-pixel geometry.
577    style: ProgressStyle,
578    /// Whether center text is painted.
579    show_label: bool,
580    /// Optional reactive center label overriding formatted progress.
581    label: Option<Binding<String>>,
582}
583
584impl<A: 'static> Widget<A> for ProgressBarWidget {
585    fn debug_name(&self) -> &'static str {
586        "ProgressBar"
587    }
588
589    fn layout(
590        &self,
591        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
592        _ctx: &mut LayoutCtx<'_>,
593        _children: &mut [LayoutChild],
594        constraints: Constraints,
595    ) -> LayoutResult {
596        progress_layout_result(self.style.bar_intrinsic_size(), self.layout, constraints)
597    }
598
599    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
600        let fraction = self.spec.fraction_for_value(self.value.read());
601        paint_progress_bar(
602            ctx,
603            bounds,
604            fraction,
605            self.variant,
606            self.disabled.read(),
607            &self.style,
608        );
609    }
610
611    fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
612    }
613
614    fn focus_policy(&self) -> FocusPolicy {
615        FocusPolicy::NotFocusable
616    }
617}
618
619impl<A: 'static> Widget<A> for CircularProgressWidget {
620    fn debug_name(&self) -> &'static str {
621        "CircularProgress"
622    }
623
624    fn layout(
625        &self,
626        _engine: &mut ailloli_ui_runtime::layout::LayoutEngine<'_, A>,
627        _ctx: &mut LayoutCtx<'_>,
628        _children: &mut [LayoutChild],
629        constraints: Constraints,
630    ) -> LayoutResult {
631        progress_layout_result(
632            self.style.circular_intrinsic_size(),
633            self.layout,
634            constraints,
635        )
636    }
637
638    fn paint(&self, ctx: &mut PaintCtx<'_>, bounds: Rect, _layout_result: &LayoutResult) {
639        let fraction = self.spec.fraction_for_value(self.value.read());
640        paint_circular_progress(
641            ctx,
642            bounds,
643            fraction,
644            self.disabled.read(),
645            &self.style,
646            self.show_label,
647            self.label.as_ref(),
648        );
649    }
650
651    fn event(&self, _ctx: &mut EventCtx<A>, _event: &Event, _bounds: Rect, _layout: &LayoutResult) {
652    }
653
654    fn focus_policy(&self) -> FocusPolicy {
655        FocusPolicy::NotFocusable
656    }
657}
658
659impl<A: 'static> IntoView<A> for ProgressBar {
660    fn into_view(self) -> View<A> {
661        finish_view_sized(
662            View::leaf(ProgressBarWidget {
663                layout: self.layout,
664                value: self.value,
665                disabled: self.disabled,
666                spec: self.spec,
667                variant: self.variant,
668                style: self.style,
669            }),
670            self.flex_item,
671            LayoutSizeHint::from_layout(self.layout),
672        )
673    }
674}
675
676impl<A: 'static> IntoView<A> for CircularProgress {
677    fn into_view(self) -> View<A> {
678        finish_view_sized(
679            View::leaf(CircularProgressWidget {
680                layout: self.layout,
681                value: self.value,
682                disabled: self.disabled,
683                spec: self.spec,
684                style: self.style,
685                show_label: self.show_label,
686                label: self.label,
687            }),
688            self.flex_item,
689            LayoutSizeHint::from_layout(self.layout),
690        )
691    }
692}
693
694/// Resolves a leaf layout with identical paint and visual bounds.
695fn progress_layout_result(
696    intrinsic: Size,
697    layout: LayoutStyle,
698    constraints: Constraints,
699) -> LayoutResult {
700    let size = apply_layout_size(intrinsic, layout, constraints);
701    let rect = Rect::new(0.0, 0.0, size.w, size.h);
702    LayoutResult {
703        size,
704        children: Vec::new(),
705        paint_bounds: rect,
706        visual_bounds: rect,
707        overlay_hit_bounds: Vec::new(),
708        clip: None,
709        is_window_root_clip: false,
710        artifact: None,
711    }
712}
713
714/// Paints track, active fill/optional stripes, then border.
715fn paint_progress_bar(
716    ctx: &mut PaintCtx<'_>,
717    bounds: Rect,
718    fraction: f32,
719    variant: ProgressVariant,
720    disabled: bool,
721    style: &ProgressStyle,
722) {
723    if bounds.w <= 0.0 || bounds.h <= 0.0 {
724        return;
725    }
726
727    let opacity = if disabled {
728        style.disabled_opacity
729    } else {
730        1.0
731    };
732    let radius = bounds.h * 0.5;
733    let track = apply_opacity(
734        if disabled {
735            style.disabled_track
736        } else {
737            style.track
738        },
739        opacity,
740    );
741    let fill = apply_opacity(
742        if disabled {
743            style.disabled_fill
744        } else {
745            style.fill
746        },
747        opacity,
748    );
749
750    ctx.push(DrawCmd::RRect(DrawRRect {
751        rect: bounds,
752        radius,
753        color: track,
754    }));
755
756    let active = Rect::new(
757        bounds.x,
758        bounds.y,
759        bounds.w * fraction.clamp(0.0, 1.0),
760        bounds.h,
761    );
762    if active.w > 0.0 {
763        ctx.push(DrawCmd::RRect(DrawRRect {
764            rect: active,
765            radius,
766            color: fill,
767        }));
768        if variant == ProgressVariant::Striped && !disabled {
769            paint_stripes(ctx, active, bounds.h, style);
770        }
771    }
772
773    let border = apply_border_opacity(style.border, opacity);
774    if border.is_visible() {
775        ctx.push(DrawCmd::Border(DrawBorder {
776            rect: bounds,
777            radius: Radius::uniform(radius),
778            border,
779        }));
780    }
781}
782
783/// Paints clipped repeating stripes with geometry derived from bar height.
784fn paint_stripes(ctx: &mut PaintCtx<'_>, active: Rect, height: f32, style: &ProgressStyle) {
785    let stripe_w = (height * 0.55).max(2.0);
786    let step = (height * 1.65).max(7.0);
787    let color = style.stripe;
788    ctx.with_clip(active, |ctx| {
789        let mut x = active.x - step;
790        while x < active.right() + step {
791            ctx.push(DrawCmd::Rect(DrawRect {
792                rect: Rect::new(x, active.y, stripe_w, active.h),
793                color,
794            }));
795            x += step;
796        }
797    });
798}
799
800/// Paints a centered ring and optional generated or custom label.
801fn paint_circular_progress(
802    ctx: &mut PaintCtx<'_>,
803    bounds: Rect,
804    fraction: f32,
805    disabled: bool,
806    style: &ProgressStyle,
807    show_label: bool,
808    label: Option<&Binding<String>>,
809) {
810    let side = bounds.w.min(bounds.h);
811    if side <= 0.0 {
812        return;
813    }
814
815    let rect = Rect::new(
816        bounds.x + (bounds.w - side) * 0.5,
817        bounds.y + (bounds.h - side) * 0.5,
818        side,
819        side,
820    );
821    let opacity = if disabled {
822        style.disabled_opacity
823    } else {
824        1.0
825    };
826    let track = apply_opacity(
827        if disabled {
828            style.disabled_track
829        } else {
830            style.track
831        },
832        opacity,
833    );
834    let fill = apply_opacity(
835        if disabled {
836            style.disabled_fill
837        } else {
838            style.fill
839        },
840        opacity,
841    );
842
843    ctx.push(DrawCmd::RingProgress(DrawRingProgress {
844        rect,
845        thickness: style.circular_thickness.min(side * 0.5).max(1.0),
846        fraction: fraction.clamp(0.0, 1.0),
847        track_color: track,
848        fill_color: fill,
849        start_angle: -std::f32::consts::FRAC_PI_2,
850    }));
851
852    if show_label || label.is_some() {
853        let text = label
854            .map(Binding::read)
855            .unwrap_or_else(|| format!("{:.0}%", fraction.clamp(0.0, 1.0) * 100.0));
856        let text_style = if disabled {
857            TextStyle {
858                color: apply_opacity(style.muted_text.color, opacity),
859                ..style.muted_text
860            }
861        } else {
862            style.text
863        };
864        paint_centered_text(ctx, rect, &text, text_style);
865    }
866}
867
868/// Paints one unwrapped line centered when a text system is available.
869fn paint_centered_text(ctx: &mut PaintCtx<'_>, rect: Rect, text: &str, style: TextStyle) {
870    let Some(ts) = ctx.text_system.as_deref_mut() else {
871        return;
872    };
873    let layout = ts.layout_cached(TextLayoutParams {
874        text,
875        style,
876        max_width: Some(rect.w.max(0.0)),
877        wrap_mode: WrapMode::NoWrap,
878    });
879    let baseline = layout
880        .lines
881        .first()
882        .map(|line| line.baseline_y)
883        .unwrap_or(0.0);
884    let x = rect.x + (rect.w - layout.metrics.width).max(0.0) * 0.5;
885    let y = rect.y + (rect.h - layout.metrics.height).max(0.0) * 0.5 + baseline;
886    ctx.push(DrawCmd::Text(DrawText {
887        pos: [x, y],
888        color: style.color,
889        decoration: ailloli_ui_core::TextDecoration::None,
890        layout,
891    }));
892}
893
894/// Multiplies and clamps color alpha to `0.0..=1.0`.
895fn apply_opacity(mut color: Color, opacity: f32) -> Color {
896    color.a = (color.a * opacity).clamp(0.0, 1.0);
897    color
898}
899
900/// Applies [`apply_opacity`] to all four border colors.
901fn apply_border_opacity(mut border: Border, opacity: f32) -> Border {
902    border.colors.left = apply_opacity(border.colors.left, opacity);
903    border.colors.top = apply_opacity(border.colors.top, opacity);
904    border.colors.right = apply_opacity(border.colors.right, opacity);
905    border.colors.bottom = apply_opacity(border.colors.bottom, opacity);
906    border
907}