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_expander_change<E>(
128 input: Option<InputRoute<'_>>,
129 requested: Option<bool>,
130 expanded: impl FnOnce() -> Result<bool, E>,
131) -> Result<Option<bool>, E> {
132 if input.is_some_and(|input| !input.is_current()) {
133 return Ok(None);
134 }
135 crate::property::watch_reads(|reads| {
136 let current = expanded()?;
137 let next = requested.unwrap_or(!current);
138 Ok(
139 (next != current && !reads.changed() && input.is_none_or(InputRoute::is_current))
140 .then_some(next),
141 )
142 })
143}
144
145#[doc(hidden)]
146pub fn prepare_expander_change(
147 input: Option<InputRoute<'_>>,
148 requested: Option<bool>,
149 expanded: impl FnOnce() -> bool,
150) -> Option<bool> {
151 try_prepare_expander_change(input, requested, || {
152 Ok::<_, std::convert::Infallible>(expanded())
153 })
154 .unwrap_or_else(|error| match error {})
155}
156
157#[doc(hidden)]
159pub fn try_prepare_action_view<T, E>(
160 read: impl FnOnce() -> Result<Option<T>, E>,
161) -> Result<Option<T>, E> {
162 crate::property::watch_reads(|reads| Ok(read()?.filter(|_| !reads.changed())))
163}
164
165#[doc(hidden)]
166pub fn prepare_action_view<T>(read: impl FnOnce() -> Option<T>) -> Option<T> {
167 try_prepare_action_view(|| Ok::<_, std::convert::Infallible>(read()))
168 .unwrap_or_else(|error| match error {})
169}
170
171impl crate::CheckState {
172 #[doc(hidden)]
174 pub fn try_prepare_toggle<E>(
175 input: Option<InputRoute<'_>>,
176 current: impl FnOnce() -> Result<Self, E>,
177 tristate: impl FnOnce() -> Result<bool, E>,
178 ) -> Result<Option<Self>, E> {
179 let route_current = || input.is_none_or(InputRoute::is_current);
180 if !route_current() {
181 return Ok(None);
182 }
183 crate::property::watch_reads(|reads| {
184 let current = current()?;
185 if reads.changed() || !route_current() {
186 return Ok(None);
187 }
188 let next = if let Some(crate::RoutedEvent::Control(ControlAction::SetSwitch(checked))) =
189 input.map(InputRoute::event)
190 {
191 let desired = Self::from(*checked);
192 (desired != current).then_some(desired)
193 } else {
194 Some(current.next(tristate()?))
195 };
196 Ok(next.filter(|_| !reads.changed() && route_current()))
197 })
198 }
199
200 #[doc(hidden)]
201 pub fn prepare_toggle(
202 input: Option<InputRoute<'_>>,
203 current: impl FnOnce() -> Self,
204 tristate: impl FnOnce() -> bool,
205 ) -> Option<Self> {
206 Self::try_prepare_toggle(
207 input,
208 || Ok::<_, std::convert::Infallible>(current()),
209 || Ok(tristate()),
210 )
211 .unwrap_or_else(|error| match error {})
212 }
213}
214
215#[doc(hidden)]
217pub fn try_prepare_row_toggle<E>(
218 node: &Node,
219 input: crate::InputRoute<'_>,
220 tristate: Option<impl FnOnce() -> Result<bool, E>>,
221 history: impl FnOnce() -> Result<bool, E>,
222) -> Result<Option<bool>, E> {
223 try_prepare_row_toggle_matching(node, input, tristate, || true, history)
224}
225
226#[doc(hidden)]
228pub fn try_prepare_row_toggle_matching<E>(
229 node: &Node,
230 input: crate::InputRoute<'_>,
231 tristate: Option<impl FnOnce() -> Result<bool, E>>,
232 field_current: impl FnOnce() -> bool,
233 history: impl FnOnce() -> Result<bool, E>,
234) -> Result<Option<bool>, E> {
235 input.try_prepare(
236 || match tristate {
237 Some(read) => Ok(read()? == node.boolean("tristate", false)),
238 None => Ok(true),
239 },
240 || {
241 if !field_current() {
242 return Ok(None);
243 }
244 history().map(Some)
245 },
246 )
247}
248
249#[doc(hidden)]
250pub fn prepare_row_toggle(
251 node: &Node,
252 input: crate::InputRoute<'_>,
253 tristate: Option<impl FnOnce() -> bool>,
254 history: impl FnOnce() -> bool,
255) -> Option<bool> {
256 prepare_row_toggle_matching(node, input, tristate, || true, history)
257}
258
259#[doc(hidden)]
260pub fn prepare_row_toggle_matching(
261 node: &Node,
262 input: crate::InputRoute<'_>,
263 tristate: Option<impl FnOnce() -> bool>,
264 field_current: impl FnOnce() -> bool,
265 history: impl FnOnce() -> bool,
266) -> Option<bool> {
267 try_prepare_row_toggle_matching(
268 node,
269 input,
270 tristate.map(|read| move || Ok::<_, std::convert::Infallible>(read())),
271 field_current,
272 || Ok(history()),
273 )
274 .unwrap_or_else(|error| match error {})
275}
276
277#[doc(hidden)]
279pub fn try_prepare_index_selection<E>(
280 index: usize,
281 available: impl FnOnce() -> Result<bool, E>,
282 contains: impl FnOnce(i64) -> Result<bool, E>,
283 current: impl FnOnce() -> Result<i64, E>,
284) -> Result<Option<i64>, E> {
285 let Ok(index) = i64::try_from(index) else {
286 return Ok(None);
287 };
288 crate::property::watch_reads(|reads| {
289 if !available()? || reads.changed() || !contains(index)? || reads.changed() {
290 return Ok(None);
291 }
292 Ok((current()? != index && !reads.changed()).then_some(index))
293 })
294}
295
296#[doc(hidden)]
297pub fn prepare_index_selection(
298 index: usize,
299 available: impl FnOnce() -> bool,
300 contains: impl FnOnce(i64) -> bool,
301 current: impl FnOnce() -> i64,
302) -> Option<i64> {
303 try_prepare_index_selection(
304 index,
305 || Ok::<_, std::convert::Infallible>(available()),
306 |index| Ok(contains(index)),
307 || Ok(current()),
308 )
309 .unwrap_or_else(|error| match error {})
310}
311
312#[doc(hidden)]
314pub fn try_prepare_source_selection<E>(
315 resolve: impl FnOnce() -> Result<Option<usize>, E>,
316 current: impl FnOnce() -> Result<i64, E>,
317) -> Result<Option<i64>, E> {
318 try_prepare_action_view(|| {
319 let Some(index) = resolve()?.and_then(|index| i64::try_from(index).ok()) else {
320 return Ok(None);
321 };
322 Ok((current()? != index).then_some(index))
323 })
324}
325
326#[doc(hidden)]
327pub fn prepare_source_selection(
328 resolve: impl FnOnce() -> Option<usize>,
329 current: impl FnOnce() -> i64,
330) -> Option<i64> {
331 try_prepare_source_selection(
332 || Ok::<_, std::convert::Infallible>(resolve()),
333 || Ok(current()),
334 )
335 .unwrap_or_else(|error| match error {})
336}
337
338impl Node {
339 #[doc(hidden)]
341 pub fn action_state_override(&self, property: &str) -> Option<crate::Value> {
342 (property == "enabled" && self.action.is_some() && !self.boolean("enabled", true))
343 .then_some(crate::Value::Bool(false))
344 }
345}
346
347impl Default for ActionKey {
348 #[expect(
349 clippy::expect_used,
350 reason = "action IDs must remain unique across all action instances"
351 )]
352 fn default() -> Self {
353 static NEXT_ACTION: AtomicU64 = AtomicU64::new(1);
354 let id = NEXT_ACTION
355 .try_update(Ordering::Relaxed, Ordering::Relaxed, |next| {
356 next.checked_add(1)
357 })
358 .expect("Action keys exhausted");
359 Self(id)
360 }
361}
362
363#[derive(Clone, Copy, Debug, PartialEq, Eq)]
364pub enum SpinAction {
365 Increase,
366 Decrease,
367 Step(i64),
368 Minimum,
369 Maximum,
370 Commit(i64),
371 CommitIfCurrent {
372 original: i64,
373 value: i64,
374 },
375 CommitDecimal(SpinDecimal),
376 CommitDecimalIfCurrent {
377 original: Option<SpinDecimal>,
378 value: SpinDecimal,
379 },
380}
381
382impl SpinAction {
383 #[doc(hidden)]
385 pub fn try_accepts_current<E>(
386 self,
387 current: impl FnOnce() -> Result<Value, E>,
388 ) -> Result<bool, E> {
389 Ok(match self {
390 Self::CommitIfCurrent { original, .. } => {
391 matches!(current()?, Value::Int(value) if value == original)
392 }
393 Self::CommitDecimalIfCurrent { original, .. } => {
394 matches!(current()?, Value::Float(value) if SpinDecimal::new(value) == original)
395 }
396 _ => true,
397 })
398 }
399
400 #[doc(hidden)]
401 pub fn accepts_current(self, current: impl FnOnce() -> Value) -> bool {
402 self.try_accepts_current(|| Ok::<_, std::convert::Infallible>(current()))
403 .unwrap_or_else(|error| match error {})
404 }
405}
406
407#[derive(Clone, Copy, Debug, PartialEq, Eq)]
408pub enum ControlAction {
409 Spin(SpinAction),
410 SetSwitch(bool),
411 Expander(bool),
412 Calendar(crate::CalendarAction),
413 Select(usize),
414 ActivateRadioOption,
415 MoveTab(TabMove),
416 CloseTab(TabClose),
417 PickTumbler {
418 index: usize,
419 row: crate::RowKey,
420 },
421 TableSelection(crate::TableSelectionAction),
422 Tree(crate::TreeAction),
423 Dialog(DialogRole),
424 DialogCommand(DialogCommand),
425 Drawer(bool),
426 Popup(bool),
427 SwipeDelegate(SwipeSide),
428 DelayButton(bool),
429 StackBack {
430 revision: u64,
431 },
432 ActivateMenuItem,
433 TextCommand(crate::TextCommand),
434 ActivateTextLink(usize),
435 ActivateAction,
436 ActivateShortcut,
437 AmbiguousShortcut,
438 AcceptComboText,
439 SubmitSearch,
440 ClearSearch,
441 SortColumn(usize),
442 ResizeColumn {
443 column: usize,
444 width: u32,
445 },
446 ResizeRow {
447 row: usize,
448 key: crate::RowKey,
449 height: u32,
450 },
451 MoveColumn {
452 from: usize,
453 to: usize,
454 },
455 MoveRow {
456 from: usize,
457 to: usize,
458 row: crate::RowKey,
459 stamp: (u64, u64),
460 },
461}
462
463pub fn is_modal_overlay(kind: &str) -> bool {
464 matches!(kind, "Dialog" | "Drawer")
465}
466
467pub fn is_window_overlay(kind: &str) -> bool {
468 is_modal_overlay(kind) || kind == "PopupWindow"
469}
470
471#[doc(hidden)]
474pub fn try_prepare_swipe_side<E>(
475 node: &Node,
476 side: SwipeSide,
477 input: InputRoute<'_>,
478 current: impl FnOnce() -> Result<SwipeSide, E>,
479 panel_visible: impl FnOnce(&str) -> Result<bool, E>,
480) -> Result<bool, E> {
481 crate::property::watch_reads(|reads| {
482 if !input.is_current()
483 || !node.accepts_swipe_side(current()?, side)
484 || reads.changed()
485 || !input.is_current()
486 {
487 return Ok(false);
488 }
489 if let Some(panel) = side.panel()
490 && !panel_visible(panel)?
491 {
492 return Ok(false);
493 }
494 Ok(!reads.changed() && input.is_current())
495 })
496}
497
498#[doc(hidden)]
499pub fn prepare_swipe_side(
500 node: &Node,
501 side: SwipeSide,
502 input: InputRoute<'_>,
503 current: impl FnOnce() -> SwipeSide,
504 panel_visible: impl FnOnce(&str) -> bool,
505) -> bool {
506 try_prepare_swipe_side(
507 node,
508 side,
509 input,
510 || Ok::<_, std::convert::Infallible>(current()),
511 |panel| Ok(panel_visible(panel)),
512 )
513 .unwrap_or_else(|error| match error {})
514}
515
516#[doc(hidden)]
517pub fn try_set_overlay_open<E>(
518 open: bool,
519 input: Option<InputRoute<'_>>,
520 current: impl FnOnce() -> Result<bool, E>,
521 set_open: impl FnOnce(bool) -> Result<(), E>,
522 notify: impl FnOnce(bool) -> Result<(), E>,
523) -> Result<bool, E> {
524 let route_current = || input.is_none_or(InputRoute::is_current);
525 let should_set = crate::property::watch_reads(|reads| {
526 Ok(route_current() && current()? != open && !reads.changed() && route_current())
527 })?;
528 if !should_set {
529 return Ok(false);
530 }
531 set_open(open)?;
532 notify(open)?;
533 Ok(true)
534}
535
536#[doc(hidden)]
537pub fn set_overlay_open(
538 open: bool,
539 input: Option<InputRoute<'_>>,
540 current: impl FnOnce() -> bool,
541 set_open: impl FnOnce(bool),
542 notify: impl FnOnce(bool),
543) -> bool {
544 try_set_overlay_open(
545 open,
546 input,
547 || Ok::<_, std::convert::Infallible>(current()),
548 |open| {
549 set_open(open);
550 Ok(())
551 },
552 |open| {
553 notify(open);
554 Ok(())
555 },
556 )
557 .unwrap_or_else(|error| match error {})
558}
559
560#[doc(hidden)]
561pub fn is_pane(kind: &str) -> bool {
562 matches!(kind, "Pane" | "ControlFrame")
563}
564
565#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
566pub enum PopupPlacement {
567 #[default]
568 Below,
569 Above,
570 Left,
571 Right,
572 Offset,
573}
574
575#[derive(Clone, Copy, Debug, PartialEq, Eq)]
576pub struct TableSort {
577 pub column: usize,
578 pub descending: bool,
579}
580
581impl TableSort {
582 #[doc(hidden)]
583 pub fn from_index(column: i64, descending: bool) -> Option<Self> {
584 Some(Self {
585 column: usize::try_from(column).ok()?,
586 descending,
587 })
588 }
589
590 #[doc(hidden)]
591 pub fn column_index(sort: Option<Self>) -> i64 {
592 sort.map_or(-1, |sort| sort.column as i64)
593 }
594
595 #[doc(hidden)]
596 pub fn is_descending(sort: Option<Self>) -> bool {
597 sort.is_some_and(|sort| sort.descending)
598 }
599}
600
601#[derive(Clone, Debug, Default, PartialEq, Eq)]
603pub struct TableColumnOrder(Option<Arc<ColumnPermutation>>);
604
605#[derive(Debug, PartialEq, Eq)]
606struct ColumnPermutation {
607 columns: Vec<usize>,
608 positions: Vec<usize>,
609}
610
611impl TableColumnOrder {
612 pub fn as_slice(&self, count: usize) -> Option<&[usize]> {
613 self.0
614 .as_deref()
615 .filter(|order| order.columns.len() == count)
616 .map(|order| order.columns.as_slice())
617 }
618
619 pub fn iter(&self, count: usize) -> impl DoubleEndedIterator<Item = usize> + ExactSizeIterator {
620 let order = self.as_slice(count);
621 (0..count).map(move |visual| order.map_or(visual, |order| order[visual]))
622 }
623
624 pub fn visual_index(&self, count: usize, column: usize) -> Option<usize> {
625 if let Some(order) = self
626 .0
627 .as_deref()
628 .filter(|order| order.columns.len() == count)
629 {
630 order.positions.get(column).copied()
631 } else {
632 (column < count).then_some(column)
633 }
634 }
635
636 #[doc(hidden)]
637 pub fn moved(&self, count: usize, from: usize, to: usize) -> Option<(usize, Self)> {
638 if from >= count || to >= count || from == to {
639 return None;
640 }
641 let mut order: Vec<_> = self.iter(count).collect();
642 let column = order.remove(from);
643 order.insert(to, column);
644 let reordered = order.iter().copied().ne(0..count);
645 Some((
646 column,
647 Self(reordered.then(|| {
648 let mut positions = vec![0; count];
649 for (visual, &logical) in order.iter().enumerate() {
650 positions[logical] = visual;
651 }
652 Arc::new(ColumnPermutation {
653 columns: order,
654 positions,
655 })
656 })),
657 ))
658 }
659}
660
661#[derive(Clone, Debug, PartialEq)]
662pub struct TableHeader {
663 pub columns: Vec<Node>,
664 pub sort: Option<TableSort>,
665 pub column_widths: Vec<Option<u32>>,
666}
667
668pub fn resizable_table_column(table: &Node, column: usize) -> Option<&Node> {
669 let definition = table.table_header.as_ref()?.columns.get(column)?;
670 (table.boolean("resizable-columns", false) && definition.boolean("resizable", true))
671 .then_some(definition)
672}
673
674#[doc(hidden)]
675pub fn resize_table_column(widths: &Property<Vec<Option<u32>>>, column: usize, width: u32) -> bool {
676 let mut next = widths.get(Vec::new);
677 if next.get(column) == Some(&Some(width)) {
678 return false;
679 }
680 if next.len() <= column {
681 next.resize(column + 1, None);
682 }
683 next[column] = Some(width);
684 widths.set(next);
685 true
686}
687
688#[doc(hidden)]
690pub fn try_table_drag_available<E>(
691 table: &Node,
692 input: InputRoute<'_>,
693 flag: impl FnOnce(&str) -> Result<bool, E>,
694 column_resizable: impl FnOnce(usize) -> Result<bool, E>,
695) -> Result<bool, E> {
696 let (property, column) = match *input.event() {
697 RoutedEvent::Control(ControlAction::ResizeColumn { column, .. }) => {
698 if resizable_table_column(table, column).is_none() {
699 return Ok(false);
700 }
701 ("resizable-columns", Some(column))
702 }
703 RoutedEvent::Control(ControlAction::ResizeRow { .. }) => ("resizable-rows", None),
704 RoutedEvent::Control(ControlAction::MoveColumn { .. }) => ("movable-columns", None),
705 RoutedEvent::Control(ControlAction::MoveRow { stamp, .. }) => {
706 if table.standard_list_stamp != Some(stamp) {
707 return Ok(false);
708 }
709 ("movable-rows", None)
710 }
711 _ => return Ok(true),
712 };
713 if !table.boolean(property, false) {
714 return Ok(false);
715 }
716 input.try_available(|| {
717 if !flag(property)? {
718 return Ok(false);
719 }
720 column.map_or(Ok(true), column_resizable)
721 })
722}
723
724#[doc(hidden)]
725pub fn table_drag_available(
726 table: &Node,
727 input: InputRoute<'_>,
728 flag: impl FnOnce(&str) -> bool,
729 column_resizable: impl FnOnce(usize) -> bool,
730) -> bool {
731 try_table_drag_available(
732 table,
733 input,
734 |name| Ok::<_, std::convert::Infallible>(flag(name)),
735 |column| Ok(column_resizable(column)),
736 )
737 .unwrap_or_else(|error| match error {})
738}
739
740#[doc(hidden)]
741pub enum TableHeaderAction {
742 Sort(TableSort),
743 MoveColumn {
744 from: usize,
745 to: usize,
746 },
747 ResizeColumn {
748 column: usize,
749 width: u32,
750 },
751 ResizeRow {
752 row: usize,
753 key: RowKey,
754 height: u32,
755 },
756}
757
758impl TableHeaderAction {
759 pub fn try_prepare<M, E>(
761 node: &Node,
762 input: InputRoute<'_>,
763 action: ControlAction,
764 sort: impl FnOnce() -> Option<TableSort>,
765 order: impl FnOnce() -> TableColumnOrder,
766 rows: impl FnOnce() -> Result<TableRows<M>, E>,
767 ) -> Result<Option<(Self, TableRows<M>)>, E> {
768 let action = match action {
769 ControlAction::SortColumn(column) => {
770 let Some(sort) = node
771 .table_header
772 .as_ref()
773 .and_then(|header| header.next_sort_if_current(column, sort()))
774 else {
775 return Ok(None);
776 };
777 Self::Sort(sort)
778 }
779 ControlAction::MoveColumn { from, to } => {
780 if !node.table_column_move_is_current(from, to, &order()) {
781 return Ok(None);
782 }
783 Self::MoveColumn { from, to }
784 }
785 ControlAction::ResizeColumn { column, width } => Self::ResizeColumn { column, width },
786 ControlAction::ResizeRow { row, key, height } => Self::ResizeRow { row, key, height },
787 _ => return Ok(None),
788 };
789 let rows = rows()?;
790 Ok(
791 (input.is_current() && node.standard_list_stamp == Some(rows.positions().stamp()))
792 .then_some((action, rows)),
793 )
794 }
795
796 pub fn prepare<M>(
797 node: &Node,
798 input: InputRoute<'_>,
799 action: ControlAction,
800 sort: impl FnOnce() -> Option<TableSort>,
801 order: impl FnOnce() -> TableColumnOrder,
802 rows: impl FnOnce() -> TableRows<M>,
803 ) -> Option<(Self, TableRows<M>)> {
804 Self::try_prepare(node, input, action, sort, order, || {
805 Ok::<_, std::convert::Infallible>(rows())
806 })
807 .unwrap_or_else(|error| match error {})
808 }
809}
810
811impl TableHeader {
812 pub fn next_sort(&self, column: usize) -> Option<TableSort> {
813 let definition = self.columns.get(column)?;
814 definition.boolean("sortable", true).then_some(TableSort {
815 column,
816 descending: self
817 .sort
818 .is_some_and(|sort| sort.column == column && !sort.descending),
819 })
820 }
821
822 #[doc(hidden)]
824 pub fn next_sort_if_current(
825 &self,
826 column: usize,
827 current: Option<TableSort>,
828 ) -> Option<TableSort> {
829 if self.sort != current {
830 return None;
831 }
832 self.next_sort(column)
833 }
834}
835
836impl Node {
837 #[doc(hidden)]
839 pub fn table_column_move_is_current(
840 &self,
841 from: usize,
842 to: usize,
843 current: &TableColumnOrder,
844 ) -> bool {
845 self.table_column_order == *current
846 && from != to
847 && self
848 .table_header
849 .as_ref()
850 .is_some_and(|header| from < header.columns.len() && to < header.columns.len())
851 }
852}
853
854#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
855pub enum DialogRole {
856 #[default]
857 Accept,
858 Reject,
859}
860
861#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
862pub enum SwipeSide {
863 #[default]
864 Closed,
865 Left,
866 Right,
867}
868
869impl SwipeSide {
870 pub fn panel(self) -> Option<&'static str> {
871 match self {
872 Self::Closed => None,
873 Self::Left => Some("SwipeLeft"),
874 Self::Right => Some("SwipeRight"),
875 }
876 }
877}
878
879#[derive(Clone, Copy, Debug, PartialEq, Eq)]
880pub enum DialogCommand {
881 Apply,
882 Reset,
883 Help,
884 Discard,
885}
886
887#[doc(hidden)]
888pub enum DialogEvent {
889 Accepted,
890 Rejected,
891 Applied,
892 Reset,
893 HelpRequested,
894 Discarded,
895}
896
897impl DialogEvent {
898 pub fn handler(&self) -> &'static str {
899 match self {
900 Self::Accepted => "accepted",
901 Self::Rejected => "rejected",
902 Self::Applied => "applied",
903 Self::Reset => "reset",
904 Self::HelpRequested => "help-requested",
905 Self::Discarded => "discarded",
906 }
907 }
908
909 pub fn try_deliver<E>(
910 action: ControlAction,
911 input: InputRoute<'_>,
912 open: impl FnOnce() -> Result<bool, E>,
913 close: impl FnOnce() -> Result<(), E>,
914 notify: impl FnOnce(Self) -> Result<(), E>,
915 ) -> Result<bool, E> {
916 if !open()? || !input.is_current() {
917 return Ok(false);
918 }
919 let event = match action {
920 ControlAction::Dialog(DialogRole::Accept) => Self::Accepted,
921 ControlAction::Dialog(DialogRole::Reject) => Self::Rejected,
922 ControlAction::DialogCommand(DialogCommand::Apply) => Self::Applied,
923 ControlAction::DialogCommand(DialogCommand::Reset) => Self::Reset,
924 ControlAction::DialogCommand(DialogCommand::Help) => Self::HelpRequested,
925 ControlAction::DialogCommand(DialogCommand::Discard) => Self::Discarded,
926 _ => return Ok(false),
927 };
928 if matches!(event, Self::Accepted | Self::Rejected | Self::Discarded) {
929 close()?;
930 }
931 notify(event)?;
932 Ok(true)
933 }
934
935 pub fn deliver(
936 action: ControlAction,
937 input: InputRoute<'_>,
938 open: impl FnOnce() -> bool,
939 close: impl FnOnce(),
940 notify: impl FnOnce(Self),
941 ) -> bool {
942 Self::try_deliver(
943 action,
944 input,
945 || Ok::<_, std::convert::Infallible>(open()),
946 || {
947 close();
948 Ok(())
949 },
950 |event| {
951 notify(event);
952 Ok(())
953 },
954 )
955 .unwrap_or_else(|error| match error {})
956 }
957}
958
959#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
960pub enum StandardButtonKind {
961 #[default]
962 Ok,
963 Open,
964 Save,
965 SaveAll,
966 Cancel,
967 Close,
968 Apply,
969 Reset,
970 RestoreDefaults,
971 Help,
972 Yes,
973 YesToAll,
974 No,
975 NoToAll,
976 Abort,
977 Retry,
978 Ignore,
979 Discard,
980}
981
982impl StandardButtonKind {
983 #[doc(hidden)]
984 pub fn accepts_message(self) -> bool {
985 matches!(self, Self::Ok | Self::Yes)
986 }
987
988 pub fn label(self) -> &'static str {
989 match self {
990 Self::Ok => "OK",
991 Self::Open => "Open",
992 Self::Save => "Save",
993 Self::SaveAll => "Save All",
994 Self::Cancel => "Cancel",
995 Self::Close => "Close",
996 Self::Apply => "Apply",
997 Self::Reset => "Reset",
998 Self::RestoreDefaults => "Restore Defaults",
999 Self::Help => "Help",
1000 Self::Yes => "Yes",
1001 Self::YesToAll => "Yes to All",
1002 Self::No => "No",
1003 Self::NoToAll => "No to All",
1004 Self::Abort => "Abort",
1005 Self::Retry => "Retry",
1006 Self::Ignore => "Ignore",
1007 Self::Discard => "Discard",
1008 }
1009 }
1010
1011 fn dialog_action(self) -> ControlAction {
1012 match self {
1013 Self::Ok
1014 | Self::Open
1015 | Self::Save
1016 | Self::SaveAll
1017 | Self::Yes
1018 | Self::YesToAll
1019 | Self::Retry
1020 | Self::Ignore => ControlAction::Dialog(DialogRole::Accept),
1021 Self::Cancel | Self::Close | Self::No | Self::NoToAll | Self::Abort => {
1022 ControlAction::Dialog(DialogRole::Reject)
1023 }
1024 Self::Apply => ControlAction::DialogCommand(DialogCommand::Apply),
1025 Self::Reset | Self::RestoreDefaults => {
1026 ControlAction::DialogCommand(DialogCommand::Reset)
1027 }
1028 Self::Help => ControlAction::DialogCommand(DialogCommand::Help),
1029 Self::Discard => ControlAction::DialogCommand(DialogCommand::Discard),
1030 }
1031 }
1032}
1033
1034pub fn dialog_button_action(node: &Node) -> Option<ControlAction> {
1035 if node.kind == "DialogButton" {
1036 return Some(ControlAction::Dialog(node.dialog_role()));
1037 }
1038 node.standard_button_kind()
1039 .map(StandardButtonKind::dialog_action)
1040}
1041
1042pub fn is_button(kind: &str) -> bool {
1043 matches!(
1044 kind,
1045 "Button" | "ToolButton" | "RoundButton" | "DialogButton" | "DelayButton"
1046 )
1047}
1048
1049pub fn delay_millis(node: &Node) -> u64 {
1050 normalized_delay_millis(node.int("delay"))
1051}
1052
1053fn normalized_delay_millis(delay: Option<i64>) -> u64 {
1054 delay.unwrap_or(3_000).clamp(0, 60_000) as u64
1055}
1056
1057#[doc(hidden)]
1059pub fn try_delay_button_transition_is_current<E>(
1060 node: &Node,
1061 checked: bool,
1062 available: impl FnOnce() -> Result<bool, E>,
1063 delay: impl FnOnce() -> Result<Option<i64>, E>,
1064 current: impl FnOnce() -> Result<bool, E>,
1065) -> Result<bool, E> {
1066 crate::property::watch_reads(|reads| {
1067 if !available()? || reads.changed() {
1068 return Ok(false);
1069 }
1070 if checked && (normalized_delay_millis(delay()?) != delay_millis(node) || reads.changed()) {
1071 return Ok(false);
1072 }
1073 Ok(current()? != checked && !reads.changed())
1074 })
1075}
1076
1077#[doc(hidden)]
1078pub fn delay_button_transition_is_current(
1079 node: &Node,
1080 checked: bool,
1081 available: impl FnOnce() -> bool,
1082 delay: impl FnOnce() -> Option<i64>,
1083 current: impl FnOnce() -> bool,
1084) -> bool {
1085 try_delay_button_transition_is_current(
1086 node,
1087 checked,
1088 || Ok::<_, std::convert::Infallible>(available()),
1089 || Ok(delay()),
1090 || Ok(current()),
1091 )
1092 .unwrap_or_else(|error| match error {})
1093}
1094
1095pub fn button_text(node: &Node) -> &str {
1096 node.text("text").unwrap_or_else(|| {
1097 if let Some(kind) = node.standard_button_kind() {
1098 return kind.label();
1099 }
1100 match (node.kind, node.dialog_role()) {
1101 ("DialogButton", DialogRole::Accept) => "OK",
1102 ("DialogButton", DialogRole::Reject) => "Cancel",
1103 _ => "",
1104 }
1105 })
1106}
1107
1108pub struct SpinRange {
1109 min: i64,
1110 max: i64,
1111 value: i64,
1112 original: Option<i64>,
1113 step: i64,
1114 wrap: bool,
1115}
1116
1117impl SpinRange {
1118 pub fn from_node(node: &Node) -> Self {
1119 let min = node.int("minimum").unwrap_or(0);
1120 let max = node.int("maximum").unwrap_or(100).max(min);
1121 let original = node.int("value");
1122 Self {
1123 min,
1124 max,
1125 value: original.unwrap_or(min).clamp(min, max),
1126 original,
1127 step: node.int("step-size").unwrap_or(1).max(0),
1128 wrap: node.boolean("wrap", false),
1129 }
1130 }
1131
1132 pub fn value(&self) -> i64 {
1133 self.value
1134 }
1135
1136 pub fn apply(&self, action: SpinAction) -> Option<i64> {
1137 let next = match action {
1138 SpinAction::Increase
1139 if self.wrap
1140 && self
1141 .value
1142 .checked_add(self.step)
1143 .is_none_or(|value| value > self.max) =>
1144 {
1145 self.min
1146 }
1147 SpinAction::Decrease
1148 if self.wrap
1149 && self
1150 .value
1151 .checked_sub(self.step)
1152 .is_none_or(|value| value < self.min) =>
1153 {
1154 self.max
1155 }
1156 SpinAction::Increase => self.value.saturating_add(self.step),
1157 SpinAction::Decrease => self.value.saturating_sub(self.step),
1158 SpinAction::Step(steps) => {
1159 let next = i128::from(self.value) + i128::from(self.step) * i128::from(steps);
1160 let min = i128::from(self.min);
1161 let max = i128::from(self.max);
1162 let step = i128::from(self.step);
1163 let value = i128::from(self.value);
1164 if self.wrap && next > max {
1165 let remaining = i128::from(steps) - (max - value) / step - 1;
1166 (min + remaining % ((max - min) / step + 1) * step) as i64
1167 } else if self.wrap && next < min {
1168 let remaining = -i128::from(steps) - (value - min) / step - 1;
1169 (max - remaining % ((max - min) / step + 1) * step) as i64
1170 } else {
1171 next.clamp(min, max) as i64
1172 }
1173 }
1174 SpinAction::Minimum => self.min,
1175 SpinAction::Maximum => self.max,
1176 SpinAction::Commit(value) => value,
1177 SpinAction::CommitIfCurrent { original, value } if self.original == Some(original) => {
1178 value
1179 }
1180 SpinAction::CommitIfCurrent { .. } => return None,
1181 SpinAction::CommitDecimal(_) | SpinAction::CommitDecimalIfCurrent { .. } => {
1182 return None;
1183 }
1184 }
1185 .clamp(self.min, self.max);
1186 (next != self.value).then_some(next)
1187 }
1188}
1189
1190pub fn spin_value_after(node: &Node, action: SpinAction) -> Option<i64> {
1191 if node.boolean("read-only", false)
1192 || matches!(
1193 action,
1194 SpinAction::Commit(_) | SpinAction::CommitIfCurrent { .. }
1195 ) && !spin_editable(node)
1196 {
1197 return None;
1198 }
1199 SpinRange::from_node(node).apply(action)
1200}
1201
1202#[doc(hidden)]
1203pub const SPIN_VIEW_PROPERTIES: &[&str] = &[
1204 "read-only",
1205 "editable",
1206 "minimum",
1207 "maximum",
1208 "decimals",
1209 "decimal-separator",
1210 "step-size",
1211 "wrap",
1212];
1213
1214#[doc(hidden)]
1216pub fn try_spin_view_is_current<E>(
1217 node: &Node,
1218 action: SpinAction,
1219 available: impl FnOnce() -> Result<bool, E>,
1220 current: impl FnOnce() -> Result<Value, E>,
1221 read: impl FnMut(&str) -> Result<Option<Value>, E>,
1222) -> Result<bool, E> {
1223 try_prepare_spin_view(node, action, available, current, read, || Ok(Some(())))
1224 .map(|prepared| prepared.is_some())
1225}
1226
1227#[doc(hidden)]
1228pub fn try_prepare_spin_view<T, E>(
1229 node: &Node,
1230 action: SpinAction,
1231 available: impl FnOnce() -> Result<bool, E>,
1232 current: impl FnOnce() -> Result<Value, E>,
1233 mut read: impl FnMut(&str) -> Result<Option<Value>, E>,
1234 prepare: impl FnOnce() -> Result<Option<T>, E>,
1235) -> Result<Option<T>, E> {
1236 let decimal = node.kind == "DoubleSpinBox";
1237 let commit = matches!(
1238 action,
1239 SpinAction::Commit(_)
1240 | SpinAction::CommitIfCurrent { .. }
1241 | SpinAction::CommitDecimal(_)
1242 | SpinAction::CommitDecimalIfCurrent { .. }
1243 );
1244 let step = matches!(
1245 action,
1246 SpinAction::Increase | SpinAction::Decrease | SpinAction::Step(_)
1247 );
1248 crate::property::watch_reads(|reads| {
1249 if !available()? || reads.changed() {
1250 return Ok(None);
1251 }
1252 for &name in SPIN_VIEW_PROPERTIES {
1253 let used = match name {
1254 "editable" => commit,
1255 "decimals" => decimal,
1256 "decimal-separator" => decimal && commit,
1257 "step-size" | "wrap" => step,
1258 _ => true,
1259 };
1260 if used && (read(name)?.as_ref() != node.properties.get(name) || reads.changed()) {
1261 return Ok(None);
1262 }
1263 }
1264 if !action.try_accepts_current(current)? || reads.changed() {
1265 return Ok(None);
1266 }
1267 Ok(prepare()?.filter(|_| !reads.changed()))
1268 })
1269}
1270
1271#[doc(hidden)]
1272pub fn spin_view_is_current(
1273 node: &Node,
1274 action: SpinAction,
1275 available: impl FnOnce() -> bool,
1276 current: impl FnOnce() -> Value,
1277 mut read: impl FnMut(&str) -> Option<Value>,
1278) -> bool {
1279 try_spin_view_is_current(
1280 node,
1281 action,
1282 || Ok::<_, std::convert::Infallible>(available()),
1283 || Ok(current()),
1284 |name| Ok(read(name)),
1285 )
1286 .unwrap_or_else(|error| match error {})
1287}
1288
1289#[doc(hidden)]
1290pub fn prepare_spin_view<T>(
1291 node: &Node,
1292 action: SpinAction,
1293 available: impl FnOnce() -> bool,
1294 current: impl FnOnce() -> Value,
1295 mut read: impl FnMut(&str) -> Option<Value>,
1296 prepare: impl FnOnce() -> Option<T>,
1297) -> Option<T> {
1298 try_prepare_spin_view(
1299 node,
1300 action,
1301 || Ok::<_, std::convert::Infallible>(available()),
1302 || Ok(current()),
1303 |name| Ok(read(name)),
1304 || Ok(prepare()),
1305 )
1306 .unwrap_or_else(|error| match error {})
1307}
1308
1309pub fn is_spin_box(kind: &str) -> bool {
1310 matches!(kind, "SpinBox" | "DoubleSpinBox")
1311}
1312
1313pub fn spin_editable(node: &Node) -> bool {
1314 is_spin_box(node.kind) && node.boolean("editable", true) && !node.boolean("read-only", false)
1315}
1316
1317pub fn spin_text(node: &Node) -> String {
1318 if node.kind == "DoubleSpinBox" {
1319 DecimalSpinRange::from_node(node).display()
1320 } else {
1321 SpinRange::from_node(node).value().to_string()
1322 }
1323}
1324
1325pub fn combo_editable(node: &Node) -> bool {
1326 node.kind == "ComboBox" && node.boolean("editable", false)
1327}
1328
1329pub fn text_input_value(node: &Node) -> &str {
1330 if combo_editable(node) {
1331 node.text("edit-text")
1332 .unwrap_or_else(|| crate::combo_text(node))
1333 } else {
1334 node.text("text").unwrap_or("")
1335 }
1336}
1337
1338pub fn search_suggestions(node: &Node) -> &[String] {
1340 let text = text_input_value(node);
1341 if node.kind != "SearchField"
1342 || node.boolean("read-only", false)
1343 || text.is_empty()
1344 || node
1345 .text("suggestions-for")
1346 .is_some_and(|query| query != text)
1347 {
1348 &[]
1349 } else {
1350 node.strings("suggestions")
1351 }
1352}
1353
1354pub fn search_suggestion(node: &Node, index: usize) -> Option<&str> {
1355 let value = search_suggestions(node).get(index)?;
1356 (!value.is_empty() && !value.chars().any(char::is_control)).then_some(value.as_str())
1357}
1358
1359pub fn page_indicator_count(node: &Node) -> usize {
1360 usize::try_from(node.int("count").unwrap_or(0).max(0)).unwrap_or(usize::MAX)
1361}
1362
1363pub fn page_indicator_index(node: &Node) -> Option<usize> {
1364 let index = usize::try_from(node.int("current-index").unwrap_or(0)).ok()?;
1365 (index < page_indicator_count(node)).then_some(index)
1366}
1367
1368fn navigation_item_kind(kind: &str) -> Option<&'static str> {
1370 match kind {
1371 "TabWidget" => Some("Tab"),
1372 "TabBar" => Some("TabButton"),
1373 "SwipeView" => Some("SwipePage"),
1374 _ => None,
1375 }
1376}
1377
1378fn group_item_available(item: &Node, expected: &str) -> bool {
1379 item.kind == expected && item.boolean("visible", true) && item.boolean("enabled", true)
1380}
1381
1382pub fn group_item(node: &Node, index: usize) -> Option<&Node> {
1383 let expected = if node.kind == "RadioGroup" {
1384 "RadioButton"
1385 } else {
1386 navigation_item_kind(node.kind)?
1387 };
1388 node.children
1389 .get(index)
1390 .filter(|item| group_item_available(item, expected))
1391}
1392
1393fn navigation_index(
1394 kind: &str,
1395 requested: Option<&str>,
1396 index: Option<i64>,
1397 items: &[Node],
1398) -> Option<usize> {
1399 if kind == "StackLayout" {
1400 return match requested {
1401 Some(value) => {
1402 resolve_navigation_value(value, items.iter().map(|item| item.text("value")))
1403 }
1404 None => usize::try_from(index.unwrap_or(0))
1405 .ok()
1406 .filter(|index| *index < items.len()),
1407 };
1408 }
1409 let expected = navigation_item_kind(kind)?;
1410 let eligible = |item: &Node| group_item_available(item, expected);
1411 if let Some(value) = requested {
1412 return resolve_navigation_value(
1413 value,
1414 items
1415 .iter()
1416 .map(|item| eligible(item).then(|| item.text("value")).flatten()),
1417 );
1418 }
1419 if kind == "TabWidget" {
1420 let slot = usize::try_from(index.unwrap_or(0)).ok()?;
1421 return items.get(slot).filter(|item| eligible(item)).map(|_| slot);
1422 }
1423 resolve_swipe_index(index, items.iter().map(eligible))
1424}
1425
1426#[doc(hidden)]
1427pub fn tab_is_closable(group: &Node, item: &Node) -> bool {
1428 matches!(
1429 (group.kind, item.kind),
1430 ("TabBar", "TabButton") | ("TabWidget", "Tab")
1431 ) && item.boolean("closable", group.boolean("tabs-closable", false))
1432}
1433
1434#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1435pub struct TabClose {
1436 pub index: usize,
1437 row: Option<crate::RowKey>,
1438 stamp: Option<(u64, u64)>,
1439}
1440
1441impl Node {
1442 #[doc(hidden)]
1443 pub fn tab_close(&self, index: usize) -> Option<TabClose> {
1444 let item = group_item(self, index)?;
1445 tab_is_closable(self, item).then_some(TabClose {
1446 index,
1447 row: item.row_key,
1448 stamp: self.standard_list_stamp,
1449 })
1450 }
1451}
1452
1453#[doc(hidden)]
1455pub fn try_prepare_tab_close<M, E>(
1456 node: &Node,
1457 request: TabClose,
1458 route: crate::InputRoute<'_>,
1459 model: impl FnOnce() -> Result<Option<M>, E>,
1460 read: impl FnOnce(&M, usize) -> Result<Option<String>, E>,
1461) -> Result<Option<String>, E> {
1462 if node.tab_close(request.index) != Some(request) {
1463 return Ok(None);
1464 }
1465 let expected = node
1466 .child_at(request.index)
1467 .and_then(|item| item.text("value"))
1468 .unwrap_or("");
1469 let mut label = None;
1470 let sample = || {
1471 if let Some(model) = model()? {
1472 label = read(&model, request.index)?.filter(|current| current == expected);
1473 }
1474 Ok(label.is_some())
1475 };
1476 let accepted = if route.checks_availability() {
1477 route.try_available(sample)?
1478 } else {
1479 sample()?
1480 };
1481 Ok(label.filter(|_| accepted && route.is_current()))
1482}
1483
1484#[doc(hidden)]
1485pub fn prepare_tab_close<M>(
1486 node: &Node,
1487 request: TabClose,
1488 route: crate::InputRoute<'_>,
1489 model: impl FnOnce() -> Option<M>,
1490 read: impl FnOnce(&M, usize, bool) -> Option<String>,
1491) -> Option<String> {
1492 try_prepare_tab_close(
1493 node,
1494 request,
1495 route,
1496 || Ok::<_, std::convert::Infallible>(model()),
1497 |model, slot| Ok(read(model, slot, true)),
1498 )
1499 .unwrap_or_else(|error| match error {})
1500}
1501
1502#[derive(Clone, Copy, Debug, PartialEq, Eq)]
1503pub struct TabMove {
1504 pub from: usize,
1505 pub to: usize,
1506 source: crate::RowKey,
1507 destination: crate::RowKey,
1508 stamp: (u64, u64),
1509}
1510
1511#[doc(hidden)]
1512pub fn moved_navigation_index(from: usize, to: usize, index: i64) -> i64 {
1513 let Ok(slot) = usize::try_from(index) else {
1514 return index;
1515 };
1516 if slot == from {
1517 to as i64
1518 } else if from < slot && slot <= to {
1519 index - 1
1520 } else if to <= slot && slot < from {
1521 index + 1
1522 } else {
1523 index
1524 }
1525}
1526
1527impl TabMove {
1528 pub fn moved_index(self, index: i64) -> i64 {
1529 moved_navigation_index(self.from, self.to, index)
1530 }
1531
1532 #[doc(hidden)]
1533 pub fn matches_model(self, model: &impl ListModel) -> bool {
1534 self.stamp == model.contents_stamp()
1535 && model.key_at(self.from) == Some(self.source)
1536 && model.key_at(self.to) == Some(self.destination)
1537 }
1538}
1539
1540impl Node {
1541 #[doc(hidden)]
1542 pub fn tab_move(&self, from: usize, to: usize) -> Option<TabMove> {
1543 if !matches!(self.kind, "TabBar" | "TabWidget")
1544 || !self.boolean("reorderable", false)
1545 || from == to
1546 {
1547 return None;
1548 }
1549 Some(TabMove {
1550 from,
1551 to,
1552 source: group_item(self, from)?.row_key?,
1553 destination: group_item(self, to)?.row_key?,
1554 stamp: self.standard_list_stamp?,
1555 })
1556 }
1557}
1558
1559#[doc(hidden)]
1560pub fn try_prepare_tab_move<E>(
1561 node: &Node,
1562 movement: TabMove,
1563 input: crate::InputRoute<'_>,
1564 model: &impl ListModel,
1565 enabled: impl FnOnce() -> Result<bool, E>,
1566 mut available: impl FnMut(usize) -> Result<bool, E>,
1567) -> Result<bool, E> {
1568 if node.tab_move(movement.from, movement.to) != Some(movement) {
1569 return Ok(false);
1570 }
1571 Ok(input.try_available(|| {
1572 Ok(enabled()?
1573 && movement.matches_model(model)
1574 && available(movement.from)?
1575 && available(movement.to)?)
1576 })? && input.is_current()
1577 && movement.matches_model(model))
1578}
1579
1580#[doc(hidden)]
1581pub fn prepare_tab_move<M: ListModel>(
1582 node: &Node,
1583 movement: TabMove,
1584 input: crate::InputRoute<'_>,
1585 model: &Rc<M>,
1586 enabled: impl FnOnce() -> bool,
1587 mut option: impl FnMut(&Rc<M>, usize, bool) -> Option<String>,
1588) -> bool {
1589 try_prepare_tab_move(
1590 node,
1591 movement,
1592 input,
1593 model.as_ref(),
1594 || Ok::<_, std::convert::Infallible>(enabled()),
1595 |index| Ok(option(model, index, false).is_some()),
1596 )
1597 .unwrap_or_else(|error| match error {})
1598}
1599
1600#[doc(hidden)]
1602pub fn group_selection_item(node: &Node, index: usize) -> Option<&Node> {
1603 let item = group_item(node, index)?;
1604 (group_index(node) != Some(index)).then_some(item)
1605}
1606
1607#[derive(Clone, Debug, PartialEq)]
1609pub(crate) struct RadioOptionBlock {
1610 end: usize,
1611 stamp: Option<(u64, u64)>,
1612}
1613
1614impl Node {
1615 #[doc(hidden)]
1616 pub fn record_radio_option_block(&mut self) {
1617 self.push_radio_option_block(None);
1618 }
1619
1620 fn push_radio_option_block(&mut self, stamp: Option<(u64, u64)>) {
1621 let end = self.children.len();
1622 let blocks = self.radio_option_blocks.get_or_insert_with(Rc::default);
1623 let start = blocks.last().map_or(0, |block| block.end);
1624 let scope = blocks.len() as u64 + 1;
1625 Rc::make_mut(blocks).push(RadioOptionBlock { end, stamp });
1626 for (row, option) in self.children[start..end].iter_mut().enumerate() {
1627 if option.kind == "RadioButton" {
1628 option.row_key.get_or_insert(crate::RowKey {
1630 model: 0,
1631 row: row as u64,
1632 scope: 0,
1633 });
1634 option.row_scope = scope;
1635 }
1636 }
1637 }
1638
1639 #[doc(hidden)]
1641 pub fn radio_option_location(&self, slot: usize) -> Option<(usize, usize)> {
1642 if slot >= self.children.len() {
1643 return None;
1644 }
1645 let Some(blocks) = &self.radio_option_blocks else {
1646 return Some((slot, 0));
1647 };
1648 let declaration = blocks.partition_point(|block| block.end <= slot);
1649 blocks.get(declaration)?;
1650 let start = declaration
1651 .checked_sub(1)
1652 .map_or(0, |previous| blocks[previous].end);
1653 Some((declaration, slot - start))
1654 }
1655
1656 #[doc(hidden)]
1657 pub fn radio_option_model_is_current(
1658 &self,
1659 declaration: usize,
1660 model: &impl ListModel,
1661 ) -> bool {
1662 self.radio_option_blocks
1663 .as_ref()
1664 .and_then(|blocks| blocks.get(declaration))
1665 .and_then(|block| block.stamp)
1666 == Some(model.contents_stamp())
1667 }
1668}
1669
1670#[doc(hidden)]
1672pub fn try_prepare_group_selection<E>(
1673 node: &Node,
1674 index: usize,
1675 route: crate::InputRoute<'_>,
1676 model_current: impl FnOnce() -> Result<bool, E>,
1677 current: impl FnOnce() -> Result<crate::ButtonGroupSelection, E>,
1678 mut option: impl FnMut(usize, bool) -> Result<Option<String>, E>,
1679) -> Result<Option<String>, E> {
1680 try_prepare_group_selection_with_model(
1681 node,
1682 index,
1683 route,
1684 || Ok((!route.checks_availability() || model_current()?).then_some(())),
1685 current,
1686 |_, slot, label| option(slot, label),
1687 )
1688}
1689
1690#[doc(hidden)]
1692pub fn try_prepare_group_selection_with_model<M, E>(
1693 node: &Node,
1694 index: usize,
1695 route: crate::InputRoute<'_>,
1696 model: impl FnOnce() -> Result<Option<M>, E>,
1697 current: impl FnOnce() -> Result<crate::ButtonGroupSelection, E>,
1698 mut option: impl FnMut(&M, usize, bool) -> Result<Option<String>, E>,
1699) -> Result<Option<String>, E> {
1700 let Some(shown) = group_item(node, index) else {
1701 return Ok(None);
1702 };
1703 let by_navigation_value = matches!(node.kind, "TabBar" | "TabWidget" | "SwipeView")
1704 && node.text("current-value").is_some();
1705 let read_value = node.kind == "RadioGroup" || by_navigation_value;
1706 let mut sample = None;
1707 if !route.checks_availability() {
1708 sample = model()?;
1709 } else if !route.try_available(|| {
1710 sample = model()?;
1711 Ok(sample.is_some())
1712 })? {
1713 return Ok(None);
1714 }
1715 let Some(sample) = sample else {
1716 return Ok(None);
1717 };
1718 let mut option = |slot, label| option(&sample, slot, label);
1719 let Some(label) = option(index, read_value)? else {
1720 return Ok(None);
1721 };
1722 if !route.is_current() || (read_value && label != crate::radio_value(shown)) {
1723 return Ok(None);
1724 }
1725 if by_navigation_value {
1726 for preceding in 0..index {
1728 if option(preceding, true)?.as_ref() == Some(&label) || !route.is_current() {
1729 return Ok(None);
1730 }
1731 }
1732 }
1733 let current = current()?;
1734 if !route.is_current() {
1735 return Ok(None);
1736 }
1737 let unchanged = match current {
1738 crate::ButtonGroupSelection::Value(value) => value == label,
1739 crate::ButtonGroupSelection::Index(current) => {
1740 let current = usize::try_from(current).ok();
1741 if current == Some(index) {
1742 true
1743 } else if matches!(node.kind, "TabBar" | "SwipeView") {
1744 let mut selected = false;
1745 let valid_current = if let Some(current) = current {
1746 option(current, false)?.is_some()
1747 } else {
1748 false
1749 };
1750 if !valid_current && route.is_current() {
1751 selected = true;
1752 for preceding in 0..index {
1753 if option(preceding, false)?.is_some() || !route.is_current() {
1754 selected = false;
1755 break;
1756 }
1757 }
1758 }
1759 selected
1760 } else {
1761 false
1762 }
1763 }
1764 };
1765 Ok((!unchanged && route.is_current()).then_some(label))
1766}
1767
1768#[doc(hidden)]
1769pub fn prepare_group_selection_with_model<M>(
1770 node: &Node,
1771 index: usize,
1772 route: crate::InputRoute<'_>,
1773 model: impl FnOnce() -> Option<M>,
1774 current: impl FnOnce() -> crate::ButtonGroupSelection,
1775 mut option: impl FnMut(&M, usize, bool) -> Option<String>,
1776) -> Option<String> {
1777 try_prepare_group_selection_with_model(
1778 node,
1779 index,
1780 route,
1781 || Ok::<_, std::convert::Infallible>(model()),
1782 || Ok(current()),
1783 |model, slot, label| Ok(option(model, slot, label)),
1784 )
1785 .unwrap_or_else(|error| match error {})
1786}
1787
1788#[doc(hidden)]
1789pub fn prepare_group_selection(
1790 node: &Node,
1791 index: usize,
1792 route: crate::InputRoute<'_>,
1793 model_current: impl FnOnce() -> bool,
1794 current: impl FnOnce() -> crate::ButtonGroupSelection,
1795 mut option: impl FnMut(usize, bool) -> Option<String>,
1796) -> Option<String> {
1797 try_prepare_group_selection(
1798 node,
1799 index,
1800 route,
1801 || Ok::<_, std::convert::Infallible>(model_current()),
1802 || Ok(current()),
1803 |index, label| Ok(option(index, label)),
1804 )
1805 .unwrap_or_else(|error| match error {})
1806}
1807
1808#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
1809#[doc(hidden)]
1810pub enum PageIdentity {
1811 Row(RowKey),
1812 Named(Arc<str>),
1813 Slot(usize, &'static str),
1814}
1815
1816impl PageIdentity {
1817 pub fn of(page: &Node, slot: usize) -> Self {
1818 if let Some(key) = page.routing_row_key() {
1819 Self::Row(key)
1820 } else if let Some(id) = page.shared_element_id() {
1821 Self::Named(id)
1822 } else if let Some(id) = page.id {
1823 Self::Named(Arc::from(id))
1824 } else {
1825 Self::Slot(slot, page.kind)
1826 }
1827 }
1828}
1829
1830#[derive(Clone, Debug, PartialEq, Eq)]
1831struct SwipePreviewRequest {
1832 from: (usize, PageIdentity),
1833 to: (usize, PageIdentity),
1834}
1835
1836#[doc(hidden)]
1838#[derive(Clone, Default)]
1839pub struct SwipePreviewHandle(Rc<Property<Option<SwipePreviewRequest>>>);
1840
1841impl std::fmt::Debug for SwipePreviewHandle {
1842 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1843 f.debug_tuple("SwipePreviewHandle")
1844 .field(&Rc::as_ptr(&self.0))
1845 .finish()
1846 }
1847}
1848
1849impl PartialEq for SwipePreviewHandle {
1850 fn eq(&self, other: &Self) -> bool {
1851 Rc::ptr_eq(&self.0, &other.0)
1852 }
1853}
1854
1855impl SwipePreviewHandle {
1856 pub fn request(&self, from: (usize, PageIdentity), to: (usize, PageIdentity)) {
1857 self.0
1858 .set_if_changed(Some(SwipePreviewRequest { from, to }));
1859 }
1860
1861 pub fn clear(&self) {
1862 self.0.set_if_changed(None);
1863 }
1864
1865 fn slot(&self, active: Option<usize>, pages: &[Node]) -> Option<usize> {
1866 let request = self.0.get(|| None)?;
1867 let available = |(slot, id): &(usize, PageIdentity)| {
1868 pages.get(*slot).is_some_and(|page| {
1869 group_item_available(page, "SwipePage") && PageIdentity::of(page, *slot) == *id
1870 })
1871 };
1872 (active == Some(request.from.0)
1873 && request.from.0 != request.to.0
1874 && available(&request.from)
1875 && available(&request.to))
1876 .then_some(request.to.0)
1877 }
1878}
1879
1880#[doc(hidden)]
1881#[derive(Clone, Debug, PartialEq)]
1882pub struct SwipePreview {
1883 pub handle: SwipePreviewHandle,
1884 pub page: Option<(usize, Node)>,
1885}
1886
1887impl Node {
1888 #[doc(hidden)]
1889 pub fn enable_swipe_preview(&mut self, handle: SwipePreviewHandle) {
1890 self.swipe_preview = Some(Box::new(SwipePreview { handle, page: None }));
1891 }
1892}
1893
1894impl Node {
1895 #[doc(hidden)]
1896 pub fn try_append_group_options<M: ListModel, E>(
1897 &mut self,
1898 source: impl FnOnce() -> Result<Rc<M>, E>,
1899 render: impl FnOnce(&Rc<M>) -> Result<Vec<Node>, E>,
1900 ) -> Result<(), E> {
1901 let radio = self.kind == "RadioGroup";
1902 let mut stamp = None;
1903 let options = crate::try_render_rows_from_source(
1904 || {
1905 let model = source()?;
1906 if radio {
1907 stamp = Some(model.contents_stamp());
1908 } else {
1909 self.snapshot_group_options(&*model);
1910 }
1911 Ok(model)
1912 },
1913 |model| render(&model),
1914 )?;
1915 self.children.extend(options);
1916 if radio {
1917 self.push_radio_option_block(stamp);
1918 }
1919 Ok(())
1920 }
1921
1922 #[doc(hidden)]
1923 pub fn append_group_options<M: ListModel>(
1924 &mut self,
1925 source: impl FnOnce() -> Rc<M>,
1926 render: impl FnOnce(&Rc<M>) -> Vec<Node>,
1927 ) {
1928 self.try_append_group_options(
1929 || Ok::<_, std::convert::Infallible>(source()),
1930 |model| Ok(render(model)),
1931 )
1932 .unwrap_or_else(|error| match error {});
1933 }
1934
1935 #[doc(hidden)]
1936 pub fn try_append_navigation_pages<M: ListModel, E>(
1937 &mut self,
1938 source: impl FnOnce() -> Result<Rc<M>, E>,
1939 describe: impl FnMut(&Rc<M>, usize) -> Result<Node, E>,
1940 mount: impl FnOnce(&Rc<M>, Option<usize>) -> Result<Vec<Node>, E>,
1941 ) -> Result<(), E> {
1942 self.try_append_navigation_pages_with_preview(source, describe, |model, [active, _]| {
1943 mount(model, active)
1944 })
1945 }
1946
1947 #[doc(hidden)]
1948 pub fn append_navigation_pages<M: ListModel>(
1949 &mut self,
1950 source: impl FnOnce() -> Rc<M>,
1951 mut describe: impl FnMut(&Rc<M>, usize) -> Node,
1952 mount: impl FnOnce(&Rc<M>, Option<usize>) -> Vec<Node>,
1953 ) {
1954 self.try_append_navigation_pages(
1955 || Ok::<_, std::convert::Infallible>(source()),
1956 |model, slot| Ok(describe(model, slot)),
1957 |model, slot| Ok(mount(model, slot)),
1958 )
1959 .unwrap_or_else(|error| match error {});
1960 }
1961
1962 #[doc(hidden)]
1964 pub fn try_append_navigation_pages_with_preview<M: ListModel, E>(
1965 &mut self,
1966 source: impl FnOnce() -> Result<Rc<M>, E>,
1967 mut describe: impl FnMut(&Rc<M>, usize) -> Result<Node, E>,
1968 mount: impl FnOnce(&Rc<M>, [Option<usize>; 2]) -> Result<Vec<Node>, E>,
1969 ) -> Result<(), E> {
1970 let requested = self.text("current-value").map(str::to_owned);
1971 let index = self.int("current-index");
1972 let visible = self.is_visible();
1973 let kind = self.kind;
1974 let mut stamp = None;
1975 let preview_handle = self
1976 .swipe_preview
1977 .as_ref()
1978 .map(|preview| preview.handle.clone());
1979 let mut painted = None;
1980 let pages = crate::try_render_rows_from_source(
1981 || {
1982 let model = source()?;
1983 stamp = Some(model.contents_stamp());
1984 Ok(model)
1985 },
1986 |model| {
1987 let stamp = model.contents_stamp();
1988 let mut pages = crate::list::try_render_stable_rows(
1989 model.as_ref(),
1990 model.structure_stamp(),
1991 0..model.row_count().min(4096),
1992 |slot| {
1993 let mut page = describe(&model, slot)?;
1994 page.set_row_key(Some(model.row_key(slot)));
1995 Ok(page)
1996 },
1997 )?;
1998 let active = visible
1999 .then(|| navigation_index(kind, requested.as_deref(), index, &pages))
2000 .flatten();
2001 let preview_slot = preview_handle
2002 .as_ref()
2003 .and_then(|handle| handle.slot(active, &pages));
2004 let mut mounted = mount(&model, [active, preview_slot])?.into_iter();
2005 if model.contents_stamp() != stamp {
2006 return Ok(Vec::new());
2007 }
2008 if let Some(slot) = active {
2009 let Some(page) = mounted.next() else {
2010 return Ok(Vec::new());
2011 };
2012 if page.row_key != pages[slot].row_key {
2013 return Ok(Vec::new());
2014 }
2015 pages[slot] = page;
2016 }
2017 if let Some(slot) = preview_slot
2018 && let Some(page) = mounted.next()
2019 && page.row_key == pages[slot].row_key
2020 {
2021 painted = Some((slot, page));
2022 }
2023 Ok(pages)
2024 },
2025 )?;
2026 if let Some(preview) = &mut self.swipe_preview {
2027 preview.page = if pages.is_empty() { None } else { painted };
2028 }
2029 self.standard_list_stamp = stamp;
2030 self.children.extend(pages);
2031 Ok(())
2032 }
2033
2034 #[doc(hidden)]
2035 pub fn append_navigation_pages_with_preview<M: ListModel>(
2036 &mut self,
2037 source: impl FnOnce() -> Rc<M>,
2038 mut describe: impl FnMut(&Rc<M>, usize) -> Node,
2039 mount: impl FnOnce(&Rc<M>, [Option<usize>; 2]) -> Vec<Node>,
2040 ) {
2041 self.try_append_navigation_pages_with_preview(
2042 || Ok::<_, std::convert::Infallible>(source()),
2043 |model, slot| Ok(describe(model, slot)),
2044 |model, slot| Ok(mount(model, slot)),
2045 )
2046 .unwrap_or_else(|error| match error {})
2047 }
2048
2049 #[doc(hidden)]
2050 pub fn snapshot_group_options(&mut self, model: &impl ListModel) {
2051 self.standard_list_stamp = Some(model.contents_stamp());
2052 }
2053
2054 #[doc(hidden)]
2055 pub fn group_options_are_current(&self, model: &impl ListModel) -> bool {
2056 self.standard_list_stamp == Some(model.contents_stamp())
2057 }
2058}
2059
2060pub fn group_index(node: &Node) -> Option<usize> {
2061 if node.kind == "StackLayout" || navigation_item_kind(node.kind).is_some() {
2062 return navigation_index(
2063 node.kind,
2064 node.text("current-value"),
2065 node.int("current-index"),
2066 &node.children,
2067 );
2068 }
2069 if node.kind == "RadioGroup" {
2070 let mut selection = node.text("current-value").map_or_else(
2071 || crate::ButtonGroupSelection::Index(node.int("current-index").unwrap_or(-1)),
2072 |value| crate::ButtonGroupSelection::Value(value.to_owned()),
2073 );
2074 return selection.select_radio_option(node.children.len(), |index, label| {
2075 group_item(node, index).map(|item| if label { crate::radio_value(item) } else { "" })
2076 });
2077 }
2078 let index = usize::try_from(node.int("current-index").unwrap_or(0)).ok()?;
2079 group_item(node, index).map(|_| index)
2080}
2081
2082impl Node {
2083 #[doc(hidden)]
2085 pub fn mount_active_swipe_page<T>(
2086 &mut self,
2087 mount: impl FnOnce(usize, &mut Node) -> T,
2088 ) -> Option<T> {
2089 if self.kind != "SwipeView" || !self.is_visible() {
2090 return None;
2091 }
2092 let index = group_index(self)?;
2093 Some(mount(index, &mut self.children[index]))
2094 }
2095
2096 #[doc(hidden)]
2098 pub fn try_mount_swipe_pages<E>(
2099 &mut self,
2100 mut mount: impl FnMut(usize, &mut Node) -> Result<(), E>,
2101 ) -> Result<(), E> {
2102 self.mount_active_swipe_page(&mut mount).transpose()?;
2103 let active = self.is_visible().then(|| group_index(self)).flatten();
2104 let mut painted = None;
2105 if let Some(slot) = self
2106 .swipe_preview
2107 .as_ref()
2108 .and_then(|preview| preview.handle.slot(active, &self.children))
2109 && let Some(mut page) = self.children.get(slot).cloned()
2110 {
2111 mount(slot, &mut page)?;
2112 painted = Some((slot, page));
2113 }
2114 if let Some(preview) = &mut self.swipe_preview {
2115 preview.page = painted;
2116 }
2117 Ok(())
2118 }
2119
2120 #[doc(hidden)]
2121 pub fn mount_swipe_pages(&mut self, mut mount: impl FnMut(usize, &mut Node)) {
2122 self.try_mount_swipe_pages(|slot, node| {
2123 mount(slot, node);
2124 Ok::<_, std::convert::Infallible>(())
2125 })
2126 .unwrap_or_else(|error| match error {});
2127 }
2128}
2129
2130#[doc(hidden)]
2132pub fn resolve_navigation_value<V: AsRef<str>>(
2133 requested: &str,
2134 options: impl IntoIterator<Item = Option<V>>,
2135) -> Option<usize> {
2136 try_resolve_navigation_value(
2137 requested,
2138 options.into_iter().map(Ok::<_, std::convert::Infallible>),
2139 )
2140 .unwrap_or_else(|error| match error {})
2141}
2142
2143#[doc(hidden)]
2144pub fn try_resolve_navigation_value<V: AsRef<str>, E>(
2145 requested: &str,
2146 options: impl IntoIterator<Item = Result<Option<V>, E>>,
2147) -> Result<Option<usize>, E> {
2148 for (index, option) in options.into_iter().enumerate() {
2149 if option?.is_some_and(|value| value.as_ref() == requested) {
2150 return Ok(Some(index));
2151 }
2152 }
2153 Ok(None)
2154}
2155
2156#[doc(hidden)]
2158pub fn resolve_swipe_index(
2159 requested: Option<i64>,
2160 available: impl IntoIterator<Item = bool>,
2161) -> Option<usize> {
2162 try_resolve_swipe_index(
2163 requested,
2164 available.into_iter().map(Ok::<_, std::convert::Infallible>),
2165 )
2166 .unwrap_or_else(|error| match error {})
2167}
2168
2169#[doc(hidden)]
2170pub fn try_resolve_swipe_index<E>(
2171 requested: Option<i64>,
2172 available: impl IntoIterator<Item = Result<bool, E>>,
2173) -> Result<Option<usize>, E> {
2174 let requested = requested.and_then(|index| usize::try_from(index).ok());
2175 let mut first = None;
2176 for (index, available) in available.into_iter().enumerate() {
2177 if available? {
2178 if requested == Some(index) {
2179 return Ok(Some(index));
2180 }
2181 first.get_or_insert(index);
2182 }
2183 }
2184 Ok(first)
2185}
2186
2187#[cfg(test)]
2188mod tests {
2189 use super::*;
2190
2191 #[test]
2192 fn integer_steps_preserve_precision_and_handle_overflow() {
2193 let mut node = Node::new("SpinBox", None);
2194 node.properties.insert("value", (i64::MAX - 4).into());
2195 node.properties.insert("maximum", i64::MAX.into());
2196 node.properties.insert("step-size", 3_i64.into());
2197 assert_eq!(
2198 SpinRange::from_node(&node).apply(SpinAction::Increase),
2199 Some(i64::MAX - 1)
2200 );
2201 node.properties.insert("value", (i64::MAX - 1).into());
2202 assert_eq!(
2203 SpinRange::from_node(&node).apply(SpinAction::Increase),
2204 Some(i64::MAX)
2205 );
2206 node.properties.insert("wrap", true.into());
2207 assert_eq!(
2208 SpinRange::from_node(&node).apply(SpinAction::Increase),
2209 Some(0)
2210 );
2211 }
2212}