1use crate::{
2 ControlAction, DialogRole, InputRoute, Node, Tumbler, TumblerItems, VecModel,
3 picker::{PickerSession, append_picker_dialog},
4};
5use std::fmt;
6
7#[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
154#[doc(hidden)]
155#[derive(Default)]
156pub struct TimePopupState(PickerSession<Time>);
157
158impl TimePopupState {
159 pub fn close(&self) {
160 self.0.close();
161 }
162
163 pub fn populate(&self, dialog: &mut Node, time: impl FnOnce() -> Time) {
164 self.try_populate(dialog, || Ok::<_, std::convert::Infallible>(time()))
165 .unwrap_or_else(|error| match error {});
166 }
167
168 pub fn try_populate<E>(
169 &self,
170 dialog: &mut Node,
171 time: impl FnOnce() -> Result<Time, E>,
172 ) -> Result<(), E> {
173 let Some(draft) = self.0.try_begin(dialog, || time().map(Time::normalized))? else {
174 return Ok(());
175 };
176 let mut picker = Node::new("TimePicker", None);
177 TimePickerOptions::from_node(dialog).populate(&mut picker, draft);
178 for wheel in &mut picker.children {
179 self.0.stamp(wheel);
180 }
181 append_picker_dialog(dialog, picker);
182 Ok(())
183 }
184
185 pub fn edit(
186 &self,
187 options: TimePickerOptions,
188 slot: usize,
189 node: &Node,
190 action: ControlAction,
191 ) -> bool {
192 let Some(next) = self
193 .0
194 .current(node)
195 .and_then(|time| options.select(time, slot, node, action))
196 else {
197 return false;
198 };
199 self.0.set(next);
200 true
201 }
202
203 pub fn try_finish_input<E>(
205 &self,
206 dialog: &Node,
207 role: DialogRole,
208 input: InputRoute<'_>,
209 options: impl FnOnce() -> Result<TimePickerOptions, E>,
210 ) -> Result<Option<Time>, E> {
211 self.0.try_finish_input(dialog, role, input, |draft| {
212 Ok((options()? == TimePickerOptions::from_node(dialog)).then_some(draft))
213 })
214 }
215
216 pub fn finish_input(
217 &self,
218 dialog: &Node,
219 role: DialogRole,
220 input: InputRoute<'_>,
221 options: impl FnOnce() -> TimePickerOptions,
222 ) -> Option<Time> {
223 self.try_finish_input(dialog, role, input, || {
224 Ok::<_, std::convert::Infallible>(options())
225 })
226 .unwrap_or_else(|error| match error {})
227 }
228
229 pub fn finish(&self, dialog: &Node) -> Option<Time> {
230 self.finish_with_role(dialog, DialogRole::Accept)
231 }
232
233 pub fn finish_with_role(&self, dialog: &Node, role: DialogRole) -> Option<Time> {
234 self.0.finish(dialog, role)
235 }
236}