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 fn new(hour: i64, minute: i64, second: i64) -> Option<Self> {
17        let value = Self {
18            hour,
19            minute,
20            second,
21        };
22        (value == value.normalized()).then_some(value)
23    }
24
25    pub fn normalized(self) -> Self {
26        Self {
27            hour: self.hour.clamp(0, 23),
28            minute: self.minute.clamp(0, 59),
29            second: self.second.clamp(0, 59),
30        }
31    }
32}
33
34impl fmt::Display for Time {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        write!(f, "{:02}:{:02}:{:02}", self.hour, self.minute, self.second)
37    }
38}
39
40thread_local! {
41    static HOURS_24: TumblerItems = numbers(0..24);
42    static HOURS_12: TumblerItems = numbers(std::iter::once(12).chain(1..12));
43    static MINUTES_SECONDS: TumblerItems = numbers(0..60);
44    static PERIODS: TumblerItems = TumblerItems::new(VecModel::from(vec!["AM".into(), "PM".into()]));
45}
46
47fn numbers(values: impl Iterator<Item = i64>) -> TumblerItems {
48    TumblerItems::new(VecModel::from(
49        values
50            .map(|value| format!("{value:02}"))
51            .collect::<Vec<_>>(),
52    ))
53}
54
55#[doc(hidden)]
56#[derive(Clone, Copy, PartialEq, Eq)]
57pub struct TimePickerOptions {
58    use_24_hours: bool,
59    show_seconds: bool,
60}
61
62impl TimePickerOptions {
63    pub fn new(use_24_hours: bool, show_seconds: bool) -> Self {
64        Self {
65            use_24_hours,
66            show_seconds,
67        }
68    }
69
70    pub fn from_node(node: &Node) -> Self {
71        Self::new(
72            node.boolean("use-24-hour-format", true),
73            node.boolean("show-seconds", false),
74        )
75    }
76
77    fn wheel(self, time: Time, slot: usize) -> Option<(&'static str, TumblerItems, i64)> {
78        Some(match slot {
79            0 if self.use_24_hours => ("Hour", HOURS_24.with(Clone::clone), time.hour),
80            0 => ("Hour", HOURS_12.with(Clone::clone), time.hour % 12),
81            1 => ("Minute", MINUTES_SECONDS.with(Clone::clone), time.minute),
82            2 if self.show_seconds => ("Second", MINUTES_SECONDS.with(Clone::clone), time.second),
83            3 if !self.use_24_hours => ("AM/PM", PERIODS.with(Clone::clone), time.hour / 12),
84            _ => return None,
85        })
86    }
87
88    pub fn populate(self, picker: &mut Node, time: Time) {
89        let time = time.normalized();
90        for slot in 0..4 {
91            let wheel = if let Some((label, model, index)) = self.wheel(time, slot) {
92                let mut wheel = Node::new("Tumbler", None);
93                wheel.tumbler_items = Some(model);
94                wheel
95                    .properties
96                    .insert("accessible-name", label.to_owned().into());
97                wheel.properties.insert("current-index", index.into());
98                wheel
99            } else {
100                Node::hidden()
101            };
102            picker.children.push(wheel);
103        }
104    }
105
106    pub fn select(
107        self,
108        time: Time,
109        slot: usize,
110        node: &Node,
111        action: ControlAction,
112    ) -> Option<Time> {
113        let ControlAction::PickTumbler { index, row } = action else {
114            return None;
115        };
116        let time = time.normalized();
117        let (_, model, current) = self.wheel(time, slot)?;
118        let index_value = i64::try_from(index).ok()?;
119        if node.kind != "Tumbler"
120            || node.tumbler_items.as_ref() != Some(&model)
121            || node.int("current-index") != Some(current)
122            || Tumbler::from_node(node).row_key(index) != Some(row)
123            || index_value == current
124        {
125            return None;
126        }
127        Some(match slot {
128            0 => Time {
129                hour: index_value
130                    + if self.use_24_hours {
131                        0
132                    } else {
133                        time.hour / 12 * 12
134                    },
135                ..time
136            },
137            1 => Time {
138                minute: index_value,
139                ..time
140            },
141            2 => Time {
142                second: index_value,
143                ..time
144            },
145            3 => Time {
146                hour: time.hour % 12 + index_value * 12,
147                ..time
148            },
149            _ => unreachable!(),
150        })
151    }
152
153    /// Resolve a wheel selection before either backend writes the time.
154    pub fn try_select_input<E>(
155        node: &Node,
156        slot: usize,
157        action: ControlAction,
158        input: InputRoute<'_>,
159        options: impl FnOnce() -> Result<Self, E>,
160        time: impl FnOnce() -> Result<Option<Time>, E>,
161    ) -> Result<Option<Time>, E> {
162        let ControlAction::PickTumbler { index, row } = action else {
163            return Ok(None);
164        };
165        if node.kind != "Tumbler"
166            || Tumbler::from_node(node).row_key(index) != Some(row)
167            || !input.is_current()
168        {
169            return Ok(None);
170        }
171        crate::property::watch_reads(|reads| {
172            let options = options()?;
173            if reads.changed() || !input.is_current() {
174                return Ok(None);
175            }
176            let Some(time) = time()? else {
177                return Ok(None);
178            };
179            Ok(options
180                .select(time, slot, node, action)
181                .filter(|_| !reads.changed() && input.is_current()))
182        })
183    }
184
185    pub fn select_input(
186        node: &Node,
187        slot: usize,
188        action: ControlAction,
189        input: InputRoute<'_>,
190        options: impl FnOnce() -> Self,
191        time: impl FnOnce() -> Time,
192    ) -> Option<Time> {
193        Self::try_select_input(
194            node,
195            slot,
196            action,
197            input,
198            || Ok::<_, std::convert::Infallible>(options()),
199            || Ok(Some(time())),
200        )
201        .unwrap_or_else(|error| match error {})
202    }
203}
204
205#[doc(hidden)]
206#[derive(Default)]
207pub struct TimePopupState(PickerSession<Time>);
208
209impl TimePopupState {
210    #[doc(hidden)]
211    pub fn accepts_input(&self, node: &Node, input: InputRoute<'_>) -> bool {
212        self.0.accepts_input(node, input)
213    }
214
215    pub fn close(&self) {
216        self.0.close();
217    }
218
219    pub fn populate(&self, dialog: &mut Node, time: impl FnOnce() -> Time) {
220        self.try_populate(dialog, || Ok::<_, std::convert::Infallible>(time()))
221            .unwrap_or_else(|error| match error {});
222    }
223
224    pub fn try_populate<E>(
225        &self,
226        dialog: &mut Node,
227        time: impl FnOnce() -> Result<Time, E>,
228    ) -> Result<(), E> {
229        let Some(draft) = self.0.try_begin(dialog, || time().map(Time::normalized))? else {
230            return Ok(());
231        };
232        let mut picker = Node::new("TimePicker", None);
233        TimePickerOptions::from_node(dialog).populate(&mut picker, draft);
234        for wheel in &mut picker.children {
235            self.0.stamp(wheel);
236        }
237        append_picker_dialog(dialog, picker);
238        Ok(())
239    }
240
241    pub fn edit(
242        &self,
243        options: TimePickerOptions,
244        slot: usize,
245        node: &Node,
246        action: ControlAction,
247    ) -> bool {
248        let Some(next) = self
249            .0
250            .current(node)
251            .and_then(|time| options.select(time, slot, node, action))
252        else {
253            return false;
254        };
255        self.0.set(next);
256        true
257    }
258
259    pub fn try_edit_input<E>(
260        &self,
261        node: &Node,
262        slot: usize,
263        action: ControlAction,
264        input: InputRoute<'_>,
265        options: impl FnOnce() -> Result<TimePickerOptions, E>,
266    ) -> Result<bool, E> {
267        if !self.accepts_input(node, input) {
268            return Ok(false);
269        }
270        let Some(next) =
271            TimePickerOptions::try_select_input(node, slot, action, input, options, || {
272                Ok(self.0.current(node))
273            })?
274        else {
275            return Ok(false);
276        };
277        self.0.set(next);
278        Ok(true)
279    }
280
281    pub fn edit_input(
282        &self,
283        node: &Node,
284        slot: usize,
285        action: ControlAction,
286        input: InputRoute<'_>,
287        options: impl FnOnce() -> TimePickerOptions,
288    ) -> bool {
289        self.try_edit_input(node, slot, action, input, || {
290            Ok::<_, std::convert::Infallible>(options())
291        })
292        .unwrap_or_else(|error| match error {})
293    }
294
295    /// Confirm only the draft displayed with the current options.
296    pub fn try_finish_input<E>(
297        &self,
298        dialog: &Node,
299        role: DialogRole,
300        input: InputRoute<'_>,
301        options: impl FnOnce() -> Result<TimePickerOptions, E>,
302    ) -> Result<Option<Time>, E> {
303        self.0.try_finish_input(dialog, role, input, |draft| {
304            Ok((options()? == TimePickerOptions::from_node(dialog)).then_some(draft))
305        })
306    }
307
308    pub fn finish_input(
309        &self,
310        dialog: &Node,
311        role: DialogRole,
312        input: InputRoute<'_>,
313        options: impl FnOnce() -> TimePickerOptions,
314    ) -> Option<Time> {
315        self.try_finish_input(dialog, role, input, || {
316            Ok::<_, std::convert::Infallible>(options())
317        })
318        .unwrap_or_else(|error| match error {})
319    }
320
321    pub fn finish(&self, dialog: &Node) -> Option<Time> {
322        self.finish_with_role(dialog, DialogRole::Accept)
323    }
324
325    pub fn finish_with_role(&self, dialog: &Node, role: DialogRole) -> Option<Time> {
326        self.0.finish(dialog, role)
327    }
328}