Skip to main content

mitsuami_core/
widget.rs

1//! What the core tells backends to create, and the properties they carry.
2
3use std::fmt;
4use std::path::PathBuf;
5use std::sync::Arc;
6
7use crate::any_value::Opaque;
8use crate::custom::CustomProps;
9use crate::draw::{Color, DisplayList};
10use crate::geometry::{Point, Size};
11use crate::services::{MenuEntry, Shortcut};
12
13/// Stable identity of a node for the lifetime of a [`Ui`](crate::Ui).
14#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
15pub struct NodeId(pub(crate) u32);
16
17impl NodeId {
18    pub fn raw(self) -> u32 {
19        self.0
20    }
21
22    /// For backends and tools that need to rebuild ids, e.g. when replaying a
23    /// command log.
24    pub fn from_raw(raw: u32) -> NodeId {
25        NodeId(raw)
26    }
27}
28
29impl fmt::Display for NodeId {
30    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31        write!(f, "#{}", self.0)
32    }
33}
34
35#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
36pub enum WidgetKind {
37    Window,
38    /// A layout host: a plain native view that we position children in.
39    Container,
40    /// A host for one item of its window's toolbar, the bar across the top
41    /// that shows the window's title (the unified NSToolbar, GTK's header
42    /// bar, a CommandBar on WinUI, Kirigami's page toolbar). A native child
43    /// of the window, after its content. The core lays out what's in it at
44    /// its natural size; the platform places it, at the bar's trailing end.
45    ToolbarItem,
46    /// A window's sidebar: the list down its leading side that picks what
47    /// the window shows (a source list in an NSSplitViewController, a
48    /// libadwaita navigation split view, NavigationView's pane on WinUI, a
49    /// first column in Kirigami's page row). A native child of the window,
50    /// after its content and toolbar items. Its items are data
51    /// ([`Prop::Sections`]), the chosen one [`Prop::SelectedIndex`]; the
52    /// platform draws, places and sizes it, and the window's content is
53    /// what's beside it.
54    Sidebar,
55    /// Core-only grouping used by control flow (`Show`, `For`). Never sent to
56    /// backends; its children are spliced into the nearest native ancestor.
57    Fragment,
58    Text,
59    Button,
60    /// A native button that stays pressed until it's clicked again (an
61    /// `NSButton` of the push-on-push-off type, gtk::ToggleButton,
62    /// ToggleButton, a checkable QQC2.Button). A `Button`'s caption, icon
63    /// and style, and a `Checkbox`'s [`Prop::Checked`], reported as
64    /// `Changed(Bool)`.
65    ToggleButton,
66    /// A native button that opens a menu of actions (a pull-down
67    /// NSPopUpButton, gtk::MenuButton, DropDownButton, a QQC2.Button that
68    /// opens a QQC2.Menu). Its caption, icon and style are a `Button`'s;
69    /// its menu is [`Prop::Menu`], and the item chosen comes as
70    /// [`UiEvent::MenuItem`](crate::UiEvent::MenuItem).
71    MenuButton,
72    TextInput,
73    /// A native password field (NSSecureTextField, PasswordBox,
74    /// gtk::PasswordEntry, Kirigami.PasswordField): a `TextInput` whose
75    /// text is hidden, as each platform hides it.
76    PasswordInput,
77    /// A native search field (NSSearchField, gtk::SearchEntry, an
78    /// AutoSuggestBox with the find icon, Kirigami.SearchField): a
79    /// `TextInput` with the platform's search icon and clear button, which
80    /// asks for a search ([`UiEvent::Search`](crate::UiEvent::Search)) as
81    /// the platform does.
82    SearchInput,
83    /// A native field for text over many lines (an NSTextView in an
84    /// NSScrollView, a TextBox that accepts Return, a gtk::TextView in a
85    /// gtk::ScrolledWindow, a QQC2.TextArea in a QQC2.ScrollView). Its
86    /// lines wrap, Return starts a new one, and it scrolls past
87    /// [`Prop::Lines`], its natural height.
88    TextArea,
89    Checkbox,
90    Switch,
91    /// A native pop-up menu of text options (NSPopUpButton, ComboBox,
92    /// gtk::DropDown, QQC2.ComboBox). Its options are [`Prop::Options`].
93    Select,
94    /// Native radio buttons, one for each of [`Prop::Options`], of which
95    /// one at most is chosen, [`Prop::SelectedIndex`] (NSButtons of the
96    /// radio type, RadioButtons, gtk::CheckButtons in a group,
97    /// QQC2.RadioButtons). Down a column, as each platform stacks them.
98    RadioGroup,
99    /// A native slider (NSSlider, Slider, gtk::Scale, QQC2.Slider): a
100    /// [`Prop::Number`] in a [`Prop::Range`], in [`Prop::Step`]s.
101    Slider,
102    /// A native field for a whole number, with buttons that step it up and
103    /// down (NumberBox, gtk::SpinButton, QQC2.SpinBox; on AppKit an
104    /// NSTextField with an NSStepper beside it, as AppKit apps pair them):
105    /// a [`Prop::Number`] in a [`Prop::Range`], stepped by [`Prop::Step`].
106    /// Whole numbers that fit an `i32`, because Qt's spin box holds an
107    /// `int`.
108    NumberInput,
109    /// A native progress bar (NSProgressIndicator, ProgressBar,
110    /// gtk::ProgressBar, QQC2.ProgressBar): a [`Prop::Progress`].
111    Progress,
112    /// A native spinner for work of unknown length (a spinning
113    /// NSProgressIndicator, gtk::Spinner, ProgressRing,
114    /// QQC2.BusyIndicator). It spins while [`Prop::Running`], and shows
115    /// nothing otherwise.
116    Spinner,
117    /// A native separator line between groups of content (a separator
118    /// NSBox, gtk::Separator, Kirigami.Separator; WinUI has none, so a
119    /// `Border` in the divider brush, as Fluent apps draw one). It runs as
120    /// [`Prop::Orientation`] says and is as thick as the platform draws
121    /// it; the layout gives it its length.
122    Separator,
123    /// A native image view (NSImageView, Image, gtk::Picture, QML Image):
124    /// a picture from [`Prop::Image`], at its own size unless the layout
125    /// sizes it, fitted as [`Prop::ImageFit`] says.
126    Image,
127    /// An icon from the platform's own set, by its name there: an SF
128    /// Symbol in an NSImageView, a themed icon in a gtk::Image or a
129    /// Kirigami.Icon, a Segoe Fluent Icons glyph in a FontIcon on WinUI.
130    /// [`Prop::Icon`] names it, at the platform's own size unless
131    /// [`Prop::IconSize`] says otherwise.
132    Icon,
133    /// A file's or folder's own icon, as the platform's file manager shows
134    /// it: `NSWorkspace`'s in an NSImageView, GIO's in a gtk::Image, its
135    /// MIME type's in a Kirigami.Icon, the shell's in a XAML Image.
136    /// [`Prop::File`] names it; it's a square as big as the platform's
137    /// small icons unless [`Prop::IconSize`] says otherwise. With
138    /// [`Prop::Thumbnail`], a preview of what's in the file where the
139    /// platform makes one.
140    FileIcon,
141    /// A native surface the app presents to with its own GPU API, off the
142    /// UI thread (an `NSView` backed by a `CAMetalLayer`, a Wayland
143    /// subsurface, a child window). The backend reports it as
144    /// `SurfaceReady`, then its size in pixels as `SurfaceResized`; with
145    /// [`Prop::TakesInput`], its keys and pointer as `SurfaceInput`.
146    GpuSurface,
147    /// A native scroll container. It has exactly one native child, the
148    /// content, which the core lays out and may be larger than the viewport.
149    ScrollView,
150    /// A native list control (NSTableView, ListView, gtk::ListView, QML
151    /// ListView). Its data is [`Prop::Rows`]. The platform decides which rows
152    /// exist (`RowShown`, `RowHidden`); its native children are the hosts of
153    /// the rows the core mounted for those (`Container`s with a
154    /// [`Prop::Row`]), in row order. It scrolls like a `ScrollView`.
155    List,
156    /// A native table: a `List` whose rows are cells under column headers
157    /// (NSTableView with columns and a header, gtk::ColumnView, a QML
158    /// TableView under a HorizontalHeaderView; WinUI has none, so a
159    /// ListView under a header of column buttons, as Fluent apps build
160    /// one). Its columns are [`Prop::Columns`], sorted as [`Prop::Sort`]
161    /// says. Its data, selection and scrolling are a `List`'s; its native
162    /// children are the hosts of the cells the core mounted for the rows it
163    /// shows (`Container`s with a [`Prop::Cell`]), in row order, then
164    /// column order. The platform sizes its columns, and the user resizes
165    /// them: it reports the width each column gives its cells
166    /// (`ColumnWidths`).
167    Table,
168    /// A native tab view: pages, one shown at a time, and a strip of their
169    /// titles to pick one (NSTabView, libadwaita's inline view switcher or
170    /// a gtk::Notebook, a SelectorBar over its pages on WinUI, Kirigami's
171    /// NavigationTabBar or a QQC2.TabBar). Its native
172    /// children are its pages' hosts (`Container`s), in order, titled by
173    /// [`Prop::TabTitles`]; the shown one is [`Prop::SelectedIndex`].
174    /// Every page stays mounted. The core lays out each page at the size
175    /// inside the tab strip and border ([`PlatformMetrics::tab_insets`](crate::PlatformMetrics)),
176    /// all in the same place, so the view is as big as its biggest page;
177    /// the platform places them and shows the chosen one.
178    Tabs,
179    /// A native box around related content, under an optional heading
180    /// ([`Prop::Title`]): an NSBox, libadwaita's card under a heading, a
181    /// Fluent card under a heading on WinUI, a QQC2.GroupBox. The core lays
182    /// out its children as a container's, inside
183    /// [`PlatformMetrics::group_insets`](crate::PlatformMetrics) (or the
184    /// titled ones), and it's at least as wide as its heading, which
185    /// backends measure. Backends draw the box behind the children, which
186    /// are its native children.
187    Group,
188    /// A custom widget (see [`CustomWidget`](crate::CustomWidget)), named
189    /// after it. Its props travel as [`Prop::Custom`].
190    Custom(&'static str),
191    /// A raw native view supplied by app code. Its factory and updates
192    /// travel as [`Prop::Native`].
193    Native,
194}
195
196impl WidgetKind {
197    pub fn is_native(self) -> bool {
198        self != WidgetKind::Fragment
199    }
200
201    /// Containers lay out children; everything else is measured by the backend.
202    pub fn is_container(self) -> bool {
203        matches!(
204            self,
205            WidgetKind::Window
206                | WidgetKind::Container
207                | WidgetKind::ToolbarItem
208                | WidgetKind::ScrollView
209                | WidgetKind::Tabs
210                | WidgetKind::Group
211        )
212    }
213
214    /// Scrolls its content: `ScrollTo` and `Scrolled` apply.
215    pub fn scrolls(self) -> bool {
216        matches!(self, WidgetKind::ScrollView | WidgetKind::List | WidgetKind::Table)
217    }
218
219    /// Has rows the platform realises: a `List` or a `Table`.
220    pub fn has_rows(self) -> bool {
221        matches!(self, WidgetKind::List | WidgetKind::Table)
222    }
223
224    pub fn name(self) -> &'static str {
225        match self {
226            WidgetKind::Window => "Window",
227            WidgetKind::Container => "Container",
228            WidgetKind::ToolbarItem => "ToolbarItem",
229            WidgetKind::Sidebar => "Sidebar",
230            WidgetKind::ScrollView => "ScrollView",
231            WidgetKind::List => "List",
232            WidgetKind::Table => "Table",
233            WidgetKind::Tabs => "Tabs",
234            WidgetKind::Group => "Group",
235            WidgetKind::Fragment => "Fragment",
236            WidgetKind::Text => "Text",
237            WidgetKind::Button => "Button",
238            WidgetKind::ToggleButton => "ToggleButton",
239            WidgetKind::MenuButton => "MenuButton",
240            WidgetKind::TextInput => "TextInput",
241            WidgetKind::PasswordInput => "PasswordInput",
242            WidgetKind::SearchInput => "SearchInput",
243            WidgetKind::TextArea => "TextArea",
244            WidgetKind::Checkbox => "Checkbox",
245            WidgetKind::Switch => "Switch",
246            WidgetKind::Select => "Select",
247            WidgetKind::RadioGroup => "RadioGroup",
248            WidgetKind::Slider => "Slider",
249            WidgetKind::NumberInput => "NumberInput",
250            WidgetKind::Progress => "Progress",
251            WidgetKind::Spinner => "Spinner",
252            WidgetKind::Separator => "Separator",
253            WidgetKind::Image => "Image",
254            WidgetKind::Icon => "Icon",
255            WidgetKind::FileIcon => "FileIcon",
256            WidgetKind::GpuSurface => "GpuSurface",
257            WidgetKind::Custom(name) => name,
258            WidgetKind::Native => "Native",
259        }
260    }
261}
262
263/// Semantic text styles, mapped to each platform's type ramp.
264#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
265pub enum TextStyle {
266    LargeTitle,
267    Title,
268    Headline,
269    #[default]
270    Body,
271    Callout,
272    Caption,
273    Monospace,
274}
275
276/// How heavy a `Text`'s font is, in place of its text style's weight.
277/// A platform whose font lacks one uses the nearest it has.
278#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
279pub enum FontWeight {
280    #[default]
281    Regular,
282    Medium,
283    Semibold,
284    Bold,
285}
286
287/// Where a `Text`'s lines go across its frame, in its reading direction:
288/// `Start` is the left in left-to-right text, the right in right-to-left.
289#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
290pub enum TextAlign {
291    #[default]
292    Start,
293    Center,
294    End,
295}
296
297/// Where a `Text` cut off at its line limit puts its ellipsis: in place
298/// of its start, its middle (a path's folders, keeping its file name) or
299/// its end. Start and end are the text's, so in right-to-left text the
300/// start is on the right. Platforms that can't put one there cut off the
301/// end, as their labels do.
302#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
303pub enum Truncation {
304    Start,
305    Middle,
306    #[default]
307    End,
308}
309
310/// A [`TextAlign`] the core has resolved against the text's direction, as
311/// backends get it.
312#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
313pub enum HorizontalAlign {
314    #[default]
315    Left,
316    Center,
317    Right,
318}
319
320/// Which way a native widget lays itself out, as backends get it: the
321/// core has resolved the node's direction (its own, its parent's, or the
322/// app's language's).
323#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
324pub enum LayoutDirection {
325    #[default]
326    LeftToRight,
327    RightToLeft,
328}
329
330/// What a `TextInput` is for, which the platform uses as it uses one: to
331/// pick an on-screen keyboard, to offer autofill, to check what's typed.
332/// Only the purposes every platform has.
333#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
334pub enum InputPurpose {
335    /// Any text.
336    #[default]
337    Text,
338    Email,
339    Url,
340    /// A telephone number.
341    Phone,
342}
343
344/// What a button does in its window or dialog, which each platform shows
345/// and handles its own way. Platforms without an equivalent ignore it.
346#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
347pub enum ButtonRole {
348    /// An ordinary button.
349    #[default]
350    Normal,
351    /// The action Return confirms: the default button on AppKit (Return
352    /// clicks it), the suggested action on GTK, the default button on Qt, the
353    /// accent button on WinUI. One per window or dialog.
354    Default,
355    /// The action Escape takes: the cancel button on AppKit (Escape clicks
356    /// it). The others show it as a normal button.
357    Cancel,
358    /// An action that destroys data: GTK's destructive action; AppKit marks
359    /// it so the system can warn. Qt and WinUI have no such style.
360    Destructive,
361}
362
363/// How a `Tabs` shows its tabs, where the platform has more than one way
364/// (GNOME and KDE). The others show theirs, and ignore it.
365#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
366pub enum TabsStyle {
367    /// The platform's own: navigation tabs on GNOME and KDE.
368    #[default]
369    Automatic,
370    /// A tab bar over the pages: GTK's `gtk::Notebook`, Qt's
371    /// `QQC2.TabBar`.
372    TabBar,
373    /// Navigation tabs above the pages: libadwaita's inline view switcher
374    /// (a tab bar before libadwaita 1.7), Kirigami's `NavigationTabBar`.
375    Navigation,
376}
377
378/// How a button is drawn, mapped to each platform's native look.
379#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
380pub enum ButtonStyle {
381    /// The same as `Bordered`, on every platform.
382    #[default]
383    Automatic,
384    /// The platform's push button, with its bezel or frame.
385    Bordered,
386    /// No bezel or frame until hovered, where the platform does that: for
387    /// toolbars, and buttons that sit among text.
388    Borderless,
389}
390
391/// What an `Image` shows.
392#[derive(Clone, Debug, PartialEq)]
393pub enum ImageSource {
394    /// An image file, decoded by the platform: PNG and JPEG everywhere,
395    /// other formats where the platform reads them. It's read when the
396    /// source is set; a file that changes under the same path isn't read
397    /// again.
398    File(PathBuf),
399    /// Pixels the app has in memory.
400    Pixels(Pixels),
401}
402
403/// An image in memory: rows of straight (not premultiplied) RGBA8, top
404/// row first, drawn at `scale` pixels to a point, so an image made at the
405/// window's scale factor is shown pixel for pixel.
406#[derive(Clone, PartialEq)]
407pub struct Pixels {
408    width: u32,
409    height: u32,
410    scale: f32,
411    rgba: Arc<[u8]>,
412}
413
414/// Its size and scale, not its bytes.
415impl fmt::Debug for Pixels {
416    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
417        write!(f, "Pixels({}×{} @{}x)", self.width, self.height, self.scale)
418    }
419}
420
421impl Pixels {
422    /// Panics unless `rgba` holds `width × height` pixels.
423    pub fn new(width: u32, height: u32, rgba: impl Into<Arc<[u8]>>) -> Pixels {
424        let rgba = rgba.into();
425        // Checked: a size that wraps could pass with too few bytes, which
426        // backends hand to the platform as the whole image.
427        let len = (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(4));
428        assert_eq!(Some(rgba.len()), len, "{width}×{height} RGBA8 pixels");
429        Pixels { width, height, scale: 1.0, rgba }
430    }
431
432    /// Pixels to a point; 1 by default.
433    pub fn scale(mut self, scale: f32) -> Pixels {
434        assert!(scale > 0.0, "a scale above 0");
435        self.scale = scale;
436        self
437    }
438
439    pub fn width(&self) -> u32 {
440        self.width
441    }
442
443    pub fn height(&self) -> u32 {
444        self.height
445    }
446
447    pub fn scale_factor(&self) -> f32 {
448        self.scale
449    }
450
451    pub fn rgba(&self) -> &[u8] {
452        &self.rgba
453    }
454
455    /// Its size in points.
456    pub fn size(&self) -> crate::Size {
457        crate::Size::new(self.width as f32 / self.scale, self.height as f32 / self.scale)
458    }
459}
460
461/// How an `Image` fills a frame the layout makes a different size from
462/// it. Only the fits every platform's image view has; without one, each
463/// fits as it does by default.
464#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
465pub enum ImageFit {
466    /// As large as fits, keeping its proportions (NSImageView
467    /// proportionally up or down, GTK `Contain`, Qt `PreserveAspectFit`,
468    /// XAML `Uniform`).
469    Contain,
470    /// The whole frame, proportions or not (axes independently, `Fill`,
471    /// `Stretch`, `Fill`).
472    Stretch,
473}
474
475/// The pointer's cursor over a `GpuSurface`, while it isn't locked.
476#[derive(Clone, Debug, Default, PartialEq)]
477pub enum Cursor {
478    /// The platform's own: the arrow.
479    #[default]
480    Default,
481    /// None: the pointer still moves, unseen (a machine that draws its own).
482    Hidden,
483    /// An image of the app's, e.g. the one a machine gives its pointer,
484    /// shown at its scale. `hotspot`: the point that points, in points from
485    /// its top left.
486    Image { pixels: Pixels, hotspot: Point },
487}
488
489/// What a modal `Window` blocks while it's open, shown each platform's way.
490#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
491pub enum Modality {
492    /// The window it belongs to (the one it's declared in): a sheet on
493    /// that window on macOS, Qt's `WindowModal`, an owned `IsModal` window
494    /// on WinUI. GTK's modal windows block the whole app.
495    Window,
496    /// Every other window of the app: a window in AppKit's modal loop,
497    /// Qt's `ApplicationModal`, a modal window on GTK, and on WinUI an
498    /// owned `IsModal` window that also disables the app's other windows.
499    Application,
500}
501
502/// The window whose content is being built: provided in each window's
503/// scope, so views can find the window they're in (a modal `Window`
504/// belongs to it, a `Toolbar`'s items go in its toolbar).
505#[derive(Clone, Copy, Debug, PartialEq, Eq)]
506pub struct CurrentWindow(pub NodeId);
507
508/// Which files a node takes when they're dropped on it: files with these
509/// extensions (any file without a list), and folders if `folders`.
510#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
511pub struct FileDrop {
512    /// Without the dot, compared ignoring case. `None`: any file.
513    pub extensions: Option<Vec<String>>,
514    pub folders: bool,
515}
516
517impl FileDrop {
518    /// Any file, no folders.
519    pub fn files() -> FileDrop {
520        FileDrop { extensions: None, folders: false }
521    }
522
523    /// Files with these extensions (`"iso"`, not `".iso"`), no folders.
524    pub fn extensions<S: Into<String>>(extensions: impl IntoIterator<Item = S>) -> FileDrop {
525        FileDrop { extensions: Some(extensions.into_iter().map(Into::into).collect()), folders: false }
526    }
527
528    /// Folders only.
529    pub fn folders() -> FileDrop {
530        FileDrop { extensions: Some(Vec::new()), folders: true }
531    }
532
533    /// Folders too.
534    pub fn and_folders(mut self) -> FileDrop {
535        self.folders = true;
536        self
537    }
538
539    /// Whether it takes this file or folder, as it is on disk.
540    pub fn accepts(&self, path: &std::path::Path) -> bool {
541        if path.is_dir() {
542            return self.folders;
543        }
544        match &self.extensions {
545            None => true,
546            Some(extensions) => path
547                .extension()
548                .and_then(|e| e.to_str())
549                .is_some_and(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e))),
550        }
551    }
552
553    /// What it takes of these, in order.
554    pub fn accepted(&self, paths: &[PathBuf]) -> Vec<PathBuf> {
555        paths.iter().filter(|p| self.accepts(p)).cloned().collect()
556    }
557}
558
559/// Which way a `Slider` or a `Separator` runs. Every platform has vertical
560/// sliders; larger values are up on all of them.
561#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
562pub enum Orientation {
563    #[default]
564    Horizontal,
565    Vertical,
566}
567
568impl Orientation {
569    pub fn vertical(self) -> bool {
570        self == Orientation::Vertical
571    }
572}
573
574/// Scrolling directions of a `ScrollView`.
575#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
576pub enum ScrollAxes {
577    #[default]
578    Vertical,
579    Horizontal,
580    Both,
581}
582
583impl ScrollAxes {
584    pub fn horizontal(self) -> bool {
585        matches!(self, ScrollAxes::Horizontal | ScrollAxes::Both)
586    }
587
588    pub fn vertical(self) -> bool {
589        matches!(self, ScrollAxes::Vertical | ScrollAxes::Both)
590    }
591}
592
593/// Identity of a row of a `List`, stable while its item's key stays in the
594/// data. Assigned by the core.
595#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
596pub struct RowKey(pub u64);
597
598/// A cell of a `Table`: its row, and its column's index.
599#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
600pub struct CellKey {
601    pub row: RowKey,
602    pub column: usize,
603}
604
605/// A column of a `Table`, as backends get it.
606#[derive(Clone, Debug, PartialEq)]
607pub struct ColumnData {
608    /// Its header's title.
609    pub title: String,
610    /// How wide it starts, in points; `None`: the platform's default. The
611    /// user can resize it, as the platform lets them.
612    pub width: Option<f32>,
613    /// It takes the room the table has past its columns' widths, shared
614    /// with the other columns that do, as the platform shares it.
615    pub expand: bool,
616    /// Its header sorts the table by it when pressed.
617    pub sortable: bool,
618}
619
620/// Which way a `Table` is sorted.
621#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
622pub enum SortOrder {
623    #[default]
624    Ascending,
625    Descending,
626}
627
628impl SortOrder {
629    /// The other way round.
630    pub fn reversed(self) -> SortOrder {
631        match self {
632            SortOrder::Ascending => SortOrder::Descending,
633            SortOrder::Descending => SortOrder::Ascending,
634        }
635    }
636}
637
638/// The column a `Table` is sorted by, and which way, as its header shows.
639#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
640pub struct ColumnSort {
641    pub column: usize,
642    pub order: SortOrder,
643}
644
645/// How many rows of a `List` can be selected.
646#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
647pub enum SelectionMode {
648    #[default]
649    None,
650    Single,
651    Multiple,
652}
653
654/// How a `List` sits in its surroundings, mapped to each platform's native
655/// look. Choosing per platform is up to the app, with `platform!`.
656#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
657pub enum ListStyle {
658    /// The same as `Plain`, on every platform.
659    #[default]
660    Automatic,
661    /// Edge to edge, on the surface around it: sidebars, a window's main
662    /// content.
663    Plain,
664    /// In a bordered box, on the platform's content background: a list
665    /// inside a form or a dialog.
666    Framed,
667}
668
669impl ListStyle {
670    pub fn framed(self) -> bool {
671        self == ListStyle::Framed
672    }
673}
674
675/// A group of a `Sidebar`'s items, under a heading if it has a title.
676#[derive(Clone, Debug, Default, PartialEq)]
677pub struct SidebarSectionData {
678    pub title: Option<String>,
679    pub items: Vec<SidebarItemData>,
680}
681
682/// One item of a `Sidebar`: its title, and the name of its icon in the
683/// platform's own set (an SF Symbol, a symbolic theme icon, a Segoe
684/// Fluent Icons glyph), which platforms without it ignore.
685#[derive(Clone, Debug, Default, PartialEq)]
686pub struct SidebarItemData {
687    pub title: String,
688    pub icon: Option<String>,
689}
690
691/// A property of a native widget. Which ones apply depends on the kind.
692#[derive(Clone, Debug, PartialEq)]
693pub enum Prop {
694    /// A window's title, or a `Group`'s heading (empty: none).
695    Title(String),
696    /// A window fills its screen, the platform's own way (a Space of its
697    /// own on macOS). The user can change it too (the title bar's button,
698    /// the window manager's key): the backend reports `FullScreenChanged`,
699    /// which the core absorbs.
700    FullScreen(bool),
701    /// The smallest content size the user can make a window, in points.
702    /// A window smaller when it's set grows to it.
703    MinSize(Size),
704    /// The content sets a window's height, not the user, who resizes only
705    /// its width; where the platform can't hold one side (GTK), neither.
706    /// The core sets it for a `WindowSize::FollowHeight` window.
707    HeightFollowsContent(bool),
708    /// A window fills its screen's working area as the platform's maximize
709    /// (on macOS, zoom) does, and is back to its own size without. The user
710    /// can change it too: the backend reports `MaximizedChanged`, which the
711    /// core absorbs. Sent only if the app chose.
712    Maximized(bool),
713    /// The user can resize a window. Without, only the app sets its size;
714    /// sent only if the app chose.
715    Resizable(bool),
716    /// Text content of a `Text`.
717    Text(String),
718    /// How many lines a `Text` shows at most, the last one cut off with an
719    /// ellipsis, as the platform draws one. `None`: all of them.
720    MaxLines(Option<u32>),
721    /// Where a `Text` cut off at its line limit puts its ellipsis. AppKit,
722    /// Qt and WinUI cut off a single line's start or middle only. Sent
723    /// only if the app chose.
724    Truncation(Truncation),
725    /// A `Text`'s or `Icon`'s colour. Semantic colours follow the
726    /// appearance (dark mode, high contrast, the accent colour); `Rgba` is
727    /// fixed. Icons in full colour keep their own; symbolic ones take it.
728    /// Sent only if the app chose.
729    TextColor(Color),
730    /// A `Text`'s weight, in place of its text style's.
731    FontWeight(FontWeight),
732    /// A `Text` in italics.
733    Italic(bool),
734    /// Where a `Text`'s lines go across its frame. The core resolves the
735    /// app's `TextAlign` against the text's direction, so it's left or
736    /// right here.
737    TextAlign(HorizontalAlign),
738    /// Which way a widget lays itself out and draws: a checkbox's box on
739    /// the right of its caption, a slider's minimum on the right, a text
740    /// field's text starting on the right. The core resolves it for every
741    /// native node, and sends it to those that are right to left, and to
742    /// every node of an app whose language is (never to an app that is
743    /// only left to right). Frames are already mirrored: containers don't
744    /// mirror what they hold.
745    LayoutDirection(LayoutDirection),
746    /// A `Text`'s text can be selected and copied by the user. Sent when
747    /// the text is created, and never changed: Qt's selectable label is
748    /// another item.
749    Selectable(bool),
750    /// Caption of a `Button`, `ToggleButton`, `MenuButton`, `Checkbox` or
751    /// `Switch`; accessible name of a `Switch`, `Select`, `RadioGroup`,
752    /// `Slider`, `NumberInput`, `Progress`, `Image`, `Icon` or `GpuSurface`,
753    /// and of a button that shows only its icon.
754    Label(String),
755    /// Current text of a `TextInput`, `PasswordInput`, `SearchInput` or
756    /// `TextArea`; a text area's lines end in `\n`.
757    Value(String),
758    /// What a text field shows while it's empty. Text areas show it where
759    /// the platform's have one (Qt, WinUI).
760    Placeholder(String),
761    /// A `TextInput` or `TextArea` shows its text, which can be selected
762    /// and copied, but not edited: by typing, or by assistive technology.
763    ReadOnly(bool),
764    /// How many lines of text a `TextArea` is tall at its natural size, in
765    /// the platform's font and line spacing; it scrolls past them. The
766    /// layout can still make it taller or shorter.
767    Lines(u32),
768    /// A `TextArea`'s lines wrap to its width. Without, a line is as long
769    /// as its text, and the area scrolls sideways. Sent only if the app
770    /// chose.
771    LineWrap(bool),
772    /// What a `TextInput` is for; sent only if the app chose.
773    InputPurpose(InputPurpose),
774    /// Checked state of a `Checkbox`, `Switch` or `ToggleButton`.
775    Checked(bool),
776    /// A `Checkbox` shows the mixed state (some of what it stands for is
777    /// checked), whatever `Checked` says. A click leaves it: where it lands
778    /// is the platform's call, and the core absorbs it as `Mixed(false)`.
779    Mixed(bool),
780    Enabled(bool),
781    TextStyle(TextStyle),
782    ButtonRole(ButtonRole),
783    ButtonStyle(ButtonStyle),
784    /// A `Select`'s or `RadioGroup`'s options, in order.
785    Options(Vec<String>),
786    /// Which option of a `Select` is chosen: always one, unless it has no
787    /// options. Which option of a `RadioGroup` is: `None` for none. Which item of a `Sidebar` is, counting across its sections:
788    /// `None` for none. Which page of a `Tabs` is shown: always one, unless
789    /// it has no pages.
790    SelectedIndex(Option<usize>),
791    /// A `Slider`'s or `NumberInput`'s value, within its range. The core
792    /// sends it after the range, which may have clamped it.
793    Number(f64),
794    /// The values a `Slider` or `NumberInput` can take.
795    Range {
796        min: f64,
797        max: f64,
798    },
799    /// A `Slider`'s step, used as the platform uses one: to snap to, where
800    /// its sliders snap, and to move by from the keyboard. What a
801    /// `NumberInput`'s buttons and arrow keys add or take away. `None`: the
802    /// platform's default.
803    Step(Option<f64>),
804    /// A `NumberInput` stepped past one end of its range goes on from the
805    /// other. Sent only if the app chose: without, it's the platform's
806    /// (AppKit's stepper wraps, the others stop).
807    WrapAround(bool),
808    /// Which way a `Slider` or a `Separator` runs.
809    Orientation(Orientation),
810    /// Text the platform shows when the pointer rests on the widget, as
811    /// its tooltip, and assistive technology reads as its description.
812    /// Any widget or container can have one; empty: none.
813    Tooltip(String),
814    /// The menu the platform shows its own way on a right-click, a long
815    /// press or the menu key: items, separators and submenus. Any widget
816    /// or container can have one; empty: none. The node reports the item
817    /// chosen as [`UiEvent::ContextMenuItem`](crate::UiEvent::ContextMenuItem).
818    ContextMenu(Vec<MenuEntry>),
819    /// A `MenuButton`'s menu: items, separators and submenus, built as a
820    /// context menu's. The node reports the item chosen as
821    /// [`UiEvent::MenuItem`](crate::UiEvent::MenuItem).
822    Menu(Vec<MenuEntry>),
823    /// A window is modal, belonging to `owner` (the window it was declared
824    /// in, if any). Sent once, before the window is shown.
825    Modal {
826        owner: Option<NodeId>,
827        modality: Modality,
828    },
829    /// What an `Image` shows.
830    Image(ImageSource),
831    /// How an `Image` fills its frame; sent only if the app chose.
832    ImageFit(ImageFit),
833    /// What an `Icon` shows, or the icon a `Button`, `ToggleButton` or
834    /// `MenuButton` shows before its caption: a name in the platform's own set (an SF Symbol, a themed
835    /// icon's name, a Segoe Fluent Icons glyph). Empty: none. A name the
836    /// set doesn't have shows as the platform shows one: nothing, or its
837    /// missing-icon icon.
838    Icon(String),
839    /// How big an `Icon` is, in points, used as the platform sizes icons:
840    /// an SF Symbol's point size (as a font's), the side of a square
841    /// elsewhere; a `FileIcon`'s square's side everywhere. Sent only if the
842    /// app chose.
843    IconSize(f32),
844    /// The file or folder a `FileIcon` shows the icon of. It's read when
845    /// set, as an image file is.
846    File(PathBuf),
847    /// A `FileIcon` shows a preview of what's in the file (a picture's,
848    /// a document's first page) in place of its icon, where the platform
849    /// makes one; its icon until then, and where it makes none.
850    Thumbnail(bool),
851    /// A button shows its icon without its caption, which stays its
852    /// accessible name. Without an icon it shows its caption.
853    IconOnly(bool),
854    /// Whether a `Spinner` spins. Stopped, it shows nothing but keeps its
855    /// place.
856    Running(bool),
857    /// How far along a `Progress` is, from 0 to 1. `None`: not known (an
858    /// indeterminate, animated bar).
859    Progress(Option<f64>),
860    /// Which axes a `ScrollView` scrolls.
861    ScrollAxes(ScrollAxes),
862    /// Whether a `ScrollView` shows scroll bars, as the platform shows them.
863    /// Without, it still scrolls, by wheel, trackpad and touch.
864    ScrollBars(bool),
865    /// A `Tabs`' page titles, in page order.
866    TabTitles(Vec<String>),
867    /// A `Tabs`' tab icons, in page order: names in the platform's own set,
868    /// as `Icon`'s; empty for none. Sent only if a tab has one.
869    TabIcons(Vec<String>),
870    /// How a `Tabs` shows its tabs. Sent only if the app chose.
871    TabsStyle(TabsStyle),
872    /// A `Sidebar`'s items, in sections, in order.
873    Sections(Vec<SidebarSectionData>),
874    /// A `Sidebar` is shown beside the window's content, or hidden, as the
875    /// platform shows and hides one. The user can change it too: the
876    /// backend reports `SidebarShownChanged`, which the core absorbs. Sent
877    /// only if the app chose.
878    SidebarShown(bool),
879    /// A `List`'s rows, in order.
880    Rows(Vec<RowKey>),
881    /// How high a `List`'s rows are likely to be, for platforms that must
882    /// size rows before they're shown.
883    EstimatedRowHeight(f32),
884    /// Which row of its `List` a row host shows.
885    Row(RowKey),
886    /// A `Table`'s columns, in order.
887    Columns(Vec<ColumnData>),
888    /// The column a `Table` is sorted by, which its header shows. The user
889    /// pressing a sortable column's header sorts it as the platform does:
890    /// the backend reports `Changed(Sort)`, which the core absorbs.
891    Sort(Option<ColumnSort>),
892    /// Which cell of its `Table` a cell host shows.
893    Cell(CellKey),
894    SelectionMode(SelectionMode),
895    ListStyle(ListStyle),
896    /// The selected rows of a `List`.
897    Selected(Vec<RowKey>),
898    /// A custom widget's props, with its renders.
899    Custom(CustomProps),
900    /// What a drawn custom widget shows. Computed by the core after layout,
901    /// so it arrives with the frames.
902    Drawing(DisplayList),
903    /// A `Native` node's factory (on create), then its updates: payloads in
904    /// the backend's own form.
905    Native(Opaque),
906    /// A `GpuSurface` takes keys and the pointer, and reports them as
907    /// `SurfaceInput`: it takes focus from a click and from Tab.
908    TakesInput(bool),
909    /// A `GpuSurface` holds the pointer: the cursor is hidden and stays
910    /// put, and its moves are reported as `SurfaceInput::Motion`. Only
911    /// while its window is the active one; the backend reports
912    /// `PointerLockEnded` when that stops, or it can't lock.
913    PointerLock(bool),
914    /// A `GpuSurface` takes every key while it has focus, the system's
915    /// shortcuts and the app's own too, as far as the platform lets an
916    /// app. Setting it focuses the surface; the backend reports
917    /// `KeyboardGrabEnded` when the surface or its window loses focus, or
918    /// it can't grab.
919    KeyboardGrab(bool),
920    /// The pointer's cursor over a `GpuSurface`.
921    Cursor(Cursor),
922    /// A `Container` or `Group` takes the files and folders this says
923    /// when they're dragged from the platform's file manager and dropped
924    /// on it; `None`: none. While acceptable files are over it, the
925    /// platform shows it'll copy them, and the node reports
926    /// `DropHover(true)`, then `DropHover(false)`; a drop reports the ones
927    /// it takes as `FilesDropped`.
928    FileDrop(Option<FileDrop>),
929    /// A `Container` or `Group` reports the pointer coming over it, or
930    /// over anything inside it, and leaving, as
931    /// [`UiEvent::Hover`](crate::UiEvent::Hover). Sent only if the app
932    /// asked (`on_hover`).
933    Hover(bool),
934    /// A `Container` or `Group` reports a double click on it, or on
935    /// anything inside it that isn't a control (a label, an icon), as
936    /// [`UiEvent::DoubleClick`](crate::UiEvent::DoubleClick). Sent only if
937    /// the app asked (`on_double_click`).
938    DoubleClick(bool),
939    /// A `List`'s or `Table`'s rows' files: dragging a row carries its
940    /// file out of the app (to the file manager, another app, a folder),
941    /// and dragging a selected row carries every selected row's, as the
942    /// platform drags a selection. The drag offers to copy. Rows without a
943    /// file don't drag. Sent before the rows, and only if the app gave
944    /// them.
945    RowFiles(Vec<(RowKey, PathBuf)>),
946    /// The keys a `Container`, `Group`, `List` or `Table` takes while it,
947    /// or a control inside it, has keyboard focus, and the focused control
948    /// doesn't use them itself: they go up from the focused control, as the
949    /// platform sends keys it doesn't use, to the nearest node that takes
950    /// them, which reports [`UiEvent::Key`](crate::UiEvent::Key). Sent only
951    /// if the app gave some.
952    Keys(Vec<Shortcut>),
953    /// Raw platform settings for a built-in widget (see
954    /// [`Tweak`](crate::Tweak)), in the backend's own form. Applied after
955    /// the widget's other props, and again whenever they change.
956    Tweak(Opaque),
957}
958
959impl Prop {
960    /// Two props with the same key replace each other.
961    pub fn key(&self) -> std::mem::Discriminant<Prop> {
962        std::mem::discriminant(self)
963    }
964
965    /// Whether changing this prop can change the intrinsic size of a widget
966    /// of this kind.
967    pub fn affects_measure(&self, kind: WidgetKind) -> bool {
968        // A spin box can be as wide as its range's longest number (GTK) or
969        // its text (Qt).
970        if kind == WidgetKind::NumberInput && matches!(self, Prop::Range { .. } | Prop::Number(_)) {
971            return true;
972        }
973        // A pull-down can be as wide as its widest item (AppKit).
974        if kind == WidgetKind::MenuButton && matches!(self, Prop::Menu(_)) {
975            return true;
976        }
977        if kind == WidgetKind::TextArea && matches!(self, Prop::Lines(_)) {
978            return true;
979        }
980        matches!(
981            self,
982            Prop::Text(_)
983                | Prop::MaxLines(_)
984                | Prop::Truncation(_)
985                | Prop::FontWeight(_)
986                | Prop::Italic(_)
987                | Prop::Label(_)
988                | Prop::Placeholder(_)
989                | Prop::Options(_)
990                | Prop::SelectedIndex(_)
991                | Prop::TextStyle(_)
992                | Prop::ButtonRole(_)
993                | Prop::ButtonStyle(_)
994                | Prop::Orientation(_)
995                | Prop::Image(_)
996                | Prop::Icon(_)
997                | Prop::IconSize(_)
998                | Prop::IconOnly(_)
999                | Prop::Custom(_)
1000                | Prop::Native(_)
1001                | Prop::Tweak(_)
1002        )
1003    }
1004}
1005
1006/// Finds a prop by pattern in a prop list.
1007#[macro_export]
1008macro_rules! find_prop {
1009    ($props:expr, $variant:ident) => {
1010        $props.iter().find_map(|p| match p {
1011            $crate::Prop::$variant(v) => Some(v.clone()),
1012            _ => None,
1013        })
1014    };
1015}
1016
1017macro_rules! static_value {
1018    ($($t:ty),*) => {$(
1019        impl mitsuami_reactive::IntoValue<$t> for $t {
1020            fn into_value(self) -> mitsuami_reactive::Value<$t> {
1021                mitsuami_reactive::Value::Static(self)
1022            }
1023        }
1024    )*};
1025}
1026
1027static_value!(
1028    FileDrop,
1029    TextStyle,
1030    FontWeight,
1031    TextAlign,
1032    Truncation,
1033    crate::draw::Color,
1034    ButtonRole,
1035    ButtonStyle,
1036    TabsStyle,
1037    Orientation,
1038    ScrollAxes,
1039    SelectionMode,
1040    SortOrder,
1041    ListStyle,
1042    InputPurpose,
1043    ImageSource,
1044    Pixels,
1045    ImageFit,
1046    Modality,
1047    Cursor,
1048    Size
1049);