Skip to main content

icedwright_protocol/
request.rs

1//! Requests, their responses, the envelopes they travel in, and notifications.
2//!
3//! Every request type is listed once, in the `requests!` invocation below, which generates its
4//! [`Request`] impl, [`METHODS`], [`AnyRequest`] and [`AnyResponse`], and a `const` assertion
5//! that no two requests share a method name.
6
7use std::borrow::Cow;
8
9use icedwright_types::{CursorSeen, Rect, ScaleFactor};
10use serde::de::DeserializeOwned;
11use serde::{Deserialize, Deserializer, Serialize, Serializer};
12
13use crate::error::ErrorBody;
14use crate::event::{WireEvent, WireStatus};
15use crate::ids::{
16    FrameCount, Generation, RequestId, WindowOrdinal, WireDuration, WireRuleId, WireTaskId,
17};
18use crate::raw::{RawTree, RawWindowInfo};
19
20mod sealed {
21    pub trait Sealed {}
22}
23
24/// A request type, tied to its response type and method name, so a client cannot send one
25/// request and read another's answer. Sealed: the list of requests is this crate's.
26pub trait Request: Serialize + DeserializeOwned + sealed::Sealed {
27    /// What the peer answers with.
28    type Response: Serialize + DeserializeOwned;
29    /// The method name on the wire.
30    const METHOD: &'static str;
31}
32
33/// The response to requests that only succeed or fail. Serialises as `null`.
34#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
35pub struct Done;
36
37/// The first request on a connection.
38#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
39pub struct Hello {
40    /// The client's [`crate::PROTOCOL`].
41    pub protocol: (u16, u16),
42    /// The client's name and version.
43    pub client: String,
44    /// Whether the client wants uncaptured keys sent through the OS.
45    #[serde(default)]
46    pub os_keyboard: bool,
47}
48
49/// The answer to [`Hello`].
50#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
51pub struct Welcome {
52    /// The probe's [`crate::PROTOCOL`].
53    pub protocol: (u16, u16),
54    /// The app's name.
55    pub app: String,
56    /// The app's process id.
57    pub pid: u32,
58    /// The iced version the app was built with.
59    pub iced: String,
60    /// Whether the probe's `semantics` feature is on.
61    pub semantics: bool,
62    /// The windows open now.
63    #[serde(default)]
64    pub windows: Vec<RawWindowInfo>,
65}
66
67/// Asks for the raw tree. With `after`, a long poll answered once the generation passes it.
68#[derive(Debug, Clone, PartialEq, Eq, Default, Serialize, Deserialize)]
69pub struct Snapshot {
70    /// Answer only once the generation is greater than this.
71    #[serde(default)]
72    pub after: Option<Generation>,
73    /// How long the probe may hold the request before answering `Unchanged`.
74    #[serde(default)]
75    pub wait: Option<WireDuration>,
76}
77
78/// The answer to [`Snapshot`].
79#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
80#[serde(rename_all = "snake_case")]
81pub enum SnapshotReply {
82    /// The tree as of a generation.
83    Tree {
84        /// The generation it was recorded at.
85        generation: Generation,
86        /// The frame count then.
87        frame: FrameCount,
88        /// Every window.
89        tree: RawTree,
90    },
91    /// The generation did not pass `after` before the wait ended.
92    Unchanged,
93}
94
95/// What the client decided on before sending a guarded input.
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97pub struct Guard {
98    /// The generation of the tree it looked at.
99    pub generation: Generation,
100    /// The target's node path, in `NodePath`'s `Display` form.
101    pub path: String,
102    /// The target's bounds then.
103    pub bounds: Rect,
104}
105
106/// Input events for one window.
107#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
108pub struct Input {
109    /// The window.
110    pub window: WindowOrdinal,
111    /// The events, applied in order.
112    pub events: Vec<WireEvent>,
113    /// When set, the probe answers `stale` if the node moved since.
114    #[serde(default)]
115    pub guard: Option<Guard>,
116}
117
118/// The cursor kind one layer was handed during a delivery.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
120pub struct CursorReading {
121    /// 0 for the base layer, then the overlay depth.
122    pub layer: u16,
123    /// What that layer was handed.
124    pub seen: CursorSeen,
125}
126
127/// The answer to [`Input`].
128#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
129pub struct Delivered {
130    /// The window.
131    pub window: WindowOrdinal,
132    /// The generation after delivery.
133    pub generation: Generation,
134    /// One status per event.
135    pub statuses: Vec<WireStatus>,
136    /// The cursor each layer was handed, for the covered-target check.
137    #[serde(default)]
138    pub cursors: Vec<CursorReading>,
139}
140
141/// Asks for a window's pixels.
142#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
143pub struct Screenshot {
144    /// The window.
145    pub window: WindowOrdinal,
146}
147
148/// The answer to [`Screenshot`]; the RGBA bytes follow as an attachment.
149#[derive(Debug, Clone, Copy, PartialEq, Serialize, Deserialize)]
150pub struct ScreenshotHeader {
151    /// The window.
152    pub window: WindowOrdinal,
153    /// Width in physical pixels.
154    pub width: u32,
155    /// Height in physical pixels.
156    pub height: u32,
157    /// The scale factor it was drawn at.
158    pub scale_factor: ScaleFactor,
159}
160
161/// Asks for the open windows.
162#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
163pub struct Windows;
164
165/// The answer to [`Windows`].
166#[derive(Debug, Clone, PartialEq, Default, Serialize, Deserialize)]
167pub struct WindowList {
168    /// The windows open now.
169    pub windows: Vec<RawWindowInfo>,
170}
171
172/// Asks the probe to give a window focus.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
174pub struct Focus {
175    /// The window.
176    pub window: WindowOrdinal,
177}
178
179/// Takes control of a window's input; real input is dropped while held.
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
181pub struct Drive {
182    /// The window.
183    pub window: WindowOrdinal,
184    /// Whether real pointer events are dropped.
185    #[serde(default)]
186    pub exclusive_pointer: bool,
187}
188
189/// Gives a window's input back.
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
191pub struct Release {
192    /// The window.
193    pub window: WindowOrdinal,
194}
195
196/// Turns the inspector's pick mode on or off; picks arrive as `Hovered` notifications.
197#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
198pub struct Inspect {
199    /// The window.
200    pub window: WindowOrdinal,
201    /// On or off.
202    pub on: bool,
203}
204
205/// Turns recording of real events on or off; they arrive as `Observed` notifications.
206#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
207pub struct Record {
208    /// On or off.
209    pub on: bool,
210}
211
212/// Holds every task of a name until released.
213#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
214pub struct HoldTask {
215    /// The task name, `TaskName::NAME`.
216    pub name: String,
217}
218
219/// Removes a rule.
220#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
221pub struct RemoveRule {
222    /// The rule.
223    pub rule: WireRuleId,
224}
225
226/// Waits for the next task of a name.
227#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
228pub struct NextTask {
229    /// The task name.
230    pub name: String,
231    /// How long the probe may wait.
232    #[serde(default)]
233    pub wait: Option<WireDuration>,
234}
235
236/// Lets a held task run.
237#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
238pub struct ReleaseTask {
239    /// The task name.
240    pub name: String,
241    /// The task.
242    pub task: WireTaskId,
243}
244
245/// What a resolved task completes with, as JSON text the probe deserialises into the task's
246/// output type.
247#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
248#[serde(rename_all = "snake_case")]
249pub enum TaskOutput {
250    /// The task's whole output.
251    Value(String),
252    /// The error of a task whose output is a `Result`.
253    Error(String),
254}
255
256/// Completes a held task without running it.
257#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
258pub struct ResolveTask {
259    /// The task name.
260    pub name: String,
261    /// The task.
262    pub task: WireTaskId,
263    /// What it completes with.
264    pub output: TaskOutput,
265}
266
267/// Answered once no named task is in flight and the probe has no input, collection or
268/// guarded request outstanding.
269#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
270pub struct WaitIdle {
271    /// How long the probe may hold the request.
272    #[serde(default)]
273    pub wait: Option<WireDuration>,
274}
275
276/// Ends the session; the probe releases every window and rule the client held.
277#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, Serialize, Deserialize)]
278pub struct Bye;
279
280macro_rules! requests {
281    ($($(#[doc = $doc:literal])* $ty:ident => $response:ty, $method:literal;)+) => {
282        $(
283            impl sealed::Sealed for $ty {}
284            impl Request for $ty {
285                type Response = $response;
286                const METHOD: &'static str = $method;
287            }
288        )+
289
290        /// Every method name, in declaration order.
291        pub const METHODS: &[&str] = &[$($method),+];
292
293        const _: () = assert!(
294            crate::__private::methods_unique(METHODS),
295            "two requests share a METHOD"
296        );
297
298        /// Any request, for the probe's dispatch. A match on it is exhaustive, so a request
299        /// cannot be added without a handler.
300        #[derive(Debug, Clone, PartialEq)]
301        #[non_exhaustive]
302        pub enum AnyRequest {
303            $($(#[doc = $doc])* $ty($ty),)+
304        }
305
306        impl AnyRequest {
307            /// The request's method name.
308            #[must_use]
309            pub fn method(&self) -> &'static str {
310                match self {
311                    $(AnyRequest::$ty(_) => <$ty as Request>::METHOD,)+
312                }
313            }
314
315            /// Reads `params` as the request `method` names, or `Ok(None)` when no request
316            /// has that name.
317            pub fn from_params<'de, D: Deserializer<'de>>(
318                method: &str,
319                params: D,
320            ) -> Result<Option<AnyRequest>, D::Error> {
321                match method {
322                    $($method => <$ty>::deserialize(params).map(|r| Some(AnyRequest::$ty(r))),)+
323                    _ => Ok(None),
324                }
325            }
326        }
327
328        /// The response to any request, named by the request it answers. Serialises as the
329        /// response itself.
330        #[derive(Debug, Clone, PartialEq)]
331        #[non_exhaustive]
332        pub enum AnyResponse {
333            $($(#[doc = $doc])* $ty($response),)+
334        }
335
336        impl AnyResponse {
337            /// The method of the request this answers.
338            #[must_use]
339            pub fn method(&self) -> &'static str {
340                match self {
341                    $(AnyResponse::$ty(_) => <$ty as Request>::METHOD,)+
342                }
343            }
344        }
345
346        impl Serialize for AnyResponse {
347            fn serialize<S: Serializer>(&self, serializer: S) -> Result<S::Ok, S::Error> {
348                match self {
349                    $(AnyResponse::$ty(response) => response.serialize(serializer),)+
350                }
351            }
352        }
353    };
354}
355
356requests! {
357    /// The handshake.
358    Hello => Welcome, "hello";
359    /// The raw tree.
360    Snapshot => SnapshotReply, "snapshot";
361    /// Input events.
362    Input => Delivered, "input";
363    /// A window's pixels.
364    Screenshot => ScreenshotHeader, "screenshot";
365    /// The open windows.
366    Windows => WindowList, "windows";
367    /// Focus a window.
368    Focus => Done, "focus";
369    /// Take a window's input.
370    Drive => Done, "drive";
371    /// Give a window's input back.
372    Release => Done, "release";
373    /// Pick mode.
374    Inspect => Done, "inspect";
375    /// Recording.
376    Record => Done, "record";
377    /// Hold tasks of a name.
378    HoldTask => WireRuleId, "hold_task";
379    /// Remove a rule.
380    RemoveRule => Done, "remove_rule";
381    /// The next task of a name.
382    NextTask => WireTaskId, "next_task";
383    /// Let a task run.
384    ReleaseTask => Done, "release_task";
385    /// Complete a task.
386    ResolveTask => Done, "resolve_task";
387    /// Wait until the app is idle.
388    WaitIdle => Done, "wait_idle";
389    /// End the session.
390    Bye => Done, "bye";
391}
392
393/// A request in its envelope. Built with [`Call::new`], which takes the method from the
394/// request type.
395#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
396pub struct Call<R> {
397    /// Chosen by the client.
398    pub id: RequestId,
399    /// The request's method.
400    pub method: Cow<'static, str>,
401    /// The request.
402    pub params: R,
403}
404
405impl<R: Request> Call<R> {
406    /// The envelope for `params`.
407    #[must_use]
408    pub fn new(id: RequestId, params: R) -> Self {
409        Self {
410            id,
411            method: Cow::Borrowed(R::METHOD),
412            params,
413        }
414    }
415}
416
417/// A reply in its envelope: `{ "id": n, "result": .. }` or `{ "id": n, "error": .. }`.
418#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
419pub struct Reply<T> {
420    /// The request's id.
421    pub id: RequestId,
422    /// The answer.
423    #[serde(flatten)]
424    pub body: ReplyBody<T>,
425}
426
427/// A result or an error.
428#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
429#[serde(rename_all = "snake_case")]
430pub enum ReplyBody<T> {
431    /// The response.
432    Result(T),
433    /// What went wrong.
434    Error(ErrorBody),
435}
436
437impl<T> ReplyBody<T> {
438    /// The response, or the error as a [`crate::ProtocolError`].
439    pub fn into_result(self) -> Result<T, crate::ProtocolError> {
440        match self {
441            ReplyBody::Result(value) => Ok(value),
442            ReplyBody::Error(body) => Err(body.into()),
443        }
444    }
445}
446
447/// What a named task did.
448#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
449#[serde(rename_all = "snake_case")]
450pub enum TaskChange {
451    /// It started.
452    Started,
453    /// A rule held it.
454    Held,
455    /// It was released.
456    Released,
457    /// The client completed it.
458    Resolved,
459    /// It finished by itself.
460    Finished,
461    /// It failed.
462    Failed {
463        /// The error's `Display` text.
464        error: String,
465    },
466}
467
468/// What the probe pushes unasked. Notifications carry `event` and no `id`.
469#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
470#[serde(tag = "event", content = "data", rename_all = "snake_case")]
471pub enum Notification {
472    /// The generation or frame count rose.
473    Generation {
474        /// The generation now.
475        generation: Generation,
476        /// The frame count now.
477        frame: FrameCount,
478    },
479    /// The node under the real pointer in pick mode.
480    Hovered {
481        /// Its raw path: the window index, then each child index, joined by `.`, as
482        /// `SemanticTree::by_raw` takes it. The probe has no inference to name a node path.
483        path: String,
484        /// The tree it was found in.
485        tree: RawTree,
486        /// Whether the user clicked it, which picks it.
487        #[serde(default)]
488        picked: bool,
489    },
490    /// A real event, while recording.
491    Observed {
492        /// The generation it arrived at.
493        generation: Generation,
494        /// The window.
495        window: WindowOrdinal,
496        /// The event.
497        event: WireEvent,
498        /// What the widgets did with it.
499        status: WireStatus,
500    },
501    /// A named task changed.
502    Task {
503        /// The task name.
504        name: String,
505        /// The task.
506        task: WireTaskId,
507        /// What happened.
508        change: TaskChange,
509    },
510    /// A window opened.
511    WindowOpened(RawWindowInfo),
512    /// A window closed.
513    WindowClosed {
514        /// The window.
515        window: WindowOrdinal,
516    },
517}