hyprforge_ui/widgets/
ring.rs1use crate::theme::{self, surface};
5use iced::widget::canvas;
6use iced::{mouse, Element, Length, Point, Radians, Rectangle, Renderer, Theme};
7
8pub fn countdown_ring<'a, Message: 'a>(left: u32, total: u32, side: f32) -> Element<'a, Message> {
18 canvas(Ring { left, total })
19 .width(Length::Fixed(side))
20 .height(Length::Fixed(side))
21 .into()
22}
23
24pub fn remaining_fraction(left: u32, total: u32) -> f32 {
26 match total {
27 0 => 0.0,
28 t => (left as f32 / t as f32).clamp(0.0, 1.0),
29 }
30}
31
32struct Ring {
33 left: u32,
34 total: u32,
35}
36
37impl<Message> canvas::Program<Message, Theme, Renderer> for Ring {
38 type State = ();
39
40 fn draw(
41 &self,
42 _state: &Self::State,
43 renderer: &Renderer,
44 theme: &Theme,
45 bounds: Rectangle,
46 _cursor: mouse::Cursor,
47 ) -> Vec<canvas::Geometry> {
48 use std::f32::consts::PI;
49 let mut frame = canvas::Frame::new(renderer, bounds.size());
50 let side = bounds.width.min(bounds.height);
51 let width = (side * 0.08).max(2.0);
52 let centre = Point::new(bounds.width / 2.0, bounds.height / 2.0);
53 let radius = side / 2.0 - width;
54
55 let track = canvas::Path::circle(centre, radius);
56 frame.stroke(
57 &track,
58 canvas::Stroke::default().with_width(width).with_color(surface::card_border()),
59 );
60
61 let fraction = remaining_fraction(self.left, self.total);
62 if fraction > 0.0 {
63 let start = -PI / 2.0;
64 let arc = canvas::Path::new(|b| {
65 b.arc(canvas::path::Arc {
66 center: centre,
67 radius,
68 start_angle: Radians(start),
69 end_angle: Radians(start + 2.0 * PI * fraction),
70 });
71 });
72 frame.stroke(
73 &arc,
74 canvas::Stroke {
75 style: canvas::Style::Solid(theme.extended_palette().primary.base.color),
76 width,
77 line_cap: canvas::LineCap::Round,
78 ..canvas::Stroke::default()
79 },
80 );
81 }
82
83 frame.fill_text(canvas::Text {
84 content: self.left.to_string(),
85 position: centre,
86 color: theme::text(),
87 size: (side * 0.36).into(),
88 align_x: iced::widget::text::Alignment::Center,
89 align_y: iced::alignment::Vertical::Center,
90 ..canvas::Text::default()
91 });
92
93 vec![frame.into_geometry()]
94 }
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn the_ring_empties_as_the_countdown_runs() {
103 assert_eq!(remaining_fraction(10, 10), 1.0);
104 assert_eq!(remaining_fraction(5, 10), 0.5);
105 assert_eq!(remaining_fraction(0, 10), 0.0);
106 }
107
108 #[test]
112 fn a_ring_with_no_total_or_too_much_left_stays_a_ring() {
113 assert_eq!(remaining_fraction(3, 0), 0.0);
114 assert_eq!(remaining_fraction(12, 10), 1.0);
115 }
116}