From de12b2ded3a684136a877ebd59afbbdecfb3d2f1 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 03:22:45 -0300 Subject: [PATCH 1/4] feat(render): layers in vector PDFs (#1815, layers) A layout's vector PDF now has optional content groups that vector editors import as layers: one per layout element, named after it, and inside a map frame's, one per map layer drawn, one per layer's labels ("Labels: ") and one for the grid. A layer is the same group on every page of a map series; two elements named alike are two groups. The catalog lists them in /OCProperties with a nested /Order. A frame's layers are marked outside its clip, each clipped on its own, so editors don't flatten them into a clipping group. Nothing drawn changes. `"pdf": {"layers": false}` on layout.export leaves them out. Part of #1815. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 50 +++++-- crates/engine/src/tests.rs | 72 +++++++++- crates/render/src/canvas.rs | 20 ++- crates/render/src/layout.rs | 26 +++- crates/render/src/lib.rs | 53 +++++++- crates/render/src/pdf.rs | 220 ++++++++++++++++++++++++++++++- crates/render/src/pdf/content.rs | 150 +++++++++++++++------ crates/render/src/vector.rs | 36 ++++- crates/ui-egui/src/lib.rs | 10 +- docs/user-guide/layouts.md | 6 + 10 files changed, 575 insertions(+), 68 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 2ca805d4fc..599f27708a 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -129,7 +129,7 @@ pub fn commands() -> Vec { .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(); @@ -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, 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, 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, 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), @@ -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, String> { +fn layout_bytes_inner( + s: &mut Session, + li: usize, + pdf: bool, + dpi: f64, + all: bool, + georeference: bool, + options: rustgis_render::pdf::Options, +) -> Result, String> { let saved = s.project.layouts.get(li).ok_or("no layout")?.clone(); if let Some(note) = named_fonts_unread(&saved) { s.warn(note); @@ -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 @@ -4425,6 +4442,20 @@ pub(crate) fn pictured_notices(s: &mut Session, frames: &[(u32, String)], pages: } } +/// How `layout.export`'s `"pdf": {…}` asks a PDF to be written: with its layers unless +/// `"layers": false` (#1815). +fn pdf_options(p: &Value) -> Result { + 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()) }; + 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. @@ -4437,6 +4468,7 @@ pub(crate) fn export_work(s: &Session, p: &Value) -> Result Result>", 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})] { + 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!("", s.encode_utf16().map(|u| format!("{u:04X}")).collect::()) + } +} + /// 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. @@ -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(); @@ -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, diff --git a/crates/render/src/canvas.rs b/crates/render/src/canvas.rs index 9e2a75be57..a95d599f95 100644 --- a/crates/render/src/canvas.rs +++ b/crates/render/src/canvas.rs @@ -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 { @@ -46,7 +48,7 @@ impl Canvas { pub fn recording(width: u32, height: u32) -> Option { 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. @@ -234,6 +236,22 @@ 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.keep(|r| { + if std::mem::take(&mut r.layer) { + r.drawing.end_group(); + } + if let Some(name) = name { + r.drawing.begin_layer(name); + 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 diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 77715d225c..ed61cf35cb 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -228,6 +228,8 @@ fn draw_page( } } for e in layout.elements.iter().filter(visible) { + // Each element is a layer of the recording, named after it (#1815). + pm.layer(Some(if e.name.trim().is_empty() { e.kind.code() } else { &e.name })); let (x, y, ew, eh) = ((e.x * k - f64::from(bounds.x())) as f32, (e.y * k - f64::from(bounds.y())) as f32, (e.w * k) as f32, (e.h * k) as f32); let Some(r) = Rect::from_xywh(x, y, ew.max(1.0), eh.max(1.0)) else { continue }; @@ -476,6 +478,7 @@ fn draw_page( } } } + pm.layer(None); Some(pm) } @@ -526,14 +529,16 @@ pub fn frame_map_preview(map: &mut Map, camera: rustgis_map::Camera, w: f64, h: /// comma or not) and its attribution drawn on it: on its recording when it was recorded, else on /// its pixels. The attribution keeps clear of the grid's labels. fn finish_frame(img: crate::Rendered, ppp: f64, grid: Option<(&Map, &View, &Grid, bool)>) -> Canvas { - let mut pm = img.recorded.unwrap_or_else(|| Canvas::from_pixmap(img.pixmap)); - for l in img.unplaced.iter().chain(&img.labels) { - text::draw(&mut pm, l, ppp as f32); - } - let labels = grid.map(|(map, view, g, comma)| draw_grid(&mut pm, map, view, g, comma)).unwrap_or_default(); + let crate::Rendered { pixmap, recorded, labels, unplaced, label_layers, attribution, .. } = img; + let mut pm = recorded.unwrap_or_else(|| Canvas::from_pixmap(pixmap)); + crate::draw_labels(&mut pm, (&unplaced, &labels, &label_layers), ppp as f32); + // The grid is a layer of its own (#1815). + pm.layer(grid.is_some().then_some("Grid")); + let grid_labels = grid.map(|(map, view, g, comma)| draw_grid(&mut pm, map, view, g, comma)).unwrap_or_default(); + pm.layer(None); let (w, h) = (pm.width() as f32 / ppp as f32, pm.height() as f32 / ppp as f32); - let inset = crate::attribution_text(&img.attribution).map_or((0.0, 0.0), |(_, tw)| attribution_inset((w, h), tw, &labels)); - crate::draw_attribution(&mut pm, &img.attribution, ppp as f32, inset); + let inset = crate::attribution_text(&attribution).map_or((0.0, 0.0), |(_, tw)| attribution_inset((w, h), tw, &grid_labels)); + crate::draw_attribution(&mut pm, &attribution, ppp as f32, inset); pm } @@ -2754,6 +2759,7 @@ mod tests { let (drawing, pictured) = render_drawing(&layout, &mut maps, 150.0, &PageInfo::default()).unwrap(); assert!(pictured.is_empty() && !drawing.overflowed()); let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); let text: String = items .iter() .filter_map(|i| if let Item::Glyphs(r) = i { Some(r) } else { None }) @@ -2805,6 +2811,7 @@ mod tests { } let (drawing, _) = render_drawing(&layout, &mut maps, 96.0, &PageInfo::default()).unwrap(); let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); let frame = items.iter().find_map(|i| if let Item::Group(g) = i { Some(g) } else { None }).expect("the frame's group"); // The turned view holds the north-up frame, turned. let Some(Item::Group(north)) = frame.items.first() else { panic!("the north-up frame inside") }; @@ -2822,6 +2829,7 @@ mod tests { let (drawing, pictured) = result.unwrap(); assert_eq!(pictured.iter().map(|p| p.1.as_str()).collect::>(), ["World"]); let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); assert!(items.iter().any(|i| matches!(i, Item::Image(_))), "the frame as a picture"); } @@ -3844,6 +3852,7 @@ mod tests { assert!(b - t > 4 * (r - l) && l > px(44.0) && r < px(56.0), "the text runs down the page: {l},{t} to {r},{b}"); let (drawing, _) = render_drawing(&layout, &mut [], 96.0, &info).unwrap(); let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); let pieces: usize = items .iter() .filter_map(|i| if let Item::Stroke { path, .. } = i { Some(path) } else { None }) @@ -3871,6 +3880,7 @@ mod tests { let png = render(&layout, &mut [], 96.0, &info).unwrap(); let (drawing, _) = render_drawing(&layout, &mut [], 96.0, &info).unwrap(); let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); let pieces: usize = items .iter() .filter_map(|i| if let Item::Stroke { path, .. } = i { Some(path) } else { None }) @@ -4004,6 +4014,7 @@ Elaboração: RustGIS", let png = render(&layout, &mut [], 96.0, &info).unwrap(); let (drawing, _) = render_drawing(&layout, &mut [], 96.0, &info).unwrap(); let (_, _, items) = drawing.finish(); + let items = crate::vector::without_layers(items); let text: String = items .iter() .filter_map(|i| if let Item::Glyphs(r) = i { Some(r) } else { None }) @@ -4560,6 +4571,7 @@ Elaboração: RustGIS", partial: Vec::new(), pending_in_place: Vec::new(), recorded: None, + label_layers: Vec::new(), }; let framed = finish_frame(img, ppp, Some((&map, &view, &all, false))); let (a, b) = (labels_pm.pixmap(), framed.pixmap()); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 3935b3ca2c..f24ed4a2e7 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -537,6 +537,9 @@ pub struct Rendered { pub pending_in_place: Vec, /// The frame kept as vectors, when it was recorded ([`render_complete_recorded`]). pub(crate) recorded: Option, + /// When recorded, each of `labels`' map layer, by id and name (`u32::MAX` and no name for + /// a label of no layer's), for [`draw_labels`]; else empty. + pub(crate) label_layers: Vec<(u32, String)>, } /// Which rasteriser [`render_backend`] targets: the tiny-skia CPU pixmap (the default, and the @@ -2571,6 +2574,7 @@ fn render_tilted(map: &mut Map, view: &View, full_res_rasters: bool, sources_rea partial, pending_in_place, recorded: None, + label_layers: Vec::new(), }) } @@ -3985,6 +3989,8 @@ fn render_frame( // The layer drawn last, whose tile layers go over it before the next. let mut below: Option = None; for li in order { + // Each layer drawn is a layer of the recording (#1815); what comes between them isn't. + pm.layer(None); // A frame no longer wanted stops between layers (see `cancel`). if cancel::requested() { break; @@ -3997,6 +4003,7 @@ fn render_frame( if !layer.visible || !layer.in_scale_range(scale) || held.contains(&layer.id) { continue; } + pm.layer(Some(&layer.name)); let opacity = layer.opacity() * group_opacity.get(&layer.id).copied().unwrap_or(1.0); let mask = masks.iter().find(|(id, _)| *id == layer.id).map(|(_, m)| m); let (blend, layer_blend) = (blend_mode(layer.blend), layer.blend); @@ -5091,6 +5098,7 @@ fn render_frame( cpu_dirty = true; } } + pm.layer(None); // A frame stopped part-way (see `cancel`) is no frame: its tiles, labels and effects aren't // worth working out. if cancel::requested() { @@ -5158,6 +5166,15 @@ fn render_frame( None => (view.width, view.height), }; let placed = place_labels_with_previews(label_candidates, fixed_labels, lw as f32, lh as f32, lock.is_some(), display.show_unplaced); + // Each placed label's map layer, for a recording to keep each layer's labels together: the + // fixed labels (graphics text) come first, then one for each key. + let label_layers: Vec<(u32, String)> = if pm.is_recording() { + let fixed = placed.labels.len().saturating_sub(placed.keys.len()); + let name = |id: u32| map.layers.iter().find(|l| l.id == id).map(|l| l.name.clone()).unwrap_or_default(); + std::iter::repeat_n((u32::MAX, String::new()), fixed).chain(placed.keys.iter().map(|((id, ..), _)| (*id, name(*id)))).collect() + } else { + Vec::new() + }; // (The lock is never taken from a tilted view: its labels' places out of sight are dropped, // so the numbers of the places they take aren't those of their class's.) if display.locked && map.label_lock.is_none() && !matches!(labels_to, Labels::Tilted(..)) { @@ -5206,6 +5223,7 @@ fn render_frame( partial, pending_in_place, recorded, + label_layers, })) } Backend::Gpu | Backend::GpuLive => { @@ -6501,14 +6519,43 @@ fn render_drawing_inner(map: &mut Map, view: &View) -> Option { c } }; - for l in r.unplaced.iter().chain(&r.labels) { - text::draw(&mut pm, l, view.pixels_per_point as f32); - } + draw_labels(&mut pm, (&r.unplaced, &r.labels, &r.label_layers), view.pixels_per_point as f32); text::scale_bar(&mut pm, view, map.ground_res_at(&view.camera)); draw_attribution(&mut pm, &r.attribution, view.pixels_per_point as f32, (0.0, 0.0)); pm.into_drawing() } +/// Draws a frame's unplaced and placed labels. A recording keeps each map layer's placed labels +/// together as a layer of their own, "Labels: " (#1815), the layers in the order of their +/// first label: placed labels don't overlap, so the page looks the same. +pub(crate) fn draw_labels(pm: &mut Canvas, (unplaced, labels, layers): (&[PlacedLabel], &[PlacedLabel], &[(u32, String)]), ppp: f32) { + for l in unplaced { + text::draw(pm, l, ppp); + } + if !pm.is_recording() || layers.len() != labels.len() { + for l in labels { + text::draw(pm, l, ppp); + } + return; + } + let mut first = std::collections::HashMap::new(); + for (i, (id, _)) in layers.iter().enumerate() { + first.entry(*id).or_insert(i); + } + let mut order: Vec = (0..labels.len()).collect(); + order.sort_by_key(|i| layers.get(*i).and_then(|(id, _)| first.get(id)).copied().unwrap_or(0)); + let mut shown = None; + for i in order { + let (Some(l), Some((id, name))) = (labels.get(i), layers.get(i)) else { continue }; + if shown != Some(*id) { + pm.layer((*id != u32::MAX).then(|| format!("Labels: {name}")).as_deref()); + shown = Some(*id); + } + text::draw(pm, l, ppp); + } + pm.layer(None); +} + /// Renders a map with its labels, a scale bar and a north arrow to PNG bytes. /// Refuses an archive changed during rendering or encoding; a caller must not write a destination on error. pub fn render_png(map: &mut Map, view: &View) -> Result, String> { diff --git a/crates/render/src/pdf.rs b/crates/render/src/pdf.rs index c96d80c172..a388930aad 100644 --- a/crates/render/src/pdf.rs +++ b/crates/render/src/pdf.rs @@ -2,7 +2,8 @@ //! [`Drawing`] kept as vectors: its paths, text and pictures become the page's content, its text //! set in fonts whose glyphs are their outlines (Type 3), searchable and copyable through each //! font's map back to Unicode. A page's map frames can be georeferenced ([`Viewport`]), which -//! makes the document a GeoPDF. +//! makes the document a GeoPDF. A drawing's layers (layout elements, map layers, their labels) +//! become optional content groups, which vector editors open as layers ([`Options::layers`]). use tiny_skia::Pixmap; @@ -224,15 +225,107 @@ impl Doc { } } -/// Writes the pages as a PDF document. +/// How a document is written. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Options { + /// The drawings' layers as optional content groups (#1815): each layout element, and in a + /// map frame each map layer and each layer's labels, a layer named after it, nested as drawn, + /// so a vector editor (Illustrator, Inkscape, Affinity, VectorCraft) opens the page with + /// them as its layers. Off, the page is the same, without them. + pub layers: bool, +} + +impl Default for Options { + fn default() -> Options { + Options { layers: true } + } +} + +/// The document's optional content groups, one for each layer drawn, in the order first drawn: +/// a layer is the same group on every page it is on (a map series' title, page after page), by +/// its name, the group it is in, and which of the layers so named there it is. +#[derive(Default)] +pub(crate) struct Layers { + /// Whether layers are written at all ([`Options::layers`]). + pub(crate) on: bool, + /// Each group's object number, name, and the group it is in (its place here). + list: Vec<(usize, String, Option)>, + by_key: std::collections::HashMap<(Option, String, usize), usize>, +} + +impl Layers { + /// The `n`th group named `name` inside group `parent`: its place here and object number, + /// numbered the first time. + pub(crate) fn group(&mut self, doc: &mut Doc, parent: Option, name: &str, n: usize) -> (usize, usize) { + let key = (parent, name.to_string(), n); + if let Some(&at) = self.by_key.get(&key) + && let Some(&(id, ..)) = self.list.get(at) + { + return (at, id); + } + let id = doc.reserve(); + self.list.push((id, name.to_string(), parent)); + self.by_key.insert(key, self.list.len() - 1); + (self.list.len() - 1, id) + } + + /// Writes the groups, and the catalog's `/OCProperties` entry naming them, every one on and + /// listed as drawn, each inside the one it is in (`/Order`); empty for none. + fn write(&self, doc: &mut Doc) -> String { + if self.list.is_empty() { + return String::new(); + } + for (id, name, _) in &self.list { + doc.put(*id, format!("<< /Type /OCG /Name {} >>", text_string(name)).as_bytes()); + } + let ids: Vec = self.list.iter().map(|(id, ..)| format!("{id} 0 R")).collect(); + format!(" /OCProperties << /OCGs [{}] /D << /Name (Layers) /BaseState /ON /Order [{}] >> >>", ids.join(" "), self.order(None)) + } + + /// The groups inside `parent`, in order, each followed by the array of those inside it. + fn order(&self, parent: Option) -> String { + let mut out = Vec::new(); + for (at, (id, _, p)) in self.list.iter().enumerate() { + if *p == parent { + out.push(format!("{id} 0 R")); + let inner = self.order(Some(at)); + if !inner.is_empty() { + out.push(format!("[{inner}]")); + } + } + } + out.join(" ") + } +} + +/// Whether `items` hold a layer. +fn has_layer(items: &[Item]) -> bool { + items.iter().any(|i| matches!(i, Item::Group(g) if g.layer.is_some() || has_layer(&g.items))) +} + +/// Writes the pages as a PDF document, with their layers ([`Options::default`]). pub fn write(pages: &[Page], title: &str) -> Vec { + write_with(pages, title, Options::default()) +} + +/// Writes the pages as a PDF document, as `options` say. +pub fn write_with(pages: &[Page], title: &str, options: Options) -> Vec { // Georeferenced frames make the document PDF 1.7 with Adobe's extension level 3, where - // geospatial measures are defined (since taken into ISO 32000-2); what else it holds is 1.4. + // geospatial measures are defined (since taken into ISO 32000-2); layers (optional content) + // make it 1.5; what else it holds is 1.4. let geo = pages.iter().any(|p| !p.viewports.is_empty()); - let mut doc = if geo { Doc::of_version("1.7") } else { Doc::new() }; + let layered = options.layers && pages.iter().any(|p| matches!(&p.content, Content::Vector { items, .. } if has_layer(items))); + let mut doc = if geo { + Doc::of_version("1.7") + } else if layered { + Doc::of_version("1.5") + } else { + Doc::new() + }; let (catalog, tree, info) = (doc.reserve(), doc.reserve(), doc.reserve()); let ids: Vec = pages.iter().map(|_| doc.reserve()).collect(); let mut fonts = fonts::Fonts::default(); + let mut layers = Layers { on: layered, ..Layers::default() }; for (p, &page) in pages.iter().zip(&ids) { let (pw, ph) = (p.width_mm * 72.0 / 25.4, p.height_mm * 72.0 / 25.4); let (contents, resources) = match &p.content { @@ -249,7 +342,7 @@ pub fn write(pages: &[Page], title: &str) -> Vec { (contents, format!("<< /XObject << /Im0 {image} 0 R >> >>")) } Content::Vector { width, height, items, .. } => { - let resources = content::page(&mut doc, &mut fonts, (*width, *height), (pw, ph), items); + let resources = content::page(&mut doc, &mut fonts, &mut layers, (*width, *height), (pw, ph), items); (resources.0, format!("{} 0 R", resources.1)) } }; @@ -268,8 +361,9 @@ pub fn write(pages: &[Page], title: &str) -> Vec { ); } fonts.write(&mut doc); + let optional = layers.write(&mut doc); let extensions = if geo { " /Extensions << /ADBE << /BaseVersion /1.7 /ExtensionLevel 3 >> >>" } else { "" }; - doc.put(catalog, format!("<< /Type /Catalog /Pages {tree} 0 R{extensions} >>").as_bytes()); + doc.put(catalog, format!("<< /Type /Catalog /Pages {tree} 0 R{extensions}{optional} >>").as_bytes()); let kids: Vec = ids.iter().map(|i| format!("{i} 0 R")).collect(); doc.put(tree, format!("<< /Type /Pages /Kids [{}] /Count {} >>", kids.join(" "), pages.len()).as_bytes()); doc.put(info, format!("<< /Title {} /Producer (RustGIS) >>", text_string(title)).as_bytes()); @@ -427,6 +521,120 @@ pub(crate) mod tests { assert!((geo.viewports[0].rect_mm[0] - 10.0).abs() < 1e-6, "{:?}", geo.viewports[0].rect_mm); } + /// A page of layers as a layout draws them: a title, a map frame (placed, clipped) holding + /// a map layer and its labels, and two elements named alike, each square in its own colour. + fn layered_page() -> Page { + use crate::vector::{Brush, Drawing}; + let square = |d: &mut Drawing, c: u8| { + let r = tiny_skia::Rect::from_xywh(1.0, 1.0, 4.0, 4.0).unwrap(); + let fill = Brush::Solid(tiny_skia::Color::from_rgba8(c, 0, 0, 255)); + d.fill(tiny_skia::PathBuilder::from_rect(r), fill, tiny_skia::FillRule::Winding, tiny_skia::Transform::identity()); + }; + let mut d = Drawing::new(20.0, 20.0); + d.begin_layer("Título (rascunho)"); + square(&mut d, 1); + d.end_group(); + d.begin_layer("Mapa"); + let mut frame = Drawing::new(20.0, 20.0); + frame.begin_layer("Países"); + square(&mut frame, 2); + frame.end_group(); + frame.begin_layer("Labels: Países"); + square(&mut frame, 3); + frame.end_group(); + d.place(frame, tiny_skia::Transform::from_translate(2.0, 2.0), 1.0, rustgis_map::effects::Blend::Normal, None); + d.end_group(); + for c in [4, 5] { + d.begin_layer("Texto"); + square(&mut d, c); + d.end_group(); + } + Page::drawing(d, 20.0, 20.0) + } + + /// A drawing's layers are optional content groups (#1815): named, nested in `/Order` as + /// drawn, each one's content marked inside its BDC/EMC; two elements named alike are two + /// groups, and a map series' pages share theirs. Without layers, the same page unmarked. + #[test] + fn layers_are_optional_content_groups() { + let pdf = write(&[layered_page(), layered_page()], "Layers"); + let text = String::from_utf8_lossy(&pdf); + assert!(text.starts_with("%PDF-1.5"), "optional content is PDF 1.5"); + let objs = objects(&pdf); + let ocg = |name: &str| { + let want = format!("<< /Type /OCG /Name {} >>", text_string(name)); + objs.iter() + .position(|o| o.0 == want) + .map(|i| i + 1) + .unwrap_or_else(|| panic!("{name}: {objs:?}", objs = objs.iter().map(|o| &o.0).collect::>())) + }; + let (title, map, layer, labels) = (ocg("Título (rascunho)"), ocg("Mapa"), ocg("Países"), ocg("Labels: Países")); + let texts: Vec = objs.iter().enumerate().filter(|o| o.1.0.contains("/Name (Texto)")).map(|o| o.0 + 1).collect(); + assert_eq!(texts.len(), 2, "two elements named alike, two groups"); + assert_eq!(objs.iter().filter(|o| o.0.contains("/Type /OCG")).count(), 6, "the second page reuses the first's"); + let catalog = &objs[0].0; + let order = format!("/Order [{title} 0 R {map} 0 R [{layer} 0 R {labels} 0 R] {} 0 R {} 0 R]", texts[0], texts[1]); + assert!( + catalog.contains("/OCProperties << /OCGs [") && catalog.contains(&order) && catalog.contains("/BaseState /ON"), + "{catalog}" + ); + // Each square inside its own group's marks, the map's inside the frame's. + let content = objs.iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).find(|c| c.contains(" BDC")).unwrap(); + let inside = |id: usize, colour: &str| { + let start = content.find(&format!("/OC /OC{id} BDC")).unwrap_or_else(|| panic!("{id}: {content}")); + let mut depth = 0; + let mut end = start; + for (i, line) in content[start..].lines().scan(start, |at, l| { + let here = *at; + *at += l.len() + 1; + Some((here, l)) + }) { + if line.ends_with(" BDC") { + depth += 1; + } else if line == "EMC" { + depth -= 1; + if depth == 0 { + end = i; + break; + } + } + } + assert!(content[start..end].contains(colour), "{id} holds {colour}: {}", &content[start..end]); + }; + inside(title, "0.004 0 0 rg"); + inside(map, "0.008 0 0 rg"); + inside(layer, "0.008 0 0 rg"); + inside(labels, "0.012 0 0 rg"); + inside(texts[1], "0.02 0 0 rg"); + assert_eq!(content.matches(" BDC").count(), content.matches("EMC\n").count()); + let page = objs.iter().find(|o| o.0.contains("/Properties <<")).map(|o| &o.0).unwrap(); + assert!(page.contains(&format!("/OC{title} {title} 0 R")), "{page}"); + // Without layers: no groups, no marks, and the same drawing. + let plain = write_with(&[layered_page()], "Layers", Options { layers: false }); + let plain_text = String::from_utf8_lossy(&plain); + assert!(plain_text.starts_with("%PDF-1.4") && !plain_text.contains("/OCProperties") && !plain_text.contains("/Type /OCG")); + let plain_content = + objects(&plain).into_iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).find(|c| c.contains(" rg")).unwrap(); + // The same things painted in the same order: only the marks and the frame's clip and + // transform, set again for each of its layers, differ. + let paints = |c: &str| -> String { + c.lines() + .filter(|l| !(l.ends_with(" BDC") || *l == "EMC" || *l == "q" || *l == "Q" || l.ends_with(" cm"))) + .map(|l| format!("{l}\n")) + .collect() + }; + assert_eq!(paints(&content), paints(&plain_content)); + // The frame's layers are marked outside its transform, each moved on its own: an editor + // can't put a layer inside a clipping group. + for id in [layer, labels] { + assert!(content.contains(&format!("/OC /OC{id} BDC\nq\n1 0 0 1 2 2 cm\n")), "{id}: {content}"); + } + // A page with no layers is written as before. + let mut a = Pixmap::new(2, 2).unwrap(); + a.fill(tiny_skia::Color::WHITE); + assert!(!String::from_utf8_lossy(&write(&[Page::new(&a, 10.0, 10.0)], "Picture")).contains("/OCProperties")); + } + #[test] fn unwritten_objects_become_nulls_and_writing_twice_keeps_the_first() { let mut doc = Doc::new(); diff --git a/crates/render/src/pdf/content.rs b/crates/render/src/pdf/content.rs index 920681ccd7..f479473058 100644 --- a/crates/render/src/pdf/content.rs +++ b/crates/render/src/pdf/content.rs @@ -1,6 +1,7 @@ //! A [`Drawing`](crate::vector::Drawing)'s items as a page's content stream: paths, glyph runs //! (in the document's [`Fonts`]), pictures, gradients (shadings, their transparency a soft mask) -//! and groups (clipped, or transparency groups for an opacity or blend mode). +//! and groups (clipped, or transparency groups for an opacity or blend mode; a layer's, marked +//! content in its optional content group, from the document's [`Layers`]). //! //! The drawing's pixels (y down) are mapped onto the page once, at the start; every item is //! written in them. Colour, transparency and line settings are written only when they change. @@ -12,15 +13,22 @@ use std::io::Write as _; use rustgis_map::effects::Blend; use tiny_skia::{Color, FillRule, LineCap, LineJoin, Path, PathSegment, Transform}; -use super::Doc; use super::fonts::Fonts; +use super::{Doc, Layers}; use crate::vector::{Brush, Clip, GlyphRun, Group, Image, Item, Stroke}; /// Writes the content of a page `size` (drawing pixels) shown at `page` (points); its content /// stream's and resource dictionary's object numbers. -pub(super) fn page(doc: &mut Doc, fonts: &mut Fonts, size: (f32, f32), page: (f64, f64), items: &[Item]) -> (usize, usize) { +pub(super) fn page( + doc: &mut Doc, + fonts: &mut Fonts, + layers: &mut Layers, + size: (f32, f32), + page: (f64, f64), + items: &[Item], +) -> (usize, usize) { let (contents, resources) = (doc.reserve(), doc.reserve()); - let mut w = Writer { doc, fonts, res: Resources::default(), resources }; + let mut w = Writer { doc, fonts, layers, res: Resources::default(), resources, parent: None, siblings: HashMap::new() }; let mut out = Vec::new(); // Drawing pixels, y down from the top, to points, y up from the bottom. let (sx, sy) = (page.0 / f64::from(size.0), page.1 / f64::from(size.1)); @@ -41,6 +49,8 @@ struct Resources { state_list: Vec, xobjects: Vec, shadings: Vec, + /// Optional content groups, by object number. + properties: Vec, } impl Resources { @@ -68,6 +78,13 @@ impl Resources { } s.push_str(" >>"); } + if !self.properties.is_empty() { + s.push_str(" /Properties <<"); + for id in &self.properties { + let _ = write!(s, " /OC{id} {id} 0 R"); + } + s.push_str(" >>"); + } if !self.shadings.is_empty() { s.push_str(" /Shading <<"); for (i, sh) in self.shadings.iter().enumerate() { @@ -106,8 +123,13 @@ struct State { struct Writer<'a> { doc: &'a mut Doc, fonts: &'a mut Fonts, + layers: &'a mut Layers, res: Resources, resources: usize, + /// The layer being written in (its place in `layers`), and how many layers of each name it + /// has had on this page so far: the second of two elements named alike is a layer of its own. + parent: Option, + siblings: HashMap<(Option, String), usize>, } impl Writer<'_> { @@ -312,52 +334,106 @@ impl Writer<'_> { } /// Writes a group inside its clip, moved by its transform: as a transparency group when it has - /// an opacity or a blend mode, else straight into the content. + /// an opacity or a blend mode, else straight into the content. A layer's items are marked as + /// its optional content group's (#1815). The layers inside a group that only clips and moves + /// (a map frame's map layers and labels) are marked outside its clip, each run of its items + /// clipped and moved on its own, which draws the same: a vector editor can't put a layer + /// inside a clipping group, so it would flatten them. fn group(&mut self, out: &mut Vec, st: &mut State, g: &Group) { + let outer = self.open_layer(out, g.layer.as_deref()); + let composite = g.opacity < 0.999 || g.blend != Blend::Normal; + let is_layer = |i: &Item| matches!(i, Item::Group(c) if c.layer.is_some()); + if self.layers.on && !composite && g.items.iter().any(is_layer) { + for run in g.items.chunk_by(|a, b| !is_layer(a) && !is_layer(b)) { + match run { + [Item::Group(c)] if c.layer.is_some() => { + let inner = self.open_layer(out, c.layer.as_deref()); + self.clipped(out, st, g, |w, out, st| w.items(out, st, &c.items)); + self.close_layer(out, inner); + } + _ => self.clipped(out, st, g, |w, out, st| w.items(out, st, run)), + } + } + } else { + self.clipped(out, st, g, |w, out, st| { + if composite { + w.transparency_group(out, g); + } else { + w.items(out, st, &g.items); + } + }); + } + self.close_layer(out, outer); + } + + /// Writes what `f` writes inside `g`'s clip, moved by its transform; nothing when the + /// transform folds it flat. + fn clipped(&mut self, out: &mut Vec, st: &mut State, g: &Group, f: impl FnOnce(&mut Self, &mut Vec, &mut State)) { let saved = st.clone(); out.extend_from_slice(b"q\n"); if let Some(clip) = &g.clip { clip_ops(out, clip); } // A transform that folds its items flat leaves nothing to see. - if g.transform.invert().is_none() { - out.extend_from_slice(b"Q\n"); - return; - } - if !g.transform.is_identity() { - write_matrix(out, g.transform); - out.extend_from_slice(b" cm\n"); - } - let composite = g.opacity < 0.999 || g.blend != Blend::Normal; - if composite { - // A transparency group, isolated (drawn on transparency, as the renderer draws a - // layer offscreen), composited with the group's opacity and blend mode. - let form = self.doc.reserve(); - let mut inner = Vec::new(); - self.items(&mut inner, &mut State::default(), &g.items); - // Room for anything the group's items can draw, in their own space: the page seen - // through every transform above the group is not known here. - let dict = format!( - "/Type /XObject /Subtype /Form /BBox [-1000000 -1000000 1000000 1000000] /Group << /S /Transparency /CS /DeviceRGB /I true >> /Resources {} 0 R", - self.resources - ); - self.doc.stream(form, &dict, &inner, false); - self.res.xobjects.push(form); - let mut entries = String::new(); - let a = fnum(g.opacity); - let _ = write!(entries, "/ca {a} /CA {a}"); - if g.blend != Blend::Normal { - let _ = write!(entries, " /BM /{}", blend_name(g.blend)); + if g.transform.invert().is_some() { + if !g.transform.is_identity() { + write_matrix(out, g.transform); + out.extend_from_slice(b" cm\n"); } - let gs = self.res.state(entries); - let _ = writeln!(out, "/G{gs} gs /X{form} Do"); - } else { - self.items(out, st, &g.items); + f(self, out, st); } out.extend_from_slice(b"Q\n"); *st = saved; } + /// `g`'s items as a transparency group, isolated (drawn on transparency, as the renderer + /// draws a layer offscreen), composited with its opacity and blend mode. + fn transparency_group(&mut self, out: &mut Vec, g: &Group) { + let form = self.doc.reserve(); + let mut inner = Vec::new(); + self.items(&mut inner, &mut State::default(), &g.items); + // Room for anything the group's items can draw, in their own space: the page seen + // through every transform above the group is not known here. + let dict = format!( + "/Type /XObject /Subtype /Form /BBox [-1000000 -1000000 1000000 1000000] /Group << /S /Transparency /CS /DeviceRGB /I true >> /Resources {} 0 R", + self.resources + ); + self.doc.stream(form, &dict, &inner, false); + self.res.xobjects.push(form); + let mut entries = String::new(); + let a = fnum(g.opacity); + let _ = write!(entries, "/ca {a} /CA {a}"); + if g.blend != Blend::Normal { + let _ = write!(entries, " /BM /{}", blend_name(g.blend)); + } + let gs = self.res.state(entries); + let _ = writeln!(out, "/G{gs} gs /X{form} Do"); + } + + /// Begins marking the layer `name` (none for `None`, or when the document writes no layers): + /// the layer written in before, for [`Writer::close_layer`]. + fn open_layer(&mut self, out: &mut Vec, name: Option<&str>) -> Option> { + let name = name.filter(|_| self.layers.on)?; + let outer = self.parent; + let n = self.siblings.entry((outer, name.to_string())).or_insert(0); + let (at, id) = self.layers.group(self.doc, outer, name, *n); + *n += 1; + if !self.res.properties.contains(&id) { + self.res.properties.push(id); + } + let _ = writeln!(out, "/OC /OC{id} BDC"); + self.parent = Some(at); + Some(outer) + } + + /// Ends the layer [`Writer::open_layer`] began, if it did. + fn close_layer(&mut self, out: &mut Vec, outer: Option>) { + if let Some(outer) = outer { + out.extend_from_slice(b"EMC\n"); + self.parent = outer; + } + } + /// Sets the fill and stroke alpha to `a` where it isn't already. fn alpha(&mut self, out: &mut Vec, st: &mut State, a: f32) { let a = if a.is_finite() { a.clamp(0.0, 1.0) } else { 1.0 }; diff --git a/crates/render/src/vector.rs b/crates/render/src/vector.rs index ec1308c2db..80faf57f2e 100644 --- a/crates/render/src/vector.rs +++ b/crates/render/src/vector.rs @@ -135,6 +135,9 @@ pub struct Group { pub blend: Blend, pub clip: Option, pub transform: Transform, + /// The layer its items make, named: a layout element, a map layer or its labels, which a PDF + /// writes as an optional content group so a vector editor opens it as a layer (#1815). + pub layer: Option, } /// A clip path: what is outside it isn't drawn. @@ -226,7 +229,22 @@ impl Drawing { let opacity = if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 }; let clip = clip.filter(|c| c.transform.is_finite()); self.cost += clip.as_ref().map_or(0, |c| path_cost(&c.path)) + 120; - self.open.push(Group { items: Vec::new(), opacity, blend, clip, transform: Transform::identity() }); + self.open.push(Group { items: Vec::new(), opacity, blend, clip, transform: Transform::identity(), layer: None }); + } + + /// Starts a layer named `name`: what is drawn until [`Drawing::end_group`] is one, drawn as + /// it would be without it (see [`Group::layer`]). + pub fn begin_layer(&mut self, name: &str) { + self.cost += 120 + name.len(); + let layer = Some(name.chars().filter(|c| !c.is_control()).take(200).collect()); + self.open.push(Group { + items: Vec::new(), + opacity: 1.0, + blend: Blend::Normal, + clip: None, + transform: Transform::identity(), + layer, + }); } /// Places `child` as a group: its items moved by `transform` (from its space to this @@ -253,7 +271,7 @@ impl Drawing { self.count += count; self.cost += cost; let opacity = if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 }; - self.add(Item::Group(Group { items, opacity, blend, clip, transform })); + self.add(Item::Group(Group { items, opacity, blend, clip, transform, layer: None })); } /// Ends the innermost group begun; nothing when none is open. An empty group is left out. @@ -384,6 +402,20 @@ pub(crate) fn deflate_rows<'a, T: 'a>(rows: impl Iterator, mut f (status == TDEFLStatus::Done).then_some(out) } +/// `items` with every layer's group replaced by its items, at any depth: for tests that look at +/// what is drawn, not at the layers it is in. +#[cfg(test)] +pub(crate) fn without_layers(items: Vec) -> Vec { + items + .into_iter() + .flat_map(|i| match i { + Item::Group(g) if g.layer.is_some() => without_layers(g.items), + Item::Group(g) => vec![Item::Group(Group { items: without_layers(g.items), ..g })], + other => vec![other], + }) + .collect() +} + /// Draws `items` (moved by `base`) back onto pixels with tiny-skia: for tests comparing a /// recording with what the renderer draws. #[cfg(test)] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7aa9082afc..727db51ee2 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1684,7 +1684,15 @@ impl RustGisApp { let georeference = self.ui.pdf_georeference; let session = &mut self.session; let r = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { - rustgis_engine::cmd::layout::layout_bytes_with(session, li, pdf, dpi, true, georeference) + rustgis_engine::cmd::layout::layout_bytes_with( + session, + li, + pdf, + dpi, + true, + georeference, + rustgis_engine::render::pdf::Options::default(), + ) })) .unwrap_or_else(|_| Err("the layout export failed unexpectedly".into())); if let Err(e) = &r { diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 27ba5a7575..e5b5cda3b9 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -370,6 +370,12 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu are pictures cut to their shape. The `dpi` also sets how fine the vectors' detail is kept, as a PNG at that resolution would show it. A frame or page whose vectors would pass 256 MB (64 MB in the browser) is drawn as a picture instead, and the export says which. + Its page has layers (PDF optional content groups), which vector editors such as Illustrator, + Inkscape, Affinity and VectorCraft open as layers, and PDF readers list in their layers panel: + one for each element, named after it, and inside a map frame's, one for each map layer and one + for each layer's labels (`Labels: `), and one for the frame's grid. A map series' pages + share them. `"pdf": {"layers": false}` on `layout.export` leaves them out. A map exported as PDF + (Publish › Export Map) has its map layers and labels as layers too. A PDF is also a GeoPDF: each map frame is georeferenced (an ISO 32000 geospatial viewport, the form GDAL, QGIS, Acrobat and Avenza read), with its map's coordinate system as WKT and its EPSG code when it has one, so a reader shows coordinates and measures in it, and GDAL or QGIS open the From 7dff24fedee9fe5925ba3d8dc30099e701ee2003 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 04:04:02 -0300 Subject: [PATCH 2/4] fix(render): review round 1 for PDF layers (#1815) - SVG: a layer's items are written in place, not in an isolated group, so a blended map layer still blends with the layers beneath it (as before layers). Tested with a Multiply layer over another. - A map layer with no name is named "Layer ", for its layer and its labels' layer; label layers' names are looked up once per layer. - debug_assert that a recording has one layer per placed label. - Docs and the Options doc name only the editor checked (VectorCraft). Co-Authored-By: Claude Opus 5.5 --- crates/render/src/lib.rs | 18 ++++++++++++++-- crates/render/src/pdf.rs | 4 ++-- crates/render/src/svg/vectors.rs | 37 ++++++++++++++++++++++++++++++++ docs/user-guide/layouts.md | 4 ++-- 4 files changed, 57 insertions(+), 6 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f24ed4a2e7..5430142127 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4003,7 +4003,7 @@ fn render_frame( if !layer.visible || !layer.in_scale_range(scale) || held.contains(&layer.id) { continue; } - pm.layer(Some(&layer.name)); + pm.layer(Some(&layer_name(layer))); let opacity = layer.opacity() * group_opacity.get(&layer.id).copied().unwrap_or(1.0); let mask = masks.iter().find(|(id, _)| *id == layer.id).map(|(_, m)| m); let (blend, layer_blend) = (blend_mode(layer.blend), layer.blend); @@ -5170,7 +5170,8 @@ fn render_frame( // fixed labels (graphics text) come first, then one for each key. let label_layers: Vec<(u32, String)> = if pm.is_recording() { let fixed = placed.labels.len().saturating_sub(placed.keys.len()); - let name = |id: u32| map.layers.iter().find(|l| l.id == id).map(|l| l.name.clone()).unwrap_or_default(); + let names: std::collections::HashMap = map.layers.iter().map(|l| (l.id, layer_name(l))).collect(); + let name = |id: u32| names.get(&id).cloned().unwrap_or_default(); std::iter::repeat_n((u32::MAX, String::new()), fixed).chain(placed.keys.iter().map(|((id, ..), _)| (*id, name(*id)))).collect() } else { Vec::new() @@ -6525,6 +6526,12 @@ fn render_drawing_inner(map: &mut Map, view: &View) -> Option { pm.into_drawing() } +/// A map layer's name as a recording's layer is named (#1815): a layer with none is named after +/// its id, as a layout element with none is after its kind. +fn layer_name(layer: &rustgis_map::Layer) -> String { + if layer.name.trim().is_empty() { format!("Layer {}", layer.id) } else { layer.name.clone() } +} + /// Draws a frame's unplaced and placed labels. A recording keeps each map layer's placed labels /// together as a layer of their own, "Labels: " (#1815), the layers in the order of their /// first label: placed labels don't overlap, so the page looks the same. @@ -6532,6 +6539,13 @@ pub(crate) fn draw_labels(pm: &mut Canvas, (unplaced, labels, layers): (&[Placed for l in unplaced { text::draw(pm, l, ppp); } + // Recorded, there is a layer for each label (see `render_frame`). + debug_assert!( + !pm.is_recording() || layers.is_empty() || layers.len() == labels.len(), + "{} layers for {} labels", + layers.len(), + labels.len() + ); if !pm.is_recording() || layers.len() != labels.len() { for l in labels { text::draw(pm, l, ppp); diff --git a/crates/render/src/pdf.rs b/crates/render/src/pdf.rs index a388930aad..4e6d1306bc 100644 --- a/crates/render/src/pdf.rs +++ b/crates/render/src/pdf.rs @@ -230,8 +230,8 @@ impl Doc { pub struct Options { /// The drawings' layers as optional content groups (#1815): each layout element, and in a /// map frame each map layer and each layer's labels, a layer named after it, nested as drawn, - /// so a vector editor (Illustrator, Inkscape, Affinity, VectorCraft) opens the page with - /// them as its layers. Off, the page is the same, without them. + /// so a vector editor that reads optional content (VectorCraft, where it was checked) opens + /// the page with them as its layers. Off, the page is the same, without them. pub layers: bool, } diff --git a/crates/render/src/svg/vectors.rs b/crates/render/src/svg/vectors.rs index 9324705b4a..193228510e 100644 --- a/crates/render/src/svg/vectors.rs +++ b/crates/render/src/svg/vectors.rs @@ -273,6 +273,12 @@ fn picture(out: &mut String, image: &Image) -> Option<()> { /// A group: inside its clip (in the outer space), moved by its transform, composited with its /// opacity and blend mode as one isolated layer; `None` as [`items`] gives it. fn group(out: &mut String, defs: &mut Defs, g: &Group) -> Option<()> { + // A layer (a PDF's optional content, #1815) only names its items, with no clip, opacity or + // transform: they are written in place, so a blended layer among them still reaches the + // layers beneath it, as on the page. + if g.layer.is_some() { + return items(out, defs, &g.items); + } let mut open = 0; if let Some(clip) = &g.clip { let id = defs.id("clip"); @@ -409,6 +415,37 @@ mod tests { assert!(defs.text.contains(r#"`), and one for the frame's grid. A map series' pages share them. `"pdf": {"layers": false}` on `layout.export` leaves them out. A map exported as PDF From 840864f5d21b315a148066b38264670cda8a1d6a Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 04:30:18 -0300 Subject: [PATCH 3/4] fix(render): PDF labels keep their placement order (#1815, layers) Labels can overlap (pinned ones, a class that shows all, labels that ignore placement), so reordering them by map layer could change which shows on top in the PDF and SVG. They are now recorded in the placement's order, as the PNG draws them, each run of one layer's labels marked as that layer. A layer can carry an id (a map layer's), and runs with the same name and id are one optional content group; layers without one stay one group each, however named. Also: the debug_assert in draw_labels is gone (its fallback stays), and an unknown key in layout.export's "pdf" is refused, naming the keys it takes. Co-Authored-By: Claude Opus 5.5 --- crates/engine/src/cmd/layout.rs | 9 +++- crates/engine/src/tests.rs | 2 +- crates/render/src/canvas.rs | 14 +++++- crates/render/src/lib.rs | 74 ++++++++++++++++++++++++-------- crates/render/src/pdf.rs | 23 +++++----- crates/render/src/pdf/content.rs | 25 +++++++---- crates/render/src/svg/vectors.rs | 2 +- crates/render/src/vector.rs | 24 +++++------ 8 files changed, 116 insertions(+), 57 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 599f27708a..67dac30479 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -4442,12 +4442,19 @@ 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). +/// `"layers": false` (#1815). A key it doesn't know is refused, with the keys it takes. fn pdf_options(p: &Value) -> Result { 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, diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e20e7af122..2ce3f49450 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -37128,7 +37128,7 @@ fn a_layout_pdf_has_its_elements_and_map_layers_as_layers() { // 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})] { + 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}"); } diff --git a/crates/render/src/canvas.rs b/crates/render/src/canvas.rs index a95d599f95..b5061c12fc 100644 --- a/crates/render/src/canvas.rs +++ b/crates/render/src/canvas.rs @@ -241,12 +241,22 @@ impl Canvas { /// 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)>) { self.keep(|r| { if std::mem::take(&mut r.layer) { r.drawing.end_group(); } - if let Some(name) = name { - r.drawing.begin_layer(name); + if let Some((name, id)) = layer { + r.drawing.begin_layer(name, id); r.layer = true; } }); diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5430142127..620794085b 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -4003,7 +4003,7 @@ fn render_frame( if !layer.visible || !layer.in_scale_range(scale) || held.contains(&layer.id) { continue; } - pm.layer(Some(&layer_name(layer))); + pm.layer_with_id(&layer_name(layer), u64::from(layer.id)); let opacity = layer.opacity() * group_opacity.get(&layer.id).copied().unwrap_or(1.0); let mask = masks.iter().find(|(id, _)| *id == layer.id).map(|(_, m)| m); let (blend, layer_blend) = (blend_mode(layer.blend), layer.blend); @@ -6533,36 +6533,28 @@ fn layer_name(layer: &rustgis_map::Layer) -> String { } /// Draws a frame's unplaced and placed labels. A recording keeps each map layer's placed labels -/// together as a layer of their own, "Labels: " (#1815), the layers in the order of their -/// first label: placed labels don't overlap, so the page looks the same. +/// as a layer of their own, "Labels: " (#1815): drawn in the placement's order, as the +/// pixels draw them (labels can overlap: pinned ones, a class that shows all), each run of one +/// layer's labels is marked as that layer, so one layer can be several runs. pub(crate) fn draw_labels(pm: &mut Canvas, (unplaced, labels, layers): (&[PlacedLabel], &[PlacedLabel], &[(u32, String)]), ppp: f32) { for l in unplaced { text::draw(pm, l, ppp); } - // Recorded, there is a layer for each label (see `render_frame`). - debug_assert!( - !pm.is_recording() || layers.is_empty() || layers.len() == labels.len(), - "{} layers for {} labels", - layers.len(), - labels.len() - ); + // Recorded, there is a layer for each label (see `render_frame`); without, no layers. if !pm.is_recording() || layers.len() != labels.len() { for l in labels { text::draw(pm, l, ppp); } return; } - let mut first = std::collections::HashMap::new(); - for (i, (id, _)) in layers.iter().enumerate() { - first.entry(*id).or_insert(i); - } - let mut order: Vec = (0..labels.len()).collect(); - order.sort_by_key(|i| layers.get(*i).and_then(|(id, _)| first.get(id)).copied().unwrap_or(0)); let mut shown = None; - for i in order { - let (Some(l), Some((id, name))) = (labels.get(i), layers.get(i)) else { continue }; + for (l, (id, name)) in labels.iter().zip(layers) { if shown != Some(*id) { - pm.layer((*id != u32::MAX).then(|| format!("Labels: {name}")).as_deref()); + if *id == u32::MAX { + pm.layer(None); + } else { + pm.layer_with_id(&format!("Labels: {name}"), u64::from(*id)); + } shown = Some(*id); } text::draw(pm, l, ppp); @@ -6738,6 +6730,50 @@ mod tests { } } + /// Labels of two map layers that overlap (a class that shows all, a pinned label) are + /// recorded in the placement's order, as the pixels draw them, so the one on top stays on + /// top: each run of one layer's labels is marked as that layer, and its runs are one PDF + /// layer (#1815). + #[test] + fn overlapping_labels_of_two_layers_keep_their_order() { + use crate::vector::Item; + let labels = [label("Aa", 10.0, None, 0.0), label("Bb", 12.0, None, 0.0), label("Cc", 14.0, None, 0.0)]; + let layers = [(1, "Rios".to_string()), (2, "Cidades".to_string()), (1, "Rios".to_string())]; + let record = || { + let mut pm = Canvas::recording(120, 40).unwrap(); + draw_labels(&mut pm, (&[], &labels, &layers), 1.0); + pm.into_drawing().unwrap() + }; + let (_, _, items) = record().finish(); + fn text(items: &[Item]) -> String { + items + .iter() + .map(|i| match i { + Item::Glyphs(r) => r.glyphs.iter().map(|g| g.ch).collect(), + Item::Group(g) => text(&g.items), + _ => String::new(), + }) + .collect() + } + let runs: Vec<(String, String)> = + items.iter().filter_map(|i| if let Item::Group(g) = i { Some((g.layer.clone()?, text(&g.items))) } else { None }).collect(); + let want = [("Labels: Rios", "Aa"), ("Labels: Cidades", "Bb"), ("Labels: Rios", "Cc")]; + assert_eq!(runs, want.map(|(a, b)| (a.to_string(), b.to_string()))); + // One PDF layer for Rios's two runs, marked around each in turn. + let pdf = crate::pdf::write(&[crate::pdf::Page::drawing(record(), 40.0, 15.0)], "Labels"); + let objs = crate::pdf::tests::objects(&pdf); + let id = |name: &str| { + let ids: Vec = + objs.iter().enumerate().filter(|o| o.1.0 == format!("<< /Type /OCG /Name ({name}) >>")).map(|o| o.0 + 1).collect(); + assert_eq!(ids.len(), 1, "{name}"); + ids[0] + }; + let (rios, cidades) = (id("Labels: Rios"), id("Labels: Cidades")); + let content = objs.iter().map(|o| String::from_utf8_lossy(&o.1).into_owned()).find(|c| c.contains(" BDC")).unwrap(); + let marks: Vec<&str> = content.lines().filter(|l| l.ends_with(" BDC")).collect(); + assert_eq!(marks, [format!("/OC /OC{rios} BDC"), format!("/OC /OC{cidades} BDC"), format!("/OC /OC{rios} BDC")]); + } + /// While a label is dragged, its callout's line is worked out where it is: from its feature, /// which stays put, to its text's nearest edge; none when its class has no callouts, or its /// text covers its feature. Its extent is what picks it. diff --git a/crates/render/src/pdf.rs b/crates/render/src/pdf.rs index 4e6d1306bc..7d285d1acf 100644 --- a/crates/render/src/pdf.rs +++ b/crates/render/src/pdf.rs @@ -243,21 +243,22 @@ impl Default for Options { /// The document's optional content groups, one for each layer drawn, in the order first drawn: /// a layer is the same group on every page it is on (a map series' title, page after page), by -/// its name, the group it is in, and which of the layers so named there it is. +/// its name, the group it is in, and its id, or without one which of the layers so named there +/// it is. #[derive(Default)] pub(crate) struct Layers { /// Whether layers are written at all ([`Options::layers`]). pub(crate) on: bool, /// Each group's object number, name, and the group it is in (its place here). list: Vec<(usize, String, Option)>, - by_key: std::collections::HashMap<(Option, String, usize), usize>, + by_key: std::collections::HashMap<(Option, String, Option, usize), usize>, } impl Layers { - /// The `n`th group named `name` inside group `parent`: its place here and object number, - /// numbered the first time. - pub(crate) fn group(&mut self, doc: &mut Doc, parent: Option, name: &str, n: usize) -> (usize, usize) { - let key = (parent, name.to_string(), n); + /// The group named `name` with `id` inside group `parent`, or without an id the `n`th so + /// named there: its place here and object number, numbered the first time. + pub(crate) fn group(&mut self, doc: &mut Doc, parent: Option, name: &str, id: Option, n: usize) -> (usize, usize) { + let key = (parent, name.to_string(), id, if id.is_some() { 0 } else { n }); if let Some(&at) = self.by_key.get(&key) && let Some(&(id, ..)) = self.list.get(at) { @@ -531,21 +532,21 @@ pub(crate) mod tests { d.fill(tiny_skia::PathBuilder::from_rect(r), fill, tiny_skia::FillRule::Winding, tiny_skia::Transform::identity()); }; let mut d = Drawing::new(20.0, 20.0); - d.begin_layer("Título (rascunho)"); + d.begin_layer("Título (rascunho)", None); square(&mut d, 1); d.end_group(); - d.begin_layer("Mapa"); + d.begin_layer("Mapa", None); let mut frame = Drawing::new(20.0, 20.0); - frame.begin_layer("Países"); + frame.begin_layer("Países", Some(7)); square(&mut frame, 2); frame.end_group(); - frame.begin_layer("Labels: Países"); + frame.begin_layer("Labels: Países", Some(7)); square(&mut frame, 3); frame.end_group(); d.place(frame, tiny_skia::Transform::from_translate(2.0, 2.0), 1.0, rustgis_map::effects::Blend::Normal, None); d.end_group(); for c in [4, 5] { - d.begin_layer("Texto"); + d.begin_layer("Texto", None); square(&mut d, c); d.end_group(); } diff --git a/crates/render/src/pdf/content.rs b/crates/render/src/pdf/content.rs index f479473058..c983f7966e 100644 --- a/crates/render/src/pdf/content.rs +++ b/crates/render/src/pdf/content.rs @@ -340,14 +340,14 @@ impl Writer<'_> { /// clipped and moved on its own, which draws the same: a vector editor can't put a layer /// inside a clipping group, so it would flatten them. fn group(&mut self, out: &mut Vec, st: &mut State, g: &Group) { - let outer = self.open_layer(out, g.layer.as_deref()); + let outer = self.open_layer(out, g); let composite = g.opacity < 0.999 || g.blend != Blend::Normal; let is_layer = |i: &Item| matches!(i, Item::Group(c) if c.layer.is_some()); if self.layers.on && !composite && g.items.iter().any(is_layer) { for run in g.items.chunk_by(|a, b| !is_layer(a) && !is_layer(b)) { match run { [Item::Group(c)] if c.layer.is_some() => { - let inner = self.open_layer(out, c.layer.as_deref()); + let inner = self.open_layer(out, c); self.clipped(out, st, g, |w, out, st| w.items(out, st, &c.items)); self.close_layer(out, inner); } @@ -410,14 +410,21 @@ impl Writer<'_> { let _ = writeln!(out, "/G{gs} gs /X{form} Do"); } - /// Begins marking the layer `name` (none for `None`, or when the document writes no layers): - /// the layer written in before, for [`Writer::close_layer`]. - fn open_layer(&mut self, out: &mut Vec, name: Option<&str>) -> Option> { - let name = name.filter(|_| self.layers.on)?; + /// Begins marking `g`'s layer, if it is one (and the document writes layers): the layer + /// written in before, for [`Writer::close_layer`]. + fn open_layer(&mut self, out: &mut Vec, g: &Group) -> Option> { + let name = g.layer.as_deref().filter(|_| self.layers.on)?; let outer = self.parent; - let n = self.siblings.entry((outer, name.to_string())).or_insert(0); - let (at, id) = self.layers.group(self.doc, outer, name, *n); - *n += 1; + // Without an id, the second of two layers named alike is another layer. + let n = match g.layer_id { + Some(_) => 0, + None => { + let n = self.siblings.entry((outer, name.to_string())).or_insert(0); + *n += 1; + *n - 1 + } + }; + let (at, id) = self.layers.group(self.doc, outer, name, g.layer_id, n); if !self.res.properties.contains(&id) { self.res.properties.push(id); } diff --git a/crates/render/src/svg/vectors.rs b/crates/render/src/svg/vectors.rs index 193228510e..6e8b7052a3 100644 --- a/crates/render/src/svg/vectors.rs +++ b/crates/render/src/svg/vectors.rs @@ -425,7 +425,7 @@ mod tests { let mut frame = Drawing::new(40.0, 40.0); for (x, blend) in [(0.0, Blend::Normal), (5.0, Blend::Multiply)] { if layered { - frame.begin_layer(if x == 0.0 { "Land" } else { "Shade" }); + frame.begin_layer(if x == 0.0 { "Land" } else { "Shade" }, None); } let mut layer = Drawing::new(40.0, 40.0); layer.fill(rect(x), Brush::Solid(Color::from_rgba8(200, 0, 0, 255)), FillRule::Winding, Transform::identity()); diff --git a/crates/render/src/vector.rs b/crates/render/src/vector.rs index 80faf57f2e..c6766cea7c 100644 --- a/crates/render/src/vector.rs +++ b/crates/render/src/vector.rs @@ -138,6 +138,10 @@ pub struct Group { /// The layer its items make, named: a layout element, a map layer or its labels, which a PDF /// writes as an optional content group so a vector editor opens it as a layer (#1815). pub layer: Option, + /// Which layer it is, where its name doesn't say (a map layer's id): groups with the same + /// name and id are runs of one layer (a map layer's labels, drawn among others'). Without + /// one, each group is a layer of its own, however named. + pub layer_id: Option, } /// A clip path: what is outside it isn't drawn. @@ -229,22 +233,16 @@ impl Drawing { let opacity = if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 }; let clip = clip.filter(|c| c.transform.is_finite()); self.cost += clip.as_ref().map_or(0, |c| path_cost(&c.path)) + 120; - self.open.push(Group { items: Vec::new(), opacity, blend, clip, transform: Transform::identity(), layer: None }); + self.open.push(Group { items: Vec::new(), opacity, blend, clip, transform: Transform::identity(), layer: None, layer_id: None }); } - /// Starts a layer named `name`: what is drawn until [`Drawing::end_group`] is one, drawn as - /// it would be without it (see [`Group::layer`]). - pub fn begin_layer(&mut self, name: &str) { + /// Starts a layer named `name` (and identified by `id`, see [`Group::layer_id`]): what is drawn + /// until [`Drawing::end_group`] is one, drawn as it would be without it (see [`Group::layer`]). + pub fn begin_layer(&mut self, name: &str, id: Option) { self.cost += 120 + name.len(); let layer = Some(name.chars().filter(|c| !c.is_control()).take(200).collect()); - self.open.push(Group { - items: Vec::new(), - opacity: 1.0, - blend: Blend::Normal, - clip: None, - transform: Transform::identity(), - layer, - }); + let (opacity, blend, transform) = (1.0, Blend::Normal, Transform::identity()); + self.open.push(Group { items: Vec::new(), opacity, blend, clip: None, transform, layer, layer_id: id }); } /// Places `child` as a group: its items moved by `transform` (from its space to this @@ -271,7 +269,7 @@ impl Drawing { self.count += count; self.cost += cost; let opacity = if opacity.is_finite() { opacity.clamp(0.0, 1.0) } else { 1.0 }; - self.add(Item::Group(Group { items, opacity, blend, clip, transform, layer: None })); + self.add(Item::Group(Group { items, opacity, blend, clip, transform, layer: None, layer_id: None })); } /// Ends the innermost group begun; nothing when none is open. An empty group is left out. From 4e1800a5f94d97ce1e71e265742801d52b2224e7 Mon Sep 17 00:00:00 2001 From: elpidioassinaturas Date: Thu, 12 Nov 2026 12:12:47 -0300 Subject: [PATCH 4/4] fix(render): a layout element's PDF layer carries its id (#1815, layers) Two elements named alike were told apart by which came first on the page, and an element that drew nothing on one page of a series passed its optional content group to the next of the same name. Each element's layer now carries its id. The guide names Print Map, not Export Map (which writes PNG or TIFF), as the map view's PDF with layers. Co-Authored-By: Claude Opus 5.5 --- crates/render/src/layout.rs | 28 ++++++++++++++++++++++++++-- docs/user-guide/layouts.md | 4 ++-- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index ed61cf35cb..d18c07d659 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -228,8 +228,9 @@ fn draw_page( } } for e in layout.elements.iter().filter(visible) { - // Each element is a layer of the recording, named after it (#1815). - pm.layer(Some(if e.name.trim().is_empty() { e.kind.code() } else { &e.name })); + // Each element is a layer of the recording, named after it (#1815) and identified by its + // id: the same layer on every page of a series, whatever other elements draw there. + pm.layer_with_id(if e.name.trim().is_empty() { e.kind.code() } else { &e.name }, u64::from(e.id)); let (x, y, ew, eh) = ((e.x * k - f64::from(bounds.x())) as f32, (e.y * k - f64::from(bounds.y())) as f32, (e.w * k) as f32, (e.h * k) as f32); let Some(r) = Rect::from_xywh(x, y, ew.max(1.0), eh.max(1.0)) else { continue }; @@ -2739,6 +2740,29 @@ mod tests { assert!(uncovered(r, [-1.0, -1.0, 102.0, 52.0]).is_empty()); } + /// Each element is a layer of the page's recording, named after it and identified by its id + /// (#1815): two elements named alike are told apart by id, not by which comes first, so an + /// element that draws nothing on one page of a series doesn't hand its layer to the other. + #[test] + fn each_element_is_a_layer_with_its_id() { + use crate::vector::Item; + let mut layout = Layout::new("Layers", 120.0, 90.0); + let text = |t: &str| ElementKind::text(t, 12.0, Rgba::rgb(0, 0, 0), false); + let (a, b) = + (layout.add("Texto", (10.0, 10.0, 60.0, 10.0), text("Um")), layout.add("Texto", (10.0, 30.0, 60.0, 10.0), text("Dois"))); + let layers = |layout: &Layout| { + let (drawing, _) = render_drawing(layout, &mut [], 96.0, &PageInfo::default()).unwrap(); + let (_, _, items) = drawing.finish(); + items.into_iter().filter_map(|i| if let Item::Group(g) = i { Some((g.layer?, g.layer_id?)) } else { None }).collect::>() + }; + assert_eq!(layers(&layout), [("Texto".to_string(), u64::from(a)), ("Texto".to_string(), u64::from(b))]); + // The first draws nothing: the second keeps its own layer. + if let Some(ElementKind::Text { text, .. }) = layout.elements.iter_mut().find(|e| e.id == a).map(|e| &mut e.kind) { + text.clear(); + } + assert_eq!(layers(&layout), [("Texto".to_string(), u64::from(b))]); + } + /// A page with a frame of the built-in world and a title. fn vector_page() -> (Layout, Vec) { let mut layout = Layout::new("Vectors", 120.0, 90.0); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 462fdcd5cc..cccdea9ac8 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -374,8 +374,8 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu as layers (VectorCraft, where it was checked), and PDF readers list in their layers panel: one for each element, named after it, and inside a map frame's, one for each map layer and one for each layer's labels (`Labels: `), and one for the frame's grid. A map series' pages - share them. `"pdf": {"layers": false}` on `layout.export` leaves them out. A map exported as PDF - (Publish › Export Map) has its map layers and labels as layers too. + share them. `"pdf": {"layers": false}` on `layout.export` leaves them out. The map view's PDF + (Publish › Print Map) has its map layers and labels as layers too. A PDF is also a GeoPDF: each map frame is georeferenced (an ISO 32000 geospatial viewport, the form GDAL, QGIS, Acrobat and Avenza read), with its map's coordinate system as WKT and its EPSG code when it has one, so a reader shows coordinates and measures in it, and GDAL or QGIS open the