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