diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index a783df0cbc..6613dec71c 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -35,6 +35,8 @@ pub struct Workflow { pub script_out: Vec<(String, bool)>, /// The Script pane's last run, shown above its results. pub script_last: Option, + /// The last run's Details window is open. + pub script_details: bool, /// When each Script pane run under way or waiting started (seconds since 1970, and the /// instant), in the order asked, for [`script_ran`] to tell as each lands. script_started: std::collections::VecDeque<(u64, web_time::Instant)>, @@ -77,11 +79,24 @@ pub struct ZonalStatsForm { /// A Script pane run, as the line above its results tells it: its number this session (so a run /// made again by mistake shows), how long it took and when it started (seconds since 1970; 0 for -/// a clock that can't tell). +/// a clock that can't tell). Its lines' whole results, or why it didn't run, for its Details +/// window. +#[derive(Default)] pub struct ScriptRun { pub n: u32, pub secs: f64, pub at: u64, + pub ran: Vec, + pub error: Option, +} + +/// A line a Script pane run ran, with its whole result. `text`, the result laid out to read a +/// line of text a row, is made the first time its Details section opens, not as the run lands. +pub struct ScriptLine { + pub line: u64, + pub command: String, + pub result: Value, + pub text: Vec, } /// The Trend Analysis section's inputs (#579), and a run under way. @@ -1582,14 +1597,29 @@ fn script_ran(app: &mut RustGisApp, landed: crate::Landed) { let at = if asked_at == 0 { 0 } else { asked_at.saturating_add(started.duration_since(asked).as_secs()) }; app.workflow.script_landed = Some(now); let n = app.workflow.script_last.as_ref().map_or(1, |r| r.n.saturating_add(1)); - app.workflow.script_last = Some(ScriptRun { n, secs: now.duration_since(started).as_secs_f64(), at }); - app.workflow.script_out = match landed { - crate::Landed::Ran(Ok(v)) => v["ran"] - .as_array() - .map(|a| a.iter().map(|r| (format!("{} → {}", r["command"].as_str().unwrap_or(""), r["result"]), false)).collect()) - .unwrap_or_default(), - crate::Landed::Ran(Err(e)) | crate::Landed::NotRun(e) => vec![(e, true)], + // A run that stops is undone whole (`Session::guarded` restores the project), so its error + // is all it has to tell. + let (ran, error) = match landed { + crate::Landed::Ran(Ok(mut v)) => match v.get_mut("ran").map(Value::take) { + Some(Value::Array(a)) => (a, None), + _ => (Vec::new(), None), + }, + crate::Landed::Ran(Err(e)) | crate::Landed::NotRun(e) => (Vec::new(), Some(e)), }; + app.workflow.script_out = match &error { + None => ran.iter().map(|r| (format!("{} → {}", r["command"].as_str().unwrap_or(""), preview(&r["result"])), false)).collect(), + Some(e) => vec![(e.clone(), true)], + }; + let ran = ran + .into_iter() + .map(|mut r| ScriptLine { + line: r["line"].as_u64().unwrap_or(0), + command: r["command"].as_str().unwrap_or("").to_string(), + result: r.get_mut("result").map(Value::take).unwrap_or_default(), + text: Vec::new(), + }) + .collect(); + app.workflow.script_last = Some(ScriptRun { n, secs: now.duration_since(started).as_secs_f64(), at, ran, error }); // Another still to land: the results say so first, above this one's, where their scroll // starts, however many lines it ran. if !app.workflow.script_started.is_empty() { @@ -1680,27 +1710,200 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) { // Above the results' scroll, so it stays in view: its number and how long it took, and on // the right when it started, as the Geoprocessing History tells it (UTC: the app has no time // zone). + let mut details = false; if let Some(r) = &app.workflow.script_last { ui.horizontal(|ui| { - let text = crate::i18n::fmt("Run #{n} ({secs} s)", &[("n", &r.n.to_string()), ("secs", &format!("{:.2}", r.secs))]); - ui.label(egui::RichText::new(text).small().strong()); - if r.at > 0 { - let (_, time) = rustgis_engine::map::graphics::civil(r.at); - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - ui.label(egui::RichText::new(crate::i18n::fmt("{time} UTC", &[("time", &time)])).small().weak()) - }); - } + ui.label(egui::RichText::new(run_line(r)).small().strong()); + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + details = ui.small_button(tl!("Details…")).on_hover_text(tl!("Each line's whole result, to read or copy")).clicked(); + if let Some(time) = run_time(r) { + ui.label(egui::RichText::new(time).small().weak()); + } + }); }); } - // In a scroll of their own, so a long error (it wraps) can't push them out of the pane. + app.workflow.script_details |= details; + // In a scroll of their own, so a long error (it wraps) can't push them out of the pane. A + // result is cut here; Details… shows it whole. egui::ScrollArea::vertical().id_salt("script_out").max_height(out_h).auto_shrink([false, true]).show(ui, |ui| { for (line, err) in &app.workflow.script_out { - let c = if *err { egui::Color32::from_rgb(0xC0, 0x30, 0x30) } else { ui.visuals().text_color() }; - ui.label(egui::RichText::new(line.chars().take(400).collect::()).monospace().small().color(c)); + let c = if *err { SCRIPT_ERROR } else { ui.visuals().text_color() }; + ui.label(egui::RichText::new(line.chars().take(SCRIPT_PREVIEW).collect::()).monospace().small().color(c)); } }); } +/// The colour of a Script pane run's error. +const SCRIPT_ERROR: egui::Color32 = egui::Color32::from_rgb(0xC0, 0x30, 0x30); + +/// A run's number and how long it took: `Run #2 (0.84 s)`. +fn run_line(r: &ScriptRun) -> String { + crate::i18n::fmt("Run #{n} ({secs} s)", &[("n", &r.n.to_string()), ("secs", &format!("{:.2}", r.secs))]) +} + +/// When a run started, in UTC (the app has no time zone), if the clock could tell. +fn run_time(r: &ScriptRun) -> Option { + (r.at > 0).then(|| crate::i18n::fmt("{time} UTC", &[("time", &rustgis_engine::map::graphics::civil(r.at).1)])) +} + +/// The most rows a result shows at once in the Details window; a longer one scrolls. +const SCRIPT_DETAILS_ROWS: f32 = 24.0; + +/// The most characters of a result, or of an error, the pane shows: a line of the results. +const SCRIPT_PREVIEW: usize = 400; + +/// The most characters in a row of the Details window: a longer line is split into rows. +const SCRIPT_ROW_CHARS: usize = 200; + +/// A result laid out to read: indented JSON, a key a line. +fn pretty(v: &Value) -> String { + serde_json::to_string_pretty(v).unwrap_or_default() +} + +/// A result as the pane shows it: its JSON on one line, written no further than the pane shows +/// (SCRIPT_PREVIEW characters), so a long one (an export's text) isn't written out whole only to +/// be cut. +fn preview(v: &Value) -> String { + /// Takes bytes until it holds enough for SCRIPT_PREVIEW characters (at most 4 bytes each), + /// then refuses the rest, which stops the writing. + struct Capped(Vec); + impl std::io::Write for Capped { + fn write(&mut self, bytes: &[u8]) -> std::io::Result { + let room = (SCRIPT_PREVIEW * 4).saturating_sub(self.0.len()); + if room == 0 { + return Err(std::io::ErrorKind::WriteZero.into()); + } + let taken = bytes.get(..bytes.len().min(room)).unwrap_or_default(); + self.0.extend_from_slice(taken); + Ok(taken.len()) + } + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } + } + let mut out = Capped(Vec::new()); + // Stopped by Capped once it's full: what was written is the preview. + let _ = serde_json::to_writer(&mut out, v); + // A character cut at the end lies past the SCRIPT_PREVIEW kept. + String::from_utf8_lossy(&out.0).chars().take(SCRIPT_PREVIEW).collect() +} + +/// A result's text as the Details window's rows: a line of the indented JSON a row, and a line +/// longer than SCRIPT_ROW_CHARS (a long string, such as an export's text, which JSON keeps on one +/// line) split into rows of that many characters, so no row in view is long to lay out. +fn rows(text: &str) -> Vec { + let mut out = Vec::new(); + for line in text.lines() { + let mut chars = line.chars().peekable(); + if chars.peek().is_none() { + out.push(String::new()); + } + while chars.peek().is_some() { + out.push(chars.by_ref().take(SCRIPT_ROW_CHARS).collect()); + } + } + out +} + +/// A run's line as the Details window heads it: `line 3: raster.gcpFit`. +fn line_head(l: &ScriptLine) -> String { + crate::i18n::fmt("line {n}: {command}", &[("n", &l.line.to_string()), ("command", &l.command)]) +} + +/// The whole of a run as Copy All gives it: its line, then each line's head and result, then why +/// it stopped. +fn run_text(r: &ScriptRun) -> String { + let mut out = run_line(r); + if let Some(time) = run_time(r) { + out.push(' '); + out.push_str(&time); + } + for l in &r.ran { + out.push_str("\n\n"); + out.push_str(&line_head(l)); + out.push('\n'); + out.push_str(&pretty(&l.result)); + } + if let Some(e) = &r.error { + out.push_str("\n\n"); + out.push_str(e); + } + out +} + +/// The Script pane's last run in a window of its own (Details…), as View Details in ArcGIS Pro's +/// Geoprocessing History: each line's whole result laid out to read, to copy one or all, where +/// the pane cuts each to a line. +pub fn script_details(app: &mut RustGisApp, ctx: &egui::Context) { + if !app.workflow.script_details { + return; + } + let Some(r) = app.workflow.script_last.as_mut() else { + app.workflow.script_details = false; + return; + }; + let mut open = true; + egui::Window::new(tl!("Script Results")) + .id(egui::Id::unique("script_details")) + .open(&mut open) + .resizable(true) + .default_size(vec2(560.0, 420.0)) + .show(ctx, |ui| { + ui.horizontal(|ui| { + ui.label(egui::RichText::new(run_line(r)).strong()); + if let Some(time) = run_time(r) { + ui.label(egui::RichText::new(time).weak()); + } + ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { + if ui.button(tl!("Copy All")).clicked() { + ui.ctx().copy_text(run_text(r)); + } + }); + }); + ui.separator(); + let n = r.n; + let row = ui.text_style_height(&egui::TextStyle::Monospace); + egui::ScrollArea::vertical().id_salt("script_details_scroll").auto_shrink([false, false]).show(ui, |ui| { + for (i, l) in r.ran.iter_mut().enumerate() { + // Folded, one line each, a click opening one; a run of its own each time, so + // what was opened in the last one folds again. + egui::CollapsingHeader::new(egui::RichText::new(line_head(l)).monospace()) + .id_salt(("script_details_line", n, i)) + .default_open(false) + .show(ui, |ui| { + if l.text.is_empty() { + l.text = rows(&pretty(&l.result)); + } + // The result as it is, not its rows: a long line isn't split. + if ui.small_button(tl!("Copy")).clicked() { + ui.ctx().copy_text(pretty(&l.result)); + } + // Only the rows in view are laid out, each short, however long the + // result: in a scroll of its own, at most SCRIPT_DETAILS_ROWS rows tall. + egui::ScrollArea::both() + .id_salt(("script_details_result", n, i)) + .max_height(row * SCRIPT_DETAILS_ROWS) + .auto_shrink([false, true]) + .show_rows(ui, row, l.text.len(), |ui, rows| { + for text in l.text.get(rows).unwrap_or_default() { + ui.add(egui::Label::new(egui::RichText::new(text).monospace()).extend()); + } + }); + }); + } + if let Some(e) = &r.error { + ui.label(egui::RichText::new(e).monospace().color(SCRIPT_ERROR)); + } else if r.ran.is_empty() { + // A script of comments or blank lines only. + ui.label(egui::RichText::new(tl!("Nothing ran: the script has no commands.")).weak()); + } + }); + }); + if !open { + app.workflow.script_details = false; + } +} + #[cfg(test)] mod tests { use super::*; @@ -1775,6 +1978,125 @@ mod tests { assert_eq!(app.workflow.script_out, vec![("cancelled".to_string(), true)]); } + /// Details… opens the last run in a window of its own, each line folded: a result the pane cuts + /// shows whole there, laid out to read, Copy copies it and Copy All the run; a run that stopped + /// shows why. + #[test] + fn script_details_show_a_runs_whole_results() { + let mut app = RustGisApp::with_sample(); + let long: serde_json::Map = (0..60).map(|i| (format!("k{i:02}"), json!("xxxxxxxxxx"))).collect(); + let ran = json!([{"line": 1, "command": "raster.gcpFit", "result": long}, {"line": 3, "command": "map.zoomFull", "result": null}]); + script_ran(&mut app, crate::Landed::Ran(Ok(json!({"ran": ran})))); + assert!(!app.workflow.script_out[0].0.chars().take(400).collect::().contains("k59"), "the pane cuts it"); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + // The app's fonts, for the results' arrow. + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + script_pane(app, ui, &Tokens::light()); + script_details(app, ui.ctx()); + }, + app, + ); + h.run(); + assert!(h.query_by_label("Copy All").is_none(), "closed until asked"); + h.get_by_label("Details…").click(); + h.run(); + assert!(h.state().workflow.script_details); + // Each line folded, its result shown when it's opened. + assert!(h.query_by_label("line 3: map.zoomFull").is_some()); + assert!(h.query_by_label_contains("\"k59\"").is_none(), "folded"); + h.get_by_label("line 1: raster.gcpFit").click(); + h.run(); + // A key a row, only the rows in view laid out; its Copy has them all. + assert!(h.query_by_label_contains("\"k00\": \"xxxxxxxxxx\"").is_some(), "laid out to read, one key a row"); + assert!(h.query_by_label_contains("\"k59\"").is_none(), "a row out of view isn't laid out"); + let copied = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.output().platform_output.commands.iter().find_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t.clone()), + _ => None, + }) + }; + h.get_by_label("Copy").click(); + h.step(); + let one = copied(&h).expect("Copy copies"); + assert!(one.starts_with("{\n \"k00\"") && one.contains("\"k59\": \"xxxxxxxxxx\"\n}"), "{one}"); + h.get_by_label("Copy All").click(); + h.step(); + let all = copied(&h).expect("Copy All copies"); + assert!( + all.starts_with("Run #1 (") && all.contains("line 1: raster.gcpFit\n{") && all.contains("line 3: map.zoomFull\nnull"), + "{all}" + ); + // A run that stopped: the window, still open, shows why. + script_ran(h.state_mut(), crate::Landed::Ran(Err("line 2: raster.gcpFit: needs 3 points".into()))); + h.run(); + assert_eq!(h.query_all_by_label("line 2: raster.gcpFit: needs 3 points").count(), 2, "in the pane and the window"); + assert!(h.query_by_label_contains("\"k59\"").is_none(), "the last run only"); + // A script of comments only: the window says nothing ran rather than staying blank. + script_ran(h.state_mut(), crate::Landed::Ran(Ok(json!({"ran": []})))); + h.run(); + assert!(h.query_by_label("Nothing ran: the script has no commands.").is_some()); + // Its ✕ closes it, until Details… again. + h.get_by_label("Close window").click(); + h.run(); + assert!(!h.state().workflow.script_details); + assert!(h.query_by_label("Copy All").is_none()); + } + + /// A long result is cut as the pane writes it, not after; and in Details a long line (an + /// export's text, one JSON string) is split into short rows, while Copy keeps it whole. + #[test] + fn long_results_are_bounded_where_they_show() { + let long = json!({"text": "a".repeat(100_000)}); + let shown = preview(&long); + assert_eq!(shown.chars().count(), SCRIPT_PREVIEW); + assert!(shown.starts_with("{\"text\":\"aaa"), "{shown}"); + assert_eq!(preview(&json!({"a": 1})), "{\"a\":1}", "a short one whole, as before"); + let wide = preview(&json!("é".repeat(1_000))); + assert!(wide.chars().count() == SCRIPT_PREVIEW && !wide.contains('\u{FFFD}'), "cut between characters"); + // In rows of at most SCRIPT_ROW_CHARS characters, nothing lost or added. + let text = pretty(&long); + let split = rows(&text); + assert!(split.len() > 500 && split.iter().all(|r| r.chars().count() <= SCRIPT_ROW_CHARS)); + assert_eq!(split.concat(), text.lines().collect::()); + let counts: Vec = rows(&"é".repeat(450)).iter().map(|r| r.chars().count()).collect(); + assert_eq!(counts, vec![200, 200, 50]); + assert_eq!(rows("{\n\n}"), vec!["{", "", "}"], "a blank line stays a row"); + // In the window: the long line's rows, and Copy with the whole text. + let mut app = RustGisApp::with_sample(); + script_ran(&mut app, crate::Landed::Ran(Ok(json!({"ran": [{"line": 1, "command": "data.convert", "result": long}]})))); + app.workflow.script_details = true; + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + script_details(app, ui.ctx()); + }, + app, + ); + h.run(); + h.get_by_label("line 1: data.convert").click(); + h.run(); + let made = h.state().workflow.script_last.as_ref().map_or(0, |r| r.ran.iter().map(|l| l.text.len()).sum()); + assert!(made > 500, "laid out in rows: {made}"); + h.get_by_label("Copy").click(); + h.step(); + let copied = h.output().platform_output.commands.iter().find_map(|c| match c { + egui::OutputCommand::CopyText(t) => Some(t.clone()), + _ => None, + }); + assert_eq!(copied, Some(pretty(&long)), "Copy keeps the long line whole"); + } + /// Interpolate runs on a thread of its own from the pane (#1291 step 3): the pane goes on while /// it works, a second run waits for the first, and its layer lands through its command, which /// Record Task takes without the raster it handed over (a replay works it out again). diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e822667d95..02351c8f50 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -4783,6 +4783,7 @@ impl RustGisApp { graphicformat::save_draft(self); dialogs::show(self, &ctx); layerchooser::show(self, &ctx); + analysispane::script_details(self, &ctx); mapview::confirm_delete(self, &ctx); autosave::offer(self, &ctx); saveprompt::show(self, &ctx); diff --git a/crates/ui-egui/src/scriptcolor.rs b/crates/ui-egui/src/scriptcolor.rs index c790a39c55..e752a28af4 100644 --- a/crates/ui-egui/src/scriptcolor.rs +++ b/crates/ui-egui/src/scriptcolor.rs @@ -530,7 +530,7 @@ mod tests { let mut app = crate::RustGisApp::with_sample(); app.workflow.script = "map.zoomFull\n".repeat(300); app.workflow.script_out = (0..12).map(|i| (format!("line {i}: {}", "a long error ".repeat(30)), true)).collect(); - app.workflow.script_last = Some(crate::analysispane::ScriptRun { n: 1, secs: 0.5, at: 1_800_000_000 }); + app.workflow.script_last = Some(crate::analysispane::ScriptRun { n: 1, secs: 0.5, at: 1_800_000_000, ..Default::default() }); let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(500.0, 700.0)).build_ui_state( |ui, app: &mut crate::RustGisApp| crate::analysispane::script_pane(app, ui, &crate::theme::Tokens::light()), app, diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index aa2149fc96..c48c74a6d7 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1103,7 +1103,11 @@ The **Script** pane runs commands from text, one per line (`id {json}`); its box short of the buttons, and then scrolls, so **Run** stays in view; Ctrl+Enter (⌘+Enter on macOS) in the box runs the script too. Above a run's results, a line tells its number, how long it took and when it started (`Run #2 (0.84 s)`, and `14:04 UTC` on the right), so a run made again by -mistake shows (Undo takes a whole run back). On the desktop, a script's tools and models, with +mistake shows (Undo takes a whole run back). The results show each line's result cut to a line; +**Details…** on the run's line opens them whole in a window, as View Details in ArcGIS Pro's +Geoprocessing History: each line folded under its command, opening to its result laid out to +read, **Copy** for one and **Copy All** for the run, and why it stopped, if it did. On the +desktop, a script's tools and models, with selections, layer renames and definition queries, the environment and the projection between them, are worked out in the background first, so the map and the rest of the window stay in use: the status bar shows **Run Script** and **Cancel**, and the results say **Running…** until