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