diff --git a/crates/alkane-gui/src/bug_report.rs b/crates/alkane-gui/src/bug_report.rs new file mode 100644 index 00000000..83293bca --- /dev/null +++ b/crates/alkane-gui/src/bug_report.rs @@ -0,0 +1,437 @@ +//! Bug reports and feature requests from the toolbar's Bug report button. +//! +//! The app posts the report to the report relay (see tools/report-relay), +//! which holds the Gitea token and files the issue in blueflare/alkane-toolkit. +//! The app itself holds no secret. A report carries its type, the user's text, +//! what the app knows about itself (version, OS, appearance, language, window +//! size) and, if the user leaves it ticked, the recent activity log with +//! credentials scrubbed. Nothing is stored locally. + +use std::io::Write; +use std::process::Stdio; +use std::sync::mpsc::{channel, Receiver}; + +/// Where reports go. `ALKANE_REPORT_URL` overrides it (tests, staging). +pub const DEFAULT_URL: &str = "https://gitea.bluefla.re/alkane-report/v1/report"; +/// Longest report text the relay accepts. +pub const MAX_TEXT_CHARS: usize = 8000; +/// Log sent with a report: at most this many of the newest lines... +const LOG_LINES: usize = 80; +/// ...cut to this many bytes on a line boundary. +const LOG_BYTES: usize = 16 * 1024; + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Kind { + Bug, + Ui, + Feature, +} + +impl Kind { + /// In the order the dialog's type choice lists them. + pub const ALL: [Kind; 3] = [Kind::Bug, Kind::Ui, Kind::Feature]; + + pub fn label(self) -> &'static str { + match self { + Kind::Bug => "Bug", + Kind::Ui => "UI change", + Kind::Feature => "Feature request", + } + } + + /// The wire value, which is also the issue label. + pub fn as_str(self) -> &'static str { + match self { + Kind::Bug => "bug", + Kind::Ui => "ui", + Kind::Feature => "feature", + } + } +} + +/// What the app knows about itself, sent with every report. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Context { + pub app_version: String, + pub platform: String, + pub os: String, + pub appearance: String, + pub language: String, + pub window: String, +} + +impl Context { + /// The running app's context. `window` is the main window's size. + pub fn current(dark: bool, language: &str, window: (i32, i32)) -> Context { + Context { + app_version: env!("CARGO_PKG_VERSION").to_string(), + platform: format!("{}-{}", std::env::consts::OS, std::env::consts::ARCH), + os: os_version(), + appearance: if dark { "dark" } else { "light" }.to_string(), + language: language.to_string(), + window: format!("{}x{}", window.0, window.1), + } + } +} + +/// A human-readable OS name and version, best effort. +fn os_version() -> String { + #[cfg(target_os = "linux")] + { + if let Ok(s) = std::fs::read_to_string("/etc/os-release") { + for line in s.lines() { + if let Some(v) = line.strip_prefix("PRETTY_NAME=") { + return v.trim_matches('"').to_string(); + } + } + } + "Linux".to_string() + } + #[cfg(target_os = "macos")] + { + let out = alkane_core::platform::quiet_command("sw_vers") + .arg("-productVersion") + .output(); + match out { + Ok(o) if o.status.success() => { + format!("macOS {}", String::from_utf8_lossy(&o.stdout).trim()) + } + _ => "macOS".to_string(), + } + } + #[cfg(windows)] + { + let out = alkane_core::platform::quiet_command("cmd") + .args(["/C", "ver"]) + .output(); + match out { + Ok(o) if o.status.success() => { + let v = String::from_utf8_lossy(&o.stdout).trim().to_string(); + if v.is_empty() { + "Windows".to_string() + } else { + v + } + } + _ => "Windows".to_string(), + } + } + #[cfg(not(any(target_os = "linux", target_os = "macos", windows)))] + { + std::env::consts::OS.to_string() + } +} + +/// Names whose values are secrets: `name=value`, `name: value` and +/// `"name": "value"` have the value replaced. +const SECRET_NAMES: [&str; 12] = [ + "password", + "passwd", + "pass", + "pwd", + "secret", + "token", + "apikey", + "api_key", + "authorization", + "cookie", + "psk", + "credential", +]; + +/// Remove credentials from log text before it leaves the machine: values of +/// secret-looking names, `user:password@` in URLs, and PEM private keys. +/// What is removed becomes `[redacted]`. +pub fn scrub(text: &str) -> String { + let mut out = Vec::new(); + let mut in_pem = false; + for line in text.lines() { + if line.contains("-----BEGIN") && line.contains("PRIVATE KEY") { + in_pem = true; + out.push("[redacted]".to_string()); + continue; + } + if in_pem { + if line.contains("-----END") { + in_pem = false; + } + continue; + } + out.push(scrub_line(line)); + } + out.join("\n") +} + +fn scrub_line(line: &str) -> String { + let mut s = scrub_url_userinfo(line); + let lower = s.to_ascii_lowercase(); + // Walk every occurrence of every secret name; redact the value after the + // next `=` or `:` (quotes and spaces skipped) up to whitespace, a quote, a + // comma, `&` or `;`. + let mut cuts: Vec<(usize, usize)> = Vec::new(); + for name in SECRET_NAMES { + let mut from = 0; + while let Some(pos) = lower[from..].find(name) { + let start = from + pos; + from = start + name.len(); + let bytes = s.as_bytes(); + let mut i = start + name.len(); + // allow a closing quote and spaces between the name and the separator + while i < bytes.len() && (bytes[i] == b'"' || bytes[i] == b'\'' || bytes[i] == b' ') { + i += 1; + } + if i >= bytes.len() || (bytes[i] != b'=' && bytes[i] != b':') { + continue; + } + i += 1; + while i < bytes.len() && (bytes[i] == b' ' || bytes[i] == b'"' || bytes[i] == b'\'') { + i += 1; + } + let vstart = i; + if name == "authorization" || name == "cookie" { + // "Authorization: Bearer ", "Cookie: a=b; c=d": the whole + // rest of the line is the secret. + i = bytes.len(); + } + while i < bytes.len() + && !matches!(bytes[i], b' ' | b'"' | b'\'' | b',' | b'&' | b';' | b'\t') + { + i += 1; + } + if i > vstart { + cuts.push((vstart, i)); + } + } + } + if cuts.is_empty() { + return s; + } + cuts.sort(); + let mut merged: Vec<(usize, usize)> = Vec::new(); + for (a, b) in cuts { + match merged.last_mut() { + Some(last) if a <= last.1 => last.1 = last.1.max(b), + _ => merged.push((a, b)), + } + } + for (a, b) in merged.into_iter().rev() { + if s.is_char_boundary(a) && s.is_char_boundary(b) { + s.replace_range(a..b, "[redacted]"); + } + } + s +} + +/// `scheme://user:password@host` -> `scheme://user:[redacted]@host`. +fn scrub_url_userinfo(line: &str) -> String { + let mut s = line.to_string(); + let mut from = 0; + while let Some(p) = s[from..].find("://") { + let auth_start = from + p + 3; + let rest = &s[auth_start..]; + let end = rest + .find(|c: char| c == '/' || c.is_whitespace()) + .unwrap_or(rest.len()); + let authority = &rest[..end]; + if let Some(at) = authority.rfind('@') { + if let Some(colon) = authority[..at].find(':') { + let a = auth_start + colon + 1; + let b = auth_start + at; + s.replace_range(a..b, "[redacted]"); + } + } + from = auth_start; + if from >= s.len() { + break; + } + } + s +} + +/// The newest activity-log lines, scrubbed and cut to the size limits. +pub fn recent_log(full_log: &str) -> String { + let lines: Vec<&str> = full_log.lines().collect(); + let tail = &lines[lines.len().saturating_sub(LOG_LINES)..]; + let mut text = scrub(&tail.join("\n")); + if text.len() > LOG_BYTES { + let mut cut = text.len() - LOG_BYTES; + while !text.is_char_boundary(cut) { + cut += 1; + } + text = text[cut..].to_string(); + if let Some(nl) = text.find('\n') { + text = text[nl + 1..].to_string(); + } + } + text +} + +/// The JSON body the relay takes. +pub fn payload(kind: Kind, text: &str, ctx: &Context, log: Option<&str>) -> String { + serde_json::json!({ + "kind": kind.as_str(), + "text": text, + "app_version": ctx.app_version, + "platform": ctx.platform, + "os": ctx.os, + "appearance": ctx.appearance, + "language": ctx.language, + "window": ctx.window, + "log": log.unwrap_or(""), + }) + .to_string() +} + +/// A filed issue: its number and web link. +#[derive(Clone, Debug, PartialEq)] +pub struct Filed { + pub number: u64, + pub url: String, +} + +/// Read the relay's answer: curl's body, then the HTTP status on the last line. +pub fn parse_response(curl_stdout: &str) -> Result { + let trimmed = curl_stdout.trim_end(); + let (body, code) = match trimmed.rfind('\n') { + Some(i) => (&trimmed[..i], trimmed[i + 1..].trim()), + None => ("", trimmed), + }; + let json: Option = serde_json::from_str(body).ok(); + if code == "201" || code == "200" { + let number = json.as_ref().and_then(|j| j["number"].as_u64()); + let url = json.as_ref().and_then(|j| j["url"].as_str()).unwrap_or(""); + return match number { + Some(number) => Ok(Filed { + number, + url: url.to_string(), + }), + None => Err("the report service answered without an issue number; \ + check the issue list before sending again" + .into()), + }; + } + let reason = json + .as_ref() + .and_then(|j| j["error"].as_str()) + .map(str::to_string); + Err(match (code, reason) { + (_, Some(r)) => r, + ("000", None) | ("", None) => "could not reach the report service".into(), + (c, None) => format!("the report service answered HTTP {c}"), + }) +} + +/// Send a report on a worker thread; the receiver gets one result. +pub fn send(body: String) -> Receiver> { + let url = std::env::var("ALKANE_REPORT_URL").unwrap_or_else(|_| DEFAULT_URL.to_string()); + let (tx, rx) = channel(); + std::thread::spawn(move || { + let result = (|| { + let mut child = alkane_core::platform::quiet_command("curl") + .args([ + "-sS", + "--max-time", + "40", + "-X", + "POST", + "-H", + "Content-Type: application/json", + "--data-binary", + "@-", + "-w", + "\n%{http_code}", + &url, + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn() + .map_err(|e| format!("could not run curl: {e}"))?; + if let Some(mut si) = child.stdin.take() { + let _ = si.write_all(body.as_bytes()); + } + let out = child + .wait_with_output() + .map_err(|e| format!("curl failed: {e}"))?; + parse_response(&String::from_utf8_lossy(&out.stdout)) + })(); + let _ = tx.send(result); + }); + rx +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn scrub_removes_credentials_and_keeps_the_rest() { + let log = "12:00:01 set pools on 192.168.1.20: url=stratum+tcp://u:hunter2@pool:3333 password=hunter2\n\ + 12:00:02 login {\"user\": \"root\", \"pass\": \"s3cret\"}\n\ + 12:00:03 Authorization: Bearer abc.def\n\ + -----BEGIN OPENSSH PRIVATE KEY-----\nAAAA\n-----END OPENSSH PRIVATE KEY-----\n\ + 12:00:04 scan finished: 9 miners"; + let s = scrub(log); + assert!(!s.contains("hunter2"), "{s}"); + assert!(!s.contains("s3cret"), "{s}"); + assert!(!s.contains("abc.def"), "{s}"); + assert!(!s.contains("AAAA"), "{s}"); + assert!(s.contains("192.168.1.20")); + assert!(s.contains("\"user\": \"root\"")); + assert!(s.contains("scan finished: 9 miners")); + assert_eq!(s.matches("[redacted]").count(), 5, "{s}"); + } + + #[test] + fn recent_log_keeps_the_newest_lines_within_limits() { + let log: Vec = (0..500) + .map(|i| format!("line {i} {}", "x".repeat(300))) + .collect(); + let tail = recent_log(&log.join("\n")); + assert!(tail.len() <= LOG_BYTES); + assert!(tail.ends_with(&log[499])); + assert!(tail.starts_with("line "), "cut on a line boundary"); + assert!(!tail.contains("line 400 "), "only the newest lines"); + } + + #[test] + fn payload_carries_kind_text_and_context() { + let ctx = Context { + app_version: "1.2.3".into(), + platform: "macos-aarch64".into(), + os: "macOS 15.1".into(), + appearance: "dark".into(), + language: "en".into(), + window: "1280x800".into(), + }; + let v: serde_json::Value = + serde_json::from_str(&payload(Kind::Ui, "Text \"quoted\"", &ctx, None)).unwrap(); + assert_eq!(v["kind"], "ui"); + assert_eq!(v["text"], "Text \"quoted\""); + assert_eq!(v["app_version"], "1.2.3"); + assert_eq!(v["log"], ""); + } + + #[test] + fn response_parsing() { + assert_eq!( + parse_response("{\"number\":42,\"url\":\"https://x/42\"}\n201"), + Ok(Filed { + number: 42, + url: "https://x/42".into() + }) + ); + assert_eq!( + parse_response("{\"error\":\"Too many reports; try again later\"}\n429"), + Err("Too many reports; try again later".into()) + ); + assert_eq!( + parse_response("\n000"), + Err("could not reach the report service".into()) + ); + assert_eq!( + parse_response("\n502"), + Err("the report service answered HTTP 502".into()) + ); + } +} diff --git a/crates/alkane-gui/src/i18n.rs b/crates/alkane-gui/src/i18n.rs index c6e6457a..3fb6b49a 100644 --- a/crates/alkane-gui/src/i18n.rs +++ b/crates/alkane-gui/src/i18n.rs @@ -34,7 +34,7 @@ impl Lang { Lang::Pt => "Portugu\u{ea}s", } } - fn code(self) -> &'static str { + pub fn code(self) -> &'static str { match self { Lang::En => "en", Lang::Zh => "zh", @@ -137,6 +137,13 @@ const TABLE: &[(&str, [&str; 6])] = &[ ("Credentials", ["Credentials", "\u{51ed}\u{636e}", "\u{0423}\u{0447}\u{0451}\u{0442}\u{043d}\u{044b}\u{0435} \u{0434}\u{0430}\u{043d}\u{043d}\u{044b}\u{0435}", "Identifiants", "Credenciales", "Credenciais"]), ("Language", ["Language", "\u{8bed}\u{8a00}", "\u{042f}\u{0437}\u{044b}\u{043a}", "Langue", "Idioma", "Idioma"]), ("Logs", ["Logs", "\u{65e5}\u{5fd7}", "\u{0416}\u{0443}\u{0440}\u{043d}\u{0430}\u{043b}", "Journaux", "Registros", "Registos"]), + ("Bug report", ["Bug report", "\u{95ee}\u{9898}\u{53cd}\u{9988}", "\u{421}\u{43e}\u{43e}\u{431}\u{449}\u{438}\u{442}\u{44c} \u{43e}\u{431} \u{43e}\u{448}\u{438}\u{431}\u{43a}\u{435}", "Signaler un bug", "Informar de un error", "Relatar um erro"]), + ("Type", ["Type", "\u{7c7b}\u{578b}", "\u{422}\u{438}\u{43f}", "Type", "Tipo", "Tipo"]), + ("Bug", ["Bug", "\u{7f3a}\u{9677}", "\u{41e}\u{448}\u{438}\u{431}\u{43a}\u{430}", "Bug", "Error", "Erro"]), + ("UI change", ["UI change", "\u{754c}\u{9762}\u{4fee}\u{6539}", "\u{418}\u{437}\u{43c}\u{435}\u{43d}\u{435}\u{43d}\u{438}\u{435} \u{438}\u{43d}\u{442}\u{435}\u{440}\u{444}\u{435}\u{439}\u{441}\u{430}", "Modification de l'interface", "Cambio de interfaz", "Altera\u{e7}\u{e3}o da interface"]), + ("Feature request", ["Feature request", "\u{529f}\u{80fd}\u{5efa}\u{8bae}", "\u{41f}\u{440}\u{435}\u{434}\u{43b}\u{43e}\u{436}\u{435}\u{43d}\u{438}\u{435} \u{444}\u{443}\u{43d}\u{43a}\u{446}\u{438}\u{438}", "Demande de fonctionnalit\u{e9}", "Solicitud de funci\u{f3}n", "Pedido de recurso"]), + ("Send", ["Send", "\u{53d1}\u{9001}", "\u{41e}\u{442}\u{43f}\u{440}\u{430}\u{432}\u{438}\u{442}\u{44c}", "Envoyer", "Enviar", "Enviar"]), + ("Open issue", ["Open issue", "\u{6253}\u{5f00}\u{95ee}\u{9898}", "\u{41e}\u{442}\u{43a}\u{440}\u{44b}\u{442}\u{44c} \u{437}\u{430}\u{434}\u{430}\u{447}\u{443}", "Ouvrir le ticket", "Abrir incidencia", "Abrir issue"]), // KPI captions ("Total", ["Total", "\u{603b}\u{6570}", "\u{0412}\u{0441}\u{0435}\u{0433}\u{043e}", "Total", "Total", "Total"]), ("Hashing", ["Hashing", "\u{6b63}\u{5728}\u{6316}\u{77ff}", "\u{0425}\u{0435}\u{0448}\u{0438}\u{0440}\u{043e}\u{0432}\u{0430}\u{043d}\u{0438}\u{0435}", "Minage", "Minando", "Minerando"]), diff --git a/crates/alkane-gui/src/main.rs b/crates/alkane-gui/src/main.rs index 574867a6..057a0cab 100644 --- a/crates/alkane-gui/src/main.rs +++ b/crates/alkane-gui/src/main.rs @@ -7,6 +7,7 @@ mod access_probe; mod askpass; +mod bug_report; mod credentials; mod export; mod fixtures; diff --git a/crates/alkane-gui/src/ui.rs b/crates/alkane-gui/src/ui.rs index 88900873..674b69e6 100644 --- a/crates/alkane-gui/src/ui.rs +++ b/crates/alkane-gui/src/ui.rs @@ -22,6 +22,12 @@ pub const ID_PRESETS: i32 = 108; pub const ID_EXPORT: i32 = 109; // Settings menu (round 15 #13): the toolbar button + its menu items. pub const ID_SETTINGS: i32 = 110; +// Bug report / feature request dialog (toolbar, between Export and Settings). +pub const ID_BUG_REPORT: i32 = 111; +const ID_REPORT_SEND: i32 = 240; +const ID_REPORT_CLOSE: i32 = 241; +const ID_REPORT_OPEN: i32 = 242; +const ID_REPORT_KIND: i32 = 243; const ID_LANG_BASE: i32 = 790; // one id per language (790 + Lang index); reserves 790..790+Lang::all().len() const ID_LOGS_OPEN: i32 = 796; // open the Logs page const ID_LOGS_REFRESH: i32 = 797; @@ -791,6 +797,15 @@ pub struct App { // Settings > Logs page (round 15 #13). logs_dialog: Widget, logs_text: Widget, + // Bug report dialog (bug_report.rs): its controls, the send in flight and + // the last filed issue's link. + report_dialog: Widget, + report_kind: Widget, + report_text: Widget, + report_log: Widget, + report_status: Widget, + report_rx: Option>>, + report_url: Option, // Restore-to-stock (round 12 #8a): background job + its typed-confirm dialog. restore: Option, restore_dialog: Widget, @@ -1024,6 +1039,7 @@ pub fn build(frame: Widget) -> App { let _filter_btn = tbtn("Filter", ID_FILTER); let _columns_btn = tbtn("Columns", ID_COLUMNS); let _export_btn = tbtn("Export", ID_EXPORT); + let _report_btn = tbtn("Bug report", ID_BUG_REPORT); // The old Credentials button is now a Settings menu (round 15 #13). let _creds_btn = tbtn("Settings", ID_SETTINGS); root.add_sizer(ctl, 0, sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, 4); @@ -1149,6 +1165,13 @@ pub fn build(frame: Widget) -> App { logview_dialog: frame, logs_dialog: frame, logs_text: frame, + report_dialog: frame, + report_kind: frame, + report_text: frame, + report_log: frame, + report_status: frame, + report_rx: None, + report_url: None, restore: None, restore_dialog: frame, pending_restore: Vec::new(), @@ -3628,6 +3651,7 @@ impl App { self.drain_refresh(); self.drain_access_probe(); self.drain_restore(); + self.drain_report(); // A completed background log fetch yields a viewer dialog to show; return // it so `dispatch` presents it modally after the App borrow is released // (round 18 #12). @@ -4348,6 +4372,168 @@ impl App { /// Build (but do not show) the Logs page (round 15 #13): the in-app activity /// log with Refresh / Clear / Close. + /// The Bug report dialog: a type (Bug, UI change, Feature request), one text + /// box whose first line becomes the issue title, and whether to include the + /// recent activity log (scrubbed). Send files it through the report relay + /// (bug_report.rs) and shows the issue number, or the reason, in the dialog. + fn build_report_dialog(&mut self) -> Widget { + let frame = Widget::main_frame(); + let t = crate::i18n::t; + let dlg = Widget::dialog(frame, &t("Bug report")); + let root = Widget::box_sizer(true); + let kindrow = Widget::box_sizer(false); + kindrow.add( + Widget::static_text(dlg, &t("Type")), + 0, + sf::ALIGN_CENTRE_VERTICAL | sf::BORDER_RIGHT, + 8, + ); + let kind = Widget::choice(dlg, ID_REPORT_KIND); + for k in crate::bug_report::Kind::ALL { + kind.choice_append(&t(k.label())); + } + kind.choice_set_selection(0); + kindrow.add(kind, 0, sf::ALIGN_CENTRE_VERTICAL, 0); + root.add_sizer(kindrow, 0, sf::BORDER_ALL, 8); + root.add( + Widget::static_text( + dlg, + &t("Describe the problem or the idea. The first line becomes the title."), + ), + 0, + sf::BORDER_LEFT | sf::BORDER_RIGHT, + 8, + ); + let text = Widget::text_ctrl(dlg, true); + text.set_min_size(560, 220); + root.add(text, 1, sf::EXPAND | sf::BORDER_ALL, 8); + let log = Widget::check_box( + dlg, + &t("Include the recent activity log (passwords removed)"), + ); + log.set_checked(true); + root.add(log, 0, sf::BORDER_LEFT | sf::BORDER_RIGHT, 8); + root.add( + Widget::static_text( + dlg, + &t("Reports are public issues on gitea.bluefla.re. The app version and OS are included."), + ), + 0, + sf::BORDER_ALL, + 8, + ); + let status = Widget::static_text(dlg, ""); + root.add( + status, + 0, + sf::EXPAND | sf::BORDER_LEFT | sf::BORDER_RIGHT, + 8, + ); + let btns = Widget::box_sizer(false); + let open = Widget::button(dlg, &t("Open issue"), ID_REPORT_OPEN); + btns.add(open, 0, sf::BORDER_ALL, 6); + btns.add_stretch(1); + btns.add( + Widget::button(dlg, &t("Close"), ID_REPORT_CLOSE), + 0, + sf::BORDER_ALL, + 6, + ); + btns.add( + Widget::button(dlg, &t("Send"), ID_REPORT_SEND), + 0, + sf::BORDER_ALL, + 6, + ); + root.add_sizer(btns, 0, sf::EXPAND | sf::BORDER_ALL, 6); + root.set_sizer_on(dlg); + dlg.set_min_size(600, 440); + dlg.fit(dlg); + self.report_dialog = dlg; + self.report_kind = kind; + self.report_text = text; + self.report_log = log; + self.report_status = status; + self.report_url = None; + dlg + } + + /// Validate the Bug report dialog and send it on a worker thread. + fn send_report(&mut self) { + let t = crate::i18n::t; + if self.report_rx.is_some() { + return; // one send at a time + } + let text = self.report_text.get_value(); + let text = text.trim(); + if text.is_empty() { + self.report_status + .set_label(&t("Write what happened or what you would like first.")); + return; + } + if text.chars().count() > crate::bug_report::MAX_TEXT_CHARS { + self.report_status.set_label(&format!( + "{} ({} / {})", + t("The text is too long"), + text.chars().count(), + crate::bug_report::MAX_TEXT_CHARS + )); + return; + } + let kinds = crate::bug_report::Kind::ALL; + let kind = usize::try_from(self.report_kind.choice_get_selection()) + .ok() + .and_then(|i| kinds.get(i).copied()) + .unwrap_or(crate::bug_report::Kind::Bug); + let size = wx_rs::get_client_size(); + let ctx = crate::bug_report::Context::current( + wx_rs::is_dark(), + crate::i18n::current().code(), + (size.width as i32, size.height as i32), + ); + let log = self + .report_log + .is_checked() + .then(|| crate::bug_report::recent_log(&crate::logs::dump())); + let body = crate::bug_report::payload(kind, text, &ctx, log.as_deref()); + self.report_status.set_label(&t("Sending...")); + self.report_rx = Some(crate::bug_report::send(body)); + } + + /// Show the Bug report result in the dialog once the send finishes. + fn drain_report(&mut self) { + let Some(rx) = &self.report_rx else { return }; + let result = match rx.try_recv() { + Ok(r) => r, + Err(std::sync::mpsc::TryRecvError::Empty) => return, + Err(std::sync::mpsc::TryRecvError::Disconnected) => { + Err("the report was not sent".to_string()) + } + }; + self.report_rx = None; + let t = crate::i18n::t; + match result { + Ok(filed) => { + crate::logs::log(format!("bug report filed as issue #{}", filed.number)); + self.report_status.set_label(&format!( + "{} #{}", + t("Thank you. Filed as issue"), + filed.number + )); + self.report_text.set_value(""); + self.report_kind.choice_set_selection(0); + if !filed.url.is_empty() { + self.report_url = Some(filed.url); + } + } + Err(e) => { + crate::logs::log(format!("bug report not sent: {e}")); + self.report_status + .set_label(&format!("{} {e}", t("Not sent:"))); + } + } + } + fn build_logs_dialog(&mut self) -> Widget { let frame = Widget::main_frame(); let dlg = Widget::dialog(frame, &crate::i18n::t("Logs")); @@ -4933,6 +5119,17 @@ impl App { ID_EXPORT_ALL => self.export_check_all(true), ID_EXPORT_NONE => self.export_check_all(false), ID_SETTINGS => self.open_settings_menu(), + ID_BUG_REPORT => return Some(self.build_report_dialog()), + ID_REPORT_SEND => self.send_report(), + ID_REPORT_CLOSE => self.report_dialog.close(0), + ID_REPORT_OPEN => match &self.report_url { + Some(url) => { + wx_rs::launch_browser(url); + } + None => self.report_status.set_label(&crate::i18n::t( + "Send a report first; its issue opens here.", + )), + }, ID_LOGS_REFRESH => self.logs_text.set_value(&crate::logs::dump()), ID_LOGS_CLEAR => { crate::logs::clear();