Skip to main content

egui_pop_api/admin/
quick.rs

1//! Quick settings: a small panel over the window it is asked in
2//! (`admin.quick`, `Ctrl+Shift+Q`) that edits a setting without the full
3//! Settings app. Before anything is typed it shows the settings the
4//! manifests mark quick ([`model::Manifest::quick`]), then those changed
5//! lately in this session ([`RECENT_SECONDS`], at most [`RECENT_MAX`]);
6//! typing searches every setting. Each row is the Settings app's own
7//! row: its editor, its reset, and its "Set for" choice only on a setting
8//! that also has a host level open now (a library). A change goes where
9//! the Settings app would write it, through the host's store. Each row
10//! links to its page in Settings.
11//!
12//! Each application window has its own panel, as the palette: it opens
13//! in the window it is asked in, and closes with it.
14
15use egui::Key;
16use egui_pop_core::lock;
17use egui_pop_core::overlay::{self, Kind, OverlaySpec};
18use egui_pop_core::strings;
19use egui_pop_core::ui::UiPop as _;
20use egui_pop_model::admin::Field;
21use egui_pop_model::ids::CommandId;
22use serde_json::json;
23
24use super::{ADMIN, Admin, CMD_OPEN, model};
25use crate::app::AppHandle;
26use crate::hooks::SettingEntry;
27use crate::strings as txt;
28
29/// Opens and closes the quick settings in the window it is asked in.
30pub const CMD_QUICK: CommandId = CommandId::from_static("admin.quick");
31
32/// How long a change counts as lately, in seconds.
33pub const RECENT_SECONDS: f64 = 3600.0;
34
35/// How many settings changed lately are shown at most.
36pub const RECENT_MAX: usize = 6;
37
38/// How many search hits are shown at most.
39const HITS_MAX: usize = 12;
40
41const SPEC_ID: &str = "egui_pop.admin.quick";
42
43/// The panel open in a window group.
44#[derive(Clone, Debug, Default)]
45pub(super) struct Open {
46    query: String,
47    /// The window it is shown in: the one active when it first draws.
48    window: Option<egui::ViewportId>,
49}
50
51/// Seconds since the epoch.
52pub fn now() -> f64 {
53    web_time::SystemTime::now()
54        .duration_since(web_time::UNIX_EPOCH)
55        .map(|d| d.as_secs_f64())
56        .unwrap_or(0.0)
57}
58
59impl Admin {
60    /// Notes that the person changed settings (their ids) at `at`
61    /// (seconds since the epoch): offered among the recent ones in the
62    /// quick settings until [`RECENT_SECONDS`] later.
63    pub fn note_changed<'a>(&self, ids: impl IntoIterator<Item = &'a str>, at: f64) {
64        let mut r = lock(&self.recent);
65        for id in ids {
66            r.retain(|(x, _)| x != id);
67            r.push((id.to_string(), at));
68        }
69        let keep = r.len().saturating_sub(64);
70        r.drain(..keep);
71    }
72
73    /// The settings marked quick that exist, in order.
74    pub fn quick_settings(&self, app: &AppHandle) -> Vec<String> {
75        let entries = app.settings();
76        self.tree(app)
77            .quick
78            .into_iter()
79            .filter(|id| entries.iter().any(|e| e.id.as_str() == id))
80            .collect()
81    }
82
83    /// The settings changed lately at `now`, the latest first, without
84    /// the quick ones, at most [`RECENT_MAX`].
85    pub fn recent_settings(&self, app: &AppHandle, now: f64) -> Vec<String> {
86        let quick = self.quick_settings(app);
87        let entries = app.settings();
88        lock(&self.recent)
89            .iter()
90            .rev()
91            .filter(|(id, at)| {
92                now - at <= RECENT_SECONDS
93                    && !quick.contains(id)
94                    && entries.iter().any(|e| e.id.as_str() == id)
95            })
96            .map(|(id, _)| id.clone())
97            .take(RECENT_MAX)
98            .collect()
99    }
100
101    /// Whether the quick settings are open in a window group.
102    pub fn quick_open_in(&self, group: egui::ViewportId) -> bool {
103        lock(&self.quick).contains_key(&group)
104    }
105
106    /// Opens or closes them in a window group; whether they are open.
107    pub fn toggle_quick(&self, group: egui::ViewportId) -> bool {
108        let mut q = lock(&self.quick);
109        if q.remove(&group).is_some() {
110            false
111        } else {
112            q.insert(group, Open::default());
113            true
114        }
115    }
116
117    /// The window they are shown in, in a window group, once drawn.
118    pub fn quick_window_in(&self, group: egui::ViewportId) -> Option<egui::ViewportId> {
119        lock(&self.quick).get(&group).and_then(|o| o.window)
120    }
121}
122
123/// The command.
124pub(super) fn commands(ctx: &mut crate::Ctx<'_>) -> Result<(), crate::PluginError> {
125    use egui_pop_model::commands::CommandSpec;
126    use egui_pop_model::keymap::BindOptions;
127    ctx.command(
128        CommandSpec::new(CMD_QUICK, "Quick settings", "File")
129            .icon("settings")
130            .description(
131                "The settings changed often and those changed lately, edited without opening Settings.",
132            )
133            .key_with("Ctrl+Shift+Q", BindOptions::global().through_modal())
134            .menu(crate::app::MENU_FILE, "8_settings", 1),
135        |call| {
136            let a = call.app.service(&ADMIN).ok_or("no admin")?;
137            let group = call.app.current_window_group();
138            let open = a.toggle_quick(group);
139            Ok(json!({ "open": open, "window": call.app.window_of_group(group) }))
140        },
141    )?;
142    Ok(())
143}
144
145/// The entries shown: the search's hits, or the quick ones then the
146/// recent ones.
147fn rows(
148    ctx: &egui::Context,
149    app: &AppHandle,
150    admin: &Admin,
151    query: &str,
152) -> (Vec<String>, Vec<String>) {
153    let q = query.trim().to_lowercase();
154    if q.is_empty() {
155        return (admin.quick_settings(app), admin.recent_settings(app, now()));
156    }
157    let hits = app
158        .settings()
159        .iter()
160        .filter(|e| {
161            let d = crate::settings_window::shown(ctx, e);
162            d.label.to_lowercase().contains(&q) || e.id.as_str().to_lowercase().contains(&q)
163        })
164        .map(|e| e.id.as_str().to_string())
165        .take(HITS_MAX)
166        .collect();
167    (hits, Vec::new())
168}
169
170/// The manifests' field of a setting (its value scopes), or a plain one.
171fn field_of(tree: &model::Tree, id: &str) -> Field {
172    tree.fields()
173        .into_iter()
174        .find(|(_, f)| f.setting_id() == Some(id))
175        .map(|(_, f)| f.clone())
176        .unwrap_or_else(|| Field::setting(id))
177}
178
179/// Draws the panel in the window of its group it opened in.
180pub(super) fn show(ui: &mut egui::Ui, app: &AppHandle) {
181    let Some(admin) = app.service(&ADMIN) else {
182        return;
183    };
184    let ctx = ui.ctx().clone();
185    let group = app.window_group(ctx.viewport_id());
186    // A closed window's panel goes with it.
187    lock(&admin.quick).retain(|g, _| app.window_group(*g) == *g);
188    if !admin.quick_open_in(group) {
189        return;
190    }
191    let window = {
192        let mut all = lock(&admin.quick);
193        let Some(s) = all.get_mut(&group) else { return };
194        *s.window.get_or_insert_with(|| app.shown_in(group))
195    };
196    if app.still_open(window) != ctx.viewport_id() {
197        return;
198    }
199    let title = strings::tr(&ctx, &txt::ADMIN_QUICK_TITLE);
200    let spec = OverlaySpec::new(SPEC_ID, &title, Kind::Modal).keep_on_escape();
201    let mut open = true;
202    let mut close = false;
203    let mut go: Option<String> = None;
204    let entries = app.settings();
205    overlay::show(&ctx, &spec, &mut open, None, |ui| {
206        let mut query = lock(&admin.quick)
207            .get(&group)
208            .map(|o| o.query.clone())
209            .unwrap_or_default();
210        let heading = ui.strong(&title);
211        let edit = ui
212            .add(
213                egui::TextEdit::singleline(&mut query)
214                    .hint_text(strings::tr(&ctx, &txt::ADMIN_QUICK_HINT))
215                    .desired_width(f32::INFINITY),
216            )
217            .labelled_by(heading.id);
218        if !ctx.memory(|m| m.focused().is_some()) {
219            edit.request_focus();
220        }
221        egui_pop_core::focus::escape_passes(ui.ctx(), edit.id);
222        if let Some(o) = lock(&admin.quick).get_mut(&group) {
223            o.query = query.clone();
224        }
225        if ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, Key::Escape)) {
226            close = true;
227            return;
228        }
229        let (first, recent) = rows(&ctx, app, &admin, &query);
230        let tree = admin.tree(app);
231        ui.set_width(420.0);
232        ui.scroll_area(egui::ScrollArea::vertical().max_height(420.0), |ui| {
233            let mut list = |ui: &mut egui::Ui, ids: &[String]| {
234                for id in ids {
235                    let Some(e) = entries.iter().find(|e| e.id.as_str() == id) else {
236                        continue;
237                    };
238                    if row(ui, app, &admin, e, &field_of(&tree, id)) {
239                        go = Some(id.clone());
240                    }
241                }
242            };
243            if query.trim().is_empty() {
244                if !first.is_empty() {
245                    ui.weak(strings::tr(&ctx, &txt::ADMIN_QUICK_MARKED));
246                    list(ui, &first);
247                }
248                if !recent.is_empty() {
249                    ui.weak(strings::tr(&ctx, &txt::ADMIN_QUICK_RECENT));
250                    list(ui, &recent);
251                }
252                if first.is_empty() && recent.is_empty() {
253                    ui.weak(strings::tr(&ctx, &txt::ADMIN_QUICK_NONE));
254                }
255            } else if first.is_empty() {
256                ui.weak(strings::tr(&ctx, &txt::ADMIN_QUICK_NO_HIT));
257            } else {
258                list(ui, &first);
259            }
260        });
261    });
262    if !open || close {
263        lock(&admin.quick).remove(&group);
264    }
265    if let Some(key) = go {
266        lock(&admin.quick).remove(&group);
267        app.run(CMD_OPEN, json!({ "key": key }));
268    }
269}
270
271/// One setting: the Settings app's row, then a link to its page; whether
272/// the link was clicked.
273fn row(ui: &mut egui::Ui, app: &AppHandle, admin: &Admin, e: &SettingEntry, f: &Field) -> bool {
274    let ctx = ui.ctx().clone();
275    let mut go = false;
276    ui.push_id(("egui_pop.admin.quick.row", e.id.as_str()), |ui| {
277        super::shell::field_row(ui, app, admin, e, f);
278        let d = crate::settings_window::shown(&ctx, e);
279        let text = strings::tr(&ctx, &txt::ADMIN_QUICK_OPEN);
280        let r = ui.link(&text);
281        egui_pop_core::a11y::name(
282            &r,
283            egui::accesskit::Role::Link,
284            &strings::tr_args(
285                &ctx,
286                &txt::ADMIN_QUICK_OPEN_NAME,
287                &[("setting", d.label.as_str())],
288            ),
289        );
290        go = r.clicked();
291    });
292    go
293}
294
295#[cfg(test)]
296mod tests {
297    use super::*;
298
299    #[test]
300    fn a_change_ages_out() {
301        let a = Admin::new();
302        a.note_changed(["x.a"], 1000.0);
303        a.note_changed(["x.b"], 2000.0);
304        a.note_changed(["x.a"], 3000.0);
305        let r: Vec<String> = lock(&a.recent).iter().map(|(i, _)| i.clone()).collect();
306        assert_eq!(r, ["x.b", "x.a"]);
307    }
308}