Skip to main content

egui_pop_api/bus/
panel_open.rs

1//! A panel opened on the bus (ADR 0029): `pop.panel.open` is the one way
2//! to open a panel, whoever asks: a menu, a tab bar's "+", a group's menu,
3//! the `<panel>.toggle` command, an agent or a test.
4//!
5//! The ask names the panel and where it opens ([`OpenPlace`]):
6//!
7//! - `last`: where it was when it closed (its area among the same tabs, at
8//!   its index; its window; its float). That place gone (the tabs it sat
9//!   with are gone), it joins the current group, the focused panel's tabs,
10//!   when its areas allow it there, else its declared area. A panel
11//!   already open is shown where it is.
12//! - `here`: in the tab group holding `group` (any panel of it, docked,
13//!   floating or detached), else in the focused panel's; moved there when
14//!   it is open elsewhere.
15//! - an area (`start_side`, …): docked there.
16//!
17//! The workbench's listener ([`PANEL_OPEN`]) runs the `workbench.show`
18//! step, so a plugin may veto it, and the layout's change is said as
19//! `pop.layout.changed`. For a panel declared with several
20//! (`PanelSpec::instances`), `instance` names which opens: `"new"` makes
21//! the next instance (`<panel>#<n>`) and opens it at `place`, an
22//! instance's id opens that one.
23
24use bus_contract::{Bus, ListenOpts, Point, PointId, PointKind};
25use egui_pop_model::ids::PanelId;
26use egui_pop_model::panels::Area;
27use serde::{Deserialize, Deserializer, Serialize, Serializer};
28
29use super::{OWNER, asking};
30use crate::steps::Outcome;
31use crate::workbench::{Change, area_from, area_name};
32
33/// Where a panel opens ([`PanelOpenAsk::place`]). Written `"last"`,
34/// `"here"` or an area's name (`"start_side"`, `"end_side"`, `"bottom"`,
35/// `"center"`).
36#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
37#[non_exhaustive]
38pub enum OpenPlace {
39    /// Where it was when it closed; that place gone, the current group
40    /// when its areas allow it, else its declared area.
41    #[default]
42    Last,
43    /// In the tab group holding [`PanelOpenAsk::group`], else the focused
44    /// panel's.
45    Here,
46    /// Docked in an area.
47    Area(Area),
48}
49
50impl OpenPlace {
51    /// Its name in an ask or a step's arguments.
52    pub fn as_str(self) -> &'static str {
53        match self {
54            OpenPlace::Last => "last",
55            OpenPlace::Here => "here",
56            OpenPlace::Area(a) => area_name(a),
57        }
58    }
59
60    /// A place from its name.
61    pub fn parse(name: &str) -> Option<OpenPlace> {
62        match name {
63            "last" => Some(OpenPlace::Last),
64            "here" => Some(OpenPlace::Here),
65            other => area_from(other).map(OpenPlace::Area),
66        }
67    }
68}
69
70impl Serialize for OpenPlace {
71    fn serialize<S: Serializer>(&self, s: S) -> Result<S::Ok, S::Error> {
72        s.serialize_str(self.as_str())
73    }
74}
75
76impl<'de> Deserialize<'de> for OpenPlace {
77    fn deserialize<D: Deserializer<'de>>(d: D) -> Result<Self, D::Error> {
78        let name = String::deserialize(d)?;
79        OpenPlace::parse(&name).ok_or_else(|| {
80            serde::de::Error::custom(format!(
81                "no place `{name}` (`last`, `here` or an area's name)"
82            ))
83        })
84    }
85}
86
87/// A panel asked open: which panel, where, and who asks.
88///
89/// ```
90/// use egui_pop_api::bus::{OpenPlace, PanelOpenAsk};
91///
92/// let ask = PanelOpenAsk::new("app.outline", OpenPlace::Here, "app").group("app.inspector");
93/// let json = serde_json::to_value(&ask).unwrap();
94/// assert_eq!(json["place"], "here");
95/// assert_eq!(json["group"], "app.inspector");
96/// ```
97///
98/// Need (layout): open a closed panel again where it was, or in a given tab group.
99#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
100#[non_exhaustive]
101pub struct PanelOpenAsk {
102    /// The panel's id.
103    pub panel: String,
104    /// Where it opens; `last` when not given.
105    #[serde(default)]
106    pub place: OpenPlace,
107    /// For [`OpenPlace::Here`]: a panel of the tab group it joins; the
108    /// focused panel's group when not given.
109    #[serde(default, skip_serializing_if = "Option::is_none")]
110    pub group: Option<String>,
111    /// For a panel declared with several: `"new"` opens a new instance,
112    /// an instance's id (`<panel>#<n>`) that one; the panel itself when
113    /// not given.
114    #[serde(default, skip_serializing_if = "Option::is_none")]
115    pub instance: Option<String>,
116    /// Who asks: a plugin's id, a menu's, an agent's.
117    pub owner: String,
118    /// The application window it is asked from, by id (`main` for the
119    /// main window): where it opens when its last place is in no window
120    /// shown (rule A). Menus, commands and keys fill it in with the
121    /// window they run in when not given.
122    #[serde(default, skip_serializing_if = "Option::is_none")]
123    pub origin: Option<String>,
124}
125
126impl PanelOpenAsk {
127    pub fn new(panel: impl Into<String>, place: OpenPlace, owner: impl Into<String>) -> Self {
128        Self {
129            panel: panel.into(),
130            place,
131            group: None,
132            instance: None,
133            owner: owner.into(),
134            origin: None,
135        }
136    }
137
138    /// The window it is asked from, by id.
139    pub fn origin(mut self, window: impl Into<String>) -> Self {
140        self.origin = Some(window.into());
141        self
142    }
143
144    /// Which instance opens: `"new"`, or an instance's id.
145    pub fn instance(mut self, instance: impl Into<String>) -> Self {
146        self.instance = Some(instance.into());
147        self
148    }
149
150    /// The tab group it joins, by one of its panels ([`OpenPlace::Here`]).
151    pub fn group(mut self, panel: impl Into<String>) -> Self {
152        self.group = Some(panel.into());
153        self
154    }
155}
156
157/// A panel is asked open (`pop.panel.open`); its listeners say what they
158/// did, one line each, in the value.
159#[derive(Debug)]
160pub struct PanelOpen;
161impl Point for PanelOpen {
162    const KIND: PointKind = PointKind::Request;
163    const ID: PointId = PointId::new("pop.panel.open");
164    type Input = PanelOpenAsk;
165    type Value = Vec<String>;
166}
167
168/// Where a panel opening goes, asked of the application
169/// ([`PanelHome`]): the panel and the window it is asked from.
170#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
171#[non_exhaustive]
172pub struct PanelHomeAsk {
173    /// The panel's id.
174    pub panel: String,
175    /// The window the opening is asked from, by id.
176    #[serde(default, skip_serializing_if = "Option::is_none")]
177    pub origin: Option<String>,
178}
179
180/// The window a panel opening goes to (`pop.panel.home`), the
181/// application's choice over rule A: the value is a window's id (`main`
182/// for the main window), `None` while no listener picks one. A window
183/// that is not shown is passed over. egui-pop has no listener of its own.
184#[derive(Debug)]
185pub struct PanelHome;
186impl Point for PanelHome {
187    const KIND: PointKind = PointKind::Alter;
188    const ID: PointId = PointId::new("pop.panel.home");
189    type Input = PanelHomeAsk;
190    type Value = Option<String>;
191}
192
193/// Which area a panel opening goes to, asked of the application
194/// ([`PanelHomeArea`]): the panel and the window it opens in.
195#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
196#[non_exhaustive]
197pub struct PanelHomeAreaAsk {
198    /// The panel's id.
199    pub panel: String,
200    /// The window it opens in, by id (`main` for the main window): the
201    /// one `pop.panel.home` answered, else the one it is asked from.
202    pub window: String,
203}
204
205/// The area a panel opening docks in (`pop.panel.home_area`), the
206/// application's choice over the panel's declared area: asked after
207/// [`PanelHome`], so an application answering a window there may answer
208/// its area here. `None` while no listener picks one: the declared area.
209/// Used where the declared area would be (a panel back to its last place
210/// stays there; an area named by the ask wins); an area the panel's rules
211/// refuse is passed over. egui-pop has no listener of its own.
212#[derive(Debug)]
213pub struct PanelHomeArea;
214impl Point for PanelHomeArea {
215    const KIND: PointKind = PointKind::Alter;
216    const ID: PointId = PointId::new("pop.panel.home_area");
217    type Input = PanelHomeAreaAsk;
218    type Value = Option<Area>;
219}
220
221/// The panel opening points, in the order [`super::order_dump`] prints
222/// them.
223pub const PANEL_OPEN_POINTS: [&str; 3] = [
224    PanelOpen::ID.as_str(),
225    PanelHome::ID.as_str(),
226    PanelHomeArea::ID.as_str(),
227];
228
229/// The workbench's listener of `pop.panel.open`: opens the panel through
230/// the `workbench.show` step.
231pub const PANEL_OPEN: &str = "pop.workbench.panel_open";
232
233/// Registers the workbench's listener of `pop.panel.open`.
234pub(super) fn install(kernel: &dyn Bus) {
235    let listened =
236        kernel.listen::<PanelOpen>(PANEL_OPEN, ListenOpts::new().owner(OWNER), |ask, did| {
237            let Some(app) = asking() else {
238                return Ok(());
239            };
240            let panel = PanelId::new(&ask.panel).map_err(|e| e.to_string())?;
241            let group = match &ask.group {
242                Some(g) => Some(PanelId::new(g).map_err(|e| e.to_string())?),
243                None => None,
244            };
245            // An instance named opens as the panel it is.
246            let panel = match ask.instance.as_deref() {
247                None | Some("new") => panel,
248                Some(id) => {
249                    let id = PanelId::new(id).map_err(|e| e.to_string())?;
250                    if id.kind() != panel.kind() {
251                        return Err(format!("`{id}` is no instance of `{panel}`").into());
252                    }
253                    id
254                }
255            };
256            let change = match (ask.instance.as_deref(), ask.place, group) {
257                (Some("new"), place, group) => Change::NewInstance(panel.clone(), place, group),
258                (_, OpenPlace::Last, _) => Change::Show(panel.clone()),
259                (_, place, group) => Change::Open(panel.clone(), place, group),
260            };
261            // The window it is asked from, and the application's choice.
262            let origin = ask
263                .origin
264                .clone()
265                .unwrap_or_else(|| crate::workbench::window_areas::current_window(&app));
266            let home = super::emit_with::<PanelHome>(
267                &app,
268                PanelHomeAsk {
269                    panel: panel.to_string(),
270                    origin: Some(origin.clone()),
271                },
272                None,
273            );
274            let area = super::emit_with::<PanelHomeArea>(
275                &app,
276                PanelHomeAreaAsk {
277                    panel: panel.to_string(),
278                    window: home.clone().unwrap_or_else(|| origin.clone()),
279                },
280                None,
281            );
282            let from = crate::workbench::window_areas::OpenFrom {
283                origin: Some(origin),
284                home,
285                area,
286            };
287            match app.change_workbench_from(change, Some(from)) {
288                Some(Outcome::Done(Ok(out))) => {
289                    let opened = out
290                        .get("instance")
291                        .and_then(serde_json::Value::as_str)
292                        .map_or_else(|| panel.to_string(), str::to_string);
293                    did.push(format!("{PANEL_OPEN}: `{opened}` opened"));
294                    Ok(())
295                }
296                Some(Outcome::Done(Err(e))) => Err(e.into()),
297                Some(Outcome::Vetoed { by, reason }) => {
298                    Err(format!("stopped by `{by}`: {reason}").into())
299                }
300                None => {
301                    did.push(format!("{PANEL_OPEN}: `{panel}` queued"));
302                    Ok(())
303                }
304            }
305        });
306    debug_assert!(listened.is_ok(), "{listened:?}");
307}