Skip to main content

xrack_runtime/
controls.rs

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