1use std::cell::{RefCell, RefMut};
7use std::collections::{BTreeMap, BTreeSet};
8use std::fmt;
9use std::rc::{Rc, Weak};
10use std::sync::{Arc, Mutex};
11
12use egui::{Context, Id, Ui};
13use egui_pop_core::binding::SharedStore;
14use egui_pop_core::debug::{DebugBridge, Feedback, FnCollector};
15use egui_pop_core::focus_mode::{self, FocusModes, Preference, SystemFocus};
16use egui_pop_core::keys::KeyDispatcher;
17use egui_pop_core::kit::KitSource;
18use egui_pop_core::overlay;
19use egui_pop_core::persist::{Persist, PersistError, Writer};
20use egui_pop_core::state;
21use egui_pop_core::strings;
22use egui_pop_core::theme::{self, Counterpart, ThemeSpec, Themes};
23use egui_pop_core::tokens::Color;
24use egui_pop_core::{a11y, fault, focus, lock};
25
26const THEME_INSTALLED: state::Slot<bool> = state::Slot::new("api.app.theme_installed");
28const TOP_BAR_RESERVE: state::Slot<f32> = state::Slot::new("api.app.top_bar_reserve");
30const TOP_BAR_END_WIDTH: state::Slot<f32> = state::Slot::new("api.app.top_bar_end_width");
32use bus_contract_journal::BusJournal;
33use bus_contract_timings::BusTimings;
34use egui_pop_model::commands::{CommandSpec, Commands, Origin, Run};
35use egui_pop_model::diagnostics::{Diagnostic, Diagnostics};
36use egui_pop_model::ids::{
37 CommandId, MenuId, OwnerId, PanelId, PluginId, SettingId, StepId, StoryId, ZoneId,
38};
39use egui_pop_model::keymap::{BindOptions, Binding, Keymap, Layer, Trace};
40use egui_pop_model::menus::{Item, MenuItem, Menus, sort_items};
41use egui_pop_model::order::{Node, order};
42use egui_pop_model::panels::{Area, PanelSpec, Panels};
43use egui_pop_model::registry::{OwnedList, Registry};
44use egui_pop_model::values::{Change, Set, Store, Value, settings_schema};
45use egui_pop_model::when::WhenContext;
46use serde_json::{Value as Json, json};
47
48use crate::ctx::{Ctx, CtxError};
49use crate::hooks::{Alter, Hook, Lifecycle, LifecycleFn, On, PaletteEntry, SettingEntry};
50use crate::host::{Dispatch, Event, Host, LocalHost, Pending, Reply, Seq, Waker, source_of};
51use crate::plugin::{BuildError, Plugin, PluginError, PluginInfo};
52use crate::services::{ServiceToken, Services};
53use crate::steps::{HookFn, HookInfo, Outcome, StepHook, StepInfo, StepSpec, StepTrace};
54use crate::stories::{Story, StoryInfo};
55use crate::zones::{self, Block, DrawFn, ZoneInfo, ZoneTable, draw_chain};
56
57const PASS_BEGUN: state::Slot<u64> = state::Slot::new("api.app.pass_begun");
61
62#[derive(Debug)]
65struct PassMarker;
66
67impl egui::plugin::Plugin for PassMarker {
68 fn debug_name(&self) -> &'static str {
69 "egui_pop_api::pass_marker"
70 }
71
72 fn on_begin_pass(&mut self, ui: &mut Ui) {
73 let ctx = ui.ctx();
74 PASS_BEGUN
75 .keyed(ctx.viewport_id())
76 .set(ctx, ctx.cumulative_pass_nr());
77 }
78}
79
80fn install_pass_marker(ctx: &Context) {
82 if ctx.plugin_opt::<PassMarker>().is_none() {
83 ctx.add_plugin(PassMarker);
84 }
85}
86
87pub(crate) fn pass_in_progress(ctx: &Context) -> Option<(egui::ViewportId, u64)> {
91 let viewport = ctx.viewport_id();
92 let pass = ctx.cumulative_pass_nr();
93 (PASS_BEGUN.keyed(viewport).get(ctx) == Some(pass)).then_some((viewport, pass))
94}
95
96pub const STEP_REBIND: StepId = StepId::from_static("keys.rebind");
100pub const STEP_LOAD_KEYMAP: StepId = StepId::from_static("keys.load");
102
103pub const CONTEXT_WINDOW: &str = "window";
107pub const CONTEXT_FOCUSED_PANEL_KIND: &str = "focusedPanelKind";
114pub const CONTEXT_UNDO_NEEDS_VIEW: &str = "undoNeedsView";
120pub const CONTEXT_REDO_NEEDS_VIEW: &str = "redoNeedsView";
122
123pub const MENU_MAIN: MenuId = MenuId::from_static("app.main");
124pub const MENU_FILE: MenuId = MenuId::from_static("app.menu.file");
125pub const MENU_EDIT: MenuId = MenuId::from_static("app.menu.edit");
126pub const MENU_VIEW: MenuId = MenuId::from_static("app.menu.view");
127pub const MENU_HELP: MenuId = MenuId::from_static("app.menu.help");
128pub const MENU_BAR_END: MenuId = MenuId::from_static("app.menu-bar.end");
135
136pub use crate::palette::CMD_PALETTE;
138pub const CMD_QUIT: CommandId = CommandId::from_static("app.quit");
139pub const CMD_UNDO: CommandId = CommandId::from_static("edit.undo");
144pub const CMD_REDO: CommandId = CommandId::from_static("edit.redo");
145pub const STEP_UNDO: StepId = StepId::from_static("edit.undo");
156pub const STEP_REDO: StepId = StepId::from_static("edit.redo");
157
158const IN_INTERFACE: &[CommandId] = &[
165 CMD_UNDO,
166 CMD_REDO,
167 crate::history_view::CMD_LIST,
168 crate::history_view::CMD_READ,
169 crate::history_view::CMD_UNDO,
170 crate::history_view::CMD_REDO,
171 crate::history_view::CMD_JUMP,
172 crate::history_view::CMD_SNAPSHOT,
173 crate::history_view::CMD_RESTORE,
174 crate::history_view::CMD_DROP_SNAPSHOT,
175 crate::history_view::CMD_UNDO_STEP,
176 crate::contexts::CMD_BACK,
177 crate::contexts::CMD_UP,
178 crate::contexts::CMD_ENTER,
179 crate::contexts::CMD_READ,
180 crate::contexts::CMD_REQUEST,
181 crate::contexts::CMD_GO,
182 crate::contexts::CMD_SET_MODE,
183 crate::contexts::CMD_HOLD,
184 crate::contexts::CMD_RELEASE,
185 crate::clipboard::CMD_CUT,
186 crate::clipboard::CMD_COPY,
187 crate::clipboard::CMD_PASTE,
188 crate::clipboard::CMD_PASTE_SPECIAL,
189 crate::clipboard::CMD_CLIP_COPY,
190 crate::clipboard::CMD_CLIP_PASTE,
191 crate::clipboard::CMD_OFFERS,
192 crate::clipboard::CMD_READ,
193 crate::clipboard::CMD_WRITE,
194];
195pub const CMD_SAVE: CommandId = CommandId::from_static("app.save");
196
197#[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)]
199#[serde(rename_all = "lowercase")]
200pub enum OverlayKind {
201 Dialog,
203 Modal,
205 Popover,
206 Menu,
208 Toasts,
210 DropHint,
213 Popup,
216}
217
218#[derive(Clone, Debug, PartialEq)]
221pub struct OverlayRect {
222 pub kind: OverlayKind,
223 pub id: String,
224 pub rect: egui::Rect,
225}
226
227pub struct ThemeService {
231 spec: Mutex<ThemeSpec>,
232 themes: Themes,
233 kits: Vec<egui_pop_core::tokens::kit::KitInfo>,
234 store: SharedStore,
235 dark: Mutex<BTreeMap<String, bool>>,
237 ctx: Mutex<Context>,
240}
241
242impl fmt::Debug for ThemeService {
243 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
244 f.debug_struct("ThemeService")
245 .field("spec", &self.spec)
246 .field("kits", &self.kits)
247 .finish_non_exhaustive()
248 }
249}
250
251impl ThemeService {
252 pub fn spec(&self) -> ThemeSpec {
253 lock(&self.spec).clone()
254 }
255
256 pub fn set(&self, spec: ThemeSpec) {
259 self.update(|s| *s = spec);
260 }
261
262 pub fn update(&self, f: impl FnOnce(&mut ThemeSpec)) {
265 let changed = {
266 let mut spec = lock(&self.spec);
267 let before = spec.clone();
268 f(&mut spec);
269 *spec != before
270 };
271 if changed {
272 lock(&self.ctx).request_repaint();
273 }
274 }
275
276 fn follow(&self, ctx: &Context) {
278 let mut mine = lock(&self.ctx);
279 if *mine != *ctx {
280 *mine = ctx.clone();
281 }
282 }
283
284 pub fn themes(&self) -> &Themes {
285 &self.themes
286 }
287
288 pub fn kits(&self) -> &[egui_pop_core::tokens::kit::KitInfo] {
295 &self.kits
296 }
297
298 pub fn preference(&self) -> egui::ThemePreference {
302 lock(&self.store)
303 .get(&format!("settings/{SETTING_THEME_PREFERENCE}"))
304 .and_then(|e| e.value.as_choice().and_then(parse_preference))
305 .unwrap_or(egui::ThemePreference::System)
306 }
307
308 pub fn set_preference(&self, preference: egui::ThemePreference) {
311 let set = Set::new(
312 &format!("settings/{SETTING_THEME_PREFERENCE}"),
313 Change::To(Value::Choice(preference_name(preference).into())),
314 Origin::User,
315 )
316 .by(&OwnerId::FRAMEWORK)
317 .untracked();
318 if let Err(e) = lock(&self.store).set(set) {
319 log::warn!(target: "egui_pop", "theme preference: {e}");
320 }
321 }
322
323 fn accent_key() -> String {
324 format!("settings/{SETTING_ACCENT_COLOR}")
325 }
326
327 fn accent_setting(&self) -> String {
330 lock(&self.store)
331 .get(&Self::accent_key())
332 .and_then(|e| e.value.as_text().map(str::to_string))
333 .unwrap_or_default()
334 }
335
336 fn apply_accent_setting(&self, text: &str) {
340 let text = text.trim();
341 if text.is_empty() {
342 self.update(|spec| {
343 if spec.accent_seed().is_some() {
344 spec.accent = None;
345 }
346 });
347 return;
348 }
349 match Color::from_hex(text) {
350 Some(seed) => self.update(|spec| *spec = spec.clone().accent_color(seed)),
351 None => log::warn!(
352 target: "egui_pop",
353 "{SETTING_ACCENT_COLOR}: `{text}` is not a #rrggbb colour, the accent is kept"
354 ),
355 }
356 }
357
358 pub fn accent_color(&self) -> Option<Color> {
362 self.spec().accent_seed()
363 }
364
365 pub fn set_accent_color(&self, seed: Option<Color>) {
371 let text = seed.map_or(String::new(), |c| Color { a: 1.0, ..c }.to_hex());
372 let set = Set::new(
373 &Self::accent_key(),
374 Change::To(Value::Text(text.clone())),
375 Origin::User,
376 )
377 .by(&OwnerId::FRAMEWORK)
378 .untracked();
379 if let Err(e) = lock(&self.store).set(set) {
380 log::warn!(target: "egui_pop", "accent colour: {e}");
381 }
382 match seed {
383 Some(seed) => self.update(|spec| *spec = spec.clone().accent_color(seed)),
384 None => self.apply_accent_setting(""),
385 }
386 }
387
388 pub fn counterpart(&self) -> Option<String> {
390 self.themes.counterpart(&self.spec())
391 }
392
393 pub fn is_dark(&self, name: &str) -> bool {
395 if let Some(d) = lock(&self.dark).get(name) {
396 return *d;
397 }
398 let d = self.themes.resolve(&ThemeSpec::new(name).alone()).is_dark();
399 lock(&self.dark).insert(name.to_string(), d);
400 d
401 }
402
403 fn mode_of(&self, name: &str) -> egui::Theme {
404 if self.is_dark(name) {
405 egui::Theme::Dark
406 } else {
407 egui::Theme::Light
408 }
409 }
410
411 pub fn shown(&self, ctx: &Context) -> String {
415 let spec = self.spec();
416 let Some(other) = self.themes.counterpart(&spec) else {
417 return spec.base;
418 };
419 let base_mode = self.mode_of(&spec.base);
420 if self.mode_of(&other) == base_mode {
421 return spec.base;
422 }
423 let wanted = match self.preference() {
424 egui::ThemePreference::Dark => egui::Theme::Dark,
425 egui::ThemePreference::Light => egui::Theme::Light,
426 egui::ThemePreference::System => ctx.system_theme().unwrap_or(base_mode),
427 };
428 if wanted == base_mode {
429 spec.base
430 } else {
431 other
432 }
433 }
434
435 pub fn pick(&self, ctx: &Context, name: &str) {
440 self.update(|spec| {
441 spec.base = name.to_string();
442 spec.counterpart = Counterpart::Auto;
443 });
444 if self.shown(ctx) != name {
445 self.set_preference(self.mode_of(name).into());
446 }
447 }
448
449 pub fn toggle(&self, ctx: &Context) -> Result<egui::Theme, String> {
453 let spec = self.spec();
454 let other = self
455 .themes
456 .counterpart(&spec)
457 .filter(|o| self.mode_of(o) != self.mode_of(&spec.base))
458 .ok_or_else(|| format!("`{}` has no light or dark counterpart", spec.base))?;
459 let shown = self.shown(ctx);
460 let next = if shown == spec.base { other } else { spec.base };
461 let mode = self.mode_of(&next);
462 self.set_preference(mode.into());
463 Ok(mode)
464 }
465}
466
467pub fn preference_name(p: egui::ThemePreference) -> &'static str {
469 match p {
470 egui::ThemePreference::System => "system",
471 egui::ThemePreference::Light => "light",
472 egui::ThemePreference::Dark => "dark",
473 }
474}
475
476pub fn parse_preference(name: &str) -> Option<egui::ThemePreference> {
478 match name {
479 "system" => Some(egui::ThemePreference::System),
480 "light" => Some(egui::ThemePreference::Light),
481 "dark" => Some(egui::ThemePreference::Dark),
482 _ => None,
483 }
484}
485
486pub const SETTING_THEME_PREFERENCE: SettingId =
489 SettingId::from_static("appearance.theme_preference");
490
491pub const SETTING_ACCENT_COLOR: SettingId = SettingId::from_static("appearance.accent_color");
494
495pub const CMD_THEME_TOGGLE: CommandId = CommandId::from_static("view.theme.toggle_light_dark");
497
498pub const THEME: ServiceToken<ThemeService> = ServiceToken::new("app.theme");
500
501pub const FOCUS_MODE: ServiceToken<FocusModes> = ServiceToken::new("app.focus_mode");
507
508pub const SETTING_FOCUS: SettingId = SettingId::from_static("appearance.focus");
510
511const FRAMEWORK_SECTION: &str = "Appearance";
513
514#[derive(Debug)]
516pub struct Call<'a> {
517 pub args: &'a Json,
518 pub origin: &'a Origin,
519 pub app: &'a AppHandle,
520}
521
522impl Call<'_> {
523 pub fn fail(&self, err: impl Into<egui_pop_model::commands::CommandError>) -> String {
535 let err = err.into();
536 let text = err.to_string();
537 if let Some((command, _)) = self.app.running_command() {
538 self.app.keep_failure(command, err);
539 }
540 text
541 }
542}
543
544pub type CommandFn = Rc<dyn Fn(&Call<'_>) -> Result<Json, String>>;
546
547fn escalation(acting: &Origin, origin: &Origin) -> Option<String> {
551 match (acting, origin) {
552 (Origin::User, _) => None,
553 (a, o) if a == o => None,
554 (Origin::Agent(_), Origin::Agent(_)) => None,
555 (a, Origin::User) => Some(format!(
556 "a command running for {} may not run another as the user; ask the user (a dialog)",
557 source_of(a)
558 )),
559 (Origin::Agent(_), o) => Some(format!(
560 "a command running for {} may not run another as {}",
561 source_of(acting),
562 source_of(o)
563 )),
564 _ => None,
565 }
566}
567
568struct ActingFor<'a>(&'a AppHandle);
571
572impl<'a> ActingFor<'a> {
573 fn new(app: &'a AppHandle, origin: &Origin) -> Self {
574 app.0.acting.borrow_mut().push(origin.clone());
575 Self(app)
576 }
577}
578
579impl Drop for ActingFor<'_> {
580 fn drop(&mut self) {
581 self.0.0.acting.borrow_mut().pop();
582 }
583}
584
585pub(crate) struct Registries {
587 pub commands: Commands<Option<CommandFn>>,
589 pub keymap: Rc<RefCell<Keymap>>,
592 pub menus: Menus,
593 pub panels: Panels,
594 pub hooks: OwnedList<Hook>,
595 pub lifecycle: OwnedList<(On, LifecycleFn)>,
596 pub settings: Registry<SettingId, String>,
597 pub command_icons: OwnedList<CommandIcon>,
600 pub offered: BTreeSet<CommandId>,
603}
604
605#[derive(Clone, Debug, PartialEq)]
608pub(crate) struct CommandIcon {
609 pub command: CommandId,
610 pub icon: String,
611 pub icon_on: Option<String>,
612}
613
614impl Registries {
615 fn new() -> Self {
616 Self {
617 commands: Commands::new(),
618 keymap: Rc::new(RefCell::new(Keymap::new())),
619 menus: Menus::new(),
620 panels: Panels::new(),
621 hooks: OwnedList::new(),
622 lifecycle: OwnedList::new(),
623 settings: Registry::new(),
624 command_icons: OwnedList::new(),
625 offered: BTreeSet::new(),
626 }
627 }
628
629 fn remove_owner(&mut self, owner: &OwnerId) -> Vec<CommandId> {
631 let commands = self.commands.remove_owner(owner);
632 self.keymap.borrow_mut().remove_owner(owner);
633 self.menus.remove_owner(owner);
634 self.panels.remove_owner(owner);
635 self.hooks.remove_owner(owner);
636 self.lifecycle.remove_owner(owner);
637 self.settings.remove_owner(owner);
638 self.command_icons.remove_owner(owner);
639 commands
640 }
641}
642
643const WORKSPACE_KEYS: OwnerId = OwnerId::from_static("workspace");
646
647fn layer_owner(layer: Layer) -> Option<OwnerId> {
650 match layer {
651 Layer::User => Some(OwnerId::USER),
652 Layer::Workspace => Some(WORKSPACE_KEYS),
653 Layer::Suggestion | Layer::Default => None,
654 }
655}
656
657type KeySourceNames = Rc<dyn Fn(&Binding) -> Option<String>>;
659
660#[derive(Clone, Debug, Default)]
662pub(crate) struct Derived {
663 pub menus: BTreeMap<MenuId, Vec<MenuItem>>,
664 pub palette: Vec<PaletteEntry>,
665 pub settings: Vec<SettingEntry>,
666 pub sections: BTreeMap<OwnerId, String>,
668 pub commands: Vec<(CommandSpec, OwnerId)>,
669 pub icons_set_by: BTreeMap<CommandId, OwnerId>,
672 pub panels: Vec<(egui_pop_model::panels::PanelSpec, OwnerId)>,
674 pub keys: BTreeMap<CommandId, Vec<String>>,
676 pub sources: BTreeMap<CommandId, Vec<Binding>>,
678 pub conflicts: Vec<(Binding, Binding)>,
680 pub system: Vec<Binding>,
682 pub dormant: Vec<DormantKey>,
684 pub layers: BTreeMap<Layer, egui_pop_model::keymap::KeymapDoc>,
686 pub rebound: BTreeSet<CommandId>,
688 pub rebound_workspace: BTreeSet<CommandId>,
690}
691
692#[derive(Clone, Debug, PartialEq, serde::Serialize)]
696#[non_exhaustive]
697pub struct DormantKey {
698 pub binding: Binding,
700 pub plugin: PluginId,
702 pub plugin_title: String,
704}
705
706#[allow(
711 clippy::large_enum_variant,
712 reason = "a declaration carries a whole CommandSpec; requests are few and short lived, and boxing would change the public variant"
713)]
714#[derive(Clone, Debug, PartialEq)]
715pub enum Request {
716 Run {
717 command: CommandId,
718 args: Json,
719 origin: Origin,
720 },
721 RunIn {
723 command: CommandId,
724 args: Json,
725 origin: Origin,
726 context: WhenContext,
727 },
728 Enable(PluginId, bool),
729 Rebind {
732 command: CommandId,
733 keys: Option<String>,
734 layer: Layer,
735 },
736 RebindAll {
739 command: CommandId,
740 keys: Vec<String>,
741 layer: Layer,
742 },
743 ResetKeys {
746 command: CommandId,
747 layer: Layer,
748 },
749 Declare {
751 owner: OwnerId,
752 spec: CommandSpec,
753 },
754 Undeclare(CommandId),
756 LoadKeymap {
758 doc: egui_pop_model::keymap::KeymapDoc,
759 layer: Layer,
760 },
761 Workbench(crate::workbench::Change),
766}
767
768struct PanelView {
769 owner: OwnerId,
770 draw: Option<PanelDraw>,
771}
772
773pub(crate) enum PanelDraw {
775 Plain(DrawFn),
776 Instance(crate::workbench::instances::InstanceDrawFn),
777}
778
779struct StoryEntry {
780 story: Story,
781}
782
783type Held = (String, Option<Seq>, String, Json);
785
786pub(crate) struct Shared {
787 ctx: RefCell<Context>,
788 store: SharedStore,
789 services: RefCell<Services>,
790 zones: RefCell<ZoneTable>,
791 panels: RefCell<BTreeMap<PanelId, PanelView>>,
792 stories: RefCell<Registry<StoryId, StoryEntry>>,
793 requests: RefCell<Vec<Request>>,
794 acting: RefCell<Vec<Origin>>,
797 context: RefCell<WhenContext>,
798 workbench: RefCell<crate::workbench::Workbench>,
799 indicators: RefCell<OwnedList<(crate::strips::Indicator, crate::strips::IndicatorState)>>,
801 indicators_seen: std::cell::Cell<Seq>,
802 drawing_areas: std::cell::Cell<bool>,
805 edge_to_edge: std::cell::Cell<bool>,
807 frameless: RefCell<Vec<Area>>,
809 bare_strips: RefCell<Vec<Area>>,
811 system_text_scale: std::cell::Cell<crate::text::SystemTextScale>,
813 system_scroll_bars: std::cell::Cell<bool>,
816 system_wheel_lines: std::cell::Cell<u32>,
818 toast_corner: std::cell::Cell<crate::toasts::Corner>,
820 pub(crate) group_handles: std::cell::Cell<crate::workbench::GroupHandles>,
823 pub(crate) dock_controls: std::cell::Cell<crate::workbench::DockControls>,
825 arrangement_strings: std::cell::Cell<crate::arrangements::ArrangementStrings>,
827 pub(crate) stack_changes: RefCell<Vec<egui_stack::bus::LayoutChange>>,
830 menu_bar: std::cell::Cell<bool>,
832 system_file_chooser: std::cell::Cell<bool>,
835 transparent_panel_windows: std::cell::Cell<bool>,
838 rounded_windows: std::cell::Cell<bool>,
841 shell_sizes: RefCell<Vec<(PanelId, f32)>>,
845 shell_bounds: RefCell<Vec<(PanelId, crate::workbench::ShellBounds)>>,
848 centre_min: std::cell::Cell<Option<crate::workbench::ShellSize>>,
850 pub(crate) panel_commands: RefCell<strings::PanelCommands>,
853 name: RefCell<String>,
855 app_id: RefCell<String>,
857 diagnostics: RefCell<Diagnostics>,
858 derived: RefCell<Derived>,
859 plugins: RefCell<Vec<PluginInfo>>,
860 history: RefCell<Vec<Run>>,
861 bridge: RefCell<DebugBridge>,
862 traces: RefCell<Vec<Trace>>,
863 pending_keys: RefCell<Option<String>>,
864 host: RefCell<Option<Box<dyn Host>>>,
866 dispatch_groups: RefCell<Option<Rc<dyn crate::host::Groups>>>,
868 gone_commands: RefCell<BTreeMap<CommandId, PluginId>>,
872 held: RefCell<Vec<Held>>,
874 journal: RefCell<crate::host::Journal>,
876 journal_on_bus: std::cell::Cell<bool>,
880 running: RefCell<BTreeMap<CommandId, usize>>,
882 running_since: RefCell<BTreeMap<CommandId, f64>>,
884 collectors: RefCell<Vec<(OwnerId, String)>>,
886 capturing: std::cell::Cell<bool>,
888 pub(crate) paint_guard: RefCell<crate::paint_guard::Guard>,
890 workspace_keys: std::cell::Cell<bool>,
892 key_source_names: RefCell<Option<KeySourceNames>>,
894 steps: RefCell<Registry<StepId, StepSpec>>,
896 step_hooks: RefCell<OwnedList<StepHook>>,
897 step_traces: RefCell<std::collections::VecDeque<StepTrace>>,
898 lists: RefCell<OwnedList<crate::menus::Provider>>,
900 list_traces: RefCell<BTreeMap<String, crate::menus::ListTrace>>,
901 popup: RefCell<Option<crate::menus::Popup>>,
903 writer: RefCell<Option<Writer>>,
906 locals: RefCell<BTreeMap<std::any::TypeId, Rc<dyn std::any::Any>>>,
910 stack_writing: std::cell::Cell<bool>,
912 running_commands: RefCell<Vec<(CommandId, Option<OwnerId>)>>,
914 pub(crate) windows: RefCell<crate::windows::Windows>,
916 pub(crate) bus: crate::bus::Bus,
919 keymap: RefCell<Rc<Keymap>>,
922}
923
924struct RunningCommand(AppHandle);
927
928impl RunningCommand {
929 fn new(app: &AppHandle, command: &CommandId, owner: Option<&OwnerId>) -> Self {
930 app.0
931 .running_commands
932 .borrow_mut()
933 .push((command.clone(), owner.cloned()));
934 RunningCommand(app.clone())
935 }
936}
937
938impl Drop for RunningCommand {
939 fn drop(&mut self) {
940 self.0.0.running_commands.borrow_mut().pop();
941 }
942}
943
944#[derive(Clone)]
948pub struct AppHandle(pub(crate) Rc<Shared>);
949
950impl fmt::Debug for AppHandle {
951 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
952 f.debug_struct("AppHandle").finish_non_exhaustive()
953 }
954}
955
956#[derive(Clone)]
958pub(crate) struct WeakApp(Weak<Shared>);
959
960impl WeakApp {
961 pub(crate) fn get(&self) -> Result<AppHandle, String> {
962 self.0
963 .upgrade()
964 .map(AppHandle)
965 .ok_or_else(|| "the application is gone".to_string())
966 }
967}
968
969impl AppHandle {
970 pub(crate) fn downgrade(&self) -> WeakApp {
971 WeakApp(self.weak())
972 }
973
974 fn new(
975 ctx: &Context,
976 host: Box<dyn Host>,
977 default_host: bool,
978 bus: Option<Arc<dyn crate::bus::bus_contract::Bus>>,
979 ) -> Self {
980 let store = host.store();
981 let keeps_journal = !default_host && host.last_seq().is_some();
982 let handle = AppHandle(Rc::new(Shared {
983 ctx: RefCell::new(ctx.clone()),
984 store,
985 services: RefCell::new(Services::default()),
986 zones: RefCell::new(ZoneTable::default()),
987 panels: RefCell::new(BTreeMap::new()),
988 stories: RefCell::new(Registry::new()),
989 requests: RefCell::new(Vec::new()),
990 acting: RefCell::new(Vec::new()),
991 context: RefCell::new(WhenContext::new()),
992 workbench: RefCell::new(crate::workbench::Workbench::default()),
993 indicators: RefCell::new(OwnedList::new()),
994 indicators_seen: std::cell::Cell::new(0),
995 drawing_areas: std::cell::Cell::new(false),
996 edge_to_edge: std::cell::Cell::new(false),
997 frameless: RefCell::new(Vec::new()),
998 bare_strips: RefCell::new(Vec::new()),
999 system_text_scale: std::cell::Cell::default(),
1000 system_scroll_bars: std::cell::Cell::default(),
1001 system_wheel_lines: std::cell::Cell::new(crate::pointer::SYSTEM_WHEEL_LINES),
1002 toast_corner: std::cell::Cell::default(),
1003 group_handles: std::cell::Cell::new(crate::workbench::DEFAULT_GROUP_HANDLES),
1004 dock_controls: std::cell::Cell::default(),
1005 arrangement_strings: std::cell::Cell::default(),
1006 stack_changes: RefCell::new(Vec::new()),
1007 menu_bar: std::cell::Cell::new(true),
1008 system_file_chooser: std::cell::Cell::new(false),
1009 transparent_panel_windows: std::cell::Cell::new(false),
1010 rounded_windows: std::cell::Cell::new(false),
1011 shell_sizes: RefCell::default(),
1012 shell_bounds: RefCell::default(),
1013 centre_min: std::cell::Cell::new(None),
1014 panel_commands: RefCell::default(),
1015 name: RefCell::default(),
1016 app_id: RefCell::default(),
1017 diagnostics: RefCell::new(Diagnostics::new()),
1018 derived: RefCell::new(Derived::default()),
1019 plugins: RefCell::new(Vec::new()),
1020 history: RefCell::new(Vec::new()),
1021 bridge: RefCell::new(DebugBridge::with_core_collectors()),
1022 traces: RefCell::new(Vec::new()),
1023 pending_keys: RefCell::new(None),
1024 host: RefCell::new(Some(host)),
1025 dispatch_groups: RefCell::new(None),
1026 gone_commands: RefCell::new(BTreeMap::new()),
1027 held: RefCell::new(Vec::new()),
1028 journal: RefCell::new(crate::host::Journal::default()),
1029 journal_on_bus: std::cell::Cell::new(false),
1030 running: RefCell::new(BTreeMap::new()),
1031 running_since: RefCell::new(BTreeMap::new()),
1032 collectors: RefCell::new(Vec::new()),
1033 capturing: std::cell::Cell::new(false),
1034 paint_guard: RefCell::default(),
1035 workspace_keys: std::cell::Cell::new(false),
1036 key_source_names: RefCell::new(None),
1037 steps: RefCell::new(Registry::new()),
1038 step_hooks: RefCell::new(OwnedList::new()),
1039 step_traces: RefCell::new(std::collections::VecDeque::new()),
1040 lists: RefCell::new(OwnedList::new()),
1041 list_traces: RefCell::new(BTreeMap::new()),
1042 popup: RefCell::new(None),
1043 writer: RefCell::new(None),
1044 locals: RefCell::new(BTreeMap::new()),
1045 stack_writing: std::cell::Cell::new(false),
1046 running_commands: RefCell::new(Vec::new()),
1047 windows: RefCell::default(),
1048 bus: crate::bus::Bus::new(bus),
1049 keymap: RefCell::default(),
1050 }));
1051 let kernel = &handle.0.bus.kernel;
1054 if kernel.journal().is_some() && !keeps_journal {
1055 match crate::bus::bus_contract::declare_all(&**kernel, &[crate::bus::HOST_JOURNAL])
1056 .into_iter()
1057 .next()
1058 {
1059 None => handle.0.journal_on_bus.set(true),
1060 Some(refused) => {
1061 log::error!(target: "egui_pop", "{refused}: egui-pop keeps its own journal");
1062 }
1063 }
1064 }
1065 if let Some(h) = handle.0.host.borrow_mut().as_mut() {
1067 h.set_job_publisher(handle.0.bus.jobs.clone());
1068 }
1069 crate::bus::settings::hear(&mut lock(&handle.0.store), &handle.0.bus.settings_heard);
1071 handle
1072 }
1073
1074 pub fn local<T: Default + 'static>(&self) -> Rc<T> {
1079 let id = std::any::TypeId::of::<T>();
1080 let any = self
1081 .0
1082 .locals
1083 .borrow_mut()
1084 .entry(id)
1085 .or_insert_with(|| Rc::new(T::default()) as Rc<dyn std::any::Any>)
1086 .clone();
1087 any.downcast::<T>()
1088 .unwrap_or_else(|_| unreachable!("kept under its own type"))
1089 }
1090
1091 pub(crate) fn report_diagnostic(&self, d: Diagnostic) {
1093 self.0.diagnostics.borrow_mut().push(d);
1094 }
1095
1096 fn weak(&self) -> Weak<Shared> {
1097 Rc::downgrade(&self.0)
1098 }
1099
1100 pub fn debug_describe(&self) -> Json {
1102 self.0.bridge.borrow().describe()
1103 }
1104
1105 pub fn debug_capabilities(&self) -> Json {
1116 use egui_pop_core::debug::{PROTOCOL, is_schema};
1117 let mut caps = self.0.bridge.borrow().capabilities();
1118 for (s, _) in self.commands() {
1119 let (args, example) = if is_schema(&s.args) {
1120 (s.args.clone(), Json::Null)
1121 } else {
1122 (Json::Null, s.args.clone())
1123 };
1124 caps.push(json!({
1125 "kind": "command",
1126 "name": s.id,
1127 "title": s.title,
1128 "description": s.description,
1129 "mutates": !s.read_only,
1130 "agent": s.agent,
1131 "destructive": s.destructive,
1132 "destructive_if": s.destructive_if,
1135 "private": s.private,
1136 "args": args,
1137 "example": example,
1138 "result": Json::Null,
1139 "call": { "collector": "commands", "action": "run", "id": s.id },
1140 }));
1141 }
1142 let windows: Vec<Json> = self
1145 .windows()
1146 .into_iter()
1147 .map(|w| json!({ "id": w.id, "title": w.title, "main": w.main, "active": w.active }))
1148 .collect();
1149 json!({ "protocol": PROTOCOL, "capabilities": caps, "windows": windows })
1150 }
1151
1152 fn bridge_call_as(
1155 &self,
1156 collector: &str,
1157 action: &str,
1158 args: &Json,
1159 origin: &Origin,
1160 ) -> Feedback {
1161 if collector == BRIDGE && action == "describe" {
1162 let refused = self
1163 .0
1164 .bridge
1165 .borrow()
1166 .refusal(collector, action, args, origin);
1167 if refused.is_none() {
1168 let f = Feedback {
1169 ok: true,
1170 collector: collector.into(),
1171 action: action.into(),
1172 mutates: false,
1173 message: format!("`{collector}.{action}` read"),
1174 data: self.debug_capabilities(),
1175 };
1176 self.0.bridge.borrow_mut().record(f.clone());
1177 return f;
1178 }
1179 }
1180 self.0
1181 .bridge
1182 .borrow_mut()
1183 .call_as(&self.egui(), collector, action, args, origin)
1184 }
1185
1186 pub(crate) fn queued_requests(&self) -> usize {
1189 self.0.requests.borrow().len()
1190 }
1191
1192 pub fn debug_bridge_mode(&self) -> egui_pop_core::debug::BridgeMode {
1196 self.0.bridge.borrow().mode()
1197 }
1198
1199 pub fn debug_snapshot(&self) -> Json {
1201 self.0.bridge.borrow().snapshot(&self.egui())
1202 }
1203
1204 pub fn window_group_named(&self, window: Option<&str>) -> Result<egui::ViewportId, String> {
1208 match window {
1209 None => Ok(self.window_group(self.active_window())),
1210 Some(w) => {
1211 let id = crate::windows::WindowId::new(w);
1212 let viewport = if w == crate::windows::WindowId::MAIN {
1213 Some(egui::ViewportId::ROOT)
1214 } else {
1215 self.window_viewport(&id)
1216 };
1217 viewport
1218 .map(|v| self.window_group(v))
1219 .ok_or_else(|| format!("no open window `{w}`"))
1220 }
1221 }
1222 }
1223
1224 pub fn command_args_refusal(&self, command: &CommandId, args: &Json) -> Option<String> {
1231 let commands = self.commands();
1232 let (spec, _) = commands.iter().find(|(s, _)| &s.id == command)?;
1233 crate::bus::args_refusal(spec, args)
1234 .map(|r| format!("refused by `{}`: {r}", crate::bus::ARGS_VALIDATOR))
1235 }
1236
1237 pub fn debug_destructive(&self, collector: &str, action: &str, args: &Json) -> bool {
1243 self.0.bridge.borrow().destructive(collector, action, args)
1244 }
1245
1246 pub fn debug_mutates(&self, collector: &str, action: &str, args: &Json) -> bool {
1251 self.0
1252 .bridge
1253 .borrow()
1254 .mutates(collector, action, args)
1255 .unwrap_or(true)
1256 }
1257
1258 pub fn debug_refusal(
1263 &self,
1264 collector: &str,
1265 action: &str,
1266 args: &Json,
1267 origin: &Origin,
1268 ) -> Option<String> {
1269 self.0
1270 .bridge
1271 .borrow()
1272 .refusal(collector, action, args, origin)
1273 }
1274
1275 pub fn debug_snapshot_in(&self, window: Option<&str>) -> Result<Json, String> {
1279 let group = self.window_group_named(window)?;
1280 let _group = crate::windows::enter_group(Some(group));
1281 Ok(self.debug_snapshot())
1282 }
1283
1284 pub fn debug_call_in(
1290 &self,
1291 window: Option<&str>,
1292 collector: &str,
1293 action: &str,
1294 args: &Json,
1295 origin: Origin,
1296 ) -> Feedback {
1297 let group = match self.window_group_named(window) {
1298 Ok(g) => g,
1299 Err(e) => {
1300 return Feedback {
1301 ok: false,
1302 collector: collector.into(),
1303 action: action.into(),
1304 mutates: false,
1305 message: e,
1306 data: Json::Null,
1307 };
1308 }
1309 };
1310 let _group = crate::windows::enter_group(Some(group));
1311 self.debug_call_as(collector, action, args, origin)
1312 }
1313
1314 pub fn debug_call(&self, collector: &str, action: &str, args: &Json) -> Feedback {
1322 self.debug_call_as(collector, action, args, egui_pop_core::debug::agent())
1323 }
1324
1325 pub fn debug_call_as(
1334 &self,
1335 collector: &str,
1336 action: &str,
1337 args: &Json,
1338 origin: Origin,
1339 ) -> Feedback {
1340 let (spec, refusal, mutates) = {
1341 let b = self.0.bridge.borrow();
1342 (
1343 b.action(collector, action),
1344 b.refusal(collector, action, args, &origin),
1345 b.mutates(collector, action, args).unwrap_or(true),
1346 )
1347 };
1348 if spec.is_none() {
1349 return self.0.bridge.borrow_mut().call_as(
1351 &self.egui(),
1352 collector,
1353 action,
1354 args,
1355 &origin,
1356 );
1357 }
1358 let source = source_of(&origin);
1359 let private = self.call_is_private(collector, action, args);
1364 if let Some(reason) = refusal {
1365 let feedback =
1366 self.0
1367 .bridge
1368 .borrow_mut()
1369 .call_as(&self.egui(), collector, action, args, &origin);
1370 let mut refused =
1371 json!({ "collector": collector, "action": action, "args": args, "reason": reason });
1372 if private {
1373 refused[crate::steps::PRIVATE] = Json::Bool(true);
1374 }
1375 self.publish(&source, None, "debug.call.refused", refused);
1376 return feedback;
1377 }
1378 let mut ran: Option<Feedback> = None;
1379 let mut asked =
1380 json!({ "collector": collector, "action": action, "args": args, "origin": source });
1381 if private {
1382 asked[crate::steps::PRIVATE] = Json::Bool(true);
1383 }
1384 let out = self.step_with(&STEP_DEBUG_CALL, asked, !mutates, |app, a| {
1388 let f = app.bridge_call_as(
1389 a["collector"].as_str().unwrap_or_default(),
1390 a["action"].as_str().unwrap_or_default(),
1391 &a["args"],
1392 &origin,
1394 );
1395 let result = if f.ok {
1398 Ok(json!({ "message": f.message }))
1399 } else {
1400 Err(f.message.clone())
1401 };
1402 ran = Some(f);
1403 result
1404 });
1405 let feedback = |ok: bool, message: String, data: Json| Feedback {
1406 ok,
1407 collector: collector.into(),
1408 action: action.into(),
1409 mutates,
1410 message,
1411 data,
1412 };
1413 let feedback = match out {
1414 Outcome::Done(result) => match ran {
1415 Some(f) => return f,
1416 None => match result {
1418 Ok(data) => feedback(
1419 true,
1420 format!("`{collector}.{action}` done by a plugin"),
1421 data,
1422 ),
1423 Err(e) => feedback(
1424 false,
1425 format!("`{collector}.{action}` failed: {e}"),
1426 Json::Null,
1427 ),
1428 },
1429 },
1430 Outcome::Vetoed { by, reason } => feedback(
1431 false,
1432 format!("`{collector}.{action}` vetoed by {by}: {reason}"),
1433 Json::Null,
1434 ),
1435 };
1436 self.0.bridge.borrow_mut().record(feedback.clone());
1437 feedback
1438 }
1439
1440 fn call_is_private(&self, collector: &str, action: &str, args: &Json) -> bool {
1444 if (collector, action) != ("commands", "run") {
1445 return false;
1446 }
1447 args.get("id")
1448 .and_then(Json::as_str)
1449 .and_then(|id| CommandId::new(id).ok())
1450 .is_none_or(|id| self.command(&id).is_none_or(|s| s.private))
1451 }
1452
1453 pub fn debug_log(&self) -> Vec<Feedback> {
1455 self.0.bridge.borrow().log().cloned().collect()
1456 }
1457
1458 pub fn key_traces(&self) -> Vec<Trace> {
1460 self.0.traces.borrow().clone()
1461 }
1462
1463 pub fn pending_keys(&self) -> Option<String> {
1465 self.0.pending_keys.borrow().clone()
1466 }
1467
1468 pub fn egui(&self) -> Context {
1470 self.0.ctx.borrow().clone()
1471 }
1472
1473 pub(crate) fn add_panel_commands(
1477 &self,
1478 entries: impl IntoIterator<Item = (String, strings::PanelCommand)>,
1479 ) {
1480 let mut all = self.0.panel_commands.borrow_mut();
1481 Arc::make_mut(&mut all).extend(entries);
1482 strings::set_panel_commands(&self.egui(), all.clone());
1483 }
1484
1485 pub fn arrangement_strings(&self) -> crate::arrangements::ArrangementStrings {
1491 self.0.arrangement_strings.get()
1492 }
1493
1494 pub fn name(&self) -> String {
1497 self.0.name.borrow().clone()
1498 }
1499
1500 pub fn app_id(&self) -> String {
1503 self.0.app_id.borrow().clone()
1504 }
1505
1506 pub fn store(&self) -> SharedStore {
1508 self.0.store.clone()
1509 }
1510
1511 pub fn value<T: egui_pop_core::binding::Bindable>(&self, path: &str) -> Option<T> {
1514 egui_pop_core::binding::read(&self.0.store, path)
1515 }
1516
1517 pub fn setting<T: egui_pop_core::binding::Bindable>(&self, id: &SettingId) -> Option<T> {
1520 self.value(&id.path())
1521 }
1522
1523 pub fn persist(&self) -> Option<Persist> {
1526 self.0.writer.borrow().as_ref().map(|w| w.persist().clone())
1527 }
1528
1529 pub fn save_later(&self, name: &str, text: String) -> bool {
1536 let ctx = self.egui();
1537 let now = egui_pop_core::motion::now(&ctx);
1538 let mut w = self.0.writer.borrow_mut();
1539 let Some(w) = w.as_mut() else {
1540 return false;
1541 };
1542 if w.offer(name, text, now) {
1543 ctx.request_repaint_after(std::time::Duration::from_secs_f64(
1544 egui_pop_core::persist::DEBOUNCE,
1545 ));
1546 }
1547 true
1548 }
1549
1550 pub fn saved_already(&self, name: &str, text: &str) {
1553 if let Some(w) = self.0.writer.borrow_mut().as_mut() {
1554 w.written(name, text);
1555 }
1556 }
1557
1558 pub fn flush_documents(&self) -> Vec<(String, Result<(), PersistError>)> {
1561 self.0
1562 .writer
1563 .borrow_mut()
1564 .as_mut()
1565 .map(Writer::flush)
1566 .unwrap_or_default()
1567 }
1568
1569 pub fn pending_documents(&self) -> Vec<String> {
1571 self.0
1572 .writer
1573 .borrow()
1574 .as_ref()
1575 .map(|w| w.pending().into_iter().map(str::to_string).collect())
1576 .unwrap_or_default()
1577 }
1578
1579 pub fn publish(&self, source: &str, cause: Option<Seq>, name: &str, data: Json) {
1585 match self.0.host.borrow_mut().as_mut() {
1586 Some(h) => {
1587 self.publish_to(h.as_mut(), source, cause, name, data);
1588 }
1589 None => self
1590 .0
1591 .held
1592 .borrow_mut()
1593 .push((source.into(), cause, name.into(), data)),
1594 }
1595 }
1596
1597 fn publish_to(
1600 &self,
1601 h: &mut dyn Host,
1602 source: &str,
1603 cause: Option<Seq>,
1604 name: &str,
1605 data: Json,
1606 ) -> Seq {
1607 if let Some(journal) = self.bus_journal() {
1608 match crate::bus::journal::publish(journal, source, cause, name, data) {
1609 Ok(seq) => return seq,
1610 Err(refused) => {
1611 log::error!(target: "egui_pop", "`{name}` not journaled: {refused}");
1612 return journal.last_seq();
1613 }
1614 }
1615 }
1616 match h.publish(source, cause, name, data.clone()) {
1619 Some(seq) => seq,
1620 None => self
1621 .0
1622 .journal
1623 .borrow_mut()
1624 .publish(source, cause, name, data),
1625 }
1626 }
1627
1628 pub fn events_since(&self, seq: Seq) -> Vec<Event> {
1634 if let Some(journal) = self.bus_journal() {
1635 return journal
1636 .since(seq, usize::MAX)
1637 .entries
1638 .iter()
1639 .map(crate::bus::journal::event_of)
1640 .collect();
1641 }
1642 self.0
1643 .host
1644 .borrow()
1645 .as_ref()
1646 .map(|h| {
1647 h.since(seq)
1648 .unwrap_or_else(|| self.0.journal.borrow().since(seq))
1649 })
1650 .unwrap_or_default()
1651 }
1652
1653 fn bus_journal(&self) -> Option<&dyn crate::bus::bus_contract_journal::Journal> {
1655 if self.0.journal_on_bus.get() {
1656 self.0.bus.kernel.journal()
1657 } else {
1658 None
1659 }
1660 }
1661
1662 fn with_host<R>(&self, f: impl FnOnce(&dyn Host) -> R) -> Option<R> {
1664 self.0.host.borrow().as_deref().map(f)
1665 }
1666
1667 pub(crate) fn dispatch_groups(&self) -> Option<Rc<dyn crate::host::Groups>> {
1669 self.0.dispatch_groups.borrow().clone()
1670 }
1671
1672 pub(crate) fn with_host_mut<R>(
1674 &self,
1675 f: impl FnOnce(&mut (dyn Host + 'static)) -> R,
1676 ) -> Option<R> {
1677 let mut host = self.0.host.borrow_mut();
1678 host.as_mut().map(|h| f(h.as_mut()))
1679 }
1680
1681 pub fn can_undo(&self) -> bool {
1685 crate::history::can_undo(self)
1686 }
1687
1688 pub fn can_redo(&self) -> bool {
1690 crate::history::can_redo(self)
1691 }
1692
1693 pub fn undo_label(&self) -> Option<String> {
1695 crate::history::undo_label(self)
1696 }
1697
1698 pub fn redo_label(&self) -> Option<String> {
1700 crate::history::redo_label(self)
1701 }
1702
1703 pub fn command_title(&self, spec: &CommandSpec) -> String {
1709 if let Some(t) = self.command_text(&spec.id).title {
1710 return t;
1711 }
1712 let ctx = self.egui();
1713 let title = strings::command_title(&ctx, spec.id.as_str(), &spec.title);
1714 let label = if spec.id == CMD_UNDO {
1715 self.undo_label()
1716 } else if spec.id == CMD_REDO {
1717 self.redo_label()
1718 } else {
1719 None
1720 };
1721 match label.filter(|l| !l.is_empty()) {
1722 Some(l) => strings::tr_args(
1723 &ctx,
1724 &crate::strings::COMMAND_WITH_CHANGE,
1725 &[("title", &title), ("change", &l)],
1726 ),
1727 None => title,
1728 }
1729 }
1730
1731 pub fn command_tooltip(&self, spec: &CommandSpec) -> String {
1736 match self.command_text(&spec.id).tooltip {
1737 Some(t) => t,
1738 None => strings::command_description(&self.egui(), spec.id.as_str(), &spec.description),
1739 }
1740 }
1741
1742 pub fn command_menu_title(&self, spec: &CommandSpec) -> String {
1747 strings::without_argument_hint(&self.command_title(spec)).to_string()
1748 }
1749
1750 pub(crate) fn section_title(&self, ctx: &Context, owner: &OwnerId, section: &str) -> String {
1754 let derived = self.0.derived.borrow();
1755 match derived.sections.get(owner) {
1756 Some(title) if title == section => strings::plugin_title(ctx, owner.as_str(), section),
1757 _ => section.to_string(),
1758 }
1759 }
1760
1761 pub(crate) fn panel_kind(&self, id: &PanelId) -> egui_pop_model::panels::PanelKind {
1764 self.workbench_mut()
1765 .spec(id)
1766 .map(|s| s.kind)
1767 .unwrap_or_default()
1768 }
1769
1770 pub(crate) fn panel_title(&self, ctx: &Context, id: &PanelId) -> String {
1771 if id.is_instance() {
1774 let renamed = self
1775 .workbench_mut()
1776 .layout
1777 .instance(id)
1778 .and_then(|i| i.title.clone());
1779 if let Some(t) = renamed {
1780 return t;
1781 }
1782 if self.workbench_mut().spec(id).is_some() {
1783 let kind = self.panel_title(ctx, &id.kind());
1784 return format!("{kind} {}", id.instance_number());
1785 }
1786 }
1787 let title = self.workbench_mut().spec(id).map(|s| s.title.clone());
1788 match title {
1789 Some(t) => strings::panel_title(ctx, id.as_str(), &t),
1790 None => id.to_string(),
1791 }
1792 }
1793
1794 pub fn undo(&self, origin: &Origin) -> Outcome {
1799 crate::history::undo(self, origin)
1800 }
1801
1802 pub fn redo(&self, origin: &Origin) -> Outcome {
1804 crate::history::redo(self, origin)
1805 }
1806
1807 pub fn overlay_rects(&self) -> Vec<OverlayRect> {
1814 let ctx = self.egui();
1815 let dialog = self
1816 .service(&crate::dialogs::DIALOGS)
1817 .and_then(|d| d.current_in(self.window_group(ctx.viewport_id())))
1818 .map(|(id, _)| id);
1819 let mut known: Vec<Id> = Vec::new();
1820 let mut out: Vec<OverlayRect> = overlay::rects(&ctx)
1821 .into_iter()
1822 .map(|(spec, rect)| {
1823 known.push(spec.id);
1824 let (kind, id) = match dialog {
1825 Some(n) if spec.id == crate::dialogs::overlay_id(n) => {
1826 (OverlayKind::Dialog, format!("dialog:{n}"))
1827 }
1828 _ => (
1829 match spec.kind {
1830 overlay::Kind::Modal => OverlayKind::Modal,
1831 overlay::Kind::Popover => OverlayKind::Popover,
1832 overlay::Kind::Menu => OverlayKind::Menu,
1833 },
1834 spec.label.clone(),
1835 ),
1836 };
1837 OverlayRect { kind, id, rect }
1838 })
1839 .collect();
1840 if let Some(hint) = self.drop_hint().filter(|h| h.armed) {
1842 out.push(OverlayRect {
1843 kind: OverlayKind::DropHint,
1844 id: hint.name(),
1845 rect: hint.rect,
1846 });
1847 }
1848 let toasts = crate::toasts::area_id();
1849 known.push(toasts);
1850 if self.active_window() == ctx.viewport_id()
1852 && self
1853 .service(&crate::toasts::TOASTS)
1854 .is_some_and(|t| !t.shown().is_empty())
1855 && let Some(rect) = ctx.memory(|m| m.area_rect(toasts))
1856 {
1857 out.push(OverlayRect {
1858 kind: OverlayKind::Toasts,
1859 id: "toasts".into(),
1860 rect,
1861 });
1862 }
1863 let mut popups: Vec<(Id, egui::Rect)> = ctx.memory(|m| {
1864 m.areas()
1865 .visible_layer_ids()
1866 .into_iter()
1867 .filter(|l| l.order == egui::Order::Foreground && !known.contains(&l.id))
1868 .filter_map(|l| m.area_rect(l.id).map(|r| (l.id, r)))
1869 .collect()
1870 });
1871 popups.sort_by_key(|a| a.0.value());
1872 let menu = self.popup().map(|p| p.menu);
1873 out.extend(popups.into_iter().map(|(id, rect)| match &menu {
1874 Some(m) if id == crate::menus::popup_id() => OverlayRect {
1875 kind: OverlayKind::Menu,
1876 id: m.to_string(),
1877 rect,
1878 },
1879 _ => OverlayRect {
1880 kind: OverlayKind::Popup,
1881 id: format!("popup:{}", id.short_debug_format()),
1882 rect,
1883 },
1884 }));
1885 out
1886 }
1887
1888 pub fn last_event(&self) -> Seq {
1893 if let Some(journal) = self.bus_journal() {
1894 return journal.last_seq();
1895 }
1896 self.0.host.borrow().as_ref().map_or(0, |h| {
1897 h.last_seq()
1898 .unwrap_or_else(|| self.0.journal.borrow().last())
1899 })
1900 }
1901
1902 pub(crate) fn add_collector(&self, owner: &OwnerId, c: FnCollector) -> Result<(), CtxError> {
1903 let name = egui_pop_core::debug::Collector::name(&c).to_string();
1904 self.0
1905 .bridge
1906 .borrow_mut()
1907 .register(c)
1908 .map_err(CtxError::Collector)?;
1909 self.0.collectors.borrow_mut().push((owner.clone(), name));
1910 Ok(())
1911 }
1912
1913 pub fn step(
1918 &self,
1919 step: &StepId,
1920 args: Json,
1921 default: impl FnOnce(&AppHandle, &Json) -> Result<Json, String>,
1922 ) -> Outcome {
1923 self.step_with(step, args, false, default)
1924 }
1925
1926 pub(crate) fn step_with(
1929 &self,
1930 step: &StepId,
1931 args: Json,
1932 quiet: bool,
1933 default: impl FnOnce(&AppHandle, &Json) -> Result<Json, String>,
1934 ) -> Outcome {
1935 let hooks: Vec<(OwnerId, HookFn)> = self
1936 .0
1937 .step_hooks
1938 .borrow()
1939 .iter()
1940 .filter(|s| s.item.step == *step)
1941 .map(|s| (s.owner.clone(), s.item.f.clone()))
1942 .collect();
1943 let declared = self.0.steps.borrow().contains(step);
1944 let (outcome, trace) = crate::steps::run(self, step, args, hooks, declared, quiet, default);
1945 if quiet && outcome.ok() {
1946 return outcome;
1947 }
1948 let mut traces = self.0.step_traces.borrow_mut();
1949 traces.push_back(trace);
1950 while traces.len() > crate::steps::TRACES {
1951 traces.pop_front();
1952 }
1953 outcome
1954 }
1955
1956 pub fn steps(&self) -> Vec<StepInfo> {
1959 let hooks = self.0.step_hooks.borrow();
1960 self.0
1961 .steps
1962 .borrow()
1963 .in_order()
1964 .into_iter()
1965 .map(|(id, slot)| StepInfo {
1966 spec: slot.item.clone(),
1967 owner: slot.owner.clone(),
1968 hooks: hooks
1969 .iter()
1970 .filter(|h| h.item.step == *id)
1971 .map(|h| HookInfo {
1972 owner: h.owner.clone(),
1973 kind: h.item.f.kind(),
1974 })
1975 .collect(),
1976 })
1977 .collect()
1978 }
1979
1980 pub fn step_traces(&self) -> Vec<StepTrace> {
1982 self.0.step_traces.borrow().iter().cloned().collect()
1983 }
1984
1985 pub(crate) fn declare_step(&self, owner: &OwnerId, spec: StepSpec) -> Result<(), CtxError> {
1986 let id = spec.id.clone();
1987 self.0
1988 .steps
1989 .borrow_mut()
1990 .insert(owner, id, spec)
1991 .map_err(|t| CtxError::Step {
1992 id: t.id.to_string(),
1993 by: t.by,
1994 })
1995 }
1996
1997 pub(crate) fn add_step_hook(&self, owner: &OwnerId, step: StepId, f: HookFn) {
1998 self.0
1999 .step_hooks
2000 .borrow_mut()
2001 .push(owner, StepHook { step, f });
2002 }
2003
2004 pub(crate) fn add_list_provider(&self, owner: &OwnerId, provider: crate::menus::Provider) {
2005 self.0.lists.borrow_mut().push(owner, provider);
2006 }
2007
2008 pub fn list_items(&self, name: &str, cx: &WhenContext) -> Vec<crate::menus::ListItem> {
2013 let provider = self
2014 .0
2015 .lists
2016 .borrow()
2017 .iter()
2018 .filter(|s| s.item.name == name)
2019 .last()
2020 .map(|s| (s.owner.clone(), s.item.f.clone()));
2021 let Some((owner, f)) = provider else {
2022 return Vec::new();
2023 };
2024 let items = f(self, cx);
2025 self.0.list_traces.borrow_mut().insert(
2026 name.to_string(),
2027 crate::menus::ListTrace {
2028 name: name.to_string(),
2029 owner,
2030 items: items.clone(),
2031 },
2032 );
2033 items
2034 }
2035
2036 pub fn lists(&self) -> Json {
2038 let traces = self.0.list_traces.borrow();
2039 json!(
2040 self.0
2041 .lists
2042 .borrow()
2043 .iter()
2044 .map(|s| json!({
2045 "name": s.item.name,
2046 "owner": s.owner,
2047 "last": traces.get(&s.item.name).map(|t| &t.items),
2048 }))
2049 .collect::<Vec<_>>()
2050 )
2051 }
2052
2053 pub(crate) fn popup(&self) -> Option<crate::menus::Popup> {
2054 self.0.popup.borrow().clone()
2055 }
2056
2057 pub(crate) fn set_popup(&self, popup: Option<crate::menus::Popup>) {
2058 *self.0.popup.borrow_mut() = popup;
2059 }
2060
2061 pub fn running(&self, id: &CommandId) -> bool {
2063 self.0.running.borrow().get(id).is_some_and(|n| *n > 0)
2064 }
2065
2066 pub fn running_since(&self, id: &CommandId) -> Option<f64> {
2070 self.0.running_since.borrow().get(id).copied()
2071 }
2072
2073 pub(crate) fn host_free(&self) -> bool {
2075 self.0.host.try_borrow().is_ok_and(|h| h.is_some())
2076 }
2077
2078 pub(crate) fn publish_now(
2079 &self,
2080 source: &str,
2081 cause: Option<Seq>,
2082 name: &str,
2083 data: Json,
2084 ) -> Seq {
2085 let mut host = self.0.host.borrow_mut();
2086 let h = host.as_mut().expect("the host is free outside a dispatch");
2087 for (s, c, n, d) in self.0.held.borrow_mut().drain(..) {
2088 self.publish_to(h.as_mut(), &s, c, &n, d);
2089 }
2090 self.publish_to(h.as_mut(), source, cause, name, data)
2091 }
2092
2093 pub fn service<T: Send + Sync + 'static>(&self, token: &ServiceToken<T>) -> Option<Arc<T>> {
2095 self.0.services.borrow().get(token)
2096 }
2097
2098 pub fn theme(&self) -> Arc<ThemeService> {
2100 self.service(&THEME)
2101 .expect("the framework provides the theme")
2102 }
2103
2104 pub fn run(&self, command: CommandId, args: Json) {
2109 self.run_as(command, args, self.acting_origin());
2110 }
2111
2112 pub fn run_as(&self, command: CommandId, args: Json, origin: Origin) {
2120 let acting = self.acting_origin();
2121 if let Some(reason) = escalation(&acting, &origin) {
2122 log::warn!(target: "egui_pop", "command `{command}`: {reason}");
2123 self.publish(
2124 &source_of(&acting),
2125 None,
2126 "command.refused",
2127 json!({ "command": command, "origin": source_of(&origin), "reason": reason }),
2128 );
2129 return;
2130 }
2131 let group = crate::windows::current_group().map(|g| self.window_group(g));
2134 if group.is_some_and(|g| g != egui::ViewportId::ROOT) {
2135 let context = self.when_context();
2136 self.push_request(Request::RunIn {
2137 command,
2138 args,
2139 origin,
2140 context,
2141 });
2142 return;
2143 }
2144 self.push_request(Request::Run {
2145 command,
2146 args,
2147 origin,
2148 });
2149 }
2150
2151 pub fn acting_origin(&self) -> Origin {
2155 self.0
2156 .acting
2157 .borrow()
2158 .last()
2159 .cloned()
2160 .unwrap_or(Origin::User)
2161 }
2162
2163 pub fn set_plugin_enabled(&self, plugin: PluginId, enabled: bool) {
2166 self.push_request(Request::Enable(plugin, enabled));
2167 }
2168
2169 pub(crate) fn push_request(&self, r: Request) {
2170 self.0.requests.borrow_mut().push(r);
2171 self.egui().request_repaint();
2172 }
2173
2174 pub(crate) fn run_in_context(&self, command: CommandId, args: Json, context: WhenContext) {
2177 self.push_request(Request::RunIn {
2178 command,
2179 args,
2180 origin: Origin::User,
2181 context,
2182 });
2183 self.egui().request_repaint_of(egui::ViewportId::ROOT);
2184 }
2185
2186 pub(crate) fn has_requests(&self) -> bool {
2188 !self.0.requests.borrow().is_empty()
2189 }
2190
2191 pub(crate) fn shared_keymap(&self) -> Rc<Keymap> {
2193 self.0.keymap.borrow().clone()
2194 }
2195
2196 pub(crate) fn capturing_keys(&self) -> bool {
2198 self.0.capturing.get()
2199 }
2200
2201 pub fn set_context(&self, key: &str, value: &str) {
2207 if !self.0.stack_writing.get() && crate::contexts::is_stack_key(key) {
2208 crate::contexts::written_by_hand(self, key, value);
2209 }
2210 self.0.context.borrow_mut().set(key, value);
2211 }
2212
2213 pub(crate) fn set_stack_context(&self, key: &str, value: &str) {
2215 self.0.stack_writing.set(true);
2216 self.0.context.borrow_mut().set(key, value);
2217 self.0.stack_writing.set(false);
2218 }
2219
2220 pub(crate) fn running_command(&self) -> Option<(CommandId, Option<OwnerId>)> {
2222 self.0.running_commands.borrow().last().cloned()
2223 }
2224
2225 pub(crate) fn warn(
2227 &self,
2228 code: &'static str,
2229 owner: Option<&OwnerId>,
2230 subject: &str,
2231 message: String,
2232 ) {
2233 self.0
2234 .diagnostics
2235 .borrow_mut()
2236 .warn(code, owner, subject, message);
2237 }
2238
2239 pub fn context(&self) -> WhenContext {
2241 self.0.context.borrow().clone()
2242 }
2243
2244 pub fn when_context(&self) -> WhenContext {
2265 let mut base = self.context();
2266 let ctx = &self.egui();
2267 let flag = |on: bool| if on { "true" } else { "false" };
2268 let overlay_open = !overlay::stack(ctx).is_empty() || egui::Popup::is_any_open(ctx);
2269 base.set("overlayOpen", flag(overlay_open));
2270 let here = ctx.viewport_id();
2271 let group = self.current_window_group_or(here);
2272 let view = if group == self.window_group(here) {
2275 here
2276 } else {
2277 self.shown_in(group)
2278 };
2279 base.set("modalOpen", flag(overlay::modal_open_in(ctx, group)));
2280 base.set("canUndo", flag(self.can_undo()));
2281 base.set("canRedo", flag(self.can_redo()));
2282 base.set(
2283 CONTEXT_UNDO_NEEDS_VIEW,
2284 flag(crate::history::needs_view(self, false)),
2285 );
2286 base.set(
2287 CONTEXT_REDO_NEEDS_VIEW,
2288 flag(crate::history::needs_view(self, true)),
2289 );
2290 let focused = if self.window_group(view) != egui::ViewportId::ROOT {
2298 Some(self.window_focused_panel(view))
2299 } else {
2300 self.try_workbench().map(|wb| wb.focused.clone())
2301 };
2302 if let Some(panel) = focused {
2303 base.set("focusedPanel", panel.as_ref().map_or("", PanelId::as_str));
2304 let kind = panel.as_ref().map(PanelId::kind);
2305 base.set(
2306 CONTEXT_FOCUSED_PANEL_KIND,
2307 kind.as_ref().map_or("", PanelId::as_str),
2308 );
2309 }
2310 if let Some(panel) = self.window_panel(view) {
2311 base.set(CONTEXT_WINDOW, panel.as_str());
2312 }
2313 let app_window = match self.window_at(view) {
2314 Some(id) => id,
2315 None => self.windows_ref().root.id.clone(),
2317 };
2318 base.set(crate::windows::CONTEXT_APP_WINDOW, app_window.as_str());
2319 for (key, on) in crate::clipboard::keys(self).into_iter().flatten() {
2320 base.set(key, flag(on));
2321 }
2322 for (key, on) in crate::layout_controls::keys(self) {
2323 base.set(key, flag(on));
2324 }
2325 base.set(
2326 "canvasActive",
2327 flag(egui_pop_core::canvas::active(ctx).is_some()),
2328 );
2329 focus::when_context(ctx, &base)
2330 }
2331
2332 pub fn window_name(&self, window: egui::ViewportId) -> String {
2334 if let Some(p) = self.window_panel(window) {
2335 return p.to_string();
2336 }
2337 if window != egui::ViewportId::ROOT
2338 && let Some(id) = self.window_at(window)
2339 {
2340 return id.to_string();
2341 }
2342 "main".to_string()
2343 }
2344
2345 pub fn describe_windows(&self) -> Json {
2348 let ctx = self.egui();
2349 let modal = overlay::modal_windows(&ctx);
2350 let mut windows = vec![egui::ViewportId::ROOT];
2351 if let Ok(wb) = self.0.workbench.try_borrow() {
2352 windows.extend(
2353 wb.layout
2354 .auxiliary
2355 .iter()
2356 .map(|a| crate::workbench::window_id(&a.panel)),
2357 );
2358 }
2359 windows.extend(self.windows().iter().skip(1).map(|w| w.viewport));
2360 let stacks = overlay::stacks(&ctx);
2361 let palettes: Vec<String> = self
2363 .service(&crate::palette::PALETTE)
2364 .map(|p| {
2365 let active = self.window_group(self.active_window());
2366 let mut groups = p.open_groups();
2367 groups.sort_by_key(|g| *g != active);
2368 groups
2369 .into_iter()
2370 .filter_map(|g| p.window_in(g))
2371 .map(|w| self.window_name(self.still_open(w)))
2372 .collect()
2373 })
2374 .unwrap_or_default();
2375 let palette = palettes.first().cloned();
2376 json!({
2377 "active": self.window_name(self.active_window()),
2378 "windows": windows.iter().map(|v| json!({
2379 "window": self.window_name(*v),
2380 "overlays": stacks
2381 .iter()
2382 .find(|(w, _)| w == v)
2383 .map(|(_, specs)| specs.iter().map(|o| o.label.clone()).collect::<Vec<_>>())
2384 .unwrap_or_default(),
2385 "modal": modal.contains(v),
2386 })).collect::<Vec<_>>(),
2387 "palette": palette,
2388 "palettes": palettes,
2389 "popup_menu": crate::menus::popup_window(self).map(|w| self.window_name(w)),
2390 "app_windows": crate::windows::describe(self),
2391 })
2392 }
2393
2394 pub fn window_panel(&self, window: egui::ViewportId) -> Option<PanelId> {
2398 if window == egui::ViewportId::ROOT {
2399 return None;
2400 }
2401 let wb = self.0.workbench.try_borrow().ok()?;
2402 wb.layout
2403 .auxiliary
2404 .iter()
2405 .find(|a| crate::workbench::window_id(&a.panel) == window)
2406 .map(|a| a.panel.clone())
2407 }
2408
2409 pub fn active_window(&self) -> egui::ViewportId {
2414 let (id, kind) = self.active_window_record();
2415 self.still_open(
2416 crate::window_invariants::viewport_of(kind, &id).unwrap_or(egui::ViewportId::ROOT),
2417 )
2418 }
2419
2420 pub(crate) fn still_open(&self, window: egui::ViewportId) -> egui::ViewportId {
2422 if self.window_panel(window).is_some() || crate::windows::is_app_window(self, window) {
2423 window
2424 } else {
2425 egui::ViewportId::ROOT
2426 }
2427 }
2428
2429 pub fn diagnostics(&self) -> Vec<Diagnostic> {
2432 let mut all = self.0.diagnostics.borrow().all().to_vec();
2433 all.extend_from_slice(lock(&self.0.store).diagnostics().all());
2434 all
2435 }
2436
2437 pub fn menu_ids(&self) -> Vec<MenuId> {
2439 self.0.derived.borrow().menus.keys().cloned().collect()
2440 }
2441
2442 pub fn menu(&self, menu: &MenuId) -> Vec<MenuItem> {
2444 self.0
2445 .derived
2446 .borrow()
2447 .menus
2448 .get(menu)
2449 .cloned()
2450 .unwrap_or_default()
2451 }
2452
2453 pub fn palette(&self) -> Vec<PaletteEntry> {
2455 self.0.derived.borrow().palette.clone()
2456 }
2457
2458 pub fn palette_search(&self, query: &str) -> Vec<crate::palette::Ranked> {
2463 crate::palette::search(self, query)
2464 }
2465
2466 pub fn settings(&self) -> Vec<SettingEntry> {
2468 self.0.derived.borrow().settings.clone()
2469 }
2470
2471 pub fn command_gone_with(&self, id: &CommandId) -> Option<PluginId> {
2475 self.0.gone_commands.borrow().get(id).cloned()
2476 }
2477
2478 pub fn dormant_keys(&self) -> Vec<DormantKey> {
2484 self.0.derived.borrow().dormant.clone()
2485 }
2486
2487 pub fn command(&self, id: &CommandId) -> Option<CommandSpec> {
2489 self.0
2490 .derived
2491 .borrow()
2492 .commands
2493 .iter()
2494 .find(|(s, _)| s.id == *id)
2495 .map(|(s, _)| s.clone())
2496 }
2497
2498 pub fn icon_set_by(&self, id: &CommandId) -> Option<OwnerId> {
2501 self.0.derived.borrow().icons_set_by.get(id).cloned()
2502 }
2503
2504 pub fn rebind(&self, command: CommandId, keys: Option<String>) {
2507 self.rebind_in(Layer::User, command, keys);
2508 }
2509
2510 pub fn rebind_in(&self, layer: Layer, command: CommandId, keys: Option<String>) {
2516 self.push_request(Request::Rebind {
2517 command,
2518 keys,
2519 layer,
2520 });
2521 }
2522
2523 pub fn rebind_gestures(&self, layer: Layer, command: CommandId, keys: &[&str]) {
2527 self.push_request(Request::RebindAll {
2528 command,
2529 keys: keys.iter().map(|k| (*k).to_string()).collect(),
2530 layer,
2531 });
2532 }
2533
2534 pub fn reset_keys(&self, command: CommandId) {
2536 self.reset_keys_in(Layer::User, command);
2537 }
2538
2539 pub fn reset_keys_in(&self, layer: Layer, command: CommandId) {
2542 self.push_request(Request::ResetKeys { command, layer });
2543 }
2544
2545 pub fn rebound_in(&self, layer: Layer, id: &CommandId) -> bool {
2548 let d = self.0.derived.borrow();
2549 match layer {
2550 Layer::User => d.rebound.contains(id),
2551 Layer::Workspace => d.rebound_workspace.contains(id),
2552 _ => false,
2553 }
2554 }
2555
2556 pub fn key_sources(&self, id: &CommandId) -> Vec<Binding> {
2558 self.0
2559 .derived
2560 .borrow()
2561 .sources
2562 .get(id)
2563 .cloned()
2564 .unwrap_or_default()
2565 }
2566
2567 pub fn offer_workspace_keys(&self, on: bool) {
2571 self.0.workspace_keys.set(on);
2572 }
2573
2574 pub fn workspace_keys_offered(&self) -> bool {
2576 self.0.workspace_keys.get()
2577 }
2578
2579 pub fn name_key_sources(&self, f: impl Fn(&Binding) -> Option<String> + 'static) {
2583 *self.0.key_source_names.borrow_mut() = Some(Rc::new(f));
2584 }
2585
2586 pub fn key_source_name(&self, ctx: &Context, binding: &Binding) -> Option<String> {
2590 let named = self.0.key_source_names.borrow().clone();
2591 if let Some(name) = named.and_then(|f| f(binding)) {
2592 return Some(name);
2593 }
2594 let key = match binding.layer {
2595 Layer::Suggestion | Layer::Default => return None,
2596 Layer::Workspace => &crate::strings::SHORTCUTS_FROM_WORKSPACE,
2597 Layer::User => &crate::strings::SHORTCUTS_FROM_USER,
2598 };
2599 Some(strings::tr(ctx, key))
2600 }
2601
2602 pub fn capture_keys(&self, on: bool) {
2605 self.0.capturing.set(on);
2606 }
2607
2608 pub fn keys_captured(&self) -> bool {
2610 self.0.capturing.get()
2611 }
2612
2613 pub fn key_conflicts_by_scope(&self) -> BTreeMap<String, Vec<(Binding, Binding)>> {
2615 let mut out: BTreeMap<String, Vec<(Binding, Binding)>> = BTreeMap::new();
2616 for (lose, win) in self.key_conflicts() {
2617 out.entry(lose.options.scope.to_string())
2618 .or_default()
2619 .push((lose, win));
2620 }
2621 out
2622 }
2623
2624 pub fn declare(&self, owner: &OwnerId, spec: CommandSpec) {
2630 self.push_request(Request::Declare {
2631 owner: owner.clone(),
2632 spec,
2633 });
2634 }
2635
2636 pub fn undeclare(&self, id: &CommandId) {
2639 self.push_request(Request::Undeclare(id.clone()));
2640 }
2641
2642 pub fn export_keymap(&self, layer: Layer) -> egui_pop_model::keymap::KeymapDoc {
2645 self.0
2646 .derived
2647 .borrow()
2648 .layers
2649 .get(&layer)
2650 .cloned()
2651 .unwrap_or_default()
2652 }
2653
2654 pub fn load_keymap(
2660 &self,
2661 doc: egui_pop_model::keymap::KeymapDoc,
2662 layer: Layer,
2663 ) -> egui_pop_model::keymap::KeymapDiff {
2664 let diff = egui_pop_model::keymap::KeymapDiff::between(&self.export_keymap(layer), &doc);
2665 self.push_request(Request::LoadKeymap { doc, layer });
2666 diff
2667 }
2668
2669 pub fn key_conflicts(&self) -> Vec<(Binding, Binding)> {
2672 self.0.derived.borrow().conflicts.clone()
2673 }
2674
2675 pub fn rebound(&self, id: &CommandId) -> bool {
2677 self.0.derived.borrow().rebound.contains(id)
2678 }
2679
2680 pub fn applies(&self, id: &CommandId, cx: &WhenContext) -> bool {
2682 self.0
2683 .derived
2684 .borrow()
2685 .commands
2686 .iter()
2687 .find(|(s, _)| s.id == *id)
2688 .is_some_and(|(s, _)| {
2689 s.when.is_empty()
2690 || egui_pop_model::when::When::parse(&s.when).is_ok_and(|w| w.eval(cx))
2691 })
2692 }
2693
2694 pub fn keys_for(&self, id: &CommandId) -> Vec<String> {
2696 self.0
2697 .derived
2698 .borrow()
2699 .keys
2700 .get(id)
2701 .cloned()
2702 .unwrap_or_default()
2703 }
2704
2705 pub fn system_bindings(&self) -> Vec<Binding> {
2709 self.0.derived.borrow().system.clone()
2710 }
2711
2712 pub fn commands(&self) -> Vec<(CommandSpec, OwnerId)> {
2714 self.0.derived.borrow().commands.clone()
2715 }
2716
2717 pub fn history(&self) -> Vec<Run> {
2719 self.0.history.borrow().clone()
2720 }
2721
2722 pub fn plugins(&self) -> Vec<PluginInfo> {
2724 self.0.plugins.borrow().clone()
2725 }
2726
2727 pub fn zones(&self) -> Vec<ZoneInfo> {
2729 self.0.zones.borrow().infos()
2730 }
2731
2732 pub fn services(&self) -> Vec<(String, OwnerId, &'static str)> {
2734 self.0
2735 .services
2736 .borrow()
2737 .list()
2738 .into_iter()
2739 .map(|(i, o, t)| (i.to_string(), o, t))
2740 .collect()
2741 }
2742
2743 pub(crate) fn zones_mut(&self) -> RefMut<'_, ZoneTable> {
2744 self.0.zones.borrow_mut()
2745 }
2746
2747 pub(crate) fn services_mut(&self) -> RefMut<'_, Services> {
2748 self.0.services.borrow_mut()
2749 }
2750
2751 pub(crate) fn add_panel_view(&self, owner: &OwnerId, id: PanelId, draw: PanelDraw) {
2752 self.0.panels.borrow_mut().insert(
2753 id,
2754 PanelView {
2755 owner: owner.clone(),
2756 draw: Some(draw),
2757 },
2758 );
2759 }
2760
2761 pub(crate) fn add_story(&self, owner: &OwnerId, story: Story) -> Result<(), CtxError> {
2762 let id = story.id.clone();
2763 self.0
2764 .stories
2765 .borrow_mut()
2766 .insert(owner, id, StoryEntry { story })
2767 .map_err(|t| CtxError::Story {
2768 id: t.id.to_string(),
2769 by: t.by,
2770 })
2771 }
2772
2773 pub fn zone_has_blocks(&self, zone: &ZoneId) -> bool {
2775 self.0
2776 .zones
2777 .borrow()
2778 .resolved
2779 .get(zone)
2780 .is_some_and(|b| !b.is_empty())
2781 }
2782
2783 pub fn show_zone(&self, ui: &mut Ui, zone: &ZoneId) {
2787 let plan: Vec<(usize, Vec<usize>, String, OwnerId)> =
2788 match self.0.zones.borrow().resolved.get(zone) {
2789 Some(blocks) => blocks
2790 .iter()
2791 .map(|r| (r.draw, r.wraps.clone(), r.id.to_string(), r.owner.clone()))
2792 .collect(),
2793 None => return,
2794 };
2795 for (draw, wraps, id, owner) in plan {
2796 let taken = {
2797 let mut z = self.0.zones.borrow_mut();
2798 let base = z.contributions.get_mut(draw).and_then(|c| c.block.take());
2799 let ws: Vec<(usize, Option<Block>)> = wraps
2800 .iter()
2801 .map(|&w| (w, z.contributions.get_mut(w).and_then(|c| c.block.take())))
2802 .collect();
2803 (base, ws)
2804 };
2805 let (Some(mut base), ws) = taken else {
2806 continue;
2807 };
2808 let mut wrap_blocks: Vec<(usize, Block)> = ws
2809 .into_iter()
2810 .filter_map(|(i, b)| b.map(|b| (i, b)))
2811 .collect();
2812 ui.push_id(("egui_pop_block", &id), |ui| {
2813 fault::boundary(ui, "block", &id, |ui| {
2814 let draw_fn: &mut DrawFn = match &mut base {
2815 Block::Add { draw, .. }
2816 | Block::Replace { draw, .. }
2817 | Block::Extend { draw, .. } => draw,
2818 Block::Wrap { .. } => return,
2819 };
2820 let mut wrap_fns: Vec<zones::WrapFn> = Vec::new();
2821 for (_, b) in &mut wrap_blocks {
2824 if let Block::Wrap { wrap, .. } = b {
2825 wrap_fns.push(std::mem::replace(wrap, Box::new(|_, _, _| {})));
2826 }
2827 }
2828 draw_chain(ui, self, draw_fn, &mut wrap_fns);
2829 egui_pop_core::inspect::region(
2831 ui,
2832 "block",
2833 &id,
2834 Some(zone.as_str()),
2835 owner.as_str(),
2836 );
2837 let mut back = wrap_fns.into_iter();
2838 for (_, b) in &mut wrap_blocks {
2839 if let Block::Wrap { wrap, .. } = b
2840 && let Some(f) = back.next()
2841 {
2842 *wrap = f;
2843 }
2844 }
2845 });
2846 });
2847 let mut z = self.0.zones.borrow_mut();
2848 if let Some(c) = z.contributions.get_mut(draw) {
2849 c.block = Some(base);
2850 }
2851 for (i, b) in wrap_blocks {
2852 if let Some(c) = z.contributions.get_mut(i) {
2853 c.block = Some(b);
2854 }
2855 }
2856 }
2857 }
2858
2859 pub fn stories(&self) -> Vec<StoryInfo> {
2861 let mut v: Vec<StoryInfo> = self
2862 .0
2863 .stories
2864 .borrow()
2865 .iter()
2866 .map(|(_, s)| StoryInfo {
2867 id: s.item.story.id.clone(),
2868 title: s.item.story.title.clone(),
2869 description: s.item.story.description.clone(),
2870 group: s.item.story.group.clone(),
2871 weight: s.item.story.weight,
2872 has_playground: s.item.story.playground.is_some(),
2873 owner: s.owner.clone(),
2874 })
2875 .collect();
2876 v.sort_by(|a, b| (&a.group, a.weight, &a.title).cmp(&(&b.group, b.weight, &b.title)));
2877 v
2878 }
2879
2880 fn with_story(&self, id: &StoryId, playground: bool, ui: &mut Ui) -> bool {
2881 let taken = {
2882 let mut s = self.0.stories.borrow_mut();
2883 s.get_mut(id).and_then(|e| {
2884 if playground {
2885 e.story.playground.take()
2886 } else {
2887 Some(std::mem::replace(&mut e.story.show, Box::new(|_, _| {})))
2888 }
2889 })
2890 };
2891 let Some(mut f) = taken else {
2892 return false;
2893 };
2894 let title = id.to_string();
2895 ui.push_id(("egui_pop_story", id.as_str(), playground), |ui| {
2896 fault::boundary(ui, "story", &title, |ui| f(ui, self));
2897 });
2898 if let Some(e) = self.0.stories.borrow_mut().get_mut(id) {
2899 if playground {
2900 e.story.playground = Some(f);
2901 } else {
2902 e.story.show = f;
2903 }
2904 }
2905 true
2906 }
2907
2908 pub fn show_story(&self, ui: &mut Ui, id: &StoryId) -> bool {
2910 self.with_story(id, false, ui)
2911 }
2912
2913 pub fn show_playground(&self, ui: &mut Ui, id: &StoryId) -> bool {
2915 self.with_story(id, true, ui)
2916 }
2917
2918 pub(crate) fn show_panel(&self, ui: &mut Ui, id: &PanelId) {
2920 let title = self.panel_title(ui.ctx(), id);
2921 let title = title.as_str();
2922 let key = if id.is_instance() && !self.0.panels.borrow().contains_key(id) {
2924 id.kind()
2925 } else {
2926 id.clone()
2927 };
2928 let taken = self
2929 .0
2930 .panels
2931 .borrow_mut()
2932 .get_mut(&key)
2933 .and_then(|p| Some((p.draw.take()?, p.owner.clone())));
2934 let Some((mut draw, owner)) = taken else {
2935 return;
2936 };
2937 let instance = crate::workbench::instances::Instance::of(id, title);
2938 let scope = scope_name(id.as_str());
2939 let region = ui.max_rect().intersect(ui.clip_rect());
2940 ui.push_id(("egui_pop_panel", id.as_str()), |ui| {
2941 focus::scope(ui, &scope, &[], |ui| {
2942 let taking = self.takes_the_focus(ui.ctx(), id, &scope);
2943 self.panel_stop(ui, id, title, taking);
2944 let failed = |fault: &fault::Fault| {
2945 log::error!(
2946 target: "egui_pop",
2947 "panel `{id}` (of `{owner}`) panicked while drawing: {}; \
2948 its region shows the fault, the rest of the window is drawn",
2949 fault.message
2950 );
2951 self.publish(
2952 "egui_pop",
2953 None,
2954 "panel.fault",
2955 json!({ "panel": id.as_str(), "owner": owner.as_str(), "message": fault.message }),
2956 );
2957 };
2958 let inert = self.panel_state(id.as_str()) != crate::bus::PanelState::Ready;
2961 let window = self
2963 .try_workbench()
2964 .and_then(|w| w.layout.window_of(id).map(|a| a.panel.clone()));
2965 egui_pop_core::areas::scope(ui, id.as_str(), inert, |ui| {
2966 let _drawing =
2968 crate::bus::drawing::Drawing::enter(self, id, window, ui.ctx().viewport_id());
2969 fault::boundary_reporting(
2970 ui,
2971 "panel",
2972 title,
2973 |ui| match &mut draw {
2974 PanelDraw::Plain(f) => f(ui, self),
2975 PanelDraw::Instance(f) => f(ui, self, &instance),
2976 },
2977 failed,
2978 );
2979 });
2980 crate::bus::panel_state::paint_content(
2983 &self.0.bus.panel_states,
2984 ui,
2985 id.as_str(),
2986 region,
2987 );
2988 egui_pop_core::inspect::region(ui, "panel", id.as_str(), None, owner.as_str());
2990 if taking {
2991 settle_panel_focus(ui);
2992 }
2993 });
2994 });
2995 if let Some(p) = self.0.panels.borrow_mut().get_mut(&key) {
2996 p.draw = Some(draw);
2997 }
2998 }
2999
3000 fn takes_the_focus(&self, ctx: &Context, id: &PanelId, scope: &str) -> bool {
3002 if !self.workbench_mut().take_focus_request(id) {
3003 return false;
3004 }
3005 ctx.request_repaint();
3006 if ctx.input(|i| i.viewport().focused) == Some(false) {
3008 self.raise_viewport(ctx.viewport_id(), "egui_pop.workbench");
3009 }
3010 if overlay::modal_open(ctx) {
3012 return false;
3013 }
3014 let inside =
3015 focus::focused(ctx).is_some() && focus::chain(ctx).iter().any(|r| r.name == scope);
3016 !inside
3017 }
3018
3019 fn panel_stop(&self, ui: &mut Ui, id: &PanelId, title: &str, taking: bool) {
3023 let stop = Id::unique(("egui_pop.panel_stop", id.as_str()));
3024 if taking {
3025 ui.memory_mut(|m| m.request_focus(stop));
3026 }
3027 if taking || ui.memory(|m| m.has_focus(stop)) {
3028 let r = ui.interact(ui.max_rect(), stop, egui::Sense::focusable_noninteractive());
3029 a11y::name(&r, egui::Role::Pane, title);
3030 }
3031 }
3032
3033 fn follow_focus(&self, ctx: &Context) {
3036 if ctx.viewport_id() == egui::ViewportId::ROOT {
3037 self.workbench_mut().age_focus_request();
3038 }
3039 if let Some(moved) = focus::take_moved(ctx)
3040 && self.workbench_mut().follow_focus(moved)
3041 {
3042 self.publish_focused();
3043 }
3044 }
3045
3046 fn publish_focused(&self) {
3047 let panel = self.focused_panel();
3048 self.publish(
3049 "egui_pop",
3050 None,
3051 "workbench.focused",
3052 json!({ "panel": panel }),
3053 );
3054 }
3055
3056 pub(crate) fn workbench_mut(&self) -> RefMut<'_, crate::workbench::Workbench> {
3057 self.0.workbench.borrow_mut()
3058 }
3059
3060 pub(crate) fn try_workbench(&self) -> Option<RefMut<'_, crate::workbench::Workbench>> {
3062 self.0.workbench.try_borrow_mut().ok()
3063 }
3064
3065 pub fn edge_to_edge(&self) -> bool {
3067 self.0.edge_to_edge.get()
3068 }
3069
3070 pub fn frameless(&self, area: Area) -> bool {
3074 self.0.frameless.borrow().contains(&area)
3075 }
3076
3077 pub fn bare_strip(&self, area: Area) -> bool {
3080 self.0.bare_strips.borrow().contains(&area)
3081 }
3082
3083 pub(crate) fn shell_bounds(&self) -> Vec<(PanelId, crate::workbench::ShellBounds)> {
3085 self.0.shell_bounds.borrow().clone()
3086 }
3087
3088 pub fn set_shell_panel_min_size(
3112 &self,
3113 panel: PanelId,
3114 size: Option<crate::workbench::ShellSize>,
3115 ) {
3116 if self.shell_panel_min_size(&panel) == size {
3117 return;
3118 }
3119 self.with_bounds(panel, |b| b.min = size);
3120 }
3121
3122 pub fn set_shell_panel_max_size(
3129 &self,
3130 panel: PanelId,
3131 size: Option<crate::workbench::ShellSize>,
3132 ) {
3133 if self.shell_panel_max_size(&panel) == size {
3134 return;
3135 }
3136 self.with_bounds(panel, |b| b.max = size);
3137 }
3138
3139 pub fn shell_panel_min_size(&self, panel: &PanelId) -> Option<crate::workbench::ShellSize> {
3145 let bounds = self.0.shell_bounds.borrow();
3146 bounds
3147 .iter()
3148 .find(|(p, _)| p == panel)
3149 .and_then(|(_, b)| b.min)
3150 }
3151
3152 pub fn shell_panel_max_size(&self, panel: &PanelId) -> Option<crate::workbench::ShellSize> {
3158 let bounds = self.0.shell_bounds.borrow();
3159 bounds
3160 .iter()
3161 .find(|(p, _)| p == panel)
3162 .and_then(|(_, b)| b.max)
3163 }
3164
3165 fn with_bounds(&self, panel: PanelId, f: impl FnOnce(&mut crate::workbench::ShellBounds)) {
3166 {
3167 let mut bounds = self.0.shell_bounds.borrow_mut();
3168 let at = match bounds.iter().position(|(p, _)| *p == panel) {
3169 Some(at) => at,
3170 None => {
3171 bounds.push((panel, Default::default()));
3172 bounds.len() - 1
3173 }
3174 };
3175 f(&mut bounds[at].1);
3176 }
3177 self.egui().request_repaint();
3178 }
3179
3180 pub fn centre_min_size(&self) -> Option<crate::workbench::ShellSize> {
3186 self.0.centre_min.get()
3187 }
3188
3189 pub fn system_text_scale(&self) -> crate::text::SystemTextScale {
3192 self.0.system_text_scale.get()
3193 }
3194
3195 pub fn system_always_shows_scroll_bars(&self) -> bool {
3198 self.0.system_scroll_bars.get()
3199 }
3200
3201 pub fn system_wheel_lines(&self) -> u32 {
3204 self.0.system_wheel_lines.get()
3205 }
3206
3207 pub fn menu_bar(&self) -> bool {
3210 self.0.menu_bar.get()
3211 }
3212
3213 pub fn system_file_chooser(&self) -> bool {
3216 self.0.system_file_chooser.get()
3217 }
3218
3219 pub fn transparent_panel_windows(&self) -> bool {
3223 self.0.transparent_panel_windows.get()
3224 }
3225
3226 pub fn rounded_windows(&self) -> bool {
3229 self.0.rounded_windows.get()
3230 }
3231
3232 pub(crate) fn set_drawing_areas(&self, on: bool) {
3233 self.0.drawing_areas.set(on);
3234 }
3235
3236 pub(crate) fn drawing_areas(&self) -> bool {
3239 self.0.drawing_areas.get()
3240 }
3241
3242 pub fn panel_visible(&self, id: &PanelId) -> bool {
3244 self.workbench_mut().shows(id)
3245 }
3246
3247 pub fn set_panel_visible(&self, id: &PanelId, visible: bool) {
3250 let palette = self.workbench_mut().spec(id).is_some_and(|s| s.palette);
3251 let change = if visible && palette {
3252 crate::workbench::Change::OpenPalette(id.clone())
3254 } else if visible {
3255 crate::workbench::Change::Show(id.clone())
3256 } else {
3257 crate::workbench::Change::Hide(id.clone())
3258 };
3259 self.change_workbench(change);
3260 }
3261
3262 pub fn layout(&self) -> egui_pop_model::layout::Layout {
3265 self.workbench_mut().layout()
3266 }
3267
3268 pub fn saved_layout(&self) -> egui_pop_model::layout::SavedLayout {
3272 let mut wb = self.workbench_mut();
3273 egui_pop_model::layout::SavedLayout {
3274 layout: wb.layout(),
3275 dormant: wb.dormant.clone(),
3276 }
3277 }
3278
3279 pub fn set_layout(&self, layout: egui_pop_model::layout::Layout) -> Vec<String> {
3282 let before = self.workbench_mut().layout.auxiliary.clone();
3283 let names = self.layout_screens();
3284 let screens: Vec<&str> = names.iter().map(String::as_str).collect();
3285 let instances = crate::workbench::instances::open_ids(self);
3286 let notes = self.workbench_mut().set_layout(layout, &screens);
3287 self.sync_panel_windows(&before);
3288 crate::workbench::instances::say(self, &instances);
3289 self.note_layout("layout.set");
3290 notes
3291 }
3292
3293 pub fn panels(&self) -> Vec<egui_pop_model::panels::PanelSpec> {
3295 self.workbench_mut().specs.clone()
3296 }
3297
3298 pub fn declared_panels(&self) -> Vec<(egui_pop_model::panels::PanelSpec, OwnerId)> {
3306 self.0.derived.borrow().panels.clone()
3307 }
3308
3309 pub fn drop_hint(&self) -> Option<crate::workbench::DropHint> {
3316 self.workbench_mut().hint.clone()
3317 }
3318
3319 pub fn window_drop(&self) -> Option<crate::workbench::WindowDrop> {
3326 self.workbench_mut().window_drop.clone()
3327 }
3328
3329 pub fn window_outlines(&self) -> Vec<PanelId> {
3337 self.workbench_mut().window_outlines().to_vec()
3338 }
3339
3340 pub fn focused_panel(&self) -> Option<PanelId> {
3344 self.workbench_mut().focused.clone()
3345 }
3346
3347 pub fn change_workbench(&self, change: crate::workbench::Change) -> Option<Outcome> {
3353 self.change_workbench_from(change, None)
3354 }
3355
3356 pub(crate) fn change_workbench_from(
3362 &self,
3363 change: crate::workbench::Change,
3364 from: Option<crate::workbench::window_areas::OpenFrom>,
3365 ) -> Option<Outcome> {
3366 if self.0.drawing_areas.get() {
3367 self.push_request(Request::Workbench(change));
3368 return None;
3369 }
3370 let (step, mut args) = change.step();
3371 if let Some(from) = from {
3372 if let Some(origin) = from.origin {
3373 args["origin"] = Json::String(origin);
3374 }
3375 if let Some(home) = from.home {
3376 args["home"] = Json::String(home);
3377 }
3378 if let Some(area) = from.area {
3379 args["home_area"] = Json::String(crate::workbench::area_name(area).into());
3380 }
3381 }
3382 let id = step.clone();
3383 let focused = self.focused_panel();
3384 let instances = crate::workbench::instances::open_ids(self);
3385 let out = self.step(&step, args, move |app, args| {
3386 let c = crate::workbench::Change::from_args(&id, args)?;
3387 if let crate::workbench::Change::Zen(on) = c {
3390 let panel = match args.get("panel").and_then(Json::as_str) {
3391 Some(p) => Some(PanelId::new(p).map_err(|e| e.to_string())?),
3392 None => None,
3393 };
3394 return app.workbench_mut().apply_zen(on, panel);
3395 }
3396 let before = app.workbench_mut().layout.auxiliary.clone();
3401 let scope = crate::workbench::float_scope(app);
3403 app.workbench_mut().float_scope = scope;
3404 let from = crate::workbench::window_areas::OpenFrom::of(app, args);
3407 let shown = app.shown_window_ids();
3408 {
3409 let mut wb = app.workbench_mut();
3410 wb.open_from = Some(from);
3411 wb.open_windows = shown;
3412 }
3413 let done = match crate::bus::panels::ask(app, &c) {
3414 Some(done) => done,
3415 None => app.workbench_mut().apply(&c),
3416 };
3417 app.workbench_mut().open_from = None;
3418 app.sync_panel_windows(&before);
3419 done
3420 });
3421 if self.focused_panel() != focused {
3422 self.publish_focused();
3423 }
3424 crate::workbench::instances::say(self, &instances);
3425 if matches!(out, Outcome::Done(Ok(_))) {
3427 self.note_layout(step.as_str());
3428 }
3429 if let (Some(event), Outcome::Done(Ok(result))) = (change.event(), &out) {
3431 self.publish("egui_pop", None, event, result.clone());
3432 }
3433 if matches!(change, crate::workbench::Change::Zen(_)) {
3434 self.follow_zen();
3435 }
3436 self.egui().request_repaint();
3437 Some(out)
3438 }
3439
3440 pub fn set_zen(&self, on: bool) -> Option<Outcome> {
3443 self.change_workbench(crate::workbench::Change::Zen(on))
3444 }
3445
3446 pub fn set_zen_panel(&self, panel: &PanelId) -> Option<Outcome> {
3456 let args = json!({ "zen": true, "panel": panel });
3457 if self.0.drawing_areas.get() {
3458 self.push_request(Request::Run {
3459 command: crate::workbench::CMD_ZEN,
3460 args: json!({ "panel": panel }),
3461 origin: Origin::User,
3462 });
3463 return None;
3464 }
3465 let step = crate::workbench::STEP_ZEN;
3466 let id = step.clone();
3467 let out = self.step(&step, args, move |app, args| {
3468 let c = crate::workbench::Change::from_args(&id, args)?;
3469 let crate::workbench::Change::Zen(on) = c else {
3470 return Err("not a zen mode change".into());
3471 };
3472 let panel = match args.get("panel").and_then(Json::as_str) {
3473 Some(p) => Some(PanelId::new(p).map_err(|e| e.to_string())?),
3474 None => None,
3475 };
3476 app.workbench_mut().apply_zen(on, panel)
3477 });
3478 self.follow_zen();
3479 self.egui().request_repaint();
3480 Some(out)
3481 }
3482
3483 pub fn zen(&self) -> bool {
3485 self.workbench_mut().zen
3486 }
3487
3488 pub fn zen_panel(&self) -> Option<PanelId> {
3494 let wb = self.workbench_mut();
3495 wb.zen_panel.clone().filter(|_| wb.zen)
3496 }
3497
3498 pub(crate) fn centre_holds_only(&self, panel: &PanelId) -> bool {
3500 let wb = self.workbench_mut();
3501 let centre = wb.panels_in(Area::Center);
3502 centre.len() == 1 && centre[0] == *panel
3503 }
3504
3505 pub(crate) fn main_zen(&self) -> bool {
3508 self.workbench_mut().main_zen()
3509 }
3510
3511 pub fn zen_target(&self) -> Option<PanelId> {
3519 use egui_pop_model::panels::PanelKind;
3520 let shows = |p: &PanelId| self.workbench_mut().layout.shows(p);
3521 if let Some(p) = self.focused_panel().filter(|p| {
3522 shows(p) && matches!(self.panel_kind(p), PanelKind::View | PanelKind::Mixed)
3523 }) {
3524 return Some(p);
3525 }
3526 if let Some(p) = self
3527 .zen_choice()
3528 .and_then(|p| PanelId::new(&p).ok())
3529 .filter(|p| shows(p))
3530 {
3531 return Some(p);
3532 }
3533 let wb = self.workbench_mut();
3534 wb.layout
3535 .active_in(egui_pop_model::panels::Area::Center)
3536 .first()
3537 .map(|p| (*p).clone())
3538 }
3539
3540 pub(crate) fn follow_zen(&self) {
3542 let on = self.zen();
3543 self.set_context("workbenchZen", if on { "true" } else { "false" });
3544 }
3545
3546 pub fn area_rect(&self, area: Area) -> Option<egui::Rect> {
3549 self.workbench_mut().rects.get(&area).copied()
3550 }
3551
3552 pub fn arrange(&self, panel: &PanelId, how: crate::workbench::Arrangement) -> Option<Outcome> {
3558 self.change_workbench(crate::workbench::Change::Arrange(panel.clone(), how))
3559 }
3560
3561 pub fn fold_area(&self, area: Area, folded: bool) -> Option<Outcome> {
3563 self.change_workbench(crate::workbench::Change::Fold(area, folded))
3564 }
3565
3566 pub fn fold_window_area(&self, window: &str, area: Area, folded: bool) -> Option<Outcome> {
3575 let change = if window == crate::windows::WindowId::MAIN {
3576 crate::workbench::Change::Fold(area, folded)
3577 } else {
3578 crate::workbench::Change::FoldWindow(window.to_string(), area, folded)
3579 };
3580 self.change_workbench(change)
3581 }
3582
3583 pub fn open_flyout(&self, panel: &PanelId, open: bool) -> Option<Outcome> {
3587 self.change_workbench(crate::workbench::Change::Flyout(panel.clone(), open))
3588 }
3589
3590 pub fn flyout(&self) -> Option<(PanelId, Option<egui::Rect>)> {
3593 let wb = self.workbench_mut();
3594 wb.flyout.clone().map(|p| (p, wb.flyout_rect))
3595 }
3596
3597 pub fn place_area(
3600 &self,
3601 area: Area,
3602 placement: egui_pop_model::layout::Placement,
3603 ) -> Option<Outcome> {
3604 self.change_workbench(crate::workbench::Change::Place(area, placement))
3605 }
3606
3607 pub fn area_placement(&self, area: Area) -> egui_pop_model::layout::Placement {
3609 self.workbench_mut().layout.placement(area)
3610 }
3611
3612 pub fn indicators(&self) -> Vec<(crate::strips::Indicator, crate::strips::IndicatorState)> {
3617 let mut v: Vec<_> = self
3618 .0
3619 .indicators
3620 .borrow()
3621 .iter()
3622 .map(|s| s.item.clone())
3623 .collect();
3624 v.sort_by_key(|(i, _)| i.weight);
3625 v
3626 }
3627
3628 pub(crate) fn add_indicator(&self, owner: &OwnerId, ind: crate::strips::Indicator) {
3629 let state = ind.initial.clone();
3630 self.0.indicators.borrow_mut().push(owner, (ind, state));
3631 }
3632
3633 pub(crate) fn feed_indicators(&self) {
3635 let seen = self.0.indicators_seen.get();
3636 let last = self.last_event();
3637 if last <= seen {
3638 return;
3639 }
3640 let events = self.events_since(seen);
3641 let mut list = self.0.indicators.borrow_mut();
3642 let mut items: Vec<_> = list.iter_mut().map(|s| &mut s.item).collect();
3643 for e in &events {
3644 for (ind, state) in items.iter_mut().map(|x| (&x.0, &mut x.1)) {
3645 if e.name.starts_with(&ind.prefix) {
3646 (ind.reduce)(state, e);
3647 state.seq = e.seq;
3648 }
3649 }
3650 }
3651 self.0.indicators_seen.set(last);
3652 }
3653
3654 pub fn move_panel(&self, panel: &PanelId, area: Area) -> Option<Outcome> {
3657 self.change_workbench(crate::workbench::Change::Move(panel.clone(), area))
3658 }
3659
3660 pub fn move_to_window(&self, panel: &PanelId, window: &PanelId) -> Option<Outcome> {
3663 self.change_workbench(crate::workbench::Change::JoinWindow(
3664 panel.clone(),
3665 window.clone(),
3666 ))
3667 }
3668
3669 pub fn detach_panel(&self, panel: &PanelId) -> Option<Outcome> {
3671 self.change_workbench(crate::workbench::Change::Detach(panel.clone()))
3672 }
3673
3674 pub fn attach_panel(&self, panel: &PanelId) -> Option<Outcome> {
3676 self.change_workbench(crate::workbench::Change::Attach(panel.clone()))
3677 }
3678
3679 pub fn focus_panel(&self, panel: &PanelId) -> Option<Outcome> {
3685 self.change_workbench(crate::workbench::Change::Focus(panel.clone()))
3686 }
3687
3688 pub(crate) fn workbench_refused(&self, what: &str, why: &str) {
3691 self.publish(
3692 "egui_pop",
3693 None,
3694 "workbench.refused",
3695 json!({ "change": what, "reason": why }),
3696 );
3697 if let Some(t) = self.service(&crate::toasts::TOASTS) {
3698 t.notify(crate::toasts::Toast::warning(why));
3699 }
3700 }
3701}
3702
3703fn outcome_result(outcome: Outcome) -> Result<Json, String> {
3705 match outcome {
3706 Outcome::Done(r) => r,
3707 Outcome::Vetoed { by, reason } => Err(format!("stopped by `{by}`: {reason}")),
3708 }
3709}
3710
3711fn zen_result(outcome: Option<Outcome>, on: bool) -> Result<Json, String> {
3714 match outcome {
3715 Some(o) => outcome_result(o),
3716 None => Ok(json!({ "zen": on })),
3717 }
3718}
3719
3720fn settle_panel_focus(ui: &mut Ui) {
3725 if let Some(preferred) = focus::preferred(ui.ctx()) {
3726 ui.memory_mut(|m| m.request_focus(preferred));
3727 }
3728}
3729
3730pub(crate) fn names_surface(target: &str, surface: &str) -> bool {
3737 if target == surface {
3738 return true;
3739 }
3740 let own = scope_name(target);
3741 if own == surface {
3742 return true;
3743 }
3744 !target.contains('#')
3745 && surface
3746 .strip_prefix(own.as_str())
3747 .and_then(|rest| rest.strip_prefix('_'))
3748 .is_some_and(|n| !n.is_empty() && n.bytes().all(|b| b.is_ascii_digit()))
3749}
3750
3751pub(crate) fn scope_name(id: &str) -> String {
3753 id.chars()
3754 .map(|c| {
3755 if c.is_ascii_alphanumeric() || c == '.' {
3756 c
3757 } else {
3758 '_'
3759 }
3760 })
3761 .collect()
3762}
3763
3764struct Slot {
3765 plugin: Box<dyn Plugin>,
3766 id: PluginId,
3767 owner: OwnerId,
3768 connected: bool,
3769 reason: Option<String>,
3770}
3771
3772pub struct AppBuilder {
3774 plugins: Vec<Box<dyn Plugin>>,
3775 grouped: Vec<PluginId>,
3778 theme: ThemeSpec,
3779 themes: Themes,
3780 persist: Option<Persist>,
3781 store: Option<SharedStore>,
3782 host: Option<Box<dyn Host>>,
3783 bus: Option<Arc<dyn crate::bus::bus_contract::Bus>>,
3785 system_focus: Option<SystemFocus>,
3786 multi_window: bool,
3788 system_text_scale: crate::text::SystemTextScale,
3789 system_scroll_bars: bool,
3790 system_wheel_lines: u32,
3791 edge_to_edge: bool,
3792 frameless: Vec<Area>,
3793 bare_strips: Vec<Area>,
3794 layout: Option<egui_pop_model::layout::Layout>,
3795 menu_bar: bool,
3796 system_file_chooser: bool,
3797 transparent_panel_windows: bool,
3798 rounded_windows: Option<bool>,
3799 shell_sizes: Vec<(PanelId, f32)>,
3800 shell_bounds: Vec<(PanelId, crate::workbench::ShellBounds)>,
3801 centre_min: Option<crate::workbench::ShellSize>,
3802 folded: Vec<Area>,
3803 over: Vec<Area>,
3804 wrap: Option<WrapUi>,
3805 on_exit: Vec<ExitFn>,
3806 name: Option<String>,
3807 app_id: Option<String>,
3808 panel_alignment: crate::workbench::PanelAlignment,
3809 toast_corner: crate::toasts::Corner,
3810 group_handles: crate::workbench::GroupHandles,
3811 dock_controls: crate::workbench::DockControls,
3812 arrangement_strings: crate::arrangements::ArrangementStrings,
3813 pointer_profile: String,
3814 dock_drag: Option<egui_pop_model::pointer::DockDrag>,
3815 kits: Vec<KitSource>,
3816 user_kits: bool,
3817 cache: Option<egui_pop_core::tokens::cache::Cache>,
3818 writer_check: Option<egui_pop_model::values::WriterCheck>,
3819 offered: Vec<String>,
3820 offered_commands: Vec<CommandId>,
3821 bridge_mode: Option<egui_pop_core::debug::BridgeMode>,
3822}
3823
3824pub type WrapUi = Box<dyn FnMut(&mut Ui, &AppHandle, &mut dyn FnMut(&mut Ui))>;
3828pub type ExitFn = Box<dyn FnMut(&AppHandle)>;
3831
3832pub const STEP_EXIT: StepId = StepId::from_static("app.exit");
3839pub const STEP_DEBUG_CALL: StepId = StepId::from_static("debug.call");
3850
3851pub const BRIDGE: &str = "bridge";
3853pub const STEP_LAYOUT_LOAD: StepId = StepId::from_static("layout.load");
3858pub const STEP_LAYOUT_SAVE: StepId = StepId::from_static("layout.save");
3862
3863impl fmt::Debug for AppBuilder {
3864 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
3865 f.debug_struct("AppBuilder")
3866 .field(
3867 "plugins",
3868 &self.plugins.iter().map(|p| p.id()).collect::<Vec<_>>(),
3869 )
3870 .field("theme", &self.theme)
3871 .finish()
3872 }
3873}
3874
3875impl Default for AppBuilder {
3876 fn default() -> Self {
3877 Self::new()
3878 }
3879}
3880
3881impl AppBuilder {
3882 pub fn new() -> Self {
3883 Self {
3884 plugins: Vec::new(),
3885 grouped: Vec::new(),
3886 theme: ThemeSpec::default(),
3887 themes: Themes::default(),
3888 persist: None,
3889 store: None,
3890 writer_check: None,
3891 offered: Vec::new(),
3892 offered_commands: Vec::new(),
3893 bridge_mode: None,
3894 host: None,
3895 bus: None,
3896 system_focus: None,
3897 multi_window: false,
3898 system_text_scale: crate::text::SystemTextScale::default(),
3899 system_scroll_bars: false,
3900 system_wheel_lines: crate::pointer::SYSTEM_WHEEL_LINES,
3901 edge_to_edge: false,
3902 frameless: Vec::new(),
3903 bare_strips: Vec::new(),
3904 layout: None,
3905 menu_bar: true,
3906 system_file_chooser: false,
3907 transparent_panel_windows: false,
3908 rounded_windows: None,
3909 shell_sizes: Vec::new(),
3910 shell_bounds: Vec::new(),
3911 centre_min: None,
3912 folded: Vec::new(),
3913 over: Vec::new(),
3914 wrap: None,
3915 on_exit: Vec::new(),
3916 name: None,
3917 app_id: None,
3918 panel_alignment: crate::workbench::PanelAlignment::Center,
3919 toast_corner: crate::toasts::Corner::default(),
3920 group_handles: crate::workbench::DEFAULT_GROUP_HANDLES,
3921 dock_controls: crate::workbench::DockControls::default(),
3922 arrangement_strings: crate::arrangements::ArrangementStrings::default(),
3923 pointer_profile: egui_pop_model::pointer::DEFAULT_PROFILE.into(),
3924 dock_drag: None,
3925 kits: Vec::new(),
3926 user_kits: false,
3927 cache: None,
3928 }
3929 }
3930
3931 pub fn panel_alignment(mut self, alignment: crate::workbench::PanelAlignment) -> Self {
3939 self.panel_alignment = alignment;
3940 self
3941 }
3942
3943 pub fn toast_corner(mut self, corner: crate::toasts::Corner) -> Self {
3946 self.toast_corner = corner;
3947 self
3948 }
3949
3950 pub fn group_handles(mut self, allowed: crate::workbench::GroupHandles) -> Self {
3959 self.group_handles = allowed;
3960 self
3961 }
3962
3963 pub fn dock_controls(mut self, controls: crate::workbench::DockControls) -> Self {
3973 self.dock_controls = controls;
3974 self
3975 }
3976
3977 pub fn arrangement_strings(mut self, words: crate::arrangements::ArrangementStrings) -> Self {
3987 self.arrangement_strings = words;
3988 self
3989 }
3990
3991 pub fn pointer_profile(mut self, id: &str) -> Self {
3997 self.pointer_profile = id.into();
3998 self
3999 }
4000
4001 pub fn dock_drag(mut self, mode: egui_pop_model::pointer::DockDrag) -> Self {
4015 self.dock_drag = Some(mode);
4016 self
4017 }
4018
4019 pub fn name(mut self, name: &str) -> Self {
4025 self.name = Some(name.into());
4026 self
4027 }
4028
4029 pub fn app_id(mut self, id: &str) -> Self {
4036 self.app_id = Some(id.into());
4037 self
4038 }
4039
4040 pub fn main_edge_to_edge(mut self, on: bool) -> Self {
4047 self.edge_to_edge = on;
4048 self
4049 }
4050
4051 pub fn frameless(mut self, areas: &[Area]) -> Self {
4074 self.frameless = areas.to_vec();
4075 self
4076 }
4077
4078 pub fn bare_strips(mut self, areas: &[Area]) -> Self {
4097 self.bare_strips = areas
4098 .iter()
4099 .copied()
4100 .filter(|a| matches!(a, Area::StartSide | Area::EndSide))
4101 .collect();
4102 self
4103 }
4104
4105 pub fn layout(mut self, layout: egui_pop_model::layout::Layout) -> Self {
4136 self.layout = Some(layout);
4137 self
4138 }
4139
4140 pub fn menu_bar(mut self, on: bool) -> Self {
4145 self.menu_bar = on;
4146 self
4147 }
4148
4149 pub fn system_file_chooser(mut self, on: bool) -> Self {
4157 self.system_file_chooser = on;
4158 self
4159 }
4160
4161 pub fn transparent_panel_windows(mut self, on: bool) -> Self {
4171 self.transparent_panel_windows = on;
4172 self
4173 }
4174
4175 pub fn rounded_windows(mut self, on: bool) -> Self {
4185 self.rounded_windows = Some(on);
4186 self
4187 }
4188
4189 pub fn shell_panel_size(mut self, panel: PanelId, size: f32) -> Self {
4194 self.shell_sizes.retain(|(p, _)| *p != panel);
4195 self.shell_sizes.push((panel, size));
4196 self
4197 }
4198
4199 pub fn shell_panel_min_size(
4223 mut self,
4224 panel: PanelId,
4225 size: impl Into<crate::workbench::ShellSize>,
4226 ) -> Self {
4227 self.bounds_of(panel).min = Some(size.into());
4228 self
4229 }
4230
4231 pub fn shell_panel_max_size(
4238 mut self,
4239 panel: PanelId,
4240 size: impl Into<crate::workbench::ShellSize>,
4241 ) -> Self {
4242 self.bounds_of(panel).max = Some(size.into());
4243 self
4244 }
4245
4246 pub fn centre_min_size(mut self, size: impl Into<crate::workbench::ShellSize>) -> Self {
4254 self.centre_min = Some(size.into());
4255 self
4256 }
4257
4258 fn bounds_of(&mut self, panel: PanelId) -> &mut crate::workbench::ShellBounds {
4259 let at = match self.shell_bounds.iter().position(|(p, _)| *p == panel) {
4260 Some(at) => at,
4261 None => {
4262 self.shell_bounds.push((panel, Default::default()));
4263 self.shell_bounds.len() - 1
4264 }
4265 };
4266 &mut self.shell_bounds[at].1
4267 }
4268
4269 pub fn folded(mut self, areas: &[Area]) -> Self {
4272 self.folded = areas.to_vec();
4273 self
4274 }
4275
4276 pub fn over(mut self, areas: &[Area]) -> Self {
4281 self.over = areas
4282 .iter()
4283 .copied()
4284 .filter(|a| matches!(a, Area::StartSide | Area::EndSide))
4285 .collect();
4286 self
4287 }
4288
4289 pub fn wrap(
4296 mut self,
4297 f: impl FnMut(&mut Ui, &AppHandle, &mut dyn FnMut(&mut Ui)) + 'static,
4298 ) -> Self {
4299 self.wrap = Some(Box::new(f));
4300 self
4301 }
4302
4303 pub fn on_exit(mut self, f: impl FnMut(&AppHandle) + 'static) -> Self {
4309 self.on_exit.push(Box::new(f));
4310 self
4311 }
4312
4313 pub fn plugin(self, plugin: impl Plugin) -> Self {
4316 self.boxed(Box::new(plugin))
4317 }
4318
4319 pub fn plugins(mut self, group: impl crate::PluginGroup) -> Self {
4322 for p in group.plugins() {
4323 let id = p.id();
4324 if self.plugins.iter().any(|q| q.id() == id) {
4325 continue;
4326 }
4327 self.grouped.push(id);
4328 self.plugins.push(p);
4329 }
4330 self
4331 }
4332
4333 pub fn boxed(mut self, plugin: Box<dyn Plugin>) -> Self {
4336 let id = plugin.id();
4337 if let Some(i) = self.grouped.iter().position(|g| *g == id) {
4338 self.grouped.remove(i);
4339 self.plugins.retain(|p| p.id() != id);
4340 }
4341 self.plugins.push(plugin);
4342 self
4343 }
4344
4345 pub fn theme(mut self, spec: ThemeSpec) -> Self {
4347 self.theme = spec;
4348 self
4349 }
4350
4351 pub fn themes(mut self, themes: Themes) -> Self {
4353 self.themes = themes;
4354 self
4355 }
4356
4357 pub fn kit(mut self, kit: impl Into<KitSource>) -> Self {
4391 self.kits.push(kit.into());
4392 self
4393 }
4394
4395 pub fn user_kits(mut self, on: bool) -> Self {
4402 self.user_kits = on;
4403 self
4404 }
4405
4406 pub fn cache(mut self, cache: egui_pop_core::tokens::cache::Cache) -> Self {
4413 self.cache = Some(cache);
4414 self
4415 }
4416
4417 pub fn persist(mut self, dir: impl Into<std::path::PathBuf>) -> Self {
4419 self.persist = Some(Persist::new(dir));
4420 self
4421 }
4422
4423 pub fn persist_in_config(self, app: &str) -> Self {
4430 let dir = crate::dirs::config_dir(app).unwrap_or_else(|| {
4431 let temp = if cfg!(target_arch = "wasm32") {
4433 std::path::PathBuf::new()
4434 } else {
4435 std::env::temp_dir()
4436 };
4437 temp.join(app)
4438 });
4439 self.persist(dir)
4440 }
4441
4442 pub fn host(mut self, host: impl Host + 'static) -> Self {
4448 self.host = Some(Box::new(host));
4449 self
4450 }
4451
4452 pub fn bus(mut self, bus: Arc<dyn crate::bus::bus_contract::Bus>) -> Self {
4466 self.bus = Some(bus);
4467 self
4468 }
4469
4470 pub fn store(mut self, store: SharedStore) -> Self {
4473 self.store = Some(store);
4474 self
4475 }
4476
4477 pub fn writer_check(mut self, check: egui_pop_model::values::WriterCheck) -> Self {
4483 self.writer_check = Some(check);
4484 self
4485 }
4486
4487 pub fn offer_to_agents(mut self, action: &str) -> Self {
4495 self.offered.push(action.into());
4496 self
4497 }
4498
4499 pub fn debug_bridge(mut self, mode: egui_pop_core::debug::BridgeMode) -> Self {
4507 self.bridge_mode = Some(mode);
4508 self
4509 }
4510
4511 pub fn chosen_debug_bridge(&self) -> Option<egui_pop_core::debug::BridgeMode> {
4516 self.bridge_mode
4517 }
4518
4519 pub fn offer_command_to_agents(mut self, command: CommandId) -> Self {
4528 self.offered_commands.push(command);
4529 self
4530 }
4531
4532 pub fn multi_window(mut self, on: bool) -> Self {
4538 self.multi_window = on;
4539 self
4540 }
4541
4542 pub fn system_focus(mut self, system: SystemFocus) -> Self {
4549 self.system_focus = Some(system);
4550 self
4551 }
4552
4553 pub fn system_text_scale(mut self, system: crate::text::SystemTextScale) -> Self {
4558 self.system_text_scale = system;
4559 self
4560 }
4561
4562 pub fn system_always_shows_scroll_bars(mut self, always: bool) -> Self {
4568 self.system_scroll_bars = always;
4569 self
4570 }
4571
4572 pub fn system_wheel_lines(mut self, lines: u32) -> Self {
4577 self.system_wheel_lines = lines;
4578 self
4579 }
4580
4581 pub fn build(self, ctx: &Context) -> Result<App, BuildError> {
4584 if let Some(bus) = &self.bus {
4585 let declared = bus.points();
4586 if let Some(taken) = crate::bus::CONTRACT
4587 .iter()
4588 .find(|d| declared.iter().any(|p| p.id == d.id && p.declared))
4589 {
4590 return Err(BuildError::Bus(
4591 crate::bus::bus_contract::Refused::AlreadyDeclared {
4592 point: taken.id.as_str(),
4593 },
4594 ));
4595 }
4596 }
4597 let nodes: Vec<Node> = self
4598 .plugins
4599 .iter()
4600 .map(|p| Node {
4601 id: p.id(),
4602 requires: p.requires(),
4603 priority: p.priority(),
4604 })
4605 .collect();
4606 let sorted = order(&nodes)?;
4607 let mut plugins: Vec<Option<Box<dyn Plugin>>> =
4608 self.plugins.into_iter().map(Some).collect();
4609 let slots: Vec<Slot> = sorted
4610 .into_iter()
4611 .map(|i| {
4612 let plugin = plugins[i].take().expect("each plugin once");
4613 let id = plugin.id();
4614 Slot {
4615 owner: OwnerId::from(&id),
4616 id,
4617 plugin,
4618 connected: false,
4619 reason: None,
4620 }
4621 })
4622 .collect();
4623 let default_host = self.host.is_none();
4624 let host = self.host.unwrap_or_else(|| {
4625 Box::new(LocalHost::new(
4626 self.store
4627 .unwrap_or_else(|| Arc::new(Mutex::new(Store::new()))),
4628 ))
4629 });
4630 let handle = AppHandle::new(ctx, host, default_host, self.bus);
4631 if let Some(check) = self.writer_check {
4632 lock(&handle.store()).set_writer_check(check);
4633 }
4634 let modes = FocusModes::new(self.system_focus.unwrap_or_default());
4635 let mut app = App {
4636 handle,
4637 plugins: slots,
4638 reg: Registries::new(),
4639 keys: WindowKeys::default(),
4640 panel_keys: BTreeMap::new(),
4641 dirty: true,
4642 started: false,
4643 theme: Rc::default(),
4644 persist: self.persist,
4645 kits: Vec::new(),
4646 in_flight: Vec::new(),
4647 waking: None,
4648 wrap: self.wrap,
4649 on_exit: self.on_exit,
4650 autosave: AutoSave::default(),
4651 rebuilds: 0,
4652 pointer: Rc::default(),
4653 keymap_changed: Rc::default(),
4654 logic_pass: None,
4655 };
4656 install_pass_marker(ctx);
4657 *app.handle.0.writer.borrow_mut() = app
4658 .persist
4659 .clone()
4660 .map(|p| Writer::new(p, egui_pop_core::persist::DEBOUNCE));
4661 app.handle.0.edge_to_edge.set(self.edge_to_edge);
4662 *app.handle.0.frameless.borrow_mut() = self.frameless;
4663 *app.handle.0.bare_strips.borrow_mut() = self.bare_strips;
4664 app.handle.0.system_text_scale.set(self.system_text_scale);
4665 app.handle.0.system_scroll_bars.set(self.system_scroll_bars);
4666 app.handle.0.system_wheel_lines.set(self.system_wheel_lines);
4667 app.handle.0.toast_corner.set(self.toast_corner);
4668 app.handle.0.group_handles.set(self.group_handles);
4669 app.handle.0.dock_controls.set(self.dock_controls);
4670 app.handle
4671 .0
4672 .arrangement_strings
4673 .set(self.arrangement_strings);
4674 app.handle.0.menu_bar.set(self.menu_bar);
4675 app.handle
4676 .0
4677 .system_file_chooser
4678 .set(self.system_file_chooser);
4679 app.handle
4680 .0
4681 .transparent_panel_windows
4682 .set(self.transparent_panel_windows);
4683 let rounded =
4684 crate::window::rounded_windows(self.rounded_windows, crate::window::windowing());
4685 app.handle.0.rounded_windows.set(rounded);
4686 egui_pop_core::frame::set_rounding(ctx, rounded);
4687 *app.handle.0.shell_sizes.borrow_mut() = self.shell_sizes;
4688 *app.handle.0.shell_bounds.borrow_mut() = self.shell_bounds;
4689 app.handle.0.centre_min.set(self.centre_min);
4690 {
4691 let mut wb = app.handle.workbench_mut();
4692 let given = self.layout.is_some();
4693 let mut start = self.layout.unwrap_or_default();
4694 for a in self.folded {
4695 if !start.folded.contains(&a) {
4696 start.folded.push(a);
4697 }
4698 }
4699 for a in self.over {
4700 if !start.over.contains(&a) {
4701 start.over.push(a);
4702 }
4703 }
4704 if given {
4705 wb.templates.push((
4707 OwnerId::FRAMEWORK,
4708 crate::arrangements::DEFAULT.to_string(),
4709 start.clone(),
4710 ));
4711 }
4712 wb.layout = start;
4713 }
4714 *app.handle.0.name.borrow_mut() = self.name.unwrap_or_default();
4715 *app.handle.0.app_id.borrow_mut() = self.app_id.unwrap_or_default();
4716 strings::set_application(ctx, &app.handle.name());
4717 let mut themes = self.themes;
4718 let mut kits = self.kits;
4719 if self.user_kits
4720 && let Some(p) = &app.persist
4721 {
4722 let dir = p.dir().join(egui_pop_core::tokens::kit::USER_KITS_DIR);
4723 let cache = self
4724 .cache
4725 .unwrap_or_else(egui_pop_core::tokens::cache::default);
4726 kits.extend(
4727 egui_pop_core::tokens::kit::discover_with(&dir, &cache)
4728 .into_iter()
4729 .map(KitSource::new),
4730 );
4731 }
4732 let mut seen = std::collections::BTreeSet::new();
4734 kits.reverse();
4735 kits.retain(|k| seen.insert(k.name().to_string()));
4736 kits.reverse();
4737 {
4738 let mut d = app.handle.0.diagnostics.borrow_mut();
4739 for kit in &kits {
4740 themes.add_kit(&kit.data);
4741 for p in kit.problems() {
4742 d.warn("kit-problem", None, kit.name(), p);
4743 }
4744 }
4745 }
4746 let infos = kits.iter().flat_map(|k| k.data.infos()).collect();
4747 app.kits = kits;
4748 app.reg.offered = self.offered_commands.iter().cloned().collect();
4749 app.framework(
4750 self.theme,
4751 themes,
4752 infos,
4753 modes,
4754 self.panel_alignment,
4755 (&self.pointer_profile, self.dock_drag),
4756 )
4757 .expect("the framework's registrations are valid");
4758 app.install_collectors();
4759 app.handle
4760 .0
4761 .bridge
4762 .borrow_mut()
4763 .set_mode(self.bridge_mode.unwrap_or_default());
4764 for a in &self.offered {
4765 app.handle.0.bridge.borrow_mut().offer_to_agents(a);
4766 }
4767 for i in 0..app.plugins.len() {
4768 if let Err(error) = app.connect_slot(i) {
4769 let plugin = app.plugins[i].id.clone();
4770 return Err(BuildError::Connect { plugin, error });
4771 }
4772 }
4773 for c in &self.offered_commands {
4774 if app.reg.commands.spec(c).is_none() {
4775 app.handle.0.diagnostics.borrow_mut().warn(
4776 "agent-offer-unknown",
4777 None,
4778 c.to_string(),
4779 "`AppBuilder::offer_command_to_agents` names no declared command; nothing is offered",
4780 );
4781 }
4782 }
4783 for a in &self.offered {
4784 let known = a
4785 .split_once('.')
4786 .and_then(|(c, n)| app.handle.0.bridge.borrow().action(c, n))
4787 .is_some();
4788 if !known {
4789 app.handle.0.diagnostics.borrow_mut().warn(
4790 "agent-offer-unknown",
4791 None,
4792 a.clone(),
4793 "`AppBuilder::offer_to_agents` names no debug collector's action (`collector.action`); nothing is offered",
4794 );
4795 }
4796 }
4797 app.load_documents();
4798 app.rebuild();
4799 app.autosave_baseline();
4800 app.listen_settings();
4801 app.listen_layout();
4802 crate::workbench::listen_stack(&app.handle);
4803 app.install_theme();
4804 app.emit(&Lifecycle::Started);
4805 app.started = true;
4806 Ok(app)
4807 }
4808
4809 #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
4814 pub fn run_native(mut self, title: &str, mut options: eframe::NativeOptions) -> eframe::Result {
4815 self.system_focus
4816 .get_or_insert_with(egui_pop_core::focus_mode::read_system);
4817 self.name.get_or_insert_with(|| title.to_string());
4818 if self.app_id.is_none() {
4819 self.app_id.clone_from(&options.viewport.app_id);
4820 }
4821 if let Some(p) = &self.persist {
4825 crate::window::restore(p.dir(), &mut options);
4826 }
4827 if self.multi_window {
4828 crate::windows::present_mode(&mut options);
4829 }
4830 crate::window::transparent_for_corners(&mut options, self.rounded_windows);
4831 let keymap_shortcuts = self.clipboard_shortcuts(&mut options);
4832 crate::runner::run(
4833 title,
4834 options,
4835 Box::new(move |cc| {
4836 crate::frame::record_native_window(cc);
4837 let app = self
4838 .build(&cc.egui_ctx)
4839 .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
4840 crate::clipboard::set_keymap_shortcuts(app.handle(), keymap_shortcuts);
4841 Ok(Box::new(app))
4842 }),
4843 )
4844 }
4845
4846 #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
4857 pub fn run_native_with(
4858 mut self,
4859 title: &str,
4860 mut options: eframe::NativeOptions,
4861 make: impl FnOnce(App, &eframe::CreationContext<'_>) -> Result<Box<dyn eframe::App>, MakeError>
4862 + 'static,
4863 ) -> eframe::Result {
4864 self.system_focus
4865 .get_or_insert_with(egui_pop_core::focus_mode::read_system);
4866 self.name.get_or_insert_with(|| title.to_string());
4867 if self.app_id.is_none() {
4868 self.app_id.clone_from(&options.viewport.app_id);
4869 }
4870 if let Some(p) = &self.persist {
4871 crate::window::restore(p.dir(), &mut options);
4872 }
4873 if self.multi_window {
4874 crate::windows::present_mode(&mut options);
4875 }
4876 crate::window::transparent_for_corners(&mut options, self.rounded_windows);
4877 let keymap_shortcuts = self.clipboard_shortcuts(&mut options);
4878 crate::runner::run(
4879 title,
4880 options,
4881 Box::new(move |cc| {
4882 crate::frame::record_native_window(cc);
4883 let app = self
4884 .build(&cc.egui_ctx)
4885 .map_err(|e| Box::new(e) as Box<dyn std::error::Error + Send + Sync>)?;
4886 crate::clipboard::set_keymap_shortcuts(app.handle(), keymap_shortcuts);
4887 let handle = app.handle().clone();
4888 make(app, cc).inspect_err(|e| report_make_error(&handle, e.as_ref()))
4889 }),
4890 )
4891 }
4892}
4893
4894impl AppBuilder {
4895 #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
4902 fn clipboard_shortcuts(&self, options: &mut eframe::NativeOptions) -> bool {
4903 if self
4904 .plugins
4905 .iter()
4906 .any(|p| p.id() == crate::clipboard::SYSTEM_PLUGIN)
4907 {
4908 options.clipboard_shortcuts = false;
4909 }
4910 !options.clipboard_shortcuts
4911 }
4912}
4913
4914pub type MakeError = Box<dyn std::error::Error + Send + Sync>;
4916
4917#[cfg(any(test, all(feature = "eframe", not(target_arch = "wasm32"))))]
4920pub(crate) fn report_make_error(app: &AppHandle, e: &(dyn std::error::Error + Send + Sync)) {
4921 log::error!(target: "egui_pop", "the application could not be made: {e}");
4922 app.publish(
4923 "egui_pop",
4924 None,
4925 "app.make_failed",
4926 json!({ "error": e.to_string() }),
4927 );
4928}
4929
4930fn load_pointer_profile(
4934 app: &AppHandle,
4935 keymap: &RefCell<Keymap>,
4936 sync: &RefCell<crate::pointer::Sync>,
4937 changed: &std::cell::Cell<bool>,
4938) {
4939 let id = crate::pointer::profile_id(app);
4940 let first = {
4941 let mut sync = sync.borrow_mut();
4942 if sync.loaded.as_deref() == Some(id.as_str()) {
4943 return;
4944 }
4945 let first = sync.loaded.is_none();
4946 sync.loaded = Some(id.clone());
4947 first
4948 };
4949 let loaded = crate::pointer::load_profile(&mut keymap.borrow_mut(), &id);
4950 match loaded {
4951 Some(profile) => {
4952 changed.set(true);
4953 if !first {
4954 crate::pointer::ask_about_overrides(app, profile);
4955 }
4956 }
4957 None => app.0.diagnostics.borrow_mut().warn(
4958 "unknown-pointer-profile",
4959 None,
4960 &id,
4961 format!(
4962 "`{id}` is not a pointer profile: `{}` stays in force",
4963 egui_pop_model::pointer::DEFAULT_PROFILE
4964 ),
4965 ),
4966 }
4967}
4968
4969const THEME_SETTINGS: [SettingId; 6] = [
4971 SETTING_ACCENT_COLOR,
4972 SETTING_THEME_PREFERENCE,
4973 crate::text::SETTING_TEXT_SIZE,
4974 crate::text::SETTING_FONT_UI,
4975 crate::text::SETTING_FONT_MONO,
4976 crate::scroll_bars::SETTING_SCROLL_BARS,
4977];
4978
4979#[derive(Default)]
4982struct ThemeFollow {
4983 read: bool,
4985 installed: Option<ThemeSpec>,
4987 accent_setting: Option<String>,
4990 text_seen: crate::text::Seen,
4992 scroll_bars_seen: Option<theme::ScrollBars>,
4994 preference: Option<egui::ThemePreference>,
4996}
4997
4998impl ThemeFollow {
4999 fn read_settings(&mut self, app: &AppHandle) {
5003 self.read = true;
5004 let service = app.theme();
5005 let accent = service.accent_setting();
5006 if self.accent_setting.as_ref() != Some(&accent) {
5007 if self.accent_setting.is_some() || !accent.trim().is_empty() {
5008 service.apply_accent_setting(&accent);
5009 }
5010 self.accent_setting = Some(accent);
5011 }
5012 let mut wanted = service.spec();
5013 let text = crate::text::apply(app, &mut self.text_seen, &mut wanted);
5014 let bars = crate::scroll_bars::apply(app, &mut self.scroll_bars_seen, &mut wanted);
5015 if text || bars {
5016 service.set(wanted);
5017 }
5018 }
5019
5020 fn install(&mut self, app: &AppHandle, force: bool) {
5023 let service = app.theme();
5024 let mut spec = service.spec();
5025 if !force && self.installed.as_ref() == Some(&spec) {
5026 return;
5027 }
5028 if self.installed.is_some() {
5029 self.accent_setting = None;
5033 self.text_seen = crate::text::Seen::default();
5034 self.scroll_bars_seen = None;
5035 self.read_settings(app);
5036 spec = service.spec();
5037 }
5038 let ctx = app.egui();
5039 theme::install_with(&ctx, service.themes(), &spec);
5040 THEME_INSTALLED.set(&ctx, true);
5041 self.installed = Some(spec);
5042 self.preference = None;
5044 let paired = theme::is_paired(&ctx);
5045 app.set_context("themePaired", if paired { "true" } else { "false" });
5046 self.follow_preference(app);
5047 }
5048
5049 fn follow_preference(&mut self, app: &AppHandle) {
5051 let preference = app.theme().preference();
5052 if self.preference != Some(preference) {
5053 theme::set_preference(&app.egui(), preference);
5054 self.preference = Some(preference);
5055 }
5056 }
5057}
5058
5059#[derive(Debug, Default)]
5062pub(crate) struct WindowKeys {
5063 dispatcher: KeyDispatcher,
5064 seen: u64,
5065}
5066
5067impl WindowKeys {
5068 pub(crate) fn dispatcher(&mut self, app: &AppHandle) -> &mut KeyDispatcher {
5071 let epoch = app.0.bus.keys_epoch.get();
5072 if epoch != self.seen {
5073 self.seen = epoch;
5074 self.dispatcher.cancel_pending();
5075 }
5076 &mut self.dispatcher
5077 }
5078}
5079
5080pub struct App {
5082 handle: AppHandle,
5083 plugins: Vec<Slot>,
5084 reg: Registries,
5085 keys: WindowKeys,
5087 panel_keys: BTreeMap<egui::ViewportId, WindowKeys>,
5090 dirty: bool,
5091 started: bool,
5092 theme: Rc<RefCell<ThemeFollow>>,
5095 persist: Option<Persist>,
5096 kits: Vec<KitSource>,
5099 in_flight: Vec<InFlight>,
5101 waking: Option<Context>,
5103 wrap: Option<WrapUi>,
5104 on_exit: Vec<ExitFn>,
5105 autosave: AutoSave,
5107 rebuilds: u64,
5109 pointer: Rc<RefCell<crate::pointer::Sync>>,
5112 keymap_changed: Rc<std::cell::Cell<bool>>,
5115 logic_pass: Option<(egui::ViewportId, u64)>,
5117}
5118
5119struct Removed {
5121 commands: Vec<CommandId>,
5122 panels: usize,
5123 mounts: crate::mounts::RemovedMounts,
5126 undo: Vec<egui_pop_model::values::DroppedSteps>,
5127}
5128
5129pub(crate) const NOTICES_DOC: &str = "notices";
5132
5133#[derive(Debug, Default)]
5136struct AutoSave {
5137 store_seq: std::cell::Cell<Option<u64>>,
5139 rebuilds: std::cell::Cell<Option<u64>>,
5141 notices_rev: std::cell::Cell<Option<u64>>,
5143}
5144
5145fn save_layout(handle: &AppHandle, persist: Option<Persist>) -> Option<Outcome> {
5149 let document = handle.with_host(|h| h.layout_document()).flatten()?;
5150 let out = handle.step(
5151 &STEP_LAYOUT_SAVE,
5152 json!({ "document": document }),
5153 move |app, args| {
5154 let document = args["document"].as_str().ok_or("`document` is missing")?;
5155 let Some(p) = persist else {
5156 return Ok(json!({ "document": document, "saved": false }));
5157 };
5158 p.save(
5159 document,
5160 &egui_pop_model::layout::schema(),
5161 &app.saved_layout(),
5162 )
5163 .map_err(|e| e.to_string())?;
5164 Ok(json!({ "document": document, "saved": true }))
5165 },
5166 );
5167 if out.ok() {
5168 handle.layout_said_now();
5169 }
5170 Some(out)
5171}
5172
5173struct InFlight {
5175 command: CommandId,
5176 args: Json,
5177 origin: Origin,
5178 seq: Seq,
5179 pending: Pending,
5180}
5181
5182impl fmt::Debug for App {
5183 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
5184 f.debug_struct("App")
5185 .field(
5186 "plugins",
5187 &self
5188 .plugins
5189 .iter()
5190 .map(|p| (&p.id, p.connected))
5191 .collect::<Vec<_>>(),
5192 )
5193 .finish_non_exhaustive()
5194 }
5195}
5196
5197impl App {
5198 pub fn builder() -> AppBuilder {
5200 AppBuilder::new()
5201 }
5202
5203 pub fn handle(&self) -> &AppHandle {
5205 &self.handle
5206 }
5207
5208 pub fn census(&self) -> BTreeMap<&'static str, usize> {
5210 let h = &self.handle.0;
5211 let store = lock(&h.store);
5212 BTreeMap::from([
5213 ("commands", self.reg.commands.len()),
5214 ("bindings", self.reg.keymap.borrow().all().count()),
5215 ("menu items", self.reg.menus.len()),
5216 ("panels", self.reg.panels.all().len()),
5217 ("panel views", h.panels.borrow().len()),
5218 ("hooks", self.reg.hooks.len()),
5219 ("lifecycle handlers", self.reg.lifecycle.len()),
5220 ("settings", self.reg.settings.len()),
5221 ("zones", h.zones.borrow().zones.len()),
5222 ("blocks", h.zones.borrow().contributions.len()),
5223 ("services", h.services.borrow().list().len()),
5224 ("stories", h.stories.borrow().len()),
5225 ("steps", h.steps.borrow().len()),
5226 ("step hooks", h.step_hooks.borrow().len()),
5227 ("list providers", h.lists.borrow().len()),
5228 ("indicators", h.indicators.borrow().len()),
5229 ("store paths", store.list("").len()),
5230 ("store listeners", store.listeners().len()),
5231 ])
5232 }
5233
5234 pub fn dispatcher(&self) -> &KeyDispatcher {
5236 &self.keys.dispatcher
5237 }
5238
5239 pub fn keymap(&self) -> std::cell::Ref<'_, Keymap> {
5241 self.reg.keymap.borrow()
5242 }
5243
5244 fn framework(
5247 &mut self,
5248 theme: ThemeSpec,
5249 themes: Themes,
5250 kits: Vec<egui_pop_core::tokens::kit::KitInfo>,
5251 modes: FocusModes,
5252 panel_alignment: crate::workbench::PanelAlignment,
5253 (pointer_profile, dock_drag): (&str, Option<egui_pop_model::pointer::DockDrag>),
5254 ) -> Result<(), CtxError> {
5255 let owner = OwnerId::FRAMEWORK;
5256 let handle = self.handle.clone();
5257 let connected: Vec<PluginId> = Vec::new();
5258 let mut ctx = Ctx {
5259 owner: owner.clone(),
5260 plugin: PluginId::from_static("framework"),
5261 rank: 0,
5262 reg: &mut self.reg,
5263 app: &handle,
5264 connected: &connected,
5265 };
5266 ctx.step(
5267 StepSpec::new(
5268 crate::menus::STEP_OPEN,
5269 "A menu opens as a popup or a context menu; a veto keeps it closed, a redirect changes its arguments.",
5270 )
5271 .args(json!({ "menu": "app.menu.edit", "args": { "path": "node/exposure" }, "how": "context" })),
5272 )?;
5273 for (zone, title) in zones::SHELL.iter().zip([
5274 "Title",
5275 "Top bar",
5276 "Activity bar",
5277 "Side bar",
5278 "Main",
5279 "Inspector",
5280 "Status bar",
5281 "Overlays",
5282 ]) {
5283 ctx.zone(zone.clone(), title)?;
5284 }
5285 ctx.zone(zones::TOP_BAR_END, "Top bar end")?;
5286 ctx.zone(zones::WINDOW_OVERLAYS, "Window overlays")?;
5287 for (spec, zone, scope) in [
5288 (
5289 PanelSpec::new(
5290 crate::workbench::PANEL_SIDE_BAR,
5291 "Side bar",
5292 Area::StartSide,
5293 )
5294 .min_size(120.0)
5295 .default_size(170.0),
5296 zones::SIDE_BAR,
5297 "sideBar",
5298 ),
5299 (
5300 PanelSpec::new(crate::workbench::PANEL_MAIN, "Main", Area::Center),
5301 zones::MAIN,
5302 "main",
5303 ),
5304 (
5305 PanelSpec::new(
5306 crate::workbench::PANEL_INSPECTOR,
5307 "Inspector",
5308 Area::EndSide,
5309 )
5310 .min_size(160.0)
5311 .default_size(240.0),
5312 zones::INSPECTOR,
5313 "inspector",
5314 ),
5315 ] {
5316 let size = handle
5317 .0
5318 .shell_sizes
5319 .borrow()
5320 .iter()
5321 .find(|(p, _)| *p == spec.id)
5322 .map(|(_, s)| *s);
5323 let spec = match size {
5324 Some(s) => {
5325 let min = spec.min_size.min(s);
5326 spec.min_size(min).default_size(s)
5327 }
5328 None => spec,
5329 };
5330 ctx.zone_panel(spec, zone, scope)?;
5331 }
5332 for spec in crate::workbench::steps() {
5333 ctx.step(spec)?;
5334 }
5335 ctx.command(
5340 CommandSpec::new(crate::workbench::CMD_ZEN, "Zen mode", "View")
5341 .description("Shows one panel alone, full size, in its window: `panel`, else the focused panel when it is a view, else the application's choice, else the centre's active tab. No title, menu or status bar, no other panel. Escape leaves it, and the layout is as it was.")
5342 .key("Shift+F11")
5343 .checked("workbenchZen")
5344 .menu(MENU_VIEW, "9_window", 2)
5345 .args(json!({ "panel": "app.viewer" })),
5346 |call| {
5347 let named = match call.args.get("panel").and_then(Json::as_str) {
5348 Some(p) => Some(PanelId::new(p).map_err(|e| e.to_string())?),
5349 None => None,
5350 };
5351 let current = call.app.zen_panel();
5354 if call.app.zen() && (named.is_none() || named == current) {
5355 return zen_result(call.app.set_zen(false), false);
5356 }
5357 match named.or_else(|| call.app.zen_target()) {
5358 Some(p) if call.app.centre_holds_only(&p) => {
5362 zen_result(call.app.set_zen(true), true)
5363 }
5364 Some(p) => zen_result(call.app.set_zen_panel(&p), true),
5365 None => zen_result(call.app.set_zen(true), true),
5366 }
5367 },
5368 )?
5369 .command(
5370 CommandSpec::new(crate::workbench::CMD_LEAVE_ZEN, "Leave zen mode", "View")
5371 .description("Shows the whole workbench again.")
5372 .when("workbenchZen"),
5373 |call| zen_result(call.app.set_zen(false), false),
5374 )?;
5375 ctx.keybinding(
5376 "Escape",
5377 crate::workbench::CMD_LEAVE_ZEN,
5378 "workbenchZen && !modePushed && !overlayOpen && !textInputFocus",
5379 Layer::Default,
5380 )?;
5381 let views: [(&str, &str, &str); 10] = [
5387 (
5388 "view.fit",
5389 "Fit the view",
5390 "Frames all the content of the canvas in use.",
5391 ),
5392 (
5393 "view.frame_selection",
5394 "Frame the selection",
5395 "Frames the selection of the canvas in use (all its content when nothing is selected).",
5396 ),
5397 (
5398 "view.zoom_in",
5399 "Zoom in",
5400 "Zooms the canvas in use in, around its centre.",
5401 ),
5402 (
5403 "view.zoom_out",
5404 "Zoom out",
5405 "Zooms the canvas in use out, around its centre.",
5406 ),
5407 (
5408 "view.zoom_100",
5409 "Zoom to 100 %",
5410 "Shows the canvas in use at 100 % (one unit, or one pixel, to a point).",
5411 ),
5412 (
5413 "view.pan_left",
5414 "Pan left",
5415 "Moves the view of the canvas in use left.",
5416 ),
5417 (
5418 "view.pan_right",
5419 "Pan right",
5420 "Moves the view of the canvas in use right.",
5421 ),
5422 (
5423 "view.pan_up",
5424 "Pan up",
5425 "Moves the view of the canvas in use up.",
5426 ),
5427 (
5428 "view.pan_down",
5429 "Pan down",
5430 "Moves the view of the canvas in use down.",
5431 ),
5432 (
5433 "view.hand",
5434 "Hand mode",
5435 "Toggles hand mode: a primary drag pans the canvases (for a pen, a touch screen or a mouse without a middle button). Space held does the same for a moment.",
5436 ),
5437 ];
5438 for (id, title, description) in views {
5439 let spec = CommandSpec::new(CommandId::from_static(id), title, "View")
5440 .description(description)
5441 .when(egui_pop_model::pointer::VIEW_KEYS_WHEN);
5442 ctx.command(spec, move |call| {
5443 if egui_pop_core::canvas::request(&call.app.egui(), id) {
5444 Ok(json!({ "queued": id }))
5445 } else {
5446 Err("no canvas has been shown".into())
5447 }
5448 })?;
5449 }
5450 ctx.command(
5452 CommandSpec::new(crate::workbench::CMD_NEXT_REGION, "Go to the next region", "View")
5453 .description("Moves the keyboard to the next part of the window: the activity bar, a side or bottom area, the centre, a palette, the flyout, the status bar.")
5454 .when("!modalOpen")
5455 .key("F6"),
5456 |call| crate::workbench::go_to_region(call.app, call.origin, false),
5457 )?
5458 .command(
5459 CommandSpec::new(crate::workbench::CMD_PREVIOUS_REGION, "Go to the previous region", "View")
5460 .description("Moves the keyboard to the previous part of the window.")
5461 .when("!modalOpen")
5462 .key("Shift+F6"),
5463 |call| crate::workbench::go_to_region(call.app, call.origin, true),
5464 )?
5465 .command(
5467 CommandSpec::new(crate::workbench::CMD_NEXT_TAB, "Go to the next tab", "View")
5468 .description("Shows and focuses the next tab of the focused panel's group.")
5469 .when("!modalOpen")
5470 .key("Ctrl+PageDown"),
5471 |call| crate::workbench::go_to_tab(call.app, false),
5472 )?
5473 .command(
5474 CommandSpec::new(crate::workbench::CMD_PREVIOUS_TAB, "Go to the previous tab", "View")
5475 .description("Shows and focuses the previous tab of the focused panel's group.")
5476 .when("!modalOpen")
5477 .key("Ctrl+PageUp"),
5478 |call| crate::workbench::go_to_tab(call.app, true),
5479 )?
5480 .command(
5483 CommandSpec::new(crate::workbench::CMD_ARRANGE_GRID, "Arrange as grid", "View")
5484 .description("Lays out the focused panel's group and the groups beside it in rows and columns.")
5485 .when("!modalOpen")
5486 .args(json!({ "panel": "app.inspector", "columns": 2 })),
5487 |call| crate::workbench::arrange_command(call.app, call.args, "grid"),
5488 )?
5489 .command(
5490 CommandSpec::new(crate::workbench::CMD_ARRANGE_ROW, "Arrange as row", "View")
5491 .description("Lays out the focused panel's group and the groups beside it side by side.")
5492 .when("!modalOpen")
5493 .args(json!({ "panel": "app.inspector" })),
5494 |call| crate::workbench::arrange_command(call.app, call.args, "row"),
5495 )?
5496 .command(
5497 CommandSpec::new(crate::workbench::CMD_ARRANGE_COLUMN, "Arrange as column", "View")
5498 .description("Lays out the focused panel's group and the groups beside it one above the other.")
5499 .when("!modalOpen")
5500 .args(json!({ "panel": "app.inspector" })),
5501 |call| crate::workbench::arrange_command(call.app, call.args, "column"),
5502 )?
5503 .command(
5504 CommandSpec::new(crate::workbench::CMD_MOVE_TO_WINDOW, "Move to window", "View")
5505 .description("Moves the focused panel, or `panel`, into the detached window holding `window`, as a tab.")
5506 .when("!modalOpen")
5507 .args(json!({ "panel": "app.outline", "window": "app.inspector" })),
5508 |call| crate::workbench::move_to_window_command(call.app, call.args),
5509 )?;
5510 crate::palettes::declare(&mut ctx)?;
5511 crate::workbench::panel_menu::declare(&mut ctx)?;
5512 for (i, (menu, label)) in [
5513 (MENU_FILE, "File"),
5514 (MENU_EDIT, "Edit"),
5515 (MENU_VIEW, "View"),
5516 (MENU_HELP, "Help"),
5517 ]
5518 .into_iter()
5519 .enumerate()
5520 {
5521 ctx.submenu(MENU_MAIN, &format!("{i}"), 0, menu, label)?;
5522 }
5523 ctx.service(
5524 &THEME,
5525 ThemeService {
5526 spec: Mutex::new(theme),
5527 themes,
5528 kits,
5529 store: handle.store(),
5530 dark: Mutex::new(BTreeMap::new()),
5531 ctx: Mutex::new(handle.egui()),
5532 },
5533 )?;
5534 ctx.setting(
5535 SETTING_THEME_PREFERENCE,
5536 egui_pop_model::values::Descriptor::choice(
5537 "Light or dark",
5538 &["system", "light", "dark"],
5539 "system",
5540 )
5541 .description(
5542 "Which variant of a theme with a light and a dark one is shown: the system's, or always the light or the dark one. A theme without a counterpart keeps its own.",
5543 ),
5544 )?;
5545 ctx.setting(
5546 SETTING_ACCENT_COLOR,
5547 egui_pop_model::values::Descriptor::text("Accent colour", "").description(
5548 "A colour (#rrggbb) the accent is generated from, light and dark: twelve steps whose text and contrast read in the theme. Empty keeps the theme's own accent.",
5549 ),
5550 )?;
5551 ctx.command(
5552 CommandSpec::new(CMD_THEME_TOGGLE, "Toggle light and dark theme", "View")
5553 .icon("theme")
5554 .description("Shows the other variant of the theme, light or dark, when it has one.")
5555 .when("themePaired")
5556 .menu(MENU_VIEW, "6_theme", 9),
5557 |call| {
5558 let mode = call.app.theme().toggle(&call.app.egui())?;
5559 Ok(json!({ "theme": call.app.theme().shown(&call.app.egui()), "dark": mode == egui::Theme::Dark }))
5560 },
5561 )?;
5562 let mut focus = egui_pop_model::values::Descriptor::choice(
5563 "Keyboard focus",
5564 &Preference::CHOICES,
5565 Preference::System.as_str(),
5566 );
5567 focus.description = format!(
5568 "Whether moving the mouse over a panel or a field gives it the keyboard \
5569 (hover), or only a click does (click). {}.",
5570 modes.system_said()
5571 );
5572 ctx.setting(SETTING_FOCUS, focus)?;
5573 crate::zoom::register(&mut ctx)?;
5574 crate::text::register(&mut ctx, handle.system_text_scale())?;
5575 crate::scroll_bars::register(&mut ctx)?;
5576 crate::toasts::register(&mut ctx, handle.0.toast_corner.get())?;
5577 crate::sliders::register(&mut ctx)?;
5578 crate::pointer::register(
5579 &mut ctx,
5580 pointer_profile,
5581 handle.system_wheel_lines(),
5582 dock_drag,
5583 )?;
5584 ctx.setting(
5585 crate::workbench::SETTING_PANEL_ALIGNMENT,
5586 egui_pop_model::values::Descriptor::choice(
5587 "Panel alignment",
5588 &crate::workbench::PanelAlignment::CHOICES,
5589 panel_alignment.as_str(),
5590 )
5591 .description(
5592 "How the bottom panel lines up with the side bars: the whole width (justify), between them (center), under the start one (start) or under the end one (end).",
5593 ),
5594 )?;
5595 crate::workbench::register_group_settings(&mut ctx, handle.0.group_handles.get())?;
5596 ctx.setting(
5597 crate::menus::SETTING_ICONS,
5598 egui_pop_model::values::Descriptor::choice(
5599 "Menu icons",
5600 &crate::menus::MenuIcons::CHOICES,
5601 crate::menus::MenuIcons::default().as_str(),
5602 )
5603 .description(
5604 "Whether menus show the commands' icons in a column on their left (on), none (off), or follow the desktop (platform: off on GNOME, as KDE Plasma says, on elsewhere).",
5605 ),
5606 )?;
5607 crate::layout_controls::declare(&mut ctx)?;
5608 crate::bus::declare(&mut ctx)?;
5609 ctx.service(&FOCUS_MODE, modes)?;
5610 ctx.step(
5611 crate::steps::StepSpec::new(
5612 STEP_DEBUG_CALL,
5613 "A debug collector's action is called (`collector`, `action`, `args`), by an agent or the user (`origin`).",
5614 )
5615 .args(json!({ "collector": "store", "action": "get", "args": { "path": "settings/x" }, "origin": "agent:debug-bridge" })),
5616 )?;
5617 ctx.step(
5618 crate::steps::StepSpec::new(
5619 STEP_EXIT,
5620 "The application closes; the default saves the settings, keymap and layout.",
5621 )
5622 .args(json!({})),
5623 )?;
5624 ctx.step(
5625 crate::steps::StepSpec::new(
5626 STEP_LAYOUT_LOAD,
5627 "The workbench's layout is loaded from a document (`document`, as the host names it).",
5628 )
5629 .args(json!({ "document": crate::host::LAYOUT_DOCUMENT })),
5630 )?
5631 .step(
5632 crate::steps::StepSpec::new(
5633 STEP_LAYOUT_SAVE,
5634 "The workbench's layout is saved to a document (`document`, as the host names it).",
5635 )
5636 .args(json!({ "document": crate::host::LAYOUT_DOCUMENT })),
5637 )?;
5638 ctx.step(
5639 crate::steps::StepSpec::new(
5640 STEP_REBIND,
5641 "The user gives a command new keys (`command`, `keys`; null: no key).",
5642 )
5643 .args(json!({ "command": "app.quit", "keys": "Ctrl+Q" })),
5644 )?
5645 .step(
5646 crate::steps::StepSpec::new(
5647 STEP_LOAD_KEYMAP,
5648 "A keymap document is loaded into the user's or the workspace's layer.",
5649 )
5650 .args(json!({ "layer": "user", "bindings": 3 })),
5651 )?;
5652 ctx.step(
5653 StepSpec::new(
5654 STEP_UNDO,
5655 "Undoes the last change in the history focus picks: the history owner's undo by default.",
5656 )
5657 .args(json!({ "label": "exposure change", "origin": "user", "scope": "app" })),
5658 )?;
5659 ctx.step(
5660 StepSpec::new(
5661 STEP_REDO,
5662 "Redoes the last undone change: the history owner's redo by default.",
5663 )
5664 .args(json!({ "label": "exposure change", "origin": "user", "scope": "app" })),
5665 )?;
5666 ctx.step(
5667 StepSpec::new(
5668 crate::history::STEP_TARGET,
5669 "Picks the history Ctrl+Z and Ctrl+Shift+Z go to (`scope`, `redo`, `rule`: focus, last_focused, none (focus routing, no view focused yet: `scope` null) or newest); a before-hook names another scope, or null for none. Run quietly whenever the target is read.",
5670 )
5671 .args(json!({ "scope": "app", "redo": false, "rule": "newest" })),
5672 )?;
5673 ctx.step(
5674 StepSpec::new(
5675 crate::history::STEP_JUMP,
5676 "Brings a history to one of its steps (`to`, 0: the start) by undos or redos, all or nothing.",
5677 )
5678 .args(json!({ "scope": "app", "to": 3, "origin": "user" })),
5679 )?;
5680 ctx.step(
5681 StepSpec::new(
5682 crate::history::STEP_RESTORE,
5683 "Brings a history back to one of its snapshots (`snapshot`), as a new step.",
5684 )
5685 .args(json!({ "scope": "app", "snapshot": 1, "origin": "user" })),
5686 )?;
5687 ctx.step(
5688 StepSpec::new(
5689 crate::history::STEP_UNDO_STEP,
5690 "Undoes one step of a history (`step`) out of order, when its owner allows it.",
5691 )
5692 .args(json!({ "scope": "app", "step": 3, "origin": "user" })),
5693 )?;
5694 ctx.on(crate::hooks::On::Pass, |app, _| crate::history::pass(app));
5695 ctx.command(
5696 CommandSpec::new(CMD_UNDO, "Undo", "Edit")
5697 .icon("undo")
5698 .description("Undo the last change.")
5699 .key_with("Ctrl+Z", BindOptions::global().through_modal())
5700 .when("!textInputFocus && (canUndo || undoNeedsView)")
5701 .menu(MENU_EDIT, "0_undo", 0),
5702 |call| outcome_result(call.app.undo(call.origin)),
5703 )?;
5704 ctx.command(
5705 CommandSpec::new(CMD_REDO, "Redo", "Edit")
5706 .icon("redo")
5707 .description("Redo the last undone change.")
5708 .key_with("Ctrl+Shift+Z", BindOptions::global().through_modal())
5709 .key_with("Ctrl+Y", BindOptions::global().through_modal())
5710 .when("!textInputFocus && (canRedo || redoNeedsView)")
5711 .menu(MENU_EDIT, "0_undo", 1),
5712 |call| outcome_result(call.app.redo(call.origin)),
5713 )?;
5714 ctx.command(
5715 CommandSpec::new(CMD_QUIT, "Quit", "File")
5716 .description("Close the application.")
5717 .key("Ctrl+Q")
5718 .menu(MENU_FILE, "9_quit", 0)
5719 .no_agent(),
5720 |call| {
5721 call.app.quit();
5722 Ok(Json::Null)
5723 },
5724 )?;
5725 let store = self.handle.store();
5726 egui_pop_model::values::register_with(&mut self.reg.commands, &owner, store, |h| {
5727 let f: CommandFn = Rc::new(move |call: &Call<'_>| h(call.args, call.origin));
5728 Some(f)
5729 })
5730 .ok();
5731 Ok(())
5732 }
5733
5734 fn install_collectors(&mut self) {
5737 let h = &self.handle;
5738 let up = |w: &Weak<Shared>| {
5739 w.upgrade()
5740 .map(AppHandle)
5741 .ok_or_else(|| "the application is gone".to_string())
5742 };
5743 let mut b = h.0.bridge.borrow_mut();
5744 let (w1, w2, w3, w4) = (h.weak(), h.weak(), h.weak(), h.weak());
5745 b.register(
5746 FnCollector::new("commands", "Every command: id, title, keys, where it applies, its icon and \"on\" icon by name (with the names that do not resolve), owner; the last runs.")
5747 .snapshot(move |_| {
5748 let Ok(app) = up(&w1) else { return Json::Null };
5749 let cx = app.when_context();
5750 let palette = app.palette();
5751 json!({
5752 "commands": app.commands().iter().map(|(s, owner)| json!({
5753 "id": s.id,
5754 "title": s.title,
5755 "category": s.category,
5756 "description": s.description,
5757 "when": s.when,
5758 "keys": palette.iter().find(|e| e.command == s.id).map(|e| e.keys.clone()).unwrap_or_default(),
5759 "agent": s.agent,
5760 "read_only": s.read_only,
5761 "destructive": s.destructive,
5762 "destructive_if": s.destructive_if,
5763 "private": s.private,
5764 "args": s.args,
5765 "running": app.running(&s.id),
5766 "owner": owner,
5767 "icon": s.icon,
5768 "icon_on": s.icon_on,
5769 "unknown_icons": unknown_icons(s),
5770 "icon_set_by": app.icon_set_by(&s.id),
5771 })).collect::<Vec<_>>(),
5772 "context": cx.iter().map(|(k, v, d)| json!({"key": k, "value": v, "depth": d})).collect::<Vec<_>>(),
5773 "history": app.history().iter().map(|r| {
5778 let mut run = json!(r);
5779 if app.command(&r.id).is_none_or(|s| s.private) {
5780 run["private"] = Json::Bool(true);
5781 }
5782 run
5783 }).collect::<Vec<_>>(),
5784 })
5785 })
5786 .action_as("run", "Runs a command (`id`, `args`) as its caller: anyone but the user only a command offered to agents.", true, move |_, args, origin| {
5787 let app = up(&w2)?;
5788 let id = args.get("id").and_then(Json::as_str).ok_or("`id` is missing")?;
5789 let id = CommandId::new(id).map_err(|e| e.to_string())?;
5790 let known = app.commands().iter().find(|(s, _)| s.id == id).map(|(s, _)| s.agent);
5791 match known {
5792 None => return Err(format!("`{id}` is not offered to agents")),
5793 Some(false) if *origin != Origin::User => {
5794 return Err(format!("`{id}` is not offered to agents"));
5795 }
5796 Some(_) => {}
5797 }
5798 let run_args = args.get("args").cloned().unwrap_or(Json::Null);
5799 if let Some(msg) = app.command_args_refusal(&id, &run_args) {
5803 app.publish(
5804 &source_of(origin),
5805 None,
5806 "command.refused",
5807 json!({
5808 "command": id,
5809 "origin": source_of(origin),
5810 "reason": msg,
5811 "by": crate::bus::ARGS_VALIDATOR,
5812 "failed": false,
5813 }),
5814 );
5815 return Err(msg);
5816 }
5817 app.run_as(id, run_args, origin.clone());
5818 Ok(json!({ "queued": true }))
5819 })
5820 .agent(true)
5822 .mutates_when(move |args| {
5824 let Ok(app) = up(&w3) else { return true };
5825 let Some(id) = args.get("id").and_then(Json::as_str) else { return true };
5826 !app.commands().iter().any(|(s, _)| s.id.as_str() == id && s.read_only)
5827 })
5828 .destructive_when(move |args| {
5833 let Ok(app) = up(&w4) else { return false };
5834 let Some(id) = args.get("id").and_then(Json::as_str) else { return false };
5835 let run_args = args.get("args").cloned().unwrap_or(Json::Null);
5838 app.commands().iter().any(|(s, _)| {
5839 s.id.as_str() == id
5840 && s.is_destructive(&run_args)
5841 && s.agent
5842 && crate::bus::args_refusal(s, &run_args).is_none()
5843 })
5844 })
5845 .args(json!({ "id": "app.palette", "args": null })),
5846 )
5847 .expect("distinct names");
5848 let (w1, w2) = (h.weak(), h.weak());
5849 b.register(
5850 FnCollector::new(
5851 "icons",
5852 "The icon vocabulary (egui-pop's names, the Phosphor set's `phosphor:<name>` when built in, the registered ones with their owner and paint), every icon a command, panel or frame declares and whether it resolves, the unknown names with who asked for them, and the icons drawn by name in the last pass (tree rows, inputs, crumbs).",
5853 )
5854 .snapshot(move |ctx| {
5855 use egui_pop_core::icon::registry;
5856 let Ok(app) = up(&w1) else { return Json::Null };
5857 let declared = declared_icons(&app);
5858 let mut unknown: Vec<Json> = registry::unknown()
5859 .into_iter()
5860 .map(|u| json!(u))
5861 .collect();
5862 for d in declared.iter().filter(|d| !d.resolves) {
5863 unknown.push(json!({
5864 "name": d.name,
5865 "surfaces": [format!("{} {}", d.surface, d.subject)],
5866 "owner": d.owner,
5867 "hint": registry::hint(&d.name),
5868 }));
5869 }
5870 json!({
5871 "builtin": registry::builtin_names().collect::<Vec<_>>(),
5872 "phosphor": {
5873 "available": registry::phosphor_available(),
5874 "prefix": registry::PHOSPHOR_PREFIX,
5875 "count": registry::phosphor_names().len(),
5876 },
5877 "registered": egui_pop_core::icon_set::registered().iter().map(|r| json!({
5878 "name": r.name,
5879 "owner": r.owner,
5880 "paint": match r.paint {
5881 egui_pop_core::icon_set::Paint::Mono => "single-colour",
5882 egui_pop_core::icon_set::Paint::Colour => "full-colour",
5883 },
5884 })).collect::<Vec<_>>(),
5885 "declared": declared,
5886 "unknown": unknown,
5887 "drawn": registry::drawn(ctx),
5888 })
5889 })
5890 .action(
5891 "search",
5892 "The names of the vocabulary containing `query` (at most `limit`, 50 by default), Phosphor's included.",
5893 false,
5894 move |_, args| {
5895 let _ = up(&w2)?;
5896 let query = args.get("query").and_then(Json::as_str).ok_or("`query` is missing")?;
5897 let limit = args.get("limit").and_then(Json::as_u64).unwrap_or(50) as usize;
5898 Ok(json!(egui_pop_core::icon::registry::search(query, limit)))
5899 },
5900 )
5901 .args(json!({ "query": "grid", "limit": 20 })),
5902 )
5903 .expect("distinct names");
5904 let (w1, w2) = (h.weak(), h.weak());
5905 b.register(
5906 FnCollector::new(
5907 "journal",
5908 "The host's event journal (sequence, source, cause, name, data): the last 64, or since a sequence number.",
5909 )
5910 .snapshot(move |_| {
5911 let Ok(app) = up(&w1) else { return Json::Null };
5912 let last = app.last_event();
5913 json!({ "last": last, "events": app.events_since(last.saturating_sub(64)) })
5914 })
5915 .action("since", "The events after `seq`.", false, move |_, args| {
5916 let app = up(&w2)?;
5917 let seq = args.get("seq").and_then(Json::as_u64).unwrap_or(0);
5918 Ok(json!(app.events_since(seq)))
5919 })
5920 .args(json!({ "seq": 0 })),
5921 )
5922 .expect("distinct names");
5923 let w = h.weak();
5924 b.register(
5925 FnCollector::new(
5926 BRIDGE,
5927 "The bridge itself, for agents: every capability as one list (`describe`), and a wait on the journal or for the application to settle (`wait`).",
5928 )
5929 .action(
5930 "describe",
5931 "Every capability: the collectors' actions and the commands, with their JSON Schemas when given (`AppHandle::debug_capabilities`).",
5932 false,
5933 |_, _| Err("answered by the application (`AppHandle::debug_capabilities`)".into()),
5934 )
5935 .agent(true)
5936 .args(Json::Null)
5937 .result_schema(json!({
5938 "type": "object",
5939 "required": ["protocol", "capabilities"],
5940 "properties": {
5941 "protocol": { "type": "integer" },
5942 "capabilities": { "type": "array", "items": { "type": "object" } }
5943 }
5944 }))
5945 .action(
5946 "wait",
5947 "Whether a journal event after `since` matches (`event`, `cause`), the application is settled (`settled: true`), or the first of several (`any`); in-process it answers at once, a transport holds it until met or `deadline_ms`.",
5948 false,
5949 move |_, args| up(&w)?.wait_answer(args),
5950 )
5951 .agent(true)
5952 .args(json!({ "event": "command.done", "since": 0 }))
5953 .schema(crate::wait::args_schema())
5954 .result_schema(crate::wait::result_schema()),
5955 )
5956 .expect("distinct names");
5957 let w = h.weak();
5958 b.register(
5959 FnCollector::new(
5960 "keys",
5961 "The keymap's last resolutions, each binding considered and why it won or lost; `dormant` lists the bindings whose command went with a disconnected plugin.",
5962 )
5963 .snapshot(move |_| {
5964 let Ok(app) = up(&w) else { return Json::Null };
5965 json!({ "pending": app.pending_keys(), "traces": app.key_traces(), "dormant": app.dormant_keys() })
5966 }),
5967 )
5968 .expect("distinct names");
5969 let w = h.weak();
5970 b.register(
5971 FnCollector::new(
5972 "zones",
5973 "Every zone and its resolved blocks: owner, weight, what replaced or wrapped them.",
5974 )
5975 .snapshot(move |_| {
5976 let Ok(app) = up(&w) else { return Json::Null };
5977 json!(app.zones())
5978 }),
5979 )
5980 .expect("distinct names");
5981 let (w1, w2) = (h.weak(), h.weak());
5982 b.register(
5983 FnCollector::new("plugins", "The plugins in connection order, connected or why not; the services.")
5984 .snapshot(move |_| {
5985 let Ok(app) = up(&w1) else { return Json::Null };
5986 json!({
5987 "plugins": app.plugins(),
5988 "services": app.services().iter().map(|(i, o, t)| json!({"id": i, "owner": o, "type": t})).collect::<Vec<_>>(),
5989 })
5990 })
5991 .action("set_enabled", "Connects or disconnects a plugin (`id`, `enabled`), before the next frame.", true, move |_, args| {
5992 let app = up(&w2)?;
5993 let id = args.get("id").and_then(Json::as_str).ok_or("`id` is missing")?;
5994 let id = PluginId::new(id).map_err(|e| e.to_string())?;
5995 if !app.plugins().iter().any(|p| p.id == id) {
5996 return Err(format!("no plugin `{id}`"));
5997 }
5998 let enabled = args.get("enabled").and_then(Json::as_bool).ok_or("`enabled` is missing")?;
5999 app.set_plugin_enabled(id, enabled);
6000 Ok(json!({ "queued": true }))
6001 })
6002 .args(json!({ "id": "plugin.id", "enabled": false })),
6003 )
6004 .expect("distinct names");
6005 let w = h.weak();
6006 b.register(
6007 FnCollector::new(
6008 "diagnostics",
6009 "What registration ignored or changed, and what happens instead.",
6010 )
6011 .snapshot(move |_| {
6012 let Ok(app) = up(&w) else { return Json::Null };
6013 json!(app.diagnostics())
6014 }),
6015 )
6016 .expect("distinct names");
6017 let w = h.weak();
6018 b.register(
6019 FnCollector::new(
6020 "steps",
6021 "Every declared step with its hooks (before, replace, after), and the last runs: who redirected, vetoed, ran and followed.",
6022 )
6023 .snapshot(move |_| {
6024 let Ok(app) = up(&w) else { return Json::Null };
6025 json!({ "steps": app.steps(), "runs": app.step_traces() })
6026 }),
6027 )
6028 .expect("distinct names");
6029 let w = h.weak();
6030 b.register(
6031 FnCollector::new(
6032 "bus",
6033 "The bus (ADR 0029): every point on it, egui-pop's and the application's (`by`), with its kind, deadline and budget, whether it is journaled or relayable, and its listeners in the order they run (owner, after, before, priority, deadline, threaded, local, missing targets, runs, failures), the ordering constraints naming a listener not there, the order as text, the window registry (`windows.list`), and the window invariants broken now and said. The capabilities the bus offers (`capabilities`: defer, timings, journal, relay) and, with a journal, its last number (`journal_seq`). When the bus offers timings: each point's passes (`timing`: count, p50, p95, max in µs, passes over budget) and each listener's runs, and `slowest`: every listener timed, the slowest first by p95.",
6034 )
6035 .snapshot(move |_| {
6036 let Ok(app) = up(&w) else { return Json::Null };
6037 let kernel = app.bus();
6038 let infos = kernel.points();
6039 let ids: Vec<&str> = infos.iter().map(|p| p.id).collect();
6040 let timings: Vec<crate::bus::bus_contract_timings::PointTimings> =
6041 kernel.timings().map(|t| t.points()).unwrap_or_default();
6042 let points: Vec<Json> = infos
6043 .iter()
6044 .map(|p| {
6045 let timed = timings.iter().find(|t| t.point == p.id);
6046 let listeners: Vec<Json> = p
6047 .listeners
6048 .iter()
6049 .map(|l| {
6050 let timing = timed
6051 .and_then(|t| t.listeners.iter().find(|x| x.id == l.id))
6052 .map(|x| crate::bus::budget::stats(&x.stats));
6053 json!({
6054 "id": l.id,
6055 "owner": l.owner,
6056 "after": l.after,
6057 "before": l.before,
6058 "priority": l.priority,
6059 "deadline_ms": l.deadline.as_millis(),
6060 "threaded": l.threaded,
6061 "local": l.local,
6062 "missing": l.missing,
6063 "runs": l.runs,
6064 "failures": l.failures,
6065 "last_failure": l.last_failure,
6066 "timing": timing,
6067 })
6068 })
6069 .collect();
6070 let by = if crate::bus::CONTRACT.iter().any(|d| d.id == p.id) {
6071 "egui_pop"
6072 } else {
6073 "application"
6074 };
6075 let timing = timed.map(|t| {
6076 let mut j = crate::bus::budget::stats(&t.passes);
6077 j["over_budget"] = json!(t.over_budget);
6078 j
6079 });
6080 json!({
6081 "point": p.id,
6082 "kind": p.kind.as_str(),
6083 "by": by,
6084 "declared": p.declared,
6085 "description": p.description,
6086 "deadline_ms": p.deadline.as_millis(),
6087 "budget_us": p.budget.map(crate::bus::budget::us),
6088 "journaled": crate::bus::bus_contract_journal::is_journaled(&p.facets),
6089 "relayable": crate::bus::bus_contract_crossing::codec(&p.facets).is_some(),
6090 "timing": timing,
6091 "listeners": listeners,
6092 })
6093 })
6094 .collect();
6095 let offers = |c| crate::bus::bus_contract::offers(&*kernel, c);
6096 json!({
6097 "capabilities": {
6098 "defer": offers(&crate::bus::bus_contract_defer::CONTRACT),
6099 "timings": offers(&crate::bus::bus_contract_timings::CONTRACT),
6100 "journal": offers(&crate::bus::bus_contract_journal::CONTRACT),
6101 "relay": offers(&crate::bus::bus_contract_crossing::CONTRACT),
6102 },
6103 "journal_seq": kernel.journal().map(|j| j.last_seq()),
6104 "points": points,
6105 "slowest": crate::bus::budget::slowest(&timings),
6106 "missing_targets": crate::bus::missing_targets(&*kernel, &ids),
6107 "order": app.bus_order_of(&ids),
6108 "windows": app.windows_list(),
6109 "invariants": { "broken_now": app.invariants_broken_now(), "said": app.broken_invariants() },
6110 })
6111 }),
6112 )
6113 .expect("distinct names");
6114 let w = h.weak();
6115 b.register(
6116 FnCollector::new(
6117 "lists",
6118 "The menus' list providers (name, owner) and the entries each gave when its menu last opened.",
6119 )
6120 .snapshot(move |_| {
6121 let Ok(app) = up(&w) else { return Json::Null };
6122 app.lists()
6123 }),
6124 )
6125 .expect("distinct names");
6126 let w = h.weak();
6127 b.register(
6128 FnCollector::new(
6129 "menu_bar",
6130 "Each menu drawn as a bar (the shell's `app.main`): the menus in the bar, those moved into its \"…\" menu, whether it collapsed into one entry, and each menu's access key.",
6131 )
6132 .snapshot(move |_| {
6133 let Ok(app) = up(&w) else { return Json::Null };
6134 json!(crate::menus::bar_layouts(&app))
6135 }),
6136 )
6137 .expect("distinct names");
6138 let w = h.weak();
6139 b.register(
6140 FnCollector::new(
6141 "toolbars",
6142 "Each toolbar drawn last (`toolbars::Toolbar`), by menu id: its orientation and labels, every tool in order (a command with its arguments, a submenu or a separator; its title, icon name, key, whether it is enabled and why not, checked, busy) and which went into its \"More tools\" menu.",
6143 )
6144 .snapshot(move |_| {
6145 let Ok(app) = up(&w) else { return Json::Null };
6146 json!(crate::toolbars::layouts(&app))
6147 }),
6148 )
6149 .expect("distinct names");
6150 let w = h.weak();
6151 b.register(
6152 FnCollector::new(
6153 "text_scale",
6154 "The text size: the factor in use, the setting's default (the system's step), whether the user chose it, and the system's text scaling (factor, step, where it was read).",
6155 )
6156 .snapshot(move |_| {
6157 let Ok(app) = up(&w) else { return Json::Null };
6158 crate::text::describe(&app)
6159 }),
6160 )
6161 .expect("distinct names");
6162 let w = h.weak();
6163 b.register(
6164 FnCollector::new(
6165 "history",
6166 "The histories (ADR 0014): each scope, whether it is active, where Edit > Undo and Redo go and what they would do (the runs are in the `steps` collector).",
6167 )
6168 .snapshot(move |_| {
6169 let Ok(app) = up(&w) else { return Json::Null };
6170 crate::history::snapshot(&app)
6171 }),
6172 )
6173 .expect("distinct names");
6174 let w = h.weak();
6175 b.register(
6176 FnCollector::new(
6177 "overlay_rects",
6178 "Every overlay on screen with where it was drawn last (points): dialogs, modals, popovers, menus, the toasts, egui's popups.",
6179 )
6180 .snapshot(move |_| {
6181 let Ok(app) = up(&w) else { return Json::Null };
6182 json!(
6183 app.overlay_rects()
6184 .iter()
6185 .map(|o| json!({
6186 "kind": o.kind,
6187 "id": o.id,
6188 "rect": [o.rect.min.x, o.rect.min.y, o.rect.max.x, o.rect.max.y],
6189 }))
6190 .collect::<Vec<_>>()
6191 )
6192 }),
6193 )
6194 .expect("distinct names");
6195 let w = h.weak();
6196 b.register(
6197 FnCollector::new(
6198 "windows",
6199 "The application's windows (`main`, or a detached panel's id): the active one (where dialogs, the palette and menus open, and toasts show), each window's open overlays (bottom first) and whether a modal blocks the others, and the windows the palette and the popup menu are shown in.",
6200 )
6201 .snapshot(move |_| {
6202 let Ok(app) = up(&w) else { return Json::Null };
6203 app.describe_windows()
6204 }),
6205 )
6206 .expect("distinct names");
6207 let w = h.weak();
6208 b.register(
6209 FnCollector::new(
6210 "workbench",
6211 "The workbench: the layout (areas, folded, closed and detached panels, flyout widths), where each area was drawn (points), the focused panel, the side areas' strip icons (`strips`: each panel's title, icon, key, whether it shows, and its indicator with `marked` when the icon shows it), the flyout open (its panel and rect), the tab being dragged and the drop hint (its rect, name, refusal, zone and index among the tabs it joins).",
6212 )
6213 .snapshot(move |_| {
6214 let Ok(app) = up(&w) else { return Json::Null };
6215 let layout = app.layout();
6216 let strips = crate::workbench::strip(&app);
6217 let wb = app.workbench_mut();
6218 json!({
6219 "layout": layout,
6220 "strips": strips,
6221 "flyout": wb.flyout.as_ref().map(|p| json!({
6222 "panel": p,
6223 "rect": wb.flyout_rect.map(|r| [r.min.x, r.min.y, r.max.x, r.max.y]),
6224 })),
6225 "rects": wb.rects.iter().map(|(a, r)| (
6226 crate::workbench::area_name(*a),
6227 [r.min.x, r.min.y, r.max.x, r.max.y],
6228 )).collect::<BTreeMap<_, _>>(),
6229 "focused": wb.focused,
6230 "zen": wb.zen,
6231 "dragging": wb.dragging.as_ref().map(|(d, a, _)| json!({
6232 "panel": d.lead(),
6233 "group": d.is_group().then(|| d.panels()),
6234 "from": crate::workbench::area_name(*a),
6235 })),
6236 "window_outlines": wb.window_outlines(),
6237 "window_drop": wb.window_drop.as_ref().map(|d| json!({
6238 "panel": d.panel,
6239 "window": d.window,
6240 "zone": format!("{:?}", d.zone).to_lowercase(),
6241 "refusal": d.refusal,
6242 })),
6243 "drop_hint": wb.hint.as_ref().map(|h| json!({
6244 "name": h.name(),
6245 "panel": h.panel,
6246 "area": h.area,
6247 "rect": [h.rect.min.x, h.rect.min.y, h.rect.max.x, h.rect.max.y],
6248 "refusal": h.refusal,
6249 "zone": format!("{:?}", h.zone).to_lowercase(),
6250 "index": h.index,
6251 "armed": h.armed,
6252 "preview": h.preview.as_ref().map(|p| json!({
6253 "area": p.area,
6254 "index": p.index,
6255 "rect": [p.rect.min.x, p.rect.min.y, p.rect.max.x, p.rect.max.y],
6256 })),
6257 })),
6258 })
6259 }),
6260 )
6261 .expect("distinct names");
6262 b.register(egui_pop_core::debug::store_collector(h.store()))
6263 .expect("distinct names");
6264 b.register(crate::mounts::collector(h.downgrade()))
6265 .expect("distinct names");
6266 }
6267
6268 pub fn debug_call(&mut self, collector: &str, action: &str, args: &Json) -> Feedback {
6271 self.debug_call_as(collector, action, args, egui_pop_core::debug::agent())
6272 }
6273
6274 pub fn debug_call_as(
6277 &mut self,
6278 collector: &str,
6279 action: &str,
6280 args: &Json,
6281 origin: Origin,
6282 ) -> Feedback {
6283 let feedback = self
6284 .handle
6285 .debug_call_as(collector, action, args, origin.clone());
6286 if collector == "commands"
6287 && action == "run"
6288 && feedback.ok
6289 && feedback.data == json!({ "queued": true })
6290 {
6291 let queued = self.handle.0.requests.borrow_mut().pop();
6292 let id = args
6293 .get("id")
6294 .and_then(Json::as_str)
6295 .and_then(|i| CommandId::new(i).ok());
6296 if let Some(id) = id {
6297 let a = args.get("args").cloned().unwrap_or(Json::Null);
6298 let reply = match queued {
6299 Some(Request::RunIn { context, .. }) => self.run_in(&id, a, origin, &context),
6300 _ => self.run(&id, a, origin),
6301 };
6302 let Some(result) = reply.now() else {
6303 return Feedback {
6304 message: format!("`{id}` is running; its result goes to the journal"),
6305 data: json!({ "pending": true }),
6306 ..feedback
6307 };
6308 };
6309 return Feedback {
6310 ok: result.is_ok(),
6311 message: match &result {
6312 Ok(_) => format!("`{id}` ran; the application may have changed"),
6313 Err(e) => format!("`{id}` failed: {e}"),
6314 },
6315 data: result.unwrap_or(Json::Null),
6316 ..feedback
6317 };
6318 }
6319 }
6320 if feedback.ok && feedback.mutates {
6321 self.process_requests();
6322 }
6323 feedback
6324 }
6325
6326 fn connected_ids(&self) -> Vec<PluginId> {
6327 self.plugins
6328 .iter()
6329 .filter(|p| p.connected)
6330 .map(|p| p.id.clone())
6331 .collect()
6332 }
6333
6334 fn connect_slot(&mut self, i: usize) -> Result<(), PluginError> {
6337 let connected = self.connected_ids();
6338 let slot = &self.plugins[i];
6339 if let Some(missing) = slot
6340 .plugin
6341 .requires()
6342 .into_iter()
6343 .find(|r| !connected.contains(r))
6344 {
6345 let reason = format!("its requirement `{missing}` is not connected");
6346 self.handle.0.diagnostics.borrow_mut().warn(
6347 "plugin-skipped",
6348 Some(&slot.owner),
6349 slot.id.as_str(),
6350 format!("{reason}: it is not connected"),
6351 );
6352 self.plugins[i].reason = Some(reason);
6353 self.update_plugin_infos();
6354 return Ok(());
6355 }
6356 let handle = self.handle.clone();
6357 let owner = slot.owner.clone();
6358 let id = slot.id.clone();
6359 let mut ctx = Ctx {
6360 owner: owner.clone(),
6361 plugin: id.clone(),
6362 rank: i + 1,
6363 reg: &mut self.reg,
6364 app: &handle,
6365 connected: &connected,
6366 };
6367 let slot = &mut self.plugins[i];
6368 let _scope = egui_pop_model::values::enter_scope(&owner);
6370 if !slot.plugin.enabled(&ctx) {
6371 slot.reason = Some("it is disabled".into());
6372 self.update_plugin_infos();
6373 return Ok(());
6374 }
6375 match slot.plugin.connect(&mut ctx) {
6376 Ok(()) => {
6377 slot.connected = true;
6378 slot.reason = None;
6379 self.handle
6380 .0
6381 .gone_commands
6382 .borrow_mut()
6383 .retain(|_, p| *p != id);
6384 self.handle.zones_mut().set_rank(&owner, i + 1);
6385 self.dirty = true;
6386 self.update_plugin_infos();
6387 if self.started {
6388 self.handle.plugin_connected(crate::bus::PluginChange::new(
6390 id.as_str(),
6391 owner.as_str(),
6392 "connected",
6393 ));
6394 self.emit(&Lifecycle::Connected(id));
6395 }
6396 Ok(())
6397 }
6398 Err(e) => {
6399 let removed = self.remove_owner(&owner);
6400 self.said_gone(&id, &owner, "failed connect", removed);
6401 let slot = &mut self.plugins[i];
6402 slot.reason = Some(format!("it failed to connect: {e}"));
6403 self.handle.0.diagnostics.borrow_mut().error(
6404 "connect-failed",
6405 Some(&owner),
6406 id.as_str(),
6407 format!("{e}: what it registered is removed"),
6408 );
6409 self.update_plugin_infos();
6410 Err(e)
6411 }
6412 }
6413 }
6414
6415 fn remove_owner(&mut self, owner: &OwnerId) -> Removed {
6416 let commands = self.reg.remove_owner(owner);
6417 let h = &self.handle.0;
6418 h.zones.borrow_mut().remove_owner(owner);
6419 let panels = {
6420 let mut panels = h.panels.borrow_mut();
6421 let n = panels.len();
6422 panels.retain(|_, p| p.owner != *owner);
6423 n - panels.len()
6424 };
6425 h.stories.borrow_mut().remove_owner(owner);
6426 h.steps.borrow_mut().remove_owner(owner);
6427 h.step_hooks.borrow_mut().remove_owner(owner);
6428 h.lists.borrow_mut().remove_owner(owner);
6429 h.list_traces.borrow_mut().retain(|_, t| t.owner != *owner);
6430 h.indicators.borrow_mut().remove_owner(owner);
6431 h.workbench.borrow_mut().templates.retain(|t| t.0 != *owner);
6432 h.services.borrow_mut().remove_owner(owner);
6433 h.bus.kernel.forget(owner.as_str());
6435 let mounts = crate::mounts::remove_owner(&self.handle, owner);
6436 let undo = lock(&h.store).remove_owner_report(owner).dropped;
6437 crate::history::remove_owner(&self.handle, owner);
6438 h.diagnostics.borrow_mut().remove_owner(owner);
6439 egui_pop_core::icon_set::unregister_owner(owner.as_str());
6440 h.collectors.borrow_mut().retain(|(o, name)| {
6441 if o == owner {
6442 h.bridge.borrow_mut().unregister(name);
6443 }
6444 o != owner
6445 });
6446 self.dirty = true;
6447 Removed {
6448 commands,
6449 panels,
6450 mounts,
6451 undo,
6452 }
6453 }
6454
6455 fn said_gone(&mut self, plugin: &PluginId, owner: &OwnerId, reason: &str, removed: Removed) {
6460 let steps: usize = removed.undo.iter().map(|d| d.steps).sum();
6461 let mixed: usize = removed.undo.iter().map(|d| d.mixed).sum();
6462 let did = self.handle.plugin_disconnected(
6466 crate::bus::PluginChange::new(plugin.as_str(), owner.as_str(), reason).commands(
6467 removed
6468 .commands
6469 .iter()
6470 .map(|c| c.as_str().to_string())
6471 .collect(),
6472 ),
6473 );
6474 let count = |key: &str| did.get(key).and_then(Json::as_u64).unwrap_or(0);
6475 let (jobs_cancelled, jobs_orphaned) = (count("jobs_cancelled"), count("jobs_orphaned"));
6476 log::info!(
6477 target: "egui_pop",
6478 "plugin `{plugin}` disconnected ({reason}): {} command(s), {} panel(s), {} component(s), {} host(s), {} mount(s), {steps} undo step(s) ({mixed} mixed) removed; {jobs_cancelled} job(s) to cancel, {jobs_orphaned} orphaned",
6479 removed.commands.len(),
6480 removed.panels,
6481 removed.mounts.components,
6482 removed.mounts.hosts,
6483 removed.mounts.mounts,
6484 );
6485 let undo: Vec<Json> = removed
6486 .undo
6487 .iter()
6488 .map(|d| json!({ "history": d.history, "steps": d.steps, "mixed": d.mixed }))
6489 .collect();
6490 let mut counted = json!({
6491 "commands": removed.commands.len(),
6492 "panels": removed.panels,
6493 "components": removed.mounts.components,
6494 "hosts": removed.mounts.hosts,
6495 "mounts": removed.mounts.mounts,
6496 "undo_steps": steps,
6497 "mixed_undo_steps": mixed,
6498 "jobs_cancelled": jobs_cancelled,
6500 "jobs_orphaned": jobs_orphaned,
6501 });
6502 for (key, value) in did {
6503 counted[key] = value;
6504 }
6505 self.handle.publish(
6506 "egui_pop",
6507 None,
6508 "plugin.disconnected",
6509 json!({
6510 "plugin": plugin,
6511 "owner": owner,
6512 "reason": reason,
6513 "removed": counted,
6514 "undo": undo,
6515 }),
6516 );
6517 crate::dialogs::owner_gone(&self.handle, plugin, owner, &removed.commands);
6521 let mut gone = self.handle.0.gone_commands.borrow_mut();
6522 for c in removed.commands {
6523 gone.insert(c, plugin.clone());
6524 }
6525 }
6526
6527 fn update_plugin_infos(&self) {
6528 *self.handle.0.plugins.borrow_mut() = self
6529 .plugins
6530 .iter()
6531 .map(|s| PluginInfo {
6532 id: s.id.clone(),
6533 title: s.plugin.title(),
6534 requires: s.plugin.requires(),
6535 priority: s.plugin.priority(),
6536 connected: s.connected,
6537 reason: s.reason.clone(),
6538 })
6539 .collect();
6540 }
6541
6542 pub fn disconnect(&mut self, plugin: &PluginId) -> Vec<PluginId> {
6547 self.disconnect_because(plugin, "removed")
6548 }
6549
6550 fn disconnect_because(&mut self, plugin: &PluginId, reason: &str) -> Vec<PluginId> {
6553 let mut out = Vec::new();
6554 let Some(i) = self.plugins.iter().position(|p| p.id == *plugin) else {
6555 return out;
6556 };
6557 if !self.plugins[i].connected {
6558 return out;
6559 }
6560 for j in (i + 1..self.plugins.len()).rev() {
6562 if self.plugins[j].connected && self.plugins[j].plugin.requires().contains(plugin) {
6563 let dep = self.plugins[j].id.clone();
6564 out.extend(self.disconnect_because(&dep, "requirement gone"));
6565 }
6566 }
6567 let handle = self.handle.clone();
6568 let connected = self.connected_ids();
6569 let slot = &mut self.plugins[i];
6570 let owner = slot.owner.clone();
6571 let mut ctx = Ctx {
6572 owner: owner.clone(),
6573 plugin: slot.id.clone(),
6574 rank: i + 1,
6575 reg: &mut self.reg,
6576 app: &handle,
6577 connected: &connected,
6578 };
6579 slot.plugin.disconnect(&mut ctx);
6580 slot.connected = false;
6581 slot.reason = Some("it was disconnected".into());
6582 let removed = self.remove_owner(&owner);
6583 self.said_gone(plugin, &owner, reason, removed);
6584 self.update_plugin_infos();
6585 self.emit(&Lifecycle::Disconnected(plugin.clone()));
6586 out.push(plugin.clone());
6587 out
6588 }
6589
6590 pub fn connect(&mut self, plugin: &PluginId) -> Result<(), PluginError> {
6592 let Some(i) = self.plugins.iter().position(|p| p.id == *plugin) else {
6593 return Err(PluginError::Failed(format!("no plugin `{plugin}`")));
6594 };
6595 if self.plugins[i].connected {
6596 return Ok(());
6597 }
6598 for r in self.plugins[i].plugin.requires() {
6599 self.connect(&r)?;
6600 }
6601 self.connect_slot(i)
6602 }
6603
6604 fn emit(&mut self, event: &Lifecycle) {
6605 let handle = self.handle.clone();
6606 for slot in self.reg.lifecycle.iter_mut() {
6609 let (on, f) = &mut slot.item;
6610 if on.matches(event) {
6611 let _scope = egui_pop_model::values::enter_scope(&slot.owner);
6612 f(&handle, event);
6613 }
6614 }
6615 }
6616
6617 pub fn rebuild(&mut self) {
6621 let mut d = Diagnostics::new();
6622 let gone: BTreeMap<CommandId, PluginId> = self
6625 .handle
6626 .0
6627 .gone_commands
6628 .borrow()
6629 .iter()
6630 .filter(|(c, _)| self.reg.commands.spec(c).is_none())
6631 .map(|(c, p)| (c.clone(), p.clone()))
6632 .collect();
6633 self.reg
6634 .keymap
6635 .borrow_mut()
6636 .set_dormant(gone.keys().cloned());
6637 let reg = &self.reg;
6638 let hooks: Vec<&Hook> = reg.hooks.iter().map(|s| &s.item).collect();
6640 let nodes: Vec<Node> = hooks
6641 .iter()
6642 .map(|h| {
6643 let id = egui_pop_model::ids::PluginId::new(h.id.as_str()).expect("same syntax");
6644 let after = h
6645 .after
6646 .iter()
6647 .filter(|a| {
6648 let known = hooks.iter().any(|o| o.id == **a);
6649 if !known {
6650 d.warn(
6651 "dangling-after",
6652 None,
6653 h.id.as_str(),
6654 format!("hook `{}` runs after `{a}`, which is not registered: it runs by priority alone", h.id),
6655 );
6656 }
6657 known
6658 })
6659 .map(|a| PluginId::new(a.as_str()).expect("same syntax"))
6660 .collect();
6661 Node {
6662 id,
6663 requires: after,
6664 priority: h.priority,
6665 }
6666 })
6667 .collect();
6668 let hook_order: Vec<usize> = match order(&nodes) {
6669 Ok(o) => o,
6670 Err(e) => {
6671 d.error(
6672 "hook-order",
6673 None,
6674 "hooks",
6675 format!("{e}: hooks run in registration order"),
6676 );
6677 (0..hooks.len()).collect()
6678 }
6679 };
6680 let mut derived = Derived::default();
6681 for id in reg.menus.ids() {
6682 let mut items = reg.menus.items(&id);
6683 sort_items(&mut items);
6684 derived.menus.insert(id, items);
6685 }
6686 derived.palette = reg
6687 .commands
6688 .specs()
6689 .filter(|s| s.palette)
6690 .map(|s| PaletteEntry {
6691 command: s.id.clone(),
6692 title: s.title.clone(),
6693 category: s.category.clone(),
6694 keys: reg
6695 .keymap
6696 .borrow()
6697 .keys_for(&s.id)
6698 .iter()
6699 .map(|k| k.to_string())
6700 .collect(),
6701 })
6702 .collect();
6703 derived
6704 .palette
6705 .sort_by(|a, b| (&a.category, &a.title).cmp(&(&b.category, &b.title)));
6706 let titles: BTreeMap<OwnerId, String> = self
6707 .plugins
6708 .iter()
6709 .map(|s| (s.owner.clone(), s.plugin.title()))
6710 .chain([(OwnerId::FRAMEWORK, FRAMEWORK_SECTION.to_string())])
6711 .collect();
6712 let store = lock(&self.handle.0.store);
6713 derived.sections.clone_from(&titles);
6714 derived.settings = reg
6715 .settings
6716 .in_order()
6717 .into_iter()
6718 .filter_map(|(id, slot)| {
6719 store.get(&slot.item).map(|e| SettingEntry {
6720 id: id.clone(),
6721 path: slot.item.clone(),
6722 owner: slot.owner.clone(),
6723 section: if slot.owner == OwnerId::FRAMEWORK
6725 && crate::text::FONT_SETTINGS.contains(id)
6726 {
6727 crate::settings_window::FONTS.to_string()
6728 } else {
6729 titles
6730 .get(&slot.owner)
6731 .cloned()
6732 .unwrap_or_else(|| slot.owner.to_string())
6733 },
6734 descriptor: e.descriptor.clone(),
6735 })
6736 })
6737 .collect();
6738 drop(store);
6739 for &i in &hook_order {
6740 match &hooks[i].alter {
6741 Alter::Menu(menu, f) => {
6742 if let Some(items) = derived.menus.get_mut(menu) {
6743 f(items);
6744 } else {
6745 let mut items = Vec::new();
6746 f(&mut items);
6747 derived.menus.insert(menu.clone(), items);
6748 }
6749 }
6750 Alter::Palette(f) => f(&mut derived.palette),
6751 Alter::Settings(f) => f(&mut derived.settings),
6752 }
6753 }
6754 derived.commands = reg
6755 .commands
6756 .specs()
6757 .map(|s| {
6758 (
6759 s.clone(),
6760 reg.commands
6761 .owner(&s.id)
6762 .cloned()
6763 .unwrap_or(OwnerId::FRAMEWORK),
6764 )
6765 })
6766 .collect();
6767 for slot in reg.command_icons.iter() {
6770 let set = &slot.item;
6771 match derived.commands.iter_mut().find(|(s, _)| s.id == set.command) {
6772 Some((spec, _)) => {
6773 spec.icon = Some(set.icon.clone());
6774 spec.icon_on.clone_from(&set.icon_on);
6775 derived
6776 .icons_set_by
6777 .insert(set.command.clone(), slot.owner.clone());
6778 }
6779 None => d.warn(
6780 "unknown-command",
6781 Some(&slot.owner),
6782 set.command.as_str(),
6783 format!(
6784 "`{}` sets the icon of command `{}`, which is not declared: nothing shows it",
6785 slot.owner, set.command
6786 ),
6787 ),
6788 }
6789 }
6790 derived.keys = reg
6791 .commands
6792 .specs()
6793 .map(|s| {
6794 let keys = reg.keymap.borrow().keys_for(&s.id);
6795 (s.id.clone(), keys.iter().map(|k| k.to_string()).collect())
6796 })
6797 .collect();
6798 derived.sources = reg
6799 .commands
6800 .specs()
6801 .map(|s| (s.id.clone(), reg.keymap.borrow().sources_for(&s.id)))
6802 .filter(|(_, b)| !b.is_empty())
6803 .collect();
6804 derived.panels = reg
6805 .panels
6806 .owned()
6807 .into_iter()
6808 .map(|(spec, owner)| (spec.clone(), owner.clone()))
6809 .collect();
6810 derived.conflicts = reg.keymap.borrow().conflicts();
6811 derived.system = reg.keymap.borrow().system_bindings();
6812 derived.dormant = reg
6813 .keymap
6814 .borrow()
6815 .dormant()
6816 .into_iter()
6817 .filter_map(|binding| {
6818 let plugin = match &binding.action {
6819 egui_pop_model::keymap::Action::Run(c) => gone.get(c)?.clone(),
6820 _ => return None,
6821 };
6822 let plugin_title = self
6823 .plugins
6824 .iter()
6825 .find(|s| s.id == plugin)
6826 .map_or_else(|| plugin.to_string(), |s| s.plugin.title());
6827 Some(DormantKey {
6828 binding,
6829 plugin,
6830 plugin_title,
6831 })
6832 })
6833 .collect();
6834 let asleep = self.handle.0.derived.borrow().dormant.clone();
6836 for k in &derived.dormant {
6837 if !asleep.contains(k) {
6838 log::info!(
6839 target: "egui_pop",
6840 "keys: `{}` ({:?} layer) is dormant: its command `{}` went with plugin `{}`",
6841 k.binding.keys,
6842 k.binding.layer,
6843 k.binding.action,
6844 k.plugin
6845 );
6846 }
6847 }
6848 derived.layers = [
6849 Layer::Suggestion,
6850 Layer::Default,
6851 Layer::Workspace,
6852 Layer::User,
6853 ]
6854 .into_iter()
6855 .map(|l| (l, reg.keymap.borrow().export_layer(l)))
6856 .collect();
6857 let before: Vec<String> = self
6859 .handle
6860 .0
6861 .derived
6862 .borrow()
6863 .conflicts
6864 .iter()
6865 .map(|(l, w)| format!("{} {} {}", l.keys, l.action, w.action))
6866 .collect();
6867 for (lose, win) in &derived.conflicts {
6868 let key = format!("{} {} {}", lose.keys, lose.action, win.action);
6869 if self.started && !before.contains(&key) {
6870 self.handle.publish(
6871 "egui_pop",
6872 None,
6873 "keys.conflict",
6874 json!({
6875 "keys": lose.keys.to_string(),
6876 "scope": lose.options.scope.to_string(),
6877 "loses": lose.action.to_string(),
6878 "wins": win.action.to_string(),
6879 }),
6880 );
6881 }
6882 }
6883 derived.rebound = reg
6884 .commands
6885 .specs()
6886 .filter(|s| {
6887 reg.keymap
6888 .borrow()
6889 .rebound(&OwnerId::USER, Layer::User, &s.id)
6890 })
6891 .map(|s| s.id.clone())
6892 .collect();
6893 derived.rebound_workspace = reg
6894 .commands
6895 .specs()
6896 .filter(|s| {
6897 reg.keymap
6898 .borrow()
6899 .rebound(&WORKSPACE_KEYS, Layer::Workspace, &s.id)
6900 })
6901 .map(|s| s.id.clone())
6902 .collect();
6903 for (menu, items) in &derived.menus {
6905 for it in items {
6906 if let Item::Command { id, .. } = &it.item
6907 && reg.commands.spec(id).is_none()
6908 {
6909 d.warn(
6910 "unknown-command",
6911 None,
6912 id.as_str(),
6913 format!("menu `{menu}` names command `{id}`, which is not declared: the item is shown greyed"),
6914 );
6915 }
6916 }
6917 }
6918 *self.handle.0.derived.borrow_mut() = derived;
6919 self.check_steps(&mut d);
6920 self.check_icons(&mut d);
6921 self.handle.zones_mut().resolve(&mut d);
6922 let zone_of = self.handle.workbench_mut().zone_of.clone();
6924 let specs: Vec<egui_pop_model::panels::PanelSpec> = self
6925 .reg
6926 .panels
6927 .all()
6928 .into_iter()
6929 .filter(|p| {
6930 zone_of
6931 .get(&p.id)
6932 .is_none_or(|z| self.handle.zone_has_blocks(z))
6933 })
6934 .cloned()
6935 .collect();
6936 let before = self.handle.workbench_mut().layout.auxiliary.clone();
6937 let names = self.handle.layout_screens();
6938 let screens: Vec<&str> = names.iter().map(String::as_str).collect();
6939 let notes = self.handle.workbench_mut().refresh(specs, &screens);
6940 self.handle.note_layout("layout.repair");
6941 for note in notes {
6942 log::info!(target: "egui_pop", "layout: {note}");
6943 }
6944 self.handle.sync_panel_windows(&before);
6945 let mut all = self.handle.0.diagnostics.borrow_mut();
6946 let kept: Vec<Diagnostic> = all
6948 .take()
6949 .into_iter()
6950 .filter(|x| !RESOLUTION_CODES.contains(&x.code))
6951 .collect();
6952 for x in kept {
6953 all.push_quiet(x);
6954 }
6955 all.extend(d.take());
6956 drop(all);
6957 self.dirty = false;
6958 self.rebuilds += 1;
6959 *self.handle.0.keymap.borrow_mut() = Rc::new(self.reg.keymap.borrow().clone());
6960 if self.started {
6961 self.emit(&Lifecycle::Rebuilt);
6962 }
6963 }
6964
6965 fn check_icons(&self, d: &mut Diagnostics) {
6969 for icon in declared_icons(&self.handle) {
6970 if !icon.resolves {
6971 d.warn(
6972 "unknown-icon",
6973 icon.owner.as_ref(),
6974 icon.subject.as_str(),
6975 format!(
6976 "{} `{}` declares the icon `{}`: {}; a placeholder is drawn",
6977 icon.surface,
6978 icon.subject,
6979 icon.name,
6980 egui_pop_core::icon::registry::hint(&icon.name)
6981 ),
6982 );
6983 }
6984 }
6985 }
6986
6987 fn check_steps(&self, d: &mut Diagnostics) {
6990 let steps = self.handle.0.steps.borrow();
6991 let hooks = self.handle.0.step_hooks.borrow();
6992 let mut replaced: BTreeMap<StepId, Vec<OwnerId>> = BTreeMap::new();
6993 for h in hooks.iter() {
6994 if !steps.contains(&h.item.step) {
6995 d.warn(
6996 "unknown-step",
6997 Some(&h.owner),
6998 h.item.step.as_str(),
6999 format!(
7000 "a {} hook on step `{}`, which nobody declares: it never runs",
7001 h.item.f.kind(),
7002 h.item.step
7003 ),
7004 );
7005 }
7006 if matches!(h.item.f, HookFn::Run(_)) {
7007 replaced
7008 .entry(h.item.step.clone())
7009 .or_default()
7010 .push(h.owner.clone());
7011 }
7012 }
7013 for (step, owners) in replaced {
7014 if owners.len() > 1 {
7015 let last = owners.last().expect("two or more");
7016 d.warn(
7017 "step-replaced-twice",
7018 Some(last),
7019 step.as_str(),
7020 format!(
7021 "step `{step}` is replaced by {}: `{last}` (the last) runs it",
7022 owners
7023 .iter()
7024 .map(|o| format!("`{o}`"))
7025 .collect::<Vec<_>>()
7026 .join(", ")
7027 ),
7028 );
7029 }
7030 }
7031 }
7032
7033 fn load_documents(&mut self) {
7034 if self.persist.is_none() {
7035 return;
7036 }
7037 if let Some(Outcome::Done(Err(e))) = self.load_layout() {
7038 self.handle.0.diagnostics.borrow_mut().error(
7039 "layout-unreadable",
7040 None,
7041 "layout",
7042 format!("{e}: the default layout is used"),
7043 );
7044 }
7045 let Some(p) = &self.persist else { return };
7046 match p.load::<egui_pop_model::values::SettingsDoc>("settings", &settings_schema()) {
7047 Ok(Some(read)) => {
7048 let d = lock(&self.handle.0.store).import(&read.value, &Origin::User);
7049 self.handle
7050 .0
7051 .diagnostics
7052 .borrow_mut()
7053 .extend(d.all().iter().cloned());
7054 }
7055 Ok(None) => {}
7056 Err(e) => self.handle.0.diagnostics.borrow_mut().error(
7057 "settings-unreadable",
7058 None,
7059 "settings",
7060 format!("{e}: the defaults are used"),
7061 ),
7062 }
7063 match p
7064 .load::<egui_pop_model::keymap::KeymapDoc>("keymap", &egui_pop_model::keymap_schema())
7065 {
7066 Ok(Some(read)) => {
7067 let d = self
7068 .reg
7069 .keymap
7070 .borrow_mut()
7071 .load(&OwnerId::USER, Layer::User, &read.value);
7072 self.handle
7073 .0
7074 .diagnostics
7075 .borrow_mut()
7076 .extend(d.all().iter().cloned());
7077 }
7078 Ok(None) => {}
7079 Err(e) => self.handle.0.diagnostics.borrow_mut().error(
7080 "keymap-unreadable",
7081 None,
7082 "keymap",
7083 format!("{e}: the default keys are used"),
7084 ),
7085 }
7086 match p.load::<egui_pop_model::notice::NoticesDoc>(
7090 NOTICES_DOC,
7091 &egui_pop_model::notice::notices_schema(),
7092 ) {
7093 Ok(Some(read)) => self.handle.0.bus.notices.restore(&read.value),
7094 Ok(None) => {}
7095 Err(e) => {
7096 log::warn!(target: "egui_pop", "the notices could not be read: {e}");
7097 }
7098 }
7099 }
7100
7101 pub fn save(&self) -> Result<(), egui_pop_core::persist::PersistError> {
7105 let Some(p) = &self.persist else {
7106 return Ok(());
7107 };
7108 let (settings, keymap) = self.document_texts()?;
7109 p.save_text("settings", &settings)?;
7110 self.handle.saved_already("settings", &settings);
7111 p.save_text("keymap", &keymap)?;
7112 self.handle.saved_already("keymap", &keymap);
7113 let layout = match self.save_layout() {
7114 Some(Outcome::Done(Err(e))) => Err(egui_pop_core::persist::PersistError::Io {
7115 path: p.dir().to_path_buf(),
7116 error: std::io::Error::other(e),
7117 }),
7118 _ => Ok(()),
7119 };
7120 self.offer_notices();
7121 let mut flushed = Ok(());
7122 for (_, r) in self.handle.flush_documents() {
7123 if let Err(e) = r {
7124 flushed = Err(e);
7125 }
7126 }
7127 layout.and(flushed)
7128 }
7129
7130 fn document_texts(&self) -> Result<(String, String), PersistError> {
7132 let doc_error = |name: &str, error| PersistError::Doc {
7133 path: std::path::PathBuf::from(name),
7134 error,
7135 backup: None,
7136 };
7137 let mut doc = lock(&self.handle.0.store).export("settings/");
7138 if let Some(admin) = self.handle.service(&crate::admin::ADMIN) {
7141 admin.app_doc(&self.handle, &mut doc.values);
7142 }
7143 let settings = settings_schema()
7144 .save(&doc)
7145 .map_err(|e| doc_error("settings", e))?;
7146 let keymap = self.reg.keymap.borrow().export(&OwnerId::USER, Layer::User);
7147 let keymap = egui_pop_model::keymap_schema()
7148 .save(&keymap)
7149 .map_err(|e| doc_error("keymap", e))?;
7150 Ok((settings, keymap))
7151 }
7152
7153 fn autosave_baseline(&mut self) {
7156 if self.persist.is_none() {
7157 return;
7158 }
7159 if let Ok((settings, keymap)) = self.document_texts() {
7160 self.handle.saved_already("settings", &settings);
7161 self.handle.saved_already("keymap", &keymap);
7162 }
7163 self.autosave
7164 .store_seq
7165 .set(Some(lock(&self.handle.0.store).seq()));
7166 self.autosave.rebuilds.set(Some(self.rebuilds));
7167 let notices = &self.handle.0.bus.notices;
7168 if let Some(text) = notices.doc_text() {
7169 self.handle.saved_already(NOTICES_DOC, &text);
7170 }
7171 self.autosave.notices_rev.set(Some(notices.rev()));
7172 self.layout_baseline();
7173 }
7174
7175 fn offer_notices(&self) {
7177 let notices = &self.handle.0.bus.notices;
7178 let rev = notices.rev();
7179 if self.autosave.notices_rev.get() != Some(rev) {
7180 self.autosave.notices_rev.set(Some(rev));
7181 if let Some(text) = notices.doc_text() {
7182 self.handle.save_later(NOTICES_DOC, text);
7183 }
7184 }
7185 }
7186
7187 fn layout_baseline(&self) {
7189 self.handle.layout_said_now();
7190 }
7191
7192 fn autosave(&mut self, ctx: &Context) {
7198 if self.persist.is_none() {
7199 return;
7200 }
7201 let now = egui_pop_core::motion::now(ctx);
7202 let seq = lock(&self.handle.0.store).seq();
7203 let keymap_may_change = self.autosave.rebuilds.get() != Some(self.rebuilds);
7204 if self.autosave.store_seq.get() != Some(seq) || keymap_may_change {
7205 self.autosave.store_seq.set(Some(seq));
7206 self.autosave.rebuilds.set(Some(self.rebuilds));
7207 if let Ok((settings, keymap)) = self.document_texts() {
7208 self.handle.save_later("settings", settings);
7209 self.handle.save_later("keymap", keymap);
7210 }
7211 }
7212 self.offer_notices();
7213 let due = {
7214 let mut w = self.handle.0.writer.borrow_mut();
7215 match w.as_mut() {
7216 Some(w) => {
7217 for (name, r) in w.tick(now) {
7218 if let Err(e) = r {
7219 log::warn!(target: "egui_pop", "saving `{name}`: {e}");
7220 }
7221 }
7222 w.next_due()
7223 }
7224 None => None,
7225 }
7226 };
7227 for d in due.into_iter() {
7228 if d > now {
7229 ctx.request_repaint_after(std::time::Duration::from_secs_f64((d - now).max(0.05)));
7230 }
7231 }
7232 }
7233
7234 pub fn layout_document(&self) -> Option<String> {
7237 self.handle.with_host(|h| h.layout_document()).flatten()
7238 }
7239
7240 pub fn load_layout(&mut self) -> Option<Outcome> {
7245 let document = self.layout_document()?;
7246 let persist = self.persist.clone();
7247 let started = self.started;
7248 Some(self.handle.step(
7249 &STEP_LAYOUT_LOAD,
7250 json!({ "document": document }),
7251 move |app, args| {
7252 let document = args["document"].as_str().ok_or("`document` is missing")?;
7253 let Some(p) = persist else {
7254 return Ok(json!({ "document": document, "loaded": false }));
7255 };
7256 let read = p
7257 .load::<egui_pop_model::layout::SavedLayout>(
7258 document,
7259 &egui_pop_model::layout::schema(),
7260 )
7261 .map_err(|e| e.to_string())?;
7262 let Some(read) = read else {
7263 return Ok(json!({ "document": document, "loaded": false }));
7264 };
7265 app.workbench_mut().dormant = read.value.dormant;
7267 let notes = if started {
7268 app.set_layout(read.value.layout)
7269 } else {
7270 app.workbench_mut().layout = read.value.layout;
7273 Vec::new()
7274 };
7275 Ok(json!({ "document": document, "loaded": true, "repaired": notes }))
7276 },
7277 ))
7278 .inspect(|o| {
7279 if o.ok() && self.started {
7280 self.layout_baseline();
7281 }
7282 })
7283 }
7284
7285 pub fn save_layout(&self) -> Option<Outcome> {
7288 save_layout(&self.handle, self.persist.clone())
7289 }
7290
7291 fn listen_layout(&mut self) {
7295 use crate::bus::{LAYOUT_SAVE, LayoutChanged, OWNER, asking};
7296 let persist = self.persist.clone();
7297 let listened = self.handle.bus().listen_local::<LayoutChanged>(
7298 LAYOUT_SAVE,
7299 bus_contract::ListenOpts::new().owner(OWNER),
7300 move |_, ()| {
7301 if persist.is_none() {
7304 return Ok(());
7305 }
7306 let Some(app) = asking() else { return Ok(()) };
7307 match save_layout(&app, persist.clone()) {
7308 Some(Outcome::Done(Err(e))) => Err(format!("saving the layout: {e}").into()),
7309 _ => Ok(()),
7310 }
7311 },
7312 );
7313 if let Err(e) = listened {
7314 log::error!(target: "egui_pop", "{LAYOUT_SAVE}: {e}");
7315 }
7316 }
7317
7318 pub fn declare(&mut self, owner: &OwnerId, spec: CommandSpec) -> Result<(), CtxError> {
7320 let id = spec.id.clone();
7321 match crate::ctx::add_command(&mut self.reg, owner, spec, None) {
7322 Ok(()) => {
7323 self.rebuild();
7324 Ok(())
7325 }
7326 Err(e) => {
7327 self.handle.publish(
7328 "egui_pop",
7329 None,
7330 "command.declare_failed",
7331 json!({ "command": id, "owner": owner, "error": e.to_string() }),
7332 );
7333 Err(e)
7334 }
7335 }
7336 }
7337
7338 pub fn undeclare(&mut self, id: &CommandId) -> bool {
7341 let Some(owner) = self.reg.commands.remove(id) else {
7342 return false;
7343 };
7344 self.reg.keymap.borrow_mut().remove_command(&owner, id);
7345 self.reg.menus.remove_command(&owner, id);
7346 self.rebuild();
7347 true
7348 }
7349
7350 pub fn load_keymap(
7354 &mut self,
7355 doc: &egui_pop_model::keymap::KeymapDoc,
7356 layer: Layer,
7357 ) -> Result<egui_pop_model::keymap::KeymapDiff, String> {
7358 let owner = layer_owner(layer).ok_or("only the user's and the workspace's layers load")?;
7359 let handle = self.handle.clone();
7360 let mut keymap = self.reg.keymap.borrow_mut();
7361 let mut diff = None;
7362 let out = handle.step(
7363 &STEP_LOAD_KEYMAP,
7364 json!({ "layer": layer, "bindings": doc.bindings.len() }),
7365 |_, _| {
7366 let before = keymap.export(&owner, layer);
7367 let d = keymap.load(&owner, layer, doc);
7368 let mut diff_now = egui_pop_model::keymap::KeymapDiff::between(
7369 &before,
7370 &keymap.export(&owner, layer),
7371 );
7372 diff_now.skipped = d.all().iter().map(|x| x.message.clone()).collect();
7373 diff_now.conflicts = keymap
7374 .conflicts()
7375 .iter()
7376 .map(|(l, w)| {
7377 format!(
7378 "{} ({}): {} loses to {}",
7379 l.keys, l.options.scope, l.action, w.action
7380 )
7381 })
7382 .collect();
7383 let summary = json!({
7384 "added": diff_now.added.len(),
7385 "removed": diff_now.removed.len(),
7386 "changed": diff_now.changed.len(),
7387 "skipped": diff_now.skipped,
7388 "conflicts": diff_now.conflicts,
7389 });
7390 diff = Some(diff_now);
7391 Ok(summary)
7392 },
7393 );
7394 drop(keymap);
7395 self.rebuild();
7396 match out {
7397 Outcome::Done(Ok(_)) => Ok(diff.unwrap_or_default()),
7398 Outcome::Done(Err(e)) => Err(e),
7399 Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
7400 }
7401 }
7402
7403 pub fn exit(&mut self) -> Outcome {
7409 let handle = self.handle.clone();
7410 handle.drain_asks();
7414 for f in &mut self.on_exit {
7415 f(&handle);
7416 }
7417 drain_before_exit(&handle);
7418 let this: &App = self;
7419 handle.step(&STEP_EXIT, json!({}), |_, _| {
7420 this.save()
7421 .map(|()| json!({ "saved": true }))
7422 .map_err(|e| e.to_string())
7423 })
7424 }
7425
7426 pub fn show_wrapped(&mut self, ui: &mut Ui) {
7429 match self.wrap.take() {
7430 Some(mut wrap) => {
7431 let handle = self.handle.clone();
7432 wrap(ui, &handle, &mut |ui| self.show(ui));
7433 self.wrap = Some(wrap);
7434 }
7435 None => self.show(ui),
7436 }
7437 }
7438
7439 fn install_theme(&mut self) {
7443 let ctx = self.handle.egui();
7444 let here = THEME_INSTALLED.get(&ctx).unwrap_or(false);
7445 if !here {
7446 for kit in &self.kits {
7447 kit.register(&ctx);
7448 }
7449 }
7450 let mut follow = self.theme.borrow_mut();
7451 if !follow.read {
7452 follow.read_settings(&self.handle);
7453 }
7454 follow.install(&self.handle, !here);
7455 }
7456
7457 fn listen_settings(&mut self) {
7461 use crate::bus::{OWNER, SettingsChanged, THEME_INSTALL, asking};
7462 let bus = self.handle.bus();
7463 let follow = self.theme.clone();
7464 let listened = bus.listen_local::<SettingsChanged>(
7465 THEME_INSTALL,
7466 bus_contract::ListenOpts::new().owner(OWNER),
7467 move |change, ()| {
7468 if !change.is_any(&THEME_SETTINGS) {
7469 return Ok(());
7470 }
7471 let Some(app) = asking() else { return Ok(()) };
7472 let Ok(mut follow) = follow.try_borrow_mut() else {
7473 return Err("the theme is being installed".into());
7474 };
7475 follow.read_settings(&app);
7476 if THEME_INSTALLED.get(&app.egui()).unwrap_or(false) {
7477 follow.install(&app, false);
7478 follow.follow_preference(&app);
7479 }
7480 Ok(())
7481 },
7482 );
7483 if let Err(e) = listened {
7484 log::error!(target: "egui_pop", "{THEME_INSTALL}: {e}");
7485 }
7486 let keymap = self.reg.keymap.clone();
7487 let sync = self.pointer.clone();
7488 let changed = self.keymap_changed.clone();
7489 let listened = bus.listen_local::<SettingsChanged>(
7490 crate::bus::POINTER_PROFILE,
7491 bus_contract::ListenOpts::new().owner(OWNER),
7492 move |change, ()| {
7493 if change.id() != crate::pointer::SETTING_PROFILE.as_str() {
7494 return Ok(());
7495 }
7496 let Some(app) = asking() else { return Ok(()) };
7497 load_pointer_profile(&app, &keymap, &sync, &changed);
7498 Ok(())
7499 },
7500 );
7501 if let Err(e) = listened {
7502 log::error!(target: "egui_pop", "{}: {e}", crate::bus::POINTER_PROFILE);
7503 }
7504 crate::frame::listen(&self.handle);
7505 }
7506
7507 fn attach(&mut self, ctx: &Context) {
7510 *self.handle.0.ctx.borrow_mut() = ctx.clone();
7511 install_pass_marker(ctx);
7512 let commands = self.handle.0.panel_commands.borrow().clone();
7513 if !strings::panel_commands(ctx).is_some_and(|c| Arc::ptr_eq(&c, &commands)) {
7514 strings::set_panel_commands(ctx, commands);
7515 }
7516 strings::set_application(ctx, &self.handle.0.name.borrow());
7517 focus::install(ctx);
7518 egui_pop_core::layers::install(ctx);
7520 egui_pop_core::scale::disable_keyboard_zoom(ctx);
7522 let zoom = crate::zoom::current(&self.handle);
7523 if (ctx.zoom_factor() - zoom).abs() > 1e-3 {
7524 ctx.set_zoom_factor(zoom);
7525 }
7526 if self.waking.as_ref() != Some(ctx) {
7527 self.waking = Some(ctx.clone());
7528 self.handle.theme().follow(ctx);
7529 self.handle.0.bus.wake_with(ctx);
7530 crate::bus::overlays::watch(ctx, &self.handle);
7531 let c = ctx.clone();
7532 if let Some(h) = self.handle.0.host.borrow_mut().as_mut() {
7533 h.set_waker(Waker::new(move || c.request_repaint()));
7534 }
7535 }
7536 if let Some(modes) = self.handle.service(&FOCUS_MODE) {
7537 let preference = lock(&self.handle.store())
7538 .get(&format!("settings/{SETTING_FOCUS}"))
7539 .and_then(|e| e.value.as_choice().and_then(Preference::parse))
7540 .unwrap_or_default();
7541 modes.set_preference(preference);
7542 focus_mode::set(ctx, &modes);
7543 }
7544 }
7545
7546 pub fn run(&mut self, command: &CommandId, args: Json, origin: Origin) -> Reply {
7552 let cx = self.handle.when_context();
7553 self.run_in(command, args, origin, &cx)
7554 }
7555
7556 pub fn run_in(
7561 &mut self,
7562 command: &CommandId,
7563 args: Json,
7564 origin: Origin,
7565 cx: &WhenContext,
7566 ) -> Reply {
7567 let window = cx.get(crate::windows::CONTEXT_APP_WINDOW);
7570 let group = (!window.is_empty())
7571 .then(|| {
7572 self.handle
7573 .window_viewport(&crate::windows::WindowId::new(window))
7574 })
7575 .flatten();
7576 let _group = crate::windows::enter_group(group);
7577 if matches!(origin, Origin::Agent(_))
7579 && self.reg.commands.spec(command).is_some_and(|s| !s.agent)
7580 {
7581 let msg = format!("`{command}` is not offered to agents");
7582 self.handle.publish(
7583 &source_of(&origin),
7584 None,
7585 "command.refused",
7586 json!({ "command": command, "origin": source_of(&origin), "reason": msg }),
7587 );
7588 self.record(command, &args, &origin, Err(msg.clone()));
7589 return Reply::Done(Err(msg));
7590 }
7591 let handler = match self.reg.commands.prepare(command, cx) {
7592 Ok(h) => h.clone(),
7593 Err(e) => {
7594 let msg = e.to_string();
7595 if matches!(e, egui_pop_model::commands::RunRefused::Unknown { .. }) {
7596 let reason = match self.handle.command_gone_with(command) {
7601 Some(p) => format!("its plugin `{p}` is disconnected"),
7602 None => msg.clone(),
7603 };
7604 self.handle.publish(
7605 &source_of(&origin),
7606 None,
7607 "command.refused",
7608 json!({ "command": command, "origin": source_of(&origin), "reason": reason }),
7609 );
7610 self.handle
7611 .settle_reported(command, &args, &Err(reason.clone()));
7612 return Reply::Done(Err(reason));
7613 }
7614 self.record(command, &args, &origin, Err(msg.clone()));
7615 return Reply::Done(Err(msg));
7616 }
7617 };
7618 if let Some(reason) = self
7623 .reg
7624 .commands
7625 .spec(command)
7626 .and_then(|s| crate::bus::args_refusal(s, &args))
7627 {
7628 let msg = format!("refused by `{}`: {reason}", crate::bus::ARGS_VALIDATOR);
7629 self.handle.publish(
7630 &source_of(&origin),
7631 None,
7632 "command.refused",
7633 json!({
7634 "command": command,
7635 "origin": source_of(&origin),
7636 "reason": msg,
7637 "by": crate::bus::ARGS_VALIDATOR,
7638 "failed": false,
7639 }),
7640 );
7641 self.record(command, &args, &origin, Err(msg.clone()));
7642 return Reply::Done(Err(msg));
7643 }
7644 let mut ask = crate::bus::CommandAsk::new(command.clone(), args.clone(), origin.clone());
7648 if !window.is_empty() {
7649 ask = ask.window(window);
7650 }
7651 if let Some(refused) = crate::bus::ask_command_run(&self.handle, ask) {
7652 let msg = crate::bus::command_refusal(&refused);
7653 self.handle.publish(
7654 &source_of(&origin),
7655 None,
7656 "command.refused",
7657 json!({
7658 "command": command,
7659 "origin": source_of(&origin),
7660 "reason": msg,
7661 "by": refused.listener,
7662 "failed": refused.failed,
7663 }),
7664 );
7665 self.record(command, &args, &origin, Err(msg.clone()));
7666 return Reply::Done(Err(msg));
7667 }
7668 let source = source_of(&origin);
7669 let _running = RunningCommand::new(&self.handle, command, self.reg.commands.owner(command));
7670 let mut dispatched = json!({ "command": command, "args": args });
7674 if self.is_private(command) {
7675 dispatched["private"] = Json::Bool(true);
7676 }
7677 let seq = self
7678 .handle
7679 .publish_now(&source, None, "command.dispatched", dispatched);
7680 if crate::jobs::is_job_command(command) {
7681 self.handle
7682 .tag_job_event(seq, egui_pop_model::jobs::JobEventKind::CommandDispatched);
7683 }
7684 let owner = self.reg.commands.owner(command).cloned();
7685 let deferred = IN_INTERFACE.contains(command);
7693 let approved = Rc::new(std::cell::Cell::new(false));
7694 let stand_in: Option<CommandFn> = (deferred && handler.is_some()).then(|| {
7695 let approved = approved.clone();
7696 Rc::new(move |_: &Call<'_>| {
7697 approved.set(true);
7698 Ok(Json::Null)
7699 }) as CommandFn
7700 });
7701 let local = if deferred {
7702 stand_in.as_ref()
7703 } else {
7704 handler.as_ref()
7705 };
7706 let mut host = self
7707 .handle
7708 .0
7709 .host
7710 .borrow_mut()
7711 .take()
7712 .expect("a command dispatched from inside a dispatch is queued (AppHandle::run)");
7713 let acting = ActingFor::new(&self.handle, &origin);
7714 let groups = self.handle.0.dispatch_groups.replace(host.groups());
7717 let reply = host.dispatch(
7718 &Dispatch::new(command, &args, &origin, cx, seq, &self.handle, local)
7719 .owned_by(owner.as_ref())
7720 .deferring(deferred),
7721 );
7722 *self.handle.0.dispatch_groups.borrow_mut() = groups;
7723 drop(acting);
7724 *self.handle.0.host.borrow_mut() = Some(host);
7725 if deferred && approved.get() {
7726 let result = match &handler {
7728 Some(h) => {
7729 let _scope = owner.as_ref().map(egui_pop_model::values::enter_scope);
7730 let _acting = ActingFor::new(&self.handle, &origin);
7731 h(&Call {
7732 args: &args,
7733 origin: &origin,
7734 app: &self.handle,
7735 })
7736 }
7737 None => Err(format!("no handler for `{command}`")),
7738 };
7739 self.finish(command, &args, &origin, seq, result.clone());
7740 return Reply::Done(result);
7741 }
7742 match reply {
7743 Reply::Done(result) => {
7744 self.finish(command, &args, &origin, seq, result.clone());
7745 Reply::Done(result)
7746 }
7747 Reply::Later(pending) => {
7748 let waiting = {
7749 let mut running = self.handle.0.running.borrow_mut();
7750 let n = running.entry(command.clone()).or_default();
7751 *n += 1;
7752 *n
7753 };
7754 if waiting == 1 {
7755 let now = egui_pop_core::motion::now(&self.handle.egui());
7756 self.handle
7757 .0
7758 .running_since
7759 .borrow_mut()
7760 .insert(command.clone(), now);
7761 }
7762 self.in_flight.push(InFlight {
7763 command: command.clone(),
7764 args,
7765 origin,
7766 seq,
7767 pending: pending.clone(),
7768 });
7769 Reply::Later(pending)
7770 }
7771 }
7772 }
7773
7774 fn is_private(&self, command: &CommandId) -> bool {
7776 self.reg.commands.spec(command).is_some_and(|s| s.private)
7777 }
7778
7779 fn finish(
7781 &mut self,
7782 command: &CommandId,
7783 args: &Json,
7784 origin: &Origin,
7785 seq: Seq,
7786 result: Result<Json, String>,
7787 ) {
7788 use egui_pop_model::jobs::JobEventKind;
7789 let (kind, mut data) = match &result {
7790 Ok(v) => (
7791 JobEventKind::CommandDone,
7792 json!({ "command": command, "result": v }),
7793 ),
7794 Err(e) => (
7795 JobEventKind::CommandFailed,
7796 json!({ "command": command, "error": e }),
7797 ),
7798 };
7799 if self.is_private(command) {
7800 data["private"] = Json::Bool(true);
7801 }
7802 let done = self
7803 .handle
7804 .publish_now(&source_of(origin), Some(seq), kind.name(), data);
7805 if crate::jobs::is_job_command(command) {
7806 self.handle.tag_job_event(done, kind);
7807 }
7808 self.record(command, args, origin, result);
7809 }
7810
7811 pub fn settle(&mut self) -> usize {
7814 profiling::scope!("pop.app.settle");
7815 let mut arrived = Vec::new();
7816 self.in_flight.retain(|f| match f.pending.take() {
7817 Some(r) => {
7818 arrived.push((
7819 f.command.clone(),
7820 f.args.clone(),
7821 f.origin.clone(),
7822 f.seq,
7823 r,
7824 ));
7825 false
7826 }
7827 None => true,
7828 });
7829 let n = arrived.len();
7830 for (command, args, origin, seq, result) in arrived {
7831 if let Some(c) = self.handle.0.running.borrow_mut().get_mut(&command) {
7832 *c = c.saturating_sub(1);
7833 if *c == 0 {
7834 self.handle.0.running_since.borrow_mut().remove(&command);
7835 }
7836 }
7837 if let Err(e) = &result {
7838 log::warn!(target: "egui_pop", "command `{command}`: {e}");
7839 }
7840 self.finish(&command, &args, &origin, seq, result);
7841 }
7842 n
7843 }
7844
7845 fn record(
7846 &mut self,
7847 command: &CommandId,
7848 args: &Json,
7849 origin: &Origin,
7850 result: Result<Json, String>,
7851 ) {
7852 self.handle.settle_reported(command, args, &result);
7853 let run = Run {
7854 id: command.clone(),
7855 args: args.clone(),
7856 origin: origin.clone(),
7857 result,
7858 };
7859 self.reg.commands.record(run.clone());
7860 let mut h = self.handle.0.history.borrow_mut();
7861 h.push(run);
7862 let len = h.len();
7863 if len > 64 {
7864 h.drain(..len - 64);
7865 }
7866 }
7867
7868 fn rebind_step(&mut self, command: &CommandId, args: Json) {
7871 let handle = self.handle.clone();
7872 let mut keymap = self.reg.keymap.borrow_mut();
7873 let mut changed = false;
7874 let out = handle.step(&STEP_REBIND, args, |_, args| {
7875 let command = args
7876 .get("command")
7877 .and_then(Json::as_str)
7878 .and_then(|c| CommandId::new(c).ok())
7879 .ok_or("`command` is missing")?;
7880 let layer: Layer = args
7881 .get("layer")
7882 .cloned()
7883 .map_or(Ok(Layer::User), serde_json::from_value)
7884 .map_err(|e| format!("`layer`: {e}"))?;
7885 let owner = layer_owner(layer)
7886 .ok_or("keys change in the user's or the workspace's layer only")?;
7887 match args.get("keys") {
7888 Some(Json::Array(list)) => {
7889 let keys: Vec<&str> = list.iter().filter_map(Json::as_str).collect();
7890 keymap.rebind_all(&owner, layer, &command, &keys)?;
7891 }
7892 other => {
7893 let keys = other.and_then(Json::as_str);
7894 keymap.rebind(&owner, layer, &command, keys)?;
7895 }
7896 }
7897 changed = true;
7898 Ok(json!({ "command": command, "keys": args.get("keys"), "layer": layer }))
7899 });
7900 if changed {
7901 self.dirty = true;
7902 }
7903 if let Outcome::Done(Err(e)) = out {
7904 log::warn!(target: "egui_pop", "keys for `{command}`: {e}");
7905 }
7906 }
7907
7908 pub fn process_requests(&mut self) {
7910 profiling::scope!("pop.app.requests");
7911 loop {
7912 let requests: Vec<Request> = std::mem::take(&mut *self.handle.0.requests.borrow_mut());
7913 if requests.is_empty() {
7914 break;
7915 }
7916 for r in requests {
7917 match r {
7918 Request::Run {
7919 command,
7920 args,
7921 origin,
7922 } => {
7923 if let Reply::Done(Err(e)) = self.run(&command, args, origin) {
7924 log::warn!(target: "egui_pop", "command `{command}`: {e}");
7925 }
7926 }
7927 Request::RunIn {
7928 command,
7929 args,
7930 origin,
7931 context,
7932 } => {
7933 if let Reply::Done(Err(e)) = self.run_in(&command, args, origin, &context) {
7934 log::warn!(target: "egui_pop", "command `{command}`: {e}");
7935 }
7936 }
7937 Request::Enable(p, true) => {
7938 if let Err(e) = self.connect(&p) {
7939 log::warn!(target: "egui_pop", "plugin `{p}`: {e}");
7940 }
7941 }
7942 Request::Enable(p, false) => {
7943 self.disconnect_because(&p, "disabled");
7944 }
7945 Request::Rebind {
7946 command,
7947 keys,
7948 layer,
7949 } => {
7950 let args = json!({ "command": command, "keys": keys, "layer": layer });
7951 self.rebind_step(&command, args);
7952 }
7953 Request::RebindAll {
7954 command,
7955 keys,
7956 layer,
7957 } => {
7958 let args = json!({ "command": command, "keys": keys, "layer": layer });
7959 self.rebind_step(&command, args);
7960 }
7961 Request::Declare { owner, spec } => {
7962 let id = spec.id.clone();
7963 if let Err(e) = self.declare(&owner, spec) {
7964 log::warn!(target: "egui_pop", "declaring `{id}`: {e}");
7965 }
7966 }
7967 Request::Undeclare(id) => {
7968 self.undeclare(&id);
7969 }
7970 Request::LoadKeymap { doc, layer } => {
7971 if let Err(e) = self.load_keymap(&doc, layer) {
7972 log::warn!(target: "egui_pop", "loading a keymap: {e}");
7973 }
7974 }
7975 Request::ResetKeys { command, layer } => {
7976 if let Some(owner) = layer_owner(layer) {
7977 self.reg.keymap.borrow_mut().reset(&owner, layer, &command);
7978 self.dirty = true;
7979 }
7980 }
7981 Request::Workbench(change) => {
7982 let what = format!("{change:?}");
7983 if let Some(Outcome::Done(Err(e))) = self.handle.change_workbench(change) {
7984 self.handle.workbench_refused(&what, &e);
7985 }
7986 }
7987 }
7988 }
7989 }
7990 if self.keymap_changed.take() {
7991 self.dirty = true;
7992 }
7993 if self.dirty {
7994 self.rebuild();
7995 }
7996 }
7997
7998 pub fn logic(&mut self, ctx: &Context) {
8013 let mut again = false;
8014 if let Some(pass) = pass_in_progress(ctx) {
8015 again = self.logic_pass == Some(pass);
8016 self.logic_pass = Some(pass);
8017 }
8018 profiling::scope!("pop.app.logic");
8019 self.attach(ctx);
8020 self.handle.deliver_settings();
8023 self.install_theme();
8024 self.settle();
8025 self.handle.feed_indicators();
8026 self.handle.deliver_events();
8029 if !again {
8030 self.handle.run_pending();
8033 self.handle.say_over_budget();
8035 self.emit(&Lifecycle::Pass);
8036 }
8037 if self.pointer.borrow().loaded.is_none() {
8038 load_pointer_profile(
8040 &self.handle,
8041 &self.reg.keymap,
8042 &self.pointer,
8043 &self.keymap_changed,
8044 );
8045 }
8046 self.process_requests();
8047 self.handle.deliver_settings();
8049 if self.keymap_changed.get() {
8050 self.process_requests();
8051 }
8052 self.publish_pointer(ctx);
8053 self.handle.settle_layout(ctx);
8055 self.autosave(ctx);
8056 }
8057
8058 fn publish_pointer(&mut self, ctx: &Context) {
8061 let print = crate::pointer::settings_print(&self.handle);
8062 let fresh = match &self.pointer.borrow().published {
8063 Some((map, rebuilds, p)) => {
8064 *rebuilds == self.rebuilds
8065 && *p == print
8066 && egui_pop_core::pointer::published(ctx).is_some_and(|m| Arc::ptr_eq(&m, map))
8067 }
8068 None => false,
8069 };
8070 if fresh {
8071 return;
8072 }
8073 let map = Arc::new(crate::pointer::map(&self.handle, &self.reg.keymap.borrow()));
8074 egui_pop_core::pointer::set_shared_map(ctx, map.clone());
8075 self.pointer.borrow_mut().published = Some((map, self.rebuilds, print));
8076 }
8077
8078 pub fn show(&mut self, ui: &mut Ui) {
8084 profiling::scope!("pop.app.show");
8085 let ctx = ui.ctx().clone();
8086 let _group = crate::windows::enter_group(Some(egui::ViewportId::ROOT));
8088 let before = ctx.global_style();
8091 self.logic(&ctx);
8092 if let Some((from, to)) = egui_pop_core::scale::changed(&ctx) {
8093 self.handle.publish(
8094 "egui_pop",
8095 None,
8096 "scale.changed",
8097 json!({ "viewport": "root", "from": from, "to": to }),
8098 );
8099 self.theme.borrow_mut().installed = None;
8101 self.install_theme();
8102 }
8103 let now = ctx.global_style();
8108 if !Arc::ptr_eq(&before, &now) && Arc::ptr_eq(ui.style(), &before) {
8109 ui.set_style(now);
8110 }
8111 self.handle.note_window(&ctx);
8112 self.handle.follow_screens(&ctx);
8115 crate::bus::files::begin_pass(&ctx, crate::windows::WindowId::MAIN);
8117 crate::bus::drag::begin_pass(&ctx, crate::windows::WindowId::MAIN);
8119 crate::workbench::forget_closed_windows(&self.handle, &ctx);
8120 if ctx.viewport_id() == egui::ViewportId::ROOT {
8124 self.handle.main_close_seen(&ctx);
8125 }
8126 let app = self.handle.clone();
8129 app.block_window(&ctx, &|v| !crate::windows::is_app_window(&app, v));
8130 overlay::begin_pass(&ctx);
8131 self.dispatch_keys(&ctx);
8132 self.process_requests();
8133 self.handle.ask_home();
8136 self.handle.declare_windows(&ctx);
8137 self.handle.mark_pass_start(ui);
8138 if !self.handle.root_pass(ui) {
8139 self.outlined(ui);
8140 }
8141 let name = self.handle.name();
8142 let name = if name.is_empty() {
8143 ctx.input(|i| i.viewport().title.clone())
8144 .unwrap_or_default()
8145 } else {
8146 name
8147 };
8148 let handle = self.handle.clone();
8149 let mut drawn = Vec::new();
8152 if !handle.root_has_content() {
8153 crate::workbench::windows(&handle, &ctx, &name, &mut |c| {
8154 drawn.push(c.viewport_id());
8155 self.dispatch_keys(c);
8156 });
8157 }
8158 self.panel_keys.retain(|v, _| drawn.contains(v));
8160 handle.show_zone(ui, &zones::OVERLAYS);
8161 handle.show_zone(ui, &zones::WINDOW_OVERLAYS);
8162 crate::bus::files::end_pass(&handle, ui);
8164 crate::bus::drag::end_pass(&handle, &ctx);
8165 handle.end_shell_pass(ui);
8168 crate::menus::draw_popup(&ctx, &self.handle);
8169 a11y::live_regions(ui);
8170 for command in egui_pop_core::indicator::take_commands(&ctx) {
8172 self.handle.run(command, Json::Null);
8173 }
8174 self.handle.drain_asks();
8179 self.process_requests();
8180 self.handle.deliver_settings();
8183 if self.keymap_changed.get() {
8184 self.process_requests();
8185 }
8186 }
8187
8188 fn dispatch_keys(&mut self, ctx: &Context) {
8192 self.handle.follow_focus(ctx);
8193 let cx = self.handle.when_context();
8194 let v = ctx.viewport_id();
8195 let keys = if v == egui::ViewportId::ROOT {
8196 &mut self.keys
8197 } else {
8198 self.panel_keys.entry(v).or_default()
8199 };
8200 let dispatcher = keys.dispatcher(&self.handle);
8201 let dispatched = if self.handle.0.capturing.get() {
8202 Vec::new()
8203 } else {
8204 dispatcher.process(ctx, &self.reg.keymap.borrow(), &cx)
8205 };
8206 if v == egui::ViewportId::ROOT || self.handle.active_window() == v {
8209 *self.handle.0.traces.borrow_mut() = dispatcher.traces().cloned().collect();
8210 *self.handle.0.pending_keys.borrow_mut() = dispatcher.pending().map(|k| k.to_string());
8211 }
8212 for d in dispatched {
8213 let unknown = self.reg.commands.spec(&d.command).is_none();
8216 if let Reply::Done(Err(e)) = self.run(&d.command, Json::Null, Origin::User) {
8217 if unknown {
8218 log::warn!(target: "egui_pop", "{}: {e}", d.keys);
8219 } else {
8220 log::info!(target: "egui_pop", "{}: {e}", d.keys);
8221 }
8222 }
8223 }
8224 }
8225
8226 fn outlined(&mut self, ui: &mut Ui) {
8229 if !crate::frame::own_frame(&self.handle) {
8230 return self.shell(ui);
8231 }
8232 let edge = egui_pop_core::frame::window_edge(ui.ctx(), &crate::window::screens());
8233 egui_pop_core::frame::paint_window_edge(ui.ctx(), edge);
8234 let outline = edge.stroke;
8235 if outline.width <= 0.0 {
8236 return self.shell(ui);
8237 }
8238 let rect = ui.max_rect();
8239 ui.scope_builder(
8240 egui::UiBuilder::new().max_rect(rect.shrink(outline.width)),
8241 |ui| self.shell(ui),
8242 );
8243 }
8244
8245 fn shell(&mut self, ui: &mut Ui) {
8246 let h = self.handle.clone();
8247 h.follow_zen();
8248 crate::zen::show(&h, ui.ctx());
8249 if h.main_zen() {
8250 h.mark_shell_start(ui);
8252 egui_pop_core::frame::hide_title_bar(ui.ctx());
8253 crate::workbench::show(&h, ui);
8254 return;
8255 }
8256 let mut no_drop = Vec::new();
8258 if h.zone_has_blocks(&zones::TITLE) {
8259 let shown = egui::Panel::top(Id::unique("egui_pop.title"))
8262 .frame(egui::Frame::NONE)
8263 .show_separator_line(false)
8265 .min_size(0.0)
8266 .show(ui, |ui| {
8267 focus::scope(ui, "titleBar", &[], |ui| h.show_zone(ui, &zones::TITLE));
8268 });
8269 no_drop.push(shown.response.rect);
8270 }
8271 h.mark_shell_start(ui);
8274 if h.hidden_by_focus_screen() {
8279 h.workbench_mut().no_drop = no_drop;
8280 return;
8281 }
8282 if h.menu_bar() {
8283 let shown = egui::Panel::top(Id::unique("egui_pop.top")).show(ui, |ui| {
8284 focus::scope(ui, "topBar", &[], |ui| {
8285 egui::MenuBar::new().ui(ui, |ui| {
8286 let reserve = TOP_BAR_RESERVE.get(ui.ctx()).unwrap_or(0.0);
8289 crate::menus::bar_within(ui, &h, &MENU_MAIN, reserve);
8290 let mut used = 0.0;
8291 if h.zone_has_blocks(&zones::TOP_BAR) {
8292 let start = ui.cursor().min.x;
8295 ui.separator();
8296 let zone = ui.scope(|ui| h.show_zone(ui, &zones::TOP_BAR));
8297 used = zone.response.rect.max.x - start + ui.spacing().item_spacing.x;
8298 }
8299 let commands = crate::menus::has_end_items(&h, &MENU_BAR_END);
8300 let blocks = h.zone_has_blocks(&zones::TOP_BAR_END);
8301 if commands || blocks {
8302 let end = ui.with_layout(
8306 egui::Layout::right_to_left(egui::Align::Center),
8307 |ui| {
8308 let mut width = 0.0;
8309 if commands {
8310 width += crate::menus::bar_end(ui, &h, &MENU_BAR_END);
8311 }
8312 if blocks {
8313 if commands {
8314 width += ui.spacing().item_spacing.x;
8315 }
8316 width += top_bar_end(ui, &h);
8317 }
8318 width
8319 },
8320 );
8321 used += end.inner + 2.0 * ui.spacing().item_spacing.x;
8322 }
8323 if used != reserve {
8324 TOP_BAR_RESERVE.set(ui.ctx(), used);
8325 if crate::menus::refit_needed(&h, &MENU_MAIN, used) {
8327 ui.ctx().request_repaint();
8328 }
8329 }
8330 });
8331 });
8332 });
8333 no_drop.push(shown.response.rect);
8334 } else if h.zone_has_blocks(&zones::TOP_BAR) || h.zone_has_blocks(&zones::TOP_BAR_END) {
8335 let shown = egui::Panel::top(Id::unique("egui_pop.top")).show(ui, |ui| {
8336 focus::scope(ui, "topBar", &[], |ui| {
8337 ui.horizontal(|ui| {
8338 h.show_zone(ui, &zones::TOP_BAR);
8339 if h.zone_has_blocks(&zones::TOP_BAR_END) {
8340 ui.with_layout(
8341 egui::Layout::right_to_left(egui::Align::Center),
8342 |ui| top_bar_end(ui, &h),
8343 );
8344 }
8345 });
8346 });
8347 });
8348 no_drop.push(shown.response.rect);
8349 }
8350 if h.zone_has_blocks(&zones::STATUS_BAR) {
8351 let shown = egui::Panel::bottom(Id::unique("egui_pop.status")).show(ui, |ui| {
8352 let region = focus::Region::new("statusBar", crate::workbench::RANK_STATUS_BAR);
8353 focus::region(ui, ®ion, |ui| {
8354 let axis = egui_pop_core::tab::Axis::Horizontal;
8356 egui_pop_core::tab::roving(ui, "statusBar", axis, |ui| {
8357 ui.horizontal(|ui| h.show_zone(ui, &zones::STATUS_BAR));
8358 });
8359 });
8360 });
8361 no_drop.push(shown.response.rect);
8362 }
8363 h.workbench_mut().no_drop = no_drop;
8364 crate::workbench::show(&h, ui);
8365 }
8366}
8367
8368#[derive(Clone, Debug, PartialEq, serde::Serialize)]
8372pub struct DeclaredIcon {
8373 pub surface: &'static str,
8376 pub subject: String,
8378 pub owner: Option<OwnerId>,
8379 pub name: String,
8380 pub resolves: bool,
8382}
8383
8384fn unknown_icons(spec: &CommandSpec) -> Vec<&str> {
8386 [&spec.icon, &spec.icon_on]
8387 .into_iter()
8388 .flatten()
8389 .map(String::as_str)
8390 .filter(|n| !egui_pop_core::icon::registry::is_known(n))
8391 .collect()
8392}
8393
8394pub fn declared_icons(app: &AppHandle) -> Vec<DeclaredIcon> {
8397 let known = |n: &str| egui_pop_core::icon::registry::is_known(n);
8398 let mut out = Vec::new();
8399 let derived = app.0.derived.borrow();
8400 for (spec, owner) in &derived.commands {
8401 let owner = derived.icons_set_by.get(&spec.id).unwrap_or(owner);
8403 for (surface, name) in [("command", &spec.icon), ("command (on)", &spec.icon_on)] {
8404 if let Some(name) = name {
8405 out.push(DeclaredIcon {
8406 surface,
8407 subject: spec.id.to_string(),
8408 owner: Some(owner.clone()),
8409 name: name.clone(),
8410 resolves: known(name),
8411 });
8412 }
8413 }
8414 }
8415 for (spec, owner) in &derived.panels {
8416 if !spec.icon.is_empty() {
8417 out.push(DeclaredIcon {
8418 surface: "panel",
8419 subject: spec.id.to_string(),
8420 owner: Some(owner.clone()),
8421 name: spec.icon.clone(),
8422 resolves: known(&spec.icon),
8423 });
8424 }
8425 }
8426 drop(derived);
8427 for slot in app.0.indicators.borrow().iter() {
8428 let (ind, _) = &slot.item;
8429 if let Some(name) = &ind.initial.icon {
8430 out.push(DeclaredIcon {
8431 surface: "status item",
8432 subject: ind.id.clone(),
8433 owner: Some(slot.owner.clone()),
8434 name: name.clone(),
8435 resolves: known(name),
8436 });
8437 }
8438 }
8439 for (frame, name) in crate::contexts::frame_icons(app) {
8440 out.push(DeclaredIcon {
8441 surface: "frame",
8442 subject: frame.to_string(),
8443 owner: None,
8444 resolves: known(&name),
8445 name,
8446 });
8447 }
8448 out
8449}
8450
8451const RESOLUTION_CODES: &[&str] = &[
8452 "unknown-icon",
8453 "unknown-zone",
8454 "duplicate-block",
8455 "dangling-replace",
8456 "dangling-extend",
8457 "dangling-wrap",
8458 "dangling-after",
8459 "hook-order",
8460 "unknown-command",
8461 "unknown-step",
8462 "step-replaced-twice",
8463];
8464
8465fn drain_before_exit(handle: &AppHandle) {
8470 const ROUNDS: usize = 8;
8471 for _ in 0..ROUNDS {
8472 if handle.drain_asks().is_empty() {
8473 return;
8474 }
8475 }
8476 let left = handle.asks_waiting();
8477 if left > 0 {
8478 log::warn!(target: "egui_pop", "{left} request(s) asked for after the drawing still wait at exit");
8479 }
8480}
8481
8482#[cfg(feature = "eframe")]
8483impl eframe::App for App {
8484 fn logic(&mut self, ctx: &Context, _frame: &mut eframe::Frame) {
8485 App::logic(self, ctx);
8486 }
8487
8488 fn ui(&mut self, ui: &mut Ui, _frame: &mut eframe::Frame) {
8489 self.show_wrapped(ui);
8490 }
8491
8492 fn clear_color(&self, _visuals: &egui::Visuals) -> [f32; 4] {
8496 if self.handle.rounded_windows() {
8497 [0.0; 4]
8498 } else {
8499 egui::Color32::from_rgba_unmultiplied(12, 12, 12, 180).to_normalized_gamma_f32()
8501 }
8502 }
8503
8504 fn on_exit(&mut self) {
8505 match self.exit() {
8506 Outcome::Done(Err(e)) => log::error!(target: "egui_pop", "saving: {e}"),
8507 Outcome::Vetoed { by, reason } => {
8508 log::warn!(target: "egui_pop", "exit step vetoed by {by}: {reason}");
8509 }
8510 Outcome::Done(Ok(_)) => {}
8511 }
8512 }
8513}
8514
8515fn top_bar_end(ui: &mut Ui, h: &AppHandle) -> f32 {
8521 let height = ui.available_height();
8522 let layout = egui::Layout::left_to_right(egui::Align::Center);
8523 let known = TOP_BAR_END_WIDTH.get(ui.ctx());
8524 let width = known.unwrap_or(0.0);
8525 let r = ui.allocate_ui_with_layout(egui::vec2(width, height), layout, |ui| {
8526 h.show_zone(ui, &zones::TOP_BAR_END);
8527 });
8528 let took = r.response.rect.width();
8529 if (took - width).abs() > 0.5 {
8530 if known.is_none() {
8531 ui.ctx()
8532 .request_discard("the top bar's end zone was measured");
8533 } else {
8534 ui.ctx().request_repaint();
8535 }
8536 }
8537 TOP_BAR_END_WIDTH.set(ui.ctx(), took);
8538 took
8539}
8540
8541#[cfg(test)]
8542mod make_tests {
8543 use super::*;
8544
8545 #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
8549 #[test]
8550 fn a_reading_clipboard_turns_eframes_clipboard_shortcuts_off() {
8551 struct Reading;
8552 impl Plugin for Reading {
8553 fn id(&self) -> PluginId {
8554 crate::clipboard::SYSTEM_PLUGIN
8555 }
8556 fn connect(&mut self, _: &mut Ctx<'_>) -> Result<(), PluginError> {
8557 Ok(())
8558 }
8559 }
8560 let mut options = eframe::NativeOptions::default();
8561 assert!(!App::builder().clipboard_shortcuts(&mut options));
8562 assert!(options.clipboard_shortcuts, "no reading backend: kept on");
8563 assert!(
8564 App::builder()
8565 .plugin(Reading)
8566 .clipboard_shortcuts(&mut options)
8567 );
8568 assert!(!options.clipboard_shortcuts);
8569 let mut options = eframe::NativeOptions {
8570 clipboard_shortcuts: false,
8571 ..Default::default()
8572 };
8573 assert!(App::builder().clipboard_shortcuts(&mut options));
8574 assert!(
8575 !options.clipboard_shortcuts,
8576 "the application's choice kept"
8577 );
8578 }
8579
8580 #[test]
8581 fn a_failed_make_is_logged_and_published() {
8582 let app = App::builder().build(&Context::default()).unwrap();
8583 let h = app.handle().clone();
8584 let mark = h.last_event();
8585 let e: MakeError = "the kernel did not start".into();
8586 report_make_error(&h, e.as_ref());
8587 let events = h.events_since(mark);
8588 let ev = events.last().expect("published");
8589 assert_eq!(ev.name, "app.make_failed");
8590 assert_eq!(ev.data["error"], "the kernel did not start");
8591 }
8592
8593 #[cfg(all(feature = "eframe", not(target_arch = "wasm32")))]
8595 #[allow(
8596 dead_code,
8597 reason = "compiled, never called: it checks that `make` may fail with an error of any kind"
8598 )]
8599 fn fallible_make(b: AppBuilder) -> eframe::Result {
8600 b.run_native_with("demo", eframe::NativeOptions::default(), |app, _| {
8601 if app.handle().panels().is_empty() {
8602 return Err("nothing to show".into());
8603 }
8604 Ok(Box::new(app))
8605 })
8606 }
8607}
8608
8609#[cfg(test)]
8610mod names_surface_tests {
8611 use super::names_surface;
8612
8613 #[test]
8614 fn a_kind_names_its_instances_surfaces_an_exact_id_only_its_own() {
8615 assert!(names_surface("sheet.graph", "sheet.graph"));
8617 assert!(names_surface("app.log", "app.log"));
8618 assert!(names_surface("app.gallery", "app.gallery_2"));
8620 assert!(names_surface("app.gallery", "app.gallery_12"));
8621 assert!(!names_surface("app.gallery", "app.gallery_x"));
8622 assert!(!names_surface("app.gallery", "app.gallery_"));
8623 assert!(!names_surface("app.gallery", "app.gallery2"));
8624 assert!(!names_surface("app.gallery", "app.galleryx_2"));
8625 assert!(names_surface("app.gallery#2", "app.gallery_2"));
8627 assert!(!names_surface("app.gallery#2", "app.gallery"));
8628 assert!(!names_surface("app.gallery#2", "app.gallery_3"));
8629 assert!(!names_surface("app.log", "app.gallery_2"));
8631 }
8632}