1use 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};
187pub use bus_contract_crossing;
190pub use bus_contract_defer;
191pub use bus_contract_journal;
192pub use bus_contract_timings;
193pub use egui_pop_hooks;
194pub 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
264#[serde(rename_all = "kebab-case")]
265#[non_exhaustive]
266pub enum Reason {
267 User,
269 Command,
271 ParentClosed,
273 OwnerGone,
275 Guard,
277 System,
279 Quit,
281}
282
283impl Reason {
284 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, Serialize, Deserialize)]
300#[serde(rename_all = "kebab-case")]
301#[non_exhaustive]
302pub enum WindowKind {
303 Main,
305 App,
307 Panel,
309 Native,
312 Popup,
314}
315
316#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
319#[non_exhaustive]
320pub struct WindowRequest {
321 pub window: String,
323 pub kind: WindowKind,
324 pub owner: String,
326 pub reason: Reason,
327 #[serde(default, skip_serializing_if = "Option::is_none")]
329 pub cause: Option<u64>,
330 #[serde(default, skip_serializing_if = "Option::is_none")]
332 pub parent: Option<String>,
333 #[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 pub fn cause(mut self, seq: u64) -> Self {
360 self.cause = Some(seq);
361 self
362 }
363
364 pub fn parent(mut self, parent: impl Into<String>) -> Self {
366 self.parent = Some(parent.into());
367 self
368 }
369
370 pub fn how(mut self, how: impl Into<String>) -> Self {
372 self.how = Some(how.into());
373 self
374 }
375}
376
377#[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#[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#[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#[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#[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#[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
441pub 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#[derive(Clone, Debug, PartialEq)]
455#[non_exhaustive]
456pub struct JobAsk {
457 pub id: String,
459 pub request: egui_pop_model::jobs::Request,
460 pub reason: Option<String>,
462 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 pub fn reason(mut self, reason: impl Into<String>) -> Self {
479 self.reason = Some(reason.into());
480 self
481 }
482
483 pub(crate) fn by_framework(mut self) -> Self {
485 self.framework = true;
486 self
487 }
488
489 pub fn is_framework(&self) -> bool {
491 self.framework
492 }
493
494 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#[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#[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#[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#[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#[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#[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#[derive(Debug)]
575struct Said {
576 source: String,
577 kind: JobEventKind,
578 data: serde_json::Value,
579}
580
581#[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 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
621const JOB_TAGS: usize = 100_000;
624
625#[derive(Clone, Debug, PartialEq)]
628#[non_exhaustive]
629pub struct PluginChange {
630 pub plugin: String,
631 pub owner: String,
632 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 pub fn commands(mut self, commands: Vec<String>) -> Self {
653 self.commands = commands;
654 self
655 }
656}
657
658#[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#[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
682pub 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
691pub const PLUGIN_POINTS: [&str; 2] = [PluginConnect::ID.as_str(), PluginDisconnect::ID.as_str()];
693
694pub 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
737pub 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
838pub const OWNER: &str = "egui_pop";
840pub const CHILDREN: &str = "pop.window.children";
842pub const FOCUS: &str = "pop.window.focus";
844pub const RAISE: &str = "pop.window.raise";
848pub const KEYS: &str = "pop.window.keys";
852pub const REGISTRY: &str = "pop.window.registry";
854pub const PLACE: &str = "pop.window.place";
857pub const INVARIANTS: &str = "pop.window.invariants";
859
860#[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 #[serde(skip_serializing_if = "Option::is_none")]
872 pub viewport: Option<String>,
873 pub opened_because: Reason,
875 pub active: bool,
878 #[serde(skip_serializing_if = "Option::is_none")]
882 pub surface: Option<serde_json::Value>,
883 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
886 pub handles: bool,
887 #[serde(skip_serializing_if = "Option::is_none")]
892 pub transparency: Option<egui_pop_core::window_surface::Transparency>,
893 #[serde(skip)]
895 pub(crate) viewport_id: Option<ViewportId>,
896}
897
898impl WindowRecord {
899 pub fn viewport_id(&self) -> Option<ViewportId> {
901 self.viewport_id
902 }
903}
904
905#[derive(Debug, Default)]
908pub(crate) struct Registry {
909 records: Vec<WindowRecord>,
910 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 fn activate(&mut self, id: &str) {
945 self.activated.retain(|a| a != id);
946 self.activated.push(id.to_string());
947 }
948
949 fn by_recency(&self) -> impl Iterator<Item = &WindowRecord> {
951 self.activated.iter().rev().filter_map(|a| self.record(a))
952 }
953
954 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 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
981pub(crate) struct Bus {
984 pub(crate) kernel: Arc<dyn bus_contract::Bus>,
985 pub(crate) registry: Arc<Mutex<Registry>>,
986 pub(crate) invariants: Mutex<crate::window_invariants::State>,
989 pub(crate) screens: RefCell<screens::Seen>,
991 focus_seen: RefCell<std::collections::BTreeMap<ViewportId, bool>>,
994 raise_pending: RefCell<std::collections::BTreeSet<ViewportId>>,
997 pub(crate) keys_epoch: Rc<Cell<u64>>,
1000 delivered: Cell<Seq>,
1002 delivering: Cell<bool>,
1004 pub(crate) jobs: JobPublisher,
1006 job_tags: RefCell<std::collections::BTreeMap<Seq, JobEventKind>>,
1009 pub(crate) settings_heard: settings::Heard,
1012 settings_delivering: Cell<bool>,
1014 wake: Arc<Mutex<Option<egui::Context>>>,
1017 pub(crate) overlays: RefCell<overlays::Overlays>,
1019 pub(crate) panel_states: panel_state::States,
1021 pub(crate) over_budget: budget::Heard,
1023 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 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, ®istry);
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 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, ¬ices);
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 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 static ASKING: RefCell<Vec<WeakApp>> = const { RefCell::new(Vec::new()) };
1117}
1118
1119pub fn asking() -> Option<AppHandle> {
1126 ASKING.with_borrow(|a| a.last().and_then(|w| w.get().ok()))
1127}
1128
1129thread_local! {
1130 static MAIN_PENDING: RefCell<Option<egui::Context>> = const { RefCell::new(None) };
1134}
1135
1136struct 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
1153struct Asking;
1156
1157impl Drop for Asking {
1158 fn drop(&mut self) {
1159 ASKING.with_borrow_mut(|a| a.pop());
1160 }
1161}
1162
1163fn 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
1172fn 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
1187struct Delivering<'a>(&'a Cell<bool>);
1189
1190impl Drop for Delivering<'_> {
1191 fn drop(&mut self) {
1192 self.0.set(false);
1193 }
1194}
1195
1196fn install(kernel: &dyn bus_contract::Bus, registry: &Arc<Mutex<Registry>>) {
1198 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 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(®istry).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(®istry).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 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(®istry).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(®istry).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 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 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 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 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 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 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 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 pub fn asks_waiting(&self) -> usize {
1490 self.bus().defer().map_or(0, |d| d.waiting())
1491 }
1492
1493 pub fn bus(&self) -> Arc<dyn bus_contract::Bus> {
1502 self.0.bus.kernel.clone()
1503 }
1504
1505 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 pub fn bus_order(&self) -> String {
1540 order_dump(&*self.0.bus.kernel, &WINDOW_POINTS)
1541 }
1542
1543 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 let req = serde_json::from_value::<WindowRequest>(args.clone())
1576 .map_err(|e| format!("not a window request: {e}"))?;
1577 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 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 pub fn bus_order_of(&self, points: &[&str]) -> String {
1624 order_dump(&*self.0.bus.kernel, points)
1625 }
1626
1627 pub fn request_panel_state(&self, ask: PanelStateAsk) -> Vec<String> {
1635 emit_with::<PanelStateSet>(self, ask, Vec::new())
1636 }
1637
1638 pub fn request_job_rows(&self, ask: JobRowsAsk) -> Vec<String> {
1646 emit_with::<JobRowsSet>(self, ask, Vec::new())
1647 }
1648
1649 pub fn request_job_source_drop(&self, ask: JobSourceAsk) -> Vec<String> {
1655 emit_with::<JobSourceDrop>(self, ask, Vec::new())
1656 }
1657
1658 pub fn describe_panel(&self, panel: &str) -> Option<PanelDescription> {
1665 emit_with::<PanelDescribe>(self, panel.to_string(), None)
1666 }
1667
1668 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 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 pub fn ui_areas(&self) -> Vec<egui_pop_core::areas::AreaRecord> {
1713 emit_with::<UiAreas>(self, (), Vec::new())
1714 }
1715
1716 pub fn zen_choice(&self) -> Option<String> {
1722 emit_with::<ZenPanel>(self, (), None)
1723 }
1724
1725 pub fn command_text(&self, command: &egui_pop_model::ids::CommandId) -> CommandText {
1731 emit_with::<CommandLabel>(self, command.clone(), CommandText::default())
1732 }
1733
1734 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 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 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 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 pub fn job_publisher(&self) -> JobPublisher {
1815 self.0.bus.jobs.clone()
1816 }
1817
1818 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 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 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 pub(crate) fn delivered_event(&self) -> Seq {
1855 self.0.bus.delivered.get()
1856 }
1857
1858 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 pub(crate) fn plugin_disconnected(
1868 &self,
1869 change: PluginChange,
1870 ) -> serde_json::Map<String, serde_json::Value> {
1871 self.deliver_events();
1873 emit_with::<PluginDisconnect>(self, change, serde_json::Map::new())
1874 }
1875
1876 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 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
1907pub const STEP_WINDOW_CLOSE: egui_pop_model::ids::StepId =
1910 egui_pop_model::ids::StepId::from_static("window.close");
1911
1912pub(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}