1use std::collections::VecDeque;
55use std::path::{Path, PathBuf};
56use std::sync::{Arc, Mutex, RwLock};
57
58use egui_pop_api::app::STEP_EXIT;
59use egui_pop_api::hooks::On;
60use egui_pop_api::services::ServiceToken;
61use egui_pop_api::steps::StepSpec;
62use egui_pop_api::toasts::{TOASTS, Toast};
63use egui_pop_api::{AppHandle, Ctx, Plugin, PluginError};
64use egui_pop_core::lock;
65use egui_pop_core::strings;
66use egui_pop_model::commands::CommandSpec;
67use egui_pop_model::ids::{CommandId, PluginId, StepId};
68use serde::{Deserialize, Serialize};
69use serde_json::{Value as Json, json};
70
71pub const PLUGIN: PluginId = PluginId::from_static("egui_pop.crash");
73pub const STEP_REPORT: StepId = StepId::from_static("crash.report");
75pub const CMD_REVEAL: CommandId = CommandId::from_static("crash.reveal");
77pub const CMD_DISMISS: CommandId = CommandId::from_static("crash.dismiss");
79pub const CRASHES: ServiceToken<Crashes> = ServiceToken::new("platform.crashes");
81pub const JOURNAL_TAIL: usize = 50;
83pub const LOG_TAIL: usize = 100;
85
86#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
88pub struct Panic {
89 pub time: String,
90 pub thread: String,
91 pub message: String,
92 pub location: String,
94 pub backtrace: String,
95}
96
97#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)]
99pub struct Report {
100 pub app: String,
101 pub version: String,
102 pub os: String,
104 pub arch: String,
105 pub os_release: String,
107 pub pid: u32,
108 pub started: String,
110 pub kind: String,
113 pub panics: Vec<Panic>,
115 pub log: Vec<String>,
117 pub journal: Vec<Json>,
119 #[serde(default)]
121 pub extra: Json,
122}
123
124impl Report {
125 pub fn new(app: &str, version: &str) -> Report {
127 Report {
128 app: app.into(),
129 version: version.into(),
130 os: std::env::consts::OS.into(),
131 arch: std::env::consts::ARCH.into(),
132 os_release: os_release(),
133 pid: crate::dirs::pid(),
134 started: crate::logs::now(),
135 kind: "ended".into(),
136 ..Report::default()
137 }
138 }
139
140 pub fn panic(app: &str, version: &str, message: &str) -> Report {
142 let mut r = Report::new(app, version);
143 r.kind = "panic".into();
144 r.panics.push(Panic {
145 time: crate::logs::now(),
146 thread: "main".into(),
147 message: message.into(),
148 location: "src/main.rs:1:1".into(),
149 backtrace: String::new(),
150 });
151 r
152 }
153
154 pub fn summary(&self) -> String {
156 match self.panics.last() {
157 Some(p) => format!("{} at {}", p.message, p.location),
158 None => "it ended without closing".into(),
159 }
160 }
161}
162
163fn os_release() -> String {
166 if cfg!(target_os = "linux") {
167 std::fs::read_to_string("/etc/os-release")
168 .ok()
169 .and_then(|t| {
170 t.lines()
171 .find_map(|l| l.strip_prefix("PRETTY_NAME="))
172 .map(|v| v.trim_matches('"').to_string())
173 })
174 .unwrap_or_default()
175 } else {
176 String::new()
177 }
178}
179
180fn session_file(dir: &Path, pid: u32) -> PathBuf {
181 dir.join(format!("session-{pid}.json"))
182}
183
184fn panic_file(dir: &Path, pid: u32) -> PathBuf {
185 dir.join(format!("panic-{pid}.json"))
186}
187
188fn alive(pid: u32) -> bool {
191 pid == crate::dirs::pid()
192 || (cfg!(target_os = "linux") && Path::new(&format!("/proc/{pid}")).exists())
193}
194
195fn write_json(path: &Path, value: &impl Serialize) -> std::io::Result<()> {
196 let text = serde_json::to_string_pretty(value).map_err(std::io::Error::other)?;
197 let tmp = path.with_extension("tmp");
198 std::fs::write(&tmp, text)?;
199 std::fs::rename(tmp, path)
200}
201
202pub fn simulate(dir: &Path, pid: u32, report: &Report) -> std::io::Result<()> {
206 std::fs::create_dir_all(dir)?;
207 let mut r = report.clone();
208 r.pid = pid;
209 write_json(&session_file(dir, pid), &r)?;
210 if !r.panics.is_empty() {
211 write_json(&panic_file(dir, pid), &r)?;
212 }
213 Ok(())
214}
215
216fn last_lines(path: &Path, n: usize) -> Vec<String> {
218 std::fs::read_to_string(path)
219 .map(|t| {
220 let lines: Vec<&str> = t.lines().collect();
221 lines[lines.len().saturating_sub(n)..]
222 .iter()
223 .map(|l| l.to_string())
224 .collect()
225 })
226 .unwrap_or_default()
227}
228
229pub fn collect(dir: &Path, log_file: Option<&Path>) -> Vec<PathBuf> {
232 let Ok(entries) = std::fs::read_dir(dir) else {
233 return Vec::new();
234 };
235 let mut out = Vec::new();
236 for e in entries.flatten() {
237 let name = e.file_name().to_string_lossy().into_owned();
238 let Some(pid) = name
239 .strip_prefix("session-")
240 .and_then(|r| r.strip_suffix(".json"))
241 .and_then(|p| p.parse::<u32>().ok())
242 else {
243 continue;
244 };
245 if alive(pid) {
246 continue;
247 }
248 let session: Option<Report> = std::fs::read_to_string(e.path())
249 .ok()
250 .and_then(|t| serde_json::from_str(&t).ok());
251 let panicked: Option<Report> = std::fs::read_to_string(panic_file(dir, pid))
252 .ok()
253 .and_then(|t| serde_json::from_str(&t).ok());
254 let report = match (panicked, session) {
255 (Some(r), _) => r,
256 (None, Some(mut r)) => {
257 r.kind = "ended".into();
258 if let Some(log) = log_file {
259 r.log = last_lines(log, LOG_TAIL);
260 }
261 r
262 }
263 (None, None) => continue,
264 };
265 let stamp = crate::logs::now().replace([':', '.'], "-");
266 let path = dir.join(format!("report-{stamp}-{pid}.json"));
267 if write_json(&path, &report).is_ok() {
268 let _ = std::fs::remove_file(e.path());
269 let _ = std::fs::remove_file(panic_file(dir, pid));
270 out.push(path);
271 }
272 }
273 out.sort();
274 out
275}
276
277#[derive(Debug, Default)]
280struct HookState {
281 dir: Option<PathBuf>,
282 report: Report,
283 journal: VecDeque<Json>,
284 #[cfg(feature = "logs")]
285 logs: Option<crate::logs::Logs>,
286}
287
288static HOOK: RwLock<Option<Arc<Mutex<HookState>>>> = RwLock::new(None);
289
290fn install_hook() {
292 static ONCE: std::sync::Once = std::sync::Once::new();
293 ONCE.call_once(|| {
294 let previous = std::panic::take_hook();
295 std::panic::set_hook(Box::new(move |info| {
296 write_panic(info);
297 previous(info);
298 }));
299 });
300}
301
302fn write_panic(info: &std::panic::PanicHookInfo<'_>) {
305 let Some(state) = HOOK.try_read().ok().and_then(|h| h.clone()) else {
306 return;
307 };
308 let Ok(mut s) = state.try_lock() else {
309 return;
310 };
311 let Some(dir) = s.dir.clone() else {
312 return;
313 };
314 let message = if let Some(m) = info.payload().downcast_ref::<&str>() {
315 (*m).to_string()
316 } else if let Some(m) = info.payload().downcast_ref::<String>() {
317 m.clone()
318 } else {
319 "a panic without a message".into()
320 };
321 let panic = Panic {
322 time: crate::logs::now(),
323 thread: std::thread::current()
324 .name()
325 .unwrap_or("unnamed")
326 .to_string(),
327 message,
328 location: info
329 .location()
330 .map(|l| format!("{}:{}:{}", l.file(), l.line(), l.column()))
331 .unwrap_or_default(),
332 backtrace: std::backtrace::Backtrace::force_capture().to_string(),
333 };
334 s.report.kind = "panic".into();
335 s.report.panics.push(panic);
336 #[cfg(feature = "logs")]
337 if let Some(l) = s.logs.clone() {
338 let tail = l.tail();
339 s.report.log = tail[tail.len().saturating_sub(LOG_TAIL)..].to_vec();
340 l.flush();
341 }
342 s.report.journal = s.journal.iter().cloned().collect();
343 let _ = std::fs::create_dir_all(&dir);
344 let _ = write_json(&panic_file(&dir, s.report.pid), &s.report);
345}
346
347#[derive(Clone, Debug)]
349pub struct Crashes {
350 dir: PathBuf,
351 log_file: Option<PathBuf>,
352 pending: Arc<Mutex<Vec<PathBuf>>>,
353}
354
355impl Crashes {
356 pub fn dir(&self) -> &Path {
358 &self.dir
359 }
360
361 pub fn reports(&self) -> Vec<PathBuf> {
363 let mut out: Vec<PathBuf> = std::fs::read_dir(&self.dir)
364 .map(|d| {
365 d.flatten()
366 .map(|e| e.path())
367 .filter(|p| {
368 p.file_name()
369 .is_some_and(|n| n.to_string_lossy().starts_with("report-"))
370 })
371 .collect()
372 })
373 .unwrap_or_default();
374 out.sort();
375 out
376 }
377
378 pub fn read(&self, path: &Path) -> Option<Report> {
380 serde_json::from_str(&std::fs::read_to_string(path).ok()?).ok()
381 }
382
383 pub fn dismiss(&self, path: &Path) -> Result<(), String> {
385 if path.parent() != Some(self.dir.as_path()) {
386 return Err(format!("{} is not a report", path.display()));
387 }
388 std::fs::remove_file(path).map_err(|e| e.to_string())
389 }
390
391 pub fn scan(&self) -> usize {
394 let found = collect(&self.dir, self.log_file.as_deref());
395 let n = found.len();
396 lock(&self.pending).extend(found);
397 n
398 }
399}
400
401fn offer(app: &AppHandle, crashes: &Crashes, path: &Path) {
403 let Some(report) = crashes.read(path) else {
404 return;
405 };
406 let args = json!({ "path": path, "report": report });
407 app.step(&STEP_REPORT, args, |app, args| {
408 let path = PathBuf::from(args["path"].as_str().unwrap_or_default());
409 if let Ok(report) = serde_json::from_value::<Report>(args["report"].clone()) {
411 write_json(&path, &report).map_err(|e| e.to_string())?;
412 }
413 let toasts = app
414 .service(&TOASTS)
415 .ok_or("no toasts to offer the report in")?;
416 let app_name = args["report"]["app"].as_str().unwrap_or_default();
417 let ctx = app.egui();
418 toasts.notify(
419 Toast::warning(&strings::tr_args(
420 &ctx,
421 &crate::strings::CRASH_OFFER,
422 &[("app", app_name)],
423 ))
424 .sticky()
425 .action(
426 &strings::tr(&ctx, &crate::strings::CRASH_SHOW),
427 CMD_REVEAL,
428 json!({ "path": path }),
429 ),
430 );
431 Ok(json!({ "offered": true, "path": path }))
432 });
433}
434
435#[derive(Debug)]
437pub struct CrashPlugin {
438 app: String,
439 version: String,
440 dir: Option<PathBuf>,
441 hook: bool,
442 state: Option<Arc<Mutex<HookState>>>,
443}
444
445impl CrashPlugin {
446 pub fn new(app: &str, version: &str) -> Self {
449 Self {
450 app: app.into(),
451 version: version.into(),
452 dir: None,
453 hook: true,
454 state: None,
455 }
456 }
457
458 pub fn dir(mut self, dir: impl Into<PathBuf>) -> Self {
460 self.dir = Some(dir.into());
461 self
462 }
463
464 pub fn hook(mut self, on: bool) -> Self {
467 self.hook = on;
468 self
469 }
470}
471
472impl Plugin for CrashPlugin {
473 fn id(&self) -> PluginId {
474 PLUGIN
475 }
476
477 fn title(&self) -> String {
478 "Crash reports".into()
479 }
480
481 fn priority(&self) -> i32 {
482 190
484 }
485
486 fn connect(&mut self, ctx: &mut Ctx<'_>) -> Result<(), PluginError> {
487 let dir = self
488 .dir
489 .clone()
490 .or_else(|| crate::dirs::crash_dir(&self.app))
491 .unwrap_or_else(|| crate::dirs::temp_dir().join(&self.app).join("crashes"));
492 ctx.step(
493 StepSpec::new(
494 STEP_REPORT,
495 "A crash report from the last session is offered (`path`, `report`); a before-hook may add to `report.extra`, an after-hook may send it.",
496 )
497 .args(json!({ "path": "report.json", "report": { "app": "Demo", "kind": "panic" } })),
498 )?;
499 #[cfg(feature = "logs")]
502 let logs = ctx.app().service(&crate::logs::LOGS).map(|l| (*l).clone());
503 let log_file = None::<PathBuf>;
504 #[cfg(feature = "logs")]
505 let log_file = log_file.or_else(|| logs.as_ref().map(|l| l.path().to_path_buf()));
506 let crashes = Crashes {
507 dir: dir.clone(),
508 log_file,
509 pending: Arc::default(),
510 };
511 crashes.scan();
512 ctx.service(&CRASHES, crashes.clone())?;
513 let reveal = crashes.clone();
514 ctx.command(
515 CommandSpec::new(CMD_REVEAL, "Show a crash report", "Help")
516 .description("Opens a crash report's file (`path`).")
517 .args(json!({ "path": "report.json" }))
518 .hidden(),
519 move |call| {
520 let path = PathBuf::from(call.args["path"].as_str().ok_or("`path` is missing")?);
521 if path.parent() != Some(reveal.dir()) {
522 return Err(format!("{} is not a report", path.display()));
523 }
524 crate::dirs::reveal(&path)?;
525 Ok(json!({ "path": path }))
526 },
527 )?;
528 let dismiss = crashes.clone();
529 ctx.command(
530 CommandSpec::new(CMD_DISMISS, "Delete a crash report", "Help")
531 .icon("delete")
532 .description("Deletes a crash report (`path`).")
533 .args(json!({ "path": "report.json" }))
534 .hidden(),
535 move |call| {
536 let path = PathBuf::from(call.args["path"].as_str().ok_or("`path` is missing")?);
537 dismiss.dismiss(&path)?;
538 Ok(json!({ "dismissed": path }))
539 },
540 )?;
541 let report = Report::new(&self.app, &self.version);
543 #[cfg(not(target_arch = "wasm32"))]
547 if let Err(e) = std::fs::create_dir_all(&dir)
548 .and_then(|()| write_json(&session_file(&dir, report.pid), &report))
549 {
550 log::warn!(target: "egui_pop", "crash reports: {}: {e}", dir.display());
551 }
552 let state = Arc::new(Mutex::new(HookState {
553 dir: Some(dir.clone()),
554 report,
555 journal: VecDeque::new(),
556 #[cfg(feature = "logs")]
557 logs,
558 }));
559 if self.hook {
562 *HOOK
563 .write()
564 .unwrap_or_else(std::sync::PoisonError::into_inner) = Some(state.clone());
565 install_hook();
566 }
567 self.state = Some(state.clone());
568 let mut seen = 0;
569 ctx.on(On::Pass, move |app, _| {
570 let events = app.events_since(seen);
572 if let Some(last) = events.last() {
573 seen = last.seq;
574 let mut s = lock(&state);
575 for e in events {
576 s.journal.push_back(json!({
577 "seq": e.seq, "source": e.source, "name": e.name, "data": e.data,
578 }));
579 }
580 while s.journal.len() > JOURNAL_TAIL {
581 s.journal.pop_front();
582 }
583 }
584 let pending: Vec<PathBuf> = lock(&crashes.pending).drain(..).collect();
585 for path in pending {
586 offer(app, &crashes, &path);
587 }
588 });
589 let pid = crate::dirs::pid();
590 ctx.after(STEP_EXIT, move |_, _, _| {
591 let _ = std::fs::remove_file(session_file(&dir, pid));
592 let _ = std::fs::remove_file(panic_file(&dir, pid));
593 });
594 Ok(())
595 }
596
597 fn disconnect(&mut self, _ctx: &mut Ctx<'_>) {
598 if let Some(state) = self.state.take() {
599 let mut hook = HOOK
600 .write()
601 .unwrap_or_else(std::sync::PoisonError::into_inner);
602 if hook.as_ref().is_some_and(|h| Arc::ptr_eq(h, &state)) {
603 *hook = None;
604 }
605 let s = lock(&state);
606 if let Some(dir) = &s.dir {
607 let _ = std::fs::remove_file(session_file(dir, s.report.pid));
608 let _ = std::fs::remove_file(panic_file(dir, s.report.pid));
609 }
610 }
611 }
612}