Skip to main content

xrack_runtime/
time_picker.rs

1use crate::{
2    ControlAction, DialogRole, InputRoute, Node, Tumbler, TumblerItems, VecModel,
3    picker::{PickerSession, append_picker_dialog},
4};
5use std::fmt;
6
7/// A time of day with second precision.
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
9pub struct Time {
10    pub hour: i64,
11    pub minute: i64,
12    pub second: i64,
13}
14
15impl Time {
16    pub const MIN: Self = Self {
17        hour: 0,
18        minute: 0,
19        second: 0,
20    };
21    pub const MAX: Self = Self {
22        hour: 23,
23        minute: 59,
24        second: 59,
25    };
26
27    pub fn new(hour: i64, minute: i64, second: i64) -> Option<Self> {
28        let value = Self {
29            hour,
30            minute,
31            second,
32        };
33        (value == value.normalized()).then_some(value)
34    }
35
36    /// Parse an ASCII time of day, with optional seconds.
37    pub fn parse_iso(text: &str) -> Option<Self> {
38        let (hour, minute, second) = match text.as_bytes() {
39            [h1, h2, b':', m1, m2] => ((*h1, *h2), (*m1, *m2), (b'0', b'0')),
40            [h1, h2, b':', m1, m2, b':', s1, s2] => ((*h1, *h2), (*m1, *m2), (*s1, *s2)),
41            _ => return None,
42        };
43        let pair = |(left, right): (u8, u8)| {
44            (left.is_ascii_digit() && right.is_ascii_digit())
45                .then(|| i64::from(left - b'0') * 10 + i64::from(right - b'0'))
46        };
47        Self::new(pair(hour)?, pair(minute)?, pair(second)?)
48    }
49
50    pub fn format_iso(self, show_seconds: bool) -> String {
51        let time = self.normalized();
52        if show_seconds {
53            time.to_string()
54        } else {
55            format!("{:02}:{:02}", time.hour, time.minute)
56        }
57    }
58
59    pub fn in_range(self, minimum: Self, maximum: Self) -> bool {
60        self == self.normalized() && (minimum.normalized()..=maximum.normalized()).contains(&self)
61    }
62
63    pub fn normalized(self) -> Self {
64        Self {
65            hour: self.hour.clamp(0, 23),
66            minute: self.minute.clamp(0, 59),
67            second: self.second.clamp(0, 59),
68        }
69    }
70}
71
72impl fmt::Display for Time {
73    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
74        write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
75    }
76}
77
78thread_local! {
79    static HOURS_24: TumblerItems = numbers(0..24);
80    static HOURS_12: TumblerItems = numbers(std::iter::once(12).chain(1..12));
81    static MINUTES_SECONDS: TumblerItems = numbers(0..60);
82    static PERIODS: TumblerItems = TumblerItems::new(VecModel::from(vec!["AM".into(), "PM".into()]));
83}
84
85fn numbers(values: impl Iterator<Item = i64>) -> TumblerItems {
86    TumblerItems::new(VecModel::from(
87        values
88            .map(|value| format!("{value:02}"))
89            .collect::<Vec<_>>(),
90    ))
91}
92
93#[doc(hidden)]
94#[derive(Clone, Copy, PartialEq, Eq)]
95pub struct TimePickerOptions {
96    use_24_hours: bool,
97    show_seconds: bool,
98    minimum: Time,
99    maximum: Time,
100}
101
102impl TimePickerOptions {
103    pub fn new(use_24_hours: bool, show_seconds: bool) -> Self {
104        Self {
105            use_24_hours,
106            show_seconds,
107            minimum: Time::MIN,
108            maximum: Time::MAX,
109        }
110    }
111
112    pub fn with_bounds(mut self, minimum: Time, maximum: Time) -> Self {
113        self.minimum = minimum.normalized();
114        self.maximum = maximum.normalized();
115        self
116    }
117
118    fn allows(self, time: Time) -> bool {
119        time.in_range(self.minimum, self.maximum)
120    }
121
122    pub fn from_node(node: &Node) -> Self {
123        Self::new(
124            node.boolean("use-24-hour-format", true),
125            node.boolean("show-seconds", false),
126        )
127        .with_bounds(
128            node.time("minimum-time").unwrap_or(Time::MIN),
129            node.time("maximum-time").unwrap_or(Time::MAX),
130        )
131    }
132
133    fn wheel(self, time: Time, slot: usize) -> Option<(&'static str, TumblerItems, i64)> {
134        Some(match slot {
135            0 if self.use_24_hours => ("Hour", HOURS_24.with(Clone::clone), time.hour),
136            0 => ("Hour", HOURS_12.with(Clone::clone), time.hour % 12),
137            1 => ("Minute", MINUTES_SECONDS.with(Clone::clone), time.minute),
138            2 if self.show_seconds => ("Second", MINUTES_SECONDS.with(Clone::clone), time.second),
139            3 if !self.use_24_hours => ("AM/PM", PERIODS.with(Clone::clone), time.hour / 12),
140            _ => return None,
141        })
142    }
143
144    pub fn populate(self, picker: &mut Node, time: Time) {
145        let time = time.normalized();
146        for slot in 0..4 {
147            let wheel = if let Some((label, model, index)) = self.wheel(time, slot) {
148                let mut wheel = Node::new("Tumbler", None);
149                wheel.tumbler_items = Some(model);
150                wheel
151                    .properties
152                    .insert("accessible-name", label.to_owned().into());
153                wheel.properties.insert("current-index", index.into());
154                wheel
155            } else {
156                Node::hidden()
157            };
158            picker.children.push(wheel);
159        }
160    }
161
162    pub fn select(
163        self,
164        time: Time,
165        slot: usize,
166        node: &Node,
167        action: ControlAction,
168    ) -> Option<Time> {
169        let ControlAction::PickTumbler { index, row } = action else {
170            return None;
171        };
172        let time = time.normalized();
173        let (_, model, current) = self.wheel(time, slot)?;
174        let index_value = i64::try_from(index).ok()?;
175        if node.kind != "Tumbler"
176            || node.tumbler_items.as_ref() != Some(&model)
177            || node.int("current-index") != Some(current)
178            || Tumbler::from_node(node).row_key(index) != Some(row)
179            || index_value == current
180        {
181            return None;
182        }
183        Some(match slot {
184            0 => Time {
185                hour: index_value
186                    + if self.use_24_hours {
187                        0
188                    } else {
189                        time.hour / 12 * 12
190                    },
191                ..time
192            },
193            1 => Time {
194                minute: index_value,
195                ..time
196            },
197            2 => Time {
198                second: index_value,
199                ..time
200            },
201            3 => Time {
202                hour: time.hour % 12 + index_value * 12,
203                ..time
204            },
205            _ => unreachable!(),
206        })
207    }
208
209    /// Resolve a wheel selection before either backend writes the time.
210    pub fn try_select_input<E>(
211        node: &Node,
212        slot: usize,
213        action: ControlAction,
214        input: InputRoute<'_>,
215        options: impl FnOnce() -> Result<Self, E>,
216        time: impl FnOnce() -> Result<Option<Time>, E>,
217    ) -> Result<Option<Time>, E> {
218        let ControlAction::PickTumbler { index, row } = action else {
219            return Ok(None);
220        };
221        if node.kind != "Tumbler"
222            || Tumbler::from_node(node).row_key(index) != Some(row)
223            || !input.is_current()
224        {
225            return Ok(None);
226        }
227        crate::property::watch_reads(|reads| {
228            let options = options()?;
229            if reads.changed() || !input.is_current() {
230                return Ok(None);
231            }
232            let Some(time) = time()? else {
233                return Ok(None);
234            };
235            Ok(options
236                .select(time, slot, node, action)
237                .filter(|_| !reads.changed() && input.is_current()))
238        })
239    }
240
241    pub fn select_input(
242        node: &Node,
243        slot: usize,
244        action: ControlAction,
245        input: InputRoute<'_>,
246        options: impl FnOnce() -> Self,
247        time: impl FnOnce() -> Time,
248    ) -> Option<Time> {
249        Self::try_select_input(
250            node,
251            slot,
252            action,
253            input,
254            || Ok::<_, std::convert::Infallible>(options()),
255            || Ok(Some(time())),
256        )
257        .unwrap_or_else(|error| match error {})
258    }
259}
260
261#[doc(hidden)]
262#[derive(Default)]
263pub struct TimePopupState(PickerSession<Time>);
264
265impl TimePopupState {
266    #[doc(hidden)]
267    pub fn accepts_input(&self, node: &Node, input: InputRoute<'_>) -> bool {
268        self.0.accepts_input(node, input)
269    }
270
271    pub fn close(&self) {
272        self.0.close();
273    }
274
275    pub fn populate(&self, dialog: &mut Node, time: impl FnOnce() -> Time) {
276        self.try_populate(dialog, || Ok::<_, std::convert::Infallible>(time()))
277            .unwrap_or_else(|error| match error {});
278    }
279
280    pub fn try_populate<E>(
281        &self,
282        dialog: &mut Node,
283        time: impl FnOnce() -> Result<Time, E>,
284    ) -> Result<(), E> {
285        let Some(draft) = self.0.try_begin(dialog, || time().map(Time::normalized))? else {
286            return Ok(());
287        };
288        let mut picker = Node::new("TimePicker", None);
289        let options = TimePickerOptions::from_node(dialog);
290        options.populate(&mut picker, draft);
291        for wheel in &mut picker.children {
292            self.0.stamp(wheel);
293        }
294        append_picker_dialog(dialog, picker, options.allows(draft));
295        Ok(())
296    }
297
298    pub fn edit(
299        &self,
300        options: TimePickerOptions,
301        slot: usize,
302        node: &Node,
303        action: ControlAction,
304    ) -> bool {
305        let Some(next) = self
306            .0
307            .current(node)
308            .and_then(|time| options.select(time, slot, node, action))
309        else {
310            return false;
311        };
312        self.0.set(next);
313        true
314    }
315
316    pub fn try_edit_input<E>(
317        &self,
318        node: &Node,
319        slot: usize,
320        action: ControlAction,
321        input: InputRoute<'_>,
322        options: impl FnOnce() -> Result<TimePickerOptions, E>,
323    ) -> Result<bool, E> {
324        if !self.accepts_input(node, input) {
325            return Ok(false);
326        }
327        let Some(next) =
328            TimePickerOptions::try_select_input(node, slot, action, input, options, || {
329                Ok(self.0.current(node))
330            })?
331        else {
332            return Ok(false);
333        };
334        self.0.set(next);
335        Ok(true)
336    }
337
338    pub fn edit_input(
339        &self,
340        node: &Node,
341        slot: usize,
342        action: ControlAction,
343        input: InputRoute<'_>,
344        options: impl FnOnce() -> TimePickerOptions,
345    ) -> bool {
346        self.try_edit_input(node, slot, action, input, || {
347            Ok::<_, std::convert::Infallible>(options())
348        })
349        .unwrap_or_else(|error| match error {})
350    }
351
352    /// Confirm only the draft displayed with the current options.
353    pub fn try_finish_input<E>(
354        &self,
355        dialog: &Node,
356        role: DialogRole,
357        input: InputRoute<'_>,
358        options: impl FnOnce() -> Result<TimePickerOptions, E>,
359    ) -> Result<Option<Time>, E> {
360        self.0.try_finish_input(dialog, role, input, |draft| {
361            let options = options()?;
362            Ok(
363                (options == TimePickerOptions::from_node(dialog) && options.allows(draft))
364                    .then_some(draft),
365            )
366        })
367    }
368
369    pub fn finish_input(
370        &self,
371        dialog: &Node,
372        role: DialogRole,
373        input: InputRoute<'_>,
374        options: impl FnOnce() -> TimePickerOptions,
375    ) -> Option<Time> {
376        self.try_finish_input(dialog, role, input, || {
377            Ok::<_, std::convert::Infallible>(options())
378        })
379        .unwrap_or_else(|error| match error {})
380    }
381
382    pub fn finish(&self, dialog: &Node) -> Option<Time> {
383        self.finish_with_role(dialog, DialogRole::Accept)
384    }
385
386    pub fn finish_with_role(&self, dialog: &Node, role: DialogRole) -> Option<Time> {
387        if role == DialogRole::Accept
388            && !TimePickerOptions::from_node(dialog).allows(self.0.current(dialog)?)
389        {
390            return None;
391        }
392        self.0.finish(dialog, role)
393    }
394}
395
396#[cfg(test)]
397mod tests {
398    use super::*;
399
400    #[test]
401    fn parses_and_formats_strict_iso_times() {
402        assert_eq!(Time::parse_iso("00:00"), Some(Time::MIN));
403        assert_eq!(Time::parse_iso("23:59:59"), Some(Time::MAX));
404        assert_eq!(Time::parse_iso("13:07"), Time::new(13, 7, 0));
405        let time = Time::new(1, 2, 3).unwrap();
406        assert_eq!(time.format_iso(false), "01:02");
407        assert_eq!(time.format_iso(true), "01:02:03");
408        for invalid in [
409            "24:00",
410            "12:60",
411            "23:59:60",
412            "1:23",
413            "01:2",
414            "01:23:",
415            "01:23Z",
416            " 01:23",
417            "12:34",
418            "01:2é",
419        ] {
420            assert!(Time::parse_iso(invalid).is_none(), "{invalid}");
421        }
422        assert!(time.in_range(Time::MIN, time));
423        assert!(!time.in_range(Time::MAX, Time::MIN));
424    }
425
426    #[test]
427    fn time_popup_keeps_an_out_of_range_draft_and_disables_confirmation() {
428        let draft = Time::new(15, 30, 12).unwrap();
429        let earlier = Time::new(15, 0, 0).unwrap();
430        let state = TimePopupState::default();
431        let dialog = |maximum: Time| {
432            let mut node = Node::new("TimePickerPopup", None);
433            node.properties.insert("open", true.into());
434            node.properties.insert("maximum-time", maximum.into());
435            node
436        };
437        let mut disabled = dialog(earlier);
438        state.populate(&mut disabled, || draft);
439        assert!(!disabled.children[1].children[1].boolean("enabled", true));
440        assert_eq!(state.finish(&disabled), None);
441        let mut enabled = dialog(draft);
442        state.populate(&mut enabled, || Time::MIN);
443        assert!(enabled.children[1].children[1].boolean("enabled", true));
444        assert_eq!(state.finish(&enabled), Some(draft));
445    }
446}