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    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`, and
146    /// with [`Prop::TextInput`] what its keys type.
147    GpuSurface,
148    /// A native scroll container. It has exactly one native child, the
149    /// content, which the core lays out and may be larger than the viewport.
150    ScrollView,
151    /// A native list control (NSTableView, ListView, gtk::ListView, QML
152    /// ListView). Its data is [`Prop::Rows`]. The platform decides which rows
153    /// exist (`RowShown`, `RowHidden`); its native children are the hosts of
154    /// the rows the core mounted for those (`Container`s with a
155    /// [`Prop::Row`]), in row order. It scrolls like a `ScrollView`.
156    List,
157    /// A native table: a `List` whose rows are cells under column headers
158    /// (NSTableView with columns and a header, gtk::ColumnView, a QML
159    /// TableView under a HorizontalHeaderView; WinUI has none, so a
160    /// ListView under a header of column buttons, as Fluent apps build
161    /// one). Its columns are [`Prop::Columns`], sorted as [`Prop::Sort`]
162    /// says. Its data, selection and scrolling are a `List`'s; its native
163    /// children are the hosts of the cells the core mounted for the rows it
164    /// shows (`Container`s with a [`Prop::Cell`]), in row order, then
165    /// column order. The platform sizes its columns, and the user resizes
166    /// them: it reports the width each column gives its cells
167    /// (`ColumnWidths`).
168    Table,
169    /// A native tab view: pages, one shown at a time, and a strip of their
170    /// titles to pick one (NSTabView, libadwaita's inline view switcher or
171    /// a gtk::Notebook, a SelectorBar over its pages on WinUI, Kirigami's
172    /// NavigationTabBar or a QQC2.TabBar). Its native
173    /// children are its pages' hosts (`Container`s), in order, titled by
174    /// [`Prop::TabTitles`]; the shown one is [`Prop::SelectedIndex`].
175    /// Every page stays mounted. The core lays out each page at the size
176    /// inside the tab strip and border ([`PlatformMetrics::tab_insets`](crate::PlatformMetrics)),
177    /// all in the same place, so the view is as big as its biggest page;
178    /// the platform places them and shows the chosen one.
179    Tabs,
180    /// Native document tabs: a strip of tabs with no pages, for documents
181    /// the app shows in one place of its own (a terminal's sessions drawn
182    /// on one surface). WinUI's TabView with items without content,
183    /// libadwaita's AdwTabBar, a QQC2.TabBar with close buttons, and on
184    /// AppKit a strip of the backend's, made as the system's tab bar. Titled by [`Prop::TabTitles`], the chosen
185    /// one [`Prop::SelectedIndex`]; the user closes them
186    /// ([`Prop::TabsClosable`]), moves them ([`Prop::TabsReorderable`]) and
187    /// asks for a new one ([`Prop::NewTabButton`]), where the app lets
188    /// them. Measured by the backend; empty where the tabs are the
189    /// window's ([`DocumentTabsStyle::Window`], [`DocumentTabsStyle::TitleRow`]).
190    DocumentTabs,
191    /// A native box around related content, under an optional heading
192    /// ([`Prop::Title`]): an NSBox, libadwaita's card under a heading, a
193    /// Fluent card under a heading on WinUI, a QQC2.GroupBox. The core lays
194    /// out its children as a container's, inside
195    /// [`PlatformMetrics::group_insets`](crate::PlatformMetrics) (or the
196    /// titled ones), and it's at least as wide as its heading, which
197    /// backends measure. Backends draw the box behind the children, which
198    /// are its native children.
199    Group,
200    /// A custom widget (see [`CustomWidget`](crate::CustomWidget)), named
201    /// after it. Its props travel as [`Prop::Custom`].
202    Custom(&'static str),
203    /// A raw native view supplied by app code. Its factory and updates
204    /// travel as [`Prop::Native`].
205    Native,
206}
207
208impl WidgetKind {
209    pub fn is_native(self) -> bool {
210        self != WidgetKind::Fragment
211    }
212
213    /// Containers lay out children; everything else is measured by the backend.
214    pub fn is_container(self) -> bool {
215        matches!(
216            self,
217            WidgetKind::Window
218                | WidgetKind::Container
219                | WidgetKind::ToolbarItem
220                | WidgetKind::ScrollView
221                | WidgetKind::Tabs
222                | WidgetKind::Group
223        )
224    }
225
226    /// Scrolls its content: `ScrollTo` and `Scrolled` apply.
227    pub fn scrolls(self) -> bool {
228        matches!(self, WidgetKind::ScrollView | WidgetKind::List | WidgetKind::Table)
229    }
230
231    /// Has rows the platform realises: a `List` or a `Table`.
232    pub fn has_rows(self) -> bool {
233        matches!(self, WidgetKind::List | WidgetKind::Table)
234    }
235
236    pub fn name(self) -> &'static str {
237        match self {
238            WidgetKind::Window => "Window",
239            WidgetKind::Container => "Container",
240            WidgetKind::ToolbarItem => "ToolbarItem",
241            WidgetKind::Sidebar => "Sidebar",
242            WidgetKind::ScrollView => "ScrollView",
243            WidgetKind::List => "List",
244            WidgetKind::Table => "Table",
245            WidgetKind::Tabs => "Tabs",
246            WidgetKind::DocumentTabs => "DocumentTabs",
247            WidgetKind::Group => "Group",
248            WidgetKind::Fragment => "Fragment",
249            WidgetKind::Text => "Text",
250            WidgetKind::Button => "Button",
251            WidgetKind::ToggleButton => "ToggleButton",
252            WidgetKind::MenuButton => "MenuButton",
253            WidgetKind::TextInput => "TextInput",
254            WidgetKind::PasswordInput => "PasswordInput",
255            WidgetKind::SearchInput => "SearchInput",
256            WidgetKind::TextArea => "TextArea",
257            WidgetKind::Checkbox => "Checkbox",
258            WidgetKind::Switch => "Switch",
259            WidgetKind::Select => "Select",
260            WidgetKind::RadioGroup => "RadioGroup",
261            WidgetKind::Slider => "Slider",
262            WidgetKind::NumberInput => "NumberInput",
263            WidgetKind::Progress => "Progress",
264            WidgetKind::Spinner => "Spinner",
265            WidgetKind::Separator => "Separator",
266            WidgetKind::Image => "Image",
267            WidgetKind::Icon => "Icon",
268            WidgetKind::FileIcon => "FileIcon",
269            WidgetKind::GpuSurface => "GpuSurface",
270            WidgetKind::Custom(name) => name,
271            WidgetKind::Native => "Native",
272        }
273    }
274}
275
276/// Semantic text styles, mapped to each platform's type ramp.
277#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
278pub enum TextStyle {
279    LargeTitle,
280    Title,
281    Headline,
282    #[default]
283    Body,
284    Callout,
285    Caption,
286    Monospace,
287}
288
289/// How heavy a `Text`'s font is, in place of its text style's weight.
290/// A platform whose font lacks one uses the nearest it has.
291#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
292pub enum FontWeight {
293    #[default]
294    Regular,
295    Medium,
296    Semibold,
297    Bold,
298}
299
300/// Where a `Text`'s lines go across its frame, in its reading direction:
301/// `Start` is the left in left-to-right text, the right in right-to-left.
302#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
303pub enum TextAlign {
304    #[default]
305    Start,
306    Center,
307    End,
308}
309
310/// Where a `Text` cut off at its line limit puts its ellipsis: in place
311/// of its start, its middle (a path's folders, keeping its file name) or
312/// its end. Start and end are the text's, so in right-to-left text the
313/// start is on the right. Platforms that can't put one there cut off the
314/// end, as their labels do.
315#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
316pub enum Truncation {
317    Start,
318    Middle,
319    #[default]
320    End,
321}
322
323/// A [`TextAlign`] the core has resolved against the text's direction, as
324/// backends get it.
325#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
326pub enum HorizontalAlign {
327    #[default]
328    Left,
329    Center,
330    Right,
331}
332
333/// Which way a native widget lays itself out, as backends get it: the
334/// core has resolved the node's direction (its own, its parent's, or the
335/// app's language's).
336#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
337pub enum LayoutDirection {
338    #[default]
339    LeftToRight,
340    RightToLeft,
341}
342
343/// What a `TextInput` is for, which the platform uses as it uses one: to
344/// pick an on-screen keyboard, to offer autofill, to check what's typed.
345/// Only the purposes every platform has.
346#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
347pub enum InputPurpose {
348    /// Any text.
349    #[default]
350    Text,
351    Email,
352    Url,
353    /// A telephone number.
354    Phone,
355}
356
357/// What a button does in its window or dialog, which each platform shows
358/// and handles its own way. Platforms without an equivalent ignore it.
359#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
360pub enum ButtonRole {
361    /// An ordinary button.
362    #[default]
363    Normal,
364    /// The action Return confirms: the default button on AppKit (Return
365    /// clicks it), the suggested action on GTK, the default button on Qt, the
366    /// accent button on WinUI. One per window or dialog.
367    Default,
368    /// The action Escape takes: the cancel button on AppKit (Escape clicks
369    /// it). The others show it as a normal button.
370    Cancel,
371    /// An action that destroys data: GTK's destructive action; AppKit marks
372    /// it so the system can warn. Qt and WinUI have no such style.
373    Destructive,
374}
375
376/// Where a window's header (`Prop::Header`) meets what scrolls under it,
377/// where the platform blurs it there (AppKit's scroll edge effect, macOS
378/// 26.1 and later). The others have no such edge, and ignore it.
379#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
380pub enum HeaderEdge {
381    /// The platform's own: soft on macOS 26.
382    #[default]
383    Automatic,
384    /// What scrolls under it fades into the blur.
385    Soft,
386    /// The header ends at a hard line, opaque down to it, as Finder's and
387    /// Mail's bars on a busy list.
388    Hard,
389}
390
391/// How a `Tabs` shows its tabs, where the platform has more than one way
392/// (GNOME and KDE). The others show theirs, and ignore it.
393#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
394pub enum TabsStyle {
395    /// The platform's own: navigation tabs on GNOME and KDE.
396    #[default]
397    Automatic,
398    /// A tab bar over the pages: GTK's `gtk::Notebook`, Qt's
399    /// `QQC2.TabBar`.
400    TabBar,
401    /// Navigation tabs above the pages: libadwaita's inline view switcher
402    /// (a tab bar before libadwaita 1.7), Kirigami's `NavigationTabBar`.
403    Navigation,
404}
405
406/// Where `DocumentTabs` show their tabs: in the window's own chrome, or
407/// in the content where they're declared.
408#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
409pub enum DocumentTabsStyle {
410    /// The platform's own: the window's on macOS and Windows (in the title
411    /// bar, as Safari, Xcode and Terminal have them), a strip in the
412    /// content on GNOME and KDE (as Console and Konsole).
413    #[default]
414    Automatic,
415    /// A strip in the content, where they're declared, on every platform:
416    /// on macOS one the backend builds, as Safari's is.
417    Strip,
418    /// The window's own: a strip in AppKit's title bar, under the title and
419    /// toolbar, WinUI's tab view in the title bar. GTK and Qt have none,
420    /// so a strip.
421    Window,
422    /// In the title's own row, beside the window's buttons and toolbar
423    /// items, the title hidden: Safari's compact tabs on macOS, and on
424    /// GNOME libadwaita's tab bar in the header bar's title's place.
425    /// WinUI's tabs in the title bar already are; Qt has none, so a strip.
426    TitleRow,
427}
428
429/// How a button is drawn, mapped to each platform's native look.
430#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
431pub enum ButtonStyle {
432    /// The same as `Bordered`, on every platform.
433    #[default]
434    Automatic,
435    /// The platform's push button, with its bezel or frame.
436    Bordered,
437    /// No bezel or frame until hovered, where the platform does that: for
438    /// toolbars, and buttons that sit among text.
439    Borderless,
440}
441
442/// What an `Image` shows.
443#[derive(Clone, Debug, PartialEq)]
444pub enum ImageSource {
445    /// An image file, decoded by the platform: PNG and JPEG everywhere,
446    /// other formats where the platform reads them. It's read when the
447    /// source is set; a file that changes under the same path isn't read
448    /// again.
449    File(PathBuf),
450    /// Pixels the app has in memory.
451    Pixels(Pixels),
452}
453
454/// An image in memory: rows of straight (not premultiplied) RGBA8, top
455/// row first, drawn at `scale` pixels to a point, so an image made at the
456/// window's scale factor is shown pixel for pixel.
457#[derive(Clone, PartialEq)]
458pub struct Pixels {
459    width: u32,
460    height: u32,
461    scale: f32,
462    rgba: Arc<[u8]>,
463}
464
465/// Its size and scale, not its bytes.
466impl fmt::Debug for Pixels {
467    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
468        write!(f, "Pixels({}×{} @{}x)", self.width, self.height, self.scale)
469    }
470}
471
472impl Pixels {
473    /// Panics unless `rgba` holds `width × height` pixels.
474    pub fn new(width: u32, height: u32, rgba: impl Into<Arc<[u8]>>) -> Pixels {
475        let rgba = rgba.into();
476        // Checked: a size that wraps could pass with too few bytes, which
477        // backends hand to the platform as the whole image.
478        let len = (width as usize).checked_mul(height as usize).and_then(|n| n.checked_mul(4));
479        assert_eq!(Some(rgba.len()), len, "{width}×{height} RGBA8 pixels");
480        Pixels { width, height, scale: 1.0, rgba }
481    }
482
483    /// Pixels to a point; 1 by default.
484    pub fn scale(mut self, scale: f32) -> Pixels {
485        assert!(scale > 0.0, "a scale above 0");
486        self.scale = scale;
487        self
488    }
489
490    pub fn width(&self) -> u32 {
491        self.width
492    }
493
494    pub fn height(&self) -> u32 {
495        self.height
496    }
497
498    pub fn scale_factor(&self) -> f32 {
499        self.scale
500    }
501
502    pub fn rgba(&self) -> &[u8] {
503        &self.rgba
504    }
505
506    /// Its size in points.
507    pub fn size(&self) -> crate::Size {
508        crate::Size::new(self.width as f32 / self.scale, self.height as f32 / self.scale)
509    }
510}
511
512/// How an `Image` fills a frame the layout makes a different size from
513/// it. Only the fits every platform's image view has; without one, each
514/// fits as it does by default.
515#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
516pub enum ImageFit {
517    /// As large as fits, keeping its proportions (NSImageView
518    /// proportionally up or down, GTK `Contain`, Qt `PreserveAspectFit`,
519    /// XAML `Uniform`).
520    Contain,
521    /// The whole frame, proportions or not (axes independently, `Fill`,
522    /// `Stretch`, `Fill`).
523    Stretch,
524}
525
526/// The pointer's cursor over a `GpuSurface`, while it isn't locked.
527#[derive(Clone, Debug, Default, PartialEq)]
528pub enum Cursor {
529    /// The platform's own: the arrow.
530    #[default]
531    Default,
532    /// None: the pointer still moves, unseen (a machine that draws its own).
533    Hidden,
534    /// An image of the app's, e.g. the one a machine gives its pointer,
535    /// shown at its scale. `hotspot`: the point that points, in points from
536    /// its top left.
537    Image { pixels: Pixels, hotspot: Point },
538    /// One of the platform's own, by what it means. A platform with none
539    /// for it shows its arrow.
540    System(SystemCursor),
541}
542
543/// The platform cursors a `Cursor::System` names: the ones the platforms
544/// share, as CSS names them.
545#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
546pub enum SystemCursor {
547    /// The text cursor, an I-beam.
548    Text,
549    /// Busy: nothing can be done (the hourglass, the spinner).
550    Wait,
551    /// Busy, but it can still be used (the arrow with a spinner).
552    Progress,
553    /// A link: the pointing hand.
554    Pointer,
555    Crosshair,
556    NotAllowed,
557    Help,
558    /// Something can be moved: arrows four ways.
559    Move,
560    /// Resizing up and down, left and right, and along the diagonals.
561    ResizeNorthSouth,
562    ResizeEastWest,
563    ResizeNorthWestSouthEast,
564    ResizeNorthEastSouthWest,
565}
566
567impl SystemCursor {
568    /// Its CSS name (`cursor:`), which GTK and freedesktop cursor themes
569    /// use too.
570    pub fn css_name(self) -> &'static str {
571        match self {
572            SystemCursor::Text => "text",
573            SystemCursor::Wait => "wait",
574            SystemCursor::Progress => "progress",
575            SystemCursor::Pointer => "pointer",
576            SystemCursor::Crosshair => "crosshair",
577            SystemCursor::NotAllowed => "not-allowed",
578            SystemCursor::Help => "help",
579            SystemCursor::Move => "move",
580            SystemCursor::ResizeNorthSouth => "ns-resize",
581            SystemCursor::ResizeEastWest => "ew-resize",
582            SystemCursor::ResizeNorthWestSouthEast => "nwse-resize",
583            SystemCursor::ResizeNorthEastSouthWest => "nesw-resize",
584        }
585    }
586}
587
588/// What a modal `Window` blocks while it's open, shown each platform's way.
589#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
590pub enum Modality {
591    /// The window it belongs to (the one it's declared in): a sheet on
592    /// that window on macOS, Qt's `WindowModal`, an owned `IsModal` window
593    /// on WinUI. GTK's modal windows block the whole app.
594    Window,
595    /// Every other window of the app: a window in AppKit's modal loop,
596    /// Qt's `ApplicationModal`, a modal window on GTK, and on WinUI an
597    /// owned `IsModal` window that also disables the app's other windows.
598    Application,
599}
600
601/// The window whose content is being built: provided in each window's
602/// scope, so views can find the window they're in (a modal `Window`
603/// belongs to it, a `Toolbar`'s items go in its toolbar).
604#[derive(Clone, Copy, Debug, PartialEq, Eq)]
605pub struct CurrentWindow(pub NodeId);
606
607/// Which files a node takes when they're dropped on it: files with these
608/// extensions (any file without a list), and folders if `folders`.
609#[derive(Clone, Debug, Default, PartialEq, Eq, Hash)]
610pub struct FileDrop {
611    /// Without the dot, compared ignoring case. `None`: any file.
612    pub extensions: Option<Vec<String>>,
613    pub folders: bool,
614}
615
616impl FileDrop {
617    /// Any file, no folders.
618    pub fn files() -> FileDrop {
619        FileDrop { extensions: None, folders: false }
620    }
621
622    /// Files with these extensions (`"iso"`, not `".iso"`), no folders.
623    pub fn extensions<S: Into<String>>(extensions: impl IntoIterator<Item = S>) -> FileDrop {
624        FileDrop { extensions: Some(extensions.into_iter().map(Into::into).collect()), folders: false }
625    }
626
627    /// Folders only.
628    pub fn folders() -> FileDrop {
629        FileDrop { extensions: Some(Vec::new()), folders: true }
630    }
631
632    /// Folders too.
633    pub fn and_folders(mut self) -> FileDrop {
634        self.folders = true;
635        self
636    }
637
638    /// Whether it takes this file or folder, as it is on disk.
639    pub fn accepts(&self, path: &std::path::Path) -> bool {
640        if path.is_dir() {
641            return self.folders;
642        }
643        match &self.extensions {
644            None => true,
645            Some(extensions) => path
646                .extension()
647                .and_then(|e| e.to_str())
648                .is_some_and(|e| extensions.iter().any(|x| x.eq_ignore_ascii_case(e))),
649        }
650    }
651
652    /// What it takes of these, in order.
653    pub fn accepted(&self, paths: &[PathBuf]) -> Vec<PathBuf> {
654        paths.iter().filter(|p| self.accepts(p)).cloned().collect()
655    }
656}
657
658/// Which way a `Slider` or a `Separator` runs. Every platform has vertical
659/// sliders; larger values are up on all of them.
660#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
661pub enum Orientation {
662    #[default]
663    Horizontal,
664    Vertical,
665}
666
667impl Orientation {
668    pub fn vertical(self) -> bool {
669        self == Orientation::Vertical
670    }
671}
672
673/// Scrolling directions of a `ScrollView`.
674#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
675pub enum ScrollAxes {
676    #[default]
677    Vertical,
678    Horizontal,
679    Both,
680}
681
682impl ScrollAxes {
683    pub fn horizontal(self) -> bool {
684        matches!(self, ScrollAxes::Horizontal | ScrollAxes::Both)
685    }
686
687    pub fn vertical(self) -> bool {
688        matches!(self, ScrollAxes::Vertical | ScrollAxes::Both)
689    }
690}
691
692/// Identity of a row of a `List`, stable while its item's key stays in the
693/// data. Assigned by the core.
694#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
695pub struct RowKey(pub u64);
696
697/// A cell of a `Table`: its row, and its column's index.
698#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
699pub struct CellKey {
700    pub row: RowKey,
701    pub column: usize,
702}
703
704/// A column of a `Table`, as backends get it.
705#[derive(Clone, Debug, PartialEq)]
706pub struct ColumnData {
707    /// Its header's title.
708    pub title: String,
709    /// How wide it starts, in points; `None`: the platform's default. The
710    /// user can resize it, as the platform lets them.
711    pub width: Option<f32>,
712    /// It takes the room the table has past its columns' widths, shared
713    /// with the other columns that do, as the platform shares it.
714    pub expand: bool,
715    /// Its header sorts the table by it when pressed.
716    pub sortable: bool,
717}
718
719/// Which way a `Table` is sorted.
720#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
721pub enum SortOrder {
722    #[default]
723    Ascending,
724    Descending,
725}
726
727impl SortOrder {
728    /// The other way round.
729    pub fn reversed(self) -> SortOrder {
730        match self {
731            SortOrder::Ascending => SortOrder::Descending,
732            SortOrder::Descending => SortOrder::Ascending,
733        }
734    }
735}
736
737/// The column a `Table` is sorted by, and which way, as its header shows.
738#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
739pub struct ColumnSort {
740    pub column: usize,
741    pub order: SortOrder,
742}
743
744/// How many rows of a `List` can be selected.
745#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
746pub enum SelectionMode {
747    #[default]
748    None,
749    Single,
750    Multiple,
751}
752
753/// How a `List` sits in its surroundings, mapped to each platform's native
754/// look. Choosing per platform is up to the app, with `platform!`.
755#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
756pub enum ListStyle {
757    /// The same as `Plain`, on every platform.
758    #[default]
759    Automatic,
760    /// Edge to edge, on the surface around it: sidebars, a window's main
761    /// content.
762    Plain,
763    /// In a bordered box, on the platform's content background: a list
764    /// inside a form or a dialog.
765    Framed,
766}
767
768impl ListStyle {
769    pub fn framed(self) -> bool {
770        self == ListStyle::Framed
771    }
772}
773
774/// A group of a `Sidebar`'s items, under a heading if it has a title.
775#[derive(Clone, Debug, Default, PartialEq)]
776pub struct SidebarSectionData {
777    pub title: Option<String>,
778    pub items: Vec<SidebarItemData>,
779}
780
781/// One item of a `Sidebar`: its title, and the name of its icon in the
782/// platform's own set (an SF Symbol, a symbolic theme icon, a Segoe
783/// Fluent Icons glyph), which platforms without it ignore.
784#[derive(Clone, Debug, Default, PartialEq)]
785pub struct SidebarItemData {
786    pub title: String,
787    pub icon: Option<String>,
788    /// A second line under the title, in the platform's secondary style.
789    pub subtitle: Option<String>,
790    /// Its context menu (empty: none). The platform shows it its own way,
791    /// on the item, and reports the choice as the sidebar's
792    /// `ContextMenuItem`; ids are unique across the sidebar's items.
793    pub menu: Vec<crate::services::MenuEntry>,
794}
795
796/// A property of a native widget. Which ones apply depends on the kind.
797#[derive(Clone, Debug, PartialEq)]
798pub enum Prop {
799    /// A window's title, or a `Group`'s heading (empty: none).
800    Title(String),
801    /// A window fills its screen, the platform's own way (a Space of its
802    /// own on macOS). The user can change it too (the title bar's button,
803    /// the window manager's key): the backend reports `FullScreenChanged`,
804    /// which the core absorbs.
805    FullScreen(bool),
806    /// The smallest content size the user can make a window, in points.
807    /// A window smaller when it's set grows to it.
808    MinSize(Size),
809    /// The content sets a window's height, not the user, who resizes only
810    /// its width; where the platform can't hold one side (GTK), neither.
811    /// The core sets it for a `WindowSize::FollowHeight` window.
812    HeightFollowsContent(bool),
813    /// A window fills its screen's working area as the platform's maximize
814    /// (on macOS, zoom) does, and is back to its own size without. The user
815    /// can change it too: the backend reports `MaximizedChanged`, which the
816    /// core absorbs. Sent only if the app chose.
817    Maximized(bool),
818    /// The user can resize a window. Without, only the app sets its size;
819    /// sent only if the app chose.
820    Resizable(bool),
821    /// Text content of a `Text`.
822    Text(String),
823    /// How many lines a `Text` shows at most, the last one cut off with an
824    /// ellipsis, as the platform draws one. `None`: all of them.
825    MaxLines(Option<u32>),
826    /// Where a `Text` cut off at its line limit puts its ellipsis. AppKit,
827    /// Qt and WinUI cut off a single line's start or middle only. Sent
828    /// only if the app chose.
829    Truncation(Truncation),
830    /// A `Text`'s or `Icon`'s colour. Semantic colours follow the
831    /// appearance (dark mode, high contrast, the accent colour); `Rgba` is
832    /// fixed. Icons in full colour keep their own; symbolic ones take it.
833    /// Sent only if the app chose.
834    TextColor(Color),
835    /// A `Text`'s weight, in place of its text style's.
836    FontWeight(FontWeight),
837    /// A `Text` in italics.
838    Italic(bool),
839    /// Where a `Text`'s lines go across its frame. The core resolves the
840    /// app's `TextAlign` against the text's direction, so it's left or
841    /// right here.
842    TextAlign(HorizontalAlign),
843    /// Which way a widget lays itself out and draws: a checkbox's box on
844    /// the right of its caption, a slider's minimum on the right, a text
845    /// field's text starting on the right. The core resolves it for every
846    /// native node, and sends it to those that are right to left, and to
847    /// every node of an app whose language is (never to an app that is
848    /// only left to right). Frames are already mirrored: containers don't
849    /// mirror what they hold.
850    LayoutDirection(LayoutDirection),
851    /// A `Text`'s text can be selected and copied by the user. Sent when
852    /// the text is created, and never changed: Qt's selectable label is
853    /// another item.
854    Selectable(bool),
855    /// Caption of a `Button`, `ToggleButton`, `MenuButton`, `Checkbox` or
856    /// `Switch`; accessible name of a `Switch`, `Select`, `RadioGroup`,
857    /// `Slider`, `NumberInput`, `Progress`, `Image`, `Icon` or `GpuSurface`,
858    /// and of a button that shows only its icon.
859    Label(String),
860    /// Current text of a `TextInput`, `PasswordInput`, `SearchInput` or
861    /// `TextArea`; a text area's lines end in `\n`.
862    Value(String),
863    /// What a text field shows while it's empty. Text areas show it where
864    /// the platform's have one (Qt, WinUI).
865    Placeholder(String),
866    /// A `TextInput` or `TextArea` shows its text, which can be selected
867    /// and copied, but not edited: by typing, or by assistive technology.
868    ReadOnly(bool),
869    /// How many lines of text a `TextArea` is tall at its natural size, in
870    /// the platform's font and line spacing; it scrolls past them. The
871    /// layout can still make it taller or shorter.
872    Lines(u32),
873    /// A `TextArea`'s lines wrap to its width. Without, a line is as long
874    /// as its text, and the area scrolls sideways. Sent only if the app
875    /// chose.
876    LineWrap(bool),
877    /// What a `TextInput` is for; sent only if the app chose.
878    InputPurpose(InputPurpose),
879    /// Checked state of a `Checkbox`, `Switch` or `ToggleButton`.
880    Checked(bool),
881    /// A `Checkbox` shows the mixed state (some of what it stands for is
882    /// checked), whatever `Checked` says. A click leaves it: where it lands
883    /// is the platform's call, and the core absorbs it as `Mixed(false)`.
884    Mixed(bool),
885    Enabled(bool),
886    TextStyle(TextStyle),
887    ButtonRole(ButtonRole),
888    ButtonStyle(ButtonStyle),
889    /// A `Select`'s or `RadioGroup`'s options, in order.
890    Options(Vec<String>),
891    /// Which option of a `Select` is chosen: always one, unless it has no
892    /// options. Which option of a `RadioGroup` is: `None` for none. Which item of a `Sidebar` is, counting across its sections:
893    /// `None` for none. Which page of a `Tabs` is shown, and which tab of
894    /// `DocumentTabs` is chosen: always one, unless it has none.
895    SelectedIndex(Option<usize>),
896    /// A `Slider`'s or `NumberInput`'s value, within its range. The core
897    /// sends it after the range, which may have clamped it.
898    Number(f64),
899    /// The values a `Slider` or `NumberInput` can take.
900    Range {
901        min: f64,
902        max: f64,
903    },
904    /// A `Slider`'s step, used as the platform uses one: to snap to, where
905    /// its sliders snap, and to move by from the keyboard. What a
906    /// `NumberInput`'s buttons and arrow keys add or take away. `None`: the
907    /// platform's default.
908    Step(Option<f64>),
909    /// A `NumberInput` stepped past one end of its range goes on from the
910    /// other. Sent only if the app chose: without, it's the platform's
911    /// (AppKit's stepper wraps, the others stop).
912    WrapAround(bool),
913    /// Which way a `Slider` or a `Separator` runs.
914    Orientation(Orientation),
915    /// Text the platform shows when the pointer rests on the widget, as
916    /// its tooltip, and assistive technology reads as its description.
917    /// Any widget or container can have one; empty: none.
918    Tooltip(String),
919    /// The menu the platform shows its own way on a right-click, a long
920    /// press or the menu key: items, separators and submenus. Any widget
921    /// or container can have one; empty: none. The node reports the item
922    /// chosen as [`UiEvent::ContextMenuItem`](crate::UiEvent::ContextMenuItem).
923    ContextMenu(Vec<MenuEntry>),
924    /// A `MenuButton`'s menu: items, separators and submenus, built as a
925    /// context menu's. The node reports the item chosen as
926    /// [`UiEvent::MenuItem`](crate::UiEvent::MenuItem).
927    Menu(Vec<MenuEntry>),
928    /// A window is modal, belonging to `owner` (the window it was declared
929    /// in, if any). Sent once, before the window is shown.
930    Modal {
931        owner: Option<NodeId>,
932        modality: Modality,
933    },
934    /// What an `Image` shows.
935    Image(ImageSource),
936    /// How an `Image` fills its frame; sent only if the app chose.
937    ImageFit(ImageFit),
938    /// What an `Icon` shows, or the icon a `Button`, `ToggleButton` or
939    /// `MenuButton` shows before its caption: a name in the platform's own set (an SF Symbol, a themed
940    /// icon's name, a Segoe Fluent Icons glyph). Empty: none. A name the
941    /// set doesn't have shows as the platform shows one: nothing, or its
942    /// missing-icon icon.
943    Icon(String),
944    /// How big an `Icon` is, in points, used as the platform sizes icons:
945    /// an SF Symbol's point size (as a font's), the side of a square
946    /// elsewhere; a `FileIcon`'s square's side everywhere. Sent only if the
947    /// app chose.
948    IconSize(f32),
949    /// The file or folder a `FileIcon` shows the icon of. It's read when
950    /// set, as an image file is.
951    File(PathBuf),
952    /// A `FileIcon` shows a preview of what's in the file (a picture's,
953    /// a document's first page) in place of its icon, where the platform
954    /// makes one; its icon until then, and where it makes none.
955    Thumbnail(bool),
956    /// A button shows its icon without its caption, which stays its
957    /// accessible name. Without an icon it shows its caption.
958    IconOnly(bool),
959    /// Whether a `Spinner` spins. Stopped, it shows nothing but keeps its
960    /// place.
961    Running(bool),
962    /// How far along a `Progress` is, from 0 to 1. `None`: not known (an
963    /// indeterminate, animated bar).
964    Progress(Option<f64>),
965    /// Which axes a `ScrollView` scrolls.
966    ScrollAxes(ScrollAxes),
967    /// Whether a `ScrollView` shows scroll bars, as the platform shows them.
968    /// Without, it still scrolls, by wheel, trackpad and touch.
969    ScrollBars(bool),
970    /// A `Tabs`' page titles, in page order; `DocumentTabs`' titles, in
971    /// order.
972    TabTitles(Vec<String>),
973    /// A `Tabs`' tab icons, in page order: names in the platform's own set,
974    /// as `Icon`'s; empty for none. Sent only if a tab has one.
975    TabIcons(Vec<String>),
976    /// How a `Tabs` shows its tabs. Sent only if the app chose.
977    TabsStyle(TabsStyle),
978    /// `DocumentTabs`' tabs have the platform's close buttons (and its
979    /// middle click, where it has one), which report
980    /// `TabCloseRequested`; the app closes the tab. Sent only if the app
981    /// asked (`on_close`).
982    TabsClosable(bool),
983    /// The user can drag `DocumentTabs`' tabs to another place among them
984    /// (and move them from the keyboard, where the platform can), which
985    /// reports `TabMoved`; the core absorbs it. Sent only if the app asked
986    /// (`on_move`).
987    TabsReorderable(bool),
988    /// `DocumentTabs` have the platform's new-tab button, which reports
989    /// `NewTabRequested`. Sent only if the app asked (`on_new`).
990    NewTabButton(bool),
991    /// Where `DocumentTabs` show their tabs. Sent only if the app chose.
992    DocumentTabsStyle(DocumentTabsStyle),
993    /// A `Sidebar`'s items, in sections, in order.
994    Sections(Vec<SidebarSectionData>),
995    /// A `Sidebar` is shown beside the window's content, or hidden, as the
996    /// platform shows and hides one. The user can change it too: the
997    /// backend reports `SidebarShownChanged`, which the core absorbs. Sent
998    /// only if the app chose.
999    SidebarShown(bool),
1000    /// A `Container` at the top of its window's content is the window's
1001    /// header, the part that stays while what's under it scrolls: on
1002    /// AppKit it goes in the title bar, under the title and toolbar, in
1003    /// their glass (a bottom `NSTitlebarAccessoryViewController`), and the
1004    /// scroll view right under it runs up under the bar, blurred at its
1005    /// edge, as Safari's and Mail's bars have it. The others have no such
1006    /// bar and leave it where it is, at the content's top; so does AppKit
1007    /// for one that isn't there, or beside a sidebar. Sent only if the app
1008    /// chose.
1009    Header(bool),
1010    /// How a header meets what scrolls under it. Sent only if the app
1011    /// chose.
1012    HeaderEdge(HeaderEdge),
1013    /// A `List`'s rows, in order.
1014    Rows(Vec<RowKey>),
1015    /// How high a `List`'s rows are likely to be, for platforms that must
1016    /// size rows before they're shown.
1017    EstimatedRowHeight(f32),
1018    /// Which row of its `List` a row host shows.
1019    Row(RowKey),
1020    /// A `Table`'s columns, in order.
1021    Columns(Vec<ColumnData>),
1022    /// The column a `Table` is sorted by, which its header shows. The user
1023    /// pressing a sortable column's header sorts it as the platform does:
1024    /// the backend reports `Changed(Sort)`, which the core absorbs.
1025    Sort(Option<ColumnSort>),
1026    /// Which cell of its `Table` a cell host shows.
1027    Cell(CellKey),
1028    SelectionMode(SelectionMode),
1029    ListStyle(ListStyle),
1030    /// The selected rows of a `List`.
1031    Selected(Vec<RowKey>),
1032    /// A custom widget's props, with its renders.
1033    Custom(CustomProps),
1034    /// What a drawn custom widget shows. Computed by the core after layout,
1035    /// so it arrives with the frames.
1036    Drawing(DisplayList),
1037    /// A `Native` node's factory (on create), then its updates: payloads in
1038    /// the backend's own form.
1039    Native(Opaque),
1040    /// A `GpuSurface` takes keys and the pointer, and reports them as
1041    /// `SurfaceInput`: it takes focus from a click and from Tab.
1042    TakesInput(bool),
1043    /// A `GpuSurface` holds the pointer: the cursor is hidden and stays
1044    /// put, and its moves are reported as `SurfaceInput::Motion`. Only
1045    /// while its window is the active one; the backend reports
1046    /// `PointerLockEnded` when that stops, or it can't lock.
1047    PointerLock(bool),
1048    /// A `GpuSurface` takes every key while it has focus, the system's
1049    /// shortcuts and the app's own too, as far as the platform lets an
1050    /// app. Setting it focuses the surface; the backend reports
1051    /// `KeyboardGrabEnded` when the surface or its window loses focus, or
1052    /// it can't grab.
1053    KeyboardGrab(bool),
1054    /// The pointer's cursor over a `GpuSurface`.
1055    Cursor(Cursor),
1056    /// A `GpuSurface` that takes input takes text too, as a text field
1057    /// does: its keys report what they type, and the platform's input
1058    /// methods are on while it has focus, committing as
1059    /// `SurfaceInput::Text`.
1060    TextInput(bool),
1061    /// Whether the platform's input methods are on while a `GpuSurface`
1062    /// takes text (they are unless this says otherwise). Off, its keys
1063    /// still report what they type, dead keys and AltGr composed in, but
1064    /// nothing composes: for a modal editor whose keys are commands
1065    /// outside its insert mode, as a terminal's are.
1066    InputMethod(bool),
1067    /// Where the caret is on a `GpuSurface` that takes text, in points from
1068    /// its top left: the input method's candidate window opens by it.
1069    TextCursor(Option<Rect>),
1070    /// A `Container` or `Group` takes the files and folders this says
1071    /// when they're dragged from the platform's file manager and dropped
1072    /// on it; `None`: none. While acceptable files are over it, the
1073    /// platform shows it'll copy them, and the node reports
1074    /// `DropHover(true)`, then `DropHover(false)`; a drop reports the ones
1075    /// it takes as `FilesDropped`.
1076    FileDrop(Option<FileDrop>),
1077    /// A `Container` or `Group` reports the pointer coming over it, or
1078    /// over anything inside it, and leaving, as
1079    /// [`UiEvent::Hover`](crate::UiEvent::Hover). Sent only if the app
1080    /// asked (`on_hover`).
1081    Hover(bool),
1082    /// A `Container` or `Group` reports a double click on it, or on
1083    /// anything inside it that isn't a control (a label, an icon), as
1084    /// [`UiEvent::DoubleClick`](crate::UiEvent::DoubleClick). Sent only if
1085    /// the app asked (`on_double_click`).
1086    DoubleClick(bool),
1087    /// A `List`'s or `Table`'s rows' files: dragging a row carries its
1088    /// file out of the app (to the file manager, another app, a folder),
1089    /// and dragging a selected row carries every selected row's, as the
1090    /// platform drags a selection. The drag offers to copy. Rows without a
1091    /// file don't drag. Sent before the rows, and only if the app gave
1092    /// them.
1093    RowFiles(Vec<(RowKey, PathBuf)>),
1094    /// The keys a `Container`, `Group`, `List` or `Table` takes while it,
1095    /// or a control inside it, has keyboard focus, and the focused control
1096    /// doesn't use them itself: they go up from the focused control, as the
1097    /// platform sends keys it doesn't use, to the nearest node that takes
1098    /// them, which reports [`UiEvent::Key`](crate::UiEvent::Key). Sent only
1099    /// if the app gave some.
1100    Keys(Vec<Shortcut>),
1101    /// Raw platform settings for a built-in widget (see
1102    /// [`Tweak`](crate::Tweak)), in the backend's own form. Applied after
1103    /// the widget's other props, and again whenever they change.
1104    Tweak(Opaque),
1105}
1106
1107impl Prop {
1108    /// Two props with the same key replace each other.
1109    pub fn key(&self) -> std::mem::Discriminant<Prop> {
1110        std::mem::discriminant(self)
1111    }
1112
1113    /// Whether changing this prop can change the intrinsic size of a widget
1114    /// of this kind.
1115    pub fn affects_measure(&self, kind: WidgetKind) -> bool {
1116        // A spin box can be as wide as its range's longest number (GTK) or
1117        // its text (Qt).
1118        if kind == WidgetKind::NumberInput && matches!(self, Prop::Range { .. } | Prop::Number(_)) {
1119            return true;
1120        }
1121        // A pull-down can be as wide as its widest item (AppKit).
1122        if kind == WidgetKind::MenuButton && matches!(self, Prop::Menu(_)) {
1123            return true;
1124        }
1125        if kind == WidgetKind::TextArea && matches!(self, Prop::Lines(_)) {
1126            return true;
1127        }
1128        // A strip is as wide as its tabs and its new-tab button, and is the
1129        // window's or the content's.
1130        if kind == WidgetKind::DocumentTabs
1131            && matches!(
1132                self,
1133                Prop::TabTitles(_) | Prop::TabsClosable(_) | Prop::NewTabButton(_) | Prop::DocumentTabsStyle(_)
1134            )
1135        {
1136            return true;
1137        }
1138        matches!(
1139            self,
1140            Prop::Text(_)
1141                | Prop::MaxLines(_)
1142                | Prop::Truncation(_)
1143                | Prop::FontWeight(_)
1144                | Prop::Italic(_)
1145                | Prop::Label(_)
1146                | Prop::Placeholder(_)
1147                | Prop::Options(_)
1148                | Prop::SelectedIndex(_)
1149                | Prop::TextStyle(_)
1150                | Prop::ButtonRole(_)
1151                | Prop::ButtonStyle(_)
1152                | Prop::Orientation(_)
1153                | Prop::Image(_)
1154                | Prop::Icon(_)
1155                | Prop::IconSize(_)
1156                | Prop::IconOnly(_)
1157                | Prop::Custom(_)
1158                | Prop::Native(_)
1159                | Prop::Tweak(_)
1160        )
1161    }
1162}
1163
1164/// Where the item at `index` of a list is after the one at `from` moved to
1165/// `to`: `DocumentTabs`' chosen tab after `TabMoved`.
1166pub fn moved_index(index: usize, from: usize, to: usize) -> usize {
1167    if index == from {
1168        to
1169    } else if from < index && index <= to {
1170        index - 1
1171    } else if to <= index && index < from {
1172        index + 1
1173    } else {
1174        index
1175    }
1176}
1177
1178/// Finds a prop by pattern in a prop list.
1179#[macro_export]
1180macro_rules! find_prop {
1181    ($props:expr, $variant:ident) => {
1182        $props.iter().find_map(|p| match p {
1183            $crate::Prop::$variant(v) => Some(v.clone()),
1184            _ => None,
1185        })
1186    };
1187}
1188
1189macro_rules! static_value {
1190    ($($t:ty),*) => {$(
1191        impl mitsuami_reactive::IntoValue<$t> for $t {
1192            fn into_value(self) -> mitsuami_reactive::Value<$t> {
1193                mitsuami_reactive::Value::Static(self)
1194            }
1195        }
1196    )*};
1197}
1198
1199static_value!(
1200    FileDrop,
1201    TextStyle,
1202    FontWeight,
1203    TextAlign,
1204    Truncation,
1205    crate::draw::Color,
1206    ButtonRole,
1207    ButtonStyle,
1208    TabsStyle,
1209    HeaderEdge,
1210    DocumentTabsStyle,
1211    Orientation,
1212    ScrollAxes,
1213    SelectionMode,
1214    SortOrder,
1215    ListStyle,
1216    InputPurpose,
1217    ImageSource,
1218    Pixels,
1219    ImageFit,
1220    Modality,
1221    Cursor,
1222    Size
1223);