1use std::cell::RefCell;
26use std::fmt;
27use std::rc::Rc;
28
29use egui::Ui;
30use egui_pop_core::inspect::{self as picker, Pick};
31use egui_pop_core::strings;
32use egui_pop_core::ui::UiPop as _;
33use egui_pop_model::clipboard::{ClipItem, FormatId, Repr, TEXT};
34use egui_pop_model::commands::{CommandSpec, Origin};
35use egui_pop_model::ids::{BlockId, CommandId};
36use serde::Serialize;
37use serde_json::{Value as Json, json};
38
39use crate::app::{AppHandle, MENU_BAR_END, MENU_VIEW};
40use crate::clipboard::{self, ClipSource, ClipType, CopyRequest};
41use crate::dialogs::{Custom, DIALOGS, DialogSpec};
42use crate::steps::Outcome;
43use crate::strings as txt;
44use crate::zones::{self, Block};
45use crate::{Ctx, PluginError};
46
47pub const CMD_INSPECT: CommandId = CommandId::from_static("devtools.inspect");
49pub const CONTEXT_INSPECTING: &str = "inspecting";
52pub const CURSOR: egui::CursorIcon = egui::CursorIcon::Crosshair;
55pub const ENDPOINT: &str = "devtools.inspect";
57pub const FORMAT: FormatId = FormatId::from_static("application/x-egui-pop.inspect+json");
59
60#[derive(Clone)]
63pub struct Describe(pub(crate) Rc<DescribeFn>);
64
65pub type DescribeFn = dyn Fn(&AppHandle, &Pick) -> Vec<(String, String)>;
67
68impl fmt::Debug for Describe {
69 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
70 f.write_str("Describe(..)")
71 }
72}
73
74#[derive(Clone, Debug, PartialEq, Serialize)]
76pub struct Inspected {
77 pub element: Pick,
78 pub window: String,
80 pub zone: Option<String>,
83 pub block: Option<String>,
84 pub panel: Option<String>,
85 pub plugin: Option<String>,
86 pub theme: String,
87 pub dark: bool,
88 pub kit: String,
91 pub density: String,
92 pub app: Vec<(String, String)>,
94}
95
96impl Inspected {
97 fn new(app: &AppHandle, element: Pick, describe: Option<&Describe>) -> Inspected {
98 let ctx = app.egui();
99 let auxiliary = app.layout().auxiliary;
100 let window = auxiliary
104 .iter()
105 .find(|a| {
106 crate::workbench::window_id(&a.panel) == element.viewport
107 || element
108 .regions
109 .iter()
110 .any(|r| r.kind == "panel" && a.panels().any(|p| r.id == p.as_str()))
111 })
112 .map_or_else(
113 || {
114 if element.viewport == egui::ViewportId::ROOT {
115 "main".to_string()
116 } else {
117 format!("{:?}", element.viewport)
118 }
119 },
120 |a| format!("panel {}", a.panel),
121 );
122 let block = element.regions.iter().rev().find(|r| r.kind == "block");
123 let panel = element.regions.iter().rev().find(|r| r.kind == "panel");
124 let spec = app.theme().spec();
125 let kit = if app.theme().kits().iter().any(|k| k.name == spec.base) {
126 spec.base.clone()
127 } else {
128 "built-in".to_string()
129 };
130 let mut out = Inspected {
131 window,
132 zone: block.and_then(|b| b.zone.clone()),
133 block: block.map(|b| b.id.clone()),
134 panel: panel.map(|p| p.id.clone()),
135 plugin: element.regions.last().map(|r| r.owner.clone()),
136 theme: spec.base.clone(),
137 dark: egui_pop_core::theme::Tokens::of(&ctx).dark_mode(),
138 kit,
139 density: spec.density.name().to_string(),
140 app: Vec::new(),
141 element,
142 };
143 if let Some(d) = describe {
144 out.app = (d.0)(app, &out.element);
145 }
146 out
147 }
148
149 pub fn rows(&self) -> Vec<(String, String)> {
151 let e = &self.element;
152 let mut rows: Vec<(String, String)> = Vec::new();
153 let mut row = |k: &str, v: String| rows.push((k.to_string(), v));
154 let what = match (&e.role, &e.label) {
155 (Some(r), Some(l)) => format!("{r} {l:?}"),
156 (Some(r), None) => r.clone(),
157 (None, Some(l)) => format!("{l:?}"),
158 (None, None) => "unnamed".to_string(),
159 };
160 row("Element", format!("{what} ({})", e.kind));
161 if let Some(r) = &e.role {
162 row("Role", r.clone());
163 }
164 if let Some(l) = &e.label {
165 row("Name", l.clone());
166 }
167 if let Some(v) = &e.value {
168 row("Value", v.clone());
169 }
170 if let Some(d) = &e.description {
171 row("Description", d.clone());
172 }
173 if let Some(w) = &e.within {
174 row("Within", w.clone());
175 }
176 row("egui id", e.id.clone());
177 row(
178 "Rect",
179 format!(
180 "x {:.0}, y {:.0}, {:.0} × {:.0} points",
181 e.rect[0], e.rect[1], e.rect[2], e.rect[3]
182 ),
183 );
184 row("Window", self.window.clone());
185 row("Layer", e.layer.clone());
186 if let Some(z) = &self.zone {
187 row("Zone", z.clone());
188 }
189 if let Some(b) = &self.block {
190 row("Block", b.clone());
191 }
192 if let Some(p) = &self.panel {
193 row("Panel", p.clone());
194 }
195 if let Some(p) = &self.plugin {
196 row("Plugin", p.clone());
197 }
198 row(
199 "Theme",
200 format!(
201 "{} ({}), kit {}, density {}",
202 self.theme,
203 if self.dark { "dark" } else { "light" },
204 self.kit,
205 self.density
206 ),
207 );
208 row(
209 "Kit part",
210 e.kit.as_ref().map_or_else(
211 || "none painted through a kit handler".to_string(),
212 |k| {
213 format!(
214 "{}{} ({}), state {}: fill {}, border {}, radius {}, text {}",
215 k.component,
216 if k.around { ", around it" } else { "" },
217 k.shape,
218 k.state,
219 k.fill,
220 k.border,
221 k.radius,
222 k.text
223 )
224 },
225 ),
226 );
227 row("Focused", yes(e.focused));
228 row("Enabled", yes(e.enabled));
229 row("Senses", e.sense.clone());
230 for (k, v) in &self.app {
231 row(k, v.clone());
232 }
233 row("Picked by", e.how.clone());
234 rows
235 }
236
237 pub fn text(&self) -> String {
239 let mut s = String::new();
240 for (k, v) in self.rows() {
241 s.push_str(&k);
242 s.push_str(": ");
243 s.push_str(&v);
244 s.push('\n');
245 }
246 s
247 }
248
249 pub fn json(&self) -> Json {
251 let mut j = serde_json::to_value(self).unwrap_or(Json::Null);
252 j["app"] = Json::Object(
253 self.app
254 .iter()
255 .map(|(k, v)| (k.clone(), Json::String(v.clone())))
256 .collect(),
257 );
258 j
259 }
260}
261
262fn yes(b: bool) -> String {
263 if b { "yes" } else { "no" }.to_string()
264}
265
266#[derive(Default)]
268struct Shared {
269 last: RefCell<Option<Inspected>>,
270 dialog: RefCell<Option<u64>>,
271 copied: RefCell<bool>,
272 describe: RefCell<Option<Describe>>,
273}
274
275fn shared(app: &AppHandle) -> Rc<Shared> {
276 app.local::<Shared>()
277}
278
279pub fn last(app: &AppHandle) -> Option<Inspected> {
281 shared(app).last.borrow().clone()
282}
283
284pub fn active(app: &AppHandle) -> bool {
286 picker::active(&app.egui())
287}
288
289pub fn start(app: &AppHandle) -> Result<(), String> {
291 if !super::enabled(app) {
292 return Err("devtools are off (the `developer.devtools` setting)".into());
293 }
294 picker::start(&app.egui());
295 app.publish("egui_pop", None, "inspect.started", Json::Null);
296 Ok(())
297}
298
299pub fn stop(app: &AppHandle) {
301 picker::stop(&app.egui());
302}
303
304pub fn copy(app: &AppHandle) -> Result<(), String> {
307 let connected = app
308 .plugins()
309 .iter()
310 .any(|p| p.id == clipboard::PLUGIN && p.connected);
311 let out = if connected {
312 match clipboard::copy(app, CopyRequest::new(ENDPOINT), &Origin::User) {
313 Outcome::Done(r) => r.map(|_| ()),
314 Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
315 }
316 } else {
317 let text = last(app).ok_or("nothing was inspected")?.text();
318 app.egui().copy_text(text);
319 Ok(())
320 };
321 if out.is_ok() {
322 *shared(app).copied.borrow_mut() = true;
323 }
324 out
325}
326
327struct Source;
328
329impl ClipSource for Source {
330 fn copy(&self, app: &AppHandle) -> Option<ClipItem> {
331 let i = last(app)?;
332 let text = i.text();
333 let mut payload = i.json();
334 payload["text"] = json!(text);
335 Some(ClipItem::new(FORMAT, 1, payload, "Inspected element").fallback(TEXT, json!(text)))
336 }
337
338 fn can_copy(&self, app: &AppHandle) -> bool {
339 last(app).is_some()
340 }
341}
342
343pub(crate) fn connect(ctx: &mut Ctx<'_>, describe: Option<Describe>) -> Result<(), PluginError> {
345 *shared(&ctx.app()).describe.borrow_mut() = describe;
346 ctx.command(
347 CommandSpec::new(CMD_INSPECT, "Inspect an element", "View")
348 .description(
349 "Enters or leaves the inspect mode: click an element (or reach it with Tab and the arrows, then Enter) to see what egui-pop knows of it (when the Devtools setting is on).",
350 )
351 .key("Ctrl+Shift+F12")
352 .when("devtoolsEnabled")
353 .icon("phosphor:cursor-click")
354 .checked(CONTEXT_INSPECTING)
355 .menu(MENU_VIEW, "8_devtools", 1)
356 .menu(MENU_BAR_END, "9_devtools", 0)
357 .no_agent(),
358 |call| {
359 if active(call.app) {
360 stop(call.app);
361 Ok(json!({ "inspecting": false }))
362 } else {
363 start(call.app)?;
364 Ok(json!({ "inspecting": true }))
365 }
366 },
367 )?;
368 ctx.clip_type(
369 ClipType::new(FORMAT, 1, "an inspected element")
370 .fallbacks(|p| vec![Repr::new(TEXT, p["text"].clone())]),
371 )?;
372 ctx.clip_endpoint(ENDPOINT, Some(Rc::new(Source)), None);
373 let app = ctx.app().downgrade();
374 ctx.collector(
375 egui_pop_core::debug::FnCollector::new(
376 "inspect",
377 "The inspect mode: whether it is on, and the last element picked (what the dialog shows, as JSON and as the text Copy gives).",
378 )
379 .snapshot(move |ctx| {
380 let last = app.get().ok().and_then(|app| last(&app));
381 json!({
382 "active": picker::active(ctx),
383 "last": last.map(|i| json!({ "json": i.json(), "text": i.text() })),
384 })
385 }),
386 )?;
387 ctx.block(
390 zones::WINDOW_OVERLAYS,
391 Block::add(BlockId::from_static("egui_pop.devtools.inspect"), 95, pass),
392 );
393 Ok(())
394}
395
396fn on_the_copy_chord(app: &AppHandle) -> bool {
401 app.keys_for(&CMD_INSPECT).iter().any(|k| {
402 egui_pop_model::keymap::Keys::parse(k).is_ok_and(|keys| match keys.0.as_slice() {
403 [c] => c.key == "c" && c.shift && !c.alt && (c.ctrl || c.meta),
404 _ => false,
405 })
406 })
407}
408
409fn pass(ui: &mut Ui, app: &AppHandle) {
411 let ctx = ui.ctx().clone();
412 let on = super::enabled(app);
413 picker::arm(&ctx, on && on_the_copy_chord(app));
414 if !on && picker::active(&ctx) {
415 picker::stop(&ctx);
416 }
417 if picker::take_left(&ctx) {
418 app.publish("egui_pop", None, "inspect.left", Json::Null);
419 }
420 if let Some(pick) = picker::take_picked(&ctx) {
421 picked(app, pick);
422 }
423 let active = picker::active(&ctx);
424 let key = if active { "true" } else { "false" };
425 if app.context().get(CONTEXT_INSPECTING) != key {
426 app.set_context(CONTEXT_INSPECTING, key);
427 ctx.request_repaint();
428 }
429 if active {
430 hint(ui);
431 if !over_dialog(app, &ctx) {
432 ctx.set_cursor_icon(CURSOR);
433 }
434 }
435}
436
437fn over_dialog(app: &AppHandle, ctx: &egui::Context) -> bool {
440 let Some(id) = *shared(app).dialog.borrow() else {
441 return false;
442 };
443 let Some(pointer) = ctx.pointer_hover_pos() else {
444 return false;
445 };
446 egui_pop_core::overlay::rect(ctx, crate::dialogs::overlay_id(id))
447 .is_some_and(|r| r.contains(pointer))
448}
449
450fn picked(app: &AppHandle, pick: Pick) {
451 let st = shared(app);
452 let describe = st.describe.borrow().clone();
453 let inspected = Inspected::new(app, pick, describe.as_ref());
454 app.publish("egui_pop", None, "inspect.picked", inspected.json());
455 *st.last.borrow_mut() = Some(inspected);
456 *st.copied.borrow_mut() = false;
457 let Some(dialogs) = app.service(&DIALOGS) else {
458 return;
459 };
460 if st.dialog.borrow().is_some_and(|id| dialogs.is_open(id)) {
462 return;
463 }
464 let title = strings::tr(&app.egui(), &txt::INSPECT_TITLE);
465 let spec = DialogSpec::new(Custom::closing(&title).size(560.0, 420.0)).closable(true);
466 if let Ok(id) = dialogs.open_custom(app, spec, body) {
467 *st.dialog.borrow_mut() = Some(id);
468 }
469}
470
471fn body(ui: &mut Ui, app: &AppHandle, pass: &mut crate::dialogs::CustomPass) {
472 let Some(i) = last(app) else {
473 pass.cancel();
474 return;
475 };
476 pass.describe(i.json());
477 let ctx = ui.ctx().clone();
478 ui.horizontal(|ui| {
479 if ui.button(strings::tr(&ctx, &txt::INSPECT_COPY)).clicked()
480 && let Err(e) = copy(app)
481 {
482 app.publish(
483 "egui_pop",
484 None,
485 "inspect.copy_failed",
486 json!({ "error": e }),
487 );
488 }
489 if app.command(&crate::about::CMD_REPORT).is_some()
494 && ui
495 .button(strings::tr(&ctx, &txt::INSPECT_REPORT))
496 .on_hover_text(strings::tr(&ctx, &txt::INSPECT_REPORT_HOVER))
497 .clicked()
498 {
499 pass.cancel();
500 app.run(crate::about::CMD_REPORT, Json::Null);
501 }
502 if ui
503 .button(strings::tr(&ctx, &txt::INSPECT_PICK_ANOTHER))
504 .clicked()
505 {
506 pass.cancel();
507 let _ = start(app);
508 }
509 if *shared(app).copied.borrow() {
510 ui.label(strings::tr(&ctx, &txt::INSPECT_COPIED));
511 }
512 });
513 ui.separator();
514 ui.scroll_area(
515 egui::ScrollArea::vertical()
516 .id_salt("egui_pop.inspect.rows")
517 .auto_shrink([false, false]),
518 |ui| {
519 egui::Grid::new("egui_pop.inspect.grid")
520 .num_columns(2)
521 .striped(true)
522 .show(ui, |ui| {
523 for (k, v) in i.rows() {
524 ui.strong(k);
525 ui.add(egui::Label::new(egui::RichText::new(v).monospace()).wrap());
526 ui.end_row();
527 }
528 });
529 },
530 );
531}
532
533fn hint(ui: &Ui) {
535 let ctx = ui.ctx();
536 let t = egui_pop_core::theme::Tokens::of(ctx);
537 let text = strings::tr(ctx, &txt::INSPECT_HINT);
538 let painter = ctx.layer_painter(egui::LayerId::new(
539 egui::Order::Debug,
540 egui::Id::unique("egui_pop.inspect.hint"),
541 ));
542 let screen = ctx.content_rect();
543 let galley = painter.layout(
544 text,
545 egui::FontId::proportional(t.font.small),
546 t.text.on_accent,
547 (screen.width() - 4.0 * t.space.m).max(80.0),
548 );
549 let pad = egui::vec2(t.space.s, t.space.xs);
550 let size = galley.size() + 2.0 * pad;
551 let rect = egui::Rect::from_min_size(
552 egui::pos2(screen.center().x - size.x / 2.0, screen.top() + t.space.s),
553 size,
554 );
555 painter.rect_filled(rect, t.radius.widget, t.accent.default);
556 painter.galley(rect.min + pad, galley, t.text.on_accent);
557}
558
559pub(crate) fn button(ui: &mut Ui, app: &AppHandle) {
561 let label = strings::tr(ui.ctx(), &txt::INSPECT_BUTTON);
562 if egui_pop_core::widgets::selectable_label(ui, active(app), label).clicked() {
563 app.run(CMD_INSPECT, Json::Null);
564 }
565}