1use crate::{DecimalSpinRange, Node, SpinDecimal};
2use std::sync::{
3 Arc,
4 atomic::{AtomicU64, Ordering},
5};
6
7#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9pub struct ActionKey(u64);
10
11impl Default for ActionKey {
12 fn default() -> Self {
13 static NEXT_ACTION: AtomicU64 = AtomicU64::new(1);
14 let id = NEXT_ACTION
15 .try_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
16 next.checked_add(1)
17 })
18 .expect("Action keys exhausted");
19 Self(id)
20 }
21}
22
23#[derive(Clone, Copy, Debug, PartialEq, Eq)]
24pub enum SpinAction {
25 Increase,
26 Decrease,
27 Step(i64),
28 Minimum,
29 Maximum,
30 Commit(i64),
31 CommitIfCurrent {
32 original: i64,
33 value: i64,
34 },
35 CommitDecimal(SpinDecimal),
36 CommitDecimalIfCurrent {
37 original: Option<SpinDecimal>,
38 value: SpinDecimal,
39 },
40}
41
42#[derive(Clone, Copy, Debug, PartialEq, Eq)]
43pub enum ControlAction {
44 Spin(SpinAction),
45 Calendar(crate::CalendarAction),
46 Select(usize),
47 ActivateRadioOption,
48 PickTumbler {
49 index: usize,
50 row: crate::RowKey,
51 },
52 TableSelection(crate::TableSelectionAction),
53 Tree(crate::TreeAction),
54 Dialog(DialogRole),
55 DialogCommand(DialogCommand),
56 Drawer(bool),
57 Popup(bool),
58 SwipeDelegate(SwipeSide),
59 DelayButton(bool),
60 StackBack {
61 revision: u64,
62 },
63 ActivateMenuItem,
64 TextCommand(crate::TextCommand),
65 ActivateTextLink(usize),
66 ActivateAction,
67 ActivateShortcut,
68 AmbiguousShortcut,
69 AcceptComboText,
70 SubmitSearch,
71 ClearSearch,
72 SortColumn(usize),
73 ResizeColumn {
74 column: usize,
75 width: u32,
76 },
77 ResizeRow {
78 row: usize,
79 key: crate::RowKey,
80 height: u32,
81 },
82 MoveColumn {
83 from: usize,
84 to: usize,
85 },
86 MoveRow {
87 from: usize,
88 to: usize,
89 row: crate::RowKey,
90 stamp: (u64, u64),
91 },
92}
93
94pub fn is_modal_overlay(kind: &str) -> bool {
95 matches!(kind, "Dialog" | "Drawer")
96}
97
98pub fn is_window_overlay(kind: &str) -> bool {
99 is_modal_overlay(kind) || kind == "PopupWindow"
100}
101
102#[doc(hidden)]
103pub fn is_pane(kind: &str) -> bool {
104 matches!(kind, "Pane" | "ControlFrame")
105}
106
107#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
108pub enum PopupPlacement {
109 #[default]
110 Below,
111 Above,
112 Left,
113 Right,
114 Offset,
115}
116
117#[derive(Clone, Copy, Debug, PartialEq, Eq)]
118pub struct TableSort {
119 pub column: usize,
120 pub descending: bool,
121}
122
123#[derive(Clone, Debug, Default, PartialEq, Eq)]
125pub struct TableColumnOrder(Option<Arc<ColumnPermutation>>);
126
127#[derive(Debug, PartialEq, Eq)]
128struct ColumnPermutation {
129 columns: Vec<usize>,
130 positions: Vec<usize>,
131}
132
133impl TableColumnOrder {
134 pub fn as_slice(&self, count: usize) -> Option<&[usize]> {
135 self.0
136 .as_deref()
137 .filter(|order| order.columns.len() == count)
138 .map(|order| order.columns.as_slice())
139 }
140
141 pub fn iter(&self, count: usize) -> impl DoubleEndedIterator<Item = usize> + ExactSizeIterator {
142 let order = self.as_slice(count);
143 (0..count).map(move |visual| order.map_or(visual, |order| order[visual]))
144 }
145
146 pub fn visual_index(&self, count: usize, column: usize) -> Option<usize> {
147 if let Some(order) = self
148 .0
149 .as_deref()
150 .filter(|order| order.columns.len() == count)
151 {
152 order.positions.get(column).copied()
153 } else {
154 (column < count).then_some(column)
155 }
156 }
157
158 #[doc(hidden)]
159 pub fn moved(&self, count: usize, from: usize, to: usize) -> Option<(usize, Self)> {
160 if from >= count || to >= count || from == to {
161 return None;
162 }
163 let mut order: Vec<_> = self.iter(count).collect();
164 let column = order.remove(from);
165 order.insert(to, column);
166 let reordered = order.iter().copied().ne(0..count);
167 Some((
168 column,
169 Self(reordered.then(|| {
170 let mut positions = vec![0; count];
171 for (visual, &logical) in order.iter().enumerate() {
172 positions[logical] = visual;
173 }
174 Arc::new(ColumnPermutation {
175 columns: order,
176 positions,
177 })
178 })),
179 ))
180 }
181}
182
183#[derive(Clone, Debug, PartialEq)]
184pub struct TableHeader {
185 pub columns: Vec<Node>,
186 pub sort: Option<TableSort>,
187 pub column_widths: Vec<Option<u32>>,
188}
189
190pub fn resizable_table_column(table: &Node, column: usize) -> Option<&Node> {
191 let definition = table.table_header.as_ref()?.columns.get(column)?;
192 (table.boolean("resizable-columns", false) && definition.boolean("resizable", true))
193 .then_some(definition)
194}
195
196impl TableHeader {
197 pub fn next_sort(&self, column: usize) -> Option<TableSort> {
198 let definition = self.columns.get(column)?;
199 definition.boolean("sortable", true).then_some(TableSort {
200 column,
201 descending: self
202 .sort
203 .is_some_and(|sort| sort.column == column && !sort.descending),
204 })
205 }
206}
207
208#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
209pub enum DialogRole {
210 #[default]
211 Accept,
212 Reject,
213}
214
215#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
216pub enum SwipeSide {
217 #[default]
218 Closed,
219 Left,
220 Right,
221}
222
223impl SwipeSide {
224 pub fn panel(self) -> Option<&'static str> {
225 match self {
226 Self::Closed => None,
227 Self::Left => Some("SwipeLeft"),
228 Self::Right => Some("SwipeRight"),
229 }
230 }
231}
232
233#[derive(Clone, Copy, Debug, PartialEq, Eq)]
234pub enum DialogCommand {
235 Apply,
236 Reset,
237 Help,
238 Discard,
239}
240
241#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
242pub enum StandardButtonKind {
243 #[default]
244 Ok,
245 Open,
246 Save,
247 SaveAll,
248 Cancel,
249 Close,
250 Apply,
251 Reset,
252 RestoreDefaults,
253 Help,
254 Yes,
255 YesToAll,
256 No,
257 NoToAll,
258 Abort,
259 Retry,
260 Ignore,
261 Discard,
262}
263
264impl StandardButtonKind {
265 pub fn label(self) -> &'static str {
266 match self {
267 Self::Ok => "OK",
268 Self::Open => "Open",
269 Self::Save => "Save",
270 Self::SaveAll => "Save All",
271 Self::Cancel => "Cancel",
272 Self::Close => "Close",
273 Self::Apply => "Apply",
274 Self::Reset => "Reset",
275 Self::RestoreDefaults => "Restore Defaults",
276 Self::Help => "Help",
277 Self::Yes => "Yes",
278 Self::YesToAll => "Yes to All",
279 Self::No => "No",
280 Self::NoToAll => "No to All",
281 Self::Abort => "Abort",
282 Self::Retry => "Retry",
283 Self::Ignore => "Ignore",
284 Self::Discard => "Discard",
285 }
286 }
287
288 fn dialog_action(self) -> ControlAction {
289 match self {
290 Self::Ok
291 | Self::Open
292 | Self::Save
293 | Self::SaveAll
294 | Self::Yes
295 | Self::YesToAll
296 | Self::Retry
297 | Self::Ignore => ControlAction::Dialog(DialogRole::Accept),
298 Self::Cancel | Self::Close | Self::No | Self::NoToAll | Self::Abort => {
299 ControlAction::Dialog(DialogRole::Reject)
300 }
301 Self::Apply => ControlAction::DialogCommand(DialogCommand::Apply),
302 Self::Reset | Self::RestoreDefaults => {
303 ControlAction::DialogCommand(DialogCommand::Reset)
304 }
305 Self::Help => ControlAction::DialogCommand(DialogCommand::Help),
306 Self::Discard => ControlAction::DialogCommand(DialogCommand::Discard),
307 }
308 }
309}
310
311pub fn dialog_button_action(node: &Node) -> Option<ControlAction> {
312 if node.kind == "DialogButton" {
313 return Some(ControlAction::Dialog(node.dialog_role()));
314 }
315 node.standard_button_kind()
316 .map(StandardButtonKind::dialog_action)
317}
318
319pub fn is_button(kind: &str) -> bool {
320 matches!(
321 kind,
322 "Button" | "ToolButton" | "RoundButton" | "DialogButton" | "DelayButton"
323 )
324}
325
326pub fn delay_millis(node: &Node) -> u64 {
327 node.int("delay").unwrap_or(3_000).clamp(0, 60_000) as u64
328}
329
330pub fn button_text(node: &Node) -> &str {
331 node.text("text").unwrap_or_else(|| {
332 if let Some(kind) = node.standard_button_kind() {
333 return kind.label();
334 }
335 match (node.kind, node.dialog_role()) {
336 ("DialogButton", DialogRole::Accept) => "OK",
337 ("DialogButton", DialogRole::Reject) => "Cancel",
338 _ => "",
339 }
340 })
341}
342
343pub struct SpinRange {
344 min: i64,
345 max: i64,
346 value: i64,
347 original: Option<i64>,
348 step: i64,
349 wrap: bool,
350}
351
352impl SpinRange {
353 pub fn from_node(node: &Node) -> Self {
354 let min = node.int("minimum").unwrap_or(0);
355 let max = node.int("maximum").unwrap_or(100).max(min);
356 let original = node.int("value");
357 Self {
358 min,
359 max,
360 value: original.unwrap_or(min).clamp(min, max),
361 original,
362 step: node.int("step-size").unwrap_or(1).max(0),
363 wrap: node.boolean("wrap", false),
364 }
365 }
366
367 pub fn value(&self) -> i64 {
368 self.value
369 }
370
371 pub fn apply(&self, action: SpinAction) -> Option<i64> {
372 let next = match action {
373 SpinAction::Increase
374 if self.wrap
375 && self
376 .value
377 .checked_add(self.step)
378 .is_none_or(|value| value > self.max) =>
379 {
380 self.min
381 }
382 SpinAction::Decrease
383 if self.wrap
384 && self
385 .value
386 .checked_sub(self.step)
387 .is_none_or(|value| value < self.min) =>
388 {
389 self.max
390 }
391 SpinAction::Increase => self.value.saturating_add(self.step),
392 SpinAction::Decrease => self.value.saturating_sub(self.step),
393 SpinAction::Step(steps) => {
394 let next = i128::from(self.value) + i128::from(self.step) * i128::from(steps);
395 let min = i128::from(self.min);
396 let max = i128::from(self.max);
397 let step = i128::from(self.step);
398 let value = i128::from(self.value);
399 if self.wrap && next > max {
400 let remaining = i128::from(steps) - (max - value) / step - 1;
401 (min + remaining % ((max - min) / step + 1) * step) as i64
402 } else if self.wrap && next < min {
403 let remaining = -i128::from(steps) - (value - min) / step - 1;
404 (max - remaining % ((max - min) / step + 1) * step) as i64
405 } else {
406 next.clamp(min, max) as i64
407 }
408 }
409 SpinAction::Minimum => self.min,
410 SpinAction::Maximum => self.max,
411 SpinAction::Commit(value) => value,
412 SpinAction::CommitIfCurrent { original, value } if self.original == Some(original) => {
413 value
414 }
415 SpinAction::CommitIfCurrent { .. } => return None,
416 SpinAction::CommitDecimal(_) | SpinAction::CommitDecimalIfCurrent { .. } => {
417 return None;
418 }
419 }
420 .clamp(self.min, self.max);
421 (next != self.value).then_some(next)
422 }
423}
424
425pub fn spin_value_after(node: &Node, action: SpinAction) -> Option<i64> {
426 if node.boolean("read-only", false)
427 || matches!(
428 action,
429 SpinAction::Commit(_) | SpinAction::CommitIfCurrent { .. }
430 ) && !spin_editable(node)
431 {
432 return None;
433 }
434 SpinRange::from_node(node).apply(action)
435}
436
437pub fn is_spin_box(kind: &str) -> bool {
438 matches!(kind, "SpinBox" | "DoubleSpinBox")
439}
440
441pub fn spin_editable(node: &Node) -> bool {
442 is_spin_box(node.kind) && node.boolean("editable", true) && !node.boolean("read-only", false)
443}
444
445pub fn spin_text(node: &Node) -> String {
446 if node.kind == "DoubleSpinBox" {
447 DecimalSpinRange::from_node(node).display()
448 } else {
449 SpinRange::from_node(node).value().to_string()
450 }
451}
452
453pub fn combo_editable(node: &Node) -> bool {
454 node.kind == "ComboBox" && node.boolean("editable", false)
455}
456
457pub fn text_input_value(node: &Node) -> &str {
458 if combo_editable(node) {
459 node.text("edit-text")
460 .unwrap_or_else(|| crate::combo_text(node))
461 } else {
462 node.text("text").unwrap_or("")
463 }
464}
465
466pub fn search_suggestions(node: &Node) -> &[String] {
468 let text = text_input_value(node);
469 if node.kind != "SearchField"
470 || node.boolean("read-only", false)
471 || text.is_empty()
472 || node
473 .text("suggestions-for")
474 .is_some_and(|query| query != text)
475 {
476 &[]
477 } else {
478 node.strings("suggestions")
479 }
480}
481
482pub fn search_suggestion(node: &Node, index: usize) -> Option<&str> {
483 let value = search_suggestions(node).get(index)?;
484 (!value.is_empty() && !value.chars().any(char::is_control)).then_some(value.as_str())
485}
486
487pub fn page_indicator_count(node: &Node) -> usize {
488 usize::try_from(node.int("count").unwrap_or(0).max(0)).unwrap_or(usize::MAX)
489}
490
491pub fn page_indicator_index(node: &Node) -> Option<usize> {
492 let index = usize::try_from(node.int("current-index").unwrap_or(0)).ok()?;
493 (index < page_indicator_count(node)).then_some(index)
494}
495
496pub fn group_item(node: &Node, index: usize) -> Option<&Node> {
498 let expected = match node.kind {
499 "RadioGroup" => "RadioButton",
500 "TabWidget" => "Tab",
501 "TabBar" => "TabButton",
502 "SwipeView" => "SwipePage",
503 _ => return None,
504 };
505 node.children.get(index).filter(|item| {
506 item.kind == expected && item.boolean("visible", true) && item.boolean("enabled", true)
507 })
508}
509
510pub fn group_index(node: &Node) -> Option<usize> {
511 if matches!(node.kind, "SwipeView" | "TabBar") {
512 return resolve_swipe_index(
513 node.int("current-index"),
514 (0..node.children.len()).map(|index| group_item(node, index).is_some()),
515 );
516 }
517 if node.kind == "RadioGroup"
518 && let Some(value) = node.text("current-value")
519 {
520 return node.children.iter().enumerate().find_map(|(index, _)| {
521 group_item(node, index)
522 .filter(|item| crate::radio_value(item) == value)
523 .map(|_| index)
524 });
525 }
526 let default = if node.kind == "RadioGroup" { -1 } else { 0 };
527 let index = usize::try_from(node.int("current-index").unwrap_or(default)).ok()?;
528 group_item(node, index).map(|_| index)
529}
530
531#[doc(hidden)]
533pub fn resolve_swipe_index(
534 requested: Option<i64>,
535 available: impl IntoIterator<Item = bool>,
536) -> Option<usize> {
537 let requested = requested.and_then(|index| usize::try_from(index).ok());
538 let mut first = None;
539 for (index, available) in available.into_iter().enumerate() {
540 if available {
541 if requested == Some(index) {
542 return Some(index);
543 }
544 first.get_or_insert(index);
545 }
546 }
547 first
548}
549
550#[cfg(test)]
551mod tests {
552 use super::*;
553
554 #[test]
555 fn integer_steps_preserve_precision_and_handle_overflow() {
556 let mut node = Node::new("SpinBox", None);
557 node.properties.insert("value", (i64::MAX - 4).into());
558 node.properties.insert("maximum", i64::MAX.into());
559 node.properties.insert("step-size", 3_i64.into());
560 assert_eq!(
561 SpinRange::from_node(&node).apply(SpinAction::Increase),
562 Some(i64::MAX - 1)
563 );
564 node.properties.insert("value", (i64::MAX - 1).into());
565 assert_eq!(
566 SpinRange::from_node(&node).apply(SpinAction::Increase),
567 Some(i64::MAX)
568 );
569 node.properties.insert("wrap", true.into());
570 assert_eq!(
571 SpinRange::from_node(&node).apply(SpinAction::Increase),
572 Some(0)
573 );
574 }
575}