Skip to main content

xrack_runtime/
controls.rs

1use crate::{
2    DecimalSpinRange, InputRoute, ListModel, Node, Property, RoutedEvent, SpinDecimal, Value,
3};
4use std::sync::{
5    Arc,
6    atomic::{AtomicU64, Ordering},
7};
8
9/// Identity shared by all presentations of one component instance's Action.
10#[derive(Clone, Copy, Debug, PartialEq, Eq)]
11pub struct ActionKey(u64);
12
13impl ActionKey {
14    #[doc(hidden)]
15    pub fn present_with(
16        self,
17        node: &mut Node,
18        checkable: impl FnOnce() -> bool,
19        enabled: impl FnOnce() -> bool,
20        checked: impl FnOnce(bool) -> bool,
21    ) {
22        self.try_present_with(
23            node,
24            || Ok::<_, std::convert::Infallible>(checkable()),
25            || Ok(enabled()),
26            |checkable| Ok(checked(checkable)),
27        )
28        .unwrap_or_else(|error| match error {});
29    }
30
31    /// Resolve presentation bindings in their render order.
32    #[doc(hidden)]
33    pub fn try_present_with<E>(
34        self,
35        node: &mut Node,
36        checkable: impl FnOnce() -> Result<bool, E>,
37        enabled: impl FnOnce() -> Result<bool, E>,
38        checked: impl FnOnce(bool) -> Result<bool, E>,
39    ) -> Result<bool, E> {
40        let checkable = checkable()?;
41        let enabled = enabled()?;
42        let checked = checked(checkable)?;
43        self.present(node, enabled, checkable, checked);
44        Ok(enabled)
45    }
46
47    #[doc(hidden)]
48    pub fn present(self, node: &mut crate::Node, enabled: bool, checkable: bool, checked: bool) {
49        node.action = Some(self);
50        node.properties.insert("enabled", enabled.into());
51        node.properties.insert("checkable", checkable.into());
52        node.properties.insert("checked", checked.into());
53    }
54}
55
56/// Return a pending checked update only while the activation bindings remain current.
57#[doc(hidden)]
58pub fn try_prepare_action_activation<E>(
59    enabled: impl FnOnce() -> Result<bool, E>,
60    checkable: impl FnOnce() -> Result<bool, E>,
61    checked: impl FnOnce() -> Result<bool, E>,
62) -> Result<Option<Option<bool>>, E> {
63    crate::property::watch_reads(|reads| {
64        if !enabled()? || reads.changed() {
65            return Ok(None);
66        }
67        let checkable = checkable()?;
68        if reads.changed() {
69            return Ok(None);
70        }
71        let next = if checkable { Some(!checked()?) } else { None };
72        Ok((!reads.changed()).then_some(next))
73    })
74}
75
76#[doc(hidden)]
77pub fn prepare_action_activation(
78    enabled: impl FnOnce() -> bool,
79    checkable: impl FnOnce() -> bool,
80    checked: impl FnOnce() -> bool,
81) -> Option<Option<bool>> {
82    try_prepare_action_activation(
83        || Ok::<_, std::convert::Infallible>(enabled()),
84        || Ok(checkable()),
85        || Ok(checked()),
86    )
87    .unwrap_or_else(|error| match error {})
88}
89
90/// Read the next expansion state while the group and its input route remain current.
91#[doc(hidden)]
92pub fn try_prepare_group_box_toggle<E>(
93    input: Option<InputRoute<'_>>,
94    checkable: impl FnOnce() -> Result<bool, E>,
95    checked: impl FnOnce() -> Result<bool, E>,
96) -> Result<Option<bool>, E> {
97    if input.is_some_and(|input| !input.is_current()) {
98        return Ok(None);
99    }
100    Ok(
101        try_prepare_action_activation(|| Ok(true), checkable, checked)?
102            .flatten()
103            .filter(|_| input.is_none_or(InputRoute::is_current)),
104    )
105}
106
107#[doc(hidden)]
108pub fn prepare_group_box_toggle(
109    input: Option<InputRoute<'_>>,
110    checkable: impl FnOnce() -> bool,
111    checked: impl FnOnce() -> bool,
112) -> Option<bool> {
113    try_prepare_group_box_toggle(
114        input,
115        || Ok::<_, std::convert::Infallible>(checkable()),
116        || Ok(checked()),
117    )
118    .unwrap_or_else(|error| match error {})
119}
120
121/// Resolve an activation target without allowing bindings to invalidate it mid-read.
122#[doc(hidden)]
123pub fn try_prepare_action_view<T, E>(
124    read: impl FnOnce() -> Result<Option<T>, E>,
125) -> Result<Option<T>, E> {
126    crate::property::watch_reads(|reads| Ok(read()?.filter(|_| !reads.changed())))
127}
128
129#[doc(hidden)]
130pub fn prepare_action_view<T>(read: impl FnOnce() -> Option<T>) -> Option<T> {
131    try_prepare_action_view(|| Ok::<_, std::convert::Infallible>(read()))
132        .unwrap_or_else(|error| match error {})
133}
134
135/// Sample toggle settings before history, with the same input guard as the write.
136#[doc(hidden)]
137pub fn try_prepare_row_toggle<E>(
138    node: &Node,
139    input: crate::InputRoute<'_>,
140    tristate: Option<impl FnOnce() -> Result<bool, E>>,
141    history: impl FnOnce() -> Result<bool, E>,
142) -> Result<Option<bool>, E> {
143    input.try_prepare(
144        || match tristate {
145            Some(read) => Ok(read()? == node.boolean("tristate", false)),
146            None => Ok(true),
147        },
148        || history().map(Some),
149    )
150}
151
152#[doc(hidden)]
153pub fn prepare_row_toggle(
154    node: &Node,
155    input: crate::InputRoute<'_>,
156    tristate: Option<impl FnOnce() -> bool>,
157    history: impl FnOnce() -> bool,
158) -> Option<bool> {
159    try_prepare_row_toggle(
160        node,
161        input,
162        tristate.map(|read| move || Ok::<_, std::convert::Infallible>(read())),
163        || Ok(history()),
164    )
165    .unwrap_or_else(|error| match error {})
166}
167
168/// Resolve an index only while the control and its options remain current.
169#[doc(hidden)]
170pub fn try_prepare_index_selection<E>(
171    index: usize,
172    available: impl FnOnce() -> Result<bool, E>,
173    contains: impl FnOnce(i64) -> Result<bool, E>,
174    current: impl FnOnce() -> Result<i64, E>,
175) -> Result<Option<i64>, E> {
176    let Ok(index) = i64::try_from(index) else {
177        return Ok(None);
178    };
179    crate::property::watch_reads(|reads| {
180        if !available()? || reads.changed() || !contains(index)? || reads.changed() {
181            return Ok(None);
182        }
183        Ok((current()? != index && !reads.changed()).then_some(index))
184    })
185}
186
187#[doc(hidden)]
188pub fn prepare_index_selection(
189    index: usize,
190    available: impl FnOnce() -> bool,
191    contains: impl FnOnce(i64) -> bool,
192    current: impl FnOnce() -> i64,
193) -> Option<i64> {
194    try_prepare_index_selection(
195        index,
196        || Ok::<_, std::convert::Infallible>(available()),
197        |index| Ok(contains(index)),
198        || Ok(current()),
199    )
200    .unwrap_or_else(|error| match error {})
201}
202
203/// Resolve a source row and discard the selection if its projection changes during the cursor read.
204#[doc(hidden)]
205pub fn try_prepare_source_selection<E>(
206    resolve: impl FnOnce() -> Result<Option<usize>, E>,
207    current: impl FnOnce() -> Result<i64, E>,
208) -> Result<Option<i64>, E> {
209    try_prepare_action_view(|| {
210        let Some(index) = resolve()?.and_then(|index| i64::try_from(index).ok()) else {
211            return Ok(None);
212        };
213        Ok((current()? != index).then_some(index))
214    })
215}
216
217#[doc(hidden)]
218pub fn prepare_source_selection(
219    resolve: impl FnOnce() -> Option<usize>,
220    current: impl FnOnce() -> i64,
221) -> Option<i64> {
222    try_prepare_source_selection(
223        || Ok::<_, std::convert::Infallible>(resolve()),
224        || Ok(current()),
225    )
226    .unwrap_or_else(|error| match error {})
227}
228
229impl Node {
230    /// A disabled Action forces its presentation's state-controlled enabled value.
231    #[doc(hidden)]
232    pub fn action_state_override(&self, property: &str) -> Option<crate::Value> {
233        (property == "enabled" && self.action.is_some() && !self.boolean("enabled", true))
234            .then_some(crate::Value::Bool(false))
235    }
236}
237
238impl Default for ActionKey {
239    fn default() -> Self {
240        static NEXT_ACTION: AtomicU64 = AtomicU64::new(1);
241        let id = NEXT_ACTION
242            .try_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
243                next.checked_add(1)
244            })
245            .expect("Action keys exhausted");
246        Self(id)
247    }
248}
249
250#[derive(Clone, Copy, Debug, PartialEq, Eq)]
251pub enum SpinAction {
252    Increase,
253    Decrease,
254    Step(i64),
255    Minimum,
256    Maximum,
257    Commit(i64),
258    CommitIfCurrent {
259        original: i64,
260        value: i64,
261    },
262    CommitDecimal(SpinDecimal),
263    CommitDecimalIfCurrent {
264        original: Option<SpinDecimal>,
265        value: SpinDecimal,
266    },
267}
268
269impl SpinAction {
270    /// Read the live control value only for a commit that carries an original value.
271    #[doc(hidden)]
272    pub fn try_accepts_current<E>(
273        self,
274        current: impl FnOnce() -> Result<Value, E>,
275    ) -> Result<bool, E> {
276        Ok(match self {
277            Self::CommitIfCurrent { original, .. } => {
278                matches!(current()?, Value::Int(value) if value == original)
279            }
280            Self::CommitDecimalIfCurrent { original, .. } => {
281                matches!(current()?, Value::Float(value) if SpinDecimal::new(value) == original)
282            }
283            _ => true,
284        })
285    }
286
287    #[doc(hidden)]
288    pub fn accepts_current(self, current: impl FnOnce() -> Value) -> bool {
289        self.try_accepts_current(|| Ok::<_, std::convert::Infallible>(current()))
290            .unwrap_or_else(|error| match error {})
291    }
292}
293
294#[derive(Clone, Copy, Debug, PartialEq, Eq)]
295pub enum ControlAction {
296    Spin(SpinAction),
297    Calendar(crate::CalendarAction),
298    Select(usize),
299    ActivateRadioOption,
300    PickTumbler {
301        index: usize,
302        row: crate::RowKey,
303    },
304    TableSelection(crate::TableSelectionAction),
305    Tree(crate::TreeAction),
306    Dialog(DialogRole),
307    DialogCommand(DialogCommand),
308    Drawer(bool),
309    Popup(bool),
310    SwipeDelegate(SwipeSide),
311    DelayButton(bool),
312    StackBack {
313        revision: u64,
314    },
315    ActivateMenuItem,
316    TextCommand(crate::TextCommand),
317    ActivateTextLink(usize),
318    ActivateAction,
319    ActivateShortcut,
320    AmbiguousShortcut,
321    AcceptComboText,
322    SubmitSearch,
323    ClearSearch,
324    SortColumn(usize),
325    ResizeColumn {
326        column: usize,
327        width: u32,
328    },
329    ResizeRow {
330        row: usize,
331        key: crate::RowKey,
332        height: u32,
333    },
334    MoveColumn {
335        from: usize,
336        to: usize,
337    },
338    MoveRow {
339        from: usize,
340        to: usize,
341        row: crate::RowKey,
342        stamp: (u64, u64),
343    },
344}
345
346pub fn is_modal_overlay(kind: &str) -> bool {
347    matches!(kind, "Dialog" | "Drawer")
348}
349
350pub fn is_window_overlay(kind: &str) -> bool {
351    is_modal_overlay(kind) || kind == "PopupWindow"
352}
353
354#[doc(hidden)]
355pub fn try_set_overlay_open<E>(
356    open: bool,
357    input: Option<InputRoute<'_>>,
358    current: impl FnOnce() -> Result<bool, E>,
359    set_open: impl FnOnce(bool) -> Result<(), E>,
360    notify: impl FnOnce(bool) -> Result<(), E>,
361) -> Result<bool, E> {
362    if current()? == open || input.is_some_and(|input| !input.is_current()) {
363        return Ok(false);
364    }
365    set_open(open)?;
366    notify(open)?;
367    Ok(true)
368}
369
370#[doc(hidden)]
371pub fn set_overlay_open(
372    open: bool,
373    input: Option<InputRoute<'_>>,
374    current: impl FnOnce() -> bool,
375    set_open: impl FnOnce(bool),
376    notify: impl FnOnce(bool),
377) -> bool {
378    try_set_overlay_open(
379        open,
380        input,
381        || Ok::<_, std::convert::Infallible>(current()),
382        |open| {
383            set_open(open);
384            Ok(())
385        },
386        |open| {
387            notify(open);
388            Ok(())
389        },
390    )
391    .unwrap_or_else(|error| match error {})
392}
393
394#[doc(hidden)]
395pub fn is_pane(kind: &str) -> bool {
396    matches!(kind, "Pane" | "ControlFrame")
397}
398
399#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
400pub enum PopupPlacement {
401    #[default]
402    Below,
403    Above,
404    Left,
405    Right,
406    Offset,
407}
408
409#[derive(Clone, Copy, Debug, PartialEq, Eq)]
410pub struct TableSort {
411    pub column: usize,
412    pub descending: bool,
413}
414
415impl TableSort {
416    #[doc(hidden)]
417    pub fn from_index(column: i64, descending: bool) -> Option<Self> {
418        Some(Self {
419            column: usize::try_from(column).ok()?,
420            descending,
421        })
422    }
423}
424
425/// Visual positions map to the declaration indices used by cells and model actions.
426#[derive(Clone, Debug, Default, PartialEq, Eq)]
427pub struct TableColumnOrder(Option<Arc<ColumnPermutation>>);
428
429#[derive(Debug, PartialEq, Eq)]
430struct ColumnPermutation {
431    columns: Vec<usize>,
432    positions: Vec<usize>,
433}
434
435impl TableColumnOrder {
436    pub fn as_slice(&self, count: usize) -> Option<&[usize]> {
437        self.0
438            .as_deref()
439            .filter(|order| order.columns.len() == count)
440            .map(|order| order.columns.as_slice())
441    }
442
443    pub fn iter(&self, count: usize) -> impl DoubleEndedIterator<Item = usize> + ExactSizeIterator {
444        let order = self.as_slice(count);
445        (0..count).map(move |visual| order.map_or(visual, |order| order[visual]))
446    }
447
448    pub fn visual_index(&self, count: usize, column: usize) -> Option<usize> {
449        if let Some(order) = self
450            .0
451            .as_deref()
452            .filter(|order| order.columns.len() == count)
453        {
454            order.positions.get(column).copied()
455        } else {
456            (column < count).then_some(column)
457        }
458    }
459
460    #[doc(hidden)]
461    pub fn moved(&self, count: usize, from: usize, to: usize) -> Option<(usize, Self)> {
462        if from >= count || to >= count || from == to {
463            return None;
464        }
465        let mut order: Vec<_> = self.iter(count).collect();
466        let column = order.remove(from);
467        order.insert(to, column);
468        let reordered = order.iter().copied().ne(0..count);
469        Some((
470            column,
471            Self(reordered.then(|| {
472                let mut positions = vec![0; count];
473                for (visual, &logical) in order.iter().enumerate() {
474                    positions[logical] = visual;
475                }
476                Arc::new(ColumnPermutation {
477                    columns: order,
478                    positions,
479                })
480            })),
481        ))
482    }
483}
484
485#[derive(Clone, Debug, PartialEq)]
486pub struct TableHeader {
487    pub columns: Vec<Node>,
488    pub sort: Option<TableSort>,
489    pub column_widths: Vec<Option<u32>>,
490}
491
492pub fn resizable_table_column(table: &Node, column: usize) -> Option<&Node> {
493    let definition = table.table_header.as_ref()?.columns.get(column)?;
494    (table.boolean("resizable-columns", false) && definition.boolean("resizable", true))
495        .then_some(definition)
496}
497
498#[doc(hidden)]
499pub fn resize_table_column(widths: &Property<Vec<Option<u32>>>, column: usize, width: u32) -> bool {
500    let mut next = widths.get(Vec::new);
501    if next.get(column) == Some(&Some(width)) {
502        return false;
503    }
504    if next.len() <= column {
505        next.resize(column + 1, None);
506    }
507    next[column] = Some(width);
508    widths.set(next);
509    true
510}
511
512/// Validate a drag against both the originating scene and the current bindings.
513#[doc(hidden)]
514pub fn try_table_drag_available<E>(
515    table: &Node,
516    input: InputRoute<'_>,
517    flag: impl FnOnce(&str) -> Result<bool, E>,
518    column_resizable: impl FnOnce(usize) -> Result<bool, E>,
519) -> Result<bool, E> {
520    let (property, column) = match *input.event() {
521        RoutedEvent::Control(ControlAction::ResizeColumn { column, .. }) => {
522            if resizable_table_column(table, column).is_none() {
523                return Ok(false);
524            }
525            ("resizable-columns", Some(column))
526        }
527        RoutedEvent::Control(ControlAction::ResizeRow { .. }) => ("resizable-rows", None),
528        RoutedEvent::Control(ControlAction::MoveColumn { .. }) => ("movable-columns", None),
529        RoutedEvent::Control(ControlAction::MoveRow { stamp, .. }) => {
530            if table.standard_list_stamp != Some(stamp) {
531                return Ok(false);
532            }
533            ("movable-rows", None)
534        }
535        _ => return Ok(true),
536    };
537    if !table.boolean(property, false) {
538        return Ok(false);
539    }
540    input.try_available(|| {
541        if !flag(property)? {
542            return Ok(false);
543        }
544        column.map_or(Ok(true), column_resizable)
545    })
546}
547
548#[doc(hidden)]
549pub fn table_drag_available(
550    table: &Node,
551    input: InputRoute<'_>,
552    flag: impl FnOnce(&str) -> bool,
553    column_resizable: impl FnOnce(usize) -> bool,
554) -> bool {
555    try_table_drag_available(
556        table,
557        input,
558        |name| Ok::<_, std::convert::Infallible>(flag(name)),
559        |column| Ok(column_resizable(column)),
560    )
561    .unwrap_or_else(|error| match error {})
562}
563
564impl TableHeader {
565    pub fn next_sort(&self, column: usize) -> Option<TableSort> {
566        let definition = self.columns.get(column)?;
567        definition.boolean("sortable", true).then_some(TableSort {
568            column,
569            descending: self
570                .sort
571                .is_some_and(|sort| sort.column == column && !sort.descending),
572        })
573    }
574
575    /// Resolve a click using the sort indicator the user actually saw.
576    #[doc(hidden)]
577    pub fn next_sort_if_current(
578        &self,
579        column: usize,
580        current: Option<TableSort>,
581    ) -> Option<TableSort> {
582        if self.sort != current {
583            return None;
584        }
585        self.next_sort(column)
586    }
587}
588
589impl Node {
590    /// A column move uses visual positions from the originating scene.
591    #[doc(hidden)]
592    pub fn table_column_move_is_current(
593        &self,
594        from: usize,
595        to: usize,
596        current: &TableColumnOrder,
597    ) -> bool {
598        self.table_column_order == *current
599            && from != to
600            && self
601                .table_header
602                .as_ref()
603                .is_some_and(|header| from < header.columns.len() && to < header.columns.len())
604    }
605}
606
607#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
608pub enum DialogRole {
609    #[default]
610    Accept,
611    Reject,
612}
613
614#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
615pub enum SwipeSide {
616    #[default]
617    Closed,
618    Left,
619    Right,
620}
621
622impl SwipeSide {
623    pub fn panel(self) -> Option<&'static str> {
624        match self {
625            Self::Closed => None,
626            Self::Left => Some("SwipeLeft"),
627            Self::Right => Some("SwipeRight"),
628        }
629    }
630}
631
632#[derive(Clone, Copy, Debug, PartialEq, Eq)]
633pub enum DialogCommand {
634    Apply,
635    Reset,
636    Help,
637    Discard,
638}
639
640#[doc(hidden)]
641pub enum DialogEvent {
642    Accepted,
643    Rejected,
644    Applied,
645    Reset,
646    HelpRequested,
647    Discarded,
648}
649
650impl DialogEvent {
651    pub fn handler(&self) -> &'static str {
652        match self {
653            Self::Accepted => "accepted",
654            Self::Rejected => "rejected",
655            Self::Applied => "applied",
656            Self::Reset => "reset",
657            Self::HelpRequested => "help-requested",
658            Self::Discarded => "discarded",
659        }
660    }
661
662    pub fn try_deliver<E>(
663        action: ControlAction,
664        input: InputRoute<'_>,
665        open: impl FnOnce() -> Result<bool, E>,
666        close: impl FnOnce() -> Result<(), E>,
667        notify: impl FnOnce(Self) -> Result<(), E>,
668    ) -> Result<bool, E> {
669        if !open()? || !input.is_current() {
670            return Ok(false);
671        }
672        let event = match action {
673            ControlAction::Dialog(DialogRole::Accept) => Self::Accepted,
674            ControlAction::Dialog(DialogRole::Reject) => Self::Rejected,
675            ControlAction::DialogCommand(DialogCommand::Apply) => Self::Applied,
676            ControlAction::DialogCommand(DialogCommand::Reset) => Self::Reset,
677            ControlAction::DialogCommand(DialogCommand::Help) => Self::HelpRequested,
678            ControlAction::DialogCommand(DialogCommand::Discard) => Self::Discarded,
679            _ => return Ok(false),
680        };
681        if matches!(event, Self::Accepted | Self::Rejected | Self::Discarded) {
682            close()?;
683        }
684        notify(event)?;
685        Ok(true)
686    }
687
688    pub fn deliver(
689        action: ControlAction,
690        input: InputRoute<'_>,
691        open: impl FnOnce() -> bool,
692        close: impl FnOnce(),
693        notify: impl FnOnce(Self),
694    ) -> bool {
695        Self::try_deliver(
696            action,
697            input,
698            || Ok::<_, std::convert::Infallible>(open()),
699            || {
700                close();
701                Ok(())
702            },
703            |event| {
704                notify(event);
705                Ok(())
706            },
707        )
708        .unwrap_or_else(|error| match error {})
709    }
710}
711
712#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
713pub enum StandardButtonKind {
714    #[default]
715    Ok,
716    Open,
717    Save,
718    SaveAll,
719    Cancel,
720    Close,
721    Apply,
722    Reset,
723    RestoreDefaults,
724    Help,
725    Yes,
726    YesToAll,
727    No,
728    NoToAll,
729    Abort,
730    Retry,
731    Ignore,
732    Discard,
733}
734
735impl StandardButtonKind {
736    #[doc(hidden)]
737    pub fn accepts_message(self) -> bool {
738        matches!(self, Self::Ok | Self::Yes)
739    }
740
741    pub fn label(self) -> &'static str {
742        match self {
743            Self::Ok => "OK",
744            Self::Open => "Open",
745            Self::Save => "Save",
746            Self::SaveAll => "Save All",
747            Self::Cancel => "Cancel",
748            Self::Close => "Close",
749            Self::Apply => "Apply",
750            Self::Reset => "Reset",
751            Self::RestoreDefaults => "Restore Defaults",
752            Self::Help => "Help",
753            Self::Yes => "Yes",
754            Self::YesToAll => "Yes to All",
755            Self::No => "No",
756            Self::NoToAll => "No to All",
757            Self::Abort => "Abort",
758            Self::Retry => "Retry",
759            Self::Ignore => "Ignore",
760            Self::Discard => "Discard",
761        }
762    }
763
764    fn dialog_action(self) -> ControlAction {
765        match self {
766            Self::Ok
767            | Self::Open
768            | Self::Save
769            | Self::SaveAll
770            | Self::Yes
771            | Self::YesToAll
772            | Self::Retry
773            | Self::Ignore => ControlAction::Dialog(DialogRole::Accept),
774            Self::Cancel | Self::Close | Self::No | Self::NoToAll | Self::Abort => {
775                ControlAction::Dialog(DialogRole::Reject)
776            }
777            Self::Apply => ControlAction::DialogCommand(DialogCommand::Apply),
778            Self::Reset | Self::RestoreDefaults => {
779                ControlAction::DialogCommand(DialogCommand::Reset)
780            }
781            Self::Help => ControlAction::DialogCommand(DialogCommand::Help),
782            Self::Discard => ControlAction::DialogCommand(DialogCommand::Discard),
783        }
784    }
785}
786
787pub fn dialog_button_action(node: &Node) -> Option<ControlAction> {
788    if node.kind == "DialogButton" {
789        return Some(ControlAction::Dialog(node.dialog_role()));
790    }
791    node.standard_button_kind()
792        .map(StandardButtonKind::dialog_action)
793}
794
795pub fn is_button(kind: &str) -> bool {
796    matches!(
797        kind,
798        "Button" | "ToolButton" | "RoundButton" | "DialogButton" | "DelayButton"
799    )
800}
801
802pub fn delay_millis(node: &Node) -> u64 {
803    normalized_delay_millis(node.int("delay"))
804}
805
806fn normalized_delay_millis(delay: Option<i64>) -> u64 {
807    delay.unwrap_or(3_000).clamp(0, 60_000) as u64
808}
809
810/// Confirm that a pending hold or reset still applies to the live button.
811#[doc(hidden)]
812pub fn try_delay_button_transition_is_current<E>(
813    node: &Node,
814    checked: bool,
815    available: impl FnOnce() -> Result<bool, E>,
816    delay: impl FnOnce() -> Result<Option<i64>, E>,
817    current: impl FnOnce() -> Result<bool, E>,
818) -> Result<bool, E> {
819    crate::property::watch_reads(|reads| {
820        if !available()? || reads.changed() {
821            return Ok(false);
822        }
823        if checked && (normalized_delay_millis(delay()?) != delay_millis(node) || reads.changed()) {
824            return Ok(false);
825        }
826        Ok(current()? != checked && !reads.changed())
827    })
828}
829
830#[doc(hidden)]
831pub fn delay_button_transition_is_current(
832    node: &Node,
833    checked: bool,
834    available: impl FnOnce() -> bool,
835    delay: impl FnOnce() -> Option<i64>,
836    current: impl FnOnce() -> bool,
837) -> bool {
838    try_delay_button_transition_is_current(
839        node,
840        checked,
841        || Ok::<_, std::convert::Infallible>(available()),
842        || Ok(delay()),
843        || Ok(current()),
844    )
845    .unwrap_or_else(|error| match error {})
846}
847
848pub fn button_text(node: &Node) -> &str {
849    node.text("text").unwrap_or_else(|| {
850        if let Some(kind) = node.standard_button_kind() {
851            return kind.label();
852        }
853        match (node.kind, node.dialog_role()) {
854            ("DialogButton", DialogRole::Accept) => "OK",
855            ("DialogButton", DialogRole::Reject) => "Cancel",
856            _ => "",
857        }
858    })
859}
860
861pub struct SpinRange {
862    min: i64,
863    max: i64,
864    value: i64,
865    original: Option<i64>,
866    step: i64,
867    wrap: bool,
868}
869
870impl SpinRange {
871    pub fn from_node(node: &Node) -> Self {
872        let min = node.int("minimum").unwrap_or(0);
873        let max = node.int("maximum").unwrap_or(100).max(min);
874        let original = node.int("value");
875        Self {
876            min,
877            max,
878            value: original.unwrap_or(min).clamp(min, max),
879            original,
880            step: node.int("step-size").unwrap_or(1).max(0),
881            wrap: node.boolean("wrap", false),
882        }
883    }
884
885    pub fn value(&self) -> i64 {
886        self.value
887    }
888
889    pub fn apply(&self, action: SpinAction) -> Option<i64> {
890        let next = match action {
891            SpinAction::Increase
892                if self.wrap
893                    && self
894                        .value
895                        .checked_add(self.step)
896                        .is_none_or(|value| value > self.max) =>
897            {
898                self.min
899            }
900            SpinAction::Decrease
901                if self.wrap
902                    && self
903                        .value
904                        .checked_sub(self.step)
905                        .is_none_or(|value| value < self.min) =>
906            {
907                self.max
908            }
909            SpinAction::Increase => self.value.saturating_add(self.step),
910            SpinAction::Decrease => self.value.saturating_sub(self.step),
911            SpinAction::Step(steps) => {
912                let next = i128::from(self.value) + i128::from(self.step) * i128::from(steps);
913                let min = i128::from(self.min);
914                let max = i128::from(self.max);
915                let step = i128::from(self.step);
916                let value = i128::from(self.value);
917                if self.wrap && next > max {
918                    let remaining = i128::from(steps) - (max - value) / step - 1;
919                    (min + remaining % ((max - min) / step + 1) * step) as i64
920                } else if self.wrap && next < min {
921                    let remaining = -i128::from(steps) - (value - min) / step - 1;
922                    (max - remaining % ((max - min) / step + 1) * step) as i64
923                } else {
924                    next.clamp(min, max) as i64
925                }
926            }
927            SpinAction::Minimum => self.min,
928            SpinAction::Maximum => self.max,
929            SpinAction::Commit(value) => value,
930            SpinAction::CommitIfCurrent { original, value } if self.original == Some(original) => {
931                value
932            }
933            SpinAction::CommitIfCurrent { .. } => return None,
934            SpinAction::CommitDecimal(_) | SpinAction::CommitDecimalIfCurrent { .. } => {
935                return None;
936            }
937        }
938        .clamp(self.min, self.max);
939        (next != self.value).then_some(next)
940    }
941}
942
943pub fn spin_value_after(node: &Node, action: SpinAction) -> Option<i64> {
944    if node.boolean("read-only", false)
945        || matches!(
946            action,
947            SpinAction::Commit(_) | SpinAction::CommitIfCurrent { .. }
948        ) && !spin_editable(node)
949    {
950        return None;
951    }
952    SpinRange::from_node(node).apply(action)
953}
954
955#[doc(hidden)]
956pub const SPIN_VIEW_PROPERTIES: &[&str] = &[
957    "read-only",
958    "editable",
959    "minimum",
960    "maximum",
961    "decimals",
962    "decimal-separator",
963    "step-size",
964    "wrap",
965];
966
967/// Check that the options used to interpret an input are still current.
968#[doc(hidden)]
969pub fn try_spin_view_is_current<E>(
970    node: &Node,
971    action: SpinAction,
972    available: impl FnOnce() -> Result<bool, E>,
973    current: impl FnOnce() -> Result<Value, E>,
974    read: impl FnMut(&str) -> Result<Option<Value>, E>,
975) -> Result<bool, E> {
976    try_prepare_spin_view(node, action, available, current, read, || Ok(Some(())))
977        .map(|prepared| prepared.is_some())
978}
979
980#[doc(hidden)]
981pub fn try_prepare_spin_view<T, E>(
982    node: &Node,
983    action: SpinAction,
984    available: impl FnOnce() -> Result<bool, E>,
985    current: impl FnOnce() -> Result<Value, E>,
986    mut read: impl FnMut(&str) -> Result<Option<Value>, E>,
987    prepare: impl FnOnce() -> Result<Option<T>, E>,
988) -> Result<Option<T>, E> {
989    let decimal = node.kind == "DoubleSpinBox";
990    let commit = matches!(
991        action,
992        SpinAction::Commit(_)
993            | SpinAction::CommitIfCurrent { .. }
994            | SpinAction::CommitDecimal(_)
995            | SpinAction::CommitDecimalIfCurrent { .. }
996    );
997    let step = matches!(
998        action,
999        SpinAction::Increase | SpinAction::Decrease | SpinAction::Step(_)
1000    );
1001    crate::property::watch_reads(|reads| {
1002        if !available()? || reads.changed() {
1003            return Ok(None);
1004        }
1005        for &name in SPIN_VIEW_PROPERTIES {
1006            let used = match name {
1007                "editable" => commit,
1008                "decimals" => decimal,
1009                "decimal-separator" => decimal && commit,
1010                "step-size" | "wrap" => step,
1011                _ => true,
1012            };
1013            if used && (read(name)?.as_ref() != node.properties.get(name) || reads.changed()) {
1014                return Ok(None);
1015            }
1016        }
1017        if !action.try_accepts_current(current)? || reads.changed() {
1018            return Ok(None);
1019        }
1020        Ok(prepare()?.filter(|_| !reads.changed()))
1021    })
1022}
1023
1024#[doc(hidden)]
1025pub fn spin_view_is_current(
1026    node: &Node,
1027    action: SpinAction,
1028    available: impl FnOnce() -> bool,
1029    current: impl FnOnce() -> Value,
1030    mut read: impl FnMut(&str) -> Option<Value>,
1031) -> bool {
1032    try_spin_view_is_current(
1033        node,
1034        action,
1035        || Ok::<_, std::convert::Infallible>(available()),
1036        || Ok(current()),
1037        |name| Ok(read(name)),
1038    )
1039    .unwrap_or_else(|error| match error {})
1040}
1041
1042#[doc(hidden)]
1043pub fn prepare_spin_view<T>(
1044    node: &Node,
1045    action: SpinAction,
1046    available: impl FnOnce() -> bool,
1047    current: impl FnOnce() -> Value,
1048    mut read: impl FnMut(&str) -> Option<Value>,
1049    prepare: impl FnOnce() -> Option<T>,
1050) -> Option<T> {
1051    try_prepare_spin_view(
1052        node,
1053        action,
1054        || Ok::<_, std::convert::Infallible>(available()),
1055        || Ok(current()),
1056        |name| Ok(read(name)),
1057        || Ok(prepare()),
1058    )
1059    .unwrap_or_else(|error| match error {})
1060}
1061
1062pub fn is_spin_box(kind: &str) -> bool {
1063    matches!(kind, "SpinBox" | "DoubleSpinBox")
1064}
1065
1066pub fn spin_editable(node: &Node) -> bool {
1067    is_spin_box(node.kind) && node.boolean("editable", true) && !node.boolean("read-only", false)
1068}
1069
1070pub fn spin_text(node: &Node) -> String {
1071    if node.kind == "DoubleSpinBox" {
1072        DecimalSpinRange::from_node(node).display()
1073    } else {
1074        SpinRange::from_node(node).value().to_string()
1075    }
1076}
1077
1078pub fn combo_editable(node: &Node) -> bool {
1079    node.kind == "ComboBox" && node.boolean("editable", false)
1080}
1081
1082pub fn text_input_value(node: &Node) -> &str {
1083    if combo_editable(node) {
1084        node.text("edit-text")
1085            .unwrap_or_else(|| crate::combo_text(node))
1086    } else {
1087        node.text("text").unwrap_or("")
1088    }
1089}
1090
1091/// Suggestions can be tagged with the query that produced them.
1092pub fn search_suggestions(node: &Node) -> &[String] {
1093    let text = text_input_value(node);
1094    if node.kind != "SearchField"
1095        || node.boolean("read-only", false)
1096        || text.is_empty()
1097        || node
1098            .text("suggestions-for")
1099            .is_some_and(|query| query != text)
1100    {
1101        &[]
1102    } else {
1103        node.strings("suggestions")
1104    }
1105}
1106
1107pub fn search_suggestion(node: &Node, index: usize) -> Option<&str> {
1108    let value = search_suggestions(node).get(index)?;
1109    (!value.is_empty() && !value.chars().any(char::is_control)).then_some(value.as_str())
1110}
1111
1112pub fn page_indicator_count(node: &Node) -> usize {
1113    usize::try_from(node.int("count").unwrap_or(0).max(0)).unwrap_or(usize::MAX)
1114}
1115
1116pub fn page_indicator_index(node: &Node) -> Option<usize> {
1117    let index = usize::try_from(node.int("current-index").unwrap_or(0)).ok()?;
1118    (index < page_indicator_count(node)).then_some(index)
1119}
1120
1121/// Resolve an eligible option without giving each option independent selection state.
1122pub fn group_item(node: &Node, index: usize) -> Option<&Node> {
1123    let expected = match node.kind {
1124        "RadioGroup" => "RadioButton",
1125        "TabWidget" => "Tab",
1126        "TabBar" => "TabButton",
1127        "SwipeView" => "SwipePage",
1128        _ => return None,
1129    };
1130    node.children.get(index).filter(|item| {
1131        item.kind == expected && item.boolean("visible", true) && item.boolean("enabled", true)
1132    })
1133}
1134
1135/// Resolve a selectable option that is distinct from the scene's selected option.
1136#[doc(hidden)]
1137pub fn group_selection_item(node: &Node, index: usize) -> Option<&Node> {
1138    let item = group_item(node, index)?;
1139    (group_index(node) != Some(index)).then_some(item)
1140}
1141
1142/// Validate the displayed option against the live group before committing a selection.
1143#[doc(hidden)]
1144pub fn try_prepare_group_selection<E>(
1145    node: &Node,
1146    index: usize,
1147    route: crate::InputRoute<'_>,
1148    model_current: impl FnOnce() -> Result<bool, E>,
1149    current: impl FnOnce() -> Result<crate::ButtonGroupSelection, E>,
1150    mut option: impl FnMut(usize, bool) -> Result<Option<String>, E>,
1151) -> Result<Option<String>, E> {
1152    let Some(shown) = group_item(node, index) else {
1153        return Ok(None);
1154    };
1155    let radio = node.kind == "RadioGroup";
1156    if !route.try_available(model_current)? {
1157        return Ok(None);
1158    }
1159    let Some(label) = option(index, radio)? else {
1160        return Ok(None);
1161    };
1162    if !route.is_current() || (radio && label != crate::radio_value(shown)) {
1163        return Ok(None);
1164    }
1165    let current = current()?;
1166    if !route.is_current() {
1167        return Ok(None);
1168    }
1169    let unchanged = match current {
1170        crate::ButtonGroupSelection::Value(value) => value == label,
1171        crate::ButtonGroupSelection::Index(current) => {
1172            let current = usize::try_from(current).ok();
1173            if current == Some(index) {
1174                true
1175            } else if matches!(node.kind, "TabBar" | "SwipeView") {
1176                let mut selected = false;
1177                let valid_current = if let Some(current) = current {
1178                    option(current, false)?.is_some()
1179                } else {
1180                    false
1181                };
1182                if !valid_current && route.is_current() {
1183                    selected = true;
1184                    for preceding in 0..index {
1185                        if option(preceding, false)?.is_some() || !route.is_current() {
1186                            selected = false;
1187                            break;
1188                        }
1189                    }
1190                }
1191                selected
1192            } else {
1193                false
1194            }
1195        }
1196    };
1197    Ok((!unchanged && route.is_current()).then_some(label))
1198}
1199
1200#[doc(hidden)]
1201pub fn prepare_group_selection(
1202    node: &Node,
1203    index: usize,
1204    route: crate::InputRoute<'_>,
1205    model_current: impl FnOnce() -> bool,
1206    current: impl FnOnce() -> crate::ButtonGroupSelection,
1207    mut option: impl FnMut(usize, bool) -> Option<String>,
1208) -> Option<String> {
1209    try_prepare_group_selection(
1210        node,
1211        index,
1212        route,
1213        || Ok::<_, std::convert::Infallible>(model_current()),
1214        || Ok(current()),
1215        |index, label| Ok(option(index, label)),
1216    )
1217    .unwrap_or_else(|error| match error {})
1218}
1219
1220impl Node {
1221    #[doc(hidden)]
1222    pub fn snapshot_group_options(&mut self, model: &impl ListModel) {
1223        self.standard_list_stamp = Some(model.contents_stamp());
1224    }
1225
1226    #[doc(hidden)]
1227    pub fn group_options_are_current(&self, model: &impl ListModel) -> bool {
1228        self.standard_list_stamp == Some(model.contents_stamp())
1229    }
1230}
1231
1232pub fn group_index(node: &Node) -> Option<usize> {
1233    if matches!(node.kind, "SwipeView" | "TabBar") {
1234        return resolve_swipe_index(
1235            node.int("current-index"),
1236            (0..node.children.len()).map(|index| group_item(node, index).is_some()),
1237        );
1238    }
1239    if node.kind == "RadioGroup"
1240        && let Some(value) = node.text("current-value")
1241    {
1242        return node.children.iter().enumerate().find_map(|(index, _)| {
1243            group_item(node, index)
1244                .filter(|item| crate::radio_value(item) == value)
1245                .map(|_| index)
1246        });
1247    }
1248    let default = if node.kind == "RadioGroup" { -1 } else { 0 };
1249    let index = usize::try_from(node.int("current-index").unwrap_or(default)).ok()?;
1250    group_item(node, index).map(|_| index)
1251}
1252
1253impl Node {
1254    /// Mount the same SwipePage that layout will select from the rendered page properties.
1255    #[doc(hidden)]
1256    pub fn mount_active_swipe_page<T>(
1257        &mut self,
1258        mount: impl FnOnce(usize, &mut Node) -> T,
1259    ) -> Option<T> {
1260        if self.kind != "SwipeView" || !self.is_visible() {
1261            return None;
1262        }
1263        let index = group_index(self)?;
1264        Some(mount(index, &mut self.children[index]))
1265    }
1266}
1267
1268/// Preserve declared page indexes while falling back to the first available page.
1269#[doc(hidden)]
1270pub fn resolve_swipe_index(
1271    requested: Option<i64>,
1272    available: impl IntoIterator<Item = bool>,
1273) -> Option<usize> {
1274    try_resolve_swipe_index(
1275        requested,
1276        available.into_iter().map(Ok::<_, std::convert::Infallible>),
1277    )
1278    .unwrap_or_else(|error| match error {})
1279}
1280
1281#[doc(hidden)]
1282pub fn try_resolve_swipe_index<E>(
1283    requested: Option<i64>,
1284    available: impl IntoIterator<Item = Result<bool, E>>,
1285) -> Result<Option<usize>, E> {
1286    let requested = requested.and_then(|index| usize::try_from(index).ok());
1287    let mut first = None;
1288    for (index, available) in available.into_iter().enumerate() {
1289        if available? {
1290            if requested == Some(index) {
1291                return Ok(Some(index));
1292            }
1293            first.get_or_insert(index);
1294        }
1295    }
1296    Ok(first)
1297}
1298
1299#[cfg(test)]
1300mod tests {
1301    use super::*;
1302
1303    #[test]
1304    fn integer_steps_preserve_precision_and_handle_overflow() {
1305        let mut node = Node::new("SpinBox", None);
1306        node.properties.insert("value", (i64::MAX - 4).into());
1307        node.properties.insert("maximum", i64::MAX.into());
1308        node.properties.insert("step-size", 3_i64.into());
1309        assert_eq!(
1310            SpinRange::from_node(&node).apply(SpinAction::Increase),
1311            Some(i64::MAX - 1)
1312        );
1313        node.properties.insert("value", (i64::MAX - 1).into());
1314        assert_eq!(
1315            SpinRange::from_node(&node).apply(SpinAction::Increase),
1316            Some(i64::MAX)
1317        );
1318        node.properties.insert("wrap", true.into());
1319        assert_eq!(
1320            SpinRange::from_node(&node).apply(SpinAction::Increase),
1321            Some(0)
1322        );
1323    }
1324}