1use std::collections::BTreeMap;
41
42use egui_pop_core::lock;
43use egui_pop_core::strings::StrKey;
44use egui_pop_model::commands::{CommandSpec, Origin};
45use egui_pop_model::ids::{CommandId, OwnerId, PluginId, StepId};
46use egui_pop_model::layout::{self, Layout};
47use egui_pop_model::values::{Change, Descriptor, Set, Value};
48use serde_json::{Value as Json, json};
49
50use crate::app::{AppHandle, MENU_VIEW};
51use crate::contexts::{self, FrameId, FrameRegistry, State};
52use crate::steps::{Outcome, StepSpec};
53use crate::strings as txt;
54use crate::{Ctx, Plugin, PluginError};
55
56pub const ARRANGEMENTS: &str = "settings/workbench.arrangements";
59pub const CURRENT: &str = "settings/workbench.arrangement";
62pub const CURRENT_BY_FRAME: &str = "settings/workbench.arrangement.frames";
65
66pub const STEP_SAVE: StepId = StepId::from_static("arrangement.save");
67pub const STEP_SWITCH: StepId = StepId::from_static("arrangement.switch");
68pub const STEP_RESET: StepId = StepId::from_static("arrangement.reset");
69pub const STEP_DELETE: StepId = StepId::from_static("arrangement.delete");
70
71pub const CMD_SAVE: CommandId = CommandId::from_static("workbench.arrangement.save");
72pub const CMD_SWITCH: CommandId = CommandId::from_static("workbench.arrangement.switch");
73pub const CMD_RESET: CommandId = CommandId::from_static("workbench.arrangement.reset");
74
75pub const DEFAULT: &str = "Default";
77
78#[derive(Debug, Default)]
80pub struct ArrangementsPlugin;
81
82pub fn saved(app: &AppHandle) -> BTreeMap<String, Layout> {
84 let text = lock(&app.store())
85 .get(ARRANGEMENTS)
86 .and_then(|e| e.value.as_text().map(str::to_string))
87 .unwrap_or_default();
88 let map: BTreeMap<String, Json> = serde_json::from_str(&text).unwrap_or_default();
89 map.into_iter()
90 .filter_map(|(name, doc)| Layout::from_json(&doc.to_string()).ok().map(|l| (name, l)))
91 .collect()
92}
93
94pub fn names(app: &AppHandle) -> Vec<String> {
96 let mut v: Vec<String> = saved(app).into_keys().collect();
97 for t in app.workbench_mut().templates.iter().map(|t| t.1.clone()) {
98 if !v.contains(&t) {
99 v.push(t);
100 }
101 }
102 if !v.iter().any(|n| n == DEFAULT) {
103 v.insert(0, DEFAULT.into());
104 }
105 v
106}
107
108fn text_of(app: &AppHandle, path: &str) -> String {
109 lock(&app.store())
110 .get(path)
111 .and_then(|e| e.value.as_text().map(str::to_string))
112 .unwrap_or_default()
113}
114
115pub fn by_frame(app: &AppHandle) -> BTreeMap<String, String> {
117 serde_json::from_str(&text_of(app, CURRENT_BY_FRAME)).unwrap_or_default()
118}
119
120pub fn arranged_frame(app: &AppHandle) -> Option<(FrameId, Option<String>)> {
124 let svc = app.service(&contexts::CONTEXTS)?;
125 arranged_in(&svc.shown(), &svc.frames())
126}
127
128pub(crate) fn arranged_in(
131 state: &State,
132 frames: &FrameRegistry,
133) -> Option<(FrameId, Option<String>)> {
134 let mode = state.modes.iter().rev().find_map(|m| {
135 frames
136 .get(&m.frame)
137 .and_then(|s| s.arrangement.clone())
138 .map(|a| (m.frame.clone(), Some(a)))
139 });
140 mode.or_else(|| {
141 state.places.last().map(|e| {
142 let declared = frames.get(&e.frame).and_then(|s| {
143 s.arrangement_of(&e.payload)
144 .or_else(|| s.arrangement.clone())
145 });
146 (e.frame.clone(), declared)
147 })
148 })
149}
150
151pub(crate) fn of_frame(
154 app: &AppHandle,
155 frame: &FrameId,
156 declared: Option<String>,
157) -> Option<String> {
158 by_frame(app).remove(frame.as_str()).or(declared)
159}
160
161pub fn current(app: &AppHandle) -> String {
164 let name = match arranged_frame(app) {
165 Some((frame, declared)) => of_frame(app, &frame, declared).unwrap_or_default(),
166 None => text_of(app, CURRENT),
167 };
168 if name.is_empty() {
169 DEFAULT.into()
170 } else {
171 name
172 }
173}
174
175fn set_current(app: &AppHandle, name: &str) -> Result<(), String> {
177 match arranged_frame(app) {
178 Some((frame, _)) => {
179 let mut map = by_frame(app);
180 map.insert(frame.to_string(), name.to_string());
181 write(app, CURRENT_BY_FRAME, json!(map).to_string())
182 }
183 None => write(app, CURRENT, name.to_string()),
184 }
185}
186
187pub fn layout_of(app: &AppHandle, name: &str) -> Option<Layout> {
190 saved(app)
191 .remove(name)
192 .or_else(|| app.workbench_mut().template(name))
193 .or_else(|| (name == DEFAULT).then(Layout::default))
194}
195
196fn write(app: &AppHandle, path: &str, text: String) -> Result<(), String> {
197 lock(&app.store())
198 .set(
199 Set::new(path, Change::To(Value::Text(text)), Origin::User)
200 .by(&OwnerId::FRAMEWORK)
201 .untracked()
202 .force(),
203 )
204 .map(|_| ())
205 .map_err(|e| e.to_string())
206}
207
208fn write_saved(app: &AppHandle, map: &BTreeMap<String, Layout>) -> Result<(), String> {
209 let docs: BTreeMap<&String, Json> = map
210 .iter()
211 .map(|(n, l)| {
212 let doc = layout::schema().save(l).unwrap_or_default();
213 (n, serde_json::from_str(&doc).unwrap_or(Json::Null))
214 })
215 .collect();
216 write(app, ARRANGEMENTS, json!(docs).to_string())
217}
218
219fn name_of(args: &Json) -> Result<String, String> {
220 let n = args
221 .get("name")
222 .and_then(Json::as_str)
223 .map(str::trim)
224 .unwrap_or_default();
225 if n.is_empty() {
226 Err("an arrangement needs a name".into())
227 } else {
228 Ok(n.to_string())
229 }
230}
231
232pub fn save(app: &AppHandle, name: &str) -> Outcome {
234 app.step(&STEP_SAVE, json!({ "name": name }), |app, args| {
235 let name = name_of(args)?;
236 let mut map = saved(app);
237 map.insert(name.clone(), app.layout());
238 write_saved(app, &map)?;
239 set_current(app, &name)?;
240 Ok(json!({ "saved": name }))
241 })
242}
243
244pub fn switch(app: &AppHandle, name: &str) -> Outcome {
247 app.step(&STEP_SWITCH, json!({ "name": name }), |app, args| {
248 let name = name_of(args)?;
249 let layout = layout_of(app, &name).ok_or_else(|| format!("no arrangement `{name}`"))?;
250 let notes = app.set_layout(layout);
251 set_current(app, &name)?;
252 Ok(json!({ "switched": name, "repaired": notes }))
253 })
254}
255
256pub fn reset(app: &AppHandle) -> Outcome {
260 let name = current(app);
261 app.step(&STEP_RESET, json!({ "name": name }), |app, args| {
262 let name = name_of(args)?;
263 let layout = app.workbench_mut().template(&name).unwrap_or_default();
264 let mut map = saved(app);
265 map.remove(&name);
266 write_saved(app, &map)?;
267 let notes = app.set_layout(layout);
268 Ok(json!({ "reset": name, "repaired": notes }))
269 })
270}
271
272pub fn delete(app: &AppHandle, name: &str) -> Outcome {
274 app.step(&STEP_DELETE, json!({ "name": name }), |app, args| {
275 let name = name_of(args)?;
276 let mut map = saved(app);
277 if map.remove(&name).is_none() {
278 return Err(format!("no saved arrangement `{name}`"));
279 }
280 write_saved(app, &map)?;
281 if text_of(app, CURRENT) == name {
282 write(app, CURRENT, DEFAULT.into())?;
283 }
284 let mut frames = by_frame(app);
286 let before = frames.len();
287 frames.retain(|_, n| *n != name);
288 if frames.len() != before {
289 write(app, CURRENT_BY_FRAME, json!(frames).to_string())?;
290 }
291 Ok(json!({ "deleted": name }))
292 })
293}
294
295#[derive(Clone, Copy, Debug, PartialEq, Eq)]
318#[non_exhaustive]
319pub struct ArrangementStrings {
320 pub save_as: StrKey,
322 pub save_title: StrKey,
324 pub save_verb: StrKey,
326 pub suggested: StrKey,
328}
329
330impl ArrangementStrings {
331 pub const fn new(
332 save_as: StrKey,
333 save_title: StrKey,
334 save_verb: StrKey,
335 suggested: StrKey,
336 ) -> Self {
337 Self {
338 save_as,
339 save_title,
340 save_verb,
341 suggested,
342 }
343 }
344}
345
346impl Default for ArrangementStrings {
347 fn default() -> Self {
348 Self::new(
349 txt::LAYOUT_SAVE_AS,
350 txt::ARRANGEMENT_SAVE_TITLE,
351 txt::ARRANGEMENT_SAVE_VERB,
352 txt::ARRANGEMENT_SUGGESTED,
353 )
354 }
355}
356
357pub fn ask_name(app: &AppHandle) -> bool {
361 let Some(dialogs) = app.service(&crate::dialogs::DIALOGS) else {
362 return false;
363 };
364 let ctx = app.egui();
365 let tr = |key| egui_pop_core::strings::tr(&ctx, key);
366 let words = app.arrangement_strings();
367 let taken = names(app);
368 let suggested = (saved(app).len() + 1..)
369 .map(|n| egui_pop_core::strings::tr_with(&ctx, &words.suggested, &[("n", n.into())]))
370 .find(|n| !taken.contains(n))
371 .unwrap_or_default();
372 let mut form =
373 crate::dialogs::Form::new(&tr(&words.save_title), &tr(&words.save_verb), CMD_SAVE).field(
374 "name",
375 Descriptor::text(&tr(&txt::ARRANGEMENT_NAME), &suggested),
376 );
377 form.args = json!({ "asked": true });
380 dialogs.open(form);
381 true
382}
383
384fn outcome(o: Outcome) -> Result<Json, String> {
385 match o {
386 Outcome::Done(r) => r,
387 Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
388 }
389}
390
391impl Plugin for ArrangementsPlugin {
392 fn id(&self) -> PluginId {
393 PluginId::from_static("egui_pop.arrangements")
394 }
395
396 fn title(&self) -> String {
397 "Arrangements".into()
398 }
399
400 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
401 let owner = ctx.owner().clone();
402 {
403 let store = ctx.app().store();
404 let mut s = lock(&store);
405 s.declare(&owner, ARRANGEMENTS, Descriptor::text("Arrangements", "{}"))
406 .map_err(|e| PluginError::Failed(e.to_string()))?;
407 s.declare(&owner, CURRENT, Descriptor::text("Arrangement", DEFAULT))
408 .map_err(|e| PluginError::Failed(e.to_string()))?;
409 s.declare(
410 &owner,
411 CURRENT_BY_FRAME,
412 Descriptor::text("Arrangement by place and mode", "{}"),
413 )
414 .map_err(|e| PluginError::Failed(e.to_string()))?;
415 }
416 for spec in [
417 StepSpec::new(STEP_SAVE, "The workbench's layout is saved under a name.")
418 .args(json!({ "name": "Writing" })),
419 StepSpec::new(
420 STEP_SWITCH,
421 "The workbench switches to a named arrangement.",
422 )
423 .args(json!({ "name": "Writing" })),
424 StepSpec::new(
425 STEP_RESET,
426 "The current arrangement goes back to its template.",
427 )
428 .args(json!({ "name": "Writing" })),
429 StepSpec::new(STEP_DELETE, "A saved arrangement is forgotten.")
430 .args(json!({ "name": "Writing" })),
431 ] {
432 ctx.step(spec)?;
433 }
434 ctx.command(
435 CommandSpec::new(CMD_SAVE, "Save the arrangement as...", "View")
436 .description("Saves the panels' places under a name.")
437 .args(json!({ "name": "" }))
438 .menu(MENU_VIEW, "3_layout", 10),
439 |call| {
440 let name = call
441 .args
442 .get("name")
443 .and_then(Json::as_str)
444 .unwrap_or_default();
445 let asked = call.args.get("asked").and_then(Json::as_bool) == Some(true);
446 if name.trim().is_empty() && !asked && ask_name(call.app) {
447 return Ok(json!({ "asked": true }));
448 }
449 outcome(save(call.app, name))
450 },
451 )?
452 .command(
453 CommandSpec::new(CMD_SWITCH, "Switch arrangement", "View")
454 .description("Puts the panels as a saved arrangement or a template has them.")
455 .args(json!({ "name": "" }))
456 .menu(MENU_VIEW, "3_layout", 11),
457 |call| {
458 let name = call
459 .args
460 .get("name")
461 .and_then(Json::as_str)
462 .unwrap_or_default();
463 outcome(switch(call.app, name))
464 },
465 )?
466 .command(
467 CommandSpec::new(CMD_RESET, "Reset the arrangement", "View")
468 .icon("reset")
469 .description("Puts the panels back as the current arrangement's template has them.")
470 .menu(MENU_VIEW, "3_layout", 12),
471 |call| outcome(reset(call.app)),
472 )?;
473 Ok(())
474 }
475}