diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 377e4e39b2..1f2857f27c 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -53,6 +53,8 @@ use picture::*; pub(in crate::cmd) use picture::{PICTURE_ADDRESS, picture_named}; mod page; use page::*; +mod preview; +pub use preview::*; mod profile; use profile::*; mod publication; diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index d6467efdf1..8774e431ff 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -63,6 +63,23 @@ fn layout_bytes_for( /// of it: texts cut off, named fonts still being read, frames drawn without their cast shadows, /// pictures drawn as a grey box, charts' notices. pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]>) -> Result, String> { + let img = layout_page(s, li, dpi, region, |layout, maps, info| match region { + Some(r) => rustgis_render::layout::render_region(layout, maps, dpi, info, r), + None => rustgis_render::layout::render(layout, maps, dpi, info), + })?; + img.encode_png().map_err(|e| e.to_string()) +} + +/// Draws layout `li`'s current page with `draw`, which draws it at `dpi` (or its part in +/// `region`), and says in `s` what the drawing leaves out of it, for whoever the page is drawn +/// for: [`layout_png`] and a publication preview. +pub(super) fn layout_page( + s: &mut Session, + li: usize, + dpi: f64, + region: Option<[f64; 4]>, + draw: impl FnOnce(&Layout, &mut [Map], &rustgis_render::layout::PageInfo) -> Result, +) -> Result { let layout = s.project.layouts.get(li).ok_or("no layout")?.clone(); if let Some(note) = named_fonts_unread(&layout) { s.warn(note); @@ -94,10 +111,7 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> } let ((img, mut unfitted), mut charts) = rustgis_render::layout::drawn_charts(|| { rustgis_render::layout::unfitted_legends(|| { - crate::cmd::share::saying_shadows(s, "The layout", |s| match region { - Some(r) => rustgis_render::layout::render_region(&layout, &mut s.project.maps, dpi, &info, r), - None => rustgis_render::layout::render(&layout, &mut s.project.maps, dpi, &info), - }) + crate::cmd::share::saying_shadows(s, "The layout", |s| draw(&layout, &mut s.project.maps, &info)) }) }); let img = img?; @@ -125,7 +139,7 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> for note in rustgis_render::layout::profiles_notice(&profiles, 1) { s.warn(note); } - img.encode_png().map_err(|e| e.to_string()) + Ok(img) } /// [`chart_notices`] of the charts of `layout` a drawing of it drew, as [`chart_notice_lines_in`] diff --git a/crates/engine/src/cmd/layout/preview.rs b/crates/engine/src/cmd/layout/preview.rs new file mode 100644 index 0000000000..c00e5cc4cb --- /dev/null +++ b/crates/engine/src/cmd/layout/preview.rs @@ -0,0 +1,105 @@ +//! The sheet `layout.publication` would make, drawn without touching the project (#3475). + +use rustgis_render::layout::PagePending; +use serde_json::Value; + +use crate::Session; +use crate::undo_memory::ReadRows; + +/// The resolution a preview is drawn at. +pub const PREVIEW_DPI: f64 = 36.0; + +/// A publication sheet as it would be made. +pub struct PublicationPreview { + pub pixmap: tiny_skia::Pixmap, + /// What was still on its way when it was drawn. + pub pending: PagePending, + /// What `layout.publication` warns of and says, and what an export of the page would say it + /// leaves out. + pub warnings: Vec, +} + +/// Makes a copy of `s` to run `layout.publication` on, there or on another thread: what the +/// command reads of the session, with the logins already open (it opens none). Its streamed +/// layers are read anew ([`rustgis_map::Map::detach_reads`]). +fn copy_of(s: &Session) -> impl FnOnce() -> (ReadRows, Session) + Send + 'static { + let mut project = s.project.clone(); + for m in &mut project.maps { + m.detach_reads(); + } + let (extensions, connections, web_logins) = (s.extensions().clone(), s.connections.clone(), s.web_logins.borrowing_open()); + let selections: Vec<(String, String)> = + s.database_logins.web_selections().into_iter().map(|(origin, id)| (origin.to_string(), id.to_string())).collect(); + let requests = s.diagnostics.capture(); + let (view_size, active_layer, opened) = (s.view_size, s.active_layer, s.opened); + let (in_place_wait, raster_defaults, grids, auto_cache) = + (s.in_place_wait, s.raster_defaults.clone(), s.offers_grid_downloads, s.auto_cache); + let (favourite, arrangements) = (s.layout_favourite.clone(), s.layout_arrangements.clone()); + let readers = s.undo_memory.readers(); + // Rows the copy shares stay counted while it holds them, should this session let them go. + let retained = readers.retain(crate::undo_memory::allocations(&project)); + move || { + let mut copy = Session::new(project); + copy.set_extensions(extensions); + copy.connections = connections; + copy.web_logins = web_logins; + for (origin, id) in &selections { + copy.database_logins.select(crate::connections::WEB, origin, id); + } + copy.requests_into = Some(requests); + (copy.view_size, copy.active_layer, copy.opened) = (view_size, active_layer, opened); + (copy.in_place_wait, copy.raster_defaults, copy.offers_grid_downloads, copy.auto_cache) = + (in_place_wait, raster_defaults, grids, auto_cache); + (copy.layout_favourite, copy.layout_arrangements) = (favourite, arrangements); + // The copy shares this session's rows, which this session already counts (#2431). + copy.undo_memory.memory = None; + copy.undo_memory.use_readers(readers); + copy.sync_policy_generation(); + (retained, copy) + } +} + +/// [`copy_of`], made here. +#[cfg(test)] +pub(crate) fn preview_copy(s: &Session) -> Session { + copy_of(s)().1 +} + +/// What draws the sheet `layout.publication` with `params` would make, at [`PREVIEW_DPI`] without +/// waiting for what is still on its way, here or on a thread of its own; `s` doesn't change. Its +/// refusal is the error, and so is a bug caught in the drawing, with its incident (natively: the +/// browser stops at a panic). The command reads streamed layers as it does when run on `s`, and +/// what the whole drawing asks of servers goes in `s`'s Diagnostics. +pub fn publication_preview_work(s: &Session, params: Value) -> impl FnOnce() -> Result + Send + 'static { + let (copy, requests) = (copy_of(s), s.diagnostics.capture()); + move || { + let _requests = requests.enter(); + std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || draw(copy, ¶ms))) + .unwrap_or_else(|payload| Err(rustgis_data::incident::bug("The preview", payload.as_ref()))) + } +} + +/// Runs `layout.publication` with `params` on the copy `copy` makes and draws the sheet. +fn draw(copy: impl FnOnce() -> (ReadRows, Session), params: &Value) -> Result { + // Bound first, so it is dropped after the copy. + let (_retained, mut copy) = copy(); + let made = copy.run("layout.publication", params)?; + let li = copy.project.layouts.len().checked_sub(1).ok_or("no layout")?; + // The page as an export draws it, but without waiting, and what it leaves out said alike. + let mut pending = PagePending::default(); + let pixmap = super::export::layout_page(&mut copy, li, PREVIEW_DPI, None, |layout, maps, info| { + let (pixmap, short) = rustgis_render::layout::render_preview(layout, maps, PREVIEW_DPI, info)?; + pending = short; + Ok(pixmap) + })?; + // What Create answers, then what it and the drawing say as notices. + let mut warnings: Vec = + made["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str().map(String::from)).collect(); + warnings.extend(copy.notices.iter().map(|n| n.text.clone())); + Ok(PublicationPreview { pixmap, pending, warnings }) +} + +/// [`publication_preview_work`], done here. +pub fn publication_preview(s: &Session, params: &Value) -> Result { + publication_preview_work(s, params.clone())() +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9a15221a5f..6146806621 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -1240,7 +1240,6 @@ pub struct Session { /// Where the requests a copy of the session makes for a model's run ahead go /// ([`cmd::workflows::ahead_on_copy`]): the session's own Diagnostics, as when they're made /// there. Its notices stay its own: the run there says them. - #[cfg(not(target_arch = "wasm32"))] pub(crate) requests_into: Option, /// A QGIS project's import prepared for the read about to run it on a copy, its logins opened /// before the read recorded the accounts (#2476): taken at once by that read. @@ -1673,7 +1672,6 @@ impl Session { grids_ahead: None, #[cfg(not(target_arch = "wasm32"))] zones_ahead: None, - #[cfg(not(target_arch = "wasm32"))] requests_into: None, #[cfg(not(target_arch = "wasm32"))] import_opened: None, @@ -2082,10 +2080,7 @@ impl Session { pub(crate) fn command_epilogue(&mut self, id: &str, params: &Value, run: impl FnOnce(&mut Self) -> CmdResult) -> CmdResult { let outermost = self.depth == 0; let _inputs = (outermost && self.log.on()).then(rustgis_data::provenance::Capture::start); - #[cfg(not(target_arch = "wasm32"))] let _diagnostic_scope = self.requests_into.as_ref().map_or_else(|| self.diagnostics.enter(), |c| c.enter()); - #[cfg(target_arch = "wasm32")] - let _diagnostic_scope = self.diagnostics.enter(); let source = self.registry.get(id).map(|spec| spec.id).or_else(|| id.starts_with(rustgis_plugins::PREFIX).then_some("Plugin")); // Restored on every path, including panics outside `guarded`, so a later notice is not // attributed to an aborted command. Mirrors the capture scope's restore-on-drop. @@ -3586,9 +3581,7 @@ impl Session { /// restarts, an address it has no record of is read only from the internet, so the user's own /// on this computer or the local network is refused. fn say_public_only_full(&mut self) { - // A copy run ahead (`requests_into`, desktop only) leaves it for the session that takes - // its results. - #[cfg(not(target_arch = "wasm32"))] + // A copy run ahead (`requests_into`) leaves it for the session that takes its results. if self.requests_into.is_some() { return; } @@ -4489,8 +4482,7 @@ impl Session { } /// Takes another session's extension choices (a copy that runs a model or script ahead, on - /// the desktop only). - #[cfg(not(target_arch = "wasm32"))] + /// the desktop, or draws a publication preview). pub(crate) fn set_extensions(&mut self, state: extensions::State) { self.extensions = state; } diff --git a/crates/engine/src/service_logins.rs b/crates/engine/src/service_logins.rs index f3f2f83621..f05f739d1f 100644 --- a/crates/engine/src/service_logins.rs +++ b/crates/engine/src/service_logins.rs @@ -433,7 +433,6 @@ impl SessionLogins { /// login not open is refused with that reason. Dropping it ends none of the logins it borrowed, /// which stay this session's; one logged out here meanwhile is no longer active, and its /// requests are refused. - #[cfg(not(target_arch = "wasm32"))] pub(crate) fn borrowing(&self, origins: &BTreeSet, refused: BTreeMap) -> Self { let mut copy = Self::new(); copy.active = self.active.iter().filter(|(_, a)| origins.contains(&a.origin)).map(|(id, a)| (id.clone(), a.clone())).collect(); @@ -443,6 +442,13 @@ impl SessionLogins { copy } + /// A borrowing copy of every login open here, for a copy of this session that draws what it + /// has (a publication preview, #3475): it opens none of its own. + pub(crate) fn borrowing_open(&self) -> Self { + let origins = self.active.values().map(|a| a.origin.clone()).collect(); + self.borrowing(&origins, BTreeMap::new()) + } + /// Starts or ends [`SessionLogins::anonymous`] reads, saying what it was. pub(crate) fn set_anonymous(&mut self, on: bool) -> bool { std::mem::replace(&mut self.anonymous, on) diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 364c19a4c1..65a19f7180 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -149,6 +149,9 @@ mod layout_chart_notices; #[path = "tests/layout_publication_parts.rs"] mod layout_publication_parts; +#[path = "tests/layout_preview.rs"] +mod layout_preview; + #[path = "tests/layout_typed_values.rs"] mod layout_typed_values; diff --git a/crates/engine/src/tests/layout_preview.rs b/crates/engine/src/tests/layout_preview.rs new file mode 100644 index 0000000000..8c2a4d5595 --- /dev/null +++ b/crates/engine/src/tests/layout_preview.rs @@ -0,0 +1,156 @@ +//! `publication_preview` (#3475): the sheet `layout.publication` would make, the project left +//! as it was. + +use super::*; +use crate::cmd::layout::{PREVIEW_DPI, PublicationPreview, layout_png, preview_copy, publication_preview}; + +fn preview(s: &Session, params: Value) -> PublicationPreview { + publication_preview(s, ¶ms).unwrap_or_else(|e| panic!("{params}: {e}")) +} + +/// The preview of `params` over the session `set` leaves, against the layout Create then makes, +/// drawn as an export draws it. +fn is_what_create_draws(set: impl Fn(&mut Session), params: Value) { + let mut s = world(); + set(&mut s); + let drawn = preview(&s, params.clone()).pixmap; + s.run("layout.publication", ¶ms).unwrap(); + let made = s.project.layouts.len() - 1; + let png = layout_png(&mut s, made, PREVIEW_DPI, None).unwrap(); + let want = tiny_skia::Pixmap::decode_png(&png).unwrap(); + assert_eq!((drawn.width(), drawn.height()), (want.width(), want.height()), "{params}"); + assert!(drawn.data() == want.data(), "{params}: the preview differs from the sheet made"); +} + +#[test] +fn a_preview_draws_the_page_and_leaves_the_project_alone() { + let mut s = world(); + s.mark_saved(); + let (project, undo) = (serde_json::to_value(&s.project).unwrap(), s.undo_label()); + let p = preview(&s, json!({"profile": "a4-portrait"})).pixmap; + let ratio = f64::from(p.height()) / f64::from(p.width()); + assert!((ratio - 297.0 / 210.0).abs() < 0.01, "{} x {}", p.width(), p.height()); + assert!((f64::from(p.width()) - 210.0 / 25.4 * PREVIEW_DPI).abs() <= 1.0, "{}", p.width()); + assert_eq!(serde_json::to_value(&s.project).unwrap(), project); + assert_eq!((s.undo_label(), s.dirty()), (undo, false)); +} + +#[test] +fn a_preview_is_the_sheet_create_draws() { + is_what_create_draws(|_| {}, json!({"profile": "a4-portrait"})); +} + +#[test] +fn a_preview_takes_the_saved_favourite() { + is_what_create_draws( + |s| { + s.run("layout.arrangement", &json!({"favourite": "mirrored"})).unwrap(); + }, + json!({"profile": "a4-portrait"}), + ); +} + +#[test] +fn a_preview_of_the_view_takes_the_views_size() { + is_what_create_draws(|s| s.view_size = (400.0, 900.0), json!({"profile": "a4-portrait"})); +} + +#[test] +fn a_figure_preview_has_the_figures_proportions() { + let p = preview(&world(), json!({"profile": "thesis-half"})).pixmap; + let ratio = f64::from(p.height()) / f64::from(p.width()); + assert!((ratio - 110.0 / 160.0).abs() < 0.01, "{} x {}", p.width(), p.height()); +} + +#[test] +fn a_refused_sheet_says_what_create_says() { + let mut s = world(); + let params = json!({"profile": "a4-portrait", "style": "unknown"}); + let said = publication_preview(&s, ¶ms).err().expect("refused"); + assert_eq!(said, s.run("layout.publication", ¶ms).unwrap_err()); + assert!(s.project.layouts.is_empty()); +} + +#[test] +fn a_preview_warns_of_what_create_warns_of() { + let mut s = world(); + s.run("map.projection", &json!({"type": "globe"})).unwrap(); + let params = json!({"profile": "a4-portrait", "scaleBar": {"units": "miles"}}); + let said = preview(&s, params.clone()).warnings; + let r = s.run("layout.publication", ¶ms).unwrap(); + assert!(!said.is_empty()); + assert_eq!(json!(said), r["warnings"]); +} + +#[test] +fn the_copy_previewed_on_keeps_the_sessions_settings() { + let mut s = world(); + s.in_place_wait = false; + s.view_size = (400.0, 900.0); + s.opened = 7; + s.active_layer = s.map().layers.first().map(|l| l.id); + s.layout_favourite = json!("mirrored"); + s.layout_arrangements.insert("mine".into(), json!({"legend": "top-left"})); + let copy = preview_copy(&s); + assert!(!copy.in_place_wait); + assert_eq!((copy.view_size, copy.opened, copy.active_layer), (s.view_size, s.opened, s.active_layer)); + assert_eq!(copy.layout_favourite, s.layout_favourite); + assert_eq!(copy.layout_arrangements, s.layout_arrangements); + assert_eq!(copy.project.maps.len(), s.project.maps.len()); +} + +/// What the page drawing leaves out, as an export of the sheet says it, is said under the preview. +#[test] +fn a_preview_says_what_the_drawing_leaves_out() { + let mut s = world(); + let params = json!({"profile": "a4-portrait", "legend": {"title": "W".repeat(150)}}); + let warned = preview(&s, params.clone()).warnings; + s.run("layout.publication", ¶ms).unwrap(); + let seen = s.notices_since(0).len(); + layout_png(&mut s, 0, PREVIEW_DPI, None).unwrap(); + let said = s.notices_since(0)[seen..].to_vec(); + assert!(!said.is_empty(), "the export says the legend's title is cut"); + for n in said { + assert!(warned.contains(&n.text), "{}: {warned:?}", n.text); + } +} + +/// A tile that never comes doesn't hold the preview, which says its frames are short of it. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_preview_does_not_wait_for_tiles() { + use rustgis_map::tiles::{TileKind, TileLayer}; + if isolate_process_test("tests::layout_preview::a_preview_does_not_wait_for_tiles") { + return; + } + isolate_plugins(); + static HELD: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); + crate::render::rustgis_tiles::cache::set_fetcher(|url, done| { + // As a request's failure is noted: under whoever the drawing's thread draws for. + rustgis_data::diagnostics::Capture::current().note_absence("GET", &url, 404); + HELD.lock().unwrap().push(Box::new(done)); + }); + let mut s = world(); + s.map_mut().tiles.push(TileLayer::new("Held", TileKind::Raster, "https://tiles.test/held/{z}/{x}/{y}.png")); + let start = std::time::Instant::now(); + let p = preview(&s, json!({"profile": "a4-portrait"})); + assert!(start.elapsed() < std::time::Duration::from_secs(20), "waited {:?}", start.elapsed()); + assert!(p.pending.frames); + assert!(!s.diagnostics.records().is_empty(), "the drawing's requests are the session's to show"); +} + +/// What Create says as notices (the locator map's name cut short) is a warning of the preview too. +#[test] +fn a_preview_warns_of_what_create_says_as_notices() { + let mut s = world(); + s.run("map.rename", &json!({"name": "m".repeat(crate::cmd::MAX_NAME)})).unwrap(); + let params = json!({"profile": "a4-portrait"}); + let warned = preview(&s, params.clone()).warnings; + let seen = s.notices_since(0).len(); + s.run("layout.publication", ¶ms).unwrap(); + let said = s.notices_since(0)[seen..].to_vec(); + assert!(!said.is_empty(), "the cut is said"); + for n in said { + assert!(warned.contains(&n.text), "{}: {warned:?}", n.text); + } +} diff --git a/crates/engine/src/undo_memory.rs b/crates/engine/src/undo_memory.rs index ad30c62195..97fbe457a9 100644 --- a/crates/engine/src/undo_memory.rs +++ b/crates/engine/src/undo_memory.rs @@ -238,7 +238,6 @@ impl Budget { } /// Joins the initiating session's registry without charging a shared copy independently. - #[cfg(not(target_arch = "wasm32"))] pub(crate) fn use_readers(&mut self, readers: Readers) { self.readers = readers; } diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 2136197a9a..66d3ad0893 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -200,6 +200,12 @@ pub fn render_pending(layout: &Layout, maps: &mut [Map], dpi: f64, info: &PageIn render_page(layout, maps, dpi, info, false, None) } +/// [`render_pending`], its frames drawn with the tiles that have come rather than waiting for the +/// others, which `frames` says: a publication preview, drawn while the window waits. +pub fn render_preview(layout: &Layout, maps: &mut [Map], dpi: f64, info: &PageInfo) -> Result<(Pixmap, PagePending), String> { + crate::without_tile_wait(|| render_pending(layout, maps, dpi, info)) +} + /// [`render_pending`], its frames waiting for cast shadows when `wait_shadows` (an export), of /// the part of the page in `region` alone when one is given ([`render_region`]). fn render_page( diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index fad01b84bc..d2889221e5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -9096,6 +9096,8 @@ thread_local! { /// Set on the interface's thread ([`on_the_interface_thread`]), and while the Layout view's /// page is drawn: frames don't wait for cast shadows (see [`without_shadow_wait`]). static NO_SHADOW_WAIT: std::cell::Cell = const { std::cell::Cell::new(false) }; + /// Set while a publication preview's page is drawn (see [`without_tile_wait`]). + static NO_TILE_WAIT: std::cell::Cell = const { std::cell::Cell::new(false) }; /// A frame drawn at full resolution had cast shadows still to come (see [`shadows_said`]). static SHADOWS_TO_COME: std::cell::Cell = const { std::cell::Cell::new(false) }; /// Why layers drawn on this thread were drawn without their cast shadows, each said once (see @@ -9190,6 +9192,20 @@ pub(crate) fn without_shadow_wait(f: impl FnOnce() -> T) -> T { out } +/// Runs `f` (a publication preview's page) with its frames drawn with the tiles that have come, +/// rather than waiting for the others. +pub(crate) fn without_tile_wait(f: impl FnOnce() -> T) -> T { + /// Puts the flag back however `f` ends: a panic caught above it leaves the wait on. + struct Before(bool); + impl Drop for Before { + fn drop(&mut self) { + let _ = NO_TILE_WAIT.try_with(|c| c.set(self.0)); + } + } + let _before = Before(NO_TILE_WAIT.with(|c| c.replace(true))); + f() +} + /// Runs `f`, which draws one frame, and whether that frame had cast shadows still to come; what /// frames before it said is kept for [`shadows_said`]. pub(crate) fn frame_with_shadows_to_come(f: impl FnOnce() -> T) -> (T, bool) { @@ -9281,6 +9297,9 @@ fn complete_passes(map: &mut Map, view: &View, record: bool, failed_source: &mut // What had come when it drew: what lands meanwhile is news to the wait. let mut drawn_at = rustgis_tiles::cache::generation(); let mut r = render_cpu(map, view, true, record, failed_source, env)?; + if NO_TILE_WAIT.with(std::cell::Cell::get) { + return Some(r); + } let start = web_time::Instant::now(); let budget = web_time::Duration::from_secs(60); let mut idle = 0; @@ -10657,6 +10676,14 @@ mod tests { assert!((a.rem_euclid(180.0) - 45.0).abs() < 0.5, "{a}"); } + /// A preview's drawing that panics leaves the tile wait as it was. + #[test] + fn a_panicking_preview_leaves_the_tile_wait_on() { + let panicked = std::panic::catch_unwind(|| without_tile_wait(|| panic!("a drawing's bug"))); + assert!(panicked.is_err()); + assert!(!NO_TILE_WAIT.with(std::cell::Cell::get)); + } + /// A drawing that panics (a command's panic is caught) leaves nothing noted: reads outside a /// drawing are noted nowhere after it, as before it. #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 0dbb745512..b7696e2458 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -357,11 +357,15 @@ fn work_off_frame_with>( work: impl FnOnce() + Send + 'static, ) { if let Err(e) = spawn(Box::new(work)) { - let why = i18n::fmt("The system refused a thread to do this on ({error}); try again", &[("error", &e.to_string())]); - *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(Err(E::from(why))); + *slot.lock().unwrap_or_else(|e| e.into_inner()) = Some(Err(E::from(thread_refused(&e)))); } } +/// What a job the system refused a thread for says, in the interface's language. +pub(crate) fn thread_refused(e: &std::io::Error) -> String { + i18n::fmt("The system refused a thread to do this on ({error}); try again", &[("error", &e.to_string())]) +} + #[cfg(test)] mod work_off_frame_tests { use std::sync::Arc; diff --git a/crates/ui-egui/src/publicationwizard/mod.rs b/crates/ui-egui/src/publicationwizard/mod.rs index e46b5ab7eb..1b233feeeb 100644 --- a/crates/ui-egui/src/publicationwizard/mod.rs +++ b/crates/ui-egui/src/publicationwizard/mod.rs @@ -17,7 +17,7 @@ use accent::accent_step; use arrange::{Arrangement, arrange_step}; use elements::{Elements, elements_step}; use map::{Area, Coords, area_extent, map_step}; -use review::review_step; +use review::{Preview, drop_stale_preview, review_step}; use rustgis_engine::Session; use rustgis_engine::cmd::layout::{ MAX_PUBLICATION_LINES, MAX_PUBLICATION_TEXT, PUBLICATION_HEADINGS, PUBLICATION_PROFILES, publication_default_reference, @@ -157,6 +157,8 @@ pub struct Draft { pub arrangement: Arrangement, /// Whether Create also sets a chosen arrangement as the favourite. pub make_favourite: bool, + /// The sheet last drawn on the review, while what it was drawn from holds. + preview: Option, } impl Draft { @@ -193,6 +195,7 @@ impl Draft { list_follows: true, arrangement: Arrangement::Best, make_favourite: false, + preview: None, } } @@ -536,6 +539,21 @@ fn step_list(ui: &mut egui::Ui, d: &mut Draft, height: f32) -> Option { picked } +/// What Create sends `layout.publication`, and Preview draws; why a pick no longer holds. It +/// resolves the area, which may walk a whole layer, so it runs only on those two. +fn create_params(s: &Session, d: &Draft) -> Result { + d.arrangement.held(s)?; + let extent = area_extent(s, &d.area, d.coords.as_ref())?; + let mut params = d.sent(s); + if let Some(Coords { sides, crs }) = extent { + params["extent"] = json!(sides); + if let Some(crs) = crs { + params["crs"] = json!(crs); + } + } + Ok(params) +} + /// Shows the wizard while it is open; Create runs `layout.publication` as the menu does, and the /// wizard stays open on a layout the command refuses. pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { @@ -547,10 +565,13 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { if !d.title_typed { d.title.clone_from(&app.session.map().name); } + drop_stale_preview(&app.session, &mut d); let t = Tokens::get(ctx); let (mut open, mut close, mut create) = (true, false, false); // What the map step's conversion of the coordinates lost, said once. let mut lost = Vec::new(); + // A bug the preview's drawing met, said once. + let mut bug = None; // Narrower on a screen too narrow for it, as the other dialogs are. let frame = egui::Frame::window(&ctx.global_style()); let screen = ctx.content_rect(); @@ -609,7 +630,7 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { Step::Sources => sources_step(ui, &mut d, app.session.map()), Step::Reference => reference_step(ui, &mut d), Step::Accent => accent_step(ui, &mut d, t.accent), - Step::Review => review_step(ui, &app.session, &d), + Step::Review => bug = review_step(ui, &app.session, &mut d, app.reads_off_frame), }); }); if let Some(step) = picked { @@ -637,21 +658,13 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { }); }); }); - for lost in lost { - app.session.warn(lost); + for said in lost.into_iter().map(String::from).chain(bug) { + app.session.warn(said); } // A layout the command refuses is said (a map with no extent), and the wizard stays. if create { - let held = d.arrangement.held(&app.session).map_err(String::from); - match held.and_then(|_| area_extent(&app.session, &d.area, d.coords.as_ref())) { - Ok(extent) => { - let mut params = d.sent(&app.session); - if let Some(Coords { sides, crs }) = extent { - params["extent"] = json!(sides); - if let Some(crs) = crs { - params["crs"] = json!(crs); - } - } + match create_params(&app.session, &d) { + Ok(params) => { if crate::ribbon::make_publication(app, params) { close = true; // Only once the layout is made: a refused one changes no preference. diff --git a/crates/ui-egui/src/publicationwizard/review.rs b/crates/ui-egui/src/publicationwizard/review.rs index b6b667bca5..331ed5659b 100644 --- a/crates/ui-egui/src/publicationwizard/review.rs +++ b/crates/ui-egui/src/publicationwizard/review.rs @@ -2,9 +2,22 @@ use super::elements::elements_value; use super::map::{area_label, name_label}; use super::*; +use rustgis_engine::analysis::control::Control; +use rustgis_engine::cmd::layout::{PublicationPreview, publication_preview_work}; +use rustgis_engine::map::Camera; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::mpsc::{Receiver, TryRecvError, channel}; -/// The review step: what was picked, step by step. -pub(super) fn review_step(ui: &mut egui::Ui, s: &Session, d: &Draft) { +/// The review step: the sheet once asked for, then what was picked; what to say in Messages, a +/// bug the preview's drawing met. +pub(super) fn review_step(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) -> Option { + let bug = preview_part(ui, s, d, off_frame); + picked_rows(ui, s, d); + bug +} + +/// What was picked, step by step. +fn picked_rows(ui: &mut egui::Ui, s: &Session, d: &Draft) { let none = tl!("(none)"); let or_none = |t: &str| if t.trim().is_empty() { none.to_string() } else { t.trim().to_string() }; egui::Grid::new("publication_wizard_review").num_columns(2).spacing(egui::vec2(12.0, 6.0)).show(ui, |ui| { @@ -54,6 +67,228 @@ pub(super) fn review_step(ui: &mut egui::Ui, s: &Session, d: &Draft) { } } +/// What a preview was drawn from, compared each frame it is shown: the area as picked, not +/// resolved ([`create_params`] may walk a whole layer), and what of the session the sheet reads +/// (`revision` moves with every command). +#[derive(PartialEq)] +struct Key { + sent: Value, + area: Area, + coords: Option, + revision: u64, + opened: u64, + camera: Camera, + view: (f64, f64), +} + +impl Key { + fn now(s: &Session, d: &Draft) -> Self { + Self { + sent: d.sent(s), + area: d.area.clone(), + coords: d.coords.clone(), + revision: s.revision, + opened: s.opened, + camera: s.map().camera, + view: s.view_size, + } + } +} + +/// The sheet asked for last: being drawn, drawn, or why there is none. +pub(super) struct Preview { + key: Key, + shown: Shown, +} + +enum Shown { + Drawing(Drawing), + /// Told to stop, by Cancel or a change of what it draws, and not ended yet: a long step (a + /// raster, one feature's path) runs to its end, so no other starts beside it. + Stopping(Drawing), + Drawn(Result), +} + +impl Preview { + /// What is left of it once Cancel is pressed or what it was drawn from changes: only a + /// drawing still running, told to stop. + fn stopped(self) -> Option { + match self.shown { + Shown::Drawing(drawing) | Shown::Stopping(drawing) => { + drawing.stop(); + Some(Self { key: self.key, shown: Shown::Stopping(drawing) }) + } + Shown::Drawn(_) => None, + } + } +} + +/// A sheet being drawn on a thread of its own, cancelled when dropped, as the wizard closing +/// drops it; its thread ends at its next look. +struct Drawing { + made: Receiver>, + control: std::sync::Arc, + /// The page drawing's own stop ([`rustgis_engine::render::cancel`]). + frames: std::sync::Arc, +} + +impl Drawing { + /// Tells the thread to stop: its reads look at the control, the page drawing at the flag. + fn stop(&self) { + self.control.cancel(); + self.frames.store(true, Ordering::Relaxed); + } +} + +impl Drop for Drawing { + fn drop(&mut self) { + self.stop(); + } +} + +struct Picture { + texture: egui::TextureHandle, + warnings: Vec, + /// Something was still on its way when it was drawn. + pending: bool, +} + +fn picture(ctx: &egui::Context, made: PublicationPreview) -> Picture { + let size = [made.pixmap.width() as usize, made.pixmap.height() as usize]; + let pixels = egui::ColorImage::from_rgba_premultiplied(size, made.pixmap.data()); + Picture { + texture: ctx.load_texture("publication_preview", pixels, egui::TextureOptions::LINEAR), + warnings: made.warnings, + pending: made.pending.frames || made.pending.legends, + } +} + +/// Starts drawing the sheet Create would make: on a thread of its own with `off_frame` (the +/// desktop app, and the phone's desktop interface, whose windows it would otherwise hold), else +/// here (the browser, which has one thread, tests and the examples). The area is resolved here +/// either way, as Create does, since it reads the wizard's draft and the session: about 2 ms for +/// 100,000 selected features and 4 ms for a layer of as many with a definition query (a debug +/// build). +fn draw(ctx: &egui::Context, s: &Session, d: &Draft, off_frame: bool) -> Shown { + let params = match create_params(s, d) { + Ok(params) => params, + Err(e) => return Shown::Drawn(Err(e)), + }; + let work = publication_preview_work(s, params); + if !off_frame { + return Shown::Drawn(work().map(|made| picture(ctx, made))); + } + let (send, made) = channel(); + let control = Control::stoppable(); + let frames = std::sync::Arc::new(AtomicBool::new(false)); + let (stop, stop_frames, repaint) = (control.clone(), frames.clone(), ctx.clone()); + let spawned = std::thread::Builder::new().name("Layout preview".into()).spawn(move || { + let _frames = rustgis_engine::render::cancel::install(stop_frames); + let drawn = rustgis_engine::analysis::run_under("Layout preview", &stop, work); + // Nothing waits for a dropped one. + let _ = send.send(drawn); + repaint.request_repaint(); + }); + match spawned { + Ok(_) => Shown::Drawing(Drawing { made, control, frames }), + Err(e) => refused(&e), + } +} + +/// A preview the system refused a thread for. +fn refused(e: &std::io::Error) -> Shown { + Shown::Drawn(Err(crate::thread_refused(e))) +} + +/// Drops the preview, its drawing told to stop, once what it was drawn from changes: asked each +/// frame whatever the step, so a choice changed elsewhere stops a drawing then. +pub(super) fn drop_stale_preview(s: &Session, d: &mut Draft) { + if d.preview.as_ref().is_some_and(|p| p.key != Key::now(s, d)) { + d.preview = d.preview.take().and_then(Preview::stopped); + } +} + +/// The Preview button, and under it the sheet it last drew, as wide as the step, with what Create +/// would warn of; a refusal in its place. While it draws, a spinner and Cancel. Returns the text +/// of a bug caught in a drawing that just ended, for Messages. +fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) -> Option { + let mut bug = None; + if let Some(preview) = &mut d.preview + && let Shown::Drawing(drawing) | Shown::Stopping(drawing) = &preview.shown + { + let made = match drawing.made.try_recv() { + Ok(made) => Some(made), + Err(TryRecvError::Empty) => None, + Err(TryRecvError::Disconnected) => Some(Err(tl!("The preview couldn't be drawn.").to_string())), + }; + if let Some(made) = made { + if matches!(preview.shown, Shown::Stopping(_)) { + // Cancelled, so nothing of it is shown; a bug it met is still said. + bug = made.err().filter(|e| rustgis_engine::data::incident::named(e).is_some()); + d.preview = None; + } else { + preview.shown = Shown::Drawn(made.map(|made| picture(ui.ctx(), made))); + bug = incident(&preview.shown); + } + } + } + let busy = d.preview.as_ref().is_some_and(|p| !matches!(p.shown, Shown::Drawn(_))); + let mut cancel = false; + ui.horizontal(|ui| { + if ui.add_enabled(!busy, egui::Button::new(tl!("Preview"))).clicked() { + let shown = draw(ui.ctx(), s, d, off_frame); + bug = incident(&shown); + d.preview = Some(Preview { key: Key::now(s, d), shown }); + } + // Asked after the click, so Cancel shows from the frame the drawing starts. + match d.preview.as_ref().map(|p| &p.shown) { + Some(Shown::Drawing(_)) => { + ui.spinner(); + cancel = ui.button(tl!("Cancel preview")).clicked(); + } + Some(Shown::Stopping(_)) => { + ui.spinner(); + ui.label(tl!("Cancelling the preview…")); + } + _ => {} + } + }); + if cancel { + d.preview = d.preview.take().and_then(Preview::stopped); + } + let Some(Preview { shown: Shown::Drawn(shown), .. }) = &d.preview else { + ui.separator(); + return bug; + }; + match shown { + Err(e) => { + ui.add(egui::Label::new(egui::RichText::new(e).color(ui.visuals().error_fg_color)).wrap()); + } + Ok(shown) => { + let size = shown.texture.size_vec2(); + let size = size * (ui.available_width() / size.x); + let picture = egui::Image::new((shown.texture.id(), size)).alt_text(tl!("Preview of the sheet")); + ui.add(picture); + if shown.pending { + ui.add(egui::Label::new(tl!("Some content was still loading: press Preview to draw it again.")).wrap()); + } + for warning in &shown.warnings { + ui.add(egui::Label::new(warning).wrap()); + } + } + } + ui.separator(); + bug +} + +/// What `shown` says of a bug caught while drawing it ([`rustgis_engine::data::incident`]). +fn incident(shown: &Shown) -> Option { + match shown { + Shown::Drawn(Err(e)) if rustgis_engine::data::incident::named(e).is_some() => Some(e.clone()), + _ => None, + } +} + /// The placement's row, and one more when Create also makes it the favourite. fn placement_rows(row: &mut impl FnMut(&str, String), s: &Session, d: &Draft) { row(tl!("Placement"), d.arrangement.label(s)); @@ -170,7 +405,8 @@ fn paper_review_row(row: &mut impl FnMut(&str, String), d: &Draft) { mod tests { use super::harness::*; use super::*; - use egui_kittest::kittest::Queryable; + use egui::accesskit::Role; + use egui_kittest::kittest::{NodeT, Queryable}; /// The review says what will be drawn: the default credit line, dated when the layout is made, and for /// a figure, that its texts and accent are left to the caption. @@ -257,4 +493,306 @@ mod tests { assert!(h.query_by_label(text).is_some(), "{text}"); } } + + type Wizard = egui_kittest::Harness<'static, RustGisApp>; + + const PICTURE: &str = "Preview of the sheet"; + + /// The wizard on its review, `set` applied to the app first. + fn reviewing(set: impl FnOnce(&mut RustGisApp)) -> Wizard { + let mut app = app(); + open(&mut app); + app.dialogs.publication.as_mut().unwrap().step = Step::Review; + set(&mut app); + harness(app) + } + + fn preview(h: &mut Wizard) { + h.get_by_role_and_label(Role::Button, "Preview").click(); + h.run_steps(4); + } + + fn pictured(h: &Wizard) -> bool { + h.query_by_role_and_label(Role::Image, PICTURE).is_some() + } + + /// The layouts there are and the step Undo would take. + fn made(h: &Wizard) -> (usize, Option<&'static str>) { + let s = &h.state().session; + (s.project.layouts.len(), s.undo_label()) + } + + #[test] + fn a_preview_shows_the_sheet_and_makes_nothing() { + let mut h = reviewing(|_| {}); + assert!(!pictured(&h), "drawn only on request"); + let before = made(&h); + preview(&mut h); + h.run_steps(20); + assert!(pictured(&h), "it stays while nothing changes"); + assert_eq!(made(&h), before); + assert!(h.query_by_role_and_label(Role::Button, "Preview").is_some(), "pressed again, it draws again"); + } + + /// The button and its picture come before the rows, which a sheet has more of than the step + /// shows at once. + #[test] + fn preview_and_its_picture_come_before_the_rows() { + let mut h = reviewing(|_| {}); + let top = |h: &Wizard, label: &str| h.get_by_label(label).rect().top(); + let button = h.get_by_role_and_label(Role::Button, "Preview").rect(); + assert!(button.bottom() <= top(&h, "Map extent"), "{button:?}"); + preview(&mut h); + let picture = h.get_by_role_and_label(Role::Image, PICTURE).rect(); + assert!(button.bottom() <= picture.top() && picture.bottom() <= top(&h, "Map extent"), "{picture:?}"); + } + + #[test] + fn a_choice_changed_removes_the_preview_and_going_back_and_forth_keeps_it() { + let mut h = reviewing(|_| {}); + preview(&mut h); + click(&mut h, "Back"); + click(&mut h, "Next"); + assert!(pictured(&h), "nothing changed"); + click(&mut h, "Back"); + { + let d = h.state_mut().dialogs.publication.as_mut().unwrap(); + (d.title, d.title_typed) = ("Another".into(), true); + } + click(&mut h, "Next"); + assert!(!pictured(&h)); + } + + #[test] + fn moving_the_map_removes_the_preview() { + let mut h = reviewing(|_| {}); + preview(&mut h); + h.state_mut().session.map_mut().camera.center.x += 1000.0; + h.run_steps(4); + assert!(!pictured(&h)); + preview(&mut h); + h.state_mut().session.view_size = (400.0, 900.0); + h.run_steps(4); + assert!(!pictured(&h), "the view resized"); + } + + #[test] + fn a_change_to_the_project_removes_the_preview() { + let mut h = reviewing(|_| {}); + preview(&mut h); + h.state_mut().run("layout.new", json!({"page": "a4", "template": "map"})).unwrap(); + h.run_steps(4); + assert!(!pictured(&h)); + preview(&mut h); + h.state_mut().run("edit.undo", Value::Null).unwrap(); + h.run_steps(4); + assert!(!pictured(&h), "undone"); + } + + /// The favourite is the app's, not the project's: Create reads it all the same. + #[test] + fn a_favourite_changed_removes_the_preview() { + let mut h = reviewing(|app| app.dialogs.publication.as_mut().unwrap().arrangement = Arrangement::Favourite); + preview(&mut h); + h.state_mut().run("layout.arrangement", json!({"favourite": "mirrored"})).unwrap(); + h.run_steps(4); + assert!(!pictured(&h)); + } + + #[test] + fn the_preview_says_what_create_warns_of_under_the_picture() { + let mut h = reviewing(|app| { + app.run("map.projection", json!({"type": "globe"})).unwrap(); + app.dialogs.publication.as_mut().unwrap().elements.scale_bar = true; + }); + let said = h.state().session.notices.len(); + let s = &h.state().session; + let params = create_params(s, h.state().dialogs.publication.as_ref().unwrap()).unwrap(); + let warnings = rustgis_engine::cmd::layout::publication_preview(s, ¶ms).unwrap().warnings; + assert!(!warnings.is_empty()); + preview(&mut h); + for w in &warnings { + assert!(h.query_by_label(w).is_some(), "{w}"); + } + assert_eq!(h.state().session.notices.len(), said); + } + + #[test] + fn a_refused_sheet_is_said_in_place_of_the_picture() { + let mut h = reviewing(|app| app.dialogs.publication.as_mut().unwrap().style = "unknown".into()); + let said = h.state().session.notices.len(); + preview(&mut h); + assert!(!pictured(&h)); + assert!(h.query_all_by_label_contains("unknown").count() > 1, "the refusal, besides the style's row"); + assert_eq!(h.state().session.notices.len(), said); + } + + #[test] + fn create_makes_the_same_layout_after_a_preview() { + let sheet = |previewed: bool| { + let mut h = reviewing(|_| {}); + if previewed { + preview(&mut h); + } + click(&mut h, "Create"); + serde_json::to_value(h.state().session.project.layouts.last().expect("made")).unwrap() + }; + assert_eq!(sheet(true), sheet(false)); + } + + /// The desktop app's wizard, which draws on a thread of its own, just asked for a preview. + fn drawing() -> Wizard { + let mut h = reviewing(|app| app.reads_off_frame = true); + h.get_by_role_and_label(Role::Button, "Preview").click(); + h.step(); + h + } + + fn cancel_of_the_preview(h: &Wizard) -> bool { + h.query_by_role_and_label(Role::Button, "Cancel preview").is_some() + } + + /// Runs frames until the drawing thread has had time to answer. + fn settle(h: &mut Wizard) { + let start = std::time::Instant::now(); + while cancel_of_the_preview(h) && start.elapsed() < std::time::Duration::from_secs(30) { + std::thread::sleep(std::time::Duration::from_millis(10)); // test-wait: the preview's thread answers + h.step(); + } + std::thread::sleep(std::time::Duration::from_millis(500)); // test-wait: a dropped drawing must not land + h.run_steps(4); + } + + #[test] + fn on_the_desktop_the_preview_draws_off_the_window_with_cancel() { + let mut h = drawing(); + assert!(cancel_of_the_preview(&h) && !pictured(&h), "drawing, not drawn on the click"); + settle(&mut h); + assert!(pictured(&h) && !cancel_of_the_preview(&h)); + } + + #[test] + fn a_cancelled_preview_shows_no_picture() { + let mut h = drawing(); + h.get_by_role_and_label(Role::Button, "Cancel preview").click(); + // The click's frame still draws the button; the next doesn't. + h.run_steps(2); + assert!(!cancel_of_the_preview(&h)); + settle(&mut h); + assert!(!pictured(&h)); + } + + #[test] + fn a_change_while_drawing_drops_the_preview() { + let mut h = drawing(); + h.state_mut().session.view_size = (400.0, 900.0); + h.step(); + assert!(!cancel_of_the_preview(&h)); + settle(&mut h); + assert!(!pictured(&h)); + } + + /// The two things a held drawing is told to stop by. + struct Stops(std::sync::Arc, std::sync::Arc); + + impl Stops { + fn told(&self) -> bool { + self.0.is_cancelled() && self.1.load(Ordering::Relaxed) + } + } + + /// A wizard whose preview's drawing the test answers for, with that drawing's control. + fn held() -> (Wizard, std::sync::mpsc::Sender>, Stops) { + let mut h = reviewing(|_| {}); + let (send, made) = channel(); + let control = Control::stoppable(); + let app = h.state_mut(); + let d = app.dialogs.publication.as_mut().unwrap(); + let frames = std::sync::Arc::new(AtomicBool::new(false)); + let drawing = Drawing { made, control: control.clone(), frames: frames.clone() }; + d.preview = Some(Preview { key: Key::now(&app.session, d), shown: Shown::Drawing(drawing) }); + h.run_steps(2); + (h, send, Stops(control, frames)) + } + + fn can_preview(h: &Wizard) -> bool { + !h.get_by_role_and_label(Role::Button, "Preview").accesskit_node().is_disabled() + } + + /// A drawing told to stop may run on, so no other starts beside it. + #[test] + fn preview_waits_for_a_cancelled_drawing_to_end() { + let stops: [fn(&mut Wizard); 2] = + [|h| h.get_by_role_and_label(Role::Button, "Cancel preview").click(), |h| h.state_mut().session.view_size = (400.0, 900.0)]; + for stop in stops { + let (mut h, send, stops) = held(); + stop(&mut h); + h.run_steps(3); + assert!(stops.told() && !can_preview(&h) && !cancel_of_the_preview(&h)); + let sheet = publication_preview_work(&h.state().session, json!({"profile": "a4-portrait"}))(); + send.send(sheet).unwrap(); + h.run_steps(3); + assert!(can_preview(&h) && !pictured(&h), "ended, and nothing of it shown"); + } + } + + #[test] + fn closing_the_wizard_stops_its_drawing() { + let (mut h, _send, stops) = held(); + assert!(!stops.told()); + click(&mut h, "Cancel"); + assert!(stops.told()); + } + + #[test] + fn a_bug_in_the_drawing_is_said_in_messages_once() { + let (mut h, send, _) = held(); + let caught = std::panic::catch_unwind(|| panic!("a drawing's bug")).unwrap_err(); + let said = rustgis_engine::data::incident::bug("The preview", caught.as_ref()); + send.send(Err(said.clone())).unwrap(); + h.run_steps(8); + assert_eq!(h.state().session.notices.iter().filter(|n| n.text == said).count(), 1); + assert!(h.query_by_label(&said).is_some(), "and in the step"); + } + + #[test] + fn a_bug_in_a_cancelled_drawing_is_still_said() { + let (mut h, send, _) = held(); + click(&mut h, "Cancel preview"); + let caught = std::panic::catch_unwind(|| panic!("a drawing's bug")).unwrap_err(); + let said = rustgis_engine::data::incident::bug("The preview", caught.as_ref()); + send.send(Err(said.clone())).unwrap(); + h.run_steps(8); + assert_eq!(h.state().session.notices.iter().filter(|n| n.text == said).count(), 1); + assert!(h.query_by_label(&said).is_none(), "no picture or refusal for a cancelled one"); + } + + #[test] + fn a_preview_refused_a_thread_says_so_as_other_jobs_do() { + let e = std::io::Error::other("no threads left"); + let Shown::Drawn(Err(said)) = refused(&e) else { panic!("a refusal") }; + assert_eq!(said, "The system refused a thread to do this on (no threads left); try again"); + } + + #[test] + fn a_choice_changed_on_another_step_stops_the_drawing_there() { + let (mut h, _send, stops) = held(); + click(&mut h, "Back"); + assert!(!stops.told(), "another step alone changes nothing"); + let d = h.state_mut().dialogs.publication.as_mut().unwrap(); + (d.title, d.title_typed) = ("Another".into(), true); + h.run_steps(4); + assert!(stops.told()); + } + + #[test] + fn the_next_wizard_opens_without_a_preview() { + let mut h = reviewing(|_| {}); + preview(&mut h); + click(&mut h, "Cancel"); + open(h.state_mut()); + h.state_mut().dialogs.publication.as_mut().unwrap().step = Step::Review; + h.run_steps(4); + assert!(!pictured(&h)); + } } diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index d71178f205..c1eee72d98 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -50,7 +50,12 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu Panel sheet, up to three, each a value and its label), the sources and reference (each one per line, with its heading; the reference can be left out) and the accent colour, with an Edge sheet's paper (the texts' colour follows it as the sheet is made, which Page Color afterwards - doesn't change), then shows what was picked; + doesn't change), then shows what was picked. There **Preview** draws the sheet Create would + make, with Create's warnings under it, or its refusal in its place; no layout is made. In the + desktop app, and in the phone's desktop interface (More › Use the Desktop Interface), it + draws while the window stays usable, with **Cancel preview**; Preview waits for a cancelled + drawing to end. The drawing doesn't wait for tiles, cast shadows or legend pictures still on their way, and says so. The + picture goes when a choice, the project or the map's view changes; Preview draws it again; **Create** makes the layout as the menu does. **Insert Statistic**, on the texts and sources steps, adds a layer figure of the active map to the field the cursor was last in there (the note or the sources, where it was in none). The map extent is the view, the features one layer shows