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 /// Text content of a `Text`.
1109 Text(String),
1110 /// How many lines a `Text` shows at most, the last one cut off with an
1111 /// ellipsis, as the platform draws one. `None`: all of them.
1112 MaxLines(Option<u32>),
1113 /// Where a `Text` cut off at its line limit puts its ellipsis. AppKit,
1114 /// Qt and WinUI cut off a single line's start or middle only. Sent
1115 /// only if the app chose.
1116 Truncation(Truncation),
1117 /// A `Text`'s or `Icon`'s colour, or the icon's on a `Button` or
1118 /// `ToggleButton` (its caption keeps the platform's). Semantic colours
1119 /// follow the appearance (dark mode, high contrast, the accent colour);
1120 /// `Rgba` is fixed. Icons in full colour keep their own; symbolic ones
1121 /// take it. Sent only if the app chose.
1122 TextColor(Color),
1123 /// A `Text`'s weight, in place of its text style's.
1124 FontWeight(FontWeight),
1125 /// A `Text` in italics.
1126 Italic(bool),
1127 /// Where a `Text`'s lines go across its frame. The core resolves the
1128 /// app's `TextAlign` against the text's direction, so it's left or
1129 /// right here.
1130 TextAlign(HorizontalAlign),
1131 /// Which way a widget lays itself out and draws: a checkbox's box on
1132 /// the right of its caption, a slider's minimum on the right, a text
1133 /// field's text starting on the right. The core resolves it for every
1134 /// native node, and sends it to those that are right to left, and to
1135 /// every node of an app whose language is (never to an app that is
1136 /// only left to right). Frames are already mirrored: containers don't
1137 /// mirror what they hold.
1138 LayoutDirection(LayoutDirection),
1139 /// A `Text`'s text can be selected and copied by the user. Sent when
1140 /// the text is created, and never changed: Qt's selectable label is
1141 /// another item.
1142 Selectable(bool),
1143 /// Caption of a `Button`, `ToggleButton`, `MenuButton`, `SplitButton`,
1144 /// `Checkbox` or `Switch`; accessible name of a `Switch`, `Select`, `RadioGroup`,
1145 /// `Slider`, `NumberInput`, `Progress`, `Image`, `Icon` or `GpuSurface`,
1146 /// and of a button that shows only its icon.
1147 Label(String),
1148 /// Current text of a `TextInput`, `PasswordInput`, `SearchInput` or
1149 /// `TextArea`; a text area's lines end in `\n`.
1150 Value(String),
1151 /// What a text field shows while it's empty. Text areas show it where
1152 /// the platform's have one (Qt, WinUI).
1153 Placeholder(String),
1154 /// What's wrong with a `TextInput`'s, `PasswordInput`'s or
1155 /// `TextArea`'s text, or `None`: the platform marks the field where it
1156 /// has a way to (GTK's `error` style), and assistive technology reads
1157 /// it as invalid, with the message as its description. The app shows
1158 /// the message, as apps on every platform place their own.
1159 Error(Option<String>),
1160 /// A `TextInput` or `TextArea` shows its text, which can be selected
1161 /// and copied, but not edited: by typing, or by assistive technology.
1162 ReadOnly(bool),
1163 /// How many lines of text a `TextArea` is tall at its natural size, in
1164 /// the platform's font and line spacing; it scrolls past them. The
1165 /// layout can still make it taller or shorter.
1166 Lines(u32),
1167 /// A `TextArea`'s lines wrap to its width. Without, a line is as long
1168 /// as its text, and the area scrolls sideways. Sent only if the app
1169 /// chose.
1170 LineWrap(bool),
1171 /// A `TextArea` keeps its end in view as the app sets its text, while
1172 /// it's there (or the area was empty): a log that follows its output,
1173 /// as Terminal and Console do. Scrolled up, it stays put. Turned on, it
1174 /// shows its end. Sent only if the app chose.
1175 FollowsEnd(bool),
1176 /// What a `TextInput` is for; sent only if the app chose.
1177 InputPurpose(InputPurpose),
1178 /// Checked state of a `Checkbox`, `Switch` or `ToggleButton`.
1179 Checked(bool),
1180 /// A `Checkbox` shows the mixed state (some of what it stands for is
1181 /// checked), whatever `Checked` says. A click leaves it: where it lands
1182 /// is the platform's call, and the core absorbs it as `Mixed(false)`.
1183 Mixed(bool),
1184 Enabled(bool),
1185 TextStyle(TextStyle),
1186 ButtonRole(ButtonRole),
1187 ButtonStyle(ButtonStyle),
1188 /// A `Select`'s or `RadioGroup`'s options, in order.
1189 Options(Vec<String>),
1190 /// Which option of a `Select` is chosen: always one, unless it has no
1191 /// options. Which option of a `RadioGroup` is: `None` for none. Which item of a `Sidebar` is, counting across its sections:
1192 /// `None` for none. Which page of a `Tabs` is shown, and which tab of
1193 /// `DocumentTabs` is chosen: always one, unless it has none.
1194 SelectedIndex(Option<usize>),
1195 /// A `Slider`'s or `NumberInput`'s value, within its range. The core
1196 /// sends it after the range, which may have clamped it. A `Split`'s
1197 /// first pane's size along it, in points, which the core keeps within
1198 /// the panes' least sizes.
1199 Number(f64),
1200 /// A `ColorWell`'s colour: an opaque [`Color::Rgba`] (semantic
1201 /// colours and alpha aren't a colour well's).
1202 ColorValue(Color),
1203 /// The values a `Slider` or `NumberInput` can take.
1204 Range {
1205 min: f64,
1206 max: f64,
1207 },
1208 /// A `Slider`'s step, used as the platform uses one: to snap to, where
1209 /// its sliders snap, and to move by from the keyboard. What a
1210 /// `NumberInput`'s buttons and arrow keys add or take away. `None`: the
1211 /// platform's default.
1212 Step(Option<f64>),
1213 /// A `NumberInput` stepped past one end of its range goes on from the
1214 /// other. Sent only if the app chose: without, it's the platform's
1215 /// (AppKit's stepper wraps, the others stop).
1216 WrapAround(bool),
1217 /// Which way a `Slider` or a `Separator` runs; a `Split`'s panes are
1218 /// side by side when it's horizontal.
1219 Orientation(Orientation),
1220 /// A `Split`'s panes' least sizes along it, first then second, from
1221 /// their styles' least width (or height): the platform stops the
1222 /// divider there. Computed by the core.
1223 PaneMinimums([f32; 2]),
1224 /// Which of a `Split`'s panes show, first then second: the divider
1225 /// shows only between two. Computed by the core from the panes'
1226 /// visibility.
1227 PanesShown([bool; 2]),
1228 /// Text the platform shows when the pointer rests on the widget, as
1229 /// its tooltip, and assistive technology reads as its description.
1230 /// Any widget or container can have one; empty: none.
1231 Tooltip(String),
1232 /// The menu the platform shows its own way on a right-click, a long
1233 /// press or the menu key: items, separators and submenus. Any widget
1234 /// or container can have one; empty: none. The node reports the item
1235 /// chosen as [`UiEvent::ContextMenuItem`](crate::UiEvent::ContextMenuItem).
1236 ContextMenu(Vec<MenuEntry>),
1237 /// The node's context menu is built as the platform opens it: the
1238 /// platform calls it, from its own moment before a menu shows, and
1239 /// shows what it returns, which is also the node's `ContextMenu`
1240 /// from then on. `None`: the menu is `ContextMenu` alone.
1241 ContextMenuOnOpen(Option<crate::services::MenuOnOpen>),
1242 /// A `MenuButton`'s or `SplitButton`'s menu: items, separators and
1243 /// submenus, built as a context menu's. The node reports the item chosen as
1244 /// [`UiEvent::MenuItem`](crate::UiEvent::MenuItem).
1245 Menu(Vec<MenuEntry>),
1246 /// A `MenuButton`'s menu is built as the platform opens it, as
1247 /// [`ContextMenuOnOpen`](Prop::ContextMenuOnOpen) builds a context
1248 /// menu: what it returns is shown, and is the node's `Menu` from then
1249 /// on. `None`: the menu is `Menu` alone.
1250 MenuOnOpen(Option<crate::services::MenuOnOpen>),
1251 /// A window is modal, belonging to `owner` (the window it was declared
1252 /// in, if any). Sent once, before the window is shown.
1253 Modal {
1254 owner: Option<NodeId>,
1255 modality: Modality,
1256 },
1257 /// What an `Image` shows.
1258 Image(ImageSource),
1259 /// How an `Image` fills its frame; sent only if the app chose.
1260 ImageFit(ImageFit),
1261 /// What an `Icon` shows, or the icon a `Button`, `ToggleButton`,
1262 /// `MenuButton` or `SplitButton` shows before its caption: a name in
1263 /// the platform's own set (an SF Symbol, a themed
1264 /// icon's name, a Segoe Fluent Icons glyph). Empty: none. A name the
1265 /// set doesn't have shows as the platform shows one: nothing, or its
1266 /// missing-icon icon.
1267 Icon(String),
1268 /// The app's own icon, in place of a named one ([`Prop::Icon`]), for
1269 /// the same widgets: drawn as the platform draws its symbolic icons.
1270 /// `None`: the named one, if any.
1271 VectorIcon(Option<crate::VectorIcon>),
1272 /// How big an `Icon` is, in points, used as the platform sizes icons:
1273 /// an SF Symbol's point size (as a font's), the side of a square
1274 /// elsewhere; a `FileIcon`'s square's side everywhere. Sent only if the
1275 /// app chose.
1276 IconSize(f32),
1277 /// The file or folder a `FileIcon` shows the icon of. It's read when
1278 /// set, as an image file is.
1279 File(PathBuf),
1280 /// A `FileIcon` shows a preview of what's in the file (a picture's,
1281 /// a document's first page) in place of its icon, where the platform
1282 /// makes one; its icon until then, and where it makes none.
1283 Thumbnail(bool),
1284 /// Where a `FileIcon` gets its icon: the file on disk, or only its
1285 /// name. By name, `Thumbnail` is ignored.
1286 FileLookup(FileLookup),
1287 /// A button shows its icon without its caption, which stays its
1288 /// accessible name. Without an icon it shows its caption.
1289 IconOnly(bool),
1290 /// Whether a `Spinner` spins. Stopped, it shows nothing but keeps its
1291 /// place.
1292 Running(bool),
1293 /// How far along a `Progress` is, from 0 to 1. `None`: not known (an
1294 /// indeterminate, animated bar).
1295 Progress(Option<f64>),
1296 /// Which axes a `ScrollView` scrolls.
1297 ScrollAxes(ScrollAxes),
1298 /// Whether a `ScrollView` shows scroll bars, as the platform shows them.
1299 /// Without, it still scrolls, by wheel, trackpad and touch.
1300 ScrollBars(bool),
1301 /// A `Tabs`' page titles, in page order; `DocumentTabs`' titles, in
1302 /// order.
1303 TabTitles(Vec<String>),
1304 /// A `Tabs`' tab icons, in page order: names in the platform's own set,
1305 /// as `Icon`'s; empty for none. Sent only if a tab has one.
1306 TabIcons(Vec<String>),
1307 /// How a `Tabs` shows its tabs. Sent only if the app chose.
1308 TabsStyle(TabsStyle),
1309 /// `DocumentTabs`' tabs have the platform's close buttons (and its
1310 /// middle click, where it has one), which report
1311 /// `TabCloseRequested`; the app closes the tab. Sent only if the app
1312 /// asked (`on_close`).
1313 TabsClosable(bool),
1314 /// The user can drag `DocumentTabs`' tabs to another place among them
1315 /// (and move them from the keyboard, where the platform can), which
1316 /// reports `TabMoved`; the core absorbs it. Sent only if the app asked
1317 /// (`on_move`).
1318 TabsReorderable(bool),
1319 /// `DocumentTabs` have the platform's new-tab button, which reports
1320 /// `NewTabRequested`. Sent only if the app asked (`on_new`).
1321 NewTabButton(bool),
1322 /// Where `DocumentTabs` show their tabs. Sent only if the app chose.
1323 DocumentTabsStyle(DocumentTabsStyle),
1324 /// A `Sidebar`'s items, in sections, in order.
1325 Sections(Vec<SidebarSectionData>),
1326 /// A `Sidebar` is shown beside the window's content, or hidden, as the
1327 /// platform shows and hides one. The user can change it too: the
1328 /// backend reports `SidebarShownChanged`, which the core absorbs. Sent
1329 /// only if the app chose.
1330 SidebarShown(bool),
1331 /// A `Popover` is shown by its parent, or not. The user dismisses one
1332 /// too (a click outside, Escape): the backend reports
1333 /// `PopoverShownChanged(false)`, which the core absorbs.
1334 PopoverShown(bool),
1335 /// What a `SearchInput` suggests for its text, in a list under it while
1336 /// the user types, as each platform shows a field's suggestions (an
1337 /// `AutoSuggestBox`'s list, a list in a window that doesn't take the
1338 /// keyboard on AppKit, a popover that doesn't on GTK, a popup that
1339 /// doesn't on Qt). The field keeps the keyboard: the arrows move
1340 /// through the list, Return picks, Escape hides it. Empty: none.
1341 Suggestions(Vec<Suggestion>),
1342 /// A `SearchInput` searches on Return (and when cleared), not as the
1343 /// user types: each platform's setting for searches that take a while
1344 /// (AppKit's `sendsWholeSearchString`, GTK's `activate` alone, WinUI's
1345 /// `QuerySubmitted` alone, Kirigami's `autoAccept` off). Sent only if
1346 /// the app chose.
1347 SearchOnReturn(bool),
1348 /// A `Container` at the top of its window's content is the window's
1349 /// header, the part that stays while what's under it scrolls: on
1350 /// AppKit it goes in the title bar, under the title and toolbar, in
1351 /// their glass (a bottom `NSTitlebarAccessoryViewController`), and the
1352 /// scroll view right under it runs up under the bar, blurred at its
1353 /// edge, as Safari's and Mail's bars have it. The others have no such
1354 /// bar and leave it where it is, at the content's top; so does AppKit
1355 /// for one that isn't there, or beside a sidebar. Sent only if the app
1356 /// chose.
1357 Header(bool),
1358 /// How a header meets what scrolls under it. Sent only if the app
1359 /// chose.
1360 HeaderEdge(HeaderEdge),
1361 /// A container that's a pane down its window's side that navigates
1362 /// (the rail that picks a Git client's pages, a mail app's folders) when the app builds
1363 /// one itself rather than with `Sidebar`. On WinUI, under tabs in the
1364 /// title bar, it's Mica Alt's commanding layer, as a header is; the
1365 /// others leave it as it is. Sent only if the app chose.
1366 SidebarPane(bool),
1367 /// A container the pointer passes through, with everything in it, to
1368 /// what's under it: a hint laid over a control. Sent only if the app
1369 /// chose.
1370 ClickThrough(bool),
1371 /// A `List`'s rows, in order.
1372 Rows(Vec<RowKey>),
1373 /// A `Tree`'s rows that show, in order: a row, then its open
1374 /// children's rows. Children of closed rows aren't sent.
1375 TreeRows(Vec<TreeRow>),
1376 /// A `Tree`'s rows whose children are being read (a folder on a
1377 /// network share opening), of the rows that show: the platform shows
1378 /// its spinner where the row's disclosure is. Sent only if the app
1379 /// said which rows load.
1380 TreeLoading(Vec<RowKey>),
1381 /// How high a `List`'s rows are likely to be, for platforms that must
1382 /// size rows before they're shown.
1383 EstimatedRowHeight(f32),
1384 /// Which row of its `List` a row host shows.
1385 Row(RowKey),
1386 /// A `Table`'s columns, in order.
1387 Columns(Vec<ColumnData>),
1388 /// The column a `Table` is sorted by, which its header shows. The user
1389 /// pressing a sortable column's header sorts it as the platform does:
1390 /// the backend reports `Changed(Sort)`, which the core absorbs.
1391 Sort(Option<ColumnSort>),
1392 /// Which cell of its `Table` a cell host shows.
1393 Cell(CellKey),
1394 SelectionMode(SelectionMode),
1395 ListStyle(ListStyle),
1396 /// The selected rows of a `List`.
1397 Selected(Vec<RowKey>),
1398 /// A custom widget's props, with its renders.
1399 Custom(CustomProps),
1400 /// What a drawn custom widget shows. Computed by the core after layout,
1401 /// so it arrives with the frames.
1402 Drawing(DisplayList),
1403 /// A `Native` node's factory (on create), then its updates: payloads in
1404 /// the backend's own form.
1405 Native(Opaque),
1406 /// A `GpuSurface` takes keys and the pointer, and reports them as
1407 /// `SurfaceInput`: it takes focus from a click and from Tab.
1408 TakesInput(bool),
1409 /// A `GpuSurface` holds the pointer: the cursor is hidden and stays
1410 /// put, and its moves are reported as `SurfaceInput::Motion`. Only
1411 /// while its window is the active one; the backend reports
1412 /// `PointerLockEnded` when that stops, or it can't lock.
1413 PointerLock(bool),
1414 /// A `GpuSurface` takes every key while it has focus, the system's
1415 /// shortcuts and the app's own too, as far as the platform lets an
1416 /// app. Setting it focuses the surface; the backend reports
1417 /// `KeyboardGrabEnded` when the surface or its window loses focus, or
1418 /// it can't grab.
1419 KeyboardGrab(bool),
1420 /// The pointer's cursor over a `GpuSurface`.
1421 Cursor(Cursor),
1422 /// A `GpuSurface` that takes input takes text too, as a text field
1423 /// does: its keys report what they type, and the platform's input
1424 /// methods are on while it has focus, committing as
1425 /// `SurfaceInput::Text`.
1426 TextInput(bool),
1427 /// Whether the platform's input methods are on while a `GpuSurface`
1428 /// takes text (they are unless this says otherwise). Off, its keys
1429 /// still report what they type, dead keys and AltGr composed in, but
1430 /// nothing composes: for a modal editor whose keys are commands
1431 /// outside its insert mode, as a terminal's are.
1432 InputMethod(bool),
1433 /// Where the caret is on a `GpuSurface` that takes text, in points from
1434 /// its top left: the input method's candidate window opens by it.
1435 TextCursor(Option<Rect>),
1436 /// A `GpuSurface` lets the window's backdrop show where what the app
1437 /// presents isn't opaque: the material the platform puts behind a
1438 /// translucent window (AppKit's behind-window vibrancy, WinUI's Mica,
1439 /// which its windows always have), or the window's own background where
1440 /// there's none. The app still presents with alpha.
1441 Transparent(bool),
1442 /// A `Container` or `Group` takes the files and folders this says
1443 /// when they're dragged from the platform's file manager and dropped
1444 /// on it; `None`: none. While acceptable files are over it, the
1445 /// platform shows it'll copy them, and the node reports
1446 /// `DropHover(true)`, then `DropHover(false)`; a drop reports the ones
1447 /// it takes as `FilesDropped`.
1448 FileDrop(Option<FileDrop>),
1449 /// A `Container` or `Group` reports the pointer coming over it, or
1450 /// over anything inside it, and leaving, as
1451 /// [`UiEvent::Hover`](crate::UiEvent::Hover). Sent only if the app
1452 /// asked (`on_hover`).
1453 Hover(bool),
1454 /// A `Container` or `Group` reports a double click on it, or on
1455 /// anything inside it that isn't a control (a label, an icon), as
1456 /// [`UiEvent::DoubleClick`](crate::UiEvent::DoubleClick). Sent only if
1457 /// the app asked (`on_double_click`).
1458 DoubleClick(bool),
1459 /// A `Container` or `Group` reports a click on it, or on anything
1460 /// inside it that isn't a control, as [`UiEvent::Click`](crate::UiEvent::Click),
1461 /// as a header that opens its section. Sent only if the app asked
1462 /// (`on_click`).
1463 Click(bool),
1464 /// A `List`'s or `Table`'s rows' files: dragging a row carries its
1465 /// file out of the app (to the file manager, another app, a folder),
1466 /// and dragging a selected row carries every selected row's, as the
1467 /// platform drags a selection. The drag offers to copy. Rows without a
1468 /// file don't drag. Sent before the rows, and only if the app gave
1469 /// them.
1470 RowFiles(Vec<(RowKey, PathBuf)>),
1471 /// A `List`'s rows can be dragged within it, and dropped where it
1472 /// says (`List::on_move`); it reports `RowsMoved`. Sent only if the app
1473 /// gave it.
1474 RowMoves(RowMoves),
1475 /// The keys a `Container`, `Group`, `List` or `Table` takes while it,
1476 /// or a control inside it, has keyboard focus, and the focused control
1477 /// doesn't use them itself: they go up from the focused control, as the
1478 /// platform sends keys it doesn't use, to the nearest node that takes
1479 /// them, which reports [`UiEvent::Key`](crate::UiEvent::Key). On a
1480 /// `TextInput` or `SearchInput`, the keys it takes before its own use
1481 /// of them (the arrows, Return, Escape): a field that moves through a
1482 /// list beside it, as Xcode's Open Quickly. A search field's
1483 /// suggestions still take theirs first. Sent only if the app gave some.
1484 Keys(Vec<Shortcut>),
1485 /// Raw platform settings for a built-in widget (see
1486 /// [`Tweak`](crate::Tweak)), in the backend's own form. Applied after
1487 /// the widget's other props, and again whenever they change.
1488 Tweak(Opaque),
1489}
1490
1491impl Prop {
1492 /// Two props with the same key replace each other.
1493 pub fn key(&self) -> std::mem::Discriminant<Prop> {
1494 std::mem::discriminant(self)
1495 }
1496
1497 /// Whether changing this prop can change the intrinsic size of a widget
1498 /// of this kind.
1499 pub fn affects_measure(&self, kind: WidgetKind) -> bool {
1500 // A spin box can be as wide as its range's longest number (GTK) or
1501 // its text (Qt).
1502 if kind == WidgetKind::NumberInput && matches!(self, Prop::Range { .. } | Prop::Number(_)) {
1503 return true;
1504 }
1505 // A pull-down can be as wide as its widest item (AppKit).
1506 if kind == WidgetKind::MenuButton && matches!(self, Prop::Menu(_)) {
1507 return true;
1508 }
1509 if kind == WidgetKind::TextArea && matches!(self, Prop::Lines(_)) {
1510 return true;
1511 }
1512 // A strip is as wide as its tabs and its new-tab button, and is the
1513 // window's or the content's.
1514 if kind == WidgetKind::DocumentTabs
1515 && matches!(
1516 self,
1517 Prop::TabTitles(_) | Prop::TabsClosable(_) | Prop::NewTabButton(_) | Prop::DocumentTabsStyle(_)
1518 )
1519 {
1520 return true;
1521 }
1522 matches!(
1523 self,
1524 Prop::Text(_)
1525 | Prop::MaxLines(_)
1526 | Prop::Truncation(_)
1527 | Prop::FontWeight(_)
1528 | Prop::Italic(_)
1529 | Prop::Label(_)
1530 | Prop::Placeholder(_)
1531 | Prop::Options(_)
1532 | Prop::SelectedIndex(_)
1533 | Prop::TextStyle(_)
1534 | Prop::ButtonRole(_)
1535 | Prop::ButtonStyle(_)
1536 | Prop::Orientation(_)
1537 | Prop::Image(_)
1538 | Prop::Icon(_)
1539 | Prop::VectorIcon(_)
1540 | Prop::IconSize(_)
1541 | Prop::IconOnly(_)
1542 | Prop::Custom(_)
1543 | Prop::Native(_)
1544 | Prop::Tweak(_)
1545 )
1546 }
1547}
1548
1549/// Where the item at `index` of a list is after the one at `from` moved to
1550/// `to`: `DocumentTabs`' chosen tab after `TabMoved`.
1551pub fn moved_index(index: usize, from: usize, to: usize) -> usize {
1552 if index == from {
1553 to
1554 } else if from < index && index <= to {
1555 index - 1
1556 } else if to <= index && index < from {
1557 index + 1
1558 } else {
1559 index
1560 }
1561}
1562
1563/// Finds a prop by pattern in a prop list.
1564#[macro_export]
1565macro_rules! find_prop {
1566 ($props:expr, $variant:ident) => {
1567 $props.iter().find_map(|p| match p {
1568 $crate::Prop::$variant(v) => Some(v.clone()),
1569 _ => None,
1570 })
1571 };
1572}
1573
1574macro_rules! static_value {
1575 ($($t:ty),*) => {$(
1576 impl mitsuami_reactive::IntoValue<$t> for $t {
1577 fn into_value(self) -> mitsuami_reactive::Value<$t> {
1578 mitsuami_reactive::Value::Static(self)
1579 }
1580 }
1581 )*};
1582}
1583
1584static_value!(
1585 FileDrop,
1586 TextStyle,
1587 FontWeight,
1588 TextAlign,
1589 Truncation,
1590 FileLookup,
1591 crate::draw::Color,
1592 ButtonRole,
1593 ButtonStyle,
1594 TabsStyle,
1595 HeaderEdge,
1596 DocumentTabsStyle,
1597 Orientation,
1598 ScrollAxes,
1599 SelectionMode,
1600 SortOrder,
1601 ListStyle,
1602 InputPurpose,
1603 ImageSource,
1604 Pixels,
1605 ImageFit,
1606 Modality,
1607 Cursor,
1608 Size,
1609 crate::VectorIcon
1610);