1use std::cell::RefCell;
2use std::collections::{BTreeSet, HashMap, VecDeque};
3use std::rc::Rc;
4use std::sync::Arc;
5
6use crate::access::AccessibilitySpec;
7use crate::artprov::IconRole;
8use crate::error::{GuiError, GuiResult};
9use crate::pickers::{ColorDialogData, FontDescriptor, FontDialogData};
10use crate::toolbar::{ToolbarItem, ToolbarOrientation};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub struct WidgetId(pub u64);
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
22pub struct GpuSurfaceCapabilities {
23 pub vulkan_surface: bool,
24 pub metal_surface: bool,
25 pub directx_surface: bool,
26 pub raw_window_handle: bool,
27 pub diagnostic_placeholder: bool,
28 pub headless_emulation: bool,
29}
30
31impl GpuSurfaceCapabilities {
32 pub const fn none() -> Self {
34 Self {
35 vulkan_surface: false,
36 metal_surface: false,
37 directx_surface: false,
38 raw_window_handle: false,
39 diagnostic_placeholder: false,
40 headless_emulation: false,
41 }
42 }
43
44 pub const fn all() -> Self {
46 Self {
47 vulkan_surface: true,
48 metal_surface: true,
49 directx_surface: true,
50 raw_window_handle: true,
51 diagnostic_placeholder: true,
52 headless_emulation: true,
53 }
54 }
55
56 pub fn supports(self, capability: &str) -> bool {
59 match capability {
60 "vulkan_surface" => self.vulkan_surface,
61 "metal_surface" => self.metal_surface,
62 "directx_surface" => self.directx_surface,
63 "raw_window_handle" => self.raw_window_handle,
64 "diagnostic_placeholder" => self.diagnostic_placeholder,
65 "headless_emulation" => self.headless_emulation,
66 "gpu_degradation_fallback" => self.diagnostic_placeholder || self.headless_emulation,
67 "gpu_surface" => self.vulkan_surface || self.metal_surface || self.directx_surface,
68 _ => false,
69 }
70 }
71}
72
73impl Default for GpuSurfaceCapabilities {
74 fn default() -> Self {
75 Self::none()
76 }
77}
78
79#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
81pub enum GpuDegradationPolicy {
82 #[default]
84 StrictFail,
85 DiagnosticPlaceholder,
87 Canvas2DFallback,
89}
90
91#[non_exhaustive]
93#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
94#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
95pub enum WidgetKind {
96 Window,
97 Container,
98 Label,
99 Button,
100 #[cfg(feature = "widgets-choice")]
101 RadioButton,
102 #[cfg(feature = "widgets-range")]
103 Slider,
104 #[cfg(feature = "widgets-range")]
105 SpinBox,
106 #[cfg(feature = "widgets-containers")]
107 Separator,
108 #[cfg(feature = "widgets-containers")]
109 GroupBox,
110 #[cfg(feature = "widgets-containers")]
111 Tabs,
112 #[cfg(feature = "widgets-media")]
113 Image,
114 #[cfg(feature = "widgets-pickers")]
115 DatePicker,
116 #[cfg(feature = "widgets-text")]
117 LinkLabel,
118 #[cfg(feature = "widgets-data")]
119 ListView,
120 #[cfg(feature = "widgets-data")]
121 TreeView,
122 #[cfg(feature = "widgets-containers")]
123 SplitPane,
124 #[cfg(feature = "widgets-pickers")]
125 FileChooserDialog,
126 #[cfg(feature = "widgets-containers")]
127 AlertDialog,
128 #[cfg(feature = "widgets-text")]
129 TextInput,
130 #[cfg(feature = "widgets-text")]
131 TextArea,
132 #[cfg(feature = "widgets-canvas")]
133 VulkanCanvas,
134 #[cfg(feature = "widgets-canvas")]
135 MetalCanvas,
137 #[cfg(feature = "widgets-choice")]
138 Checkbox,
139 #[cfg(feature = "widgets-choice")]
140 ComboBox,
141 #[cfg(feature = "widgets-range")]
142 ProgressBar,
143 #[cfg(feature = "widgets-data")]
144 DataList,
145 #[cfg(feature = "widgets-data")]
146 DataGrid,
147 #[cfg(feature = "widgets-canvas")]
148 Canvas,
149 #[cfg(feature = "widgets-pickers")]
152 ColorDialog,
153 #[cfg(feature = "widgets-pickers")]
156 FontDialog,
157 Toolbar,
161 #[cfg(feature = "widgets-pickers")]
163 Calendar,
164 #[cfg(feature = "widgets-text")]
166 RichText,
167 #[cfg(feature = "widgets-choice")]
169 MultiSelect,
170}
171
172pub const ALL_KINDS: &[WidgetKind] = &[
178 WidgetKind::Window,
179 WidgetKind::Container,
180 WidgetKind::Label,
181 WidgetKind::Button,
182 #[cfg(feature = "widgets-choice")]
183 WidgetKind::RadioButton,
184 #[cfg(feature = "widgets-range")]
185 WidgetKind::Slider,
186 #[cfg(feature = "widgets-range")]
187 WidgetKind::SpinBox,
188 #[cfg(feature = "widgets-containers")]
189 WidgetKind::Separator,
190 #[cfg(feature = "widgets-containers")]
191 WidgetKind::GroupBox,
192 #[cfg(feature = "widgets-containers")]
193 WidgetKind::Tabs,
194 #[cfg(feature = "widgets-media")]
195 WidgetKind::Image,
196 #[cfg(feature = "widgets-pickers")]
197 WidgetKind::DatePicker,
198 #[cfg(feature = "widgets-text")]
199 WidgetKind::LinkLabel,
200 #[cfg(feature = "widgets-data")]
201 WidgetKind::ListView,
202 #[cfg(feature = "widgets-data")]
203 WidgetKind::TreeView,
204 #[cfg(feature = "widgets-containers")]
205 WidgetKind::SplitPane,
206 #[cfg(feature = "widgets-pickers")]
207 WidgetKind::FileChooserDialog,
208 #[cfg(feature = "widgets-containers")]
209 WidgetKind::AlertDialog,
210 #[cfg(feature = "widgets-text")]
211 WidgetKind::TextInput,
212 #[cfg(feature = "widgets-text")]
213 WidgetKind::TextArea,
214 #[cfg(feature = "widgets-canvas")]
215 WidgetKind::VulkanCanvas,
216 #[cfg(feature = "widgets-canvas")]
217 WidgetKind::MetalCanvas,
218 #[cfg(feature = "widgets-choice")]
219 WidgetKind::Checkbox,
220 #[cfg(feature = "widgets-choice")]
221 WidgetKind::ComboBox,
222 #[cfg(feature = "widgets-range")]
223 WidgetKind::ProgressBar,
224 #[cfg(feature = "widgets-data")]
225 WidgetKind::DataList,
226 #[cfg(feature = "widgets-data")]
227 WidgetKind::DataGrid,
228 #[cfg(feature = "widgets-canvas")]
229 WidgetKind::Canvas,
230 #[cfg(feature = "widgets-pickers")]
231 WidgetKind::ColorDialog,
232 #[cfg(feature = "widgets-pickers")]
233 WidgetKind::FontDialog,
234 WidgetKind::Toolbar,
235 #[cfg(feature = "widgets-pickers")]
236 WidgetKind::Calendar,
237 #[cfg(feature = "widgets-text")]
238 WidgetKind::RichText,
239 #[cfg(feature = "widgets-choice")]
240 WidgetKind::MultiSelect,
241];
242
243#[non_exhaustive]
264#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
265pub enum WidgetProperty {
266 Checked,
268 Value,
270 Range,
272 Step,
274 SelectedIndex,
276 TabItems,
278 SelectedIndices,
280 RowDrag,
283 DataListItems,
285 ListViewColumns,
287 ListViewRows,
289 DataGridRows,
291 DataGridModel,
293 DataGridRowHeight,
295 DataGridColWidth,
297 DataGridFrozenPanes,
299 DataGridSelection,
301 TreeItems,
303 AlertLevel,
305 ImageSource,
307 ImageFit,
309 ButtonIcon,
312 FileChooserMode,
314 ColorDialogData,
316 FontDialogData,
318 ToolbarItems,
320 ToolbarOrientation,
322 DateValue,
324 LinkUrl,
326 TextSelection,
328 TextCompletion,
330 PlaceholderText,
332 ContainerDirection,
334 ContainerWrap,
336 ContainerScroll,
338 ContainerGap,
340 ContainerPadding,
343 CanvasScene,
345 CanvasSurface,
347 CloseGuard,
349 LayoutRoot,
351 WindowCallback,
353 NativeHandle,
355 DrawDemoCube,
357 CopyToClipboard,
360 PasteFromClipboard,
363 KeyedRows,
365 ClearSelection,
368 VisibleAnchor,
370 CalendarDates,
372 CalendarBounds,
374 CalendarFirstDayOfWeek,
376 CalendarSelectionMode,
378 LabelAlignment,
380 LabelWrap,
382 RichTextRuns,
384 RichTextImages,
386 Monospace,
388 MetalHandle,
390 Font,
392 RowIcons,
394}
395
396impl WidgetProperty {
397 pub const ALL: &'static [WidgetProperty] = &[
399 WidgetProperty::Checked,
400 WidgetProperty::Value,
401 WidgetProperty::Range,
402 WidgetProperty::Step,
403 WidgetProperty::SelectedIndex,
404 WidgetProperty::TabItems,
405 WidgetProperty::SelectedIndices,
406 WidgetProperty::RowDrag,
407 WidgetProperty::DataListItems,
408 WidgetProperty::ListViewColumns,
409 WidgetProperty::ListViewRows,
410 WidgetProperty::DataGridRows,
411 WidgetProperty::DataGridModel,
412 WidgetProperty::DataGridRowHeight,
413 WidgetProperty::DataGridColWidth,
414 WidgetProperty::DataGridFrozenPanes,
415 WidgetProperty::DataGridSelection,
416 WidgetProperty::TreeItems,
417 WidgetProperty::AlertLevel,
418 WidgetProperty::ImageSource,
419 WidgetProperty::ImageFit,
420 WidgetProperty::ButtonIcon,
421 WidgetProperty::FileChooserMode,
422 WidgetProperty::ColorDialogData,
423 WidgetProperty::FontDialogData,
424 WidgetProperty::ToolbarItems,
425 WidgetProperty::ToolbarOrientation,
426 WidgetProperty::DateValue,
427 WidgetProperty::LinkUrl,
428 WidgetProperty::TextSelection,
429 WidgetProperty::TextCompletion,
430 WidgetProperty::ContainerDirection,
431 WidgetProperty::ContainerWrap,
432 WidgetProperty::ContainerScroll,
433 WidgetProperty::ContainerGap,
434 WidgetProperty::ContainerPadding,
435 WidgetProperty::CanvasScene,
436 WidgetProperty::CanvasSurface,
437 WidgetProperty::CloseGuard,
438 WidgetProperty::LayoutRoot,
439 WidgetProperty::WindowCallback,
440 WidgetProperty::NativeHandle,
441 WidgetProperty::DrawDemoCube,
442 WidgetProperty::CopyToClipboard,
443 WidgetProperty::PasteFromClipboard,
444 WidgetProperty::KeyedRows,
445 WidgetProperty::ClearSelection,
446 WidgetProperty::VisibleAnchor,
447 WidgetProperty::CalendarDates,
448 WidgetProperty::CalendarBounds,
449 WidgetProperty::CalendarFirstDayOfWeek,
450 WidgetProperty::CalendarSelectionMode,
451 WidgetProperty::LabelAlignment,
452 WidgetProperty::LabelWrap,
453 WidgetProperty::RichTextRuns,
454 WidgetProperty::PlaceholderText,
455 WidgetProperty::RichTextImages,
456 WidgetProperty::Monospace,
457 WidgetProperty::MetalHandle,
458 WidgetProperty::Font,
459 WidgetProperty::RowIcons,
460 ];
461
462 pub const fn applicable_kinds(self) -> &'static [WidgetKind] {
465 match self {
466 #[cfg(feature = "widgets-choice")]
467 WidgetProperty::Checked => &[WidgetKind::Checkbox, WidgetKind::RadioButton],
468 #[cfg(not(feature = "widgets-choice"))]
469 WidgetProperty::Checked => &[],
470 #[cfg(feature = "widgets-range")]
471 WidgetProperty::Value => &[
472 WidgetKind::Slider,
473 WidgetKind::SpinBox,
474 WidgetKind::ProgressBar,
475 ],
476 #[cfg(not(feature = "widgets-range"))]
477 WidgetProperty::Value => &[],
478 #[cfg(feature = "widgets-range")]
479 WidgetProperty::Range | WidgetProperty::Step => {
480 &[WidgetKind::Slider, WidgetKind::SpinBox]
481 }
482 #[cfg(not(feature = "widgets-range"))]
483 WidgetProperty::Range | WidgetProperty::Step => &[],
484 WidgetProperty::SelectedIndex => {
485 const KINDS: &[WidgetKind] = &[
486 #[cfg(feature = "widgets-containers")]
487 WidgetKind::Tabs,
488 #[cfg(feature = "widgets-choice")]
489 WidgetKind::ComboBox,
490 #[cfg(feature = "widgets-data")]
491 WidgetKind::DataList,
492 #[cfg(feature = "widgets-data")]
493 WidgetKind::ListView,
494 ];
495 KINDS
496 }
497 #[cfg(feature = "widgets-containers")]
498 WidgetProperty::TabItems => &[WidgetKind::Tabs],
499 #[cfg(not(feature = "widgets-containers"))]
500 WidgetProperty::TabItems => &[],
501 #[cfg(all(feature = "widgets-choice", feature = "widgets-data"))]
502 WidgetProperty::SelectedIndices => &[
503 WidgetKind::ListView,
504 WidgetKind::DataList,
505 WidgetKind::TreeView,
506 WidgetKind::MultiSelect,
507 ],
508 #[cfg(all(feature = "widgets-choice", not(feature = "widgets-data")))]
509 WidgetProperty::SelectedIndices => &[WidgetKind::MultiSelect],
510 #[cfg(all(not(feature = "widgets-choice"), feature = "widgets-data"))]
511 WidgetProperty::SelectedIndices => &[
512 WidgetKind::ListView,
513 WidgetKind::DataList,
514 WidgetKind::TreeView,
515 ],
516 #[cfg(all(not(feature = "widgets-choice"), not(feature = "widgets-data")))]
517 WidgetProperty::SelectedIndices => &[],
518 #[cfg(feature = "widgets-data")]
519 WidgetProperty::RowDrag => &[
520 WidgetKind::ListView,
521 WidgetKind::DataList,
522 WidgetKind::DataGrid,
523 WidgetKind::TreeView,
524 ],
525 #[cfg(not(feature = "widgets-data"))]
526 WidgetProperty::RowDrag => &[],
527 #[cfg(all(feature = "widgets-choice", feature = "widgets-data"))]
528 WidgetProperty::DataListItems => &[
529 WidgetKind::DataList,
530 WidgetKind::ListView,
531 WidgetKind::MultiSelect,
532 ],
533 #[cfg(all(feature = "widgets-choice", not(feature = "widgets-data")))]
534 WidgetProperty::DataListItems => &[WidgetKind::MultiSelect],
535 #[cfg(all(not(feature = "widgets-choice"), feature = "widgets-data"))]
536 WidgetProperty::DataListItems => &[WidgetKind::DataList, WidgetKind::ListView],
537 #[cfg(all(not(feature = "widgets-choice"), not(feature = "widgets-data")))]
538 WidgetProperty::DataListItems => &[],
539 #[cfg(feature = "widgets-data")]
540 WidgetProperty::ListViewColumns | WidgetProperty::ListViewRows => {
541 &[WidgetKind::ListView]
542 }
543 #[cfg(not(feature = "widgets-data"))]
544 WidgetProperty::ListViewColumns | WidgetProperty::ListViewRows => &[],
545 #[cfg(feature = "widgets-data")]
546 WidgetProperty::DataGridRows
547 | WidgetProperty::DataGridModel
548 | WidgetProperty::DataGridRowHeight
549 | WidgetProperty::DataGridColWidth
550 | WidgetProperty::DataGridFrozenPanes
551 | WidgetProperty::DataGridSelection => &[WidgetKind::DataGrid],
552 #[cfg(not(feature = "widgets-data"))]
553 WidgetProperty::DataGridRows
554 | WidgetProperty::DataGridModel
555 | WidgetProperty::DataGridRowHeight
556 | WidgetProperty::DataGridColWidth
557 | WidgetProperty::DataGridFrozenPanes
558 | WidgetProperty::DataGridSelection => &[],
559 #[cfg(feature = "widgets-data")]
560 WidgetProperty::TreeItems => &[WidgetKind::TreeView],
561 #[cfg(not(feature = "widgets-data"))]
562 WidgetProperty::TreeItems => &[],
563 #[cfg(feature = "widgets-containers")]
564 WidgetProperty::AlertLevel => &[WidgetKind::AlertDialog],
565 #[cfg(not(feature = "widgets-containers"))]
566 WidgetProperty::AlertLevel => &[],
567 #[cfg(feature = "widgets-media")]
568 WidgetProperty::ImageSource | WidgetProperty::ImageFit => &[WidgetKind::Image],
569 #[cfg(not(feature = "widgets-media"))]
570 WidgetProperty::ImageSource | WidgetProperty::ImageFit => &[],
571 #[cfg(feature = "widgets-pickers")]
572 WidgetProperty::ButtonIcon => &[WidgetKind::Button, WidgetKind::FileChooserDialog],
573 #[cfg(not(feature = "widgets-pickers"))]
574 WidgetProperty::ButtonIcon => &[WidgetKind::Button],
575 #[cfg(feature = "widgets-pickers")]
576 WidgetProperty::FileChooserMode => &[WidgetKind::FileChooserDialog],
577 #[cfg(not(feature = "widgets-pickers"))]
578 WidgetProperty::FileChooserMode => &[],
579 #[cfg(feature = "widgets-pickers")]
580 WidgetProperty::ColorDialogData => &[WidgetKind::ColorDialog],
581 #[cfg(not(feature = "widgets-pickers"))]
582 WidgetProperty::ColorDialogData => &[],
583 #[cfg(feature = "widgets-pickers")]
584 WidgetProperty::FontDialogData => &[WidgetKind::FontDialog],
585 #[cfg(not(feature = "widgets-pickers"))]
586 WidgetProperty::FontDialogData => &[],
587 WidgetProperty::ToolbarItems | WidgetProperty::ToolbarOrientation => {
588 &[WidgetKind::Toolbar]
589 }
590 #[cfg(feature = "widgets-pickers")]
591 WidgetProperty::DateValue => &[WidgetKind::DatePicker],
592 #[cfg(not(feature = "widgets-pickers"))]
593 WidgetProperty::DateValue => &[],
594 #[cfg(feature = "widgets-text")]
595 WidgetProperty::LinkUrl => &[WidgetKind::LinkLabel],
596 #[cfg(not(feature = "widgets-text"))]
597 WidgetProperty::LinkUrl => &[],
598 #[cfg(feature = "widgets-text")]
599 WidgetProperty::TextSelection => &[
600 WidgetKind::TextInput,
601 WidgetKind::TextArea,
602 WidgetKind::RichText,
603 ],
604 #[cfg(not(feature = "widgets-text"))]
605 WidgetProperty::TextSelection => &[],
606 #[cfg(feature = "widgets-text")]
607 WidgetProperty::TextCompletion => &[WidgetKind::TextInput],
608 #[cfg(not(feature = "widgets-text"))]
609 WidgetProperty::TextCompletion => &[],
610 WidgetProperty::ContainerDirection
611 | WidgetProperty::ContainerWrap
612 | WidgetProperty::ContainerScroll => {
613 const KINDS: &[WidgetKind] = &[
614 WidgetKind::Container,
615 #[cfg(feature = "widgets-containers")]
616 WidgetKind::GroupBox,
617 #[cfg(feature = "widgets-containers")]
618 WidgetKind::SplitPane,
619 ];
620 KINDS
621 }
622 WidgetProperty::ContainerGap | WidgetProperty::ContainerPadding => {
623 const KINDS: &[WidgetKind] = &[
624 WidgetKind::Container,
625 #[cfg(feature = "widgets-containers")]
626 WidgetKind::GroupBox,
627 ];
628 KINDS
629 }
630 #[cfg(feature = "widgets-canvas")]
631 WidgetProperty::CanvasScene | WidgetProperty::CanvasSurface => &[WidgetKind::Canvas],
632 #[cfg(not(feature = "widgets-canvas"))]
633 WidgetProperty::CanvasScene | WidgetProperty::CanvasSurface => &[],
634 WidgetProperty::CloseGuard
635 | WidgetProperty::LayoutRoot
636 | WidgetProperty::WindowCallback => &[WidgetKind::Window],
637 #[cfg(feature = "widgets-canvas")]
638 WidgetProperty::NativeHandle => &[WidgetKind::VulkanCanvas],
639 #[cfg(not(feature = "widgets-canvas"))]
640 WidgetProperty::NativeHandle => &[],
641 #[cfg(feature = "widgets-canvas")]
642 WidgetProperty::DrawDemoCube => &[WidgetKind::VulkanCanvas, WidgetKind::MetalCanvas],
643 #[cfg(not(feature = "widgets-canvas"))]
644 WidgetProperty::DrawDemoCube => &[],
645 WidgetProperty::CopyToClipboard | WidgetProperty::PasteFromClipboard => {
646 const KINDS: &[WidgetKind] = &[
647 #[cfg(feature = "widgets-data")]
648 WidgetKind::DataList,
649 #[cfg(feature = "widgets-data")]
650 WidgetKind::ListView,
651 #[cfg(feature = "widgets-data")]
652 WidgetKind::DataGrid,
653 #[cfg(feature = "widgets-text")]
654 WidgetKind::TextInput,
655 #[cfg(feature = "widgets-text")]
656 WidgetKind::TextArea,
657 WidgetKind::Label,
658 ];
659 KINDS
660 }
661 #[cfg(feature = "widgets-data")]
662 WidgetProperty::KeyedRows | WidgetProperty::VisibleAnchor => &[
663 WidgetKind::DataList,
664 WidgetKind::ListView,
665 WidgetKind::DataGrid,
666 ],
667 #[cfg(not(feature = "widgets-data"))]
668 WidgetProperty::KeyedRows | WidgetProperty::VisibleAnchor => &[],
669 #[cfg(feature = "widgets-data")]
670 WidgetProperty::ClearSelection => &[
671 WidgetKind::DataList,
672 WidgetKind::ListView,
673 WidgetKind::DataGrid,
674 WidgetKind::TreeView,
675 ],
676 #[cfg(not(feature = "widgets-data"))]
677 WidgetProperty::ClearSelection => &[],
678 #[cfg(feature = "widgets-pickers")]
679 WidgetProperty::CalendarDates
680 | WidgetProperty::CalendarBounds
681 | WidgetProperty::CalendarFirstDayOfWeek
682 | WidgetProperty::CalendarSelectionMode => &[WidgetKind::Calendar],
683 #[cfg(not(feature = "widgets-pickers"))]
684 WidgetProperty::CalendarDates
685 | WidgetProperty::CalendarBounds
686 | WidgetProperty::CalendarFirstDayOfWeek
687 | WidgetProperty::CalendarSelectionMode => &[],
688 WidgetProperty::LabelAlignment => &[WidgetKind::Label, WidgetKind::Button],
689 WidgetProperty::LabelWrap => &[WidgetKind::Label],
690 #[cfg(feature = "widgets-text")]
691 WidgetProperty::RichTextRuns | WidgetProperty::RichTextImages => {
692 &[WidgetKind::RichText]
693 }
694 #[cfg(not(feature = "widgets-text"))]
695 WidgetProperty::RichTextRuns | WidgetProperty::RichTextImages => &[],
696 #[cfg(feature = "widgets-text")]
697 WidgetProperty::PlaceholderText => &[WidgetKind::TextInput],
698 #[cfg(not(feature = "widgets-text"))]
699 WidgetProperty::PlaceholderText => &[],
700 WidgetProperty::Monospace => {
701 const KINDS: &[WidgetKind] = &[
702 WidgetKind::Label,
703 #[cfg(feature = "widgets-text")]
704 WidgetKind::TextArea,
705 #[cfg(feature = "widgets-text")]
706 WidgetKind::TextInput,
707 #[cfg(feature = "widgets-text")]
708 WidgetKind::RichText,
709 ];
710 KINDS
711 }
712 #[cfg(feature = "widgets-canvas")]
713 WidgetProperty::MetalHandle => &[WidgetKind::MetalCanvas],
714 #[cfg(not(feature = "widgets-canvas"))]
715 WidgetProperty::MetalHandle => &[],
716 WidgetProperty::Font => {
717 const KINDS: &[WidgetKind] = &[
718 WidgetKind::Label,
719 WidgetKind::Button,
720 #[cfg(feature = "widgets-text")]
721 WidgetKind::TextInput,
722 #[cfg(feature = "widgets-text")]
723 WidgetKind::TextArea,
724 ];
725 KINDS
726 }
727 #[cfg(feature = "widgets-data")]
728 WidgetProperty::RowIcons => &[WidgetKind::DataList, WidgetKind::ListView],
729 #[cfg(not(feature = "widgets-data"))]
730 WidgetProperty::RowIcons => &[],
731 }
732 }
733
734 pub const fn operation(self) -> &'static str {
737 match self {
738 WidgetProperty::Checked => "set_checked",
739 WidgetProperty::Value => "set_value",
740 WidgetProperty::Range => "set_range",
741 WidgetProperty::Step => "set_step",
742 WidgetProperty::SelectedIndex => "set_selected_index",
743 WidgetProperty::TabItems => "set_tab_items",
744 WidgetProperty::SelectedIndices => "set_selected_indices",
745 WidgetProperty::RowDrag => "set_row_drag",
746 WidgetProperty::DataListItems => "set_data_list_items",
747 WidgetProperty::ListViewColumns => "set_list_columns",
748 WidgetProperty::ListViewRows => "set_list_rows",
749 WidgetProperty::DataGridRows => "set_data_grid_rows",
750 WidgetProperty::DataGridModel => "set_data_grid_model",
751 WidgetProperty::DataGridRowHeight => "set_data_grid_row_height",
752 WidgetProperty::DataGridColWidth => "set_data_grid_col_width",
753 WidgetProperty::DataGridFrozenPanes => "set_data_grid_frozen_panes",
754 WidgetProperty::DataGridSelection => "set_data_grid_selection",
755 WidgetProperty::TreeItems => "set_tree_items",
756 WidgetProperty::AlertLevel => "set_alert_level",
757 WidgetProperty::ImageSource => "set_image_source",
758 WidgetProperty::ImageFit => "set_image_fit",
759 WidgetProperty::ButtonIcon => "set_icon",
760 WidgetProperty::FileChooserMode => "set_file_chooser_mode",
761 WidgetProperty::ColorDialogData => "set_color_dialog_data",
762 WidgetProperty::FontDialogData => "set_font_dialog_data",
763 WidgetProperty::ToolbarItems => "set_toolbar_items",
764 WidgetProperty::ToolbarOrientation => "set_toolbar_orientation",
765 WidgetProperty::DateValue => "set_date_value",
766 WidgetProperty::LinkUrl => "set_link_url",
767 WidgetProperty::TextSelection => "set_text_selection",
768 WidgetProperty::TextCompletion => "set_text_completion_items",
769 WidgetProperty::ContainerDirection => "set_container_direction",
770 WidgetProperty::ContainerWrap => "set_container_wrap",
771 WidgetProperty::ContainerScroll => "set_container_scroll",
772 WidgetProperty::ContainerGap => "set_container_gap",
773 WidgetProperty::ContainerPadding => "set_container_padding",
774 WidgetProperty::CanvasScene => "set_canvas_scene",
775 WidgetProperty::CanvasSurface => "set_canvas_surface",
776 WidgetProperty::CloseGuard => "set_close_guard",
777 WidgetProperty::LayoutRoot => "set_layout_root",
778 WidgetProperty::WindowCallback => "window_callback",
779 WidgetProperty::NativeHandle => "native_handle",
780 WidgetProperty::DrawDemoCube => "draw_demo_cube",
781 WidgetProperty::CopyToClipboard => "copy_to_clipboard",
782 WidgetProperty::PasteFromClipboard => "paste_from_clipboard",
783 WidgetProperty::KeyedRows => "set_rows_keyed",
784 WidgetProperty::ClearSelection => "clear_selection",
785 WidgetProperty::VisibleAnchor => "visible_anchor",
786 WidgetProperty::CalendarDates => "set_calendar_selected_dates",
787 WidgetProperty::CalendarBounds => "set_calendar_bounds",
788 WidgetProperty::CalendarFirstDayOfWeek => "set_calendar_first_day_of_week",
789 WidgetProperty::CalendarSelectionMode => "set_calendar_selection_mode",
790 WidgetProperty::LabelAlignment => "set_label_alignment",
791 WidgetProperty::LabelWrap => "set_label_wrap",
792 WidgetProperty::RichTextRuns => "set_rich_text_runs",
793 WidgetProperty::PlaceholderText => "set_placeholder_text",
794 WidgetProperty::RichTextImages => "set_rich_text_images",
795 WidgetProperty::Monospace => "set_monospace",
796 WidgetProperty::MetalHandle => "metal_canvas_handle",
797 WidgetProperty::Font => "set_font",
798 WidgetProperty::RowIcons => "set_row_icons",
799 }
800 }
801
802 pub const fn name(self) -> &'static str {
804 self.operation()
805 }
806
807 pub fn supports(self, kind: WidgetKind) -> bool {
809 self.applicable_kinds().contains(&kind)
810 }
811}
812
813impl WidgetKind {
814 pub fn requires_property(self, property: WidgetProperty) -> bool {
816 property.supports(self)
817 }
818
819 pub fn is_window_like(self) -> bool {
821 match self {
822 WidgetKind::Window => true,
823 #[cfg(feature = "widgets-pickers")]
824 WidgetKind::FileChooserDialog | WidgetKind::ColorDialog | WidgetKind::FontDialog => {
825 true
826 }
827 #[cfg(feature = "widgets-containers")]
828 WidgetKind::AlertDialog => true,
829 _ => false,
830 }
831 }
832
833 pub fn is_dialog(self) -> bool {
835 match self {
836 #[cfg(feature = "widgets-pickers")]
837 WidgetKind::FileChooserDialog | WidgetKind::ColorDialog | WidgetKind::FontDialog => {
838 true
839 }
840 #[cfg(feature = "widgets-containers")]
841 WidgetKind::AlertDialog => true,
842 _ => false,
843 }
844 }
845}
846
847#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
849#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
850pub struct CalendarDate {
851 pub year: i32,
852 pub month: u32,
853 pub day: u32,
854}
855
856impl CalendarDate {
857 pub const fn new(year: i32, month: u32, day: u32) -> Self {
859 Self { year, month, day }
860 }
861
862 pub fn is_valid(&self) -> bool {
864 if self.year == 0 || self.month < 1 || self.month > 12 {
865 return false;
866 }
867 let max_days = Self::days_in_month(self.year, self.month);
868 self.day >= 1 && self.day <= max_days
869 }
870
871 pub const fn is_leap_year(year: i32) -> bool {
873 (year % 4 == 0 && year % 100 != 0) || (year % 400 == 0)
874 }
875
876 pub const fn days_in_month(year: i32, month: u32) -> u32 {
878 match month {
879 1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
880 4 | 6 | 9 | 11 => 30,
881 2 => {
882 if Self::is_leap_year(year) {
883 29
884 } else {
885 28
886 }
887 }
888 _ => 0,
889 }
890 }
891}
892
893#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
895#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
896pub enum CalendarFirstDayOfWeek {
897 #[default]
899 LocaleDefault,
900 Sunday,
902 Monday,
904}
905
906#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
908#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
909pub enum CalendarSelectionMode {
910 #[default]
912 Single,
913 Range,
915 Multiple,
917}
918
919#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
921#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
922pub enum LabelAlignment {
923 #[default]
925 Left,
926 Center,
928 Right,
930}
931
932#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
934#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
935pub enum LabelWrap {
936 #[default]
938 None,
939 Word,
941 Char,
943 WordChar,
945}
946
947pub type LabelWrapMode = LabelWrap;
949
950impl LabelWrap {
951 pub const NO_WRAP: Self = Self::None;
953
954 #[allow(non_upper_case_globals)]
956 pub const NoWrap: Self = Self::None;
957
958 pub const fn is_wrapping(self) -> bool {
960 !matches!(self, Self::None)
961 }
962}
963
964impl From<bool> for LabelWrap {
965 fn from(wrap: bool) -> Self {
966 if wrap {
967 Self::Word
968 } else {
969 Self::None
970 }
971 }
972}
973
974impl From<TextAlignment> for LabelAlignment {
975 fn from(alignment: TextAlignment) -> Self {
976 match alignment {
977 TextAlignment::Left => Self::Left,
978 TextAlignment::Center => Self::Center,
979 TextAlignment::Right => Self::Right,
980 }
981 }
982}
983
984impl From<LabelAlignment> for TextAlignment {
985 fn from(alignment: LabelAlignment) -> Self {
986 match alignment {
987 LabelAlignment::Left => Self::Left,
988 LabelAlignment::Center => Self::Center,
989 LabelAlignment::Right => Self::Right,
990 }
991 }
992}
993
994#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
996#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
997pub enum ContainerDirection {
998 Vertical,
1000 Horizontal,
1002}
1003
1004#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1006#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1007pub enum ContainerWrap {
1008 #[default]
1010 NoWrap,
1011 Wrap,
1013 WrapReverse,
1015}
1016
1017#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1019#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1020pub enum AlertLevel {
1021 Info,
1022 Warning,
1023 Error,
1024}
1025
1026#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1031#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1032pub enum ImageFit {
1033 #[default]
1035 Contain,
1036 Cover,
1038 Fill,
1040 None,
1042}
1043
1044impl ImageFit {
1045 pub const fn as_str(self) -> &'static str {
1047 match self {
1048 Self::Contain => "contain",
1049 Self::Cover => "cover",
1050 Self::Fill => "fill",
1051 Self::None => "none",
1052 }
1053 }
1054}
1055
1056#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
1058#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1059pub enum FileChooserMode {
1060 #[default]
1062 OpenFile,
1063 PickFolder,
1065 SaveFile,
1067}
1068
1069impl FileChooserMode {
1070 pub const fn as_str(self) -> &'static str {
1072 match self {
1073 Self::OpenFile => "open-file",
1074 Self::PickFolder => "pick-folder",
1075 Self::SaveFile => "save-file",
1076 }
1077 }
1078}
1079
1080#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1082#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1083pub struct Color {
1084 pub r: u8,
1085 pub g: u8,
1086 pub b: u8,
1087}
1088
1089impl Color {
1090 pub const fn rgb(r: u8, g: u8, b: u8) -> Self {
1092 Self { r, g, b }
1093 }
1094}
1095
1096#[derive(Debug, Clone, PartialEq, Default)]
1098#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1099pub struct TextStyle {
1100 pub bold: bool,
1101 pub italic: bool,
1102 pub underline: bool,
1103 pub strikethrough: bool,
1104 pub monospace: bool,
1105 pub scale: Option<f32>,
1106 pub fg_color: Option<Color>,
1107 pub bg_color: Option<Color>,
1108 pub link: Option<String>,
1109 pub dimmed: bool,
1110 pub paragraph_indent: u32,
1111}
1112
1113impl TextStyle {
1114 pub const fn new() -> Self {
1116 Self {
1117 bold: false,
1118 italic: false,
1119 underline: false,
1120 strikethrough: false,
1121 monospace: false,
1122 scale: None,
1123 fg_color: None,
1124 bg_color: None,
1125 link: None,
1126 dimmed: false,
1127 paragraph_indent: 0,
1128 }
1129 }
1130
1131 pub const fn bold(mut self, bold: bool) -> Self {
1133 self.bold = bold;
1134 self
1135 }
1136
1137 pub const fn italic(mut self, italic: bool) -> Self {
1139 self.italic = italic;
1140 self
1141 }
1142
1143 pub const fn underline(mut self, underline: bool) -> Self {
1145 self.underline = underline;
1146 self
1147 }
1148
1149 pub const fn strikethrough(mut self, strikethrough: bool) -> Self {
1151 self.strikethrough = strikethrough;
1152 self
1153 }
1154
1155 pub const fn monospace(mut self, monospace: bool) -> Self {
1157 self.monospace = monospace;
1158 self
1159 }
1160
1161 pub const fn scale(mut self, scale: f32) -> Self {
1163 self.scale = Some(scale);
1164 self
1165 }
1166
1167 pub const fn fg_color(mut self, color: Color) -> Self {
1169 self.fg_color = Some(color);
1170 self
1171 }
1172
1173 pub const fn bg_color(mut self, color: Color) -> Self {
1175 self.bg_color = Some(color);
1176 self
1177 }
1178
1179 pub fn link(mut self, link: impl Into<String>) -> Self {
1181 self.link = Some(link.into());
1182 self
1183 }
1184
1185 pub const fn dimmed(mut self, dimmed: bool) -> Self {
1187 self.dimmed = dimmed;
1188 self
1189 }
1190
1191 pub const fn paragraph_indent(mut self, indent: u32) -> Self {
1193 self.paragraph_indent = indent;
1194 self
1195 }
1196}
1197
1198#[derive(Debug, Clone, PartialEq, Default)]
1200#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1201pub struct TextRun {
1202 pub range: std::ops::Range<usize>,
1203 pub style: TextStyle,
1204}
1205
1206impl TextRun {
1207 pub fn new(range: std::ops::Range<usize>, style: TextStyle) -> Self {
1209 Self { range, style }
1210 }
1211}
1212
1213#[derive(Debug, Clone, PartialEq, Eq)]
1215#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1216pub struct RichTextImage {
1217 pub offset: usize,
1218 pub source: String,
1219 pub max_width: Option<u32>,
1220}
1221
1222impl RichTextImage {
1223 pub fn new(offset: usize, source: impl Into<String>, max_width: Option<u32>) -> Self {
1225 Self {
1226 offset,
1227 source: source.into(),
1228 max_width,
1229 }
1230 }
1231}
1232
1233#[derive(Debug, Clone, PartialEq, Eq)]
1235#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1236pub struct ClipboardImage {
1237 pub width: u32,
1238 pub height: u32,
1239 pub rgba: Vec<u8>,
1241 pub png_bytes: Vec<u8>,
1243}
1244
1245impl ClipboardImage {
1246 pub fn new(width: u32, height: u32, rgba: Vec<u8>) -> Self {
1248 let png_bytes = encode_rgba_to_png(width, height, &rgba);
1249 Self {
1250 width,
1251 height,
1252 rgba,
1253 png_bytes,
1254 }
1255 }
1256
1257 pub fn with_png(width: u32, height: u32, rgba: Vec<u8>, png_bytes: Vec<u8>) -> Self {
1259 Self {
1260 width,
1261 height,
1262 rgba,
1263 png_bytes,
1264 }
1265 }
1266}
1267
1268pub fn encode_rgba_to_png(width: u32, height: u32, rgba: &[u8]) -> Vec<u8> {
1270 fn crc32(data: &[u8]) -> u32 {
1271 let mut crc = 0xFFFF_FFFFu32;
1272 for &byte in data {
1273 crc ^= u32::from(byte);
1274 for _ in 0..8 {
1275 let mask = (crc & 1).wrapping_neg();
1276 crc = (crc >> 1) ^ (0xEDB8_8320 & mask);
1277 }
1278 }
1279 !crc
1280 }
1281
1282 fn adler32(data: &[u8]) -> u32 {
1283 let mut s1 = 1u32;
1284 let mut s2 = 0u32;
1285 for &byte in data {
1286 s1 = (s1 + u32::from(byte)) % 65521;
1287 s2 = (s2 + s1) % 65521;
1288 }
1289 (s2 << 16) | s1
1290 }
1291
1292 let mut out = Vec::new();
1293 out.extend_from_slice(b"\x89PNG\r\n\x1a\n");
1294
1295 let mut ihdr = Vec::with_capacity(13);
1297 ihdr.extend_from_slice(&width.to_be_bytes());
1298 ihdr.extend_from_slice(&height.to_be_bytes());
1299 ihdr.push(8); ihdr.push(6); ihdr.push(0); ihdr.push(0); ihdr.push(0); let mut ihdr_chunk = Vec::new();
1306 ihdr_chunk.extend_from_slice(b"IHDR");
1307 ihdr_chunk.extend_from_slice(&ihdr);
1308 let ihdr_crc = crc32(&ihdr_chunk);
1309
1310 out.extend_from_slice(&(ihdr.len() as u32).to_be_bytes());
1311 out.extend_from_slice(&ihdr_chunk);
1312 out.extend_from_slice(&ihdr_crc.to_be_bytes());
1313
1314 let w_bytes = (width as usize) * 4;
1316 let mut raw = Vec::with_capacity((height as usize) * (w_bytes + 1));
1317 for y in 0..(height as usize) {
1318 raw.push(0); let start = y * w_bytes;
1320 let end = (start + w_bytes).min(rgba.len());
1321 if start < rgba.len() {
1322 raw.extend_from_slice(&rgba[start..end]);
1323 if end - start < w_bytes {
1324 raw.resize(raw.len() + (w_bytes - (end - start)), 0);
1325 }
1326 } else {
1327 raw.resize(raw.len() + w_bytes, 0);
1328 }
1329 }
1330
1331 let mut zlib = Vec::new();
1333 zlib.push(0x78);
1334 zlib.push(0x01);
1335
1336 let chunks: Vec<&[u8]> = if raw.is_empty() {
1337 vec![&[]]
1338 } else {
1339 raw.chunks(65535).collect()
1340 };
1341 let total_chunks = chunks.len();
1342 for (i, chunk) in chunks.iter().enumerate() {
1343 let is_final = i == total_chunks - 1;
1344 let header = if is_final { 0x01 } else { 0x00 };
1345 zlib.push(header);
1346 let len = chunk.len() as u16;
1347 let nlen = !len;
1348 zlib.extend_from_slice(&len.to_le_bytes());
1349 zlib.extend_from_slice(&nlen.to_le_bytes());
1350 zlib.extend_from_slice(chunk);
1351 }
1352 let adler = adler32(&raw);
1353 zlib.extend_from_slice(&adler.to_be_bytes());
1354
1355 let mut idat_chunk = Vec::new();
1357 idat_chunk.extend_from_slice(b"IDAT");
1358 idat_chunk.extend_from_slice(&zlib);
1359 let idat_crc = crc32(&idat_chunk);
1360
1361 out.extend_from_slice(&(zlib.len() as u32).to_be_bytes());
1362 out.extend_from_slice(&idat_chunk);
1363 out.extend_from_slice(&idat_crc.to_be_bytes());
1364
1365 let mut iend_chunk = Vec::new();
1367 iend_chunk.extend_from_slice(b"IEND");
1368 let iend_crc = crc32(&iend_chunk);
1369
1370 out.extend_from_slice(&0u32.to_be_bytes());
1371 out.extend_from_slice(&iend_chunk);
1372 out.extend_from_slice(&iend_crc.to_be_bytes());
1373
1374 out
1375}
1376
1377#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1379pub struct CanvasRect {
1380 pub x: i32,
1381 pub y: i32,
1382 pub width: i32,
1383 pub height: i32,
1384}
1385
1386#[derive(Debug, Clone, PartialEq, Eq)]
1396pub struct CanvasSurface {
1397 width: u32,
1398 height: u32,
1399 pixels: Arc<Vec<u8>>,
1400}
1401
1402impl CanvasSurface {
1403 pub fn from_rgba(width: u32, height: u32, pixels: Vec<u8>) -> Result<Self, GuiError> {
1405 if width == 0 || height == 0 {
1406 return Err(GuiError::Backend(
1407 "canvas surface dimensions must be non-zero".to_owned(),
1408 ));
1409 }
1410 let expected = width as usize * height as usize * 4;
1411 if pixels.len() != expected {
1412 return Err(GuiError::Backend(format!(
1413 "canvas surface expects {expected} bytes, found {}",
1414 pixels.len()
1415 )));
1416 }
1417 Ok(Self {
1418 width,
1419 height,
1420 pixels: Arc::new(pixels),
1421 })
1422 }
1423
1424 pub fn width(&self) -> u32 {
1426 self.width
1427 }
1428
1429 pub fn height(&self) -> u32 {
1431 self.height
1432 }
1433
1434 pub fn pixels(&self) -> &[u8] {
1436 &self.pixels
1437 }
1438}
1439
1440#[derive(Debug, Clone, PartialEq)]
1442pub struct CanvasScene {
1443 pub primitives: Vec<CanvasPrimitive>,
1444 pub logical_width: f32,
1445 pub logical_height: f32,
1446}
1447
1448impl CanvasScene {
1449 pub fn new(logical_width: f32, logical_height: f32) -> Self {
1450 Self {
1451 primitives: Vec::new(),
1452 logical_width,
1453 logical_height,
1454 }
1455 }
1456
1457 pub fn validate(&self) -> GuiResult<()> {
1459 let invalid = !self.logical_width.is_finite()
1460 || !self.logical_height.is_finite()
1461 || self.logical_width <= 0.0
1462 || self.logical_height <= 0.0;
1463
1464 if invalid {
1465 return Err(GuiError::Backend(
1466 "Canvas scene logical size must be finite and positive".to_owned(),
1467 ));
1468 }
1469 Ok(())
1470 }
1471}
1472
1473#[derive(Debug, Clone, PartialEq, Eq)]
1475pub enum CanvasPrimitive {
1476 Rect {
1477 rect: CanvasRect,
1478 fill: Option<Color>,
1479 stroke: Option<Color>,
1480 stroke_width: u8,
1481 },
1482 Line {
1483 from: (i32, i32),
1484 to: (i32, i32),
1485 color: Color,
1486 width: u8,
1487 },
1488 Text {
1491 pos: (i32, i32),
1492 text: String,
1493 color: Color,
1494 size: u8,
1495 },
1496 Image {
1497 rect: CanvasRect,
1498 source: String,
1499 },
1500}
1501
1502#[derive(Debug, Clone, PartialEq, Eq)]
1504pub struct TreeItem {
1505 pub label: String,
1507 pub children: Vec<TreeItem>,
1509}
1510
1511impl TreeItem {
1512 pub fn new(label: impl Into<String>) -> Self {
1514 Self {
1515 label: label.into(),
1516 children: Vec::new(),
1517 }
1518 }
1519
1520 pub fn with_child(mut self, child: TreeItem) -> Self {
1522 self.children.push(child);
1523 self
1524 }
1525
1526 pub fn indented_rows(&self) -> Vec<String> {
1529 let mut rows = Vec::new();
1530 self.collect_rows(0, &mut rows);
1531 rows
1532 }
1533
1534 fn collect_rows(&self, depth: usize, rows: &mut Vec<String>) {
1535 rows.push(format!("{}{}", " ".repeat(depth), self.label));
1536 for child in &self.children {
1537 child.collect_rows(depth + 1, rows);
1538 }
1539 }
1540}
1541
1542#[derive(Debug, Clone, PartialEq, Eq)]
1549pub struct ColumnSpec {
1550 pub title: String,
1552 pub width: Option<i32>,
1555}
1556
1557impl ColumnSpec {
1558 pub fn new(title: impl Into<String>) -> Self {
1560 Self {
1561 title: title.into(),
1562 width: None,
1563 }
1564 }
1565
1566 pub fn with_width(mut self, width: i32) -> Self {
1570 self.width = if width > 0 { Some(width) } else { None };
1571 self
1572 }
1573}
1574
1575#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1581#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1582pub struct RowKey(pub u64);
1583
1584#[derive(Debug, Clone, PartialEq, Eq)]
1586#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1587pub struct RowSet {
1588 pub key: RowKey,
1590 pub cells: Vec<String>,
1592}
1593
1594impl RowSet {
1595 pub fn new(key: u64, cells: &[&str]) -> Self {
1597 Self {
1598 key: RowKey(key),
1599 cells: cells.iter().map(|cell| (*cell).to_owned()).collect(),
1600 }
1601 }
1602
1603 pub fn text(&self) -> String {
1605 self.cells.first().cloned().unwrap_or_default()
1606 }
1607}
1608
1609#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
1617pub struct RowDelta {
1618 pub inserted: usize,
1619 pub updated: usize,
1620 pub removed: usize,
1621 pub moved: usize,
1622 pub unchanged: usize,
1623}
1624
1625impl RowDelta {
1626 pub fn is_noop(&self) -> bool {
1629 self.inserted == 0 && self.updated == 0 && self.removed == 0 && self.moved == 0
1630 }
1631}
1632
1633pub fn diff_rows(old_rows: &[RowSet], new_rows: &[RowSet]) -> GuiResult<RowDelta> {
1649 let mut new_keys: std::collections::HashSet<u64> =
1650 std::collections::HashSet::with_capacity(new_rows.len());
1651 for row in new_rows {
1652 if !new_keys.insert(row.key.0) {
1653 return Err(GuiError::Backend("duplicate row key".to_owned()));
1654 }
1655 }
1656
1657 let old_index: std::collections::HashMap<u64, usize> = old_rows
1658 .iter()
1659 .enumerate()
1660 .map(|(index, row)| (row.key.0, index))
1661 .collect();
1662
1663 let mut delta = RowDelta::default();
1664 for (new_pos, row) in new_rows.iter().enumerate() {
1665 match old_index.get(&row.key.0) {
1666 None => delta.inserted += 1,
1667 Some(&old_pos) => {
1668 if old_rows[old_pos].cells != row.cells {
1669 delta.updated += 1;
1670 } else if old_pos != new_pos {
1671 delta.moved += 1;
1672 } else {
1673 delta.unchanged += 1;
1674 }
1675 }
1676 }
1677 }
1678 delta.removed = old_rows
1681 .iter()
1682 .filter(|row| !new_keys.contains(&row.key.0))
1683 .count();
1684 Ok(delta)
1685}
1686
1687#[derive(Debug, Clone, PartialEq, Eq)]
1689#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1690pub enum RowOp {
1691 Insert { index: usize, row: RowSet },
1693 Update { index: usize, row: RowSet },
1695 Remove { index: usize, key: RowKey },
1697 Move {
1699 from_index: usize,
1700 to_index: usize,
1701 key: RowKey,
1702 },
1703 Reorder { order: Vec<usize> },
1705}
1706
1707pub fn diff_row_ops(
1711 old_rows: &[RowSet],
1712 new_rows: &[RowSet],
1713 delta: &RowDelta,
1714) -> Option<Vec<RowOp>> {
1715 if old_rows.is_empty() || delta.is_noop() {
1716 return None;
1717 }
1718
1719 if delta.inserted == 0 && delta.removed == 0 && delta.moved == 0 && delta.updated > 0 {
1721 if old_rows.len() != new_rows.len() {
1722 return None;
1723 }
1724 let mut ops = Vec::with_capacity(delta.updated);
1725 for (i, (old, new)) in old_rows.iter().zip(new_rows.iter()).enumerate() {
1726 if old.key != new.key {
1727 return None;
1728 }
1729 if old.cells != new.cells {
1730 ops.push(RowOp::Update {
1731 index: i,
1732 row: new.clone(),
1733 });
1734 }
1735 }
1736 return Some(ops);
1737 }
1738
1739 if delta.inserted == 1 && delta.removed == 0 && delta.updated == 0 {
1741 if new_rows.len() != old_rows.len() + 1 {
1742 return None;
1743 }
1744 let insert_idx = (0..old_rows.len())
1745 .find(|&i| old_rows[i].key != new_rows[i].key)
1746 .unwrap_or(old_rows.len());
1747 if new_rows[insert_idx + 1..] == old_rows[insert_idx..] {
1749 return Some(vec![RowOp::Insert {
1750 index: insert_idx,
1751 row: new_rows[insert_idx].clone(),
1752 }]);
1753 }
1754 return None;
1755 }
1756
1757 if delta.removed == 1 && delta.inserted == 0 && delta.updated == 0 {
1759 if old_rows.len() != new_rows.len() + 1 {
1760 return None;
1761 }
1762 let remove_idx = (0..new_rows.len())
1763 .find(|&i| old_rows[i].key != new_rows[i].key)
1764 .unwrap_or(new_rows.len());
1765 if old_rows[remove_idx + 1..] == new_rows[remove_idx..] {
1767 return Some(vec![RowOp::Remove {
1768 index: remove_idx,
1769 key: old_rows[remove_idx].key,
1770 }]);
1771 }
1772 return None;
1773 }
1774
1775 if delta.moved > 0 && delta.inserted == 0 && delta.removed == 0 && delta.updated == 0 {
1777 if old_rows.len() != new_rows.len() {
1778 return None;
1779 }
1780 let old_index: std::collections::HashMap<u64, usize> = old_rows
1781 .iter()
1782 .enumerate()
1783 .map(|(index, row)| (row.key.0, index))
1784 .collect();
1785 let order: Vec<usize> = new_rows
1786 .iter()
1787 .filter_map(|r| old_index.get(&r.key.0).copied())
1788 .collect();
1789 if order.len() != old_rows.len() {
1790 return None;
1791 }
1792
1793 for (to_idx, &from_idx) in order.iter().enumerate() {
1795 if to_idx == from_idx {
1796 continue;
1797 }
1798 let mut matches = true;
1799 let mut expected = 0;
1800 for (new_i, &old_i) in order.iter().enumerate() {
1801 if new_i == to_idx {
1802 continue;
1803 }
1804 if expected == from_idx {
1805 expected += 1;
1806 }
1807 if old_i != expected {
1808 matches = false;
1809 break;
1810 }
1811 expected += 1;
1812 }
1813 if matches {
1814 return Some(vec![RowOp::Move {
1815 from_index: from_idx,
1816 to_index: to_idx,
1817 key: new_rows[to_idx].key,
1818 }]);
1819 }
1820 }
1821
1822 return Some(vec![RowOp::Reorder { order }]);
1823 }
1824
1825 None
1826}
1827
1828pub fn apply_row_ops_to_rows(rows: &mut Vec<RowSet>, ops: &[RowOp]) {
1830 for op in ops {
1831 match op {
1832 RowOp::Update { index, row } => {
1833 if let Some(target) = rows.get_mut(*index) {
1834 *target = row.clone();
1835 }
1836 }
1837 RowOp::Insert { index, row } => {
1838 let idx = (*index).min(rows.len());
1839 rows.insert(idx, row.clone());
1840 }
1841 RowOp::Remove { index, .. } => {
1842 if *index < rows.len() {
1843 rows.remove(*index);
1844 }
1845 }
1846 RowOp::Move {
1847 from_index,
1848 to_index,
1849 ..
1850 } => {
1851 if *from_index < rows.len() {
1852 let r = rows.remove(*from_index);
1853 let to = (*to_index).min(rows.len());
1854 rows.insert(to, r);
1855 }
1856 }
1857 RowOp::Reorder { order } => {
1858 if order.len() == rows.len() {
1859 let old = std::mem::take(rows);
1860 rows.reserve(order.len());
1861 let mut old_opt: Vec<Option<RowSet>> = old.into_iter().map(Some).collect();
1862 for &old_idx in order {
1863 if let Some(opt) = old_opt.get_mut(old_idx) {
1864 if let Some(r) = opt.take() {
1865 rows.push(r);
1866 }
1867 }
1868 }
1869 }
1870 }
1871 }
1872 }
1873}
1874
1875pub fn apply_row_ops_to_cells(cells: &mut Vec<Vec<String>>, ops: &[RowOp]) {
1877 for op in ops {
1878 match op {
1879 RowOp::Update { index, row } => {
1880 if let Some(target) = cells.get_mut(*index) {
1881 *target = row.cells.clone();
1882 }
1883 }
1884 RowOp::Insert { index, row } => {
1885 let idx = (*index).min(cells.len());
1886 cells.insert(idx, row.cells.clone());
1887 }
1888 RowOp::Remove { index, .. } => {
1889 if *index < cells.len() {
1890 cells.remove(*index);
1891 }
1892 }
1893 RowOp::Move {
1894 from_index,
1895 to_index,
1896 ..
1897 } => {
1898 if *from_index < cells.len() {
1899 let c = cells.remove(*from_index);
1900 let to = (*to_index).min(cells.len());
1901 cells.insert(to, c);
1902 }
1903 }
1904 RowOp::Reorder { order } => {
1905 if order.len() == cells.len() {
1906 let old = std::mem::take(cells);
1907 cells.reserve(order.len());
1908 let mut old_opt: Vec<Option<Vec<String>>> = old.into_iter().map(Some).collect();
1909 for &old_idx in order {
1910 if let Some(opt) = old_opt.get_mut(old_idx) {
1911 if let Some(c) = opt.take() {
1912 cells.push(c);
1913 }
1914 }
1915 }
1916 }
1917 }
1918 }
1919 }
1920}
1921
1922pub fn apply_row_ops_to_items(items: &mut Vec<String>, ops: &[RowOp]) {
1924 for op in ops {
1925 match op {
1926 RowOp::Update { index, row } => {
1927 if let Some(target) = items.get_mut(*index) {
1928 *target = row.text();
1929 }
1930 }
1931 RowOp::Insert { index, row } => {
1932 let idx = (*index).min(items.len());
1933 items.insert(idx, row.text());
1934 }
1935 RowOp::Remove { index, .. } => {
1936 if *index < items.len() {
1937 items.remove(*index);
1938 }
1939 }
1940 RowOp::Move {
1941 from_index,
1942 to_index,
1943 ..
1944 } => {
1945 if *from_index < items.len() {
1946 let item = items.remove(*from_index);
1947 let to = (*to_index).min(items.len());
1948 items.insert(to, item);
1949 }
1950 }
1951 RowOp::Reorder { order } => {
1952 if order.len() == items.len() {
1953 let old = std::mem::take(items);
1954 items.reserve(order.len());
1955 let mut old_opt: Vec<Option<String>> = old.into_iter().map(Some).collect();
1956 for &old_idx in order {
1957 if let Some(opt) = old_opt.get_mut(old_idx) {
1958 if let Some(item) = opt.take() {
1959 items.push(item);
1960 }
1961 }
1962 }
1963 }
1964 }
1965 }
1966 }
1967}
1968
1969#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
1971#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1972pub enum TextAlignment {
1973 Left,
1974 Center,
1975 Right,
1976}
1977
1978#[derive(Debug, Clone, PartialEq, Default)]
1980pub struct GridCellAttr {
1981 pub bg_color: Option<Color>,
1982 pub text_color: Option<Color>,
1983 pub alignment: Option<TextAlignment>,
1984 pub font_bold: bool,
1985 pub font_italic: bool,
1986 pub font_size: Option<u8>,
1987}
1988
1989#[derive(Debug, Clone, PartialEq)]
1991pub enum GridCellEditor {
1992 Text,
1993 Boolean,
1994 Enum(Vec<String>),
1995 Number { min: i32, max: i32, step: i32 },
1996}
1997
1998#[derive(Debug, Clone, PartialEq)]
2000pub enum GridCellRenderer {
2001 Text,
2002 Boolean,
2003 Canvas(CanvasScene),
2004}
2005
2006pub trait DataGridModel {
2008 fn row_count(&self) -> usize;
2010 fn col_count(&self) -> usize;
2012 fn value_at(&self, row: usize, col: usize) -> String;
2014
2015 fn is_row_resident(&self, _row: usize) -> bool {
2025 true
2026 }
2027
2028 fn pin_visible_band(&self, _first_row: usize, _count: usize) {}
2041
2042 fn clear_pinned_band(&self) {}
2045
2046 fn get_attr(&self, _row: usize, _col: usize) -> Option<GridCellAttr> {
2048 None
2049 }
2050
2051 fn set_value_at(&mut self, _row: usize, _col: usize, _value: String) {}
2053 fn get_editor(&self, _row: usize, _col: usize) -> Option<GridCellEditor> {
2054 None
2055 }
2056
2057 fn get_renderer(&self, _row: usize, _col: usize) -> Option<GridCellRenderer> {
2059 None
2060 }
2061
2062 fn cell_span(&self, _row: usize, _col: usize) -> (usize, usize) {
2064 (1, 1)
2065 }
2066}
2067
2068pub struct SimpleDataGridModel {
2070 pub rows: Vec<Vec<String>>,
2071}
2072
2073impl DataGridModel for SimpleDataGridModel {
2074 fn row_count(&self) -> usize {
2075 self.rows.len()
2076 }
2077
2078 fn col_count(&self) -> usize {
2079 self.rows.first().map(|r| r.len()).unwrap_or(0)
2080 }
2081
2082 fn value_at(&self, row: usize, col: usize) -> String {
2083 self.rows
2084 .get(row)
2085 .and_then(|r| r.get(col))
2086 .cloned()
2087 .unwrap_or_default()
2088 }
2089}
2090
2091#[derive(Debug, Clone, PartialEq, Eq)]
2097pub struct WindowedDataGridConfig {
2098 pub max_resident_rows: usize,
2101 pub max_resident_bytes: usize,
2105 pub placeholder: String,
2109}
2110
2111impl WindowedDataGridConfig {
2112 pub fn new(max_resident_rows: usize, max_resident_bytes: usize) -> Self {
2114 Self {
2115 max_resident_rows: max_resident_rows.max(1),
2116 max_resident_bytes: max_resident_bytes.max(1),
2117 placeholder: "…".to_owned(),
2118 }
2119 }
2120
2121 pub fn with_placeholder(mut self, placeholder: impl Into<String>) -> Self {
2123 self.placeholder = placeholder.into();
2124 self
2125 }
2126}
2127
2128#[derive(Debug, Clone, PartialEq, Eq)]
2130pub enum WindowedDelivery {
2131 Applied { evicted: Vec<usize> },
2134 Rejected(WindowedDeliveryRejection),
2138}
2139
2140#[derive(Debug, Clone, Copy, PartialEq, Eq)]
2143pub enum WindowedDeliveryRejection {
2144 RowOutOfRange,
2147 NotInFlight,
2150 Oversized,
2154 NoEvictableVictim,
2158}
2159
2160pub struct WindowedDataGridModel {
2219 handle: WindowedDataGridHandle,
2220 on_fetch_requested: Box<dyn Fn(usize)>,
2221 on_repaint_requested: Box<dyn Fn()>,
2222}
2223
2224impl WindowedDataGridModel {
2225 pub fn new(
2239 row_count: usize,
2240 col_count: usize,
2241 config: WindowedDataGridConfig,
2242 on_fetch_requested: impl Fn(usize) + 'static,
2243 on_repaint_requested: impl Fn() + 'static,
2244 ) -> Self {
2245 Self {
2246 handle: WindowedDataGridHandle {
2247 row_count,
2248 col_count,
2249 config,
2250 state: Rc::new(RefCell::new(WindowedState::default())),
2251 },
2252 on_fetch_requested: Box::new(on_fetch_requested),
2253 on_repaint_requested: Box::new(on_repaint_requested),
2254 }
2255 }
2256
2257 pub fn handle(&self) -> WindowedDataGridHandle {
2264 self.handle.clone()
2265 }
2266}
2267
2268impl DataGridModel for WindowedDataGridModel {
2269 fn row_count(&self) -> usize {
2270 self.handle.row_count
2271 }
2272
2273 fn col_count(&self) -> usize {
2274 self.handle.col_count
2275 }
2276
2277 fn value_at(&self, row: usize, col: usize) -> String {
2282 if row >= self.handle.row_count || col >= self.handle.col_count {
2283 return String::new();
2284 }
2285 let scheduled = {
2286 let mut state = self.handle.state.borrow_mut();
2287 if state.resident.contains_key(&row) {
2288 state.hits += 1;
2289 state.touch(row);
2290 return state
2291 .resident
2292 .get(&row)
2293 .and_then(|resident| resident.cells.get(col))
2294 .cloned()
2295 .unwrap_or_default();
2296 }
2297 state.misses += 1;
2298 if state.in_flight.insert(row) {
2299 state.fetches_requested += 1;
2300 true
2301 } else {
2302 false
2303 }
2304 };
2305 if scheduled {
2306 (self.on_fetch_requested)(row);
2309 (self.on_repaint_requested)();
2310 }
2311 self.handle.config.placeholder.clone()
2312 }
2313
2314 fn is_row_resident(&self, row: usize) -> bool {
2318 row < self.handle.row_count && self.handle.state.borrow().resident.contains_key(&row)
2319 }
2320
2321 fn pin_visible_band(&self, first_row: usize, count: usize) {
2326 self.handle.pin_visible_band(first_row, count);
2327 }
2328
2329 fn clear_pinned_band(&self) {
2331 self.handle.clear_pinned_band();
2332 }
2333}
2334
2335impl std::fmt::Debug for WindowedDataGridModel {
2336 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2337 f.debug_struct("WindowedDataGridModel")
2338 .field("window", &self.handle)
2339 .finish()
2340 }
2341}
2342
2343#[derive(Clone)]
2352pub struct WindowedDataGridHandle {
2353 row_count: usize,
2354 col_count: usize,
2355 config: WindowedDataGridConfig,
2356 state: Rc<RefCell<WindowedState>>,
2357}
2358
2359impl WindowedDataGridHandle {
2360 pub fn deliver_row(&self, row: usize, cells: Vec<String>) -> WindowedDelivery {
2370 if row >= self.row_count {
2371 self.state.borrow_mut().rejected_deliveries += 1;
2372 return WindowedDelivery::Rejected(WindowedDeliveryRejection::RowOutOfRange);
2373 }
2374 let mut cells = cells;
2375 cells.truncate(self.col_count);
2376 let bytes: usize = cells.iter().map(String::len).sum();
2377
2378 let mut state = self.state.borrow_mut();
2379 if !state.in_flight.remove(&row) {
2380 state.rejected_deliveries += 1;
2381 return WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight);
2382 }
2383 if bytes > self.config.max_resident_bytes {
2384 state.rejected_deliveries += 1;
2385 return WindowedDelivery::Rejected(WindowedDeliveryRejection::Oversized);
2386 }
2387
2388 if let Some(previous) = state.resident.remove(&row) {
2392 state.resident_bytes -= previous.bytes;
2393 state.lru.retain(|resident| *resident != row);
2394 }
2395
2396 let mut evicted: Vec<usize> = Vec::new();
2397 while state.resident.len() >= self.config.max_resident_rows
2398 || state.resident_bytes.saturating_add(bytes) > self.config.max_resident_bytes
2399 {
2400 let victim = state
2401 .lru
2402 .iter()
2403 .copied()
2404 .find(|candidate| !state.is_pinned(*candidate));
2405 let Some(victim) = victim else {
2406 state.rejected_deliveries += 1;
2407 return WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim);
2408 };
2409 state.lru.retain(|resident| *resident != victim);
2410 if let Some(previous) = state.resident.remove(&victim) {
2411 state.resident_bytes -= previous.bytes;
2412 state.evictions += 1;
2413 evicted.push(victim);
2414 }
2415 }
2416
2417 state.resident.insert(row, ResidentRow { cells, bytes });
2418 state.resident_bytes += bytes;
2419 state.lru.push_back(row);
2420 WindowedDelivery::Applied { evicted }
2421 }
2422
2423 pub fn pin_visible_band(&self, first_row: usize, count: usize) {
2433 let mut state = self.state.borrow_mut();
2434 state.pinned_band = if count == 0 {
2435 None
2436 } else {
2437 Some((first_row, count))
2438 };
2439 }
2440
2441 pub fn clear_pinned_band(&self) {
2443 self.state.borrow_mut().pinned_band = None;
2444 }
2445
2446 pub fn pinned_band(&self) -> Option<(usize, usize)> {
2448 self.state.borrow().pinned_band
2449 }
2450
2451 pub fn is_row_resident(&self, row: usize) -> bool {
2453 row < self.row_count && self.state.borrow().resident.contains_key(&row)
2454 }
2455
2456 pub fn is_row_in_flight(&self, row: usize) -> bool {
2458 self.state.borrow().in_flight.contains(&row)
2459 }
2460
2461 pub fn resident_row_count(&self) -> usize {
2463 self.state.borrow().resident.len()
2464 }
2465
2466 pub fn resident_bytes(&self) -> usize {
2469 self.state.borrow().resident_bytes
2470 }
2471
2472 pub fn in_flight_count(&self) -> usize {
2474 self.state.borrow().in_flight.len()
2475 }
2476
2477 pub fn hits(&self) -> usize {
2479 self.state.borrow().hits
2480 }
2481
2482 pub fn misses(&self) -> usize {
2485 self.state.borrow().misses
2486 }
2487
2488 pub fn fetches_requested(&self) -> usize {
2491 self.state.borrow().fetches_requested
2492 }
2493
2494 pub fn evictions(&self) -> usize {
2496 self.state.borrow().evictions
2497 }
2498
2499 pub fn rejected_deliveries(&self) -> usize {
2501 self.state.borrow().rejected_deliveries
2502 }
2503}
2504
2505impl std::fmt::Debug for WindowedDataGridHandle {
2506 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
2507 let state = self.state.borrow();
2508 f.debug_struct("WindowedDataGridHandle")
2509 .field("row_count", &self.row_count)
2510 .field("col_count", &self.col_count)
2511 .field("resident_rows", &state.resident.len())
2512 .field("resident_bytes", &state.resident_bytes)
2513 .field("in_flight", &state.in_flight.len())
2514 .field("hits", &state.hits)
2515 .field("misses", &state.misses)
2516 .field("evictions", &state.evictions)
2517 .finish()
2518 }
2519}
2520
2521#[derive(Default)]
2522struct WindowedState {
2523 resident: HashMap<usize, ResidentRow>,
2524 lru: VecDeque<usize>,
2526 in_flight: BTreeSet<usize>,
2528 pinned_band: Option<(usize, usize)>,
2531 resident_bytes: usize,
2532 hits: usize,
2533 misses: usize,
2534 fetches_requested: usize,
2535 evictions: usize,
2536 rejected_deliveries: usize,
2537}
2538
2539impl WindowedState {
2540 fn touch(&mut self, row: usize) {
2541 if let Some(position) = self.lru.iter().position(|resident| *resident == row) {
2542 self.lru.remove(position);
2543 }
2544 self.lru.push_back(row);
2545 }
2546
2547 fn is_pinned(&self, row: usize) -> bool {
2548 match self.pinned_band {
2549 Some((first, count)) => row >= first && row - first < count,
2550 None => false,
2551 }
2552 }
2553}
2554
2555struct ResidentRow {
2556 cells: Vec<String>,
2557 bytes: usize,
2558}
2559
2560#[derive(Debug, Clone, PartialEq)]
2562pub struct WidgetSpec {
2563 pub id: WidgetId,
2565 pub kind: WidgetKind,
2567 pub text: Option<String>,
2569 pub text_selection: Option<(usize, usize)>,
2572 pub completion_items: Vec<String>,
2578 pub placeholder_text: Option<String>,
2580 pub parent: Option<WidgetId>,
2582 pub container_direction: Option<ContainerDirection>,
2584 pub container_wrap: Option<ContainerWrap>,
2586 pub container_scroll_vertical: bool,
2588 pub container_scroll_horizontal: bool,
2590 pub container_gap: Option<i32>,
2593 pub container_padding: Option<i32>,
2596 pub size: Option<(i32, i32)>,
2598 pub position: Option<(i32, i32)>,
2600 pub data_list_items: Vec<String>,
2602 pub list_columns: Vec<ColumnSpec>,
2606 pub list_rows: Vec<Vec<String>>,
2611 pub data_grid_rows: Arc<Vec<Vec<String>>>,
2616 pub tree_items: Vec<TreeItem>,
2618 pub background_color: Option<Color>,
2620 pub alert_level: Option<AlertLevel>,
2622 pub checked: Option<bool>,
2624 pub enabled: Option<bool>,
2626 pub range: Option<(i32, i32)>,
2628 pub step: Option<i32>,
2630 pub value: Option<i32>,
2632 pub group_name: Option<String>,
2634 pub tab_items: Vec<String>,
2639 pub selected_index: Option<usize>,
2641 pub selected_indices: Vec<usize>,
2643 pub row_drag_source: bool,
2645 pub row_drop_target: bool,
2647 pub file_drop_target: bool,
2649 pub image_source: Option<String>,
2651 pub image_fit: ImageFit,
2653 pub icon: Option<IconRole>,
2656 pub file_chooser_mode: FileChooserMode,
2658 pub date_value: Option<String>,
2660 pub link_url: Option<String>,
2662 pub tooltip: Option<String>,
2664 pub accessibility: AccessibilitySpec,
2666 pub focusable: Option<bool>,
2669 pub split_ratio: Option<u8>,
2671 pub canvas_scene: Option<CanvasScene>,
2673 pub canvas_surface: Option<CanvasSurface>,
2675 pub color_dialog_data: Option<ColorDialogData>,
2678 pub font_dialog_data: Option<FontDialogData>,
2681 pub toolbar_items: Vec<ToolbarItem>,
2684 pub toolbar_orientation: ToolbarOrientation,
2686 pub calendar_selected_dates: Vec<CalendarDate>,
2688 pub calendar_min_date: Option<CalendarDate>,
2690 pub calendar_max_date: Option<CalendarDate>,
2692 pub calendar_first_day_of_week: CalendarFirstDayOfWeek,
2694 pub calendar_selection_mode: CalendarSelectionMode,
2696 pub label_alignment: LabelAlignment,
2698 pub label_wrap: LabelWrap,
2700 pub rich_text_runs: Vec<TextRun>,
2702 pub rich_text_images: Vec<RichTextImage>,
2704 pub monospace: bool,
2706 pub font: Option<FontDescriptor>,
2708 pub row_icons: Vec<Option<IconRole>>,
2710}
2711
2712impl WidgetSpec {
2713 pub fn new(id: WidgetId, kind: WidgetKind) -> Self {
2717 Self {
2718 id,
2719 kind,
2720 text: None,
2721 text_selection: None,
2722 completion_items: Vec::new(),
2723 parent: None,
2724 container_direction: if kind == WidgetKind::Container {
2725 Some(ContainerDirection::Vertical)
2726 } else {
2727 None
2728 },
2729 container_wrap: if kind == WidgetKind::Container {
2730 Some(ContainerWrap::NoWrap)
2731 } else {
2732 None
2733 },
2734 container_scroll_vertical: false,
2735 container_scroll_horizontal: false,
2736 container_gap: None,
2737 container_padding: None,
2738 size: None,
2739 position: None,
2740 data_list_items: Vec::new(),
2741 list_columns: Vec::new(),
2742 list_rows: Vec::new(),
2743 data_grid_rows: Arc::new(Vec::new()),
2744 tree_items: Vec::new(),
2745 background_color: None,
2746 alert_level: {
2747 #[cfg(feature = "widgets-containers")]
2748 {
2749 if kind == WidgetKind::AlertDialog {
2750 Some(AlertLevel::Info)
2751 } else {
2752 None
2753 }
2754 }
2755 #[cfg(not(feature = "widgets-containers"))]
2756 {
2757 None
2758 }
2759 },
2760 checked: None,
2761 enabled: None,
2762 range: None,
2763 step: None,
2764 value: None,
2765 group_name: None,
2766 tab_items: Vec::new(),
2767 selected_index: None,
2768 selected_indices: Vec::new(),
2769 row_drag_source: false,
2770 row_drop_target: false,
2771 file_drop_target: false,
2772 image_source: None,
2773 image_fit: ImageFit::default(),
2774 icon: None,
2775 file_chooser_mode: FileChooserMode::default(),
2776 date_value: None,
2777 link_url: None,
2778 tooltip: None,
2779 accessibility: AccessibilitySpec::for_kind(kind),
2780 focusable: None,
2781 split_ratio: None,
2782 canvas_scene: None,
2783 canvas_surface: None,
2784 color_dialog_data: None,
2785 font_dialog_data: None,
2786 toolbar_items: Vec::new(),
2787 toolbar_orientation: ToolbarOrientation::default(),
2788 calendar_selected_dates: Vec::new(),
2789 calendar_min_date: None,
2790 calendar_max_date: None,
2791 calendar_first_day_of_week: CalendarFirstDayOfWeek::default(),
2792 calendar_selection_mode: CalendarSelectionMode::default(),
2793 label_alignment: match kind {
2794 WidgetKind::Button => LabelAlignment::Center,
2795 _ => LabelAlignment::default(),
2796 },
2797 label_wrap: LabelWrap::default(),
2798 rich_text_runs: Vec::new(),
2799 rich_text_images: Vec::new(),
2800 placeholder_text: None,
2801 monospace: false,
2802 font: None,
2803 row_icons: Vec::new(),
2804 }
2805 }
2806
2807 pub fn ensure_property(&self, property: WidgetProperty) -> GuiResult<()> {
2810 if property.supports(self.kind) {
2811 Ok(())
2812 } else {
2813 Err(GuiError::UnsupportedWidget(property.operation()))
2814 }
2815 }
2816
2817 pub fn requires_property(&self, property: WidgetProperty) -> GuiResult<()> {
2819 self.ensure_property(property)
2820 }
2821
2822 pub fn with_text(mut self, text: impl Into<String>) -> Self {
2824 self.text = Some(text.into());
2825 self
2826 }
2827
2828 pub fn with_completion_items(mut self, items: Vec<String>) -> Self {
2830 self.completion_items = items;
2831 self
2832 }
2833
2834 pub fn with_parent(mut self, parent: WidgetId) -> Self {
2836 self.parent = Some(parent);
2837 self
2838 }
2839
2840 pub fn with_container_direction(mut self, direction: ContainerDirection) -> Self {
2842 self.container_direction = Some(direction);
2843 self
2844 }
2845
2846 pub fn with_container_wrap(mut self, wrap: ContainerWrap) -> Self {
2848 self.container_wrap = Some(wrap);
2849 self
2850 }
2851
2852 pub fn with_container_scroll(mut self, vertical: bool, horizontal: bool) -> Self {
2854 self.container_scroll_vertical = vertical;
2855 self.container_scroll_horizontal = horizontal;
2856 self
2857 }
2858
2859 pub fn with_container_gap(mut self, gap: i32) -> Self {
2861 self.container_gap = Some(gap.max(0));
2862 self
2863 }
2864
2865 pub fn with_container_padding(mut self, padding: i32) -> Self {
2868 self.container_padding = Some(padding.max(0));
2869 self
2870 }
2871
2872 pub fn with_size(mut self, width: i32, height: i32) -> Self {
2874 self.size = Some((width, height));
2875 self
2876 }
2877
2878 pub fn with_position(mut self, x: i32, y: i32) -> Self {
2880 self.position = Some((x, y));
2881 self
2882 }
2883
2884 pub fn with_data_list_items(mut self, items: impl IntoIterator<Item = String>) -> Self {
2886 self.data_list_items = items.into_iter().collect();
2887 self
2888 }
2889
2890 pub fn with_list_columns(mut self, columns: impl IntoIterator<Item = ColumnSpec>) -> Self {
2893 self.list_columns = columns.into_iter().collect();
2894 self
2895 }
2896
2897 pub fn with_list_rows(mut self, rows: impl IntoIterator<Item = Vec<String>>) -> Self {
2900 self.list_rows = rows.into_iter().collect();
2901 self
2902 }
2903
2904 pub fn with_data_grid_rows(mut self, rows: impl IntoIterator<Item = Vec<String>>) -> Self {
2906 self.data_grid_rows = Arc::new(rows.into_iter().collect());
2907 self
2908 }
2909
2910 pub fn with_tree_items(mut self, items: impl IntoIterator<Item = TreeItem>) -> Self {
2912 self.tree_items = items.into_iter().collect();
2913 self
2914 }
2915
2916 pub fn with_background_color(mut self, color: Color) -> Self {
2918 self.background_color = Some(color);
2919 self
2920 }
2921
2922 pub fn with_alert_level(mut self, level: AlertLevel) -> Self {
2924 self.alert_level = Some(level);
2925 self
2926 }
2927
2928 pub fn with_checked(mut self, checked: bool) -> Self {
2930 self.checked = Some(checked);
2931 self
2932 }
2933
2934 pub fn with_enabled(mut self, enabled: bool) -> Self {
2936 self.enabled = Some(enabled);
2937 self
2938 }
2939
2940 pub fn with_range(mut self, min: i32, max: i32) -> Self {
2942 self.range = Some((min, max));
2943 self
2944 }
2945
2946 pub fn with_step(mut self, step: i32) -> Self {
2948 self.step = Some(step);
2949 self
2950 }
2951
2952 pub fn with_value(mut self, value: i32) -> Self {
2954 self.value = Some(value);
2955 self
2956 }
2957
2958 pub fn with_selected_indices(mut self, indices: impl IntoIterator<Item = usize>) -> Self {
2960 self.selected_indices = indices.into_iter().collect();
2961 self
2962 }
2963
2964 pub fn with_row_drag_source(mut self, enabled: bool) -> Self {
2966 self.row_drag_source = enabled;
2967 self
2968 }
2969
2970 pub fn with_row_drop_target(mut self, enabled: bool) -> Self {
2972 self.row_drop_target = enabled;
2973 self
2974 }
2975
2976 pub fn with_file_drop_target(mut self, enabled: bool) -> Self {
2978 self.file_drop_target = enabled;
2979 self
2980 }
2981
2982 pub fn with_group_name(mut self, name: impl Into<String>) -> Self {
2984 self.group_name = Some(name.into());
2985 self
2986 }
2987
2988 pub fn with_tab_items(mut self, items: impl IntoIterator<Item = String>) -> Self {
2995 self.tab_items = items.into_iter().collect();
2996 self
2997 }
2998
2999 pub fn with_selected_index(mut self, selected_index: usize) -> Self {
3001 self.selected_index = Some(selected_index);
3002 self
3003 }
3004
3005 pub fn with_image_source(mut self, source: impl Into<String>) -> Self {
3007 self.image_source = Some(source.into());
3008 self
3009 }
3010
3011 pub fn with_image_fit(mut self, fit: ImageFit) -> Self {
3013 self.image_fit = fit;
3014 self
3015 }
3016
3017 pub fn with_file_chooser_mode(mut self, mode: FileChooserMode) -> Self {
3019 self.file_chooser_mode = mode;
3020 self
3021 }
3022
3023 pub fn with_date_value(mut self, date: impl Into<String>) -> Self {
3025 self.date_value = Some(date.into());
3026 self
3027 }
3028
3029 pub fn with_link_url(mut self, url: impl Into<String>) -> Self {
3031 self.link_url = Some(url.into());
3032 self
3033 }
3034
3035 pub fn with_tooltip(mut self, tooltip: impl Into<String>) -> Self {
3037 self.tooltip = Some(tooltip.into());
3038 self
3039 }
3040
3041 pub fn with_accessible_name(mut self, name: impl Into<String>) -> Self {
3043 self.accessibility.name = Some(name.into());
3044 self
3045 }
3046
3047 pub fn with_accessible_description(mut self, description: impl Into<String>) -> Self {
3049 self.accessibility.description = Some(description.into());
3050 self
3051 }
3052
3053 pub fn with_focusable(mut self, focusable: bool) -> Self {
3056 self.focusable = Some(focusable);
3057 self
3058 }
3059
3060 pub fn with_split_ratio(mut self, ratio: u8) -> Self {
3062 self.split_ratio = Some(ratio.min(100));
3063 self
3064 }
3065
3066 pub fn with_canvas_scene(mut self, scene: CanvasScene) -> Self {
3068 self.canvas_scene = Some(scene);
3069 self
3070 }
3071
3072 pub fn with_canvas_surface(mut self, surface: CanvasSurface) -> Self {
3074 self.canvas_surface = Some(surface);
3075 self
3076 }
3077
3078 pub fn with_color_dialog_data(mut self, data: ColorDialogData) -> Self {
3080 self.color_dialog_data = Some(data);
3081 self
3082 }
3083
3084 pub fn with_font_dialog_data(mut self, data: FontDialogData) -> Self {
3086 self.font_dialog_data = Some(data);
3087 self
3088 }
3089
3090 pub fn with_toolbar_items(mut self, items: Vec<ToolbarItem>) -> Self {
3092 self.toolbar_items = items;
3093 self
3094 }
3095
3096 pub fn with_toolbar_orientation(mut self, orientation: ToolbarOrientation) -> Self {
3098 self.toolbar_orientation = orientation;
3099 self
3100 }
3101
3102 pub fn with_calendar_selected_dates(
3104 mut self,
3105 dates: impl IntoIterator<Item = CalendarDate>,
3106 ) -> Self {
3107 self.calendar_selected_dates = dates.into_iter().collect();
3108 self
3109 }
3110
3111 pub fn with_calendar_bounds(
3113 mut self,
3114 min: Option<CalendarDate>,
3115 max: Option<CalendarDate>,
3116 ) -> Self {
3117 self.calendar_min_date = min;
3118 self.calendar_max_date = max;
3119 self
3120 }
3121
3122 pub fn with_calendar_first_day_of_week(mut self, first_day: CalendarFirstDayOfWeek) -> Self {
3124 self.calendar_first_day_of_week = first_day;
3125 self
3126 }
3127
3128 pub fn with_calendar_selection_mode(mut self, mode: CalendarSelectionMode) -> Self {
3130 self.calendar_selection_mode = mode;
3131 self
3132 }
3133
3134 pub fn with_label_alignment(mut self, alignment: impl Into<LabelAlignment>) -> Self {
3136 self.label_alignment = alignment.into();
3137 self
3138 }
3139
3140 pub fn with_label_wrap(mut self, wrap: impl Into<LabelWrap>) -> Self {
3142 self.label_wrap = wrap.into();
3143 self
3144 }
3145
3146 pub fn with_label_wrap_mode(self, wrap: impl Into<LabelWrap>) -> Self {
3148 self.with_label_wrap(wrap)
3149 }
3150
3151 pub fn with_rich_text_runs(mut self, runs: impl IntoIterator<Item = TextRun>) -> Self {
3153 self.rich_text_runs = runs.into_iter().collect();
3154 self
3155 }
3156
3157 pub fn with_rich_text_images(
3159 mut self,
3160 images: impl IntoIterator<Item = RichTextImage>,
3161 ) -> Self {
3162 self.rich_text_images = images.into_iter().collect();
3163 self
3164 }
3165
3166 pub fn with_placeholder_text(mut self, text: impl Into<String>) -> Self {
3168 self.placeholder_text = Some(text.into());
3169 self
3170 }
3171
3172 pub fn with_monospace(mut self, monospace: bool) -> Self {
3174 self.monospace = monospace;
3175 self
3176 }
3177}
3178
3179pub fn abstractable_widget_types() -> &'static [WidgetKind] {
3181 &[
3184 WidgetKind::Window,
3185 WidgetKind::Container,
3186 WidgetKind::Label,
3187 WidgetKind::Button,
3188 #[cfg(feature = "widgets-choice")]
3189 WidgetKind::RadioButton,
3190 #[cfg(feature = "widgets-range")]
3191 WidgetKind::Slider,
3192 #[cfg(feature = "widgets-range")]
3193 WidgetKind::SpinBox,
3194 #[cfg(feature = "widgets-containers")]
3195 WidgetKind::Separator,
3196 #[cfg(feature = "widgets-containers")]
3197 WidgetKind::GroupBox,
3198 #[cfg(feature = "widgets-containers")]
3199 WidgetKind::Tabs,
3200 #[cfg(feature = "widgets-media")]
3201 WidgetKind::Image,
3202 #[cfg(feature = "widgets-pickers")]
3203 WidgetKind::DatePicker,
3204 #[cfg(feature = "widgets-text")]
3205 WidgetKind::LinkLabel,
3206 #[cfg(feature = "widgets-data")]
3207 WidgetKind::ListView,
3208 #[cfg(feature = "widgets-data")]
3209 WidgetKind::TreeView,
3210 #[cfg(feature = "widgets-containers")]
3211 WidgetKind::SplitPane,
3212 #[cfg(feature = "widgets-pickers")]
3213 WidgetKind::FileChooserDialog,
3214 #[cfg(feature = "widgets-containers")]
3215 WidgetKind::AlertDialog,
3216 #[cfg(feature = "widgets-text")]
3217 WidgetKind::TextInput,
3218 #[cfg(feature = "widgets-text")]
3219 WidgetKind::TextArea,
3220 #[cfg(feature = "widgets-canvas")]
3221 WidgetKind::VulkanCanvas,
3222 #[cfg(feature = "widgets-choice")]
3223 WidgetKind::Checkbox,
3224 #[cfg(feature = "widgets-choice")]
3225 WidgetKind::ComboBox,
3226 #[cfg(feature = "widgets-range")]
3227 WidgetKind::ProgressBar,
3228 #[cfg(feature = "widgets-data")]
3229 WidgetKind::DataList,
3230 #[cfg(feature = "widgets-data")]
3231 WidgetKind::DataGrid,
3232 #[cfg(feature = "widgets-canvas")]
3233 WidgetKind::Canvas,
3234 #[cfg(feature = "widgets-pickers")]
3235 WidgetKind::ColorDialog,
3236 #[cfg(feature = "widgets-pickers")]
3237 WidgetKind::FontDialog,
3238 WidgetKind::Toolbar,
3239 #[cfg(feature = "widgets-pickers")]
3240 WidgetKind::Calendar,
3241 #[cfg(feature = "widgets-choice")]
3242 WidgetKind::MultiSelect,
3243 ]
3244}
3245
3246#[cfg(test)]
3247mod tests {
3248 use super::*;
3249 use std::cell::Cell;
3250 use std::sync::mpsc;
3251 use std::time::Duration;
3252
3253 #[test]
3254 fn widget_spec_builder_sets_fields() {
3255 let id = WidgetId(1);
3256 let parent = WidgetId(9);
3257 let spec = WidgetSpec::new(id, WidgetKind::Button)
3258 .with_text("Click me")
3259 .with_parent(parent);
3260
3261 assert_eq!(spec.id, id);
3262 assert_eq!(spec.kind, WidgetKind::Button);
3263 assert_eq!(spec.text.as_deref(), Some("Click me"));
3264 assert_eq!(spec.parent, Some(parent));
3265 assert_eq!(spec.container_direction, None);
3266 assert!(!spec.container_scroll_vertical);
3267 assert!(!spec.container_scroll_horizontal);
3268 assert_eq!(spec.size, None);
3269 assert_eq!(spec.position, None);
3270 assert_eq!(spec.data_list_items, Vec::<String>::new());
3271 assert!(spec.data_grid_rows.is_empty());
3272 assert_eq!(spec.background_color, None);
3273 assert_eq!(spec.alert_level, None);
3274 assert_eq!(spec.checked, None);
3275 assert_eq!(spec.range, None);
3276 assert_eq!(spec.step, None);
3277 assert_eq!(spec.value, None);
3278 assert_eq!(spec.group_name, None);
3279 assert_eq!(spec.tab_items, Vec::<String>::new());
3280 assert_eq!(spec.selected_index, None);
3281 assert_eq!(spec.image_source, None);
3282 assert_eq!(spec.date_value, None);
3283 assert_eq!(spec.link_url, None);
3284 assert_eq!(spec.tooltip, None);
3285 assert_eq!(spec.split_ratio, None);
3286 assert_eq!(spec.label_alignment, LabelAlignment::Center);
3287 assert_eq!(spec.label_wrap, LabelWrap::None);
3288
3289 let spec = spec.with_tooltip("Helpful hint");
3290 assert_eq!(spec.tooltip.as_deref(), Some("Helpful hint"));
3291 }
3292
3293 #[test]
3294 fn widget_spec_builder_sets_size() {
3295 let spec = WidgetSpec::new(WidgetId(5), WidgetKind::Button).with_size(120, 44);
3296
3297 assert_eq!(spec.size, Some((120, 44)));
3298 }
3299
3300 #[test]
3301 fn widget_spec_builder_sets_position() {
3302 let spec = WidgetSpec::new(WidgetId(7), WidgetKind::Button).with_position(32, 48);
3303
3304 assert_eq!(spec.position, Some((32, 48)));
3305 }
3306
3307 #[test]
3308 fn widget_spec_builder_sets_background_color() {
3309 let color = Color::rgb(24, 42, 64);
3310 let spec = WidgetSpec::new(WidgetId(6), WidgetKind::Label).with_background_color(color);
3311
3312 assert_eq!(spec.background_color, Some(color));
3313 }
3314
3315 #[test]
3316 #[cfg(feature = "widgets-data")]
3317 fn widget_spec_builder_sets_data_items() {
3318 let list_spec = WidgetSpec::new(WidgetId(10), WidgetKind::DataList)
3319 .with_data_list_items(vec!["A".to_owned(), "B".to_owned()]);
3320 assert_eq!(
3321 list_spec.data_list_items,
3322 vec!["A".to_owned(), "B".to_owned()]
3323 );
3324
3325 let grid_spec =
3326 WidgetSpec::new(WidgetId(11), WidgetKind::DataGrid).with_data_grid_rows(vec![
3327 vec!["r1c1".to_owned(), "r1c2".to_owned()],
3328 vec!["r2c1".to_owned(), "r2c2".to_owned()],
3329 ]);
3330 let expected = vec![
3331 vec!["r1c1".to_owned(), "r1c2".to_owned()],
3332 vec!["r2c1".to_owned(), "r2c2".to_owned()],
3333 ];
3334 assert_eq!(grid_spec.data_grid_rows.as_ref(), &expected);
3335 }
3336
3337 #[test]
3338 fn column_spec_width_preference_follows_shared_size_semantics() {
3339 let column = ColumnSpec::new("Name");
3340 assert_eq!(column.title, "Name");
3341 assert_eq!(column.width, None);
3342 assert_eq!(ColumnSpec::new("Name").with_width(80).width, Some(80));
3343 assert_eq!(
3344 ColumnSpec::new("Name").with_width(0).width,
3345 None,
3346 "non-positive width means no preference"
3347 );
3348 assert_eq!(ColumnSpec::new("Name").with_width(-4).width, None);
3349 }
3350
3351 #[test]
3352 #[cfg(feature = "widgets-data")]
3353 fn widget_spec_builder_sets_list_columns_and_rows() {
3354 let spec = WidgetSpec::new(WidgetId(12), WidgetKind::ListView)
3355 .with_list_columns(vec![ColumnSpec::new("Name"), ColumnSpec::new("Size")])
3356 .with_list_rows(vec![
3357 vec!["a.txt".to_owned(), "12 KB".to_owned()],
3358 vec!["folder".to_owned()],
3359 ]);
3360 assert_eq!(spec.list_columns.len(), 2);
3361 assert_eq!(spec.list_columns[1].title, "Size");
3362 assert_eq!(spec.list_rows.len(), 2);
3363 assert_eq!(spec.list_rows[1], vec!["folder".to_owned()]);
3364
3365 spec_with_columns(WidgetKind::ListView).expect("ListView accepted");
3368 assert_eq!(
3369 spec_with_columns(WidgetKind::DataList).expect_err("DataList rejected"),
3370 GuiError::UnsupportedWidget("set_list_columns")
3371 );
3372 }
3373
3374 fn spec_with_columns(kind: WidgetKind) -> GuiResult<()> {
3376 WidgetSpec::new(WidgetId(13), kind).ensure_property(WidgetProperty::ListViewColumns)
3377 }
3378
3379 #[test]
3380 fn row_diff_classifies_insert_update_move_keep_and_remove() {
3381 let old = [
3382 RowSet::new(1, &["a"]),
3383 RowSet::new(2, &["b"]),
3384 RowSet::new(3, &["c"]),
3385 ];
3386 let new = [
3387 RowSet::new(4, &["d"]),
3388 RowSet::new(2, &["b2"]),
3389 RowSet::new(3, &["c"]),
3390 RowSet::new(1, &["a"]),
3391 ];
3392 assert_eq!(
3393 diff_rows(&old, &new).expect("diff"),
3394 RowDelta {
3395 inserted: 1,
3396 updated: 1,
3397 removed: 0,
3398 moved: 1,
3399 unchanged: 1,
3400 }
3401 );
3402 }
3403
3404 #[test]
3405 fn row_diff_counts_removals_reorders_and_duplicates() {
3406 let old = [
3407 RowSet::new(1, &["a"]),
3408 RowSet::new(2, &["b"]),
3409 RowSet::new(3, &["c"]),
3410 ];
3411 let new = [RowSet::new(1, &["a"])];
3412 let delta = diff_rows(&old, &new).expect("diff");
3413 assert_eq!(delta.removed, 2);
3414 assert_eq!(delta.unchanged, 1);
3415 assert!(!delta.is_noop());
3416
3417 let reordered = [old[2].clone(), old[0].clone(), old[1].clone()];
3420 let delta = diff_rows(&old, &reordered).expect("diff");
3421 assert_eq!(
3422 delta,
3423 RowDelta {
3424 inserted: 0,
3425 updated: 0,
3426 removed: 0,
3427 moved: 3,
3428 unchanged: 0,
3429 }
3430 );
3431 assert!(diff_rows(&old, &old).expect("diff").is_noop());
3432
3433 let duplicates = [RowSet::new(9, &["x"]), RowSet::new(9, &["y"])];
3435 assert_eq!(
3436 diff_rows(&old, &duplicates),
3437 Err(GuiError::Backend("duplicate row key".to_owned()))
3438 );
3439 }
3440
3441 #[test]
3442 fn row_set_builder_and_single_cell_text() {
3443 let row = RowSet::new(7, &["Name", "12 KB"]);
3444 assert_eq!(row.key, RowKey(7));
3445 assert_eq!(row.cells, vec!["Name".to_owned(), "12 KB".to_owned()]);
3446 assert_eq!(row.text(), "Name");
3447 assert_eq!(RowSet::new(8, &[]).text(), "");
3448 }
3449
3450 #[test]
3451 fn container_defaults_to_vertical_direction() {
3452 let spec = WidgetSpec::new(WidgetId(2), WidgetKind::Container);
3453 assert_eq!(spec.container_direction, Some(ContainerDirection::Vertical));
3454 assert!(!spec.container_scroll_vertical);
3455 assert!(!spec.container_scroll_horizontal);
3456 }
3457
3458 #[test]
3459 fn container_builder_sets_scroll_flags() {
3460 let spec =
3461 WidgetSpec::new(WidgetId(3), WidgetKind::Container).with_container_scroll(true, false);
3462 assert!(spec.container_scroll_vertical);
3463 assert!(!spec.container_scroll_horizontal);
3464 }
3465
3466 #[test]
3467 fn abstractable_widget_types_contains_expected_kinds() {
3468 let list = abstractable_widget_types();
3469 assert!(list.contains(&WidgetKind::Window));
3470 assert!(list.contains(&WidgetKind::Button));
3471 #[cfg(feature = "widgets-choice")]
3472 assert!(list.contains(&WidgetKind::RadioButton));
3473 #[cfg(feature = "widgets-range")]
3474 assert!(list.contains(&WidgetKind::Slider));
3475 #[cfg(feature = "widgets-range")]
3476 assert!(list.contains(&WidgetKind::SpinBox));
3477 #[cfg(feature = "widgets-containers")]
3478 assert!(list.contains(&WidgetKind::Separator));
3479 #[cfg(feature = "widgets-containers")]
3480 assert!(list.contains(&WidgetKind::GroupBox));
3481 #[cfg(feature = "widgets-containers")]
3482 assert!(list.contains(&WidgetKind::Tabs));
3483 #[cfg(feature = "widgets-media")]
3484 assert!(list.contains(&WidgetKind::Image));
3485 #[cfg(feature = "widgets-pickers")]
3486 assert!(list.contains(&WidgetKind::DatePicker));
3487 #[cfg(feature = "widgets-text")]
3488 assert!(list.contains(&WidgetKind::LinkLabel));
3489 #[cfg(feature = "widgets-data")]
3490 assert!(list.contains(&WidgetKind::ListView));
3491 #[cfg(feature = "widgets-data")]
3492 assert!(list.contains(&WidgetKind::TreeView));
3493 #[cfg(feature = "widgets-containers")]
3494 assert!(list.contains(&WidgetKind::SplitPane));
3495 #[cfg(feature = "widgets-pickers")]
3496 assert!(list.contains(&WidgetKind::FileChooserDialog));
3497 #[cfg(feature = "widgets-containers")]
3498 assert!(list.contains(&WidgetKind::AlertDialog));
3499 #[cfg(feature = "widgets-text")]
3500 assert!(list.contains(&WidgetKind::TextArea));
3501 #[cfg(feature = "widgets-canvas")]
3502 assert!(list.contains(&WidgetKind::VulkanCanvas));
3503 #[cfg(feature = "widgets-choice")]
3504 assert!(list.contains(&WidgetKind::Checkbox));
3505 #[cfg(feature = "widgets-choice")]
3506 assert!(list.contains(&WidgetKind::ComboBox));
3507 #[cfg(feature = "widgets-range")]
3508 assert!(list.contains(&WidgetKind::ProgressBar));
3509 #[cfg(feature = "widgets-data")]
3510 assert!(list.contains(&WidgetKind::DataList));
3511 #[cfg(feature = "widgets-data")]
3512 assert!(list.contains(&WidgetKind::DataGrid));
3513 #[cfg(feature = "widgets-canvas")]
3514 assert!(list.contains(&WidgetKind::Canvas));
3515 #[cfg(feature = "widgets-pickers")]
3516 assert!(list.contains(&WidgetKind::ColorDialog));
3517 #[cfg(feature = "widgets-pickers")]
3518 assert!(list.contains(&WidgetKind::FontDialog));
3519 assert!(list.contains(&WidgetKind::Toolbar));
3520 #[cfg(feature = "widgets-pickers")]
3521 assert!(list.contains(&WidgetKind::Calendar));
3522 #[cfg(feature = "widgets-choice")]
3523 assert!(list.contains(&WidgetKind::MultiSelect));
3524 let mut expected_len = 8;
3525 if cfg!(feature = "widgets-containers") {
3526 expected_len += 5;
3527 }
3528 if cfg!(feature = "widgets-choice") {
3529 expected_len += 4;
3530 }
3531 if cfg!(feature = "widgets-data") {
3532 expected_len += 4;
3533 }
3534 if cfg!(feature = "widgets-media") {
3535 expected_len += 1;
3536 }
3537 if cfg!(feature = "widgets-canvas") {
3538 expected_len += 2;
3539 }
3540 if cfg!(feature = "widgets-range") {
3541 expected_len += 3;
3542 }
3543 if cfg!(feature = "widgets-pickers") {
3544 expected_len += 5;
3545 }
3546 assert_eq!(list.len(), expected_len);
3547 }
3548
3549 #[cfg(feature = "widgets-containers")]
3550 #[test]
3551 fn alert_dialog_defaults_to_info_level() {
3552 let spec = WidgetSpec::new(WidgetId(12), WidgetKind::AlertDialog);
3553 assert_eq!(spec.alert_level, Some(AlertLevel::Info));
3554 }
3555
3556 #[cfg(feature = "widgets-containers")]
3557 #[test]
3558 fn alert_dialog_builder_sets_level() {
3559 let spec = WidgetSpec::new(WidgetId(13), WidgetKind::AlertDialog)
3560 .with_alert_level(AlertLevel::Error);
3561 assert_eq!(spec.alert_level, Some(AlertLevel::Error));
3562 }
3563
3564 #[test]
3565 fn extended_builder_metadata_sets_fields() {
3566 let spec = WidgetSpec::new(WidgetId(14), WidgetKind::Button)
3567 .with_checked(true)
3568 .with_range(1, 10)
3569 .with_step(2)
3570 .with_value(7)
3571 .with_group_name("group-a")
3572 .with_tab_items(vec!["One".to_owned(), "Two".to_owned()])
3573 .with_selected_index(1)
3574 .with_image_source("./assets/icon.png")
3575 .with_date_value("2026-03-06")
3576 .with_link_url("https://example.com")
3577 .with_split_ratio(80);
3578
3579 assert_eq!(spec.checked, Some(true));
3580 assert_eq!(spec.range, Some((1, 10)));
3581 assert_eq!(spec.step, Some(2));
3582 assert_eq!(spec.value, Some(7));
3583 assert_eq!(spec.group_name.as_deref(), Some("group-a"));
3584 assert_eq!(spec.tab_items, vec!["One".to_owned(), "Two".to_owned()]);
3585 assert_eq!(spec.selected_index, Some(1));
3586 assert_eq!(spec.image_source.as_deref(), Some("./assets/icon.png"));
3587 assert_eq!(spec.date_value.as_deref(), Some("2026-03-06"));
3588 assert_eq!(spec.link_url.as_deref(), Some("https://example.com"));
3589 assert_eq!(spec.split_ratio, Some(80));
3590 }
3591
3592 #[cfg(feature = "widgets-pickers")]
3593 #[test]
3594 fn calendar_date_and_spec_builder_validation() {
3595 let valid_date = CalendarDate::new(2024, 2, 29);
3596 assert!(valid_date.is_valid(), "2024 is leap year");
3597 let invalid_date = CalendarDate::new(2023, 2, 29);
3598 assert!(!invalid_date.is_valid(), "2023 is not leap year");
3599
3600 let spec = WidgetSpec::new(WidgetId(20), WidgetKind::Calendar)
3601 .with_calendar_selected_dates(vec![valid_date])
3602 .with_calendar_bounds(
3603 Some(CalendarDate::new(2024, 1, 1)),
3604 Some(CalendarDate::new(2024, 12, 31)),
3605 )
3606 .with_calendar_first_day_of_week(CalendarFirstDayOfWeek::Monday)
3607 .with_calendar_selection_mode(CalendarSelectionMode::Range);
3608
3609 assert_eq!(spec.calendar_selected_dates, vec![valid_date]);
3610 assert_eq!(spec.calendar_min_date, Some(CalendarDate::new(2024, 1, 1)));
3611 assert_eq!(
3612 spec.calendar_max_date,
3613 Some(CalendarDate::new(2024, 12, 31))
3614 );
3615 assert_eq!(
3616 spec.calendar_first_day_of_week,
3617 CalendarFirstDayOfWeek::Monday
3618 );
3619 assert_eq!(spec.calendar_selection_mode, CalendarSelectionMode::Range);
3620 }
3621
3622 #[test]
3623 fn widget_spec_builder_sets_label_alignment_and_wrap() {
3624 let default_spec = WidgetSpec::new(WidgetId(21), WidgetKind::Label);
3625 assert_eq!(default_spec.label_alignment, LabelAlignment::Left);
3626 assert_eq!(default_spec.label_wrap, LabelWrap::None);
3627 assert!(!default_spec.label_wrap.is_wrapping());
3628
3629 let spec = WidgetSpec::new(WidgetId(22), WidgetKind::Label)
3630 .with_label_alignment(LabelAlignment::Center)
3631 .with_label_wrap(LabelWrap::Word);
3632
3633 assert_eq!(spec.label_alignment, LabelAlignment::Center);
3634 assert_eq!(spec.label_wrap, LabelWrap::Word);
3635 assert!(spec.label_wrap.is_wrapping());
3636
3637 let right_spec = WidgetSpec::new(WidgetId(23), WidgetKind::Label)
3638 .with_label_alignment(LabelAlignment::Right)
3639 .with_label_wrap(true);
3640 assert_eq!(right_spec.label_alignment, LabelAlignment::Right);
3641 assert_eq!(right_spec.label_wrap, LabelWrap::Word);
3642
3643 let nowrap_spec = WidgetSpec::new(WidgetId(24), WidgetKind::Label).with_label_wrap(false);
3644 assert_eq!(nowrap_spec.label_wrap, LabelWrap::None);
3645
3646 let char_wrap_spec =
3647 WidgetSpec::new(WidgetId(25), WidgetKind::Label).with_label_wrap_mode(LabelWrap::Char);
3648 assert_eq!(char_wrap_spec.label_wrap, LabelWrap::Char);
3649
3650 let word_char_spec =
3651 WidgetSpec::new(WidgetId(26), WidgetKind::Label).with_label_wrap(LabelWrap::WordChar);
3652 assert_eq!(word_char_spec.label_wrap, LabelWrap::WordChar);
3653
3654 assert_eq!(
3656 LabelAlignment::from(TextAlignment::Left),
3657 LabelAlignment::Left
3658 );
3659 assert_eq!(
3660 LabelAlignment::from(TextAlignment::Center),
3661 LabelAlignment::Center
3662 );
3663 assert_eq!(
3664 LabelAlignment::from(TextAlignment::Right),
3665 LabelAlignment::Right
3666 );
3667 assert_eq!(
3668 TextAlignment::from(LabelAlignment::Left),
3669 TextAlignment::Left
3670 );
3671 assert_eq!(
3672 TextAlignment::from(LabelAlignment::Center),
3673 TextAlignment::Center
3674 );
3675 assert_eq!(
3676 TextAlignment::from(LabelAlignment::Right),
3677 TextAlignment::Right
3678 );
3679
3680 let from_text_align = WidgetSpec::new(WidgetId(27), WidgetKind::Label)
3682 .with_label_alignment(TextAlignment::Right);
3683 assert_eq!(from_text_align.label_alignment, LabelAlignment::Right);
3684
3685 assert!(default_spec
3687 .ensure_property(WidgetProperty::LabelAlignment)
3688 .is_ok());
3689 assert!(default_spec
3690 .ensure_property(WidgetProperty::LabelWrap)
3691 .is_ok());
3692 let button_spec = WidgetSpec::new(WidgetId(28), WidgetKind::Button);
3693 assert!(button_spec
3694 .ensure_property(WidgetProperty::LabelAlignment)
3695 .is_ok());
3696 assert_eq!(
3697 button_spec.ensure_property(WidgetProperty::LabelWrap),
3698 Err(GuiError::UnsupportedWidget("set_label_wrap"))
3699 );
3700 }
3701
3702 #[test]
3703 #[cfg(feature = "widgets-text")]
3704 fn rich_text_runs_and_style_widget_spec() {
3705 let style = TextStyle::new()
3706 .bold(true)
3707 .italic(true)
3708 .underline(true)
3709 .strikethrough(true)
3710 .monospace(true)
3711 .scale(1.5)
3712 .fg_color(Color::rgb(255, 0, 0))
3713 .bg_color(Color::rgb(0, 255, 0))
3714 .link("https://example.com")
3715 .dimmed(true)
3716 .paragraph_indent(2);
3717
3718 assert!(style.bold);
3719 assert!(style.italic);
3720 assert!(style.underline);
3721 assert!(style.strikethrough);
3722 assert!(style.monospace);
3723 assert_eq!(style.scale, Some(1.5));
3724 assert_eq!(style.fg_color, Some(Color::rgb(255, 0, 0)));
3725 assert_eq!(style.bg_color, Some(Color::rgb(0, 255, 0)));
3726 assert_eq!(style.link.as_deref(), Some("https://example.com"));
3727 assert!(style.dimmed);
3728 assert_eq!(style.paragraph_indent, 2);
3729
3730 let run = TextRun::new(0..12, style.clone());
3731 assert_eq!(run.range, 0..12);
3732 assert_eq!(run.style, style);
3733
3734 let spec = WidgetSpec::new(WidgetId(29), WidgetKind::RichText)
3735 .with_rich_text_runs(vec![run.clone()]);
3736 assert_eq!(spec.kind, WidgetKind::RichText);
3737 assert_eq!(spec.rich_text_runs, vec![run]);
3738
3739 assert!(spec.ensure_property(WidgetProperty::RichTextRuns).is_ok());
3741 assert!(spec.requires_property(WidgetProperty::RichTextRuns).is_ok());
3742 assert_eq!(WidgetProperty::RichTextRuns.name(), "set_rich_text_runs");
3743 assert_eq!(
3744 WidgetProperty::RichTextRuns.operation(),
3745 "set_rich_text_runs"
3746 );
3747
3748 let button_spec = WidgetSpec::new(WidgetId(30), WidgetKind::Button);
3749 assert_eq!(
3750 button_spec.ensure_property(WidgetProperty::RichTextRuns),
3751 Err(GuiError::UnsupportedWidget("set_rich_text_runs"))
3752 );
3753 assert_eq!(
3754 button_spec.requires_property(WidgetProperty::RichTextRuns),
3755 Err(GuiError::UnsupportedWidget("set_rich_text_runs"))
3756 );
3757 }
3758
3759 #[test]
3760 #[cfg(feature = "widgets-text")]
3761 fn rich_text_images_widget_spec() {
3762 let img = RichTextImage::new(10, "assets/diagram.png", Some(640));
3763 assert_eq!(img.offset, 10);
3764 assert_eq!(img.source, "assets/diagram.png");
3765 assert_eq!(img.max_width, Some(640));
3766
3767 let spec = WidgetSpec::new(WidgetId(31), WidgetKind::RichText)
3768 .with_rich_text_images(vec![img.clone()]);
3769 assert_eq!(spec.kind, WidgetKind::RichText);
3770 assert_eq!(spec.rich_text_images, vec![img]);
3771
3772 assert!(spec.ensure_property(WidgetProperty::RichTextImages).is_ok());
3774 assert!(spec
3775 .requires_property(WidgetProperty::RichTextImages)
3776 .is_ok());
3777 assert_eq!(
3778 WidgetProperty::RichTextImages.name(),
3779 "set_rich_text_images"
3780 );
3781 assert_eq!(
3782 WidgetProperty::RichTextImages.operation(),
3783 "set_rich_text_images"
3784 );
3785
3786 let button_spec = WidgetSpec::new(WidgetId(32), WidgetKind::Button);
3787 assert_eq!(
3788 button_spec.ensure_property(WidgetProperty::RichTextImages),
3789 Err(GuiError::UnsupportedWidget("set_rich_text_images"))
3790 );
3791 assert_eq!(
3792 button_spec.requires_property(WidgetProperty::RichTextImages),
3793 Err(GuiError::UnsupportedWidget("set_rich_text_images"))
3794 );
3795 }
3796
3797 fn variant_index(property: WidgetProperty) -> usize {
3804 match property {
3805 WidgetProperty::Checked => 0,
3806 WidgetProperty::Value => 1,
3807 WidgetProperty::Range => 2,
3808 WidgetProperty::Step => 3,
3809 WidgetProperty::SelectedIndex => 4,
3810 WidgetProperty::TabItems => 5,
3811 WidgetProperty::SelectedIndices => 6,
3812 WidgetProperty::RowDrag => 7,
3813 WidgetProperty::DataListItems => 8,
3814 WidgetProperty::ListViewColumns => 9,
3815 WidgetProperty::ListViewRows => 10,
3816 WidgetProperty::DataGridRows => 11,
3817 WidgetProperty::DataGridModel => 12,
3818 WidgetProperty::DataGridRowHeight => 13,
3819 WidgetProperty::DataGridColWidth => 14,
3820 WidgetProperty::DataGridFrozenPanes => 15,
3821 WidgetProperty::DataGridSelection => 16,
3822 WidgetProperty::TreeItems => 17,
3823 WidgetProperty::AlertLevel => 18,
3824 WidgetProperty::ImageSource => 19,
3825 WidgetProperty::ImageFit => 20,
3826 WidgetProperty::ButtonIcon => 21,
3827 WidgetProperty::FileChooserMode => 22,
3828 WidgetProperty::ColorDialogData => 23,
3829 WidgetProperty::FontDialogData => 24,
3830 WidgetProperty::ToolbarItems => 25,
3831 WidgetProperty::ToolbarOrientation => 26,
3832 WidgetProperty::DateValue => 27,
3833 WidgetProperty::LinkUrl => 28,
3834 WidgetProperty::TextSelection => 29,
3835 WidgetProperty::TextCompletion => 30,
3836 WidgetProperty::ContainerDirection => 31,
3837 WidgetProperty::ContainerScroll => 32,
3838 WidgetProperty::ContainerGap => 33,
3839 WidgetProperty::ContainerPadding => 34,
3840 WidgetProperty::CanvasScene => 35,
3841 WidgetProperty::CanvasSurface => 36,
3842 WidgetProperty::CloseGuard => 37,
3843 WidgetProperty::LayoutRoot => 38,
3844 WidgetProperty::WindowCallback => 39,
3845 WidgetProperty::NativeHandle => 40,
3846 WidgetProperty::DrawDemoCube => 41,
3847 WidgetProperty::CopyToClipboard => 42,
3848 WidgetProperty::PasteFromClipboard => 43,
3849 WidgetProperty::KeyedRows => 44,
3850 WidgetProperty::ClearSelection => 45,
3851 WidgetProperty::VisibleAnchor => 46,
3852 WidgetProperty::CalendarDates => 47,
3853 WidgetProperty::CalendarBounds => 48,
3854 WidgetProperty::CalendarFirstDayOfWeek => 49,
3855 WidgetProperty::CalendarSelectionMode => 50,
3856 WidgetProperty::LabelAlignment => 51,
3857 WidgetProperty::LabelWrap => 52,
3858 WidgetProperty::RichTextRuns => 53,
3859 WidgetProperty::PlaceholderText => 54,
3860 WidgetProperty::RichTextImages => 55,
3861 WidgetProperty::Monospace => 56,
3862 WidgetProperty::MetalHandle => 57,
3863 WidgetProperty::ContainerWrap => 58,
3864 WidgetProperty::Font => 59,
3865 WidgetProperty::RowIcons => 60,
3866 }
3867 }
3868
3869 #[test]
3870 fn property_all_covers_every_declared_variant() {
3871 let mut indices: Vec<usize> = WidgetProperty::ALL
3872 .iter()
3873 .copied()
3874 .map(variant_index)
3875 .collect();
3876 indices.sort_unstable();
3877 assert_eq!(
3878 indices,
3879 (0..WidgetProperty::ALL.len()).collect::<Vec<usize>>(),
3880 "WidgetProperty::ALL must list every variant exactly once"
3881 );
3882 }
3883
3884 #[test]
3885 fn property_table_rows_are_well_formed() {
3886 let mut operations = Vec::new();
3887 for &property in WidgetProperty::ALL {
3888 let row = property.applicable_kinds();
3889 let image_property = matches!(
3890 property,
3891 WidgetProperty::ImageSource | WidgetProperty::ImageFit
3892 );
3893 let canvas_property = matches!(
3894 property,
3895 WidgetProperty::CanvasScene
3896 | WidgetProperty::CanvasSurface
3897 | WidgetProperty::NativeHandle
3898 | WidgetProperty::DrawDemoCube
3899 | WidgetProperty::MetalHandle
3900 );
3901 let range_property = matches!(
3902 property,
3903 WidgetProperty::Value | WidgetProperty::Range | WidgetProperty::Step
3904 );
3905 let choice_property = matches!(property, WidgetProperty::Checked);
3906 let data_property = matches!(property, WidgetProperty::RowIcons);
3907 if (cfg!(feature = "widgets-media") || !image_property)
3908 && (cfg!(feature = "widgets-canvas") || !canvas_property)
3909 && (cfg!(feature = "widgets-range") || !range_property)
3910 && (cfg!(feature = "widgets-choice") || !choice_property)
3911 && (cfg!(feature = "widgets-data") || !data_property)
3912 {
3913 assert!(
3914 !row.is_empty(),
3915 "{property:?} must accept at least one kind"
3916 );
3917 } else {
3918 assert!(
3919 row.is_empty(),
3920 "{property:?} must have no applicable kind when its feature is off"
3921 );
3922 }
3923 for kind in row {
3924 assert!(
3925 ALL_KINDS.contains(kind),
3926 "{property:?} row names {kind:?}, which ALL_KINDS does not declare"
3927 );
3928 }
3929 let mut unique = row.to_vec();
3930 unique.sort_by_key(|kind| variant_kind_index(*kind));
3931 unique.dedup();
3932 assert_eq!(
3933 unique.len(),
3934 row.len(),
3935 "{property:?} row contains duplicate kinds"
3936 );
3937
3938 let operation = property.operation();
3939 assert!(
3940 !operation.is_empty(),
3941 "{property:?} must have a stable operation name"
3942 );
3943 assert!(
3944 !operations.contains(&operation),
3945 "operation name {operation:?} is used by two properties"
3946 );
3947 operations.push(operation);
3948 }
3949
3950 let mut kinds = ALL_KINDS.to_vec();
3951 kinds.sort_by_key(|kind| variant_kind_index(*kind));
3952 let declared = kinds.len();
3953 kinds.dedup();
3954 assert_eq!(declared, kinds.len(), "ALL_KINDS contains duplicates");
3955
3956 if !cfg!(feature = "widgets-media") {
3957 assert!(ALL_KINDS.iter().all(|kind| {
3958 !WidgetProperty::ImageSource.supports(*kind)
3959 && !WidgetProperty::ImageFit.supports(*kind)
3960 }));
3961 }
3962
3963 if !cfg!(feature = "widgets-canvas") {
3964 assert!(ALL_KINDS.iter().all(|kind| {
3965 !WidgetProperty::CanvasScene.supports(*kind)
3966 && !WidgetProperty::CanvasSurface.supports(*kind)
3967 && !WidgetProperty::NativeHandle.supports(*kind)
3968 && !WidgetProperty::DrawDemoCube.supports(*kind)
3969 && !WidgetProperty::MetalHandle.supports(*kind)
3970 }));
3971 }
3972
3973 if !cfg!(feature = "widgets-range") {
3974 assert!(ALL_KINDS.iter().all(|kind| {
3975 !WidgetProperty::Value.supports(*kind)
3976 && !WidgetProperty::Range.supports(*kind)
3977 && !WidgetProperty::Step.supports(*kind)
3978 }));
3979 }
3980
3981 if !cfg!(feature = "widgets-choice") {
3982 assert!(ALL_KINDS
3983 .iter()
3984 .all(|kind| { !WidgetProperty::Checked.supports(*kind) }));
3985 }
3986
3987 if !cfg!(feature = "widgets-data") {
3988 assert!(ALL_KINDS
3989 .iter()
3990 .all(|kind| { !WidgetProperty::RowIcons.supports(*kind) }));
3991 }
3992 }
3993
3994 fn variant_kind_index(kind: WidgetKind) -> usize {
3997 ALL_KINDS
3998 .iter()
3999 .position(|candidate| *candidate == kind)
4000 .expect("ALL_KINDS must declare every kind")
4001 }
4002
4003 #[test]
4004 fn ensure_property_accepts_exactly_the_applicability_row() {
4005 for &property in WidgetProperty::ALL {
4006 for &kind in ALL_KINDS {
4007 let spec = WidgetSpec::new(WidgetId(1), kind);
4008 let result = spec.ensure_property(property);
4009 if property.supports(kind) {
4010 assert!(
4011 result.is_ok(),
4012 "{} must accept {kind:?}",
4013 property.operation()
4014 );
4015 } else {
4016 assert_eq!(
4017 result,
4018 Err(GuiError::UnsupportedWidget(property.operation())),
4019 "{} must reject {kind:?} with the typed error",
4020 property.operation()
4021 );
4022 }
4023 }
4024 }
4025 }
4026
4027 struct WindowedProbe {
4033 model: WindowedDataGridModel,
4034 handle: WindowedDataGridHandle,
4035 requested: Rc<RefCell<Vec<usize>>>,
4036 repaints: Rc<Cell<usize>>,
4037 }
4038
4039 fn probe(row_count: usize, col_count: usize, config: WindowedDataGridConfig) -> WindowedProbe {
4040 let requested = Rc::new(RefCell::new(Vec::new()));
4041 let repaints = Rc::new(Cell::new(0usize));
4042 let model = WindowedDataGridModel::new(
4043 row_count,
4044 col_count,
4045 config,
4046 {
4047 let requested = Rc::clone(&requested);
4048 move |row| requested.borrow_mut().push(row)
4049 },
4050 {
4051 let repaints = Rc::clone(&repaints);
4052 move || repaints.set(repaints.get() + 1)
4053 },
4054 );
4055 let handle = model.handle();
4056 WindowedProbe {
4057 model,
4058 handle,
4059 requested,
4060 repaints,
4061 }
4062 }
4063
4064 #[test]
4065 fn windowed_model_schedules_one_fetch_per_row_and_answers_reads_from_the_window() {
4066 let probe = probe(3, 2, WindowedDataGridConfig::new(2, 1024));
4067
4068 assert_eq!(probe.model.value_at(0, 1), "…");
4070 assert_eq!(probe.handle.misses(), 1);
4071 assert_eq!(probe.handle.fetches_requested(), 1);
4072 assert_eq!(*probe.requested.borrow(), vec![0]);
4073 assert_eq!(probe.repaints.get(), 1);
4074 assert!(probe.handle.is_row_in_flight(0));
4075 assert!(!probe.model.is_row_resident(0));
4076
4077 assert_eq!(probe.model.value_at(1, 0), "…");
4080 assert_eq!(probe.model.value_at(1, 1), "…");
4081 assert_eq!(probe.handle.misses(), 3);
4082 assert_eq!(probe.handle.fetches_requested(), 2);
4083 assert_eq!(*probe.requested.borrow(), vec![0, 1]);
4084 assert_eq!(probe.repaints.get(), 2);
4085
4086 assert_eq!(
4088 probe
4089 .handle
4090 .deliver_row(1, vec!["1a".to_owned(), "1b".to_owned()]),
4091 WindowedDelivery::Applied {
4092 evicted: Vec::new()
4093 }
4094 );
4095 assert!(probe.handle.is_row_resident(1));
4096 assert!(probe.model.is_row_resident(1));
4097 assert!(!probe.handle.is_row_in_flight(1));
4098 assert_eq!(probe.model.value_at(1, 1), "1b");
4099 assert_eq!(probe.handle.hits(), 1);
4100 assert_eq!(probe.handle.resident_row_count(), 1);
4101
4102 assert_eq!(probe.model.value_at(3, 0), "");
4105 assert_eq!(probe.model.value_at(1, 2), "");
4106 assert_eq!(probe.handle.misses(), 3);
4107 assert_eq!(probe.handle.hits(), 1);
4108 assert!(
4109 !probe.model.is_row_resident(3),
4110 "out-of-range is not resident"
4111 );
4112 }
4113
4114 #[test]
4115 fn windowed_model_lru_eviction_prefers_the_least_recently_used_row() {
4116 let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
4117 for row in 0..2 {
4118 assert_eq!(probe.model.value_at(row, 0), "…");
4119 assert_eq!(
4120 probe.handle.deliver_row(row, vec![format!("r{row}")]),
4121 WindowedDelivery::Applied {
4122 evicted: Vec::new()
4123 }
4124 );
4125 }
4126
4127 assert_eq!(probe.model.value_at(2, 0), "…");
4129 assert_eq!(
4130 probe.handle.deliver_row(2, vec!["r2".to_owned()]),
4131 WindowedDelivery::Applied { evicted: vec![0] }
4132 );
4133 assert!(!probe.handle.is_row_resident(0));
4134 assert_eq!(probe.handle.resident_row_count(), 2);
4135 assert_eq!(probe.handle.evictions(), 1);
4136
4137 assert_eq!(probe.model.value_at(1, 0), "r1");
4139 assert_eq!(probe.model.value_at(3, 0), "…");
4140 assert_eq!(
4141 probe.handle.deliver_row(3, vec!["r3".to_owned()]),
4142 WindowedDelivery::Applied { evicted: vec![2] }
4143 );
4144 assert!(probe.handle.is_row_resident(1));
4145 assert!(probe.handle.is_row_resident(3));
4146 assert_eq!(probe.handle.evictions(), 2);
4147 }
4148
4149 #[test]
4150 fn windowed_model_evicts_on_the_byte_budget_and_refuses_oversized_rows() {
4151 let probe = probe(8, 1, WindowedDataGridConfig::new(8, 10));
4152 assert_eq!(probe.model.value_at(0, 0), "…");
4153 assert_eq!(
4154 probe.handle.deliver_row(0, vec!["aaaaa".to_owned()]),
4155 WindowedDelivery::Applied {
4156 evicted: Vec::new()
4157 }
4158 );
4159 assert_eq!(probe.model.value_at(1, 0), "…");
4160 assert_eq!(
4161 probe.handle.deliver_row(1, vec!["bbbbb".to_owned()]),
4162 WindowedDelivery::Applied {
4163 evicted: Vec::new()
4164 }
4165 );
4166 assert_eq!(probe.handle.resident_bytes(), 10);
4167
4168 assert_eq!(probe.model.value_at(2, 0), "…");
4170 assert_eq!(
4171 probe.handle.deliver_row(2, vec!["ccccc".to_owned()]),
4172 WindowedDelivery::Applied { evicted: vec![0] }
4173 );
4174 assert_eq!(probe.handle.resident_bytes(), 10);
4175 assert!(!probe.handle.is_row_resident(0));
4176
4177 assert_eq!(probe.model.value_at(3, 0), "…");
4181 assert_eq!(
4182 probe.handle.deliver_row(3, vec!["ccccccccccc".to_owned()]),
4183 WindowedDelivery::Rejected(WindowedDeliveryRejection::Oversized)
4184 );
4185 assert!(!probe.handle.is_row_resident(3));
4186 assert!(!probe.handle.is_row_in_flight(3));
4187 assert_eq!(probe.handle.rejected_deliveries(), 1);
4188 let fetches_before = probe.handle.fetches_requested();
4189 assert_eq!(probe.model.value_at(3, 0), "…");
4190 assert_eq!(probe.handle.fetches_requested(), fetches_before + 1);
4191 }
4192
4193 #[test]
4194 fn windowed_model_visible_band_pins_survive_until_replaced_or_cleared() {
4195 let probe = probe(8, 1, WindowedDataGridConfig::new(3, 1024));
4196 probe.handle.pin_visible_band(0, 2);
4197 assert_eq!(probe.handle.pinned_band(), Some((0, 2)));
4198 for row in 0..3 {
4199 assert_eq!(probe.model.value_at(row, 0), "…");
4200 assert_eq!(
4201 probe.handle.deliver_row(row, vec![format!("r{row}")]),
4202 WindowedDelivery::Applied {
4203 evicted: Vec::new()
4204 }
4205 );
4206 }
4207 assert_eq!(probe.handle.resident_row_count(), 3);
4208
4209 assert_eq!(probe.model.value_at(3, 0), "…");
4212 assert_eq!(
4213 probe.handle.deliver_row(3, vec!["r3".to_owned()]),
4214 WindowedDelivery::Applied { evicted: vec![2] }
4215 );
4216 assert!(probe.handle.is_row_resident(0));
4217 assert!(probe.handle.is_row_resident(1));
4218
4219 assert_eq!(probe.model.value_at(4, 0), "…");
4221 assert_eq!(
4222 probe.handle.deliver_row(4, vec!["r4".to_owned()]),
4223 WindowedDelivery::Applied { evicted: vec![3] }
4224 );
4225 assert!(probe.handle.is_row_resident(0));
4226 assert!(probe.handle.is_row_resident(1));
4227 assert_eq!(probe.handle.resident_row_count(), 3);
4228
4229 probe.handle.clear_pinned_band();
4231 assert_eq!(probe.handle.pinned_band(), None);
4232 assert_eq!(probe.model.value_at(5, 0), "…");
4233 assert_eq!(
4234 probe.handle.deliver_row(5, vec!["r5".to_owned()]),
4235 WindowedDelivery::Applied { evicted: vec![0] }
4236 );
4237
4238 probe.handle.pin_visible_band(1, 1);
4241 assert_eq!(probe.model.value_at(6, 0), "…");
4242 assert_eq!(
4243 probe.handle.deliver_row(6, vec!["r6".to_owned()]),
4244 WindowedDelivery::Applied { evicted: vec![4] }
4245 );
4246 assert!(probe.handle.is_row_resident(1));
4247 assert!(probe.handle.is_row_resident(5));
4248 assert!(probe.handle.is_row_resident(6));
4249 assert_eq!(probe.handle.evictions(), 4);
4250 }
4251
4252 #[test]
4253 fn windowed_model_refuses_delivery_when_every_resident_row_is_pinned() {
4254 let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
4255 probe.handle.pin_visible_band(0, 2);
4256 for row in 0..2 {
4257 assert_eq!(probe.model.value_at(row, 0), "…");
4258 assert_eq!(
4259 probe.handle.deliver_row(row, vec![format!("r{row}")]),
4260 WindowedDelivery::Applied {
4261 evicted: Vec::new()
4262 }
4263 );
4264 }
4265
4266 assert_eq!(probe.model.value_at(2, 0), "…");
4267 assert_eq!(
4268 probe.handle.deliver_row(2, vec!["r2".to_owned()]),
4269 WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim)
4270 );
4271 assert_eq!(probe.handle.rejected_deliveries(), 1);
4272 assert_eq!(probe.handle.evictions(), 0);
4273 assert!(!probe.handle.is_row_resident(2));
4274 assert_eq!(probe.handle.resident_row_count(), 2, "the bound held");
4275
4276 probe.handle.clear_pinned_band();
4279 let fetches_before = probe.handle.fetches_requested();
4280 assert_eq!(probe.model.value_at(2, 0), "…");
4281 assert_eq!(probe.handle.fetches_requested(), fetches_before + 1);
4282 assert_eq!(
4283 probe.handle.deliver_row(2, vec!["r2".to_owned()]),
4284 WindowedDelivery::Applied { evicted: vec![0] }
4285 );
4286 assert!(probe.handle.is_row_resident(2));
4287 }
4288
4289 #[test]
4290 fn data_grid_model_trait_forwards_band_pins_to_the_windowed_handle() {
4291 let probe = probe(8, 1, WindowedDataGridConfig::new(2, 1024));
4292 let model: &dyn DataGridModel = &probe.model;
4293
4294 let eager: &dyn DataGridModel = &SimpleDataGridModel {
4297 rows: vec![vec!["a".to_owned()]],
4298 };
4299 eager.pin_visible_band(0, 8);
4300 eager.clear_pinned_band();
4301
4302 model.pin_visible_band(0, 2);
4306 assert_eq!(probe.handle.pinned_band(), Some((0, 2)));
4307 for row in 0..2 {
4308 assert_eq!(model.value_at(row, 0), "…");
4309 assert_eq!(
4310 probe.handle.deliver_row(row, vec![format!("r{row}")]),
4311 WindowedDelivery::Applied {
4312 evicted: Vec::new()
4313 }
4314 );
4315 }
4316 assert_eq!(model.value_at(2, 0), "…");
4317 assert_eq!(
4318 probe.handle.deliver_row(2, vec!["r2".to_owned()]),
4319 WindowedDelivery::Rejected(WindowedDeliveryRejection::NoEvictableVictim)
4320 );
4321
4322 model.clear_pinned_band();
4324 assert_eq!(probe.handle.pinned_band(), None);
4325 }
4326
4327 #[test]
4328 fn windowed_model_discards_stale_duplicate_and_out_of_range_deliveries() {
4329 let probe = probe(3, 1, WindowedDataGridConfig::new(2, 1024));
4330
4331 assert_eq!(
4333 probe.handle.deliver_row(1, vec!["stale".to_owned()]),
4334 WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight)
4335 );
4336 assert_eq!(
4338 probe.handle.deliver_row(9, vec!["x".to_owned()]),
4339 WindowedDelivery::Rejected(WindowedDeliveryRejection::RowOutOfRange)
4340 );
4341 assert_eq!(probe.model.value_at(0, 0), "…");
4343 assert!(matches!(
4344 probe.handle.deliver_row(0, vec!["r0".to_owned()]),
4345 WindowedDelivery::Applied { .. }
4346 ));
4347 assert_eq!(
4348 probe.handle.deliver_row(0, vec!["again".to_owned()]),
4349 WindowedDelivery::Rejected(WindowedDeliveryRejection::NotInFlight)
4350 );
4351 assert_eq!(probe.model.value_at(0, 0), "r0", "no stale overwrite");
4352 assert_eq!(probe.handle.rejected_deliveries(), 3);
4353 }
4354
4355 #[test]
4356 fn windowed_model_drop_closes_the_request_channel_fail_closed() {
4357 let (request_tx, request_rx) = mpsc::channel::<usize>();
4358 let (result_tx, result_rx) = mpsc::channel::<(usize, Vec<String>)>();
4359 let (done_tx, done_rx) = mpsc::channel::<()>();
4360
4361 let worker = std::thread::spawn(move || {
4362 while let Ok(row) = request_rx.recv() {
4363 if result_tx.send((row, vec![format!("row {row}")])).is_err() {
4364 break;
4365 }
4366 }
4367 let _ = done_tx.send(());
4368 });
4369
4370 let model = WindowedDataGridModel::new(
4371 100,
4372 1,
4373 WindowedDataGridConfig::new(4, 4096),
4374 move |row| {
4375 let _ = request_tx.send(row);
4376 },
4377 || {},
4378 );
4379
4380 assert_eq!(model.value_at(7, 0), "…");
4384 assert!(model.handle().is_row_in_flight(7));
4385 drop(model);
4386
4387 done_rx
4388 .recv_timeout(Duration::from_secs(5))
4389 .expect("the producer must stop once the model's request channel closes");
4390 worker.join().expect("worker thread");
4391
4392 for (row, _) in result_rx.try_iter() {
4395 assert_eq!(row, 7);
4396 }
4397 }
4398
4399 #[test]
4400 fn eager_models_report_every_row_resident_by_default() {
4401 let model = SimpleDataGridModel {
4402 rows: vec![vec!["a".to_owned()]],
4403 };
4404 assert!(model.is_row_resident(0));
4405 assert!(
4406 model.is_row_resident(500),
4407 "the default has no non-resident state; out-of-range reads are still total"
4408 );
4409 }
4410
4411 #[test]
4412 fn row_ops_diff_and_apply_update_insert_remove_move() {
4413 let r1 = RowSet::new(1, &["a", "b"]);
4414 let r2 = RowSet::new(2, &["c", "d"]);
4415 let r3 = RowSet::new(3, &["e", "f"]);
4416 let base = vec![r1.clone(), r2.clone(), r3.clone()];
4417
4418 let mut updated = base.clone();
4420 updated[1] = RowSet::new(2, &["c_mod", "d_mod"]);
4421 let delta = diff_rows(&base, &updated).unwrap();
4422 let ops = diff_row_ops(&base, &updated, &delta).expect("pure update should yield ops");
4423 assert_eq!(ops.len(), 1);
4424 match &ops[0] {
4425 RowOp::Update { index, row } => {
4426 assert_eq!(*index, 1);
4427 assert_eq!(row.cells, vec!["c_mod", "d_mod"]);
4428 }
4429 _ => panic!("expected RowOp::Update"),
4430 }
4431 let mut rows = base.clone();
4432 apply_row_ops_to_rows(&mut rows, &ops);
4433 assert_eq!(rows, updated);
4434
4435 let r_new = RowSet::new(99, &["x", "y"]);
4437 let inserted = vec![r1.clone(), r_new.clone(), r2.clone(), r3.clone()];
4438 let delta = diff_rows(&base, &inserted).unwrap();
4439 let ops = diff_row_ops(&base, &inserted, &delta).expect("single insert should yield ops");
4440 assert_eq!(ops.len(), 1);
4441 match &ops[0] {
4442 RowOp::Insert { index, row } => {
4443 assert_eq!(*index, 1);
4444 assert_eq!(row.key.0, 99);
4445 }
4446 _ => panic!("expected RowOp::Insert"),
4447 }
4448 let mut rows = base.clone();
4449 apply_row_ops_to_rows(&mut rows, &ops);
4450 assert_eq!(rows, inserted);
4451
4452 let removed = vec![r1.clone(), r3.clone()];
4454 let delta = diff_rows(&base, &removed).unwrap();
4455 let ops = diff_row_ops(&base, &removed, &delta).expect("single remove should yield ops");
4456 assert_eq!(ops.len(), 1);
4457 match &ops[0] {
4458 RowOp::Remove { index, key } => {
4459 assert_eq!(*index, 1);
4460 assert_eq!(key.0, 2);
4461 }
4462 _ => panic!("expected RowOp::Remove"),
4463 }
4464 let mut rows = base.clone();
4465 apply_row_ops_to_rows(&mut rows, &ops);
4466 assert_eq!(rows, removed);
4467
4468 let moved = vec![r2.clone(), r3.clone(), r1.clone()];
4470 let delta = diff_rows(&base, &moved).unwrap();
4471 let ops = diff_row_ops(&base, &moved, &delta).expect("single move should yield ops");
4472 assert_eq!(ops.len(), 1);
4473 match &ops[0] {
4474 RowOp::Move {
4475 from_index,
4476 to_index,
4477 key,
4478 } => {
4479 assert_eq!(*from_index, 0);
4480 assert_eq!(*to_index, 2);
4481 assert_eq!(key.0, 1);
4482 }
4483 _ => panic!("expected RowOp::Move"),
4484 }
4485 let mut rows = base.clone();
4486 apply_row_ops_to_rows(&mut rows, &ops);
4487 assert_eq!(rows, moved);
4488
4489 let mut cells = vec![
4491 vec!["a".to_owned(), "b".to_owned()],
4492 vec!["c".to_owned(), "d".to_owned()],
4493 ];
4494 let op = RowOp::Update {
4495 index: 0,
4496 row: RowSet::new(1, &["new_a", "new_b"]),
4497 };
4498 apply_row_ops_to_cells(&mut cells, &[op]);
4499 assert_eq!(cells[0], vec!["new_a", "new_b"]);
4500
4501 let mut items = vec!["item1".to_owned(), "item2".to_owned()];
4502 let op_item = RowOp::Insert {
4503 index: 1,
4504 row: RowSet::new(10, &["inserted"]),
4505 };
4506 apply_row_ops_to_items(&mut items, &[op_item]);
4507 assert_eq!(items, vec!["item1", "inserted", "item2"]);
4508 }
4509}