Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down
24 changes: 19 additions & 5 deletions crates/engine/src/cmd/layout/export.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<Vec<u8>, 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<tiny_skia::Pixmap, String>,
) -> Result<tiny_skia::Pixmap, String> {
let layout = s.project.layouts.get(li).ok_or("no layout")?.clone();
if let Some(note) = named_fonts_unread(&layout) {
s.warn(note);
Expand Down Expand Up @@ -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?;
Expand Down Expand Up @@ -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`]
Expand Down
105 changes: 105 additions & 0 deletions crates/engine/src/cmd/layout/preview.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,105 @@
//! The sheet `layout.publication` would make, drawn without touching the project (#3475).

use rustgis_render::layout::PagePending;
use serde_json::Value;

use crate::Session;
use crate::undo_memory::ReadRows;

/// The resolution a preview is drawn at.
pub const PREVIEW_DPI: f64 = 36.0;

/// A publication sheet as it would be made.
pub struct PublicationPreview {
pub pixmap: tiny_skia::Pixmap,
/// What was still on its way when it was drawn.
pub pending: PagePending,
/// What `layout.publication` warns of and says, and what an export of the page would say it
/// leaves out.
pub warnings: Vec<String>,
}

/// Makes a copy of `s` to run `layout.publication` on, there or on another thread: what the
/// command reads of the session, with the logins already open (it opens none). Its streamed
/// layers are read anew ([`rustgis_map::Map::detach_reads`]).
fn copy_of(s: &Session) -> impl FnOnce() -> (ReadRows, Session) + Send + 'static {
let mut project = s.project.clone();
for m in &mut project.maps {
m.detach_reads();
}
let (extensions, connections, web_logins) = (s.extensions().clone(), s.connections.clone(), s.web_logins.borrowing_open());
let selections: Vec<(String, String)> =
s.database_logins.web_selections().into_iter().map(|(origin, id)| (origin.to_string(), id.to_string())).collect();
let requests = s.diagnostics.capture();
let (view_size, active_layer, opened) = (s.view_size, s.active_layer, s.opened);
let (in_place_wait, raster_defaults, grids, auto_cache) =
(s.in_place_wait, s.raster_defaults.clone(), s.offers_grid_downloads, s.auto_cache);
let (favourite, arrangements) = (s.layout_favourite.clone(), s.layout_arrangements.clone());
let readers = s.undo_memory.readers();
// Rows the copy shares stay counted while it holds them, should this session let them go.
let retained = readers.retain(crate::undo_memory::allocations(&project));
move || {
let mut copy = Session::new(project);
copy.set_extensions(extensions);
copy.connections = connections;
copy.web_logins = web_logins;
for (origin, id) in &selections {
copy.database_logins.select(crate::connections::WEB, origin, id);
}
copy.requests_into = Some(requests);
(copy.view_size, copy.active_layer, copy.opened) = (view_size, active_layer, opened);
(copy.in_place_wait, copy.raster_defaults, copy.offers_grid_downloads, copy.auto_cache) =
(in_place_wait, raster_defaults, grids, auto_cache);
(copy.layout_favourite, copy.layout_arrangements) = (favourite, arrangements);
// The copy shares this session's rows, which this session already counts (#2431).
copy.undo_memory.memory = None;
copy.undo_memory.use_readers(readers);
copy.sync_policy_generation();
(retained, copy)
}
}

/// [`copy_of`], made here.
#[cfg(test)]
pub(crate) fn preview_copy(s: &Session) -> Session {
copy_of(s)().1
}

/// What draws the sheet `layout.publication` with `params` would make, at [`PREVIEW_DPI`] without
/// waiting for what is still on its way, here or on a thread of its own; `s` doesn't change. Its
/// refusal is the error, and so is a bug caught in the drawing, with its incident (natively: the
/// browser stops at a panic). The command reads streamed layers as it does when run on `s`, and
/// what the whole drawing asks of servers goes in `s`'s Diagnostics.
pub fn publication_preview_work(s: &Session, params: Value) -> impl FnOnce() -> Result<PublicationPreview, String> + Send + 'static {
let (copy, requests) = (copy_of(s), s.diagnostics.capture());
move || {
let _requests = requests.enter();
std::panic::catch_unwind(std::panic::AssertUnwindSafe(move || draw(copy, &params)))
.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<PublicationPreview, String> {
// Bound first, so it is dropped after the copy.
let (_retained, mut copy) = copy();
let made = copy.run("layout.publication", params)?;
let li = copy.project.layouts.len().checked_sub(1).ok_or("no layout")?;
// The page as an export draws it, but without waiting, and what it leaves out said alike.
let mut pending = PagePending::default();
let pixmap = super::export::layout_page(&mut copy, li, PREVIEW_DPI, None, |layout, maps, info| {
let (pixmap, short) = rustgis_render::layout::render_preview(layout, maps, PREVIEW_DPI, info)?;
pending = short;
Ok(pixmap)
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
})?;
// What Create answers, then what it and the drawing say as notices.
let mut warnings: Vec<String> =
made["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str().map(String::from)).collect();
warnings.extend(copy.notices.iter().map(|n| n.text.clone()));
Ok(PublicationPreview { pixmap, pending, warnings })
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
}

/// [`publication_preview_work`], done here.
pub fn publication_preview(s: &Session, params: &Value) -> Result<PublicationPreview, String> {
publication_preview_work(s, params.clone())()
}
12 changes: 2 additions & 10 deletions crates/engine/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<rustgis_data::diagnostics::Capture>,
/// 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.
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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() {
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
return;
}
Expand Down Expand Up @@ -4489,8 +4482,7 @@ impl Session {
}

/// Takes another session's extension choices (a copy that runs a model or script ahead, on
/// the desktop only).
#[cfg(not(target_arch = "wasm32"))]
/// the desktop, or draws a publication preview).
pub(crate) fn set_extensions(&mut self, state: extensions::State) {
self.extensions = state;
}
Expand Down
8 changes: 7 additions & 1 deletion crates/engine/src/service_logins.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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<String>, refused: BTreeMap<String, String>) -> 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();
Expand All @@ -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)
Expand Down
3 changes: 3 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down
156 changes: 156 additions & 0 deletions crates/engine/src/tests/layout_preview.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,156 @@
//! `publication_preview` (#3475): the sheet `layout.publication` would make, the project left
//! as it was.

use super::*;
use crate::cmd::layout::{PREVIEW_DPI, PublicationPreview, layout_png, preview_copy, publication_preview};

fn preview(s: &Session, params: Value) -> PublicationPreview {
publication_preview(s, &params).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", &params).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, &params).err().expect("refused");
assert_eq!(said, s.run("layout.publication", &params).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", &params).unwrap();
assert!(!said.is_empty());
assert_eq!(json!(said), r["warnings"]);
}

#[test]
fn the_copy_previewed_on_keeps_the_sessions_settings() {
let mut s = world();
s.in_place_wait = false;
s.view_size = (400.0, 900.0);
s.opened = 7;
s.active_layer = s.map().layers.first().map(|l| l.id);
s.layout_favourite = json!("mirrored");
s.layout_arrangements.insert("mine".into(), json!({"legend": "top-left"}));
let copy = preview_copy(&s);
assert!(!copy.in_place_wait);
assert_eq!((copy.view_size, copy.opened, copy.active_layer), (s.view_size, s.opened, s.active_layer));
assert_eq!(copy.layout_favourite, s.layout_favourite);
assert_eq!(copy.layout_arrangements, s.layout_arrangements);
assert_eq!(copy.project.maps.len(), s.project.maps.len());
}

/// What the page drawing leaves out, as an export of the sheet says it, is said under the preview.
#[test]
fn a_preview_says_what_the_drawing_leaves_out() {
let mut s = world();
let params = json!({"profile": "a4-portrait", "legend": {"title": "W".repeat(150)}});
let warned = preview(&s, params.clone()).warnings;
s.run("layout.publication", &params).unwrap();
let seen = s.notices_since(0).len();
layout_png(&mut s, 0, PREVIEW_DPI, None).unwrap();
let said = s.notices_since(0)[seen..].to_vec();
assert!(!said.is_empty(), "the export says the legend's title is cut");
for n in said {
assert!(warned.contains(&n.text), "{}: {warned:?}", n.text);
}
}

/// A tile that never comes doesn't hold the preview, which says its frames are short of it.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_preview_does_not_wait_for_tiles() {
use rustgis_map::tiles::{TileKind, TileLayer};
if isolate_process_test("tests::layout_preview::a_preview_does_not_wait_for_tiles") {
return;
}
isolate_plugins();
static HELD: std::sync::Mutex<Vec<Box<dyn std::any::Any + Send>>> = std::sync::Mutex::new(Vec::new());
crate::render::rustgis_tiles::cache::set_fetcher(|url, done| {
// As a request's failure is noted: under whoever the drawing's thread draws for.
rustgis_data::diagnostics::Capture::current().note_absence("GET", &url, 404);
HELD.lock().unwrap().push(Box::new(done));
});
let mut s = world();
s.map_mut().tiles.push(TileLayer::new("Held", TileKind::Raster, "https://tiles.test/held/{z}/{x}/{y}.png"));
let start = std::time::Instant::now();
let p = preview(&s, json!({"profile": "a4-portrait"}));
assert!(start.elapsed() < std::time::Duration::from_secs(20), "waited {:?}", start.elapsed());
assert!(p.pending.frames);
assert!(!s.diagnostics.records().is_empty(), "the drawing's requests are the session's to show");
}

/// What Create says as notices (the locator map's name cut short) is a warning of the preview too.
#[test]
fn a_preview_warns_of_what_create_says_as_notices() {
let mut s = world();
s.run("map.rename", &json!({"name": "m".repeat(crate::cmd::MAX_NAME)})).unwrap();
let params = json!({"profile": "a4-portrait"});
let warned = preview(&s, params.clone()).warnings;
let seen = s.notices_since(0).len();
s.run("layout.publication", &params).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);
}
}
Loading
Loading