Skip to main content

egui_pop_api/
wait.rs

1//! Waiting on the application: until a journal event matches, or until
2//! the application is settled. The `bridge.wait` capability and the test
3//! kit's frame-stepping wait (`egui_pop_test::wait::wait_until`) share it.
4//!
5//! <div class="warning">Experimental: may change in any release
6//! (docs/stability.md).</div>
7//!
8//! The check never blocks: [`AppHandle::wait_met`] says whether the
9//! condition holds now. Who waits holds the call and checks again after
10//! each frame until it holds or a deadline passes: a kittest harness
11//! steps frames, a transport re-checks on the UI thread. The UI thread
12//! itself never sleeps on it.
13//!
14//! ```
15//! use egui_pop_api::about::{AboutPlugin, AppInfo};
16//! use egui_pop_api::{App, DefaultPlugins};
17//! use egui_pop_api::wait::{WaitFor, Waited};
18//! use serde_json::json;
19//!
20//! let mut app = App::builder()
21//!     .plugins(DefaultPlugins)
22//!     .plugin(AboutPlugin::new(AppInfo::new("Demo", "1.0.0")))
23//!     .build(&egui::Context::default())
24//!     .unwrap();
25//! let since = app.handle().last_event();
26//! let f = app.debug_call("commands", "run", &json!({ "id": "about.read" }));
27//! assert!(f.ok, "{}", f.message);
28//! let done = app.handle().wait_met(&WaitFor::event("command.done"), since);
29//! assert!(matches!(done, Some(Waited::Event(e)) if e.data["command"] == "about.read"));
30//! // The same through the bridge, as an agent asks it.
31//! let f = app.debug_call(
32//!     "bridge",
33//!     "wait",
34//!     &json!({ "event": "command.done", "since": since }),
35//! );
36//! assert_eq!(f.data["met"], true);
37//! ```
38
39use serde::Serialize;
40use serde_json::{Value as Json, json};
41
42use crate::app::AppHandle;
43use crate::host::{Event, Seq};
44
45/// What a wait waits for.
46#[derive(Clone, Debug, PartialEq, Serialize)]
47#[serde(rename_all = "snake_case")]
48pub enum WaitFor {
49    /// A journal event after the wait's start named `name` and, when
50    /// given, following from `cause` (a command's dispatch).
51    Event { name: String, cause: Option<Seq> },
52    /// The application is settled: no command queued or running, every
53    /// job idle (orphaned jobs aside), and no repaint asked for.
54    Settled,
55    /// The first of these that holds.
56    Any(Vec<WaitFor>),
57}
58
59impl WaitFor {
60    /// An event by name, whatever its cause.
61    pub fn event(name: &str) -> Self {
62        Self::Event {
63            name: name.into(),
64            cause: None,
65        }
66    }
67
68    /// Reads `bridge.wait`'s arguments: `{ "event", "cause" }`,
69    /// `{ "settled": true }` or `{ "any": [..] }`.
70    pub fn from_args(args: &Json) -> Result<Self, String> {
71        if let Some(any) = args.get("any") {
72            let any = any.as_array().ok_or("`any` is not a list")?;
73            return any
74                .iter()
75                .map(Self::from_args)
76                .collect::<Result<Vec<_>, _>>()
77                .map(Self::Any);
78        }
79        if let Some(name) = args.get("event") {
80            let name = name.as_str().ok_or("`event` is not a name")?;
81            let cause = match args.get("cause") {
82                None | Some(Json::Null) => None,
83                Some(c) => Some(c.as_u64().ok_or("`cause` is not a sequence number")?),
84            };
85            return Ok(Self::Event {
86                name: name.into(),
87                cause,
88            });
89        }
90        if args.get("settled").and_then(Json::as_bool) == Some(true) {
91            return Ok(Self::Settled);
92        }
93        Err("give `event` (with an optional `cause`), `settled: true` or `any`".into())
94    }
95
96    /// As [`WaitFor::from_args`] reads it.
97    pub fn to_args(&self) -> Json {
98        match self {
99            Self::Event { name, cause } => json!({ "event": name, "cause": cause }),
100            Self::Settled => json!({ "settled": true }),
101            Self::Any(any) => json!({ "any": any.iter().map(Self::to_args).collect::<Vec<_>>() }),
102        }
103    }
104}
105
106/// What ended a wait.
107#[derive(Clone, Debug, PartialEq, Serialize)]
108#[serde(rename_all = "snake_case")]
109pub enum Waited {
110    /// This event matched.
111    Event(Event),
112    /// The application settled.
113    Settled,
114}
115
116/// The JSON Schema of `bridge.wait`'s arguments.
117pub fn args_schema() -> Json {
118    json!({
119        "$schema": "https://json-schema.org/draft/2020-12/schema",
120        "type": "object",
121        "description": "Wait for a journal event after `since` (`event`, optional `cause`), for the application to settle (`settled: true`), or for the first of several (`any`).",
122        "properties": {
123            "event": { "type": "string", "description": "The event's name (`command.done`)." },
124            "cause": { "type": ["integer", "null"], "minimum": 0, "description": "The event it follows from." },
125            "settled": { "type": "boolean" },
126            "any": { "type": "array", "items": { "type": "object" } },
127            "since": { "type": "integer", "minimum": 0, "description": "Only events after this sequence number; by default the call's own." },
128            "deadline_ms": { "type": "integer", "minimum": 0, "description": "How long the transport holds the call; in-process the call answers at once." }
129        }
130    })
131}
132
133/// The JSON Schema of `bridge.wait`'s result.
134pub fn result_schema() -> Json {
135    json!({
136        "$schema": "https://json-schema.org/draft/2020-12/schema",
137        "type": "object",
138        "required": ["met", "last"],
139        "properties": {
140            "met": { "type": "boolean" },
141            "by": { "enum": ["event", "settled", null] },
142            "event": { "type": ["object", "null"] },
143            "last": { "type": "integer", "description": "The journal's last sequence number: the next check's `since`." },
144            "orphaned": { "type": "integer", "minimum": 0, "description": "Orphaned jobs going on (their plugin is disconnected): not waited on by `settled`." }
145        }
146    })
147}
148
149impl AppHandle {
150    /// Whether the application is settled: no command queued for the
151    /// next frame or running (a host's later reply), every job idle,
152    /// and no repaint asked for. An orphaned job (its plugin is
153    /// disconnected) is not waited on: it may never end;
154    /// [`AppHandle::orphaned_jobs`] counts it.
155    pub fn settled(&self) -> bool {
156        self.queued_requests() == 0
157            && !self.commands().iter().any(|(s, _)| self.running(&s.id))
158            && self.service(&crate::jobs::JOBS).is_none_or(|j| {
159                // Up to the last `job.*` event, not the last pass's.
160                self.deliver_events();
161                j.idle()
162            })
163            && !self.egui().has_requested_repaint()
164    }
165
166    /// The orphaned jobs still going on: left by a disconnected plugin,
167    /// not waited on by [`AppHandle::settled`]; 0 without the jobs
168    /// plugin. Read from the jobs model, the bus having delivered the
169    /// journal's `job.*` events up to the last one.
170    pub fn orphaned_jobs(&self) -> usize {
171        self.service(&crate::jobs::JOBS).map_or(0, |j| {
172            self.deliver_events();
173            j.orphans().len()
174        })
175    }
176
177    /// Whether `until` holds now, for events after `since`; what made
178    /// it hold. Never blocks (see the [module](self)).
179    pub fn wait_met(&self, until: &WaitFor, since: Seq) -> Option<Waited> {
180        match until {
181            WaitFor::Event { name, cause } => self
182                .events_since(since)
183                .into_iter()
184                .find(|e| e.name == *name && cause.is_none_or(|c| e.cause == Some(c)))
185                .map(Waited::Event),
186            WaitFor::Settled => self.settled().then_some(Waited::Settled),
187            WaitFor::Any(any) => any.iter().find_map(|w| self.wait_met(w, since)),
188        }
189    }
190
191    /// `bridge.wait`'s answer: `{ "met", "by", "event", "last",
192    /// "orphaned" }`.
193    pub(crate) fn wait_answer(&self, args: &Json) -> Result<Json, String> {
194        let until = WaitFor::from_args(args)?;
195        let last = self.last_event();
196        let since = args.get("since").and_then(Json::as_u64).unwrap_or(last);
197        let orphaned = self.orphaned_jobs();
198        Ok(match self.wait_met(&until, since) {
199            Some(Waited::Event(e)) => {
200                json!({ "met": true, "by": "event", "event": e, "last": last, "orphaned": orphaned })
201            }
202            Some(Waited::Settled) => {
203                json!({ "met": true, "by": "settled", "event": null, "last": last, "orphaned": orphaned })
204            }
205            None => {
206                json!({ "met": false, "by": null, "event": null, "last": last, "orphaned": orphaned })
207            }
208        })
209    }
210}