egui_pop_api/workbench/instances.rs
1//! Panel instances: a panel declared with several
2//! ([`PanelSpec::instances`](egui_pop_model::panels::PanelSpec::instances),
3//! [`Instances::Multiple`])
4//! opens as many times as asked.
5//!
6//! <div class="warning">Experimental: may change in any release
7//! (docs/stability.md).</div>
8//!
9//! The panel declared is instance 1; each new one is `<kind>#<n>`
10//! ([`PanelId::instance`]), still a [`PanelId`], so the dock, the focus,
11//! the fault boundary and the panel menu treat it as any panel. One draw
12//! function draws them all ([`Ctx::instance_panel`](crate::Ctx::instance_panel)),
13//! told which [`Instance`] it draws. Each instance holds a payload the
14//! application owns (opaque JSON): kept in the layout
15//! (`Layout::instances`), saved with it and handed back on restore
16//! ([`AppHandle::instance_payload`], [`AppHandle::set_instance_payload`]).
17//!
18//! `pop.panel.open` with `instance: "new"` opens a new one where it is
19//! asked; closing an instance drops it with its payload (closing the
20//! panel declared keeps its place, as any panel's). The journal says
21//! both: `panel.instance.opened` and `panel.instance.closed`
22//! (`{ "panel": <id>, "kind": <kind> }`).
23//!
24//! An instance's tab title is the kind's with its number ("Gallery 2")
25//! until the application names it: `pop.panel.retitle`
26//! ([`AppHandle::set_instance_title`]) keeps the title in the layout's
27//! instance entry, saved and restored with it, and `null` gives the
28//! generated one back. The journal says `panel.instance.retitled`
29//! (`{ "panel": <id>, "kind": <kind>, "title": <title or null> }`).
30
31use std::collections::BTreeSet;
32
33use egui::Ui;
34use egui_pop_model::ids::PanelId;
35use egui_pop_model::panels::Instances;
36use serde_json::{Value as Json, json};
37
38use crate::app::AppHandle;
39
40/// Draws an instance of a panel declared with several.
41pub type InstanceDrawFn = Box<dyn FnMut(&mut Ui, &AppHandle, &Instance)>;
42
43/// The instance a panel's draw function draws.
44#[derive(Clone, Debug, PartialEq, Eq)]
45#[non_exhaustive]
46pub struct Instance {
47 /// The panel declared (`app.gallery`).
48 pub kind: PanelId,
49 /// This instance's id: the kind for instance 1, else `<kind>#<n>`.
50 pub id: PanelId,
51 /// Its number, from 1.
52 pub number: u32,
53 /// Its title as shown: the one the application named
54 /// ([`AppHandle::set_instance_title`]), else the generated one
55 /// ("Gallery 2").
56 pub title: String,
57}
58
59impl Instance {
60 pub(crate) fn of(id: &PanelId, title: &str) -> Instance {
61 Instance {
62 kind: id.kind(),
63 id: id.clone(),
64 number: id.instance_number(),
65 title: title.to_string(),
66 }
67 }
68}
69
70/// The journal's event when an instance opens.
71pub const EVENT_OPENED: &str = "panel.instance.opened";
72/// The journal's event when an instance closes (its payload dropped).
73pub const EVENT_CLOSED: &str = "panel.instance.closed";
74/// The journal's event when an instance's title changes
75/// (`pop.panel.retitle`); `title` is `null` when the generated one is back.
76pub const EVENT_RETITLED: &str = "panel.instance.retitled";
77
78/// The instances open now (`<kind>#<n>`).
79pub(crate) fn open_ids(app: &AppHandle) -> BTreeSet<PanelId> {
80 app.workbench_mut()
81 .specs
82 .iter()
83 .filter(|s| s.id.is_instance())
84 .map(|s| s.id.clone())
85 .collect()
86}
87
88/// Says on the journal the instances opened and closed since `before`.
89pub(crate) fn say(app: &AppHandle, before: &BTreeSet<PanelId>) {
90 let now = open_ids(app);
91 for id in now.difference(before) {
92 app.publish(
93 "egui_pop",
94 None,
95 EVENT_OPENED,
96 json!({ "panel": id, "kind": id.kind() }),
97 );
98 }
99 for id in before.difference(&now) {
100 app.publish(
101 "egui_pop",
102 None,
103 EVENT_CLOSED,
104 json!({ "panel": id, "kind": id.kind() }),
105 );
106 }
107}
108
109impl AppHandle {
110 /// The payload the application keeps for a panel instance (`Null`
111 /// when it has none): as it was set, or as the layout restored it.
112 ///
113 /// <div class="warning">Experimental: may change in any release
114 /// (docs/stability.md).</div>
115 pub fn instance_payload(&self, id: &PanelId) -> Json {
116 self.workbench_mut()
117 .layout
118 .instance(id)
119 .map(|i| i.payload.clone())
120 .unwrap_or(Json::Null)
121 }
122
123 /// Sets the payload of a panel instance open now (or of the panel
124 /// declared, instance 1, of a kind declared with several), saved with
125 /// the layout. The layout's change is said (`pop.layout.changed`).
126 ///
127 /// <div class="warning">Experimental: may change in any release
128 /// (docs/stability.md).</div>
129 pub fn set_instance_payload(&self, id: &PanelId, payload: Json) -> Result<(), String> {
130 {
131 let mut wb = self.workbench_mut();
132 let multiple = wb
133 .spec(&id.kind())
134 .is_some_and(|s| s.instances == Instances::Multiple);
135 if !multiple || wb.spec(id).is_none() {
136 return Err(format!(
137 "`{id}` is no open instance of a panel declared with several"
138 ));
139 }
140 if wb.layout.instance(id).is_some_and(|i| i.payload == payload) {
141 return Ok(());
142 }
143 wb.layout.instance_mut(id).payload = payload;
144 }
145 self.note_layout("panel.instance.payload");
146 Ok(())
147 }
148
149 /// Names the tab title of a panel instance open now (`<kind>#<n>`),
150 /// through `pop.panel.retitle`; `None` gives the generated title
151 /// back ("Gallery 2"). The title is kept in the layout's instance
152 /// entry, saved and restored with it, and read by the tab, the panel
153 /// menu, the View menu, accessibility and [`Instance::title`]. The
154 /// panel declared, a panel declared once and an instance not open are
155 /// refused with the reason, as a blank title is.
156 ///
157 /// <div class="warning">Experimental: may change in any release
158 /// (docs/stability.md).</div>
159 pub fn set_instance_title(&self, id: &PanelId, title: Option<String>) -> Result<(), String> {
160 self.retitle_panel(crate::bus::PanelRetitleAsk::new(id.as_str(), title))
161 .map(|_| ())
162 }
163
164 /// The workbench's answer to `pop.panel.retitle`: keeps the title in
165 /// the instance's layout entry; whether it changed.
166 pub(crate) fn retitle_instance(
167 &self,
168 id: &PanelId,
169 title: Option<String>,
170 ) -> Result<bool, String> {
171 let title = match title {
172 Some(t) if t.trim().is_empty() => {
173 return Err(format!(
174 "`{id}`: a title cannot be blank (null gives the generated one back)"
175 ));
176 }
177 t => t,
178 };
179 {
180 let Some(mut wb) = self.try_workbench() else {
181 return Err(format!("`{id}`: the workbench is busy"));
182 };
183 let multiple = wb
184 .spec(&id.kind())
185 .is_some_and(|s| s.instances == Instances::Multiple);
186 if !multiple {
187 return Err(format!(
188 "`{id}` is no instance of a panel declared with several"
189 ));
190 }
191 if !id.is_instance() {
192 return Err(format!(
193 "`{id}` is the panel declared: only its instances `<kind>#<n>` take a title"
194 ));
195 }
196 if wb.spec(id).is_none() {
197 return Err(format!("`{id}` is no open instance"));
198 }
199 if wb.layout.instance(id).and_then(|i| i.title.as_ref()) == title.as_ref() {
200 return Ok(false);
201 }
202 wb.layout.instance_mut(id).title = title.clone();
203 wb.follow_instances();
204 }
205 self.publish(
206 "egui_pop",
207 None,
208 EVENT_RETITLED,
209 json!({ "panel": id, "kind": id.kind(), "title": title }),
210 );
211 self.note_layout("panel.instance.title");
212 Ok(true)
213 }
214
215 /// The instances of a panel declared with several, open now, the
216 /// panel declared first when it shows.
217 ///
218 /// <div class="warning">Experimental: may change in any release
219 /// (docs/stability.md).</div>
220 pub fn panel_instances(&self, kind: &PanelId) -> Vec<PanelId> {
221 let kind = kind.kind();
222 let mut wb = self.workbench_mut();
223 let mut out: Vec<PanelId> = wb
224 .specs
225 .iter()
226 .filter(|s| s.id.is_instance() && s.id.kind() == kind)
227 .map(|s| s.id.clone())
228 .collect();
229 out.sort_by_key(PanelId::instance_number);
230 if wb.shows(&kind) {
231 out.insert(0, kind);
232 }
233 out
234 }
235}