Skip to main content

compose_rust/
protocol.rs

1//! Fixed-layout little-endian boundary protocol.
2
3use crate::schema::{
4    AssetKind, BackgroundRepeat, ColorScheme, DesignSystem, FileDelivery, FileDialogKind,
5    FileDialogStatus, FileOp, IoStatus, Key, MAX_MODIFIER_WORDS, MaterialRole, MessageDuration,
6    MessageHorizontal, MessagePlacement, MessageVertical, Modifier, MotionRole,
7    NotificationImportance, NotificationPermission, NotificationPresentation, Paint, PropertyKind,
8    SEMANTICS_STATE_MASK, Selection, SemanticsRole, ShapeRole, SpaceRole, TYPE_ROLE_COUNT, Theme,
9    WidgetKind, modifier_extra_words,
10};
11use core::fmt;
12
13const TAG_ENVELOPE: u16 = 0;
14const TAG_CREATE: u16 = 1;
15const TAG_SET_PROP: u16 = 2;
16const TAG_SET_MODIFIER: u16 = 3;
17const TAG_INSERT: u16 = 4;
18const TAG_MOVE: u16 = 5;
19const TAG_REMOVE: u16 = 6;
20const TAG_SET_TEXT: u16 = 7;
21const TAG_APPEND_TEXT: u16 = 8;
22const TAG_SET_THEME: u16 = 9;
23const TAG_REGISTER_ASSET: u16 = 10;
24const TAG_RELEASE_ASSET: u16 = 11;
25const TAG_SHOW_MESSAGE: u16 = 12;
26const TAG_SET_WINDOW: u16 = 13;
27const TAG_POST_NOTIFICATION: u16 = 14;
28const TAG_WITHDRAW_NOTIFICATION: u16 = 15;
29const TAG_REQUEST_NOTIFICATION_PERMISSION: u16 = 16;
30const TAG_EDIT_CODE: u16 = 17;
31const TAG_START_ANIMATION: u16 = 18;
32const TAG_CONTROL_ANIMATION: u16 = 19;
33// 20 to 22 are the code editor's: the selection, a range to bring into view, a fold.
34const TAG_SET_SELECTION: u16 = 20;
35const TAG_REVEAL_RANGE: u16 = 21;
36const TAG_SET_FOLDED: u16 = 22;
37// 23 and 24 are the windows': a theme for one window, and bringing one forward.
38const TAG_SET_WINDOW_THEME: u16 = 23;
39const TAG_FOCUS_WINDOW: u16 = 24;
40const TAG_REQUEST_FOCUS: u16 = 25;
41// 26 asks for a platform file dialog. Its answer is the event numbered 50.
42const TAG_SHOW_FILE_DIALOG: u16 = 26;
43/// `ShowFileDialog` after its header: the request, the window, the kind and the default
44/// filter, then four string references. 44 bytes, so the record is 48.
45const SHOW_FILE_DIALOG_PAYLOAD_LEN: usize = 4 + 4 + 2 + 2 + 4 * 8;
46// 27 sets application-level overlay theme tokens for Dialog, Menu, Dropdown and Sheet.
47const TAG_SET_OVERLAY_TOKENS: u16 = 27;
48// 28 replaces several ranges of a code editor's document as one edit, all of them or none.
49const TAG_EDIT_CODE_GROUP: u16 = 28;
50/// `EditCodeGroup` in full: the 4 byte head, the node, the request, the base version and
51/// the reference to the edits.
52const EDIT_CODE_GROUP_LEN: usize = 24;
53const TAG_SET_SCROLL_OFFSET: u16 = 30;
54/// 9 u16 fields (18 bytes) + 1 u16 reserved (2 bytes) + 1 u32 scrim (4 bytes) = 24 bytes.
55const OVERLAY_TOKENS_PAYLOAD_LEN: usize = 56;
56/// What `toast_border_width` is sent as when the design system keeps its own line.
57const TOAST_BORDER_DESIGN_SYSTEM: u16 = u16::MAX;
58// 29 puts plain text on the platform clipboard. Nothing answers it.
59const TAG_SET_CLIPBOARD_TEXT: u16 = 29;
60// 30 is held for the code editor's scroll offset. 31 asks for the clipboard's plain text,
61// answered by one `ClipboardText` event carrying the same request number.
62const TAG_READ_CLIPBOARD: u16 = 31;
63// 32 asks the Renderer to carry out one storage operation, answered by one `IoAnswer`
64// event carrying the same request number.
65const TAG_STORAGE_CALL: u16 = 32;
66/// `StorageCall` after its header: the request, the operation, a reserved half word, then
67/// the store, the key and the bytes as three references. 32 bytes, so the record is 36.
68const STORAGE_CALL_PAYLOAD_LEN: usize = 4 + 2 + 2 + 3 * 8;
69// 33 asks something of a file the Renderer holds a handle for, answered by one `IoAnswer`
70// or `FileHandles` event carrying the same request number. 34 lets go of such a handle and
71// is not answered.
72const TAG_FILE_CALL: u16 = 33;
73/// `FileCall` after its header: the request, the operation, the create flag and the handle,
74/// then the name's and the bytes' references. 28 bytes, so the record is 32.
75const FILE_CALL_PAYLOAD_LEN: usize = 4 + 2 + 2 + 4 + 8 + 8;
76const TAG_RELEASE_FILE_HANDLE: u16 = 34;
77// 35 asks a scroll
78// container to go to an offset and 36 to bring a rectangle into view. Both are requests:
79// the Renderer owns the position and reports what it did in `ScrollChanged`.
80const TAG_SCROLL_TO: u16 = 35;
81const TAG_SCROLL_INTO_VIEW: u16 = 36;
82// 37 and 38 are the platform view commands, below. 39 asks a code editor where a position
83// is on screen, answered by one `PositionRect` event carrying the same request number.
84const TAG_QUERY_POSITION_RECT: u16 = 39;
85/// `QueryPositionRect` in full: the 4 byte head, the node, the request, the line and the
86/// column.
87const QUERY_POSITION_RECT_LEN: usize = 20;
88// 41 sets every selection of a code editor at once.
89const TAG_SET_SELECTIONS: u16 = 41;
90/// `SetSelections` in full: the 4 byte head, the node, the base version and the reference
91/// to the selections.
92const SET_SELECTIONS_LEN: usize = 20;
93// 40 puts a snippet into a code editor and opens its tab stops.
94const TAG_INSERT_SNIPPET: u16 = 40;
95/// `InsertSnippet` in full: the 4 byte head, the node, the base version, the range and the
96/// snippet's reference.
97const INSERT_SNIPPET_LEN: usize = 36;
98/// `ScrollTo` in full: the 4 byte head, the node, the item, the flags and two `f64`.
99const SCROLL_TO_LEN: usize = 32;
100/// `ScrollIntoView` in full: the 4 byte head, the node, the target, four `u16` and four `f64`.
101const SCROLL_INTO_VIEW_LEN: usize = 52;
102// 37 puts a platform view the Host made into a `NativeView` node's place, or takes it out
103// with handle 0. 38 moves keyboard focus into that view or back to the scene. Neither is
104// answered; focus moving is reported in `NativeViewFocus`.
105const TAG_ATTACH_NATIVE_VIEW: u16 = 37;
106const TAG_FOCUS_NATIVE_VIEW: u16 = 38;
107/// `AttachNativeView` in full: the 4 byte head, the node, two reserved words, and the handle
108/// as a `u64` on an eight byte boundary.
109const ATTACH_NATIVE_VIEW_LEN: usize = 24;
110/// `FocusNativeView` in full: the 4 byte head, the node, the focus word, and a trailing
111/// reserved word.
112const FOCUS_NATIVE_VIEW_LEN: usize = 16;
113/// The head of a `StartAnimation` record, before its keyframes.
114const ANIMATION_HEADER_LEN: usize = 52;
115/// A keyframe before its value: offset, timing, step position, flags and four numbers.
116const KEYFRAME_HEAD_LEN: usize = 24;
117/// One transform function: its kind and six numbers.
118const TRANSFORM_FUNCTION_LEN: usize = 28;
119const KEYFRAME_FROM_PRESENTED: u16 = 1;
120const ENVELOPE_LEN: usize = 12;
121/// `SetTheme` after its header: four `u16` fields, one font slot per type role, and the
122/// palette's `(offset, len)` reference. 52 bytes, so the record is 56.
123pub const THEME_PAYLOAD_LEN: usize = 8 + 4 * TYPE_ROLE_COUNT + 8;
124/// The shortest mutation record on the wire (`RequestNotificationPermission`: the 4-byte
125/// header and nothing else).
126const MIN_RECORD_LEN: usize = 4;
127
128const VALUE_NONE: u16 = 0;
129const VALUE_STRING: u16 = 1;
130const VALUE_BOOL: u16 = 2;
131const VALUE_I64: u16 = 3;
132const VALUE_F32: u16 = 4;
133/// An opaque byte run in the arena. Same `(offset, length)` layout as a string, with no
134/// UTF-8 check, because a Canvas command list is not text.
135const VALUE_BYTES: u16 = 5;
136
137#[derive(Clone, Debug, PartialEq)]
138pub enum PropertyValue<'a> {
139    None,
140    String(&'a str),
141    Bool(bool),
142    Integer(i64),
143    Float(f32),
144    Bytes(&'a [u8]),
145}
146
147#[derive(Clone, Debug, PartialEq)]
148pub enum Mutation<'a> {
149    Create {
150        node_id: u32,
151        widget: WidgetKind,
152    },
153    SetProp {
154        node_id: u32,
155        property: PropertyKind,
156        value: PropertyValue<'a>,
157    },
158    SetModifier {
159        node_id: u32,
160        index: u16,
161        modifier: Modifier,
162    },
163    Insert {
164        parent_id: u32,
165        node_id: u32,
166        index: u32,
167    },
168    Move {
169        parent_id: u32,
170        node_id: u32,
171        index: u32,
172    },
173    Remove {
174        node_id: u32,
175    },
176    SetText {
177        node_id: u32,
178        text: &'a str,
179        selection: Option<Selection>,
180    },
181    /// Appends the streamed tail to a Text node instead of resending the whole string.
182    AppendText {
183        node_id: u32,
184        text: &'a str,
185    },
186    /// The root theme. Sent once as the first record of the initial batch.
187    SetTheme(Theme),
188    /// What the application asked of its own window.
189    ///
190    /// Written once per rebuild beside the theme, and read by the Renderer before it
191    /// stands the window up: `compose_rust_host_init` answers with the first batch, so
192    /// the setting is in hand before there is a window to apply it to. Platforms where
193    /// the window is not ours ignore it, which is not an error but an absence of anywhere
194    /// to put it.
195    SetWindow(crate::schema::Window),
196    /// Hands the Renderer the bytes of one asset. The Renderer copies them into its own
197    /// cache inside this call, because the batch buffer is only valid for the call that
198    /// carries it and an image has to outlive the frame that draws it.
199    RegisterAsset {
200        asset_id: u32,
201        kind: AssetKind,
202        bytes: &'a [u8],
203    },
204    /// Drops an asset from the Renderer's cache. The Host owns the lifetime.
205    ReleaseAsset {
206        asset_id: u32,
207    },
208    /// Says a sentence to the user once. It is not a node, because the Host would then
209    /// have to hold "showing until four seconds from now" and run a render to take it
210    /// away again. How long it stays, where it sits and what happens when a second one
211    /// arrives while the first is up are all the Renderer's.
212    ///
213    /// `handler_id` is what the action label reports when it is pressed, or 0 when the
214    /// message has no action, in which case `action` is empty too.
215    ///
216    /// `placement` and `offset_dp` are where the application asked for it to be drawn,
217    /// and `None` leaves each to the design system. On the wire an absent placement is two
218    /// zero tags and an absent offset is a NaN, so a record written before they existed
219    /// reads as a message with neither.
220    ShowMessage {
221        handler_id: u64,
222        text: &'a str,
223        action: &'a str,
224        duration: MessageDuration,
225        placement: Option<MessagePlacement>,
226        offset_dp: Option<f32>,
227    },
228    /// Asks the platform to show one notification outside the window.
229    ///
230    /// Not a node, for the same reason a message is not: it outlives the component that
231    /// posted it, and when it goes away depends on what the user does in the notification
232    /// centre, which the Host never hears about. Posting again under the same `key`
233    /// replaces it. An empty `key` asks the Renderer to name it, and such a notification
234    /// can be neither replaced nor withdrawn. An empty action label means no button.
235    PostNotification {
236        key: &'a str,
237        title: &'a str,
238        body: &'a str,
239        channel: &'a str,
240        action_1: &'a str,
241        action_2: &'a str,
242        importance: NotificationImportance,
243        presentation: NotificationPresentation,
244    },
245    /// Takes back the notification posted under `key`, if it is still showing.
246    WithdrawNotification {
247        key: &'a str,
248    },
249    /// Asks the platform for permission to show notifications. It carries nothing: the
250    /// answer comes back as a permission event.
251    RequestNotificationPermission,
252    /// Replaces a range of a code editor's document, as it stood at `base_version`, with
253    /// `text`.
254    ///
255    /// The Renderer owns the document, so this is a request and not an assignment: where
256    /// the reader has typed since that version the range is moved along with what they
257    /// typed, and where they typed in the same place the edit is refused and
258    /// `CodeEditRejected` names `request_id`. An edit that is applied comes back as an
259    /// ordinary `CodeChanged`, so the version stays one sequence whoever made the edit.
260    EditCode {
261        node_id: u32,
262        request_id: u32,
263        base_version: u32,
264        start_line: u32,
265        start_column: u32,
266        end_line: u32,
267        end_column: u32,
268        text: &'a str,
269    },
270    /// Hands the Renderer one animation to play on its own frame clock until it ends.
271    /// Nothing crosses the boundary while it plays unless it asked for events.
272    StartAnimation(crate::schema::Animation<'a>),
273    /// Pauses, resumes or cancels one animation the Renderer is playing. A key the Renderer
274    /// does not hold, or an id that is not the one it holds, is left alone: an animation
275    /// that ended on its own is not an error to stop.
276    ControlAnimation {
277        node_id: u32,
278        animation_id: u32,
279        property: crate::schema::AnimatedProperty,
280        slot: u8,
281        op: crate::schema::AnimationControl,
282        /// On the Renderer's frame clock. Zero means the first frame that draws it.
283        at_time_nanos: u64,
284    },
285    /// Puts a code editor's selection between two places in the document as it stood at
286    /// `base_version`. Both ends are moved along with whatever was typed since, and an end
287    /// that is outside the document, or between the two halves of a pair, drops the
288    /// command and comes back as a protocol error.
289    SetSelection {
290        node_id: u32,
291        base_version: u32,
292        anchor_line: u32,
293        anchor_column: u32,
294        active_line: u32,
295        active_column: u32,
296    },
297    /// Scrolls a code editor until a range of the document, as it stood at `base_version`,
298    /// is on screen. A range inside a folded stretch unfolds it first.
299    RevealRange {
300        node_id: u32,
301        base_version: u32,
302        start_line: u32,
303        start_column: u32,
304        end_line: u32,
305        end_column: u32,
306        align: crate::schema::RevealAlign,
307    },
308    /// Folds or unfolds the stretch of a code editor that starts on `start_line`.
309    SetFolded {
310        node_id: u32,
311        start_line: u32,
312        collapsed: bool,
313    },
314    /// A theme for one `Window` node, over the application's. The payload is
315    /// `SetTheme`'s, after the node id. A window without one follows the application's.
316    SetWindowTheme {
317        node_id: u32,
318        theme: Theme,
319    },
320    /// Brings a window forward and makes it the key window. A command and not a
321    /// property: it happens once.
322    FocusWindow {
323        node_id: u32,
324    },
325    /// Moves input focus to `node_id`, or clears focus when `node_id` is 0.
326    RequestFocus {
327        node_id: u32,
328    },
329    /// Asks the platform to show a file dialog on a window and answers later, once, with a
330    /// `FileDialogResult` event that carries `request`.
331    ///
332    /// `window` is a `Window` node id, or 0 for the implicit root window. `filters` is one
333    /// string: a label and its comma-joined extensions as a pair, pairs joined by NUL
334    /// (`"Images\0png,jpg\0Docs\0pdf,txt"`). `default_filter` is the position of the
335    /// filter selected first.
336    ShowFileDialog {
337        request: u32,
338        window: u32,
339        kind: FileDialogKind,
340        default_filter: u16,
341        title: &'a str,
342        directory: &'a str,
343        name: &'a str,
344        filters: &'a str,
345    },
346    /// Application-level overlay theme tokens for Dialog, Menu, Dropdown and Sheet.
347    SetOverlayTokens(crate::schema::OverlayTokens),
348    /// Puts `text` on the platform clipboard as plain text.
349    ///
350    /// Not a node and not answered: a Renderer with no clipboard drops it.
351    SetClipboardText {
352        text: &'a str,
353    },
354    /// Asks for the plain text on the platform clipboard. Answered exactly once, later, by a
355    /// `ClipboardText` event that carries `request`.
356    ReadClipboard {
357        request: u32,
358    },
359    /// Scrolls a code editor so that `offset_px` physical pixels of its document are above
360    /// the top of its view. The Renderer keeps the offset inside what the document allows,
361    /// and reports where it ended up through `CodeScrolled` like any other scroll.
362    SetScrollOffset {
363        node_id: u32,
364        offset_px: f64,
365    },
366    /// Asks the Renderer to carry out one operation on the application's storage, where the
367    /// Renderer is the side that can reach it (a browser's IndexedDB). Answered exactly
368    /// once, later, by an `IoAnswer` event that carries `request`.
369    ///
370    /// `store` is the application identifier, `key` the value's name (empty for `Keys`),
371    /// and `data` the value to write (empty for every operation but `Write`).
372    StorageCall {
373        request: u32,
374        op: crate::schema::StorageOp,
375        store: &'a str,
376        key: &'a str,
377        data: &'a [u8],
378    },
379    /// Asks something of a file the Renderer holds a handle for: reading it, writing
380    /// `data` to it, listing a folder, or finding (and with `create`, making) the child
381    /// called `name`. Answered exactly once, later: a read or a write by an `IoAnswer`, a
382    /// listing or a child by a `FileHandles`, and any of them that failed by an `IoAnswer`
383    /// with the reason. `name` is empty but for `Child`, `data` but for `Write`.
384    FileCall {
385        request: u32,
386        op: FileOp,
387        create: bool,
388        handle: u32,
389        name: &'a str,
390        data: &'a [u8],
391    },
392    /// The Host holds nothing that names `handle` any more, so the Renderer may let go of
393    /// the file behind it. Not answered. A handle the Renderer does not hold is ignored.
394    ReleaseFileHandle {
395        handle: u32,
396    },
397    /// Asks the scroll container `node_id` to go to an offset in physical pixels. `flags`
398    /// is the wire word (`schema::scroll_to_flags`): animate, apply `x_px`, apply `y_px`.
399    /// An axis whose bit is off is not touched. `item` is the lazy list item the offset is
400    /// measured from, and 0 elsewhere.
401    ScrollTo {
402        node_id: u32,
403        item: u32,
404        flags: u32,
405        x_px: f64,
406        y_px: f64,
407    },
408    /// Asks the scroll container `node_id` to bring a rectangle into view. The fields are
409    /// the wire's: `target_kind` from `schema::scroll_target_kind`, the two alignments as
410    /// `schema::ScrollAlign` values, and `flags` from `schema::scroll_into_view_flags`.
411    ScrollIntoView {
412        node_id: u32,
413        target: u32,
414        target_kind: u16,
415        align_x: u16,
416        align_y: u16,
417        flags: u16,
418        rect: crate::schema::Rect,
419    },
420    /// Puts the platform view `handle` in the place of the `NativeView` node `node_id`,
421    /// replacing any view it had. `NativeHandle(0)` takes the node's view out. The view is
422    /// still the Host's: the Renderer never destroys it.
423    AttachNativeView {
424        node_id: u32,
425        handle: crate::schema::NativeHandle,
426    },
427    /// Gives keyboard focus to the platform view of the `NativeView` node `node_id`
428    /// (`focus` true), or hands it back to the scene.
429    FocusNativeView {
430        node_id: u32,
431        focus: bool,
432    },
433    /// Asks the code editor `node_id` where a caret at `line` and `column` would be drawn.
434    /// Answered exactly once, by a `PositionRect` event carrying `request`: a rectangle in
435    /// the window's dp, or none where the position is not on screen.
436    QueryPositionRect {
437        node_id: u32,
438        request: u32,
439        line: u32,
440        column: u32,
441    },
442    /// Replaces several ranges of a code editor's document, as it stood at `base_version`,
443    /// as one edit: all of them or none.
444    ///
445    /// `edits` is the blob [`crate::code::encode_edit_group`] writes. Every range is in the
446    /// document at `base_version`, so no edit moves another; they may come in any order and
447    /// must not overlap. The Renderer answers each group with exactly one
448    /// `CodeEditGroupResult` carrying `request_id`, after the `CodeChanged` events of the
449    /// changes it made, one per edit from the end of the document backwards.
450    EditCodeGroup {
451        node_id: u32,
452        request_id: u32,
453        base_version: u32,
454        edits: &'a [u8],
455    },
456    /// Replaces a range of a code editor's document, as it stood at `base_version`, with a
457    /// snippet, and lets the reader step through its tab stops.
458    ///
459    /// `snippet` is in the subset of VS Code's snippet syntax [`crate::code`] describes:
460    /// `$1`, `${1:placeholder}`, `${1|one,two|}`, `$0` and `\$`. The text it leaves is
461    /// reported as ordinary `CodeChanged` events, and undoes as one step.
462    InsertSnippet {
463        node_id: u32,
464        base_version: u32,
465        start_line: u32,
466        start_column: u32,
467        end_line: u32,
468        end_column: u32,
469        snippet: &'a str,
470    },
471    /// Sets every selection of a code editor at once, the first the primary one, each read
472    /// against the document as it stood at `base_version`. `selections` is 16-byte records
473    /// (anchor line, anchor column, active line, active column), which
474    /// [`crate::code::encode_selections`] writes.
475    SetSelections {
476        node_id: u32,
477        base_version: u32,
478        selections: &'a [u8],
479    },
480}
481
482#[derive(Clone, Debug, Eq, PartialEq)]
483pub enum ProtocolError {
484    Truncated,
485    InvalidEnvelope,
486    InvalidRecordLength,
487    InvalidTag(u16),
488    InvalidWidget(u16),
489    InvalidProperty(u16),
490    InvalidValueKind(u16),
491    InvalidModifier(u16),
492    InvalidTheme(u16),
493    InvalidAssetKind(u16),
494    InvalidMessageDuration(u16),
495    /// A message placement tag this decoder does not know, or a placement with one of its
496    /// two halves missing.
497    InvalidMessagePlacement(u16),
498    /// A notification importance or presentation this decoder does not know.
499    InvalidNotification(u16),
500    InvalidStringRange,
501    InvalidUtf8,
502    LengthOverflow,
503    /// The Renderer refused a whole measure call with this status: its buffer could not be
504    /// read, it came from the wrong thread, or there was nothing to measure with yet.
505    MeasureRefused(i32),
506    /// An animation record that is well formed bytes but not an animation: an unknown
507    /// value, fewer than two keyframes, offsets that do not run from 0 to 1, a negative or
508    /// non-numeric duration or iteration count, keyframes whose values or transform lists
509    /// do not match, or a length that does not hold its keyframes.
510    InvalidAnimation,
511    /// A `Window` node that is not a child of the root, or a node moved from one window
512    /// into another. Compose keeps one composition per window and has no
513    /// way to hand a node from one to the next.
514    MisplacedWindow,
515}
516
517#[derive(Clone, Debug, PartialEq)]
518pub struct HostEvent<'a> {
519    pub node_id: u32,
520    pub handler_id: u64,
521    pub payload: crate::schema::EventPayload<'a>,
522}
523
524const EVENT_CLICK: u16 = 1;
525const EVENT_TEXT_CHANGED: u16 = 2;
526const EVENT_TEXT_SUBMITTED: u16 = 3;
527const EVENT_FOCUS_LOST: u16 = 4;
528const EVENT_PROTOCOL_ERROR: u16 = 5;
529const EVENT_KEY_DOWN: u16 = 6;
530const EVENT_RANGE_REQUESTED: u16 = 7;
531// Tag 8 is the pointer event and 9 to 15 are reserved for the gesture events, so this one
532// starts at 16 and the window size report continues from 17.
533const EVENT_POINTER: u16 = 8;
534const POINTER_RECORD_LEN: usize = 72;
535const EVENT_VALUE_CHANGED: u16 = 16;
536const EVENT_WINDOW_SIZE_CHANGED: u16 = 17;
537const EVENT_RESYNC: u16 = 18;
538const EVENT_LIFECYCLE_START: u16 = 19;
539const EVENT_LIFECYCLE_STOP: u16 = 20;
540const EVENT_DESIGN_SYSTEM_RESOLVED: u16 = 21;
541const EVENT_FILES_ENTERED: u16 = 22;
542const EVENT_FILES_DROPPED: u16 = 23;
543const EVENT_NOTIFICATION_ACTIVATED: u16 = 24;
544const EVENT_NOTIFICATION_PERMISSION_CHANGED: u16 = 25;
545const EVENT_CODE_CHANGED: u16 = 26;
546const EVENT_CODE_EDIT_REJECTED: u16 = 27;
547const EVENT_CODE_HOVERED: u16 = 28;
548const EVENT_CODE_SAVE_REQUESTED: u16 = 29;
549const EVENT_DECORATION_ACTIVATED: u16 = 30;
550const EVENT_ANIMATION: u16 = 31;
551const EVENT_REDUCED_MOTION_CHANGED: u16 = 32;
552// Tags 26 to 32 belong to events other requirements have numbered.
553const EVENT_ZOOM_CHANGED: u16 = 33;
554// 33 is the zoom event's. 34 to 38 are the code editor's.
555const EVENT_SELECTION_CHANGED: u16 = 34;
556const EVENT_VISIBLE_RANGE_CHANGED: u16 = 35;
557const EVENT_EDITOR_FOCUS_CHANGED: u16 = 36;
558const EVENT_FOLD_CHANGED: u16 = 37;
559const EVENT_COMPOSITION_CHANGED: u16 = 38;
560// 39 to 47 are the windows'.
561const EVENT_WINDOW_CLOSE_REQUESTED: u16 = 39;
562const EVENT_WINDOW_FOCUS_CHANGED: u16 = 40;
563const EVENT_WINDOW_MOVED: u16 = 41;
564const EVENT_WINDOW_DRAG: u16 = 42;
565const EVENT_WINDOW_DRAG_OVER: u16 = 43;
566const EVENT_WINDOW_UNAVAILABLE: u16 = 44;
567const EVENT_WINDOW_CLOSED: u16 = 45;
568const EVENT_WINDOW_REQUESTED: u16 = 46;
569const EVENT_APPLICATION_REOPEN: u16 = 47;
570// 48 and 49 are the node focus-gained and key-up events.
571const EVENT_FOCUS_GAINED: u16 = 48;
572const EVENT_KEY_UP: u16 = 49;
573const EVENT_FILE_DIALOG_RESULT: u16 = 50;
574// 51 says what became of a grouped edit of a code editor.
575const EVENT_CODE_EDIT_GROUP_RESULT: u16 = 51;
576/// `CodeEditGroupResult` in full: the 16 byte header and five words.
577const CODE_EDIT_GROUP_RESULT_LEN: usize = 36;
578// 52 is the system's light or dark appearance, one `u32` after the header. 53 is a
579// window's density, one `f32`. 54 and 55 are the code editor's row height and scroll
580// offset, each one `f64` of physical pixels.
581const EVENT_COLOR_SCHEME_CHANGED: u16 = 52;
582const EVENT_DENSITY_CHANGED: u16 = 53;
583const EVENT_CODE_METRICS: u16 = 54;
584const EVENT_CODE_SCROLLED: u16 = 55;
585/// `FileDialogResult` in full: the 16 byte header, three words and the paths' reference.
586const FILE_DIALOG_RESULT_LEN: usize = 36;
587// 51 to 55 are held by events other requirements have numbered.
588const EVENT_CLIPBOARD_TEXT: u16 = 56;
589/// `ClipboardText` in full: the 16 byte header, three words and the text's reference.
590const CLIPBOARD_TEXT_LEN: usize = 36;
591const EVENT_IO_ANSWER: u16 = 57;
592/// `IoAnswer` in full: the 16 byte header, two words and the data's reference.
593const IO_ANSWER_LEN: usize = 32;
594const EVENT_FILE_HANDLES: u16 = 58;
595/// `FileHandles` in full: the 16 byte header, five words and two string references.
596const FILE_HANDLES_LEN: usize = 52;
597const EVENT_STORAGE_LOCATION: u16 = 59;
598const EVENT_SCROLL_CHANGED: u16 = 60;
599/// `ScrollChanged` in full: the 16 byte header, the item, the flags and six `f64`.
600const SCROLL_CHANGED_LEN: usize = 72;
601const EVENT_NATIVE_VIEW_PARENT: u16 = 61;
602/// `NativeViewParent` in full: the 16 byte header, the handle, the kind, a reserved half
603/// word and the scale.
604const NATIVE_VIEW_PARENT_LEN: usize = 32;
605const EVENT_NATIVE_VIEW_FOCUS: u16 = 62;
606/// `NativeViewFocus` in full: the 16 byte header, the focus word and its padding.
607const NATIVE_VIEW_FOCUS_LEN: usize = 24;
608const EVENT_MOTION_FINISHED: u16 = 63;
609/// `MotionFinished` in full: the 16 byte header and two `f32` in dp.
610const MOTION_FINISHED_LEN: usize = 24;
611// 64 is where a code editor's caret is drawn and 65 the answer to a position query, both
612// with a rectangle of four `f32`.
613const EVENT_CARET_RECT: u16 = 64;
614const EVENT_POSITION_RECT: u16 = 65;
615/// `CaretRect` and `PositionRect` in full: the 16 byte header, two words and four `f32`.
616const CODE_RECT_EVENT_LEN: usize = 40;
617// 66 is a pointer over a code editor: the pointer record and the place in the text under it.
618const EVENT_CODE_POINTER: u16 = 66;
619// 67 is every selection of a code editor: the version, then the selections' reference.
620const EVENT_SELECTIONS_CHANGED: u16 = 67;
621const SELECTIONS_CHANGED_LEN: usize = 28;
622const CODE_POINTER_LEN: usize = POINTER_RECORD_LEN + 8;
623/// The line and the column of a pointer that is over no character.
624const NO_CODE_POSITION: u32 = u32::MAX;
625
626/// Where `SetWindow` keeps the mode and the last window policy: in the bits of the
627/// `resizable` word above the flag.
628const WINDOW_MODE_SHIFT: u32 = 8;
629const WINDOW_POLICY_SHIFT: u32 = 12;
630
631/// The phases of a `WindowDrag`.
632pub const WINDOW_DRAG_MOVE: u32 = 1;
633pub const WINDOW_DRAG_END: u32 = 2;
634pub const WINDOW_DRAG_CANCEL: u32 = 3;
635/// The kinds of a `WindowDragOver`.
636pub const WINDOW_DRAG_OVER_ENTER: u32 = 1;
637pub const WINDOW_DRAG_OVER_MOVE: u32 = 2;
638pub const WINDOW_DRAG_OVER_LEAVE: u32 = 3;
639pub const WINDOW_DRAG_OVER_DROP: u32 = 4;
640
641const MODIFIER_SHIFT: u8 = 1 << 0;
642const MODIFIER_CTRL: u8 = 1 << 1;
643const MODIFIER_ALT: u8 = 1 << 2;
644const MODIFIER_META: u8 = 1 << 3;
645
646/// Reads a pointer enum's tag out of a `u32` word. A word that does not fit a tag, or names
647/// none, is a value the sides disagree on.
648fn pointer_tag<T: TryFrom<u16, Error = ()>>(
649    bytes: &[u8],
650    offset: usize,
651) -> Result<T, ProtocolError> {
652    let raw = read_u32(bytes, offset)?;
653    u16::try_from(raw)
654        .ok()
655        .and_then(|tag| T::try_from(tag).ok())
656        .ok_or(ProtocolError::InvalidValueKind(
657            raw.min(u32::from(u16::MAX)) as u16,
658        ))
659}
660
661/// The 72-byte pointer record: see the field table of the pointer event.
662fn decode_pointer(bytes: &[u8]) -> Result<crate::schema::EventPayload<'_>, ProtocolError> {
663    Ok(crate::schema::EventPayload::Pointer {
664        kind: pointer_tag(bytes, 16)?,
665        pointer_id: read_u32(bytes, 20)?,
666        pointer_type: pointer_tag(bytes, 24)?,
667        x: f32::from_bits(read_u32(bytes, 28)?),
668        y: f32::from_bits(read_u32(bytes, 32)?),
669        buttons: read_u32(bytes, 36)?,
670        button: read_u32(bytes, 40)?,
671        modifiers: read_u32(bytes, 44)?,
672        click_count: read_u32(bytes, 48)?,
673        delta_x: f32::from_bits(read_u32(bytes, 52)?),
674        delta_y: f32::from_bits(read_u32(bytes, 56)?),
675        delta_mode: pointer_tag(bytes, 60)?,
676        timestamp_nanos: read_u64(bytes, 64)?,
677    })
678}
679
680/// Decode one Renderer-to-Host event record.
681pub fn decode_event(bytes: &[u8]) -> Result<HostEvent<'_>, ProtocolError> {
682    if bytes.len() < 16 {
683        return Err(ProtocolError::Truncated);
684    }
685    let tag = read_u16(bytes, 0)?;
686    let record_len = usize::from(read_u16(bytes, 2)?);
687    if record_len < 16 || record_len % 4 != 0 || record_len > bytes.len() {
688        return Err(ProtocolError::InvalidRecordLength);
689    }
690    let node_id = read_u32(bytes, 4)?;
691    let handler_id = read_u64(bytes, 8)?;
692    let payload = match tag {
693        EVENT_CLICK if record_len == 16 => crate::schema::EventPayload::Clicked,
694        EVENT_TEXT_CHANGED if record_len == 24 => {
695            crate::schema::EventPayload::TextChanged(read_string(bytes, 16, record_len)?)
696        }
697        EVENT_TEXT_SUBMITTED if record_len == 24 => {
698            crate::schema::EventPayload::TextSubmitted(read_string(bytes, 16, record_len)?)
699        }
700        EVENT_FOCUS_LOST if record_len == 16 => crate::schema::EventPayload::FocusLost,
701        EVENT_FOCUS_GAINED if record_len == 16 => crate::schema::EventPayload::FocusGained,
702        EVENT_PROTOCOL_ERROR if record_len == 28 => crate::schema::EventPayload::ProtocolError {
703            code: read_u32(bytes, 16)?,
704            message: read_string(bytes, 20, record_len)?,
705        },
706        EVENT_KEY_DOWN if record_len == 32 => {
707            let raw_key = read_u16(bytes, 16)?;
708            let modifiers = *bytes.get(18).ok_or(ProtocolError::Truncated)?;
709            let repeat = *bytes.get(19).ok_or(ProtocolError::Truncated)? != 0;
710            crate::schema::EventPayload::KeyDown {
711                key: Key::try_from(raw_key)
712                    .map_err(|()| ProtocolError::InvalidValueKind(raw_key))?,
713                shift_key: modifiers & MODIFIER_SHIFT != 0,
714                ctrl_key: modifiers & MODIFIER_CTRL != 0,
715                alt_key: modifiers & MODIFIER_ALT != 0,
716                meta_key: modifiers & MODIFIER_META != 0,
717                repeat,
718                code: read_u32(bytes, 20)?,
719                text: read_string(bytes, 24, record_len)?,
720            }
721        }
722        // A key-up has the key-down's layout, so a Host handler reads both the same way.
723        EVENT_KEY_UP if record_len == 32 => {
724            let raw_key = read_u16(bytes, 16)?;
725            let modifiers = *bytes.get(18).ok_or(ProtocolError::Truncated)?;
726            let repeat = *bytes.get(19).ok_or(ProtocolError::Truncated)? != 0;
727            crate::schema::EventPayload::KeyUp {
728                key: Key::try_from(raw_key)
729                    .map_err(|()| ProtocolError::InvalidValueKind(raw_key))?,
730                shift_key: modifiers & MODIFIER_SHIFT != 0,
731                ctrl_key: modifiers & MODIFIER_CTRL != 0,
732                alt_key: modifiers & MODIFIER_ALT != 0,
733                meta_key: modifiers & MODIFIER_META != 0,
734                repeat,
735                code: read_u32(bytes, 20)?,
736                text: read_string(bytes, 24, record_len)?,
737            }
738        }
739        EVENT_RANGE_REQUESTED if record_len == 24 => crate::schema::EventPayload::RangeRequested {
740            start: read_u32(bytes, 16)?,
741            count: read_u32(bytes, 20)?,
742        },
743        EVENT_VALUE_CHANGED if record_len == 24 => {
744            crate::schema::EventPayload::ValueChanged(f64::from_bits(read_u64(bytes, 16)?))
745        }
746        EVENT_WINDOW_SIZE_CHANGED if record_len == 44 => {
747            let raw_class = read_u32(bytes, 24)?;
748            let class = u16::try_from(raw_class)
749                .ok()
750                .and_then(|value| crate::schema::WindowSizeClass::try_from(value).ok())
751                .ok_or(ProtocolError::InvalidValueKind(raw_class as u16))?;
752            let raw_height_class = read_u32(bytes, 28)?;
753            let height_class = u16::try_from(raw_height_class)
754                .ok()
755                .and_then(|value| crate::schema::WindowHeightClass::try_from(value).ok())
756                .ok_or(ProtocolError::InvalidValueKind(raw_height_class as u16))?;
757            crate::schema::EventPayload::WindowSizeChanged {
758                width_dp: f32::from_bits(read_u32(bytes, 16)?),
759                height_dp: f32::from_bits(read_u32(bytes, 20)?),
760                class,
761                height_class,
762                safe_area_top: f32::from_bits(read_u32(bytes, 32)?),
763                safe_area_leading: f32::from_bits(read_u32(bytes, 36)?),
764                safe_area_trailing: f32::from_bits(read_u32(bytes, 40)?),
765            }
766        }
767        EVENT_DESIGN_SYSTEM_RESOLVED if record_len == 20 => {
768            let raw = read_u32(bytes, 16)?;
769            let system = u16::try_from(raw)
770                .ok()
771                .and_then(|tag| crate::schema::DesignSystem::try_from(tag).ok())
772                .ok_or(ProtocolError::InvalidValueKind(raw as u16))?;
773            crate::schema::EventPayload::DesignSystemResolved(system)
774        }
775        EVENT_FILES_ENTERED if record_len == 16 => crate::schema::EventPayload::FilesEntered,
776        EVENT_FILES_DROPPED if record_len == 24 => {
777            crate::schema::EventPayload::FilesDropped(read_string(bytes, 16, record_len)?)
778        }
779        EVENT_NOTIFICATION_ACTIVATED if record_len == 28 => {
780            let action = read_u32(bytes, 16)?;
781            // Zero is the body and one and two are the two buttons a notification can have.
782            // Anything else names a button that cannot exist.
783            if action > 2 {
784                return Err(ProtocolError::InvalidValueKind(
785                    action.min(u32::from(u16::MAX)) as u16,
786                ));
787            }
788            crate::schema::EventPayload::NotificationActivated {
789                action,
790                key: read_string(bytes, 20, record_len)?,
791            }
792        }
793        EVENT_NOTIFICATION_PERMISSION_CHANGED if record_len == 20 => {
794            let raw = read_u32(bytes, 16)?;
795            let state = u16::try_from(raw)
796                .ok()
797                .and_then(|tag| NotificationPermission::try_from(tag).ok())
798                .ok_or(ProtocolError::InvalidValueKind(
799                    raw.min(u32::from(u16::MAX)) as u16,
800                ))?;
801            crate::schema::EventPayload::NotificationPermissionChanged(state)
802        }
803        EVENT_ANIMATION if record_len == 40 => {
804            let raw_kind = u16::from(read_u8(bytes, 20)?);
805            let raw_property = u16::from(read_u8(bytes, 21)?);
806            crate::schema::EventPayload::AnimationEvent {
807                animation_id: read_u32(bytes, 16)?,
808                kind: crate::schema::AnimationEventKind::try_from(raw_kind)
809                    .map_err(|()| ProtocolError::InvalidValueKind(raw_kind))?,
810                property: crate::schema::AnimatedProperty::try_from(raw_property)
811                    .map_err(|()| ProtocolError::InvalidValueKind(raw_property))?,
812                slot: read_u8(bytes, 22)?,
813                iteration: read_u32(bytes, 24)?,
814                elapsed_ms: f32::from_bits(read_u32(bytes, 28)?),
815                time_nanos: read_u64(bytes, 32)?,
816            }
817        }
818        EVENT_POINTER if record_len == POINTER_RECORD_LEN => decode_pointer(bytes)?,
819        EVENT_REDUCED_MOTION_CHANGED if record_len == 20 => {
820            let raw = read_u32(bytes, 16)?;
821            let state = u16::try_from(raw)
822                .ok()
823                .and_then(|tag| crate::schema::ReducedMotion::try_from(tag).ok())
824                .ok_or(ProtocolError::InvalidValueKind(
825                    raw.min(u32::from(u16::MAX)) as u16,
826                ))?;
827            crate::schema::EventPayload::ReducedMotionChanged(state)
828        }
829        EVENT_COLOR_SCHEME_CHANGED if record_len == 20 => {
830            let raw = read_u32(bytes, 16)?;
831            let scheme = u16::try_from(raw)
832                .ok()
833                .and_then(|tag| crate::schema::SystemColorScheme::try_from(tag).ok())
834                .ok_or(ProtocolError::InvalidValueKind(
835                    raw.min(u32::from(u16::MAX)) as u16,
836                ))?;
837            crate::schema::EventPayload::ColorSchemeChanged(scheme)
838        }
839        EVENT_DENSITY_CHANGED if record_len == 20 => {
840            let scale = f32::from_bits(read_u32(bytes, 16)?);
841            // A density is a positive number of pixels. Zero, a negative number and NaN
842            // are not, and a layout that divided by one would not recover.
843            if scale.is_nan() || scale <= 0.0 {
844                return Err(ProtocolError::InvalidValueKind(0));
845            }
846            crate::schema::EventPayload::DensityChanged { scale }
847        }
848        EVENT_CODE_CHANGED if record_len == 44 => crate::schema::EventPayload::CodeChanged {
849            version: read_u32(bytes, 16)?,
850            start_line: read_u32(bytes, 20)?,
851            start_column: read_u32(bytes, 24)?,
852            end_line: read_u32(bytes, 28)?,
853            end_column: read_u32(bytes, 32)?,
854            text: read_string(bytes, 36, record_len)?,
855        },
856        EVENT_CODE_EDIT_REJECTED if record_len == 44 => {
857            crate::schema::EventPayload::CodeEditRejected {
858                request_id: read_u32(bytes, 16)?,
859                base_version: read_u32(bytes, 20)?,
860                current_version: read_u32(bytes, 24)?,
861                start_line: read_u32(bytes, 28)?,
862                start_column: read_u32(bytes, 32)?,
863                end_line: read_u32(bytes, 36)?,
864                end_column: read_u32(bytes, 40)?,
865            }
866        }
867        EVENT_CODE_HOVERED if record_len == 36 => {
868            let raw_phase = read_u32(bytes, 32)?;
869            let phase = u16::try_from(raw_phase)
870                .ok()
871                .and_then(|tag| crate::schema::HoverPhase::try_from(tag).ok())
872                .ok_or(ProtocolError::InvalidValueKind(raw_phase as u16))?;
873            crate::schema::EventPayload::CodeHovered {
874                decoration: read_u64(bytes, 16)?,
875                line: read_u32(bytes, 24)?,
876                column: read_u32(bytes, 28)?,
877                phase,
878            }
879        }
880        EVENT_CODE_SAVE_REQUESTED if record_len == 24 => {
881            crate::schema::EventPayload::CodeSaveRequested {
882                version: read_u32(bytes, 16)?,
883            }
884        }
885        EVENT_DECORATION_ACTIVATED if record_len == 24 => {
886            crate::schema::EventPayload::DecorationActivated {
887                decoration: read_u64(bytes, 16)?,
888            }
889        }
890        EVENT_CODE_CHANGED..=EVENT_DECORATION_ACTIVATED => {
891            return Err(ProtocolError::InvalidRecordLength);
892        }
893        EVENT_SELECTION_CHANGED if record_len == 36 => {
894            crate::schema::EventPayload::SelectionChanged {
895                version: read_u32(bytes, 16)?,
896                anchor_line: read_u32(bytes, 20)?,
897                anchor_column: read_u32(bytes, 24)?,
898                active_line: read_u32(bytes, 28)?,
899                active_column: read_u32(bytes, 32)?,
900            }
901        }
902        EVENT_VISIBLE_RANGE_CHANGED if record_len == 28 => {
903            crate::schema::EventPayload::VisibleRangeChanged {
904                version: read_u32(bytes, 16)?,
905                first_line: read_u32(bytes, 20)?,
906                last_line: read_u32(bytes, 24)?,
907            }
908        }
909        EVENT_EDITOR_FOCUS_CHANGED if record_len == 24 => {
910            crate::schema::EventPayload::EditorFocusChanged {
911                focused: read_flag(bytes, 16)?,
912            }
913        }
914        EVENT_FOLD_CHANGED if record_len == 24 => crate::schema::EventPayload::FoldChanged {
915            start_line: read_u32(bytes, 16)?,
916            collapsed: read_flag(bytes, 20)?,
917        },
918        EVENT_COMPOSITION_CHANGED if record_len == 24 => {
919            crate::schema::EventPayload::CompositionChanged {
920                composing: read_flag(bytes, 16)?,
921            }
922        }
923        EVENT_SELECTION_CHANGED..=EVENT_COMPOSITION_CHANGED => {
924            return Err(ProtocolError::InvalidRecordLength);
925        }
926        EVENT_WINDOW_CLOSE_REQUESTED if record_len == 16 => {
927            crate::schema::EventPayload::WindowCloseRequested
928        }
929        EVENT_WINDOW_FOCUS_CHANGED if record_len == 20 => {
930            crate::schema::EventPayload::WindowFocusChanged {
931                focused: read_flag(bytes, 16)?,
932            }
933        }
934        EVENT_WINDOW_MOVED if record_len == 32 => crate::schema::EventPayload::WindowMoved {
935            x: f32::from_bits(read_u32(bytes, 16)?),
936            y: f32::from_bits(read_u32(bytes, 20)?),
937            width: f32::from_bits(read_u32(bytes, 24)?),
938            height: f32::from_bits(read_u32(bytes, 28)?),
939        },
940        EVENT_WINDOW_DRAG if record_len == 32 => {
941            let phase = read_u32(bytes, 16)?;
942            if !(WINDOW_DRAG_MOVE..=WINDOW_DRAG_CANCEL).contains(&phase) {
943                return Err(ProtocolError::InvalidValueKind(
944                    phase.min(u32::from(u16::MAX)) as u16,
945                ));
946            }
947            crate::schema::EventPayload::WindowDrag {
948                phase,
949                screen_x: f32::from_bits(read_u32(bytes, 20)?),
950                screen_y: f32::from_bits(read_u32(bytes, 24)?),
951                over_window: read_u32(bytes, 28)?,
952            }
953        }
954        EVENT_WINDOW_DRAG_OVER if record_len == 32 => {
955            let kind = read_u32(bytes, 16)?;
956            if !(WINDOW_DRAG_OVER_ENTER..=WINDOW_DRAG_OVER_DROP).contains(&kind) {
957                return Err(ProtocolError::InvalidValueKind(
958                    kind.min(u32::from(u16::MAX)) as u16,
959                ));
960            }
961            crate::schema::EventPayload::WindowDragOver {
962                kind,
963                window: read_u32(bytes, 20)?,
964                x: f32::from_bits(read_u32(bytes, 24)?),
965                y: f32::from_bits(read_u32(bytes, 28)?),
966            }
967        }
968        EVENT_WINDOW_UNAVAILABLE if record_len == 16 => {
969            crate::schema::EventPayload::WindowUnavailable
970        }
971        EVENT_WINDOW_CLOSED if record_len == 16 => crate::schema::EventPayload::WindowClosed,
972        EVENT_WINDOW_REQUESTED if record_len == 28 => {
973            crate::schema::EventPayload::WindowRequested {
974                request: read_u32(bytes, 16)?,
975                key: read_string(bytes, 20, record_len)?,
976            }
977        }
978        EVENT_APPLICATION_REOPEN if record_len == 16 => {
979            crate::schema::EventPayload::ApplicationReopen
980        }
981        EVENT_FILE_DIALOG_RESULT if record_len == FILE_DIALOG_RESULT_LEN => {
982            let raw_status = read_u32(bytes, 20)?;
983            let status = u16::try_from(raw_status)
984                .ok()
985                .and_then(|tag| FileDialogStatus::try_from(tag).ok())
986                .ok_or(ProtocolError::InvalidValueKind(
987                    raw_status.min(u32::from(u16::MAX)) as u16,
988                ))?;
989            crate::schema::EventPayload::FileDialogResult {
990                request: read_u32(bytes, 16)?,
991                status,
992                filter: read_u32(bytes, 24)?,
993                paths: read_string(bytes, 28, record_len)?,
994            }
995        }
996        EVENT_FILE_DIALOG_RESULT => return Err(ProtocolError::InvalidRecordLength),
997        EVENT_CODE_EDIT_GROUP_RESULT if record_len == CODE_EDIT_GROUP_RESULT_LEN => {
998            let raw_status = read_u32(bytes, 20)?;
999            let status = u16::try_from(raw_status)
1000                .ok()
1001                .and_then(|tag| crate::schema::EditGroupStatus::try_from(tag).ok())
1002                .ok_or(ProtocolError::InvalidValueKind(
1003                    raw_status.min(u32::from(u16::MAX)) as u16,
1004                ))?;
1005            crate::schema::EventPayload::CodeEditGroupResult {
1006                request_id: read_u32(bytes, 16)?,
1007                status,
1008                base_version: read_u32(bytes, 24)?,
1009                current_version: read_u32(bytes, 28)?,
1010                index: read_u32(bytes, 32)?,
1011            }
1012        }
1013        EVENT_CODE_EDIT_GROUP_RESULT => return Err(ProtocolError::InvalidRecordLength),
1014        EVENT_CLIPBOARD_TEXT if record_len == CLIPBOARD_TEXT_LEN => {
1015            crate::schema::EventPayload::ClipboardText {
1016                request: read_u32(bytes, 16)?,
1017                status: read_u32(bytes, 20)?,
1018                len: read_u32(bytes, 24)?,
1019                text: read_string(bytes, 28, record_len)?,
1020            }
1021        }
1022        EVENT_CLIPBOARD_TEXT => return Err(ProtocolError::InvalidRecordLength),
1023        EVENT_CODE_METRICS if record_len == 24 => crate::schema::EventPayload::CodeMetrics {
1024            line_height_px: f64::from_bits(read_u64(bytes, 16)?),
1025        },
1026        EVENT_CODE_SCROLLED if record_len == 24 => crate::schema::EventPayload::CodeScrolled {
1027            offset_px: f64::from_bits(read_u64(bytes, 16)?),
1028        },
1029        EVENT_CODE_METRICS | EVENT_CODE_SCROLLED => {
1030            return Err(ProtocolError::InvalidRecordLength);
1031        }
1032        EVENT_IO_ANSWER if record_len == IO_ANSWER_LEN => {
1033            let raw_status = read_u32(bytes, 20)?;
1034            let status = u16::try_from(raw_status)
1035                .ok()
1036                .and_then(|tag| IoStatus::try_from(tag).ok())
1037                .ok_or(ProtocolError::InvalidValueKind(
1038                    raw_status.min(u32::from(u16::MAX)) as u16,
1039                ))?;
1040            crate::schema::EventPayload::IoAnswer {
1041                request: read_u32(bytes, 16)?,
1042                status,
1043                data: read_bytes(bytes, 24, record_len)?,
1044            }
1045        }
1046        EVENT_IO_ANSWER => return Err(ProtocolError::InvalidRecordLength),
1047        EVENT_FILE_HANDLES if record_len == FILE_HANDLES_LEN => {
1048            let raw_status = read_u32(bytes, 20)?;
1049            let status = u16::try_from(raw_status)
1050                .ok()
1051                .and_then(|tag| FileDialogStatus::try_from(tag).ok())
1052                .ok_or(ProtocolError::InvalidValueKind(
1053                    raw_status.min(u32::from(u16::MAX)) as u16,
1054                ))?;
1055            let raw_delivery = read_u32(bytes, 28)?;
1056            let delivery = u16::try_from(raw_delivery)
1057                .ok()
1058                .and_then(|tag| FileDelivery::try_from(tag).ok())
1059                .ok_or(ProtocolError::InvalidValueKind(
1060                    raw_delivery.min(u32::from(u16::MAX)) as u16,
1061                ))?;
1062            let names = read_string(bytes, 36, record_len)?;
1063            let kinds = read_string(bytes, 44, record_len)?;
1064            // One letter per name, and only the two letters there are. A list whose kinds do
1065            // not line up with its names would hand the application a file as a folder.
1066            if let Some(unknown) = kinds.bytes().find(|kind| *kind != b'f' && *kind != b'd') {
1067                return Err(ProtocolError::InvalidValueKind(u16::from(unknown)));
1068            }
1069            let count = if names.is_empty() {
1070                0
1071            } else {
1072                names.split('\0').count()
1073            };
1074            if count != kinds.len() || names.split('\0').any(|name| count != 0 && name.is_empty()) {
1075                return Err(ProtocolError::InvalidStringRange);
1076            }
1077            crate::schema::EventPayload::FileHandles {
1078                request: read_u32(bytes, 16)?,
1079                status,
1080                filter: read_u32(bytes, 24)?,
1081                delivery,
1082                first_handle: read_u32(bytes, 32)?,
1083                names,
1084                kinds,
1085            }
1086        }
1087        EVENT_FILE_HANDLES => return Err(ProtocolError::InvalidRecordLength),
1088        EVENT_STORAGE_LOCATION if record_len == 24 => {
1089            crate::schema::EventPayload::StorageLocation(read_string(bytes, 16, record_len)?)
1090        }
1091        EVENT_STORAGE_LOCATION => return Err(ProtocolError::InvalidRecordLength),
1092        EVENT_SCROLL_CHANGED if record_len == SCROLL_CHANGED_LEN => {
1093            use crate::schema::scroll_changed_flags as flag;
1094            let flags = read_u32(bytes, 20)?;
1095            if flags & !flag::KNOWN != 0 {
1096                // A bit with no meaning here is a newer or a broken Renderer, and guessing
1097                // what it says about the position would be worse than refusing the report.
1098                return Err(ProtocolError::InvalidValueKind(
1099                    (flags & !flag::KNOWN).trailing_zeros() as u16,
1100                ));
1101            }
1102            crate::schema::EventPayload::ScrollChanged {
1103                item: read_u32(bytes, 16)?,
1104                settled: flags & flag::SETTLED != 0,
1105                can_scroll_backward: flags & flag::CAN_SCROLL_BACKWARD != 0,
1106                can_scroll_forward: flags & flag::CAN_SCROLL_FORWARD != 0,
1107                x_px: f64::from_bits(read_u64(bytes, 24)?),
1108                y_px: f64::from_bits(read_u64(bytes, 32)?),
1109                max_x_px: f64::from_bits(read_u64(bytes, 40)?),
1110                max_y_px: f64::from_bits(read_u64(bytes, 48)?),
1111                viewport_width_px: f64::from_bits(read_u64(bytes, 56)?),
1112                viewport_height_px: f64::from_bits(read_u64(bytes, 64)?),
1113            }
1114        }
1115        EVENT_SCROLL_CHANGED => return Err(ProtocolError::InvalidRecordLength),
1116        EVENT_NATIVE_VIEW_PARENT if record_len == NATIVE_VIEW_PARENT_LEN => {
1117            let raw_kind = read_u16(bytes, 24)?;
1118            let kind = crate::schema::NativeParentKind::try_from(raw_kind)
1119                .map_err(|()| ProtocolError::InvalidValueKind(raw_kind))?;
1120            let reserved = read_u16(bytes, 26)?;
1121            if reserved != 0 {
1122                // A newer Renderer saying something here that this Host cannot read.
1123                return Err(ProtocolError::InvalidValueKind(reserved));
1124            }
1125            let scale = f32::from_bits(read_u32(bytes, 28)?);
1126            if !scale.is_finite() || scale <= 0.0 {
1127                // A view sized with this would be sized wrong or not at all.
1128                return Err(ProtocolError::InvalidValueKind(0));
1129            }
1130            crate::schema::EventPayload::NativeViewParent {
1131                handle: crate::schema::NativeHandle(read_u64(bytes, 16)?),
1132                kind,
1133                scale,
1134            }
1135        }
1136        EVENT_NATIVE_VIEW_FOCUS if record_len == NATIVE_VIEW_FOCUS_LEN => {
1137            crate::schema::EventPayload::NativeViewFocus {
1138                focused: read_flag(bytes, 16)?,
1139            }
1140        }
1141        EVENT_NATIVE_VIEW_PARENT | EVENT_NATIVE_VIEW_FOCUS => {
1142            return Err(ProtocolError::InvalidRecordLength);
1143        }
1144        EVENT_MOTION_FINISHED if record_len == MOTION_FINISHED_LEN => {
1145            crate::schema::EventPayload::MotionFinished {
1146                width_dp: f32::from_bits(read_u32(bytes, 16)?),
1147                height_dp: f32::from_bits(read_u32(bytes, 20)?),
1148            }
1149        }
1150        EVENT_MOTION_FINISHED => return Err(ProtocolError::InvalidRecordLength),
1151        EVENT_CARET_RECT if record_len == CODE_RECT_EVENT_LEN => {
1152            crate::schema::EventPayload::CaretRect {
1153                line: read_u32(bytes, 16)?,
1154                column: read_u32(bytes, 20)?,
1155                rect: read_code_rect(bytes, 24)?,
1156            }
1157        }
1158        EVENT_POSITION_RECT if record_len == CODE_RECT_EVENT_LEN => {
1159            let found = read_u32(bytes, 20)?;
1160            let rect = read_code_rect(bytes, 24)?;
1161            crate::schema::EventPayload::PositionRect {
1162                request: read_u32(bytes, 16)?,
1163                rect: match found {
1164                    0 => None,
1165                    1 => Some(rect),
1166                    other => {
1167                        return Err(ProtocolError::InvalidValueKind(
1168                            other.min(u32::from(u16::MAX)) as u16,
1169                        ));
1170                    }
1171                },
1172            }
1173        }
1174        EVENT_CARET_RECT | EVENT_POSITION_RECT => {
1175            return Err(ProtocolError::InvalidRecordLength);
1176        }
1177        EVENT_CODE_POINTER if record_len == CODE_POINTER_LEN => {
1178            let crate::schema::EventPayload::Pointer {
1179                kind,
1180                pointer_id,
1181                pointer_type,
1182                x,
1183                y,
1184                buttons,
1185                button,
1186                modifiers,
1187                click_count,
1188                delta_x,
1189                delta_y,
1190                delta_mode,
1191                timestamp_nanos,
1192            } = decode_pointer(bytes)?
1193            else {
1194                unreachable!("decode_pointer reads a pointer record");
1195            };
1196            let line = read_u32(bytes, POINTER_RECORD_LEN)?;
1197            let column = read_u32(bytes, POINTER_RECORD_LEN + 4)?;
1198            let position = match (line, column) {
1199                (NO_CODE_POSITION, NO_CODE_POSITION) => None,
1200                // One half of "nowhere" is a record the two sides disagree on.
1201                (NO_CODE_POSITION, _) | (_, NO_CODE_POSITION) => {
1202                    return Err(ProtocolError::InvalidValueKind(u16::MAX));
1203                }
1204                (line, column) => Some(crate::code::Position::new(line, column)),
1205            };
1206            crate::schema::EventPayload::CodePointer {
1207                kind,
1208                pointer_id,
1209                pointer_type,
1210                x,
1211                y,
1212                buttons,
1213                button,
1214                modifiers,
1215                click_count,
1216                delta_x,
1217                delta_y,
1218                delta_mode,
1219                timestamp_nanos,
1220                position,
1221            }
1222        }
1223        EVENT_CODE_POINTER => return Err(ProtocolError::InvalidRecordLength),
1224        EVENT_SELECTIONS_CHANGED if record_len == SELECTIONS_CHANGED_LEN => {
1225            let selections = read_bytes(bytes, 20, record_len)?;
1226            if selections.len() % crate::code::SELECTION_LEN != 0 {
1227                return Err(ProtocolError::InvalidRecordLength);
1228            }
1229            crate::schema::EventPayload::SelectionsChanged {
1230                version: read_u32(bytes, 16)?,
1231                selections,
1232            }
1233        }
1234        EVENT_SELECTIONS_CHANGED => return Err(ProtocolError::InvalidRecordLength),
1235        EVENT_WINDOW_CLOSE_REQUESTED..=EVENT_APPLICATION_REOPEN => {
1236            return Err(ProtocolError::InvalidRecordLength);
1237        }
1238        EVENT_ZOOM_CHANGED if record_len == 28 => {
1239            let level = read_u32(bytes, 24)? as i32;
1240            if !(i32::from(crate::zoom::MIN_ZOOM_LEVEL)..=i32::from(crate::zoom::MAX_ZOOM_LEVEL))
1241                .contains(&level)
1242            {
1243                return Err(ProtocolError::InvalidValueKind(level as u16));
1244            }
1245            crate::schema::EventPayload::ZoomChanged {
1246                k: f32::from_bits(read_u32(bytes, 16)?),
1247                os: f32::from_bits(read_u32(bytes, 20)?),
1248                level,
1249            }
1250        }
1251        EVENT_RESYNC if record_len == 16 => crate::schema::EventPayload::Resync,
1252        EVENT_LIFECYCLE_START if record_len == 16 => crate::schema::EventPayload::LifecycleStart,
1253        EVENT_LIFECYCLE_STOP if record_len == 16 => crate::schema::EventPayload::LifecycleStop,
1254        EVENT_CLICK..=EVENT_RANGE_REQUESTED
1255        | EVENT_VALUE_CHANGED..=EVENT_NOTIFICATION_PERMISSION_CHANGED
1256        | EVENT_ANIMATION
1257        | EVENT_POINTER
1258        | EVENT_REDUCED_MOTION_CHANGED
1259        | EVENT_COLOR_SCHEME_CHANGED
1260        | EVENT_DENSITY_CHANGED
1261        | EVENT_ZOOM_CHANGED
1262        | EVENT_FOCUS_GAINED
1263        | EVENT_KEY_UP => {
1264            return Err(ProtocolError::InvalidRecordLength);
1265        }
1266        other => return Err(ProtocolError::InvalidTag(other)),
1267    };
1268    Ok(HostEvent {
1269        node_id,
1270        handler_id,
1271        payload,
1272    })
1273}
1274
1275/// The four `f32` of a code editor rectangle, starting at `offset`.
1276fn read_code_rect(bytes: &[u8], offset: usize) -> Result<crate::code::CodeRect, ProtocolError> {
1277    Ok(crate::code::CodeRect {
1278        x: f32::from_bits(read_u32(bytes, offset)?),
1279        y: f32::from_bits(read_u32(bytes, offset + 4)?),
1280        width: f32::from_bits(read_u32(bytes, offset + 8)?),
1281        height: f32::from_bits(read_u32(bytes, offset + 12)?),
1282    })
1283}
1284
1285fn put_code_rect(output: &mut Vec<u8>, rect: crate::code::CodeRect) {
1286    for value in [rect.x, rect.y, rect.width, rect.height] {
1287        output.extend_from_slice(&value.to_bits().to_le_bytes());
1288    }
1289}
1290
1291/// Test/mock helper for constructing a Renderer-to-Host event.
1292pub fn encode_event(event: &HostEvent<'_>, output: &mut Vec<u8>) -> Result<(), ProtocolError> {
1293    output.clear();
1294    if let crate::schema::EventPayload::KeyDown {
1295        key,
1296        shift_key,
1297        ctrl_key,
1298        alt_key,
1299        meta_key,
1300        repeat,
1301        code,
1302        text,
1303    } = event.payload
1304    {
1305        output.extend_from_slice(&EVENT_KEY_DOWN.to_le_bytes());
1306        output.extend_from_slice(&32_u16.to_le_bytes());
1307        output.extend_from_slice(&event.node_id.to_le_bytes());
1308        output.extend_from_slice(&event.handler_id.to_le_bytes());
1309        output.extend_from_slice(&(key as u16).to_le_bytes());
1310        let modifiers = (u8::from(shift_key) * MODIFIER_SHIFT)
1311            | (u8::from(ctrl_key) * MODIFIER_CTRL)
1312            | (u8::from(alt_key) * MODIFIER_ALT)
1313            | (u8::from(meta_key) * MODIFIER_META);
1314        output.push(modifiers);
1315        output.push(u8::from(repeat));
1316        output.extend_from_slice(&code.to_le_bytes());
1317        let len = u32::try_from(text.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1318        output.extend_from_slice(&32_u32.to_le_bytes());
1319        output.extend_from_slice(&len.to_le_bytes());
1320        output.extend_from_slice(text.as_bytes());
1321        return Ok(());
1322    }
1323    if let crate::schema::EventPayload::KeyUp {
1324        key,
1325        shift_key,
1326        ctrl_key,
1327        alt_key,
1328        meta_key,
1329        repeat,
1330        code,
1331        text,
1332    } = event.payload
1333    {
1334        output.extend_from_slice(&EVENT_KEY_UP.to_le_bytes());
1335        output.extend_from_slice(&32_u16.to_le_bytes());
1336        output.extend_from_slice(&event.node_id.to_le_bytes());
1337        output.extend_from_slice(&event.handler_id.to_le_bytes());
1338        output.extend_from_slice(&(key as u16).to_le_bytes());
1339        let modifiers = (u8::from(shift_key) * MODIFIER_SHIFT)
1340            | (u8::from(ctrl_key) * MODIFIER_CTRL)
1341            | (u8::from(alt_key) * MODIFIER_ALT)
1342            | (u8::from(meta_key) * MODIFIER_META);
1343        output.push(modifiers);
1344        output.push(u8::from(repeat));
1345        output.extend_from_slice(&code.to_le_bytes());
1346        let len = u32::try_from(text.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1347        output.extend_from_slice(&32_u32.to_le_bytes());
1348        output.extend_from_slice(&len.to_le_bytes());
1349        output.extend_from_slice(text.as_bytes());
1350        return Ok(());
1351    }
1352    if let crate::schema::EventPayload::ValueChanged(value) = event.payload {
1353        output.extend_from_slice(&EVENT_VALUE_CHANGED.to_le_bytes());
1354        output.extend_from_slice(&24_u16.to_le_bytes());
1355        output.extend_from_slice(&event.node_id.to_le_bytes());
1356        output.extend_from_slice(&event.handler_id.to_le_bytes());
1357        output.extend_from_slice(&value.to_bits().to_le_bytes());
1358        return Ok(());
1359    }
1360    if let crate::schema::EventPayload::WindowSizeChanged {
1361        width_dp,
1362        height_dp,
1363        class,
1364        height_class,
1365        safe_area_top,
1366        safe_area_leading,
1367        safe_area_trailing,
1368    } = event.payload
1369    {
1370        output.extend_from_slice(&EVENT_WINDOW_SIZE_CHANGED.to_le_bytes());
1371        output.extend_from_slice(&44_u16.to_le_bytes());
1372        output.extend_from_slice(&event.node_id.to_le_bytes());
1373        output.extend_from_slice(&event.handler_id.to_le_bytes());
1374        output.extend_from_slice(&width_dp.to_bits().to_le_bytes());
1375        output.extend_from_slice(&height_dp.to_bits().to_le_bytes());
1376        output.extend_from_slice(&u32::from(u16::from(class)).to_le_bytes());
1377        output.extend_from_slice(&u32::from(u16::from(height_class)).to_le_bytes());
1378        output.extend_from_slice(&safe_area_top.to_bits().to_le_bytes());
1379        output.extend_from_slice(&safe_area_leading.to_bits().to_le_bytes());
1380        output.extend_from_slice(&safe_area_trailing.to_bits().to_le_bytes());
1381        return Ok(());
1382    }
1383    if let crate::schema::EventPayload::DesignSystemResolved(system) = event.payload {
1384        output.extend_from_slice(&EVENT_DESIGN_SYSTEM_RESOLVED.to_le_bytes());
1385        output.extend_from_slice(&20_u16.to_le_bytes());
1386        output.extend_from_slice(&event.node_id.to_le_bytes());
1387        output.extend_from_slice(&event.handler_id.to_le_bytes());
1388        // The tag in a word, which keeps the record a multiple of four the way every
1389        // other record here is.
1390        output.extend_from_slice(&u32::from(u16::from(system)).to_le_bytes());
1391        return Ok(());
1392    }
1393    if let crate::schema::EventPayload::NotificationPermissionChanged(state) = event.payload {
1394        output.extend_from_slice(&EVENT_NOTIFICATION_PERMISSION_CHANGED.to_le_bytes());
1395        output.extend_from_slice(&20_u16.to_le_bytes());
1396        output.extend_from_slice(&event.node_id.to_le_bytes());
1397        output.extend_from_slice(&event.handler_id.to_le_bytes());
1398        output.extend_from_slice(&u32::from(u16::from(state)).to_le_bytes());
1399        return Ok(());
1400    }
1401    if let crate::schema::EventPayload::AnimationEvent {
1402        animation_id,
1403        kind,
1404        property,
1405        slot,
1406        iteration,
1407        elapsed_ms,
1408        time_nanos,
1409    } = event.payload
1410    {
1411        output.extend_from_slice(&EVENT_ANIMATION.to_le_bytes());
1412        output.extend_from_slice(&40_u16.to_le_bytes());
1413        output.extend_from_slice(&event.node_id.to_le_bytes());
1414        output.extend_from_slice(&event.handler_id.to_le_bytes());
1415        output.extend_from_slice(&animation_id.to_le_bytes());
1416        output.push(kind as u8);
1417        output.push(property as u8);
1418        output.push(slot);
1419        output.push(0);
1420        output.extend_from_slice(&iteration.to_le_bytes());
1421        output.extend_from_slice(&elapsed_ms.to_bits().to_le_bytes());
1422        output.extend_from_slice(&time_nanos.to_le_bytes());
1423        return Ok(());
1424    }
1425    if let crate::schema::EventPayload::Pointer {
1426        kind,
1427        pointer_id,
1428        pointer_type,
1429        x,
1430        y,
1431        buttons,
1432        button,
1433        modifiers,
1434        click_count,
1435        delta_x,
1436        delta_y,
1437        delta_mode,
1438        timestamp_nanos,
1439    } = event.payload
1440    {
1441        output.extend_from_slice(&EVENT_POINTER.to_le_bytes());
1442        output.extend_from_slice(&(POINTER_RECORD_LEN as u16).to_le_bytes());
1443        output.extend_from_slice(&event.node_id.to_le_bytes());
1444        output.extend_from_slice(&event.handler_id.to_le_bytes());
1445        output.extend_from_slice(&u32::from(u16::from(kind)).to_le_bytes());
1446        output.extend_from_slice(&pointer_id.to_le_bytes());
1447        output.extend_from_slice(&u32::from(u16::from(pointer_type)).to_le_bytes());
1448        output.extend_from_slice(&x.to_bits().to_le_bytes());
1449        output.extend_from_slice(&y.to_bits().to_le_bytes());
1450        output.extend_from_slice(&buttons.to_le_bytes());
1451        output.extend_from_slice(&button.to_le_bytes());
1452        output.extend_from_slice(&modifiers.to_le_bytes());
1453        output.extend_from_slice(&click_count.to_le_bytes());
1454        output.extend_from_slice(&delta_x.to_bits().to_le_bytes());
1455        output.extend_from_slice(&delta_y.to_bits().to_le_bytes());
1456        output.extend_from_slice(&u32::from(u16::from(delta_mode)).to_le_bytes());
1457        output.extend_from_slice(&timestamp_nanos.to_le_bytes());
1458        return Ok(());
1459    }
1460    if let crate::schema::EventPayload::CodePointer {
1461        kind,
1462        pointer_id,
1463        pointer_type,
1464        x,
1465        y,
1466        buttons,
1467        button,
1468        modifiers,
1469        click_count,
1470        delta_x,
1471        delta_y,
1472        delta_mode,
1473        timestamp_nanos,
1474        position,
1475    } = event.payload
1476    {
1477        // The pointer record as a `Pointer` event writes it, under this tag and length.
1478        encode_event(
1479            &HostEvent {
1480                node_id: event.node_id,
1481                handler_id: event.handler_id,
1482                payload: crate::schema::EventPayload::Pointer {
1483                    kind,
1484                    pointer_id,
1485                    pointer_type,
1486                    x,
1487                    y,
1488                    buttons,
1489                    button,
1490                    modifiers,
1491                    click_count,
1492                    delta_x,
1493                    delta_y,
1494                    delta_mode,
1495                    timestamp_nanos,
1496                },
1497            },
1498            output,
1499        )?;
1500        output[0..2].copy_from_slice(&EVENT_CODE_POINTER.to_le_bytes());
1501        output[2..4].copy_from_slice(&(CODE_POINTER_LEN as u16).to_le_bytes());
1502        let (line, column) = position.map_or((NO_CODE_POSITION, NO_CODE_POSITION), |at| {
1503            (at.line, at.column)
1504        });
1505        output.extend_from_slice(&line.to_le_bytes());
1506        output.extend_from_slice(&column.to_le_bytes());
1507        return Ok(());
1508    }
1509    if let crate::schema::EventPayload::ReducedMotionChanged(state) = event.payload {
1510        output.extend_from_slice(&EVENT_REDUCED_MOTION_CHANGED.to_le_bytes());
1511        output.extend_from_slice(&20_u16.to_le_bytes());
1512        output.extend_from_slice(&event.node_id.to_le_bytes());
1513        output.extend_from_slice(&event.handler_id.to_le_bytes());
1514        output.extend_from_slice(&u32::from(u16::from(state)).to_le_bytes());
1515        return Ok(());
1516    }
1517    if let crate::schema::EventPayload::ColorSchemeChanged(scheme) = event.payload {
1518        output.extend_from_slice(&EVENT_COLOR_SCHEME_CHANGED.to_le_bytes());
1519        output.extend_from_slice(&20_u16.to_le_bytes());
1520        output.extend_from_slice(&event.node_id.to_le_bytes());
1521        output.extend_from_slice(&event.handler_id.to_le_bytes());
1522        output.extend_from_slice(&u32::from(u16::from(scheme)).to_le_bytes());
1523        return Ok(());
1524    }
1525    if let crate::schema::EventPayload::DensityChanged { scale } = event.payload {
1526        output.extend_from_slice(&EVENT_DENSITY_CHANGED.to_le_bytes());
1527        output.extend_from_slice(&20_u16.to_le_bytes());
1528        output.extend_from_slice(&event.node_id.to_le_bytes());
1529        output.extend_from_slice(&event.handler_id.to_le_bytes());
1530        output.extend_from_slice(&scale.to_bits().to_le_bytes());
1531        return Ok(());
1532    }
1533    match event.payload {
1534        crate::schema::EventPayload::CodeChanged {
1535            version,
1536            start_line,
1537            start_column,
1538            end_line,
1539            end_column,
1540            text,
1541        } => {
1542            put_event_header(output, EVENT_CODE_CHANGED, 44, event);
1543            for value in [version, start_line, start_column, end_line, end_column] {
1544                output.extend_from_slice(&value.to_le_bytes());
1545            }
1546            let len = u32::try_from(text.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1547            output.extend_from_slice(&44_u32.to_le_bytes());
1548            output.extend_from_slice(&len.to_le_bytes());
1549            output.extend_from_slice(text.as_bytes());
1550            return Ok(());
1551        }
1552        crate::schema::EventPayload::CodeEditRejected {
1553            request_id,
1554            base_version,
1555            current_version,
1556            start_line,
1557            start_column,
1558            end_line,
1559            end_column,
1560        } => {
1561            put_event_header(output, EVENT_CODE_EDIT_REJECTED, 44, event);
1562            for value in [
1563                request_id,
1564                base_version,
1565                current_version,
1566                start_line,
1567                start_column,
1568                end_line,
1569                end_column,
1570            ] {
1571                output.extend_from_slice(&value.to_le_bytes());
1572            }
1573            return Ok(());
1574        }
1575        crate::schema::EventPayload::CodeHovered {
1576            decoration,
1577            line,
1578            column,
1579            phase,
1580        } => {
1581            put_event_header(output, EVENT_CODE_HOVERED, 36, event);
1582            output.extend_from_slice(&decoration.to_le_bytes());
1583            output.extend_from_slice(&line.to_le_bytes());
1584            output.extend_from_slice(&column.to_le_bytes());
1585            output.extend_from_slice(&u32::from(u16::from(phase)).to_le_bytes());
1586            return Ok(());
1587        }
1588        crate::schema::EventPayload::CodeSaveRequested { version } => {
1589            put_event_header(output, EVENT_CODE_SAVE_REQUESTED, 24, event);
1590            output.extend_from_slice(&version.to_le_bytes());
1591            // The padding that keeps the record a multiple of four bytes.
1592            output.extend_from_slice(&0_u32.to_le_bytes());
1593            return Ok(());
1594        }
1595        crate::schema::EventPayload::DecorationActivated { decoration } => {
1596            put_event_header(output, EVENT_DECORATION_ACTIVATED, 24, event);
1597            output.extend_from_slice(&decoration.to_le_bytes());
1598            return Ok(());
1599        }
1600        crate::schema::EventPayload::SelectionChanged {
1601            version,
1602            anchor_line,
1603            anchor_column,
1604            active_line,
1605            active_column,
1606        } => {
1607            put_event_header(output, EVENT_SELECTION_CHANGED, 36, event);
1608            for value in [
1609                version,
1610                anchor_line,
1611                anchor_column,
1612                active_line,
1613                active_column,
1614            ] {
1615                output.extend_from_slice(&value.to_le_bytes());
1616            }
1617            return Ok(());
1618        }
1619        crate::schema::EventPayload::VisibleRangeChanged {
1620            version,
1621            first_line,
1622            last_line,
1623        } => {
1624            put_event_header(output, EVENT_VISIBLE_RANGE_CHANGED, 28, event);
1625            for value in [version, first_line, last_line] {
1626                output.extend_from_slice(&value.to_le_bytes());
1627            }
1628            return Ok(());
1629        }
1630        crate::schema::EventPayload::EditorFocusChanged { focused } => {
1631            put_event_header(output, EVENT_EDITOR_FOCUS_CHANGED, 24, event);
1632            output.extend_from_slice(&u32::from(focused).to_le_bytes());
1633            output.extend_from_slice(&0_u32.to_le_bytes());
1634            return Ok(());
1635        }
1636        crate::schema::EventPayload::FoldChanged {
1637            start_line,
1638            collapsed,
1639        } => {
1640            put_event_header(output, EVENT_FOLD_CHANGED, 24, event);
1641            output.extend_from_slice(&start_line.to_le_bytes());
1642            output.extend_from_slice(&u32::from(collapsed).to_le_bytes());
1643            return Ok(());
1644        }
1645        crate::schema::EventPayload::CompositionChanged { composing } => {
1646            put_event_header(output, EVENT_COMPOSITION_CHANGED, 24, event);
1647            output.extend_from_slice(&u32::from(composing).to_le_bytes());
1648            output.extend_from_slice(&0_u32.to_le_bytes());
1649            return Ok(());
1650        }
1651        _ => {}
1652    }
1653    match event.payload {
1654        crate::schema::EventPayload::WindowFocusChanged { focused } => {
1655            put_event_header(output, EVENT_WINDOW_FOCUS_CHANGED, 20, event);
1656            output.extend_from_slice(&u32::from(focused).to_le_bytes());
1657            return Ok(());
1658        }
1659        crate::schema::EventPayload::WindowMoved {
1660            x,
1661            y,
1662            width,
1663            height,
1664        } => {
1665            put_event_header(output, EVENT_WINDOW_MOVED, 32, event);
1666            for value in [x, y, width, height] {
1667                output.extend_from_slice(&value.to_bits().to_le_bytes());
1668            }
1669            return Ok(());
1670        }
1671        crate::schema::EventPayload::WindowDrag {
1672            phase,
1673            screen_x,
1674            screen_y,
1675            over_window,
1676        } => {
1677            put_event_header(output, EVENT_WINDOW_DRAG, 32, event);
1678            output.extend_from_slice(&phase.to_le_bytes());
1679            output.extend_from_slice(&screen_x.to_bits().to_le_bytes());
1680            output.extend_from_slice(&screen_y.to_bits().to_le_bytes());
1681            output.extend_from_slice(&over_window.to_le_bytes());
1682            return Ok(());
1683        }
1684        crate::schema::EventPayload::WindowDragOver { kind, window, x, y } => {
1685            put_event_header(output, EVENT_WINDOW_DRAG_OVER, 32, event);
1686            output.extend_from_slice(&kind.to_le_bytes());
1687            output.extend_from_slice(&window.to_le_bytes());
1688            output.extend_from_slice(&x.to_bits().to_le_bytes());
1689            output.extend_from_slice(&y.to_bits().to_le_bytes());
1690            return Ok(());
1691        }
1692        _ => {}
1693    }
1694    if let crate::schema::EventPayload::CodeEditGroupResult {
1695        request_id,
1696        status,
1697        base_version,
1698        current_version,
1699        index,
1700    } = event.payload
1701    {
1702        put_event_header(
1703            output,
1704            EVENT_CODE_EDIT_GROUP_RESULT,
1705            CODE_EDIT_GROUP_RESULT_LEN as u16,
1706            event,
1707        );
1708        for value in [
1709            request_id,
1710            u32::from(status as u16),
1711            base_version,
1712            current_version,
1713            index,
1714        ] {
1715            output.extend_from_slice(&value.to_le_bytes());
1716        }
1717        return Ok(());
1718    }
1719    if let crate::schema::EventPayload::FileDialogResult {
1720        request,
1721        status,
1722        filter,
1723        paths,
1724    } = event.payload
1725    {
1726        put_event_header(
1727            output,
1728            EVENT_FILE_DIALOG_RESULT,
1729            FILE_DIALOG_RESULT_LEN as u16,
1730            event,
1731        );
1732        output.extend_from_slice(&request.to_le_bytes());
1733        output.extend_from_slice(&u32::from(status as u16).to_le_bytes());
1734        output.extend_from_slice(&filter.to_le_bytes());
1735        let len = u32::try_from(paths.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1736        output.extend_from_slice(&(FILE_DIALOG_RESULT_LEN as u32).to_le_bytes());
1737        output.extend_from_slice(&len.to_le_bytes());
1738        output.extend_from_slice(paths.as_bytes());
1739        return Ok(());
1740    }
1741    if let crate::schema::EventPayload::ClipboardText {
1742        request,
1743        status,
1744        len,
1745        text,
1746    } = event.payload
1747    {
1748        put_event_header(
1749            output,
1750            EVENT_CLIPBOARD_TEXT,
1751            CLIPBOARD_TEXT_LEN as u16,
1752            event,
1753        );
1754        output.extend_from_slice(&request.to_le_bytes());
1755        output.extend_from_slice(&status.to_le_bytes());
1756        output.extend_from_slice(&len.to_le_bytes());
1757        let text_len = u32::try_from(text.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1758        output.extend_from_slice(&(CLIPBOARD_TEXT_LEN as u32).to_le_bytes());
1759        output.extend_from_slice(&text_len.to_le_bytes());
1760        output.extend_from_slice(text.as_bytes());
1761        return Ok(());
1762    }
1763    match event.payload {
1764        crate::schema::EventPayload::CodeMetrics { line_height_px } => {
1765            put_event_header(output, EVENT_CODE_METRICS, 24, event);
1766            output.extend_from_slice(&line_height_px.to_bits().to_le_bytes());
1767            return Ok(());
1768        }
1769        crate::schema::EventPayload::CodeScrolled { offset_px } => {
1770            put_event_header(output, EVENT_CODE_SCROLLED, 24, event);
1771            output.extend_from_slice(&offset_px.to_bits().to_le_bytes());
1772            return Ok(());
1773        }
1774        _ => {}
1775    }
1776    if let crate::schema::EventPayload::SelectionsChanged {
1777        version,
1778        selections,
1779    } = event.payload
1780    {
1781        put_event_header(
1782            output,
1783            EVENT_SELECTIONS_CHANGED,
1784            SELECTIONS_CHANGED_LEN as u16,
1785            event,
1786        );
1787        output.extend_from_slice(&version.to_le_bytes());
1788        let len = u32::try_from(selections.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1789        output.extend_from_slice(&(SELECTIONS_CHANGED_LEN as u32).to_le_bytes());
1790        output.extend_from_slice(&len.to_le_bytes());
1791        output.extend_from_slice(selections);
1792        return Ok(());
1793    }
1794    if let crate::schema::EventPayload::IoAnswer {
1795        request,
1796        status,
1797        data,
1798    } = event.payload
1799    {
1800        put_event_header(output, EVENT_IO_ANSWER, IO_ANSWER_LEN as u16, event);
1801        output.extend_from_slice(&request.to_le_bytes());
1802        output.extend_from_slice(&u32::from(u16::from(status)).to_le_bytes());
1803        let data_len = u32::try_from(data.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1804        output.extend_from_slice(&(IO_ANSWER_LEN as u32).to_le_bytes());
1805        output.extend_from_slice(&data_len.to_le_bytes());
1806        output.extend_from_slice(data);
1807        return Ok(());
1808    }
1809    if let crate::schema::EventPayload::FileHandles {
1810        request,
1811        status,
1812        filter,
1813        delivery,
1814        first_handle,
1815        names,
1816        kinds,
1817    } = event.payload
1818    {
1819        put_event_header(output, EVENT_FILE_HANDLES, FILE_HANDLES_LEN as u16, event);
1820        output.extend_from_slice(&request.to_le_bytes());
1821        output.extend_from_slice(&u32::from(status as u16).to_le_bytes());
1822        output.extend_from_slice(&filter.to_le_bytes());
1823        output.extend_from_slice(&u32::from(delivery as u16).to_le_bytes());
1824        output.extend_from_slice(&first_handle.to_le_bytes());
1825        let names_len = u32::try_from(names.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1826        let kinds_len = u32::try_from(kinds.len()).map_err(|_| ProtocolError::LengthOverflow)?;
1827        let kinds_at = (FILE_HANDLES_LEN as u32)
1828            .checked_add(names_len)
1829            .ok_or(ProtocolError::LengthOverflow)?;
1830        output.extend_from_slice(&(FILE_HANDLES_LEN as u32).to_le_bytes());
1831        output.extend_from_slice(&names_len.to_le_bytes());
1832        output.extend_from_slice(&kinds_at.to_le_bytes());
1833        output.extend_from_slice(&kinds_len.to_le_bytes());
1834        output.extend_from_slice(names.as_bytes());
1835        output.extend_from_slice(kinds.as_bytes());
1836        return Ok(());
1837    }
1838    if let crate::schema::EventPayload::ScrollChanged {
1839        item,
1840        settled,
1841        can_scroll_backward,
1842        can_scroll_forward,
1843        x_px,
1844        y_px,
1845        max_x_px,
1846        max_y_px,
1847        viewport_width_px,
1848        viewport_height_px,
1849    } = event.payload
1850    {
1851        use crate::schema::scroll_changed_flags as flag;
1852        put_event_header(
1853            output,
1854            EVENT_SCROLL_CHANGED,
1855            SCROLL_CHANGED_LEN as u16,
1856            event,
1857        );
1858        let mut flags = 0_u32;
1859        if settled {
1860            flags |= flag::SETTLED;
1861        }
1862        if can_scroll_backward {
1863            flags |= flag::CAN_SCROLL_BACKWARD;
1864        }
1865        if can_scroll_forward {
1866            flags |= flag::CAN_SCROLL_FORWARD;
1867        }
1868        output.extend_from_slice(&item.to_le_bytes());
1869        output.extend_from_slice(&flags.to_le_bytes());
1870        for value in [
1871            x_px,
1872            y_px,
1873            max_x_px,
1874            max_y_px,
1875            viewport_width_px,
1876            viewport_height_px,
1877        ] {
1878            output.extend_from_slice(&value.to_bits().to_le_bytes());
1879        }
1880        return Ok(());
1881    }
1882    if let crate::schema::EventPayload::NativeViewParent {
1883        handle,
1884        kind,
1885        scale,
1886    } = event.payload
1887    {
1888        put_event_header(
1889            output,
1890            EVENT_NATIVE_VIEW_PARENT,
1891            NATIVE_VIEW_PARENT_LEN as u16,
1892            event,
1893        );
1894        output.extend_from_slice(&handle.0.to_le_bytes());
1895        output.extend_from_slice(&(kind as u16).to_le_bytes());
1896        output.extend_from_slice(&0_u16.to_le_bytes());
1897        output.extend_from_slice(&scale.to_bits().to_le_bytes());
1898        return Ok(());
1899    }
1900    if let crate::schema::EventPayload::NativeViewFocus { focused } = event.payload {
1901        put_event_header(
1902            output,
1903            EVENT_NATIVE_VIEW_FOCUS,
1904            NATIVE_VIEW_FOCUS_LEN as u16,
1905            event,
1906        );
1907        output.extend_from_slice(&u32::from(focused).to_le_bytes());
1908        output.extend_from_slice(&0_u32.to_le_bytes());
1909        return Ok(());
1910    }
1911    if let crate::schema::EventPayload::MotionFinished {
1912        width_dp,
1913        height_dp,
1914    } = event.payload
1915    {
1916        put_event_header(
1917            output,
1918            EVENT_MOTION_FINISHED,
1919            MOTION_FINISHED_LEN as u16,
1920            event,
1921        );
1922        output.extend_from_slice(&width_dp.to_bits().to_le_bytes());
1923        output.extend_from_slice(&height_dp.to_bits().to_le_bytes());
1924        return Ok(());
1925    }
1926    if let crate::schema::EventPayload::CaretRect { line, column, rect } = event.payload {
1927        put_event_header(output, EVENT_CARET_RECT, CODE_RECT_EVENT_LEN as u16, event);
1928        output.extend_from_slice(&line.to_le_bytes());
1929        output.extend_from_slice(&column.to_le_bytes());
1930        put_code_rect(output, rect);
1931        return Ok(());
1932    }
1933    if let crate::schema::EventPayload::PositionRect { request, rect } = event.payload {
1934        put_event_header(
1935            output,
1936            EVENT_POSITION_RECT,
1937            CODE_RECT_EVENT_LEN as u16,
1938            event,
1939        );
1940        output.extend_from_slice(&request.to_le_bytes());
1941        output.extend_from_slice(&u32::from(rect.is_some()).to_le_bytes());
1942        put_code_rect(output, rect.unwrap_or_default());
1943        return Ok(());
1944    }
1945    if let crate::schema::EventPayload::ZoomChanged { k, os, level } = event.payload {
1946        output.extend_from_slice(&EVENT_ZOOM_CHANGED.to_le_bytes());
1947        output.extend_from_slice(&28_u16.to_le_bytes());
1948        output.extend_from_slice(&event.node_id.to_le_bytes());
1949        output.extend_from_slice(&event.handler_id.to_le_bytes());
1950        output.extend_from_slice(&k.to_bits().to_le_bytes());
1951        output.extend_from_slice(&os.to_bits().to_le_bytes());
1952        output.extend_from_slice(&level.to_le_bytes());
1953        return Ok(());
1954    }
1955    if let crate::schema::EventPayload::RangeRequested { start, count } = event.payload {
1956        output.extend_from_slice(&EVENT_RANGE_REQUESTED.to_le_bytes());
1957        output.extend_from_slice(&24_u16.to_le_bytes());
1958        output.extend_from_slice(&event.node_id.to_le_bytes());
1959        output.extend_from_slice(&event.handler_id.to_le_bytes());
1960        output.extend_from_slice(&start.to_le_bytes());
1961        output.extend_from_slice(&count.to_le_bytes());
1962        return Ok(());
1963    }
1964    let (tag, record_len, text, error_code) = match &event.payload {
1965        crate::schema::EventPayload::Clicked => (EVENT_CLICK, 16_u16, None, None),
1966        crate::schema::EventPayload::TextChanged(value) => {
1967            (EVENT_TEXT_CHANGED, 24, Some(*value), None)
1968        }
1969        crate::schema::EventPayload::TextSubmitted(value) => {
1970            (EVENT_TEXT_SUBMITTED, 24, Some(*value), None)
1971        }
1972        crate::schema::EventPayload::FocusLost => (EVENT_FOCUS_LOST, 16, None, None),
1973        crate::schema::EventPayload::FocusGained => (EVENT_FOCUS_GAINED, 16, None, None),
1974        crate::schema::EventPayload::FilesEntered => (EVENT_FILES_ENTERED, 16, None, None),
1975        crate::schema::EventPayload::FilesDropped(paths) => {
1976            (EVENT_FILES_DROPPED, 24, Some(*paths), None)
1977        }
1978        crate::schema::EventPayload::StorageLocation(path) => {
1979            (EVENT_STORAGE_LOCATION, 24, Some(*path), None)
1980        }
1981        crate::schema::EventPayload::Resync => (EVENT_RESYNC, 16, None, None),
1982        crate::schema::EventPayload::WindowCloseRequested => {
1983            (EVENT_WINDOW_CLOSE_REQUESTED, 16, None, None)
1984        }
1985        crate::schema::EventPayload::WindowUnavailable => {
1986            (EVENT_WINDOW_UNAVAILABLE, 16, None, None)
1987        }
1988        crate::schema::EventPayload::WindowClosed => (EVENT_WINDOW_CLOSED, 16, None, None),
1989        crate::schema::EventPayload::ApplicationReopen => {
1990            (EVENT_APPLICATION_REOPEN, 16, None, None)
1991        }
1992        // The shape of a protocol error: one word, then one string.
1993        crate::schema::EventPayload::WindowRequested { key, request } => {
1994            (EVENT_WINDOW_REQUESTED, 28, Some(*key), Some(*request))
1995        }
1996        crate::schema::EventPayload::LifecycleStart => (EVENT_LIFECYCLE_START, 16, None, None),
1997        crate::schema::EventPayload::LifecycleStop => (EVENT_LIFECYCLE_STOP, 16, None, None),
1998        crate::schema::EventPayload::ProtocolError { code, message } => {
1999            (EVENT_PROTOCOL_ERROR, 28, Some(*message), Some(*code))
2000        }
2001        // The same shape as a protocol error: one word, then one string.
2002        crate::schema::EventPayload::NotificationActivated { action, key } => {
2003            (EVENT_NOTIFICATION_ACTIVATED, 28, Some(*key), Some(*action))
2004        }
2005        crate::schema::EventPayload::KeyDown { .. }
2006        | crate::schema::EventPayload::KeyUp { .. }
2007        | crate::schema::EventPayload::RangeRequested { .. }
2008        | crate::schema::EventPayload::ValueChanged(_)
2009        | crate::schema::EventPayload::WindowSizeChanged { .. }
2010        | crate::schema::EventPayload::DesignSystemResolved(_)
2011        | crate::schema::EventPayload::NotificationPermissionChanged(_)
2012        | crate::schema::EventPayload::CodeChanged { .. }
2013        | crate::schema::EventPayload::CodeEditRejected { .. }
2014        | crate::schema::EventPayload::CodeHovered { .. }
2015        | crate::schema::EventPayload::CodeSaveRequested { .. }
2016        | crate::schema::EventPayload::DecorationActivated { .. }
2017        | crate::schema::EventPayload::SelectionChanged { .. }
2018        | crate::schema::EventPayload::VisibleRangeChanged { .. }
2019        | crate::schema::EventPayload::EditorFocusChanged { .. }
2020        | crate::schema::EventPayload::FoldChanged { .. }
2021        | crate::schema::EventPayload::CompositionChanged { .. }
2022        | crate::schema::EventPayload::WindowFocusChanged { .. }
2023        | crate::schema::EventPayload::WindowMoved { .. }
2024        | crate::schema::EventPayload::WindowDrag { .. }
2025        | crate::schema::EventPayload::WindowDragOver { .. }
2026        | crate::schema::EventPayload::CodeMetrics { .. }
2027        | crate::schema::EventPayload::CodeScrolled { .. }
2028        | crate::schema::EventPayload::FileDialogResult { .. }
2029        | crate::schema::EventPayload::ClipboardText { .. }
2030        | crate::schema::EventPayload::IoAnswer { .. }
2031        | crate::schema::EventPayload::FileHandles { .. }
2032        | crate::schema::EventPayload::ScrollChanged { .. }
2033        | crate::schema::EventPayload::NativeViewParent { .. }
2034        | crate::schema::EventPayload::NativeViewFocus { .. }
2035        | crate::schema::EventPayload::MotionFinished { .. }
2036        | crate::schema::EventPayload::CaretRect { .. }
2037        | crate::schema::EventPayload::PositionRect { .. }
2038        | crate::schema::EventPayload::CodePointer { .. }
2039        | crate::schema::EventPayload::CodeEditGroupResult { .. }
2040        | crate::schema::EventPayload::SelectionsChanged { .. } => unreachable!(),
2041        crate::schema::EventPayload::AnimationEvent { .. }
2042        | crate::schema::EventPayload::Pointer { .. }
2043        | crate::schema::EventPayload::ReducedMotionChanged(_)
2044        | crate::schema::EventPayload::ColorSchemeChanged(_)
2045        | crate::schema::EventPayload::DensityChanged { .. }
2046        | crate::schema::EventPayload::ZoomChanged { .. } => unreachable!(),
2047    };
2048    output.extend_from_slice(&tag.to_le_bytes());
2049    output.extend_from_slice(&record_len.to_le_bytes());
2050    output.extend_from_slice(&event.node_id.to_le_bytes());
2051    output.extend_from_slice(&event.handler_id.to_le_bytes());
2052    if let Some(code) = error_code {
2053        output.extend_from_slice(&code.to_le_bytes());
2054    }
2055    if let Some(text) = text {
2056        let offset = u32::from(record_len);
2057        let len = u32::try_from(text.len()).map_err(|_| ProtocolError::LengthOverflow)?;
2058        output.extend_from_slice(&offset.to_le_bytes());
2059        output.extend_from_slice(&len.to_le_bytes());
2060        output.extend_from_slice(text.as_bytes());
2061    }
2062    Ok(())
2063}
2064
2065/// The sixteen bytes every event starts with: the tag, the record's length, the node and
2066/// the handler.
2067fn put_event_header(output: &mut Vec<u8>, tag: u16, record_len: u16, event: &HostEvent<'_>) {
2068    output.extend_from_slice(&tag.to_le_bytes());
2069    output.extend_from_slice(&record_len.to_le_bytes());
2070    output.extend_from_slice(&event.node_id.to_le_bytes());
2071    output.extend_from_slice(&event.handler_id.to_le_bytes());
2072}
2073
2074impl fmt::Display for ProtocolError {
2075    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
2076        write!(formatter, "protocol error: {self:?}")
2077    }
2078}
2079
2080impl std::error::Error for ProtocolError {}
2081
2082/// Reusable encoder. Once capacities are warmed, `clear` and `finish` allocate no memory.
2083pub struct BatchEncoder {
2084    records: Vec<u8>,
2085    strings: Vec<u8>,
2086    string_fixups: Vec<usize>,
2087    arena: Vec<u8>,
2088    record_count: u32,
2089}
2090
2091impl Default for BatchEncoder {
2092    fn default() -> Self {
2093        Self::with_capacity(4096, 1024, 64)
2094    }
2095}
2096
2097impl BatchEncoder {
2098    pub fn with_capacity(record_bytes: usize, string_bytes: usize, string_count: usize) -> Self {
2099        let mut encoder = Self {
2100            records: Vec::with_capacity(record_bytes),
2101            strings: Vec::with_capacity(string_bytes),
2102            string_fixups: Vec::with_capacity(string_count),
2103            arena: Vec::with_capacity(record_bytes + string_bytes),
2104            record_count: 0,
2105        };
2106        encoder.clear();
2107        encoder
2108    }
2109
2110    pub fn clear(&mut self) {
2111        self.records.clear();
2112        self.strings.clear();
2113        self.string_fixups.clear();
2114        self.arena.clear();
2115        self.record_count = 0;
2116        self.begin_record(TAG_ENVELOPE, 8);
2117        self.put_u32(0);
2118        self.put_u32(0);
2119    }
2120
2121    pub fn encode(&mut self, mutation: &Mutation<'_>) -> Result<(), ProtocolError> {
2122        match mutation {
2123            Mutation::Create { node_id, widget } => {
2124                self.begin_record(TAG_CREATE, 8);
2125                self.put_u32(*node_id);
2126                self.put_u16(*widget as u16);
2127                self.put_u16(0);
2128            }
2129            Mutation::SetProp {
2130                node_id,
2131                property,
2132                value,
2133            } => {
2134                self.begin_record(TAG_SET_PROP, 20);
2135                self.put_u32(*node_id);
2136                self.put_u16(*property as u16);
2137                match value {
2138                    PropertyValue::None => {
2139                        self.put_u16(VALUE_NONE);
2140                        self.put_u64(0);
2141                        self.put_u32(0);
2142                    }
2143                    PropertyValue::String(value) => {
2144                        self.put_u16(VALUE_STRING);
2145                        self.put_string_ref(value)?;
2146                        self.put_u32(0);
2147                    }
2148                    PropertyValue::Bool(value) => {
2149                        self.put_u16(VALUE_BOOL);
2150                        self.put_u64(u64::from(*value));
2151                        self.put_u32(0);
2152                    }
2153                    PropertyValue::Integer(value) => {
2154                        self.put_u16(VALUE_I64);
2155                        self.put_u64(*value as u64);
2156                        self.put_u32(0);
2157                    }
2158                    PropertyValue::Float(value) => {
2159                        self.put_u16(VALUE_F32);
2160                        self.put_u64(u64::from(value.to_bits()));
2161                        self.put_u32(0);
2162                    }
2163                    PropertyValue::Bytes(value) => {
2164                        self.put_u16(VALUE_BYTES);
2165                        self.put_bytes_ref(value)?;
2166                        self.put_u32(0);
2167                    }
2168                }
2169            }
2170            Mutation::SetModifier {
2171                node_id,
2172                index,
2173                modifier,
2174            } => {
2175                let (tag, words) = modifier_fields(modifier);
2176                // The tag fixes how long the value is, so the record is as long as the
2177                // schema says that tag's records are and every other modifier keeps the
2178                // 28 bytes it always had.
2179                let extra = modifier_extra_words(tag).ok_or(ProtocolError::InvalidModifier(tag))?;
2180                self.begin_record(TAG_SET_MODIFIER, 24 + 8 * u16::from(extra));
2181                self.put_u32(*node_id);
2182                self.put_u16(*index);
2183                self.put_u16(tag);
2184                for word in &words[..2 + usize::from(extra)] {
2185                    self.put_u64(*word);
2186                }
2187            }
2188            Mutation::Insert {
2189                parent_id,
2190                node_id,
2191                index,
2192            } => {
2193                self.begin_record(TAG_INSERT, 12);
2194                self.put_u32(*parent_id);
2195                self.put_u32(*node_id);
2196                self.put_u32(*index);
2197            }
2198            Mutation::Move {
2199                parent_id,
2200                node_id,
2201                index,
2202            } => {
2203                self.begin_record(TAG_MOVE, 12);
2204                self.put_u32(*parent_id);
2205                self.put_u32(*node_id);
2206                self.put_u32(*index);
2207            }
2208            Mutation::Remove { node_id } => {
2209                self.begin_record(TAG_REMOVE, 4);
2210                self.put_u32(*node_id);
2211            }
2212            Mutation::SetText {
2213                node_id,
2214                text,
2215                selection,
2216            } => {
2217                self.begin_record(TAG_SET_TEXT, 20);
2218                self.put_u32(*node_id);
2219                self.put_string_ref(text)?;
2220                let (start, end) =
2221                    selection.map_or((u32::MAX, u32::MAX), |value| (value.start, value.end));
2222                self.put_u32(start);
2223                self.put_u32(end);
2224            }
2225            Mutation::AppendText { node_id, text } => {
2226                self.begin_record(TAG_APPEND_TEXT, 12);
2227                self.put_u32(*node_id);
2228                self.put_string_ref(text)?;
2229            }
2230            Mutation::RegisterAsset {
2231                asset_id,
2232                kind,
2233                bytes,
2234            } => {
2235                self.begin_record(TAG_REGISTER_ASSET, 16);
2236                self.put_u32(*asset_id);
2237                self.put_u16(*kind as u16);
2238                self.put_u16(0);
2239                self.put_bytes_ref(bytes)?;
2240            }
2241            Mutation::ReleaseAsset { asset_id } => {
2242                self.begin_record(TAG_RELEASE_ASSET, 4);
2243                self.put_u32(*asset_id);
2244            }
2245            Mutation::ShowMessage {
2246                handler_id,
2247                text,
2248                action,
2249                duration,
2250                placement,
2251                offset_dp,
2252            } => {
2253                self.begin_record(TAG_SHOW_MESSAGE, 36);
2254                self.put_u64(*handler_id);
2255                self.put_string_ref(text)?;
2256                self.put_string_ref(action)?;
2257                self.put_u16(*duration as u16);
2258                // The two placement tags take the word that used to be padding, so a
2259                // record without a placement keeps the bytes it always had there.
2260                self.put_u16(placement.map_or(0, |placement| placement.vertical as u16));
2261                self.put_u16(placement.map_or(0, |placement| placement.horizontal as u16));
2262                self.put_u16(0);
2263                self.put_u32(offset_dp.unwrap_or(f32::NAN).to_bits());
2264            }
2265            Mutation::EditCode {
2266                node_id,
2267                request_id,
2268                base_version,
2269                start_line,
2270                start_column,
2271                end_line,
2272                end_column,
2273                text,
2274            } => {
2275                self.begin_record(TAG_EDIT_CODE, 36);
2276                self.put_u32(*node_id);
2277                self.put_u32(*request_id);
2278                self.put_u32(*base_version);
2279                self.put_u32(*start_line);
2280                self.put_u32(*start_column);
2281                self.put_u32(*end_line);
2282                self.put_u32(*end_column);
2283                self.put_string_ref(text)?;
2284            }
2285            Mutation::EditCodeGroup {
2286                node_id,
2287                request_id,
2288                base_version,
2289                edits,
2290            } => {
2291                self.begin_record(TAG_EDIT_CODE_GROUP, (EDIT_CODE_GROUP_LEN - 4) as u16);
2292                self.put_u32(*node_id);
2293                self.put_u32(*request_id);
2294                self.put_u32(*base_version);
2295                self.put_bytes_ref(edits)?;
2296            }
2297            Mutation::SetSelection {
2298                node_id,
2299                base_version,
2300                anchor_line,
2301                anchor_column,
2302                active_line,
2303                active_column,
2304            } => {
2305                self.begin_record(TAG_SET_SELECTION, 24);
2306                self.put_u32(*node_id);
2307                self.put_u32(*base_version);
2308                self.put_u32(*anchor_line);
2309                self.put_u32(*anchor_column);
2310                self.put_u32(*active_line);
2311                self.put_u32(*active_column);
2312            }
2313            Mutation::RevealRange {
2314                node_id,
2315                base_version,
2316                start_line,
2317                start_column,
2318                end_line,
2319                end_column,
2320                align,
2321            } => {
2322                self.begin_record(TAG_REVEAL_RANGE, 28);
2323                self.put_u32(*node_id);
2324                self.put_u32(*base_version);
2325                self.put_u32(*start_line);
2326                self.put_u32(*start_column);
2327                self.put_u32(*end_line);
2328                self.put_u32(*end_column);
2329                self.put_u32(u32::from(*align as u16));
2330            }
2331            Mutation::SetFolded {
2332                node_id,
2333                start_line,
2334                collapsed,
2335            } => {
2336                self.begin_record(TAG_SET_FOLDED, 12);
2337                self.put_u32(*node_id);
2338                self.put_u32(*start_line);
2339                self.put_u32(u32::from(*collapsed));
2340            }
2341            Mutation::SetTheme(theme) => {
2342                self.begin_record(TAG_SET_THEME, THEME_PAYLOAD_LEN as u16);
2343                self.put_theme(theme)?;
2344            }
2345            Mutation::SetWindowTheme { node_id, theme } => {
2346                self.begin_record(TAG_SET_WINDOW_THEME, 4 + THEME_PAYLOAD_LEN as u16);
2347                self.put_u32(*node_id);
2348                self.put_theme(theme)?;
2349            }
2350            Mutation::FocusWindow { node_id } => {
2351                self.begin_record(TAG_FOCUS_WINDOW, 4);
2352                self.put_u32(*node_id);
2353            }
2354            Mutation::RequestFocus { node_id } => {
2355                self.begin_record(TAG_REQUEST_FOCUS, 4);
2356                self.put_u32(*node_id);
2357            }
2358            Mutation::SetScrollOffset { node_id, offset_px } => {
2359                self.begin_record(TAG_SET_SCROLL_OFFSET, 12);
2360                self.put_u32(*node_id);
2361                self.put_u64(offset_px.to_bits());
2362            }
2363            Mutation::ShowFileDialog {
2364                request,
2365                window,
2366                kind,
2367                default_filter,
2368                title,
2369                directory,
2370                name,
2371                filters,
2372            } => {
2373                self.begin_record(TAG_SHOW_FILE_DIALOG, SHOW_FILE_DIALOG_PAYLOAD_LEN as u16);
2374                self.put_u32(*request);
2375                self.put_u32(*window);
2376                self.put_u16(*kind as u16);
2377                self.put_u16(*default_filter);
2378                self.put_string_ref(title)?;
2379                self.put_string_ref(directory)?;
2380                self.put_string_ref(name)?;
2381                self.put_string_ref(filters)?;
2382            }
2383            Mutation::SetOverlayTokens(overlay) => {
2384                self.begin_record(TAG_SET_OVERLAY_TOKENS, OVERLAY_TOKENS_PAYLOAD_LEN as u16);
2385                self.put_u16(overlay.sheet_corner_radius);
2386                self.put_u16(overlay.dialog_corner_radius);
2387                self.put_u16(overlay.popup_corner_radius);
2388                self.put_u16(overlay.sheet_elevation);
2389                self.put_u16(overlay.popup_elevation);
2390                self.put_u16(overlay.dialog_elevation);
2391                self.put_u16(overlay.sheet_padding);
2392                self.put_u16(overlay.dialog_padding);
2393                self.put_u16(overlay.popup_padding);
2394                self.put_u16(0);
2395                self.put_u32(overlay.scrim);
2396                self.put_u16(overlay.toast_elevation);
2397                self.put_u16(overlay.toast_corner_radius);
2398                self.put_u32(overlay.toast_container_light);
2399                self.put_u32(overlay.toast_container_dark);
2400                self.put_u32(overlay.toast_content_light);
2401                self.put_u32(overlay.toast_content_dark);
2402                self.put_u16(
2403                    overlay
2404                        .toast_border_width
2405                        .unwrap_or(TOAST_BORDER_DESIGN_SYSTEM),
2406                );
2407                self.put_u16(overlay.toast_padding_horizontal);
2408                self.put_u16(overlay.toast_padding_vertical);
2409                self.put_u16(overlay.toast_font_size);
2410                self.put_u16(overlay.toast_line_height);
2411                self.put_u16(0);
2412            }
2413            Mutation::SetClipboardText { text } => {
2414                self.begin_record(TAG_SET_CLIPBOARD_TEXT, 8);
2415                self.put_string_ref(text)?;
2416            }
2417            Mutation::ReadClipboard { request } => {
2418                self.begin_record(TAG_READ_CLIPBOARD, 4);
2419                self.put_u32(*request);
2420            }
2421            Mutation::StorageCall {
2422                request,
2423                op,
2424                store,
2425                key,
2426                data,
2427            } => {
2428                self.begin_record(TAG_STORAGE_CALL, STORAGE_CALL_PAYLOAD_LEN as u16);
2429                self.put_u32(*request);
2430                self.put_u16(u16::from(*op));
2431                self.put_u16(0);
2432                self.put_string_ref(store)?;
2433                self.put_string_ref(key)?;
2434                self.put_bytes_ref(data)?;
2435            }
2436            Mutation::FileCall {
2437                request,
2438                op,
2439                create,
2440                handle,
2441                name,
2442                data,
2443            } => {
2444                self.begin_record(TAG_FILE_CALL, FILE_CALL_PAYLOAD_LEN as u16);
2445                self.put_u32(*request);
2446                self.put_u16(*op as u16);
2447                self.put_u16(u16::from(*create));
2448                self.put_u32(*handle);
2449                self.put_string_ref(name)?;
2450                self.put_bytes_ref(data)?;
2451            }
2452            Mutation::ReleaseFileHandle { handle } => {
2453                self.begin_record(TAG_RELEASE_FILE_HANDLE, 4);
2454                self.put_u32(*handle);
2455            }
2456            Mutation::ScrollTo {
2457                node_id,
2458                item,
2459                flags,
2460                x_px,
2461                y_px,
2462            } => {
2463                self.begin_record(TAG_SCROLL_TO, (SCROLL_TO_LEN - 4) as u16);
2464                self.put_u32(*node_id);
2465                self.put_u32(*item);
2466                self.put_u32(*flags);
2467                self.put_u64(x_px.to_bits());
2468                self.put_u64(y_px.to_bits());
2469            }
2470            Mutation::SetSelections {
2471                node_id,
2472                base_version,
2473                selections,
2474            } => {
2475                self.begin_record(TAG_SET_SELECTIONS, (SET_SELECTIONS_LEN - 4) as u16);
2476                self.put_u32(*node_id);
2477                self.put_u32(*base_version);
2478                self.put_bytes_ref(selections)?;
2479            }
2480            Mutation::InsertSnippet {
2481                node_id,
2482                base_version,
2483                start_line,
2484                start_column,
2485                end_line,
2486                end_column,
2487                snippet,
2488            } => {
2489                self.begin_record(TAG_INSERT_SNIPPET, (INSERT_SNIPPET_LEN - 4) as u16);
2490                self.put_u32(*node_id);
2491                self.put_u32(*base_version);
2492                self.put_u32(*start_line);
2493                self.put_u32(*start_column);
2494                self.put_u32(*end_line);
2495                self.put_u32(*end_column);
2496                self.put_string_ref(snippet)?;
2497            }
2498            Mutation::QueryPositionRect {
2499                node_id,
2500                request,
2501                line,
2502                column,
2503            } => {
2504                self.begin_record(
2505                    TAG_QUERY_POSITION_RECT,
2506                    (QUERY_POSITION_RECT_LEN - 4) as u16,
2507                );
2508                self.put_u32(*node_id);
2509                self.put_u32(*request);
2510                self.put_u32(*line);
2511                self.put_u32(*column);
2512            }
2513            Mutation::ScrollIntoView {
2514                node_id,
2515                target,
2516                target_kind,
2517                align_x,
2518                align_y,
2519                flags,
2520                rect,
2521            } => {
2522                self.begin_record(TAG_SCROLL_INTO_VIEW, (SCROLL_INTO_VIEW_LEN - 4) as u16);
2523                self.put_u32(*node_id);
2524                self.put_u32(*target);
2525                self.put_u16(*target_kind);
2526                self.put_u16(*align_x);
2527                self.put_u16(*align_y);
2528                self.put_u16(*flags);
2529                self.put_u64(rect.x_px.to_bits());
2530                self.put_u64(rect.y_px.to_bits());
2531                self.put_u64(rect.width_px.to_bits());
2532                self.put_u64(rect.height_px.to_bits());
2533            }
2534            Mutation::AttachNativeView { node_id, handle } => {
2535                self.begin_record(TAG_ATTACH_NATIVE_VIEW, (ATTACH_NATIVE_VIEW_LEN - 4) as u16);
2536                self.put_u32(*node_id);
2537                self.put_u32(0);
2538                self.put_u32(0);
2539                self.put_u64(handle.0);
2540            }
2541            Mutation::FocusNativeView { node_id, focus } => {
2542                self.begin_record(TAG_FOCUS_NATIVE_VIEW, (FOCUS_NATIVE_VIEW_LEN - 4) as u16);
2543                self.put_u32(*node_id);
2544                self.put_u32(u32::from(*focus));
2545                self.put_u32(0);
2546            }
2547            Mutation::SetWindow(window) => {
2548                self.begin_record(TAG_SET_WINDOW, 28);
2549                self.put_u16(window.chrome as u16);
2550                self.put_u16(window.title_bar as u16);
2551                self.put_u16(window.width);
2552                self.put_u16(window.height);
2553                self.put_u16(window.min_width);
2554                self.put_u16(window.min_height);
2555                // Bit 0 is `resizable` and bit 1 asks for every whole-dp size change. The
2556                // mode and the last window policy ride in the bits above them that were
2557                // always zero, so a window that asks for none writes the bytes it always
2558                // wrote.
2559                self.put_u16(
2560                    u16::from(window.resizable)
2561                        | (u16::from(window.report_size) << 1)
2562                        | ((window.mode as u16) << WINDOW_MODE_SHIFT)
2563                        | ((window.last_window_closed as u16) << WINDOW_POLICY_SHIFT),
2564                );
2565                // The application's zoom level, in what used to be the padding that keeps
2566                // the record a multiple of four: a byte saying whether there is one, then
2567                // the level as a signed byte. Zero is "none", so a window that asks for
2568                // nothing reads exactly as it did before the level existed.
2569                self.put_u16(match window.zoom_level {
2570                    None => 0,
2571                    Some(level) => 1 | (u16::from(crate::zoom::clamp_level(level) as u8) << 8),
2572                });
2573                self.put_string_ref(window.title)?;
2574                self.put_u32(window.icon);
2575            }
2576            Mutation::PostNotification {
2577                key,
2578                title,
2579                body,
2580                channel,
2581                action_1,
2582                action_2,
2583                importance,
2584                presentation,
2585            } => {
2586                self.begin_record(TAG_POST_NOTIFICATION, 52);
2587                self.put_string_ref(key)?;
2588                self.put_string_ref(title)?;
2589                self.put_string_ref(body)?;
2590                self.put_string_ref(channel)?;
2591                self.put_string_ref(action_1)?;
2592                self.put_string_ref(action_2)?;
2593                self.put_u16(*importance as u16);
2594                self.put_u16(*presentation as u16);
2595            }
2596            Mutation::WithdrawNotification { key } => {
2597                self.begin_record(TAG_WITHDRAW_NOTIFICATION, 8);
2598                self.put_string_ref(key)?;
2599            }
2600            Mutation::RequestNotificationPermission => {
2601                self.begin_record(TAG_REQUEST_NOTIFICATION_PERMISSION, 0);
2602            }
2603            Mutation::StartAnimation(animation) => self.put_animation(animation)?,
2604            Mutation::ControlAnimation {
2605                node_id,
2606                animation_id,
2607                property,
2608                slot,
2609                op,
2610                at_time_nanos,
2611            } => {
2612                self.begin_record(TAG_CONTROL_ANIMATION, 20);
2613                self.put_u32(*node_id);
2614                self.put_u32(*animation_id);
2615                self.records.push(*property as u8);
2616                self.records.push(*slot);
2617                self.records.push(*op as u8);
2618                self.records.push(0);
2619                self.put_u64(*at_time_nanos);
2620            }
2621        }
2622        self.record_count = self
2623            .record_count
2624            .checked_add(1)
2625            .ok_or(ProtocolError::LengthOverflow)?;
2626        Ok(())
2627    }
2628
2629    pub fn finish(&mut self) -> Result<&[u8], ProtocolError> {
2630        let records_len =
2631            u32::try_from(self.records.len()).map_err(|_| ProtocolError::LengthOverflow)?;
2632        self.records[4..8].copy_from_slice(&records_len.to_le_bytes());
2633        self.records[8..12].copy_from_slice(&self.record_count.to_le_bytes());
2634        let total = self
2635            .records
2636            .len()
2637            .checked_add(self.strings.len())
2638            .ok_or(ProtocolError::LengthOverflow)?;
2639        self.arena.clear();
2640        if self.arena.capacity() < total {
2641            self.arena.reserve(total);
2642        }
2643        self.arena.extend_from_slice(&self.records);
2644        self.arena.extend_from_slice(&self.strings);
2645        for &position in &self.string_fixups {
2646            let relative = read_u32(&self.arena, position)?;
2647            let absolute = records_len
2648                .checked_add(relative)
2649                .ok_or(ProtocolError::LengthOverflow)?;
2650            self.arena[position..position + 4].copy_from_slice(&absolute.to_le_bytes());
2651        }
2652        Ok(&self.arena)
2653    }
2654
2655    /// Where the arena a finished batch lives in starts, and how much of it is mapped.
2656    ///
2657    /// A runtime that cannot read the Host's memory directly wraps this range once and
2658    /// keeps the view: every batch is a prefix of the arena, so it is read where it lies
2659    /// and no byte is copied out. Growing the arena moves it, which is why the address is
2660    /// reported again on every call rather than once at startup.
2661    pub fn arena(&self) -> (*const u8, usize) {
2662        (self.arena.as_ptr(), self.arena.capacity())
2663    }
2664
2665    pub fn capacity(&self) -> usize {
2666        self.records.capacity() + self.strings.capacity() + self.arena.capacity()
2667    }
2668
2669    /// Writes a `StartAnimation`: the 52 byte head, then each keyframe with its value.
2670    ///
2671    /// The bytes are written as they are given; whether they make an animation is the
2672    /// decoder's question, asked on both sides, so a Host that sends a bad one hears about
2673    /// it as a protocol error rather than not at all.
2674    fn put_animation(
2675        &mut self,
2676        animation: &crate::schema::Animation<'_>,
2677    ) -> Result<(), ProtocolError> {
2678        use crate::schema::{KeyframeValue, Timing};
2679        let keyframes_len: usize = animation
2680            .keyframes
2681            .iter()
2682            .map(|keyframe| {
2683                KEYFRAME_HEAD_LEN
2684                    + match &keyframe.value {
2685                        KeyframeValue::Alpha(_) => 4,
2686                        KeyframeValue::Paint(_) => 8,
2687                        KeyframeValue::Transform(functions) => {
2688                            4 + TRANSFORM_FUNCTION_LEN * functions.len()
2689                        }
2690                    }
2691            })
2692            .sum();
2693        let payload = u16::try_from(ANIMATION_HEADER_LEN - 4 + keyframes_len)
2694            .ok()
2695            .filter(|payload| *payload <= u16::MAX - 4)
2696            .ok_or(ProtocolError::LengthOverflow)?;
2697        let keyframe_count =
2698            u16::try_from(animation.keyframes.len()).map_err(|_| ProtocolError::LengthOverflow)?;
2699        self.begin_record(TAG_START_ANIMATION, payload);
2700        self.put_u32(animation.node_id);
2701        self.put_u32(animation.animation_id);
2702        self.records.push(animation.property as u8);
2703        self.records.push(animation.slot);
2704        self.records.push(animation.direction as u8);
2705        self.records.push(animation.fill as u8);
2706        self.records.push(animation.play_state as u8);
2707        self.records
2708            .push(animation.interpolation.map_or(0, |value| value as u8));
2709        self.put_u16(keyframe_count);
2710        self.put_u64(animation.start_time_nanos);
2711        self.put_u32(animation.delay_ms.to_bits());
2712        self.put_u32(animation.duration_ms.to_bits());
2713        self.put_u32(animation.iterations.to_bits());
2714        self.put_u32(animation.origin_x.to_bits());
2715        self.put_u32(animation.origin_y.to_bits());
2716        self.records.push(animation.events.0);
2717        self.records.extend_from_slice(&[0, 0, 0]);
2718        for keyframe in animation.keyframes.iter() {
2719            self.put_u32(keyframe.offset.to_bits());
2720            let (kind, position, numbers) = match keyframe.timing {
2721                Timing::Linear => (1_u8, 0_u8, [0_u32; 4]),
2722                Timing::CubicBezier { x1, y1, x2, y2 } => (
2723                    2,
2724                    0,
2725                    [x1.to_bits(), y1.to_bits(), x2.to_bits(), y2.to_bits()],
2726                ),
2727                Timing::Steps { count, position } => (3, position as u8, [count, 0, 0, 0]),
2728            };
2729            self.records.push(kind);
2730            self.records.push(position);
2731            self.put_u16(if keyframe.from_presented {
2732                KEYFRAME_FROM_PRESENTED
2733            } else {
2734                0
2735            });
2736            for number in numbers {
2737                self.put_u32(number);
2738            }
2739            match &keyframe.value {
2740                KeyframeValue::Alpha(value) => self.put_u32(value.to_bits()),
2741                KeyframeValue::Paint(paint) => self.put_u64(paint.to_bits()),
2742                KeyframeValue::Transform(functions) => {
2743                    let count = u16::try_from(functions.len())
2744                        .map_err(|_| ProtocolError::LengthOverflow)?;
2745                    self.put_u16(count);
2746                    self.put_u16(0);
2747                    for function in functions.iter() {
2748                        self.put_u32(u32::from(u16::from(function.kind)));
2749                        for value in function.values {
2750                            self.put_u32(value.to_bits());
2751                        }
2752                    }
2753                }
2754            }
2755        }
2756        Ok(())
2757    }
2758
2759    /// The body of a `SetTheme`, which `SetWindowTheme` carries after its node id.
2760    fn put_theme(&mut self, theme: &Theme) -> Result<(), ProtocolError> {
2761        self.put_u16(theme.design_system as u16);
2762        self.put_u16(theme.fallback as u16);
2763        self.put_u16(theme.color_scheme as u16);
2764        self.put_u16(u16::from(theme.adaptive));
2765        // One slot per type role, zero where the role keeps the system font. Sent
2766        // whether or not any of them is filled, because the record is fixed
2767        // layout and a theme change is one record rather than a per frame cost.
2768        for asset in theme.fonts {
2769            self.put_u32(asset);
2770        }
2771        // The application's colours, as a run of eight byte entries behind the
2772        // records the way a string is. Zero long where there is no palette, so a
2773        // theme without one costs the eight bytes of the reference and nothing
2774        // else.
2775        self.put_palette_ref(theme.palette)
2776    }
2777
2778    fn begin_record(&mut self, tag: u16, payload_len: u16) {
2779        self.put_u16(tag);
2780        self.put_u16(payload_len + 4);
2781    }
2782
2783    /// Writes a palette's entries straight into the trailing region, so encoding a theme
2784    /// allocates nothing beyond what that region already has.
2785    fn put_palette_ref(
2786        &mut self,
2787        palette: Option<&crate::palette::Palette>,
2788    ) -> Result<(), ProtocolError> {
2789        let start = self.strings.len();
2790        let offset = u32::try_from(start).map_err(|_| ProtocolError::LengthOverflow)?;
2791        if let Some(palette) = palette {
2792            palette.write_into(&mut self.strings);
2793        }
2794        let len =
2795            u32::try_from(self.strings.len() - start).map_err(|_| ProtocolError::LengthOverflow)?;
2796        self.string_fixups.push(self.records.len());
2797        self.put_u32(offset);
2798        self.put_u32(len);
2799        Ok(())
2800    }
2801
2802    fn put_string_ref(&mut self, value: &str) -> Result<(), ProtocolError> {
2803        self.put_bytes_ref(value.as_bytes())
2804    }
2805
2806    /// Asset bytes ride in the same trailing region as strings, with the same
2807    /// `(offset, len)` reference and the same fixup, so the record stays fixed layout.
2808    fn put_bytes_ref(&mut self, value: &[u8]) -> Result<(), ProtocolError> {
2809        let offset =
2810            u32::try_from(self.strings.len()).map_err(|_| ProtocolError::LengthOverflow)?;
2811        let len = u32::try_from(value.len()).map_err(|_| ProtocolError::LengthOverflow)?;
2812        self.string_fixups.push(self.records.len());
2813        self.put_u32(offset);
2814        self.put_u32(len);
2815        self.strings.extend_from_slice(value);
2816        Ok(())
2817    }
2818
2819    fn put_u16(&mut self, value: u16) {
2820        self.records.extend_from_slice(&value.to_le_bytes());
2821    }
2822
2823    fn put_u32(&mut self, value: u32) {
2824        self.records.extend_from_slice(&value.to_le_bytes());
2825    }
2826
2827    fn put_u64(&mut self, value: u64) {
2828        self.records.extend_from_slice(&value.to_le_bytes());
2829    }
2830}
2831
2832/// Reads the body of a `SetTheme` that starts at `payload`, which `SetWindowTheme` also
2833/// carries, after its node id.
2834fn decode_theme(bytes: &[u8], payload: usize, records_len: usize) -> Result<Theme, ProtocolError> {
2835    let design_system = read_u16(bytes, payload)?;
2836    let fallback = read_u16(bytes, payload + 2)?;
2837    let color_scheme = read_u16(bytes, payload + 4)?;
2838    let adaptive = read_u16(bytes, payload + 6)?;
2839    if adaptive > 1 {
2840        return Err(ProtocolError::InvalidTheme(adaptive));
2841    }
2842    let mut fonts = [0u32; TYPE_ROLE_COUNT];
2843    for (index, slot) in fonts.iter_mut().enumerate() {
2844        *slot = read_u32(bytes, payload + 8 + 4 * index)?;
2845    }
2846    // Entries that are wrong are left out and the rest stand, which is what
2847    // the Renderer does with them as well. Leaked like the window's title: a
2848    // theme holds its palette for the life of the program, and this decoder
2849    // is what tests and the mock renderer read a batch back with.
2850    let palette_bytes = read_bytes(bytes, payload + 8 + 4 * TYPE_ROLE_COUNT, records_len)?;
2851    let palette = if palette_bytes.is_empty() {
2852        None
2853    } else {
2854        let (palette, _problems) = crate::palette::decode_palette(palette_bytes);
2855        Some(&*Box::leak(Box::new(palette)))
2856    };
2857    Ok(Theme {
2858        design_system: DesignSystem::try_from(design_system)
2859            .map_err(|()| ProtocolError::InvalidTheme(design_system))?,
2860        fallback: DesignSystem::try_from(fallback)
2861            .map_err(|()| ProtocolError::InvalidTheme(fallback))?,
2862        color_scheme: ColorScheme::try_from(color_scheme)
2863            .map_err(|()| ProtocolError::InvalidTheme(color_scheme))?,
2864        adaptive: adaptive == 1,
2865        fonts,
2866        palette,
2867        overlay: None,
2868    })
2869}
2870
2871pub fn decode_batch(bytes: &[u8]) -> Result<Vec<Mutation<'_>>, ProtocolError> {
2872    if bytes.len() < ENVELOPE_LEN
2873        || read_u16(bytes, 0)? != TAG_ENVELOPE
2874        || read_u16(bytes, 2)? != 12
2875    {
2876        return Err(ProtocolError::InvalidEnvelope);
2877    }
2878    let records_len =
2879        usize::try_from(read_u32(bytes, 4)?).map_err(|_| ProtocolError::LengthOverflow)?;
2880    let count = usize::try_from(read_u32(bytes, 8)?).map_err(|_| ProtocolError::LengthOverflow)?;
2881    if records_len < ENVELOPE_LEN || records_len > bytes.len() || records_len % 4 != 0 {
2882        return Err(ProtocolError::InvalidEnvelope);
2883    }
2884    // `count` is attacker-controlled, so it only sizes the buffer up to what the
2885    // record region could actually hold. The shortest mutation record is a bare header at
2886    // 4 bytes, so that is the ceiling. Reserving `count` directly let a 12-byte message ask
2887    // for a >100 GB allocation.
2888    let capacity = count.min((records_len - ENVELOPE_LEN) / MIN_RECORD_LEN);
2889    let mut output = Vec::with_capacity(capacity);
2890    let mut position = ENVELOPE_LEN;
2891    while position < records_len {
2892        let tag = read_u16(bytes, position)?;
2893        let len = usize::from(read_u16(bytes, position + 2)?);
2894        if len < 4 || len % 4 != 0 || position + len > records_len {
2895            return Err(ProtocolError::InvalidRecordLength);
2896        }
2897        let payload = position + 4;
2898        let mutation = match tag {
2899            TAG_CREATE if len == 12 => Mutation::Create {
2900                node_id: read_u32(bytes, payload)?,
2901                widget: WidgetKind::try_from(read_u16(bytes, payload + 4)?).map_err(|()| {
2902                    ProtocolError::InvalidWidget(read_u16(bytes, payload + 4).unwrap_or(0))
2903                })?,
2904            },
2905            TAG_SET_PROP if len == 24 => {
2906                let property_raw = read_u16(bytes, payload + 4)?;
2907                let value_kind = read_u16(bytes, payload + 6)?;
2908                let value = match value_kind {
2909                    VALUE_NONE => PropertyValue::None,
2910                    VALUE_STRING => {
2911                        PropertyValue::String(read_string(bytes, payload + 8, records_len)?)
2912                    }
2913                    VALUE_BOOL => PropertyValue::Bool(read_u64(bytes, payload + 8)? != 0),
2914                    VALUE_I64 => PropertyValue::Integer(read_u64(bytes, payload + 8)? as i64),
2915                    VALUE_F32 => {
2916                        PropertyValue::Float(f32::from_bits(read_u64(bytes, payload + 8)? as u32))
2917                    }
2918                    VALUE_BYTES => {
2919                        PropertyValue::Bytes(read_bytes(bytes, payload + 8, records_len)?)
2920                    }
2921                    other => return Err(ProtocolError::InvalidValueKind(other)),
2922                };
2923                Mutation::SetProp {
2924                    node_id: read_u32(bytes, payload)?,
2925                    property: PropertyKind::try_from(property_raw)
2926                        .map_err(|()| ProtocolError::InvalidProperty(property_raw))?,
2927                    value,
2928                }
2929            }
2930            TAG_SET_MODIFIER if len >= 28 => {
2931                // The modifier's tag says how long its record is: 28 bytes and eight more
2932                // for each word the schema gives it beyond the first two. A record of any
2933                // other length is refused before its value is read.
2934                let modifier_tag = read_u16(bytes, payload + 6)?;
2935                let extra = usize::from(
2936                    modifier_extra_words(modifier_tag)
2937                        .ok_or(ProtocolError::InvalidModifier(modifier_tag))?,
2938                );
2939                if len != 28 + 8 * extra {
2940                    return Err(ProtocolError::InvalidRecordLength);
2941                }
2942                let mut words = [0_u64; MAX_MODIFIER_WORDS];
2943                for (word_index, word) in words.iter_mut().take(2 + extra).enumerate() {
2944                    *word = read_u64(bytes, payload + 8 + 8 * word_index)?;
2945                }
2946                Mutation::SetModifier {
2947                    node_id: read_u32(bytes, payload)?,
2948                    index: read_u16(bytes, payload + 4)?,
2949                    modifier: decode_modifier(modifier_tag, &words)?,
2950                }
2951            }
2952            TAG_INSERT if len == 16 => Mutation::Insert {
2953                parent_id: read_u32(bytes, payload)?,
2954                node_id: read_u32(bytes, payload + 4)?,
2955                index: read_u32(bytes, payload + 8)?,
2956            },
2957            TAG_MOVE if len == 16 => Mutation::Move {
2958                parent_id: read_u32(bytes, payload)?,
2959                node_id: read_u32(bytes, payload + 4)?,
2960                index: read_u32(bytes, payload + 8)?,
2961            },
2962            TAG_REMOVE if len == 8 => Mutation::Remove {
2963                node_id: read_u32(bytes, payload)?,
2964            },
2965            TAG_SET_TEXT if len == 24 => {
2966                let start = read_u32(bytes, payload + 12)?;
2967                let end = read_u32(bytes, payload + 16)?;
2968                Mutation::SetText {
2969                    node_id: read_u32(bytes, payload)?,
2970                    text: read_string(bytes, payload + 4, records_len)?,
2971                    selection: (start != u32::MAX || end != u32::MAX)
2972                        .then_some(Selection { start, end }),
2973                }
2974            }
2975            TAG_APPEND_TEXT if len == 16 => Mutation::AppendText {
2976                node_id: read_u32(bytes, payload)?,
2977                text: read_string(bytes, payload + 4, records_len)?,
2978            },
2979            TAG_SET_THEME if len == 4 + THEME_PAYLOAD_LEN => {
2980                Mutation::SetTheme(decode_theme(bytes, payload, records_len)?)
2981            }
2982            TAG_SET_WINDOW_THEME if len == 8 + THEME_PAYLOAD_LEN => Mutation::SetWindowTheme {
2983                node_id: read_u32(bytes, payload)?,
2984                theme: decode_theme(bytes, payload + 4, records_len)?,
2985            },
2986            TAG_FOCUS_WINDOW if len == 8 => Mutation::FocusWindow {
2987                node_id: read_u32(bytes, payload)?,
2988            },
2989            TAG_REQUEST_FOCUS if len == 8 => Mutation::RequestFocus {
2990                node_id: read_u32(bytes, payload)?,
2991            },
2992            TAG_SHOW_FILE_DIALOG if len == 4 + SHOW_FILE_DIALOG_PAYLOAD_LEN => {
2993                let raw_kind = read_u16(bytes, payload + 8)?;
2994                Mutation::ShowFileDialog {
2995                    request: read_u32(bytes, payload)?,
2996                    window: read_u32(bytes, payload + 4)?,
2997                    kind: FileDialogKind::try_from(raw_kind)
2998                        .map_err(|()| ProtocolError::InvalidValueKind(raw_kind))?,
2999                    default_filter: read_u16(bytes, payload + 10)?,
3000                    title: read_string(bytes, payload + 12, records_len)?,
3001                    directory: read_string(bytes, payload + 20, records_len)?,
3002                    name: read_string(bytes, payload + 28, records_len)?,
3003                    filters: read_string(bytes, payload + 36, records_len)?,
3004                }
3005            }
3006            TAG_SHOW_FILE_DIALOG => return Err(ProtocolError::InvalidRecordLength),
3007            TAG_SET_OVERLAY_TOKENS if len == 4 + OVERLAY_TOKENS_PAYLOAD_LEN => {
3008                let sheet_corner_radius = read_u16(bytes, payload)?;
3009                let dialog_corner_radius = read_u16(bytes, payload + 2)?;
3010                let popup_corner_radius = read_u16(bytes, payload + 4)?;
3011                let sheet_elevation = read_u16(bytes, payload + 6)?;
3012                let popup_elevation = read_u16(bytes, payload + 8)?;
3013                let dialog_elevation = read_u16(bytes, payload + 10)?;
3014                let sheet_padding = read_u16(bytes, payload + 12)?;
3015                let dialog_padding = read_u16(bytes, payload + 14)?;
3016                let popup_padding = read_u16(bytes, payload + 16)?;
3017                let scrim = read_u32(bytes, payload + 20)?;
3018                let toast_elevation = read_u16(bytes, payload + 24)?;
3019                let toast_corner_radius = read_u16(bytes, payload + 26)?;
3020                let border = read_u16(bytes, payload + 44)?;
3021                Mutation::SetOverlayTokens(crate::schema::OverlayTokens {
3022                    sheet_corner_radius,
3023                    dialog_corner_radius,
3024                    popup_corner_radius,
3025                    sheet_elevation,
3026                    popup_elevation,
3027                    dialog_elevation,
3028                    sheet_padding,
3029                    dialog_padding,
3030                    popup_padding,
3031                    scrim,
3032                    toast_elevation,
3033                    toast_corner_radius,
3034                    toast_container_light: read_u32(bytes, payload + 28)?,
3035                    toast_container_dark: read_u32(bytes, payload + 32)?,
3036                    toast_content_light: read_u32(bytes, payload + 36)?,
3037                    toast_content_dark: read_u32(bytes, payload + 40)?,
3038                    toast_border_width: (border != TOAST_BORDER_DESIGN_SYSTEM).then_some(border),
3039                    toast_padding_horizontal: read_u16(bytes, payload + 46)?,
3040                    toast_padding_vertical: read_u16(bytes, payload + 48)?,
3041                    toast_font_size: read_u16(bytes, payload + 50)?,
3042                    toast_line_height: read_u16(bytes, payload + 52)?,
3043                })
3044            }
3045            TAG_SET_OVERLAY_TOKENS => return Err(ProtocolError::InvalidRecordLength),
3046            TAG_SET_CLIPBOARD_TEXT if len == 12 => Mutation::SetClipboardText {
3047                text: read_string(bytes, payload, records_len)?,
3048            },
3049            TAG_READ_CLIPBOARD if len == 8 => Mutation::ReadClipboard {
3050                request: read_u32(bytes, payload)?,
3051            },
3052            TAG_STORAGE_CALL if len == 4 + STORAGE_CALL_PAYLOAD_LEN => {
3053                let raw_op = read_u16(bytes, payload + 4)?;
3054                Mutation::StorageCall {
3055                    request: read_u32(bytes, payload)?,
3056                    op: crate::schema::StorageOp::try_from(raw_op)
3057                        .map_err(|()| ProtocolError::InvalidValueKind(raw_op))?,
3058                    store: read_string(bytes, payload + 8, records_len)?,
3059                    key: read_string(bytes, payload + 16, records_len)?,
3060                    data: read_bytes(bytes, payload + 24, records_len)?,
3061                }
3062            }
3063            TAG_FILE_CALL if len == 4 + FILE_CALL_PAYLOAD_LEN => {
3064                let raw_op = read_u16(bytes, payload + 4)?;
3065                let raw_create = read_u16(bytes, payload + 6)?;
3066                if raw_create > 1 {
3067                    return Err(ProtocolError::InvalidValueKind(raw_create));
3068                }
3069                Mutation::FileCall {
3070                    request: read_u32(bytes, payload)?,
3071                    op: FileOp::try_from(raw_op)
3072                        .map_err(|()| ProtocolError::InvalidValueKind(raw_op))?,
3073                    create: raw_create == 1,
3074                    handle: read_u32(bytes, payload + 8)?,
3075                    name: read_string(bytes, payload + 12, records_len)?,
3076                    data: read_bytes(bytes, payload + 20, records_len)?,
3077                }
3078            }
3079            TAG_RELEASE_FILE_HANDLE if len == 8 => Mutation::ReleaseFileHandle {
3080                handle: read_u32(bytes, payload)?,
3081            },
3082            TAG_SCROLL_TO if len == SCROLL_TO_LEN => Mutation::ScrollTo {
3083                node_id: read_u32(bytes, payload)?,
3084                item: read_u32(bytes, payload + 4)?,
3085                flags: read_u32(bytes, payload + 8)?,
3086                x_px: f64::from_bits(read_u64(bytes, payload + 12)?),
3087                y_px: f64::from_bits(read_u64(bytes, payload + 20)?),
3088            },
3089            TAG_SCROLL_INTO_VIEW if len == SCROLL_INTO_VIEW_LEN => Mutation::ScrollIntoView {
3090                node_id: read_u32(bytes, payload)?,
3091                target: read_u32(bytes, payload + 4)?,
3092                target_kind: read_u16(bytes, payload + 8)?,
3093                align_x: read_u16(bytes, payload + 10)?,
3094                align_y: read_u16(bytes, payload + 12)?,
3095                flags: read_u16(bytes, payload + 14)?,
3096                rect: crate::schema::Rect {
3097                    x_px: f64::from_bits(read_u64(bytes, payload + 16)?),
3098                    y_px: f64::from_bits(read_u64(bytes, payload + 24)?),
3099                    width_px: f64::from_bits(read_u64(bytes, payload + 32)?),
3100                    height_px: f64::from_bits(read_u64(bytes, payload + 40)?),
3101                },
3102            },
3103            TAG_ATTACH_NATIVE_VIEW if len == ATTACH_NATIVE_VIEW_LEN => {
3104                require_zero_word(bytes, payload + 4)?;
3105                require_zero_word(bytes, payload + 8)?;
3106                Mutation::AttachNativeView {
3107                    node_id: read_u32(bytes, payload)?,
3108                    handle: crate::schema::NativeHandle(read_u64(bytes, payload + 12)?),
3109                }
3110            }
3111            TAG_FOCUS_NATIVE_VIEW if len == FOCUS_NATIVE_VIEW_LEN => {
3112                require_zero_word(bytes, payload + 8)?;
3113                Mutation::FocusNativeView {
3114                    node_id: read_u32(bytes, payload)?,
3115                    focus: read_flag(bytes, payload + 4)?,
3116                }
3117            }
3118            TAG_SET_WINDOW if len == 32 => {
3119                let chrome = read_u16(bytes, payload)?;
3120                let title_bar = read_u16(bytes, payload + 2)?;
3121                // Bit 0 is `resizable`; the mode and the last window policy are the
3122                // nibbles above the second byte. Anything else standing is a record the
3123                // sides disagree on.
3124                let flags = read_u16(bytes, payload + 12)?;
3125                if flags & 0x00FC != 0 {
3126                    return Err(ProtocolError::InvalidValueKind(flags));
3127                }
3128                let resizable = flags & 1;
3129                let report_size = flags & 0x0002 != 0;
3130                let mode_tag = (flags >> WINDOW_MODE_SHIFT) & 0xF;
3131                let policy_tag = flags >> WINDOW_POLICY_SHIFT;
3132                let zoom = read_u16(bytes, payload + 14)?;
3133                let zoom_level = match zoom & 0xFF {
3134                    0 => None,
3135                    1 => {
3136                        let level = (zoom >> 8) as u8 as i8;
3137                        if !(crate::zoom::MIN_ZOOM_LEVEL..=crate::zoom::MAX_ZOOM_LEVEL)
3138                            .contains(&level)
3139                        {
3140                            return Err(ProtocolError::InvalidValueKind(zoom));
3141                        }
3142                        Some(level)
3143                    }
3144                    _ => return Err(ProtocolError::InvalidValueKind(zoom)),
3145                };
3146                Mutation::SetWindow(crate::schema::Window {
3147                    chrome: crate::schema::Chrome::try_from(chrome)
3148                        .map_err(|()| ProtocolError::InvalidValueKind(chrome))?,
3149                    title_bar: crate::schema::TitleBar::try_from(title_bar)
3150                        .map_err(|()| ProtocolError::InvalidValueKind(title_bar))?,
3151                    width: read_u16(bytes, payload + 4)?,
3152                    height: read_u16(bytes, payload + 6)?,
3153                    min_width: read_u16(bytes, payload + 8)?,
3154                    min_height: read_u16(bytes, payload + 10)?,
3155                    resizable: resizable == 1,
3156                    zoom_level,
3157                    report_size,
3158                    mode: crate::schema::WindowMode::try_from(mode_tag)
3159                        .map_err(|()| ProtocolError::InvalidValueKind(flags))?,
3160                    last_window_closed: crate::schema::LastWindowClosed::try_from(policy_tag)
3161                        .map_err(|()| ProtocolError::InvalidValueKind(flags))?,
3162                    // Leaked on purpose, once per window. The record's owner is the
3163                    // window, the window outlives the batch it arrived in, and there is
3164                    // one of these per process.
3165                    icon: read_u32(bytes, payload + 24)?,
3166                    title: Box::leak(
3167                        read_string(bytes, payload + 16, records_len)?
3168                            .to_owned()
3169                            .into_boxed_str(),
3170                    ),
3171                })
3172            }
3173            TAG_REGISTER_ASSET if len == 20 => {
3174                let raw_kind = read_u16(bytes, payload + 4)?;
3175                Mutation::RegisterAsset {
3176                    asset_id: read_u32(bytes, payload)?,
3177                    kind: AssetKind::try_from(raw_kind)
3178                        .map_err(|()| ProtocolError::InvalidAssetKind(raw_kind))?,
3179                    bytes: read_bytes(bytes, payload + 8, records_len)?,
3180                }
3181            }
3182            TAG_RELEASE_ASSET if len == 8 => Mutation::ReleaseAsset {
3183                asset_id: read_u32(bytes, payload)?,
3184            },
3185            TAG_SHOW_MESSAGE if len == 40 => {
3186                let raw_duration = read_u16(bytes, payload + 24)?;
3187                let raw_vertical = read_u16(bytes, payload + 26)?;
3188                let raw_horizontal = read_u16(bytes, payload + 28)?;
3189                let placement = match (raw_vertical, raw_horizontal) {
3190                    (0, 0) => None,
3191                    (0, raw) | (raw, 0) => {
3192                        return Err(ProtocolError::InvalidMessagePlacement(raw));
3193                    }
3194                    (vertical, horizontal) => Some(MessagePlacement {
3195                        vertical: MessageVertical::try_from(vertical)
3196                            .map_err(|()| ProtocolError::InvalidMessagePlacement(vertical))?,
3197                        horizontal: MessageHorizontal::try_from(horizontal)
3198                            .map_err(|()| ProtocolError::InvalidMessagePlacement(horizontal))?,
3199                    }),
3200                };
3201                let offset = f32::from_bits(read_u32(bytes, payload + 32)?);
3202                Mutation::ShowMessage {
3203                    handler_id: read_u64(bytes, payload)?,
3204                    text: read_string(bytes, payload + 8, records_len)?,
3205                    action: read_string(bytes, payload + 16, records_len)?,
3206                    duration: MessageDuration::try_from(raw_duration)
3207                        .map_err(|()| ProtocolError::InvalidMessageDuration(raw_duration))?,
3208                    placement,
3209                    offset_dp: (!offset.is_nan()).then_some(offset),
3210                }
3211            }
3212            TAG_EDIT_CODE if len == 40 => Mutation::EditCode {
3213                node_id: read_u32(bytes, payload)?,
3214                request_id: read_u32(bytes, payload + 4)?,
3215                base_version: read_u32(bytes, payload + 8)?,
3216                start_line: read_u32(bytes, payload + 12)?,
3217                start_column: read_u32(bytes, payload + 16)?,
3218                end_line: read_u32(bytes, payload + 20)?,
3219                end_column: read_u32(bytes, payload + 24)?,
3220                text: read_string(bytes, payload + 28, records_len)?,
3221            },
3222            TAG_POST_NOTIFICATION if len == 56 => {
3223                let raw_importance = read_u16(bytes, payload + 48)?;
3224                let raw_presentation = read_u16(bytes, payload + 50)?;
3225                Mutation::PostNotification {
3226                    key: read_string(bytes, payload, records_len)?,
3227                    title: read_string(bytes, payload + 8, records_len)?,
3228                    body: read_string(bytes, payload + 16, records_len)?,
3229                    channel: read_string(bytes, payload + 24, records_len)?,
3230                    action_1: read_string(bytes, payload + 32, records_len)?,
3231                    action_2: read_string(bytes, payload + 40, records_len)?,
3232                    importance: NotificationImportance::try_from(raw_importance)
3233                        .map_err(|()| ProtocolError::InvalidNotification(raw_importance))?,
3234                    presentation: NotificationPresentation::try_from(raw_presentation)
3235                        .map_err(|()| ProtocolError::InvalidNotification(raw_presentation))?,
3236                }
3237            }
3238            TAG_WITHDRAW_NOTIFICATION if len == 12 => Mutation::WithdrawNotification {
3239                key: read_string(bytes, payload, records_len)?,
3240            },
3241            TAG_REQUEST_NOTIFICATION_PERMISSION if len == 4 => {
3242                Mutation::RequestNotificationPermission
3243            }
3244            TAG_START_ANIMATION if len >= ANIMATION_HEADER_LEN => {
3245                // A keyframe that runs past the end of its record is a count that does not
3246                // match the length, which is the record being wrong rather than the batch.
3247                Mutation::StartAnimation(
3248                    decode_animation(&bytes[position..position + len]).map_err(|error| {
3249                        if error == ProtocolError::Truncated {
3250                            ProtocolError::InvalidAnimation
3251                        } else {
3252                            error
3253                        }
3254                    })?,
3255                )
3256            }
3257            TAG_CONTROL_ANIMATION if len == 24 => {
3258                let raw_property = u16::from(read_u8(bytes, payload + 8)?);
3259                let raw_op = u16::from(read_u8(bytes, payload + 10)?);
3260                Mutation::ControlAnimation {
3261                    node_id: read_u32(bytes, payload)?,
3262                    animation_id: read_u32(bytes, payload + 4)?,
3263                    property: crate::schema::AnimatedProperty::try_from(raw_property)
3264                        .map_err(|()| ProtocolError::InvalidAnimation)?,
3265                    slot: read_u8(bytes, payload + 9)?,
3266                    op: crate::schema::AnimationControl::try_from(raw_op)
3267                        .map_err(|()| ProtocolError::InvalidAnimation)?,
3268                    at_time_nanos: read_u64(bytes, payload + 12)?,
3269                }
3270            }
3271            TAG_SET_SELECTION if len == 28 => Mutation::SetSelection {
3272                node_id: read_u32(bytes, payload)?,
3273                base_version: read_u32(bytes, payload + 4)?,
3274                anchor_line: read_u32(bytes, payload + 8)?,
3275                anchor_column: read_u32(bytes, payload + 12)?,
3276                active_line: read_u32(bytes, payload + 16)?,
3277                active_column: read_u32(bytes, payload + 20)?,
3278            },
3279            TAG_REVEAL_RANGE if len == 32 => {
3280                let raw_align = read_u32(bytes, payload + 24)?;
3281                Mutation::RevealRange {
3282                    node_id: read_u32(bytes, payload)?,
3283                    base_version: read_u32(bytes, payload + 4)?,
3284                    start_line: read_u32(bytes, payload + 8)?,
3285                    start_column: read_u32(bytes, payload + 12)?,
3286                    end_line: read_u32(bytes, payload + 16)?,
3287                    end_column: read_u32(bytes, payload + 20)?,
3288                    align: u16::try_from(raw_align)
3289                        .ok()
3290                        .and_then(|tag| crate::schema::RevealAlign::try_from(tag).ok())
3291                        .ok_or(ProtocolError::InvalidValueKind(
3292                            raw_align.min(u32::from(u16::MAX)) as u16,
3293                        ))?,
3294                }
3295            }
3296            TAG_SET_FOLDED if len == 16 => Mutation::SetFolded {
3297                node_id: read_u32(bytes, payload)?,
3298                start_line: read_u32(bytes, payload + 4)?,
3299                collapsed: read_flag(bytes, payload + 8)?,
3300            },
3301            TAG_SET_SCROLL_OFFSET if len == 16 => Mutation::SetScrollOffset {
3302                node_id: read_u32(bytes, payload)?,
3303                offset_px: f64::from_bits(read_u64(bytes, payload + 4)?),
3304            },
3305            TAG_SET_SCROLL_OFFSET => return Err(ProtocolError::InvalidRecordLength),
3306            TAG_QUERY_POSITION_RECT if len == QUERY_POSITION_RECT_LEN => {
3307                Mutation::QueryPositionRect {
3308                    node_id: read_u32(bytes, payload)?,
3309                    request: read_u32(bytes, payload + 4)?,
3310                    line: read_u32(bytes, payload + 8)?,
3311                    column: read_u32(bytes, payload + 12)?,
3312                }
3313            }
3314            TAG_QUERY_POSITION_RECT => return Err(ProtocolError::InvalidRecordLength),
3315            TAG_INSERT_SNIPPET if len == INSERT_SNIPPET_LEN => Mutation::InsertSnippet {
3316                node_id: read_u32(bytes, payload)?,
3317                base_version: read_u32(bytes, payload + 4)?,
3318                start_line: read_u32(bytes, payload + 8)?,
3319                start_column: read_u32(bytes, payload + 12)?,
3320                end_line: read_u32(bytes, payload + 16)?,
3321                end_column: read_u32(bytes, payload + 20)?,
3322                snippet: read_string(bytes, payload + 24, records_len)?,
3323            },
3324            TAG_INSERT_SNIPPET => return Err(ProtocolError::InvalidRecordLength),
3325            TAG_SET_SELECTIONS if len == SET_SELECTIONS_LEN => Mutation::SetSelections {
3326                node_id: read_u32(bytes, payload)?,
3327                base_version: read_u32(bytes, payload + 4)?,
3328                selections: read_bytes(bytes, payload + 8, records_len)?,
3329            },
3330            TAG_SET_SELECTIONS => return Err(ProtocolError::InvalidRecordLength),
3331            TAG_EDIT_CODE_GROUP if len == EDIT_CODE_GROUP_LEN => Mutation::EditCodeGroup {
3332                node_id: read_u32(bytes, payload)?,
3333                request_id: read_u32(bytes, payload + 4)?,
3334                base_version: read_u32(bytes, payload + 8)?,
3335                edits: read_bytes(bytes, payload + 12, records_len)?,
3336            },
3337            TAG_CREATE..=TAG_EDIT_CODE
3338            | TAG_START_ANIMATION
3339            | TAG_CONTROL_ANIMATION
3340            | TAG_SET_SELECTION..=TAG_SET_FOLDED
3341            | TAG_SET_WINDOW_THEME..=TAG_SET_CLIPBOARD_TEXT
3342            | TAG_READ_CLIPBOARD
3343            | TAG_STORAGE_CALL
3344            | TAG_FILE_CALL
3345            | TAG_RELEASE_FILE_HANDLE
3346            | TAG_SCROLL_TO
3347            | TAG_SCROLL_INTO_VIEW
3348            | TAG_ATTACH_NATIVE_VIEW
3349            | TAG_FOCUS_NATIVE_VIEW => {
3350                return Err(ProtocolError::InvalidRecordLength);
3351            }
3352            other => return Err(ProtocolError::InvalidTag(other)),
3353        };
3354        output.push(mutation);
3355        position += len;
3356    }
3357    if output.len() != count {
3358        return Err(ProtocolError::InvalidEnvelope);
3359    }
3360    Ok(output)
3361}
3362
3363/// Reads one `StartAnimation` record, given whole, and refuses anything that is not an
3364/// animation the Renderer could play. The Renderer asks the same questions of the same
3365/// bytes, so a record one side refuses is refused on the other as well.
3366fn decode_animation(record: &[u8]) -> Result<crate::schema::Animation<'static>, ProtocolError> {
3367    use crate::schema::{
3368        AnimatedProperty, Animation, AnimationEvents, ColorInterpolation, FillMode, Keyframe,
3369        KeyframeValue, PlayState, PlaybackDirection, StepPosition, Timing, TransformFunction,
3370        TransformFunctionKind,
3371    };
3372    let bad = ProtocolError::InvalidAnimation;
3373    fn byte_enum<T: TryFrom<u16, Error = ()>>(
3374        record: &[u8],
3375        at: usize,
3376    ) -> Result<T, ProtocolError> {
3377        T::try_from(u16::from(read_u8(record, at)?)).map_err(|()| ProtocolError::InvalidAnimation)
3378    }
3379    let float = |at: usize| read_u32(record, at).map(f32::from_bits);
3380    let property: AnimatedProperty = byte_enum(record, 12)?;
3381    let direction: PlaybackDirection = byte_enum(record, 14)?;
3382    let fill: FillMode = byte_enum(record, 15)?;
3383    let play_state: PlayState = byte_enum(record, 16)?;
3384    let colour = matches!(
3385        property,
3386        AnimatedProperty::Color | AnimatedProperty::Background | AnimatedProperty::BorderColor
3387    );
3388    let interpolation = match (colour, read_u8(record, 17)?) {
3389        (false, 0) => None,
3390        (true, raw) => Some(
3391            ColorInterpolation::try_from(u16::from(raw))
3392                .map_err(|()| ProtocolError::InvalidAnimation)?,
3393        ),
3394        (false, _) => return Err(bad),
3395    };
3396    let keyframe_count = usize::from(read_u16(record, 18)?);
3397    let delay_ms = float(28)?;
3398    let duration_ms = float(32)?;
3399    let iterations = float(36)?;
3400    let origin_x = float(40)?;
3401    let origin_y = float(44)?;
3402    let events = read_u8(record, 48)?;
3403    if keyframe_count < 2
3404        || !delay_ms.is_finite()
3405        || !(duration_ms.is_finite() && duration_ms >= 0.0)
3406        || iterations.is_nan()
3407        || iterations < 0.0
3408        || !(origin_x.is_finite() && origin_y.is_finite())
3409        || events & !AnimationEvents::ALL.0 != 0
3410    {
3411        return Err(bad);
3412    }
3413    let mut keyframes = Vec::with_capacity(keyframe_count);
3414    let mut at = ANIMATION_HEADER_LEN;
3415    for index in 0..keyframe_count {
3416        let offset = float(at)?;
3417        let raw_timing = read_u8(record, at + 4)?;
3418        let raw_position = read_u8(record, at + 5)?;
3419        let flags = read_u16(record, at + 6)?;
3420        let timing = match raw_timing {
3421            1 => Timing::Linear,
3422            2 => {
3423                let (x1, y1, x2, y2) = (
3424                    float(at + 8)?,
3425                    float(at + 12)?,
3426                    float(at + 16)?,
3427                    float(at + 20)?,
3428                );
3429                if ![x1, y1, x2, y2].iter().all(|value| value.is_finite())
3430                    || !(0.0..=1.0).contains(&x1)
3431                    || !(0.0..=1.0).contains(&x2)
3432                {
3433                    return Err(bad);
3434                }
3435                Timing::CubicBezier { x1, y1, x2, y2 }
3436            }
3437            3 => {
3438                let count = read_u32(record, at + 8)?;
3439                let position =
3440                    StepPosition::try_from(u16::from(raw_position)).map_err(|()| bad.clone())?;
3441                let least = if position == StepPosition::JumpNone {
3442                    2
3443                } else {
3444                    1
3445                };
3446                if count < least {
3447                    return Err(bad);
3448                }
3449                Timing::Steps { count, position }
3450            }
3451            _ => return Err(bad),
3452        };
3453        if flags & !KEYFRAME_FROM_PRESENTED != 0
3454            || (index > 0 && flags & KEYFRAME_FROM_PRESENTED != 0)
3455            || !(0.0..=1.0).contains(&offset)
3456        {
3457            return Err(bad);
3458        }
3459        let value_at = at + KEYFRAME_HEAD_LEN;
3460        let (value, value_len) = match property {
3461            AnimatedProperty::Alpha => {
3462                let value = float(value_at)?;
3463                if !value.is_finite() {
3464                    return Err(bad);
3465                }
3466                (KeyframeValue::Alpha(value), 4)
3467            }
3468            AnimatedProperty::Color
3469            | AnimatedProperty::Background
3470            | AnimatedProperty::BorderColor => {
3471                // A colour can be mixed with another colour; a brush cannot.
3472                let paint = Paint::from_bits(read_u64(record, value_at)?)
3473                    .filter(|paint| !matches!(paint, Paint::Asset(_)))
3474                    .ok_or(bad.clone())?;
3475                (KeyframeValue::Paint(paint), 8)
3476            }
3477            AnimatedProperty::Transform => {
3478                let count = usize::from(read_u16(record, value_at)?);
3479                let mut functions = Vec::with_capacity(count);
3480                for function in 0..count {
3481                    let function_at = value_at + 4 + TRANSFORM_FUNCTION_LEN * function;
3482                    let raw_kind = read_u32(record, function_at)?;
3483                    let kind = u16::try_from(raw_kind)
3484                        .ok()
3485                        .and_then(|kind| TransformFunctionKind::try_from(kind).ok())
3486                        .ok_or(bad.clone())?;
3487                    let mut values = [0.0_f32; 6];
3488                    for (slot, value) in values.iter_mut().enumerate() {
3489                        *value = float(function_at + 4 + 4 * slot)?;
3490                    }
3491                    if !values.iter().all(|value| value.is_finite()) {
3492                        return Err(bad);
3493                    }
3494                    functions.push(TransformFunction { kind, values });
3495                }
3496                (
3497                    KeyframeValue::Transform(std::borrow::Cow::Owned(functions)),
3498                    4 + TRANSFORM_FUNCTION_LEN * count,
3499                )
3500            }
3501        };
3502        keyframes.push(Keyframe {
3503            offset,
3504            timing,
3505            from_presented: flags & KEYFRAME_FROM_PRESENTED != 0,
3506            value,
3507        });
3508        at = value_at + value_len;
3509    }
3510    if at != record.len() {
3511        return Err(bad);
3512    }
3513    // Offsets start at 0, end at 1 and never go back, and every transform list has the
3514    // same kinds in the same order. A list the Host did not line up cannot be interpolated
3515    // one function to the next, which is the only way the Renderer interpolates them.
3516    let first = keyframes.first().map(|keyframe| keyframe.offset);
3517    let last = keyframes.last().map(|keyframe| keyframe.offset);
3518    if first != Some(0.0)
3519        || last != Some(1.0)
3520        || keyframes
3521            .windows(2)
3522            .any(|pair| pair[1].offset < pair[0].offset)
3523    {
3524        return Err(bad);
3525    }
3526    if let Some(KeyframeValue::Transform(shape)) = keyframes.first().map(|keyframe| &keyframe.value)
3527    {
3528        let kinds: Vec<_> = shape.iter().map(|function| function.kind).collect();
3529        let lined_up = keyframes.iter().all(|keyframe| match &keyframe.value {
3530            KeyframeValue::Transform(functions) => functions
3531                .iter()
3532                .map(|function| function.kind)
3533                .eq(kinds.iter().copied()),
3534            _ => false,
3535        });
3536        if !lined_up {
3537            return Err(bad);
3538        }
3539    }
3540    Ok(Animation {
3541        node_id: read_u32(record, 4)?,
3542        animation_id: read_u32(record, 8)?,
3543        property,
3544        slot: read_u8(record, 13)?,
3545        direction,
3546        fill,
3547        play_state,
3548        interpolation,
3549        start_time_nanos: read_u64(record, 20)?,
3550        delay_ms,
3551        duration_ms,
3552        iterations,
3553        origin_x,
3554        origin_y,
3555        events: AnimationEvents(events),
3556        keyframes: std::borrow::Cow::Owned(keyframes),
3557    })
3558}
3559
3560/// Two `f32` share one `u64`, with the first value in the low 32 bits.
3561const fn pack_floats(low: f32, high: f32) -> u64 {
3562    (low.to_bits() as u64) | ((high.to_bits() as u64) << 32)
3563}
3564
3565const fn unpack_low(word: u64) -> f32 {
3566    f32::from_bits(word as u32)
3567}
3568
3569const fn unpack_high(word: u64) -> f32 {
3570    f32::from_bits((word >> 32) as u32)
3571}
3572
3573/// The value's words with nothing past the first two, which is every modifier but the few
3574/// whose schema entry gives them more.
3575const fn two_words(first: u64, second: u64) -> [u64; MAX_MODIFIER_WORDS] {
3576    [first, second, 0, 0, 0, 0, 0, 0, 0, 0]
3577}
3578
3579fn float_word(value: f32) -> u64 {
3580    u64::from(value.to_bits())
3581}
3582
3583/// A modifier's tag and the words of its value. Only as many words as the schema gives
3584/// that tag are written; the rest are zero and never leave this function.
3585fn modifier_fields(modifier: &Modifier) -> (u16, [u64; MAX_MODIFIER_WORDS]) {
3586    match modifier {
3587        Modifier::Empty => (0, two_words(0, 0)),
3588        Modifier::Padding(value) => (1, two_words(float_word(*value), 0)),
3589        Modifier::FillMaxWidth => (2, two_words(0, 0)),
3590        Modifier::MatchParentSize => (31, two_words(0, 0)),
3591        Modifier::FillMaxHeight => (3, two_words(0, 0)),
3592        Modifier::Width(value) => (4, two_words(float_word(*value), 0)),
3593        Modifier::Height(value) => (5, two_words(float_word(*value), 0)),
3594        Modifier::Size { width, height } => (6, two_words(float_word(*width), float_word(*height))),
3595        Modifier::Background(paint) => (7, two_words(paint.to_bits(), 0)),
3596        Modifier::Clickable { handler_id } => (8, two_words(*handler_id, 0)),
3597        Modifier::PaddingRole(role) => (9, two_words(*role as u64, 0)),
3598        Modifier::PaddingEach {
3599            start,
3600            top,
3601            end,
3602            bottom,
3603        } => (
3604            10,
3605            two_words(pack_floats(*start, *top), pack_floats(*end, *bottom)),
3606        ),
3607        Modifier::Weight(value) => (11, two_words(float_word(*value), 0)),
3608        Modifier::Shape {
3609            top_start,
3610            top_end,
3611            bottom_end,
3612            bottom_start,
3613        } => (
3614            12,
3615            two_words(
3616                pack_floats(*top_start, *top_end),
3617                pack_floats(*bottom_end, *bottom_start),
3618            ),
3619        ),
3620        Modifier::ShapeRole(role) => (13, two_words(*role as u64, 0)),
3621        Modifier::Border { width, paint } => (14, two_words(float_word(*width), paint.to_bits())),
3622        Modifier::Elevation(dp) => (15, two_words(float_word(*dp), 0)),
3623        Modifier::ObserveSize { token, every_dp } => {
3624            (16, two_words(u64::from(*token), u64::from(*every_dp)))
3625        }
3626        Modifier::Motion(role) => (17, two_words(*role as u64, 0)),
3627        Modifier::Material(role) => (18, two_words(*role as u64, 0)),
3628        Modifier::Offset { x, y } => (19, two_words(float_word(*x), float_word(*y))),
3629        Modifier::RequiredSize { width, height } => {
3630            (20, two_words(float_word(*width), float_word(*height)))
3631        }
3632        Modifier::BorderEach {
3633            top,
3634            right,
3635            bottom,
3636            left,
3637            top_paint,
3638            right_paint,
3639            bottom_paint,
3640            left_paint,
3641        } => (
3642            21,
3643            [
3644                pack_floats(*top, *right),
3645                pack_floats(*bottom, *left),
3646                top_paint.to_bits(),
3647                right_paint.to_bits(),
3648                bottom_paint.to_bits(),
3649                left_paint.to_bits(),
3650                0,
3651                0,
3652                0,
3653                0,
3654            ],
3655        ),
3656        Modifier::CornerEach {
3657            top_left,
3658            top_right,
3659            bottom_right,
3660            bottom_left,
3661        } => (
3662            22,
3663            two_words(
3664                pack_floats(*top_left, *top_right),
3665                pack_floats(*bottom_right, *bottom_left),
3666            ),
3667        ),
3668        Modifier::Shadow {
3669            x,
3670            y,
3671            blur,
3672            spread,
3673            paint,
3674        } => (
3675            23,
3676            [
3677                pack_floats(*x, *y),
3678                pack_floats(*blur, *spread),
3679                paint.to_bits(),
3680                0,
3681                0,
3682                0,
3683                0,
3684                0,
3685                0,
3686                0,
3687            ],
3688        ),
3689        Modifier::WindowDrag(enabled) => (32, two_words(u64::from(*enabled), 0)),
3690        Modifier::Clip(enabled) => (24, two_words(u64::from(*enabled), 0)),
3691        Modifier::Alpha(value) => (25, two_words(float_word(*value), 0)),
3692        Modifier::PressFeedback { scale, tint_alpha } => {
3693            (33, two_words(pack_floats(*scale, *tint_alpha), 0))
3694        }
3695        Modifier::Semantics { role, state } => (34, two_words(*role as u64, u64::from(*state))),
3696        Modifier::CornerCurve { smoothing } => (35, two_words(float_word(*smoothing), 0)),
3697        Modifier::BackgroundBrush {
3698            x,
3699            y,
3700            width,
3701            height,
3702            paint,
3703            repeat,
3704            tile_width,
3705            tile_height,
3706        } => (
3707            28,
3708            [
3709                pack_floats(*x, *y),
3710                pack_floats(*width, *height),
3711                paint.to_bits(),
3712                u64::from(u16::from(*repeat)),
3713                pack_floats(*tile_width, *tile_height),
3714                0,
3715                0,
3716                0,
3717                0,
3718                0,
3719            ],
3720        ),
3721        Modifier::SizeIn {
3722            min_width,
3723            max_width,
3724            min_height,
3725            max_height,
3726        } => (
3727            36,
3728            two_words(
3729                pack_floats(*min_width, *max_width),
3730                pack_floats(*min_height, *max_height),
3731            ),
3732        ),
3733        Modifier::AspectRatio {
3734            ratio,
3735            match_height_constraints_first,
3736        } => (
3737            37,
3738            two_words(
3739                pack_floats(*ratio, 0.0),
3740                u64::from(*match_height_constraints_first),
3741            ),
3742        ),
3743        Modifier::MinTouchTarget { size } => (38, two_words(float_word(*size), 0)),
3744        Modifier::Overlay(paint) => (39, two_words(paint.to_bits(), 0)),
3745        Modifier::Sticky => (41, two_words(0, 0)),
3746        Modifier::UnboundedWidth => (40, two_words(0, 0)),
3747        Modifier::Transform {
3748            a,
3749            b,
3750            c,
3751            d,
3752            e,
3753            f,
3754            origin_x,
3755            origin_y,
3756        } => (
3757            26,
3758            [
3759                pack_floats(*a, *b),
3760                pack_floats(*c, *d),
3761                pack_floats(*e, *f),
3762                pack_floats(*origin_x, *origin_y),
3763                0,
3764                0,
3765                0,
3766                0,
3767                0,
3768                0,
3769            ],
3770        ),
3771        Modifier::Transform3D {
3772            m,
3773            origin_x,
3774            origin_y,
3775            backface_hidden,
3776        } => (
3777            27,
3778            [
3779                pack_floats(m[0], m[1]),
3780                pack_floats(m[2], m[3]),
3781                pack_floats(m[4], m[5]),
3782                pack_floats(m[6], m[7]),
3783                pack_floats(m[8], m[9]),
3784                pack_floats(m[10], m[11]),
3785                pack_floats(m[12], m[13]),
3786                pack_floats(m[14], m[15]),
3787                pack_floats(*origin_x, *origin_y),
3788                u64::from(*backface_hidden),
3789            ],
3790        ),
3791    }
3792}
3793
3794fn decode_role<T: TryFrom<u16, Error = ()>>(first: u64) -> Result<T, ProtocolError> {
3795    let tag = u16::try_from(first).map_err(|_| ProtocolError::InvalidModifier(0))?;
3796    T::try_from(tag).map_err(|()| ProtocolError::InvalidModifier(tag))
3797}
3798
3799fn decode_paint(bits: u64) -> Result<Paint, ProtocolError> {
3800    Paint::from_bits(bits).ok_or(ProtocolError::InvalidModifier(0))
3801}
3802
3803fn decode_modifier(tag: u16, words: &[u64; MAX_MODIFIER_WORDS]) -> Result<Modifier, ProtocolError> {
3804    let [
3805        first,
3806        second,
3807        third,
3808        fourth,
3809        fifth,
3810        sixth,
3811        seventh,
3812        eighth,
3813        ninth,
3814        tenth,
3815    ] = *words;
3816    match tag {
3817        0 => Ok(Modifier::Empty),
3818        1 => Ok(Modifier::Padding(f32::from_bits(first as u32))),
3819        2 => Ok(Modifier::FillMaxWidth),
3820        3 => Ok(Modifier::FillMaxHeight),
3821        4 => Ok(Modifier::Width(f32::from_bits(first as u32))),
3822        5 => Ok(Modifier::Height(f32::from_bits(first as u32))),
3823        6 => Ok(Modifier::Size {
3824            width: f32::from_bits(first as u32),
3825            height: f32::from_bits(second as u32),
3826        }),
3827        7 => Ok(Modifier::Background(decode_paint(first)?)),
3828        8 => Ok(Modifier::Clickable { handler_id: first }),
3829        9 => Ok(Modifier::PaddingRole(decode_role::<SpaceRole>(first)?)),
3830        10 => Ok(Modifier::PaddingEach {
3831            start: unpack_low(first),
3832            top: unpack_high(first),
3833            end: unpack_low(second),
3834            bottom: unpack_high(second),
3835        }),
3836        11 => Ok(Modifier::Weight(f32::from_bits(first as u32))),
3837        12 => Ok(Modifier::Shape {
3838            top_start: unpack_low(first),
3839            top_end: unpack_high(first),
3840            bottom_end: unpack_low(second),
3841            bottom_start: unpack_high(second),
3842        }),
3843        13 => Ok(Modifier::ShapeRole(decode_role::<ShapeRole>(first)?)),
3844        14 => Ok(Modifier::Border {
3845            width: f32::from_bits(first as u32),
3846            paint: decode_paint(second)?,
3847        }),
3848        15 => Ok(Modifier::Elevation(f32::from_bits(first as u32))),
3849        16 => Ok(Modifier::ObserveSize {
3850            token: first as u32,
3851            every_dp: match second {
3852                0 => false,
3853                1 => true,
3854                _ => return Err(ProtocolError::InvalidModifier(16)),
3855            },
3856        }),
3857        17 => Ok(Modifier::Motion(decode_role::<MotionRole>(first)?)),
3858        18 => Ok(Modifier::Material(decode_role::<MaterialRole>(first)?)),
3859        19 => Ok(Modifier::Offset {
3860            x: f32::from_bits(first as u32),
3861            y: f32::from_bits(second as u32),
3862        }),
3863        20 => Ok(Modifier::RequiredSize {
3864            width: f32::from_bits(first as u32),
3865            height: f32::from_bits(second as u32),
3866        }),
3867        21 => Ok(Modifier::BorderEach {
3868            top: unpack_low(first),
3869            right: unpack_high(first),
3870            bottom: unpack_low(second),
3871            left: unpack_high(second),
3872            top_paint: decode_paint(third)?,
3873            right_paint: decode_paint(fourth)?,
3874            bottom_paint: decode_paint(fifth)?,
3875            left_paint: decode_paint(sixth)?,
3876        }),
3877        22 => Ok(Modifier::CornerEach {
3878            top_left: unpack_low(first),
3879            top_right: unpack_high(first),
3880            bottom_right: unpack_low(second),
3881            bottom_left: unpack_high(second),
3882        }),
3883        23 => Ok(Modifier::Shadow {
3884            x: unpack_low(first),
3885            y: unpack_high(first),
3886            blur: unpack_low(second),
3887            spread: unpack_high(second),
3888            paint: decode_paint(third)?,
3889        }),
3890        // A flag is 0 or 1. Anything else is a record the two sides disagree about, and
3891        // reading it as "on" would hide that.
3892        24 => match first {
3893            0 => Ok(Modifier::Clip(false)),
3894            1 => Ok(Modifier::Clip(true)),
3895            _ => Err(ProtocolError::InvalidModifier(24)),
3896        },
3897        32 => match first {
3898            0 => Ok(Modifier::WindowDrag(false)),
3899            1 => Ok(Modifier::WindowDrag(true)),
3900            _ => Err(ProtocolError::InvalidModifier(32)),
3901        },
3902        25 => Ok(Modifier::Alpha(f32::from_bits(first as u32))),
3903        26 => {
3904            let values = [
3905                unpack_low(first),
3906                unpack_high(first),
3907                unpack_low(second),
3908                unpack_high(second),
3909                unpack_low(third),
3910                unpack_high(third),
3911                unpack_low(fourth),
3912                unpack_high(fourth),
3913            ];
3914            // A NaN or an infinity in a matrix makes everything under it undrawable, and
3915            // the two sides would not even agree on how. Refused here, as the Renderer
3916            // refuses it.
3917            if values.iter().any(|value| !value.is_finite()) {
3918                return Err(ProtocolError::InvalidModifier(26));
3919            }
3920            let [a, b, c, d, e, f, origin_x, origin_y] = values;
3921            Ok(Modifier::Transform {
3922                a,
3923                b,
3924                c,
3925                d,
3926                e,
3927                f,
3928                origin_x,
3929                origin_y,
3930            })
3931        }
3932        27 => {
3933            let values = [
3934                unpack_low(first),
3935                unpack_high(first),
3936                unpack_low(second),
3937                unpack_high(second),
3938                unpack_low(third),
3939                unpack_high(third),
3940                unpack_low(fourth),
3941                unpack_high(fourth),
3942                unpack_low(fifth),
3943                unpack_high(fifth),
3944                unpack_low(sixth),
3945                unpack_high(sixth),
3946                unpack_low(seventh),
3947                unpack_high(seventh),
3948                unpack_low(eighth),
3949                unpack_high(eighth),
3950                unpack_low(ninth),
3951                unpack_high(ninth),
3952            ];
3953            // The same refusal as the 2D matrix: a NaN or an infinity would draw nothing
3954            // on one side and something on the other.
3955            if values.iter().any(|value| !value.is_finite()) {
3956                return Err(ProtocolError::InvalidModifier(27));
3957            }
3958            let backface_hidden = match tenth {
3959                0 => false,
3960                1 => true,
3961                _ => return Err(ProtocolError::InvalidModifier(27)),
3962            };
3963            let mut m = [0.0; 16];
3964            m.copy_from_slice(&values[..16]);
3965            Ok(Modifier::Transform3D {
3966                m,
3967                origin_x: values[16],
3968                origin_y: values[17],
3969                backface_hidden,
3970            })
3971        }
3972        31 => Ok(Modifier::MatchParentSize),
3973        33 => Ok(Modifier::PressFeedback {
3974            scale: unpack_low(first),
3975            tint_alpha: unpack_high(first),
3976        }),
3977        34 => {
3978            let state = u32::try_from(second)
3979                .ok()
3980                .filter(|state| state & !SEMANTICS_STATE_MASK == 0)
3981                .ok_or(ProtocolError::InvalidModifier(34))?;
3982            Ok(Modifier::Semantics {
3983                role: decode_role::<SemanticsRole>(first)?,
3984                state,
3985            })
3986        }
3987        28 => {
3988            let values = [
3989                unpack_low(first),
3990                unpack_high(first),
3991                unpack_low(second),
3992                unpack_high(second),
3993                unpack_low(fifth),
3994                unpack_high(fifth),
3995            ];
3996            // A tile that is not a size has no copies to place, and a value that is not a
3997            // number would be drawn by one side and not the other. Refused here, as the
3998            // Renderer refuses them.
3999            if values.iter().any(|value| !value.is_finite()) || values[4] <= 0.0 || values[5] <= 0.0
4000            {
4001                return Err(ProtocolError::InvalidModifier(28));
4002            }
4003            let [x, y, width, height, tile_width, tile_height] = values;
4004            Ok(Modifier::BackgroundBrush {
4005                x,
4006                y,
4007                width,
4008                height,
4009                paint: decode_paint(third)?,
4010                repeat: decode_role::<BackgroundRepeat>(fourth)?,
4011                tile_width,
4012                tile_height,
4013            })
4014        }
4015        // Carried as sent. An out-of-range value is not an error; the Renderer draws it as
4016        // the nearer end of 0..=1.
4017        35 => Ok(Modifier::CornerCurve {
4018            smoothing: unpack_low(first),
4019        }),
4020        36 => Ok(Modifier::SizeIn {
4021            min_width: unpack_low(first),
4022            max_width: unpack_high(first),
4023            min_height: unpack_low(second),
4024            max_height: unpack_high(second),
4025        }),
4026        37 => {
4027            let match_height_constraints_first = match second {
4028                0 => false,
4029                1 => true,
4030                _ => return Err(ProtocolError::InvalidModifier(37)),
4031            };
4032            Ok(Modifier::AspectRatio {
4033                ratio: unpack_low(first),
4034                match_height_constraints_first,
4035            })
4036        }
4037        38 => Ok(Modifier::MinTouchTarget {
4038            size: unpack_low(first),
4039        }),
4040        39 => Ok(Modifier::Overlay(decode_paint(first)?)),
4041        41 => Ok(Modifier::Sticky),
4042        40 => Ok(Modifier::UnboundedWidth),
4043        other => Err(ProtocolError::InvalidModifier(other)),
4044    }
4045}
4046
4047/// Reads a `(offset: u32, len: u32)` string reference at `position`.
4048///
4049/// Strings live in the arena that follows the records, so `arena_start` is the
4050/// first byte a string may legally point at. Without that floor a hostile Renderer can
4051/// aim a string at the record region and have the decoder reinterpret record headers as
4052/// text, garbage decoding into a valid-looking mutation.
4053fn read_string(bytes: &[u8], position: usize, arena_start: usize) -> Result<&str, ProtocolError> {
4054    let value = read_bytes(bytes, position, arena_start)?;
4055    std::str::from_utf8(value).map_err(|_| ProtocolError::InvalidUtf8)
4056}
4057
4058/// The same arena range a string uses, without the UTF-8 requirement.
4059fn read_bytes(bytes: &[u8], position: usize, arena_start: usize) -> Result<&[u8], ProtocolError> {
4060    let offset =
4061        usize::try_from(read_u32(bytes, position)?).map_err(|_| ProtocolError::LengthOverflow)?;
4062    let len = usize::try_from(read_u32(bytes, position + 4)?)
4063        .map_err(|_| ProtocolError::LengthOverflow)?;
4064    let end = offset
4065        .checked_add(len)
4066        .ok_or(ProtocolError::InvalidStringRange)?;
4067    if offset < arena_start {
4068        return Err(ProtocolError::InvalidStringRange);
4069    }
4070    bytes
4071        .get(offset..end)
4072        .ok_or(ProtocolError::InvalidStringRange)
4073}
4074
4075fn read_u8(bytes: &[u8], position: usize) -> Result<u8, ProtocolError> {
4076    bytes.get(position).copied().ok_or(ProtocolError::Truncated)
4077}
4078
4079fn read_u16(bytes: &[u8], position: usize) -> Result<u16, ProtocolError> {
4080    let value = bytes
4081        .get(position..position + 2)
4082        .ok_or(ProtocolError::Truncated)?;
4083    Ok(u16::from_le_bytes([value[0], value[1]]))
4084}
4085
4086fn read_u32(bytes: &[u8], position: usize) -> Result<u32, ProtocolError> {
4087    let value = bytes
4088        .get(position..position + 4)
4089        .ok_or(ProtocolError::Truncated)?;
4090    Ok(u32::from_le_bytes([value[0], value[1], value[2], value[3]]))
4091}
4092
4093/// A word that is 0 or 1. Any other value is a protocol error, not a third state.
4094/// Refuses a reserved word that is not zero: a record from a newer or a broken side, whose
4095/// meaning here would be a guess.
4096fn require_zero_word(bytes: &[u8], position: usize) -> Result<(), ProtocolError> {
4097    match read_u32(bytes, position)? {
4098        0 => Ok(()),
4099        other => Err(ProtocolError::InvalidValueKind(
4100            other.min(u32::from(u16::MAX)) as u16,
4101        )),
4102    }
4103}
4104
4105fn read_flag(bytes: &[u8], position: usize) -> Result<bool, ProtocolError> {
4106    match read_u32(bytes, position)? {
4107        0 => Ok(false),
4108        1 => Ok(true),
4109        other => Err(ProtocolError::InvalidValueKind(
4110            other.min(u32::from(u16::MAX)) as u16,
4111        )),
4112    }
4113}
4114
4115fn read_u64(bytes: &[u8], position: usize) -> Result<u64, ProtocolError> {
4116    let value = bytes
4117        .get(position..position + 8)
4118        .ok_or(ProtocolError::Truncated)?;
4119    Ok(u64::from_le_bytes(
4120        value.try_into().map_err(|_| ProtocolError::Truncated)?,
4121    ))
4122}
4123
4124#[cfg(test)]
4125mod tests {
4126    use super::*;
4127    use crate::schema::TypeRole;
4128
4129    #[test]
4130    fn round_trips_all_m0_mutations() {
4131        let mutations = [
4132            Mutation::Create {
4133                node_id: 1,
4134                widget: WidgetKind::Column,
4135            },
4136            Mutation::SetProp {
4137                node_id: 2,
4138                property: PropertyKind::Text,
4139                value: PropertyValue::String("안녕"),
4140            },
4141            Mutation::SetProp {
4142                node_id: 3,
4143                property: PropertyKind::Enabled,
4144                value: PropertyValue::Bool(true),
4145            },
4146            Mutation::SetModifier {
4147                node_id: 1,
4148                index: 0,
4149                modifier: Modifier::Padding(16.0),
4150            },
4151            Mutation::Insert {
4152                parent_id: 1,
4153                node_id: 2,
4154                index: 0,
4155            },
4156            Mutation::Move {
4157                parent_id: 1,
4158                node_id: 2,
4159                index: 1,
4160            },
4161            Mutation::Remove { node_id: 3 },
4162            Mutation::SetText {
4163                node_id: 4,
4164                text: "compose",
4165                selection: Some(Selection { start: 1, end: 4 }),
4166            },
4167            Mutation::AppendText {
4168                node_id: 4,
4169                text: " token",
4170            },
4171        ];
4172        let mut encoder = BatchEncoder::default();
4173        for mutation in &mutations {
4174            encoder.encode(mutation).unwrap();
4175        }
4176        let decoded = decode_batch(encoder.finish().unwrap()).unwrap();
4177        assert_eq!(decoded, mutations);
4178    }
4179
4180    /// A role Paint and a literal Paint occupy the same record length and
4181    /// decode back to the value that was encoded.
4182    #[test]
4183    fn fr13_paint_role_and_literal_share_one_record_length() {
4184        let encode_one = |modifier| {
4185            let mut encoder = BatchEncoder::default();
4186            encoder
4187                .encode(&Mutation::SetModifier {
4188                    node_id: 1,
4189                    index: 0,
4190                    modifier,
4191                })
4192                .unwrap();
4193            encoder.finish().unwrap().to_vec()
4194        };
4195        let role = encode_one(Modifier::Background(Paint::Role(
4196            crate::schema::ColorRole::Surface,
4197        )));
4198        let literal = encode_one(Modifier::Background(Paint::Literal(
4199            crate::schema::Color::rgb(0x1b1b1f),
4200        )));
4201        assert_eq!(role.len(), literal.len());
4202        assert_eq!(
4203            decode_batch(&role).unwrap(),
4204            [Mutation::SetModifier {
4205                node_id: 1,
4206                index: 0,
4207                modifier: Modifier::Background(Paint::Role(crate::schema::ColorRole::Surface)),
4208            }]
4209        );
4210        assert_eq!(
4211            decode_batch(&literal).unwrap(),
4212            [Mutation::SetModifier {
4213                node_id: 1,
4214                index: 0,
4215                modifier: Modifier::Background(Paint::Literal(crate::schema::Color::rgb(0x1b1b1f))),
4216            }]
4217        );
4218    }
4219
4220    #[test]
4221    fn fr68_semantics_round_trips_and_refuses_unknown_state_bits() {
4222        let expected = Modifier::Semantics {
4223            role: SemanticsRole::Switch,
4224            state: (2 << crate::schema::SEMANTICS_CHECKED_SHIFT)
4225                | (1 << crate::schema::SEMANTICS_SELECTED_SHIFT),
4226        };
4227        let mutation = Mutation::SetModifier {
4228            node_id: 1,
4229            index: 0,
4230            modifier: expected.clone(),
4231        };
4232        let mut encoder = BatchEncoder::default();
4233        encoder.encode(&mutation).unwrap();
4234        assert_eq!(decode_batch(encoder.finish().unwrap()).unwrap(), [mutation]);
4235
4236        let words = [SemanticsRole::Button as u64, 0x4000, 0, 0, 0, 0, 0, 0, 0, 0];
4237        assert_eq!(
4238            decode_modifier(34, &words),
4239            Err(ProtocolError::InvalidModifier(34))
4240        );
4241    }
4242
4243    #[test]
4244    fn fr71_every_new_role_round_trips_and_is_exposed() {
4245        use crate::schema::*;
4246        let roles = [
4247            (SemanticsRole::TabList, 9),
4248            (SemanticsRole::Tree, 10),
4249            (SemanticsRole::TreeItem, 11),
4250            (SemanticsRole::Menu, 12),
4251            (SemanticsRole::MenuItem, 13),
4252            (SemanticsRole::TextBox, 14),
4253            (SemanticsRole::Heading, 15),
4254            (SemanticsRole::Navigation, 16),
4255            (SemanticsRole::List, 17),
4256            (SemanticsRole::ListItem, 18),
4257            (SemanticsRole::Group, 19),
4258        ];
4259        let state = (2 << SEMANTICS_EXPANDED_SHIFT)
4260            | (2 << SEMANTICS_DISABLED_SHIFT)
4261            | (1 << SEMANTICS_FOCUSED_SHIFT)
4262            | SEMANTICS_HIDDEN_BIT
4263            | SEMANTICS_CLICK_ACTION_BIT
4264            | SEMANTICS_FOCUS_ACTION_BIT
4265            | SEMANTICS_HAS_POPUP_BIT;
4266        assert_eq!(state & !SEMANTICS_STATE_MASK, 0);
4267        for (role, value) in roles {
4268            assert_eq!(role as u64, value, "{role:?} changed its wire value");
4269            let mutation = Mutation::SetModifier {
4270                node_id: 1,
4271                index: 0,
4272                modifier: Modifier::Semantics { role, state },
4273            };
4274            let mut encoder = BatchEncoder::default();
4275            encoder.encode(&mutation).unwrap();
4276            assert_eq!(decode_batch(encoder.finish().unwrap()).unwrap(), [mutation]);
4277        }
4278        assert!(
4279            ROLE_ENUM_SCHEMA
4280                .iter()
4281                .any(|e| e.name == "SemanticsRole" && e.variants.len() == 19),
4282            "the schema must list all 19 roles"
4283        );
4284    }
4285
4286    #[test]
4287    fn nfr7_unknown_semantics_bit_is_a_protocol_error() {
4288        // Bit 14 is the first one above the mask.
4289        let words = [SemanticsRole::Group as u64, 1 << 14, 0, 0, 0, 0, 0, 0, 0, 0];
4290        assert_eq!(
4291            decode_modifier(34, &words),
4292            Err(ProtocolError::InvalidModifier(34))
4293        );
4294        // The highest bit the mask allows still decodes.
4295        let words = [SemanticsRole::Group as u64, 1 << 13, 0, 0, 0, 0, 0, 0, 0, 0];
4296        assert!(decode_modifier(34, &words).is_ok());
4297    }
4298
4299    #[test]
4300    fn fr51_press_feedback_round_trips() {
4301        let expected = [Mutation::SetModifier {
4302            node_id: 1,
4303            index: 0,
4304            modifier: Modifier::PressFeedback {
4305                scale: 0.975,
4306                tint_alpha: 0.07,
4307            },
4308        }];
4309        let mut encoder = BatchEncoder::default();
4310        encoder.encode(&expected[0]).unwrap();
4311        assert_eq!(decode_batch(encoder.finish().unwrap()).unwrap(), expected);
4312    }
4313
4314    #[test]
4315    fn fr50_corner_curve_round_trips() {
4316        for smoothing in [0.0, 0.6, 1.0, -2.5, 7.0] {
4317            let expected = [Mutation::SetModifier {
4318                node_id: 1,
4319                index: 0,
4320                modifier: Modifier::CornerCurve { smoothing },
4321            }];
4322            let mut encoder = BatchEncoder::default();
4323            encoder.encode(&expected[0]).unwrap();
4324            let bytes = encoder.finish().unwrap().to_vec();
4325            assert_eq!(u16::from_le_bytes([bytes[22], bytes[23]]), 35);
4326            assert_eq!(decode_batch(&bytes).unwrap(), expected);
4327        }
4328    }
4329
4330    /// Every design primitive fits in `(tag, u64, u64)` and survives a round trip.
4331    #[test]
4332    fn fr13_design_modifiers_round_trip_in_two_words() {
4333        let modifiers = [
4334            Modifier::PaddingRole(SpaceRole::Md),
4335            Modifier::PaddingEach {
4336                start: 1.0,
4337                top: 2.0,
4338                end: 3.0,
4339                bottom: 4.0,
4340            },
4341            Modifier::Weight(0.25),
4342            Modifier::Shape {
4343                top_start: 4.0,
4344                top_end: 8.0,
4345                bottom_end: 12.0,
4346                bottom_start: 16.0,
4347            },
4348            Modifier::ShapeRole(ShapeRole::Full),
4349            Modifier::Border {
4350                width: 2.0,
4351                paint: Paint::Role(crate::schema::ColorRole::Outline),
4352            },
4353            Modifier::Elevation(6.0),
4354        ];
4355        let mut encoder = BatchEncoder::default();
4356        let expected: Vec<_> = modifiers
4357            .iter()
4358            .enumerate()
4359            .map(|(index, modifier)| Mutation::SetModifier {
4360                node_id: 1,
4361                index: index as u16,
4362                modifier: modifier.clone(),
4363            })
4364            .collect();
4365        for mutation in &expected {
4366            encoder.encode(mutation).unwrap();
4367        }
4368        let bytes = encoder.finish().unwrap();
4369        // Every modifier record is the same fixed 28 bytes.
4370        assert_eq!(bytes.len(), ENVELOPE_LEN + expected.len() * 28);
4371        assert_eq!(decode_batch(bytes).unwrap(), expected);
4372    }
4373
4374    /// A node's shadows are several `Shadow` records at consecutive chain positions,
4375    /// each with its own offset, blur, spread and paint (alpha included), and every one
4376    /// survives a round trip in the order it was written.
4377    #[test]
4378    fn fr42_shadow_a_list_of_shadows_round_trips_in_order() {
4379        let shadows = [
4380            Modifier::Shadow {
4381                x: 0.0,
4382                y: 1.0,
4383                blur: 2.0,
4384                spread: 0.0,
4385                paint: Paint::Literal(crate::schema::Color::argb(0x1400_0000)),
4386            },
4387            Modifier::Shadow {
4388                x: 0.0,
4389                y: 4.0,
4390                blur: 12.0,
4391                spread: -2.0,
4392                paint: Paint::Literal(crate::schema::Color::argb(0x2900_0000)),
4393            },
4394            Modifier::Shadow {
4395                x: -3.5,
4396                y: 24.0,
4397                blur: 48.0,
4398                spread: 4.0,
4399                paint: Paint::Role(crate::schema::ColorRole::Outline),
4400            },
4401        ];
4402        let expected: Vec<_> = shadows
4403            .iter()
4404            .enumerate()
4405            .map(|(index, modifier)| Mutation::SetModifier {
4406                node_id: 7,
4407                index: 9 + index as u16,
4408                modifier: modifier.clone(),
4409            })
4410            .collect();
4411        let mut encoder = BatchEncoder::default();
4412        for mutation in &expected {
4413            encoder.encode(mutation).unwrap();
4414        }
4415        let bytes = encoder.finish().unwrap();
4416        assert_eq!(decode_batch(bytes).unwrap(), expected);
4417    }
4418
4419    /// `SetTheme` is four `u16` fields and one font slot per type role.
4420    ///
4421    /// Fixed length whether or not any font is named, because the record is fixed layout
4422    /// and a theme is sent once rather than per frame. The slots cost 36 bytes on a
4423    /// message that appears once in a session.
4424    #[test]
4425    fn fr23_set_theme_round_trips_with_a_slot_for_every_type_role() {
4426        let theme = Theme::adaptive(DesignSystem::Cupertino)
4427            .with_color_scheme(ColorScheme::Dark)
4428            .with_font(TypeRole::Display, 7);
4429        let length = 20 + 4 * TYPE_ROLE_COUNT as u16;
4430        let mut encoder = BatchEncoder::default();
4431        encoder.encode(&Mutation::SetTheme(theme)).unwrap();
4432        let bytes = encoder.finish().unwrap();
4433        assert_eq!(bytes.len(), ENVELOPE_LEN + length as usize);
4434        assert_eq!(read_u16(bytes, ENVELOPE_LEN).unwrap(), TAG_SET_THEME);
4435        assert_eq!(read_u16(bytes, ENVELOPE_LEN + 2).unwrap(), length);
4436        assert_eq!(decode_batch(bytes).unwrap(), [Mutation::SetTheme(theme)]);
4437    }
4438
4439    /// A font named for one role leaves every other role on the system font.
4440    #[test]
4441    fn fr23_a_font_is_named_for_one_role_and_no_others() {
4442        let theme = Theme::unified(DesignSystem::Material3).with_font(TypeRole::Display, 3);
4443        assert_eq!(theme.font(TypeRole::Display), Some(3));
4444        for role in [
4445            TypeRole::Body,
4446            TypeRole::Title,
4447            TypeRole::Mono,
4448            TypeRole::Caption,
4449        ] {
4450            assert_eq!(theme.font(role), None);
4451        }
4452    }
4453
4454    /// One font for the whole screen: every role but code takes it, and code stays
4455    /// monospaced until a font is named for it.
4456    #[test]
4457    fn fr52_a_default_font_names_every_role_but_mono() {
4458        let theme = Theme::unified(DesignSystem::Material3).with_default_font(5);
4459        for role in [
4460            TypeRole::Display,
4461            TypeRole::Headline,
4462            TypeRole::Title,
4463            TypeRole::Subtitle,
4464            TypeRole::Body,
4465            TypeRole::BodyStrong,
4466            TypeRole::Label,
4467            TypeRole::Caption,
4468        ] {
4469            assert_eq!(theme.font(role), Some(5), "{role:?}");
4470        }
4471        assert_eq!(theme.font(TypeRole::Mono), None);
4472        assert_eq!(theme.font(TypeRole::None), None);
4473
4474        let both = theme
4475            .with_font(TypeRole::Mono, 9)
4476            .with_font(TypeRole::Display, 3);
4477        assert_eq!(both.font(TypeRole::Mono), Some(9));
4478        assert_eq!(
4479            both.font(TypeRole::Display),
4480            Some(3),
4481            "the role named last wins"
4482        );
4483        assert_eq!(both.font(TypeRole::Body), Some(5));
4484
4485        let mut encoder = BatchEncoder::default();
4486        encoder.encode(&Mutation::SetTheme(theme)).unwrap();
4487        let bytes = encoder.finish().unwrap();
4488        assert_eq!(decode_batch(bytes).unwrap(), [Mutation::SetTheme(theme)]);
4489    }
4490
4491    /// An out-of-range theme tag is an error, never a panic.
4492    #[test]
4493    fn fr14_rejects_unknown_theme_tags() {
4494        let mut encoder = BatchEncoder::default();
4495        encoder
4496            .encode(&Mutation::SetTheme(Theme::default()))
4497            .unwrap();
4498        let mut bytes = encoder.finish().unwrap().to_vec();
4499        bytes[ENVELOPE_LEN + 4..ENVELOPE_LEN + 6].copy_from_slice(&99_u16.to_le_bytes());
4500        assert_eq!(decode_batch(&bytes), Err(ProtocolError::InvalidTheme(99)));
4501    }
4502
4503    #[test]
4504    fn rejects_unknown_tags_without_panicking() {
4505        let mut bytes = vec![0, 0, 12, 0, 20, 0, 0, 0, 1, 0, 0, 0];
4506        bytes.extend_from_slice(&999_u16.to_le_bytes());
4507        bytes.extend_from_slice(&8_u16.to_le_bytes());
4508        bytes.extend_from_slice(&0_u32.to_le_bytes());
4509        assert_eq!(decode_batch(&bytes), Err(ProtocolError::InvalidTag(999)));
4510    }
4511
4512    #[test]
4513    fn pr4_renderer_events_round_trip_fixed_layout() {
4514        let events = [
4515            HostEvent {
4516                node_id: 7,
4517                handler_id: 11,
4518                payload: crate::EventPayload::Clicked,
4519            },
4520            HostEvent {
4521                node_id: 8,
4522                handler_id: 12,
4523                payload: crate::EventPayload::TextChanged("한글"),
4524            },
4525            HostEvent {
4526                node_id: 8,
4527                handler_id: 13,
4528                payload: crate::EventPayload::TextSubmitted("done"),
4529            },
4530            HostEvent {
4531                node_id: 8,
4532                handler_id: 14,
4533                payload: crate::EventPayload::FocusLost,
4534            },
4535            HostEvent {
4536                node_id: 9,
4537                handler_id: 16,
4538                payload: crate::EventPayload::RangeRequested {
4539                    start: 100,
4540                    count: 20,
4541                },
4542            },
4543            HostEvent {
4544                node_id: 8,
4545                handler_id: 15,
4546                payload: crate::EventPayload::KeyDown {
4547                    key: Key::Enter,
4548                    shift_key: true,
4549                    ctrl_key: false,
4550                    alt_key: true,
4551                    meta_key: false,
4552                    repeat: true,
4553                    code: 0x28,
4554                    text: "Enter",
4555                },
4556            },
4557        ];
4558        let mut bytes = Vec::new();
4559        for event in events {
4560            encode_event(&event, &mut bytes).unwrap();
4561            assert_eq!(decode_event(&bytes).unwrap(), event);
4562        }
4563    }
4564
4565    #[test]
4566    fn fr19_9_window_safe_area_round_trips() {
4567        let event = HostEvent {
4568            node_id: 0,
4569            handler_id: 0,
4570            payload: crate::EventPayload::WindowSizeChanged {
4571                width_dp: 841.5,
4572                height_dp: 600.25,
4573                class: crate::WindowSizeClass::Expanded,
4574                height_class: crate::WindowHeightClass::Medium,
4575                safe_area_top: 28.5,
4576                safe_area_leading: 72.0,
4577                safe_area_trailing: 13.0,
4578            },
4579        };
4580        let mut bytes = Vec::new();
4581        encode_event(&event, &mut bytes).unwrap();
4582        assert_eq!(bytes.len(), 44);
4583        assert_eq!(decode_event(&bytes).unwrap(), event);
4584    }
4585
4586    #[test]
4587    fn nfr7_malformed_key_down_text_is_a_protocol_error() {
4588        let event = HostEvent {
4589            node_id: 1,
4590            handler_id: 2,
4591            payload: crate::EventPayload::KeyDown {
4592                key: Key::Enter,
4593                shift_key: false,
4594                ctrl_key: false,
4595                alt_key: false,
4596                meta_key: false,
4597                repeat: false,
4598                code: 0x51,
4599                text: "ArrowDown",
4600            },
4601        };
4602        let mut bytes = Vec::new();
4603        encode_event(&event, &mut bytes).unwrap();
4604        assert_eq!(decode_event(&bytes).unwrap(), event);
4605        // The text points past the end of the record.
4606        let mut past_end = bytes.clone();
4607        past_end[28..32].copy_from_slice(&200_u32.to_le_bytes());
4608        assert_eq!(
4609            decode_event(&past_end),
4610            Err(ProtocolError::InvalidStringRange)
4611        );
4612        // The text starts inside the header, before the string area.
4613        let mut inside_header = bytes.clone();
4614        inside_header[24..28].copy_from_slice(&8_u32.to_le_bytes());
4615        assert_eq!(
4616            decode_event(&inside_header),
4617            Err(ProtocolError::InvalidStringRange)
4618        );
4619        // The text is not UTF-8.
4620        let mut not_utf8 = bytes;
4621        not_utf8[32] = 0xff;
4622        assert_eq!(decode_event(&not_utf8), Err(ProtocolError::InvalidUtf8));
4623    }
4624
4625    #[test]
4626    fn fr19_9_short_window_size_record_is_a_protocol_error() {
4627        let mut bytes = vec![0; 32];
4628        bytes[0..2].copy_from_slice(&EVENT_WINDOW_SIZE_CHANGED.to_le_bytes());
4629        bytes[2..4].copy_from_slice(&32_u16.to_le_bytes());
4630        assert!(decode_event(&bytes).is_err());
4631        bytes[2..4].copy_from_slice(&44_u16.to_le_bytes());
4632        assert!(decode_event(&bytes).is_err());
4633    }
4634
4635    #[test]
4636    fn fr20_unknown_window_size_class_is_a_protocol_error() {
4637        let event = HostEvent {
4638            node_id: 0,
4639            handler_id: 0,
4640            payload: crate::EventPayload::WindowSizeChanged {
4641                width_dp: 320.0,
4642                height_dp: 640.0,
4643                class: crate::WindowSizeClass::Compact,
4644                height_class: crate::WindowHeightClass::Medium,
4645                safe_area_top: 0.0,
4646                safe_area_leading: 0.0,
4647                safe_area_trailing: 0.0,
4648            },
4649        };
4650        let mut bytes = Vec::new();
4651        encode_event(&event, &mut bytes).unwrap();
4652        bytes[24..28].copy_from_slice(&99_u32.to_le_bytes());
4653        assert_eq!(
4654            decode_event(&bytes),
4655            Err(ProtocolError::InvalidValueKind(99))
4656        );
4657    }
4658
4659    #[test]
4660    fn fr20_unknown_window_height_class_is_a_protocol_error() {
4661        let event = HostEvent {
4662            node_id: 0,
4663            handler_id: 0,
4664            payload: crate::EventPayload::WindowSizeChanged {
4665                width_dp: 320.0,
4666                height_dp: 640.0,
4667                class: crate::WindowSizeClass::Compact,
4668                height_class: crate::WindowHeightClass::Medium,
4669                safe_area_top: 0.0,
4670                safe_area_leading: 0.0,
4671                safe_area_trailing: 0.0,
4672            },
4673        };
4674        let mut bytes = Vec::new();
4675        encode_event(&event, &mut bytes).unwrap();
4676        bytes[28..32].copy_from_slice(&99_u32.to_le_bytes());
4677        assert_eq!(
4678            decode_event(&bytes),
4679            Err(ProtocolError::InvalidValueKind(99))
4680        );
4681    }
4682
4683    #[test]
4684    fn fr20_window_size_classes_follow_the_material_boundaries() {
4685        use crate::WindowSizeClass;
4686        assert_eq!(
4687            WindowSizeClass::from_width_dp(599.9),
4688            WindowSizeClass::Compact
4689        );
4690        assert_eq!(
4691            WindowSizeClass::from_width_dp(600.0),
4692            WindowSizeClass::Medium
4693        );
4694        assert_eq!(
4695            WindowSizeClass::from_width_dp(839.9),
4696            WindowSizeClass::Medium
4697        );
4698        assert_eq!(
4699            WindowSizeClass::from_width_dp(840.0),
4700            WindowSizeClass::Expanded
4701        );
4702    }
4703
4704    #[test]
4705    fn fr20_window_height_classes_follow_the_material_boundaries() {
4706        use crate::WindowHeightClass;
4707        assert_eq!(
4708            WindowHeightClass::from_height_dp(479.9),
4709            WindowHeightClass::Compact
4710        );
4711        assert_eq!(
4712            WindowHeightClass::from_height_dp(480.0),
4713            WindowHeightClass::Medium
4714        );
4715        assert_eq!(
4716            WindowHeightClass::from_height_dp(899.9),
4717            WindowHeightClass::Medium
4718        );
4719        assert_eq!(
4720            WindowHeightClass::from_height_dp(900.0),
4721            WindowHeightClass::Expanded
4722        );
4723    }
4724
4725    fn post_notification() -> Mutation<'static> {
4726        Mutation::PostNotification {
4727            key: "session/7",
4728            title: "세션이 끝났습니다",
4729            body: "refactor-parser: 테스트 214개 통과",
4730            channel: "세션",
4731            action_1: "열기",
4732            action_2: "",
4733            importance: NotificationImportance::Urgent,
4734            presentation: NotificationPresentation::WhenInactive,
4735        }
4736    }
4737
4738    /// The three notification commands keep the lengths the wire fixes for them: six string
4739    /// references and two closed enums, one string reference, and a bare header.
4740    #[test]
4741    fn fr36_notification_commands_round_trip_at_their_fixed_lengths() {
4742        let mutations = [
4743            post_notification(),
4744            Mutation::WithdrawNotification { key: "session/7" },
4745            Mutation::RequestNotificationPermission,
4746        ];
4747        let mut lengths = Vec::new();
4748        let mut encoder = BatchEncoder::default();
4749        for mutation in &mutations {
4750            encoder.encode(mutation).unwrap();
4751        }
4752        let bytes = encoder.finish().unwrap();
4753        let mut position = ENVELOPE_LEN;
4754        for _ in &mutations {
4755            let length = read_u16(bytes, position + 2).unwrap();
4756            lengths.push((read_u16(bytes, position).unwrap(), length));
4757            position += usize::from(length);
4758        }
4759        assert_eq!(
4760            lengths,
4761            [
4762                (TAG_POST_NOTIFICATION, 56),
4763                (TAG_WITHDRAW_NOTIFICATION, 12),
4764                (TAG_REQUEST_NOTIFICATION_PERMISSION, 4),
4765            ]
4766        );
4767        assert_eq!(decode_batch(bytes).unwrap(), mutations);
4768    }
4769
4770    /// A message's placement and offset ride in the record after the fields it always had,
4771    /// which stay at their offsets, and a message that names neither still reads as one
4772    /// with neither.
4773    #[test]
4774    fn fr21_message_placement_round_trips() {
4775        let placed = Mutation::ShowMessage {
4776            handler_id: 9,
4777            text: "Copied",
4778            action: "",
4779            duration: MessageDuration::Short,
4780            placement: Some(MessagePlacement {
4781                vertical: MessageVertical::Bottom,
4782                horizontal: MessageHorizontal::Center,
4783            }),
4784            offset_dp: Some(96.0),
4785        };
4786        let unplaced = Mutation::ShowMessage {
4787            handler_id: 0,
4788            text: "Saved",
4789            action: "",
4790            duration: MessageDuration::Long,
4791            placement: None,
4792            offset_dp: None,
4793        };
4794        let top_end = Mutation::ShowMessage {
4795            handler_id: 0,
4796            text: "Synced",
4797            action: "",
4798            duration: MessageDuration::Short,
4799            placement: Some(MessagePlacement {
4800                vertical: MessageVertical::Top,
4801                horizontal: MessageHorizontal::End,
4802            }),
4803            offset_dp: None,
4804        };
4805        let mutations = [placed, unplaced, top_end];
4806        let mut encoder = BatchEncoder::default();
4807        for mutation in &mutations {
4808            encoder.encode(mutation).unwrap();
4809        }
4810        let bytes = encoder.finish().unwrap();
4811        let record = ENVELOPE_LEN;
4812        assert_eq!(read_u16(bytes, record).unwrap(), TAG_SHOW_MESSAGE);
4813        assert_eq!(read_u16(bytes, record + 2).unwrap(), 40);
4814        // The old fields where they always were: the handler, the duration.
4815        assert_eq!(read_u64(bytes, record + 4).unwrap(), 9);
4816        assert_eq!(read_u16(bytes, record + 28).unwrap(), 1);
4817        // Then the vertical and the horizontal tag, and the offset as an f32.
4818        assert_eq!(read_u16(bytes, record + 30).unwrap(), 2);
4819        assert_eq!(read_u16(bytes, record + 32).unwrap(), 2);
4820        assert_eq!(f32::from_bits(read_u32(bytes, record + 36).unwrap()), 96.0);
4821        // No placement is two zero tags, no offset a NaN.
4822        let second = record + 40;
4823        assert_eq!(read_u16(bytes, second + 30).unwrap(), 0);
4824        assert_eq!(read_u16(bytes, second + 32).unwrap(), 0);
4825        assert!(f32::from_bits(read_u32(bytes, second + 36).unwrap()).is_nan());
4826        assert_eq!(decode_batch(bytes).unwrap(), mutations);
4827
4828        // A placement with one half missing, or a tag this side does not know, is an
4829        // error rather than a guess.
4830        for (offset, raw) in [(30, 0_u16), (32, 0), (30, 7), (32, 9)] {
4831            let mut broken = bytes.to_vec();
4832            broken[record + offset..record + offset + 2].copy_from_slice(&raw.to_le_bytes());
4833            assert!(
4834                matches!(
4835                    decode_batch(&broken),
4836                    Err(ProtocolError::InvalidMessagePlacement(_))
4837                ),
4838                "offset {offset} set to {raw} must be refused"
4839            );
4840        }
4841    }
4842
4843    /// An importance or a presentation this side does not know is an error, never a guess
4844    /// and never a panic.
4845    #[test]
4846    fn fr36_unknown_importance_and_presentation_are_protocol_errors() {
4847        for (offset, expected) in [(52, 9_u16), (54, 7_u16)] {
4848            let mut encoder = BatchEncoder::default();
4849            encoder.encode(&post_notification()).unwrap();
4850            let mut bytes = encoder.finish().unwrap().to_vec();
4851            bytes[ENVELOPE_LEN + offset..ENVELOPE_LEN + offset + 2]
4852                .copy_from_slice(&expected.to_le_bytes());
4853            assert_eq!(
4854                decode_batch(&bytes),
4855                Err(ProtocolError::InvalidNotification(expected))
4856            );
4857        }
4858    }
4859
4860    /// A known notification tag at the wrong length is a length error, the same as any
4861    /// other known record.
4862    #[test]
4863    fn fr36_a_notification_record_of_the_wrong_length_is_rejected() {
4864        let mut bytes = vec![0, 0, 12, 0, 20, 0, 0, 0, 1, 0, 0, 0];
4865        bytes.extend_from_slice(&TAG_REQUEST_NOTIFICATION_PERMISSION.to_le_bytes());
4866        bytes.extend_from_slice(&8_u16.to_le_bytes());
4867        bytes.extend_from_slice(&0_u32.to_le_bytes());
4868        assert_eq!(
4869            decode_batch(&bytes),
4870            Err(ProtocolError::InvalidRecordLength)
4871        );
4872    }
4873
4874    /// The two notification events: a word and a string after the common head, and a word
4875    /// on its own.
4876    #[test]
4877    fn fr36_notification_events_round_trip_fixed_layout() {
4878        let activated = HostEvent {
4879            node_id: 0,
4880            handler_id: 0,
4881            payload: crate::EventPayload::NotificationActivated {
4882                action: 2,
4883                key: "session/7",
4884            },
4885        };
4886        let mut bytes = Vec::new();
4887        encode_event(&activated, &mut bytes).unwrap();
4888        assert_eq!(read_u16(&bytes, 0).unwrap(), EVENT_NOTIFICATION_ACTIVATED);
4889        assert_eq!(read_u16(&bytes, 2).unwrap(), 28);
4890        assert_eq!(bytes.len(), 28 + "session/7".len());
4891        assert_eq!(decode_event(&bytes).unwrap(), activated);
4892
4893        for state in [
4894            NotificationPermission::NotDetermined,
4895            NotificationPermission::Granted,
4896            NotificationPermission::Denied,
4897            NotificationPermission::Unsupported,
4898        ] {
4899            let changed = HostEvent {
4900                node_id: 0,
4901                handler_id: 0,
4902                payload: crate::EventPayload::NotificationPermissionChanged(state),
4903            };
4904            encode_event(&changed, &mut bytes).unwrap();
4905            assert_eq!(bytes.len(), 20);
4906            assert_eq!(decode_event(&bytes).unwrap(), changed);
4907        }
4908    }
4909
4910    /// A permission state outside the four is reported, not mapped onto one of them.
4911    #[test]
4912    fn fr36_unknown_permission_state_is_a_protocol_error() {
4913        let mut bytes = Vec::new();
4914        encode_event(
4915            &HostEvent {
4916                node_id: 0,
4917                handler_id: 0,
4918                payload: crate::EventPayload::NotificationPermissionChanged(
4919                    NotificationPermission::Granted,
4920                ),
4921            },
4922            &mut bytes,
4923        )
4924        .unwrap();
4925        bytes[16..20].copy_from_slice(&5_u32.to_le_bytes());
4926        assert_eq!(
4927            decode_event(&bytes),
4928            Err(ProtocolError::InvalidValueKind(5))
4929        );
4930    }
4931
4932    /// A notification has a body and at most two buttons, so an activation naming a third
4933    /// is a malformed event.
4934    #[test]
4935    fn fr36_an_activation_naming_a_third_button_is_a_protocol_error() {
4936        let mut bytes = Vec::new();
4937        encode_event(
4938            &HostEvent {
4939                node_id: 0,
4940                handler_id: 0,
4941                payload: crate::EventPayload::NotificationActivated {
4942                    action: 1,
4943                    key: "k",
4944                },
4945            },
4946            &mut bytes,
4947        )
4948        .unwrap();
4949        bytes[16..20].copy_from_slice(&3_u32.to_le_bytes());
4950        assert_eq!(
4951            decode_event(&bytes),
4952            Err(ProtocolError::InvalidValueKind(3))
4953        );
4954    }
4955
4956    /// How large the Renderer is drawing: two floats and a signed level after the head.
4957    #[test]
4958    fn fr43_zoom_changed_round_trips_fixed_layout() {
4959        let event = HostEvent {
4960            node_id: 0,
4961            handler_id: 0,
4962            payload: crate::EventPayload::ZoomChanged {
4963                k: 1.25 * 1.44,
4964                os: 1.25,
4965                level: 2,
4966            },
4967        };
4968        let mut bytes = Vec::new();
4969        encode_event(&event, &mut bytes).unwrap();
4970        assert_eq!(read_u16(&bytes, 0).unwrap(), 33);
4971        assert_eq!(read_u16(&bytes, 2).unwrap(), 28);
4972        assert_eq!(bytes.len(), 28);
4973        assert_eq!(decode_event(&bytes).unwrap(), event);
4974
4975        let smaller = HostEvent {
4976            node_id: 0,
4977            handler_id: 0,
4978            payload: crate::EventPayload::ZoomChanged {
4979                k: 0.5,
4980                os: 1.0,
4981                level: -4,
4982            },
4983        };
4984        encode_event(&smaller, &mut bytes).unwrap();
4985        assert_eq!(decode_event(&bytes).unwrap(), smaller);
4986    }
4987
4988    /// A level outside the range the Renderer can be at is a protocol error.
4989    #[test]
4990    fn fr43_a_zoom_level_out_of_range_is_rejected() {
4991        let event = HostEvent {
4992            node_id: 0,
4993            handler_id: 0,
4994            payload: crate::EventPayload::ZoomChanged {
4995                k: 1.0,
4996                os: 1.0,
4997                level: 9,
4998            },
4999        };
5000        let mut bytes = Vec::new();
5001        encode_event(&event, &mut bytes).unwrap();
5002        assert_eq!(
5003            decode_event(&bytes),
5004            Err(ProtocolError::InvalidValueKind(9))
5005        );
5006        bytes[2..4].copy_from_slice(&24_u16.to_le_bytes());
5007        assert_eq!(
5008            decode_event(&bytes),
5009            Err(ProtocolError::InvalidRecordLength)
5010        );
5011    }
5012
5013    /// The window record carries the application's zoom level where it asked for one, and
5014    /// a window that asked for nothing is byte for byte what it was before the level.
5015    #[test]
5016    fn fr43_the_window_record_carries_a_zoom_level() {
5017        for level in [None, Some(-8), Some(0), Some(2), Some(8)] {
5018            let mut window = crate::schema::Window::new().with_title("zoom");
5019            window.zoom_level = level;
5020            let mut encoder = BatchEncoder::default();
5021            encoder.encode(&Mutation::SetWindow(window)).unwrap();
5022            let bytes = encoder.finish().unwrap().to_vec();
5023            if level.is_none() {
5024                assert_eq!(read_u16(&bytes, ENVELOPE_LEN + 18).unwrap(), 0);
5025            }
5026            let decoded = decode_batch(&bytes).unwrap();
5027            assert_eq!(decoded, vec![Mutation::SetWindow(window)]);
5028        }
5029        assert_eq!(
5030            crate::schema::Window::new().with_zoom_level(20).zoom_level,
5031            Some(8)
5032        );
5033    }
5034
5035    /// Bit 1 of the flags word asks the implicit window for every whole-dp size change. A
5036    /// window that does not ask encodes the bytes it always did.
5037    #[test]
5038    fn fr20_8_set_window_report_size_bit_roundtrips() {
5039        for report in [false, true] {
5040            let window = crate::schema::Window::new()
5041                .with_title("size")
5042                .with_report_size(report);
5043            let mut encoder = BatchEncoder::default();
5044            encoder.encode(&Mutation::SetWindow(window)).unwrap();
5045            let bytes = encoder.finish().unwrap().to_vec();
5046            let flags = read_u16(&bytes, ENVELOPE_LEN + 16).unwrap();
5047            assert_eq!(flags, 1 | (u16::from(report) << 1));
5048            assert_eq!(
5049                decode_batch(&bytes).unwrap(),
5050                vec![Mutation::SetWindow(window)]
5051            );
5052        }
5053        // The default window, byte by byte from the record layout.
5054        let window = crate::schema::Window::new();
5055        let mut encoder = BatchEncoder::default();
5056        encoder.encode(&Mutation::SetWindow(window)).unwrap();
5057        let bytes = encoder.finish().unwrap().to_vec();
5058        let record = &bytes[ENVELOPE_LEN..];
5059        assert_eq!(record.len(), 32);
5060        assert_eq!(read_u16(record, 0).unwrap(), TAG_SET_WINDOW);
5061        assert_eq!(read_u16(record, 2).unwrap(), 32);
5062        assert_eq!(read_u16(record, 4).unwrap(), window.chrome as u16);
5063        assert_eq!(read_u16(record, 6).unwrap(), window.title_bar as u16);
5064        for at in [8, 10, 12, 14] {
5065            assert_eq!(read_u16(record, at).unwrap(), 0);
5066        }
5067        // Resizable only: the mode and the policy are the defaults for the platform.
5068        let expected_flags = 1
5069            | ((window.mode as u16) << WINDOW_MODE_SHIFT)
5070            | ((window.last_window_closed as u16) << WINDOW_POLICY_SHIFT);
5071        assert_eq!(read_u16(record, 16).unwrap(), expected_flags);
5072        assert_eq!(read_u16(record, 18).unwrap(), 0);
5073        assert_eq!(read_u32(record, 28).unwrap(), 0);
5074    }
5075
5076    /// The other low bits of the flags word are still nobody's, so a record that sets
5077    /// one is a protocol error.
5078    #[test]
5079    fn fr20_8_set_window_rejects_unknown_flag_bits() {
5080        let mut encoder = BatchEncoder::default();
5081        encoder
5082            .encode(&Mutation::SetWindow(crate::schema::Window::new()))
5083            .unwrap();
5084        let bytes = encoder.finish().unwrap().to_vec();
5085        let flags = read_u16(&bytes, ENVELOPE_LEN + 16).unwrap();
5086        for bit in 2..8 {
5087            let bad = flags | (1 << bit);
5088            let mut copy = bytes.clone();
5089            copy[ENVELOPE_LEN + 16..ENVELOPE_LEN + 18].copy_from_slice(&bad.to_le_bytes());
5090            assert_eq!(
5091                decode_batch(&copy),
5092                Err(ProtocolError::InvalidValueKind(bad)),
5093                "bit {bit}"
5094            );
5095        }
5096    }
5097
5098    #[test]
5099    fn fr65_request_focus_round_trips_in_eight_bytes() {
5100        for node_id in [0_u32, 7, u32::MAX] {
5101            let mut encoder = BatchEncoder::default();
5102            encoder.encode(&Mutation::RequestFocus { node_id }).unwrap();
5103            let bytes = encoder.finish().unwrap().to_vec();
5104            assert_eq!(bytes.len(), ENVELOPE_LEN + 8);
5105            assert_eq!(read_u16(&bytes, ENVELOPE_LEN).unwrap(), TAG_REQUEST_FOCUS);
5106            assert_eq!(read_u16(&bytes, ENVELOPE_LEN + 2).unwrap(), 8);
5107            assert_eq!(read_u32(&bytes, ENVELOPE_LEN + 4).unwrap(), node_id);
5108            assert_eq!(
5109                decode_batch(&bytes).unwrap(),
5110                vec![Mutation::RequestFocus { node_id }]
5111            );
5112        }
5113        let mut encoder = BatchEncoder::default();
5114        encoder
5115            .encode(&Mutation::RequestFocus { node_id: 7 })
5116            .unwrap();
5117        let mut bad = encoder.finish().unwrap().to_vec();
5118        bad.extend_from_slice(&[0; 4]);
5119        let records_len = u32::try_from(bad.len()).unwrap();
5120        bad[4..8].copy_from_slice(&records_len.to_le_bytes());
5121        bad[ENVELOPE_LEN + 2..ENVELOPE_LEN + 4].copy_from_slice(&12_u16.to_le_bytes());
5122        assert_eq!(decode_batch(&bad), Err(ProtocolError::InvalidRecordLength));
5123    }
5124
5125    /// The request and the result are fixed records. Both survive a round trip with
5126    /// Korean text and NUL separated lists in them, an unknown kind or status is a
5127    /// protocol error, and no prefix of either record decodes or panics.
5128    #[test]
5129    fn fr72_file_dialog_records_round_trip_and_unknown_enums_are_errors() {
5130        let filters = "이미지\0png,jpg\0Docs\0pdf,txt";
5131        for kind in [
5132            FileDialogKind::OpenFile,
5133            FileDialogKind::OpenFiles,
5134            FileDialogKind::OpenFolder,
5135            FileDialogKind::OpenFolders,
5136            FileDialogKind::Save,
5137        ] {
5138            let request = Mutation::ShowFileDialog {
5139                request: 7,
5140                window: 20,
5141                kind,
5142                default_filter: 1,
5143                title: "파일 고르기",
5144                directory: "/home/한글",
5145                name: "보고서.txt",
5146                filters,
5147            };
5148            let mut encoder = BatchEncoder::default();
5149            encoder.encode(&request).unwrap();
5150            let bytes = encoder.finish().unwrap().to_vec();
5151            assert_eq!(
5152                read_u16(&bytes, ENVELOPE_LEN).unwrap(),
5153                TAG_SHOW_FILE_DIALOG
5154            );
5155            assert_eq!(read_u16(&bytes, ENVELOPE_LEN + 2).unwrap(), 48);
5156            assert_eq!(decode_batch(&bytes).unwrap(), vec![request]);
5157        }
5158
5159        let empty = Mutation::ShowFileDialog {
5160            request: u32::MAX,
5161            window: 0,
5162            kind: FileDialogKind::Save,
5163            default_filter: 0,
5164            title: "",
5165            directory: "",
5166            name: "",
5167            filters: "",
5168        };
5169        let mut encoder = BatchEncoder::default();
5170        encoder.encode(&empty).unwrap();
5171        assert_eq!(
5172            decode_batch(encoder.finish().unwrap()).unwrap(),
5173            vec![empty]
5174        );
5175
5176        let full = Mutation::ShowFileDialog {
5177            request: 1,
5178            window: 2,
5179            kind: FileDialogKind::OpenFile,
5180            default_filter: 3,
5181            title: "t",
5182            directory: "/d",
5183            name: "n",
5184            filters,
5185        };
5186        let mut encoder = BatchEncoder::default();
5187        encoder.encode(&full).unwrap();
5188        let bytes = encoder.finish().unwrap().to_vec();
5189        for raw_kind in [0_u16, 6, 9, u16::MAX] {
5190            let mut bad = bytes.clone();
5191            bad[ENVELOPE_LEN + 12..ENVELOPE_LEN + 14].copy_from_slice(&raw_kind.to_le_bytes());
5192            assert_eq!(
5193                decode_batch(&bad),
5194                Err(ProtocolError::InvalidValueKind(raw_kind))
5195            );
5196        }
5197        let mut short = bytes.clone();
5198        short[ENVELOPE_LEN + 2..ENVELOPE_LEN + 4].copy_from_slice(&44_u16.to_le_bytes());
5199        assert_eq!(
5200            decode_batch(&short),
5201            Err(ProtocolError::InvalidRecordLength)
5202        );
5203        for cut in 0..bytes.len() {
5204            assert!(
5205                decode_batch(&bytes[..cut]).is_err(),
5206                "a batch cut at {cut} bytes decoded"
5207            );
5208        }
5209
5210        let paths = "/Users/한글/문서.txt\0/tmp/b c.png";
5211        for (status, filter) in [
5212            (FileDialogStatus::Chosen, 1_u32),
5213            (FileDialogStatus::Cancelled, u32::MAX),
5214            (FileDialogStatus::Unavailable, u32::MAX),
5215        ] {
5216            let result = HostEvent {
5217                node_id: 0,
5218                handler_id: 0,
5219                payload: crate::EventPayload::FileDialogResult {
5220                    request: 41,
5221                    status,
5222                    filter,
5223                    paths: if status == FileDialogStatus::Chosen {
5224                        paths
5225                    } else {
5226                        ""
5227                    },
5228                },
5229            };
5230            let mut bytes = Vec::new();
5231            encode_event(&result, &mut bytes).unwrap();
5232            assert_eq!(read_u16(&bytes, 0).unwrap(), EVENT_FILE_DIALOG_RESULT);
5233            assert_eq!(
5234                usize::from(read_u16(&bytes, 2).unwrap()),
5235                FILE_DIALOG_RESULT_LEN
5236            );
5237            assert_eq!(decode_event(&bytes).unwrap(), result);
5238        }
5239
5240        let result = HostEvent {
5241            node_id: 0,
5242            handler_id: 0,
5243            payload: crate::EventPayload::FileDialogResult {
5244                request: 3,
5245                status: FileDialogStatus::Chosen,
5246                filter: 0,
5247                paths,
5248            },
5249        };
5250        let mut bytes = Vec::new();
5251        encode_event(&result, &mut bytes).unwrap();
5252        for raw_status in [0_u32, 4, 0x1_0000, u32::MAX] {
5253            let mut bad = bytes.clone();
5254            bad[20..24].copy_from_slice(&raw_status.to_le_bytes());
5255            assert_eq!(
5256                decode_event(&bad),
5257                Err(ProtocolError::InvalidValueKind(
5258                    raw_status.min(u32::from(u16::MAX)) as u16
5259                ))
5260            );
5261        }
5262        let mut wrong_length = bytes.clone();
5263        wrong_length[2..4].copy_from_slice(&32_u16.to_le_bytes());
5264        assert_eq!(
5265            decode_event(&wrong_length),
5266            Err(ProtocolError::InvalidRecordLength)
5267        );
5268        let mut not_utf8 = bytes.clone();
5269        let last = not_utf8.len() - 1;
5270        not_utf8[last] = 0xFF;
5271        assert_eq!(decode_event(&not_utf8), Err(ProtocolError::InvalidUtf8));
5272        for cut in 0..bytes.len() {
5273            assert!(
5274                decode_event(&bytes[..cut]).is_err(),
5275                "an event cut at {cut} bytes decoded"
5276            );
5277        }
5278    }
5279
5280    #[test]
5281    fn fr65_text_field_on_composition_change_delivers_bool() {
5282        use std::cell::RefCell;
5283        use std::rc::Rc;
5284        use std::sync::Arc;
5285        use std::sync::atomic::{AtomicUsize, Ordering};
5286
5287        let seen: Rc<RefCell<Vec<bool>>> = Rc::new(RefCell::new(Vec::new()));
5288        let calls = Arc::new(AtomicUsize::new(0));
5289        let calls_for_root = Arc::clone(&calls);
5290        let mut host = crate::ComposeHost::with_content(move || {
5291            let calls_inner = Arc::clone(&calls_for_root);
5292            crate::ui::TextField().on_composition_change(move |composing| {
5293                calls_inner.fetch_add(if composing { 10 } else { 1 }, Ordering::SeqCst);
5294            });
5295        });
5296        let init = host.rebuild().unwrap().to_vec();
5297        let mutations = decode_batch(&init).unwrap();
5298        let prop = mutations
5299            .iter()
5300            .find_map(|mutation| match mutation {
5301                Mutation::SetProp {
5302                    node_id,
5303                    property: PropertyKind::OnCompositionChange,
5304                    value: PropertyValue::Integer(handler),
5305                } => Some((*node_id, *handler as u64)),
5306                _ => None,
5307            })
5308            .expect("TextField with on_composition_change must emit OnCompositionChange");
5309        let mut wire = Vec::new();
5310        encode_event(
5311            &HostEvent {
5312                node_id: prop.0,
5313                handler_id: prop.1,
5314                payload: crate::EventPayload::CompositionChanged { composing: true },
5315            },
5316            &mut wire,
5317        )
5318        .unwrap();
5319        host.dispatch_event(&wire).unwrap();
5320        encode_event(
5321            &HostEvent {
5322                node_id: prop.0,
5323                handler_id: prop.1,
5324                payload: crate::EventPayload::CompositionChanged { composing: false },
5325            },
5326            &mut wire,
5327        )
5328        .unwrap();
5329        host.dispatch_event(&wire).unwrap();
5330        assert_eq!(calls.load(Ordering::SeqCst), 11);
5331        drop(seen);
5332    }
5333
5334    #[test]
5335    fn fr45_focus_gained_and_lost_pair() {
5336        use std::sync::Arc;
5337        use std::sync::Mutex;
5338
5339        let trace: Arc<Mutex<Vec<&'static str>>> = Arc::new(Mutex::new(Vec::new()));
5340        let trace_for_root = Arc::clone(&trace);
5341        let mut host = crate::ComposeHost::with_content(move || {
5342            let gained_trace = Arc::clone(&trace_for_root);
5343            let lost_trace = Arc::clone(&trace_for_root);
5344            crate::ui::TextField()
5345                .on_focus_gained(move || {
5346                    gained_trace.lock().unwrap().push("gained");
5347                })
5348                .on_focus_lost(move || {
5349                    lost_trace.lock().unwrap().push("lost");
5350                });
5351        });
5352        let init = host.rebuild().unwrap().to_vec();
5353        let mutations = decode_batch(&init).unwrap();
5354        let gained_prop = mutations
5355            .iter()
5356            .find_map(|mutation| match mutation {
5357                Mutation::SetProp {
5358                    node_id,
5359                    property: PropertyKind::OnFocusGained,
5360                    value: PropertyValue::Integer(handler),
5361                } => Some((*node_id, *handler as u64)),
5362                _ => None,
5363            })
5364            .expect("TextField with on_focus_gained must emit OnFocusGained");
5365        let lost_prop = mutations
5366            .iter()
5367            .find_map(|mutation| match mutation {
5368                Mutation::SetProp {
5369                    node_id,
5370                    property: PropertyKind::OnFocusLost,
5371                    value: PropertyValue::Integer(handler),
5372                } => Some((*node_id, *handler as u64)),
5373                _ => None,
5374            })
5375            .expect("TextField with on_focus_lost must emit OnFocusLost");
5376        assert_eq!(gained_prop.0, lost_prop.0);
5377        assert_eq!(PropertyKind::OnFocusGained as u16, 117);
5378
5379        let gained_event = HostEvent {
5380            node_id: gained_prop.0,
5381            handler_id: gained_prop.1,
5382            payload: crate::EventPayload::FocusGained,
5383        };
5384        let mut wire = Vec::new();
5385        encode_event(&gained_event, &mut wire).unwrap();
5386        assert_eq!(wire.len(), 16);
5387        assert_eq!(read_u16(&wire, 0).unwrap(), EVENT_FOCUS_GAINED);
5388        assert_eq!(EVENT_FOCUS_GAINED, 48);
5389        assert_eq!(decode_event(&wire).unwrap(), gained_event);
5390        host.dispatch_event(&wire).unwrap();
5391
5392        let lost_event = HostEvent {
5393            node_id: lost_prop.0,
5394            handler_id: lost_prop.1,
5395            payload: crate::EventPayload::FocusLost,
5396        };
5397        encode_event(&lost_event, &mut wire).unwrap();
5398        assert_eq!(decode_event(&wire).unwrap(), lost_event);
5399        host.dispatch_event(&wire).unwrap();
5400
5401        assert_eq!(*trace.lock().unwrap(), vec!["gained", "lost"]);
5402    }
5403
5404    #[test]
5405    fn fr45_key_up_follows_key_down() {
5406        use std::sync::Arc;
5407        use std::sync::Mutex;
5408
5409        // What each key event carried: which handler, the key, then the four modifiers.
5410        type KeyTrace = Vec<(&'static str, Key, bool, bool, bool, bool)>;
5411        let trace: Arc<Mutex<KeyTrace>> = Arc::new(Mutex::new(Vec::new()));
5412        let trace_for_root = Arc::clone(&trace);
5413        let mut host = crate::ComposeHost::with_content(move || {
5414            let down_trace = Arc::clone(&trace_for_root);
5415            let up_trace = Arc::clone(&trace_for_root);
5416            crate::ui::TextField()
5417                .on_key_down(move |event| {
5418                    down_trace.lock().unwrap().push((
5419                        "down",
5420                        event.key(),
5421                        event.shift_key(),
5422                        event.ctrl_key(),
5423                        event.alt_key(),
5424                        event.meta_key(),
5425                    ));
5426                })
5427                .on_key_up(move |event| {
5428                    up_trace.lock().unwrap().push((
5429                        "up",
5430                        event.key(),
5431                        event.shift_key(),
5432                        event.ctrl_key(),
5433                        event.alt_key(),
5434                        event.meta_key(),
5435                    ));
5436                });
5437        });
5438        let init = host.rebuild().unwrap().to_vec();
5439        let mutations = decode_batch(&init).unwrap();
5440        let down_prop = mutations
5441            .iter()
5442            .find_map(|mutation| match mutation {
5443                Mutation::SetProp {
5444                    node_id,
5445                    property: PropertyKind::OnKeyDown,
5446                    value: PropertyValue::Integer(handler),
5447                } => Some((*node_id, *handler as u64)),
5448                _ => None,
5449            })
5450            .expect("TextField with on_key_down must emit OnKeyDown");
5451        let up_prop = mutations
5452            .iter()
5453            .find_map(|mutation| match mutation {
5454                Mutation::SetProp {
5455                    node_id,
5456                    property: PropertyKind::OnKeyUp,
5457                    value: PropertyValue::Integer(handler),
5458                } => Some((*node_id, *handler as u64)),
5459                _ => None,
5460            })
5461            .expect("TextField with on_key_up must emit OnKeyUp");
5462        assert_eq!(down_prop.0, up_prop.0);
5463        assert_eq!(PropertyKind::OnKeyUp as u16, 118);
5464
5465        let down_event = HostEvent {
5466            node_id: down_prop.0,
5467            handler_id: down_prop.1,
5468            payload: crate::EventPayload::KeyDown {
5469                key: Key::Enter,
5470                shift_key: true,
5471                ctrl_key: false,
5472                alt_key: true,
5473                meta_key: false,
5474                repeat: false,
5475                code: 0x28,
5476                text: "Enter",
5477            },
5478        };
5479        let mut wire = Vec::new();
5480        encode_event(&down_event, &mut wire).unwrap();
5481        assert_eq!(decode_event(&wire).unwrap(), down_event);
5482        host.dispatch_event(&wire).unwrap();
5483
5484        let up_event = HostEvent {
5485            node_id: up_prop.0,
5486            handler_id: up_prop.1,
5487            payload: crate::EventPayload::KeyUp {
5488                key: Key::Enter,
5489                shift_key: true,
5490                ctrl_key: false,
5491                alt_key: true,
5492                meta_key: false,
5493                repeat: false,
5494                code: 0x28,
5495                text: "Enter",
5496            },
5497        };
5498        encode_event(&up_event, &mut wire).unwrap();
5499        assert_eq!(wire.len(), 37);
5500        assert_eq!(read_u16(&wire, 0).unwrap(), EVENT_KEY_UP);
5501        assert_eq!(EVENT_KEY_UP, 49);
5502        assert_eq!(decode_event(&wire).unwrap(), up_event);
5503        host.dispatch_event(&wire).unwrap();
5504
5505        assert_eq!(
5506            *trace.lock().unwrap(),
5507            vec![
5508                ("down", Key::Enter, true, false, true, false),
5509                ("up", Key::Enter, true, false, true, false),
5510            ]
5511        );
5512    }
5513
5514    #[test]
5515    fn fr45_unregistered_nodes_get_no_events() {
5516        let mut host = crate::ComposeHost::with_content(|| {
5517            crate::ui::TextField();
5518            crate::ui::Box().content(|| {});
5519        });
5520        let init = host.rebuild().unwrap().to_vec();
5521        let mutations = decode_batch(&init).unwrap();
5522        for mutation in &mutations {
5523            if let Mutation::SetProp { property, .. } = mutation {
5524                assert_ne!(
5525                    *property,
5526                    PropertyKind::OnFocusGained,
5527                    "unregistered node must not emit OnFocusGained"
5528                );
5529                assert_ne!(
5530                    *property,
5531                    PropertyKind::OnKeyUp,
5532                    "unregistered node must not emit OnKeyUp"
5533                );
5534            }
5535        }
5536    }
5537
5538    /// The keys menus, lists and overlays act on have their own name, appended after
5539    /// `Other` so no earlier tag moves, and each one survives the wire.
5540    #[test]
5541    fn fr12_named_keys_are_appended_and_round_trip() {
5542        let named = [
5543            (Key::Enter, 1u16, 0x28u32, "Enter"),
5544            (Key::Other, 2, 0x04, "a"),
5545            (Key::Escape, 3, 0x29, "Escape"),
5546            (Key::Tab, 4, 0x2B, "Tab"),
5547            (Key::Backspace, 5, 0x2A, "Backspace"),
5548            (Key::Delete, 6, 0x4C, "Delete"),
5549            (Key::ArrowUp, 7, 0x52, "ArrowUp"),
5550            (Key::ArrowDown, 8, 0x51, "ArrowDown"),
5551            (Key::ArrowLeft, 9, 0x50, "ArrowLeft"),
5552            (Key::ArrowRight, 10, 0x4F, "ArrowRight"),
5553            (Key::Home, 11, 0x4A, "Home"),
5554            (Key::End, 12, 0x4D, "End"),
5555            (Key::PageUp, 13, 0x4B, "PageUp"),
5556            (Key::PageDown, 14, 0x4E, "PageDown"),
5557        ];
5558        let mut wire = Vec::new();
5559        for (key, tag, code, text) in named {
5560            assert_eq!(Key::try_from(tag), Ok(key), "tag {tag} names {text}");
5561            let event = HostEvent {
5562                node_id: 4,
5563                handler_id: 9,
5564                payload: crate::EventPayload::KeyDown {
5565                    key,
5566                    shift_key: false,
5567                    ctrl_key: false,
5568                    alt_key: false,
5569                    meta_key: false,
5570                    repeat: false,
5571                    code,
5572                    text,
5573                },
5574            };
5575            encode_event(&event, &mut wire).unwrap();
5576            assert_eq!(read_u16(&wire, 16).unwrap(), tag);
5577            assert_eq!(decode_event(&wire).unwrap(), event);
5578        }
5579        assert_eq!(Key::try_from(15), Ok(Key::F1));
5580    }
5581
5582    /// The function keys and the menu key have their own name after `PageDown`, so no
5583    /// earlier tag moves. Shift+F10, the other way to open a context menu, is `F10` with
5584    /// Shift held rather than a key of its own.
5585    #[test]
5586    fn fr12_function_and_context_menu_keys() {
5587        let functions = [
5588            Key::F1,
5589            Key::F2,
5590            Key::F3,
5591            Key::F4,
5592            Key::F5,
5593            Key::F6,
5594            Key::F7,
5595            Key::F8,
5596            Key::F9,
5597            Key::F10,
5598            Key::F11,
5599            Key::F12,
5600        ];
5601        for (index, key) in functions.into_iter().enumerate() {
5602            assert_eq!(Key::try_from(15 + index as u16), Ok(key), "F{}", index + 1);
5603        }
5604        assert_eq!(Key::try_from(27), Ok(Key::ContextMenu));
5605        assert_eq!(Key::try_from(28), Err(()));
5606
5607        let presses = [
5608            (Key::F2, 16u16, false, 0x3Bu32, "F2"),
5609            (Key::F12, 26, false, 0x45, "F12"),
5610            (Key::F10, 24, true, 0x43, "F10"),
5611            (Key::ContextMenu, 27, false, 0x65, "ContextMenu"),
5612        ];
5613        let mut wire = Vec::new();
5614        for (key, tag, shift_key, code, text) in presses {
5615            let event = HostEvent {
5616                node_id: 4,
5617                handler_id: 9,
5618                payload: crate::EventPayload::KeyDown {
5619                    key,
5620                    shift_key,
5621                    ctrl_key: false,
5622                    alt_key: false,
5623                    meta_key: false,
5624                    repeat: false,
5625                    code,
5626                    text,
5627                },
5628            };
5629            encode_event(&event, &mut wire).unwrap();
5630            assert_eq!(read_u16(&wire, 16).unwrap(), tag, "{text}");
5631            assert_eq!(decode_event(&wire).unwrap(), event);
5632        }
5633    }
5634
5635    /// A drawer or a popup menu is a container, not a `Dialog` or a `Sheet`, so the
5636    /// Renderer does not dismiss it. Its own `on_key_down` sees Escape by its DOM key
5637    /// string and HID usage, and consuming it is the call's result.
5638    #[test]
5639    fn fr45_container_key_down_sees_escape_and_consumes_it() {
5640        use std::sync::{Arc, Mutex};
5641
5642        let seen: Arc<Mutex<Vec<(String, u32)>>> = Arc::new(Mutex::new(Vec::new()));
5643        let seen_for_root = Arc::clone(&seen);
5644        let mut host = crate::ComposeHost::with_content(move || {
5645            let seen = Arc::clone(&seen_for_root);
5646            crate::ui::Column()
5647                .on_key_down(move |event| {
5648                    seen.lock()
5649                        .unwrap()
5650                        .push((event.text().to_owned(), event.code()));
5651                    if event.text() == "Escape" {
5652                        event.consume();
5653                    }
5654                })
5655                .content(|| {
5656                    crate::ui::Text("session list");
5657                });
5658        });
5659        let init = host.rebuild().unwrap().to_vec();
5660        let mutations = decode_batch(&init).unwrap();
5661        let (node_id, handler_id) = mutations
5662            .iter()
5663            .find_map(|mutation| match mutation {
5664                Mutation::SetProp {
5665                    node_id,
5666                    property: PropertyKind::OnKeyDown,
5667                    value: PropertyValue::Integer(handler),
5668                } => Some((*node_id, *handler as u64)),
5669                _ => None,
5670            })
5671            .expect("a Column with on_key_down must emit OnKeyDown");
5672        let created_column = mutations.iter().any(|mutation| {
5673            matches!(
5674                mutation,
5675                Mutation::Create { node_id: id, widget: crate::WidgetKind::Column, .. } if *id == node_id
5676            )
5677        });
5678        assert!(
5679            created_column,
5680            "the key handler belongs to the Column itself"
5681        );
5682
5683        let mut wire = Vec::new();
5684        let mut press = |code: u32, text: &'static str| {
5685            encode_event(
5686                &HostEvent {
5687                    node_id,
5688                    handler_id,
5689                    payload: crate::EventPayload::KeyDown {
5690                        key: if code == 0x29 {
5691                            Key::Escape
5692                        } else {
5693                            Key::ArrowDown
5694                        },
5695                        shift_key: false,
5696                        ctrl_key: false,
5697                        alt_key: false,
5698                        meta_key: false,
5699                        repeat: false,
5700                        code,
5701                        text,
5702                    },
5703                },
5704                &mut wire,
5705            )
5706            .unwrap();
5707            host.dispatch_event(&wire).unwrap().1
5708        };
5709        assert_ne!(
5710            press(0x29, "Escape"),
5711            0,
5712            "Escape was consumed by the container"
5713        );
5714        assert_eq!(
5715            press(0x51, "ArrowDown"),
5716            0,
5717            "an unhandled key is left to the Renderer"
5718        );
5719
5720        assert_eq!(
5721            *seen.lock().unwrap(),
5722            vec![("Escape".to_owned(), 0x29), ("ArrowDown".to_owned(), 0x51)]
5723        );
5724    }
5725}