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, Rect, 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    /// A native button with a menu of other actions beside its own (an
73    /// `NSComboButton` of the split style, WinUI's SplitButton,
74    /// adw::SplitButton; Kirigami has none, so a QQC2.Button with an arrow
75    /// QQC2.Button joined to it, as KDE apps pair them). Its caption, icon
76    /// and style are a `Button`'s, and it reports a click as one does; its
77    /// menu is [`Prop::Menu`], whose item chosen comes as
78    /// [`UiEvent::MenuItem`](crate::UiEvent::MenuItem).
79    SplitButton,
80    TextInput,
81    /// A native password field (NSSecureTextField, PasswordBox,
82    /// gtk::PasswordEntry, Kirigami.PasswordField): a `TextInput` whose
83    /// text is hidden, as each platform hides it.
84    PasswordInput,
85    /// A native search field (NSSearchField, gtk::SearchEntry, an
86    /// AutoSuggestBox with the find icon, Kirigami.SearchField): a
87    /// `TextInput` with the platform's search icon and clear button, which
88    /// asks for a search ([`UiEvent::Search`](crate::UiEvent::Search)) as
89    /// the platform does.
90    SearchInput,
91    /// A native field for text over many lines (an NSTextView in an
92    /// NSScrollView, a TextBox that accepts Return, a gtk::TextView in a
93    /// gtk::ScrolledWindow, a QQC2.TextArea in a QQC2.ScrollView). Its
94    /// lines wrap, Return starts a new one, and it scrolls past
95    /// [`Prop::Lines`], its natural height.
96    TextArea,
97    Checkbox,
98    Switch,
99    /// A native pop-up menu of text options (NSPopUpButton, ComboBox,
100    /// gtk::DropDown, QQC2.ComboBox). Its options are [`Prop::Options`].
101    Select,
102    /// Native radio buttons, one for each of [`Prop::Options`], of which
103    /// one at most is chosen, [`Prop::SelectedIndex`] (NSButtons of the
104    /// radio type, RadioButtons, gtk::CheckButtons in a group,
105    /// QQC2.RadioButtons). Down a column, as each platform stacks them.
106    RadioGroup,
107    /// A native slider (NSSlider, Slider, gtk::Scale, QQC2.Slider): a
108    /// [`Prop::Number`] in a [`Prop::Range`], in [`Prop::Step`]s.
109    Slider,
110    /// A native field for a whole number, with buttons that step it up and
111    /// down (NumberBox, gtk::SpinButton, QQC2.SpinBox; on AppKit an
112    /// NSTextField with an NSStepper beside it, as AppKit apps pair them):
113    /// a [`Prop::Number`] in a [`Prop::Range`], stepped by [`Prop::Step`].
114    /// Whole numbers that fit an `i32`, because Qt's spin box holds an
115    /// `int`.
116    NumberInput,
117    /// A native colour well: a button showing a colour, which opens the
118    /// platform's own way to pick another (NSColorWell, its colour panel;
119    /// GTK's ColorDialogButton; WinUI's ColorPicker in a flyout under a
120    /// DropDownButton; on Qt a button opening the ColorDialog, as KDE apps
121    /// pair them). Its colour is [`Prop::ColorValue`], opaque; the user's
122    /// pick comes as `Changed(Color)`.
123    ColorWell,
124    /// A native progress bar (NSProgressIndicator, ProgressBar,
125    /// gtk::ProgressBar, QQC2.ProgressBar): a [`Prop::Progress`].
126    Progress,
127    /// A native spinner for work of unknown length (a spinning
128    /// NSProgressIndicator, gtk::Spinner, ProgressRing,
129    /// QQC2.BusyIndicator). It spins while [`Prop::Running`], and shows
130    /// nothing otherwise.
131    Spinner,
132    /// A native separator line between groups of content (a separator
133    /// NSBox, gtk::Separator, Kirigami.Separator; WinUI has none, so a
134    /// `Border` in the divider brush, as Fluent apps draw one). It runs as
135    /// [`Prop::Orientation`] says and is as thick as the platform draws
136    /// it; the layout gives it its length.
137    Separator,
138    /// A native image view (NSImageView, Image, gtk::Picture, QML Image):
139    /// a picture from [`Prop::Image`], at its own size unless the layout
140    /// sizes it, fitted as [`Prop::ImageFit`] says.
141    Image,
142    /// An icon from the platform's own set, by its name there: an SF
143    /// Symbol in an NSImageView, a themed icon in a gtk::Image or a
144    /// Kirigami.Icon, a Segoe Fluent Icons glyph in a FontIcon on WinUI.
145    /// [`Prop::Icon`] names it, at the platform's own size unless
146    /// [`Prop::IconSize`] says otherwise.
147    Icon,
148    /// A file's or folder's own icon, as the platform's file manager shows
149    /// it: `NSWorkspace`'s in an NSImageView, GIO's in a gtk::Image, its
150    /// MIME type's in a Kirigami.Icon, the shell's in a XAML Image.
151    /// [`Prop::File`] names it; it's a square as big as the platform's
152    /// small icons unless [`Prop::IconSize`] says otherwise. With
153    /// [`Prop::Thumbnail`], a preview of what's in the file where the
154    /// platform makes one; with [`Prop::FileLookup`], a type's icon from
155    /// the name alone.
156    FileIcon,
157    /// A native surface the app presents to with its own GPU API, off the
158    /// UI thread (an `NSView` backed by a `CAMetalLayer`, a Wayland
159    /// subsurface, a child window). The backend reports it as
160    /// `SurfaceReady`, then its size in pixels as `SurfaceResized`; with
161    /// [`Prop::TakesInput`], its keys and pointer as `SurfaceInput`, and
162    /// with [`Prop::TextInput`] what its keys type.
163    GpuSurface,
164    /// A native scroll container. It has exactly one native child, the
165    /// content, which the core lays out and may be larger than the viewport.
166    ScrollView,
167    /// A native list control (NSTableView, ListView, gtk::ListView, QML
168    /// ListView). Its data is [`Prop::Rows`]. The platform decides which rows
169    /// exist (`RowShown`, `RowHidden`); its native children are the hosts of
170    /// the rows the core mounted for those (`Container`s with a
171    /// [`Prop::Row`]), in row order. It scrolls like a `ScrollView`.
172    List,
173    /// A native table: a `List` whose rows are cells under column headers
174    /// (NSTableView with columns and a header, gtk::ColumnView, a QML
175    /// TableView under a HorizontalHeaderView; WinUI has none, so a
176    /// ListView under a header of column buttons, as Fluent apps build
177    /// one). Its columns are [`Prop::Columns`], sorted as [`Prop::Sort`]
178    /// says. Its data, selection and scrolling are a `List`'s; its native
179    /// children are the hosts of the cells the core mounted for the rows it
180    /// shows (`Container`s with a [`Prop::Cell`]), in row order, then
181    /// column order. The platform sizes its columns, and the user resizes
182    /// them: it reports the width each column gives its cells
183    /// (`ColumnWidths`).
184    Table,
185    /// A native tree: a `List` whose rows nest, opened and closed by a
186    /// disclosure the platform draws (NSOutlineView, a gtk::ListView over a
187    /// gtk::TreeListModel with gtk::TreeExpanders, a QML TreeView, WinUI's
188    /// TreeView). Its data is [`Prop::TreeRows`], the rows that show; its
189    /// selection, scrolling and native children are a `List`'s. The user
190    /// opens and closes rows (`RowExpanded`), and the platform says how
191    /// far it indents their content (`TreeIndent`).
192    Tree,
193    /// A native tab view: pages, one shown at a time, and a strip of their
194    /// titles to pick one (NSTabView, libadwaita's inline view switcher or
195    /// a gtk::Notebook, a SelectorBar over its pages on WinUI, Kirigami's
196    /// NavigationTabBar or a QQC2.TabBar). Its native
197    /// children are its pages' hosts (`Container`s), in order, titled by
198    /// [`Prop::TabTitles`]; the shown one is [`Prop::SelectedIndex`].
199    /// Every page stays mounted. The core lays out each page at the size
200    /// inside the tab strip and border ([`PlatformMetrics::tab_insets`](crate::PlatformMetrics)),
201    /// all in the same place, so the view is as big as its biggest page;
202    /// the platform places them and shows the chosen one.
203    Tabs,
204    /// Native document tabs: a strip of tabs with no pages, for documents
205    /// the app shows in one place of its own (a terminal's sessions drawn
206    /// on one surface). WinUI's TabView with items without content,
207    /// libadwaita's AdwTabBar, a QQC2.TabBar with close buttons, and on
208    /// AppKit a strip of the backend's, made as the system's tab bar. Titled by [`Prop::TabTitles`], the chosen
209    /// one [`Prop::SelectedIndex`]; the user closes them
210    /// ([`Prop::TabsClosable`]), moves them ([`Prop::TabsReorderable`]) and
211    /// asks for a new one ([`Prop::NewTabButton`]), where the app lets
212    /// them. Measured by the backend; empty where the tabs are the
213    /// window's ([`DocumentTabsStyle::Window`], [`DocumentTabsStyle::TitleRow`]).
214    DocumentTabs,
215    /// A native box around related content, under an optional heading
216    /// ([`Prop::Title`]): an NSBox, libadwaita's card under a heading, a
217    /// Fluent card under a heading on WinUI, a QQC2.GroupBox. The core lays
218    /// out its children as a container's, inside
219    /// [`PlatformMetrics::group_insets`](crate::PlatformMetrics) (or the
220    /// titled ones), and it's at least as wide as its heading, which
221    /// backends measure. Backends draw the box behind the children, which
222    /// are its native children.
223    Group,
224    /// Two panes with a divider between them that the user drags: side by
225    /// side, or with `Orientation::Vertical` one over the other. Its two
226    /// children are the panes. The core lays them out: the first as long
227    /// along the split as its `Number`, then the platform's divider
228    /// ([`PlatformMetrics::split_divider`](crate::PlatformMetrics)), then
229    /// the second, which takes what's left, so the first keeps its size as
230    /// the split grows. Each pane is at least its style's least size
231    /// ([`Prop::PaneMinimums`]). The platform draws the divider and reports
232    /// where the user drags it as `Changed(Number)`. A hidden pane
233    /// collapses, with the divider, and the other takes the whole split
234    /// ([`Prop::PanesShown`]); the position is kept for when it's back.
235    Split,
236    /// A platform's popover, attached to its parent (a container) while
237    /// [`Prop::PopoverShown`]: an NSPopover, a gtk::Popover, a XAML Flyout,
238    /// a QQC2.Popup. It's out of its parent's layout: the core lays out its
239    /// children at their natural size, as a toolbar item's, and the
240    /// platform places it by its parent, where it fits. A click outside or
241    /// Escape dismisses it, as the platform's do: the backend reports
242    /// `PopoverShownChanged(false)`, which the core absorbs.
243    Popover,
244    /// A custom widget (see [`CustomWidget`](crate::CustomWidget)), named
245    /// after it. Its props travel as [`Prop::Custom`].
246    Custom(&'static str),
247    /// A raw native view supplied by app code. Its factory and updates
248    /// travel as [`Prop::Native`].
249    Native,
250}
251
252impl WidgetKind {
253    pub fn is_native(self) -> bool {
254        self != WidgetKind::Fragment
255    }
256
257    /// Containers lay out children; everything else is measured by the backend.
258    pub fn is_container(self) -> bool {
259        matches!(
260            self,
261            WidgetKind::Window
262                | WidgetKind::Container
263                | WidgetKind::ToolbarItem
264                | WidgetKind::ScrollView
265                | WidgetKind::Tabs
266                | WidgetKind::Group
267                | WidgetKind::Split
268                | WidgetKind::Popover
269        )
270    }
271
272    /// Scrolls its content: `ScrollTo` and `Scrolled` apply.
273    pub fn scrolls(self) -> bool {
274        matches!(self, WidgetKind::ScrollView | WidgetKind::List | WidgetKind::Table | WidgetKind::Tree)
275    }
276
277    /// Has rows the platform realises: a `List`, a `Table` or a `Tree`.
278    pub fn has_rows(self) -> bool {
279        matches!(self, WidgetKind::List | WidgetKind::Table | WidgetKind::Tree)
280    }
281
282    pub fn name(self) -> &'static str {
283        match self {
284            WidgetKind::Window => "Window",
285            WidgetKind::Container => "Container",
286            WidgetKind::ToolbarItem => "ToolbarItem",
287            WidgetKind::Sidebar => "Sidebar",
288            WidgetKind::ScrollView => "ScrollView",
289            WidgetKind::List => "List",
290            WidgetKind::Table => "Table",
291            WidgetKind::Tree => "Tree",
292            WidgetKind::Tabs => "Tabs",
293            WidgetKind::DocumentTabs => "DocumentTabs",
294            WidgetKind::Group => "Group",
295            WidgetKind::Popover => "Popover",
296            WidgetKind::Split => "Split",
297            WidgetKind::Fragment => "Fragment",
298            WidgetKind::Text => "Text",
299            WidgetKind::Button => "Button",
300            WidgetKind::ToggleButton => "ToggleButton",
301            WidgetKind::MenuButton => "MenuButton",
302            WidgetKind::SplitButton => "SplitButton",
303            WidgetKind::TextInput => "TextInput",
304            WidgetKind::PasswordInput => "PasswordInput",
305            WidgetKind::SearchInput => "SearchInput",
306            WidgetKind::TextArea => "TextArea",
307            WidgetKind::Checkbox => "Checkbox",
308            WidgetKind::Switch => "Switch",
309            WidgetKind::Select => "Select",
310            WidgetKind::RadioGroup => "RadioGroup",
311            WidgetKind::Slider => "Slider",
312            WidgetKind::NumberInput => "NumberInput",
313            WidgetKind::ColorWell => "ColorWell",
314            WidgetKind::Progress => "Progress",
315            WidgetKind::Spinner => "Spinner",
316            WidgetKind::Separator => "Separator",
317            WidgetKind::Image => "Image",
318            WidgetKind::Icon => "Icon",
319            WidgetKind::FileIcon => "FileIcon",
320            WidgetKind::GpuSurface => "GpuSurface",
321            WidgetKind::Custom(name) => name,
322            WidgetKind::Native => "Native",
323        }
324    }
325}
326
327/// Semantic text styles, mapped to each platform's type ramp.
328#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
329pub enum TextStyle {
330    LargeTitle,
331    Title,
332    Headline,
333    #[default]
334    Body,
335    Callout,
336    Caption,
337    Monospace,
338}
339
340/// How heavy a `Text`'s font is, in place of its text style's weight.
341/// A platform whose font lacks one uses the nearest it has.
342#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
343pub enum FontWeight {
344    #[default]
345    Regular,
346    Medium,
347    Semibold,
348    Bold,
349}
350
351/// Where a `Text`'s lines go across its frame, in its reading direction:
352/// `Start` is the left in left-to-right text, the right in right-to-left.
353#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
354pub enum TextAlign {
355    #[default]
356    Start,
357    Center,
358    End,
359}
360
361/// Where a `Text` cut off at its line limit puts its ellipsis: in place
362/// of its start, its middle (a path's folders, keeping its file name) or
363/// its end. Start and end are the text's, so in right-to-left text the
364/// start is on the right. Platforms that can't put one there cut off the
365/// end, as their labels do.
366#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
367pub enum Truncation {
368    Start,
369    Middle,
370    #[default]
371    End,
372}
373
374/// Where a `FileIcon` gets its icon. From disk, the platform reads the
375/// file or folder for its own icon; by name, nothing is read, as file
376/// managers show files that aren't on disk (a download, an archive's
377/// contents, a file only in an old revision).
378#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
379pub enum FileLookup {
380    /// The file or folder at the path: an app's own icon, a folder's
381    /// custom one, a document's by its type.
382    #[default]
383    Disk,
384    /// A file of the type the path's name says (its extension, or the
385    /// whole name where the platform knows one, `Makefile`).
386    FileName,
387    /// A plain folder.
388    Folder,
389}
390
391/// A [`TextAlign`] the core has resolved against the text's direction, as
392/// backends get it.
393#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
394pub enum HorizontalAlign {
395    #[default]
396    Left,
397    Center,
398    Right,
399}
400
401/// Which way a native widget lays itself out, as backends get it: the
402/// core has resolved the node's direction (its own, its parent's, or the
403/// app's language's).
404#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
405pub enum LayoutDirection {
406    #[default]
407    LeftToRight,
408    RightToLeft,
409}
410
411/// What a `TextInput` is for, which the platform uses as it uses one: to
412/// pick an on-screen keyboard, to offer autofill, to check what's typed.
413/// Only the purposes every platform has.
414#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
415pub enum InputPurpose {
416    /// Any text.
417    #[default]
418    Text,
419    Email,
420    Url,
421    /// A telephone number.
422    Phone,
423}
424
425/// What a button does in its window or dialog, which each platform shows
426/// and handles its own way. Platforms without an equivalent ignore it.
427#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
428pub enum ButtonRole {
429    /// An ordinary button.
430    #[default]
431    Normal,
432    /// The action Return confirms: the default button on AppKit (Return
433    /// clicks it), the suggested action on GTK, the default button on Qt, the
434    /// accent button on WinUI. One per window or dialog.
435    Default,
436    /// The action Escape takes: the cancel button on AppKit (Escape clicks
437    /// it). The others show it as a normal button.
438    Cancel,
439    /// An action that destroys data: GTK's destructive action; AppKit marks
440    /// it so the system can warn. Qt and WinUI have no such style.
441    Destructive,
442}
443
444/// Where a window's header (`Prop::Header`) meets what scrolls under it,
445/// where the platform blurs it there (AppKit's scroll edge effect, macOS
446/// 26.1 and later). The others have no such edge, and ignore it.
447#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
448pub enum HeaderEdge {
449    /// The platform's own: soft on macOS 26.
450    #[default]
451    Automatic,
452    /// What scrolls under it fades into the blur.
453    Soft,
454    /// The header ends at a hard line, opaque down to it, as Finder's and
455    /// Mail's bars on a busy list.
456    Hard,
457}
458
459/// How a `Tabs` shows its tabs, where the platform has more than one way
460/// (GNOME and KDE). The others show theirs, and ignore it.
461#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
462pub enum TabsStyle {
463    /// The platform's own: navigation tabs on GNOME and KDE.
464    #[default]
465    Automatic,
466    /// A tab bar over the pages: GTK's `gtk::Notebook`, Qt's
467    /// `QQC2.TabBar`.
468    TabBar,
469    /// Navigation tabs above the pages: libadwaita's inline view switcher
470    /// (a tab bar before libadwaita 1.7), Kirigami's `NavigationTabBar`.
471    Navigation,
472}
473
474/// Where `DocumentTabs` show their tabs: in the window's own chrome, or
475/// in the content where they're declared.
476#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
477pub enum DocumentTabsStyle {
478    /// The platform's own: the window's on macOS and Windows (in the title
479    /// bar, as Safari, Xcode and Terminal have them), a strip in the
480    /// content on GNOME and KDE (as Console and Konsole).
481    #[default]
482    Automatic,
483    /// A strip in the content, where they're declared, on every platform:
484    /// on macOS one the backend builds, as Safari's is.
485    Strip,
486    /// The window's own: a strip in AppKit's title bar, under the title and
487    /// toolbar, WinUI's tab view in the title bar. GTK and Qt have none,
488    /// so a strip.
489    Window,
490    /// In the title's own row, beside the window's buttons and toolbar
491    /// items, the title hidden: Safari's compact tabs on macOS, and on
492    /// GNOME libadwaita's tab bar in the header bar's title's place.
493    /// WinUI's tabs in the title bar already are; Qt has none, so a strip.
494    TitleRow,
495}
496
497/// How a button is drawn, mapped to each platform's native look.
498#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
499pub enum ButtonStyle {
500    /// The same as `Bordered`, on every platform.
501    #[default]
502    Automatic,
503    /// The platform's push button, with its bezel or frame.
504    Bordered,
505    /// No bezel or frame until hovered, where the platform does that: for
506    /// toolbars, and buttons that sit among text.
507    Borderless,
508    /// Filled with the accent colour, as the platform marks the action it
509    /// suggests among others (AppKit's primary tint prominence, GTK's
510    /// `suggested-action`, WinUI's accent style), without being the
511    /// window's default button: Return doesn't press it. Buttons and menu
512    /// and split buttons; on others, `Bordered`. Breeze has no such style
513    /// (only its default button is tinted), nor AppKit's combo button, so
514    /// those stay bordered.
515    Prominent,
516}
517
518/// A suggestion of a `SearchInput`: what it says, and a second line in the
519/// secondary style (a file's folder, an author's email).
520#[derive(Clone, Debug, PartialEq)]
521pub struct Suggestion {
522    pub title: String,
523    pub detail: Option<String>,
524}
525
526/// What an `Image` shows.
527#[derive(Clone, Debug, PartialEq)]
528pub enum ImageSource {
529    /// An image file, decoded by the platform: PNG and JPEG everywhere,
530    /// other formats where the platform reads them. It's read when the
531    /// source is set; a file that changes under the same path isn't read
532    /// again.
533    File(PathBuf),
534    /// Pixels the app has in memory.
535    Pixels(Pixels),
536}
537
538/// An image in memory: rows of straight (not premultiplied) RGBA8, top
539/// row first, drawn at `scale` pixels to a point, so an image made at the
540/// window's scale factor is shown pixel for pixel.
541#[derive(Clone, PartialEq)]
542pub struct Pixels {
543    width: u32,
544    height: u32,
545    scale: f32,
546    rgba: Arc<[u8]>,
547}
548
549/// Its size and scale, not its bytes.
550impl fmt::Debug for Pixels {
551    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
552        write!(f, "Pixels({}×{} @{}x)", self.width, self.height, self.scale)
553    }
554}
555
556impl Pixels {
557    /// Panics unless `rgba` holds `width × height` pixels.
558    pub fn new(width: u32, height: u32, rgba: impl Into<Arc<[u8]>>) -> Pixels {
559        let rgba = rgba.into();
560        // Checked: a size that wraps could pass with too few bytes, which
561        // backends hand to the platform as the whole image.
562        let len = (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(4));
563        assert_eq!(Some(rgba.len()), len, "{width}×{height} RGBA8 pixels");
564        Pixels { width, height, scale: 1.0, rgba }
565    }
566
567    /// Pixels to a point; 1 by default.
568    pub fn scale(mut self, scale: f32) -> Pixels {
569        assert!(scale > 0.0, "a scale above 0");
570        self.scale = scale;
571        self
572    }
573
574    pub fn width(&self) -> u32 {
575        self.width
576    }
577
578    pub fn height(&self) -> u32 {
579        self.height
580    }
581
582    pub fn scale_factor(&self) -> f32 {
583        self.scale
584    }
585
586    pub fn rgba(&self) -> &[u8] {
587        &self.rgba
588    }
589
590    /// Its size in points.
591    pub fn size(&self) -> crate::Size {
592        crate::Size::new(self.width as f32 / self.scale, self.height as f32 / self.scale)
593    }
594}
595
596/// How an `Image` fills a frame the layout makes a different size from
597/// it. Only the fits every platform's image view has; without one, each
598/// fits as it does by default.
599#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
600pub enum ImageFit {
601    /// As large as fits, keeping its proportions (NSImageView
602    /// proportionally up or down, GTK `Contain`, Qt `PreserveAspectFit`,
603    /// XAML `Uniform`).
604    Contain,
605    /// The whole frame, proportions or not (axes independently, `Fill`,
606    /// `Stretch`, `Fill`).
607    Stretch,
608}
609
610/// The pointer's cursor over a `GpuSurface`, while it isn't locked.
611#[derive(Clone, Debug, Default, PartialEq)]
612pub enum Cursor {
613    /// The platform's own: the arrow.
614    #[default]
615    Default,
616    /// None: the pointer still moves, unseen (a machine that draws its own).
617    Hidden,
618    /// An image of the app's, e.g. the one a machine gives its pointer,
619    /// shown at its scale. `hotspot`: the point that points, in points from
620    /// its top left.
621    Image { pixels: Pixels, hotspot: Point },
622    /// One of the platform's own, by what it means. A platform with none
623    /// for it shows its arrow.
624    System(SystemCursor),
625}
626
627/// The platform cursors a `Cursor::System` names: the ones the platforms
628/// share, as CSS names them.
629#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
630pub enum SystemCursor {
631    /// The text cursor, an I-beam.
632    Text,
633    /// Busy: nothing can be done (the hourglass, the spinner).
634    Wait,
635    /// Busy, but it can still be used (the arrow with a spinner).
636    Progress,
637    /// A link: the pointing hand.
638    Pointer,
639    Crosshair,
640    NotAllowed,
641    Help,
642    /// Something can be moved: arrows four ways.
643    Move,
644    /// Resizing up and down, left and right, and along the diagonals.
645    ResizeNorthSouth,
646    ResizeEastWest,
647    ResizeNorthWestSouthEast,
648    ResizeNorthEastSouthWest,
649}
650
651impl SystemCursor {
652    /// Its CSS name (`cursor:`), which GTK and freedesktop cursor themes
653    /// use too.
654    pub fn css_name(self) -> &'static str {
655        match self {
656            SystemCursor::Text => "text",
657            SystemCursor::Wait => "wait",
658            SystemCursor::Progress => "progress",
659            SystemCursor::Pointer => "pointer",
660            SystemCursor::Crosshair => "crosshair",
661            SystemCursor::NotAllowed => "not-allowed",
662            SystemCursor::Help => "help",
663            SystemCursor::Move => "move",
664            SystemCursor::ResizeNorthSouth => "ns-resize",
665            SystemCursor::ResizeEastWest => "ew-resize",
666            SystemCursor::ResizeNorthWestSouthEast => "nwse-resize",
667            SystemCursor::ResizeNorthEastSouthWest => "nesw-resize",
668        }
669    }
670}
671
672/// What a modal `Window` blocks while it's open, shown each platform's way.
673#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
674pub enum Modality {
675    /// The window it belongs to (the one it's declared in): a sheet on
676    /// that window on macOS, Qt's `WindowModal`, an owned `IsModal` window
677    /// on WinUI. GTK's modal windows block the whole app.
678    Window,
679    /// Every other window of the app: a window in AppKit's modal loop,
680    /// Qt's `ApplicationModal`, a modal window on GTK, and on WinUI an
681    /// owned `IsModal` window that also disables the app's other windows.
682    Application,
683}
684
685/// The window whose content is being built: provided in each window's
686/// scope, so views can find the window they're in (a modal `Window`
687/// belongs to it, a `Toolbar`'s items go in its toolbar).
688#[derive(Clone, Copy, Debug, PartialEq, Eq)]
689pub struct CurrentWindow(pub NodeId);
690
691/// Which files a node takes when they're dropped on it: files with these
692/// extensions (any file without a list), and folders if `folders`.
693#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
694pub struct FileDrop {
695    /// Without the dot, compared ignoring case. `None`: any file.
696    pub extensions: Option<Vec<String>>,
697    pub folders: bool,
698}
699
700impl FileDrop {
701    /// Any file, no folders.
702    pub fn files() -> FileDrop {
703        FileDrop { extensions: None, folders: false }
704    }
705
706    /// Files with these extensions (`"iso"`, not `".iso"`), no folders.
707    pub fn extensions<S: Into<String>>(extensions: impl IntoIterator<Item = S>) -> FileDrop {
708        FileDrop { extensions: Some(extensions.into_iter().map(Into::into).collect()), folders: false }
709    }
710
711    /// Folders only.
712    pub fn folders() -> FileDrop {
713        FileDrop { extensions: Some(Vec::new()), folders: true }
714    }
715
716    /// Folders too.
717    pub fn and_folders(mut self) -> FileDrop {
718        self.folders = true;
719        self
720    }
721
722    /// Whether it takes this file or folder, as it is on disk.
723    pub fn accepts(&self, path: &std::path::Path) -> bool {
724        if path.is_dir() {
725            return self.folders;
726        }
727        match &self.extensions {
728            None => true,
729            Some(extensions) => path
730                .extension()
731                .and_then(|e| e.to_str())
732                .is_some_and(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e))),
733        }
734    }
735
736    /// What it takes of these, in order.
737    pub fn accepted(&self, paths: &[PathBuf]) -> Vec<PathBuf> {
738        paths.iter().filter(|p| self.accepts(p)).cloned().collect()
739    }
740}
741
742/// Which way a `Slider` or a `Separator` runs. Every platform has vertical
743/// sliders; larger values are up on all of them.
744#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
745pub enum Orientation {
746    #[default]
747    Horizontal,
748    Vertical,
749}
750
751impl Orientation {
752    pub fn vertical(self) -> bool {
753        self == Orientation::Vertical
754    }
755}
756
757/// Scrolling directions of a `ScrollView`.
758#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
759pub enum ScrollAxes {
760    #[default]
761    Vertical,
762    Horizontal,
763    Both,
764}
765
766impl ScrollAxes {
767    pub fn horizontal(self) -> bool {
768        matches!(self, ScrollAxes::Horizontal | ScrollAxes::Both)
769    }
770
771    pub fn vertical(self) -> bool {
772        matches!(self, ScrollAxes::Vertical | ScrollAxes::Both)
773    }
774}
775
776/// Where rows dragged within a list can be dropped (`List::on_move`): onto
777/// a row (into a group, say), between rows (to reorder them), or both. A
778/// drop on the list's empty part is at its end, either way.
779#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
780pub struct RowMoves {
781    pub onto_rows: bool,
782    pub between_rows: bool,
783}
784
785impl RowMoves {
786    pub fn onto_rows() -> RowMoves {
787        RowMoves { onto_rows: true, between_rows: false }
788    }
789
790    pub fn between_rows() -> RowMoves {
791        RowMoves { onto_rows: false, between_rows: true }
792    }
793
794    pub fn and_between_rows(self) -> RowMoves {
795        RowMoves { between_rows: true, ..self }
796    }
797
798    pub fn and_onto_rows(self) -> RowMoves {
799        RowMoves { onto_rows: true, ..self }
800    }
801
802    /// Where a drop the platform proposes lands, by what the list takes:
803    /// onto a row where only between rows is taken is before it, and
804    /// between rows where only onto them is taken is onto the row there.
805    /// Rows aren't dropped onto one of themselves: `None`. Every backend
806    /// asks this while a drag is over its list, and shows what it answers.
807    pub fn target(&self, dragged: &[RowKey], proposed: RowDrop<RowKey>) -> Option<RowDrop<RowKey>> {
808        let target = match proposed {
809            RowDrop::On(row) if !self.onto_rows => RowDrop::Before(row),
810            RowDrop::Before(row) if !self.between_rows => RowDrop::On(row),
811            other => other,
812        };
813        match target {
814            RowDrop::On(row) if dragged.contains(&row) => None,
815            _ if !self.onto_rows && !self.between_rows => None,
816            target => Some(target),
817        }
818    }
819
820    /// `target` in a `Tree`, whose rows nest (`row` gives a row's place, as
821    /// `TreeRows` says): onto a row is into it, so only a row that opens
822    /// takes rows onto it, and before one is at its place among its
823    /// parent's rows. Nothing lands while the pointer is over a dragged row
824    /// (`over`, the row under it), or anywhere inside one: the rows would
825    /// stay where they are, or a folder would go inside itself.
826    pub fn tree_target(
827        &self,
828        dragged: &[RowKey],
829        over: Option<RowKey>,
830        proposed: RowDrop<RowKey>,
831        row: impl Fn(RowKey) -> Option<crate::TreeRow>,
832    ) -> Option<RowDrop<RowKey>> {
833        let inside_dragged = |key: RowKey| {
834            let mut at = Some(key);
835            while let Some(r) = at {
836                if dragged.contains(&r) {
837                    return true;
838                }
839                at = row(r).and_then(|r| r.parent);
840            }
841            false
842        };
843        if over.is_some_and(inside_dragged) {
844            return None;
845        }
846        let target = self.target(dragged, proposed)?;
847        match target {
848            RowDrop::On(r) if !row(r).is_some_and(|r| r.expandable) => None,
849            RowDrop::On(r) | RowDrop::Before(r) if inside_dragged(r) => None,
850            target => Some(target),
851        }
852    }
853
854    /// What the pointer, `x` across the tree (from its rows' left edge, if
855    /// known) and `y` of `height` down the row `key`, proposes in a `Tree`
856    /// (`row` gives a row's place, as `TreeRows` says). Over a row that
857    /// opens, its top quarter is before it, its bottom quarter after it,
858    /// and the middle onto it; over a row that doesn't, its top half is
859    /// before it and its bottom half after it.
860    ///
861    /// After an open folder is before its first row. After another row,
862    /// the levels from the row's own down to the next row's (`next`) are
863    /// all places: at the next row's level, before it; at a deeper one, the
864    /// end of the folder at that level (onto it, where a folder's last rows
865    /// put rows). `x` picks the level, as outlines pick it: the level whose
866    /// content starts nearest it, by `indent`; without it, the row's own.
867    /// Past the last top row, at the top level, the end. Backends that
868    /// propose by the pointer ask this, so every tree proposes alike, and
869    /// show an end-of-folder drop as a line under the row, at the level.
870    pub fn tree_proposal(
871        key: RowKey,
872        x: Option<f32>,
873        y: f32,
874        height: f32,
875        indent: crate::TreeIndent,
876        next: Option<RowKey>,
877        row: impl Fn(RowKey) -> Option<crate::TreeRow>,
878    ) -> RowDrop<RowKey> {
879        let Some(me) = row(key) else { return RowDrop::End };
880        let next_row = next.and_then(&row);
881        let after = || {
882            if let (Some(next), Some(n)) = (next, next_row)
883                && n.parent == Some(key)
884            {
885                return RowDrop::Before(next);
886            }
887            let shallowest = next_row.map_or(0, |n| n.depth).min(me.depth);
888            let level = match x {
889                Some(x) if indent.per_level > 0.0 => {
890                    let level = ((x - indent.start) / indent.per_level + 0.5).floor();
891                    (level.max(0.0) as u32).clamp(shallowest, me.depth)
892                }
893                _ => me.depth,
894            };
895            if let (Some(next), Some(n)) = (next, next_row)
896                && level == n.depth
897            {
898                return RowDrop::Before(next);
899            }
900            // The row's folder at that level: its own, or one it's in.
901            let mut at = me;
902            while at.depth > level {
903                match at.parent.and_then(&row) {
904                    Some(parent) => at = parent,
905                    None => break,
906                }
907            }
908            at.parent.map_or(RowDrop::End, RowDrop::On)
909        };
910        match me.expandable {
911            true if y < height / 4.0 => RowDrop::Before(key),
912            true if y > height * 3.0 / 4.0 => after(),
913            true => RowDrop::On(key),
914            false if y < height / 2.0 => RowDrop::Before(key),
915            false => after(),
916        }
917    }
918}
919
920/// Where rows dragged within a list were dropped: onto a row, before one,
921/// or at the end (the list's empty part).
922#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
923pub enum RowDrop<K> {
924    On(K),
925    Before(K),
926    End,
927}
928
929impl<K> RowDrop<K> {
930    pub fn map<J>(self, f: impl FnOnce(K) -> J) -> RowDrop<J> {
931        match self {
932            RowDrop::On(k) => RowDrop::On(f(k)),
933            RowDrop::Before(k) => RowDrop::Before(f(k)),
934            RowDrop::End => RowDrop::End,
935        }
936    }
937}
938
939/// Identity of a row of a `List`, stable while its item's key stays in the
940/// data. Assigned by the core.
941#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
942pub struct RowKey(pub u64);
943
944/// A row of a `Tree` that shows, as backends get it: its place in the
945/// tree, and whether it opens.
946#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
947pub struct TreeRow {
948    pub row: RowKey,
949    /// The row it's in, `None` at the top. It comes before this row, which
950    /// it's open to show.
951    pub parent: Option<RowKey>,
952    /// 0 at the top, one more than its parent's.
953    pub depth: u32,
954    /// It opens, children or not (a folder, empty or not yet read): the
955    /// platform shows its disclosure.
956    pub expandable: bool,
957    /// It's open: its children's rows, if it has any, follow it.
958    pub expanded: bool,
959}
960
961/// How far a `Tree` indents its rows' content, as its platform draws it
962/// (`TreeIndent`): a row's content is the rows' width less `start +
963/// per_level × depth`.
964#[derive(Clone, Copy, Debug, Default, PartialEq)]
965pub struct TreeIndent {
966    /// Where a top row's content starts: the disclosure's room.
967    pub start: f32,
968    /// What each level adds.
969    pub per_level: f32,
970}
971
972impl TreeIndent {
973    /// How far the content of a row at `depth` starts.
974    pub fn at(self, depth: u32) -> f32 {
975        self.start + self.per_level * depth as f32
976    }
977}
978
979/// A cell of a `Table`: its row, and its column's index.
980#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
981pub struct CellKey {
982    pub row: RowKey,
983    pub column: usize,
984}
985
986/// A column of a `Table`, as backends get it.
987#[derive(Clone, Debug, PartialEq)]
988pub struct ColumnData {
989    /// Its header's title.
990    pub title: String,
991    /// How wide it starts, in points; `None`: the platform's default. The
992    /// user can resize it, as the platform lets them.
993    pub width: Option<f32>,
994    /// It takes the room the table has past its columns' widths, shared
995    /// with the other columns that do, as the platform shares it.
996    pub expand: bool,
997    /// Its header sorts the table by it when pressed.
998    pub sortable: bool,
999    /// Its cells fill their row, without the platform's padding: as wide as
1000    /// the column and as high as the row (a commit graph whose lines join
1001    /// from row to row). Report its full width in `ColumnWidths`, and the
1002    /// row's height without it in `RowHeight`.
1003    pub fills_row: bool,
1004}
1005
1006/// Which way a `Table` is sorted.
1007#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1008pub enum SortOrder {
1009    #[default]
1010    Ascending,
1011    Descending,
1012}
1013
1014impl SortOrder {
1015    /// The other way round.
1016    pub fn reversed(self) -> SortOrder {
1017        match self {
1018            SortOrder::Ascending => SortOrder::Descending,
1019            SortOrder::Descending => SortOrder::Ascending,
1020        }
1021    }
1022}
1023
1024/// The column a `Table` is sorted by, and which way, as its header shows.
1025#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
1026pub struct ColumnSort {
1027    pub column: usize,
1028    pub order: SortOrder,
1029}
1030
1031/// How many rows of a `List` can be selected.
1032#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1033pub enum SelectionMode {
1034    #[default]
1035    None,
1036    Single,
1037    Multiple,
1038}
1039
1040/// How a `List` sits in its surroundings, mapped to each platform's native
1041/// look. Choosing per platform is up to the app, with `platform!`.
1042#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
1043pub enum ListStyle {
1044    /// The same as `Plain`, on every platform.
1045    #[default]
1046    Automatic,
1047    /// Edge to edge, on the surface around it: sidebars, a window's main
1048    /// content.
1049    Plain,
1050    /// In a bordered box, on the platform's content background: a list
1051    /// inside a form or a dialog.
1052    Framed,
1053}
1054
1055impl ListStyle {
1056    pub fn framed(self) -> bool {
1057        self == ListStyle::Framed
1058    }
1059}
1060
1061/// A group of a `Sidebar`'s items, under a heading if it has a title.
1062#[derive(Clone, Debug, Default, PartialEq)]
1063pub struct SidebarSectionData {
1064    pub title: Option<String>,
1065    pub items: Vec<SidebarItemData>,
1066}
1067
1068/// One item of a `Sidebar`: its title, and the name of its icon in the
1069/// platform's own set (an SF Symbol, a symbolic theme icon, a Segoe
1070/// Fluent Icons glyph), which platforms without it ignore.
1071#[derive(Clone, Debug, Default, PartialEq)]
1072pub struct SidebarItemData {
1073    pub title: String,
1074    pub icon: Option<String>,
1075    /// A second line under the title, in the platform's secondary style.
1076    pub subtitle: Option<String>,
1077    /// Its context menu (empty: none). The platform shows it its own way,
1078    /// on the item, and reports the choice as the sidebar's
1079    /// `ContextMenuItem`; ids are unique across the sidebar's items.
1080    pub menu: Vec<crate::services::MenuEntry>,
1081}
1082
1083/// A property of a native widget. Which ones apply depends on the kind.
1084#[derive(Clone, Debug, PartialEq)]
1085pub enum Prop {
1086    /// A window's title, or a `Group`'s heading (empty: none).
1087    Title(String),
1088    /// A window fills its screen, the platform's own way (a Space of its
1089    /// own on macOS). The user can change it too (the title bar's button,
1090    /// the window manager's key): the backend reports `FullScreenChanged`,
1091    /// which the core absorbs.
1092    FullScreen(bool),
1093    /// The smallest content size the user can make a window, in points.
1094    /// A window smaller when it's set grows to it.
1095    MinSize(Size),
1096    /// The content sets a window's height, not the user, who resizes only
1097    /// its width; where the platform can't hold one side (GTK), neither.
1098    /// The core sets it for a `WindowSize::FollowHeight` window.
1099    HeightFollowsContent(bool),
1100    /// A window fills its screen's working area as the platform's maximize
1101    /// (on macOS, zoom) does, and is back to its own size without. The user
1102    /// can change it too: the backend reports `MaximizedChanged`, which the
1103    /// core absorbs. Sent only if the app chose.
1104    Maximized(bool),
1105    /// The user can resize a window. Without, only the app sets its size;
1106    /// sent only if the app chose.
1107    Resizable(bool),
1108    /// A window's restored frame (see [`WindowFrame`]). The app's places
1109    /// and sizes the window, moved onto a screen if it's on none any more
1110    /// and no larger than that screen's work area; the user moving or
1111    /// resizing it changes it too: the backend reports `FrameChanged`
1112    /// (once as it shows, then as it changes), which the core absorbs.
1113    /// Maximizing it or putting it in full screen doesn't. Sent only if
1114    /// the app chose.
1115    Frame(crate::WindowFrame),
1116    /// Where a window opens when no `Frame` places it. Read as it opens,
1117    /// so the platform keeps it, not the window. Sent only if the app
1118    /// chose.
1119    Placement(crate::Placement),
1120    /// Text content of a `Text`.
1121    Text(String),
1122    /// How many lines a `Text` shows at most, the last one cut off with an
1123    /// ellipsis, as the platform draws one. `None`: all of them.
1124    MaxLines(Option<u32>),
1125    /// Where a `Text` cut off at its line limit puts its ellipsis. AppKit,
1126    /// Qt and WinUI cut off a single line's start or middle only. Sent
1127    /// only if the app chose.
1128    Truncation(Truncation),
1129    /// A `Text`'s or `Icon`'s colour, or the icon's on a `Button` or
1130    /// `ToggleButton` (its caption keeps the platform's). Semantic colours
1131    /// follow the appearance (dark mode, high contrast, the accent colour);
1132    /// `Rgba` is fixed. Icons in full colour keep their own; symbolic ones
1133    /// take it. Sent only if the app chose.
1134    TextColor(Color),
1135    /// A `Text`'s weight, in place of its text style's.
1136    FontWeight(FontWeight),
1137    /// A `Text` in italics.
1138    Italic(bool),
1139    /// Where a `Text`'s lines go across its frame. The core resolves the
1140    /// app's `TextAlign` against the text's direction, so it's left or
1141    /// right here.
1142    TextAlign(HorizontalAlign),
1143    /// Which way a widget lays itself out and draws: a checkbox's box on
1144    /// the right of its caption, a slider's minimum on the right, a text
1145    /// field's text starting on the right. The core resolves it for every
1146    /// native node, and sends it to those that are right to left, and to
1147    /// every node of an app whose language is (never to an app that is
1148    /// only left to right). Frames are already mirrored: containers don't
1149    /// mirror what they hold.
1150    LayoutDirection(LayoutDirection),
1151    /// A `Text`'s text can be selected and copied by the user. Sent when
1152    /// the text is created, and never changed: Qt's selectable label is
1153    /// another item.
1154    Selectable(bool),
1155    /// Caption of a `Button`, `ToggleButton`, `MenuButton`, `SplitButton`,
1156    /// `Checkbox` or `Switch`; accessible name of a `Switch`, `Select`, `RadioGroup`,
1157    /// `Slider`, `NumberInput`, `Progress`, `Image`, `Icon` or `GpuSurface`,
1158    /// and of a button that shows only its icon.
1159    Label(String),
1160    /// Current text of a `TextInput`, `PasswordInput`, `SearchInput` or
1161    /// `TextArea`; a text area's lines end in `\n`.
1162    Value(String),
1163    /// What a text field shows while it's empty. Text areas show it where
1164    /// the platform's have one (Qt, WinUI).
1165    Placeholder(String),
1166    /// What's wrong with a `TextInput`'s, `PasswordInput`'s or
1167    /// `TextArea`'s text, or `None`: the platform marks the field where it
1168    /// has a way to (GTK's `error` style), and assistive technology reads
1169    /// it as invalid, with the message as its description. The app shows
1170    /// the message, as apps on every platform place their own.
1171    Error(Option<String>),
1172    /// A `TextInput` or `TextArea` shows its text, which can be selected
1173    /// and copied, but not edited: by typing, or by assistive technology.
1174    ReadOnly(bool),
1175    /// How many lines of text a `TextArea` is tall at its natural size, in
1176    /// the platform's font and line spacing; it scrolls past them. The
1177    /// layout can still make it taller or shorter.
1178    Lines(u32),
1179    /// A `TextArea`'s lines wrap to its width. Without, a line is as long
1180    /// as its text, and the area scrolls sideways. Sent only if the app
1181    /// chose.
1182    LineWrap(bool),
1183    /// A `TextArea` keeps its end in view as the app sets its text, while
1184    /// it's there (or the area was empty): a log that follows its output,
1185    /// as Terminal and Console do. Scrolled up, it stays put. Turned on, it
1186    /// shows its end. Sent only if the app chose.
1187    FollowsEnd(bool),
1188    /// What a `TextInput` is for; sent only if the app chose.
1189    InputPurpose(InputPurpose),
1190    /// Checked state of a `Checkbox`, `Switch` or `ToggleButton`.
1191    Checked(bool),
1192    /// A `Checkbox` shows the mixed state (some of what it stands for is
1193    /// checked), whatever `Checked` says. A click leaves it: where it lands
1194    /// is the platform's call, and the core absorbs it as `Mixed(false)`.
1195    Mixed(bool),
1196    Enabled(bool),
1197    TextStyle(TextStyle),
1198    ButtonRole(ButtonRole),
1199    ButtonStyle(ButtonStyle),
1200    /// A `Select`'s or `RadioGroup`'s options, in order.
1201    Options(Vec<String>),
1202    /// Which option of a `Select` is chosen: always one, unless it has no
1203    /// options. Which option of a `RadioGroup` is: `None` for none. Which item of a `Sidebar` is, counting across its sections:
1204    /// `None` for none. Which page of a `Tabs` is shown, and which tab of
1205    /// `DocumentTabs` is chosen: always one, unless it has none.
1206    SelectedIndex(Option<usize>),
1207    /// A `Slider`'s or `NumberInput`'s value, within its range. The core
1208    /// sends it after the range, which may have clamped it. A `Split`'s
1209    /// first pane's size along it, in points, which the core keeps within
1210    /// the panes' least sizes.
1211    Number(f64),
1212    /// A `ColorWell`'s colour: an opaque [`Color::Rgba`] (semantic
1213    /// colours and alpha aren't a colour well's).
1214    ColorValue(Color),
1215    /// The values a `Slider` or `NumberInput` can take.
1216    Range {
1217        min: f64,
1218        max: f64,
1219    },
1220    /// A `Slider`'s step, used as the platform uses one: to snap to, where
1221    /// its sliders snap, and to move by from the keyboard. What a
1222    /// `NumberInput`'s buttons and arrow keys add or take away. `None`: the
1223    /// platform's default.
1224    Step(Option<f64>),
1225    /// A `NumberInput` stepped past one end of its range goes on from the
1226    /// other. Sent only if the app chose: without, it's the platform's
1227    /// (AppKit's stepper wraps, the others stop).
1228    WrapAround(bool),
1229    /// Which way a `Slider` or a `Separator` runs; a `Split`'s panes are
1230    /// side by side when it's horizontal.
1231    Orientation(Orientation),
1232    /// A `Split`'s panes' least sizes along it, first then second, from
1233    /// their styles' least width (or height): the platform stops the
1234    /// divider there. Computed by the core.
1235    PaneMinimums([f32; 2]),
1236    /// Which of a `Split`'s panes show, first then second: the divider
1237    /// shows only between two. Computed by the core from the panes'
1238    /// visibility.
1239    PanesShown([bool; 2]),
1240    /// Text the platform shows when the pointer rests on the widget, as
1241    /// its tooltip, and assistive technology reads as its description.
1242    /// Any widget or container can have one; empty: none.
1243    Tooltip(String),
1244    /// The menu the platform shows its own way on a right-click, a long
1245    /// press or the menu key: items, separators and submenus. Any widget
1246    /// or container can have one; empty: none. The node reports the item
1247    /// chosen as [`UiEvent::ContextMenuItem`](crate::UiEvent::ContextMenuItem).
1248    ContextMenu(Vec<MenuEntry>),
1249    /// The node's context menu is built as the platform opens it: the
1250    /// platform calls it, from its own moment before a menu shows, and
1251    /// shows what it returns, which is also the node's `ContextMenu`
1252    /// from then on. `None`: the menu is `ContextMenu` alone.
1253    ContextMenuOnOpen(Option<crate::services::MenuOnOpen>),
1254    /// A `MenuButton`'s or `SplitButton`'s menu: items, separators and
1255    /// submenus, built as a context menu's. The node reports the item chosen as
1256    /// [`UiEvent::MenuItem`](crate::UiEvent::MenuItem).
1257    Menu(Vec<MenuEntry>),
1258    /// A `MenuButton`'s menu is built as the platform opens it, as
1259    /// [`ContextMenuOnOpen`](Prop::ContextMenuOnOpen) builds a context
1260    /// menu: what it returns is shown, and is the node's `Menu` from then
1261    /// on. `None`: the menu is `Menu` alone.
1262    MenuOnOpen(Option<crate::services::MenuOnOpen>),
1263    /// A window is modal, belonging to `owner` (the window it was declared
1264    /// in, if any). Sent once, before the window is shown.
1265    Modal {
1266        owner: Option<NodeId>,
1267        modality: Modality,
1268    },
1269    /// What an `Image` shows.
1270    Image(ImageSource),
1271    /// How an `Image` fills its frame; sent only if the app chose.
1272    ImageFit(ImageFit),
1273    /// What an `Icon` shows, or the icon a `Button`, `ToggleButton`,
1274    /// `MenuButton` or `SplitButton` shows before its caption: a name in
1275    /// the platform's own set (an SF Symbol, a themed
1276    /// icon's name, a Segoe Fluent Icons glyph). Empty: none. A name the
1277    /// set doesn't have shows as the platform shows one: nothing, or its
1278    /// missing-icon icon.
1279    Icon(String),
1280    /// The app's own icon, in place of a named one ([`Prop::Icon`]), for
1281    /// the same widgets: drawn as the platform draws its symbolic icons.
1282    /// `None`: the named one, if any.
1283    VectorIcon(Option<crate::VectorIcon>),
1284    /// How big an `Icon` is, in points, used as the platform sizes icons:
1285    /// an SF Symbol's point size (as a font's), the side of a square
1286    /// elsewhere; a `FileIcon`'s square's side everywhere. Sent only if the
1287    /// app chose.
1288    IconSize(f32),
1289    /// The file or folder a `FileIcon` shows the icon of. It's read when
1290    /// set, as an image file is.
1291    File(PathBuf),
1292    /// A `FileIcon` shows a preview of what's in the file (a picture's,
1293    /// a document's first page) in place of its icon, where the platform
1294    /// makes one; its icon until then, and where it makes none.
1295    Thumbnail(bool),
1296    /// Where a `FileIcon` gets its icon: the file on disk, or only its
1297    /// name. By name, `Thumbnail` is ignored.
1298    FileLookup(FileLookup),
1299    /// A button shows its icon without its caption, which stays its
1300    /// accessible name. Without an icon it shows its caption.
1301    IconOnly(bool),
1302    /// Whether a `Spinner` spins. Stopped, it shows nothing but keeps its
1303    /// place.
1304    Running(bool),
1305    /// How far along a `Progress` is, from 0 to 1. `None`: not known (an
1306    /// indeterminate, animated bar).
1307    Progress(Option<f64>),
1308    /// Which axes a `ScrollView` scrolls.
1309    ScrollAxes(ScrollAxes),
1310    /// Whether a `ScrollView` shows scroll bars, as the platform shows them.
1311    /// Without, it still scrolls, by wheel, trackpad and touch.
1312    ScrollBars(bool),
1313    /// A `Tabs`' page titles, in page order; `DocumentTabs`' titles, in
1314    /// order.
1315    TabTitles(Vec<String>),
1316    /// A `Tabs`' tab icons, in page order: names in the platform's own set,
1317    /// as `Icon`'s; empty for none. Sent only if a tab has one.
1318    TabIcons(Vec<String>),
1319    /// How a `Tabs` shows its tabs. Sent only if the app chose.
1320    TabsStyle(TabsStyle),
1321    /// `DocumentTabs`' tabs have the platform's close buttons (and its
1322    /// middle click, where it has one), which report
1323    /// `TabCloseRequested`; the app closes the tab. Sent only if the app
1324    /// asked (`on_close`).
1325    TabsClosable(bool),
1326    /// The user can drag `DocumentTabs`' tabs to another place among them
1327    /// (and move them from the keyboard, where the platform can), which
1328    /// reports `TabMoved`; the core absorbs it. Sent only if the app asked
1329    /// (`on_move`).
1330    TabsReorderable(bool),
1331    /// `DocumentTabs` have the platform's new-tab button, which reports
1332    /// `NewTabRequested`. Sent only if the app asked (`on_new`).
1333    NewTabButton(bool),
1334    /// Where `DocumentTabs` show their tabs. Sent only if the app chose.
1335    DocumentTabsStyle(DocumentTabsStyle),
1336    /// A `Sidebar`'s items, in sections, in order.
1337    Sections(Vec<SidebarSectionData>),
1338    /// A `Sidebar` is shown beside the window's content, or hidden, as the
1339    /// platform shows and hides one. The user can change it too: the
1340    /// backend reports `SidebarShownChanged`, which the core absorbs. Sent
1341    /// only if the app chose.
1342    SidebarShown(bool),
1343    /// A `Popover` is shown by its parent, or not. The user dismisses one
1344    /// too (a click outside, Escape): the backend reports
1345    /// `PopoverShownChanged(false)`, which the core absorbs.
1346    PopoverShown(bool),
1347    /// What a `SearchInput` suggests for its text, in a list under it while
1348    /// the user types, as each platform shows a field's suggestions (an
1349    /// `AutoSuggestBox`'s list, a list in a window that doesn't take the
1350    /// keyboard on AppKit, a popover that doesn't on GTK, a popup that
1351    /// doesn't on Qt). The field keeps the keyboard: the arrows move
1352    /// through the list, Return picks, Escape hides it. Empty: none.
1353    Suggestions(Vec<Suggestion>),
1354    /// A `SearchInput` searches on Return (and when cleared), not as the
1355    /// user types: each platform's setting for searches that take a while
1356    /// (AppKit's `sendsWholeSearchString`, GTK's `activate` alone, WinUI's
1357    /// `QuerySubmitted` alone, Kirigami's `autoAccept` off). Sent only if
1358    /// the app chose.
1359    SearchOnReturn(bool),
1360    /// A `Container` at the top of its window's content is the window's
1361    /// header, the part that stays while what's under it scrolls: on
1362    /// AppKit it goes in the title bar, under the title and toolbar, in
1363    /// their glass (a bottom `NSTitlebarAccessoryViewController`), and the
1364    /// scroll view right under it runs up under the bar, blurred at its
1365    /// edge, as Safari's and Mail's bars have it. The others have no such
1366    /// bar and leave it where it is, at the content's top; so does AppKit
1367    /// for one that isn't there, or beside a sidebar. Sent only if the app
1368    /// chose.
1369    Header(bool),
1370    /// How a header meets what scrolls under it. Sent only if the app
1371    /// chose.
1372    HeaderEdge(HeaderEdge),
1373    /// A container that's a pane down its window's side that navigates
1374    /// (the rail that picks a Git client's pages, a mail app's folders) when the app builds
1375    /// one itself rather than with `Sidebar`. On WinUI, under tabs in the
1376    /// title bar, it's Mica Alt's commanding layer, as a header is; the
1377    /// others leave it as it is. Sent only if the app chose.
1378    SidebarPane(bool),
1379    /// A container the pointer passes through, with everything in it, to
1380    /// what's under it: a hint laid over a control. Sent only if the app
1381    /// chose.
1382    ClickThrough(bool),
1383    /// A `List`'s rows, in order.
1384    Rows(Vec<RowKey>),
1385    /// A `Tree`'s rows that show, in order: a row, then its open
1386    /// children's rows. Children of closed rows aren't sent.
1387    TreeRows(Vec<TreeRow>),
1388    /// A `Tree`'s rows whose children are being read (a folder on a
1389    /// network share opening), of the rows that show: the platform shows
1390    /// its spinner where the row's disclosure is. Sent only if the app
1391    /// said which rows load.
1392    TreeLoading(Vec<RowKey>),
1393    /// How high a `List`'s rows are likely to be, for platforms that must
1394    /// size rows before they're shown.
1395    EstimatedRowHeight(f32),
1396    /// Which row of its `List` a row host shows.
1397    Row(RowKey),
1398    /// A `Table`'s columns, in order.
1399    Columns(Vec<ColumnData>),
1400    /// The column a `Table` is sorted by, which its header shows. The user
1401    /// pressing a sortable column's header sorts it as the platform does:
1402    /// the backend reports `Changed(Sort)`, which the core absorbs.
1403    Sort(Option<ColumnSort>),
1404    /// Which cell of its `Table` a cell host shows.
1405    Cell(CellKey),
1406    SelectionMode(SelectionMode),
1407    ListStyle(ListStyle),
1408    /// The selected rows of a `List`.
1409    Selected(Vec<RowKey>),
1410    /// A custom widget's props, with its renders.
1411    Custom(CustomProps),
1412    /// What a drawn custom widget shows. Computed by the core after layout,
1413    /// so it arrives with the frames.
1414    Drawing(DisplayList),
1415    /// A `Native` node's factory (on create), then its updates: payloads in
1416    /// the backend's own form.
1417    Native(Opaque),
1418    /// A `GpuSurface` takes keys and the pointer, and reports them as
1419    /// `SurfaceInput`: it takes focus from a click and from Tab.
1420    TakesInput(bool),
1421    /// A `GpuSurface` holds the pointer: the cursor is hidden and stays
1422    /// put, and its moves are reported as `SurfaceInput::Motion`. Only
1423    /// while its window is the active one; the backend reports
1424    /// `PointerLockEnded` when that stops, or it can't lock.
1425    PointerLock(bool),
1426    /// A `GpuSurface` takes every key while it has focus, the system's
1427    /// shortcuts and the app's own too, as far as the platform lets an
1428    /// app. Setting it focuses the surface; the backend reports
1429    /// `KeyboardGrabEnded` when the surface or its window loses focus, or
1430    /// it can't grab.
1431    KeyboardGrab(bool),
1432    /// The pointer's cursor over a `GpuSurface`.
1433    Cursor(Cursor),
1434    /// A `GpuSurface` that takes input takes text too, as a text field
1435    /// does: its keys report what they type, and the platform's input
1436    /// methods are on while it has focus, committing as
1437    /// `SurfaceInput::Text`.
1438    TextInput(bool),
1439    /// Whether the platform's input methods are on while a `GpuSurface`
1440    /// takes text (they are unless this says otherwise). Off, its keys
1441    /// still report what they type, dead keys and AltGr composed in, but
1442    /// nothing composes: for a modal editor whose keys are commands
1443    /// outside its insert mode, as a terminal's are.
1444    InputMethod(bool),
1445    /// Where the caret is on a `GpuSurface` that takes text, in points from
1446    /// its top left: the input method's candidate window opens by it.
1447    TextCursor(Option<Rect>),
1448    /// A `GpuSurface` lets the window's backdrop show where what the app
1449    /// presents isn't opaque: the material the platform puts behind a
1450    /// translucent window (AppKit's behind-window vibrancy, WinUI's Mica,
1451    /// which its windows always have), or the window's own background where
1452    /// there's none. The app still presents with alpha.
1453    Transparent(bool),
1454    /// A `Container` or `Group` takes the files and folders this says
1455    /// when they're dragged from the platform's file manager and dropped
1456    /// on it; `None`: none. While acceptable files are over it, the
1457    /// platform shows it'll copy them, and the node reports
1458    /// `DropHover(true)`, then `DropHover(false)`; a drop reports the ones
1459    /// it takes as `FilesDropped`.
1460    FileDrop(Option<FileDrop>),
1461    /// A `Container` or `Group` reports the pointer coming over it, or
1462    /// over anything inside it, and leaving, as
1463    /// [`UiEvent::Hover`](crate::UiEvent::Hover). Sent only if the app
1464    /// asked (`on_hover`).
1465    Hover(bool),
1466    /// A `Container` or `Group` reports a double click on it, or on
1467    /// anything inside it that isn't a control (a label, an icon), as
1468    /// [`UiEvent::DoubleClick`](crate::UiEvent::DoubleClick). Sent only if
1469    /// the app asked (`on_double_click`).
1470    DoubleClick(bool),
1471    /// A `Container` or `Group` reports a click on it, or on anything
1472    /// inside it that isn't a control, as [`UiEvent::Click`](crate::UiEvent::Click),
1473    /// as a header that opens its section. Sent only if the app asked
1474    /// (`on_click`).
1475    Click(bool),
1476    /// A `List`'s or `Table`'s rows' files: dragging a row carries its
1477    /// file out of the app (to the file manager, another app, a folder),
1478    /// and dragging a selected row carries every selected row's, as the
1479    /// platform drags a selection. The drag offers to copy. Rows without a
1480    /// file don't drag. Sent before the rows, and only if the app gave
1481    /// them.
1482    RowFiles(Vec<(RowKey, PathBuf)>),
1483    /// A `List`'s rows can be dragged within it, and dropped where it
1484    /// says (`List::on_move`); it reports `RowsMoved`. Sent only if the app
1485    /// gave it.
1486    RowMoves(RowMoves),
1487    /// The keys a `Container`, `Group`, `List` or `Table` takes while it,
1488    /// or a control inside it, has keyboard focus, and the focused control
1489    /// doesn't use them itself: they go up from the focused control, as the
1490    /// platform sends keys it doesn't use, to the nearest node that takes
1491    /// them, which reports [`UiEvent::Key`](crate::UiEvent::Key). On a
1492    /// `TextInput` or `SearchInput`, the keys it takes before its own use
1493    /// of them (the arrows, Return, Escape): a field that moves through a
1494    /// list beside it, as Xcode's Open Quickly. A search field's
1495    /// suggestions still take theirs first. Sent only if the app gave some.
1496    Keys(Vec<Shortcut>),
1497    /// Raw platform settings for a built-in widget (see
1498    /// [`Tweak`](crate::Tweak)), in the backend's own form. Applied after
1499    /// the widget's other props, and again whenever they change.
1500    Tweak(Opaque),
1501}
1502
1503impl Prop {
1504    /// Two props with the same key replace each other.
1505    pub fn key(&self) -> std::mem::Discriminant<Prop> {
1506        std::mem::discriminant(self)
1507    }
1508
1509    /// Whether changing this prop can change the intrinsic size of a widget
1510    /// of this kind.
1511    pub fn affects_measure(&self, kind: WidgetKind) -> bool {
1512        // A spin box can be as wide as its range's longest number (GTK) or
1513        // its text (Qt).
1514        if kind == WidgetKind::NumberInput && matches!(self, Prop::Range { .. } | Prop::Number(_)) {
1515            return true;
1516        }
1517        // A pull-down can be as wide as its widest item (AppKit).
1518        if kind == WidgetKind::MenuButton && matches!(self, Prop::Menu(_)) {
1519            return true;
1520        }
1521        if kind == WidgetKind::TextArea && matches!(self, Prop::Lines(_)) {
1522            return true;
1523        }
1524        // A strip is as wide as its tabs and its new-tab button, and is the
1525        // window's or the content's.
1526        if kind == WidgetKind::DocumentTabs
1527            && matches!(
1528                self,
1529                Prop::TabTitles(_) | Prop::TabsClosable(_) | Prop::NewTabButton(_) | Prop::DocumentTabsStyle(_)
1530            )
1531        {
1532            return true;
1533        }
1534        matches!(
1535            self,
1536            Prop::Text(_)
1537                | Prop::MaxLines(_)
1538                | Prop::Truncation(_)
1539                | Prop::FontWeight(_)
1540                | Prop::Italic(_)
1541                | Prop::Label(_)
1542                | Prop::Placeholder(_)
1543                | Prop::Options(_)
1544                | Prop::SelectedIndex(_)
1545                | Prop::TextStyle(_)
1546                | Prop::ButtonRole(_)
1547                | Prop::ButtonStyle(_)
1548                | Prop::Orientation(_)
1549                | Prop::Image(_)
1550                | Prop::Icon(_)
1551                | Prop::VectorIcon(_)
1552                | Prop::IconSize(_)
1553                | Prop::IconOnly(_)
1554                | Prop::Custom(_)
1555                | Prop::Native(_)
1556                | Prop::Tweak(_)
1557        )
1558    }
1559}
1560
1561/// Where the item at `index` of a list is after the one at `from` moved to
1562/// `to`: `DocumentTabs`' chosen tab after `TabMoved`.
1563pub fn moved_index(index: usize, from: usize, to: usize) -> usize {
1564    if index == from {
1565        to
1566    } else if from < index && index <= to {
1567        index - 1
1568    } else if to <= index && index < from {
1569        index + 1
1570    } else {
1571        index
1572    }
1573}
1574
1575/// Finds a prop by pattern in a prop list.
1576#[macro_export]
1577macro_rules! find_prop {
1578    ($props:expr, $variant:ident) => {
1579        $props.iter().find_map(|p| match p {
1580            $crate::Prop::$variant(v) => Some(v.clone()),
1581            _ => None,
1582        })
1583    };
1584}
1585
1586macro_rules! static_value {
1587    ($($t:ty),*) => {$(
1588        impl mitsuami_reactive::IntoValue<$t> for $t {
1589            fn into_value(self) -> mitsuami_reactive::Value<$t> {
1590                mitsuami_reactive::Value::Static(self)
1591            }
1592        }
1593    )*};
1594}
1595
1596static_value!(
1597    FileDrop,
1598    TextStyle,
1599    FontWeight,
1600    TextAlign,
1601    Truncation,
1602    FileLookup,
1603    crate::draw::Color,
1604    ButtonRole,
1605    ButtonStyle,
1606    TabsStyle,
1607    HeaderEdge,
1608    DocumentTabsStyle,
1609    Orientation,
1610    ScrollAxes,
1611    SelectionMode,
1612    SortOrder,
1613    ListStyle,
1614    InputPurpose,
1615    ImageSource,
1616    Pixels,
1617    ImageFit,
1618    Modality,
1619    Cursor,
1620    Size,
1621    crate::VectorIcon
1622);