1use egui_pop_model::diagnostics::{Diagnostic, Level};
24use egui_pop_model::ids::OwnerId;
25use egui_pop_model::mount::{
26 self, ClaimKey, Dismiss, Fit, FocusPolicy, HostDisplay, HostOffer, HostSize, Keep, Keyboard,
27 Lifetime, Mountable, Window,
28};
29use egui_pop_model::panels::{PanelHost, Place};
30use serde::Serialize;
31use serde_json::{Value as Json, json};
32use std::cell::RefCell;
33
34use crate::app::{AppHandle, WeakApp};
35use crate::ctx::Ctx;
36
37pub const PANEL: &str = "panel";
39pub const PALETTE: &str = "palette";
41pub const WINDOW: &str = "window";
43pub const DIALOG: &str = "dialog";
45pub const CUSTOM_DIALOG: &str = "dialog.custom";
48pub const MODAL: &str = "modal";
50pub const POPOVER: &str = "popover";
52pub const LINE: &str = "line";
54pub const STATUS_BAR: &str = "status-bar";
56pub const SETTINGS_PAGE: &str = "settings.page";
59pub const STORY: &str = "story";
61
62pub const SLIDERS: &str = "sliders";
64pub const FORMS: &str = "forms";
66pub const PROGRESS: &str = "progress";
68pub const JOBS_CENTRE: &str = "jobs-centre";
70pub const THEME_EDITOR: &str = "theme-editor";
72pub const TIPS: &str = "tips";
74
75pub fn panel() -> HostOffer {
77 HostOffer::new(PANEL, "P", "Docked panel")
78 .source("Ctx::panel, PanelSpec, workbench")
79 .resizable(true)
80 .keeps(&[Keep::Place])
81 .display(HostDisplay::Wide)
82 .hides_content(true)
83}
84
85pub fn palette() -> HostOffer {
88 HostOffer::new(PALETTE, "F", "Floating palette")
89 .source("palettes")
90 .size(HostSize::Content)
91 .resizable(true)
92 .focus(FocusPolicy::ClickInto)
93 .keeps(&[Keep::Place, Keep::Size])
94 .hides_content(true)
95}
96
97pub fn window() -> HostOffer {
99 HostOffer::new(WINDOW, "W", "Auxiliary window")
100 .source("workbench::windows, show_viewport_immediate")
101 .resizable(true)
102 .window(Window::Auxiliary)
103 .keeps(&[Keep::Place, Keep::Size])
104 .cursor_images(false)
105 .headless(false)
106}
107
108pub fn dialog() -> HostOffer {
110 HostOffer::new(DIALOG, "D", "Dialog (four kinds)")
111 .source("dialogs: Confirm, Form, Choose, Info")
112 .size(HostSize::Content)
113 .focus(FocusPolicy::ModalExclusive)
114 .owns_keys(&[ClaimKey::Enter, ClaimKey::Escape])
115 .dismissed_by(&[Dismiss::Answer, Dismiss::Escape])
116 .lifetime(Lifetime::Transient)
117 .keeps(&[Keep::Place])
118 .gives_app(false)
119 .scope(false)
120 .fault_boundary(false)
121 .free_content(false)
122}
123
124pub fn modal() -> HostOffer {
126 HostOffer::new(MODAL, "M", "Raw modal")
127 .source("overlay::show with Kind::Modal")
128 .size(HostSize::Content)
129 .focus(FocusPolicy::ModalExclusive)
130 .owns_keys(&[ClaimKey::Escape])
131 .dismissed_by(&[Dismiss::Escape])
132 .lifetime(Lifetime::Transient)
133 .scope(false)
134}
135
136pub fn popover() -> HostOffer {
138 HostOffer::new(POPOVER, "O", "Popover")
139 .source("overlay::show with Kind::Popover, egui::Popup")
140 .size(HostSize::Content)
141 .owns_keys(&[ClaimKey::Escape])
142 .dismissed_by(&[Dismiss::Escape, Dismiss::OutsideClick])
143 .lifetime(Lifetime::Transient)
144 .scope(false)
145 .fault_boundary(false)
146}
147
148pub fn line() -> HostOffer {
150 HostOffer::new(LINE, "L", "Line zone")
151 .source("zones: TOP_BAR, TOP_BAR_END, TITLE_BAR, ACTIVITY_BAR")
152 .size(HostSize::Row)
153}
154
155pub fn status_bar() -> HostOffer {
157 HostOffer::new(STATUS_BAR, "S", "Status bar")
158 .source("zones: STATUS_BAR, strips")
159 .size(HostSize::Row)
160}
161
162pub fn story() -> HostOffer {
164 HostOffer::new(STORY, "G", "Gallery story")
165 .source("Ctx::story, Story")
166 .resizable(true)
167 .display(HostDisplay::Wide)
168}
169
170pub fn hosts() -> Vec<HostOffer> {
173 vec![
174 panel(),
175 palette(),
176 window(),
177 dialog(),
178 crate::dialogs::custom_host(),
179 modal(),
180 popover(),
181 line(),
182 status_bar(),
183 crate::settings_pages::host(),
184 story(),
185 ]
186}
187
188pub fn panel_host(place: Place) -> PanelHost {
191 let offer = match place {
192 Place::Area(_) => panel(),
193 Place::Floating => palette(),
194 Place::Window => window(),
195 };
196 PanelHost { place, offer }
197}
198
199pub fn sliders() -> Mountable {
201 Mountable::new(SLIDERS, "Sliders")
202 .crate_name("egui-pop-core")
203 .claims(&[ClaimKey::Enter, ClaimKey::Escape])
204 .drag()
205 .min(120.0, 20.0)
206 .role("slider")
207 .descriptor_field()
208}
209
210pub fn forms() -> Mountable {
212 Mountable::new(FORMS, "Forms")
213 .crate_name("egui-pop-core")
214 .claims(&[ClaimKey::Enter])
215 .min(200.0, 48.0)
216 .popups()
217 .role("form")
218 .descriptor_field()
219}
220
221pub fn progress() -> Mountable {
223 Mountable::new(PROGRESS, "Progress")
224 .crate_name("egui-pop-core")
225 .keyboard(Keyboard::None)
226 .min(40.0, 4.0)
227 .preferred(200.0, 8.0)
228 .role("progressbar")
229 .preview()
230}
231
232pub fn jobs_centre() -> Mountable {
234 Mountable::new(JOBS_CENTRE, "Jobs centre")
235 .crate_name("egui-pop-api")
236 .keymap()
237 .min(240.0, 120.0)
238 .fills()
239 .single()
240 .needs_app()
241 .role("list")
242}
243
244pub fn theme_editor() -> Mountable {
246 Mountable::new(THEME_EDITOR, "Theme editor")
247 .crate_name("egui-pop-api")
248 .keymap()
249 .min(520.0, 320.0)
250 .fills()
251 .single()
252 .needs_app()
253 .session()
254 .popups()
255 .role("form")
256}
257
258pub fn tips() -> Mountable {
260 Mountable::new(TIPS, "Tips")
261 .crate_name("egui-pop-api")
262 .min(240.0, 80.0)
263 .needs_app()
264 .role("group")
265}
266
267pub fn components() -> Vec<Mountable> {
269 vec![
270 sliders(),
271 forms(),
272 progress(),
273 jobs_centre(),
274 theme_editor(),
275 tips(),
276 ]
277}
278
279#[derive(Clone, Debug, PartialEq, Serialize)]
281pub struct Placement {
282 pub host: String,
284 pub code: String,
286 pub name: String,
287 pub fit: Fit,
288}
289
290#[derive(Clone, Debug, PartialEq, Serialize)]
292pub struct Mounted {
293 pub component: String,
294 pub host: String,
295 pub fit: Fit,
296}
297
298#[derive(Debug, Default)]
302pub(crate) struct Registry {
303 components: RefCell<Vec<(OwnerId, Mountable)>>,
304 hosts: RefCell<Vec<(OwnerId, HostOffer)>>,
305 mounted: RefCell<Vec<(Option<OwnerId>, Mounted)>>,
306}
307
308#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
310pub(crate) struct RemovedMounts {
311 pub components: usize,
312 pub hosts: usize,
313 pub mounts: usize,
314}
315
316pub(crate) fn remove_owner(app: &AppHandle, owner: &OwnerId) -> RemovedMounts {
320 let registry = app.mount_registry();
321 let mut components = registry.components.borrow_mut();
322 let mut hosts = registry.hosts.borrow_mut();
323 let mut mounted = registry.mounted.borrow_mut();
324 let its_components: Vec<String> = (components.iter())
325 .filter(|(o, _)| o == owner)
326 .map(|(_, m)| m.id.clone())
327 .collect();
328 let its_hosts: Vec<String> = (hosts.iter())
329 .filter(|(o, _)| o == owner)
330 .map(|(_, h)| h.id.clone())
331 .collect();
332 components.retain(|(o, _)| o != owner);
333 hosts.retain(|(o, _)| o != owner);
334 let before = mounted.len();
335 mounted.retain(|(by, m)| {
336 by.as_ref() != Some(owner)
337 && !its_components.contains(&m.component)
338 && !its_hosts.contains(&m.host)
339 });
340 RemovedMounts {
341 components: its_components.len(),
342 hosts: its_hosts.len(),
343 mounts: before - mounted.len(),
344 }
345}
346
347impl AppHandle {
348 fn mount_registry(&self) -> std::rc::Rc<Registry> {
349 self.local::<Registry>()
350 }
351
352 pub(crate) fn owner_connected(&self, owner: &OwnerId) -> bool {
355 *owner == OwnerId::FRAMEWORK
356 || self
357 .plugins()
358 .iter()
359 .any(|p| p.connected && OwnerId::from(&p.id) == *owner)
360 }
361
362 pub fn mountables(&self) -> Vec<Mountable> {
365 let mut out = components();
366 let declared = self.mount_registry().components.borrow().clone();
367 out.extend(
368 declared
369 .into_iter()
370 .filter(|(o, _)| self.owner_connected(o))
371 .map(|(_, m)| m),
372 );
373 out
374 }
375
376 pub fn host_offers(&self) -> Vec<HostOffer> {
379 let mut out = hosts();
380 let declared = self.mount_registry().hosts.borrow().clone();
381 out.extend(
382 declared
383 .into_iter()
384 .filter(|(o, _)| self.owner_connected(o))
385 .map(|(_, h)| h),
386 );
387 out
388 }
389
390 pub fn where_can(&self, component: &str) -> Result<Vec<Placement>, String> {
393 let needs = self
394 .mountables()
395 .into_iter()
396 .find(|m| m.id == component)
397 .ok_or_else(|| format!("no component `{component}` is declared"))?;
398 Ok(self
399 .host_offers()
400 .into_iter()
401 .map(|h| Placement {
402 fit: mount::check(&needs, &h),
403 host: h.id,
404 code: h.code,
405 name: h.name,
406 })
407 .collect())
408 }
409
410 pub fn check_mount(&self, component: &str, host: &str) -> Result<Fit, String> {
412 self.where_can(component)?
413 .into_iter()
414 .find(|p| p.host == host)
415 .map(|p| p.fit)
416 .ok_or_else(|| format!("no host `{host}` is declared"))
417 }
418
419 pub fn mount(&self, component: &str, host: &str) -> Result<Fit, String> {
423 let fit = match self.check_mount(component, host) {
424 Ok(fit) => fit,
425 Err(e) => {
426 self.report_diagnostic(Diagnostic {
427 level: Level::Error,
428 code: "mount-unknown",
429 owner: None,
430 subject: format!("{component} in {host}"),
431 message: format!("{e}; nothing is mounted"),
432 });
433 return Err(e);
434 }
435 };
436 self.record_mount(component, host, fit)
437 }
438
439 pub(crate) fn mount_needs(&self, needs: &Mountable, host: &HostOffer) -> Result<Fit, String> {
442 self.record_mount(&needs.id, &host.id, mount::check(needs, host))
443 }
444
445 fn record_mount(&self, component: &str, host: &str, fit: Fit) -> Result<Fit, String> {
446 if let Some(refusal) = fit.refusal() {
447 let reason = refusal.reason();
448 self.report_diagnostic(Diagnostic {
449 level: Level::Error,
450 code: "mount-refused",
451 owner: None,
452 subject: format!("{component} in {host}"),
453 message: format!("{reason}; nothing is mounted"),
454 });
455 return Err(reason);
456 }
457 let registry = self.mount_registry();
458 let mut mounted = registry.mounted.borrow_mut();
459 if !mounted
460 .iter()
461 .any(|(_, m)| m.component == component && m.host == host)
462 {
463 mounted.push((
464 egui_pop_model::values::current_scope(),
465 Mounted {
466 component: component.into(),
467 host: host.into(),
468 fit: fit.clone(),
469 },
470 ));
471 }
472 Ok(fit)
473 }
474
475 pub fn unmount(&self, component: &str, host: &str) -> bool {
478 let registry = self.mount_registry();
479 let mut mounted = registry.mounted.borrow_mut();
480 let before = mounted.len();
481 mounted.retain(|(_, m)| !(m.component == component && m.host == host));
482 mounted.len() != before
483 }
484
485 pub fn mounts(&self) -> Vec<Mounted> {
487 (self.mount_registry().mounted.borrow().iter())
488 .map(|(_, m)| m.clone())
489 .collect()
490 }
491}
492
493impl Ctx<'_> {
494 pub fn mountable(&mut self, needs: Mountable) -> &mut Self {
499 let registry = self.app.local::<Registry>();
500 let builtin = components().iter().any(|m| m.id == needs.id);
501 let ok = declare(
502 &mut registry.components.borrow_mut(),
503 &self.owner,
504 builtin,
505 needs.id.clone(),
506 needs,
507 |m| m.id.as_str(),
508 );
509 if let Err(id) = ok {
510 self.app
511 .report_diagnostic(duplicate(&self.owner, id, "component"));
512 }
513 self
514 }
515
516 pub fn host_offer(&mut self, offer: HostOffer) -> &mut Self {
519 let registry = self.app.local::<Registry>();
520 let builtin = hosts().iter().any(|h| h.id == offer.id);
521 let ok = declare(
522 &mut registry.hosts.borrow_mut(),
523 &self.owner,
524 builtin,
525 offer.id.clone(),
526 offer,
527 |h| h.id.as_str(),
528 );
529 if let Err(id) = ok {
530 self.app
531 .report_diagnostic(duplicate(&self.owner, id, "host"));
532 }
533 self
534 }
535}
536
537fn declare<T>(
540 list: &mut Vec<(OwnerId, T)>,
541 owner: &OwnerId,
542 builtin: bool,
543 id: String,
544 item: T,
545 id_of: impl Fn(&T) -> &str,
546) -> Result<(), String> {
547 if builtin {
548 return Err(id);
549 }
550 match list.iter().position(|(_, t)| id_of(t) == id) {
551 Some(i) if list[i].0 == *owner => {
552 list[i].1 = item;
553 Ok(())
554 }
555 Some(_) => Err(id),
556 None => {
557 list.push((owner.clone(), item));
558 Ok(())
559 }
560 }
561}
562
563fn duplicate(owner: &OwnerId, id: String, what: &str) -> Diagnostic {
564 Diagnostic {
565 level: Level::Warning,
566 code: "duplicate-id",
567 owner: Some(owner.clone()),
568 subject: id,
569 message: format!("a {what} of this id is declared already; this declaration is ignored"),
570 }
571}
572
573pub(crate) fn collector(app: WeakApp) -> egui_pop_core::debug::FnCollector {
575 let (a, b, c) = (app.clone(), app.clone(), app);
576 egui_pop_core::debug::FnCollector::new(
577 "mounts",
578 "The mount contract (ADR 0013): every component and host declared, what is mounted where with its conditions; `where_can` and `check` give the verdicts.",
579 )
580 .snapshot(move |_| {
581 let Ok(app) = a.get() else { return Json::Null };
582 json!({
583 "components": app.mountables(),
584 "hosts": app.host_offers(),
585 "mounted": app.mounts(),
586 })
587 })
588 .action(
589 "where_can",
590 "Every host and its verdict for a component (`component`).",
591 false,
592 move |_, args| {
593 let app = b.get()?;
594 let id = args
595 .get("component")
596 .and_then(Json::as_str)
597 .ok_or("`component` is missing")?;
598 Ok(json!(app.where_can(id)?))
599 },
600 )
601 .args(json!({ "component": "viewport" }))
602 .action(
603 "check",
604 "The verdict for a component in a host (`component`, `host`), with the reason when it does not fit.",
605 false,
606 move |_, args| {
607 let app = c.get()?;
608 let get = |k: &str| {
609 args.get(k)
610 .and_then(Json::as_str)
611 .ok_or_else(|| format!("`{k}` is missing"))
612 };
613 let fit = app.check_mount(get("component")?, get("host")?)?;
614 let reason = fit.refusal().map(mount::Refusal::reason);
615 Ok(json!({ "fit": fit, "cell": fit.cell(), "reason": reason }))
616 },
617 )
618 .args(json!({ "component": "viewport", "host": "dialog.custom" }))
619}