Skip to main content

egui_pop_api/
arrangements.rs

1//! Arrangements, as a plugin ([`ArrangementsPlugin`], in
2//! `DefaultPlugins`): named layouts of the workbench, saved, switched
3//! and reset. They are kept in the host's store
4//! (`settings/workbench.arrangements`, one versioned layout document per
5//! name, and `settings/workbench.arrangement`, the current name), so they
6//! are saved with the settings, or wherever a host keeps its store.
7//!
8//! <div class="warning">Experimental: may change in any release
9//! (docs/stability.md).</div>
10//!
11//! With the context stack (ADR 0012), the current arrangement is the
12//! **arranged frame's**: the last active mode that declares an
13//! arrangement (`FrameSpec::arrangement`), else the top place, else the
14//! root. The root's name stays in `settings/workbench.arrangement`, as
15//! it always was; each place's and mode's in
16//! `settings/workbench.arrangement.frames` (a JSON object, frame id to
17//! name), written when the user switches or saves there. A frame the
18//! user never arranged starts from the arrangement it declares. Settings
19//! files written before keep their meaning: their name is the root's.
20//!
21//! Applications offer **templates**, named layouts of their own
22//! (`Ctx::arrangement`, owned by the plugin): switching to one starts from it, and resetting the
23//! current arrangement goes back to its template (or to every panel in
24//! its default area). A saved layout is repaired against today's panels
25//! when switched to (ADR 0003: what changed is said).
26//!
27//! Saving without a name (`workbench.arrangement.save` with `name`
28//! empty, as the View menu and the layout menu run it) asks for one in
29//! a dialog, a new name suggested, when the dialogs plugin is there.
30//!
31//! Steps (ADR 0011), each with its default:
32//!
33//! | Step | Arguments |
34//! |---|---|
35//! | `arrangement.save` | `{ "name" }` |
36//! | `arrangement.switch` | `{ "name" }` |
37//! | `arrangement.reset` | `{ "name" }` (the current one) |
38//! | `arrangement.delete` | `{ "name" }` |
39
40use 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
56/// Where the saved arrangements are: a JSON object, name to layout
57/// document.
58pub const ARRANGEMENTS: &str = "settings/workbench.arrangements";
59/// The current arrangement's name at the root of the context stack (the
60/// whole application without it).
61pub const CURRENT: &str = "settings/workbench.arrangement";
62/// The current arrangement of each place and arranged mode of the
63/// context stack: a JSON object, frame id to name.
64pub 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
75/// The name of the arrangement every application starts with.
76pub const DEFAULT: &str = "Default";
77
78/// The plugin.
79#[derive(Debug, Default)]
80pub struct ArrangementsPlugin;
81
82/// The saved arrangements, by name.
83pub 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
94/// Every name to switch to: the saved ones and the templates.
95pub 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
115/// The current arrangement of each frame the user arranged.
116pub fn by_frame(app: &AppHandle) -> BTreeMap<String, String> {
117    serde_json::from_str(&text_of(app, CURRENT_BY_FRAME)).unwrap_or_default()
118}
119
120/// The frame of the context stack whose arrangement is shown: the last
121/// active mode declaring an arrangement, else the top place; `None` at
122/// the root (or without the stack). With the arrangement it declares.
123pub 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
128/// [`arranged_frame`] of a state. A place declares the arrangement its
129/// payload chooses (`FrameSpec::arrangement_for`), else its own.
130pub(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
151/// A frame's current arrangement: the one the user chose there, else the
152/// one it declares.
153pub(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
161/// The current arrangement's name: the arranged frame's (see
162/// [`arranged_frame`]), else the root's.
163pub 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
175/// Makes `name` the current arrangement where the user is.
176fn 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
187/// The layout an arrangement names: a saved one, else a template, else
188/// every panel in its default area for [`DEFAULT`].
189pub 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
232/// Saves the workbench's layout as `name` (`arrangement.save`).
233pub 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
244/// Switches to an arrangement (`arrangement.switch`): a saved one, else
245/// a template.
246pub 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
256/// Puts the current arrangement back as its template has it (or every
257/// panel in its default area), forgetting what was saved under its name
258/// (`arrangement.reset`).
259pub 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
272/// Forgets a saved arrangement (`arrangement.delete`).
273pub 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        // The frames that were on it go back to what they declare.
285        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/// The texts that name an arrangement, which an application may word its
296/// own way (`AppBuilder::arrangement_strings`): "Save the current
297/// arrangement as…" in the layout menu, the save dialog's title and
298/// button, and the name it suggests (`{ $n }`: one more than the saved
299/// ones). Whole strings, not a word put into egui-pop's sentences, so
300/// each language keeps its grammar. By default egui-pop's own.
301///
302/// ```
303/// use egui_pop_api::arrangements::ArrangementStrings;
304/// use egui_pop_core::strings::StrKey;
305///
306/// let studio = ArrangementStrings::new(
307///     StrKey::new("app-studio-save-as", "Save the Studio layout as…"),
308///     StrKey::new("app-studio-save-title", "Save the Studio layout"),
309///     StrKey::new("app-studio-save-verb", "Save the layout"),
310///     StrKey::new("app-studio-suggested", "Studio layout { $n }"),
311/// );
312/// assert_ne!(studio, ArrangementStrings::default());
313/// ```
314///
315/// <div class="warning">Experimental: may change in any release
316/// (docs/stability.md).</div>
317#[derive(Clone, Copy, Debug, PartialEq, Eq)]
318#[non_exhaustive]
319pub struct ArrangementStrings {
320    /// The layout menu's entry saving the current arrangement.
321    pub save_as: StrKey,
322    /// The save dialog's title.
323    pub save_title: StrKey,
324    /// The save dialog's button.
325    pub save_verb: StrKey,
326    /// The name the dialog suggests, with `{ $n }`.
327    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
357/// Asks for the name to save the current arrangement under, in a form
358/// that runs `workbench.arrangement.save` with it; `false` without the
359/// dialogs plugin.
360pub 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    // Answered, the save runs with the name, empty or not: never asked
378    // again.
379    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}