From c30e3cbf1e42c924fd2869903a630c951a9f5ed0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 14:13:21 -0500 Subject: [PATCH 01/10] feat(layout): preview the sheet on the Layout Wizard's review step --- crates/engine/src/cmd/layout.rs | 2 + crates/engine/src/cmd/layout/preview.rs | 66 +++++ crates/engine/src/service_logins.rs | 8 +- crates/engine/src/tests.rs | 3 + crates/engine/src/tests/layout_preview.rs | 119 +++++++++ crates/render/src/layout.rs | 6 + crates/render/src/lib.rs | 14 ++ crates/ui-egui/src/publicationwizard/mod.rs | 34 ++- .../ui-egui/src/publicationwizard/review.rs | 234 +++++++++++++++++- docs/user-guide/layouts.md | 5 +- 10 files changed, 475 insertions(+), 16 deletions(-) create mode 100644 crates/engine/src/cmd/layout/preview.rs create mode 100644 crates/engine/src/tests/layout_preview.rs 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/preview.rs b/crates/engine/src/cmd/layout/preview.rs new file mode 100644 index 0000000000..fcd9de2ff6 --- /dev/null +++ b/crates/engine/src/cmd/layout/preview.rs @@ -0,0 +1,66 @@ +//! The sheet `layout.publication` would make, drawn without touching the project (#3475). + +use rustgis_render::layout::{PageInfo, PagePending}; +use serde_json::Value; + +use crate::Session; + +/// 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. + pub warnings: Vec, +} + +/// A copy of `s` to run `layout.publication` on: 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`]). +pub(crate) fn preview_copy(s: &Session) -> Session { + let mut project = s.project.clone(); + for m in &mut project.maps { + m.detach_reads(); + } + let mut copy = Session::new(project); + copy.set_extensions(s.extensions().clone()); + copy.connections = s.connections.clone(); + copy.web_logins = s.web_logins.borrowing_open(); + for (origin, id) in s.database_logins.web_selections() { + copy.database_logins.select(crate::connections::WEB, origin, id); + } + #[cfg(not(target_arch = "wasm32"))] + { + copy.requests_into = Some(s.diagnostics.capture()); + } + (copy.view_size, copy.active_layer, copy.opened) = (s.view_size, s.active_layer, s.opened); + (copy.in_place_wait, copy.raster_defaults, copy.offers_grid_downloads, copy.auto_cache) = + (s.in_place_wait, s.raster_defaults.clone(), s.offers_grid_downloads, s.auto_cache); + copy.layout_favourite.clone_from(&s.layout_favourite); + copy.layout_arrangements.clone_from(&s.layout_arrangements); + // The copy shares this session's rows, which this session already counts (#2431). + copy.undo_memory.memory = None; + copy.undo_memory.use_readers(s.undo_memory.readers()); + copy.sync_policy_generation(); + copy +} + +/// The sheet `layout.publication` with `params` would make, drawn at [`PREVIEW_DPI`] without +/// waiting for what is still on its way; `s` doesn't change. Its refusal is the error. The command +/// reads streamed layers as it does when run on `s`. +pub fn publication_preview(s: &Session, params: &Value) -> Result { + let mut copy = preview_copy(s); + let made = copy.run("layout.publication", params)?; + let layout = copy.project.layouts.last().ok_or("no layout")?.clone(); + let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; + let (drawn, said) = + rustgis_render::shadows_said(|| rustgis_render::layout::render_preview(&layout, &mut copy.project.maps, PREVIEW_DPI, &info)); + let (pixmap, mut pending) = drawn?; + // Cast shadows still being worked out are content on its way too. + pending.frames |= said.to_come; + let warnings = made["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str().map(String::from)).collect(); + Ok(PublicationPreview { pixmap, pending, warnings }) +} 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..ba01e3184e --- /dev/null +++ b/crates/engine/src/tests/layout_preview.rs @@ -0,0 +1,119 @@ +//! `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()); +} + +/// 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(|_, done| 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); +} 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..33bacfb24d 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,15 @@ 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 { + let before = NO_TILE_WAIT.with(|c| c.replace(true)); + let out = f(); + NO_TILE_WAIT.with(|c| c.set(before)); + out +} + /// 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 +9292,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; diff --git a/crates/ui-egui/src/publicationwizard/mod.rs b/crates/ui-egui/src/publicationwizard/mod.rs index e46b5ab7eb..b58bbb0f07 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, 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) { @@ -609,7 +627,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 => review_step(ui, &app.session, &mut d), }); }); if let Some(step) = picked { @@ -642,16 +660,8 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { } // 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..a568a0126f 100644 --- a/crates/ui-egui/src/publicationwizard/review.rs +++ b/crates/ui-egui/src/publicationwizard/review.rs @@ -2,9 +2,17 @@ use super::elements::elements_value; use super::map::{area_label, name_label}; use super::*; +use rustgis_engine::cmd::layout::publication_preview; +use rustgis_engine::map::Camera; -/// 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: what was picked, and the sheet they make once asked for. +pub(super) fn review_step(ui: &mut egui::Ui, s: &Session, d: &mut Draft) { + picked_rows(ui, s, d); + preview_part(ui, s, d); +} + +/// 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 +62,92 @@ pub(super) fn review_step(ui: &mut egui::Ui, s: &Session, d: &Draft) { } } +/// What a preview was drawn from, cheap enough to compare each frame: the area as picked, not +/// resolved ([`create_params`] may walk a whole layer), and what of the session the sheet reads. +#[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 last drawn, or why there is none. +pub(super) struct Preview { + key: Key, + shown: Result, +} + +struct Shown { + texture: egui::TextureHandle, + warnings: Vec, + /// Something was still on its way when it was drawn. + pending: bool, +} + +/// Draws the sheet Create would make. +fn draw(ctx: &egui::Context, s: &Session, d: &Draft) -> Result { + let made = publication_preview(s, &create_params(s, d)?)?; + let size = [made.pixmap.width() as usize, made.pixmap.height() as usize]; + let pixels = egui::ColorImage::from_rgba_premultiplied(size, made.pixmap.data()); + Ok(Shown { + texture: ctx.load_texture("publication_preview", pixels, egui::TextureOptions::LINEAR), + warnings: made.warnings, + pending: made.pending.frames || made.pending.legends, + }) +} + +/// 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. +fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft) { + if d.preview.as_ref().is_some_and(|p| p.key != Key::now(s, d)) { + d.preview = None; + } + ui.add_space(8.0); + let asked = ui.button(tl!("Preview")).clicked(); + if asked { + d.preview = Some(Preview { key: Key::now(s, d), shown: draw(ui.ctx(), s, d) }); + } + let Some(preview) = &d.preview else { return }; + let r = match &preview.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")); + let r = 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()); + } + r + } + }; + // Drawn under the rows, out of sight in a short window. + if asked { + r.scroll_to_me(Some(egui::Align::Min)); + } +} + /// 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,6 +264,7 @@ fn paper_review_row(row: &mut impl FnMut(&str, String), d: &Draft) { mod tests { use super::harness::*; use super::*; + use egui::accesskit::Role; use egui_kittest::kittest::Queryable; /// The review says what will be drawn: the default credit line, dated when the layout is made, and for @@ -257,4 +352,139 @@ 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) + } + + /// Presses Preview, which sits under the rows, out of the step's sight. + fn preview(h: &mut Wizard) { + h.get_by_role_and_label(Role::Button, "Preview").click_accesskit(); + 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"); + } + + #[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"); + } + + #[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)); + } + + #[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..4165e7ceab 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -50,7 +50,10 @@ 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. It + 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 From ea46fb670af17a05fe3a56111a67e22c6dc9cb9f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 14:35:29 -0500 Subject: [PATCH 02/10] fix(layout): the preview says Create's notices; its copy builds for the web --- crates/engine/src/cmd/layout/preview.rs | 8 ++++++-- crates/engine/src/lib.rs | 3 +-- crates/engine/src/tests/layout_preview.rs | 16 ++++++++++++++++ crates/engine/src/undo_memory.rs | 1 - 4 files changed, 23 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layout/preview.rs b/crates/engine/src/cmd/layout/preview.rs index fcd9de2ff6..8fc0aec336 100644 --- a/crates/engine/src/cmd/layout/preview.rs +++ b/crates/engine/src/cmd/layout/preview.rs @@ -13,7 +13,7 @@ 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. + /// What `layout.publication` warns of and says, and what the drawing left out. pub warnings: Vec, } @@ -61,6 +61,10 @@ pub fn publication_preview(s: &Session, params: &Value) -> Result = + 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())); + warnings.extend(said.notices); Ok(PublicationPreview { pixmap, pending, warnings }) } diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 9a15221a5f..fcbbbf8431 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -4489,8 +4489,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/tests/layout_preview.rs b/crates/engine/src/tests/layout_preview.rs index ba01e3184e..049d9b8957 100644 --- a/crates/engine/src/tests/layout_preview.rs +++ b/crates/engine/src/tests/layout_preview.rs @@ -117,3 +117,19 @@ fn a_preview_does_not_wait_for_tiles() { assert!(start.elapsed() < std::time::Duration::from_secs(20), "waited {:?}", start.elapsed()); assert!(p.pending.frames); } + +/// 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; } From f321e74adfb9245c3ef88cf871c128a5b6ddd1bf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 14:41:19 -0500 Subject: [PATCH 03/10] fix(layout): the wizard's Preview button comes before the review's rows --- .../ui-egui/src/publicationwizard/review.rs | 38 +++++++++++-------- 1 file changed, 23 insertions(+), 15 deletions(-) diff --git a/crates/ui-egui/src/publicationwizard/review.rs b/crates/ui-egui/src/publicationwizard/review.rs index a568a0126f..139c4cad02 100644 --- a/crates/ui-egui/src/publicationwizard/review.rs +++ b/crates/ui-egui/src/publicationwizard/review.rs @@ -5,10 +5,10 @@ use super::*; use rustgis_engine::cmd::layout::publication_preview; use rustgis_engine::map::Camera; -/// The review step: what was picked, and the sheet they make once asked for. +/// The review step: the sheet once asked for, then what was picked. pub(super) fn review_step(ui: &mut egui::Ui, s: &Session, d: &mut Draft) { - picked_rows(ui, s, d); preview_part(ui, s, d); + picked_rows(ui, s, d); } /// What was picked, step by step. @@ -120,32 +120,28 @@ fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft) { if d.preview.as_ref().is_some_and(|p| p.key != Key::now(s, d)) { d.preview = None; } - ui.add_space(8.0); - let asked = ui.button(tl!("Preview")).clicked(); - if asked { + if ui.button(tl!("Preview")).clicked() { d.preview = Some(Preview { key: Key::now(s, d), shown: draw(ui.ctx(), s, d) }); } let Some(preview) = &d.preview else { return }; - let r = match &preview.shown { - Err(e) => ui.add(egui::Label::new(egui::RichText::new(e).color(ui.visuals().error_fg_color)).wrap()), + match &preview.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")); - let r = ui.add(picture); + 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()); } - r } - }; - // Drawn under the rows, out of sight in a short window. - if asked { - r.scroll_to_me(Some(egui::Align::Min)); } + ui.separator(); } /// The placement's row, and one more when Create also makes it the favourite. @@ -366,9 +362,8 @@ mod tests { harness(app) } - /// Presses Preview, which sits under the rows, out of the step's sight. fn preview(h: &mut Wizard) { - h.get_by_role_and_label(Role::Button, "Preview").click_accesskit(); + h.get_by_role_and_label(Role::Button, "Preview").click(); h.run_steps(4); } @@ -394,6 +389,19 @@ mod tests { 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(|_| {}); From 7c492ff14c2308acf7697275ca6e2f94a04f6551 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 14:45:42 -0500 Subject: [PATCH 04/10] docs(layout): say why the wizard's preview draws on the UI thread; pin the favourite case --- .../ui-egui/src/publicationwizard/review.rs | 19 ++++++++++++++++--- 1 file changed, 16 insertions(+), 3 deletions(-) diff --git a/crates/ui-egui/src/publicationwizard/review.rs b/crates/ui-egui/src/publicationwizard/review.rs index 139c4cad02..c04313d90b 100644 --- a/crates/ui-egui/src/publicationwizard/review.rs +++ b/crates/ui-egui/src/publicationwizard/review.rs @@ -62,8 +62,9 @@ fn picked_rows(ui: &mut egui::Ui, s: &Session, d: &Draft) { } } -/// What a preview was drawn from, cheap enough to compare each frame: the area as picked, not -/// resolved ([`create_params`] may walk a whole layer), and what of the session the sheet reads. +/// 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, @@ -102,7 +103,9 @@ struct Shown { pending: bool, } -/// Draws the sheet Create would make. +/// Draws the sheet Create would make, on the UI thread, as Create runs `layout.publication` +/// there: only on request, not waiting for tiles. A thread of its own would not serve the browser, +/// and `layout.publication` has no progress or Cancel to give. fn draw(ctx: &egui::Context, s: &Session, d: &Draft) -> Result { let made = publication_preview(s, &create_params(s, d)?)?; let size = [made.pixmap.width() as usize, made.pixmap.height() as usize]; @@ -444,6 +447,16 @@ mod tests { 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| { From a8bbf8a5ab427fc83275093d012b87588ee0eb41 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 15:02:10 -0500 Subject: [PATCH 05/10] fix(layout): draw the wizard's preview off the window's thread, with Cancel --- crates/engine/src/cmd/layout/preview.rs | 111 +++++++----- crates/ui-egui/src/publicationwizard/mod.rs | 2 +- .../ui-egui/src/publicationwizard/review.rs | 161 +++++++++++++++--- docs/user-guide/layouts.md | 3 +- 4 files changed, 215 insertions(+), 62 deletions(-) diff --git a/crates/engine/src/cmd/layout/preview.rs b/crates/engine/src/cmd/layout/preview.rs index 8fc0aec336..3f9227460c 100644 --- a/crates/engine/src/cmd/layout/preview.rs +++ b/crates/engine/src/cmd/layout/preview.rs @@ -4,6 +4,7 @@ use rustgis_render::layout::{PageInfo, 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; @@ -17,54 +18,82 @@ pub struct PublicationPreview { pub warnings: Vec, } -/// A copy of `s` to run `layout.publication` on: 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`]). -pub(crate) fn preview_copy(s: &Session) -> Session { +/// 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 mut copy = Session::new(project); - copy.set_extensions(s.extensions().clone()); - copy.connections = s.connections.clone(); - copy.web_logins = s.web_logins.borrowing_open(); - for (origin, id) in s.database_logins.web_selections() { - copy.database_logins.select(crate::connections::WEB, origin, id); - } + 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(); #[cfg(not(target_arch = "wasm32"))] - { - copy.requests_into = Some(s.diagnostics.capture()); - } - (copy.view_size, copy.active_layer, copy.opened) = (s.view_size, s.active_layer, s.opened); - (copy.in_place_wait, copy.raster_defaults, copy.offers_grid_downloads, copy.auto_cache) = + 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); - copy.layout_favourite.clone_from(&s.layout_favourite); - copy.layout_arrangements.clone_from(&s.layout_arrangements); - // The copy shares this session's rows, which this session already counts (#2431). - copy.undo_memory.memory = None; - copy.undo_memory.use_readers(s.undo_memory.readers()); - copy.sync_policy_generation(); - copy + 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); + } + #[cfg(not(target_arch = "wasm32"))] + { + 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. The command reads streamed layers as it does when run on `s`. +pub fn publication_preview_work(s: &Session, params: Value) -> impl FnOnce() -> Result + Send + 'static { + let copy = copy_of(s); + move || { + // Bound first, so it is dropped after the copy. + let (_retained, mut copy) = copy(); + let made = copy.run("layout.publication", ¶ms)?; + let layout = copy.project.layouts.last().ok_or("no layout")?.clone(); + let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; + let (drawn, said) = + rustgis_render::shadows_said(|| rustgis_render::layout::render_preview(&layout, &mut copy.project.maps, PREVIEW_DPI, &info)); + let (pixmap, mut pending) = drawn?; + // Cast shadows still being worked out are content on its way too. + pending.frames |= said.to_come; + // What Create answers, then what it says as notices, then what the drawing left out. + 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())); + warnings.extend(said.notices); + Ok(PublicationPreview { pixmap, pending, warnings }) + } } -/// The sheet `layout.publication` with `params` would make, drawn at [`PREVIEW_DPI`] without -/// waiting for what is still on its way; `s` doesn't change. Its refusal is the error. The command -/// reads streamed layers as it does when run on `s`. +/// [`publication_preview_work`], done here. pub fn publication_preview(s: &Session, params: &Value) -> Result { - let mut copy = preview_copy(s); - let made = copy.run("layout.publication", params)?; - let layout = copy.project.layouts.last().ok_or("no layout")?.clone(); - let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; - let (drawn, said) = - rustgis_render::shadows_said(|| rustgis_render::layout::render_preview(&layout, &mut copy.project.maps, PREVIEW_DPI, &info)); - let (pixmap, mut pending) = drawn?; - // Cast shadows still being worked out are content on its way too. - pending.frames |= said.to_come; - // What Create answers, then what it says as notices, then what the drawing left out. - 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())); - warnings.extend(said.notices); - Ok(PublicationPreview { pixmap, pending, warnings }) + publication_preview_work(s, params.clone())() } diff --git a/crates/ui-egui/src/publicationwizard/mod.rs b/crates/ui-egui/src/publicationwizard/mod.rs index b58bbb0f07..ba4b2f033a 100644 --- a/crates/ui-egui/src/publicationwizard/mod.rs +++ b/crates/ui-egui/src/publicationwizard/mod.rs @@ -627,7 +627,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, &mut d), + Step::Review => review_step(ui, &app.session, &mut d, app.reads_off_frame), }); }); if let Some(step) = picked { diff --git a/crates/ui-egui/src/publicationwizard/review.rs b/crates/ui-egui/src/publicationwizard/review.rs index c04313d90b..ad60416015 100644 --- a/crates/ui-egui/src/publicationwizard/review.rs +++ b/crates/ui-egui/src/publicationwizard/review.rs @@ -2,12 +2,14 @@ use super::elements::elements_value; use super::map::{area_label, name_label}; use super::*; -use rustgis_engine::cmd::layout::publication_preview; +use rustgis_engine::analysis::control::Control; +use rustgis_engine::cmd::layout::{PublicationPreview, publication_preview_work}; use rustgis_engine::map::Camera; +use std::sync::mpsc::{Receiver, TryRecvError, channel}; /// The review step: the sheet once asked for, then what was picked. -pub(super) fn review_step(ui: &mut egui::Ui, s: &Session, d: &mut Draft) { - preview_part(ui, s, d); +pub(super) fn review_step(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) { + preview_part(ui, s, d, off_frame); picked_rows(ui, s, d); } @@ -90,44 +92,113 @@ impl Key { } } -/// The sheet last drawn, or why there is none. +/// The sheet asked for last: being drawn, drawn, or why there is none. pub(super) struct Preview { key: Key, - shown: Result, + shown: Shown, } -struct Shown { +enum Shown { + Drawing(Drawing), + Drawn(Result), +} + +/// A sheet being drawn on a thread of its own, cancelled when dropped: by Cancel, a change of +/// what it draws, or the wizard closing. +struct Drawing { + made: Receiver>, + control: std::sync::Arc, +} + +impl Drop for Drawing { + fn drop(&mut self) { + self.control.cancel(); + } +} + +struct Picture { texture: egui::TextureHandle, warnings: Vec, /// Something was still on its way when it was drawn. pending: bool, } -/// Draws the sheet Create would make, on the UI thread, as Create runs `layout.publication` -/// there: only on request, not waiting for tiles. A thread of its own would not serve the browser, -/// and `layout.publication` has no progress or Cancel to give. -fn draw(ctx: &egui::Context, s: &Session, d: &Draft) -> Result { - let made = publication_preview(s, &create_params(s, d)?)?; +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()); - Ok(Shown { + 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, 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. +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 (stop, repaint) = (control.clone(), ctx.clone()); + let spawned = std::thread::Builder::new().name("Layout preview".into()).spawn(move || { + // Stops at Cancel. A drawing that panics drops `send`, which the step says. + 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 }), + Err(e) => Shown::Drawn(Err(e.to_string())), + } } /// 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. -fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft) { +/// would warn of; a refusal in its place. While it draws, a spinner and Cancel. +fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) { if d.preview.as_ref().is_some_and(|p| p.key != Key::now(s, d)) { d.preview = None; } - if ui.button(tl!("Preview")).clicked() { - d.preview = Some(Preview { key: Key::now(s, d), shown: draw(ui.ctx(), s, d) }); + if let Some(preview) = &mut d.preview + && let Shown::Drawing(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 { + preview.shown = Shown::Drawn(made.map(|made| picture(ui.ctx(), made))); + } } - let Some(preview) = &d.preview else { return }; - match &preview.shown { + let drawing = d.preview.as_ref().is_some_and(|p| matches!(p.shown, Shown::Drawing(_))); + let mut cancel = false; + ui.horizontal(|ui| { + if ui.add_enabled(!drawing, egui::Button::new(tl!("Preview"))).clicked() { + d.preview = Some(Preview { key: Key::now(s, d), shown: draw(ui.ctx(), s, d, off_frame) }); + } + // Asked after the click, so Cancel shows from the frame the drawing starts. + if d.preview.as_ref().is_some_and(|p| matches!(p.shown, Shown::Drawing(_))) { + ui.spinner(); + cancel = ui.button(tl!("Cancel preview")).clicked(); + } + }); + if cancel { + d.preview = None; + } + let Some(Preview { shown: Shown::Drawn(shown), .. }) = &d.preview else { + ui.separator(); + return; + }; + match shown { Err(e) => { ui.add(egui::Label::new(egui::RichText::new(e).color(ui.visuals().error_fg_color)).wrap()); } @@ -498,6 +569,58 @@ mod tests { 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)); + } + #[test] fn the_next_wizard_opens_without_a_preview() { let mut h = reviewing(|_| {}); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 4165e7ceab..7fb4a9bbf7 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -51,7 +51,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu 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. There **Preview** draws the sheet Create would - make, with Create's warnings under it, or its refusal in its place; no layout is made. It + make, with Create's warnings under it, or its refusal in its place; no layout is made. In the + desktop app and on the phone it draws while the window stays usable, with **Cancel preview**. It 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 From 370170c1b49b9d2746c1294cb16d4668f4bccaa7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 15:13:54 -0500 Subject: [PATCH 06/10] fix(layout): the wizard's preview waits for a cancelled drawing to end --- .../ui-egui/src/publicationwizard/review.rs | 96 ++++++++++++++++--- docs/user-guide/layouts.md | 4 +- 2 files changed, 84 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/publicationwizard/review.rs b/crates/ui-egui/src/publicationwizard/review.rs index ad60416015..4332bf5982 100644 --- a/crates/ui-egui/src/publicationwizard/review.rs +++ b/crates/ui-egui/src/publicationwizard/review.rs @@ -100,11 +100,28 @@ pub(super) struct Preview { enum Shown { Drawing(Drawing), + /// Told to stop, by Cancel or a change of what it draws, and not ended yet: the plain page + /// drawing doesn't look at Cancel, so no other starts beside it. + Stopping(Drawing), Drawn(Result), } -/// A sheet being drawn on a thread of its own, cancelled when dropped: by Cancel, a change of -/// what it draws, or the wizard closing. +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.control.cancel(); + 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 may then run to its end. struct Drawing { made: Receiver>, control: std::sync::Arc, @@ -134,8 +151,11 @@ fn picture(ctx: &egui::Context, made: PublicationPreview) -> Picture { } /// Starts drawing the sheet Create would make: on a thread of its own with `off_frame` (the -/// desktop app and the phone, 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. +/// 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, @@ -149,7 +169,8 @@ fn draw(ctx: &egui::Context, s: &Session, d: &Draft, off_frame: bool) -> Shown { let control = Control::stoppable(); let (stop, repaint) = (control.clone(), ctx.clone()); let spawned = std::thread::Builder::new().name("Layout preview".into()).spawn(move || { - // Stops at Cancel. A drawing that panics drops `send`, which the step says. + // Cancel stops it where the work looks at it: its reads, not the plain page drawing. + // A drawing that panics drops `send`, which the step says. let drawn = rustgis_engine::analysis::run_under("Layout preview", &stop, work); // Nothing waits for a dropped one. let _ = send.send(drawn); @@ -165,10 +186,10 @@ fn draw(ctx: &egui::Context, s: &Session, d: &Draft, off_frame: bool) -> Shown { /// would warn of; a refusal in its place. While it draws, a spinner and Cancel. fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) { if d.preview.as_ref().is_some_and(|p| p.key != Key::now(s, d)) { - d.preview = None; + d.preview = d.preview.take().and_then(Preview::stopped); } if let Some(preview) = &mut d.preview - && let Shown::Drawing(drawing) = &preview.shown + && let Shown::Drawing(drawing) | Shown::Stopping(drawing) = &preview.shown { let made = match drawing.made.try_recv() { Ok(made) => Some(made), @@ -176,23 +197,34 @@ fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) Err(TryRecvError::Disconnected) => Some(Err(tl!("The preview couldn't be drawn.").to_string())), }; if let Some(made) = made { - preview.shown = Shown::Drawn(made.map(|made| picture(ui.ctx(), made))); + if matches!(preview.shown, Shown::Stopping(_)) { + d.preview = None; + } else { + preview.shown = Shown::Drawn(made.map(|made| picture(ui.ctx(), made))); + } } } - let drawing = d.preview.as_ref().is_some_and(|p| matches!(p.shown, Shown::Drawing(_))); + 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(!drawing, egui::Button::new(tl!("Preview"))).clicked() { + if ui.add_enabled(!busy, egui::Button::new(tl!("Preview"))).clicked() { d.preview = Some(Preview { key: Key::now(s, d), shown: draw(ui.ctx(), s, d, off_frame) }); } // Asked after the click, so Cancel shows from the frame the drawing starts. - if d.preview.as_ref().is_some_and(|p| matches!(p.shown, Shown::Drawing(_))) { - ui.spinner(); - cancel = ui.button(tl!("Cancel preview")).clicked(); + 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 = None; + d.preview = d.preview.take().and_then(Preview::stopped); } let Some(Preview { shown: Shown::Drawn(shown), .. }) = &d.preview else { ui.separator(); @@ -335,7 +367,7 @@ mod tests { use super::harness::*; use super::*; use egui::accesskit::Role; - use egui_kittest::kittest::Queryable; + 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. @@ -621,6 +653,40 @@ mod tests { assert!(!pictured(&h)); } + /// A wizard whose preview's drawing the test answers for, with that drawing's control. + fn held() -> (Wizard, std::sync::mpsc::Sender>, std::sync::Arc) { + 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 drawing = Drawing { made, control: control.clone() }; + d.preview = Some(Preview { key: Key::now(&app.session, d), shown: Shown::Drawing(drawing) }); + h.run_steps(2); + (h, send, control) + } + + 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, control) = held(); + stop(&mut h); + h.run_steps(3); + assert!(control.is_cancelled() && !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 the_next_wizard_opens_without_a_preview() { let mut h = reviewing(|_| {}); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 7fb4a9bbf7..ede2685706 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -52,7 +52,9 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu 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. 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 on the phone it draws while the window stays usable, with **Cancel preview**. It + 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. It 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 From 64f44439067d5f55d09a2d0c1fce5cf387a62a2d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 15:50:49 -0500 Subject: [PATCH 07/10] fix(layout): catch a bug in the preview's drawing, stop it with the page flag and keep its requests --- crates/engine/src/cmd/layout/preview.rs | 51 +++++----- crates/engine/src/lib.rs | 9 +- crates/engine/src/tests/layout_preview.rs | 7 +- crates/render/src/lib.rs | 21 +++- crates/ui-egui/src/publicationwizard/mod.rs | 8 +- .../ui-egui/src/publicationwizard/review.rs | 98 +++++++++++++++---- docs/user-guide/layouts.md | 3 +- 7 files changed, 135 insertions(+), 62 deletions(-) diff --git a/crates/engine/src/cmd/layout/preview.rs b/crates/engine/src/cmd/layout/preview.rs index 3f9227460c..7d98dd051a 100644 --- a/crates/engine/src/cmd/layout/preview.rs +++ b/crates/engine/src/cmd/layout/preview.rs @@ -29,7 +29,6 @@ fn copy_of(s: &Session) -> impl FnOnce() -> (ReadRows, Session) + Send + 'static 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(); - #[cfg(not(target_arch = "wasm32"))] 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) = @@ -46,10 +45,7 @@ fn copy_of(s: &Session) -> impl FnOnce() -> (ReadRows, Session) + Send + 'static for (origin, id) in &selections { copy.database_logins.select(crate::connections::WEB, origin, id); } - #[cfg(not(target_arch = "wasm32"))] - { - copy.requests_into = Some(requests); - } + 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); @@ -70,29 +66,38 @@ pub(crate) fn preview_copy(s: &Session) -> Session { /// 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. The command reads streamed layers as it does when run on `s`. +/// 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 = copy_of(s); + let (copy, requests) = (copy_of(s), s.diagnostics.capture()); move || { - // Bound first, so it is dropped after the copy. - let (_retained, mut copy) = copy(); - let made = copy.run("layout.publication", ¶ms)?; - let layout = copy.project.layouts.last().ok_or("no layout")?.clone(); - let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; - let (drawn, said) = - rustgis_render::shadows_said(|| rustgis_render::layout::render_preview(&layout, &mut copy.project.maps, PREVIEW_DPI, &info)); - let (pixmap, mut pending) = drawn?; - // Cast shadows still being worked out are content on its way too. - pending.frames |= said.to_come; - // What Create answers, then what it says as notices, then what the drawing left out. - 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())); - warnings.extend(said.notices); - Ok(PublicationPreview { pixmap, pending, warnings }) + 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 layout = copy.project.layouts.last().ok_or("no layout")?.clone(); + let info = PageInfo { page: 1, pages: 1, page_name: String::new() }; + let (drawn, said) = + rustgis_render::shadows_said(|| rustgis_render::layout::render_preview(&layout, &mut copy.project.maps, PREVIEW_DPI, &info)); + let (pixmap, mut pending) = drawn?; + // Cast shadows still being worked out are content on its way too. + pending.frames |= said.to_come; + // What Create answers, then what it says as notices, then what the drawing left out. + 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())); + warnings.extend(said.notices); + 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 fcbbbf8431..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; } diff --git a/crates/engine/src/tests/layout_preview.rs b/crates/engine/src/tests/layout_preview.rs index 049d9b8957..ec35b66677 100644 --- a/crates/engine/src/tests/layout_preview.rs +++ b/crates/engine/src/tests/layout_preview.rs @@ -109,13 +109,18 @@ fn a_preview_does_not_wait_for_tiles() { } isolate_plugins(); static HELD: std::sync::Mutex>> = std::sync::Mutex::new(Vec::new()); - crate::render::rustgis_tiles::cache::set_fetcher(|_, done| HELD.lock().unwrap().push(Box::new(done))); + 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. diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 33bacfb24d..d2889221e5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -9195,10 +9195,15 @@ pub(crate) fn without_shadow_wait(f: impl FnOnce() -> T) -> T { /// 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 { - let before = NO_TILE_WAIT.with(|c| c.replace(true)); - let out = f(); - NO_TILE_WAIT.with(|c| c.set(before)); - out + /// 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 @@ -10671,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/publicationwizard/mod.rs b/crates/ui-egui/src/publicationwizard/mod.rs index ba4b2f033a..1f6f1650cf 100644 --- a/crates/ui-egui/src/publicationwizard/mod.rs +++ b/crates/ui-egui/src/publicationwizard/mod.rs @@ -569,6 +569,8 @@ pub fn show(app: &mut RustGisApp, ctx: &egui::Context) { 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(); @@ -627,7 +629,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, &mut d, app.reads_off_frame), + Step::Review => bug = review_step(ui, &app.session, &mut d, app.reads_off_frame), }); }); if let Some(step) = picked { @@ -655,8 +657,8 @@ 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 { diff --git a/crates/ui-egui/src/publicationwizard/review.rs b/crates/ui-egui/src/publicationwizard/review.rs index 4332bf5982..435b2c2ac5 100644 --- a/crates/ui-egui/src/publicationwizard/review.rs +++ b/crates/ui-egui/src/publicationwizard/review.rs @@ -5,12 +5,15 @@ 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: the sheet once asked for, then what was picked. -pub(super) fn review_step(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) { - preview_part(ui, s, d, off_frame); +/// 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. @@ -100,8 +103,8 @@ pub(super) struct Preview { enum Shown { Drawing(Drawing), - /// Told to stop, by Cancel or a change of what it draws, and not ended yet: the plain page - /// drawing doesn't look at Cancel, so no other starts beside it. + /// 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), } @@ -112,7 +115,7 @@ impl Preview { fn stopped(self) -> Option { match self.shown { Shown::Drawing(drawing) | Shown::Stopping(drawing) => { - drawing.control.cancel(); + drawing.stop(); Some(Self { key: self.key, shown: Shown::Stopping(drawing) }) } Shown::Drawn(_) => None, @@ -121,15 +124,25 @@ impl Preview { } /// A sheet being drawn on a thread of its own, cancelled when dropped, as the wizard closing -/// drops it; its thread may then run to its end. +/// 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.control.cancel(); + self.stop(); } } @@ -167,24 +180,26 @@ fn draw(ctx: &egui::Context, s: &Session, d: &Draft, off_frame: bool) -> Shown { } let (send, made) = channel(); let control = Control::stoppable(); - let (stop, repaint) = (control.clone(), ctx.clone()); + 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 || { - // Cancel stops it where the work looks at it: its reads, not the plain page drawing. - // A drawing that panics drops `send`, which the step says. + 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 }), + Ok(_) => Shown::Drawing(Drawing { made, control, frames }), Err(e) => Shown::Drawn(Err(e.to_string())), } } /// 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. -fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) { +/// 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 d.preview.as_ref().is_some_and(|p| p.key != Key::now(s, d)) { d.preview = d.preview.take().and_then(Preview::stopped); } @@ -201,6 +216,7 @@ fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) d.preview = None; } else { preview.shown = Shown::Drawn(made.map(|made| picture(ui.ctx(), made))); + bug = incident(&preview.shown); } } } @@ -208,7 +224,9 @@ fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) let mut cancel = false; ui.horizontal(|ui| { if ui.add_enabled(!busy, egui::Button::new(tl!("Preview"))).clicked() { - d.preview = Some(Preview { key: Key::now(s, d), shown: draw(ui.ctx(), s, d, off_frame) }); + 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) { @@ -228,7 +246,7 @@ fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) } let Some(Preview { shown: Shown::Drawn(shown), .. }) = &d.preview else { ui.separator(); - return; + return bug; }; match shown { Err(e) => { @@ -248,6 +266,15 @@ fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) } } 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. @@ -653,17 +680,27 @@ mod tests { 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>, std::sync::Arc) { + 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 drawing = Drawing { made, control: control.clone() }; + 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, control) + (h, send, Stops(control, frames)) } fn can_preview(h: &Wizard) -> bool { @@ -676,10 +713,10 @@ mod tests { 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, control) = held(); + let (mut h, send, stops) = held(); stop(&mut h); h.run_steps(3); - assert!(control.is_cancelled() && !can_preview(&h) && !cancel_of_the_preview(&h)); + 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); @@ -687,6 +724,25 @@ mod tests { } } + #[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 the_next_wizard_opens_without_a_preview() { let mut h = reviewing(|_| {}); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index ede2685706..c1eee72d98 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -54,8 +54,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu 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. It - doesn't wait for tiles, cast shadows or legend pictures still on their way, and says so. The + 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 From 6392d56425da053401c325df92471b831fc7e0a0 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 16:19:02 -0500 Subject: [PATCH 08/10] fix(layout): the preview says what the page drawing leaves out, and a cancelled drawing's bug --- crates/engine/src/cmd/layout/export.rs | 24 +++++++++++++++---- crates/engine/src/cmd/layout/preview.rs | 23 +++++++++--------- crates/engine/src/tests/layout_preview.rs | 16 +++++++++++++ .../ui-egui/src/publicationwizard/review.rs | 14 +++++++++++ 4 files changed, 61 insertions(+), 16 deletions(-) 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 index 7d98dd051a..c00e5cc4cb 100644 --- a/crates/engine/src/cmd/layout/preview.rs +++ b/crates/engine/src/cmd/layout/preview.rs @@ -1,6 +1,6 @@ //! The sheet `layout.publication` would make, drawn without touching the project (#3475). -use rustgis_render::layout::{PageInfo, PagePending}; +use rustgis_render::layout::PagePending; use serde_json::Value; use crate::Session; @@ -14,7 +14,8 @@ 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 the drawing left out. + /// What `layout.publication` warns of and says, and what an export of the page would say it + /// leaves out. pub warnings: Vec, } @@ -83,18 +84,18 @@ fn draw(copy: impl FnOnce() -> (ReadRows, Session), params: &Value) -> Result = 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())); - warnings.extend(said.notices); Ok(PublicationPreview { pixmap, pending, warnings }) } diff --git a/crates/engine/src/tests/layout_preview.rs b/crates/engine/src/tests/layout_preview.rs index ec35b66677..8c2a4d5595 100644 --- a/crates/engine/src/tests/layout_preview.rs +++ b/crates/engine/src/tests/layout_preview.rs @@ -99,6 +99,22 @@ fn the_copy_previewed_on_keeps_the_sessions_settings() { 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] diff --git a/crates/ui-egui/src/publicationwizard/review.rs b/crates/ui-egui/src/publicationwizard/review.rs index 435b2c2ac5..0396d6b8bf 100644 --- a/crates/ui-egui/src/publicationwizard/review.rs +++ b/crates/ui-egui/src/publicationwizard/review.rs @@ -213,6 +213,8 @@ fn preview_part(ui: &mut egui::Ui, s: &Session, d: &mut Draft, off_frame: bool) }; 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))); @@ -743,6 +745,18 @@ mod tests { 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 the_next_wizard_opens_without_a_preview() { let mut h = reviewing(|_| {}); From 1adf0c4fabed49e61e6dcbac64b957492bdb685c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 16:46:02 -0500 Subject: [PATCH 09/10] fix(layout): a preview refused a thread says so in the interface's language --- crates/ui-egui/src/lib.rs | 8 ++++++-- crates/ui-egui/src/publicationwizard/review.rs | 14 +++++++++++++- 2 files changed, 19 insertions(+), 3 deletions(-) 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/review.rs b/crates/ui-egui/src/publicationwizard/review.rs index 0396d6b8bf..ba72ebee38 100644 --- a/crates/ui-egui/src/publicationwizard/review.rs +++ b/crates/ui-egui/src/publicationwizard/review.rs @@ -191,10 +191,15 @@ fn draw(ctx: &egui::Context, s: &Session, d: &Draft, off_frame: bool) -> Shown { }); match spawned { Ok(_) => Shown::Drawing(Drawing { made, control, frames }), - Err(e) => Shown::Drawn(Err(e.to_string())), + 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))) +} + /// 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. @@ -757,6 +762,13 @@ mod tests { 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 the_next_wizard_opens_without_a_preview() { let mut h = reviewing(|_| {}); From 4c3667fd0b1c58ec729b87c53fe6a2b483e7c22c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Mon, 30 Nov 2026 17:11:46 -0500 Subject: [PATCH 10/10] fix(layout): a choice changed on another step stops the preview's drawing there --- crates/ui-egui/src/publicationwizard/mod.rs | 3 ++- .../ui-egui/src/publicationwizard/review.rs | 22 ++++++++++++++++--- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/crates/ui-egui/src/publicationwizard/mod.rs b/crates/ui-egui/src/publicationwizard/mod.rs index 1f6f1650cf..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::{Preview, 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, @@ -565,6 +565,7 @@ 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. diff --git a/crates/ui-egui/src/publicationwizard/review.rs b/crates/ui-egui/src/publicationwizard/review.rs index ba72ebee38..331ed5659b 100644 --- a/crates/ui-egui/src/publicationwizard/review.rs +++ b/crates/ui-egui/src/publicationwizard/review.rs @@ -200,14 +200,19 @@ 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 d.preview.as_ref().is_some_and(|p| p.key != Key::now(s, d)) { - d.preview = d.preview.take().and_then(Preview::stopped); - } if let Some(preview) = &mut d.preview && let Shown::Drawing(drawing) | Shown::Stopping(drawing) = &preview.shown { @@ -769,6 +774,17 @@ mod tests { 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(|_| {});