Skip to main content

egui_pop_api/admin/
focus.rs

1//! The focus the Settings edit: whose host values (a library's, a
2//! workspace's...) the Settings show and write, when the host has several
3//! windows that each have their own.
4//!
5//! The host names its foci ([`SettingsFoci::foci`]): an id, a label, the
6//! application windows that belong to each. Opened from a window
7//! (`admin.open`), the Settings edit that window's focus; a header above
8//! the page names it and a switch picks another, shown once there are
9//! several foci. Editing a focus is the host's to do
10//! ([`SettingsFoci::edit`]): it attaches the store holding that focus's
11//! values and offers its scopes, so the fields show that focus's values.
12//! A setting with no host level is the app's and the same in every focus.
13//!
14//! egui-pop resolves one value per setting in a process: the layers of
15//! the focus edited are the ones applied.
16
17use std::sync::Arc;
18
19use egui::Ui;
20use egui::accesskit::Role;
21use egui_pop_core::{a11y, lock, strings};
22use egui_pop_model::commands::CommandSpec;
23use egui_pop_model::ids::CommandId;
24use serde_json::{Value as Json, json};
25
26use super::{ADMIN, APP_WINDOW, Admin};
27use crate::app::AppHandle;
28use crate::strings as txt;
29use crate::windows::WindowId;
30use crate::{Ctx, PluginError};
31
32/// Edits a focus's values in the Settings (`{"id"}`); without `id`, says
33/// which is edited and which there are.
34pub const CMD_FOCUS: CommandId = CommandId::from_static("admin.focus");
35
36/// A focus the Settings can edit.
37#[derive(Clone, Debug, PartialEq, Eq)]
38pub struct SettingsFocus {
39    /// Its id, kept while it is open.
40    pub id: String,
41    /// What the header names it, in the interface's language ("Main
42    /// window: library Photos").
43    pub label: String,
44    /// The application windows that belong to it: Settings opened from one
45    /// of them edit it.
46    pub windows: Vec<WindowId>,
47}
48
49impl SettingsFocus {
50    pub fn new(id: &str, label: impl Into<String>, windows: &[WindowId]) -> SettingsFocus {
51        SettingsFocus {
52            id: id.into(),
53            label: label.into(),
54            windows: windows.to_vec(),
55        }
56    }
57}
58
59/// The host's foci, as the Settings ask for them.
60pub trait SettingsFoci: Send + Sync + 'static {
61    /// The foci open now, the main one first: the first is edited when
62    /// the one edited closes.
63    fn foci(&self, app: &AppHandle) -> Vec<SettingsFocus>;
64
65    /// Makes the Settings edit a focus: the host attaches its store
66    /// ([`Admin::attach_store`]) and offers its scopes ([`Admin::offer`]).
67    ///
68    /// # Errors
69    /// The focus cannot be edited.
70    fn edit(&self, app: &AppHandle, focus: &str) -> Result<(), String>;
71}
72
73/// The host's foci and the one edited.
74#[derive(Default)]
75pub(super) struct Foci {
76    host: Option<Arc<dyn SettingsFoci>>,
77    edited: Option<String>,
78}
79
80impl Admin {
81    /// Gives the Settings the host's foci (see the module's docs).
82    pub fn set_foci(&self, foci: impl SettingsFoci) {
83        lock(&self.foci).host = Some(Arc::new(foci));
84    }
85
86    /// The host's foci open now (none without [`Admin::set_foci`]).
87    pub fn foci(&self, app: &AppHandle) -> Vec<SettingsFocus> {
88        let host = lock(&self.foci).host.clone();
89        host.map(|h| h.foci(app)).unwrap_or_default()
90    }
91
92    /// The focus the Settings edit, once one was chosen.
93    pub fn edited_focus(&self) -> Option<String> {
94        lock(&self.foci).edited.clone()
95    }
96
97    /// Makes the Settings edit a focus of the host's.
98    ///
99    /// # Errors
100    /// No such focus, or the host cannot edit it.
101    pub fn edit_focus(&self, app: &AppHandle, id: &str) -> Result<(), String> {
102        let host = lock(&self.foci).host.clone().ok_or("no foci")?;
103        if !host.foci(app).iter().any(|f| f.id == id) {
104            return Err(format!("no focus `{id}`"));
105        }
106        if self.edited_focus().as_deref() == Some(id) {
107            return Ok(());
108        }
109        host.edit(app, id)?;
110        lock(&self.foci).edited = Some(id.into());
111        Ok(())
112    }
113
114    /// The Settings asked in `window`: they edit its focus. The Settings'
115    /// own window, or a window of no focus, leaves the one edited.
116    pub(super) fn asked_in(&self, app: &AppHandle, window: &WindowId) {
117        if window.as_str() == APP_WINDOW {
118            return;
119        }
120        let focus = self
121            .foci(app)
122            .into_iter()
123            .find(|f| f.windows.contains(window));
124        if let Some(f) = focus
125            && let Err(e) = self.edit_focus(app, &f.id)
126        {
127            log::warn!("settings: the focus `{}` not edited: {e}", f.id);
128        }
129    }
130
131    /// Each pass: a focus edited that closed gives way to the first.
132    pub(super) fn keep_focus(&self, app: &AppHandle) {
133        let Some(edited) = self.edited_focus() else {
134            return;
135        };
136        let foci = self.foci(app);
137        if foci.iter().any(|f| f.id == edited) {
138            return;
139        }
140        lock(&self.foci).edited = None;
141        if let Some(first) = foci.first()
142            && let Err(e) = self.edit_focus(app, &first.id)
143        {
144            log::warn!("settings: the focus `{}` not edited: {e}", first.id);
145        }
146    }
147}
148
149/// The header above the page: the focus edited and the switch, when the
150/// host has several.
151pub(super) fn header(ui: &mut Ui, app: &AppHandle, admin: &Admin) {
152    let foci = admin.foci(app);
153    if foci.len() < 2 {
154        return;
155    }
156    let ctx = ui.ctx().clone();
157    let edited = admin.edited_focus();
158    let current = foci
159        .iter()
160        .find(|f| Some(&f.id) == edited.as_ref())
161        .unwrap_or(&foci[0]);
162    let mut picked = current.id.clone();
163    ui.horizontal(|ui| {
164        let title = strings::tr(&ctx, &txt::ADMIN_FOCUS);
165        ui.label(&title);
166        let r = egui::ComboBox::from_id_salt("egui_pop.admin.focus")
167            .selected_text(&current.label)
168            .show_ui(ui, |ui| {
169                for f in &foci {
170                    ui.selectable_value(&mut picked, f.id.clone(), &f.label);
171                }
172            })
173            .response
174            .on_hover_text(strings::tr(&ctx, &txt::ADMIN_FOCUS_TIP));
175        a11y::name(&r, Role::ComboBox, &title);
176    });
177    if picked != current.id
178        && let Err(e) = admin.edit_focus(app, &picked)
179    {
180        log::warn!("settings: the focus `{picked}` not edited: {e}");
181    }
182}
183
184pub(super) fn commands(ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
185    ctx.command(
186        CommandSpec::new(CMD_FOCUS, "Settings: edit a focus", "File")
187            .hidden()
188            .args(json!({ "id": "" })),
189        |call| {
190            let a = call.app.service(&ADMIN).ok_or("no admin")?;
191            if let Some(id) = call
192                .args
193                .get("id")
194                .and_then(Json::as_str)
195                .filter(|i| !i.is_empty())
196            {
197                a.edit_focus(call.app, id)?;
198            }
199            Ok(state(call.app, &a))
200        },
201    )?;
202    Ok(())
203}
204
205/// The foci and the one edited, as agents read them.
206pub(super) fn state(app: &AppHandle, admin: &Admin) -> Json {
207    json!({
208        "edited": admin.edited_focus(),
209        "foci": admin.foci(app).iter().map(|f| json!({
210            "id": f.id,
211            "label": f.label,
212            "windows": f.windows.iter().map(WindowId::as_str).collect::<Vec<_>>(),
213        })).collect::<Vec<_>>(),
214    })
215}