Skip to main content

compose_rust/
schema.rs

1//! Closed Rust-side schema and metadata used for Kotlin code generation.
2
3#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4pub struct EnumVariantSchema {
5    pub name: &'static str,
6    pub tag: u16,
7}
8
9#[derive(Clone, Copy, Debug, Eq, PartialEq)]
10pub enum FieldType {
11    Float,
12    U32,
13    U64,
14    /// A `Paint`, either a `ColorRole` or a literal ARGB `Color`.
15    Paint,
16    /// A role enum, named so codegen can emit the matching Kotlin type.
17    Role(&'static str),
18    /// A word that is 0 or 1. Any other value is a protocol error, not a third state.
19    Bool,
20    /// An `f32` that has to be a number. NaN or an infinity is a protocol error, for a
21    /// value that would otherwise turn a whole subtree into nothing on one side only.
22    FiniteFloat,
23}
24
25/// Which half of which `u64` word of a modifier's value a field occupies.
26///
27/// Two `f32` share one `u64`: the low 32 bits hold the first value. Every modifier has the
28/// `first` and `second` words; the words after them exist only for a modifier whose
29/// schema entry gives it `extra_words`.
30#[derive(Clone, Copy, Debug, Eq, PartialEq)]
31pub enum FieldSlot {
32    FirstLow,
33    FirstHigh,
34    First,
35    SecondLow,
36    SecondHigh,
37    Second,
38    ThirdLow,
39    ThirdHigh,
40    Third,
41    FourthLow,
42    FourthHigh,
43    Fourth,
44    FifthLow,
45    FifthHigh,
46    Fifth,
47    SixthLow,
48    SixthHigh,
49    Sixth,
50    SeventhLow,
51    SeventhHigh,
52    Seventh,
53    EighthLow,
54    EighthHigh,
55    Eighth,
56    NinthLow,
57    NinthHigh,
58    Ninth,
59    TenthLow,
60    TenthHigh,
61    Tenth,
62}
63
64impl FieldSlot {
65    /// Which word, counting from zero, and whether the field is that word's high half.
66    pub const fn word(self) -> (usize, bool) {
67        match self {
68            Self::FirstLow | Self::First => (0, false),
69            Self::FirstHigh => (0, true),
70            Self::SecondLow | Self::Second => (1, false),
71            Self::SecondHigh => (1, true),
72            Self::ThirdLow | Self::Third => (2, false),
73            Self::ThirdHigh => (2, true),
74            Self::FourthLow | Self::Fourth => (3, false),
75            Self::FourthHigh => (3, true),
76            Self::FifthLow | Self::Fifth => (4, false),
77            Self::FifthHigh => (4, true),
78            Self::SixthLow | Self::Sixth => (5, false),
79            Self::SixthHigh => (5, true),
80            Self::SeventhLow | Self::Seventh => (6, false),
81            Self::SeventhHigh => (6, true),
82            Self::EighthLow | Self::Eighth => (7, false),
83            Self::EighthHigh => (7, true),
84            Self::NinthLow | Self::Ninth => (8, false),
85            Self::NinthHigh => (8, true),
86            Self::TenthLow | Self::Tenth => (9, false),
87            Self::TenthHigh => (9, true),
88        }
89    }
90}
91
92#[derive(Clone, Copy, Debug, Eq, PartialEq)]
93pub struct FieldSchema {
94    pub name: &'static str,
95    pub ty: FieldType,
96    pub slot: FieldSlot,
97}
98
99#[derive(Clone, Copy, Debug, Eq, PartialEq)]
100pub struct VariantSchema {
101    pub name: &'static str,
102    pub tag: u16,
103    /// How many eight byte words this modifier's value takes beyond the two every
104    /// `SetModifier` record carries. The record is `28 + 8 * extra_words` bytes long, fixed
105    /// per tag, so a decoder knows the length from the tag before it reads the value.
106    pub extra_words: u8,
107    pub fields: &'static [FieldSchema],
108}
109
110/// The most words any modifier's value takes, the two every record has included.
111pub const MAX_MODIFIER_WORDS: usize = 10;
112
113/// The `extra_words` the schema gives a modifier tag, or `None` for a tag it does not list.
114pub const fn modifier_extra_words(tag: u16) -> Option<u8> {
115    let mut index = 0;
116    while index < MODIFIER_SCHEMA.len() {
117        if MODIFIER_SCHEMA[index].tag == tag {
118            return Some(MODIFIER_SCHEMA[index].extra_words);
119        }
120        index += 1;
121    }
122    None
123}
124
125#[derive(Clone, Copy, Debug, Eq, PartialEq)]
126pub enum EventPayloadType {
127    None,
128    Text,
129    ProtocolError,
130    KeyDown,
131    Range,
132    /// One `f64`. Every value-carrying widget shares it, so the same concept has one
133    /// name on the wire whether the value counts days or slides between two ends.
134    Double,
135    /// Width, height, classes, and three safe-area insets.
136    WindowSize,
137    /// One `u16`: the tag of the design system the Renderer resolved the theme to.
138    DesignSystem,
139    /// A `u32` saying what was pressed (0 for the body, 1 or 2 for an action button), then
140    /// the notification's key as a string reference.
141    NotificationActivation,
142    /// One `u32`: the notification permission the Renderer last saw.
143    NotificationPermission,
144    /// One moment in a renderer-played animation: its id, what happened, the property and
145    /// slot it plays on, the iteration, the elapsed time and the frame time.
146    Animation,
147    /// One `u32`: whether the platform asks for reduced motion.
148    ReducedMotion,
149    /// One committed edit to a code editor's document: the version it produced, the range
150    /// it replaced in the document as it stood before, and the text that replaced it.
151    CodeChange,
152    /// A Host edit the Renderer would not apply: the request it answers, the version it
153    /// was written against, the version the document had reached, and the range as sent.
154    CodeEditRejected,
155    /// A pointer resting on, or leaving, a place in a code editor: the decoration under it,
156    /// where it is, and which of the two it was.
157    CodeHover,
158    /// The save shortcut, with the version of the document it was pressed on.
159    CodeSave,
160    /// The id the application gave one decoration, which was pressed or accepted.
161    Decoration,
162    /// One pointer happening inside a subscribed node: its kind, which pointer, where,
163    /// which buttons and modifiers, the wheel deltas and when. A fixed 72-byte record.
164    Pointer,
165    /// Two `f32` and an `i32`: the whole zoom factor, the system's text size, and the
166    /// application's zoom level.
167    Zoom,
168    /// Where a code editor's selection is: the document version and the two ends.
169    CodeSelection,
170    /// Which lines of a code editor are on screen, folded lines left out.
171    CodeVisibleRange,
172    /// One word, 0 or 1: whether a code editor holds the keyboard focus.
173    CodeFocus,
174    /// The line a fold starts on and whether it is now collapsed.
175    CodeFold,
176    /// One word, 0 or 1: whether an input method is composing in a code editor. The
177    /// composed text is never part of it.
178    CodeComposition,
179    /// One word, 0 or 1: whether a window is the key window.
180    WindowFocus,
181    /// Where a window's outer frame is and how large it is: `x`, `y`, `width`, `height`,
182    /// all `f32` in screen dp.
183    WindowMove,
184    /// A torn-off window being dragged: the phase, the pointer's screen position, and the
185    /// window under the pointer.
186    WindowDrag,
187    /// A dragged window passing over a subscribed node: the kind, the dragged window, and
188    /// the position inside the node.
189    WindowDragOver,
190    /// A window the platform or the user asked the application for: a request number, then
191    /// the `RestoreKey` as a string reference. The one window event that carries a string.
192    WindowRequest,
193    /// What became of one file dialog: the request number, the status, the filter in use
194    /// and the paths as one string reference.
195    FileDialogResult,
196    /// What one clipboard read found: the request number, the status word, the text's length
197    /// in bytes, and the text as one string reference.
198    ClipboardText,
199    /// The one answer to an input or output request the Host made of the Renderer: the
200    /// request number, an `IoStatus`, and the bytes it carries as one reference.
201    IoAnswer,
202    /// Files the Renderer holds handles for: the request number, the status, the filter in
203    /// use, how they were delivered, the first handle number, then the names (NUL
204    /// separated) and one kind letter per name, as two references.
205    FileHandles,
206    /// Where a scroll container is: the first visible item, the flags, then six `f64` in
207    /// physical pixels (offset, furthest offset and viewport, x before y). A fixed 72-byte
208    /// record.
209    ScrollChanged,
210    /// The size a node's size motion settled at: `width_dp` and `height_dp`, two `f32` in
211    /// dp. A fixed 24-byte record.
212    MotionFinished,
213    /// Where a code editor's caret is drawn: the line and the column it stands at, then
214    /// `x`, `y`, `width` and `height` as `f32` in the window's dp. A fixed 40-byte record.
215    CodeCaretRect,
216    /// The answer to one position query: the request number, a word that is 1 when the
217    /// position is on screen and 0 when it is not, then the rectangle as in
218    /// `CodeCaretRect`, all zero when there is none. A fixed 40-byte record.
219    CodePositionRect,
220    /// A pointer event over a code editor: the 72-byte `Pointer` record, then the line and
221    /// the column of the text under the pointer, both `u32::MAX` where it is over none. A
222    /// fixed 80-byte record.
223    CodePointer,
224    /// Every selection of a code editor, the primary first: the document version, then a
225    /// reference to 16-byte records behind the record (anchor line, anchor column, active
226    /// line, active column). A fixed 28-byte record and its selections.
227    CodeSelections,
228    /// What became of one grouped edit of a code editor: the request id, an
229    /// `EditGroupStatus` word, the version the group was written against, the version the
230    /// document is at now and the index of the edit that decided it (or, applied, how many
231    /// edits went in). A fixed 36-byte record.
232    CodeEditGroupResult,
233    /// One `u32`: whether the system appearance is light (0) or dark (1).
234    ColorScheme,
235    /// One `f32`: how many device pixels one dp of a window covers.
236    Density,
237    /// The handle a window's platform views are made against: the handle as a `u64`, the
238    /// kind of handle as a `u16`, a reserved `u16`, and the window's backing scale as an
239    /// `f32`. A fixed 32-byte record.
240    NativeViewParent,
241}
242
243#[derive(Clone, Copy, Debug, Eq, PartialEq)]
244pub struct EventSchema {
245    pub name: &'static str,
246    pub tag: u16,
247    pub payload: EventPayloadType,
248}
249
250/// Canonical schema text. Variant order is wire-significant and must only be appended to.
251pub const SCHEMA_DESCRIPTOR: &str = concat!(
252    "compose-rust/v1;",
253    "widgets=Column,Row,Box,Text,TextField,Button,Spacer,LazyColumn,ScrollColumn,Image,Icon,Checkbox,RadioButton,Switch,Slider,ProgressIndicator,Divider,Card,Surface,Dialog,Menu,Tabs,TopAppBar,LazyRow,Tooltip,Canvas,DatePicker,TimePicker,Dropdown,Navigation,NavigationItem,Sheet,Scaffold,ScaffoldSlot,LazyGrid,FileDropTarget,ScrollRow,Chip,FloatingAction,Badge,SelectionContainer,SplitPane,CodeEditor,AbsoluteBox,Window,FlowRow,Popover,NativeView;",
254    "properties=text,placeholder,enabled,multiline,on_click,on_value_change,on_submit,on_focus_lost,on_key_down,item_count,item_key,on_range_requested,type_role,font_size,font_weight,line_height,letter_spacing,color,text_align,max_lines,overflow,arrangement,spacing,space_role,alignment,variant,asset,checked,steps,determinate,circular,vertical,open,on_dismiss,selected_index,commands,value,min,max,icon,slot,columns,min_column_width,spans,on_files_entered,on_files_dropped,section,count,collapsible,button_kind,decorations,syntax_spans,tab_width,on_edit_rejected,on_hover,on_save,on_decoration_click,folds,gutter_decorations,on_selection_change,font,word_break,overflow_wrap,tab_size,absolute_size,soft_wrap,span_fonts,on_visible_range_change,on_editor_focus_change,on_fold_change,on_composition_change,on_pointer,pointer_kinds,cursor,user_select,island_zoom,window_title,window_size,window_min_size,window_resizable,window_chrome,window_title_bar,window_icon,window_position,window_restore_key,window_zoom_level,drag_from_pointer,on_window_close_requested,on_window_focus_changed,on_window_moved,on_window_drag,on_window_unavailable,on_window_closed,on_window_drag_over,tear_off_key,on_focus_gained,on_key_up,accessible_name,track_color,thumb_color,active_track_color,container_color,check_color,control_size,report_size,scrim,bare,horizontal_spacing,vertical_spacing,horizontal_alignment,vertical_alignment,max_items_in_each_row,placement,align,offset_dp,line_numbers,gutter_min_width_dp,gutter_padding_dp,text_inset_dp,code_editor_colors,on_code_metrics,on_code_scrolled,compact_navigation,on_scroll_changed,collapse_below,snap,max_height_fraction,font_feature_settings,on_motion_finished,on_edit_group_result,on_caret_rect,on_key_preview,on_code_pointer,radio_group,minimap,view_zones,word_wrap,content_scale,thumb_size,placeholder_color,caret_color,icon_asset,presentation,max_width,separator,span_font_features,content_padding_dp,fixed_gutter_columns,native_visible,on_native_view_focus;",
255    "modifiers=Empty,Padding,FillMaxWidth,FillMaxHeight,Width,Height,Size,Background,Clickable,PaddingRole,PaddingEach,Weight,Shape,ShapeRole,Border,Elevation,ObserveSize,Motion,Material,Offset,RequiredSize,BorderEach,CornerEach,Shadow,Clip,Alpha,Transform,Transform3D,MatchParentSize,WindowDrag,PressFeedback,Semantics,CornerCurve,BackgroundBrush,SizeIn,AspectRatio,MinTouchTarget,Overlay,Sticky,UnboundedWidth;",
256    "keys=Enter,Other;",
257    "events=Clicked,TextChanged,TextSubmitted,FocusLost,ProtocolError,KeyDown,RangeRequested,ValueChanged,WindowSizeChanged,DesignSystemResolved,FilesEntered,FilesDropped,NotificationActivated,NotificationPermissionChanged,CodeChanged,CodeEditRejected,CodeHovered,CodeSaveRequested,DecorationActivated,AnimationEvent,ReducedMotionChanged,Pointer,ZoomChanged,SelectionChanged,VisibleRangeChanged,EditorFocusChanged,FoldChanged,CompositionChanged,WindowCloseRequested,WindowFocusChanged,WindowMoved,WindowDrag,WindowDragOver,WindowUnavailable,WindowClosed,WindowRequested,ApplicationReopen,FocusGained,KeyUp,FileDialogResult,CodeEditGroupResult,ClipboardText,CodeMetrics,CodeScrolled,IoAnswer,FileHandles,StorageLocation,ScrollChanged,NativeViewParent,NativeViewFocus,MotionFinished,CaretRect,PositionRect,CodePointer,ColorSchemeChanged,SelectionsChanged,DensityChanged;",
258    "windowsizeclasses=Compact,Medium,Expanded;",
259    "windowheightclasses=Compact,Medium,Expanded;",
260    "commands=Create,SetProp,SetModifier,Insert,Move,Remove,SetText,AppendText,SetTheme,SetWindow,RegisterAsset,ReleaseAsset,ShowMessage,PostNotification,WithdrawNotification,RequestNotificationPermission,EditCode,StartAnimation,ControlAnimation,SetSelection,RevealRange,SetFolded,SetWindowTheme,FocusWindow,RequestFocus,ShowFileDialog,SetOverlayTokens,EditCodeGroup,SetClipboardText,ReadClipboard,SetScrollOffset,StorageCall,FileCall,ReleaseFileHandle,ScrollTo,ScrollIntoView,AttachNativeView,FocusNativeView,QueryPositionRect,InsertSnippet,SetSelections;",
261    // The fields of the overlay tokens record in wire order. A field is only appended, and
262    // appending one changes the record's length, so it is part of what the hash covers.
263    "overlaytokens=sheet_corner_radius,dialog_corner_radius,popup_corner_radius,sheet_elevation,popup_elevation,dialog_elevation,sheet_padding,dialog_padding,popup_padding,scrim,toast_elevation,toast_corner_radius,toast_container_light,toast_container_dark,toast_content_light,toast_content_dark,toast_border_width,toast_padding_horizontal,toast_padding_vertical,toast_font_size,toast_line_height;",
264    // The fields of the message record in wire order, appended to in the same way.
265    "showmessage=handler_id,text,action,duration,vertical,horizontal,offset_dp"
266);
267
268const fn hash_bytes(mut hash: u64, bytes: &[u8]) -> u64 {
269    let mut index = 0;
270    while index < bytes.len() {
271        hash ^= bytes[index] as u64;
272        hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
273        index += 1;
274    }
275    hash
276}
277
278const fn hash_enum_schema(mut hash: u64, schema: &[EnumVariantSchema]) -> u64 {
279    let mut index = 0;
280    while index < schema.len() {
281        hash = hash_bytes(hash, schema[index].name.as_bytes());
282        hash = hash_bytes(hash, &schema[index].tag.to_le_bytes());
283        index += 1;
284    }
285    hash
286}
287
288const fn schema_hash() -> u64 {
289    let mut hash = hash_bytes(0xcbf2_9ce4_8422_2325_u64, SCHEMA_DESCRIPTOR.as_bytes());
290    hash = hash_bytes(hash, crate::extensions::SCHEMA_DESCRIPTOR.as_bytes());
291    hash = hash_bytes(hash, crate::measure::SCHEMA_DESCRIPTOR.as_bytes());
292    hash = hash_enum_schema(hash, WIDGET_SCHEMA);
293    hash = hash_enum_schema(hash, PROPERTY_SCHEMA);
294    hash = hash_enum_schema(hash, KEY_SCHEMA);
295    hash = hash_enum_schema(hash, WINDOW_SIZE_CLASS_SCHEMA);
296    hash = hash_enum_schema(hash, WINDOW_HEIGHT_CLASS_SCHEMA);
297    let mut role_index = 0;
298    while role_index < ROLE_ENUM_SCHEMA.len() {
299        hash = hash_bytes(hash, ROLE_ENUM_SCHEMA[role_index].name.as_bytes());
300        hash = hash_enum_schema(hash, ROLE_ENUM_SCHEMA[role_index].variants);
301        role_index += 1;
302    }
303    let mut index = 0;
304    while index < MODIFIER_SCHEMA.len() {
305        let modifier = MODIFIER_SCHEMA[index];
306        hash = hash_bytes(hash, modifier.name.as_bytes());
307        hash = hash_bytes(hash, &modifier.tag.to_le_bytes());
308        hash = hash_bytes(hash, &[modifier.extra_words]);
309        let mut field_index = 0;
310        while field_index < modifier.fields.len() {
311            let field = modifier.fields[field_index];
312            hash = hash_bytes(hash, field.name.as_bytes());
313            hash = hash_bytes(
314                hash,
315                &[match field.ty {
316                    FieldType::Float => 1,
317                    FieldType::U32 => 2,
318                    FieldType::U64 => 3,
319                    FieldType::Paint => 4,
320                    FieldType::Role(_) => 5,
321                    FieldType::Bool => 6,
322                    FieldType::FiniteFloat => 7,
323                }],
324            );
325            if let FieldType::Role(role) = field.ty {
326                hash = hash_bytes(hash, role.as_bytes());
327            }
328            hash = hash_bytes(
329                hash,
330                &[match field.slot {
331                    FieldSlot::FirstLow => 0,
332                    FieldSlot::FirstHigh => 1,
333                    FieldSlot::First => 2,
334                    FieldSlot::SecondLow => 3,
335                    FieldSlot::SecondHigh => 4,
336                    FieldSlot::Second => 5,
337                    FieldSlot::ThirdLow => 6,
338                    FieldSlot::ThirdHigh => 7,
339                    FieldSlot::Third => 8,
340                    FieldSlot::FourthLow => 9,
341                    FieldSlot::FourthHigh => 10,
342                    FieldSlot::Fourth => 11,
343                    FieldSlot::FifthLow => 12,
344                    FieldSlot::FifthHigh => 13,
345                    FieldSlot::Fifth => 14,
346                    FieldSlot::SixthLow => 15,
347                    FieldSlot::SixthHigh => 16,
348                    FieldSlot::Sixth => 17,
349                    FieldSlot::SeventhLow => 18,
350                    FieldSlot::SeventhHigh => 19,
351                    FieldSlot::Seventh => 20,
352                    FieldSlot::EighthLow => 21,
353                    FieldSlot::EighthHigh => 22,
354                    FieldSlot::Eighth => 23,
355                    FieldSlot::NinthLow => 24,
356                    FieldSlot::NinthHigh => 25,
357                    FieldSlot::Ninth => 26,
358                    FieldSlot::TenthLow => 27,
359                    FieldSlot::TenthHigh => 28,
360                    FieldSlot::Tenth => 29,
361                }],
362            );
363            field_index += 1;
364        }
365        index += 1;
366    }
367    index = 0;
368    while index < crate::drawing::DRAW_COMMAND_SCHEMA.len() {
369        let command = crate::drawing::DRAW_COMMAND_SCHEMA[index];
370        hash = hash_bytes(hash, command.name.as_bytes());
371        hash = hash_bytes(hash, &command.tag.to_le_bytes());
372        let mut field_index = 0;
373        while field_index < command.fields.len() {
374            let field = command.fields[field_index];
375            hash = hash_bytes(hash, field.name.as_bytes());
376            hash = hash_bytes(hash, &[field.word]);
377            hash = hash_bytes(
378                hash,
379                &[match field.ty {
380                    crate::drawing::DrawFieldType::Float => 1,
381                    crate::drawing::DrawFieldType::U32 => 2,
382                    crate::drawing::DrawFieldType::Role(_) => 3,
383                }],
384            );
385            if let crate::drawing::DrawFieldType::Role(role) = field.ty {
386                hash = hash_bytes(hash, role.as_bytes());
387            }
388            field_index += 1;
389        }
390        index += 1;
391    }
392    index = 0;
393    while index < EVENT_SCHEMA.len() {
394        let event = EVENT_SCHEMA[index];
395        hash = hash_bytes(hash, event.name.as_bytes());
396        hash = hash_bytes(hash, &event.tag.to_le_bytes());
397        hash = hash_bytes(
398            hash,
399            &[match event.payload {
400                EventPayloadType::None => 0,
401                EventPayloadType::Text => 1,
402                EventPayloadType::ProtocolError => 2,
403                EventPayloadType::KeyDown => 3,
404                EventPayloadType::Range => 4,
405                EventPayloadType::Double => 5,
406                EventPayloadType::WindowSize => 6,
407                EventPayloadType::DesignSystem => 7,
408                EventPayloadType::NotificationActivation => 8,
409                EventPayloadType::NotificationPermission => 9,
410                EventPayloadType::Animation => 10,
411                EventPayloadType::ReducedMotion => 11,
412                EventPayloadType::CodeChange => 12,
413                EventPayloadType::CodeEditRejected => 13,
414                EventPayloadType::CodeHover => 14,
415                EventPayloadType::CodeSave => 15,
416                EventPayloadType::Decoration => 16,
417                EventPayloadType::Pointer => 17,
418                EventPayloadType::Zoom => 18,
419                EventPayloadType::CodeSelection => 19,
420                EventPayloadType::CodeVisibleRange => 20,
421                EventPayloadType::CodeFocus => 21,
422                EventPayloadType::CodeFold => 22,
423                EventPayloadType::CodeComposition => 23,
424                EventPayloadType::WindowFocus => 24,
425                EventPayloadType::WindowMove => 25,
426                EventPayloadType::WindowDrag => 26,
427                EventPayloadType::WindowDragOver => 27,
428                EventPayloadType::WindowRequest => 28,
429                EventPayloadType::FileDialogResult => 29,
430                EventPayloadType::ClipboardText => 30,
431                EventPayloadType::IoAnswer => 31,
432                EventPayloadType::FileHandles => 32,
433                EventPayloadType::ScrollChanged => 33,
434                EventPayloadType::MotionFinished => 34,
435                EventPayloadType::CodeCaretRect => 35,
436                EventPayloadType::CodePositionRect => 36,
437                EventPayloadType::CodePointer => 37,
438                EventPayloadType::CodeEditGroupResult => 38,
439                EventPayloadType::ColorScheme => 39,
440                EventPayloadType::CodeSelections => 40,
441                EventPayloadType::Density => 41,
442                EventPayloadType::NativeViewParent => 42,
443            }],
444        );
445        index += 1;
446    }
447    hash = crate::code::hash_record_schema(hash, crate::code::DECORATION_RECORD);
448    hash = crate::code::hash_record_schema(hash, crate::code::SYNTAX_SPAN_RECORD);
449    hash = crate::code::hash_record_schema(hash, crate::code::FOLD_RECORD);
450    hash = crate::code::hash_record_schema(hash, crate::code::GUTTER_DECORATION_RECORD);
451    hash = crate::code::hash_record_schema(hash, crate::code::CODE_EDITOR_COLORS_RECORD);
452    hash = crate::code::hash_record_schema(hash, crate::code::VIEW_ZONE_RECORD);
453    hash = hash_bytes(hash, &SEMANTICS_STATE_MASK.to_le_bytes());
454    hash
455}
456
457/// Stable handshake hash of the complete ordered schema metadata.
458pub const SCHEMA_HASH: u64 = schema_hash();
459pub const PROTOCOL_VERSION: u16 = 1;
460
461fn wire_name_eq(input: &str, schema_name: &str) -> bool {
462    input
463        .bytes()
464        .filter(|byte| *byte != b'_')
465        .map(|byte| byte.to_ascii_lowercase())
466        .eq(schema_name.bytes().map(|byte| byte.to_ascii_lowercase()))
467}
468
469macro_rules! define_wire_enum {
470    ($schema:ident, $name:ident { $($variant:ident = $tag:literal),+ $(,)? }) => {
471        define_wire_enum!($schema, $name { $($variant = $tag),+ } unlisted {});
472    };
473    // `unlisted` variants exist in Rust and travel as their tag, but are not in the schema
474    // table, so codegen mirrors no Kotlin enum entry for them and `TryFrom` does not
475    // produce them. The one there is, `TypeRole::None`, is tag 0, which every role
476    // decoder already reads as "no role", and an entry for it in the Kotlin enum would
477    // shift every ordinal the Renderer indexes its token tables by.
478    (
479        $schema:ident,
480        $name:ident { $($variant:ident = $tag:literal),+ $(,)? }
481        unlisted { $($extra:ident = $extra_tag:literal),* $(,)? }
482    ) => {
483        #[derive(Clone, Copy, Debug, Eq, PartialEq)]
484        #[repr(u16)]
485        pub enum $name {
486            $($extra = $extra_tag,)*
487            $($variant = $tag),+
488        }
489
490        pub const $schema: &[EnumVariantSchema] = &[
491            $(EnumVariantSchema { name: stringify!($variant), tag: $tag }),+
492        ];
493
494        impl From<$name> for u16 {
495            fn from(value: $name) -> Self {
496                value as Self
497            }
498        }
499
500        impl TryFrom<u16> for $name {
501            type Error = ();
502
503            // Spelled `()` rather than `Self::Error`: a `ColorRole::Error` variant would
504            // otherwise make the associated item ambiguous.
505            fn try_from(value: u16) -> Result<Self, ()> {
506                match value {
507                    $($tag => Ok(Self::$variant),)+
508                    _ => Err(()),
509                }
510            }
511        }
512
513        impl $name {
514            // The unit error is the wire's own convention: a name either is a variant or is
515            // not, and the caller reports which name it was.
516            #[allow(dead_code, clippy::result_unit_err)]
517            #[doc(hidden)]
518            #[allow(clippy::result_unit_err)]
519            pub fn from_name(value: &str) -> Result<Self, ()> {
520                $(if wire_name_eq(value, stringify!($variant)) {
521                    return Ok(Self::$variant);
522                })+
523                Err(())
524            }
525        }
526    };
527}
528
529crate::extensions::define_widget_schema_with_extensions!(define_wire_enum; WIDGET_SCHEMA, WidgetKind {
530    Column = 1,
531    Row = 2,
532    Box = 3,
533    Text = 4,
534    TextField = 5,
535    Button = 6,
536    Spacer = 7,
537    LazyColumn = 8,
538    ScrollColumn = 9,
539    Image = 10,
540    Icon = 11,
541    // The selection controls and the indicators. Each one emits a state and a role and
542    // nothing about how it is drawn: the tick, the track, the thumb and the sweep of an
543    // indeterminate bar are the design system's.
544    Checkbox = 12,
545    RadioButton = 13,
546    Switch = 14,
547    Slider = 15,
548    ProgressIndicator = 16,
549    Divider = 17,
550    Card = 18,
551    Surface = 19,
552    Dialog = 20,
553    Menu = 21,
554    Tabs = 22,
555    TopAppBar = 23,
556    LazyRow = 24,
557    Tooltip = 25,
558    // Drawing commands instead of child nodes. The command list is its only property.
559    Canvas = 26,
560    DatePicker = 27,
561    TimePicker = 28,
562    Dropdown = 29,
563    // One declaration, three presentations. The Renderer picks a bottom bar, a rail or a
564    // permanent drawer from the width it has already measured, so the same tree looks
565    // native on a phone and on a desktop without the Host branching on the size class.
566    Navigation = 30,
567    // One destination. Its label and its icon are properties rather than children,
568    // because a child tree would fix the arrangement the presentations need to differ in.
569    NavigationItem = 31,
570    // A temporary surface that slides in from an edge of the screen. Which edge is the
571    // Renderer's decision, for the same reason the navigation presentation is.
572    Sheet = 32,
573    // The screen's frame. The application fills slots and the Renderer decides what each
574    // one becomes on this platform and at this width, which is the same decision
575    // `Navigation` already makes for itself, widened to the whole frame.
576    Scaffold = 33,
577    // One filled slot. A wrapper rather than a property on the slot's own root, because
578    // an application may put any tree in a slot and the Renderer has to know which slot
579    // it is looking at without reading into it.
580    ScaffoldSlot = 34,
581    // A lazy grid. The windowing protocol is the list's, unchanged: the Renderer asks for a
582    // range of items and the Host materialises exactly that range. What the grid adds is
583    // that the Renderer rounds the range it asks for to whole rows, because a row is what
584    // it lays out, and how many items a row holds is its own decision when the columns
585    // were given as a minimum width rather than a count.
586    LazyGrid = 35,
587    // A place files may be dropped. Being this widget is the willingness: a node that is
588    // not one is never offered as a target, so the platform shows no drop cursor over it
589    // and nothing is reported.
590    FileDropTarget = 36,
591    // The whole content with a horizontal scroll, which is a ScrollColumn turned on its
592    // side. Every child is materialised and the scroll position is the Renderer's, so
593    // nothing about scrolling crosses the boundary; a long horizontal list is a LazyRow.
594    ScrollRow = 37,
595    // A small token that is chosen or filters. It carries its label and whether it is
596    // chosen, and the chosen state is the Host's: it changes only because the Host's own
597    // click handler changed it. The shape is the design system's.
598    Chip = 38,
599    // The one action a screen is about. It carries an icon, a label and a click. Where it
600    // goes and what it is drawn as is the design system's: a disc floating over the page
601    // is one system's answer, a plus at the trailing end of the bar is another's, and an
602    // accent button at the head of the command bar is a third.
603    FloatingAction = 39,
604    // A small mark on something else that says how many, that there is something new, or
605    // one short word. With one child it is attached to that child; with none it stands on
606    // its own, at the end of a row. Where it sits on the child, its shape, and how a large
607    // count is shortened are the design system's: nothing here can ask for a corner or a
608    // ceiling.
609    Badge = 40,
610    // A region whose text can be dragged over and copied, as one selection across every
611    // Text inside it. Text outside one cannot be selected. The selection and the copy are
612    // the Renderer's entirely, so nothing about either crosses the boundary.
613    SelectionContainer = 41,
614    // Two panes side by side, a side pane and a body, with a divider the user drags to
615    // change the side pane's width. Exactly two children, the side pane first.
616    //
617    // The drag is the Renderer's, like a scroll position: nothing crosses the boundary
618    // while it moves, and the width it ends on is reported once through the value change
619    // event. How the divider looks and how far its grip reaches, the side pane's default
620    // width, the body's minimum, and whether a narrow place shows the two panes side by
621    // side, with the side pane laid over the body, or one at a time, are the design
622    // system's answers.
623    SplitPane = 42,
624    // Several lines of code that the reader edits. The text, the caret, the selection,
625    // the scroll position and the undo history are the Renderer's, the way a text field's
626    // are, and the Host is told about each committed edit with the version it produced.
627    // What the Host adds on top is said as ranges: colour runs for the syntax, and
628    // decorations for diagnostics, lenses, hover anchors and inline suggestions. How any
629    // of it is drawn, from the gutter to the weight of an underline, is the design
630    // system's.
631    CodeEditor = 43,
632    // Children laid where the Host already put them. Each child is placed at its own
633    // `Offset`, relative to this box, and no child moves or sizes another: the layout was
634    // computed on the Host (an HTML engine, for instance) and laying it out a second time
635    // here would only be a second answer that can disagree with the first. Later children
636    // draw over earlier ones, so a stacking order is the child order.
637    AbsoluteBox = 44,
638    // A platform window, a child of the root and only of the root. The children of a
639    // `Window` are that window's content. Putting one anywhere else, or moving a node from
640    // one window into another, is a protocol error: Compose keeps one composition per
641    // window and has no way to hand a node from one to the next.
642    Window = 45,
643    // A row that wraps. Children are measured at their own width and placed one after
644    // another on a line; a child that does not fit in what is left of the line starts the
645    // next one. A child wider than the whole line has the line to itself and is measured
646    // at the line's width, so nothing runs out of the row.
647    FlowRow = 46,
648    // A floating box of any content attached to an anchor. The first child is the anchor
649    // and is always drawn; the rest is the content, drawn only while the Host says it is
650    // open. A `Menu` is the same shape with entries in it and a place the design system
651    // fixes; here the Host names the side and the edge, and the Renderer keeps the box
652    // inside the window by flipping it to the other side or sliding it along the edge.
653    // 46 is held for a widget on another branch.
654    Popover = 47,
655    // A place in the window for a platform view the Host made: an `NSView`, an `HWND`, an
656    // X11 window or an Android `View`. The Renderer places it over the node's rectangle,
657    // cuts it to what its ancestors and the overlays above it leave showing, and hands
658    // keyboard focus to it and back. It never makes, links or destroys one. It takes no
659    // children and has no size of its own: its modifiers and its parent's constraints size
660    // it, and what the modifiers draw shows only where the view does not cover the node.
661    NativeView = 48,
662});
663
664#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
665#[repr(u8)]
666pub enum LoopMode {
667    #[default]
668    Renderer = 0,
669    Platform = 1,
670}
671
672#[derive(Clone, Copy, Debug, Eq, PartialEq)]
673pub struct Selection {
674    pub start: u32,
675    pub end: u32,
676}
677
678// Compose key identities supported by the M0 schema.
679define_wire_enum!(KEY_SCHEMA, Key {
680    Enter = 1,
681    // Any key the enum does not name. The event's `code` and `text` say which one.
682    Other = 2,
683    // Keys a menu, a list or an overlay acts on. Appended only: a tag never moves, so an
684    // older Renderer that sends `Other` for these still decodes.
685    Escape = 3,
686    Tab = 4,
687    Backspace = 5,
688    Delete = 6,
689    ArrowUp = 7,
690    ArrowDown = 8,
691    ArrowLeft = 9,
692    ArrowRight = 10,
693    Home = 11,
694    End = 12,
695    PageUp = 13,
696    PageDown = 14,
697    // The function keys and the key that opens a context menu, appended after the rest.
698    F1 = 15,
699    F2 = 16,
700    F3 = 17,
701    F4 = 18,
702    F5 = 19,
703    F6 = 20,
704    F7 = 21,
705    F8 = 22,
706    F9 = 23,
707    F10 = 24,
708    F11 = 25,
709    F12 = 26,
710    ContextMenu = 27,
711});
712
713define_wire_enum!(WINDOW_SIZE_CLASS_SCHEMA, WindowSizeClass {
714    Compact = 0,
715    Medium = 1,
716    Expanded = 2,
717});
718
719impl WindowSizeClass {
720    /// The width in dp at which `Medium` begins, and the width at which `Expanded` does.
721    ///
722    /// These are the Material 3 window size class boundaries. Using different numbers
723    /// would make the Compose components adapt at one width and the Rust layout branch at
724    /// another, and that mismatch is visible on screen.
725    pub const MEDIUM_MIN_WIDTH_DP: f32 = 600.0;
726    pub const EXPANDED_MIN_WIDTH_DP: f32 = 840.0;
727
728    /// The class a window of this width belongs to. Height does not take part.
729    pub fn from_width_dp(width_dp: f32) -> Self {
730        if width_dp >= Self::EXPANDED_MIN_WIDTH_DP {
731            Self::Expanded
732        } else if width_dp >= Self::MEDIUM_MIN_WIDTH_DP {
733            Self::Medium
734        } else {
735            Self::Compact
736        }
737    }
738}
739
740define_wire_enum!(WINDOW_HEIGHT_CLASS_SCHEMA, WindowHeightClass {
741    Compact = 0,
742    Medium = 1,
743    Expanded = 2,
744});
745
746impl WindowHeightClass {
747    /// The height in dp at which `Medium` begins, and the height at which `Expanded` does.
748    ///
749    /// The same published table the width boundaries came from, so a layout that folds
750    /// when it runs out of vertical room folds at the height Compose's own components
751    /// treat as short.
752    pub const MEDIUM_MIN_HEIGHT_DP: f32 = 480.0;
753    pub const EXPANDED_MIN_HEIGHT_DP: f32 = 900.0;
754
755    /// The class a window of this height belongs to. Width does not take part.
756    pub fn from_height_dp(height_dp: f32) -> Self {
757        if height_dp >= Self::EXPANDED_MIN_HEIGHT_DP {
758            Self::Expanded
759        } else if height_dp >= Self::MEDIUM_MIN_HEIGHT_DP {
760            Self::Medium
761        } else {
762            Self::Compact
763        }
764    }
765}
766
767/// A role enum that codegen mirrors into Kotlin.
768#[derive(Clone, Copy, Debug, Eq, PartialEq)]
769pub struct RoleEnumSchema {
770    pub name: &'static str,
771    pub variants: &'static [EnumVariantSchema],
772}
773
774// An opaque ARGB colour. Gradients and image brushes are deliberately absent: they do not
775// fit the two words a modifier variant has, and they would need resources to cross the
776// boundary, which the fixed-layout records cannot carry.
777#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
778#[repr(transparent)]
779pub struct Color(pub u32);
780
781impl Color {
782    /// An opaque colour from a 24-bit `0xRRGGBB` value.
783    pub const fn rgb(value: u32) -> Self {
784        Self(0xff00_0000 | (value & 0x00ff_ffff))
785    }
786
787    /// A colour from a full 32-bit `0xAARRGGBB` value.
788    pub const fn argb(value: u32) -> Self {
789        Self(value)
790    }
791
792    pub const fn to_argb(self) -> u32 {
793        self.0
794    }
795}
796
797// Semantic colour slots. The design system resolves them, inside the Renderer.
798define_wire_enum!(COLOR_ROLE_SCHEMA, ColorRole {
799    Primary = 1,
800    OnPrimary = 2,
801    Secondary = 3,
802    OnSecondary = 4,
803    Surface = 5,
804    OnSurface = 6,
805    SurfaceVariant = 7,
806    OnSurfaceVariant = 8,
807    Background = 9,
808    OnBackground = 10,
809    Outline = 11,
810    OutlineVariant = 12,
811    Error = 13,
812    OnError = 14,
813    // The layer a panel is made of: a thing raised off the page, holding the page's own
814    // reading ink. It exists because `Surface` cannot do that job everywhere. Material 3
815    // gives `Surface` and `Background` one value on purpose and expresses depth through
816    // tonal containers instead, so a panel filled with `Surface` on a page of `Background`
817    // is drawn, in the right colour, and is invisible. `SurfaceVariant` is not the answer
818    // either: its ink pair is the muted secondary ink, so a panel holding primary content
819    // would have to set that content half faded. This is the one role every design system
820    // promises to make visible against the page, and `OnSurface` is what reads on it.
821    SurfaceContainer = 15,
822    // The third accent, and a quiet fill for each of the three.
823    //
824    // Two accents and a page say a button, a bar and a heading. They cannot say a grid of
825    // subject tiles where the subject is the colour, a mood picker, or a panel of costs
826    // beside a panel of totals. Those screens need fills that read as relatives of one
827    // another, are not reading surfaces, and are quiet enough that body text sits on them.
828    //
829    // A container is a colour in the table rather than its accent at a lower opacity.
830    // Opacity only means something once you know what is behind it, and a role has to
831    // answer before anyone knows that. So each container is its own value and carries its
832    // own ink, held to the body-text bound rather than the label bound, because the reason
833    // it exists is that paragraphs land on it.
834    //
835    // The three containers are not required to be told apart from each other. Material 3's
836    // baseline primary and secondary containers are neighbouring tones of one palette, and
837    // that is its published scheme, not a mistake. A caller who needs three fills that
838    // separate at a glance reaches for the tertiary pair.
839    Tertiary = 16,
840    OnTertiary = 17,
841    PrimaryContainer = 18,
842    OnPrimaryContainer = 19,
843    SecondaryContainer = 20,
844    OnSecondaryContainer = 21,
845    TertiaryContainer = 22,
846    OnTertiaryContainer = 23,
847    // What a highlighter paints code with. A conversation shows code blocks and diffs, and
848    // with only literals to paint them the same grey comment would be stamped into seven
849    // systems and two schemes, which is how a light comment grey disappears on a dark page.
850    // So a token kind is a role like any other, and each system answers it from the code
851    // editor of its own platform.
852    //
853    // The split follows what tree-sitter's highlight names, VS Code's semantic token kinds
854    // and TextMate scopes all agree on. Each of those divides more finely, and the finer
855    // names fold into one of these (`keyword.return` is a keyword). A token that fits none
856    // is left in the body ink rather than given a colour of its own.
857    //
858    // The fifteen syntax inks hold the body-text bound on the code block's panel, comments
859    // included: a comment can be quieter in hue and lightness, but one nobody can read is
860    // a comment that is not there.
861    SyntaxKeyword = 24,
862    SyntaxString = 25,
863    SyntaxComment = 26,
864    SyntaxNumber = 27,
865    SyntaxConstant = 28,
866    SyntaxType = 29,
867    SyntaxFunction = 30,
868    SyntaxVariable = 31,
869    SyntaxProperty = 32,
870    SyntaxOperator = 33,
871    SyntaxPunctuation = 34,
872    SyntaxTag = 35,
873    SyntaxAttribute = 36,
874    SyntaxEscape = 37,
875    SyntaxMacro = 38,
876    // A diff. The ink marks an added or removed line and its text; the container is the
877    // whole line's background, drawn as the line node's own background; the emphasis is
878    // the background behind the words that actually changed, drawn by the span. Added and
879    // removed are never told apart by colour alone: the `+` and `-` at the head of a line
880    // stay, because the two backgrounds can look the same to a red-green colour blind
881    // reader.
882    DiffAdded = 39,
883    DiffRemoved = 40,
884    DiffModified = 41,
885    DiffAddedContainer = 42,
886    DiffRemovedContainer = 43,
887    DiffAddedEmphasis = 44,
888    DiffRemovedEmphasis = 45,
889});
890
891/// How many colour roles there are, which is how many rows every token table has and how
892/// many slots a palette carries per scheme.
893pub const COLOR_ROLE_COUNT: usize = 45;
894
895// The nine-rung type ladder every supported design system maps onto.
896//
897// `None` is text with no rung at all, which is what a page laid out by CSS draws: its size,
898// weight, line height, letter spacing and font come from the text's own values and nothing
899// from the design system. It is the only text that may name a font of its own. It is not
900// in the schema table, because it is not a rung: see `define_wire_enum!`.
901define_wire_enum!(TYPE_ROLE_SCHEMA, TypeRole {
902    Display = 1,
903    Headline = 2,
904    Title = 3,
905    Subtitle = 4,
906    Body = 5,
907    BodyStrong = 6,
908    Label = 7,
909    Caption = 8,
910    Mono = 9,
911} unlisted {
912    None = 0,
913});
914
915// Where a line of text may break, as CSS `word-break` says it. `Normal` breaks where the
916// language does: between words, and between syllables in Korean. `KeepAll` breaks only at
917// spaces, which is how Korean prose is usually set. `BreakAll` breaks between any two
918// characters.
919define_wire_enum!(WORD_BREAK_SCHEMA, WordBreak {
920    Normal = 1,
921    KeepAll = 2,
922    BreakAll = 3,
923});
924
925// Whether a word too long for its line may be broken inside, as CSS `overflow-wrap` says
926// it. `Anywhere` also lets that break count when the narrowest width the text can take is
927// worked out; `BreakWord` does not.
928define_wire_enum!(OVERFLOW_WRAP_SCHEMA, OverflowWrap {
929    Normal = 1,
930    Anywhere = 2,
931    BreakWord = 3,
932});
933
934// The families CSS names without naming a font. Which installed font each one is, is the
935// platform's answer.
936define_wire_enum!(GENERIC_FAMILY_SCHEMA, GenericFamily {
937    SystemUi = 1,
938    SansSerif = 2,
939    Serif = 3,
940    Monospace = 4,
941});
942
943// Corner roles. The radius is the design system's decision, except for `Full`, which is
944// a pill in every one of them: each end is a half circle of half the node's shorter
945// side, worked out by the Renderer from the size the node was measured at, so the
946// application never sends a radius that depends on a height.
947define_wire_enum!(SHAPE_ROLE_SCHEMA, ShapeRole {
948    None = 1,
949    ExtraSmall = 2,
950    Small = 3,
951    Medium = 4,
952    Large = 5,
953    Full = 6,
954});
955
956// How long a change takes and along which curve. A role rather than a duration, because
957// Material's emphasized curve and Cupertino's spring are different answers to the same
958// question, and a milliseconds figure from the application would settle it in the wrong
959// place. A system asked to reduce motion answers every one of these instantly.
960define_wire_enum!(MOTION_ROLE_SCHEMA, MotionRole {
961    Instant = 1,
962    Quick = 2,
963    Standard = 3,
964    Slow = 4,
965    Emphasized = 5,
966});
967
968// What a surface is made of. Four roles rather than a blur radius, because Cupertino and
969// Liquid Glass answer with blur, Material 3 with elevation and a tone laid over the
970// surface, and the GNOME and KDE systems with an opaque fill. A radius from the
971// application would be a blur instruction to systems that do not blur.
972define_wire_enum!(MATERIAL_ROLE_SCHEMA, MaterialRole {
973    Thin = 1,
974    Regular = 2,
975    Thick = 3,
976    Chrome = 4,
977});
978
979// What a node is to assistive technology. Compose's own `Role` names, so the Renderer maps
980// each one to the platform's. `None` leaves the role the widget already has.
981define_wire_enum!(SEMANTICS_ROLE_SCHEMA, SemanticsRole {
982    None = 1,
983    Button = 2,
984    Checkbox = 3,
985    Switch = 4,
986    RadioButton = 5,
987    Tab = 6,
988    Image = 7,
989    DropdownList = 8,
990    TabList = 9,
991    Tree = 10,
992    TreeItem = 11,
993    Menu = 12,
994    MenuItem = 13,
995    TextBox = 14,
996    Heading = 15,
997    Navigation = 16,
998    List = 17,
999    ListItem = 18,
1000    Group = 19,
1001});
1002
1003// Density roles, because dp density differs per design system.
1004define_wire_enum!(SPACE_ROLE_SCHEMA, SpaceRole {
1005    None = 1,
1006    Xs = 2,
1007    Sm = 3,
1008    Md = 4,
1009    Lg = 5,
1010    Xl = 6,
1011    Xxl = 7,
1012});
1013
1014// `Start` and `End` follow the writing direction and swap in right-to-left text. `Left`
1015// and `Right` are physical, as CSS `text-align: left|right` is, and never swap.
1016define_wire_enum!(TEXT_ALIGN_SCHEMA, TextAlign {
1017    Start = 1,
1018    Center = 2,
1019    End = 3,
1020    Justify = 4,
1021    Left = 5,
1022    Right = 6,
1023});
1024
1025define_wire_enum!(TEXT_OVERFLOW_SCHEMA, TextOverflow {
1026    Clip = 1,
1027    Ellipsis = 2,
1028    Visible = 3,
1029});
1030
1031define_wire_enum!(ARRANGEMENT_SCHEMA, Arrangement {
1032    Start = 1,
1033    Center = 2,
1034    End = 3,
1035    SpaceBetween = 4,
1036    SpaceAround = 5,
1037    SpaceEvenly = 6,
1038});
1039
1040define_wire_enum!(ALIGNMENT_SCHEMA, Alignment {
1041    TopStart = 1,
1042    TopCenter = 2,
1043    TopEnd = 3,
1044    CenterStart = 4,
1045    Center = 5,
1046    CenterEnd = 6,
1047    BottomStart = 7,
1048    BottomCenter = 8,
1049    BottomEnd = 9,
1050});
1051
1052// The neutral component variant names the design system styles.
1053define_wire_enum!(BUTTON_VARIANT_SCHEMA, ButtonVariant {
1054    Filled = 1,
1055    Tonal = 2,
1056    Outlined = 3,
1057    Text = 4,
1058    Operator = 5,
1059});
1060
1061// What a button is, independently from the visual emphasis its variant carries.
1062define_wire_enum!(BUTTON_KIND_SCHEMA, ButtonKind {
1063    Standard = 1,
1064    ActionKey = 2,
1065});
1066
1067// What the bytes behind an asset id are. A kind the Renderer cannot read is a reported
1068// protocol error, not a guess.
1069define_wire_enum!(ASSET_KIND_SCHEMA, AssetKind {
1070    Png = 1,
1071    Jpeg = 2,
1072    Svg = 3,
1073    VectorIcon = 4,
1074    // A font file, registered so that a type role can resolve to it. The bytes are the
1075    // font, which is why this is an asset and not a name: a name would put the check that
1076    // the font exists at run time on the reader's machine, and a missing one there is a
1077    // screen in the wrong typeface with nobody to tell.
1078    Font = 5,
1079    // A gradient or an image fill, registered so that any Paint may name it. The bytes
1080    // are the brush's own fixed layout rather than a file: nothing on any platform stores
1081    // a list of stops as a document, and a format would be a parser to write and keep.
1082    Brush = 6,
1083});
1084
1085// How a brush carries on past the area it was given.
1086define_wire_enum!(TILE_MODE_SCHEMA, TileMode {
1087    // Stops at the edge and drags the last colour outwards, which is what a gradient
1088    // filling a surface wants.
1089    Clamp = 1,
1090    Repeat = 2,
1091    // Repeats, flipping every other copy, so the seams do not show.
1092    Mirror = 3,
1093});
1094
1095// The closed set of icon meanings. An icon is addressed by what it is for, never by a
1096// system icon name: a name would defer the check that the icon exists to run time, and it
1097// would pin one platform's artwork into the protocol. The role is what lets the same
1098// declaration come out as SF Symbols under Cupertino and Material Symbols under Material 3.
1099define_wire_enum!(ICON_ROLE_SCHEMA, IconRole {
1100    Back = 1,
1101    Forward = 2,
1102    Close = 3,
1103    Search = 4,
1104    Add = 5,
1105    Check = 6,
1106    Settings = 7,
1107    More = 8,
1108    // The meanings a set of destinations needs before any other: where the application
1109    // starts, the list it is mostly about, and what has arrived.
1110    Home = 9,
1111    List = 10,
1112    Inbox = 11,
1113    // What a window's own bar needs: the button that opens everything this screen does
1114    // not have room for, and the one that goes back over what has already happened. Both
1115    // are in the reference bar of more than one sample, and neither is a destination, so
1116    // neither could be said with the three above.
1117    Menu = 12,
1118    History = 13,
1119    // What putting the samples beside the applications they are drawn from turned up: eight
1120    // meanings the set could not say. Each is a meaning rather than a picture, so a system
1121    // that draws sending as a paper aeroplane is still answering `Send`.
1122    //
1123    // None of them is an existing role used loosely. A composer's send was drawn with
1124    // `Forward` for a while, and an arrow pointing sideways says "on to the next one"
1125    // rather than "send this".
1126    Send = 14,
1127    Mic = 15,
1128    Image = 16,
1129    Video = 17,
1130    Library = 18,
1131    Sidebar = 19,
1132    Compose = 20,
1133    Collapse = 21,
1134});
1135
1136// How long a transient message stays on screen. Closed, and deliberately short: a message
1137// that has to be acknowledged is a `Dialog`, so there is no indefinite duration. What the
1138// two names mean in milliseconds is the design system's decision.
1139define_wire_enum!(MESSAGE_DURATION_SCHEMA, MessageDuration {
1140    Short = 1,
1141    Long = 2,
1142});
1143
1144// The edge a transient message is drawn along, where the application chose one. Tag 0 on the
1145// wire is "the design system's place", which is what a message that names no placement
1146// gets, so neither enum lists it.
1147define_wire_enum!(MESSAGE_VERTICAL_SCHEMA, MessageVertical {
1148    Top = 1,
1149    Bottom = 2,
1150});
1151
1152// Where along that edge the message sits. Start and End follow the layout direction, the
1153// same way a `Row`'s do.
1154define_wire_enum!(MESSAGE_HORIZONTAL_SCHEMA, MessageHorizontal {
1155    Start = 1,
1156    Center = 2,
1157    End = 3,
1158});
1159
1160/// Where a transient message is drawn, for an application that wants a place other than
1161/// the design system's.
1162///
1163/// Wherever it is, the message stays clear of the safe area and of the application's own
1164/// bars: a message at the bottom sits above a bottom tab bar, and one at the top below the
1165/// top bar.
1166#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1167pub struct MessagePlacement {
1168    pub vertical: MessageVertical,
1169    pub horizontal: MessageHorizontal,
1170}
1171
1172// How much a notification matters. Closed for the same reason a message's duration is: what
1173// it is worth in sound, in an Android channel's importance or in getting through Do Not
1174// Disturb is the platform's answer, so the Host has no way to send a sound file or a
1175// priority number.
1176define_wire_enum!(NOTIFICATION_IMPORTANCE_SCHEMA, NotificationImportance {
1177    Normal = 1,
1178    Urgent = 2,
1179});
1180
1181// Whether a notification is shown while the application's window is the active one.
1182// `WhenInactive` is dropped by the Renderer when the window has focus: whether it has is
1183// the Renderer's state, and a Host that wanted to judge it would need every focus change
1184// sent across.
1185define_wire_enum!(NOTIFICATION_PRESENTATION_SCHEMA, NotificationPresentation {
1186    Always = 1,
1187    WhenInactive = 2,
1188});
1189
1190// Whether this run may show notifications. `Unsupported` is a platform or a run that has
1191// no way to show one (no bundle identifier, no AppUserModelID, no notification daemon),
1192// which is an answer and not an error.
1193define_wire_enum!(NOTIFICATION_PERMISSION_SCHEMA, NotificationPermission {
1194    NotDetermined = 1,
1195    Granted = 2,
1196    Denied = 3,
1197    Unsupported = 4,
1198});
1199
1200// The design systems of phase one. Later ones append variants here and nowhere else: a new
1201// design system is one variant plus one token table and rule implementation in the Renderer.
1202//
1203// `LiquidGlass` is the language macOS 26 and iOS 26 draw, and it sits beside `Cupertino`
1204// rather than replacing it: one draws grouped inset lists on a grey page, the other draws
1205// translucent floating capsules, and an application that wants one does not want the
1206// other. Tags are append only, so it lands after the Linux three even though it belongs
1207// next to `Cupertino` in any list a reader would write.
1208define_wire_enum!(DESIGN_SYSTEM_SCHEMA, DesignSystem {
1209    Material3 = 1,
1210    Cupertino = 2,
1211    Fluent = 3,
1212    Gnome = 4,
1213    Breeze = 5,
1214    Deepin = 6,
1215    LiquidGlass = 7,
1216});
1217
1218// Light and dark selection. `FollowSystem` leaves the choice to the Renderer, which learns
1219// of a system change first and applies it without involving the Host.
1220define_wire_enum!(COLOR_SCHEME_SCHEMA, ColorScheme {
1221    Light = 1,
1222    Dark = 2,
1223    FollowSystem = 3,
1224});
1225
1226// Which part of the screen's frame a `Scaffold` slot fills.
1227//
1228// What each one becomes is the Renderer's: a top bar may be the window's caption, an
1229// ordinary bar under the system title bar, or a large title that shrinks as the page
1230// scrolls; a bottom bar may be a bar, a rail or a permanent drawer; a floating action
1231// may float, sit in the toolbar, or fold into a menu. The application says which slot
1232// it filled and nothing about the answer.
1233define_wire_enum!(SLOT_ROLE_SCHEMA, SlotRole {
1234    TopBar = 1,
1235    BottomBar = 2,
1236    FloatingAction = 3,
1237    Content = 4,
1238});
1239
1240// What a code editor decoration is: a mark under a range, a line of text above a line, a
1241// range that answers a resting pointer, and a suggestion shown in place. Each is what a
1242// language server or an extension host already speaks in, so an application can pass its
1243// answers through without inventing its own. After them, the two backgrounds a diff view
1244// is drawn with: a tint across whole lines, the width of the editor, and a stronger one
1245// over the characters that changed. Then muted text after the end of a line, which is not
1246// text: a blame annotation, an inline value. Values are only appended.
1247define_wire_enum!(DECORATION_KIND_SCHEMA, DecorationKind {
1248    Underline = 1,
1249    CodeLens = 2,
1250    HoverAnchor = 3,
1251    GhostText = 4,
1252    LineBackground = 5,
1253    RangeBackground = 6,
1254    AfterLine = 7,
1255});
1256
1257// How serious an underlined diagnostic is. The four a language server reports, in its
1258// order. The colour each one gets is the design system's unless the application names a
1259// role, and how the mark is drawn, a squiggle or a straight line, is always the system's.
1260define_wire_enum!(SEVERITY_SCHEMA, Severity {
1261    Error = 1,
1262    Warning = 2,
1263    Information = 3,
1264    Hint = 4,
1265});
1266
1267// Whether a pointer has come to rest over a place in a code editor or has left it. Two
1268// values, because the Host is told once on arriving and once on leaving and never while
1269// the pointer stays.
1270define_wire_enum!(HOVER_PHASE_SCHEMA, HoverPhase {
1271    Rest = 1,
1272    Leave = 2,
1273});
1274
1275// What a mark beside the line numbers of a code editor looks like: a dot, a bar the height
1276// of the line, or one character the application names. The colour is a role or the design
1277// system's; the size and the placement of all three are always the system's.
1278define_wire_enum!(GUTTER_DECORATION_KIND_SCHEMA, GutterDecorationKind {
1279    Dot = 1,
1280    Bar = 2,
1281    Glyph = 3,
1282});
1283
1284// The side of its anchor a `Popover` opens on. `Start` and `End` follow the layout
1285// direction. It is the side asked for: the Renderer opens on the opposite one when the
1286// content does not fit between the anchor and the window's edge.
1287define_wire_enum!(POPOVER_PLACEMENT_SCHEMA, PopoverPlacement {
1288    Top = 1,
1289    Bottom = 2,
1290    Start = 3,
1291    End = 4,
1292});
1293
1294// Which edge of its anchor a `Popover` lines up with, along the side it opened on.
1295define_wire_enum!(POPOVER_ALIGN_SCHEMA, PopoverAlign {
1296    Start = 1,
1297    Center = 2,
1298    End = 3,
1299});
1300
1301// Where `RevealRange` puts the range it brings into view: the least scroll that shows it,
1302// the middle of the view, or the top.
1303define_wire_enum!(REVEAL_ALIGN_SCHEMA, RevealAlign {
1304    Nearest = 1,
1305    Center = 2,
1306    Top = 3,
1307});
1308
1309// The vocabulary of animations the Renderer plays on its own frame clock. Every one is a
1310// byte on the wire and every one starts at 1, so a zero is always a record the two sides
1311// disagree about.
1312
1313// What an animation changes. Each has a place it is drawn from: the node's first `Alpha`,
1314// its `color` property, its first `Background`, its first `Transform`, and the colour of
1315// every side of its first `Border` or `BorderEach`. A container's `color` is the colour
1316// the text inside it inherits, so one animation on it recolours all of that text.
1317define_wire_enum!(ANIMATED_PROPERTY_SCHEMA, AnimatedProperty {
1318    Alpha = 1,
1319    Color = 2,
1320    Background = 3,
1321    Transform = 4,
1322    BorderColor = 5,
1323});
1324
1325define_wire_enum!(PLAYBACK_DIRECTION_SCHEMA, PlaybackDirection {
1326    Normal = 1,
1327    Reverse = 2,
1328    Alternate = 3,
1329    AlternateReverse = 4,
1330});
1331
1332define_wire_enum!(FILL_MODE_SCHEMA, FillMode {
1333    None = 1,
1334    Forwards = 2,
1335    Backwards = 3,
1336    Both = 4,
1337});
1338
1339define_wire_enum!(PLAY_STATE_SCHEMA, PlayState {
1340    Running = 1,
1341    Paused = 2,
1342});
1343
1344// How two colours are mixed: the way CSS's older colour syntax does, or in Oklab, the
1345// default of CSS Color 4's newer syntax.
1346define_wire_enum!(COLOR_INTERPOLATION_SCHEMA, ColorInterpolation {
1347    SrgbPremultiplied = 1,
1348    Oklab = 2,
1349});
1350
1351define_wire_enum!(TIMING_KIND_SCHEMA, TimingKind {
1352    Linear = 1,
1353    CubicBezier = 2,
1354    Steps = 3,
1355});
1356
1357define_wire_enum!(STEP_POSITION_SCHEMA, StepPosition {
1358    JumpStart = 1,
1359    JumpEnd = 2,
1360    JumpNone = 3,
1361    JumpBoth = 4,
1362});
1363
1364define_wire_enum!(TRANSFORM_FUNCTION_KIND_SCHEMA, TransformFunctionKind {
1365    Translate = 1,
1366    Rotate = 2,
1367    Scale = 3,
1368    Skew = 4,
1369    Matrix = 5,
1370});
1371
1372define_wire_enum!(ANIMATION_CONTROL_SCHEMA, AnimationControl {
1373    Pause = 1,
1374    Resume = 2,
1375    Cancel = 3,
1376});
1377
1378define_wire_enum!(ANIMATION_EVENT_KIND_SCHEMA, AnimationEventKind {
1379    Ready = 1,
1380    Active = 2,
1381    Iteration = 3,
1382    End = 4,
1383});
1384
1385define_wire_enum!(REDUCED_MOTION_SCHEMA, ReducedMotion {
1386    Off = 1,
1387    On = 2,
1388    Unknown = 3,
1389});
1390
1391// Whether the system appearance is light or dark, as the Renderer reads it. Unlike
1392// `ColorScheme`, it has no `FollowSystem`: it is the answer that choice follows.
1393define_wire_enum!(SYSTEM_COLOR_SCHEME_SCHEMA, SystemColorScheme {
1394    Light = 0,
1395    Dark = 1,
1396});
1397
1398define_wire_enum!(POINTER_KIND_SCHEMA, PointerKind {
1399    Move = 1,
1400    Enter = 2,
1401    Leave = 3,
1402    Down = 4,
1403    Up = 5,
1404    Cancel = 6,
1405    Wheel = 7,
1406    ContextMenu = 8,
1407});
1408
1409define_wire_enum!(POINTER_TYPE_SCHEMA, PointerType {
1410    Mouse = 1,
1411    Touch = 2,
1412    Pen = 3,
1413});
1414
1415define_wire_enum!(WHEEL_DELTA_MODE_SCHEMA, WheelDeltaMode {
1416    Pixel = 0,
1417    Line = 1,
1418    Page = 2,
1419});
1420
1421// CSS `cursor` keywords, by name and in the order CSS lists them. `Auto` is "let the widget
1422// under the pointer decide".
1423define_wire_enum!(CURSOR_SCHEMA, Cursor {
1424    Auto = 0,
1425    Default = 1,
1426    Pointer = 2,
1427    Text = 3,
1428    VerticalText = 4,
1429    Crosshair = 5,
1430    Move = 6,
1431    Grab = 7,
1432    Grabbing = 8,
1433    NotAllowed = 9,
1434    NoDrop = 10,
1435    Wait = 11,
1436    Progress = 12,
1437    Help = 13,
1438    ContextMenu = 14,
1439    Cell = 15,
1440    Copy = 16,
1441    Alias = 17,
1442    AllScroll = 18,
1443    ZoomIn = 19,
1444    ZoomOut = 20,
1445    ColResize = 21,
1446    RowResize = 22,
1447    EResize = 23,
1448    NResize = 24,
1449    NeResize = 25,
1450    NwResize = 26,
1451    SResize = 27,
1452    SeResize = 28,
1453    SwResize = 29,
1454    WResize = 30,
1455    EwResize = 31,
1456    NsResize = 32,
1457    NeswResize = 33,
1458    NwseResize = 34,
1459    None = 35,
1460});
1461
1462// CSS `user-select`, resolved by the Host. `Auto` follows the parent.
1463define_wire_enum!(USER_SELECT_SCHEMA, UserSelect {
1464    Auto = 0,
1465    None = 1,
1466    Text = 2,
1467    All = 3,
1468});
1469
1470/// Every role enum codegen mirrors, in wire order. Appending is the only allowed edit.
1471pub const ROLE_ENUM_SCHEMA: &[RoleEnumSchema] = &[
1472    RoleEnumSchema {
1473        name: "ColorRole",
1474        variants: COLOR_ROLE_SCHEMA,
1475    },
1476    RoleEnumSchema {
1477        name: "TypeRole",
1478        variants: TYPE_ROLE_SCHEMA,
1479    },
1480    RoleEnumSchema {
1481        name: "ShapeRole",
1482        variants: SHAPE_ROLE_SCHEMA,
1483    },
1484    RoleEnumSchema {
1485        name: "MotionRole",
1486        variants: MOTION_ROLE_SCHEMA,
1487    },
1488    RoleEnumSchema {
1489        name: "TileMode",
1490        variants: TILE_MODE_SCHEMA,
1491    },
1492    RoleEnumSchema {
1493        name: "MaterialRole",
1494        variants: MATERIAL_ROLE_SCHEMA,
1495    },
1496    RoleEnumSchema {
1497        name: "SemanticsRole",
1498        variants: SEMANTICS_ROLE_SCHEMA,
1499    },
1500    RoleEnumSchema {
1501        name: "SpaceRole",
1502        variants: SPACE_ROLE_SCHEMA,
1503    },
1504    RoleEnumSchema {
1505        name: "TextAlign",
1506        variants: TEXT_ALIGN_SCHEMA,
1507    },
1508    RoleEnumSchema {
1509        name: "TextOverflow",
1510        variants: TEXT_OVERFLOW_SCHEMA,
1511    },
1512    RoleEnumSchema {
1513        name: "Arrangement",
1514        variants: ARRANGEMENT_SCHEMA,
1515    },
1516    RoleEnumSchema {
1517        name: "Alignment",
1518        variants: ALIGNMENT_SCHEMA,
1519    },
1520    RoleEnumSchema {
1521        name: "ButtonVariant",
1522        variants: BUTTON_VARIANT_SCHEMA,
1523    },
1524    RoleEnumSchema {
1525        name: "ButtonKind",
1526        variants: BUTTON_KIND_SCHEMA,
1527    },
1528    RoleEnumSchema {
1529        name: "DesignSystem",
1530        variants: DESIGN_SYSTEM_SCHEMA,
1531    },
1532    RoleEnumSchema {
1533        name: "ColorScheme",
1534        variants: COLOR_SCHEME_SCHEMA,
1535    },
1536    RoleEnumSchema {
1537        name: "AssetKind",
1538        variants: ASSET_KIND_SCHEMA,
1539    },
1540    RoleEnumSchema {
1541        name: "IconRole",
1542        variants: ICON_ROLE_SCHEMA,
1543    },
1544    RoleEnumSchema {
1545        name: "MessageDuration",
1546        variants: MESSAGE_DURATION_SCHEMA,
1547    },
1548    RoleEnumSchema {
1549        name: "MessageVertical",
1550        variants: MESSAGE_VERTICAL_SCHEMA,
1551    },
1552    RoleEnumSchema {
1553        name: "MessageHorizontal",
1554        variants: MESSAGE_HORIZONTAL_SCHEMA,
1555    },
1556    RoleEnumSchema {
1557        name: "Chrome",
1558        variants: CHROME_SCHEMA,
1559    },
1560    RoleEnumSchema {
1561        name: "TitleBar",
1562        variants: TITLE_BAR_SCHEMA,
1563    },
1564    RoleEnumSchema {
1565        name: "SlotRole",
1566        variants: SLOT_ROLE_SCHEMA,
1567    },
1568    RoleEnumSchema {
1569        name: "NotificationImportance",
1570        variants: NOTIFICATION_IMPORTANCE_SCHEMA,
1571    },
1572    RoleEnumSchema {
1573        name: "NotificationPresentation",
1574        variants: NOTIFICATION_PRESENTATION_SCHEMA,
1575    },
1576    RoleEnumSchema {
1577        name: "NotificationPermission",
1578        variants: NOTIFICATION_PERMISSION_SCHEMA,
1579    },
1580    RoleEnumSchema {
1581        name: "WordBreak",
1582        variants: WORD_BREAK_SCHEMA,
1583    },
1584    RoleEnumSchema {
1585        name: "OverflowWrap",
1586        variants: OVERFLOW_WRAP_SCHEMA,
1587    },
1588    RoleEnumSchema {
1589        name: "GenericFamily",
1590        variants: GENERIC_FAMILY_SCHEMA,
1591    },
1592    RoleEnumSchema {
1593        name: "AnimatedProperty",
1594        variants: ANIMATED_PROPERTY_SCHEMA,
1595    },
1596    RoleEnumSchema {
1597        name: "PlaybackDirection",
1598        variants: PLAYBACK_DIRECTION_SCHEMA,
1599    },
1600    RoleEnumSchema {
1601        name: "FillMode",
1602        variants: FILL_MODE_SCHEMA,
1603    },
1604    RoleEnumSchema {
1605        name: "PlayState",
1606        variants: PLAY_STATE_SCHEMA,
1607    },
1608    RoleEnumSchema {
1609        name: "ColorInterpolation",
1610        variants: COLOR_INTERPOLATION_SCHEMA,
1611    },
1612    RoleEnumSchema {
1613        name: "TimingKind",
1614        variants: TIMING_KIND_SCHEMA,
1615    },
1616    RoleEnumSchema {
1617        name: "StepPosition",
1618        variants: STEP_POSITION_SCHEMA,
1619    },
1620    RoleEnumSchema {
1621        name: "TransformFunctionKind",
1622        variants: TRANSFORM_FUNCTION_KIND_SCHEMA,
1623    },
1624    RoleEnumSchema {
1625        name: "AnimationControl",
1626        variants: ANIMATION_CONTROL_SCHEMA,
1627    },
1628    RoleEnumSchema {
1629        name: "AnimationEventKind",
1630        variants: ANIMATION_EVENT_KIND_SCHEMA,
1631    },
1632    RoleEnumSchema {
1633        name: "ReducedMotion",
1634        variants: REDUCED_MOTION_SCHEMA,
1635    },
1636    RoleEnumSchema {
1637        name: "SystemColorScheme",
1638        variants: SYSTEM_COLOR_SCHEME_SCHEMA,
1639    },
1640    RoleEnumSchema {
1641        name: "DecorationKind",
1642        variants: DECORATION_KIND_SCHEMA,
1643    },
1644    RoleEnumSchema {
1645        name: "Severity",
1646        variants: SEVERITY_SCHEMA,
1647    },
1648    RoleEnumSchema {
1649        name: "HoverPhase",
1650        variants: HOVER_PHASE_SCHEMA,
1651    },
1652    RoleEnumSchema {
1653        name: "GutterDecorationKind",
1654        variants: GUTTER_DECORATION_KIND_SCHEMA,
1655    },
1656    RoleEnumSchema {
1657        name: "RevealAlign",
1658        variants: REVEAL_ALIGN_SCHEMA,
1659    },
1660    RoleEnumSchema {
1661        name: "PointerKind",
1662        variants: POINTER_KIND_SCHEMA,
1663    },
1664    RoleEnumSchema {
1665        name: "PointerType",
1666        variants: POINTER_TYPE_SCHEMA,
1667    },
1668    RoleEnumSchema {
1669        name: "WheelDeltaMode",
1670        variants: WHEEL_DELTA_MODE_SCHEMA,
1671    },
1672    RoleEnumSchema {
1673        name: "Cursor",
1674        variants: CURSOR_SCHEMA,
1675    },
1676    RoleEnumSchema {
1677        name: "UserSelect",
1678        variants: USER_SELECT_SCHEMA,
1679    },
1680    RoleEnumSchema {
1681        name: "WindowMode",
1682        variants: WINDOW_MODE_SCHEMA,
1683    },
1684    RoleEnumSchema {
1685        name: "LastWindowClosed",
1686        variants: LAST_WINDOW_CLOSED_SCHEMA,
1687    },
1688    RoleEnumSchema {
1689        name: "FileDialogKind",
1690        variants: FILE_DIALOG_KIND_SCHEMA,
1691    },
1692    RoleEnumSchema {
1693        name: "FileDialogStatus",
1694        variants: FILE_DIALOG_STATUS_SCHEMA,
1695    },
1696    RoleEnumSchema {
1697        name: "EditGroupStatus",
1698        variants: EDIT_GROUP_STATUS_SCHEMA,
1699    },
1700    RoleEnumSchema {
1701        name: "CompactNavigation",
1702        variants: COMPACT_NAVIGATION_SCHEMA,
1703    },
1704    RoleEnumSchema {
1705        name: "Snap",
1706        variants: SNAP_SCHEMA,
1707    },
1708    RoleEnumSchema {
1709        name: "MinimapSide",
1710        variants: MINIMAP_SIDE_SCHEMA,
1711    },
1712    RoleEnumSchema {
1713        name: "WordWrapMode",
1714        variants: WORD_WRAP_MODE_SCHEMA,
1715    },
1716    RoleEnumSchema {
1717        name: "StorageOp",
1718        variants: STORAGE_OP_SCHEMA,
1719    },
1720    RoleEnumSchema {
1721        name: "IoStatus",
1722        variants: IO_STATUS_SCHEMA,
1723    },
1724    RoleEnumSchema {
1725        name: "FileDelivery",
1726        variants: FILE_DELIVERY_SCHEMA,
1727    },
1728    RoleEnumSchema {
1729        name: "FileOp",
1730        variants: FILE_OP_SCHEMA,
1731    },
1732    RoleEnumSchema {
1733        name: "HorizontalAlignment",
1734        variants: HORIZONTAL_ALIGNMENT_SCHEMA,
1735    },
1736    RoleEnumSchema {
1737        name: "VerticalAlignment",
1738        variants: VERTICAL_ALIGNMENT_SCHEMA,
1739    },
1740    RoleEnumSchema {
1741        name: "PopoverPlacement",
1742        variants: POPOVER_PLACEMENT_SCHEMA,
1743    },
1744    RoleEnumSchema {
1745        name: "PopoverAlign",
1746        variants: POPOVER_ALIGN_SCHEMA,
1747    },
1748    RoleEnumSchema {
1749        name: "ContentScale",
1750        variants: CONTENT_SCALE_SCHEMA,
1751    },
1752    RoleEnumSchema {
1753        name: "BackgroundRepeat",
1754        variants: BACKGROUND_REPEAT_SCHEMA,
1755    },
1756    RoleEnumSchema {
1757        name: "SheetPresentation",
1758        variants: SHEET_PRESENTATION_SCHEMA,
1759    },
1760];
1761
1762/// Every place that takes a colour takes a `Paint`, so colour is expressed once.
1763///
1764/// Encoded as one `u64`: the high 32 bits are the kind, the low 32 bits are the value.
1765#[derive(Clone, Copy, Debug, Eq, PartialEq)]
1766pub enum Paint {
1767    Role(ColorRole),
1768    Literal(Color),
1769    /// A registered brush: a gradient, or a picture laid out as a fill.
1770    ///
1771    /// An id rather than the thing itself, because a list of stops does not fit the two
1772    /// words a modifier has and because a brush outlives the frame that draws it, which
1773    /// is what the asset path already exists for.
1774    Asset(u32),
1775}
1776
1777const PAINT_KIND_ROLE: u64 = 1;
1778const PAINT_KIND_LITERAL: u64 = 2;
1779const PAINT_KIND_ASSET: u64 = 3;
1780
1781impl Paint {
1782    pub const fn to_bits(self) -> u64 {
1783        match self {
1784            Self::Role(role) => (PAINT_KIND_ROLE << 32) | role as u64,
1785            Self::Literal(color) => (PAINT_KIND_LITERAL << 32) | color.0 as u64,
1786            Self::Asset(id) => (PAINT_KIND_ASSET << 32) | id as u64,
1787        }
1788    }
1789
1790    pub fn from_bits(bits: u64) -> Option<Self> {
1791        let value = bits as u32;
1792        match bits >> 32 {
1793            PAINT_KIND_ROLE => Some(Self::Role(
1794                ColorRole::try_from(u16::try_from(value).ok()?).ok()?,
1795            )),
1796            PAINT_KIND_LITERAL => Some(Self::Literal(Color(value))),
1797            PAINT_KIND_ASSET => Some(Self::Asset(value)),
1798            _ => None,
1799        }
1800    }
1801}
1802
1803// How the window wears its title bar.
1804//
1805// `Modern` runs content into the title bar area and is the default, because every desktop
1806// platform now expects it and a window with a separate system bar looks a decade old.
1807//
1808// `System` is the platform's ordinary bar, and it is kept deliberately. Some tool-shaped
1809// applications want one, and more importantly it is where an application goes when
1810// `Modern` turns out to be wrong on some machine: a default with no way out of it is a
1811// default that strands people.
1812define_wire_enum!(CHROME_SCHEMA, Chrome {
1813    Modern = 1,
1814    System = 2,
1815    FullSize = 3,
1816});
1817
1818// Which of two title bars this window has. `Chrome` chooses who draws the caption; this
1819// chooses, inside that, what kind of window the caption belongs to.
1820//
1821// What each one means is not the same on every platform, and the numbers are never the
1822// Host's. On macOS the buttons sit further in and the window is rounded more; on Windows
1823// and Linux the caption is a different height and the buttons stay where that platform
1824// puts them.
1825define_wire_enum!(TITLE_BAR_SCHEMA, TitleBar {
1826    // What an application on that platform actually looks like now, which is why it is the
1827    // default.
1828    Normal = 1,
1829    // An ordinary window. For tool applications, for the places the other reads oddly, and
1830    // as the way back.
1831    Simple = 2,
1832});
1833
1834// What a `Navigation` becomes in a compact window, where the application chose. Medium and
1835// Expanded stay the design system's answer whatever is chosen here.
1836//
1837// `Default` is no choice at all: the design system answers, which is a bottom bar on most
1838// of them and the put-away sidebar on Apple's desktop systems. It travels as tag 0, which
1839// is the same as not sending the property, so it is not in the schema table.
1840//
1841// `Sidebar` is the sidebar put away behind a toggle that brings it over the page, on every
1842// design system. `None` leaves the destinations off a compact window altogether, with
1843// nothing to call them: the application draws its own way to them. The name is Compose's
1844// `NavigationSuiteType.None`.
1845define_wire_enum!(COMPACT_NAVIGATION_SCHEMA, CompactNavigation {
1846    Sidebar = 1,
1847    None = 2,
1848} unlisted {
1849    Default = 0,
1850});
1851
1852// How a `Sheet` is presented: entering from an edge (`Edge = 0`, the default) or centered in
1853// the window (`Centered = 1`).
1854define_wire_enum!(SHEET_PRESENTATION_SCHEMA, SheetPresentation {
1855    Edge = 0,
1856    Centered = 1,
1857});
1858
1859// Where a scroll container comes to rest once a drag or a fling ends.
1860//
1861// `None` is free scrolling: the container stops wherever the drag or the fling left it. It
1862// travels as tag 0, which is the same as not sending the property, so it is not in the
1863// schema table.
1864//
1865// `ItemStart` stops with the start edge of the nearest direct child on the start of the
1866// visible area, the way CSS `scroll-snap-type: mandatory` with `scroll-snap-align: start`
1867// does.
1868// Where a code editor breaks a long line, the mode part of the `WordWrap` property: at the
1869// edge of the view, at a number of columns, or at whichever of the two comes first. `Off`
1870// breaks no line, which is what an editor that never sets it does.
1871define_wire_enum!(WORD_WRAP_MODE_SCHEMA, WordWrapMode {
1872    Viewport = 1,
1873    Column = 2,
1874    Bounded = 3,
1875} unlisted {
1876    Off = 0,
1877});
1878
1879// Which side of a code editor its minimap is drawn on: the whole document shrunk, with the
1880// part on screen marked, which a press or a drag scrolls to. `Off` draws none, which is what
1881// an editor that never sets it does.
1882define_wire_enum!(MINIMAP_SIDE_SCHEMA, MinimapSide {
1883    Right = 1,
1884    Left = 2,
1885} unlisted {
1886    Off = 0,
1887});
1888
1889define_wire_enum!(SNAP_SCHEMA, Snap {
1890    ItemStart = 1,
1891} unlisted {
1892    None = 0,
1893});
1894
1895// How an `Image` lays its picture into the box it was given, as Compose's `ContentScale`.
1896//
1897// `Fit` keeps the picture's proportions and shows all of it, centred, leaving the rest of
1898// the box empty. `Crop` keeps the proportions and covers the whole box, centred, cutting
1899// off what falls outside. `FillBounds` stretches the picture to the box in each direction
1900// on its own, which is CSS `object-fit: fill`. Not sending the property draws `Fit`.
1901define_wire_enum!(CONTENT_SCALE_SCHEMA, ContentScale {
1902    Fit = 1,
1903    Crop = 2,
1904    FillBounds = 3,
1905});
1906
1907// How a `BackgroundBrush` repeats its rectangle across the node, as CSS
1908// `background-repeat` does: not at all, in both directions, along the width only, or
1909// along the height only. A repeat runs both ways from the rectangle, so a node is covered
1910// to its edges whichever corner the rectangle sits in.
1911define_wire_enum!(BACKGROUND_REPEAT_SCHEMA, BackgroundRepeat {
1912    NoRepeat = 1,
1913    Repeat = 2,
1914    RepeatX = 3,
1915    RepeatY = 4,
1916});
1917
1918// How the application uses windows. `Single` is every application until now: the
1919// root's content fills the one window `SetWindow` describes. `Windows` is the multi-window
1920// mode, in which the root's children are `Window` nodes and `SetWindow` describes nothing
1921// but the mode.
1922define_wire_enum!(WINDOW_MODE_SCHEMA, WindowMode {
1923    Single = 0,
1924    Windows = 1,
1925});
1926
1927// What happens when the last `Window` node is removed. `Exit` ends the renderer
1928// loop, `KeepRunning` leaves the process up with no window. Ignored by `Single`.
1929define_wire_enum!(LAST_WINDOW_CLOSED_SCHEMA, LastWindowClosed {
1930    Exit = 0,
1931    KeepRunning = 1,
1932});
1933
1934// What a file dialog asks the user to pick. Closed: each kind is a different platform panel
1935// with different rules about how many paths come back, so a free-form set of flags would
1936// allow combinations no panel can honour.
1937define_wire_enum!(FILE_DIALOG_KIND_SCHEMA, FileDialogKind {
1938    OpenFile = 1,
1939    OpenFiles = 2,
1940    OpenFolder = 3,
1941    OpenFolders = 4,
1942    Save = 5,
1943});
1944
1945// How a file dialog ended. `Unavailable` means this run has no way to show one, which is an
1946// answer and not an error, and is never used for a user's cancel.
1947define_wire_enum!(FILE_DIALOG_STATUS_SCHEMA, FileDialogStatus {
1948    Chosen = 1,
1949    Cancelled = 2,
1950    Unavailable = 3,
1951});
1952
1953// What became of one grouped edit of a code editor. The group goes in whole or not at all,
1954// and each way it can stay out asks the application for something different: `Rejected`
1955// means the reader typed where it would have written, so read the document again and send
1956// it again; `TooOld` means the version it was written against is older than the editor
1957// remembers, so the application's copy has to be brought back in step; `Invalid` means the
1958// group itself makes no sense (edits that overlap, a range outside the document, a version
1959// from the future).
1960define_wire_enum!(EDIT_GROUP_STATUS_SCHEMA, EditGroupStatus {
1961    Applied = 1,
1962    Rejected = 2,
1963    Invalid = 3,
1964    TooOld = 4,
1965});
1966
1967// How the files a Renderer holds handles for reached it. Closed, because what an
1968// application may do with a file depends on it: only a `Handle` can be written again.
1969define_wire_enum!(FILE_DELIVERY_SCHEMA, FileDelivery {
1970    // The file itself, in the file system. Writing it again changes the same file.
1971    Handle = 1,
1972    // A copy the browser handed over from a file input. It can only be read.
1973    Upload = 2,
1974    // A save that became a download. Each write is a new download.
1975    Download = 3,
1976});
1977
1978// What one `FileCall` asks of a file the Renderer holds a handle for.
1979define_wire_enum!(FILE_OP_SCHEMA, FileOp {
1980    Read = 1,
1981    Write = 2,
1982    Entries = 3,
1983    Child = 4,
1984});
1985
1986// What a `StorageCall` asks the Renderer to do with the application's storage. Closed: a
1987// Renderer that meets an operation it does not know cannot answer it truthfully.
1988define_wire_enum!(STORAGE_OP_SCHEMA, StorageOp {
1989    Read = 1,
1990    Write = 2,
1991    Remove = 3,
1992    Keys = 4,
1993});
1994
1995// How one input or output request ended, as an `IoAnswer` says it. Shared by storage and by
1996// files picked on the web, so one answer reads the same whichever asked. Closed, so a word
1997// this side does not know is a record the two sides disagree on.
1998define_wire_enum!(IO_STATUS_SCHEMA, IoStatus {
1999    Ok = 1,
2000    NotFound = 2,
2001    QuotaExceeded = 3,
2002    Unavailable = 4,
2003    PermissionDenied = 5,
2004    Failed = 6,
2005    ReadOnly = 7,
2006    TooLarge = 8,
2007});
2008
2009// Where the children of one line of a `FlowRow` sit along it, when they do not fill it.
2010define_wire_enum!(HORIZONTAL_ALIGNMENT_SCHEMA, HorizontalAlignment {
2011    Start = 1,
2012    Center = 2,
2013    End = 3,
2014});
2015
2016// Where a child of a `FlowRow` sits inside the height of its line, when it is shorter
2017// than the tallest child on that line.
2018define_wire_enum!(VERTICAL_ALIGNMENT_SCHEMA, VerticalAlignment {
2019    Top = 1,
2020    Center = 2,
2021    Bottom = 3,
2022});
2023
2024/// What an application may decide about its own window.
2025///
2026/// The window belongs to the Renderer, so this is short and stays short. What is here is
2027/// what an application knows and the Renderer cannot guess: what the window is called and
2028/// how large it should open. Nothing here names a colour or a corner, because those are
2029/// the design system's, and nothing here is read more than once.
2030#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2031pub struct Window {
2032    pub chrome: Chrome,
2033    /// Which of the two title bars this window has.
2034    pub title_bar: TitleBar,
2035    /// What the window calls itself.
2036    ///
2037    /// Empty means the application said nothing, and the renderer uses its own name for
2038    /// it. It is not decoration: a desktop lists windows by this, and a window with no
2039    /// title of its own is listed under whatever the renderer happened to be called.
2040    pub title: &'static str,
2041    /// The picture the window wears, as an asset id, or zero for none.
2042    ///
2043    /// An id rather than a path or a name, because a path is a fact about the machine the
2044    /// application was built on and a name asks the toolkit to find something it may not
2045    /// have. Registering the bytes and referring to them is what every other picture in
2046    /// this protocol does.
2047    pub icon: u32,
2048    /// Zero means the Renderer chooses, which is what an application that said nothing
2049    /// gets. A size is in the same density independent pixels gestures are measured in.
2050    pub width: u16,
2051    pub height: u16,
2052    pub min_width: u16,
2053    pub min_height: u16,
2054    pub resizable: bool,
2055    /// The application's zoom level, where it asked for one.
2056    ///
2057    /// `None` leaves the level to the Renderer, which starts from what the reader chose
2058    /// last time. A level set here is applied, remembered and reported back the way one
2059    /// chosen with the keys is. Kept inside `-8..=8`.
2060    pub zoom_level: Option<i8>,
2061    /// Whether the implicit single window reports every whole-dp change of its size,
2062    /// not only a change of size class. Off by default. Windows made with `Window`
2063    /// nodes opt in through the node's `report_size` property instead.
2064    pub report_size: bool,
2065    /// One window (the default) or several. In the second the root's children are
2066    /// `Window` nodes and the rest of this record describes no window.
2067    pub mode: WindowMode,
2068    /// What to do when the last window goes. Only read in `WindowMode::Windows`.
2069    pub last_window_closed: LastWindowClosed,
2070}
2071
2072impl Window {
2073    pub const fn new() -> Self {
2074        Self {
2075            chrome: Chrome::Modern,
2076            title_bar: TitleBar::Normal,
2077            title: "",
2078            icon: 0,
2079            width: 0,
2080            height: 0,
2081            min_width: 0,
2082            min_height: 0,
2083            resizable: true,
2084            zoom_level: None,
2085            report_size: false,
2086            mode: WindowMode::Single,
2087            last_window_closed: LastWindowClosed::Exit,
2088        }
2089    }
2090
2091    /// Several windows, one per `Window` node under the root. With the default
2092    /// policy of the platform: a macOS application stays up with no window, the others
2093    /// exit.
2094    pub const fn with_windows(mut self) -> Self {
2095        self.mode = WindowMode::Windows;
2096        self.last_window_closed = if cfg!(target_os = "macos") {
2097            LastWindowClosed::KeepRunning
2098        } else {
2099            LastWindowClosed::Exit
2100        };
2101        self
2102    }
2103
2104    /// What happens when the last window is removed. Only meaningful with
2105    /// [`Window::with_windows`].
2106    pub const fn with_last_window_closed(mut self, policy: LastWindowClosed) -> Self {
2107        self.last_window_closed = policy;
2108        self
2109    }
2110
2111    /// Which of the two title bars this window has.
2112    ///
2113    /// `Normal` unless it is said otherwise, because that is the window an application on
2114    /// this platform has now. What the mode is worth in pixels is the design system's, so
2115    /// nothing here is a measurement.
2116    pub const fn with_title_bar(mut self, title_bar: TitleBar) -> Self {
2117        self.title_bar = title_bar;
2118        self
2119    }
2120
2121    /// Names the window. A literal, because this is read once before the window is stood
2122    /// up and never again, so there is nothing for a computed title to change.
2123    pub const fn with_title(mut self, title: &'static str) -> Self {
2124        self.title = title;
2125        self
2126    }
2127
2128    /// Dresses the window in an asset that was registered with [`AssetKind::Png`].
2129    pub const fn with_icon(mut self, asset_id: u32) -> Self {
2130        self.icon = asset_id;
2131        self
2132    }
2133
2134    pub const fn chrome(self, chrome: Chrome) -> Self {
2135        self.with_chrome(chrome)
2136    }
2137
2138    pub const fn with_chrome(mut self, chrome: Chrome) -> Self {
2139        self.chrome = chrome;
2140        self
2141    }
2142
2143    pub const fn with_size(mut self, width: u16, height: u16) -> Self {
2144        self.width = width;
2145        self.height = height;
2146        self
2147    }
2148
2149    pub const fn with_min_size(mut self, width: u16, height: u16) -> Self {
2150        self.min_width = width;
2151        self.min_height = height;
2152        self
2153    }
2154
2155    pub const fn resizable(mut self, resizable: bool) -> Self {
2156        self.resizable = resizable;
2157        self
2158    }
2159
2160    /// Asks the implicit single window to report every whole-dp change of its size.
2161    pub const fn with_report_size(mut self, report: bool) -> Self {
2162        self.report_size = report;
2163        self
2164    }
2165
2166    /// Starts the window at an application zoom level, kept inside `-8..=8`.
2167    pub const fn with_zoom_level(mut self, level: i8) -> Self {
2168        self.zoom_level = Some(if level < -8 {
2169            -8
2170        } else if level > 8 {
2171            8
2172        } else {
2173            level
2174        });
2175        self
2176    }
2177}
2178
2179impl Default for Window {
2180    fn default() -> Self {
2181        Self::new()
2182    }
2183}
2184
2185/// A design system choice plus how it reacts to the host platform.
2186#[derive(Clone, Copy, Debug, Eq, PartialEq)]
2187pub struct Theme {
2188    pub design_system: DesignSystem,
2189    pub fallback: DesignSystem,
2190    pub color_scheme: ColorScheme,
2191    pub adaptive: bool,
2192    /// The font asset each type role resolves to, or zero for the system font.
2193    ///
2194    /// Per theme and not per node. A node that could name its own font would be a node
2195    /// deciding typography, and the whole point of roles is that it does not: an
2196    /// application changes what `Display` is made of, and every title changes with it.
2197    ///
2198    /// Indexed by the role's wire tag minus one, so the array and the enum cannot drift
2199    /// apart without the compiler saying so.
2200    pub fonts: [u32; TYPE_ROLE_COUNT],
2201    /// The application's own colours, laid over whichever design system is chosen.
2202    ///
2203    /// A reference to something that lives for the whole program, so that a theme stays
2204    /// `Copy` and can still be built in a `const`. The same palette goes onto every system
2205    /// an adaptive theme may pick, because a brand colour does not change with the
2206    /// platform. A palette built while the application runs is handed to `use_theme`,
2207    /// which owns it, so application code never has to give it that lifetime itself.
2208    pub palette: Option<&'static crate::palette::Palette>,
2209    /// Application-level overlay theme tokens for Dialog, Menu, Dropdown, and Sheet.
2210    pub overlay: Option<&'static OverlayTokens>,
2211}
2212
2213/// How many type roles there are, which is how many font slots a theme carries.
2214pub const TYPE_ROLE_COUNT: usize = 9;
2215
2216/// Application-level overlay theme tokens for Dialog, Menu, Dropdown, Sheet and the
2217/// transient message. Every measure is in dp, and 0 keeps the design system's own.
2218#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
2219pub struct OverlayTokens {
2220    pub sheet_corner_radius: u16,
2221    pub dialog_corner_radius: u16,
2222    pub popup_corner_radius: u16,
2223    pub sheet_elevation: u16,
2224    pub popup_elevation: u16,
2225    pub dialog_elevation: u16,
2226    pub sheet_padding: u16,
2227    pub dialog_padding: u16,
2228    pub popup_padding: u16,
2229    pub scrim: u32,
2230    /// How high the transient message floats, which is how much shadow it casts.
2231    pub toast_elevation: u16,
2232    /// The corner radius of the transient message.
2233    pub toast_corner_radius: u16,
2234    /// The transient message's fill in the light scheme, as ARGB; 0 keeps the design system's.
2235    pub toast_container_light: u32,
2236    /// The transient message's fill in the dark scheme, as ARGB; 0 keeps the design system's.
2237    pub toast_container_dark: u32,
2238    /// The transient message's text in the light scheme, as ARGB; 0 keeps the design system's.
2239    pub toast_content_light: u32,
2240    /// The transient message's text in the dark scheme, as ARGB; 0 keeps the design system's.
2241    pub toast_content_dark: u32,
2242    /// The width of the line around the transient message in dp. `None` keeps the design
2243    /// system's line, and `Some(0)` draws none.
2244    pub toast_border_width: Option<u16>,
2245    /// The space left and right of the transient message's text, in dp.
2246    pub toast_padding_horizontal: u16,
2247    /// The space above and below the transient message's text, in dp.
2248    pub toast_padding_vertical: u16,
2249    /// The size of the transient message's text, in sp.
2250    pub toast_font_size: u16,
2251    /// The line height of the transient message's text, in sp.
2252    pub toast_line_height: u16,
2253}
2254
2255impl OverlayTokens {
2256    pub const fn new() -> Self {
2257        Self {
2258            sheet_corner_radius: 0,
2259            dialog_corner_radius: 0,
2260            popup_corner_radius: 0,
2261            sheet_elevation: 0,
2262            popup_elevation: 0,
2263            dialog_elevation: 0,
2264            sheet_padding: 0,
2265            dialog_padding: 0,
2266            popup_padding: 0,
2267            scrim: 0,
2268            toast_elevation: 0,
2269            toast_corner_radius: 0,
2270            toast_container_light: 0,
2271            toast_container_dark: 0,
2272            toast_content_light: 0,
2273            toast_content_dark: 0,
2274            toast_border_width: None,
2275            toast_padding_horizontal: 0,
2276            toast_padding_vertical: 0,
2277            toast_font_size: 0,
2278            toast_line_height: 0,
2279        }
2280    }
2281
2282    pub const fn sheet_corner_radius(mut self, radius: u16) -> Self {
2283        self.sheet_corner_radius = radius;
2284        self
2285    }
2286
2287    pub const fn dialog_corner_radius(mut self, radius: u16) -> Self {
2288        self.dialog_corner_radius = radius;
2289        self
2290    }
2291
2292    pub const fn popup_corner_radius(mut self, radius: u16) -> Self {
2293        self.popup_corner_radius = radius;
2294        self
2295    }
2296
2297    pub const fn sheet_elevation(mut self, elevation: u16) -> Self {
2298        self.sheet_elevation = elevation;
2299        self
2300    }
2301
2302    pub const fn popup_elevation(mut self, elevation: u16) -> Self {
2303        self.popup_elevation = elevation;
2304        self
2305    }
2306
2307    pub const fn dialog_elevation(mut self, elevation: u16) -> Self {
2308        self.dialog_elevation = elevation;
2309        self
2310    }
2311
2312    pub const fn sheet_padding(mut self, padding: u16) -> Self {
2313        self.sheet_padding = padding;
2314        self
2315    }
2316
2317    pub const fn dialog_padding(mut self, padding: u16) -> Self {
2318        self.dialog_padding = padding;
2319        self
2320    }
2321
2322    pub const fn popup_padding(mut self, padding: u16) -> Self {
2323        self.popup_padding = padding;
2324        self
2325    }
2326
2327    pub const fn scrim(mut self, color: Color) -> Self {
2328        self.scrim = color.to_argb();
2329        self
2330    }
2331
2332    pub const fn scrim_argb(mut self, argb: u32) -> Self {
2333        self.scrim = argb;
2334        self
2335    }
2336
2337    /// The transient message's elevation in dp: a shadow under it the height of a surface
2338    /// that far up. A message is not a node and takes no Modifier, so this is where its
2339    /// shadow is set, once for the application.
2340    pub const fn toast_elevation(mut self, elevation: u16) -> Self {
2341        self.toast_elevation = elevation;
2342        self
2343    }
2344
2345    /// The transient message's corner radius in dp.
2346    pub const fn toast_corner_radius(mut self, radius: u16) -> Self {
2347        self.toast_corner_radius = radius;
2348        self
2349    }
2350
2351    /// The transient message's fill, one colour for the light scheme and one for the dark.
2352    /// The renderer takes the one for the scheme it is drawing in, so a message can be
2353    /// drawn inverted (dark on a light page, light on a dark one).
2354    pub const fn toast_container(mut self, light: Color, dark: Color) -> Self {
2355        self.toast_container_light = light.to_argb();
2356        self.toast_container_dark = dark.to_argb();
2357        self
2358    }
2359
2360    /// The transient message's text colour for the light scheme and for the dark.
2361    pub const fn toast_content(mut self, light: Color, dark: Color) -> Self {
2362        self.toast_content_light = light.to_argb();
2363        self.toast_content_dark = dark.to_argb();
2364        self
2365    }
2366
2367    /// The width of the line around the transient message in dp; 0 draws none.
2368    pub const fn toast_border_width(mut self, width: u16) -> Self {
2369        self.toast_border_width = Some(width);
2370        self
2371    }
2372
2373    /// The space around the transient message's text in dp: left and right, then above and
2374    /// below.
2375    pub const fn toast_padding(mut self, horizontal: u16, vertical: u16) -> Self {
2376        self.toast_padding_horizontal = horizontal;
2377        self.toast_padding_vertical = vertical;
2378        self
2379    }
2380
2381    /// The transient message's text size and line height in sp.
2382    pub const fn toast_type(mut self, font_size: u16, line_height: u16) -> Self {
2383        self.toast_font_size = font_size;
2384        self.toast_line_height = line_height;
2385        self
2386    }
2387}
2388
2389impl Theme {
2390    /// The same design system on every platform.
2391    pub const fn unified(design_system: DesignSystem) -> Self {
2392        Self {
2393            design_system,
2394            fallback: design_system,
2395            color_scheme: ColorScheme::FollowSystem,
2396            adaptive: false,
2397            fonts: [0; TYPE_ROLE_COUNT],
2398            palette: None,
2399            overlay: None,
2400        }
2401    }
2402
2403    /// Follows the host platform. The fallback is required, so no platform is left undecided.
2404    pub const fn adaptive(fallback: DesignSystem) -> Self {
2405        Self {
2406            design_system: fallback,
2407            fallback,
2408            color_scheme: ColorScheme::FollowSystem,
2409            adaptive: true,
2410            fonts: [0; TYPE_ROLE_COUNT],
2411            palette: None,
2412            overlay: None,
2413        }
2414    }
2415
2416    pub const fn with_color_scheme(mut self, color_scheme: ColorScheme) -> Self {
2417        self.color_scheme = color_scheme;
2418        self
2419    }
2420
2421    /// Resolves one type role to a registered font, leaving every other role alone.
2422    ///
2423    /// The asset has to be registered before the theme that names it reaches the
2424    /// Renderer, the same way a picture does. An id that names nothing is reported and
2425    /// the role falls back to the system font, because a screen in the wrong typeface is
2426    /// better than no screen.
2427    ///
2428    /// `TypeRole::None` has no font slot: text with no role names its own font, so asking
2429    /// the theme to give it one changes nothing.
2430    pub const fn with_font(mut self, role: TypeRole, asset: u32) -> Self {
2431        if let TypeRole::None = role {
2432            return self;
2433        }
2434        self.fonts[role as usize - 1] = asset;
2435        self
2436    }
2437
2438    /// Resolves every type role but `Mono` to one registered font: the application's own
2439    /// typeface, set once for the whole screen.
2440    ///
2441    /// The font is usually a [`crate::FontStack`], so a role is set in the first family and
2442    /// each letter it lacks comes from the next, with the machine's fonts after the last.
2443    /// `Mono` is left alone because code set in a proportional face is columns that no
2444    /// longer line up; name a font for it with [`Theme::with_font`]. A role named before or
2445    /// after this with `with_font` keeps whichever was said last.
2446    pub const fn with_default_font(mut self, asset: u32) -> Self {
2447        let mut index = 0;
2448        while index < TYPE_ROLE_COUNT {
2449            if index != TypeRole::Mono as usize - 1 {
2450                self.fonts[index] = asset;
2451            }
2452            index += 1;
2453        }
2454        self
2455    }
2456
2457    /// Lays the application's own colours over the design system.
2458    ///
2459    /// Only colour roles change. Shape, type, spacing, elevation, motion and how each
2460    /// component is drawn stay the design system's, so the same brand colour reads as
2461    /// that system's button rather than as a copy of another's. Both schemes go to the
2462    /// Renderer at once, so a switch between light and dark never asks the Host.
2463    pub const fn with_palette(mut self, palette: &'static crate::palette::Palette) -> Self {
2464        self.palette = Some(palette);
2465        self
2466    }
2467
2468    /// Overrides overlay geometry, spacing, elevation and scrim for Dialog, Menu, Dropdown and Sheet.
2469    pub const fn with_overlay_tokens(mut self, overlay: &'static OverlayTokens) -> Self {
2470        self.overlay = Some(overlay);
2471        self
2472    }
2473
2474    /// The font this role resolves to, or `None` for the system font.
2475    pub const fn font(&self, role: TypeRole) -> Option<u32> {
2476        if let TypeRole::None = role {
2477            return None;
2478        }
2479        match self.fonts[role as usize - 1] {
2480            0 => None,
2481            asset => Some(asset),
2482        }
2483    }
2484}
2485
2486/// Saying nothing follows the host platform, with Material 3 where the platform has no look
2487/// of its own. The default used to be `unified(Material3)`, on the theory that a default
2488/// looking the same everywhere is more predictable. In practice that meant macOS showed a
2489/// Material screen with no configuration, which is the wrong first impression for a toolkit
2490/// that claims native desktop UI, and it meant nothing on the default path ever exercised
2491/// platform adaptation. A default that can be broken without anyone noticing is not
2492/// predictability. An application that wants one design system everywhere says
2493/// `Theme::unified(..)`, which is a clearer statement of that intent than silence was.
2494impl Default for Theme {
2495    fn default() -> Self {
2496        Self::adaptive(DesignSystem::Material3)
2497    }
2498}
2499
2500#[derive(Clone, Debug, PartialEq)]
2501pub enum Modifier {
2502    Empty,
2503    Padding(f32),
2504    FillMaxWidth,
2505    FillMaxHeight,
2506    Width(f32),
2507    Height(f32),
2508    Size {
2509        width: f32,
2510        height: f32,
2511    },
2512    /// A `Paint`, not a raw ARGB. Colour has exactly one wire representation.
2513    Background(Paint),
2514    Clickable {
2515        handler_id: u64,
2516    },
2517    PaddingRole(SpaceRole),
2518    PaddingEach {
2519        start: f32,
2520        top: f32,
2521        end: f32,
2522        bottom: f32,
2523    },
2524    Weight(f32),
2525    Shape {
2526        top_start: f32,
2527        top_end: f32,
2528        bottom_end: f32,
2529        bottom_start: f32,
2530    },
2531    ShapeRole(ShapeRole),
2532    Border {
2533        width: f32,
2534        paint: Paint,
2535    },
2536    /// One dp value. How the shadow is drawn is the design system's rule: tonal lift plus a
2537    /// shadow, a wide soft shadow, or layered shadow plus a hairline stroke.
2538    Elevation(f32),
2539    /// Asks the Renderer to report this node's measured size, the way it reports the
2540    /// window's.
2541    ///
2542    /// The token is the application's own name for the node. A node id belongs to the
2543    /// Renderer and is never something the Host chose, so a screen that wants to know how
2544    /// wide one of its own containers ended up needs a name it gave itself. The Renderer
2545    /// does not read it.
2546    ///
2547    /// With `every_dp` off, a report goes out on the first measurement and then only when
2548    /// the node's width or height class changes. With it on, a report also goes out when
2549    /// the width or height, rounded to the nearest whole dp, changes inside one class, at
2550    /// most once a frame and carrying the last size. It rides in the second word, which
2551    /// was always zero before, so a record with it off is the same bytes it always was.
2552    ObserveSize {
2553        token: u32,
2554        every_dp: bool,
2555    },
2556    /// Which curve and length this node's changes run along.
2557    ///
2558    /// The node says how important the change is, not how long it takes. Appearing,
2559    /// disappearing, a selection moving and a size changing all read this.
2560    Motion(MotionRole),
2561    /// What this node's surface is made of.
2562    ///
2563    /// A role, so that a system which blurs blurs and a system which does not lifts its
2564    /// surface instead. Nothing here claims a particular effect was achieved.
2565    Material(MaterialRole),
2566    /// Where this node sits inside its parent, in dp from the parent's top left corner.
2567    ///
2568    /// The position a layout engine on the Host already computed. Left and right are the
2569    /// screen's, not the reading direction's: the Host's coordinates are physical, so a
2570    /// right-to-left page is not mirrored a second time here.
2571    Offset {
2572        x: f32,
2573        y: f32,
2574    },
2575    /// This node's size in dp, whatever its parent's constraints say. The size a layout
2576    /// engine on the Host already computed, which is not open to negotiation.
2577    RequiredSize {
2578        width: f32,
2579        height: f32,
2580    },
2581    /// A border whose four sides each have their own width and paint. A node whose four
2582    /// sides are the same uses `Border`.
2583    BorderEach {
2584        top: f32,
2585        right: f32,
2586        bottom: f32,
2587        left: f32,
2588        top_paint: Paint,
2589        right_paint: Paint,
2590        bottom_paint: Paint,
2591        left_paint: Paint,
2592    },
2593    /// A radius in dp for each corner, cut as plain circular arcs. The background, the
2594    /// border, the shadow and a `Clip` all follow it. A node with one radius for every
2595    /// corner uses `Shape`.
2596    CornerEach {
2597        top_left: f32,
2598        top_right: f32,
2599        bottom_right: f32,
2600        bottom_left: f32,
2601    },
2602    /// One shadow cast by this node's outline: an offset, a blur radius and a spread in dp,
2603    /// and its paint, drawn only outside the node as CSS draws `box-shadow`. Several
2604    /// shadows are several of these. A modifier list draws in its order, so a later shadow
2605    /// lies over an earlier one; CSS puts the first of its list on top, so a Host sends
2606    /// that list last to first.
2607    Shadow {
2608        x: f32,
2609        y: f32,
2610        blur: f32,
2611        spread: f32,
2612        paint: Paint,
2613    },
2614    /// Whether this node's content is cut to its outline: the `CornerEach` shape where it
2615    /// has one, its rectangle otherwise.
2616    Clip(bool),
2617    /// Marks this node as a window drag region or excludes it from one.
2618    WindowDrag(bool),
2619    /// The opacity of this node and everything in it, from 0 to 1, applied once to the
2620    /// whole group rather than to each child.
2621    Alpha(f32),
2622    /// Draws this node and everything in it through a 2D affine matrix, the way CSS
2623    /// `transform` does, without changing its layout. Pointer input follows the drawn
2624    /// shape.
2625    ///
2626    /// The matrix means what CSS `matrix(a, b, c, d, e, f)` means: a point `(x, y)` goes to
2627    /// `(a x + c y + e, b x + d y + f)`, with `e` and `f` in dp. The origin is a fraction of
2628    /// the node's measured size, `(0.5, 0.5)` being its centre, so it stays right when the
2629    /// size is decided on the Renderer's side. An origin given as a length is folded into
2630    /// the matrix by the Host, which then sends `(0, 0)`. A matrix with no inverse draws
2631    /// nothing and takes no input. No value may be NaN or infinite.
2632    Transform {
2633        a: f32,
2634        b: f32,
2635        c: f32,
2636        d: f32,
2637        e: f32,
2638        f: f32,
2639        origin_x: f32,
2640        origin_y: f32,
2641    },
2642    /// Draws this node and everything in it through a 4x4 matrix, the way CSS 3D
2643    /// `transform` does, without changing its layout. Pointer input follows the drawn
2644    /// shape.
2645    ///
2646    /// `m` is column-major, in the order of CSS `matrix3d(...)`: element `m[4 * column +
2647    /// row]`. A point `(x, y, z, 1)` goes to `M * (x, y, z, 1)`, and the screen position is
2648    /// the first two results divided by the fourth. Translations are in dp. A perspective
2649    /// term is already inside the matrix, so the Renderer is never sent one separately. The
2650    /// origin means what it means for [`Modifier::Transform`] and its z is zero.
2651    ///
2652    /// `backface_hidden` is CSS `backface-visibility: hidden`: a node whose back is turned
2653    /// to the viewer is not drawn and takes no input. A matrix with no inverse draws
2654    /// nothing. No value may be NaN or infinite.
2655    Transform3D {
2656        m: [f32; 16],
2657        origin_x: f32,
2658        origin_y: f32,
2659        backface_hidden: bool,
2660    },
2661    /// Matches the bounds of a Box parent without contributing to its size.
2662    MatchParentSize,
2663    /// Controls the scale and tint of a pressed surface.
2664    PressFeedback {
2665        scale: f32,
2666        tint_alpha: f32,
2667    },
2668    /// What this node is to assistive technology: its role, and whether it is checked or
2669    /// selected. `state` holds two tri-state fields, `SEMANTICS_CHECKED_SHIFT` and
2670    /// `SEMANTICS_SELECTED_SHIFT` bits up, each 0 for unset, 1 for off and 2 for on. The
2671    /// accessible name is the `AccessibleName` property, because a string does not fit in
2672    /// a modifier's words. Above those, `expanded`, `disabled` and `focused` are tri-state
2673    /// fields in the same encoding, `SEMANTICS_HIDDEN_BIT` leaves the node out of the
2674    /// accessibility tree, the two action bits expose a click and a focus action, and
2675    /// `SEMANTICS_HAS_POPUP_BIT` says the node opens a popup.
2676    Semantics {
2677        role: SemanticsRole,
2678        state: u32,
2679    },
2680    /// How this node's rounded corners curve, from 0 to 1. 0 is a plain circular arc; above
2681    /// it the curve starts further along each side and its curvature changes continuously,
2682    /// as Figma's corner smoothing does (0.6 is what iOS looks like). The radius still
2683    /// comes from `Shape`, `ShapeRole` or `CornerEach`; this changes only the curve, and
2684    /// a node without a radius is not changed. A value outside 0..=1 is drawn as the nearer
2685    /// end and NaN as 0, so one bad shape cannot stop the program; see
2686    /// [`corner_smoothing`].
2687    CornerCurve {
2688        smoothing: f32,
2689    },
2690    /// A brush laid into a rectangle of this node and repeated across it, the way CSS
2691    /// draws one `background-image` layer with its `background-position`,
2692    /// `background-size` and `background-repeat`.
2693    ///
2694    /// `x`, `y`, `width` and `height` are the rectangle in dp from the node's top left
2695    /// corner, which is one tile: a gradient is measured against it, not against the node.
2696    /// `repeat` says which ways the tile repeats and `tile_width` and `tile_height` how far
2697    /// apart the copies are, in dp; a plain CSS repeat sends the rectangle's own size, and
2698    /// `space` or `round` the step the Host worked out. The layer is cut to the node's
2699    /// outline, its corners included. Several layers are several of these, the first
2700    /// drawn at the bottom, so a Host sends a CSS list last to first. A tile width or
2701    /// height of zero or less, and any value that is not a finite number, is refused.
2702    BackgroundBrush {
2703        x: f32,
2704        y: f32,
2705        width: f32,
2706        height: f32,
2707        paint: Paint,
2708        repeat: BackgroundRepeat,
2709        tile_width: f32,
2710        tile_height: f32,
2711    },
2712    /// Constrains the layout size between minimum and maximum bounds in dp.
2713    /// Unconstrained bounds are `f32::NAN`.
2714    SizeIn {
2715        min_width: f32,
2716        max_width: f32,
2717        min_height: f32,
2718        max_height: f32,
2719    },
2720    /// Attempts to size content to match an aspect ratio (width / height).
2721    AspectRatio {
2722        ratio: f32,
2723        match_height_constraints_first: bool,
2724    },
2725    /// The least size, in dp, of the area that takes this node's presses. A node drawn
2726    /// smaller takes presses over a box grown to this size around it, centred on it; its
2727    /// size, its place and how it is drawn do not change, so neither does anything laid out
2728    /// beside it. A node already this large is not changed.
2729    MinTouchTarget {
2730        size: f32,
2731    },
2732    /// A paint laid over the node, over its content and its background, in the outline its
2733    /// background fills: the box the node is drawn in, cut to the same corners (`Shape`,
2734    /// `ShapeRole` or `CornerEach`, curved as `CornerCurve` says). It takes no room, so a
2735    /// node sized by its content stays the size it was. A press tint or a selection wash is
2736    /// one of these.
2737    Overlay(Paint),
2738    /// Pins a child to the start edge of a scrolling container (such as ScrollRow)
2739    /// while the rest of the content scrolls.
2740    Sticky,
2741    /// Measures the node with no maximum width, so `ObserveSize` reports the width its
2742    /// content asks for. The node still takes the width its parent offered, and what is
2743    /// wider than that is clipped.
2744    UnboundedWidth,
2745}
2746
2747/// The smoothing a `CornerCurve` value draws with: clamped to 0..=1, NaN as 0.
2748pub fn corner_smoothing(smoothing: f32) -> f32 {
2749    if smoothing.is_nan() {
2750        0.0
2751    } else {
2752        smoothing.clamp(0.0, 1.0)
2753    }
2754}
2755
2756/// Where the checked field sits in `Modifier::Semantics::state`.
2757pub const SEMANTICS_CHECKED_SHIFT: u32 = 0;
2758/// Where the selected field sits in `Modifier::Semantics::state`.
2759pub const SEMANTICS_SELECTED_SHIFT: u32 = 2;
2760/// Where the expanded field sits in `Modifier::Semantics::state`: 0 unset, 1 collapsed,
2761/// 2 expanded.
2762pub const SEMANTICS_EXPANDED_SHIFT: u32 = 4;
2763/// Where the disabled field sits in `Modifier::Semantics::state`: 0 unset, 1 enabled,
2764/// 2 disabled.
2765pub const SEMANTICS_DISABLED_SHIFT: u32 = 6;
2766/// Where the focused field sits in `Modifier::Semantics::state`: 0 unset, 1 not focused,
2767/// 2 focused.
2768pub const SEMANTICS_FOCUSED_SHIFT: u32 = 8;
2769/// The bit that excludes the node from the accessibility tree.
2770pub const SEMANTICS_HIDDEN_BIT: u32 = 1 << 10;
2771/// The bit that exposes a click action on the node.
2772pub const SEMANTICS_CLICK_ACTION_BIT: u32 = 1 << 11;
2773/// The bit that exposes a focus action on the node.
2774pub const SEMANTICS_FOCUS_ACTION_BIT: u32 = 1 << 12;
2775/// The bit that says the node opens a popup.
2776pub const SEMANTICS_HAS_POPUP_BIT: u32 = 1 << 13;
2777/// Every bit `Modifier::Semantics::state` may set.
2778pub const SEMANTICS_STATE_MASK: u32 = 0b11_1111_1111_1111;
2779
2780impl Modifier {
2781    /// A border with a width and a paint for each side, in CSS order: top, right, bottom,
2782    /// left.
2783    ///
2784    /// Four equal sides are one `Border`, which is the record every node with an ordinary
2785    /// border already sends. `BorderEach` is written only where the sides differ, so a
2786    /// screen that never mixes them never sends the longer record.
2787    pub fn border_sides(widths: [f32; 4], paints: [Paint; 4]) -> Self {
2788        let [top, right, bottom, left] = widths;
2789        let [top_paint, right_paint, bottom_paint, left_paint] = paints;
2790        if widths.iter().all(|width| width.to_bits() == top.to_bits())
2791            && paints.iter().all(|paint| *paint == top_paint)
2792        {
2793            return Self::Border {
2794                width: top,
2795                paint: top_paint,
2796            };
2797        }
2798        Self::BorderEach {
2799            top,
2800            right,
2801            bottom,
2802            left,
2803            top_paint,
2804            right_paint,
2805            bottom_paint,
2806            left_paint,
2807        }
2808    }
2809
2810    /// A radius for each corner, in CSS order: top left, top right, bottom right, bottom
2811    /// left.
2812    ///
2813    /// One radius for every corner is one `Shape`, the record an ordinary rounded node
2814    /// already sends. `CornerEach` is written only where the corners differ.
2815    pub fn corner_radii(radii: [f32; 4]) -> Self {
2816        let [top_left, top_right, bottom_right, bottom_left] = radii;
2817        if radii
2818            .iter()
2819            .all(|radius| radius.to_bits() == top_left.to_bits())
2820        {
2821            return Self::Shape {
2822                top_start: top_left,
2823                top_end: top_left,
2824                bottom_end: top_left,
2825                bottom_start: top_left,
2826            };
2827        }
2828        Self::CornerEach {
2829            top_left,
2830            top_right,
2831            bottom_right,
2832            bottom_left,
2833        }
2834    }
2835}
2836
2837/// The timing function of one keyframe, which shapes the segment to the next one.
2838#[derive(Clone, Copy, Debug, PartialEq)]
2839pub enum Timing {
2840    Linear,
2841    /// CSS `cubic-bezier(x1, y1, x2, y2)`. Both `x` values are between 0 and 1.
2842    CubicBezier {
2843        x1: f32,
2844        y1: f32,
2845        x2: f32,
2846        y2: f32,
2847    },
2848    /// CSS `steps(count, position)`. `count` is at least 1, and at least 2 for `JumpNone`.
2849    Steps {
2850        count: u32,
2851        position: StepPosition,
2852    },
2853}
2854
2855/// One CSS transform function: its kind and up to six values, the unused ones zero.
2856///
2857/// `Translate` is x and y in dp, `Rotate` degrees (not folded into one turn, so 0 to 720
2858/// is two turns), `Scale` x and y, `Skew` the x and y angles in degrees, and `Matrix` the
2859/// six values of CSS `matrix()`.
2860#[derive(Clone, Copy, Debug, PartialEq)]
2861pub struct TransformFunction {
2862    pub kind: TransformFunctionKind,
2863    pub values: [f32; 6],
2864}
2865
2866impl TransformFunction {
2867    pub const fn translate(x: f32, y: f32) -> Self {
2868        Self {
2869            kind: TransformFunctionKind::Translate,
2870            values: [x, y, 0.0, 0.0, 0.0, 0.0],
2871        }
2872    }
2873
2874    pub const fn rotate(degrees: f32) -> Self {
2875        Self {
2876            kind: TransformFunctionKind::Rotate,
2877            values: [degrees, 0.0, 0.0, 0.0, 0.0, 0.0],
2878        }
2879    }
2880
2881    pub const fn scale(x: f32, y: f32) -> Self {
2882        Self {
2883            kind: TransformFunctionKind::Scale,
2884            values: [x, y, 0.0, 0.0, 0.0, 0.0],
2885        }
2886    }
2887
2888    pub const fn skew(x_degrees: f32, y_degrees: f32) -> Self {
2889        Self {
2890            kind: TransformFunctionKind::Skew,
2891            values: [x_degrees, y_degrees, 0.0, 0.0, 0.0, 0.0],
2892        }
2893    }
2894
2895    pub const fn matrix(a: f32, b: f32, c: f32, d: f32, e: f32, f: f32) -> Self {
2896        Self {
2897            kind: TransformFunctionKind::Matrix,
2898            values: [a, b, c, d, e, f],
2899        }
2900    }
2901}
2902
2903/// What one keyframe holds, which has to be what its animation's property takes.
2904#[derive(Clone, Debug, PartialEq)]
2905pub enum KeyframeValue {
2906    Alpha(f32),
2907    /// For `Color`, `Background` and `BorderColor`. A role is resolved against the theme every frame.
2908    Paint(Paint),
2909    /// A list of functions, the same kinds in the same order in every keyframe.
2910    Transform(std::borrow::Cow<'static, [TransformFunction]>),
2911}
2912
2913#[derive(Clone, Debug, PartialEq)]
2914pub struct Keyframe {
2915    /// Where in an iteration this keyframe stands, from 0 to 1.
2916    pub offset: f32,
2917    /// How the segment from this keyframe to the next is timed.
2918    pub timing: Timing,
2919    /// Starts from whatever the node shows the frame this animation begins, instead of
2920    /// `value`. Only the first keyframe may say so: it is how a CSS transition that
2921    /// changes course midway carries on from where it was without a jump.
2922    pub from_presented: bool,
2923    pub value: KeyframeValue,
2924}
2925
2926/// Which moments of an animation are reported back as `AnimationEvent`s. None, the
2927/// default, means the animation plays to its end without a single call to the Host.
2928#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
2929pub struct AnimationEvents(pub u8);
2930
2931impl AnimationEvents {
2932    pub const NONE: Self = Self(0);
2933    pub const READY: Self = Self(1);
2934    pub const ACTIVE: Self = Self(2);
2935    pub const ITERATION: Self = Self(4);
2936    pub const END: Self = Self(8);
2937    /// Every kind there is. A bit outside these is a record the sides disagree about.
2938    pub const ALL: Self = Self(1 | 2 | 4 | 8);
2939
2940    pub const fn union(self, other: Self) -> Self {
2941        Self(self.0 | other.0)
2942    }
2943
2944    pub const fn contains(self, other: Self) -> bool {
2945        self.0 & other.0 == other.0
2946    }
2947}
2948
2949/// One animation the Renderer plays to its end on its own frame clock, described once.
2950///
2951/// The key is `(node_id, property, slot)`: a second animation with the same key replaces
2952/// the first, and of the ones in effect on one property the highest slot is what shows.
2953/// Timing follows Web Animations Level 1, which is what CSS transitions and animations
2954/// are defined by.
2955#[derive(Clone, Debug, PartialEq)]
2956pub struct Animation<'a> {
2957    pub node_id: u32,
2958    /// The Host's own name for the animation, returned in every event about it.
2959    pub animation_id: u32,
2960    pub property: AnimatedProperty,
2961    pub slot: u8,
2962    pub direction: PlaybackDirection,
2963    pub fill: FillMode,
2964    pub play_state: PlayState,
2965    /// For `Color`, `Background` and `BorderColor` only, and required there.
2966    pub interpolation: Option<ColorInterpolation>,
2967    /// On the Renderer's frame clock. Zero starts it on the first frame that draws it.
2968    pub start_time_nanos: u64,
2969    /// May be negative, which starts it partway through.
2970    pub delay_ms: f32,
2971    pub duration_ms: f32,
2972    /// Infinite for `infinite`.
2973    pub iterations: f32,
2974    /// For `Transform` only: the origin, as a fraction of the node's size.
2975    pub origin_x: f32,
2976    pub origin_y: f32,
2977    pub events: AnimationEvents,
2978    /// At least two, the first at offset 0 and the last at 1.
2979    pub keyframes: std::borrow::Cow<'a, [Keyframe]>,
2980}
2981
2982const NO_FIELDS: &[FieldSchema] = &[];
2983const OBSERVE_SIZE_FIELDS: &[FieldSchema] = &[
2984    FieldSchema {
2985        name: "token",
2986        ty: FieldType::U32,
2987        slot: FieldSlot::FirstLow,
2988    },
2989    FieldSchema {
2990        name: "everyDp",
2991        ty: FieldType::Bool,
2992        slot: FieldSlot::Second,
2993    },
2994];
2995const VALUE_FLOAT_FIELD: &[FieldSchema] = &[FieldSchema {
2996    name: "value",
2997    ty: FieldType::Float,
2998    slot: FieldSlot::FirstLow,
2999}];
3000const SIZE_FIELDS: &[FieldSchema] = &[
3001    FieldSchema {
3002        name: "width",
3003        ty: FieldType::Float,
3004        slot: FieldSlot::FirstLow,
3005    },
3006    FieldSchema {
3007        name: "height",
3008        ty: FieldType::Float,
3009        slot: FieldSlot::SecondLow,
3010    },
3011];
3012const PAINT_FIELD: &[FieldSchema] = &[FieldSchema {
3013    name: "paint",
3014    ty: FieldType::Paint,
3015    slot: FieldSlot::First,
3016}];
3017const HANDLER_ID_FIELD: &[FieldSchema] = &[FieldSchema {
3018    name: "handlerId",
3019    ty: FieldType::U64,
3020    slot: FieldSlot::First,
3021}];
3022const SPACE_ROLE_FIELD: &[FieldSchema] = &[FieldSchema {
3023    name: "role",
3024    ty: FieldType::Role("SpaceRole"),
3025    slot: FieldSlot::FirstLow,
3026}];
3027const SHAPE_ROLE_FIELD: &[FieldSchema] = &[FieldSchema {
3028    name: "role",
3029    ty: FieldType::Role("ShapeRole"),
3030    slot: FieldSlot::FirstLow,
3031}];
3032const MOTION_ROLE_FIELD: &[FieldSchema] = &[FieldSchema {
3033    name: "role",
3034    ty: FieldType::Role("MotionRole"),
3035    slot: FieldSlot::FirstLow,
3036}];
3037const MATERIAL_ROLE_FIELD: &[FieldSchema] = &[FieldSchema {
3038    name: "role",
3039    ty: FieldType::Role("MaterialRole"),
3040    slot: FieldSlot::FirstLow,
3041}];
3042const PADDING_EACH_FIELDS: &[FieldSchema] = &[
3043    FieldSchema {
3044        name: "start",
3045        ty: FieldType::Float,
3046        slot: FieldSlot::FirstLow,
3047    },
3048    FieldSchema {
3049        name: "top",
3050        ty: FieldType::Float,
3051        slot: FieldSlot::FirstHigh,
3052    },
3053    FieldSchema {
3054        name: "end",
3055        ty: FieldType::Float,
3056        slot: FieldSlot::SecondLow,
3057    },
3058    FieldSchema {
3059        name: "bottom",
3060        ty: FieldType::Float,
3061        slot: FieldSlot::SecondHigh,
3062    },
3063];
3064const SHAPE_FIELDS: &[FieldSchema] = &[
3065    FieldSchema {
3066        name: "topStart",
3067        ty: FieldType::Float,
3068        slot: FieldSlot::FirstLow,
3069    },
3070    FieldSchema {
3071        name: "topEnd",
3072        ty: FieldType::Float,
3073        slot: FieldSlot::FirstHigh,
3074    },
3075    FieldSchema {
3076        name: "bottomEnd",
3077        ty: FieldType::Float,
3078        slot: FieldSlot::SecondLow,
3079    },
3080    FieldSchema {
3081        name: "bottomStart",
3082        ty: FieldType::Float,
3083        slot: FieldSlot::SecondHigh,
3084    },
3085];
3086const BORDER_FIELDS: &[FieldSchema] = &[
3087    FieldSchema {
3088        name: "width",
3089        ty: FieldType::Float,
3090        slot: FieldSlot::FirstLow,
3091    },
3092    FieldSchema {
3093        name: "paint",
3094        ty: FieldType::Paint,
3095        slot: FieldSlot::Second,
3096    },
3097];
3098const OFFSET_FIELDS: &[FieldSchema] = &[
3099    FieldSchema {
3100        name: "x",
3101        ty: FieldType::Float,
3102        slot: FieldSlot::FirstLow,
3103    },
3104    FieldSchema {
3105        name: "y",
3106        ty: FieldType::Float,
3107        slot: FieldSlot::SecondLow,
3108    },
3109];
3110const BORDER_EACH_FIELDS: &[FieldSchema] = &[
3111    FieldSchema {
3112        name: "top",
3113        ty: FieldType::Float,
3114        slot: FieldSlot::FirstLow,
3115    },
3116    FieldSchema {
3117        name: "right",
3118        ty: FieldType::Float,
3119        slot: FieldSlot::FirstHigh,
3120    },
3121    FieldSchema {
3122        name: "bottom",
3123        ty: FieldType::Float,
3124        slot: FieldSlot::SecondLow,
3125    },
3126    FieldSchema {
3127        name: "left",
3128        ty: FieldType::Float,
3129        slot: FieldSlot::SecondHigh,
3130    },
3131    FieldSchema {
3132        name: "topPaint",
3133        ty: FieldType::Paint,
3134        slot: FieldSlot::Third,
3135    },
3136    FieldSchema {
3137        name: "rightPaint",
3138        ty: FieldType::Paint,
3139        slot: FieldSlot::Fourth,
3140    },
3141    FieldSchema {
3142        name: "bottomPaint",
3143        ty: FieldType::Paint,
3144        slot: FieldSlot::Fifth,
3145    },
3146    FieldSchema {
3147        name: "leftPaint",
3148        ty: FieldType::Paint,
3149        slot: FieldSlot::Sixth,
3150    },
3151];
3152const CORNER_EACH_FIELDS: &[FieldSchema] = &[
3153    FieldSchema {
3154        name: "topLeft",
3155        ty: FieldType::Float,
3156        slot: FieldSlot::FirstLow,
3157    },
3158    FieldSchema {
3159        name: "topRight",
3160        ty: FieldType::Float,
3161        slot: FieldSlot::FirstHigh,
3162    },
3163    FieldSchema {
3164        name: "bottomRight",
3165        ty: FieldType::Float,
3166        slot: FieldSlot::SecondLow,
3167    },
3168    FieldSchema {
3169        name: "bottomLeft",
3170        ty: FieldType::Float,
3171        slot: FieldSlot::SecondHigh,
3172    },
3173];
3174const SHADOW_FIELDS: &[FieldSchema] = &[
3175    FieldSchema {
3176        name: "x",
3177        ty: FieldType::Float,
3178        slot: FieldSlot::FirstLow,
3179    },
3180    FieldSchema {
3181        name: "y",
3182        ty: FieldType::Float,
3183        slot: FieldSlot::FirstHigh,
3184    },
3185    FieldSchema {
3186        name: "blur",
3187        ty: FieldType::Float,
3188        slot: FieldSlot::SecondLow,
3189    },
3190    FieldSchema {
3191        name: "spread",
3192        ty: FieldType::Float,
3193        slot: FieldSlot::SecondHigh,
3194    },
3195    FieldSchema {
3196        name: "paint",
3197        ty: FieldType::Paint,
3198        slot: FieldSlot::Third,
3199    },
3200];
3201const TRANSFORM_FIELDS: &[FieldSchema] = &[
3202    FieldSchema {
3203        name: "a",
3204        ty: FieldType::FiniteFloat,
3205        slot: FieldSlot::FirstLow,
3206    },
3207    FieldSchema {
3208        name: "b",
3209        ty: FieldType::FiniteFloat,
3210        slot: FieldSlot::FirstHigh,
3211    },
3212    FieldSchema {
3213        name: "c",
3214        ty: FieldType::FiniteFloat,
3215        slot: FieldSlot::SecondLow,
3216    },
3217    FieldSchema {
3218        name: "d",
3219        ty: FieldType::FiniteFloat,
3220        slot: FieldSlot::SecondHigh,
3221    },
3222    FieldSchema {
3223        name: "e",
3224        ty: FieldType::FiniteFloat,
3225        slot: FieldSlot::ThirdLow,
3226    },
3227    FieldSchema {
3228        name: "f",
3229        ty: FieldType::FiniteFloat,
3230        slot: FieldSlot::ThirdHigh,
3231    },
3232    FieldSchema {
3233        name: "originX",
3234        ty: FieldType::FiniteFloat,
3235        slot: FieldSlot::FourthLow,
3236    },
3237    FieldSchema {
3238        name: "originY",
3239        ty: FieldType::FiniteFloat,
3240        slot: FieldSlot::FourthHigh,
3241    },
3242];
3243const TRANSFORM_3D_FIELDS: &[FieldSchema] = &[
3244    FieldSchema {
3245        name: "m0",
3246        ty: FieldType::FiniteFloat,
3247        slot: FieldSlot::FirstLow,
3248    },
3249    FieldSchema {
3250        name: "m1",
3251        ty: FieldType::FiniteFloat,
3252        slot: FieldSlot::FirstHigh,
3253    },
3254    FieldSchema {
3255        name: "m2",
3256        ty: FieldType::FiniteFloat,
3257        slot: FieldSlot::SecondLow,
3258    },
3259    FieldSchema {
3260        name: "m3",
3261        ty: FieldType::FiniteFloat,
3262        slot: FieldSlot::SecondHigh,
3263    },
3264    FieldSchema {
3265        name: "m4",
3266        ty: FieldType::FiniteFloat,
3267        slot: FieldSlot::ThirdLow,
3268    },
3269    FieldSchema {
3270        name: "m5",
3271        ty: FieldType::FiniteFloat,
3272        slot: FieldSlot::ThirdHigh,
3273    },
3274    FieldSchema {
3275        name: "m6",
3276        ty: FieldType::FiniteFloat,
3277        slot: FieldSlot::FourthLow,
3278    },
3279    FieldSchema {
3280        name: "m7",
3281        ty: FieldType::FiniteFloat,
3282        slot: FieldSlot::FourthHigh,
3283    },
3284    FieldSchema {
3285        name: "m8",
3286        ty: FieldType::FiniteFloat,
3287        slot: FieldSlot::FifthLow,
3288    },
3289    FieldSchema {
3290        name: "m9",
3291        ty: FieldType::FiniteFloat,
3292        slot: FieldSlot::FifthHigh,
3293    },
3294    FieldSchema {
3295        name: "m10",
3296        ty: FieldType::FiniteFloat,
3297        slot: FieldSlot::SixthLow,
3298    },
3299    FieldSchema {
3300        name: "m11",
3301        ty: FieldType::FiniteFloat,
3302        slot: FieldSlot::SixthHigh,
3303    },
3304    FieldSchema {
3305        name: "m12",
3306        ty: FieldType::FiniteFloat,
3307        slot: FieldSlot::SeventhLow,
3308    },
3309    FieldSchema {
3310        name: "m13",
3311        ty: FieldType::FiniteFloat,
3312        slot: FieldSlot::SeventhHigh,
3313    },
3314    FieldSchema {
3315        name: "m14",
3316        ty: FieldType::FiniteFloat,
3317        slot: FieldSlot::EighthLow,
3318    },
3319    FieldSchema {
3320        name: "m15",
3321        ty: FieldType::FiniteFloat,
3322        slot: FieldSlot::EighthHigh,
3323    },
3324    FieldSchema {
3325        name: "originX",
3326        ty: FieldType::FiniteFloat,
3327        slot: FieldSlot::NinthLow,
3328    },
3329    FieldSchema {
3330        name: "originY",
3331        ty: FieldType::FiniteFloat,
3332        slot: FieldSlot::NinthHigh,
3333    },
3334    FieldSchema {
3335        name: "backfaceHidden",
3336        ty: FieldType::Bool,
3337        slot: FieldSlot::Tenth,
3338    },
3339];
3340const ENABLED_FIELD: &[FieldSchema] = &[FieldSchema {
3341    name: "enabled",
3342    ty: FieldType::Bool,
3343    slot: FieldSlot::First,
3344}];
3345
3346const PRESS_FEEDBACK_FIELDS: &[FieldSchema] = &[
3347    FieldSchema {
3348        name: "scale",
3349        ty: FieldType::Float,
3350        slot: FieldSlot::FirstLow,
3351    },
3352    FieldSchema {
3353        name: "tintAlpha",
3354        ty: FieldType::Float,
3355        slot: FieldSlot::FirstHigh,
3356    },
3357];
3358
3359const CORNER_CURVE_FIELDS: &[FieldSchema] = &[FieldSchema {
3360    name: "smoothing",
3361    ty: FieldType::Float,
3362    slot: FieldSlot::FirstLow,
3363}];
3364
3365const BACKGROUND_BRUSH_FIELDS: &[FieldSchema] = &[
3366    FieldSchema {
3367        name: "x",
3368        ty: FieldType::FiniteFloat,
3369        slot: FieldSlot::FirstLow,
3370    },
3371    FieldSchema {
3372        name: "y",
3373        ty: FieldType::FiniteFloat,
3374        slot: FieldSlot::FirstHigh,
3375    },
3376    FieldSchema {
3377        name: "width",
3378        ty: FieldType::FiniteFloat,
3379        slot: FieldSlot::SecondLow,
3380    },
3381    FieldSchema {
3382        name: "height",
3383        ty: FieldType::FiniteFloat,
3384        slot: FieldSlot::SecondHigh,
3385    },
3386    FieldSchema {
3387        name: "paint",
3388        ty: FieldType::Paint,
3389        slot: FieldSlot::Third,
3390    },
3391    FieldSchema {
3392        name: "repeat",
3393        ty: FieldType::Role("BackgroundRepeat"),
3394        slot: FieldSlot::FourthLow,
3395    },
3396    FieldSchema {
3397        name: "tile_width",
3398        ty: FieldType::FiniteFloat,
3399        slot: FieldSlot::FifthLow,
3400    },
3401    FieldSchema {
3402        name: "tile_height",
3403        ty: FieldType::FiniteFloat,
3404        slot: FieldSlot::FifthHigh,
3405    },
3406];
3407
3408const MIN_TOUCH_TARGET_FIELDS: &[FieldSchema] = &[FieldSchema {
3409    name: "size",
3410    ty: FieldType::Float,
3411    slot: FieldSlot::FirstLow,
3412}];
3413
3414const SEMANTICS_FIELDS: &[FieldSchema] = &[
3415    FieldSchema {
3416        name: "role",
3417        ty: FieldType::Role("SemanticsRole"),
3418        slot: FieldSlot::FirstLow,
3419    },
3420    FieldSchema {
3421        name: "state",
3422        ty: FieldType::U32,
3423        slot: FieldSlot::SecondLow,
3424    },
3425];
3426
3427const SIZE_IN_FIELDS: &[FieldSchema] = &[
3428    FieldSchema {
3429        name: "minWidth",
3430        ty: FieldType::Float,
3431        slot: FieldSlot::FirstLow,
3432    },
3433    FieldSchema {
3434        name: "maxWidth",
3435        ty: FieldType::Float,
3436        slot: FieldSlot::FirstHigh,
3437    },
3438    FieldSchema {
3439        name: "minHeight",
3440        ty: FieldType::Float,
3441        slot: FieldSlot::SecondLow,
3442    },
3443    FieldSchema {
3444        name: "maxHeight",
3445        ty: FieldType::Float,
3446        slot: FieldSlot::SecondHigh,
3447    },
3448];
3449
3450const ASPECT_RATIO_FIELDS: &[FieldSchema] = &[
3451    FieldSchema {
3452        name: "ratio",
3453        ty: FieldType::Float,
3454        slot: FieldSlot::FirstLow,
3455    },
3456    FieldSchema {
3457        name: "matchHeightConstraintsFirst",
3458        ty: FieldType::Bool,
3459        slot: FieldSlot::Second,
3460    },
3461];
3462
3463pub const MODIFIER_SCHEMA: &[VariantSchema] = &[
3464    VariantSchema {
3465        name: "Empty",
3466        tag: 0,
3467        extra_words: 0,
3468        fields: NO_FIELDS,
3469    },
3470    VariantSchema {
3471        name: "Padding",
3472        tag: 1,
3473        extra_words: 0,
3474        fields: VALUE_FLOAT_FIELD,
3475    },
3476    VariantSchema {
3477        name: "FillMaxWidth",
3478        tag: 2,
3479        extra_words: 0,
3480        fields: NO_FIELDS,
3481    },
3482    VariantSchema {
3483        name: "FillMaxHeight",
3484        tag: 3,
3485        extra_words: 0,
3486        fields: NO_FIELDS,
3487    },
3488    VariantSchema {
3489        name: "Width",
3490        tag: 4,
3491        extra_words: 0,
3492        fields: VALUE_FLOAT_FIELD,
3493    },
3494    VariantSchema {
3495        name: "Height",
3496        tag: 5,
3497        extra_words: 0,
3498        fields: VALUE_FLOAT_FIELD,
3499    },
3500    VariantSchema {
3501        name: "Size",
3502        tag: 6,
3503        extra_words: 0,
3504        fields: SIZE_FIELDS,
3505    },
3506    VariantSchema {
3507        name: "Background",
3508        tag: 7,
3509        extra_words: 0,
3510        fields: PAINT_FIELD,
3511    },
3512    VariantSchema {
3513        name: "Clickable",
3514        tag: 8,
3515        extra_words: 0,
3516        fields: HANDLER_ID_FIELD,
3517    },
3518    VariantSchema {
3519        name: "PaddingRole",
3520        tag: 9,
3521        extra_words: 0,
3522        fields: SPACE_ROLE_FIELD,
3523    },
3524    VariantSchema {
3525        name: "PaddingEach",
3526        tag: 10,
3527        extra_words: 0,
3528        fields: PADDING_EACH_FIELDS,
3529    },
3530    VariantSchema {
3531        name: "Weight",
3532        tag: 11,
3533        extra_words: 0,
3534        fields: VALUE_FLOAT_FIELD,
3535    },
3536    VariantSchema {
3537        name: "Shape",
3538        tag: 12,
3539        extra_words: 0,
3540        fields: SHAPE_FIELDS,
3541    },
3542    VariantSchema {
3543        name: "ShapeRole",
3544        tag: 13,
3545        extra_words: 0,
3546        fields: SHAPE_ROLE_FIELD,
3547    },
3548    VariantSchema {
3549        name: "Border",
3550        tag: 14,
3551        extra_words: 0,
3552        fields: BORDER_FIELDS,
3553    },
3554    VariantSchema {
3555        name: "Elevation",
3556        tag: 15,
3557        extra_words: 0,
3558        fields: VALUE_FLOAT_FIELD,
3559    },
3560    VariantSchema {
3561        name: "ObserveSize",
3562        tag: 16,
3563        extra_words: 0,
3564        fields: OBSERVE_SIZE_FIELDS,
3565    },
3566    VariantSchema {
3567        name: "Motion",
3568        tag: 17,
3569        extra_words: 0,
3570        fields: MOTION_ROLE_FIELD,
3571    },
3572    VariantSchema {
3573        name: "Material",
3574        tag: 18,
3575        extra_words: 0,
3576        fields: MATERIAL_ROLE_FIELD,
3577    },
3578    // The elements an HTML and CSS screen is drawn with: boxes a layout engine on the Host
3579    // already placed and sized, and the decoration CSS gives them.
3580    VariantSchema {
3581        name: "Offset",
3582        tag: 19,
3583        extra_words: 0,
3584        fields: OFFSET_FIELDS,
3585    },
3586    VariantSchema {
3587        name: "RequiredSize",
3588        tag: 20,
3589        extra_words: 0,
3590        fields: SIZE_FIELDS,
3591    },
3592    // Four widths and four paints are six words, so the record is four words longer.
3593    VariantSchema {
3594        name: "BorderEach",
3595        tag: 21,
3596        extra_words: 4,
3597        fields: BORDER_EACH_FIELDS,
3598    },
3599    VariantSchema {
3600        name: "CornerEach",
3601        tag: 22,
3602        extra_words: 0,
3603        fields: CORNER_EACH_FIELDS,
3604    },
3605    // Four measurements and a paint are three words, one more than the record has.
3606    VariantSchema {
3607        name: "Shadow",
3608        tag: 23,
3609        extra_words: 1,
3610        fields: SHADOW_FIELDS,
3611    },
3612    VariantSchema {
3613        name: "Clip",
3614        tag: 24,
3615        extra_words: 0,
3616        fields: ENABLED_FIELD,
3617    },
3618    VariantSchema {
3619        name: "Alpha",
3620        tag: 25,
3621        extra_words: 0,
3622        fields: VALUE_FLOAT_FIELD,
3623    },
3624    // Eight `f32` are four words: the linear part, the translation, and the origin.
3625    VariantSchema {
3626        name: "Transform",
3627        tag: 26,
3628        extra_words: 2,
3629        fields: TRANSFORM_FIELDS,
3630    },
3631    // Sixteen matrix values, the origin and a flag are ten words, eight more than the two
3632    // every record has: 92 bytes.
3633    VariantSchema {
3634        name: "Transform3D",
3635        tag: 27,
3636        extra_words: 8,
3637        fields: TRANSFORM_3D_FIELDS,
3638    },
3639    VariantSchema {
3640        name: "MatchParentSize",
3641        tag: 31,
3642        extra_words: 0,
3643        fields: NO_FIELDS,
3644    },
3645    VariantSchema {
3646        name: "WindowDrag",
3647        tag: 32,
3648        extra_words: 0,
3649        fields: ENABLED_FIELD,
3650    },
3651    VariantSchema {
3652        name: "PressFeedback",
3653        tag: 33,
3654        extra_words: 0,
3655        fields: PRESS_FEEDBACK_FIELDS,
3656    },
3657    VariantSchema {
3658        name: "Semantics",
3659        tag: 34,
3660        extra_words: 0,
3661        fields: SEMANTICS_FIELDS,
3662    },
3663    // 28 to 30 were set aside for modifiers that have not landed, so the next free tag is
3664    // 35.
3665    VariantSchema {
3666        name: "CornerCurve",
3667        tag: 35,
3668        extra_words: 0,
3669        fields: CORNER_CURVE_FIELDS,
3670    },
3671    // 28, the first of the tags set aside above. The rectangle, the paint, the repeat and
3672    // the step take five words, three past the two every record has.
3673    VariantSchema {
3674        name: "BackgroundBrush",
3675        tag: 28,
3676        extra_words: 3,
3677        fields: BACKGROUND_BRUSH_FIELDS,
3678    },
3679    VariantSchema {
3680        name: "SizeIn",
3681        tag: 36,
3682        extra_words: 0,
3683        fields: SIZE_IN_FIELDS,
3684    },
3685    VariantSchema {
3686        name: "AspectRatio",
3687        tag: 37,
3688        extra_words: 0,
3689        fields: ASPECT_RATIO_FIELDS,
3690    },
3691    VariantSchema {
3692        name: "MinTouchTarget",
3693        tag: 38,
3694        extra_words: 0,
3695        fields: MIN_TOUCH_TARGET_FIELDS,
3696    },
3697    VariantSchema {
3698        name: "Overlay",
3699        tag: 39,
3700        extra_words: 0,
3701        fields: PAINT_FIELD,
3702    },
3703    VariantSchema {
3704        name: "Sticky",
3705        tag: 41,
3706        extra_words: 0,
3707        fields: NO_FIELDS,
3708    },
3709    VariantSchema {
3710        name: "UnboundedWidth",
3711        tag: 40,
3712        extra_words: 0,
3713        fields: NO_FIELDS,
3714    },
3715];
3716
3717#[derive(Clone, Debug, PartialEq)]
3718pub struct ColumnProps {
3719    pub enabled: bool,
3720}
3721
3722#[derive(Clone, Debug, PartialEq)]
3723pub struct RowProps {
3724    pub enabled: bool,
3725}
3726
3727#[derive(Clone, Debug, PartialEq)]
3728pub struct BoxProps {
3729    pub enabled: bool,
3730}
3731
3732#[derive(Clone, Debug, PartialEq)]
3733pub struct TextProps<'a> {
3734    pub text: &'a str,
3735}
3736
3737#[derive(Clone, Debug, PartialEq)]
3738pub struct TextFieldProps<'a> {
3739    pub placeholder: &'a str,
3740    pub enabled: bool,
3741    pub multiline: bool,
3742}
3743
3744#[derive(Clone, Debug, PartialEq)]
3745pub struct ButtonProps<'a> {
3746    pub text: &'a str,
3747    pub enabled: bool,
3748}
3749
3750#[derive(Clone, Debug, PartialEq)]
3751pub struct SpacerProps {
3752    pub width: f32,
3753    pub height: f32,
3754}
3755
3756crate::extensions::define_property_schema_with_extensions!(define_wire_enum; PROPERTY_SCHEMA, PropertyKind {
3757    Text = 1,
3758    Placeholder = 2,
3759    Enabled = 3,
3760    Multiline = 4,
3761    OnClick = 5,
3762    OnValueChange = 6,
3763    OnSubmit = 7,
3764    OnFocusLost = 8,
3765    OnKeyDown = 9,
3766    ItemCount = 10,
3767    ItemKey = 11,
3768    OnRangeRequested = 12,
3769    TypeRole = 13,
3770    FontSize = 14,
3771    FontWeight = 15,
3772    LineHeight = 16,
3773    LetterSpacing = 17,
3774    Color = 18,
3775    TextAlign = 19,
3776    MaxLines = 20,
3777    Overflow = 21,
3778    Arrangement = 22,
3779    Spacing = 23,
3780    SpaceRole = 24,
3781    Alignment = 25,
3782    Variant = 26,
3783    // The id of an asset the Host registered. Image and Icon carry nothing else: the
3784    // bytes were copied into the Renderer's cache once, at registration.
3785    Asset = 28,
3786    // Whether a toggle is on. One boolean for all three of them: a selected radio button
3787    // and a switch that is on are the same fact, and the schema names a concept once.
3788    Checked = 32,
3789    // Discrete stops between a slider's two ends. Zero leaves it continuous.
3790    Steps = 33,
3791    // Whether a progress indicator knows how far along it is. When it does not, `Value`
3792    // is not read at all.
3793    Determinate = 34,
3794    // Which of the two forms a progress indicator takes. It picks a shape, not a size.
3795    Circular = 35,
3796    // A divider's axis, which is the only thing a divider carries.
3797    Vertical = 36,
3798    // Whether an overlay is showing. The Renderer owns the state; this seeds it and
3799    // carries changes that came from outside the Renderer.
3800    Open = 40,
3801    OnDismiss = 41,
3802    SelectedIndex = 42,
3803    // The Canvas drawing command list, a byte blob in the batch arena.
3804    Commands = 50,
3805    // The control's current value, in the widget's own unit: an epoch day count for a
3806    // date, minutes since midnight for a time, the chosen position for a Dropdown, a
3807    // position between the ends for a Slider, a fraction for a ProgressIndicator. One tag,
3808    // because "this control's value" is one concept whichever widget holds it.
3809    Value = 51,
3810    // The ends of the selectable range, in the same unit as `Value`.
3811    Min = 52,
3812    Max = 53,
3813    // The meaning of the icon a destination carries, as an `IconRole` tag. Tag 0 is "not
3814    // sent", so a destination without an icon is label only.
3815    Icon = 60,
3816    // Which slot of a Scaffold this subtree fills.
3817    Slot = 61,
3818    // How many columns a grid has, where the screen said a number.
3819    Columns = 62,
3820    // How narrow a column may get before the grid drops one, where the screen said a
3821    // width instead of a number. The Renderer divides its own width by this, which is the
3822    // same kind of judgement as a size class and for the same reason is not the Host's.
3823    MinColumnWidth = 63,
3824    // Runs of different treatment inside one string, as a blob of fixed-length records.
3825    // A Text that says nothing about runs carries none of this and travels as it always
3826    // did.
3827    Spans = 64,
3828    // A node that is willing to have files dropped on it. The handler is the willingness:
3829    // a node without one is never told that files are over it, which is what keeps a
3830    // screen from lighting up every container it has.
3831    OnFilesEntered = 65,
3832    OnFilesDropped = 66,
3833    // Which named group of a navigation's strip this destination belongs to. Neighbouring
3834    // destinations carrying the same string are one group and the string is its heading.
3835    //
3836    // 76 rather than 67, because 67 through 74 are reserved for the gestures and 75 for a
3837    // button's kind. A reservation is not a free tag.
3838    Section = 76,
3839    // How many a badge counts. Absent rather than zero when the badge is a dot or a word,
3840    // because "no count" and "a count of nothing" are different things to show.
3841    //
3842    // 80 opens a fresh block of ten for widget tags 40 onwards, after the last tag in use
3843    // anywhere, so two pieces of work landing in either order cannot collide.
3844    Count = 80,
3845    // Whether a split pane's side pane may be folded away by dragging past its minimum, or
3846    // by the keyboard, or by the platform's own show and hide sidebar command. Whether a
3847    // side pane can be hidden is a fact about the screen rather than about the design
3848    // system: a list of sessions can, a settings screen's list of sections cannot.
3849    //
3850    // 90 opens the split pane's block of ten, after the badge's.
3851    Collapsible = 90,
3852    // What a button is, as opposed to how loud it is: a plain button, or one key of a
3853    // dense grid of them. The variant still chooses the fill and the emphasis; this lets
3854    // the design system give the key its own calculator's silhouette, so the Host never
3855    // sends a radius or a shape role to get one.
3856    //
3857    // 75 was reserved for this when the gestures took 67 through 74, and stays here
3858    // rather than with its neighbours by number because this list is append only.
3859    ButtonKind = 75,
3860    // A code editor's own block, after the split pane's.
3861    //
3862    // The decorations over the document and the colour runs of its syntax, each a blob of
3863    // fixed-length records sent whole. Every record carries the document version its
3864    // range was written against, so a list computed while the reader kept typing still
3865    // lands where it was meant to.
3866    Decorations = 100,
3867    SyntaxSpans = 101,
3868    // How many columns a tab advances. Absent leaves it to the design system.
3869    TabWidth = 102,
3870    OnEditRejected = 103,
3871    OnHover = 104,
3872    OnSave = 105,
3873    // One listener for every decoration that can be pressed or accepted. The ids inside
3874    // the decoration blob are the application's own names for them, not handlers, so the
3875    // event carries the id and the application tells them apart.
3876    OnDecorationClick = 106,
3877    // The editor's additions: the stretches that can be folded and the marks beside the
3878    // line numbers, each a blob of fixed-length records sent whole, and the listener for
3879    // the selection moving. The other four listeners are in the block at 130.
3880    Folds = 107,
3881    GutterDecorations = 108,
3882    OnSelectionChange = 109,
3883    // The text a page laid out by CSS draws, which takes its letters from its own values
3884    // rather than from a rung of the type ladder. 110 opens the block for it.
3885    //
3886    // The fonts to try, in order, for text whose role is `TypeRole::None`: a list of up to
3887    // eight registered font assets, installed families by name and generic families, as a
3888    // blob. Text with a role ignores it, because its font is the theme's.
3889    Font = 110,
3890    // Where a line may break, and whether a word too long for its line may be broken
3891    // inside. The `WordBreak` and `OverflowWrap` roles.
3892    WordBreak = 111,
3893    OverflowWrap = 112,
3894    // How many spaces' width apart the tab stops are. Absent is eight. A tab advances to
3895    // the next stop, which only the side that measures the letters can work out.
3896    TabSize = 113,
3897    // Whether the sizes are CSS pixels, which the system's font scale does not enlarge.
3898    AbsoluteSize = 114,
3899    // Whether lines wrap at the width they are given. Absent is yes; `false` is CSS
3900    // `nowrap` and `pre`, whose lines run as long as their text.
3901    SoftWrap = 115,
3902    // The font each run of a `Text` with no role is set in, as a blob beside `Spans`
3903    // rather than inside its records: a run record keeps the 36 bytes it has always had,
3904    // and only text that names fonts carries this at all.
3905    SpanFonts = 116,
3906    // The rest of the code editor's listeners, in the first block free after the text and
3907    // pointer blocks. The visible lines changing, the editor gaining or losing focus, a
3908    // stretch folded or unfolded, and an input method starting or ending a composition.
3909    OnVisibleRangeChange = 130,
3910    OnEditorFocusChange = 131,
3911    OnFoldChange = 132,
3912    OnCompositionChange = 133,
3913    // The node's pointer subscription: the handler, and the kinds it wants as a bit mask
3914    // (`1 << (kind - 1)`). 67 was reserved for a gesture handler that was never sent, so
3915    // it is free to carry this one. It is listed here, after the newer blocks, because
3916    // this list is append only.
3917    OnPointer = 67,
3918    // 140 opens the block after the animation and HTML-text properties.
3919    PointerKinds = 140,
3920    // The cursor the platform shows over the node and whether its text can be selected.
3921    // The Host resolves CSS inheritance and sends the value for each node.
3922    Cursor = 141,
3923    UserSelect = 142,
3924    // How large an HTML island is drawn, as the f32 factor `k` (see `ZoomChanged`), on the
3925    // island's root `AbsoluteBox`. 120 opens the block for zoom. Absent is 1.
3926    IslandZoom = 120,
3927    // The window block, after the cursor block. Every one of them belongs to a
3928    // `Window` node except the last two, which can sit on any node.
3929    //
3930    // The title. A string.
3931    WindowTitle = 150,
3932    // The size when the window opens, width then height, two `f32` in dp as 8 bytes. A
3933    // later change resizes the window; a size the user chose is not given back.
3934    WindowSize = 151,
3935    // The smallest size, in the same 8 bytes.
3936    WindowMinSize = 152,
3937    WindowResizable = 153,
3938    // A `Chrome` tag and a `TitleBar` tag, as integers.
3939    WindowChrome = 154,
3940    WindowTitleBar = 155,
3941    // The asset id of the window's icon; zero is the application's own.
3942    WindowIcon = 156,
3943    // Where the window sits, x then y, two `f32` in screen dp as 8 bytes. Removing it
3944    // leaves the placement to the platform.
3945    WindowPosition = 157,
3946    // The application's stable name for the window, a string, which matches a window the
3947    // system brings back to the node that describes it.
3948    WindowRestoreKey = 158,
3949    // The window's own zoom level, an integer in -8..=8.
3950    WindowZoomLevel = 159,
3951    // Open the window under a pointer that is held down and follow it until it is let go:
3952    // `pointer_id` as a `u32`, then the anchor `x` and `y` as two `f32`, 12 bytes. Read
3953    // when the window opens and not again.
3954    DragFromPointer = 160,
3955    // The handlers of the window events, each the handler id as an integer.
3956    OnWindowCloseRequested = 161,
3957    OnWindowFocusChanged = 162,
3958    OnWindowMoved = 163,
3959    OnWindowDrag = 164,
3960    OnWindowUnavailable = 165,
3961    OnWindowClosed = 166,
3962    // Not window properties: any node may take them. A node that has the handler is told
3963    // when a dragged window passes over it, and a node that has the key can be pulled out
3964    // into a window of its own, named by it.
3965    OnWindowDragOver = 167,
3966    TearOffKey = 168,
3967    OnFocusGained = 117,
3968    OnKeyUp = 118,
3969    // The name assistive technology reads for a node, a string. On a widget it overrides
3970    // the visible label, and on an icon-only button it beats the name the icon's meaning
3971    // would give. 117 and 118 are reserved for another pending change, and 119 is the next
3972    // free number; 120 is `IslandZoom`.
3973    AccessibleName = 119,
3974    // Colours and size of the selection controls. A node that does not set one leaves
3975    // the design system's value, so a control that sends none draws as it always has.
3976    // The colours are `Paint` bits; the size is two f32 (width, height) in dp.
3977    // 120 is the island zoom, so these start at 121.
3978    TrackColor = 121,
3979    ThumbColor = 122,
3980    ActiveTrackColor = 123,
3981    ContainerColor = 124,
3982    CheckColor = 125,
3983    ControlSize = 126,
3984    // Opt in to a `WindowSizeChanged` whenever the window's width or height, rounded to
3985    // whole dp, changes, and not only when the size class does. A `Window` node's boolean;
3986    // absent is false.
3987    ReportSize = 127,
3988    // Scrim colour for modal overlays (Dialog, Sheet, Menu), as a `Paint` bit value.
3989    // A `Popover` draws no scrim unless it is asked to, so there it is also a boolean:
3990    // true draws the design system's scrim, and a `Paint` draws that colour.
3991    Scrim = 128,
3992    // A `TextField` or `Dropdown` drawn without the design system's frame (fill, line,
3993    // underline, corner clip, inner padding, minimum height, focus line). A boolean;
3994    // absent is false. A node `Background` or `Border` is still drawn.
3995    Bare = 169,
3996    // A `FlowRow`'s layout. The gap between children on one line and the gap between
3997    // lines, each a literal dp; where a line's children sit along it and where each child
3998    // sits inside its line's height, as `HorizontalAlignment` and `VerticalAlignment` tags;
3999    // and the most children one line may hold, an integer, absent for no limit. 169 is
4000    // taken by another pending property, so these start at 170.
4001    HorizontalSpacing = 170,
4002    VerticalSpacing = 171,
4003    HorizontalAlignment = 172,
4004    VerticalAlignment = 173,
4005    MaxItemsInEachRow = 174,
4006    // The popover block. All three belong to a `Popover`. 169 to 174 are held for
4007    // properties on other branches.
4008    //
4009    // The side of the anchor the content opens on, a `PopoverPlacement` tag. Absent is
4010    // `Bottom`.
4011    Placement = 175,
4012    // The edge of the anchor the content lines up with, a `PopoverAlign` tag. Absent is
4013    // `Start`.
4014    Align = 176,
4015    // The gap between the anchor and the content, an `f32` in dp. Absent leaves the gap
4016    // to the design system.
4017    OffsetDp = 177,
4018    // How a code editor is laid out and coloured where the application says so. A node
4019    // that sets none of them draws with the design system's values. 169 to 177 are
4020    // numbered for properties that are not here yet.
4021    //
4022    // Whether the line numbers are drawn, a boolean. Absent is yes.
4023    LineNumbers = 178,
4024    // The least width of the line number column with its padding, the padding on each side
4025    // of a line number, and the space between the gutter and the text. Each an f32 in dp.
4026    GutterMinWidthDp = 179,
4027    GutterPaddingDp = 180,
4028    TextInsetDp = 181,
4029    // One colour record as a blob: a `ColorRole` for each of the container, the gutter, a
4030    // line number, the current line's number and the current line. Zero leaves a slot to
4031    // the design system.
4032    CodeEditorColors = 182,
4033    // The handlers of the editor's row height and of its scroll offset.
4034    OnCodeMetrics = 183,
4035    OnCodeScrolled = 184,
4036    // What a `Navigation` becomes in a compact window, as a `CompactNavigation` tag. Absent
4037    // or 0 leaves it to the design system.
4038    CompactNavigation = 185,
4039    // The handler a scroll container reports its position to, the handler id as an
4040    // integer. One handler shared by every scroll container rather than one widget's
4041    // block, so it takes the number after the last one in use: 169 to 184 are held by
4042    // properties other requirements have numbered.
4043    OnScrollChanged = 186,
4044    // The width in dp, an f32, below which a split pane shows one pane at a time instead of
4045    // its size class deciding. At or above it the split pane never stacks, and the design
4046    // system still chooses between two columns and a side pane laid over the body. Absent
4047    // or 0 keeps the size class's own line. The next place in the split pane's block after
4048    // `Collapsible`.
4049    CollapseBelow = 91,
4050    // Where a `ScrollRow` or `ScrollColumn` comes to rest, as a `Snap` tag. Absent or 0 is
4051    // free scrolling. 187 is held by a property on another branch.
4052    Snap = 188,
4053    // The tallest a `Sheet` grows, as an `f32` fraction of the window's height above 0 and
4054    // at most 1. Below it the sheet is as tall as its content; at it the content scrolls.
4055    // Absent leaves the height to the design system. 187 is held by a property on another
4056    // branch.
4057    MaxHeightFraction = 189,
4058    // OpenType features for a `Text` or a `TextField`, such as tabular figures. A blob of
4059    // 8-byte records, at most 16: the four tag bytes, then the value as a little-endian
4060    // u32. A tag that comes twice takes the later value. Absent, or empty, is no features.
4061    // 187 is held by a property on another branch, and 188 to 191 are in use.
4062    FontFeatureSettings = 192,
4063    // The handler a node's size motion reports to once it settles, the handler id as an
4064    // integer. Any node may take it, so it is numbered after the last one in use rather
4065    // than inside a widget's block: 187 is held by a property on another branch, and 188
4066    // to 192 are in use.
4067    OnMotionFinished = 193,
4068    // The handler a code editor reports what became of each grouped edit to, the handler id
4069    // as an integer: one `CodeEditGroupResult` for every `EditCodeGroup`.
4070    OnEditGroupResult = 194,
4071    // The handler a code editor tells where its caret is drawn.
4072    OnCaretRect = 195,
4073    // The handler a code editor offers each key press to before it handles the key itself.
4074    // It hears the `KeyDown` record a key handler does, and a press it consumes is not the
4075    // editor's. Never while an input method is composing.
4076    OnKeyPreview = 196,
4077    // The handler a code editor sends its pointer events to, each with the place in the
4078    // text under the pointer. The kinds it hears are the `PointerKinds` mask's.
4079    OnCodePointer = 197,
4080    // Whether a `Column` or a `Row` is a group of radio buttons, a boolean. Such a group is
4081    // one stop for Tab, its arrow keys move between the radio buttons inside it, and
4082    // assistive technology hears it as a radio group. Absent is no.
4083    RadioGroup = 198,
4084    // Whether a code editor draws a minimap beside its text, and on which side, as a
4085    // `MinimapSide` tag. Absent or 0 draws none. 199 and 200 are held by the editor's view
4086    // zones and its word wrap.
4087    Minimap = 201,
4088    // A code editor's view zones, rows after a line that are not text, as a blob of
4089    // fixed-length records sent whole, with the text they show behind them.
4090    ViewZones = 199,
4091    // Where a code editor breaks a line too long for it onto the rows below, as an integer:
4092    // the `WordWrapMode` tag in the low 16 bits and the column count above them. Absent or
4093    // 0 breaks no line.
4094    WordWrap = 200,
4095    // How an `Image` lays its picture into its box, as a `ContentScale` tag. Absent or 0
4096    // is `Fit`, which is how every picture was drawn before there was a choice. 37 is the
4097    // next place in the 28 to 39 block, after the divider's `Vertical`.
4098    ContentScale = 37,
4099    // The diameter in dp a Slider draws its thumb at, an f32. Absent is the design system's
4100    // size. The track and the area that takes a press stay as they are.
4101    ThumbSize = 202,
4102    // The placeholder text colour and caret colour of a TextField as Paint bits.
4103    // Absent leaves the design system's defaults.
4104    PlaceholderColor = 203,
4105    CaretColor = 204,
4106    // The id of an SVG asset an `Icon` draws in its icon slot, tinted with the icon's
4107    // colour: every fill and stroke in the picture takes that colour and keeps its own
4108    // alpha. It is sized as an `IconRole` icon is, so a row of icons lines up whichever kind
4109    // each one is.
4110    IconAsset = 205,
4111    // The presentation of a `Sheet`: whether it enters from an edge (`Edge = 0`) or appears
4112    // in the centre of the window (`Centered = 1`). Absent or 0 is `Edge`.
4113    Presentation = 206,
4114    // The maximum width of a centered `Sheet` in dp, an integer. 0 leaves it to the design
4115    // system (560 dp).
4116    MaxWidth = 207,
4117    // Whether a bar across the top of a screen draws the design system's hairline
4118    // separator underneath. Absent lets the design system decide.
4119    Separator = 208,
4120    // The OpenType features for individual runs of a `Text`, as a blob beside `Spans`
4121    // rather than inside its records: a run record keeps the 36 bytes it has always had,
4122    // and only text that sets per-span font features carries this at all.
4123    SpanFontFeatures = 209,
4124    // Room above the first line and below the last line of a code editor that scrolls with
4125    // the document, as a blob of two f32 in dp: top, then bottom. Absent is none. The gutter
4126    // and its divider still fill the viewport.
4127    ContentPaddingDp = 210,
4128    // Whether a code editor always keeps the fold column and the change-bar column in its
4129    // gutter, so the text starts at the same place whether or not the file has folds or
4130    // changes. A boolean, absent is no.
4131    FixedGutterColumns = 211,
4132    // A `NativeView`'s two properties. 187 is held by a property on another branch.
4133    //
4134    // Whether the platform view shows, a boolean. Absent is yes. A hidden view stays in the
4135    // window with its state, so showing it again shows the same page.
4136    NativeVisible = 190,
4137    // The handler that hears the platform view take and lose keyboard focus.
4138    OnNativeViewFocus = 191,
4139});
4140
4141#[derive(Clone, Debug, PartialEq)]
4142pub enum EventPayload<'a> {
4143    Clicked,
4144    TextChanged(&'a str),
4145    TextSubmitted(&'a str),
4146    FocusLost,
4147    ProtocolError {
4148        code: u32,
4149        message: &'a str,
4150    },
4151    KeyDown {
4152        key: Key,
4153        shift_key: bool,
4154        ctrl_key: bool,
4155        alt_key: bool,
4156        meta_key: bool,
4157        /// True when the event comes from a held key repeating.
4158        repeat: bool,
4159        /// The physical key as a USB HID usage value, the same on every layout.
4160        code: u32,
4161        /// The DOM `key` string, such as `"ArrowDown"` or `"a"`.
4162        text: &'a str,
4163    },
4164    /// The Renderer asks the Host to materialise the visible item range.
4165    RangeRequested {
4166        start: u32,
4167        count: u32,
4168    },
4169    /// A control's new value, in the widget's own unit: an epoch count for a picker, a
4170    /// position for a slider, 0.0 or 1.0 for a toggle. The Renderer decided how the user
4171    /// reached it, so nothing about calendars, wheels, tracks or thumbs crosses here.
4172    ///
4173    /// One `f64` holds all of them: integers up to 2^53 survive it exactly, so splitting
4174    /// the event in two would only give the same concept two names.
4175    ValueChanged(f64),
4176    /// The window, or one observed node, moved into a different size class. The Renderer
4177    /// measures it and sends this only when a class changes, never on every layout pass.
4178    /// A `node_id` of 0 is the window; anything else is the node that asked to be
4179    /// measured.
4180    WindowSizeChanged {
4181        width_dp: f32,
4182        height_dp: f32,
4183        class: WindowSizeClass,
4184        height_class: WindowHeightClass,
4185        safe_area_top: f32,
4186        safe_area_leading: f32,
4187        safe_area_trailing: f32,
4188    },
4189    /// Files are over a node that said it would take them. Nothing about what they are:
4190    /// the platforms disagree about what is knowable before a drop, and a screen that
4191    /// only needs to light up does not need to know.
4192    FilesEntered,
4193    /// Files were let go over a node. The paths arrive together, separated by a byte no
4194    /// path on any of the three desktops may contain.
4195    FilesDropped(&'a str),
4196    /// The Renderer resolved the theme and this is what it chose. Sent once and then
4197    /// only when the answer changes, the same way a size class is.
4198    DesignSystemResolved(DesignSystem),
4199    /// The Renderer lost its node table and asks for the whole tree again. A recreated
4200    /// Activity is the case that produces it.
4201    Resync,
4202    /// The platform brought the UI back. Timers and animations resume.
4203    LifecycleStart,
4204    /// The platform stopped the UI. Timers and animations are suppressed, so a process
4205    /// that is not on screen is not asked to draw.
4206    LifecycleStop,
4207    /// The user pressed a notification the application posted. `action` is 0 for the body
4208    /// and 1 or 2 for an action button; `key` is the name the application gave it.
4209    ///
4210    /// A name rather than a handler, because a notification outlives the component that
4211    /// posted it by hours and a callback dies with its scope.
4212    NotificationActivated {
4213        action: u32,
4214        key: &'a str,
4215    },
4216    /// Whether notifications may be shown, sent once after start and then only when the
4217    /// answer changes.
4218    NotificationPermissionChanged(NotificationPermission),
4219    /// One committed edit to a code editor's document.
4220    ///
4221    /// The range is in the document as it stood before the edit, and `version` is the
4222    /// version the edit produced. Lines and columns count from zero and columns are UTF-16
4223    /// code units, which is what a language server counts in, so the event can be handed
4224    /// to one unchanged. Text still being composed by an input method never arrives here:
4225    /// only what the reader committed does.
4226    CodeChanged {
4227        version: u32,
4228        start_line: u32,
4229        start_column: u32,
4230        end_line: u32,
4231        end_column: u32,
4232        text: &'a str,
4233    },
4234    /// An edit the Host asked for and the Renderer did not apply, because the reader had
4235    /// changed the same place since the version the edit was written against.
4236    CodeEditRejected {
4237        request_id: u32,
4238        base_version: u32,
4239        current_version: u32,
4240        start_line: u32,
4241        start_column: u32,
4242        end_line: u32,
4243        end_column: u32,
4244    },
4245    /// A pointer came to rest over a place in a code editor, or left it. `decoration` is
4246    /// the id of the hover anchor under it, or zero where there is none.
4247    CodeHovered {
4248        decoration: u64,
4249        line: u32,
4250        column: u32,
4251        phase: HoverPhase,
4252    },
4253    /// The reader pressed the platform's save shortcut on a code editor.
4254    CodeSaveRequested {
4255        version: u32,
4256    },
4257    /// A decoration was pressed or accepted, named by the id the application gave it.
4258    DecorationActivated {
4259        decoration: u64,
4260    },
4261    /// Something happened to an animation the Renderer is playing, sent only for the kinds
4262    /// the animation asked for. It names the node the animation plays on and no handler.
4263    AnimationEvent {
4264        animation_id: u32,
4265        kind: AnimationEventKind,
4266        property: AnimatedProperty,
4267        slot: u8,
4268        /// The iteration the animation was in at that moment.
4269        iteration: u32,
4270        /// What CSS reports as `elapsedTime`: active time, without the delay, in ms.
4271        elapsed_ms: f32,
4272        /// The frame the moment happened in; for `Ready`, the start time it was given.
4273        time_nanos: u64,
4274    },
4275    /// Whether the platform asks for reduced motion, sent once after start and then only
4276    /// when the answer changes.
4277    ReducedMotionChanged(ReducedMotion),
4278    /// Whether the system appearance is light or dark, sent once before the first frame and
4279    /// then only when it changes. It is sent whatever the theme's `color_scheme` is.
4280    ColorSchemeChanged(SystemColorScheme),
4281    /// A pointer did something inside a node that subscribed to it. Coordinates are in dp
4282    /// from the node's top left corner, `buttons` is what is held now and `button` is the
4283    /// one that caused a `Down` or an `Up`. `timestamp_nanos` is on the frame time's clock.
4284    Pointer {
4285        kind: PointerKind,
4286        pointer_id: u32,
4287        pointer_type: PointerType,
4288        x: f32,
4289        y: f32,
4290        buttons: u32,
4291        button: u32,
4292        modifiers: u32,
4293        click_count: u32,
4294        delta_x: f32,
4295        delta_y: f32,
4296        delta_mode: WheelDeltaMode,
4297        timestamp_nanos: u64,
4298    },
4299    /// How large the Renderer is drawing: `k = os × 1.2^level`. Sent once at start and
4300    /// again whenever any of the three changes. A move to a screen of another density
4301    /// changes none of them and is not reported.
4302    ZoomChanged {
4303        k: f32,
4304        os: f32,
4305        level: i32,
4306    },
4307    /// How many device pixels one dp of a window covers, 2.0 on a screen at 200% for
4308    /// example. Sent once before the first frame and again whenever it changes, as when a
4309    /// window moves to a screen of another scale. It says nothing about the zoom, which
4310    /// `ZoomChanged` reports on its own.
4311    DensityChanged {
4312        scale: f32,
4313    },
4314    /// The selection of a code editor moved, or an edit moved it. `version` is the document
4315    /// version it is read against, the same series `CodeChanged` counts, and an edit's
4316    /// change always arrives first. Columns are UTF-16 units and never fall between the
4317    /// two halves of a pair.
4318    SelectionChanged {
4319        version: u32,
4320        anchor_line: u32,
4321        anchor_column: u32,
4322        active_line: u32,
4323        active_column: u32,
4324    },
4325    /// The lines of a code editor that are on screen changed. Folded lines are skipped, so
4326    /// `first_line` and `last_line` are the first and last lines the reader can see.
4327    VisibleRangeChanged {
4328        version: u32,
4329        first_line: u32,
4330        last_line: u32,
4331    },
4332    /// A code editor gained or lost the keyboard focus.
4333    EditorFocusChanged {
4334        focused: bool,
4335    },
4336    /// The reader folded or unfolded the stretch that starts on `start_line`.
4337    FoldChanged {
4338        start_line: u32,
4339        collapsed: bool,
4340    },
4341    /// An input method started or ended a composition in a code editor. What is being
4342    /// composed stays in the Renderer: only the fact crosses.
4343    CompositionChanged {
4344        composing: bool,
4345    },
4346    /// The user asked to close a window. The window stays until the application removes its
4347    /// `Window` node. Delivered to the node.
4348    WindowCloseRequested,
4349    /// A window became the key window or stopped being it.
4350    WindowFocusChanged {
4351        focused: bool,
4352    },
4353    /// A window's outer frame moved or changed size, in screen dp. At most once a frame.
4354    WindowMoved {
4355        x: f32,
4356        y: f32,
4357        width: f32,
4358        height: f32,
4359    },
4360    /// A torn-off window being dragged. `phase` is 1 for a move, 2 for the end and 3 for a
4361    /// cancel; `over_window` is the node id of the window under the pointer, or 0.
4362    WindowDrag {
4363        phase: u32,
4364        screen_x: f32,
4365        screen_y: f32,
4366        over_window: u32,
4367    },
4368    /// A dragged window passing over a node that has `OnWindowDragOver`. `kind` is 1 for
4369    /// enter, 2 for move, 3 for leave and 4 for drop, `window` is the dragged window's node
4370    /// id, and the position is inside the node, in dp.
4371    WindowDragOver {
4372        kind: u32,
4373        window: u32,
4374        x: f32,
4375        y: f32,
4376    },
4377    /// A window that could not be opened here: the platform has no second window, or it
4378    /// refused. Delivered once, to the node.
4379    WindowUnavailable,
4380    /// The platform closed a window without asking. The window is already gone.
4381    WindowClosed,
4382    /// A window the application has no node for yet, with the `RestoreKey` it was made
4383    /// under (empty for a new one) and a request number. Delivered to the root.
4384    WindowRequested {
4385        key: &'a str,
4386        request: u32,
4387    },
4388    /// The user opened the application again while it had no window. Delivered to the
4389    /// root.
4390    ApplicationReopen,
4391    /// The node or a descendant inside it gained keyboard focus.
4392    FocusGained,
4393    /// A key was released while the node held focus.
4394    KeyUp {
4395        key: Key,
4396        shift_key: bool,
4397        ctrl_key: bool,
4398        alt_key: bool,
4399        meta_key: bool,
4400        /// Always false: a release does not repeat. Present so a key-up carries the same
4401        /// fields as a key-down.
4402        repeat: bool,
4403        /// The physical key as a USB HID usage value, the same on every layout.
4404        code: u32,
4405        /// The DOM `key` string, such as `"ArrowDown"` or `"a"`.
4406        text: &'a str,
4407    },
4408    /// The height of one row of a code editor in physical pixels, as it is drawn. Sent when
4409    /// the editor is first drawn and whenever the height changes.
4410    CodeMetrics {
4411        line_height_px: f64,
4412    },
4413    /// How far a code editor is scrolled down, in physical pixels. At most once a frame.
4414    CodeScrolled {
4415        offset_px: f64,
4416    },
4417    /// A file dialog ended. `request` is the number the Host gave it, `filter` is the
4418    /// position of the filter in use (`u32::MAX` when there is none) and `paths` holds the
4419    /// chosen paths separated by one NUL byte, empty unless the status is `Chosen`.
4420    /// Delivered to the Host itself, with no node and no handler.
4421    FileDialogResult {
4422        request: u32,
4423        status: FileDialogStatus,
4424        filter: u32,
4425        paths: &'a str,
4426    },
4427    /// One clipboard read ended. `request` is the number the Host gave it, `status` is a
4428    /// word from `clipboard::read_status`, `len` is the text's length in UTF-8 bytes and
4429    /// `text` the text itself, empty unless the status is text. Delivered to the Host itself,
4430    /// with no node and no handler.
4431    ClipboardText {
4432        request: u32,
4433        status: u32,
4434        len: u32,
4435        text: &'a str,
4436    },
4437    /// The one answer to an input or output request: a storage operation the browser
4438    /// carried out, or an operation on a file picked on the web. `request` is the number
4439    /// the Host gave it, and `data` is what the operation hands back: a value or a file
4440    /// that was read, or the keys joined by NUL, and nothing for an operation that only
4441    /// writes. Delivered to the Host itself, with no node and no handler.
4442    IoAnswer {
4443        request: u32,
4444        status: IoStatus,
4445        data: &'a [u8],
4446    },
4447    /// Files the Renderer now holds handles for: the answer to a file dialog that was
4448    /// chosen, or to a folder's `Entries` or `Child`. The handles are `first_handle`,
4449    /// `first_handle + 1` and so on, one per name. `names` holds the names separated by one
4450    /// NUL byte and `kinds` one letter per name, `f` for a file and `d` for a folder.
4451    /// `filter` is the position of the filter in use, `u32::MAX` when there is none.
4452    /// Delivered to the Host itself, with no node and no handler.
4453    FileHandles {
4454        request: u32,
4455        status: FileDialogStatus,
4456        filter: u32,
4457        delivery: FileDelivery,
4458        first_handle: u32,
4459        names: &'a str,
4460        kinds: &'a str,
4461    },
4462    /// Where the application's storage lives on a platform whose Host cannot work it out
4463    /// from the environment: Android's application files directory, which only a
4464    /// `Context` knows. Sent once by that Renderer at start. Delivered to the Host itself.
4465    StorageLocation(&'a str),
4466    /// Where a scroll container is, reported by the Renderer to the node's
4467    /// `OnScrollChanged` handler: at most once a frame while it moves, and once more with
4468    /// `settled` when it stops. Every length is in physical pixels, the unit the Renderer
4469    /// scrolls in, so a value read here and sent back in a `ScrollTo` is the same place.
4470    ///
4471    /// In a lazy list `item` is the first visible item and the main-axis offset is the
4472    /// distance into that item; the list does not know its whole length, so its main-axis
4473    /// `max` is `-1.0`. Elsewhere `item` is 0.
4474    ScrollChanged {
4475        item: u32,
4476        /// The movement ended: a drag, a fling or an animation came to rest.
4477        settled: bool,
4478        /// The container can still scroll towards the start of its main axis.
4479        can_scroll_backward: bool,
4480        /// The container can still scroll towards the end of its main axis.
4481        can_scroll_forward: bool,
4482        x_px: f64,
4483        y_px: f64,
4484        max_x_px: f64,
4485        max_y_px: f64,
4486        viewport_width_px: f64,
4487        viewport_height_px: f64,
4488    },
4489    /// A node's size motion came to rest, reported to the node's `OnMotionFinished`
4490    /// handler with the size it settled at, in dp.
4491    ///
4492    /// Sent once for each run that reaches its target: a run that is interrupted by a new
4493    /// target sends nothing, and only the one that settles does. The first layout and a
4494    /// layout that leaves the size as it was send nothing, and neither does a node removed
4495    /// while its size is moving. Under reduced motion the size changes in one frame and
4496    /// this arrives in that frame.
4497    MotionFinished {
4498        width_dp: f32,
4499        height_dp: f32,
4500    },
4501    /// Where a code editor draws its caret, in the window's dp with the scroll and the zoom
4502    /// already in it. At most once a frame, when the caret or the view moves.
4503    CaretRect {
4504        line: u32,
4505        column: u32,
4506        rect: crate::code::CodeRect,
4507    },
4508    /// The answer to one `QueryPositionRect`, carrying the request number the Host gave
4509    /// it. `None` where the position is not on screen.
4510    PositionRect {
4511        request: u32,
4512        rect: Option<crate::code::CodeRect>,
4513    },
4514    /// A pointer event over a code editor: every field a `Pointer` event has, with the same
4515    /// meaning and the same rules, and the place in the text under the pointer. `position`
4516    /// is `None` where the pointer is not over a character: over the gutter, past the end
4517    /// of a line or below the last one.
4518    CodePointer {
4519        kind: PointerKind,
4520        pointer_id: u32,
4521        pointer_type: PointerType,
4522        x: f32,
4523        y: f32,
4524        buttons: u32,
4525        button: u32,
4526        modifiers: u32,
4527        click_count: u32,
4528        delta_x: f32,
4529        delta_y: f32,
4530        delta_mode: WheelDeltaMode,
4531        timestamp_nanos: u64,
4532        position: Option<crate::code::Position>,
4533    },
4534    /// Every selection of a code editor, the primary first, read against `version`: sent
4535    /// while there is more than one, and once more when it comes back to one, to the same
4536    /// listener as `SelectionChanged`, which goes on reporting the primary alone.
4537    /// `selections` is 16-byte records, which [`crate::code::SelectionsChange`] reads.
4538    SelectionsChanged {
4539        version: u32,
4540        selections: &'a [u8],
4541    },
4542    /// What became of one `EditCodeGroup`, sent exactly once for each. `current_version`
4543    /// is the version after the last change the group made where it went in, and the
4544    /// document's version where it did not. `index` is the position in the group, as sent,
4545    /// of the edit that kept it out, or the number of edits that went in.
4546    CodeEditGroupResult {
4547        request_id: u32,
4548        status: EditGroupStatus,
4549        base_version: u32,
4550        current_version: u32,
4551        index: u32,
4552    },
4553    /// The handle a window's platform views are made against, sent for each window once a
4554    /// `NativeView` is in it, again when the handle or the backing scale changes, and with
4555    /// a zero handle when the window closes. The node is the `Window` node, or 0 for the
4556    /// single window. Delivered to the Host itself, with no handler.
4557    NativeViewParent {
4558        handle: NativeHandle,
4559        kind: NativeParentKind,
4560        /// The window's backing scale: how many pixels make one point.
4561        scale: f32,
4562    },
4563    /// A `NativeView`'s platform view took keyboard focus (`true`) or lost it, reported to
4564    /// the node's `OnNativeViewFocus` handler.
4565    NativeViewFocus {
4566        focused: bool,
4567    },
4568}
4569
4570/// A platform view, or the window it is made in, as the platform names it: an `NSView*`
4571/// or `UIView*` pointer, an `HWND` or an X11 window id. 0 is no view. The Renderer only
4572/// places the view; whoever made it still owns it and destroys it.
4573#[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
4574pub struct NativeHandle(pub u64);
4575
4576impl NativeHandle {
4577    /// No view: attaching it takes the node's view away.
4578    pub const NONE: NativeHandle = NativeHandle(0);
4579
4580    /// Whether this names no view.
4581    pub const fn is_none(self) -> bool {
4582        self.0 == 0
4583    }
4584}
4585
4586/// What kind of handle a window gives its platform views to be made against.
4587#[derive(Clone, Copy, Debug, Eq, PartialEq)]
4588#[repr(u16)]
4589pub enum NativeParentKind {
4590    /// The `NSView*` of a macOS window's content.
4591    AppKit = 1,
4592    /// A Windows top-level `HWND`.
4593    Win32 = 2,
4594    /// An X11 window id.
4595    X11 = 3,
4596    /// An Android view.
4597    Android = 4,
4598    /// The `UIView*` of an iOS window's content.
4599    UIKit = 5,
4600}
4601
4602impl TryFrom<u16> for NativeParentKind {
4603    type Error = ();
4604
4605    fn try_from(value: u16) -> Result<Self, ()> {
4606        match value {
4607            1 => Ok(Self::AppKit),
4608            2 => Ok(Self::Win32),
4609            3 => Ok(Self::X11),
4610            4 => Ok(Self::Android),
4611            5 => Ok(Self::UIKit),
4612            _ => Err(()),
4613        }
4614    }
4615}
4616
4617/// A rectangle in physical pixels, for [`ScrollTarget`].
4618#[derive(Clone, Copy, Debug, Default, PartialEq)]
4619pub struct Rect {
4620    pub x_px: f64,
4621    pub y_px: f64,
4622    pub width_px: f64,
4623    pub height_px: f64,
4624}
4625
4626impl Rect {
4627    pub const fn new(x_px: f64, y_px: f64, width_px: f64, height_px: f64) -> Self {
4628        Self {
4629            x_px,
4630            y_px,
4631            width_px,
4632            height_px,
4633        }
4634    }
4635}
4636
4637/// A request to scroll a container to an offset, written by `Batch::scroll_to`.
4638///
4639/// An axis left `None` is not touched, so setting one axis never sends a stale value for
4640/// the other. The Renderer keeps each value inside the range the content allows, and
4641/// ignores the request while the user is dragging or flinging the container.
4642#[derive(Clone, Copy, Debug, Default, PartialEq)]
4643pub struct ScrollTo {
4644    pub x_px: Option<f64>,
4645    pub y_px: Option<f64>,
4646    /// In a lazy list, the item the offset is measured from. 0 everywhere else.
4647    pub item: u32,
4648    pub animate: bool,
4649}
4650
4651/// How a rectangle is brought into view along one axis: CSS's `block` and `inline` values,
4652/// and `Keep` for an axis that must not move.
4653#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
4654#[repr(u16)]
4655pub enum ScrollAlign {
4656    /// The axis does not move.
4657    #[default]
4658    Keep = 0,
4659    Start = 1,
4660    Center = 2,
4661    End = 3,
4662    /// No movement when the rectangle is already in view, otherwise the smallest one that
4663    /// shows it. A rectangle larger than the viewport is aligned to its start.
4664    Nearest = 4,
4665}
4666
4667/// What a `ScrollIntoView` rectangle is measured from.
4668#[derive(Clone, Copy, Debug, PartialEq)]
4669pub enum ScrollTarget {
4670    /// The container's content: the origin is the content's top left at offset zero. Not
4671    /// for a lazy list, which has no content coordinates.
4672    Content(Rect),
4673    /// A descendant node of the container: the origin is that node's top left, and a
4674    /// rectangle with no width and no height means the whole node.
4675    Node(u32, Rect),
4676    /// An item of a lazy list by its index: the origin is the item's start, and a rectangle
4677    /// with no width and no height means the whole item.
4678    Item(u32, Rect),
4679}
4680
4681/// A request to bring a rectangle into view in one container, written by
4682/// `Batch::scroll_into_view`.
4683#[derive(Clone, Copy, Debug, PartialEq)]
4684pub struct ScrollIntoView {
4685    pub target: ScrollTarget,
4686    pub align_x: ScrollAlign,
4687    pub align_y: ScrollAlign,
4688    pub animate: bool,
4689}
4690
4691/// The bits of a `ScrollTo` record's flags word.
4692pub mod scroll_to_flags {
4693    pub const ANIMATE: u32 = 1;
4694    pub const X: u32 = 1 << 1;
4695    pub const Y: u32 = 1 << 2;
4696}
4697
4698/// The values of a `ScrollIntoView` record's target kind.
4699pub mod scroll_target_kind {
4700    pub const CONTENT: u16 = 0;
4701    pub const NODE: u16 = 1;
4702    pub const ITEM: u16 = 2;
4703}
4704
4705/// The bit of a `ScrollIntoView` record's flags.
4706pub mod scroll_into_view_flags {
4707    pub const ANIMATE: u16 = 1;
4708}
4709
4710/// The bits of a `ScrollChanged` event's flags word.
4711pub mod scroll_changed_flags {
4712    pub const SETTLED: u32 = 1;
4713    pub const CAN_SCROLL_BACKWARD: u32 = 1 << 1;
4714    pub const CAN_SCROLL_FORWARD: u32 = 1 << 2;
4715    /// Every bit that has a meaning. Any other bit set is a protocol error.
4716    pub const KNOWN: u32 = SETTLED | CAN_SCROLL_BACKWARD | CAN_SCROLL_FORWARD;
4717}
4718
4719pub const EVENT_SCHEMA: &[EventSchema] = &[
4720    EventSchema {
4721        name: "Clicked",
4722        tag: 1,
4723        payload: EventPayloadType::None,
4724    },
4725    EventSchema {
4726        name: "TextChanged",
4727        tag: 2,
4728        payload: EventPayloadType::Text,
4729    },
4730    EventSchema {
4731        name: "TextSubmitted",
4732        tag: 3,
4733        payload: EventPayloadType::Text,
4734    },
4735    EventSchema {
4736        name: "FocusLost",
4737        tag: 4,
4738        payload: EventPayloadType::None,
4739    },
4740    EventSchema {
4741        name: "ProtocolError",
4742        tag: 5,
4743        payload: EventPayloadType::ProtocolError,
4744    },
4745    EventSchema {
4746        name: "KeyDown",
4747        tag: 6,
4748        payload: EventPayloadType::KeyDown,
4749    },
4750    EventSchema {
4751        name: "RangeRequested",
4752        tag: 7,
4753        payload: EventPayloadType::Range,
4754    },
4755    EventSchema {
4756        name: "ValueChanged",
4757        // Tag 8 is the pointer event and 9 to 15 are reserved for the gesture events.
4758        tag: 16,
4759        payload: EventPayloadType::Double,
4760    },
4761    EventSchema {
4762        name: "WindowSizeChanged",
4763        tag: 17,
4764        payload: EventPayloadType::WindowSize,
4765    },
4766    // The three below address the Host itself rather than a node, so they carry no handler
4767    // and the Host answers them before it looks one up.
4768    EventSchema {
4769        name: "Resync",
4770        tag: 18,
4771        payload: EventPayloadType::None,
4772    },
4773    EventSchema {
4774        name: "LifecycleStart",
4775        tag: 19,
4776        payload: EventPayloadType::None,
4777    },
4778    EventSchema {
4779        name: "LifecycleStop",
4780        tag: 20,
4781        payload: EventPayloadType::None,
4782    },
4783    // Addressed to the Host rather than to a node, like the three above: it is a fact
4784    // about the window, not something that happened inside it.
4785    EventSchema {
4786        name: "DesignSystemResolved",
4787        tag: 21,
4788        payload: EventPayloadType::DesignSystem,
4789    },
4790    EventSchema {
4791        name: "FilesEntered",
4792        tag: 22,
4793        payload: EventPayloadType::None,
4794    },
4795    // One string for however many paths, which is the string convention unchanged. A
4796    // second way of carrying a list would be a second thing to keep in step.
4797    EventSchema {
4798        name: "FilesDropped",
4799        tag: 23,
4800        payload: EventPayloadType::Text,
4801    },
4802    // Both address the Host itself, like the resolved design system: a notification is not
4803    // in the tree, so there is no node and no handler to name.
4804    EventSchema {
4805        name: "NotificationActivated",
4806        tag: 24,
4807        payload: EventPayloadType::NotificationActivation,
4808    },
4809    EventSchema {
4810        name: "NotificationPermissionChanged",
4811        tag: 25,
4812        payload: EventPayloadType::NotificationPermission,
4813    },
4814    EventSchema {
4815        name: "CodeChanged",
4816        tag: 26,
4817        payload: EventPayloadType::CodeChange,
4818    },
4819    EventSchema {
4820        name: "CodeEditRejected",
4821        tag: 27,
4822        payload: EventPayloadType::CodeEditRejected,
4823    },
4824    EventSchema {
4825        name: "CodeHovered",
4826        tag: 28,
4827        payload: EventPayloadType::CodeHover,
4828    },
4829    EventSchema {
4830        name: "CodeSaveRequested",
4831        tag: 29,
4832        payload: EventPayloadType::CodeSave,
4833    },
4834    EventSchema {
4835        name: "DecorationActivated",
4836        tag: 30,
4837        payload: EventPayloadType::Decoration,
4838    },
4839    EventSchema {
4840        name: "AnimationEvent",
4841        tag: 31,
4842        payload: EventPayloadType::Animation,
4843    },
4844    // About the platform rather than a node, like the notification permission.
4845    EventSchema {
4846        name: "ReducedMotionChanged",
4847        tag: 32,
4848        payload: EventPayloadType::ReducedMotion,
4849    },
4850    // Tag 8 is the pointer event and 9 stays reserved. It is listed last because this table
4851    // is append only, not because its tag is the highest.
4852    EventSchema {
4853        name: "Pointer",
4854        tag: 8,
4855        payload: EventPayloadType::Pointer,
4856    },
4857    // Tags 26 to 32 are taken by events other requirements have numbered.
4858    EventSchema {
4859        name: "ZoomChanged",
4860        tag: 33,
4861        payload: EventPayloadType::Zoom,
4862    },
4863    EventSchema {
4864        name: "SelectionChanged",
4865        tag: 34,
4866        payload: EventPayloadType::CodeSelection,
4867    },
4868    EventSchema {
4869        name: "VisibleRangeChanged",
4870        tag: 35,
4871        payload: EventPayloadType::CodeVisibleRange,
4872    },
4873    EventSchema {
4874        name: "EditorFocusChanged",
4875        tag: 36,
4876        payload: EventPayloadType::CodeFocus,
4877    },
4878    EventSchema {
4879        name: "FoldChanged",
4880        tag: 37,
4881        payload: EventPayloadType::CodeFold,
4882    },
4883    EventSchema {
4884        name: "CompositionChanged",
4885        tag: 38,
4886        payload: EventPayloadType::CodeComposition,
4887    },
4888    EventSchema {
4889        name: "WindowCloseRequested",
4890        tag: 39,
4891        payload: EventPayloadType::None,
4892    },
4893    EventSchema {
4894        name: "WindowFocusChanged",
4895        tag: 40,
4896        payload: EventPayloadType::WindowFocus,
4897    },
4898    EventSchema {
4899        name: "WindowMoved",
4900        tag: 41,
4901        payload: EventPayloadType::WindowMove,
4902    },
4903    EventSchema {
4904        name: "WindowDrag",
4905        tag: 42,
4906        payload: EventPayloadType::WindowDrag,
4907    },
4908    EventSchema {
4909        name: "WindowDragOver",
4910        tag: 43,
4911        payload: EventPayloadType::WindowDragOver,
4912    },
4913    EventSchema {
4914        name: "WindowUnavailable",
4915        tag: 44,
4916        payload: EventPayloadType::None,
4917    },
4918    EventSchema {
4919        name: "WindowClosed",
4920        tag: 45,
4921        payload: EventPayloadType::None,
4922    },
4923    EventSchema {
4924        name: "WindowRequested",
4925        tag: 46,
4926        payload: EventPayloadType::WindowRequest,
4927    },
4928    EventSchema {
4929        name: "ApplicationReopen",
4930        tag: 47,
4931        payload: EventPayloadType::None,
4932    },
4933    EventSchema {
4934        name: "FocusGained",
4935        tag: 48,
4936        payload: EventPayloadType::None,
4937    },
4938    EventSchema {
4939        name: "KeyUp",
4940        tag: 49,
4941        payload: EventPayloadType::KeyDown,
4942    },
4943    // Like the notification events this addresses the Host itself: a dialog is not in the tree, so there is no
4944    // node and no handler to name, and the request number finds the callback.
4945    EventSchema {
4946        name: "FileDialogResult",
4947        tag: 50,
4948        payload: EventPayloadType::FileDialogResult,
4949    },
4950    // What became of a grouped edit of a code editor, reported to the editor's own handler.
4951    EventSchema {
4952        name: "CodeEditGroupResult",
4953        tag: 51,
4954        payload: EventPayloadType::CodeEditGroupResult,
4955    },
4956    // Tags 52 and 53 are held by events other requirements have numbered. Like a file
4957    // dialog's end, a clipboard read addresses the Host itself and is found by its request
4958    // number.
4959    EventSchema {
4960        name: "ClipboardText",
4961        tag: 56,
4962        payload: EventPayloadType::ClipboardText,
4963    },
4964    // The answer to a storage operation, and to a file operation on the web.
4965    EventSchema {
4966        name: "IoAnswer",
4967        tag: 57,
4968        payload: EventPayloadType::IoAnswer,
4969    },
4970    // Files a dialog, or a folder, handed the Renderer handles for.
4971    EventSchema {
4972        name: "FileHandles",
4973        tag: 58,
4974        payload: EventPayloadType::FileHandles,
4975    },
4976    // Android's files directory, which the Host cannot find on its own. A string, like a
4977    // text change, so it needs no payload type of its own.
4978    EventSchema {
4979        name: "StorageLocation",
4980        tag: 59,
4981        payload: EventPayloadType::Text,
4982    },
4983    // Where a scroll container is, reported to the node's own handler.
4984    EventSchema {
4985        name: "ScrollChanged",
4986        tag: 60,
4987        payload: EventPayloadType::ScrollChanged,
4988    },
4989    // The handle a window's platform views are made against, addressed to the Host itself.
4990    EventSchema {
4991        name: "NativeViewParent",
4992        tag: 61,
4993        payload: EventPayloadType::NativeViewParent,
4994    },
4995    // A platform view took or lost keyboard focus. One word and its padding, the shape the
4996    // code editor's focus report has.
4997    EventSchema {
4998        name: "NativeViewFocus",
4999        tag: 62,
5000        payload: EventPayloadType::CodeFocus,
5001    },
5002    // 51 to 53 are numbered for events that are not here yet. Both of these carry one
5003    // `f64` of physical pixels, the shape `ValueChanged` has.
5004    EventSchema {
5005        name: "CodeMetrics",
5006        tag: 54,
5007        payload: EventPayloadType::Double,
5008    },
5009    EventSchema {
5010        name: "CodeScrolled",
5011        tag: 55,
5012        payload: EventPayloadType::Double,
5013    },
5014    // A node's size motion settled, reported to the node's own handler.
5015    EventSchema {
5016        name: "MotionFinished",
5017        tag: 63,
5018        payload: EventPayloadType::MotionFinished,
5019    },
5020    // Where a code editor's caret is drawn,
5021    // and the answer to a question about where a position is.
5022    EventSchema {
5023        name: "CaretRect",
5024        tag: 64,
5025        payload: EventPayloadType::CodeCaretRect,
5026    },
5027    EventSchema {
5028        name: "PositionRect",
5029        tag: 65,
5030        payload: EventPayloadType::CodePositionRect,
5031    },
5032    // A pointer over a code editor, with the place in the text under it.
5033    EventSchema {
5034        name: "CodePointer",
5035        tag: 66,
5036        payload: EventPayloadType::CodePointer,
5037    },
5038    // About the platform rather than a node, like the reduced motion setting.
5039    EventSchema {
5040        name: "ColorSchemeChanged",
5041        tag: 52,
5042        payload: EventPayloadType::ColorScheme,
5043    },
5044    // Every selection of a code editor, to its selection listener.
5045    EventSchema {
5046        name: "SelectionsChanged",
5047        tag: 67,
5048        payload: EventPayloadType::CodeSelections,
5049    },
5050    // About a window's screen rather than a node: the device pixels in one dp. Listed last
5051    // because this table is append only, not because its tag is the highest.
5052    EventSchema {
5053        name: "DensityChanged",
5054        tag: 53,
5055        payload: EventPayloadType::Density,
5056    },
5057];
5058
5059/// One argument of a boundary operation.
5060///
5061/// The set is deliberately tiny, because only primitives, pointers and lengths cross the
5062/// boundary. Every platform binding can then be generated from the same list.
5063#[derive(Clone, Copy, Debug, Eq, PartialEq)]
5064pub enum BoundaryParam {
5065    /// A readable byte range. It arrives as a direct byte buffer and a length on Android,
5066    /// as a pointer and a length on desktop.
5067    Bytes { name: &'static str },
5068    /// A 64-bit platform frame timestamp.
5069    Nanos { name: &'static str },
5070}
5071
5072impl BoundaryParam {
5073    pub const fn name(self) -> &'static str {
5074        match self {
5075            Self::Bytes { name } | Self::Nanos { name } => name,
5076        }
5077    }
5078}
5079
5080/// One logical boundary operation, stated without saying which side calls it.
5081///
5082/// `symbol` is the Host's C export. Every platform binding, the GraalVM function
5083/// declarations, the Android shims and the browser's imports and trampoline, is a rendering
5084/// of this table, which is why none of them is written by hand.
5085#[derive(Clone, Copy, Debug, Eq, PartialEq)]
5086pub struct BoundaryOp {
5087    /// Direction-neutral name, in PascalCase.
5088    pub name: &'static str,
5089    pub symbol: &'static str,
5090    pub params: &'static [BoundaryParam],
5091    /// Whether the operation answers with a mutation batch.
5092    pub returns_batch: bool,
5093    /// Whether the call may skip the runtime's thread state transition on Android. That
5094    /// is only sound for a call that cannot run long, because the thread stays runnable
5095    /// and the garbage collector cannot suspend it while the call is in flight. A call
5096    /// that runs the VirtualDom can run long.
5097    pub fast: bool,
5098}
5099
5100pub const BOUNDARY_SCHEMA: &[BoundaryOp] = &[
5101    BoundaryOp {
5102        name: "Init",
5103        symbol: "compose_rust_host_init",
5104        params: &[BoundaryParam::Bytes { name: "handshake" }],
5105        returns_batch: true,
5106        fast: false,
5107    },
5108    BoundaryOp {
5109        name: "DispatchEvent",
5110        symbol: "compose_rust_host_dispatch_event",
5111        params: &[BoundaryParam::Bytes { name: "event" }],
5112        returns_batch: true,
5113        fast: false,
5114    },
5115    BoundaryOp {
5116        name: "RenderFrame",
5117        symbol: "compose_rust_host_render_frame",
5118        params: &[BoundaryParam::Nanos {
5119            name: "frameTimeNanos",
5120        }],
5121        returns_batch: true,
5122        fast: false,
5123    },
5124    BoundaryOp {
5125        name: "ReleaseBatch",
5126        symbol: "compose_rust_host_release_batch",
5127        params: &[],
5128        returns_batch: false,
5129        fast: true,
5130    },
5131    BoundaryOp {
5132        name: "Shutdown",
5133        symbol: "compose_rust_host_shutdown",
5134        params: &[],
5135        returns_batch: false,
5136        fast: false,
5137    },
5138];
5139
5140/// The JVM class the Android shims bind to. The Kotlin file is generated under the same
5141/// name, so the two sides cannot drift.
5142pub const ANDROID_BRIDGE_CLASS: &str = "dev/darkpyonix/composerust/ui/platform/HostBridge";
5143
5144// ---------------------------------------------------------------------------------------
5145// The browser's shared linear memory.
5146//
5147// One `WebAssembly.Memory` holds both modules' data. The Kotlin module defines and exports
5148// it, because a Kotlin/Wasm module has no way to import one, and the Rust module is linked
5149// with `--import-memory` so that the arena the Host writes is the arena the Renderer reads.
5150// Nothing below crosses the boundary as data: these are the addresses and offsets both
5151// generated halves are written against.
5152// ---------------------------------------------------------------------------------------
5153
5154/// The first address that belongs to the Rust module.
5155///
5156/// Below it is the Kotlin module's `kotlin.wasm.unsafe` allocator; at and above it are the
5157/// Rust module's data, stack and heap, which the linker is told with `--global-base`. Two
5158/// allocators handing out addresses in one memory is the hazard: an overlap does not crash,
5159/// it draws the wrong screen, so the Renderer checks which side of this line its own
5160/// addresses fall on before it makes the first boundary call.
5161pub const WEB_RUST_REGION_BASE: u32 = 4 * 1024 * 1024;
5162
5163/// One field of the `MutationBatch` record the Host writes into the shared memory.
5164#[derive(Clone, Copy, Debug, Eq, PartialEq)]
5165pub struct WebBatchField {
5166    /// PascalCase, so the generated Kotlin constant reads as a name rather than an offset.
5167    pub name: &'static str,
5168    pub offset: u32,
5169    pub width: u32,
5170    pub description: &'static str,
5171}
5172
5173/// `MutationBatch` as a wasm32 target lays it out.
5174///
5175/// The offsets are written down rather than read from `offset_of!` because codegen runs on
5176/// the machine that generates, not the machine that runs: a 64-bit host makes the same
5177/// `#[repr(C)]` struct 24 bytes with an 8 byte pointer. The generated wasm glue asserts
5178/// this table against the real layout, so a compiler that disagrees stops that build
5179/// instead of producing a Renderer that reads the wrong four bytes.
5180pub const WEB_BATCH_FIELDS: &[WebBatchField] = &[
5181    WebBatchField {
5182        name: "Address",
5183        offset: 0,
5184        width: 4,
5185        description: "where the batch starts, as an address in the shared memory",
5186    },
5187    WebBatchField {
5188        name: "Length",
5189        offset: 4,
5190        width: 4,
5191        description: "the batch's length in bytes",
5192    },
5193    WebBatchField {
5194        name: "Result",
5195        offset: 8,
5196        width: 8,
5197        description: "the handler's synchronous result",
5198    },
5199];
5200
5201/// How long that record is, including the padding `#[repr(C)]` adds before the result.
5202pub const WEB_BATCH_BYTES: u32 = 16;
5203
5204/// How much room the Host lends the Renderer to encode one event into.
5205///
5206/// The same figure the Android connection allocates for the same job. An event that would
5207/// not fit is refused by the encoder rather than truncated.
5208pub const WEB_EVENT_BUFFER_BYTES: u32 = 4096;
5209
5210/// The largest event buffer the Host lends a browser Renderer.
5211///
5212/// An event that does not fit in the first buffer is encoded into a larger one the Host
5213/// lends on request, doubling each time, and this is where the doubling stops. An event
5214/// larger than this is refused rather than cut short: a single event that large is a bug
5215/// in whatever produced it, and lending without a ceiling would turn that bug into running
5216/// out of memory. The other platforms grow their own buffers to the same ceiling.
5217pub const WEB_EVENT_BUFFER_MAX_BYTES: u32 = 64 * 1024 * 1024;
5218
5219/// The Host export a browser Renderer borrows a larger event buffer from.
5220///
5221/// It is setup, like `compose_rust_host_web_start`, not a boundary operation: the
5222/// Renderer calls it only when an event outgrows the buffer it has, and keeps what it gets.
5223/// It goes through the trampoline like the boundary operations, in the slot after theirs.
5224pub const WEB_LEND_EVENT_BUFFER_SYMBOL: &str = "compose_rust_host_web_lend_event_buffer";
5225
5226/// Where the event buffer starts inside the block `compose_rust_host_web_start` reports.
5227///
5228/// The out record comes first, at offset zero, and the event buffer follows it.
5229pub const WEB_EVENT_BUFFER_OFFSET: u32 = WEB_BATCH_BYTES;
5230
5231/// The extra Host export a browser needs, because a page has no library loader.
5232///
5233/// It does what `JNI_OnLoad` does on Android, registering the root component and installing
5234/// the renderer API, and it answers with the address of the block above.
5235pub const WEB_START_SYMBOL: &str = "compose_rust_host_web_start";
5236
5237/// The wasm import module the Host's frame request comes from.
5238///
5239/// This direction has no JavaScript on it: the page hands Kotlin's exported function object
5240/// straight to the Rust instantiation, which the engine binds as a wasm-to-wasm call. It can,
5241/// because Rust is instantiated second and Kotlin's exports already exist by then.
5242pub const WEB_RENDERER_IMPORT_MODULE: &str = "compose_rust_renderer";
5243
5244/// The global the loader publishes the trampoline's table under.
5245///
5246/// The loader creates the table and the Renderer's generated `installHost` fills it with the
5247/// Host's exports. That body is a `@JsFun`, inlined into the import object module Kotlin
5248/// generates, so the only name it can reach the loader's table through is a property of the
5249/// global object. Nothing reads it on a call: a call goes through the table from wasm.
5250pub const WEB_TABLE_GLOBAL: &str = "__composeRustHostTable";
5251
5252/// The global the loader module publishes the compiled Host module under.
5253///
5254/// Besides the trampoline, compiling is all the page does, and the reason the page has to
5255/// do it at all is that compiling is asynchronous while the boundary is not: the fetch has
5256/// to have finished before the Renderer's `main` runs. Everything after it, the memory, the
5257/// Host's imports, the entry point and filling the table, is in the generated Kotlin,
5258/// because only the Renderer's own module can name them.
5259pub const WEB_MODULE_GLOBAL: &str = "__composeRustHostModule";