Skip to main content

egui_pop_api/
about.rs

1//! About the application, as a plugin ([`AboutPlugin`]): Help > About
2//! *application* opens a dialog with the application's name, icon,
3//! version, one-line description, licences, authors and links, and a
4//! "Copy version info" button for bug reports. The host describes the
5//! application with an [`AppInfo`].
6//!
7//! <div class="warning">Experimental: may change in any release
8//! (docs/stability.md).</div>
9//!
10//! Links open through egui's `Context::open_url` (a new tab on the web,
11//! the system's browser on the desktop).
12//!
13//! "Copy version info" copies plain text ([`AppInfo::version_info`]:
14//! the application's version, egui-pop's and egui's, the platform and
15//! the renderer when the host gave it) through the `clipboard.copy`
16//! step when [`crate::clipboard::ClipboardPlugin`] is connected (the
17//! `about.version` endpoint), else straight to the system clipboard.
18//!
19//! Commands: `about` (Help > About *application*; its title says
20//! `{ $application }`), for agents `about.read` (the same as JSON, kept
21//! out of the palette), and `help.report` (Help > Report a problem, the
22//! palette, the inspect dialog's Report button, the About dialog's link):
23//! a new issue opened in the browser, prefilled with the version info,
24//! the platform, the page shown and the last inspect pick ([`report`]);
25//! and `help.suggest` (Help > Suggest an idea, the palette): a new issue
26//! for an idea, prefilled with the page shown, in the repository's idea
27//! form when the plugin names one ([`AboutPlugin::idea_form`]). Both are
28//! declared only when the [`AppInfo`] says where issues
29//! go ([`AppInfo::issues`]): a library cannot know where an
30//! application's bugs belong, and a command leading nowhere is noise.
31//!
32//! With a journal recorder ([`AboutPlugin::journal`], [`journal`]),
33//! `help.report` first shows what the report attaches, in a dialog: the
34//! last minutes of the journal, redacted, the versions, the bus's points
35//! and the application's own context ([`AboutPlugin::context`]). Nothing
36//! leaves the machine on its own: its button copies the text and opens
37//! the issue, where the user pastes it (`help.report.send`). Agents read
38//! the same with `help.report.bundle`.
39//!
40//! ```
41//! use egui_pop_api::about::{ABOUT, AboutPlugin, AppInfo};
42//! use egui_pop_api::App;
43//!
44//! let info = AppInfo::new("Darkroom", "1.2.0")
45//!     .description("A photo editor.")
46//!     .licence("GPL-3.0-or-later")
47//!     .author("The Darkroom contributors")
48//!     .repository("https://example.org/darkroom");
49//! let app = App::builder()
50//!     .plugin(AboutPlugin::new(info))
51//!     .build(&egui::Context::default())
52//!     .unwrap();
53//! let about = app.handle().service(&ABOUT).unwrap();
54//! assert_eq!(about.info().name, "Darkroom");
55//! assert!(about.info().version_info().starts_with("Darkroom 1.2.0\n"));
56//! ```
57
58use std::fmt;
59use std::rc::Rc;
60use std::sync::{Arc, Mutex};
61
62use egui::Ui;
63use egui_pop_core::lock;
64use egui_pop_core::strings;
65use egui_pop_core::ui::{TextRole, UiPop as _};
66use egui_pop_model::clipboard::{ClipItem, TEXT};
67use egui_pop_model::commands::{CommandSpec, Origin};
68use egui_pop_model::ids::{CommandId, PluginId};
69use serde_json::{Value as Json, json};
70
71pub mod journal;
72pub mod report;
73
74use crate::app::{AppHandle, MENU_HELP};
75use crate::clipboard::{self, ClipSource, CopyRequest};
76use crate::dialogs::{Custom, DIALOGS};
77use crate::hooks::On;
78use crate::services::ServiceToken;
79use crate::steps::Outcome;
80use crate::strings as txt;
81use crate::{Ctx, Plugin, PluginError};
82
83/// The plugin's id.
84pub const ABOUT_PLUGIN: PluginId = PluginId::from_static("egui_pop.about");
85
86/// What the application says about itself, as a service.
87pub const ABOUT: ServiceToken<About> = ServiceToken::new("egui_pop.about");
88
89/// Help > About *application*.
90pub const CMD_ABOUT: CommandId = CommandId::from_static("about");
91/// The same, as JSON, for agents.
92pub const CMD_ABOUT_READ: CommandId = CommandId::from_static("about.read");
93/// Help > Report a problem: a prefilled new issue, in the browser.
94pub const CMD_REPORT: CommandId = CommandId::from_static("help.report");
95/// Help > Suggest an idea: a new issue for an idea, in the browser.
96pub const CMD_SUGGEST: CommandId = CommandId::from_static("help.suggest");
97/// The report dialog's button: copies the report and opens the issue.
98pub const CMD_REPORT_SEND: CommandId = CommandId::from_static("help.report.send");
99/// The report's attachment as JSON (the journal window, redacted), for
100/// agents.
101pub const CMD_REPORT_BUNDLE: CommandId = CommandId::from_static("help.report.bundle");
102
103/// The clipboard endpoint "Copy version info" copies from.
104pub const VERSION_ENDPOINT: &str = "about.version";
105
106/// egui-pop's version: its application API's.
107pub const EGUI_POP_VERSION: &str = env!("CARGO_PKG_VERSION");
108
109/// The egui series egui-pop is built against (one egui-pop minor per
110/// egui minor); a test keeps it in step with the workspace.
111pub const EGUI_VERSION: &str = "0.37";
112
113/// Draws the application's icon in a square of the given side.
114pub type IconFn = Arc<dyn Fn(&mut Ui, f32) + Send + Sync>;
115
116/// What the application says about itself: the host fills it.
117#[derive(Clone, Default)]
118pub struct AppInfo {
119    /// Its name; empty: the application's (`AppBuilder::name`).
120    pub name: String,
121    /// Its version, typically `env!("CARGO_PKG_VERSION")`.
122    pub version: String,
123    /// What it is, in one line.
124    pub description: String,
125    /// Its licences, as SPDX expressions (`MIT OR Apache-2.0`).
126    pub licences: Vec<String>,
127    pub authors: Vec<String>,
128    /// Its source code.
129    pub repository: Option<String>,
130    pub website: Option<String>,
131    pub docs: Option<String>,
132    /// Where to report a problem: the issue list
133    /// (`https://github.com/owner/repo/issues`). Set, `help.report`
134    /// opens a new issue under it, prefilled.
135    pub issues: Option<String>,
136    /// The repository's issue form `help.report` fills (`bug.yml`, in
137    /// `.github/ISSUE_TEMPLATE/`), its fields named as
138    /// [`report`]'s `FIELD_*`; without it, the report goes in the body.
139    pub issue_form: Option<String>,
140    /// What draws the interface (`wgpu: Vulkan, llvmpipe`), for the
141    /// version info; the host knows it.
142    pub renderer: Option<String>,
143    /// Its icon, drawn at the top of the dialog.
144    pub icon: Option<IconFn>,
145}
146
147impl fmt::Debug for AppInfo {
148    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
149        f.debug_struct("AppInfo")
150            .field("name", &self.name)
151            .field("version", &self.version)
152            .field("description", &self.description)
153            .field("licences", &self.licences)
154            .field("authors", &self.authors)
155            .field("repository", &self.repository)
156            .field("website", &self.website)
157            .field("docs", &self.docs)
158            .field("issues", &self.issues)
159            .field("issue_form", &self.issue_form)
160            .field("renderer", &self.renderer)
161            .field("icon", &self.icon.is_some())
162            .finish()
163    }
164}
165
166impl AppInfo {
167    pub fn new(name: &str, version: &str) -> Self {
168        Self {
169            name: name.into(),
170            version: version.into(),
171            ..Self::default()
172        }
173    }
174
175    pub fn description(mut self, text: &str) -> Self {
176        self.description = text.into();
177        self
178    }
179
180    /// Adds a licence (an SPDX expression).
181    pub fn licence(mut self, spdx: &str) -> Self {
182        self.licences.push(spdx.into());
183        self
184    }
185
186    pub fn author(mut self, author: &str) -> Self {
187        self.authors.push(author.into());
188        self
189    }
190
191    pub fn repository(mut self, url: &str) -> Self {
192        self.repository = Some(url.into());
193        self
194    }
195
196    pub fn website(mut self, url: &str) -> Self {
197        self.website = Some(url.into());
198        self
199    }
200
201    pub fn docs(mut self, url: &str) -> Self {
202        self.docs = Some(url.into());
203        self
204    }
205
206    /// Where to report a problem: the issue list. It turns
207    /// `help.report` on.
208    pub fn issues(mut self, url: &str) -> Self {
209        self.issues = Some(url.into());
210        self
211    }
212
213    /// The issue form `help.report` fills (`bug.yml`).
214    pub fn issue_form(mut self, file: &str) -> Self {
215        self.issue_form = Some(file.into());
216        self
217    }
218
219    pub fn renderer(mut self, renderer: &str) -> Self {
220        self.renderer = Some(renderer.into());
221        self
222    }
223
224    /// The icon, drawn by `f` in a square of the side it is given.
225    pub fn icon(mut self, f: impl Fn(&mut Ui, f32) + Send + Sync + 'static) -> Self {
226        self.icon = Some(Arc::new(f));
227        self
228    }
229
230    /// Where the application runs: the operating system and the
231    /// architecture, or the web with the browser and its operating
232    /// system, read from the user agent (`web (wasm32), Firefox 132 on
233    /// Linux`).
234    pub fn platform() -> String {
235        if cfg!(target_arch = "wasm32") {
236            match user_agent() {
237                Some(ua) => format!("web (wasm32), {}", report::describe_user_agent(&ua)),
238                None => "web (wasm32)".into(),
239            }
240        } else {
241            format!("{} {}", std::env::consts::OS, std::env::consts::ARCH)
242        }
243    }
244
245    /// The version info, as plain text for a bug report: the
246    /// application and its version, egui-pop's and egui's, the platform,
247    /// the renderer when known.
248    pub fn version_info(&self) -> String {
249        let mut lines = vec![
250            format!("{} {}", self.name, self.version).trim().to_string(),
251            format!("egui-pop {EGUI_POP_VERSION}"),
252            format!("egui {EGUI_VERSION}"),
253            format!("Platform: {}", Self::platform()),
254        ];
255        if let Some(r) = &self.renderer {
256            lines.push(format!("Renderer: {r}"));
257        }
258        lines.join("\n") + "\n"
259    }
260
261    /// Everything, as `about.read` answers it.
262    pub fn to_json(&self) -> Json {
263        json!({
264            "name": self.name,
265            "version": self.version,
266            "description": self.description,
267            "licences": self.licences,
268            "authors": self.authors,
269            "links": {
270                "repository": self.repository,
271                "website": self.website,
272                "docs": self.docs,
273                "issues": self.issues,
274            },
275            "issue_form": self.issue_form,
276            "egui_pop": EGUI_POP_VERSION,
277            "egui": EGUI_VERSION,
278            "platform": Self::platform(),
279            "renderer": self.renderer,
280            "version_info": self.version_info(),
281        })
282    }
283}
284
285/// The browser's user agent, on the web.
286fn user_agent() -> Option<String> {
287    #[cfg(all(target_arch = "wasm32", feature = "eframe"))]
288    {
289        eframe::web_sys::window().and_then(|w| w.navigator().user_agent().ok())
290    }
291    #[cfg(not(all(target_arch = "wasm32", feature = "eframe")))]
292    {
293        None
294    }
295}
296
297/// What the application says about itself.
298#[derive(Debug, Default)]
299pub struct About {
300    info: Mutex<AppInfo>,
301}
302
303impl About {
304    /// The application's info.
305    pub fn info(&self) -> AppInfo {
306        lock(&self.info).clone()
307    }
308
309    /// Changes it (the renderer, known once the window is up).
310    pub fn update(&self, f: impl FnOnce(&mut AppInfo)) {
311        f(&mut lock(&self.info));
312    }
313}
314
315/// Says which page or view is shown, for a report (`None`: it cannot).
316pub type PageFn = dyn Fn(&AppHandle) -> Option<String>;
317
318/// A part of the application's context a report attaches (the shape of
319/// its library, its layout, its settings that differ from the defaults),
320/// as JSON; redacted like the journal.
321pub type ContextFn = dyn Fn(&AppHandle) -> Json;
322
323/// Help > About *application*, `about.read` for agents, and
324/// `help.report` and `help.suggest` when the info says where issues go.
325#[derive(Default)]
326pub struct AboutPlugin {
327    info: AppInfo,
328    page: Option<Rc<PageFn>>,
329    idea_form: Option<String>,
330    journal: Option<journal::RecorderConfig>,
331    context: Vec<(String, Rc<ContextFn>)>,
332    alias: Option<(String, Rc<journal::AliasFn>)>,
333}
334
335impl fmt::Debug for AboutPlugin {
336    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
337        f.debug_struct("AboutPlugin")
338            .field("info", &self.info)
339            .field("page", &self.page.is_some())
340            .field("idea_form", &self.idea_form)
341            .field("journal", &self.journal)
342            .field("alias", &self.alias.as_ref().map(|(p, _)| p))
343            .field(
344                "context",
345                &self.context.iter().map(|(n, _)| n).collect::<Vec<_>>(),
346            )
347            .finish()
348    }
349}
350
351impl AboutPlugin {
352    pub fn new(info: AppInfo) -> Self {
353        Self {
354            info,
355            page: None,
356            idea_form: None,
357            journal: None,
358            context: Vec::new(),
359            alias: None,
360        }
361    }
362
363    /// Ids a report replaces by aliases (`photo-1`, `photo-2`…, numbered
364    /// in order of appearance across the report): every token (a run of
365    /// letters and digits) of its journal and context for which
366    /// `matches` says yes. For ids that are fingerprints, such as a
367    /// file's content hash.
368    pub fn alias(mut self, prefix: &str, matches: impl Fn(&str) -> bool + 'static) -> Self {
369        self.alias = Some((prefix.into(), Rc::new(matches)));
370        self
371    }
372
373    /// Records the journal for reports: the last minutes of it (5 by
374    /// default), redacted, kinds the configuration skips left out;
375    /// `help.report` then shows it before the issue opens.
376    pub fn journal(mut self, config: journal::RecorderConfig) -> Self {
377        self.journal = Some(config);
378        self
379    }
380
381    /// A part of the application's context a report attaches, under
382    /// `name` (`library`, `layout`, `settings`), read when the report is
383    /// made; redacted like the journal. The application keeps names,
384    /// paths and ids out of it: the redaction is a safety net.
385    pub fn context(mut self, name: &str, f: impl Fn(&AppHandle) -> Json + 'static) -> Self {
386        self.context.push((name.into(), Rc::new(f)));
387        self
388    }
389
390    /// The repository's issue form for ideas `help.suggest` fills
391    /// (`feature.yml`, in `.github/ISSUE_TEMPLATE/`), its page field
392    /// named [`report::FIELD_PAGE`]; without it, the idea goes in the
393    /// body.
394    pub fn idea_form(mut self, file: &str) -> Self {
395        self.idea_form = Some(file.into());
396        self
397    }
398
399    /// Says which page or view is shown, for `help.report`'s page field
400    /// and title.
401    pub fn page(mut self, f: impl Fn(&AppHandle) -> Option<String> + 'static) -> Self {
402        self.page = Some(Rc::new(f));
403        self
404    }
405}
406
407/// The page function, for [`report_of`], the idea form, the journal
408/// recorder and the report shown in its dialog.
409#[derive(Default)]
410struct Shared {
411    page: std::cell::RefCell<Option<Rc<PageFn>>>,
412    idea_form: std::cell::RefCell<Option<String>>,
413    recorder: std::cell::RefCell<Option<journal::Recorder>>,
414    redactor: std::cell::RefCell<journal::Redactor>,
415    context: std::cell::RefCell<Vec<(String, Rc<ContextFn>)>>,
416    alias: std::cell::RefCell<Option<(String, Rc<journal::AliasFn>)>>,
417    /// The report the dialog shows, as its button copies it.
418    shown: std::cell::RefCell<Option<String>>,
419}
420
421/// The version info, as the `about.version` endpoint copies it.
422struct VersionSource;
423
424impl ClipSource for VersionSource {
425    fn copy(&self, app: &AppHandle) -> Option<ClipItem> {
426        let text = app.service(&ABOUT)?.info().version_info();
427        Some(ClipItem::new(TEXT, 0, json!(text), "Version info").fallback(TEXT, json!(text)))
428    }
429}
430
431impl Plugin for AboutPlugin {
432    fn id(&self) -> PluginId {
433        ABOUT_PLUGIN
434    }
435
436    fn title(&self) -> String {
437        "About".into()
438    }
439
440    fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
441        const CAT: &str = "Help";
442        let mut info = self.info.clone();
443        if info.name.is_empty() {
444            info.name = ctx.app().name();
445        }
446        ctx.service(
447            &ABOUT,
448            About {
449                info: Mutex::new(info),
450            },
451        )?;
452        ctx.clip_endpoint(VERSION_ENDPOINT, Some(Rc::new(VersionSource)), None);
453        *ctx.app().local::<Shared>().page.borrow_mut() = self.page.clone();
454        *ctx.app().local::<Shared>().idea_form.borrow_mut() = self.idea_form.clone();
455        if let Some(config) = &self.journal {
456            let shared = ctx.app().local::<Shared>();
457            *shared.recorder.borrow_mut() = Some(journal::Recorder::new(config.clone()));
458            *shared.redactor.borrow_mut() = journal::Redactor::current();
459            *shared.context.borrow_mut() = self.context.clone();
460            *shared.alias.borrow_mut() = self.alias.clone();
461            ctx.on(On::Pass, |app, _| record(app));
462            ctx.command(
463                CommandSpec::new(CMD_REPORT_BUNDLE, "Read the problem report", CAT)
464                    .description("What Report a problem attaches, as JSON: the last minutes of the journal, redacted, the versions, the bus's points and the application's context.")
465                    .hidden()
466                    .read_only()
467                    .private(),
468                |call| {
469                    let bundle = report_bundle(call.app)?;
470                    serde_json::to_value(&bundle).map_err(|e| e.to_string())
471                },
472            )?;
473        }
474        if self.info.issues.is_some() {
475            ctx.command(
476                CommandSpec::new(CMD_REPORT, "Report a problem", CAT)
477                    .description("Opens a new issue in the browser, prefilled with the version info, the platform, the page shown and the last element inspected; with a journal recorded, shows what the report attaches first.")
478                    .menu(MENU_HELP, "8_report", 0),
479                |call| {
480                    let url = report_url(call.app)?;
481                    if recording(call.app) && call.app.service(&DIALOGS).is_some() {
482                        let dialog = open_bundle(call.app)?;
483                        return Ok(json!({ "url": url.url, "trimmed": url.trimmed, "dialog": dialog }));
484                    }
485                    open_report(call.app, &url.url)?;
486                    Ok(json!({ "url": url.url, "trimmed": url.trimmed }))
487                },
488            )?
489            .command(
490                CommandSpec::new(CMD_REPORT_SEND, "Copy the report and open the issue", CAT)
491                    .description("Copies the report shown by Report a problem and opens the new issue in the browser, to paste it there.")
492                    .hidden(),
493                |call| {
494                    let text = call
495                        .app
496                        .local::<Shared>()
497                        .shown
498                        .borrow_mut()
499                        .take()
500                        .ok_or("no report is shown")?;
501                    call.app.egui().copy_text(text.clone());
502                    let url = report_url(call.app)?;
503                    open_report(call.app, &url.url)?;
504                    Ok(json!({ "url": url.url, "copied": text.len() }))
505                },
506            )?
507            .command(
508                CommandSpec::new(CMD_SUGGEST, "Suggest an idea", CAT)
509                    .description("Opens a new issue for an idea in the browser, prefilled with the page shown.")
510                    .menu(MENU_HELP, "8_report", 1),
511                |call| {
512                    let url = idea_url(call.app)?;
513                    open_report(call.app, &url.url)?;
514                    Ok(json!({ "url": url.url, "trimmed": url.trimmed }))
515                },
516            )?;
517        }
518        ctx.command(
519            CommandSpec::new(CMD_ABOUT, "About { $application }", CAT)
520                .description("The application's name, version, licence, authors and links, with its version info to copy.")
521                .icon("info")
522                .menu(MENU_HELP, "9_about", 0),
523            |call| open(call.app).map(|_| Json::Null),
524        )?;
525        ctx.command(
526            CommandSpec::new(CMD_ABOUT_READ, "Read about the application", CAT)
527                .description("The application's name, version, description, licences, authors and links, egui-pop's and egui's versions, the platform, the renderer and the version info as text.")
528                .hidden()
529                .read_only(),
530            |call| {
531                let about = call
532                    .app
533                    .service(&ABOUT)
534                    .ok_or("the about plugin is not connected")?;
535                Ok(about.info().to_json())
536            },
537        )?;
538        Ok(())
539    }
540}
541
542/// The dialog's title, in the interface's language.
543pub fn title(ctx: &egui::Context, info: &AppInfo) -> String {
544    strings::tr_args(ctx, &txt::ABOUT_TITLE, &[("application", &info.name)])
545}
546
547/// Opens the About dialog (it needs [`AboutPlugin`] and the dialogs
548/// plugin); returns the dialog's id.
549pub fn open(app: &AppHandle) -> Result<u64, String> {
550    let about = app
551        .service(&ABOUT)
552        .ok_or("the about plugin is not connected")?;
553    let dialogs = app
554        .service(&DIALOGS)
555        .ok_or("the dialogs plugin is not connected")?;
556    let info = about.info();
557    let spec = Custom::closing(&title(&app.egui(), &info)).size(440.0, 300.0);
558    let mut copied = false;
559    dialogs.open_custom(app, spec, move |ui, app, pass| {
560        pass.describe(about.info().to_json());
561        ui.scroll_area(
562            egui::ScrollArea::vertical().auto_shrink([false, false]),
563            |ui| copied |= show(ui, app, copied),
564        );
565    })
566}
567
568/// Copies the version info: through the clipboard's `clipboard.copy`
569/// step when its plugin is connected, else to the system clipboard.
570pub fn copy_version_info(app: &AppHandle) -> Result<(), String> {
571    let connected = app
572        .plugins()
573        .iter()
574        .any(|p| p.id == clipboard::PLUGIN && p.connected);
575    if connected {
576        return match clipboard::copy(app, CopyRequest::new(VERSION_ENDPOINT), &Origin::User) {
577            Outcome::Done(r) => r.map(|_| ()),
578            Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
579        };
580    }
581    let about = app
582        .service(&ABOUT)
583        .ok_or("the about plugin is not connected")?;
584    app.egui().copy_text(about.info().version_info());
585    Ok(())
586}
587
588/// What a report says: the version info, the platform, the page shown
589/// (when the application says it), the last inspect pick.
590pub fn report_of(app: &AppHandle) -> Result<report::Report, String> {
591    let about = app
592        .service(&ABOUT)
593        .ok_or("the about plugin is not connected")?;
594    let info = about.info();
595    let platform = AppInfo::platform();
596    let version: String = info
597        .version_info()
598        .lines()
599        .filter(|l| !l.starts_with("Platform: "))
600        .map(|l| format!("{l}\n"))
601        .collect();
602    let page = app
603        .local::<Shared>()
604        .page
605        .borrow()
606        .clone()
607        .and_then(|f| f(app));
608    let title = match &page {
609        Some(p) => format!("Problem in {p}"),
610        None => format!("Problem in {}", info.name),
611    };
612    let pick = crate::devtools::inspect::last(app).map(|i| i.text());
613    Ok(report::Report {
614        title,
615        version,
616        platform,
617        page,
618        pick,
619    })
620}
621
622/// The new-issue URL `help.report` opens (it needs [`AboutPlugin`] with
623/// [`AppInfo::issues`]).
624pub fn report_url(app: &AppHandle) -> Result<report::IssueUrl, String> {
625    let about = app
626        .service(&ABOUT)
627        .ok_or("the about plugin is not connected")?;
628    let info = about.info();
629    let issues = info
630        .issues
631        .as_deref()
632        .ok_or("the application says nowhere to report issues")?;
633    Ok(report_of(app)?.url(issues, info.issue_form.as_deref()))
634}
635
636/// The new-issue URL `help.suggest` opens: the idea form, prefilled
637/// with the page shown (it needs [`AboutPlugin`] with
638/// [`AppInfo::issues`]).
639pub fn idea_url(app: &AppHandle) -> Result<report::IssueUrl, String> {
640    let about = app
641        .service(&ABOUT)
642        .ok_or("the about plugin is not connected")?;
643    let info = about.info();
644    let issues = info
645        .issues
646        .as_deref()
647        .ok_or("the application says nowhere to report issues")?;
648    let mut report = report_of(app)?;
649    report.title = match &report.page {
650        Some(p) => format!("Idea for {p}"),
651        None => format!("Idea for {}", info.name),
652    };
653    let form = app.local::<Shared>().idea_form.borrow().clone();
654    Ok(report.idea_url(issues, form.as_deref()))
655}
656
657/// Whether the journal is recorded for reports.
658pub fn recording(app: &AppHandle) -> bool {
659    app.local::<Shared>().recorder.borrow().is_some()
660}
661
662/// Reads the journal's new entries into the recorder.
663fn record(app: &AppHandle) {
664    let shared = app.local::<Shared>();
665    let last = match shared.recorder.borrow().as_ref() {
666        Some(r) => r.last(),
667        None => return,
668    };
669    let events = app.events_since(last);
670    let redactor = shared.redactor.borrow();
671    if let Some(r) = shared.recorder.borrow_mut().as_mut() {
672        r.record(web_time::Instant::now(), &events, &redactor);
673    }
674}
675
676/// What a report attaches (it needs [`AboutPlugin::journal`]): the
677/// journal's window, redacted, the versions, the page shown, the bus's
678/// points and the application's context.
679pub fn report_bundle(app: &AppHandle) -> Result<journal::Bundle, String> {
680    record(app);
681    let shared = app.local::<Shared>();
682    let report = report_of(app)?;
683    let now = web_time::Instant::now();
684    let recorder = shared.recorder.borrow();
685    let recorder = recorder
686        .as_ref()
687        .ok_or("the journal is not recorded (AboutPlugin::journal)")?;
688    let redactor = shared.redactor.borrow();
689    let mut context = std::collections::BTreeMap::new();
690    for (name, f) in shared.context.borrow().iter() {
691        let mut v = f(app);
692        redactor.json(&mut v);
693        context.insert(name.clone(), v);
694    }
695    let (missed, capped) = recorder.lost();
696    let mut entries = recorder.window(now);
697    if let Some((prefix, matches)) = shared.alias.borrow().as_ref() {
698        let mut aliases = journal::Aliases::new(prefix, &**matches);
699        for e in &mut entries {
700            aliases.json(&mut e.data);
701        }
702        for v in context.values_mut() {
703            aliases.json(v);
704        }
705    }
706    Ok(journal::Bundle {
707        version: report.version,
708        platform: report.platform,
709        page: report.page.map(|p| redactor.text(&p)),
710        window_s: recorder.config().window.as_secs(),
711        missed,
712        capped,
713        journal: entries,
714        context,
715        bus: journal::bus_description(&*app.bus()),
716    })
717}
718
719/// The settings that differ from their defaults, by id, for a report's
720/// context ([`AboutPlugin::context`]): numbers, switches and choices as
721/// they are; a free text only as `"<text>"`, since it may name a person,
722/// a place or a path.
723pub fn changed_settings(app: &AppHandle) -> Json {
724    use egui_pop_model::values::Value;
725    let store = app.store();
726    let store = lock(&store);
727    let mut out = serde_json::Map::new();
728    for s in app.settings() {
729        let Some(entry) = store.get(&s.path) else {
730            continue;
731        };
732        if entry.value == s.descriptor.default {
733            continue;
734        }
735        let v = match &entry.value {
736            Value::Text(_) => Json::from("<text>"),
737            other => serde_json::to_value(other).unwrap_or(Json::Null),
738        };
739        out.insert(s.id.to_string(), v);
740    }
741    Json::Object(out)
742}
743
744/// Opens the dialog showing what a report attaches; its button copies
745/// it and opens the issue (`help.report.send`).
746fn open_bundle(app: &AppHandle) -> Result<u64, String> {
747    let dialogs = app
748        .service(&DIALOGS)
749        .ok_or("the dialogs plugin is not connected")?;
750    let bundle = report_bundle(app)?;
751    let text = bundle.text();
752    *app.local::<Shared>().shown.borrow_mut() = Some(text.clone());
753    let ctx = app.egui();
754    let minutes = bundle.window_s.div_ceil(60).to_string();
755    let intro = strings::tr_args(&ctx, &txt::REPORT_INTRO, &[("minutes", &minutes)]);
756    let spec = Custom::new(
757        &strings::tr(&ctx, &txt::ABOUT_ISSUES),
758        &strings::tr(&ctx, &txt::REPORT_SEND),
759        CMD_REPORT_SEND,
760    )
761    .size(640.0, 420.0);
762    let entries = bundle.journal.len();
763    let bytes = text.len();
764    dialogs.open_custom(app, spec, move |ui, _app, pass| {
765        pass.describe(json!({ "entries": entries, "bytes": bytes }));
766        ui.label(&intro);
767        ui.add_space(6.0);
768        ui.scroll_area(egui::ScrollArea::both().auto_shrink([false, false]), |ui| {
769            ui.add(egui::Label::new(egui::RichText::new(&text).monospace()).selectable(true));
770        });
771    })
772}
773
774/// Opens the URL: through the links service when its plugin is
775/// connected (a new tab on the web, the system's browser on the
776/// desktop), else egui's `open_url`.
777fn open_report(app: &AppHandle, url: &str) -> Result<(), String> {
778    if crate::links::links(app).is_none() {
779        app.egui().open_url(egui::OpenUrl::new_tab(url));
780        return Ok(());
781    }
782    let label = strings::tr(&app.egui(), &txt::ABOUT_ISSUES);
783    match crate::links::open(app, egui_pop_model::links::Request::new(url).label(&label)) {
784        Outcome::Done(r) => r.map(|_| ()),
785        Outcome::Vetoed { by, reason } => Err(format!("vetoed by {by}: {reason}")),
786    }
787}
788
789fn link(ui: &mut Ui, label: &str, url: &Option<String>) {
790    if let Some(url) = url {
791        ui.hyperlink_to(label, url).on_hover_text(url);
792    }
793}
794
795/// Draws what the application says about itself (it needs
796/// [`AboutPlugin`]): the About dialog's body, also usable in a page.
797/// `copied`: the version info was copied (the button says so). Returns
798/// whether the version info was copied this pass.
799pub fn show(ui: &mut Ui, app: &AppHandle, copied: bool) -> bool {
800    let Some(about) = app.service(&ABOUT) else {
801        return false;
802    };
803    let info = about.info();
804    let ctx = ui.ctx().clone();
805    ui.horizontal(|ui| {
806        if let Some(icon) = &info.icon {
807            icon(ui, 48.0);
808        }
809        ui.vertical(|ui| {
810            ui.text_role(TextRole::Title, &info.name);
811            if !info.version.is_empty() {
812                ui.text_role(
813                    TextRole::Meta,
814                    strings::tr_args(&ctx, &txt::ABOUT_VERSION, &[("version", &info.version)]),
815                );
816            }
817        });
818    });
819    if !info.description.is_empty() {
820        ui.add_space(4.0);
821        ui.label(&info.description);
822    }
823    ui.add_space(8.0);
824    egui::Grid::new("egui_pop.about.facts")
825        .num_columns(2)
826        .spacing([12.0, 4.0])
827        .show(ui, |ui| {
828            if !info.licences.is_empty() {
829                ui.text_role(TextRole::Muted, strings::tr(&ctx, &txt::ABOUT_LICENCE));
830                ui.label(info.licences.join(", "));
831                ui.end_row();
832            }
833            if !info.authors.is_empty() {
834                ui.text_role(TextRole::Muted, strings::tr(&ctx, &txt::ABOUT_AUTHORS));
835                ui.label(info.authors.join(", "));
836                ui.end_row();
837            }
838        });
839    ui.add_space(8.0);
840    ui.horizontal_wrapped(|ui| {
841        link(
842            ui,
843            &strings::tr(&ctx, &txt::ABOUT_REPOSITORY),
844            &info.repository,
845        );
846        link(ui, &strings::tr(&ctx, &txt::ABOUT_WEBSITE), &info.website);
847        link(ui, &strings::tr(&ctx, &txt::ABOUT_DOCS), &info.docs);
848        // Reporting goes through `help.report`, prefilled; the bare
849        // issue list only when the command is not there.
850        let issues = strings::tr(&ctx, &txt::ABOUT_ISSUES);
851        if app.command(&CMD_REPORT).is_some() {
852            let hover = info.issues.clone().unwrap_or_default();
853            if ui.link(&issues).on_hover_text(hover).clicked() {
854                app.run(CMD_REPORT, Json::Null);
855            }
856        } else {
857            link(ui, &issues, &info.issues);
858        }
859    });
860    ui.add_space(8.0);
861    let mut now = false;
862    ui.horizontal(|ui| {
863        if ui
864            .button(strings::tr(&ctx, &txt::ABOUT_COPY))
865            .on_hover_text(info.version_info())
866            .clicked()
867        {
868            match copy_version_info(app) {
869                Ok(()) => now = true,
870                Err(e) => log::warn!("about: {e}"),
871            }
872        }
873        if copied || now {
874            ui.text_role(TextRole::Muted, strings::tr(&ctx, &txt::ABOUT_COPIED));
875        }
876    });
877    now
878}