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
57 changes: 48 additions & 9 deletions crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ pub fn commands() -> Vec<C> {
.params(r#"{"layout"?}"#),
C::new("layout.export", "Export Layout", "Publish › Output", |s, p| super::exports::write_here(s, p, "layout.export")).inputs(layout_inputs).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files))
.view()
.params(r#"{"layout"?, "path": "*.png|*.pdf|*.svg" (PNG/SVG: current page; SVG: each element a group of its own; text and shapes as SVG, map frames and surrounds as vectors, rasters and tiles in them as pictures at dpi), "dpi"?: 72..600, "allPages"?: bool (PDF only; default true: every map series page, up to 500; false: the current page), "georeference"?: bool (PDF only; default true: map frames carry their coordinates, a GeoPDF; false: none)}"#),
.params(r#"{"layout"?, "path": "*.png|*.pdf|*.svg" (PNG/SVG: current page; SVG: each element a group of its own; text and shapes as SVG, map frames and surrounds as vectors, rasters and tiles in them as pictures at dpi), "dpi"?: 72..600, "allPages"?: bool (PDF only; default true: every map series page, up to 500; false: the current page), "georeference"?: bool (PDF only; default true: map frames carry their coordinates, a GeoPDF; false: none), "pdf"?: {"layers"?: bool (default true: each element, and in a map frame each layer and its labels, a PDF layer that vector editors open as a layer; false: none)}}"#),
C::new("layout.save", "Save Layout File", "Publish › Save As", |s, p| {
let path = ps(p, "path").ok_or("path is required")?;
let l = active(s, p)?.clone();
Expand Down Expand Up @@ -4188,15 +4188,24 @@ fn named_fonts_unread(layout: &Layout) -> Option<&'static str> {
/// Layout `li` as a PDF (kept as vectors; every map series page when `all`; its map frames
/// georeferenced) or a PNG of the current page, at `dpi`.
pub fn layout_bytes(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: bool) -> Result<Vec<u8>, String> {
layout_bytes_with(s, li, pdf, dpi, all, true)
layout_bytes_with(s, li, pdf, dpi, all, true, rustgis_render::pdf::Options::default())
}

/// [`layout_bytes`], a PDF's map frames georeferenced only when `georeference` (#1191).
/// Returns an actionable error if a linked archive changes while the pages are drawn.
pub fn layout_bytes_with(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: bool, georeference: bool) -> Result<Vec<u8>, String> {
/// [`layout_bytes`], a PDF's map frames georeferenced only when `georeference` (#1191), written
/// as `options` say (its layers, #1815). Returns an actionable error if a linked archive changes
/// while the pages are drawn.
pub fn layout_bytes_with(
s: &mut Session,
li: usize,
pdf: bool,
dpi: f64,
all: bool,
georeference: bool,
options: rustgis_render::pdf::Options,
) -> Result<Vec<u8>, String> {
let layout = s.project.layouts.get(li).ok_or("no layout")?;
let revisions = rustgis_render::layout::archive_revisions(layout, &s.project.maps);
let result = layout_bytes_inner(s, li, pdf, dpi, all, georeference);
let result = layout_bytes_inner(s, li, pdf, dpi, all, georeference, options);
let layout = s.project.layouts.get(li).ok_or("no layout")?;
revisions.finish_revision(
rustgis_render::layout::archive_revisions(layout, &s.project.maps),
Expand All @@ -4205,7 +4214,15 @@ pub fn layout_bytes_with(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: b
)?
}

fn layout_bytes_inner(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: bool, georeference: bool) -> Result<Vec<u8>, String> {
fn layout_bytes_inner(
s: &mut Session,
li: usize,
pdf: bool,
dpi: f64,
all: bool,
georeference: bool,
options: rustgis_render::pdf::Options,
) -> Result<Vec<u8>, String> {
let saved = s.project.layouts.get(li).ok_or("no layout")?.clone();
if let Some(note) = named_fonts_unread(&saved) {
s.warn(note);
Expand Down Expand Up @@ -4309,7 +4326,7 @@ fn layout_bytes_inner(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: bool
let (pages, png) = result?;
pictured_notices(s, &frames_pictured, &pages_pictured);
georeference_notices(s, &left_out, &by_corners, pages.len());
if pdf { Ok(rustgis_render::pdf::write(&pages, &saved.name)) } else { png.ok_or_else(|| "nothing to draw".to_string()) }
if pdf { Ok(rustgis_render::pdf::write_with(&pages, &saved.name, options)) } else { png.ok_or_else(|| "nothing to draw".to_string()) }
}

/// Says which map frames a PDF doesn't georeference, with why, and which it georeferences by their
Expand Down Expand Up @@ -4425,6 +4442,27 @@ pub(crate) fn pictured_notices(s: &mut Session, frames: &[(u32, String)], pages:
}
}

/// The keys `layout.export`'s `"pdf"` takes.
const PDF_KEYS: &[&str] = &["layers"];

/// How `layout.export`'s `"pdf": {…}` asks a PDF to be written: with its layers unless
/// `"layers": false` (#1815). A key it doesn't know is refused, with the keys it takes.
fn pdf_options(p: &Value) -> Result<rustgis_render::pdf::Options, String> {
let mut options = rustgis_render::pdf::Options::default();
let Some(pdf) = p.get("pdf").filter(|v| !v.is_null()) else { return Ok(options) };
let Some(pdf) = pdf.as_object() else { return Err(r#"pdf is an object: {"layers": true|false}"#.into()) };
// A key it doesn't know (a typo) is refused, not left to change nothing unsaid.
if let Some(key) = pdf.keys().find(|k| !PDF_KEYS.contains(&k.as_str())) {
return Err(format!("pdf has no key \"{key}\": its keys are {}", PDF_KEYS.join(", ")));
}
match pdf.get("layers") {
None | Some(Value::Null) => {}
Some(Value::Bool(on)) => options.layers = *on,
Some(_) => return Err("pdf.layers is true or false".into()),
}
Ok(options)
}

/// `layout.export`: a layout to a PNG, PDF or SVG. It draws a copy of the project, so the project
/// can change meanwhile (a map series steps through its pages on the copy); a cancelled export
/// stops at the next page, or its map's wait for tiles, and writes nothing.
Expand All @@ -4437,6 +4475,7 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result<super::exports::Work
return Err("export to a .png, .pdf or .svg file".into());
}
let (dpi, all, georeference) = (f(p, "dpi").unwrap_or(150.0), b(p, "allPages").unwrap_or(true), b(p, "georeference").unwrap_or(true));
let options = pdf_options(p)?;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit (confidence ~35%): "pdf" is validated for every format, but only applies to PDF.

pdf_options(p)? runs for .png and .svg too, so {"pdf": {"layers": false}} on a PNG export is accepted and does nothing, with no notice. georeference has the same behaviour today, so this follows existing precedent and is not a regression. A small fix would be to refuse the key when the target is not a PDF:

Suggested change
let options = pdf_options(p)?;
let options = pdf_options(p)?;
if !pdf && p.get("pdf").is_some_and(|v| !v.is_null()) {
return Err("pdf applies to a .pdf file only".into());
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Leaving this as is: pdf follows georeference and allPages, which also apply only to a PDF and are accepted, and ignored, for PNG and SVG; its name and its option ("a PDF layer") say what it is for.

let mut project = s.project.clone();
for m in &mut project.maps {
m.detach_reads();
Expand All @@ -4447,7 +4486,7 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result<super::exports::Work
let bytes = if svg {
layout_svg(&mut copy, li, dpi)?.into_bytes()
} else {
layout_bytes_with(&mut copy, li, pdf, dpi, all, georeference)?
layout_bytes_with(&mut copy, li, pdf, dpi, all, georeference, options)?
};
rustgis_data::progress::check().map_err(|e| e.to_string())?;
rustgis_data::io::write_atomic(Path::new(&path), &bytes).map_err(|e| format!("{path}: {e}"))?;
Expand Down
72 changes: 70 additions & 2 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -37089,6 +37089,73 @@ fn a_pdf_says_which_frames_and_pages_it_draws_as_pictures() {
);
}

/// A layout's PDF has layers (#1815): each element an optional content group named after it,
/// its map frame's map layers and their labels inside the frame's; the GeoPDF viewports stay.
/// `"pdf": {"layers": false}` leaves them out, a bad value is refused, and a layout with no map
/// has its elements' layers alone.
#[test]
fn a_layout_pdf_has_its_elements_and_map_layers_as_layers() {
let mut s = world();
s.run("labels.field", &json!({"layer": "Countries", "field": "name"})).unwrap();
s.run("layout.new", &json!({"page": "a4", "orientation": "landscape", "template": "map"})).unwrap();
s.run("layout.addElement", &json!({"kind": "text", "text": "Uso (rascunho)"})).unwrap();
let path = std::env::temp_dir().join(format!("rustgis-layers-{}.pdf", std::process::id()));
let export = |s: &mut Session, extra: Value| {
let mut p = json!({"path": path, "dpi": 72});
if let (Some(p), Some(extra)) = (p.as_object_mut(), extra.as_object()) {
p.extend(extra.clone());
}
s.run("layout.export", &p).map(|_| String::from_utf8_lossy(&std::fs::read(&path).unwrap()).into_owned())
};
let pdf = export(&mut s, json!({})).unwrap();
let name = |n: &str| format!("<< /Type /OCG /Name {} >>", literal_pdf(n));
let id = |pdf: &str, n: &str| {
let at = pdf.find(&name(n)).unwrap_or_else(|| panic!("no layer {n}"));
pdf[..at].rsplit("endobj\n").next().and_then(|o| o.split(' ').next()).map(str::to_string).unwrap()
};
let layout = s.project.layouts[0].clone();
for e in layout.elements.iter().filter(|e| e.visible) {
let n = if e.name.trim().is_empty() { e.kind.code().to_string() } else { e.name.clone() };
assert!(pdf.contains(&name(&n)), "element {n}");
}
let frame = layout.elements.iter().find(|e| e.kind.code() == "mapFrame").unwrap();
let (f, countries, labels) = (id(&pdf, &frame.name), id(&pdf, "Countries"), id(&pdf, "Labels: Countries"));
let order = pdf.split("/Order [").nth(1).unwrap();
let inner = order.split(&format!("{f} 0 R [")).nth(1).unwrap_or_else(|| panic!("the frame's layers nest in it: {order}"));
let inner = inner.split(']').next().unwrap();
assert!(inner.contains(&format!("{countries} 0 R")) && inner.contains(&format!("{labels} 0 R")), "{inner}");
assert!(pdf.contains("/VP [<< /Type /Viewport"), "still a GeoPDF");
// Without layers, and refused values.
let plain = export(&mut s, json!({"pdf": {"layers": false}})).unwrap();
assert!(!plain.contains("/OCProperties") && !plain.contains("/Type /OCG") && plain.contains("/VP [<< /Type /Viewport"));
for bad in [json!({"pdf": {"layers": "no"}}), json!({"pdf": false}), json!({"pdf": {"layer": false}})] {
let err = export(&mut s, bad.clone()).unwrap_err();
assert!(err.contains("pdf"), "{bad}: {err}");
}
// A layout with no map: its elements' layers, one each.
let mut s = Session::new(Project::default());
s.run("layout.new", &json!({"page": "a4"})).unwrap();
s.project.layouts[0].elements.retain(|e| e.kind.code() != "mapFrame");
s.run("layout.addElement", &json!({"kind": "text", "text": "Só texto"})).unwrap();
let added = s.project.layouts[0].elements.last().map(|e| e.name.clone()).unwrap();
let pdf = export(&mut s, json!({})).unwrap();
let drawn = s.project.layouts[0].elements.iter().filter(|e| e.visible).count();
assert!(pdf.contains(&name(&added)) && pdf.contains("/OCProperties") && !pdf.contains("/VP ["), "{added}");
assert!(pdf.matches("/Type /OCG").count() <= drawn && !pdf.contains("Labels:"), "{drawn}");
let _ = std::fs::remove_file(&path);
}

/// `s` as a PDF text string, as the PDF writer writes names: ASCII in parentheses, its
/// parentheses and backslashes escaped, anything else UTF-16BE hex.
fn literal_pdf(s: &str) -> String {
if s.is_ascii() {
let escaped: String = s.chars().flat_map(|c| if matches!(c, '(' | ')' | '\\') { vec!['\\', c] } else { vec![c] }).collect();
format!("({escaped})")
} else {
format!("<FEFF{}>", s.encode_utf16().map(|u| format!("{u:04X}")).collect::<String>())
}
}

/// A layout's PDF georeferences its map frames (#1191): each as an ISO 32000 viewport with its
/// corners and its map's coordinate system, so that the frame's corners, taken back to the map,
/// make the frame's rectangle. A tilted frame is left out, and said.
Expand Down Expand Up @@ -37126,7 +37193,8 @@ fn a_layout_pdf_georeferences_its_map_frames() {
// Tilted, it shows no flat map to measure on: left out, and said.
s.run("layout.update", &json!({"element": frame.id, "pitch": 30})).unwrap();
let (pdf, said) = export(&mut s);
assert!(pdf.starts_with("%PDF-1.4") && !pdf.contains("/VP ["));
// (PDF 1.5 for its layers, #1815.)
assert!(pdf.starts_with("%PDF-1.5") && !pdf.contains("/VP ["));
assert!(said.iter().any(|t| t == &format!("The PDF doesn't georeference 1 map frame ({}: it is tilted)", frame.name)), "{said:?}");
// A world projection RustGIS computes itself (Winkel Tripel) is written as WKT too.
s.run("layout.update", &json!({"element": frame.id, "pitch": 0})).unwrap();
Expand Down Expand Up @@ -37155,7 +37223,7 @@ fn a_layout_pdf_georeferences_its_map_frames() {
let mark = s.notice_mark();
s.run("layout.export", &json!({"path": path, "dpi": 72, "georeference": false})).unwrap();
let plain = String::from_utf8_lossy(&std::fs::read(&path).unwrap()).into_owned();
assert!(plain.starts_with("%PDF-1.4") && !plain.contains("/VP ["));
assert!(plain.starts_with("%PDF-1.5") && !plain.contains("/VP ["), "1.5 for its layers (#1815)");
assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("georeference")));
// On SAD69 (shifted from WGS 84) the corners are on SAD69, tens of metres from WGS 84's, and
// moved as PROJ moves them: EPSG:4326 to EPSG:4618 takes this corner (-46.888358 E,
Expand Down
30 changes: 29 additions & 1 deletion crates/render/src/canvas.rs
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ struct Recording {
dirty: bool,
/// Applied to what is kept ([`Canvas::with_transform`]).
ts: Transform,
/// A layer is open ([`Canvas::layer`]).
layer: bool,
}

impl Canvas {
Expand All @@ -46,7 +48,7 @@ impl Canvas {
pub fn recording(width: u32, height: u32) -> Option<Canvas> {
let pm = Pixmap::new(width, height)?;
let drawing = Drawing::new(width as f32, height as f32);
Some(Canvas { pm, rec: Some(Box::new(Recording { drawing, dirty: false, ts: Transform::identity() })) })
Some(Canvas { pm, rec: Some(Box::new(Recording { drawing, dirty: false, ts: Transform::identity(), layer: false })) })
}

/// Whether it records.
Expand Down Expand Up @@ -234,6 +236,32 @@ impl Canvas {
self.keep(|r| r.drawing.end_group());
}

/// Ends the layer set before, if any, and keeps what is drawn from now on in a layer named
/// `name` (none for `None`): a layout element, a map layer, its labels (#1815). Only a
/// recording keeps layers; they change nothing drawn. Layers set this way don't nest: each
/// ends the one before, so a caller can set one at the top of a loop that may `continue`.
pub fn layer(&mut self, name: Option<&str>) {
self.set_layer(name.map(|n| (n, None)));
}

/// [`Canvas::layer`] for a layer identified by `id` as well as named (see
/// [`vector::Group::layer_id`]): a map layer's, or its labels', whose runs make one layer.
pub fn layer_with_id(&mut self, name: &str, id: u64) {
self.set_layer(Some((name, Some(id))));
}

fn set_layer(&mut self, layer: Option<(&str, Option<u64>)>) {
self.keep(|r| {
if std::mem::take(&mut r.layer) {
r.drawing.end_group();
}
if let Some((name, id)) = layer {
r.drawing.begin_layer(name, id);
r.layer = true;
}
});
}

/// Places `child` on this one as a group: moved by `transform`, composited with `opacity` and
/// `blend`, inside `clip` (in this canvas's space). `child` comes from [`Canvas::sub`] (or
/// draws pixels), so it records only when this canvas does: its recording is placed on this
Expand Down
Loading
Loading