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: 1 addition & 1 deletion GEOLIBRE_PARITY.md
Original file line number Diff line number Diff line change
Expand Up @@ -208,7 +208,7 @@ model-builder.md, segmentation.md, obia.md_
## Layouts & printing
_GeoLibre: docs/features.md › Map tools, printing, and media; docs/user-guide/print-layout.md_

- [ ] **SVG layout export**. Partial: PDF and PNG (_Roadmap: any time_).
- [x] **SVG layout export**: each element a named group, map frames and surrounds as vectors.
- [ ] **Atlas along a line, page-filtered tables and charts, copy to clipboard**. Partial:
per-feature map series (_Roadmap: any time_ for the clipboard).
- [ ] **Map and video recording**: canvas recording, a marker along a line to MP4, camera tours.
Expand Down
5 changes: 2 additions & 3 deletions ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,7 @@ And alongside it:
Built in means no runner download, the selection honoured, geodesic distances and attributes
kept. Before adding a tool, check whether the GeoLibre suite already has it (`gp.tools`); a
built-in version must justify itself on one of those.
- SVG layout export with map frames and surrounds as vectors (they are pictures in it today); STL
export; copy a layout to the clipboard.
- STL export; copy a layout to the clipboard.
- UTM and MGRS grids and coordinate readouts.
- H3 grids built in, next to the A5 grids (the GeoLibre suite has H3 tools only when its runner
is installed).
Expand Down Expand Up @@ -228,7 +227,7 @@ Open questions rather than plans; discuss before building.
path, suitability); ModelBuilder on a node canvas, scripts with command, parameter and value completion,
and history copied as code; the GeoLibre and Whitebox suite (1,000+ tools) natively and in the browser.
- Layouts (map frames, surrounds, map series, publication sheets and figures in one command,
format panes, guides, snapping, element locking and order, measured grids and vector PDF),
format panes, guides, snapping, element locking and order, measured grids, vector PDF and SVG),
reports, presentations and notebooks; the web app embeddable in a page (`?embed`).
- Sharing as open formats (web maps, OGC API Features collections, MapLibre styles, glTF
scenes, locators), offline areas with sync, deep learning pixel classification, hosted
Expand Down
29 changes: 18 additions & 11 deletions crates/engine/src/cmd/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ pub fn commands() -> Vec<C> {
.params(r#"{"layout"?}"#),
C::new("layout.export", "Export Layout", "Publish › Output", export)
.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 pictures at dpi), "dpi"?: 72..600, "allPages"?: bool (PDF only; default true: every map series page, up to 500; false: the current page)}"#),
.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)}"#),
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 @@ -3243,9 +3243,10 @@ pub fn layout_bytes(s: &mut Session, li: usize, pdf: bool, dpi: f64, all: bool)
if pdf { Ok(rustgis_render::pdf::write(&pages, &saved.name)) } else { png.ok_or_else(|| "nothing to draw".to_string()) }
}

/// Says which map frames (by name) and pages (by number) a PDF draws as pictures because their
/// Says which layout elements, map frames and surrounds (by name), and pages (by number) an export
/// draws as pictures because their
/// vectors would pass the size a page's content may come to: one notice for each, with a count.
pub(crate) fn pictured_notices(s: &mut Session, frames: &[String], pages: &[usize]) {
pub(crate) fn pictured_notices(s: &mut Session, frames: &[(u32, String)], pages: &[usize]) {
let mb = rustgis_render::vector::MAX_COST >> 20;
// The first of a list, and how many more there are.
let listed = |items: Vec<String>, most: usize| {
Expand All @@ -3256,21 +3257,24 @@ pub(crate) fn pictured_notices(s: &mut Session, frames: &[String], pages: &[usiz
}
text
};
let mut names: Vec<String> = frames.to_vec();
names.sort_unstable();
names.dedup();
// Each element once (a frame on every page of a series is one frame), by its id and name: two
// elements sharing a name are two.
let mut elements: Vec<(u32, String)> = frames.to_vec();
elements.sort_unstable();
elements.dedup();
let names: Vec<String> = elements.into_iter().map(|(_, name)| name).collect();
if !names.is_empty() {
let n = names.len();
s.warn(format!(
"The PDF draws {n} map frame{} as pictures, not vectors: their vectors would pass {mb} MB ({})",
"The export draws {n} layout element{} as pictures, not vectors: their vectors would pass {mb} MB ({})",
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if n == 1 { "" } else { "s" },
listed(names, 10)
));
}
if !pages.is_empty() {
let n = pages.len();
s.warn(format!(
"The PDF draws {n} page{} as pictures, not vectors: their vectors would pass {mb} MB (page {})",
"The export draws {n} page{} as pictures, not vectors: their vectors would pass {mb} MB (page {})",
if n == 1 { "" } else { "s" },
listed(pages.iter().map(usize::to_string).collect(), 20)
));
Expand All @@ -3297,7 +3301,8 @@ fn export(s: &mut Session, p: &Value) -> CmdResult {
Ok(json!({"path": path, "bytes": bytes.len()}))
}

/// The layout `li` as it is now (a map series at its current page) as SVG, pictures at `dpi`.
/// The layout `li` as it is now (a map series at its current page) as SVG, kept as vectors with
/// pictures at `dpi`; a frame too large for vectors is a picture, and the export says so.
fn layout_svg(s: &mut Session, li: usize, dpi: f64) -> Result<String, String> {
let dpi = if dpi.is_finite() { dpi.clamp(36.0, 600.0) } else { 150.0 };
let current = s.project.layouts.get(li).ok_or("no layout")?.series.as_ref().map_or(0, |sr| sr.page);
Expand All @@ -3309,8 +3314,10 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64) -> Result<String, String> {
};
// Rendering borrows the current layout; it does not step or modify the series page.
let layout = s.project.layouts.get(li).ok_or("no layout")?;
rustgis_render::svg::layout_svg(layout, &mut s.project.maps, dpi, &info)
.ok_or_else(|| "could not draw the page; check its map sources and export size".into())
let (text, pictured) = rustgis_render::svg::layout_svg(layout, &mut s.project.maps, dpi, &info)
.ok_or("could not draw the page; check its map sources and export size")?;
pictured_notices(s, &pictured, &[]);

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.

The new SVG notice path (pictured_notices for an SVG export) has no test that fires it. The only SVG engine test asserts that clean input gives no notice, and the notice-text test calls pictured_notices directly, not through layout.export with SVG. AGENTS.md asks for a test both ways: a lossy SVG export gets the notice with a count and names, and a clean one gets none. Confidence: medium (~60%) that this is a real gap.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Answered rather than changed: firing it end to end needs an element whose vectors pass 256 MB, and the budget's test hook lives in the render crate. The two sides are covered: an_element_too_large_for_vectors_is_a_picture_and_named pushes a frame past a lowered budget through layout_svg and checks it comes back named, and a_pdf_says_which_frames_and_pages_it_draws_as_pictures checks the notice for given elements; the engine joins them in one line (pictured_notices(s, &pictured, &[])).

Ok(text)
}

pub(crate) fn import(s: &mut Session, text: &str) -> CmdResult {
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/presentation.rs
Original file line number Diff line number Diff line change
Expand Up @@ -387,7 +387,7 @@ fn pdf_page(
k: usize,
dpi: f64,
(width, height): (f64, f64),
) -> Result<(rustgis_render::pdf::Page, Vec<String>), String> {
) -> Result<(rustgis_render::pdf::Page, Vec<(u32, String)>), String> {
let pres = s.project.presentations.get(i).ok_or("no presentation")?;
let n = pres.pages.len();
let page = pres.pages.get(k).ok_or_else(|| format!("no page {k}"))?;
Expand Down
22 changes: 15 additions & 7 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -20502,11 +20502,11 @@ fn text_elements_take_an_installed_font_family_by_name() {
assert!(back.element(id).is_some_and(|e| matches!(&e.kind, ElementKind::Text { font_name: None, .. })));
// The page draws in the fallback, and the SVG names the family first.
assert!(!crate::cmd::layout::layout_bytes(&mut s, 0, false, 72.0, false).unwrap().is_empty());
let svg = rustgis_render::svg::layout_svg(&s.project.layouts[0], &mut s.project.maps, 72.0, &Default::default()).unwrap();
let svg = rustgis_render::svg::layout_svg(&s.project.layouts[0], &mut s.project.maps, 72.0, &Default::default()).unwrap().0;
assert!(svg.contains(r#"font-family="&apos;No Such Family 762&apos;, serif""#), "{svg}");
// A name's own quote and backslash are escaped for CSS, not dropped.
s.run("layout.update", &json!({"element": id, "font": r"O'Brien\Sans", "fallback": "sans"})).unwrap();
let svg = rustgis_render::svg::layout_svg(&s.project.layouts[0], &mut s.project.maps, 72.0, &Default::default()).unwrap();
let svg = rustgis_render::svg::layout_svg(&s.project.layouts[0], &mut s.project.maps, 72.0, &Default::default()).unwrap().0;
assert!(svg.contains(r#"font-family="&apos;O\&apos;Brien\\Sans&apos;, sans-serif""#), "{svg}");
// A generic name with control characters around it is still the generic family.
s.run("layout.update", &json!({"element": id, "font": "serif\u{0}"})).unwrap();
Expand Down Expand Up @@ -23058,7 +23058,9 @@ fn a_layout_exports_to_svg_with_each_element_its_own_group() {
.unwrap();
s.run("layout.addElement", &json!({"kind": "rectangle", "x": 5, "y": 5, "w": 40, "h": 20})).unwrap();
let out = std::env::temp_dir().join(format!("rustgis-layout-{}.svg", std::process::id()));
let mark = s.notice_mark();
let r = s.run("layout.export", &json!({"path": out.to_string_lossy(), "dpi": 72})).unwrap();
assert!(!s.notices_since(mark).iter().any(|n| n.text.contains("as pictures, not vectors")), "nothing too large for vectors");
let svg = std::fs::read_to_string(&out).unwrap();
let _ = std::fs::remove_file(&out);
assert_eq!(r["bytes"].as_u64(), Some(svg.len() as u64));
Expand All @@ -23072,11 +23074,12 @@ fn a_layout_exports_to_svg_with_each_element_its_own_group() {
for e in layout.elements.iter().filter(|e| e.visible) {
assert!(svg.contains(&format!(r#"<g id="element-{}""#, e.id)), "element {} ({}) has a group", e.id, e.name);
}
// Text stays text, escaped; shapes stay shapes; what has no vector form yet is a picture in its place.
// Text stays text, escaped; shapes stay shapes; map frames and surrounds are vectors.
assert!(svg.contains("Cities &amp; rivers &lt;2026&gt;</text>"), "the title is text");
assert!(svg.contains(&format!(r#"<g id="element-{title}""#)));
assert!(svg.contains("<rect"), "the rectangle is a shape");
assert!(svg.contains(r#"<image"#) && svg.contains("data:image/png;base64,"), "the map frame is a picture");
assert!(svg.contains(r#"<g clip-path="url(#clip"#) && svg.matches("<path ").count() > 50, "the map frame is vectors, cut to the frame");
assert!(svg.contains("<use xlink:href=\"#glyph"), "its labels and the surrounds' text are glyphs");
assert!(svg.trim_end().ends_with("</svg>"));
// SVG exports only the current series page, even when allPages is supplied.
s.run("layout.series", &json!({"layer": "Lakes", "nameField": "name"})).unwrap();
Expand Down Expand Up @@ -24668,13 +24671,18 @@ fn a_pdf_says_which_frames_and_pages_it_draws_as_pictures() {
let mark = s.notice_mark();
crate::cmd::layout::pictured_notices(&mut s, &[], &[]);
assert!(s.notices_since(mark).is_empty(), "nothing drawn as a picture, nothing said");
let frames = ["Inset".to_string(), "Main".to_string(), "Main".to_string()];
// "Main" pictured on two pages is one element; another element named "Main" is a second.
let frames = [(3, "Inset".to_string()), (1, "Main".to_string()), (1, "Main".to_string()), (7, "Main".to_string())];
crate::cmd::layout::pictured_notices(&mut s, &frames, &[2, 5]);
let said: Vec<&str> = s.notices_since(mark).iter().map(|n| n.text.as_str()).collect();
assert_eq!(said.len(), 2, "one notice for each kind: {said:?}");
// Each frame once, however many pages it was pictured on.
assert!(said[0].starts_with("The PDF draws 2 map frames as pictures") && said[0].ends_with("(Inset, Main)"), "{}", said[0]);
assert!(said[1].starts_with("The PDF draws 2 pages as pictures") && said[1].ends_with("(page 2, 5)"), "{}", said[1]);
assert!(
said[0].starts_with("The export draws 3 layout elements as pictures") && said[0].ends_with("(Main, Inset, Main)"),
"{}",
said[0]
);
assert!(said[1].starts_with("The export draws 2 pages as pictures") && said[1].ends_with("(page 2, 5)"), "{}", said[1]);
let mark = s.notice_mark();
crate::cmd::layout::pictured_notices(&mut s, &[], &(1..=25).collect::<Vec<_>>());
assert!(
Expand Down
46 changes: 36 additions & 10 deletions crates/render/src/layout.rs
Original file line number Diff line number Diff line change
Expand Up @@ -61,10 +61,15 @@ pub fn render(layout: &Layout, maps: &mut [Map], dpi: f64, info: &PageInfo) -> O
/// [`render`] kept as vectors (for a vector PDF): text, shapes, surrounds and flat, north-up map
/// frames as paths and glyphs, what is pixels by nature (rasters, tiles, pictures, a tilted or
/// globe frame) as pictures drawn at `dpi`, in the drawing's pixels at that resolution. With it,
/// the names of the frames drawn as pictures because their vectors passed
/// the frames (id and name) drawn as pictures because their vectors passed
/// [`crate::vector::MAX_COST`]. A drawing that overflowed all the same (its surrounds) is
/// incomplete: [`crate::vector::Drawing::overflowed`] says so.
pub fn render_drawing(layout: &Layout, maps: &mut [Map], dpi: f64, info: &PageInfo) -> Option<(crate::vector::Drawing, Vec<String>)> {
pub fn render_drawing(
layout: &Layout,
maps: &mut [Map],
dpi: f64,
info: &PageInfo,
) -> Option<(crate::vector::Drawing, Vec<(u32, String)>)> {
let (w, h, k) = page_geometry(layout, dpi);
let bounds = tiny_skia::IntRect::from_xywh(0, 0, w, h)?;
let mut pictured = Vec::new();
Expand All @@ -84,17 +89,38 @@ pub(crate) fn page_geometry(layout: &Layout, dpi: f64) -> (u32, u32, f64) {
/// One element on transparency, allocating only its on-page pixel bounds.
/// Outer `None` means rendering failed; inner `None` means the element is off-page.
pub(crate) fn render_element(layout: &Layout, id: u32, maps: &mut [Map], dpi: f64, info: &PageInfo) -> Option<Option<(Pixmap, [f64; 4])>> {
let Some((bounds, k, mm)) = element_bounds(layout, id, dpi)? else { return Some(None) };
let pm = draw_page(layout, maps, info, k, bounds, Some(id), None)?.into_pixmap();
Some(Some((pm, mm)))
}

/// [`render_element`] kept as vectors (see [`render_drawing`]): the element alone, recorded in
/// the pixels of its on-page bounds at `dpi`, those bounds in millimetres, and the pixels a
/// millimetre. The frames drawn as pictures (past the budget) go to `pictured`.
pub(crate) fn record_element(
layout: &Layout,
id: u32,
maps: &mut [Map],
dpi: f64,
info: &PageInfo,
pictured: &mut Vec<(u32, String)>,
) -> Option<Option<(crate::vector::Drawing, [f64; 4], f64)>> {
let Some((bounds, k, mm)) = element_bounds(layout, id, dpi)? else { return Some(None) };
let drawing = draw_page(layout, maps, info, k, bounds, Some(id), Some(pictured))?.into_drawing()?;
Some(Some((drawing, mm, k)))
}

/// Element `id`'s on-page bounds in whole pixels at `dpi`, the pixels a millimetre, and the bounds
/// in millimetres; inner `None` for an element off the page.
fn element_bounds(layout: &Layout, id: u32, dpi: f64) -> Option<Option<(tiny_skia::IntRect, f64, [f64; 4])>> {
let e = layout.element(id)?;
let (w, h, k) = page_geometry(layout, dpi);
let x0 = (e.x * k).floor().clamp(0.0, f64::from(w));
let y0 = (e.y * k).floor().clamp(0.0, f64::from(h));
let x1 = ((e.x + e.w) * k).ceil().clamp(0.0, f64::from(w));
let y1 = ((e.y + e.h) * k).ceil().clamp(0.0, f64::from(h));
let Some(bounds) = tiny_skia::IntRect::from_xywh(x0 as i32, y0 as i32, (x1 - x0) as u32, (y1 - y0) as u32) else {
return Some(None);
};
let pm = draw_page(layout, maps, info, k, bounds, Some(id), None)?.into_pixmap();
Some(Some((pm, [x0 / k, y0 / k, (x1 - x0) / k, (y1 - y0) / k])))
let bounds = tiny_skia::IntRect::from_xywh(x0 as i32, y0 as i32, (x1 - x0) as u32, (y1 - y0) as u32);
Some(bounds.map(|b| (b, k, [x0 / k, y0 / k, (x1 - x0) / k, (y1 - y0) / k])))
}

/// Draws the selected region with the full layout's frame and dynamic-text context, recorded
Expand All @@ -107,7 +133,7 @@ fn draw_page(
k: f64,
bounds: tiny_skia::IntRect,
element: Option<u32>,
mut record: Option<&mut Vec<String>>,
mut record: Option<&mut Vec<(u32, String)>>,
) -> Option<Canvas> {
let ppp = k / PT_PER_MM;
let mut pm =
Expand Down Expand Up @@ -178,7 +204,7 @@ fn draw_page(
{
frame_pm = pixels;
if let Some(list) = record.as_deref_mut() {
list.push(e.name.clone());
list.push((e.id, e.name.clone()));
}
}
if let Some(g) = grid {
Expand Down Expand Up @@ -1986,7 +2012,7 @@ mod tests {
let result = render_drawing(&layout, &mut maps, 72.0, &PageInfo::default());
TEST_MAX_COST.with(|l| l.set(None));
let (drawing, pictured) = result.unwrap();
assert_eq!(pictured, ["World"]);
assert_eq!(pictured.iter().map(|p| p.1.as_str()).collect::<Vec<_>>(), ["World"]);
let (_, _, items) = drawing.finish();
assert!(items.iter().any(|i| matches!(i, Item::Image(_))), "the frame as a picture");
}
Expand Down
2 changes: 1 addition & 1 deletion crates/render/src/report.rs
Original file line number Diff line number Diff line change
Expand Up @@ -288,7 +288,7 @@ pub fn pdf_page(
dpi: f64,
layouts: &[Layout],
maps: &mut [Map],
) -> Option<(crate::pdf::Page, Vec<String>)> {
) -> Option<(crate::pdf::Page, Vec<(u32, String)>)> {
let page = pages.get(n)?;
let dpi = if dpi.is_finite() { dpi.clamp(24.0, 600.0) } else { 96.0 };
if let Page::Layout(li) = page {
Expand Down
Loading
Loading