Skip to main content

egui_pop_api/
devtools.rs

1//! Devtools, as a plugin ([`DevtoolsPlugin`], opt-in): the debug
2//! bridge's collectors shown in the application itself, in a panel of
3//! the workbench (`egui_pop.devtools`, bottom), behind a setting
4//! (`developer.devtools`, off by default) so end users never meet it; an
5//! application shown to developers turns it on by default
6//! ([`DevtoolsPlugin::on_by_default`]).
7//! `Shift+F12` (View > Devtools) opens it when the setting is on. Not
8//! `F12`: browsers open their own developer tools with it before a web
9//! build sees it, as they take Ctrl+Shift+C, I, J, K (Cmd+Option on a
10//! Mac) and Shift+F5, F7, F9.
11//!
12//! <div class="warning">Experimental: may change in any release
13//! (docs/stability.md).</div>
14//!
15//! Tabs: the key resolutions (each binding considered and its verdict),
16//! the journal's last events, the steps and their hooks, the focus
17//! chain and the overlays, the scale of each window, and every collector
18//! as JSON with its actions (an action that mutates says so).
19//!
20//! The inspect mode ([`inspect`], `devtools.inspect`, Ctrl+Shift+F12):
21//! click an element to see what egui-pop knows of it, and copy it.
22//!
23//! Steps (ADR 0011): `devtools.call` (`{ "collector", "action",
24//! "args" }`): a collector action run from the panel ([`call`]); a
25//! plugin may veto it (an action too dangerous to offer in the panel).
26//! The panel is the user's: its default calls the action as the user
27//! (`AppHandle::debug_call_as`), through the `debug.call` step every
28//! call of the bridge goes through, so a veto there (a kiosk build)
29//! covers the panel and agents alike.
30
31use std::sync::{Arc, Mutex};
32
33use egui::Ui;
34use egui_pop_core::lock;
35use egui_pop_core::strings;
36use egui_pop_core::ui::UiPop as _;
37use egui_pop_core::widgets;
38use egui_pop_model::commands::{CommandSpec, Origin};
39use egui_pop_model::ids::{CommandId, PanelId, PluginId, SettingId, StepId};
40use egui_pop_model::panels::{Area, PanelSpec};
41use egui_pop_model::values::Descriptor;
42use serde_json::{Value as Json, json};
43
44use crate::app::{AppHandle, MENU_VIEW};
45use crate::steps::StepSpec;
46use crate::strings as txt;
47use crate::{Ctx, Plugin, PluginError};
48
49pub mod inspect;
50
51/// The setting that lets devtools open.
52pub const SETTING_DEVTOOLS: SettingId = SettingId::from_static("developer.devtools");
53/// The panel.
54pub const PANEL_DEVTOOLS: PanelId = PanelId::from_static("egui_pop.devtools");
55/// Opens or closes the panel.
56pub const CMD_DEVTOOLS: CommandId = CommandId::from_static("app.devtools");
57/// A collector action run from the panel.
58pub const STEP_CALL: StepId = StepId::from_static("devtools.call");
59
60/// The tabs.
61pub const TABS: [&str; 6] = [
62    txt::DEVTOOLS_TAB_KEYS.fallback,
63    txt::DEVTOOLS_TAB_JOURNAL.fallback,
64    txt::DEVTOOLS_TAB_STEPS.fallback,
65    txt::DEVTOOLS_TAB_FOCUS.fallback,
66    txt::DEVTOOLS_TAB_SCALE.fallback,
67    txt::DEVTOOLS_TAB_COLLECTORS.fallback,
68];
69
70#[derive(Debug, Default)]
71struct State {
72    tab: usize,
73    collector: String,
74    args: String,
75    last: Option<String>,
76}
77
78/// The plugin.
79#[derive(Debug, Default)]
80pub struct DevtoolsPlugin {
81    state: Arc<Mutex<State>>,
82    describe: Option<inspect::Describe>,
83    on_by_default: bool,
84}
85
86impl DevtoolsPlugin {
87    /// What the application adds to an inspected element: rows of a
88    /// name and a value (the gallery: its page and story).
89    #[must_use]
90    pub fn describe(
91        mut self,
92        f: impl Fn(&AppHandle, &egui_pop_core::inspect::Pick) -> Vec<(String, String)> + 'static,
93    ) -> Self {
94        self.describe = Some(inspect::Describe(std::rc::Rc::new(f)));
95        self
96    }
97
98    /// The `developer.devtools` setting's default: off (end users never
99    /// meet devtools), on for an application shown to developers (the
100    /// gallery). The user's choice, once made, wins either way.
101    #[must_use]
102    pub fn on_by_default(mut self, on: bool) -> Self {
103        self.on_by_default = on;
104        self
105    }
106}
107
108/// Runs a collector's action as the panel's buttons do: through the
109/// `devtools.call` step, whose default calls it as the user
110/// (`Origin::User`) through the `debug.call` step.
111pub fn call(app: &AppHandle, collector: &str, action: &str, args: Json) -> crate::steps::Outcome {
112    app.step(
113        &STEP_CALL,
114        json!({ "collector": collector, "action": action, "args": args }),
115        |app, args| {
116            let f = app.debug_call_as(
117                args["collector"].as_str().unwrap_or_default(),
118                args["action"].as_str().unwrap_or_default(),
119                &args["args"],
120                Origin::User,
121            );
122            if f.ok { Ok(f.data) } else { Err(f.message) }
123        },
124    )
125}
126
127/// Whether the setting lets devtools open.
128pub fn enabled(app: &AppHandle) -> bool {
129    lock(&app.store())
130        .get(&format!("settings/{SETTING_DEVTOOLS}"))
131        .and_then(|e| e.value.as_bool())
132        .unwrap_or(false)
133}
134
135impl Plugin for DevtoolsPlugin {
136    fn id(&self) -> PluginId {
137        PluginId::from_static("egui_pop.devtools")
138    }
139
140    fn title(&self) -> String {
141        "Developer".into()
142    }
143
144    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
145        ctx.setting(
146            SETTING_DEVTOOLS,
147            Descriptor::bool("Devtools", self.on_by_default).description(
148                "Lets the devtools panel open (View > Devtools): key resolutions, the journal, steps, focus, scale and every debug collector.",
149            ),
150        )?;
151        ctx.step(
152            StepSpec::new(
153                STEP_CALL,
154                "Devtools runs a debug collector's action (`collector`, `action`, `args`).",
155            )
156            .args(json!({ "collector": "commands", "action": "run", "args": {} })),
157        )?;
158        ctx.command(
159            CommandSpec::new(CMD_DEVTOOLS, "Devtools", "View")
160                .description(
161                    "Opens or closes the devtools panel (when the Devtools setting is on).",
162                )
163                .key("Shift+F12")
164                .when("devtoolsEnabled")
165                .menu(MENU_VIEW, "8_devtools", 0)
166                .no_agent(),
167            |call| {
168                let shown = call.app.panel_visible(&PANEL_DEVTOOLS);
169                if shown {
170                    call.app.set_panel_visible(&PANEL_DEVTOOLS, false);
171                } else {
172                    call.app.focus_panel(&PANEL_DEVTOOLS);
173                }
174                Ok(json!({ "open": !shown }))
175            },
176        )?;
177        inspect::connect(ctx, self.describe.clone())?;
178        let state = self.state.clone();
179        ctx.panel(
180            PanelSpec::new(PANEL_DEVTOOLS, "Devtools", Area::Bottom)
181                .min_size(120.0)
182                .default_size(260.0)
183                .icon("command")
184                .closed(),
185            move |ui, app| show(ui, app, &state),
186        )?;
187        // The setting is followed every frame, the panel shown or not.
188        ctx.block(
189            crate::zones::OVERLAYS,
190            crate::zones::Block::add(
191                egui_pop_model::ids::BlockId::from_static("egui_pop.devtools.follow"),
192                90,
193                |_, app| follow(app),
194            ),
195        );
196        Ok(())
197    }
198}
199
200/// Keeps the `devtoolsEnabled` context key in line with the setting, and
201/// closes the panel when the setting goes off.
202pub(crate) fn follow(app: &AppHandle) {
203    let on = enabled(app);
204    let key = if on { "true" } else { "false" };
205    if app.context().get("devtoolsEnabled") != key {
206        app.set_context("devtoolsEnabled", key);
207        if !on && app.panel_visible(&PANEL_DEVTOOLS) {
208            app.set_panel_visible(&PANEL_DEVTOOLS, false);
209        }
210    }
211}
212
213fn show(ui: &mut Ui, app: &AppHandle, state: &Arc<Mutex<State>>) {
214    follow(app);
215    if !enabled(app) {
216        ui.weak(strings::tr(ui.ctx(), &txt::DEVTOOLS_OFF));
217        return;
218    }
219    let mut s = lock(state);
220    ui.horizontal(|ui| {
221        inspect::button(ui, app);
222        ui.separator();
223        for (i, name) in txt::DEVTOOLS_TABS.iter().enumerate() {
224            let name = strings::tr(ui.ctx(), name);
225            if widgets::selectable_label(ui, s.tab == i, name).clicked() {
226                s.tab = i;
227            }
228        }
229    });
230    ui.separator();
231    ui.scroll_area(
232        egui::ScrollArea::vertical()
233            .id_salt("egui_pop.devtools.scroll")
234            .auto_shrink([false, false]),
235        |ui| match s.tab {
236            0 => keys(ui, app),
237            1 => journal(ui, app),
238            2 => steps(ui, app),
239            3 => focus(ui, app),
240            4 => scale(ui, app),
241            _ => collectors(ui, app, &mut s),
242        },
243    );
244}
245
246fn keys(ui: &mut Ui, app: &AppHandle) {
247    if let Some(p) = app.pending_keys() {
248        ui.strong(strings::tr_args(
249            ui.ctx(),
250            &txt::DEVTOOLS_WAITING,
251            &[("keys", &p.to_string())],
252        ));
253    }
254    let traces = app.key_traces();
255    if traces.is_empty() {
256        ui.weak(strings::tr(ui.ctx(), &txt::DEVTOOLS_PRESS_A_KEY));
257    }
258    for t in traces.iter().rev().take(16) {
259        ui.monospace(t.to_string());
260    }
261}
262
263fn journal(ui: &mut Ui, app: &AppHandle) {
264    let last = app.last_event();
265    for e in app.events_since(last.saturating_sub(48)).iter().rev() {
266        ui.monospace(format!(
267            "#{} {} {}{} {}",
268            e.seq,
269            e.source,
270            e.name,
271            e.cause
272                .map(|c| format!(" (after #{c})"))
273                .unwrap_or_default(),
274            e.data
275        ));
276    }
277}
278
279fn steps(ui: &mut Ui, app: &AppHandle) {
280    let ctx = ui.ctx().clone();
281    egui::Grid::new("egui_pop.devtools.steps")
282        .num_columns(2)
283        .striped(true)
284        .show(ui, |ui| {
285            for s in app.steps() {
286                ui.monospace(s.spec.id.as_str());
287                ui.label(if s.hooks.is_empty() {
288                    strings::tr(&ctx, &txt::DEVTOOLS_NO_HOOKS)
289                } else {
290                    s.hooks
291                        .iter()
292                        .map(|h| {
293                            strings::tr_args(
294                                &ctx,
295                                &txt::DEVTOOLS_HOOK_BY,
296                                &[("kind", h.kind), ("owner", h.owner.as_str())],
297                            )
298                        })
299                        .collect::<Vec<_>>()
300                        .join(", ")
301                });
302                ui.end_row();
303            }
304        });
305    ui.separator();
306    for t in app.step_traces().iter().rev().take(12) {
307        let how = match (&t.vetoed_by, &t.result) {
308            (Some((by, why)), _) => format!("vetoed by {by}: {why}"),
309            (None, Some(Ok(v))) => format!("ran by {}: {v}", t.ran_by.clone().unwrap_or_default()),
310            (None, Some(Err(e))) => {
311                format!("failed ({}): {e}", t.ran_by.clone().unwrap_or_default())
312            }
313            _ => String::new(),
314        };
315        ui.monospace(format!("{} {} {how}", t.step, t.args));
316    }
317}
318
319fn focus(ui: &mut Ui, app: &AppHandle) {
320    let snap = app.debug_snapshot();
321    ui.strong(strings::tr(ui.ctx(), &txt::DEVTOOLS_FOCUS_CHAIN));
322    ui.monospace(snap["focus"].to_string());
323    ui.strong(strings::tr(ui.ctx(), &txt::DEVTOOLS_OVERLAYS));
324    ui.monospace(snap["overlays"].to_string());
325    ui.strong(strings::tr(ui.ctx(), &txt::DEVTOOLS_CONTEXT_KEYS));
326    for (k, v, d) in app.when_context().iter() {
327        ui.monospace(format!("{k} = {v} (depth {d})"));
328    }
329}
330
331fn scale(ui: &mut Ui, app: &AppHandle) {
332    let snap = app.debug_snapshot();
333    ui.monospace(serde_json::to_string_pretty(&snap["screen"]).unwrap_or_default());
334}
335
336fn collectors(ui: &mut Ui, app: &AppHandle, s: &mut State) {
337    let described = app.debug_describe();
338    let names: Vec<String> = described
339        .as_array()
340        .map(|a| {
341            a.iter()
342                .filter_map(|c| c["name"].as_str().map(String::from))
343                .collect()
344        })
345        .unwrap_or_default();
346    if s.collector.is_empty() || !names.contains(&s.collector) {
347        s.collector = names.first().cloned().unwrap_or_default();
348    }
349    ui.horizontal_wrapped(|ui| {
350        for n in &names {
351            if widgets::selectable_label(ui, *n == s.collector, n).clicked() {
352                s.collector.clone_from(n);
353            }
354        }
355    });
356    let Some(c) = described
357        .as_array()
358        .and_then(|a| a.iter().find(|c| c["name"] == s.collector.as_str()))
359        .cloned()
360    else {
361        return;
362    };
363    ui.weak(c["description"].as_str().unwrap_or_default());
364    if let Some(actions) = c["actions"].as_array().filter(|a| !a.is_empty()) {
365        ui.horizontal(|ui| {
366            let label = ui.label(strings::tr(ui.ctx(), &txt::DEVTOOLS_ARGUMENTS));
367            ui.add(egui::TextEdit::singleline(&mut s.args).desired_width(280.0))
368                .labelled_by(label.id);
369        });
370        ui.horizontal_wrapped(|ui| {
371            for a in actions {
372                let name = a["name"].as_str().unwrap_or_default().to_string();
373                let mutates = a["mutates"].as_bool().unwrap_or(false);
374                let label = if mutates {
375                    strings::tr_args(ui.ctx(), &txt::DEVTOOLS_MUTATES, &[("action", &name)])
376                } else {
377                    name.clone()
378                };
379                if ui
380                    .button(label)
381                    .on_hover_text(a["description"].as_str().unwrap_or_default())
382                    .clicked()
383                {
384                    let args: Json =
385                        serde_json::from_str(&s.args).unwrap_or_else(|_| a["args"].clone());
386                    let out = call(app, &s.collector, &name, args);
387                    s.last = Some(match out {
388                        crate::steps::Outcome::Done(Ok(v)) => format!("ok: {v}"),
389                        crate::steps::Outcome::Done(Err(e)) => format!("failed: {e}"),
390                        crate::steps::Outcome::Vetoed { by, reason } => {
391                            format!("vetoed by {by}: {reason}")
392                        }
393                    });
394                }
395            }
396        });
397        if let Some(l) = &s.last {
398            ui.monospace(l);
399        }
400    }
401    ui.separator();
402    let snap = app.debug_snapshot();
403    ui.monospace(serde_json::to_string_pretty(&snap[s.collector.as_str()]).unwrap_or_default());
404}