1use std::fmt;
7use std::rc::Rc;
8use std::sync::Arc;
9
10use egui::Ui;
11use egui_pop_core::binding::SharedStore;
12use egui_pop_core::strings::{self, StrKey};
13use egui_pop_model::commands::{CommandSpec, RegisterError};
14use egui_pop_model::ids::{CommandId, MenuId, OwnerId, PanelId, PluginId, SettingId, ZoneId};
15use egui_pop_model::keymap::{Action, BindOptions, Layer};
16use egui_pop_model::menus::MenuItem;
17use egui_pop_model::panels::PanelSpec;
18use egui_pop_model::values::{Applied, DeclareError, Descriptor, Refused, Set};
19use serde_json::Value as Json;
20
21use crate::app::{AppHandle, Call, CommandFn, Registries};
22use crate::hooks::{Hook, LifecycleFn, On};
23use crate::services::ServiceToken;
24use crate::stories::Story;
25use crate::strings as txt;
26use crate::zones::Block;
27
28#[derive(Clone, Debug, PartialEq, Eq)]
30pub enum CtxError {
31 Command(RegisterError),
32 Keys {
34 keys: String,
35 error: String,
36 },
37 Menu(String),
38 Panel(String),
39 Zone {
41 zone: ZoneId,
42 by: OwnerId,
43 },
44 Setting(DeclareError),
47 Service {
48 id: String,
49 by: OwnerId,
50 },
51 Story {
52 id: String,
53 by: OwnerId,
54 },
55 Hook {
56 id: String,
57 by: OwnerId,
58 },
59 Step {
61 id: String,
62 by: OwnerId,
63 },
64 Collector(String),
66 Frame(String),
69 Clipboard(String),
71}
72
73impl fmt::Display for CtxError {
74 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
75 match self {
76 CtxError::Command(e) => write!(f, "{e}"),
77 CtxError::Keys { keys, error } => write!(f, "key binding `{keys}`: {error}"),
78 CtxError::Menu(e) | CtxError::Panel(e) => write!(f, "{e}"),
79 CtxError::Zone { zone, by } => write!(f, "zone `{zone}` is already declared by `{by}`"),
80 CtxError::Setting(e) => write!(f, "{e}"),
81 CtxError::Collector(e) | CtxError::Frame(e) | CtxError::Clipboard(e) => {
82 write!(f, "{e}")
83 }
84 CtxError::Service { id, by } => {
85 write!(f, "service `{id}` is already provided by `{by}`")
86 }
87 CtxError::Story { id, by } => {
88 write!(f, "story `{id}` is already contributed by `{by}`")
89 }
90 CtxError::Hook { id, by } => write!(f, "hook `{id}` is already registered by `{by}`"),
91 CtxError::Step { id, by } => write!(f, "step `{id}` is already declared by `{by}`"),
92 }
93 }
94}
95
96impl std::error::Error for CtxError {}
97
98#[derive(Clone)]
103pub struct ValueWriter {
104 store: SharedStore,
105 scope: OwnerId,
106}
107
108impl fmt::Debug for ValueWriter {
109 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
110 f.debug_struct("ValueWriter")
111 .field("scope", &self.scope)
112 .finish_non_exhaustive()
113 }
114}
115
116impl ValueWriter {
117 pub fn new(store: SharedStore, scope: OwnerId) -> Self {
119 Self { store, scope }
120 }
121
122 pub fn set(&self, set: Set) -> Result<Applied, Refused> {
125 egui_pop_core::lock(&self.store).set(set.by(&self.scope))
126 }
127
128 pub fn scope(&self) -> &OwnerId {
130 &self.scope
131 }
132}
133
134pub struct Ctx<'a> {
136 pub(crate) owner: OwnerId,
137 pub(crate) plugin: PluginId,
138 pub(crate) rank: usize,
139 pub(crate) reg: &'a mut Registries,
140 pub(crate) app: &'a AppHandle,
141 pub(crate) connected: &'a [PluginId],
142}
143
144impl fmt::Debug for Ctx<'_> {
145 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
146 f.debug_struct("Ctx").field("plugin", &self.plugin).finish()
147 }
148}
149
150impl<'a> Ctx<'a> {
151 pub fn plugin(&self) -> &PluginId {
153 &self.plugin
154 }
155
156 pub fn owner(&self) -> &OwnerId {
158 &self.owner
159 }
160
161 pub fn app(&self) -> AppHandle {
163 self.app.clone()
164 }
165
166 pub fn writer(&self) -> ValueWriter {
171 ValueWriter::new(self.app.store(), self.owner.clone())
172 }
173
174 pub fn icon(
179 &mut self,
180 name: &str,
181 svg: impl Into<std::sync::Arc<[u8]>>,
182 paint: egui_pop_core::icon_set::Paint,
183 ) -> Result<egui_pop_core::icon::Icon, egui_pop_core::icon_set::IconError> {
184 egui_pop_core::icon_set::register_for(self.plugin.as_str(), name, svg, paint)
185 }
186
187 pub fn is_connected(&self, plugin: &PluginId) -> bool {
189 self.connected.contains(plugin)
190 }
191
192 pub fn command(
197 &mut self,
198 spec: CommandSpec,
199 handler: impl Fn(&Call<'_>) -> Result<Json, String> + 'static,
200 ) -> Result<&mut Self, CtxError> {
201 let handler: CommandFn = Rc::new(handler);
202 self.add_command(spec, Some(handler))
203 }
204
205 pub fn declare(&mut self, spec: CommandSpec) -> Result<&mut Self, CtxError> {
209 self.add_command(spec, None)
210 }
211
212 fn add_command(
213 &mut self,
214 spec: CommandSpec,
215 handler: Option<CommandFn>,
216 ) -> Result<&mut Self, CtxError> {
217 add_command(self.reg, &self.owner, spec, handler)?;
218 Ok(self)
219 }
220
221 pub fn keybinding(
224 &mut self,
225 keys: &str,
226 command: CommandId,
227 when: &str,
228 layer: Layer,
229 ) -> Result<&mut Self, CtxError> {
230 self.reg
231 .keymap
232 .borrow_mut()
233 .bind(&self.owner, layer, keys, Action::Run(command), when)
234 .map_err(|error| CtxError::Keys {
235 keys: keys.into(),
236 error,
237 })?;
238 Ok(self)
239 }
240
241 pub fn keybinding_with(
244 &mut self,
245 keys: &str,
246 command: CommandId,
247 when: &str,
248 layer: Layer,
249 options: BindOptions,
250 ) -> Result<&mut Self, CtxError> {
251 self.reg
252 .keymap
253 .borrow_mut()
254 .bind_with(
255 &self.owner,
256 layer,
257 keys,
258 Action::Run(command),
259 when,
260 options,
261 )
262 .map_err(|error| CtxError::Keys {
263 keys: keys.into(),
264 error,
265 })?;
266 Ok(self)
267 }
268
269 pub fn unbind(&mut self, keys: &str, layer: Layer) -> Result<&mut Self, CtxError> {
271 self.reg
272 .keymap
273 .borrow_mut()
274 .bind(&self.owner, layer, keys, Action::Unbind, "")
275 .map_err(|error| CtxError::Keys {
276 keys: keys.into(),
277 error,
278 })?;
279 Ok(self)
280 }
281
282 pub fn command_icon(
290 &mut self,
291 command: CommandId,
292 icon: &str,
293 icon_on: Option<&str>,
294 ) -> &mut Self {
295 self.reg.command_icons.push(
296 &self.owner,
297 crate::app::CommandIcon {
298 command,
299 icon: icon.into(),
300 icon_on: icon_on.map(Into::into),
301 },
302 );
303 self
304 }
305
306 pub fn menu_item(&mut self, item: MenuItem) -> Result<&mut Self, CtxError> {
308 self.reg
309 .menus
310 .contribute(&self.owner, item)
311 .map_err(CtxError::Menu)?;
312 Ok(self)
313 }
314
315 pub fn list_provider(
319 &mut self,
320 name: &str,
321 f: impl Fn(&AppHandle, &egui_pop_model::when::WhenContext) -> Vec<crate::menus::ListItem>
322 + 'static,
323 ) -> &mut Self {
324 self.app.add_list_provider(
325 &self.owner,
326 crate::menus::Provider {
327 name: name.into(),
328 f: Rc::new(f),
329 },
330 );
331 self
332 }
333
334 pub fn submenu(
336 &mut self,
337 parent: MenuId,
338 group: &str,
339 order: i32,
340 menu: MenuId,
341 label: &str,
342 ) -> Result<&mut Self, CtxError> {
343 self.menu_item(MenuItem::submenu(parent, group, order, menu, label))
344 }
345
346 pub fn panel(
351 &mut self,
352 spec: PanelSpec,
353 draw: impl FnMut(&mut Ui, &AppHandle) + 'static,
354 ) -> Result<&mut Self, CtxError> {
355 let id: PanelId = spec.id.clone();
356 let title = spec.title.clone();
357 self.reg
358 .panels
359 .declare(&self.owner, spec)
360 .map_err(CtxError::Panel)?;
361 self.app.add_panel_view(
362 &self.owner,
363 id.clone(),
364 crate::app::PanelDraw::Plain(Box::new(draw)),
365 );
366 self.panel_commands(id, title)
367 }
368
369 pub fn instance_panel(
380 &mut self,
381 spec: PanelSpec,
382 draw: impl FnMut(&mut Ui, &AppHandle, &crate::workbench::instances::Instance) + 'static,
383 ) -> Result<&mut Self, CtxError> {
384 let spec = spec.instances(egui_pop_model::panels::Instances::Multiple);
385 let id: PanelId = spec.id.clone();
386 let title = spec.title.clone();
387 self.reg
388 .panels
389 .declare(&self.owner, spec)
390 .map_err(CtxError::Panel)?;
391 self.app.add_panel_view(
392 &self.owner,
393 id.clone(),
394 crate::app::PanelDraw::Instance(Box::new(draw)),
395 );
396 self.panel_commands(id, title)
397 }
398
399 fn panel_commands(&mut self, id: PanelId, title: String) -> Result<&mut Self, CtxError> {
401 let command = |suffix: &str| {
402 CommandId::new(format!("{id}.{suffix}")).map_err(|e| CtxError::Panel(e.to_string()))
403 };
404 let (focus, toggle) = (id.clone(), id.clone());
405 let fill = |key: &StrKey| strings::fill(key.fallback, &[("panel", &title)]);
406 let (focus_id, toggle_id) = (command("focus")?, command("toggle")?);
407 self.app.add_panel_commands(
410 [
411 (
412 &focus_id,
413 txt::PANEL_FOCUS_TITLE,
414 txt::PANEL_FOCUS_DESCRIPTION,
415 ),
416 (
417 &toggle_id,
418 txt::PANEL_TOGGLE_TITLE,
419 txt::PANEL_TOGGLE_DESCRIPTION,
420 ),
421 ]
422 .map(|(cmd, title_key, description)| {
423 (
424 cmd.to_string(),
425 strings::PanelCommand {
426 title: title_key,
427 description,
428 panel: id.to_string(),
429 panel_title: title.clone(),
430 },
431 )
432 }),
433 );
434 self.command(
435 CommandSpec::new(focus_id, &fill(&txt::PANEL_FOCUS_TITLE), "View")
436 .description(&fill(&txt::PANEL_FOCUS_DESCRIPTION)),
437 move |call| {
438 call.app.focus_panel(&focus);
439 if !matches!(call.origin, egui_pop_model::commands::Origin::User)
441 && egui_pop_core::focus::text_input_owns_keyboard(&call.app.egui())
442 {
443 call.app.workbench_mut().cancel_focus_request();
444 }
445 Ok(Json::Null)
446 },
447 )?
448 .command(
449 CommandSpec::new(toggle_id, &fill(&txt::PANEL_TOGGLE_TITLE), "View")
450 .description(&fill(&txt::PANEL_TOGGLE_DESCRIPTION)),
451 move |call| {
452 let shown = call.app.panel_visible(&toggle);
453 if shown {
454 call.app.set_panel_visible(&toggle, false);
455 } else {
456 let ask = crate::bus::PanelOpenAsk::new(
458 toggle.as_str(),
459 crate::bus::OpenPlace::Last,
460 crate::bus::OWNER,
461 );
462 call.app.open_panel(ask)?;
463 }
464 Ok(serde_json::json!({ "shown": !shown }))
465 },
466 )?;
467 Ok(self)
468 }
469
470 pub(crate) fn zone_panel(
473 &mut self,
474 spec: PanelSpec,
475 zone: ZoneId,
476 scope: &'static str,
477 ) -> Result<&mut Self, CtxError> {
478 let id = spec.id.clone();
479 self.reg
480 .panels
481 .declare(&self.owner, spec.bare())
482 .map_err(CtxError::Panel)?;
483 self.app
484 .workbench_mut()
485 .zone_of
486 .insert(id.clone(), zone.clone());
487 self.app.add_panel_view(
488 &self.owner,
489 id,
490 crate::app::PanelDraw::Plain(Box::new(move |ui, app| {
491 egui_pop_core::focus::scope(ui, scope, &[], |ui| app.show_zone(ui, &zone));
492 })),
493 );
494 Ok(self)
495 }
496
497 pub fn zone(&mut self, zone: ZoneId, title: &str) -> Result<&mut Self, CtxError> {
499 self.app
500 .zones_mut()
501 .declare(&self.owner, zone.clone(), title)
502 .map_err(|by| CtxError::Zone { zone, by })?;
503 Ok(self)
504 }
505
506 pub fn block(&mut self, zone: ZoneId, block: Block) -> &mut Self {
510 self.app
511 .zones_mut()
512 .contribute(&self.owner, self.rank, zone, block);
513 self
514 }
515
516 pub fn value(&mut self, path: &str, descriptor: Descriptor) -> Result<&mut Self, CtxError> {
540 egui_pop_core::lock(&self.app.store())
541 .declare(&self.owner, path, descriptor)
542 .map_err(CtxError::Setting)?;
543 Ok(self)
544 }
545
546 pub fn setting(
550 &mut self,
551 id: SettingId,
552 descriptor: Descriptor,
553 ) -> Result<&mut Self, CtxError> {
554 let path = id.path();
555 egui_pop_core::lock(&self.app.store())
556 .declare(&self.owner, &path, descriptor)
557 .map_err(CtxError::Setting)?;
558 self.reg
559 .settings
560 .insert(&self.owner, id, path)
561 .map_err(|t| {
562 CtxError::Setting(DeclareError::Taken {
563 path: t.id.path(),
564 by: t.by,
565 })
566 })?;
567 Ok(self)
568 }
569
570 pub fn collector(
572 &mut self,
573 collector: egui_pop_core::debug::FnCollector,
574 ) -> Result<&mut Self, CtxError> {
575 self.app.add_collector(&self.owner, collector)?;
576 Ok(self)
577 }
578
579 pub fn service<T: Send + Sync + 'static>(
581 &mut self,
582 token: &ServiceToken<T>,
583 value: T,
584 ) -> Result<&mut Self, CtxError> {
585 self.app
586 .services_mut()
587 .provide(&self.owner, token, Arc::new(value))
588 .map_err(|by| CtxError::Service {
589 id: token.id().to_string(),
590 by,
591 })?;
592 Ok(self)
593 }
594
595 pub fn local_scope(
605 &mut self,
606 surface: &str,
607 scope: impl crate::history::LocalScope + 'static,
608 ) -> &mut Self {
609 crate::history::register(&self.app(), &self.owner, surface, Rc::new(scope));
610 self
611 }
612
613 pub fn history_target(&mut self, surface: &str, scope: crate::history::ScopeId) -> &mut Self {
626 crate::history::declare_target(&self.app(), &self.owner, surface, scope);
627 self
628 }
629
630 pub fn on(
632 &mut self,
633 when: On,
634 f: impl FnMut(&AppHandle, &crate::hooks::Lifecycle) + 'static,
635 ) -> &mut Self {
636 let f: LifecycleFn = Box::new(f);
637 self.reg.lifecycle.push(&self.owner, (when, f));
638 self
639 }
640
641 pub fn on_change(
643 &mut self,
644 prefix: &str,
645 f: impl FnMut(&egui_pop_model::values::Changed) + Send + 'static,
646 ) -> &mut Self {
647 egui_pop_core::lock(&self.app.store()).listen(&self.owner, prefix, f);
648 self
649 }
650
651 pub fn hook(&mut self, hook: Hook) -> Result<&mut Self, CtxError> {
653 if let Some(s) = self.reg.hooks.iter().find(|s| s.item.id == hook.id) {
654 return Err(CtxError::Hook {
655 id: hook.id.to_string(),
656 by: s.owner.clone(),
657 });
658 }
659 self.reg.hooks.push(&self.owner, hook);
660 Ok(self)
661 }
662
663 pub fn step(&mut self, spec: crate::steps::StepSpec) -> Result<&mut Self, CtxError> {
666 self.app.declare_step(&self.owner, spec)?;
667 Ok(self)
668 }
669
670 pub fn before(
673 &mut self,
674 step: egui_pop_model::ids::StepId,
675 f: impl Fn(&AppHandle, &Json) -> crate::steps::Before + 'static,
676 ) -> &mut Self {
677 self.app
678 .add_step_hook(&self.owner, step, crate::steps::HookFn::Before(Rc::new(f)));
679 self
680 }
681
682 pub fn replace(
685 &mut self,
686 step: egui_pop_model::ids::StepId,
687 f: impl Fn(&AppHandle, &Json) -> Result<Json, String> + 'static,
688 ) -> &mut Self {
689 self.app
690 .add_step_hook(&self.owner, step, crate::steps::HookFn::Run(Rc::new(f)));
691 self
692 }
693
694 pub fn after(
696 &mut self,
697 step: egui_pop_model::ids::StepId,
698 f: impl Fn(&AppHandle, &Json, &Result<Json, String>) + 'static,
699 ) -> &mut Self {
700 self.app
701 .add_step_hook(&self.owner, step, crate::steps::HookFn::After(Rc::new(f)));
702 self
703 }
704
705 pub fn indicator(&mut self, indicator: crate::strips::Indicator) -> &mut Self {
715 if let Some(Err(e)) = indicator.clause() {
716 self.app.warn(
717 "indicator-when",
718 Some(&self.owner),
719 &indicator.id,
720 format!("the `when` clause of the indicator `{}`: {e}", indicator.id),
721 );
722 }
723 self.app.add_indicator(&self.owner, indicator);
724 self
725 }
726
727 pub fn arrangement(&mut self, name: &str, layout: egui_pop_model::layout::Layout) -> &mut Self {
731 self.app
732 .workbench_mut()
733 .templates
734 .push((self.owner.clone(), name.to_string(), layout));
735 self
736 }
737
738 pub fn story(&mut self, story: Story) -> Result<&mut Self, CtxError> {
740 self.app.add_story(&self.owner, story)?;
741 Ok(self)
742 }
743}
744
745pub(crate) fn add_command(
748 reg: &mut Registries,
749 owner: &OwnerId,
750 mut spec: CommandSpec,
751 handler: Option<CommandFn>,
752) -> Result<(), CtxError> {
753 if reg.offered.contains(&spec.id) {
754 spec.agent = true;
756 }
757 for k in &spec.keys {
758 egui_pop_model::keymap::Keys::parse(&k.keys).map_err(|error| CtxError::Keys {
759 keys: k.keys.clone(),
760 error,
761 })?;
762 }
763 let keys = spec.keys.clone();
764 let menus = spec.menus.clone();
765 let id = spec.id.clone();
766 let when = spec.when.clone();
767 let checked = spec.checked.clone();
768 reg.commands
769 .register(owner, spec, handler)
770 .map_err(CtxError::Command)?;
771 for k in keys {
772 reg.keymap
773 .borrow_mut()
774 .bind_with(
775 owner,
776 Layer::Default,
777 &k.keys,
778 Action::Run(id.clone()),
779 &when,
780 k.options,
781 )
782 .map_err(|error| CtxError::Keys {
783 keys: k.keys,
784 error,
785 })?;
786 }
787 for m in menus {
788 reg.menus
789 .contribute(
790 owner,
791 MenuItem::command(m.menu, &m.group, m.order, id.clone())
792 .when(&when, true)
793 .checked(&checked),
794 )
795 .map_err(CtxError::Menu)?;
796 }
797 Ok(())
798}