icedwright-protocol 0.1.0

Wire types for icedwright: the raw semantic tree a live app records and the typed remote protocol
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
//! Requests, their responses, the envelopes they travel in, and notifications.
//!
//! Every request type is listed once, in the `requests!` invocation below, which generates its
//! [`Request`] impl, [`METHODS`], [`AnyRequest`] and [`AnyResponse`], and a `const` assertion
//! that no two requests share a method name.

use std::borrow::Cow;

use icedwright_types::{CursorSeen, Rect, ScaleFactor};
use serde::de::DeserializeOwned;
use serde::{Deserialize, Deserializer, Serialize, Serializer};

use crate::error::ErrorBody;
use crate::event::{WireEvent, WireStatus};
use crate::ids::{
    FrameCount, Generation, RequestId, WindowOrdinal, WireDuration, WireRuleId, WireTaskId,
};
use crate::raw::{RawTree, RawWindowInfo};

mod sealed {
    pub trait Sealed {}
}

/// A request type, tied to its response type and method name, so a client cannot send one
/// request and read another's answer. Sealed: the list of requests is this crate's.
pub trait Request: Serialize + DeserializeOwned + sealed::Sealed {
    /// What the peer answers with.
    type Response: Serialize + DeserializeOwned;
    /// The method name on the wire.
    const METHOD: &'static str;
}

/// The response to requests that only succeed or fail. Serialises as `null`.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Done;

/// The first request on a connection.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct Hello {
    /// The client's [`crate::PROTOCOL`].
    pub protocol: (u16, u16),
    /// The client's name and version.
    pub client: String,
    /// Whether the client wants uncaptured keys sent through the OS.
    #[serde(default)]
    pub os_keyboard: bool,
}

/// The answer to [`Hello`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Welcome {
    /// The probe's [`crate::PROTOCOL`].
    pub protocol: (u16, u16),
    /// The app's name.
    pub app: String,
    /// The app's process id.
    pub pid: u32,
    /// The iced version the app was built with.
    pub iced: String,
    /// Whether the probe's `semantics` feature is on.
    pub semantics: bool,
    /// The windows open now.
    #[serde(default)]
    pub windows: Vec<RawWindowInfo>,
}

/// Asks for the raw tree. With `after`, a long poll answered once the generation passes it.
#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Snapshot {
    /// Answer only once the generation is greater than this.
    #[serde(default)]
    pub after: Option<Generation>,
    /// How long the probe may hold the request before answering `Unchanged`.
    #[serde(default)]
    pub wait: Option<WireDuration>,
}

/// The answer to [`Snapshot`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum SnapshotReply {
    /// The tree as of a generation.
    Tree {
        /// The generation it was recorded at.
        generation: Generation,
        /// The frame count then.
        frame: FrameCount,
        /// Every window.
        tree: RawTree,
    },
    /// The generation did not pass `after` before the wait ended.
    Unchanged,
}

/// What the client decided on before sending a guarded input.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Guard {
    /// The generation of the tree it looked at.
    pub generation: Generation,
    /// The target's node path, in `NodePath`'s `Display` form.
    pub path: String,
    /// The target's bounds then.
    pub bounds: Rect,
}

/// Input events for one window.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Input {
    /// The window.
    pub window: WindowOrdinal,
    /// The events, applied in order.
    pub events: Vec<WireEvent>,
    /// When set, the probe answers `stale` if the node moved since.
    #[serde(default)]
    pub guard: Option<Guard>,
}

/// The cursor kind one layer was handed during a delivery.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct CursorReading {
    /// 0 for the base layer, then the overlay depth.
    pub layer: u16,
    /// What that layer was handed.
    pub seen: CursorSeen,
}

/// The answer to [`Input`].
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Delivered {
    /// The window.
    pub window: WindowOrdinal,
    /// The generation after delivery.
    pub generation: Generation,
    /// One status per event.
    pub statuses: Vec<WireStatus>,
    /// The cursor each layer was handed, for the covered-target check.
    #[serde(default)]
    pub cursors: Vec<CursorReading>,
}

/// Asks for a window's pixels.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Screenshot {
    /// The window.
    pub window: WindowOrdinal,
}

/// The answer to [`Screenshot`]; the RGBA bytes follow as an attachment.
#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
pub struct ScreenshotHeader {
    /// The window.
    pub window: WindowOrdinal,
    /// Width in physical pixels.
    pub width: u32,
    /// Height in physical pixels.
    pub height: u32,
    /// The scale factor it was drawn at.
    pub scale_factor: ScaleFactor,
}

/// Asks for the open windows.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Windows;

/// The answer to [`Windows`].
#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
pub struct WindowList {
    /// The windows open now.
    pub windows: Vec<RawWindowInfo>,
}

/// Asks the probe to give a window focus.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Focus {
    /// The window.
    pub window: WindowOrdinal,
}

/// Takes control of a window's input; real input is dropped while held.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Drive {
    /// The window.
    pub window: WindowOrdinal,
    /// Whether real pointer events are dropped.
    #[serde(default)]
    pub exclusive_pointer: bool,
}

/// Gives a window's input back.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Release {
    /// The window.
    pub window: WindowOrdinal,
}

/// Turns the inspector's pick mode on or off; picks arrive as `Hovered` notifications.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Inspect {
    /// The window.
    pub window: WindowOrdinal,
    /// On or off.
    pub on: bool,
}

/// Turns recording of real events on or off; they arrive as `Observed` notifications.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct Record {
    /// On or off.
    pub on: bool,
}

/// Holds every task of a name until released.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct HoldTask {
    /// The task name, `TaskName::NAME`.
    pub name: String,
}

/// Removes a rule.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub struct RemoveRule {
    /// The rule.
    pub rule: WireRuleId,
}

/// Waits for the next task of a name.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct NextTask {
    /// The task name.
    pub name: String,
    /// How long the probe may wait.
    #[serde(default)]
    pub wait: Option<WireDuration>,
}

/// Lets a held task run.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ReleaseTask {
    /// The task name.
    pub name: String,
    /// The task.
    pub task: WireTaskId,
}

/// What a resolved task completes with, as JSON text the probe deserialises into the task's
/// output type.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskOutput {
    /// The task's whole output.
    Value(String),
    /// The error of a task whose output is a `Result`.
    Error(String),
}

/// Completes a held task without running it.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
pub struct ResolveTask {
    /// The task name.
    pub name: String,
    /// The task.
    pub task: WireTaskId,
    /// What it completes with.
    pub output: TaskOutput,
}

/// Answered once no named task is in flight and the probe has no input, collection or
/// guarded request outstanding.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct WaitIdle {
    /// How long the probe may hold the request.
    #[serde(default)]
    pub wait: Option<WireDuration>,
}

/// Ends the session; the probe releases every window and rule the client held.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
pub struct Bye;

macro_rules! requests {
    ($($(#[doc = $doc:literal])* $ty:ident => $response:ty, $method:literal;)+) => {
        $(
            impl sealed::Sealed for $ty {}
            impl Request for $ty {
                type Response = $response;
                const METHOD: &'static str = $method;
            }
        )+

        /// Every method name, in declaration order.
        pub const METHODS: &[&str] = &[$($method),+];

        const _: () = assert!(
            crate::__private::methods_unique(METHODS),
            "two requests share a METHOD"
        );

        /// Any request, for the probe's dispatch. A match on it is exhaustive, so a request
        /// cannot be added without a handler.
        #[derive(Debug, Clone, PartialEq)]
        #[non_exhaustive]
        pub enum AnyRequest {
            $($(#[doc = $doc])* $ty($ty),)+
        }

        impl AnyRequest {
            /// The request's method name.
            #[must_use]
            pub fn method(&self) -> &'static str {
                match self {
                    $(AnyRequest::$ty(_) => <$ty as Request>::METHOD,)+
                }
            }

            /// Reads `params` as the request `method` names, or `Ok(None)` when no request
            /// has that name.
            pub fn from_params<'de, D: Deserializer<'de>>(
                method: &str,
                params: D,
            ) -> Result<Option<AnyRequest>, D::Error> {
                match method {
                    $($method => <$ty>::deserialize(params).map(|r| Some(AnyRequest::$ty(r))),)+
                    _ => Ok(None),
                }
            }
        }

        /// The response to any request, named by the request it answers. Serialises as the
        /// response itself.
        #[derive(Debug, Clone, PartialEq)]
        #[non_exhaustive]
        pub enum AnyResponse {
            $($(#[doc = $doc])* $ty($response),)+
        }

        impl AnyResponse {
            /// The method of the request this answers.
            #[must_use]
            pub fn method(&self) -> &'static str {
                match self {
                    $(AnyResponse::$ty(_) => <$ty as Request>::METHOD,)+
                }
            }
        }

        impl Serialize for AnyResponse {
            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
                match self {
                    $(AnyResponse::$ty(response) => response.serialize(serializer),)+
                }
            }
        }
    };
}

requests! {
    /// The handshake.
    Hello => Welcome, "hello";
    /// The raw tree.
    Snapshot => SnapshotReply, "snapshot";
    /// Input events.
    Input => Delivered, "input";
    /// A window's pixels.
    Screenshot => ScreenshotHeader, "screenshot";
    /// The open windows.
    Windows => WindowList, "windows";
    /// Focus a window.
    Focus => Done, "focus";
    /// Take a window's input.
    Drive => Done, "drive";
    /// Give a window's input back.
    Release => Done, "release";
    /// Pick mode.
    Inspect => Done, "inspect";
    /// Recording.
    Record => Done, "record";
    /// Hold tasks of a name.
    HoldTask => WireRuleId, "hold_task";
    /// Remove a rule.
    RemoveRule => Done, "remove_rule";
    /// The next task of a name.
    NextTask => WireTaskId, "next_task";
    /// Let a task run.
    ReleaseTask => Done, "release_task";
    /// Complete a task.
    ResolveTask => Done, "resolve_task";
    /// Wait until the app is idle.
    WaitIdle => Done, "wait_idle";
    /// End the session.
    Bye => Done, "bye";
}

/// A request in its envelope. Built with [`Call::new`], which takes the method from the
/// request type.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Call<R> {
    /// Chosen by the client.
    pub id: RequestId,
    /// The request's method.
    pub method: Cow<'static, str>,
    /// The request.
    pub params: R,
}

impl<R: Request> Call<R> {
    /// The envelope for `params`.
    #[must_use]
    pub fn new(id: RequestId, params: R) -> Self {
        Self {
            id,
            method: Cow::Borrowed(R::METHOD),
            params,
        }
    }
}

/// A reply in its envelope: `{ "id": n, "result": .. }` or `{ "id": n, "error": .. }`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Reply<T> {
    /// The request's id.
    pub id: RequestId,
    /// The answer.
    #[serde(flatten)]
    pub body: ReplyBody<T>,
}

/// A result or an error.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ReplyBody<T> {
    /// The response.
    Result(T),
    /// What went wrong.
    Error(ErrorBody),
}

impl<T> ReplyBody<T> {
    /// The response, or the error as a [`crate::ProtocolError`].
    pub fn into_result(self) -> Result<T, crate::ProtocolError> {
        match self {
            ReplyBody::Result(value) => Ok(value),
            ReplyBody::Error(body) => Err(body.into()),
        }
    }
}

/// What a named task did.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum TaskChange {
    /// It started.
    Started,
    /// A rule held it.
    Held,
    /// It was released.
    Released,
    /// The client completed it.
    Resolved,
    /// It finished by itself.
    Finished,
    /// It failed.
    Failed {
        /// The error's `Display` text.
        error: String,
    },
}

/// What the probe pushes unasked. Notifications carry `event` and no `id`.
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(tag = "event", content = "data", rename_all = "snake_case")]
pub enum Notification {
    /// The generation or frame count rose.
    Generation {
        /// The generation now.
        generation: Generation,
        /// The frame count now.
        frame: FrameCount,
    },
    /// The node under the real pointer in pick mode.
    Hovered {
        /// Its raw path: the window index, then each child index, joined by `.`, as
        /// `SemanticTree::by_raw` takes it. The probe has no inference to name a node path.
        path: String,
        /// The tree it was found in.
        tree: RawTree,
        /// Whether the user clicked it, which picks it.
        #[serde(default)]
        picked: bool,
    },
    /// A real event, while recording.
    Observed {
        /// The generation it arrived at.
        generation: Generation,
        /// The window.
        window: WindowOrdinal,
        /// The event.
        event: WireEvent,
        /// What the widgets did with it.
        status: WireStatus,
    },
    /// A named task changed.
    Task {
        /// The task name.
        name: String,
        /// The task.
        task: WireTaskId,
        /// What happened.
        change: TaskChange,
    },
    /// A window opened.
    WindowOpened(RawWindowInfo),
    /// A window closed.
    WindowClosed {
        /// The window.
        window: WindowOrdinal,
    },
}