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