diff --git a/apps/rustgis/src/main.rs b/apps/rustgis/src/main.rs index 22dab12f83..89a8e2c061 100644 --- a/apps/rustgis/src/main.rs +++ b/apps/rustgis/src/main.rs @@ -801,6 +801,8 @@ fn main() -> eframe::Result { // The marker, shared from here: what runs is noted in it, start-up commands (a project or file // opened) included, so a run that ends without closing says what it was doing. let other_copy = marker.as_ref().is_err_and(|no| no.other_copy); + // Without a marker an unclean exit isn't noticed, so the report can't say the last run closed. + let tracked = marker.is_ok(); let marker: running::Shared = std::sync::Arc::new(std::sync::Mutex::new(marker.ok())); let crumbs = marker.clone(); app.session.on_run = Some(Box::new(move |run| running::note(&crumbs, run))); @@ -816,7 +818,12 @@ fn main() -> eframe::Result { if crashed.is_some() || unclean { // Notices are shown as written: translate this one now that the language is known. rustgis_ui_egui::i18n::set_current(app.chosen_lang()); - app.session.notify(last_run_notice(&app, crashed.as_deref(), unclean, last_command.as_ref()), true); + let notice = last_run_notice(&app, crashed.as_deref(), unclean, last_command.as_ref()); + // Kept for Report a Problem too: Messages may have let it go by then. + app.last_run = rustgis_engine::problem_report::LastRun::Left(notice.clone()); + app.session.notify(notice, true); + } else if tracked { + app.last_run = rustgis_engine::problem_report::LastRun::Closed; } if let Some(e) = no_autosave { log::warn!("no autosave: {e}"); diff --git a/apps/rustgis/src/menu.rs b/apps/rustgis/src/menu.rs index a6c033a922..5481e7ab6b 100644 --- a/apps/rustgis/src/menu.rs +++ b/apps/rustgis/src/menu.rs @@ -145,6 +145,7 @@ const MENUS: &[(&str, &[Entry])] = &[ Item("RustGIS Help", Command("ui.learn", ""), None), Item("Keyboard Shortcuts", Command("ui.shortcuts", ""), None), Separator, + Item("Report a Problem", Command("ui.reportProblem", ""), None), Item("Report an Issue", Command("ui.learn", r#"{"url":"https://github.com/opengeos/RustGIS/issues/new/choose"}"#), None), ], ), diff --git a/crates/data/src/incident.rs b/crates/data/src/incident.rs index c7fb800291..d661d119a3 100644 --- a/crates/data/src/incident.rs +++ b/crates/data/src/incident.rs @@ -125,6 +125,11 @@ pub fn caught(payload: &(dyn std::any::Any + Send)) -> Incident { incident } +/// The incidents kept, oldest first: for a bug report. +pub fn kept() -> Vec { + lock(&RECENT).iter().cloned().collect() +} + /// An incident kept by its reference. pub fn find(id: &str) -> Option { lock(&RECENT).iter().rev().find(|i| i.id == id).cloned() diff --git a/crates/engine/src/cmd/webdata.rs b/crates/engine/src/cmd/webdata.rs index d65a153630..d5970f1f13 100644 --- a/crates/engine/src/cmd/webdata.rs +++ b/crates/engine/src/cmd/webdata.rs @@ -329,7 +329,7 @@ fn national_map_template(s: &NmService) -> String { } /// A query value with everything but letters, digits and `-_.~` percent-encoded. -fn percent_encode(s: &str) -> String { +pub(crate) fn percent_encode(s: &str) -> String { s.bytes() .map(|b| { if b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b'~') { diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 92c20da669..21671acf88 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -30,6 +30,7 @@ pub mod shape_conversion; pub use peer::Peer; pub(crate) use roles::{Document, ParamRole, Role}; mod parameters; +pub mod problem_report; pub mod project_log; mod received; pub use parameters::{params_envelope, script_line, split_script_id}; diff --git a/crates/engine/src/problem_report.rs b/crates/engine/src/problem_report.rs new file mode 100644 index 0000000000..45c359d49e --- /dev/null +++ b/crates/engine/src/problem_report.rs @@ -0,0 +1,277 @@ +//! What a bug report needs from this session, as one text the user reads before sharing it: the +//! RustGIS and computer it ran on, the bugs it met ([`rustgis_data::incident`]), the last commands +//! as Script pane lines to run again, and the Messages history. Logins and secrets are taken out: +//! the free text by [`Session::redacted`], a command's parameters as the session log kept them +//! (secrets already out) with addresses and active logins scrubbed, and Messages as the history +//! kept them (redacted as they were said). File paths and layer names stay, as the report needs +//! them, and the user sees them before anything is copied. + +use std::fmt::Write; + +use rustgis_data::diagnostics::Filter; + +use crate::Session; +use crate::project_log::LogEntry; + +/// The most commands the report gives, the newest. +pub const COMMANDS: usize = 50; + +/// What only the front end knows. +#[derive(Clone, Debug, Default)] +pub struct About { + /// The front end: `desktop`, `browser`, `phone`. + pub front_end: String, + /// The graphics the map is drawn with (backend, adapter, driver), when it says. + pub graphics: Option, + /// What the last run of the app left. + pub last_run: LastRun, +} + +/// How the app's last run ended, as its shell knows it. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub enum LastRun { + /// The shell doesn't keep track (the browser, the phone), or couldn't this time. + #[default] + NotReported, + Closed, + /// It didn't close normally, or met an internal error: the shell's notice, which says what + /// it was running. + Left(String), +} + +impl Session { + /// The report, logins and secrets taken out. Each section says when it is empty, so a reader + /// tells "none" from "left out". + pub fn problem_report(&self, about: &About) -> String { + let mut out = self.report_head(about); + out.push_str(&self.commands_section()); + let messages = self.diagnostics.report(Filter::All); + // The history's own heading, under this one. + let messages = messages.split_once('\n').map_or(messages.as_str(), |(_, rest)| rest); + let _ = writeln!(out, "\n## Messages ({})", self.diagnostics.records().len()); + out.push_str(messages); + out + } + + /// The app, the computer, the last run and the incidents. Each part is redacted on its own: + /// the redaction bounds what it is given, and the whole of them could pass that bound, cutting + /// the newest incidents or putting all of it out. + fn report_head(&self, about: &About) -> String { + let redacted = |text: &str| Self::redacted(text).into_string(); + let mut out = String::from("RustGIS diagnostics\n"); + let _ = writeln!(out, "Version: {}", env!("CARGO_PKG_VERSION")); + let _ = writeln!(out, "System: {} {}", std::env::consts::OS, std::env::consts::ARCH); + if !about.front_end.is_empty() { + let _ = writeln!(out, "Front end: {}", about.front_end); + } + let graphics = about.graphics.as_deref().map_or_else(|| "not reported".to_string(), redacted); + let _ = writeln!(out, "Graphics: {graphics}"); + let _ = writeln!(out, "Threads: {} of {} cores", rustgis_data::threads::max(), rustgis_data::threads::cores()); + let last_run = match &about.last_run { + LastRun::NotReported => "not reported".to_string(), + LastRun::Closed => "closed normally".to_string(), + LastRun::Left(notice) => redacted(notice), + }; + let _ = writeln!(out, "Last run: {last_run}"); + + let incidents = rustgis_data::incident::kept(); + let _ = writeln!(out, "\n## Incidents ({})", incidents.len()); + if incidents.is_empty() { + out.push_str("None this session.\n"); + } + for incident in &incidents { + // The reference and version as they are (the reference is six hexadecimal digits), so a + // message past the redaction's bound, which puts all of it out, doesn't take them too. + let _ = writeln!(out, "\nIncident {} in RustGIS {}", incident.id, env!("CARGO_PKG_VERSION")); + let _ = writeln!(out, "{}", redacted(&incident.message)); + if let Some(at) = &incident.location { + let _ = writeln!(out, "at {}", redacted(at)); + } + } + out + } + + /// The last [`COMMANDS`] commands as Script pane lines, oldest first, each after a comment + /// saying when it ran and how it ended: one that failed says its error, and one the log kept + /// less of (cut to fit, secrets taken out) or that a script can't run says so, as it + /// wouldn't run again as it ran. + fn commands_section(&self) -> String { + let (entries, _, total) = self.log.select(|_| true, COMMANDS); + let mut out = format!("\n## Last commands ({} of {total}), as a script\n", entries.len()); + if !self.log.on() { + out.push_str("# The session log is turned off: commands since then aren't listed.\n"); + } + if let Some(dropped) = self.log.dropped_said() { + let _ = writeln!(out, "# {dropped}."); + } + if entries.is_empty() { + out.push_str("None this session.\n"); + } + for e in &entries { + let ended = match &e.error { + Some(error) => format!("failed: {}", error.replace('\n', " ")), + None if e.ok => "ok".to_string(), + None => "failed".to_string(), + }; + let mut said = vec![format!("{} UTC, {} ms, {ended}", e.time_utc(), e.millis)]; + // Its parameters as the log kept them, secrets out, with addresses and logins in use + // scrubbed now, value by value before they are written as JSON (whose escapes would + // hide a login with a quote in it); a redaction made for prose would take the JSON + // out with them. A scrub that changed them changed what it runs. + let scrubbed = LogEntry { params: scrubbed_values(&e.params), ..e.clone() }; + let line = scrubbed.script_line(); + if e.partial || scrubbed.params != e.params { + said.push("its parameters were cut or had secrets taken out, so it may not run as it ran".into()); + } + let scriptable = self.registry.get(&e.command).is_some() && !crate::cmd::workflows::refused_in_script(&e.command); + if !scriptable { + said.push("a script can't run it".into()); + } + let said = Self::redacted(&said.join("; ")).into_string(); + let _ = writeln!(out, "# {}", said.replace('\n', " ")); + if scriptable { + let _ = writeln!(out, "{line}"); + } else { + let _ = writeln!(out, "# {line}"); + } + } + out + } +} + +/// `params` with each text in it, keys too, scrubbed of addresses' logins and the logins in use; a +/// number too, as a login can be one, given as text when the scrub changed it. +fn scrubbed_values(params: &serde_json::Value) -> serde_json::Value { + use serde_json::Value; + match params { + Value::String(s) => Value::String(crate::durable::generated_text(s)), + Value::Number(n) => { + let text = n.to_string(); + let scrubbed = crate::durable::generated_text(&text); + if scrubbed == text { params.clone() } else { Value::String(scrubbed) } + } + Value::Array(items) => Value::Array(items.iter().map(scrubbed_values).collect()), + Value::Object(map) => Value::Object(map.iter().map(|(k, v)| (crate::durable::generated_text(k), scrubbed_values(v))).collect()), + other => other.clone(), + } +} + +/// Where a new bug report starts: the repository's bug report form. +pub const NEW_ISSUE: &str = "https://github.com/opengeos/RustGIS/issues/new"; + +/// A new bug report on GitHub, its form filled in with the version and the system and graphics +/// (`about`), which go to GitHub as the form opens; its logs field asks for the report to be +/// pasted, so the report itself goes only once the user pastes it and submits. +pub fn issue_address(about: &About) -> String { + let mut system = format!("{} {}", std::env::consts::OS, std::env::consts::ARCH); + if !about.front_end.is_empty() { + let _ = write!(system, ", {}", about.front_end); + } + if let Some(graphics) = &about.graphics { + // Redacted as the report's own line is. + let _ = write!(system, ", {}", Session::redacted(graphics).as_str()); + } + let logs = "Paste the diagnostics from Help › Report a Problem here: Report on GitHub put them on the clipboard."; + let fields = [("template", "bug_report.yml"), ("version", env!("CARGO_PKG_VERSION")), ("os", system.as_str()), ("screenshots", logs)]; + let query: Vec = fields.iter().map(|(k, v)| format!("{k}={}", crate::cmd::webdata::percent_encode(v))).collect(); + format!("{NEW_ISSUE}?{}", query.join("&")) +} + +/// `report` as it is pasted into the form: in a fence longer than any run of backticks in it, so +/// none of it ends the fence and reads as the form's Markdown. +pub fn fenced(report: &str) -> String { + let mut fence = "```".to_string(); + while report.contains(fence.as_str()) { + fence.push('`'); + } + format!("{fence}text\n{report}\n{fence}") +} + +#[cfg(test)] +mod tests { + use serde_json::json; + + use super::*; + use crate::Project; + + fn entry(command: &str, params: serde_json::Value) -> LogEntry { + LogEntry { command: command.into(), params, ok: true, ..Default::default() } + } + + #[test] + fn the_report_names_the_app_the_bugs_the_commands_and_the_messages() { + rustgis_data::incident::install(); + let mut s = Session::new(Project::default()); + s.log.clear(); + s.diagnostics.clear(); + let payload = std::panic::catch_unwind(|| panic!("a report's own bug")).unwrap_err(); + let incident = rustgis_data::incident::caught(payload.as_ref()); + s.log.push(entry("map.new", json!({"name": "Parcels"}))); + s.log.push(LogEntry { error: Some("no such file".into()), ok: false, ..entry("layer.addData", json!({"path": "/x/a.shp"})) }); + s.log.push(LogEntry { partial: true, ..entry("map.new", json!({"name": "S…"})) }); + s.log.push(entry("script.run", json!({"script": "map.new"}))); + s.log.push(entry("layer.addData", json!({"path": "https://user:secret@example.org/a.geojson?token=private"}))); + s.notify("Read 3 features https://user:secret@example.org/?token=private", false); + let about = About { front_end: "desktop".into(), graphics: Some("Vulkan, Test GPU".into()), last_run: LastRun::Closed }; + let report = s.problem_report(&about); + assert!(report.contains(&format!("Version: {}", env!("CARGO_PKG_VERSION"))), "{report}"); + assert!(report.contains("Graphics: Vulkan, Test GPU") && report.contains("Last run: closed normally"), "{report}"); + assert!(report.contains(&format!("Incident {}", incident.id)) && report.contains("a report's own bug"), "{report}"); + // The commands run again as a script; the failed one says why, the cut one says so. + assert!(report.contains("\nmap.new {\"name\":\"Parcels\"}\n"), "{report}"); + assert!(report.contains("failed: no such file\nlayer.addData {\"path\":\"/x/a.shp\"}\n"), "{report}"); + assert!(report.contains("may not run as it ran\nmap.new {\"name\":\"S…\"}\n"), "{report}"); + assert!(report.contains("a script can't run it\n# script.run"), "{report}"); + assert!(report.contains("Read 3 features") && report.contains("example.org"), "{report}"); + // A login in an address is taken out of a command's parameters and of a message alike. + assert!(report.contains("layer.addData {\"path\":\"https://example.org/"), "{report}"); + // Scrubbed now, it no longer runs as it ran, and says so. + assert!(report.contains("may not run as it ran\nlayer.addData {\"path\":\"https://example.org/"), "{report}"); + assert!(!report.contains("user:secret") && !report.contains("token=private"), "{report}"); + } + + #[test] + fn the_issue_address_fills_the_form_but_leaves_the_report_out() { + let about = About { front_end: "desktop".into(), graphics: Some("Vulkan & co".into()), last_run: LastRun::NotReported }; + let address = issue_address(&about); + assert!(address.starts_with(NEW_ISSUE) && address.contains("template=bug_report.yml"), "{address}"); + // Values are escaped: an `&` doesn't start another field. + assert!(address.contains("desktop%2C%20Vulkan%20%26%20co") && address.contains("Paste%20the%20diagnostics"), "{address}"); + // Backticks in the report don't end its fence. + assert_eq!(fenced("a ``` b"), "````text\na ``` b\n````"); + } + + /// Incidents past the redaction's bound together are each kept whole, and the lines above + /// them too. + #[test] + fn many_long_incidents_keep_the_head_and_each_other() { + rustgis_data::incident::install(); + let s = Session::new(Project::default()); + let ids: Vec = (0..6) + .map(|i| { + // The last past the redaction's whole bound, which puts its message out. + let long = if i == 5 { 20_000 } else { 4000 }; + let payload = std::panic::catch_unwind(move || panic!("long bug {i} {}", "x".repeat(long))).unwrap_err(); + rustgis_data::incident::caught(payload.as_ref()).id + }) + .collect(); + let report = s.problem_report(&About::default()); + assert!(report.starts_with("RustGIS diagnostics\nVersion: "), "{report}"); + for id in &ids { + assert!(report.contains(&format!("Incident {id}")), "{id}"); + } + } + + #[test] + fn an_empty_session_says_each_section_is_empty() { + let mut s = Session::new(Project::default()); + s.log.clear(); + s.diagnostics.clear(); + let report = s.problem_report(&About::default()); + assert!(report.contains("Last run: not reported"), "{report}"); + let report = s.problem_report(&About { last_run: LastRun::Left("didn't close".into()), ..Default::default() }); + assert!(report.contains("## Last commands (0 of 0), as a script\nNone this session."), "{report}"); + assert!(report.contains("Graphics: not reported") && report.contains("Last run: didn't close"), "{report}"); + assert!(report.contains("## Messages (0)"), "{report}"); + } +} diff --git a/crates/engine/src/project_log.rs b/crates/engine/src/project_log.rs index a05d4aded1..837c6779d3 100644 --- a/crates/engine/src/project_log.rs +++ b/crates/engine/src/project_log.rs @@ -656,6 +656,26 @@ impl LogEntry { self.inputs_omitted = self.inputs_omitted.saturating_add(u64::try_from(omitted).unwrap_or(u64::MAX)); } + /// Its parameters as one line of JSON: none for no parameters. + pub fn params_text(&self) -> String { + match &self.params { + Value::Null => String::new(), + Value::Object(m) if m.is_empty() => String::new(), + p => p.to_string(), + } + } + + /// A Script pane line for it: its command and parameters, as History's Copy as Command writes + /// one. Undo and redo alone: what the log keeps of them is the step's label, not a parameter. + pub fn script_line(&self) -> String { + let params = self.params_text(); + if params.is_empty() || matches!(self.command.as_str(), "edit.undo" | "edit.redo") { + self.command.clone() + } else { + format!("{} {params}", self.command) + } + } + /// When it started, as `2026-10-30 14:05:09` (UTC). pub fn time_utc(&self) -> String { let (date, time) = rustgis_map::graphics::civil(self.at / 1000); diff --git a/crates/engine/src/tests/credential_output.rs b/crates/engine/src/tests/credential_output.rs index c5a9baa5e4..26099f4f02 100644 --- a/crates/engine/src/tests/credential_output.rs +++ b/crates/engine/src/tests/credential_output.rs @@ -1061,3 +1061,42 @@ fn copernicus_sign_in_secrets_stay_out_of_history_and_errors() { assert_eq!(status, json!({"signedIn": false, "remembered": false, "expired": false})); assert_eq!(s.run("copernicus.logout", &Value::Null).unwrap(), status); } + +/// Report a Problem's command lines take a login in use out of a logged parameter even when it +/// has a quote in it, which the line's JSON writes escaped, and say the line no longer runs as it +/// ran. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn the_problem_report_masks_a_login_in_use_with_a_quote_in_it() { + if isolate_process_test("tests::credential_output::the_problem_report_masks_a_login_in_use_with_a_quote_in_it") { + return; + } + use crate::render::rustgis_tiles::logins; + let login = "p\"ass-X7-synthetic"; + let mut s = Session::new(Project::default()); + s.log.clear(); + s.log.push(crate::project_log::LogEntry { command: "map.new".into(), params: json!({"name": login}), ok: true, ..Default::default() }); + // A number can be a login too. + s.log.push(crate::project_log::LogEntry { + command: "map.zoomTo".into(), + params: json!({"scale": 9_073_640_215_u64}), + ok: true, + ..Default::default() + }); + let binding = + logins::activate("https://report-quote.invalid", "synthetic-report-quote", logins::Method::Header("X-Key".into()), login, false) + .unwrap(); + let number = logins::activate( + "https://report-number.invalid", + "synthetic-report-number", + logins::Method::Header("X-Pin".into()), + "9073640215", + false, + ) + .unwrap(); + let report = s.problem_report(&crate::problem_report::About::default()); + let (quoted, numeric) = (logins::deactivate(&binding), logins::deactivate(&number)); + assert!(quoted && numeric); + assert!(!report.contains("ass-X7-synthetic") && !report.contains("9073640215"), "{report}"); + assert!(report.contains("may not run as it ran\nmap.new"), "{report}"); +} diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 70d60652b2..921477fa96 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -1411,6 +1411,7 @@ pub(crate) const UI_COMMANDS: &[(&str, &str, &str)] = &[ ("ui.traceEdges", "Trace", "Edit › Features"), ("ui.exportMap", "Export Map…", "Publish › Output"), ("ui.checkUpdate", "Check for Updates…", "Help › Help"), + ("ui.reportProblem", "Report a Problem", "Help › Help"), ("ui.touchInterface", "Use the Touch Interface", "View › Interface"), ]; diff --git a/crates/ui-egui/src/diagnosticlog.rs b/crates/ui-egui/src/diagnosticlog.rs index 69c99e9742..6da2e98b1c 100644 --- a/crates/ui-egui/src/diagnosticlog.rs +++ b/crates/ui-egui/src/diagnosticlog.rs @@ -45,6 +45,13 @@ pub(crate) fn show(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { { ui.ctx().copy_text(app.session.diagnostics.report(app.ui.diagnostic_filter)); } + if ui + .button(tl!("Report a Problem")) + .on_hover_text(tl!("See the diagnostics a bug report needs, then copy them or open a bug report on GitHub")) + .clicked() + { + app.open_problem_report(); + } if ui .add_enabled(!records.is_empty(), egui::Button::new(tl!("Clear"))) .on_hover_text(tl!("Clear all diagnostic history for this session")) diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b69ad33643..c795fb356f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -90,6 +90,7 @@ mod pluginstart; mod pluginsui; mod popupmedia; mod portalsui; +mod problemreport; mod publicationwizard; #[cfg(not(target_arch = "wasm32"))] mod readjob; @@ -1026,6 +1027,8 @@ pub struct UiState { /// A ribbon button being shown by a task step's Show Me. pub show_me: Option, pub about: bool, + /// Help › Report a Problem, while open. + pub problem_report: Option, pub shortcuts: bool, /// The keyboard shortcuts. pub keymap: keymap::Keymap, @@ -1295,6 +1298,7 @@ impl Default for UiState { command_search_composing: false, show_me: None, about: false, + problem_report: None, shortcuts: false, keymap: keymap::Keymap::default(), shortcut_editor: shortcutui::Editor::default(), @@ -1509,6 +1513,9 @@ pub struct RustGisApp { /// The touch interface a phone's shell offers (`rustgis-ui-touch`), kept while the desktop /// interface is in its place so `ui.touchInterface` can bring it back. `None` elsewhere. pub touch: Option, + /// How the app's last run ended, as its shell said at start, for Report a Problem: not + /// reported where the shell doesn't keep track. + pub last_run: rustgis_engine::problem_report::LastRun, /// Whether the user wants the device's position shown: a shell that can report one (a /// phone's) starts and stops its positioning by this, and fills in [`RustGisApp::position`]. pub locate: bool, @@ -1892,6 +1899,7 @@ impl RustGisApp { reads_off_frame: false, chrome: None, touch: None, + last_run: rustgis_engine::problem_report::LastRun::NotReported, locate: false, position: None, fixes: std::collections::VecDeque::new(), @@ -4687,6 +4695,7 @@ impl RustGisApp { } "ui.commandSearch" => self.ui.command_search = Some(String::new()), "ui.about" => self.ui.about = true, + "ui.reportProblem" => self.open_problem_report(), // Back from the desktop interface to the phone's, which the shell left in `touch`. "ui.touchInterface" => match (self.chrome, self.touch) { (Some(_), _) => {} @@ -7870,6 +7879,7 @@ impl RustGisApp { chrome::command_search(self, &ctx); shortcutui::show(self, &ctx); chrome::about(self, &ctx); + problemreport::show(self, &ctx); #[cfg(not(target_arch = "wasm32"))] agentthreads::windows(self, &ctx); // The keys that follow a click of this frame, now that the panes have taken it and the diff --git a/crates/ui-egui/src/problemreport.rs b/crates/ui-egui/src/problemreport.rs new file mode 100644 index 0000000000..ad73137485 --- /dev/null +++ b/crates/ui-egui/src/problemreport.rs @@ -0,0 +1,105 @@ +//! Help › Report a Problem: the session's diagnostics ([`Session::problem_report`]) shown in full, +//! for the user to read and edit before anything leaves the app, with Copy, and Report on GitHub, +//! which copies them and opens the bug report form with the version and system filled in. The +//! diagnostics stay on the clipboard: they reach GitHub only when the user pastes and submits. +//! +//! [`Session::problem_report`]: rustgis_engine::Session::problem_report + +use egui::{Align2, RichText}; +use rustgis_engine::problem_report::{About, fenced, issue_address}; + +use crate::RustGisApp; +use crate::theme::Tokens; + +/// The open window: the report as it was when opened (so it doesn't change while read), as the +/// user edited it, and what its last button did. +pub struct Window { + pub text: String, + about: About, + said: Option, +} + +impl RustGisApp { + /// What the report says only the front end knows: which one it is, the graphics the map is + /// drawn with, and what the last run left ([`RustGisApp::last_run`]). + pub fn problem_about(&self) -> About { + let front_end = if cfg!(target_arch = "wasm32") { + "browser" + } else if cfg!(any(target_os = "android", target_os = "ios")) { + "phone" + } else { + "desktop" + }; + let graphics = self.map.render_state.as_ref().map(|rs| { + let info = rs.adapter.get_info(); + let mut said = format!("{:?}, {} ({:?})", info.backend, info.name, info.device_type); + if !info.driver.is_empty() { + said.push_str(&format!(", driver {} {}", info.driver, info.driver_info)); + } + said.trim_end().to_string() + }); + About { front_end: front_end.into(), graphics, last_run: self.last_run.clone() } + } + + /// Opens the window with the report as it is now. + pub(crate) fn open_problem_report(&mut self) { + let about = self.problem_about(); + let text = self.session.problem_report(&about); + self.ui.problem_report = Some(Window { text, about, said: None }); + } +} + +pub(crate) fn show(app: &mut RustGisApp, ctx: &egui::Context) { + let Some(window) = app.ui.problem_report.as_mut() else { return }; + let t = Tokens::get(ctx); + let mut open = true; + let mut copy = None; + let mut visit = None; + egui::Window::new(tl!("Report a Problem")) + .open(&mut open) + .collapsible(false) + .default_size([640.0, 520.0]) + .pivot(Align2::CENTER_CENTER) + .default_pos(ctx.content_rect().center()) + .show(ctx, |ui| { + crate::i18n::paragraph( + ui, + "These diagnostics help someone find what went wrong: this RustGIS and computer, the bugs met, the last commands as a script that runs them again, and Messages. Logins and secrets RustGIS recognises are taken out, but not every password can be told from other text, and file paths and layer names stay. Read them first, and delete anything you don't want to share: Copy and Report on GitHub use the text as you leave it.", + crate::theme::regular(12.0), + t.text, + ); + ui.add_space(6.0); + ui.horizontal_wrapped(|ui| { + if ui.button(tl!("Copy")).on_hover_text(tl!("Copy the diagnostics to paste into a bug report")).clicked() { + copy = Some(window.text.clone()); + window.said = Some(tl!("Copied.").to_string()); + } + let report = ui + .button(tl!("Report on GitHub…")) + .on_hover_text(tl!("Copy the diagnostics and open a new bug report on GitHub with the version and system filled in. Paste the diagnostics into it; nothing is posted until you submit it.")); + if report.clicked() { + copy = Some(fenced(&window.text)); + visit = Some(issue_address(&window.about)); + window.said = Some(tl!("Opened the bug report form. Paste the diagnostics from the clipboard into its logs field.").to_string()); + } + if let Some(said) = &window.said { + ui.label(RichText::new(said.as_str()).small().color(t.text_dim)); + } + }); + ui.separator(); + let label = ui.label(RichText::new(tl!("Diagnostics")).small().color(t.text_dim)); + egui::ScrollArea::vertical().id_salt("problem_report_text").auto_shrink([false, false]).show(ui, |ui| { + // Editable: what the user takes out isn't copied. + ui.add(egui::TextEdit::multiline(&mut window.text).font(egui::TextStyle::Monospace).desired_width(f32::INFINITY)).labelled_by(label.id); + }); + }); + if let Some(text) = copy { + ctx.copy_text(text); + } + if let Some(address) = visit { + app.ui.open_url = Some(address); + } + if !open { + app.ui.problem_report = None; + } +} diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 22c0ee6529..10bc2d758b 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -4426,6 +4426,17 @@ fn help_tab(app: &mut RustGisApp, ui: &mut Ui) { }); group(ui, "Help", |ui| { big(ui, app, "help", "About", "About RustGIS.", "ui.about", Value::Null, false, false); + big( + ui, + app, + "message_log", + "Report a\nProblem", + "See the diagnostics a bug report needs, then copy them or open a bug report on GitHub.", + "ui.reportProblem", + Value::Null, + false, + false, + ); if !cfg!(target_arch = "wasm32") { big( ui, diff --git a/crates/ui-egui/src/sessionlog.rs b/crates/ui-egui/src/sessionlog.rs index 5e9d242176..acdedefcd9 100644 --- a/crates/ui-egui/src/sessionlog.rs +++ b/crates/ui-egui/src/sessionlog.rs @@ -37,7 +37,7 @@ struct Row { impl Row { fn of(e: LogEntry, registry: &rustgis_engine::Registry) -> Row { let scriptable = registry.get(&e.command).is_some() && !rustgis_engine::cmd::workflows::refused_in_script(&e.command); - let params = params_text(&e); + let params = e.params_text(); // One line in the list; the whole of it (up to the log's 4 KB) on hover. let mut line: String = params.chars().take(120).collect(); if line.len() < params.len() { @@ -204,27 +204,6 @@ pub fn pane(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { }); } -/// An entry's parameters as one line of JSON: none for no parameters. -fn params_text(e: &LogEntry) -> String { - match &e.params { - Value::Null => String::new(), - Value::Object(m) if m.is_empty() => String::new(), - p => p.to_string(), - } -} - -/// A Script pane line for entry `e`: its command and parameters, as History's Copy as Command -/// writes one. Undo and redo alone: what the log keeps of them is the step's label, not a -/// parameter. -fn command_line(e: &LogEntry) -> String { - let params = params_text(e); - if params.is_empty() || matches!(e.command.as_str(), "edit.undo" | "edit.redo") { - e.command.clone() - } else { - format!("{} {params}", e.command) - } -} - /// The script a `script.run` entry ran, as the log kept it. fn script_of(e: &LogEntry) -> Option<&str> { if e.command == "script.run" { e.params.get("script").and_then(Value::as_str) } else { None } @@ -302,7 +281,7 @@ fn row(ui: &mut Ui, item: &Row, t: &Tokens, running: bool) -> Option { } else { let copy = ui.add_enabled(item.scriptable, egui::Button::new(tl!("Copy Command"))); if copy.on_hover_text(tl!("A line for the Script pane")).on_disabled_hover_text(tl!("It can't run in a script")).clicked() { - ui.ctx().copy_text(command_line(e)); + ui.ctx().copy_text(e.script_line()); picked = e.partial.then_some(Picked::CopiedPartial); ui.close(); } diff --git a/crates/ui-egui/tests/integration/diagnostics.rs b/crates/ui-egui/tests/integration/diagnostics.rs index 96fe76b424..9051388750 100644 --- a/crates/ui-egui/tests/integration/diagnostics.rs +++ b/crates/ui-egui/tests/integration/diagnostics.rs @@ -82,3 +82,42 @@ fn diagnostics_preserves_closed_history_filters_copies_and_clears() { assert_eq!(h.state().ui.right, Some(RightPane::Diagnostics)); h.get_by_label("Map draw"); } + +/// Report a Problem shows the report before anything leaves the app; Copy copies it, and Report +/// on GitHub copies it and opens the bug report form, sending nothing itself. +#[test] +fn report_a_problem_shows_copies_and_opens_the_bug_report_form() { + let mut app = RustGisApp::new(Session::new(Project::default())); + app.session.map_mut().tiles.clear(); + app.session.diagnostics.clear(); + app.last_run = rustgis_engine::problem_report::LastRun::Left("RustGIS didn't close normally last time, between commands.".into()); + assert!(app.run("layer.addData", json!({"path":"/report-missing/absent.geojson"})).is_err()); + app.run("ui.reportProblem", json!({})).unwrap(); + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(1366.0, 900.0)).with_step_dt(0.1).with_max_steps(64).build_ui_state( + |ui, app: &mut RustGisApp| { + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run_steps(3); + let text = h.state().ui.problem_report.as_ref().map(|w| w.text.clone()).expect("the window is open"); + assert!(text.contains("Last run: RustGIS didn't close normally"), "{text}"); + assert!(text.contains("layer.addData {\"path\":\"/report-missing/absent.geojson\"}"), "{text}"); + let output = |h: &egui_kittest::Harness<'_, RustGisApp>| h.output().platform_output.commands.clone(); + h.get_by_label("Copy").click(); + h.step(); + assert!(output(&h).iter().any(|c| matches!(c, egui::OutputCommand::CopyText(t) if *t == text)), "{:?}", output(&h)); + h.get_by_label("Report on GitHub…").click(); + h.step(); + let opened = output(&h); + assert!( + opened.iter().any(|c| matches!(c, egui::OutputCommand::OpenUrl(u) if u.url.starts_with(rustgis_engine::problem_report::NEW_ISSUE))), + "{opened:?}" + ); + // The report stays on the clipboard, out of the address. + assert!(!opened.iter().any(|c| matches!(c, egui::OutputCommand::OpenUrl(u) if u.url.contains("report-missing"))), "{opened:?}"); + assert!(opened.iter().any(|c| matches!(c, egui::OutputCommand::CopyText(t) if t.contains("report-missing"))), "{opened:?}"); + h.get_by_label_contains("Opened the bug report form"); +} diff --git a/docs/user-guide/index.md b/docs/user-guide/index.md index 94a8599a34..fc707dc628 100644 --- a/docs/user-guide/index.md +++ b/docs/user-guide/index.md @@ -161,6 +161,22 @@ A credential field in the middle of a line is removed when its value is one word a value of several words reads as prose and is kept (`… password: correct horse battery`). Review copied diagnostics for private layer names or file paths before sharing them. +### Report a Problem + +**Help › Report a Problem** (also in the Messages pane, and the Help menu on macOS) shows, in +one window, what a bug report needs from this session: the RustGIS version, the system, the +graphics the map is drawn with, whether the last run closed normally, each bug met this session +with its incident reference and where in RustGIS it happened, the last 50 commands from the +[session log](workspace.md#session-log) as Script pane lines that run them again, and the whole Messages history. A command that +failed says its error; one whose parameters were cut or had a secret taken out, or that a script +can't run, says so in a comment. Logins and secrets are removed as in Messages, with the same +limits; file paths and layer names stay. + +You can edit the text: **Copy** copies it as you leave it, so delete anything you don't want to +share. **Report on GitHub…** copies it too and opens a new bug report with the version and system +filled in; paste the diagnostics into its logs field. Opening the form sends GitHub only the +version and system; the diagnostics go when you paste them and submit. + ## The ribbon | Tab | Groups | @@ -175,7 +191,7 @@ Review copied diagnostics for private layer names or file paths before sharing t | **Publish** | While a layout is open, its groups first (Page, Map Frames, Map Surrounds, Shapes, Text, Export); then Report, Presentation, Output (Export Map, Export Features, Print Map, Capture To Clipboard, Report, Presentation, Export To 3D), Package, Share As, Layout, Save As, Thumbnail | | **Plugins** | Plugins (Plugin Manager, Install From File, Browse Plugins), Extensions (the [Extensions](#extensions) window), plus a group for each enabled [plugin](../plugins.md) with commands or tools; a plugin with its own tab adds that tab instead | | **Settings** | Theme (the theme list, Follow the System, Interface Scale), Customize (Ribbon, Quick Access), Language (interface language and worldview), Start-up (Start With, Projection, Extent), Autosave on the desktop | -| **Help** | Performance (Diagnostic Monitor), Learn (Learning Resources), Help (About, Check for Updates on the desktop, Command Search, Shortcuts) | +| **Help** | Performance (Diagnostic Monitor), Learn (Learning Resources), Help (About, Report a Problem, Check for Updates on the desktop, Command Search, Shortcuts) | | **Imagery** | The [Imagery extension](#extensions)'s tab, after Help, while it is on (it is off until you turn it on): Ortho Mapping, Reality Mapping, Alignment, Image Analysis, Image Classification, Imagery Sharing, Mensuration, Imagery Tools | The tabs stay the same whatever is selected: Style, Labeling and Data act on the layer selected in Layers.