Skip to main content

egui_pop_api/
bus.rs

1//! The bus: requests, events and the listeners of each, joined
2//! ([ADR 0029](https://github.com/quazardous/egui-pop/blob/main/docs/adr/0029-not-on-the-bus.md)).
3//!
4//! <div class="warning">Experimental: may change in any release
5//! (docs/stability.md).</div>
6//!
7//! A module knows the bus, not its neighbours. A state change another
8//! part may care about is a **request**, asked with who asks and why (a
9//! step, ADR 0011, named `<noun>.<verb>`), and an **event** said once it
10//! is done or refused (the journal, `<noun>.<past>`). Whoever cares
11//! listens, under a name and at a place it declares, on the bus the
12//! application holds ([`AppHandle::bus`]); nobody calls a neighbour to
13//! tell it.
14//!
15//! The bus is a contract ([ADR 0030](https://github.com/quazardous/egui-pop/blob/main/docs/adr/0030-the-bus-is-a-contract.md),
16//! the `bus-contract` crate): the application supplies it
17//! (`AppBuilder::bus`), or egui-pop makes a hook kernel of its own.
18//! egui-pop declares its points from [`CONTRACT`] and registers its
19//! listeners on it; it never constructs a bus it is given.
20//!
21//! The window lifecycle is the first family on it. Its points
22//! ([`WindowOpen`], [`WindowClose`], [`WindowReparent`], [`PopupOpen`],
23//! [`PopupClose`]) take a [`WindowRequest`]; the registry
24//! ([`REGISTRY`]) listens to them and is the one list of what is on
25//! screen ([`AppHandle::windows_list`]). Closing an application window
26//! ([`AppHandle::request_window_close`]) runs, in one call and in this
27//! order:
28//!
29//! 1. [`CHILDREN`]: what belongs to the window goes with it (its dialogs);
30//! 2. the owner's listener (`pop.admin.window` for the Settings app): the
31//!    state the window showed closes;
32//! 3. [`FOCUS`]: the window worked in before becomes the active one;
33//! 4. [`REGISTRY`]: the window is closed, no longer declared to the
34//!    backend, hidden where the system allows;
35//! 5. [`PLACE`]: its place is kept (written to disk later);
36//! 6. [`INVARIANTS`]: last, checks the registry agrees.
37//!
38//! `window.closed` is said after the last of them, so whoever reads it
39//! finds the owner's state, the focus and the registry already agree.
40//! [`order_dump`] prints who runs when; the `bus` collector of the debug
41//! bridge shows it too.
42//!
43//! The Settings app's window is wholly on the bus: the app asks
44//! `pop.window.open` and `pop.window.close` for it as its owner, in the call that
45//! changed what it wants, and its listener (`pop.admin.window`) keeps the
46//! app's state with the window on both points. A plugin disconnected has
47//! its windows closed ([`OWNER_GONE`], reason `owner-gone`).
48//!
49//! The shell's windows are on the bus too: opening an application window
50//! is its `pop.window.open` ([`AppHandle::request_window_open`], the
51//! application as owner for [`AppHandle::open_window`]); the main
52//! window's close, whatever asked (the system, its title bar's Close,
53//! [`AppHandle::close_window`], [`AppHandle::quit`] with the reason
54//! `quit`), is its `pop.window.close`, which closes every other window by its
55//! own `pop.window.close` first; a window's content moving into the main
56//! window when it closes, and back when the main window is asked to its
57//! front, is a `pop.window.reparent` ([`AppHandle::request_window_reparent`]).
58//! Detached panels' windows are the workbench's: detaching a panel is its
59//! window's `pop.window.open`, docking it back its `pop.window.reparent` into the
60//! main window, closing its window its `pop.window.close`, the workbench's
61//! listener ([`WORKBENCH_WINDOW`]) changing the layout whoever asked.
62//! Dialogs and file choices are on the bus too: a dialog coming up is its
63//! `pop.popup.open` (`dialog:<n>`, parent: its window), a file choice started
64//! its `pop.popup.open` (`file:<n>`), or `pop.window.open` of a native window for
65//! the system's chooser ([`AppHandle::request_native_open`]); each ends by
66//! its `pop.popup.close` or `pop.window.close`. A window closing closes its
67//! popups and native windows first, each by its own request (reason
68//! `parent-closed`), and their owners' listeners (`pop.dialogs.popup`,
69//! `pop.files.choice`) cancel what they showed in the same call. The overlay
70//! stack's overlays (the palette, menus, flyouts, popovers) and the egui
71//! popups it follows (context menus, the menu bar's menus, hover cards)
72//! are popups too: each opening and closing is its `pop.popup.open` or
73//! `pop.popup.close`, asked in that call with how it closed (`how`), and a
74//! close asked by anyone closes it in the stack ([`OVERLAY_STACK`]);
75//! tooltips and a field's lists stay off, per-frame painting.
76//!
77//! The active window, the one the person works in, is the registry's too
78//! ([`WindowActivate`], [`AppHandle::request_window_activate`]): a press
79//! or a key in a window asks it (`user`), a window gaining the system's
80//! focus asks it (`system`), the application asking a window to the
81//! front asks it (`command`, raised by [`RAISE`], the one place egui-pop
82//! sends `ViewportCommand::Focus`); `window.activated` is said when it
83//! changed, and a window closing while active hands it to the window
84//! worked in before it.
85//!
86//! The job lifecycle is the second family. Asking about a job is a
87//! request ([`JobCancel`], [`JobPause`], [`JobResume`], [`JobRetry`], each
88//! a [`JobAsk`], asked by [`AppHandle::request_job`]); whoever runs the
89//! job does the work and answers with its job events, published typed on
90//! [`JobEvents`] (`pop.job.event`, a [`JobEvent`] of a [`JobEventKind`])
91//! with a [`JobPublisher`]. Those events, and the job commands' dispatch
92//! and answer, are delivered to its listeners in journal order, once each
93//! ([`AppHandle::deliver_events`]): the jobs plugin's model is one of them
94//! (`pop.jobs.model`), so no job state changes but on the bus. A plugin
95//! connecting or disconnecting is asked on [`PluginConnect`] and
96//! [`PluginDisconnect`] (a [`PluginChange`]), the disconnection before
97//! `plugin.disconnected` is said: the jobs a plugin leaves are cancelled
98//! or said orphaned by a listener of its disconnection, and taken back by
99//! one of its connection.
100//!
101//! An application's own rows in the jobs list are on it too
102//! ([`job_rows`](egui_pop_model::job_rows)): a **row source** is declared,
103//! its rows replaced, by `pop.jobs.rows` ([`JobRowsSet`]) and taken away
104//! by `pop.jobs.source.drop` ([`JobSourceDrop`]), from any thread; the
105//! jobs plugin's listener ([`JOB_SOURCES`]) keeps them for the list.
106//!
107//! Files dropped from another program are on it too: every window's pass
108//! reads the files dropped on it once, as its `pop.files.drop` ([`FilesDrop`],
109//! a [`FileDrop`] naming the window); whoever takes them listens, and
110//! nobody taking them is said as `files.refused`.
111//!
112//! Settings are on it too: every change of a setting's value is said
113//! once by the value store, its one writer, as `pop.settings.changed`
114//! ([`SettingsChanged`], a [`SettingChange`]: path, scope, by), whether
115//! it was made here or by another client of the host's store; the theme,
116//! the pointer profile and the main window's frame are its listeners
117//! ([`THEME_INSTALL`], [`POINTER_PROFILE`], [`FRAME_DECORATIONS`]), and an
118//! application's part that follows a setting listens there too.
119//!
120//! A drag across windows is on it too ([`drag`]): a drag begins as
121//! `pop.drag.start` ([`DragStart`], its kind and window); let go over a drop
122//! target that takes it, in its window or another, it is `pop.drag.drop`
123//! ([`DragDrop`]) and `drag.dropped`; refused, let go over nothing or
124//! cancelled, `drag.refused` with the reason. Where it hovers each pass
125//! stays off the bus (per-frame painting).
126//!
127//! The screens are on it too: a screen plugged in or
128//! unplugged, as told by whatever runs the event loop
129//! ([`crate::window::set_screens`]), is said as `pop.screen.added`
130//! ([`ScreenAdded`]) or `pop.screen.removed` ([`ScreenRemoved`]), by its
131//! name; on `pop.screen.removed` a detached panel's window kept on it docks
132//! back ([`WORKBENCH_SCREENS`]) and every other window left off every
133//! screen moves onto one ([`PLACE`]).
134//!
135//! The layout is on it too: every real change of the workbench's layout
136//! is said once, when the gesture that made it ends, as `pop.layout.changed`
137//! ([`LayoutChanged`], a [`LayoutChange`] naming its causes); the layout
138//! is saved by its listener ([`LAYOUT_SAVE`]), an application's copy of
139//! it follows after.
140//!
141//! A panel's state is on it too: whoever knows a panel's content is not
142//! current asks `pop.panel.state` ([`PanelStateSet`], from any thread), and
143//! the workbench's chrome shows it ([`PANEL_CHROME`]), never the panel.
144//! What a declared panel is, its kind (whether it edits) included, is
145//! `pop.panel.describe` ([`PanelDescribe`], answered by [`PANEL_DESCRIBE`]).
146//! Opening a panel, wherever it is asked from (a menu, a tab bar's "+",
147//! a group's menu, its toggle command, an agent), is `pop.panel.open`
148//! ([`PanelOpen`], a [`PanelOpenAsk`] naming the panel and where it opens:
149//! where it was, here or an area; answered by [`PANEL_OPEN`]).
150//! Naming an open panel instance's tab title, or giving it its generated
151//! title back, is `pop.panel.retitle` ([`PanelRetitle`], a
152//! [`PanelRetitleAsk`]; answered by [`PANEL_RETITLE`]).
153//! The interactive areas each window's last pass registered, what each
154//! writes (display, navigate, edit) and whether an edit area is inert,
155//! are `pop.ui.areas` ([`UiAreas`], answered by [`AREA_REGISTRY`]).
156//! Which panel zen mode shows when none is named and the focused panel
157//! is not a view is the application's, asked on `pop.zen.panel`
158//! ([`ZenPanel`]).
159//! A command's live title and tooltip, for a command whose text follows
160//! the application's state, are the application's, asked on
161//! `pop.command.label` ([`CommandLabel`], a [`CommandText`]).
162//! Notices are on it too (`docs/notices.md`): a message for
163//! the user (an error, a warning, a success, a question) is raised once
164//! as `pop.notice.raised` ([`NoticeRaised`], [`AppHandle::report`]); a
165//! condition ending is `pop.notice.resolved`, notices read
166//! `pop.notice.seen`, notices put away `pop.notice.dismissed`; egui-pop's
167//! store ([`NOTICE_STORE`]) keeps the last ones ([`AppHandle::notices`]).
168
169use std::cell::{Cell, RefCell};
170use std::rc::Rc;
171use std::sync::{Arc, Mutex};
172
173use bus_contract::{ListenOpts, Point, PointDecl, PointId, PointKind};
174use bus_contract_defer::BusDefer;
175use egui::{ViewportCommand, ViewportId};
176use egui_pop_core::lock;
177use serde::{Deserialize, Serialize};
178use serde_json::json;
179
180use crate::app::{AppHandle, WeakApp};
181use crate::host::{Event, Seq};
182use crate::windows::WindowId;
183pub use egui_pop_model::jobs::JobEventKind;
184
185pub use bus_contract;
186pub use bus_contract::{missing_targets, order_dump};
187/// The capability contracts egui-pop reaches on the bus (bus-contract
188/// 0.5 moved them out of the core).
189pub use bus_contract_crossing;
190pub use bus_contract_defer;
191pub use bus_contract_journal;
192pub use bus_contract_timings;
193pub use egui_pop_hooks;
194/// The kernel's trace tap (bus-kernel's `Trace` capability): a sink
195/// observing the bus hears each emit, listener heard, ask and drain, on
196/// the emitting thread, where [`drawing_panel`] names the panel drawing.
197pub use egui_pop_hooks::trace::{self, BusTrace};
198
199mod activate;
200pub use activate::raise_main_window;
201pub(crate) mod areas;
202pub use areas::{AREA_POINTS, AREA_REGISTRY, UiAreas};
203pub(crate) mod budget;
204mod command_label;
205pub mod drawing;
206pub use drawing::{DrawingPanel, TopologyOf, drawing_panel};
207mod commands;
208pub(crate) mod journal;
209pub use command_label::{COMMAND_LABEL_POINTS, CommandLabel, CommandText};
210pub use commands::{ARGS_VALIDATOR, COMMAND_POINTS, CommandAsk, CommandRun};
211pub(crate) use commands::{args_refusal, ask as ask_command_run, reason as command_refusal};
212pub use journal::{HOST_JOURNAL, HostEvent, HostEvents};
213pub mod drag;
214pub use drag::{DRAG_POINTS, DragBegin, DragDelivery, DragDrop, DragStart, TARGET as DRAG_TARGET};
215pub(crate) mod files;
216pub use files::{BROWSER as FILES_BROWSER, FILES_POINTS, FileDrop, FilesDrop};
217pub(crate) mod job_rows;
218pub use job_rows::{
219    JOB_ROW_POINTS, JobRowsAsk, JobRowsSet, JobSourceAsk, JobSourceDrop, SOURCES as JOB_SOURCES,
220};
221pub(crate) mod layout;
222pub use layout::{
223    LAYOUT_POINTS, LAYOUT_SAVE, LayoutChange, LayoutChanged, SETTLE as LAYOUT_SETTLE,
224};
225pub(crate) mod notices;
226pub use notices::{
227    NOTICE_POINTS, NOTICE_ROUTE, NOTICE_STORE, NoticeBadge, NoticeDismissed, NoticeRaised,
228    NoticeResolved, NoticeSeen,
229};
230mod owners;
231pub use owners::OWNER_GONE;
232pub(crate) mod panel_describe;
233pub use panel_describe::{PANEL_DESCRIBE, PANEL_DESCRIBE_POINTS, PanelDescribe, PanelDescription};
234pub(crate) mod panel_open;
235pub use panel_open::{
236    OpenPlace, PANEL_OPEN, PANEL_OPEN_POINTS, PanelHome, PanelHomeArea, PanelHomeAreaAsk,
237    PanelHomeAsk, PanelOpen, PanelOpenAsk,
238};
239pub(crate) mod panel_retitle;
240pub use panel_retitle::{PANEL_RETITLE, PANEL_RETITLE_POINTS, PanelRetitle, PanelRetitleAsk};
241pub(crate) mod panel_state;
242pub use panel_state::{
243    PANEL_CHROME, PANEL_STATE_POINTS, PanelState, PanelStateAsk, PanelStateSet, TabMark, mark_id,
244};
245pub(crate) mod panels;
246pub use panels::{WORKBENCH_OWNER, WORKBENCH_WINDOW};
247pub(crate) mod overlays;
248pub use overlays::{OVERLAY_OWNER, POPUP_PREFIX as OVERLAY_POPUP_PREFIX, STACK as OVERLAY_STACK};
249mod popups;
250pub(crate) mod settings;
251pub use settings::{
252    FRAME_DECORATIONS, POINTER_PROFILE, SETTINGS_POINTS, SettingChange, SettingsChanged,
253    THEME_INSTALL,
254};
255pub(crate) mod screens;
256pub use screens::{SCREEN_POINTS, ScreenAdded, ScreenChange, ScreenRemoved, WORKBENCH_SCREENS};
257mod shell;
258pub use shell::STEP_WINDOW_REPARENT;
259mod zen;
260pub use zen::{ZEN_POINTS, ZenPanel};
261
262/// Why a window or a popup opens or closes.
263#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
264#[serde(rename_all = "kebab-case")]
265#[non_exhaustive]
266pub enum Reason {
267    /// The person: a title bar's close, a Close button, Escape.
268    User,
269    /// A command or the application's code.
270    Command,
271    /// Its parent window closed.
272    ParentClosed,
273    /// Its owner went (a plugin disconnected, the state it showed closed).
274    OwnerGone,
275    /// The paint guard (a window that painted nothing, an orphan).
276    Guard,
277    /// The system (the backend dropped it).
278    System,
279    /// The application quits.
280    Quit,
281}
282
283impl Reason {
284    /// The reason as the journal writes it (`parent-closed`).
285    pub fn as_str(self) -> &'static str {
286        match self {
287            Reason::User => "user",
288            Reason::Command => "command",
289            Reason::ParentClosed => "parent-closed",
290            Reason::OwnerGone => "owner-gone",
291            Reason::Guard => "guard",
292            Reason::System => "system",
293            Reason::Quit => "quit",
294        }
295    }
296}
297
298/// What a window of the registry is.
299#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
300#[serde(rename_all = "kebab-case")]
301#[non_exhaustive]
302pub enum WindowKind {
303    /// The main window (the root viewport).
304    Main,
305    /// An application window ([`AppHandle::open_window`]).
306    App,
307    /// A detached panel's window.
308    Panel,
309    /// A native window egui does not paint (a system file chooser, a web
310    /// view).
311    Native,
312    /// A popup inside or over a window.
313    Popup,
314}
315
316/// A window or popup request: which, of what kind, who asks, why, and
317/// the event that caused it.
318#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
319#[non_exhaustive]
320pub struct WindowRequest {
321    /// The window's id ([`WindowId`]), or the popup's.
322    pub window: String,
323    pub kind: WindowKind,
324    /// Who asks: a plugin's id, a command's, a parent window's.
325    pub owner: String,
326    pub reason: Reason,
327    /// The journal sequence number of the event that caused it.
328    #[serde(default, skip_serializing_if = "Option::is_none")]
329    pub cause: Option<u64>,
330    /// The parent window, for a child window or a popup.
331    #[serde(default, skip_serializing_if = "Option::is_none")]
332    pub parent: Option<String>,
333    /// How a popup closed, when the person or its stack closed it:
334    /// `escape`, `outside`, `chosen`, `owner`, `below` (an overlay under
335    /// it closed), `gone` (its widget no longer drawn).
336    #[serde(default, skip_serializing_if = "Option::is_none")]
337    pub how: Option<String>,
338}
339
340impl WindowRequest {
341    pub fn new(
342        window: impl Into<String>,
343        kind: WindowKind,
344        owner: impl Into<String>,
345        reason: Reason,
346    ) -> Self {
347        Self {
348            window: window.into(),
349            kind,
350            owner: owner.into(),
351            reason,
352            cause: None,
353            parent: None,
354            how: None,
355        }
356    }
357
358    /// The journal event that caused it.
359    pub fn cause(mut self, seq: u64) -> Self {
360        self.cause = Some(seq);
361        self
362    }
363
364    /// Its parent window.
365    pub fn parent(mut self, parent: impl Into<String>) -> Self {
366        self.parent = Some(parent.into());
367        self
368    }
369
370    /// How the popup closed (`escape`, `chosen`…).
371    pub fn how(mut self, how: impl Into<String>) -> Self {
372        self.how = Some(how.into());
373        self
374    }
375}
376
377/// A window opens (`pop.window.open`); its listeners say what they did, one
378/// line each, in the value.
379#[derive(Debug)]
380pub struct WindowOpen;
381impl Point for WindowOpen {
382    const KIND: PointKind = PointKind::Request;
383    const ID: PointId = PointId::new("pop.window.open");
384    type Input = WindowRequest;
385    type Value = Vec<String>;
386}
387
388/// A window closes (`pop.window.close`).
389#[derive(Debug)]
390pub struct WindowClose;
391impl Point for WindowClose {
392    const KIND: PointKind = PointKind::Request;
393    const ID: PointId = PointId::new("pop.window.close");
394    type Input = WindowRequest;
395    type Value = Vec<String>;
396}
397
398/// A window's content moves to another window (`pop.window.reparent`).
399#[derive(Debug)]
400pub struct WindowReparent;
401impl Point for WindowReparent {
402    const KIND: PointKind = PointKind::Request;
403    const ID: PointId = PointId::new("pop.window.reparent");
404    type Input = WindowRequest;
405    type Value = Vec<String>;
406}
407
408/// A popup opens in a window (`pop.popup.open`).
409#[derive(Debug)]
410pub struct PopupOpen;
411impl Point for PopupOpen {
412    const KIND: PointKind = PointKind::Request;
413    const ID: PointId = PointId::new("pop.popup.open");
414    type Input = WindowRequest;
415    type Value = Vec<String>;
416}
417
418/// A popup closes (`pop.popup.close`).
419#[derive(Debug)]
420pub struct PopupClose;
421impl Point for PopupClose {
422    const KIND: PointKind = PointKind::Request;
423    const ID: PointId = PointId::new("pop.popup.close");
424    type Input = WindowRequest;
425    type Value = Vec<String>;
426}
427
428/// A window becomes the active one, the window worked in (`pop.window.activate`):
429/// the person pressed or typed in it (`user`), the system gave it the
430/// focus (`system`), or the application asks it to the front (`command`,
431/// raised by [`RAISE`]).
432#[derive(Debug)]
433pub struct WindowActivate;
434impl Point for WindowActivate {
435    const KIND: PointKind = PointKind::Request;
436    const ID: PointId = PointId::new("pop.window.activate");
437    type Input = WindowRequest;
438    type Value = Vec<String>;
439}
440
441/// The window and popup points, in the order [`order_dump`] prints them.
442pub const WINDOW_POINTS: [&str; 6] = [
443    WindowOpen::ID.as_str(),
444    WindowClose::ID.as_str(),
445    WindowReparent::ID.as_str(),
446    WindowActivate::ID.as_str(),
447    PopupOpen::ID.as_str(),
448    PopupClose::ID.as_str(),
449];
450
451/// A request about a job, asked of whoever runs it (the host, or the
452/// application's own runner): which job, what, and why when it is not
453/// the person asking.
454#[derive(Clone, Debug, PartialEq)]
455#[non_exhaustive]
456pub struct JobAsk {
457    /// The job's id.
458    pub id: String,
459    pub request: egui_pop_model::jobs::Request,
460    /// Why, when it is not the person asking (its plugin disconnected).
461    pub reason: Option<String>,
462    /// Asked by the framework itself, whoever acts now: its command runs
463    /// as `script:egui_pop`.
464    pub(crate) framework: bool,
465}
466
467impl JobAsk {
468    pub fn new(id: impl Into<String>, request: egui_pop_model::jobs::Request) -> Self {
469        Self {
470            id: id.into(),
471            request,
472            reason: None,
473            framework: false,
474        }
475    }
476
477    /// Why it is asked.
478    pub fn reason(mut self, reason: impl Into<String>) -> Self {
479        self.reason = Some(reason.into());
480        self
481    }
482
483    /// The framework's own request (the jobs of a plugin that went).
484    pub(crate) fn by_framework(mut self) -> Self {
485        self.framework = true;
486        self
487    }
488
489    /// Whether the framework itself asks it.
490    pub fn is_framework(&self) -> bool {
491        self.framework
492    }
493
494    /// The command's arguments: `{ "id" }`, with `reason` when given.
495    pub fn args(&self) -> serde_json::Value {
496        let mut args = json!({ "id": self.id });
497        if let Some(r) = &self.reason {
498            args["reason"] = json!(r);
499        }
500        args
501    }
502}
503
504/// A job is asked to stop (`pop.job.cancel`); its listeners say what they
505/// did, one line each, in the value.
506#[derive(Debug)]
507pub struct JobCancel;
508impl Point for JobCancel {
509    const KIND: PointKind = PointKind::Request;
510    const ID: PointId = PointId::new("pop.job.cancel");
511    type Input = JobAsk;
512    type Value = Vec<String>;
513}
514
515/// A job is asked to pause (`pop.job.pause`).
516#[derive(Debug)]
517pub struct JobPause;
518impl Point for JobPause {
519    const KIND: PointKind = PointKind::Request;
520    const ID: PointId = PointId::new("pop.job.pause");
521    type Input = JobAsk;
522    type Value = Vec<String>;
523}
524
525/// A paused job is asked to go on (`pop.job.resume`).
526#[derive(Debug)]
527pub struct JobResume;
528impl Point for JobResume {
529    const KIND: PointKind = PointKind::Request;
530    const ID: PointId = PointId::new("pop.job.resume");
531    type Input = JobAsk;
532    type Value = Vec<String>;
533}
534
535/// A failed or cancelled job is asked to run again (`pop.job.retry`).
536#[derive(Debug)]
537pub struct JobRetry;
538impl Point for JobRetry {
539    const KIND: PointKind = PointKind::Request;
540    const ID: PointId = PointId::new("pop.job.retry");
541    type Input = JobAsk;
542    type Value = Vec<String>;
543}
544
545/// A job event, as [`JobEvents`] carries it: what happened, typed
546/// ([`JobEventKind`]), its data (see [`egui_pop_model::jobs`]), who said
547/// it, and its number and cause in the journal it is recorded in.
548#[derive(Clone, Debug, PartialEq)]
549#[non_exhaustive]
550pub struct JobEvent {
551    pub seq: Seq,
552    pub source: String,
553    pub cause: Option<Seq>,
554    pub kind: JobEventKind,
555    pub data: serde_json::Value,
556}
557
558/// A job event was said (`pop.job.event`): each event the host published
559/// with a [`JobPublisher`] ([`AppHandle::publish_job`]), and each event of
560/// a job command (dispatched, done, failed), delivered once, in journal
561/// order ([`AppHandle::deliver_events`]). The point's kind is typed: no
562/// listener reads a journal entry's name, and an entry named `job.*`
563/// that was not published on this point is not a job event.
564#[derive(Debug)]
565pub struct JobEvents;
566impl Point for JobEvents {
567    const KIND: PointKind = PointKind::Event;
568    const ID: PointId = PointId::new("pop.job.event");
569    type Input = JobEvent;
570    type Value = ();
571}
572
573/// A job event said, not delivered yet.
574#[derive(Debug)]
575struct Said {
576    source: String,
577    kind: JobEventKind,
578    data: serde_json::Value,
579}
580
581/// Publishes job events on `pop.job.event`, from any thread: the host's
582/// side of the jobs contract. The application hands one to its host
583/// ([`Host::set_job_publisher`](crate::host::Host::set_job_publisher));
584/// [`AppHandle::job_publisher`] gives one too. Each event is recorded in
585/// the journal (under its kind's label, [`JobEventKind::name`], for the
586/// journal's readers) and delivered to the point's listeners at the next
587/// delivery, in the order said; the interface is woken.
588#[derive(Clone, Default)]
589pub struct JobPublisher {
590    said: Arc<Mutex<Vec<Said>>>,
591    wake: Arc<Mutex<Option<egui::Context>>>,
592}
593
594impl std::fmt::Debug for JobPublisher {
595    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
596        f.debug_struct("JobPublisher")
597            .field("waiting", &lock(&self.said).len())
598            .finish()
599    }
600}
601
602impl JobPublisher {
603    /// Says a job event: `kind`, with its data, by `source` (`host`, a
604    /// plugin…).
605    pub fn publish(&self, source: &str, kind: JobEventKind, data: serde_json::Value) {
606        lock(&self.said).push(Said {
607            source: source.into(),
608            kind,
609            data,
610        });
611        if let Some(ctx) = lock(&self.wake).as_ref() {
612            ctx.request_repaint_of(ViewportId::ROOT);
613        }
614    }
615
616    fn take(&self) -> Vec<Said> {
617        std::mem::take(&mut *lock(&self.said))
618    }
619}
620
621/// How many journal numbers of job events are kept, for a jobs plugin
622/// connected late to read them back.
623const JOB_TAGS: usize = 100_000;
624
625/// A plugin connecting or disconnecting: which, its owner id, why, and
626/// the commands it registered (gone with it on a disconnection).
627#[derive(Clone, Debug, PartialEq)]
628#[non_exhaustive]
629pub struct PluginChange {
630    pub plugin: String,
631    pub owner: String,
632    /// Why: `connected`, `removed`, `failed connect`…
633    pub reason: String,
634    pub commands: Vec<String>,
635}
636
637impl PluginChange {
638    pub fn new(
639        plugin: impl Into<String>,
640        owner: impl Into<String>,
641        reason: impl Into<String>,
642    ) -> Self {
643        Self {
644            plugin: plugin.into(),
645            owner: owner.into(),
646            reason: reason.into(),
647            commands: Vec::new(),
648        }
649    }
650
651    /// The commands it registered.
652    pub fn commands(mut self, commands: Vec<String>) -> Self {
653        self.commands = commands;
654        self
655    }
656}
657
658/// A plugin is connected (`pop.plugin.connect`), what it registers in
659/// place; its listeners take back what it had left.
660#[derive(Debug)]
661pub struct PluginConnect;
662impl Point for PluginConnect {
663    const KIND: PointKind = PointKind::Request;
664    const ID: PointId = PointId::new("pop.plugin.connect");
665    type Input = PluginChange;
666    type Value = Vec<String>;
667}
668
669/// A plugin is disconnected (`pop.plugin.disconnect`), what it registered
670/// removed, before `plugin.disconnected` is said: each listener adds what
671/// it did to the value (`jobs_cancelled`…), which the event's `removed`
672/// carries.
673#[derive(Debug)]
674pub struct PluginDisconnect;
675impl Point for PluginDisconnect {
676    const KIND: PointKind = PointKind::Request;
677    const ID: PointId = PointId::new("pop.plugin.disconnect");
678    type Input = PluginChange;
679    type Value = serde_json::Map<String, serde_json::Value>;
680}
681
682/// The job points, in the order [`order_dump`] prints them.
683pub const JOB_POINTS: [&str; 5] = [
684    JobCancel::ID.as_str(),
685    JobPause::ID.as_str(),
686    JobResume::ID.as_str(),
687    JobRetry::ID.as_str(),
688    JobEvents::ID.as_str(),
689];
690
691/// The plugin points, in the order [`order_dump`] prints them.
692pub const PLUGIN_POINTS: [&str; 2] = [PluginConnect::ID.as_str(), PluginDisconnect::ID.as_str()];
693
694/// Every point egui-pop declares: the window, job, plugin, files,
695/// settings, drag, screen, panel state, layout, panel description and
696/// command, area, panel opening, panel retitling, zen and command
697/// label, notice and job row source points.
698pub const POINTS: [&str; 36] = [
699    WindowOpen::ID.as_str(),
700    WindowClose::ID.as_str(),
701    WindowReparent::ID.as_str(),
702    WindowActivate::ID.as_str(),
703    PopupOpen::ID.as_str(),
704    PopupClose::ID.as_str(),
705    JobCancel::ID.as_str(),
706    JobPause::ID.as_str(),
707    JobResume::ID.as_str(),
708    JobRetry::ID.as_str(),
709    JobEvents::ID.as_str(),
710    PluginConnect::ID.as_str(),
711    PluginDisconnect::ID.as_str(),
712    FilesDrop::ID.as_str(),
713    SettingsChanged::ID.as_str(),
714    DragStart::ID.as_str(),
715    DragDrop::ID.as_str(),
716    ScreenAdded::ID.as_str(),
717    ScreenRemoved::ID.as_str(),
718    PanelStateSet::ID.as_str(),
719    LayoutChanged::ID.as_str(),
720    PanelDescribe::ID.as_str(),
721    CommandRun::ID.as_str(),
722    UiAreas::ID.as_str(),
723    PanelOpen::ID.as_str(),
724    PanelHome::ID.as_str(),
725    PanelHomeArea::ID.as_str(),
726    PanelRetitle::ID.as_str(),
727    ZenPanel::ID.as_str(),
728    CommandLabel::ID.as_str(),
729    NoticeRaised::ID.as_str(),
730    NoticeResolved::ID.as_str(),
731    NoticeSeen::ID.as_str(),
732    NoticeDismissed::ID.as_str(),
733    JobRowsSet::ID.as_str(),
734    JobSourceDrop::ID.as_str(),
735];
736
737/// egui-pop's contract table (ADR 0030): every point it declares on the
738/// bus it is given, with its kind and description, readable before an
739/// application is built.
740pub const CONTRACT: &[PointDecl] = &[
741    PointDecl::of::<WindowOpen>("A window opens: its id, kind, owner, parent."),
742    PointDecl::of::<WindowClose>(
743        "A window closes, whoever asked: its children, its owner's state, the focus, the registry and its place follow, in one call.",
744    ),
745    PointDecl::of::<WindowReparent>(
746        "A window's content moves to another window (into the main window and back).",
747    ),
748    PointDecl::of::<WindowActivate>(
749        "A window becomes the active one (the person worked in it, the system focused it, or a command asks it to the front): the registry holds it as active, a command's raises it; `window.activated` follows when it changed.",
750    ),
751    PointDecl::of::<PopupOpen>("A popup opens in a window."),
752    PointDecl::of::<PopupClose>("A popup closes."),
753    PointDecl::of::<JobCancel>(
754        "A job is asked to stop: whoever runs it is asked, and the job shows as asked until it answers.",
755    ),
756    PointDecl::of::<JobPause>("A job is asked to pause."),
757    PointDecl::of::<JobResume>("A paused job is asked to go on."),
758    PointDecl::of::<JobRetry>("A failed or cancelled job is asked to run again."),
759    PointDecl::of::<JobEvents>(
760        "A job event was said, typed by its kind (started, progress, finished, failed…): published by the host, or a job command's dispatch and answer; delivered once each, in journal order.",
761    ),
762    PointDecl::of::<PluginConnect>("A plugin is connected: what it had left is taken back."),
763    PointDecl::of::<PluginDisconnect>(
764        "A plugin is disconnected, before `plugin.disconnected` is said: what it leaves is closed or marked, each listener counting what it did.",
765    ),
766    PointDecl::of::<FilesDrop>(
767        "Files from another program are dropped on a window: whoever takes them says so; `files.dropped` follows, or `files.refused` when nobody took them.",
768    ),
769    PointDecl::of::<SettingsChanged>(
770        "A setting's value changed, here or by another client of the host's store: said once by the value store, its one writer (path, scope, by); whoever follows the setting does its part.",
771    ),
772    PointDecl::of::<DragStart>(
773        "A drag begins in a window (a tab, a tab group, an application's payload): its kind and the window; `drag.started` follows.",
774    ),
775    PointDecl::of::<DragDrop>(
776        "A drag is let go over a drop target that takes it, in its window or another: the window and the target; `drag.dropped` follows. A target refusing it, a drag let go over nothing, or cancelled, is said as `drag.refused` with the reason.",
777    ),
778    PointDecl::of::<ScreenAdded>(
779        "A screen was plugged in, as told by whatever runs the event loop: its name as the system gives it, its rectangle in points, its scale factor.",
780    ),
781    PointDecl::of::<ScreenRemoved>(
782        "A screen was unplugged: a detached panel's window kept on it docks back, every other window left off every screen moves onto one (not where the system hides window positions).",
783    ),
784    PointDecl::of::<PanelStateSet>(
785        "A panel's state is asked, from any thread: its content stale, updating, failed (with the reason) or ready again; the panel's chrome shows it (content dimmed, a delayed busy mark on its corner and tab), never the panel.",
786    ),
787    PointDecl::of::<LayoutChanged>(
788        "The workbench's layout changed (a panel docked, detached, floated, moved, opened or closed, a split or a palette resized, a layout put in): said once per change, once its gesture ended; the layout is saved to the host's document by `layout.save`, an application's copy follows it.",
789    ),
790    PointDecl::of::<PanelDescribe>(
791        "A declared panel is described, by its id: its title, whether it is a palette, and its kind (view, control or mixed: whether it edits), the kind whose mark its chrome shows; asked on the interface's thread.",
792    ),
793    PointDecl::of::<CommandRun>(
794        "A command is about to run, whatever asked it (a key, the palette, a menu, a toolbar, an agent): a listener may refuse it with a reason, and the handler does not run; fail-closed, so a listener that fails refuses it too. `command.refused` names who refused and why.",
795    )
796    .fail_closed(),
797    PointDecl::of::<PanelOpen>(
798        "A panel is asked open, whoever asks (a menu, a tab bar's \"+\", a group's menu, its toggle command, an agent): `last` puts it back where it was when it closed (that place gone, in the focused panel's tab group when its areas allow it, else its declared area), `here` in the tab group holding `group` (else the focused panel's), an area's name docks it there; the workbench runs the `workbench.show` step, which a plugin may veto; asked on the interface's thread.",
799    ),
800    PointDecl::of::<PanelHome>(
801        "A panel opening asks the application where it goes, by the window it is asked from: the application answers with a window's id (a panel's home window); none, or a window not shown, and rule A places it (its last place while that window is shown, else the window it was asked from, in its own area); asked on the interface's thread.",
802    ),
803    PointDecl::of::<PanelHomeArea>(
804        "A panel opening asks the application which area it docks in, in the window it opens in (the one `pop.panel.home` answered, else the one it is asked from): the application answers with an area; none, or an area the panel's rules refuse, and it docks in its declared area. A panel back to its last place stays there, and an area the ask names wins; asked on the interface's thread.",
805    ),
806    PointDecl::of::<PanelRetitle>(
807        "An open instance `<kind>#<n>` of a panel declared with several is asked retitled: its title is kept in the layout's instance entry (saved and restored with it) and read by its tab, the panel menu, the View menu and accessibility; `title: null` gives the generated title back; the panel declared, a panel declared once or an instance not open is refused with the reason; `panel.instance.retitled` follows a change; asked on the interface's thread.",
808    ),
809    PointDecl::of::<ZenPanel>(
810        "Zen mode asks which panel matters now, when it starts without a panel named and the focused panel is not a view: the application answers with an open panel's id (the surface a double click reaches, an image viewer); none, and the centre's active tab is shown; asked on the interface's thread.",
811    ),
812    PointDecl::of::<CommandLabel>(
813        "A command's live title and tooltip are asked, by its id, each time a menu item, a toolbar button or a shortcut tooltip naming it is drawn: the application answers for the commands whose text follows its state (\"Zen: Compare\"), in the interface's language; none, and the declared title and description are shown, translated; asked on the interface's thread.",
814    ),
815    PointDecl::of::<UiAreas>(
816        "The interactive areas are listed, each window's last pass: each one's kind (display, navigate or edit), for an edit area the control it writes, its value and path, its panel, its grips, and whether it is inert (its panel's state not current); asked on the interface's thread.",
817    ),
818    PointDecl::of::<NoticeRaised>(
819        "A notice is raised (an error, a warning, a success, a piece of information, a question): its id, time, severity, kind (event, condition, ask), origin (user, background, node, system), headline, reason, hint, details, actions, subject, place and node; kept by the notice store; said from any thread, by any module, plugin or node.",
820    ),
821    PointDecl::of::<NoticeResolved>(
822        "Conditions raised as notices ended, by their ids: the store marks them resolved.",
823    ),
824    PointDecl::of::<NoticeSeen>(
825        "Notices were read, by their ids (shown and acknowledged): the store marks them seen.",
826    ),
827    PointDecl::of::<NoticeDismissed>(
828        "Notices were put away by the user, by their ids: the store drops them.",
829    ),
830    PointDecl::of::<JobRowsSet>(
831        "An application's row source in the jobs list is declared or its rows replaced, from any thread: the source's id, title (the filter's label), owner and every row it has now (id, title, state, progress, detail, symbol, group, actions); the jobs plugin keeps them, and the list shows them beside its own jobs.",
832    ),
833    PointDecl::of::<JobSourceDrop>(
834        "An application's row source is taken away from the jobs list, its rows with it, from any thread; a plugin disconnected takes the sources it owns with it.",
835    ),
836];
837
838/// What owns egui-pop's own listeners.
839pub const OWNER: &str = "egui_pop";
840/// What belongs to a closing window goes with it: its dialogs.
841pub const CHILDREN: &str = "pop.window.children";
842/// The window worked in before a closing one becomes the active one.
843pub const FOCUS: &str = "pop.window.focus";
844/// A window asked to the front by a command (`pop.window.activate`, reason
845/// `command`) is shown, restored and given the system's focus: the one
846/// place egui-pop sends `ViewportCommand::Focus`.
847pub const RAISE: &str = "pop.window.raise";
848/// Another window becoming the active one drops every window's shortcut
849/// in progress: a chord begun in one window is never finished in another
850/// (a local listener: the windows' key dispatchers are the interface's).
851pub const KEYS: &str = "pop.window.keys";
852/// The one list of windows and popups ([`AppHandle::windows_list`]).
853pub const REGISTRY: &str = "pop.window.registry";
854/// A window's place, kept when it closes, and moved onto a screen left
855/// when its screen is unplugged (`pop.screen.removed`).
856pub const PLACE: &str = "pop.window.place";
857/// Checks, last, the window invariants ([`crate::window_invariants`]).
858pub const INVARIANTS: &str = "pop.window.invariants";
859
860/// A window or popup as the registry holds it.
861#[derive(Clone, Debug, PartialEq, Serialize)]
862#[non_exhaustive]
863pub struct WindowRecord {
864    pub id: String,
865    pub kind: WindowKind,
866    pub owner: String,
867    #[serde(skip_serializing_if = "Option::is_none")]
868    pub parent: Option<String>,
869    /// Its viewport, as egui's debug text names it (`9FA2`), when it has
870    /// one.
871    #[serde(skip_serializing_if = "Option::is_none")]
872    pub viewport: Option<String>,
873    /// The reason of the request that opened it.
874    pub opened_because: Reason,
875    /// Whether it is the active window, the one worked in
876    /// (`pop.window.activate`): one window of the list is.
877    pub active: bool,
878    /// What draws into its own surface besides egui, as that part says it
879    /// (`egui_pop_core::window_surface`): the image viewport's image
880    /// surface, its format, colour space, route or why it has none.
881    #[serde(skip_serializing_if = "Option::is_none")]
882    pub surface: Option<serde_json::Value>,
883    /// Whether its native window's handles are known (`runner::window`
884    /// answers for its viewport): what a surface of its own needs.
885    #[serde(default, skip_serializing_if = "std::ops::Not::not")]
886    pub handles: bool,
887    /// How its native window was built for a surface below egui:
888    /// transparent, or opaque and why
889    /// (`egui_pop_core::window_surface::transparency`), when its builder
890    /// said it.
891    #[serde(skip_serializing_if = "Option::is_none")]
892    pub transparency: Option<egui_pop_core::window_surface::Transparency>,
893    /// Its viewport, to read `surface`.
894    #[serde(skip)]
895    pub(crate) viewport_id: Option<ViewportId>,
896}
897
898impl WindowRecord {
899    /// Its viewport, when it has one.
900    pub fn viewport_id(&self) -> Option<ViewportId> {
901        self.viewport_id
902    }
903}
904
905/// The registry's state: the windows and popups open, the main window
906/// first, then in opening order.
907#[derive(Debug, Default)]
908pub(crate) struct Registry {
909    records: Vec<WindowRecord>,
910    /// The windows activated (`pop.window.activate`), the active one last.
911    activated: Vec<String>,
912}
913
914impl Registry {
915    fn open(&mut self, req: &WindowRequest, viewport: Option<ViewportId>) {
916        self.records.retain(|r| r.id != req.window);
917        self.records.push(WindowRecord {
918            id: req.window.clone(),
919            kind: req.kind,
920            owner: req.owner.clone(),
921            parent: req.parent.clone(),
922            viewport: viewport.map(|v| format!("{v:?}")),
923            opened_because: req.reason,
924            active: false,
925            surface: None,
926            handles: false,
927            transparency: None,
928            viewport_id: viewport,
929        });
930    }
931
932    fn close(&mut self, id: &str) -> bool {
933        let before = self.records.len();
934        self.records.retain(|r| r.id != id);
935        self.activated.retain(|a| a != id);
936        before != self.records.len()
937    }
938
939    fn record(&self, id: &str) -> Option<&WindowRecord> {
940        self.records.iter().find(|r| r.id == id)
941    }
942
943    /// `id` is the active window.
944    fn activate(&mut self, id: &str) {
945        self.activated.retain(|a| a != id);
946        self.activated.push(id.to_string());
947    }
948
949    /// The windows activated still held, the active one first.
950    fn by_recency(&self) -> impl Iterator<Item = &WindowRecord> {
951        self.activated.iter().rev().filter_map(|a| self.record(a))
952    }
953
954    /// The active window: the last activated still held, else the main
955    /// window.
956    pub(crate) fn active(&self) -> (String, WindowKind) {
957        self.by_recency()
958            .next()
959            .map(|r| (r.id.clone(), r.kind))
960            .unwrap_or_else(|| (WindowId::MAIN.to_string(), WindowKind::Main))
961    }
962
963    fn holds(&self, id: &str) -> bool {
964        self.records.iter().any(|r| r.id == id)
965    }
966
967    /// The children of `from` (its popups, its native windows) become
968    /// `to`'s: `from`'s content moved there. How many.
969    fn adopt(&mut self, from: &str, to: &str) -> usize {
970        let mut moved = 0;
971        for r in &mut self.records {
972            if r.parent.as_deref() == Some(from) && r.id != to {
973                r.parent = Some(to.to_string());
974                moved += 1;
975            }
976        }
977        moved
978    }
979}
980
981/// The bus an application holds: the bus it was given (or the default
982/// kernel) and the window registry.
983pub(crate) struct Bus {
984    pub(crate) kernel: Arc<dyn bus_contract::Bus>,
985    pub(crate) registry: Arc<Mutex<Registry>>,
986    /// What the window invariants remember between passes
987    /// ([`crate::window_invariants`]).
988    pub(crate) invariants: Mutex<crate::window_invariants::State>,
989    /// The screens this application follows ([`screens`]).
990    pub(crate) screens: RefCell<screens::Seen>,
991    /// Whether each window had the system's focus at its last pass: a
992    /// window gaining it asks `pop.window.activate` (`system`) once.
993    focus_seen: RefCell<std::collections::BTreeMap<ViewportId, bool>>,
994    /// Application windows raised by a command, asked the focus again
995    /// from their own next pass (one not drawn yet has no system window).
996    raise_pending: RefCell<std::collections::BTreeSet<ViewportId>>,
997    /// Counts the changes of the active window ([`KEYS`]): a window's key
998    /// dispatcher that saw another count drops its shortcut in progress.
999    pub(crate) keys_epoch: Rc<Cell<u64>>,
1000    /// The last journal event delivered to the event points' listeners.
1001    delivered: Cell<Seq>,
1002    /// A delivery runs: one asked from inside it is left to it.
1003    delivering: Cell<bool>,
1004    /// The job events said, not recorded yet.
1005    pub(crate) jobs: JobPublisher,
1006    /// The journal numbers of the job events, with their kind: what goes
1007    /// to [`JobEvents`], by number, never by name.
1008    job_tags: RefCell<std::collections::BTreeMap<Seq, JobEventKind>>,
1009    /// The settings the value store changed, not said yet
1010    /// ([`AppHandle::deliver_settings`]).
1011    pub(crate) settings_heard: settings::Heard,
1012    /// A delivery of settings runs.
1013    settings_delivering: Cell<bool>,
1014    /// The context a pass is asked of when an emit on another thread
1015    /// queues local listeners ([`AppHandle::run_pending`]).
1016    wake: Arc<Mutex<Option<egui::Context>>>,
1017    /// The overlays of the stack the registry holds as popups.
1018    pub(crate) overlays: RefCell<overlays::Overlays>,
1019    /// Each panel's state not ready (`pop.panel.state`), for its chrome.
1020    pub(crate) panel_states: panel_state::States,
1021    /// Passes over a point's budget, to say (`bus.overBudget`).
1022    pub(crate) over_budget: budget::Heard,
1023    /// The last notices raised ([`NOTICE_STORE`]) and their routing
1024    /// ([`NOTICE_ROUTE`]).
1025    pub(crate) notices: notices::Store,
1026}
1027
1028impl std::fmt::Debug for Bus {
1029    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
1030        f.debug_struct("Bus").finish_non_exhaustive()
1031    }
1032}
1033
1034impl Default for Bus {
1035    fn default() -> Self {
1036        Bus::new(None)
1037    }
1038}
1039
1040impl Bus {
1041    /// On the bus the application supplies (`AppBuilder::bus`), or on
1042    /// the default kernel: egui-pop's points declared, its listeners
1043    /// registered.
1044    pub(crate) fn new(supplied: Option<Arc<dyn bus_contract::Bus>>) -> Self {
1045        let kernel = supplied.unwrap_or_else(|| Arc::new(egui_pop_hooks::Kernel::new()));
1046        let mut main = Registry::default();
1047        main.open(
1048            &WindowRequest::new(WindowId::MAIN, WindowKind::Main, "app", Reason::System),
1049            Some(ViewportId::ROOT),
1050        );
1051        main.activate(WindowId::MAIN);
1052        let registry = Arc::new(Mutex::new(main));
1053        install(&*kernel, &registry);
1054        let keys_epoch = Rc::new(Cell::new(0));
1055        activate::install_keys(&*kernel, keys_epoch.clone());
1056        let wake: Arc<Mutex<Option<egui::Context>>> = Arc::default();
1057        {
1058            let wake = wake.clone();
1059            // Local listeners queued and requests asked for after the
1060            // drawing both wait for the main window's pass, whichever
1061            // window asked: it runs them (`run_pending`, `drain_asks`).
1062            kernel.on_pending(move |_| {
1063                if let Some(ctx) = lock(&wake).as_ref() {
1064                    ctx.request_repaint_of(ViewportId::ROOT);
1065                }
1066            });
1067        }
1068        let panel_states = panel_state::States::default();
1069        panel_state::install(&*kernel, &panel_states, wake.clone());
1070        panel_describe::install(&*kernel);
1071        panel_open::install(&*kernel);
1072        panel_retitle::install(&*kernel);
1073        areas::install(&*kernel, wake.clone());
1074        let over_budget = budget::install(&*kernel);
1075        let notices = Arc::new(notices::Hub::new(wake.clone()));
1076        notices::install(&*kernel, &notices);
1077        let jobs = JobPublisher {
1078            said: Arc::default(),
1079            wake: wake.clone(),
1080        };
1081        Bus {
1082            kernel,
1083            registry,
1084            invariants: Mutex::default(),
1085            screens: RefCell::default(),
1086            focus_seen: RefCell::default(),
1087            raise_pending: RefCell::default(),
1088            keys_epoch,
1089            delivered: Cell::new(0),
1090            delivering: Cell::new(false),
1091            jobs,
1092            job_tags: RefCell::default(),
1093            settings_heard: settings::Heard::default(),
1094            settings_delivering: Cell::new(false),
1095            wake,
1096            overlays: RefCell::default(),
1097            panel_states,
1098            over_budget,
1099            notices,
1100        }
1101    }
1102
1103    /// The context to wake when local listeners are queued for the
1104    /// interface's thread.
1105    pub(crate) fn wake_with(&self, ctx: &egui::Context) {
1106        let mut wake = lock(&self.wake);
1107        if wake.as_ref() != Some(ctx) {
1108            *wake = Some(ctx.clone());
1109        }
1110    }
1111}
1112
1113thread_local! {
1114    /// The applications whose request is running, innermost last: what a
1115    /// listener acts on. Listeners run inline, on the thread that asked.
1116    static ASKING: RefCell<Vec<WeakApp>> = const { RefCell::new(Vec::new()) };
1117}
1118
1119/// The application whose request runs now, for a listener (listeners
1120/// are `Send + Sync` and keep no handle): an application's listener of
1121/// `pop.files.drop` runs its import command on it. `None` outside a request.
1122///
1123/// <div class="warning">Experimental: may change in any release
1124/// (docs/stability.md).</div>
1125pub fn asking() -> Option<AppHandle> {
1126    ASKING.with_borrow(|a| a.last().and_then(|w| w.get().ok()))
1127}
1128
1129thread_local! {
1130    /// The context whose main window's pass runs [`AppHandle::run_pending`]
1131    /// now: a listener it runs is drawn by that pass, which asks for no
1132    /// other main pass ([`AppHandle::wake_window`]).
1133    static MAIN_PENDING: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
1134}
1135
1136/// Marks [`MAIN_PENDING`] while the main window's pass runs the pending
1137/// listeners; the previous mark back when they end, even by a panic.
1138struct MainPending(Option<egui::Context>);
1139
1140impl MainPending {
1141    fn enter(ctx: egui::Context) -> Self {
1142        Self(MAIN_PENDING.with_borrow_mut(|m| m.replace(ctx)))
1143    }
1144}
1145
1146impl Drop for MainPending {
1147    fn drop(&mut self) {
1148        let previous = self.0.take();
1149        MAIN_PENDING.with_borrow_mut(|m| *m = previous);
1150    }
1151}
1152
1153/// Takes the application off [`ASKING`] when the request ends, even by a
1154/// panic a listener's boundary did not catch.
1155struct Asking;
1156
1157impl Drop for Asking {
1158    fn drop(&mut self) {
1159        ASKING.with_borrow_mut(|a| a.pop());
1160    }
1161}
1162
1163/// Runs `P`'s listeners for `app`, inline: what they did, in order, and
1164/// their failures logged.
1165fn emit<P: Point<Input = WindowRequest, Value = Vec<String>>>(
1166    app: &AppHandle,
1167    req: WindowRequest,
1168) -> Vec<String> {
1169    emit_with::<P>(app, req, Vec::new())
1170}
1171
1172/// Runs `P`'s listeners for `app`, inline, from `value`: what they left,
1173/// their failures logged.
1174fn emit_with<P: Point>(app: &AppHandle, input: P::Input, value: P::Value) -> P::Value
1175where
1176    P::Value: Clone,
1177{
1178    ASKING.with_borrow_mut(|a| a.push(app.downgrade()));
1179    let _asking = Asking;
1180    let out = app.0.bus.kernel.alter::<P>(input, value);
1181    for f in &out.failures {
1182        log::error!(target: "egui_pop", "{f}");
1183    }
1184    out.value
1185}
1186
1187/// Ends a delivery, even by a panic a listener's boundary did not catch.
1188struct Delivering<'a>(&'a Cell<bool>);
1189
1190impl Drop for Delivering<'_> {
1191    fn drop(&mut self) {
1192        self.0.set(false);
1193    }
1194}
1195
1196/// Declares the window points and registers egui-pop's listeners.
1197fn install(kernel: &dyn bus_contract::Bus, registry: &Arc<Mutex<Registry>>) {
1198    // A second application on the same bus finds its points declared
1199    // (ADR 0030: one egui-pop application per bus).
1200    for refused in bus_contract::declare_all(kernel, CONTRACT) {
1201        log::error!(target: "egui_pop", "{refused}: one egui-pop application per bus");
1202    }
1203    let mine = || ListenOpts::new().owner(OWNER);
1204    // `pop.window.close`, in the ADR's order.
1205    let listened = [
1206        kernel.listen::<WindowClose>(CHILDREN, mine().before(FOCUS).priority(1000), |req, did| {
1207            let Some(app) = asking() else { return Ok(()) };
1208            if req.kind == WindowKind::Main {
1209                shell::close_children_of_main(&app, req, did);
1210            }
1211            popups::close_children(&app, req, did);
1212            Ok(())
1213        }),
1214        kernel.listen::<WindowClose>(FOCUS, mine().before(REGISTRY), |req, did| {
1215            let Some(app) = asking() else { return Ok(()) };
1216            app.forget_focus(req);
1217            if app.focus_before_close(&req.window).is_some() {
1218                did.push(format!("{FOCUS}: the window worked in before is active"));
1219            }
1220            Ok(())
1221        }),
1222        {
1223            let registry = registry.clone();
1224            kernel.listen::<WindowClose>(REGISTRY, mine().after(FOCUS), move |req, did| {
1225                let held = lock(&registry).close(&req.window);
1226                if let Some(app) = asking() {
1227                    match req.kind {
1228                        WindowKind::App => app.registry_close(&WindowId::new(&req.window)),
1229                        WindowKind::Main if held => app.registry_close_main(),
1230                        WindowKind::Panel if held => panels::left(&app, &req.window),
1231                        _ => {}
1232                    }
1233                }
1234                if held {
1235                    did.push(format!("{REGISTRY}: closed"));
1236                }
1237                Ok(())
1238            })
1239        },
1240        kernel.listen::<WindowClose>(PLACE, mine().after(REGISTRY), |req, did| {
1241            let Some(app) = asking() else { return Ok(()) };
1242            if req.kind == WindowKind::App && app.keep_closing_place(&WindowId::new(&req.window)) {
1243                did.push(format!("{PLACE}: its place kept"));
1244            }
1245            Ok(())
1246        }),
1247        {
1248            let registry = registry.clone();
1249            kernel.listen::<WindowClose>(INVARIANTS, mine().last(), move |req, did| {
1250                let left = lock(&registry).holds(&req.window);
1251                let mut rest = true;
1252                if let Some(app) = asking() {
1253                    if left {
1254                        app.invariant_broken(crate::window_invariants::closed_left(req));
1255                    }
1256                    rest = app.check_invariants_after_request();
1257                }
1258                if left {
1259                    return Err(format!("`{}` is still in the registry", req.window).into());
1260                }
1261                did.push(format!(
1262                    "{INVARIANTS}: {}",
1263                    if rest { "held" } else { "broken" }
1264                ));
1265                Ok(())
1266            })
1267        },
1268    ];
1269    for l in listened {
1270        debug_assert!(l.is_ok(), "{l:?}");
1271    }
1272    // The paths not moved yet report to the registry through their points.
1273    let registry_open = |registry: Arc<Mutex<Registry>>| {
1274        move |req: &WindowRequest, did: &mut Vec<String>| {
1275            let viewport = crate::window_invariants::viewport_of(req.kind, &req.window);
1276            lock(&registry).open(req, viewport);
1277            did.push(format!("{REGISTRY}: holds it"));
1278            Ok(())
1279        }
1280    };
1281    let _ = kernel.listen::<WindowOpen>(REGISTRY, mine(), registry_open(registry.clone()));
1282    let _ = kernel.listen::<PopupOpen>(REGISTRY, mine(), registry_open(registry.clone()));
1283    {
1284        let registry = registry.clone();
1285        let _ = kernel.listen::<PopupClose>(REGISTRY, mine(), move |req, did| {
1286            if lock(&registry).close(&req.window) {
1287                did.push(format!("{REGISTRY}: closed"));
1288            }
1289            Ok(())
1290        });
1291    }
1292    shell::install(kernel, registry);
1293    activate::install(kernel, registry);
1294    panels::install(kernel);
1295    owners::install(kernel);
1296    files::install(kernel);
1297    overlays::install(kernel);
1298    drag::install(kernel);
1299    screens::install(kernel);
1300    // The invariants check runs last on every other window point: the
1301    // rules the registry alone answers (the backend's and the paint
1302    // guard's are checked in the main window's pass).
1303    let check = |_: &WindowRequest, did: &mut Vec<String>| {
1304        let held = asking().is_none_or(|app| app.check_invariants_after_request());
1305        did.push(format!(
1306            "{INVARIANTS}: {}",
1307            if held { "held" } else { "broken" }
1308        ));
1309        Ok(())
1310    };
1311    let others = [
1312        kernel.listen::<WindowOpen>(INVARIANTS, mine().last(), check),
1313        kernel.listen::<WindowReparent>(INVARIANTS, mine().last(), check),
1314        kernel.listen::<WindowActivate>(INVARIANTS, mine().last(), check),
1315        kernel.listen::<PopupOpen>(INVARIANTS, mine().last(), check),
1316        kernel.listen::<PopupClose>(INVARIANTS, mine().last(), check),
1317    ];
1318    for l in others {
1319        debug_assert!(l.is_ok(), "{l:?}");
1320    }
1321}
1322
1323impl AppHandle {
1324    /// Registers a local listener on `P` under `id` for the window
1325    /// `window`: each time it runs, that window is woken, so what it
1326    /// changed is drawn there within one frame. Bound to the calling
1327    /// thread (the interface's), as [`bus_contract::Bus::listen_local_any`].
1328    ///
1329    /// An emit on this thread runs it inline and asks for a pass of the
1330    /// window. An emit from another thread queues it: the bus waker asks
1331    /// for the main window's pass, which runs it ([`AppHandle::run_pending`];
1332    /// a request asked for after the drawing is heard at the main
1333    /// window's drain), and its run then asks for the window's pass.
1334    /// The main window is woken as before; the window is woken as well,
1335    /// rather than redrawn by hand. A window drawn in the main one (the
1336    /// main window itself, a detached panel's, every window where the
1337    /// windows are embedded: the web, kittest) and a window not open
1338    /// wake the main window.
1339    ///
1340    /// <div class="warning">Experimental: may change in any release
1341    /// (docs/stability.md).</div>
1342    pub fn listen_local_in<P: Point>(
1343        &self,
1344        window: &WindowId,
1345        id: impl Into<String>,
1346        opts: ListenOpts,
1347        run: impl Fn(&P::Input, &mut P::Value) -> Result<(), bus_contract::HookError> + 'static,
1348    ) -> Result<(), bus_contract::Refused> {
1349        let (app, window) = (self.downgrade(), window.clone());
1350        self.bus().listen_local::<P>(id, opts, move |input, value| {
1351            let out = run(input, value);
1352            if let Ok(app) = app.get() {
1353                app.wake_window(&window);
1354            }
1355            out
1356        })
1357    }
1358
1359    /// Asks for a pass of the window `window`: its own viewport's when
1360    /// it is an open application window with a system window of its own;
1361    /// else the main window's, where it is drawn (or nothing is).
1362    /// Asked by a listener [`AppHandle::run_pending`] runs in the main
1363    /// window's pass, the main window's pass is not asked for: that pass
1364    /// has not drawn yet, so it draws what the listener changed.
1365    ///
1366    /// <div class="warning">Experimental: may change in any release
1367    /// (docs/stability.md).</div>
1368    pub fn wake_window(&self, window: &WindowId) {
1369        let ctx = self.egui();
1370        let wake_main = || {
1371            if !MAIN_PENDING.with_borrow(|m| m.as_ref() == Some(&ctx)) {
1372                ctx.request_repaint_of(ViewportId::ROOT);
1373            }
1374        };
1375        let viewport = match self.0.windows.try_borrow() {
1376            Ok(w) => w.viewport_of(window),
1377            // Asked while the registry is changed (a listener run from a
1378            // window's opening or closing): its viewport and the main
1379            // window's, whichever draws it.
1380            Err(_) => {
1381                wake_main();
1382                Some(window.deferred_viewport())
1383            }
1384        };
1385        match viewport {
1386            Some(v) if v != ViewportId::ROOT && !ctx.embed_viewports() => {
1387                ctx.request_repaint_of(v);
1388            }
1389            _ => wake_main(),
1390        }
1391    }
1392
1393    /// Runs the local listeners ([`bus_contract::Bus::listen_local_any`])
1394    /// that emits on other threads queued for this thread, in their
1395    /// order, with this application as [`asking`]; their failures
1396    /// logged. The application calls it once per pass, before the
1397    /// `On::Pass` handlers; an emit that queues some asks for a pass.
1398    ///
1399    /// <div class="warning">Experimental: may change in any release
1400    /// (docs/stability.md).</div>
1401    pub fn run_pending(&self) -> Vec<bus_contract::PendingRun> {
1402        ASKING.with_borrow_mut(|a| a.push(self.downgrade()));
1403        let _asking = Asking;
1404        let ctx = self.egui();
1405        let in_main = matches!(
1406            crate::app::pass_in_progress(&ctx),
1407            Some((ViewportId::ROOT, _))
1408        );
1409        let _main = in_main.then(|| MainPending::enter(ctx));
1410        let ran = self.0.bus.kernel.run_pending();
1411        for f in ran.iter().flat_map(|r| &r.failures) {
1412            log::error!(target: "egui_pop", "{f}");
1413        }
1414        ran
1415    }
1416
1417    /// Asks the request `P` now and hears it after the drawing: its
1418    /// listeners run at the bus's next drain on this thread
1419    /// ([`AppHandle::drain_asks`]), which the application makes once per
1420    /// pass after the panels and windows are drawn, and once more before
1421    /// it quits. For code that cannot be re-entered while it draws (a
1422    /// panel with its state borrowed). The ask's number; `None` when the
1423    /// application's bus does not offer the `Defer` capability
1424    /// ([`bus_contract_defer::BusDefer::defer`]), the caller then asking it at once
1425    /// or keeping it.
1426    ///
1427    /// Asked in a detached panel's window, drawn inside the main window's
1428    /// pass, it is heard at the end of that pass. Asked in an application
1429    /// window (a deferred viewport, drawn on the same thread after the
1430    /// main window), it waits in the same queue for the main window's
1431    /// next pass, which is asked for.
1432    ///
1433    /// <div class="warning">Experimental: may change in any release
1434    /// (docs/stability.md).</div>
1435    pub fn ask<P: Point>(&self, input: P::Input, value: P::Value) -> Option<u64>
1436    where
1437        P::Value: Clone,
1438    {
1439        let bus = self.bus();
1440        let defer = bus.defer()?;
1441        Some(defer.ask::<P>(input, value))
1442    }
1443
1444    /// Runs the requests asked on this thread for after the drawing
1445    /// ([`AppHandle::ask`], or [`bus_contract_defer::Defer`] on the
1446    /// application's bus), in ask order, with this application as
1447    /// [`asking`]; what each did, failures logged and refusals noted.
1448    /// An ask made by a listener while it runs waits for the next drain.
1449    /// A drain that ran something asks for a pass, so what it changed is
1450    /// drawn. Empty when nothing waits or the bus has no `Defer`.
1451    ///
1452    /// The application calls it once per pass after the panels and
1453    /// windows are drawn ([`crate::App::show`]) and before it quits
1454    /// ([`crate::App::exit`]); a host drawing the application in its own
1455    /// way may call it too.
1456    ///
1457    /// <div class="warning">Experimental: may change in any release
1458    /// (docs/stability.md).</div>
1459    pub fn drain_asks(&self) -> Vec<bus_contract::PendingRun> {
1460        let bus = self.bus();
1461        let Some(defer) = bus.defer() else {
1462            return Vec::new();
1463        };
1464        if defer.waiting() == 0 {
1465            return Vec::new();
1466        }
1467        ASKING.with_borrow_mut(|a| a.push(self.downgrade()));
1468        let _asking = Asking;
1469        let ran = defer.drain();
1470        for r in &ran {
1471            for f in &r.failures {
1472                log::error!(target: "egui_pop", "{f}");
1473            }
1474            if let Some(refused) = &r.refused {
1475                log::info!(target: "egui_pop", "{refused}");
1476            }
1477        }
1478        if !ran.is_empty() {
1479            self.egui().request_repaint_of(ViewportId::ROOT);
1480        }
1481        ran
1482    }
1483
1484    /// How many requests wait for this thread's next drain
1485    /// ([`AppHandle::drain_asks`]): zero when the bus has no `Defer`.
1486    ///
1487    /// <div class="warning">Experimental: may change in any release
1488    /// (docs/stability.md).</div>
1489    pub fn asks_waiting(&self) -> usize {
1490        self.bus().defer().map_or(0, |d| d.waiting())
1491    }
1492
1493    /// The application's bus: the one given to `AppBuilder::bus`, or the
1494    /// hook kernel egui-pop made, where its requests' listeners are
1495    /// registered (ADR 0029, ADR 0030). A part that cares about a window closing
1496    /// listens to [`WindowClose`] under a name of its own, declaring its
1497    /// place (`after` / `before` the listeners of this module).
1498    ///
1499    /// <div class="warning">Experimental: may change in any release
1500    /// (docs/stability.md).</div>
1501    pub fn bus(&self) -> Arc<dyn bus_contract::Bus> {
1502        self.0.bus.kernel.clone()
1503    }
1504
1505    /// The windows and popups on screen, as the registry holds them: the
1506    /// main window first, then in opening order (`windows.list`).
1507    ///
1508    /// <div class="warning">Experimental: may change in any release
1509    /// (docs/stability.md).</div>
1510    pub fn windows_list(&self) -> Vec<WindowRecord> {
1511        let r = lock(&self.0.bus.registry);
1512        let (active, _) = r.active();
1513        let mut list = r.records.clone();
1514        drop(r);
1515        let ctx = self.egui();
1516        for w in &mut list {
1517            w.active = w.id == active;
1518            w.surface = w
1519                .viewport_id
1520                .and_then(|v| egui_pop_core::window_surface::get(&ctx, v));
1521            w.transparency = w
1522                .viewport_id
1523                .and_then(|v| egui_pop_core::window_surface::transparency(&ctx, v));
1524            #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
1525            {
1526                w.handles = w
1527                    .viewport_id
1528                    .is_some_and(|v| crate::runner::window(v).is_some());
1529            }
1530        }
1531        list
1532    }
1533
1534    /// The order the listeners of the window and popup points run in
1535    /// ([`order_dump`]).
1536    ///
1537    /// <div class="warning">Experimental: may change in any release
1538    /// (docs/stability.md).</div>
1539    pub fn bus_order(&self) -> String {
1540        order_dump(&*self.0.bus.kernel, &WINDOW_POINTS)
1541    }
1542
1543    /// Asks for an application window's close (`pop.window.close`): its
1544    /// listeners all run now, in their declared order, the owner's state
1545    /// closing with it; `window.closed` is said after the last one. A
1546    /// before-hook on the `window.close` step may veto it, and a window
1547    /// not open is refused: both said as `window.refused`. Whether it
1548    /// closed.
1549    ///
1550    /// The system window itself goes at the main window's next pass,
1551    /// which no longer declares it; a pass of it in between draws its
1552    /// last page.
1553    ///
1554    /// <div class="warning">Experimental: may change in any release
1555    /// (docs/stability.md).</div>
1556    pub fn request_window_close(&self, request: WindowRequest) -> bool {
1557        let id = WindowId::new(&request.window);
1558        let open = match request.kind {
1559            WindowKind::App => self.windows_ref().entry(&id).is_some(),
1560            WindowKind::Main => lock(&self.0.bus.registry).holds(WindowId::MAIN),
1561            _ => lock(&self.0.bus.registry).holds(&request.window),
1562        };
1563        if !open {
1564            self.publish(
1565                "egui_pop",
1566                None,
1567                "window.refused",
1568                json!({ "request": WindowClose::ID.as_str(), "window": request.window, "owner": request.owner, "reason": "no open window of this id" }),
1569            );
1570            return false;
1571        }
1572        let args = serde_json::to_value(&request).unwrap_or_default();
1573        let outcome = self.step(&STEP_WINDOW_CLOSE, args, |app, args| {
1574            // A before-hook may have redirected it.
1575            let req = serde_json::from_value::<WindowRequest>(args.clone())
1576                .map_err(|e| format!("not a window request: {e}"))?;
1577            // The main window's close with another window open moves
1578            // that window into it (ADR 0025): a `pop.window.reparent`.
1579            if let Some(moved) = shell::move_in_instead(app, &req) {
1580                return Ok(moved);
1581            }
1582            let did = emit::<WindowClose>(app, req);
1583            Ok(json!({ "did": did }))
1584        });
1585        match outcome {
1586            crate::steps::Outcome::Vetoed { by, reason } => {
1587                self.publish(
1588                    "egui_pop",
1589                    None,
1590                    "window.refused",
1591                    json!({ "request": WindowClose::ID.as_str(), "window": request.window, "owner": request.owner, "vetoed_by": by, "reason": reason }),
1592                );
1593                false
1594            }
1595            crate::steps::Outcome::Done(Ok(moved)) if moved.get(shell::MOVED_IN).is_some() => {
1596                // It did not close: the window moved in instead.
1597                false
1598            }
1599            crate::steps::Outcome::Done(result) => {
1600                let mut data = json!({
1601                    "window": request.window,
1602                    "kind": request.kind,
1603                    "owner": request.owner,
1604                    "reason": request.reason,
1605                });
1606                if let Some(c) = request.cause {
1607                    data["cause"] = json!(c);
1608                }
1609                if let Err(e) = &result {
1610                    data["error"] = json!(e);
1611                }
1612                self.publish("egui_pop", request.cause, "window.closed", data);
1613                result.is_ok()
1614            }
1615        }
1616    }
1617
1618    /// The order the listeners of the job and plugin points run in
1619    /// ([`order_dump`]).
1620    ///
1621    /// <div class="warning">Experimental: may change in any release
1622    /// (docs/stability.md).</div>
1623    pub fn bus_order_of(&self, points: &[&str]) -> String {
1624        order_dump(&*self.0.bus.kernel, points)
1625    }
1626
1627    /// Asks a panel's state (`pop.panel.state`): its listeners run now, in
1628    /// their declared order (the workbench's keeps it for the panel's
1629    /// chrome). What they did, one line each. An application holding the
1630    /// bus may ask it there, from any thread.
1631    ///
1632    /// <div class="warning">Experimental: may change in any release
1633    /// (docs/stability.md).</div>
1634    pub fn request_panel_state(&self, ask: PanelStateAsk) -> Vec<String> {
1635        emit_with::<PanelStateSet>(self, ask, Vec::new())
1636    }
1637
1638    /// Declares a row source in the jobs list, or replaces its rows
1639    /// (`pop.jobs.rows`): its listeners run now (the jobs plugin's keeps
1640    /// them for the list). What they did, one line each. An application
1641    /// holding the bus may ask it there, from any thread.
1642    ///
1643    /// <div class="warning">Experimental: may change in any release
1644    /// (docs/stability.md).</div>
1645    pub fn request_job_rows(&self, ask: JobRowsAsk) -> Vec<String> {
1646        emit_with::<JobRowsSet>(self, ask, Vec::new())
1647    }
1648
1649    /// Takes a row source away from the jobs list
1650    /// (`pop.jobs.source.drop`), its rows with it.
1651    ///
1652    /// <div class="warning">Experimental: may change in any release
1653    /// (docs/stability.md).</div>
1654    pub fn request_job_source_drop(&self, ask: JobSourceAsk) -> Vec<String> {
1655        emit_with::<JobSourceDrop>(self, ask, Vec::new())
1656    }
1657
1658    /// Describes a declared panel (`pop.panel.describe`): its listeners run
1659    /// now (the workbench's fills it from the declaration, its kind
1660    /// included); `None` for a panel nobody knows.
1661    ///
1662    /// <div class="warning">Experimental: may change in any release
1663    /// (docs/stability.md).</div>
1664    pub fn describe_panel(&self, panel: &str) -> Option<PanelDescription> {
1665        emit_with::<PanelDescribe>(self, panel.to_string(), None)
1666    }
1667
1668    /// Opens a panel (`pop.panel.open`): its listeners run now (the
1669    /// workbench's runs the `workbench.show` step, or queues it while the
1670    /// areas are drawn); what they did, one line each, or why it did not
1671    /// open.
1672    ///
1673    /// <div class="warning">Experimental: may change in any release
1674    /// (docs/stability.md).</div>
1675    pub fn open_panel(&self, ask: PanelOpenAsk) -> Result<Vec<String>, String> {
1676        ASKING.with_borrow_mut(|a| a.push(self.downgrade()));
1677        let _asking = Asking;
1678        let out = self.0.bus.kernel.alter::<PanelOpen>(ask, Vec::new());
1679        if out.failures.is_empty() {
1680            Ok(out.value)
1681        } else {
1682            let why: Vec<String> = out.failures.iter().map(ToString::to_string).collect();
1683            Err(why.join("; "))
1684        }
1685    }
1686
1687    /// Retitles an open panel instance (`pop.panel.retitle`): its
1688    /// listeners run now (the workbench's keeps the title in the layout's
1689    /// instance entry); what they did, one line each, or why it was
1690    /// refused. [`AppHandle::set_instance_title`] asks it from code.
1691    ///
1692    /// <div class="warning">Experimental: may change in any release
1693    /// (docs/stability.md).</div>
1694    pub fn retitle_panel(&self, ask: PanelRetitleAsk) -> Result<Vec<String>, String> {
1695        ASKING.with_borrow_mut(|a| a.push(self.downgrade()));
1696        let _asking = Asking;
1697        let out = self.0.bus.kernel.alter::<PanelRetitle>(ask, Vec::new());
1698        if out.failures.is_empty() {
1699            Ok(out.value)
1700        } else {
1701            let why: Vec<String> = out.failures.iter().map(ToString::to_string).collect();
1702            Err(why.join("; "))
1703        }
1704    }
1705
1706    /// The interactive areas of each window's last pass (`pop.ui.areas`):
1707    /// what each writes, an edit area's control, value and grips, and
1708    /// whether it is inert.
1709    ///
1710    /// <div class="warning">Experimental: may change in any release
1711    /// (docs/stability.md).</div>
1712    pub fn ui_areas(&self) -> Vec<egui_pop_core::areas::AreaRecord> {
1713        emit_with::<UiAreas>(self, (), Vec::new())
1714    }
1715
1716    /// The application's choice of the panel zen mode shows
1717    /// (`pop.zen.panel`): `None` while no listener picks one.
1718    ///
1719    /// <div class="warning">Experimental: may change in any release
1720    /// (docs/stability.md).</div>
1721    pub fn zen_choice(&self) -> Option<String> {
1722        emit_with::<ZenPanel>(self, (), None)
1723    }
1724
1725    /// What the application says of a command's title and tooltip now
1726    /// (`pop.command.label`): empty while no listener answers.
1727    ///
1728    /// <div class="warning">Experimental: may change in any release
1729    /// (docs/stability.md).</div>
1730    pub fn command_text(&self, command: &egui_pop_model::ids::CommandId) -> CommandText {
1731        emit_with::<CommandLabel>(self, command.clone(), CommandText::default())
1732    }
1733
1734    /// A panel's state as last asked (`pop.panel.state`): ready when never
1735    /// asked.
1736    ///
1737    /// <div class="warning">Experimental: may change in any release
1738    /// (docs/stability.md).</div>
1739    pub fn panel_state(&self, panel: &str) -> PanelState {
1740        lock(&self.0.bus.panel_states)
1741            .get(panel)
1742            .map_or(PanelState::Ready, |k| k.state.clone())
1743    }
1744
1745    /// Asks about a job (`pop.job.cancel`, `pop.job.pause`, `pop.job.resume`,
1746    /// `pop.job.retry`): its listeners run now, in their declared order (the
1747    /// jobs plugin's: the job shows as asked, then whoever runs it is
1748    /// asked); the answer comes as the runner's job events. What they
1749    /// did, one line each; with nobody listening (no jobs plugin) it is
1750    /// refused, said as `job.refused`.
1751    ///
1752    /// <div class="warning">Experimental: may change in any release
1753    /// (docs/stability.md).</div>
1754    pub fn request_job(&self, ask: JobAsk) -> Vec<String> {
1755        use egui_pop_model::jobs::Request;
1756        let point = ask.request.command();
1757        let id = ask.id.clone();
1758        let did = match ask.request {
1759            Request::Cancel => emit_with::<JobCancel>(self, ask, Vec::new()),
1760            Request::Pause => emit_with::<JobPause>(self, ask, Vec::new()),
1761            Request::Resume => emit_with::<JobResume>(self, ask, Vec::new()),
1762            Request::Retry => emit_with::<JobRetry>(self, ask, Vec::new()),
1763        };
1764        if did.is_empty() {
1765            log::warn!(target: "egui_pop", "`{point}` of job `{id}`: nobody listens (no jobs plugin)");
1766            self.publish(
1767                "egui_pop",
1768                None,
1769                "job.refused",
1770                json!({ "request": point, "id": id, "reason": "nobody listens to it (no jobs plugin)" }),
1771            );
1772        }
1773        did
1774    }
1775
1776    /// Delivers the journal's events not delivered yet to the event
1777    /// points' listeners ([`JobEvents`]), in journal order, once each.
1778    /// Each pass does it before its handlers run; a read that must see
1779    /// every event up to the last (a wait, a plugin going) does it first.
1780    /// Asked from inside a delivery, it returns at once: the delivery
1781    /// running goes on, and what it did not take waits for the next.
1782    ///
1783    /// <div class="warning">Experimental: may change in any release
1784    /// (docs/stability.md).</div>
1785    pub fn deliver_events(&self) {
1786        let bus = &self.0.bus;
1787        if bus.delivering.replace(true) {
1788            return;
1789        }
1790        let _delivering = Delivering(&bus.delivering);
1791        self.record_job_events();
1792        let events = self.events_since(bus.delivered.get());
1793        for e in events {
1794            bus.delivered.set(e.seq);
1795            if let Some(job) = self.job_event_of(&e) {
1796                emit_with::<JobEvents>(self, job, ());
1797            }
1798        }
1799    }
1800
1801    /// Says a job event on `pop.job.event` ([`JobPublisher::publish`]):
1802    /// recorded and delivered at the next delivery.
1803    ///
1804    /// <div class="warning">Experimental: may change in any release
1805    /// (docs/stability.md).</div>
1806    pub fn publish_job(&self, source: &str, kind: JobEventKind, data: serde_json::Value) {
1807        self.0.bus.jobs.publish(source, kind, data);
1808    }
1809
1810    /// A publisher of job events, for any thread.
1811    ///
1812    /// <div class="warning">Experimental: may change in any release
1813    /// (docs/stability.md).</div>
1814    pub fn job_publisher(&self) -> JobPublisher {
1815        self.0.bus.jobs.clone()
1816    }
1817
1818    /// Notes that the journal's event `seq` is a job event of `kind`.
1819    pub(crate) fn tag_job_event(&self, seq: Seq, kind: JobEventKind) {
1820        let mut tags = self.0.bus.job_tags.borrow_mut();
1821        tags.insert(seq, kind);
1822        while tags.len() > JOB_TAGS {
1823            tags.pop_first();
1824        }
1825    }
1826
1827    /// The job event a journal event is, by its number: one recorded as
1828    /// such, never one named like one.
1829    pub(crate) fn job_event_of(&self, e: &Event) -> Option<JobEvent> {
1830        let kind = *self.0.bus.job_tags.borrow().get(&e.seq)?;
1831        Some(JobEvent {
1832            seq: e.seq,
1833            source: e.source.clone(),
1834            cause: e.cause,
1835            kind,
1836            data: e.data.clone(),
1837        })
1838    }
1839
1840    /// Records the job events said in the journal, in order, when the
1841    /// host is free (else they wait for the next delivery).
1842    fn record_job_events(&self) {
1843        if !self.host_free() {
1844            return;
1845        }
1846        for said in self.0.bus.jobs.take() {
1847            let seq = self.publish_now(&said.source, None, said.kind.name(), said.data);
1848            self.tag_job_event(seq, said.kind);
1849        }
1850    }
1851
1852    /// The last journal event delivered ([`AppHandle::deliver_events`]):
1853    /// a listener registering late reads the record up to it.
1854    pub(crate) fn delivered_event(&self) -> Seq {
1855        self.0.bus.delivered.get()
1856    }
1857
1858    /// Asks the plugin points' listeners about a plugin connected: what
1859    /// they did.
1860    pub(crate) fn plugin_connected(&self, change: PluginChange) -> Vec<String> {
1861        self.deliver_events();
1862        emit_with::<PluginConnect>(self, change, Vec::new())
1863    }
1864
1865    /// Asks the plugin points' listeners about a plugin disconnected,
1866    /// before `plugin.disconnected` is said: what they did, counted.
1867    pub(crate) fn plugin_disconnected(
1868        &self,
1869        change: PluginChange,
1870    ) -> serde_json::Map<String, serde_json::Value> {
1871        // Up to the last event: a job started since the last pass counts.
1872        self.deliver_events();
1873        emit_with::<PluginDisconnect>(self, change, serde_json::Map::new())
1874    }
1875
1876    /// `pop.window.registry`'s part on an application window: marked closed,
1877    /// so the main window's next pass no longer declares its viewport and
1878    /// the backend lets its system window go; hidden at once where the
1879    /// system allows it; forgotten by the window shim, the paint guard and
1880    /// the overlays; the main window asked for that pass.
1881    fn registry_close(&self, id: &WindowId) {
1882        let found = {
1883            let mut w = self.windows_mut();
1884            match w.entries.iter_mut().find(|e| &e.id == id && !e.closed) {
1885                Some(e) => {
1886                    e.closed = true;
1887                    Some(e.title.clone())
1888                }
1889                None => None,
1890            }
1891        };
1892        let Some(title) = found else { return };
1893        let viewport = id.deferred_viewport();
1894        let ctx = self.egui();
1895        if !ctx.embed_viewports() {
1896            // Its passes until the backend drops it draw its last page.
1897            crate::paint_guard::closing(viewport, title);
1898            ctx.send_viewport_cmd_to(viewport, ViewportCommand::Visible(false));
1899        }
1900        crate::windows::forget_viewport(viewport);
1901        self.app_window_closed(viewport, id.as_str());
1902        self.sync_separate_windows();
1903        ctx.request_repaint_of(ViewportId::ROOT);
1904    }
1905}
1906
1907/// The `window.close` step: the request as steps trace it (before-hooks
1908/// may veto or redirect it).
1909pub const STEP_WINDOW_CLOSE: egui_pop_model::ids::StepId =
1910    egui_pop_model::ids::StepId::from_static("window.close");
1911
1912/// Declares the window requests' steps.
1913pub(crate) fn declare(ctx: &mut crate::Ctx<'_>) -> Result<(), crate::ctx::CtxError> {
1914    ctx.step(
1915        crate::steps::StepSpec::new(
1916            STEP_WINDOW_CLOSE,
1917            "A window closes (`window`, `kind`, `owner`, `reason`, `cause`): its listeners on the bus run in their declared order; `window.closed` follows. The main window's, with another window open and not quitting, moves that window into it instead (`pop.window.reparent`).",
1918        )
1919        .args(json!({ "window": "settings", "kind": "app", "owner": "egui_pop.admin", "reason": "user" })),
1920    )?;
1921    shell::declare(ctx)?;
1922    Ok(())
1923}