diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 3f7af2d76e..5585b83a21 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -14,7 +14,7 @@ use crate::{CmdResult, CommandSpec as C, Session}; pub fn commands() -> Vec { vec![ C::new("project.importQgis", "Import QGIS Project", "Project › Import", import_project).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Reserved).with(crate::policy::Effect::Files).with(crate::policy::Effect::Network)).params( - r#"{"path"?: "*.qgs|*.qgz", "text"?: "a .qgs file's text", "data"?: "a .qgs or .qgz file, base64", "dir"?: "the folder its relative paths start from (default: the file's)"} → the layers added and notes on what wasn't carried over"#, + r#"{"path"?: "*.qgs|*.qgz", "text"?: "a .qgs file's text", "data"?: "a .qgs or .qgz file, base64", "dir"?: "the folder its relative paths start from (default: the file's)"} → the map, the layers added, the print layouts added (`layouts`, when any) and notes on what wasn't carried over"#, ), C::new("style.importQgis", "Import QGIS Style", "Style › Styles", import_style).roles(&[]).effects(crate::policy::Effects::NONE.with(crate::policy::Effect::Files)).when(need_layer).params( r#"{"layer"?, "path"?: "*.qml", "text"?: "a .qml file's text", "data"?: "a .qml file, base64"} → notes on what wasn't carried over"#, @@ -218,7 +218,9 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { let parsed = super::reads::take::(s, PARSED); #[cfg(target_arch = "wasm32")] let parsed: Option = None; - let Parsed { project, mut report } = match parsed { + // On the copy, its layouts keep their names: they are numbered where they land. + let on_copy = parsed.is_some(); + let Parsed { mut project, mut report } = match parsed { Some(parsed) => parsed, None => parse(p)?, }; @@ -226,8 +228,9 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { // skipped image, and no layer is added for a cancelled run. rustgis_data::progress::check().map_err(|e| e.to_string())?; // A map of its own, named as the project. - let name = map_name(&project); - s.run_part("map.new", &json!({"name": name}))?; + s.run_part("map.new", &json!({"name": map_name(&project)}))?; + // Numbered when a map has the project's name already, as the answer says. + let name = s.map().name.clone(); // QGIS draws a project on its canvas alone: no basemap, no graticule. let m = s.map_mut(); m.basemap = rustgis_map::Basemap::Blank; @@ -347,6 +350,7 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { add_relations(s, &project, &came_in, &mut report); go_to_view(s, &project, degrees); add_bookmarks(s, &project, &mut report); + let layouts = add_layouts(s, &mut project, dir.as_deref(), &mut pictures, &mut report, !on_copy)?; let notes: Vec = report.notes.iter().map(note_json).collect(); if !report.notes.is_empty() { let left = report.notes.iter().filter(|n| n.kind == NoteKind::Skipped).count(); @@ -361,7 +365,11 @@ fn import_project(s: &mut Session, p: &Value) -> CmdResult { ); } notify_report(s, &report); - Ok(json!({"map": name, "layers": added, "notes": notes})) + let mut answer = json!({"map": name, "layers": added, "notes": notes}); + if !layouts.is_empty() { + answer["layouts"] = json!(layouts); + } + Ok(answer) } /// What one of a project's layers came in as. @@ -1100,7 +1108,7 @@ fn add_annotations( Some(read) => Some(read.clone()), None => { let read = match checked_annotation_picture(picture, dir) { - Err(why) => Err(format!("{picture}: {why}")), + Err(why) => Err(format!("{}: {why}", qgis::picture_named(picture))), Ok(source) => { // Its size first, from its text or its file's length (base64 is 4 bytes for 3): // one that can't fit isn't read. @@ -1257,6 +1265,296 @@ fn add_annotations( Ok((l.name.clone(), drawn)) } +/// Adds the project's print layouts ([`qgis::ProjectLayout`]), each named as QGIS names it (a +/// name a layout has is numbered): its map frames showing the map the import made (`s`'s +/// active one), each placed where its QGIS map item's extent is, in the item's coordinate system +/// (else the project's), and its pictures read from their files within the import's picture +/// budget (`pictures`). A frame that can't be placed shows the map's view; a picture that can't +/// be read is left out; both noted, as are layouts past the project's limit. Their names, in +/// order. +/// +/// On the thread that runs the import. Its work is bounded: at most [`qgis::MAX_LAYOUTS`] layouts +/// of at most 500 elements, their coordinate systems parsed once each (at most +/// [`MAX_BOOKMARK_CRS`]), and their pictures within [`MAX_PICTURE_BYTES`], each use of a file +/// read and counted. Cancel is looked at before each layout and each picture. The layouts are +/// taken out of `project`; each is named as the QGIS page, `number`ed when a layout has the name. +fn add_layouts( + s: &mut Session, + project: &mut qgis::Project, + dir: Option<&str>, + pictures: &mut Pictures, + report: &mut Report, + number: bool, +) -> Result, String> { + let mut names = Vec::new(); + let read_layouts = std::mem::take(&mut project.layouts); + if read_layouts.is_empty() { + return Ok(names); + } + let map = s.map().name.clone(); + let (mut unplaced, mut over, mut too_many, mut unread, mut past_failed) = (0usize, 0usize, 0usize, 0usize, 0usize); + let mut repairs = rustgis_map::layout::LayoutRepairs::default(); + let (mut scaled, mut cut_names) = (0usize, 0usize); + // What the pictures that came in are drawn as otherwise than QGIS draws them, kind by kind. + let mut picture_notes: Vec<(&'static str, usize)> = Vec::new(); + let mut first_error: Option = None; + let mut transformers: std::collections::HashMap> = + std::collections::HashMap::new(); + let (w, _) = s.view_size; + let view = (s.map().center_lonlat(), s.map().ground_res() * w); + for read in read_layouts { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + // At most what a project holds: counted against this project's layouts, or, on a copy + // of it, against the layouts made, since the project they land in is counted at landing + // (one deleted meanwhile leaves room). + let held = if number { s.project.layouts.len() } else { names.len() }; + if held >= crate::project::MAX_LAYOUTS { + too_many += 1; + continue; + } + let mut layout = read.layout; + for f in &read.frames { + let crs = f.crs.as_deref().or(project.crs.as_deref()); + let t = crs.and_then(|crs| { + if !transformers.contains_key(crs) && transformers.len() >= MAX_BOOKMARK_CRS { + return None; + } + transformers + .entry(crs.to_string()) + .or_insert_with(|| rustgis_data::raster::crs::Crs::parse(crs).and_then(|c| c.transformer()).ok()) + .clone() + }); + let Some(e) = layout.element_mut(f.element) else { continue }; + let placed = t.as_ref().and_then(|t| frame_place(s.map(), t, f.extent, e.w)); + if placed.is_none() { + unplaced += 1; + } + let (c, scale) = placed.unwrap_or_else(|| { + let (c, ground_w) = view; + (c, ground_w / (e.w.max(1.0) / 1000.0)) + }); + let kept = scale.clamp(rustgis_map::layout::MIN_FRAME_SCALE, rustgis_map::layout::MAX_FRAME_SCALE); + // A placed frame whose scale a frame can't take shows less or more than QGIS's item. + scaled += usize::from(placed.is_some() && kept != scale); + if let rustgis_map::layout::ElementKind::MapFrame { map: m, center, scale: sc, .. } = &mut e.kind { + m.clone_from(&map); + *center = c; + *sc = kept; + } + } + for p in &read.pictures { + rustgis_data::progress::check().map_err(|e| e.to_string())?; + let untried = pictures.untried; + match layout_picture(pictures, &p.source, dir) { + Some(Ok(b64)) => { + if let Some(e) = layout.element_mut(p.element) { + let source = (!p.source.starts_with("base64:")).then(|| p.source.clone()); + e.kind = rustgis_map::layout::ElementKind::Picture { image: b64, source }; + for note in &p.notes { + match picture_notes.iter_mut().find(|(n, _)| n == note) { + Some((_, count)) => *count += 1, + None => picture_notes.push((note, 1)), + } + } + } + } + Some(Err(e)) => { + unread += 1; + first_error.get_or_insert(e); + layout.remove(p.element); + } + None => { + if pictures.untried > untried { + past_failed += 1; + } else { + over += 1; + } + layout.remove(p.element); + } + } + } + if number { + let (named, cut) = layout_named(&layout.name, |n| s.project.layouts.iter().any(|l| l.name.eq_ignore_ascii_case(n))); + layout.name = named; + cut_names += usize::from(cut); + } + // Within what a layout keeps (its page, its elements' sizes and texts): what changed is said. + let r = layout.clamp(); + repairs.elements_adjusted += r.elements_adjusted; + repairs.elements_cut += r.elements_cut; + repairs.elements_removed += r.elements_removed; + repairs.page_adjusted += r.page_adjusted; + names.push(layout.name.clone()); + s.project.layouts.push(layout); + } + if unplaced > 0 { + report.approximated( + "", + format!("its print layouts' map items whose extent can't be placed on the map, showing the map's view ({unplaced})"), + ); + } + if let Some(e) = first_error { + report.skipped("", format!("its print layouts' pictures that don't read ({unread}; the first: {e})")); + } + for (note, n) in picture_notes { + report.approximated("", format!("its print layouts' {note} ({n})")); + } + if over > 0 { + report.skipped( + "", + format!("its print layouts' pictures past the {} of pictures an import takes ({over})", size_text(MAX_PICTURE_BYTES)), + ); + } + if past_failed > 0 { + report.skipped( + "", + format!( + "its print layouts' pictures not read, past the {} of pictures that don't read an import tries ({past_failed})", + size_text(MAX_PICTURE_BYTES) + ), + ); + } + if too_many > 0 { + report.skipped("", format!("its print layouts past the {} a project holds ({too_many})", crate::project::MAX_LAYOUTS)); + } + if cut_names > 0 { + report.approximated("", names_cut(cut_names)); + } + let brought = [ + (scaled, "map items whose scale was brought within a frame's range (2:1 to 1:10,000,000,000)"), + (repairs.page_adjusted, "pages or papers brought within what a layout takes (20 mm to 5 m a side, an opaque paper)"), + (repairs.elements_adjusted, "elements whose sizes or settings were brought within a layout's limits"), + (repairs.elements_cut, "elements whose names or texts were cut to a layout's limits"), + ]; + for (n, what) in brought { + if n > 0 { + report.approximated("", format!("its print layouts' {what} ({n})")); + } + } + if repairs.elements_removed > 0 { + report.skipped("", format!("its print layouts' elements past what a layout holds ({})", repairs.elements_removed)); + } + Ok(names) +} + +/// `name` numbered as [`super::numbered`] numbers a name `taken` (`Plan 2`), a page's number kept +/// whole (`Plan (page 2) 2`, the name cut before it to fit); and whether the number cut it. +fn layout_named(name: &str, taken: impl Fn(&str) -> bool) -> (String, bool) { + if !taken(name) { + return (name.to_string(), false); + } + let page_number = |i: usize| { + name.ends_with(')') && name.get(i + 7..name.len() - 1).is_some_and(|d| !d.is_empty() && d.chars().all(|c| c.is_ascii_digit())) + }; + // A page's number too long to leave room for any of the name is no page's number to keep. + let (base, page) = match name.rfind(" (page ") { + Some(i) if page_number(i) && name.len() - i < super::MAX_NAME / 2 => name.split_at(i), + _ => (name, ""), + }; + let mut k = 1u64; + loop { + k += 1; + let suffix = format!("{page} {k}"); + let room = super::MAX_NAME.saturating_sub(suffix.chars().count()); + let kept: String = base.chars().take(room).collect(); + let candidate = format!("{}{suffix}", kept.trim_end()); + if !taken(&candidate) { + return (candidate, kept.chars().count() < base.chars().count()); + } + } +} + +/// The note for `n` layout names cut to fit the number telling them apart. +fn names_cut(n: usize) -> String { + format!("its print layouts' names cut to fit the number telling them from a layout of that name ({n})") +} + +/// The centre (longitude/latitude) and scale at which a frame `w_mm` wide shows `extent` (in the +/// coordinate system `t` reads) on `m`: its corners and centre taken to the map's flat +/// projection, the frame as wide as their extent there. `None` where they don't all take. +fn frame_place(m: &rustgis_map::Map, t: &rustgis_data::raster::crs::Transformer, extent: [f64; 4], w_mm: f64) -> Option<(Coord, f64)> { + let [x0, y0, x1, y1] = extent; + let flat = m.flat(); + let mut e = Extent::EMPTY; + for (x, y) in [(x0, y0), (x1, y0), (x1, y1), (x0, y1), ((x0 + x1) / 2.0, (y0 + y1) / 2.0)] { + let ll = t.to_lonlat(Coord::new(x, y)).filter(|c| c.x.is_finite() && c.y.is_finite() && c.y.abs() <= 90.0)?; + let p = flat.forward_checked(ll)?; + e.expand(p); + } + if e.is_empty() || e.width() <= 0.0 || w_mm <= 0.0 { + return None; + } + let center = flat.inverse(e.center())?; + let per = (flat.ground_per_unit(e.center()) * m.body().ratio()).max(1e-9); + let scale = e.width() * per / (w_mm / 1000.0); + scale.is_finite().then_some((center, scale)) +} + +/// A layout picture's image (base64), read for each use within the import's picture budget (a +/// failed read is kept, not tried again): +/// `None` past the budget, an error where it doesn't read. +fn layout_picture(pictures: &mut Pictures, picture: &str, dir: Option<&str>) -> Option> { + let left = MAX_PICTURE_BYTES.saturating_sub(pictures.bytes); + // An inline picture is its own text: never copied into the caches, nor hashed to look it up. + let inline = picture.starts_with("base64:"); + if inline && picture.len() - "base64:".len() > left { + return None; + } + if !inline && pictures.over.contains(picture) { + return None; + } + let cached = if inline { None } else { pictures.read.get(picture) }; + // Reads that failed are bounded too: past [`MAX_PICTURE_BYTES`] of them, a picture not yet + // read isn't tried (`None`, counted in `untried`). + if cached.is_none() && pictures.failed >= MAX_PICTURE_BYTES { + pictures.untried += 1; + return None; + } + let read = match cached { + Some(read) => read.clone(), + None => { + // The image, and the bytes reading it takes (a file's, or the inline text's). + let (read, tried) = match checked_annotation_picture(picture, dir) { + Err(why) => (Err(format!("{}: {why}", qgis::picture_named(picture))), 0), + Ok(qgis::ImageSource::Base64) => { + (super::graphics::picture(&json!({"image": picture.strip_prefix("base64:").unwrap_or_default()})), picture.len()) + } + Ok(qgis::ImageSource::File(path)) => { + let len = std::fs::metadata(&path).ok().map(|m| usize::try_from(m.len()).unwrap_or(usize::MAX)); + // Its size first, from its length (base64 is 4 bytes for 3): one that can't fit isn't read. + if len.is_some_and(|len| len.div_ceil(3).saturating_mul(4) > left) { + pictures.over.insert(picture.to_string()); + return None; + } + (super::graphics::picture(&json!({"path": path})), len.unwrap_or(0)) + } + }; + // Only a failure is kept for the next use: an image read is held by its element, and + // read again for another (a second copy here would outlive the import's budget). + if read.is_err() { + pictures.failed = pictures.failed.saturating_add(tried); + if !inline { + pictures.read.insert(picture.to_string(), read.clone()); + } + } + read + } + }; + match read { + Ok(b64) if b64.len() > left => { + if !inline { + pictures.over.insert(picture.to_string()); + } + None + } + Ok(b64) => { + pictures.bytes += b64.len(); + Some(Ok(b64)) + } + Err(e) => Some(Err(e)), + } +} + /// The most bytes of pictures (base64) one import adds to graphics layers (in tests, a few /// small pictures'). const MAX_PICTURE_BYTES: usize = if cfg!(test) { 1 << 10 } else { 64 << 20 }; @@ -1275,6 +1573,10 @@ struct Pictures { /// Those read that didn't fit what was left of the budget, not kept. over: std::collections::HashSet, bytes: usize, + /// The bytes of the pictures that were read and didn't read as an image. + failed: usize, + /// Uses of pictures not tried, past [`MAX_PICTURE_BYTES`] of failed reads. + untried: usize, } /// The box `rect` (a rectangle's polygon) shrunk to a picture's aspect (`size`: its width and @@ -2195,6 +2497,8 @@ struct Imported { /// A tile archive's framing still waiting for its bounds, on the map made. style_view: Option<(rustgis_map::TileLayer, rustgis_map::Camera, u64)>, made: Vec<(String, String, String)>, + /// The print layouts it added, their map frames showing its map by its name on the copy. + layouts: Vec, answer: Value, } @@ -2319,6 +2623,7 @@ pub(crate) fn import_ahead(s: &mut Session, p: &Value, native: bool) -> Option = copy.project.tables.iter().map(|t| t.id).collect(); + let layouts = copy.project.layouts.len(); // The copy imports the project as parsed already, reading nothing of it again: the files // read for it are its inputs too. rustgis_data::provenance::record(inputs); @@ -2337,7 +2642,8 @@ pub(crate) fn import_ahead(s: &mut Session, p: &Value, native: bool) -> Option CmdResult { s.project.add_table(table); } let mut map = imported.map; + let copied_name = map.name.clone(); // Named as `map.new` names one here: for the project, unless a map has that name. let mut name = imported.base.clone(); let mut i = 1; @@ -2429,6 +2736,56 @@ fn land_import(s: &mut Session, ahead: ImportAhead) -> CmdResult { crate::service_logins::release_held(s, &ahead.held); let mut answer = imported.answer; answer["map"] = json!(name); + // Its layouts, named as the QGIS pages (numbered here, against this project's layouts), their + // frames showing the map by its name here. + let mut layouts = Vec::new(); + let (mut too_many, mut cut_names) = (0usize, 0usize); + for mut layout in imported.layouts { + if s.project.layouts.len() >= crate::project::MAX_LAYOUTS { + too_many += 1; + continue; + } + let (named, cut) = layout_named(&layout.name, |n| s.project.layouts.iter().any(|l| l.name.eq_ignore_ascii_case(n))); + layout.name = named; + cut_names += usize::from(cut); + for e in &mut layout.elements { + if let rustgis_map::layout::ElementKind::MapFrame { map: m, .. } = &mut e.kind + && m.eq_ignore_ascii_case(&copied_name) + { + m.clone_from(&name); + } + } + layouts.push(layout.name.clone()); + s.project.layouts.push(layout); + } + if too_many > 0 { + let said = + format!("{too_many} of the QGIS project's print layouts left out: a project holds at most {}", crate::project::MAX_LAYOUTS); + // The import is usable: what fitted landed, as its other losses are said. + s.notify(said, false); + // In the answer's notes too, as the import's own are. + let mut left = Report::default(); + left.skipped("", format!("its print layouts past the {} a project holds ({too_many})", crate::project::MAX_LAYOUTS)); + if let Some(notes) = answer.get_mut("notes").and_then(Value::as_array_mut) { + notes.extend(left.notes.iter().map(note_json)); + } + } + if cut_names > 0 { + s.notify(format!("{cut_names} of the QGIS project's print layout names cut to fit the number telling them apart"), false); + let mut cut = Report::default(); + cut.approximated("", names_cut(cut_names)); + if let Some(notes) = answer.get_mut("notes").and_then(Value::as_array_mut) { + notes.extend(cut.notes.iter().map(note_json)); + } + } + // The copy's names, or none where none came in here. + if layouts.is_empty() { + if let Some(a) = answer.as_object_mut() { + a.remove("layouts"); + } + } else { + answer["layouts"] = json!(layouts); + } Ok(answer) } @@ -2511,6 +2868,148 @@ fn import_style(s: &mut Session, p: &Value) -> CmdResult { mod tests { use super::*; + /// A layout picture read is held by its element, not kept again for the import: each use + /// reads and counts its own; a failure is kept, not read again. + #[test] + fn a_numbered_layout_name_stays_within_a_name() { + // A page's number too long to keep: the name numbered as any, within a name's characters. + let name = format!("x (page {})", "9".repeat(191)); + let (named, cut) = layout_named(&name, |n| n == name); + assert!(named.chars().count() == super::super::MAX_NAME && named.starts_with("x (page") && named.ends_with(" 2"), "{named}"); + assert!(cut); + let (named, cut) = layout_named("Plan (page 2)", |n| n == "Plan (page 2)"); + assert_eq!((named.as_str(), cut), ("Plan (page 2) 2", false)); + } + + #[test] + fn layout_pictures_keep_no_second_copy() { + let png = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../map/testdata/qgis/generated/data/picture.png"); + let png = png.display().to_string(); + let mut pictures = Pictures::default(); + let first = layout_picture(&mut pictures, &png, None).unwrap().unwrap(); + assert!(pictures.read.is_empty()); + assert_eq!(pictures.bytes, first.len()); + layout_picture(&mut pictures, &png, None).unwrap().unwrap(); + assert_eq!(pictures.bytes, 2 * first.len()); + let missing = "/no/such/picture.png"; + assert!(layout_picture(&mut pictures, missing, None).unwrap().is_err()); + assert!(pictures.read.get(missing).is_some_and(Result::is_err)); + } + + /// Pictures that don't read are bounded too: past the budget of failed reads, the next + /// distinct file isn't read, and that is said. + #[test] + fn failed_picture_reads_are_bounded() { + let dir = std::env::temp_dir().join(format!("rustgis-failed-pictures-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let mut pictures = Pictures::default(); + let mut project = qgis::Project::default(); + let mut layout = rustgis_map::layout::Layout::new("P".to_string(), 210.0, 297.0); + let mut list = Vec::new(); + for i in 0..4 { + let path = dir.join(format!("bad{i}.png")); + std::fs::write(&path, vec![b'x'; 600]).unwrap(); + let element = layout.add( + format!("Picture {i}"), + (1.0, 1.0, 5.0, 5.0), + rustgis_map::layout::ElementKind::Picture { image: String::new(), source: None }, + ); + list.push(qgis::LayoutPicture { element, source: path.display().to_string(), notes: Vec::new() }); + } + project.layouts.push(qgis::ProjectLayout { layout, frames: Vec::new(), pictures: list }); + let mut s = Session::new(crate::Project::default()); + let mut report = Report::default(); + add_layouts(&mut s, &mut project, None, &mut pictures, &mut report, true).unwrap(); + std::fs::remove_dir_all(&dir).ok(); + // 600 bytes each: two are read (1,200 bytes, past the 1 KiB of tests), two aren't. + assert_eq!(pictures.failed, 1200); + assert_eq!(pictures.untried, 2); + let said = |part: &str| report.notes.iter().any(|n| n.text.contains(part)); + assert!(said("that don't read an import tries (2)"), "{:?}", report.notes); + assert!(said("pictures that don't read (2;"), "{:?}", report.notes); + } + + /// An inline picture is read from its own text, never kept in the caches; one past the budget + /// isn't read. + #[test] + fn inline_layout_pictures_are_never_cached() { + use base64::Engine as _; + let png = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../map/testdata/qgis/generated/data/picture.png"); + let inline = format!("base64:{}", base64::engine::general_purpose::STANDARD.encode(std::fs::read(png).unwrap())); + let mut pictures = Pictures::default(); + assert!(layout_picture(&mut pictures, &inline, None).unwrap().is_ok()); + assert!(pictures.read.is_empty() && pictures.over.is_empty()); + let big = format!("base64:{}", "A".repeat(MAX_PICTURE_BYTES + 4)); + assert!(layout_picture(&mut pictures, &big, None).is_none()); + assert!(pictures.read.is_empty() && pictures.over.is_empty()); + } + + /// A picture's notes are said only when it comes in: a turned picture whose file doesn't read + /// is left out and says nothing else; one that reads says it. A refused picture's note names + /// its file, not its folder. + #[test] + fn a_pictures_notes_are_said_only_when_it_comes_in() { + let png = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../map/testdata/qgis/generated/data/picture.png"); + let turned = "turned pictures, drawn upright"; + for (source, comes_in) in [(png.display().to_string(), true), ("/home/someone/no/such/x.png".to_string(), false)] { + let mut layout = rustgis_map::layout::Layout::new("P".to_string(), 210.0, 297.0); + let element = layout.add( + "Picture".to_string(), + (1.0, 1.0, 5.0, 5.0), + rustgis_map::layout::ElementKind::Picture { image: String::new(), source: None }, + ); + let mut project = qgis::Project::default(); + project.layouts.push(qgis::ProjectLayout { + layout, + frames: Vec::new(), + pictures: vec![qgis::LayoutPicture { element, source, notes: vec![turned] }], + }); + let mut s = Session::new(crate::Project::default()); + let mut report = Report::default(); + add_layouts(&mut s, &mut project, None, &mut Pictures::default(), &mut report, true).unwrap(); + let said = |part: &str| report.notes.iter().any(|n| n.text.contains(part)); + assert_eq!(said(&format!("{turned} (1)")), comes_in, "{:?}", report.notes); + assert!(!said("someone"), "{:?}", report.notes); + assert_eq!(said("x.png: "), !comes_in, "{:?}", report.notes); + } + } + + /// On a copy of a full project, the layouts are made anyway (bounded by what a project + /// holds): the project they land in is counted at landing. + #[test] + fn layouts_made_on_a_full_copy_wait_for_landing() { + let mut project = crate::Project::default(); + for i in 0..crate::project::MAX_LAYOUTS { + project.layouts.push(rustgis_map::layout::Layout::new(format!("L{i}"), 210.0, 297.0)); + } + let mut s = Session::new(project); + let mut read = qgis::Project::default(); + for i in 0..crate::project::MAX_LAYOUTS + 1 { + read.layouts.push(qgis::ProjectLayout { + layout: rustgis_map::layout::Layout::new(format!("Q{i}"), 210.0, 297.0), + frames: Vec::new(), + pictures: Vec::new(), + }); + } + let mut report = Report::default(); + let names = add_layouts(&mut s, &mut read, None, &mut Pictures::default(), &mut report, false).unwrap(); + assert_eq!(names.len(), crate::project::MAX_LAYOUTS); + let note = format!("its print layouts past the {} a project holds (1)", crate::project::MAX_LAYOUTS); + assert!(report.notes.iter().any(|n| n.text.contains(¬e)), "{:?}", report.notes); + // In the project itself, those past what it holds are left out there. + let mut report = Report::default(); + let mut again = qgis::Project::default(); + again.layouts.push(qgis::ProjectLayout { + layout: rustgis_map::layout::Layout::new("R".to_string(), 210.0, 297.0), + frames: Vec::new(), + pictures: Vec::new(), + }); + let mut s = Session::new(crate::Project::default()); + s.project.layouts = + (0..crate::project::MAX_LAYOUTS).map(|i| rustgis_map::layout::Layout::new(format!("L{i}"), 210.0, 297.0)).collect(); + assert!(add_layouts(&mut s, &mut again, None, &mut Pictures::default(), &mut report, true).unwrap().is_empty()); + } + #[test] fn add_annotations_refuses_unsafe_picture_paths_defensively() { let mut s = Session::new(crate::Project::default()); diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index d5e17b9e72..b40f50c9a2 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -5516,7 +5516,9 @@ fn qgis_import_codes_only_the_notes_that_lose_data() { layer("Arcs", "memory", "CompoundCurve?crs=EPSG:4326&field=a:string"), ] .concat(); - let text = format!(r#"{layers}"#); + let text = format!( + r#"{layers}"# + ); let mark = s.notice_mark(); let result = s.run("project.importQgis", &json!({"text": text})).unwrap(); let notes = result["notes"].as_array().unwrap(); @@ -5528,7 +5530,7 @@ fn qgis_import_codes_only_the_notes_that_lose_data() { // A memory layer opens empty, so its Z values and curves held no data: plain. assert_eq!(json_loss("Heights", "Z and M"), Some(None)); assert_eq!(json_loss("Arcs", "curves read as lines"), Some(None)); - assert_eq!(json_loss("", "print layouts"), Some(None), "a layout is drawing, not data: no code"); + assert_eq!(json_loss("", "print layouts' legends"), Some(None), "a layout is drawing, not data: no code"); let said = s.notices_since(mark); let with = |code| said.iter().filter(|n| n.loss() == Some(code)).collect::>(); assert!(with(LossCode::DroppedFeature)[0].text.contains("Unsupported"), "{said:?}"); @@ -44662,6 +44664,7 @@ mod ogc_server; mod ogc_dataset; mod qgis_import_ahead; +mod qgis_layouts; mod qgis_services; #[path = "../../../tests/support/esripbf.rs"] diff --git a/crates/engine/src/tests/cancellation.rs b/crates/engine/src/tests/cancellation.rs index c02f322faf..9d9c7232ca 100644 --- a/crates/engine/src/tests/cancellation.rs +++ b/crates/engine/src/tests/cancellation.rs @@ -302,7 +302,9 @@ pub(super) fn long_commands(boundaries: bool) { Place./place.geojsonPlaceogr Tablefile:./place.csv?type=csv&xField=x&yField=yTabledelimitedtext - "#; + + + "#; std::fs::write(out("import.qgs"), project).unwrap(); read(&s, "project.importQgis", &json!({"path": out("import.qgs")})); diff --git a/crates/engine/src/tests/qgis_layouts.rs b/crates/engine/src/tests/qgis_layouts.rs new file mode 100644 index 0000000000..abf209c2f4 --- /dev/null +++ b/crates/engine/src/tests/qgis_layouts.rs @@ -0,0 +1,219 @@ +//! A QGIS project's print layouts imported as layouts of the project (piece 12a of #882): their +//! map frames showing the map the import makes, where QGIS's map items show it; their pictures +//! read; Undo taking them away with the map; and the same from an import run on a copy. + +use super::{Project, Session}; +use rustgis_analysis::control::Control; +use rustgis_map::layout::ElementKind; +use serde_json::json; + +fn sheets() -> serde_json::Value { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("../map/testdata/qgis/generated/qgs/layout-sheets.qgs"); + json!({"path": path.display().to_string()}) +} + +/// The A4 sheet's map frame: the map it shows, its centre and scale. +fn frame(s: &Session, layout: &str) -> (String, rustgis_geom::Coord, f64, f64) { + let l = s.project.layouts.iter().find(|l| l.name == layout).unwrap(); + l.elements + .iter() + .find_map(|e| match &e.kind { + ElementKind::MapFrame { map, center, scale, bearing, .. } => Some((map.clone(), *center, *scale, *bearing)), + _ => None, + }) + .unwrap() +} + +#[test] +fn a_qgis_projects_layouts_come_in_showing_its_map() { + let mut s = Session::new(Project::default()); + let layouts = s.project.layouts.len(); + let answer = s.run("project.importQgis", &sheets()).unwrap(); + assert_eq!(answer["layouts"], json!(["Sheet A4", "Sheet A4 (page 2)", "Sheet Letter"])); + assert_eq!(s.project.layouts.len(), layouts + 3); + // Within a layout's limits as read: nothing brought within them. + let notes = answer["notes"].as_array().unwrap(); + assert!( + !notes.iter().any(|n| n["text"].as_str().is_some_and(|t| t.contains("brought within") || t.contains("past what a layout holds"))), + "{notes:?}" + ); + let (map, center, scale, bearing) = frame(&s, "Sheet A4"); + assert_eq!(map, "Sheets"); + // The item shows 1,700 m of LV95 across 200 mm: 1:8,500, centred on its extent's centre. + let back = rustgis_data::raster::crs::Crs::parse("EPSG:2056") + .unwrap() + .transformer() + .unwrap() + .to_lonlat(rustgis_geom::Coord::new(2697150.0, 1261837.5)) + .unwrap(); + assert!((center.x - back.x).abs() < 1e-6 && (center.y - back.y).abs() < 1e-6, "{center:?} {back:?}"); + // 1:8,500 on LV95's grid; the frame shows the same 1,700 m of it across its 200 mm. + let m = s.project.maps.iter().find(|m| m.name == "Sheets").unwrap(); + let cam = rustgis_map::layout::frame_camera(m, center, scale, 0.0, 0.0); + let across = cam.res * 200.0 * rustgis_map::layout::PT_PER_MM; + assert!((across - 1700.0).abs() < 1e-3, "{across} ({scale})"); + assert!((bearing + 10.0).abs() < 1e-9); + // Its picture read from its file. + let a4 = s.project.layouts.iter().find(|l| l.name == "Sheet A4").unwrap(); + let picture = a4.elements.iter().find_map(|e| match &e.kind { + ElementKind::Picture { image, source } => Some((image.clone(), source.clone())), + _ => None, + }); + let (image, source) = picture.unwrap(); + assert!(!image.is_empty()); + assert!(source.is_some_and(|s| s.replace('\\', "/").ends_with("data/picture.png"))); + // One Undo step takes the map and its layouts away. + s.run("edit.undo", &json!({})).unwrap(); + assert_eq!(s.project.layouts.len(), layouts); +} + +/// A layout name the project has already is numbered, as a new layout's is; its frame shows the +/// map the import made. +#[test] +fn an_imported_layout_named_as_one_there_is_numbered() { + let mut s = Session::new(Project::default()); + s.run("project.importQgis", &sheets()).unwrap(); + let answer = s.run("project.importQgis", &sheets()).unwrap(); + assert_eq!(answer["map"], "Sheets2"); + assert_eq!(answer["layouts"], json!(["Sheet A4 2", "Sheet A4 (page 2) 2", "Sheet Letter 2"])); + assert_eq!(frame(&s, "Sheet A4 2").0, "Sheets2"); + assert_eq!(frame(&s, "Sheet A4").0, "Sheets"); +} + +/// Run on a copy (the desktop app's way), the layouts land with the map, named as the session +/// has them then, their frames showing the map by its name here. +#[test] +fn an_import_on_a_copy_lands_its_layouts_with_its_map() { + let mut here = Session::new(Project::default()); + let inline = here.run("project.importQgis", &sheets()).unwrap(); + let mut s = Session::new(Project::default()); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &sheets()).unwrap(); + assert!(read.reads()); + let done = read.run(&Control::new()).unwrap(); + let answer = crate::cmd::reads::read_land(&mut s, done).unwrap(); + assert_eq!(answer, inline); + assert!(s.project.layouts == here.project.layouts); + // Meanwhile, a map took its name and a layout one of its layouts' names. + let mut s = Session::new(Project::default()); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &sheets()).unwrap(); + let done = read.run(&Control::new()).unwrap(); + s.map_mut().name = "Sheets".into(); + s.project.layouts.push(rustgis_map::layout::Layout::new("Sheet Letter", 210.0, 297.0)); + let answer = crate::cmd::reads::read_land(&mut s, done).unwrap(); + assert_eq!(answer["map"], "Sheets2"); + assert_eq!(answer["layouts"], json!(["Sheet A4", "Sheet A4 (page 2)", "Sheet Letter 2"])); + assert_eq!(frame(&s, "Sheet A4").0, "Sheets2"); + s.run("edit.undo", &json!({})).unwrap(); + assert_eq!(s.project.layouts.len(), 1); +} + +/// A layout that had a QGIS layout's name when the copy started, renamed to that name numbered by +/// the time it lands, leaves the name free: the QGIS layout takes it, numbered from its own name. +#[test] +fn an_import_on_a_copy_numbers_from_the_qgis_names() { + let mut s = Session::new(Project::default()); + s.project.layouts.push(rustgis_map::layout::Layout::new("Sheet A4", 210.0, 297.0)); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &sheets()).unwrap(); + let done = read.run(&Control::new()).unwrap(); + if let Some(l) = s.project.layouts.iter_mut().find(|l| l.name == "Sheet A4") { + l.name = "Sheet A4 2".into(); + } + let answer = crate::cmd::reads::read_land(&mut s, done).unwrap(); + assert_eq!(answer["layouts"], json!(["Sheet A4", "Sheet A4 (page 2)", "Sheet Letter"])); +} + +/// A project that holds as many layouts as it can by the time the copy's import lands takes none +/// of its layouts, says so, and answers none. +#[test] +fn an_import_landing_on_a_full_project_answers_no_layouts() { + let mut s = Session::new(Project::default()); + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &sheets()).unwrap(); + let done = read.run(&Control::new()).unwrap(); + while s.project.layouts.len() < crate::project::MAX_LAYOUTS { + let n = s.project.layouts.len(); + s.project.layouts.push(rustgis_map::layout::Layout::new(format!("L{n}"), 210.0, 297.0)); + } + let mark = s.notice_mark(); + let answer = crate::cmd::reads::read_land(&mut s, done).unwrap(); + assert!(answer.get("layouts").is_none(), "{answer}"); + assert_eq!(s.project.layouts.len(), crate::project::MAX_LAYOUTS); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("3 of the QGIS project's print layouts left out"))); + // In the answer's notes too. + let notes = answer["notes"].as_array().unwrap(); + assert!( + notes.iter().any(|n| n["text"].as_str().is_some_and(|t| t.contains("print layouts past the 200 a project holds (3)"))), + "{notes:?}" + ); +} + +/// What a layout keeps changes an imported one (a page smaller than 20 mm): said. +#[test] +fn an_imported_layout_brought_within_limits_is_said() { + let text = r#"T"#; + let mut s = Session::new(Project::default()); + let answer = s.run("project.importQgis", &json!({"text": text})).unwrap(); + let l = s.project.layouts.iter().find(|l| l.name == "Tiny").unwrap(); + assert!((l.width - 20.0).abs() < 1e-9); + let notes = answer["notes"].as_array().unwrap(); + assert!( + notes.iter().any(|n| n["text"].as_str().is_some_and(|t| t.contains("pages or papers brought within what a layout takes"))), + "{notes:?}" + ); +} + +/// A map item showing more or less than a frame's scales reach is shown at the nearest, said. +#[test] +fn a_map_item_past_a_frames_scales_is_said() { + let text = r#"TEPSG:2056 + + + "#; + let mut s = Session::new(Project::default()); + let answer = s.run("project.importQgis", &json!({"text": text})).unwrap(); + assert!((frame(&s, "Close").2 - rustgis_map::layout::MIN_FRAME_SCALE).abs() < 1e-12); + let notes = answer["notes"].as_array().unwrap(); + assert!( + notes.iter().any(|n| n["text"] + .as_str() + .is_some_and(|t| t.contains("map items whose scale was brought within a frame's range") && t.ends_with("(1)"))), + "{notes:?}" + ); +} + +/// A layout whose name is as long as a name goes, imported where it is taken, is numbered with +/// its page's number kept whole and the cut said, inline and from a copy. +#[test] +fn a_long_layout_name_numbered_keeps_its_page_and_says_the_cut() { + let long = "N".repeat(200); + let text = format!( + r#"T"# + ); + let mut s = Session::new(Project::default()); + s.run("project.importQgis", &json!({"text": text})).unwrap(); + let answer = s.run("project.importQgis", &json!({"text": text})).unwrap(); + let names: Vec = serde_json::from_value(answer["layouts"].clone()).unwrap(); + assert!(names[0].ends_with("N 2") && names[0].chars().count() == 200, "{names:?}"); + assert!(names[1].ends_with("N (page 2) 2") && names[1].chars().count() == 200, "{names:?}"); + let said = |answer: &serde_json::Value| { + answer["notes"] + .as_array() + .unwrap() + .iter() + .any(|n| n["text"].as_str().is_some_and(|t| t.contains("names cut to fit the number") && t.ends_with("(2)"))) + }; + assert!(said(&answer), "{answer}"); + // From a copy: numbered where it lands, said there. + let read = crate::cmd::reads::read_ahead(&mut s, "project.importQgis", &json!({"text": text})).unwrap(); + let done = read.run(&Control::new()).unwrap(); + let mark = s.notice_mark(); + let answer = crate::cmd::reads::read_land(&mut s, done).unwrap(); + let names: Vec = serde_json::from_value(answer["layouts"].clone()).unwrap(); + assert!(names[1].ends_with("N (page 2) 3"), "{names:?}"); + assert!(said(&answer), "{answer}"); + assert!(s.notices_since(mark).iter().any(|n| n.text.contains("2 of the QGIS project's print layout names cut"))); + // A name with room for its number isn't said. + let mut s = Session::new(Project::default()); + s.run("project.importQgis", &sheets()).unwrap(); + let answer = s.run("project.importQgis", &sheets()).unwrap(); + assert!(!said(&answer), "{answer}"); +} diff --git a/crates/map/src/qgis/annotation.rs b/crates/map/src/qgis/annotation.rs index 6703a84b2f..2dd208128c 100644 --- a/crates/map/src/qgis/annotation.rs +++ b/crates/map/src/qgis/annotation.rs @@ -564,13 +564,13 @@ fn text_graphic(item: Node, geometry: Geometry, align: TextAlign, layer: &str, r /// A font family that only names a kind of font (QGIS's default "Sans Serif"): RustGIS's is one /// too. -fn generic(family: &str) -> bool { +pub(super) fn generic(family: &str) -> bool { matches!(family.to_ascii_lowercase().as_str(), "sans serif" | "sans-serif" | "sans" | "ms shell dlg 2") } /// HTML's text without its tags, `
` and the ends of paragraphs as line breaks, and the common /// entities read. -fn plain(html: &str) -> String { +pub(super) fn plain(html: &str) -> String { // What HTML draws of `html`, as lines: tags dropped (and what's in a head, style, script or // title), a `<` that opens no tag kept, runs of white space one space as HTML draws them, // a line broken at `
` and between blocks, entities read. diff --git a/crates/map/src/qgis/layout.rs b/crates/map/src/qgis/layout.rs new file mode 100644 index 0000000000..84d2691ae8 --- /dev/null +++ b/crates/map/src/qgis/layout.rs @@ -0,0 +1,1370 @@ +//! A QGIS project's print layouts as RustGIS layouts (piece 12a of #882): each page a layout, +//! its map items map frames (placed on the imported map by the engine, from the extent each shows), +//! its labels text, its pictures pictures (read by the engine, from the file each names), its +//! rectangles and ellipses those shapes, and its lines and polygons straight lines along their +//! edges. Items are drawn in QGIS's order (its `zValue`), placed where QGIS draws them on their +//! page in millimetres, a turned label turned about its centre as QGIS turns it. +//! +//! What a RustGIS layout has no place for is noted, counted over all the layouts: scale bars, +//! legends, north arrows, tables, HTML and the other item kinds, map grids and overviews, the +//! atlas, groups, blending, and settings set by expressions. A QGIS 2 composer isn't read. + +use roxmltree::Node; + +use super::{Report, annotation, child, color, labels, listed, symbol}; +use crate::Rgba; +use crate::layout::{ + Background, ElementKind, FRAME_BORDER_COLOR, INDICATOR_COLOR, INDICATOR_WIDTH, Layout, LineDir, LineHead, TextAlign, TextVAlign, +}; + +/// The most layouts an import reads; those past it are noted. +pub const MAX_LAYOUTS: usize = 200; +/// The most items of a page that become elements; a RustGIS layout keeps 500 ([`Layout::clamp`]). +pub const MAX_ELEMENTS: usize = 500; +/// The most pages of one layout read, each a layout of its own. +const MAX_PAGES: usize = 50; +/// The longest text kept of a label, in characters. +const MAX_TEXT: usize = crate::layout::MAX_TEXT_CHARS; +/// The longest layout name and element name kept, in characters. +const MAX_LAYOUT_NAME: usize = 200; +const MAX_ELEMENT_NAME: usize = 100; +/// The largest side an element has, in millimetres (`Layout::add` keeps it so). +const MAX_SIDE: f64 = 5000.0; +/// The most vertices of a line or polygon item read, each edge a line. +const MAX_NODES: usize = 200; +/// The most of the project's title and layouts' names written out into labels over an import, in +/// bytes: past it, a label is left without them, said. +const MAX_TITLE_TEXT: usize = 4 << 20; + +/// A QGIS layout's page, as a RustGIS layout, with what the engine finishes: its map frames' +/// places and its pictures' images. +#[derive(Clone, Debug, PartialEq)] +pub struct ProjectLayout { + /// The layout: its map frames show no map yet (an empty `map`), centred on 0, 0 at 1:1. + pub layout: Layout, + pub frames: Vec, + pub pictures: Vec, +} + +/// A map frame of a [`ProjectLayout`] and the extent its QGIS map item shows. +#[derive(Clone, Debug, PartialEq)] +pub struct LayoutFrame { + /// The element. + pub element: u32, + /// [xmin, ymin, xmax, ymax], in `crs`: the rectangle the item shows, before its map's turn. + pub extent: [f64; 4], + /// The item's own coordinate system; `None`, the project's. + pub crs: Option, +} + +/// A picture of a [`ProjectLayout`] and the image it shows. +#[derive(Clone, Debug, PartialEq)] +pub struct LayoutPicture { + /// The element: a picture with no image yet. + pub element: u32, + /// The image: a file resolved from the project's folder, or `base64:…`. + pub source: String, + /// What it comes in as otherwise than QGIS draws it, as notes say it (`turned pictures, drawn + /// upright`): said by the engine once the picture comes in, as one that doesn't read is left out. + pub notes: Vec<&'static str>, +} + +/// What the layouts held that their RustGIS layouts don't carry over, counted over them all. +#[derive(Default)] +pub(super) struct Tally { + legends: usize, + scale_bars: usize, + north_arrows: usize, + tables: usize, + html: usize, + markers: usize, + other: usize, + other_kinds: Vec, + groups: usize, + map_backgrounds: usize, + grids: usize, + overviews: usize, + atlases: usize, + locked_layers: usize, + turned_items: usize, + blended: usize, + translucent: usize, + data_defined: usize, + not_exported: usize, + pub(super) expressions: usize, + project_title: usize, + html_labels: usize, + justified: usize, + svg: usize, + no_picture: usize, + bad_picture: Vec, + bad_pictures: usize, + oversized: usize, + polygon_fills: usize, + joined_lines: usize, + unplaced: usize, + over: usize, + pixels: usize, + unread_text: Vec<&'static str>, + unread_texts: usize, + /// What reading their symbols and text sizes noted. + notes: Report, + cut_lines: usize, + cut_texts: usize, + /// Pages left out (past [`MAX_PAGES`], or whose size doesn't read), and the items on them. + pages_left: usize, + off_pages: usize, + own_crs: usize, + turned_backgrounds: usize, + cut_names: usize, + date_formats: usize, + /// Dates, times and map scales printed in RustGIS's format. + formats: usize, + /// Layouts with no page that reads, given an A4 one. + no_pages: usize, + /// Labels in QGIS 3's older style whose font size doesn't read. + font_sizes: usize, + /// The labels showing the project's title, as (layout, element, how many times, its whole + /// text, whether reading its expressions stopped short), while their QGIS layout is read: on + /// a page without a map, the title as written. + titled: Vec<(usize, u32, usize, String, bool)>, + /// Whether [`tokens`] stopped short of the text it was given (past what a text holds). + pub(super) stopped: bool, + /// Label sizes outside what a text takes (1 to 400 pt). + label_sizes: usize, + /// Labels' own text, layout names and titles written into labels with their braces as + /// parentheses. + braces: usize, + /// Pages past the [`MAX_LAYOUTS`] layouts an import makes, and QGIS layouts with none left. + pages_past: usize, + layouts_past: usize, + /// The bytes of the project's title and layouts' names written out into labels, and the + /// labels left without the title, and the names left out, past [`MAX_TITLE_TEXT`]. + title_bytes: usize, + titles_left: usize, + names_left: usize, + /// The length of the project's title as a label writes it, in bytes: what reading a label's + /// expressions counts for each of its title's on a page without a map. + pub(super) title_len: usize, + /// Line edges whose box is narrower than an element can be across or down (a slanted edge + /// nearly flat or upright, or a very short one), widened to it. + thin_edges: usize, + /// Items other than lines narrower than an element can be across or down, widened to it. + tiny: usize, + /// Labels whose margins leave their text less than an element can be across or down, its box + /// widened to it. + tiny_text: usize, +} + +/// `text` written into a label as it reads: its braces as parentheses, as a brace starts one of +/// RustGIS's tokens (`{date}`). +fn as_written(text: &str) -> String { + text.replace('{', "(").replace('}', ")") +} + +/// Reads the project's print layouts (``), each page a [`ProjectLayout`], `dir` the +/// project's folder (pictures named relative to it), `title` the project's title. What can't be +/// carried over is noted. +pub fn read_layouts(root: Node, dir: &str, title: &str, report: &mut Report) -> Vec { + let composers = root.children().filter(|c| c.has_tag_name("Composer")).count(); + if composers > 0 { + report.skipped("", format!("its print composers of QGIS 2 ({composers})")); + } + let Some(list) = child(root, "Layouts") else { return Vec::new() }; + let mut tally = Tally::default(); + // A label holds no more than its text's characters of it (one that holds it cut is said). + let cut = title.chars().nth(MAX_TEXT).is_some(); + let title = Title { text: as_written(&title.chars().take(MAX_TEXT).collect::()), cut, braced: title.contains(['{', '}']) }; + tally.title_len = title.text.len(); + let mut out = Vec::new(); + let mut names = Vec::new(); + let all: Vec = list.children().filter(|c| c.has_tag_name("Layout")).collect(); + for layout in all.iter().take(MAX_LAYOUTS) { + // An import makes no more layouts than it keeps: a page a layout, counted over them all. + let room = MAX_LAYOUTS.saturating_sub(out.len()); + if room == 0 { + tally.layouts_past += 1; + continue; + } + let read = read_layout(*layout, dir, &title, room, &mut tally); + if read.len() > 1 { + names.push(read.first().map(|l| l.layout.name.clone()).unwrap_or_default()); + } + out.extend(read); + } + // Those read for no room and those not read, together. + let past = tally.layouts_past + all.len().saturating_sub(MAX_LAYOUTS); + if past > 0 { + report.skipped("", format!("its print layouts past the {MAX_LAYOUTS} layouts an import makes (a page a layout) ({past})")); + } + if !names.is_empty() { + let refs: Vec<&str> = names.iter().map(String::as_str).collect(); + report.approximated("", format!("print layouts of several pages, each page a layout of its own ({})", listed(&refs))); + } + tally.say(report); + out +} + +/// The project's title as a label on a page without a map writes it: its text (braces as +/// parentheses), whether it was cut to fit a text, and whether it had braces. +struct Title { + text: String, + cut: bool, + braced: bool, +} + +/// A layout's pages, each as a layout of its own: the first under the layout's name, the others +/// numbered by their place among the QGIS layout's pages (`Plan (page 2)`); no more than `room`. +fn read_layout(node: Node, dir: &str, title: &Title, room: usize, tally: &mut Tally) -> Vec { + let given = node.attribute("name").map(str::trim).filter(|n| !n.is_empty()).unwrap_or("Layout"); + tally.cut_names += usize::from(given.chars().nth(MAX_LAYOUT_NAME).is_some()); + let name: String = given.chars().take(MAX_LAYOUT_NAME).collect(); + // The resolution a size in pixels is read at. + let dpi = num(node, "printResolution").filter(|d| *d >= 1.0 && *d <= 10_000.0).unwrap_or(300.0); + // Its pages, each where it starts down the layout, and read (its size) when it is one of + // the first [`MAX_PAGES`] and reads. + let collection = child(node, "PageCollection"); + // The paper: a page's fill symbol's colour (when not white), else its collection's. + let paper = collection.and_then(paper_of).flatten(); + let entries = + collection.map_or(0, |pc| pc.children().filter(|c| c.has_tag_name("LayoutItem") && c.attribute("type") == Some(PAGE)).count()); + tally.pages_left += entries.saturating_sub(MAX_PAGE_NODES); + let mut pages: Vec = collection + .map(|pc| { + pc.children() + .filter(|c| c.has_tag_name("LayoutItem") && c.attribute("type") == Some(PAGE)) + .take(MAX_PAGE_NODES) + .enumerate() + .map(|(i, p)| Slot { + top: p.attribute("position").and_then(|v| pair(v, dpi)).map(|(_, y)| y), + page: if i < MAX_PAGES { Page::read(p, dpi) } else { None }, + paper: paper_of(p).unwrap_or(paper), + layout: None, + }) + .collect() + }) + .unwrap_or_default(); + tally.pages_left += pages.iter().filter(|s| s.page.is_none()).count(); + if pages.iter().all(|s| s.page.is_none()) { + // A layout with no page QGIS can read: A4 portrait, as QGIS starts one, said (the pages + // that don't read counted above). + tally.no_pages += 1; + pages = vec![Slot { top: Some(0.0), page: Some(Page { top: 0.0, w: 210.0, h: 297.0 }), paper, layout: None }]; + } + if child(node, "Atlas").is_some_and(|a| a.attribute("enabled") == Some("1")) { + tally.atlases += 1; + } + let mut layouts: Vec = Vec::new(); + for (i, slot) in pages.iter_mut().enumerate() { + let Some(p) = &slot.page else { continue }; + let n = layouts.len(); + if n >= room { + // Its items are counted with the pages left out. + tally.pages_past += 1; + continue; + } + let name = if n == 0 { + name.clone() + } else { + // Room for the page's number (its place among the QGIS layout's) in a name's characters. + let page = format!(" (page {})", i + 1); + let room = MAX_LAYOUT_NAME.saturating_sub(page.chars().count()); + tally.cut_names += usize::from(name.chars().nth(room).is_some()); + format!("{}{page}", name.chars().take(room).collect::().trim_end()) + }; + let mut layout = Layout::new(name, p.w, p.h); + layout.paper = slot.paper; + slot.layout = Some(n); + layouts.push(ProjectLayout { layout, frames: Vec::new(), pictures: Vec::new() }); + } + // The items bottom first, as QGIS draws them (by `zValue`, ties in the file's order, which + // lists them top first). + let mut items: Vec<(f64, usize, Node)> = node + .children() + .filter(|c| c.has_tag_name("LayoutItem")) + .enumerate() + .map(|(i, n)| (num(n, "zValue").unwrap_or(0.0), usize::MAX - i, n)) + .collect(); + items.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + // Each multi-frame's type, by its id: what a frame item shows. + let multiframes: std::collections::HashMap<&str, &str> = node + .children() + .filter(|c| c.has_tag_name("LayoutMultiFrame")) + .filter_map(|m| Some((m.attribute("uuid")?, m.attribute("type")?))) + .collect(); + // `@layout_name` prints the QGIS layout's name as far as a text holds, not the layout's. + let pages = Pages::new(pages, entries.max(1), given.chars().take(MAX_TEXT).collect()); + tally.titled.clear(); + for (_, _, item) in items { + read_item(item, &pages, &mut layouts, &multiframes, dir, dpi, tally); + } + // A page without a map shows the project's title as written (a frame shows its map's name). + // Its text is cut to what a text holds after that, and a cut said. + for (page, element, n, whole, stopped) in std::mem::take(&mut tally.titled) { + let Some(l) = layouts.get_mut(page) else { continue }; + if l.layout.elements.iter().any(|e| matches!(e.kind, ElementKind::MapFrame { .. })) { + tally.cut_texts += usize::from(stopped || whole.chars().nth(MAX_TEXT).is_some()); + continue; + } + let Some(e) = l.layout.element_mut(element) else { continue }; + let ElementKind::Text { text, .. } = &mut e.kind else { continue }; + tally.project_title = tally.project_title.saturating_sub(1); + // The title's bytes this label writes out (no more than a text holds). + let cost = n.saturating_mul(title.text.len()).min(4 * MAX_TEXT); + if tally.title_bytes.saturating_add(cost) > MAX_TITLE_TEXT { + // Past what an import writes out of it: the label without its title, said. + tally.titles_left += 1; + let kept = whole.replace("{map}", ""); + tally.cut_texts += usize::from(stopped || kept.chars().nth(MAX_TEXT).is_some()); + *text = kept.chars().take(MAX_TEXT).collect(); + continue; + } + tally.braces += usize::from(title.braced); + // Written out no further than a text holds. + let mut parts = whole.split("{map}"); + let mut titled = parts.next().unwrap_or_default().to_string(); + for part in parts { + if titled.len() > 4 * MAX_TEXT { + break; + } + titled.push_str(&title.text); + titled.push_str(part); + } + tally.cut_texts += usize::from(stopped || title.cut || titled.chars().nth(MAX_TEXT).is_some()); + *text = titled.chars().take(MAX_TEXT).collect(); + tally.title_bytes += cost; + } + layouts +} + +/// The paper a fill symbol under `node` gives: `None` with no symbol, `Some(None)` for white (or a +/// colour that doesn't read). +fn paper_of(node: Node) -> Option> { + let s = node.children().find(|c| c.has_tag_name("symbol"))?; + Some( + s.descendants() + .find(|d| d.has_tag_name("layer")) + .and_then(|l| super::prop(&super::props(l), "color").and_then(color)) + .filter(|c| *c != Rgba::rgb(255, 255, 255)), + ) +} + +/// A layout's pages, with where each starts in order (for finding an item's page by halving) +/// and how many pages the QGIS layout has. +struct Pages { + slots: Vec, + /// (top, index in `slots`), by top, then index. + order: Vec<(f64, usize)>, + total: usize, + /// The QGIS layout's name. + name: String, +} + +impl Pages { + fn new(slots: Vec, total: usize, name: String) -> Pages { + let mut order: Vec<(f64, usize)> = slots.iter().enumerate().filter_map(|(i, s)| Some((s.top?, i))).collect(); + order.sort_by(|a, b| a.0.total_cmp(&b.0).then(a.1.cmp(&b.1))); + Pages { slots, order, total, name } + } + + /// The page a point `y` down the layout is on: the one starting last above it. + /// With its place among the QGIS layout's pages (0 for the first). + fn at(&self, y: f64) -> Option<(usize, &Slot)> { + let n = self.order.partition_point(|(top, _)| *top <= y + 1e-6); + let i = n.checked_sub(1).and_then(|k| self.order.get(k)).map_or(0, |(_, i)| *i); + self.slots.get(i).map(|s| (i, s)) + } +} + +/// QGIS's layout item types, as `type` names them. +const PAGE: &str = "65638"; +const MAP: &str = "65639"; +const PICTURE: &str = "65640"; +const LABEL: &str = "65641"; +const LEGEND: &str = "65642"; +const SHAPE: &str = "65643"; +const POLYGON: &str = "65644"; +const POLYLINE: &str = "65645"; +const SCALE_BAR: &str = "65646"; +const FRAME: &str = "65647"; +const GROUP: &str = "65637"; +const MARKER: &str = "65653"; +/// QGIS's multi-frame types: an HTML frame, an attribute table. +const HTML: &str = "65648"; +const ATTRIBUTE_TABLE: &str = "65649"; + +/// The most page entries of one layout looked at. +const MAX_PAGE_NODES: usize = 10_000; + +/// A page of a QGIS layout: where it starts, the page when it is read, its paper, and the layout +/// it became. +struct Slot { + top: Option, + page: Option, + paper: Option, + layout: Option, +} + +/// A page: where it sits in the layout's coordinates (pages are stacked down, a gap between +/// them) and its size, in millimetres. +struct Page { + top: f64, + w: f64, + h: f64, +} + +impl Page { + fn read(node: Node, dpi: f64) -> Option { + let (_, top) = pair(node.attribute("position")?, dpi)?; + let (w, h) = pair(node.attribute("size")?, dpi)?; + (w > 0.0 && h > 0.0).then_some(Page { top, w, h }) + } +} + +/// An item's box on its page, unturned: (page, x, y, w, h) in millimetres, and its turn. +struct Placed { + /// The layout its page became, its page's place among the QGIS layout's (0 for the first), + /// and how many pages that has. + page: usize, + number: usize, + pages: usize, + /// The resolution a size in pixels is read at. + dpi: f64, + x: f64, + y: f64, + w: f64, + h: f64, + /// Degrees clockwise, as QGIS's `itemRotation`. + turn: f64, +} + +impl Placed { + /// The point (mm, on the page) of `(u, v)` in the item's own unturned box. + fn at(&self, u: f64, v: f64) -> (f64, f64) { + let (cx, cy) = (self.x + self.w / 2.0, self.y + self.h / 2.0); + let (sin, cos) = self.turn.to_radians().sin_cos(); + let (dx, dy) = (u - self.w / 2.0, v - self.h / 2.0); + (cx + dx * cos - dy * sin, cy + dx * sin + dy * cos) + } +} + +/// Where `item` is drawn: QGIS saves the place of its reference point (`referencePoint`, its top +/// left by default) after its turn (`itemRotation`, about its centre), in its layout's units. +fn placed(item: Node, pages: &Pages, dpi: f64, tally: &mut Tally) -> Option { + let read = |k: &str| item.attribute(k).and_then(|v| pair(v, dpi)); + let (Some((px, py)), Some((w, h))) = (read("position"), read("size")) else { + tally.unplaced += 1; + return None; + }; + let turn = num(item, "itemRotation").unwrap_or(0.0); + // The reference point: 0 to 8, by rows from the top left. + let r = num(item, "referencePoint").map_or(0, |r| r as i64).clamp(0, 8); + let (rx, ry) = ((r % 3) as f64 / 2.0, (r / 3) as f64 / 2.0); + let (sin, cos) = turn.to_radians().sin_cos(); + let (dx, dy) = (rx * w - w / 2.0, ry * h - h / 2.0); + let (cx, cy) = (px - (dx * cos - dy * sin), py - (dx * sin + dy * cos)); + let (x, y) = (cx - w / 2.0, cy - h / 2.0); + if ![x, y, w, h, turn].iter().all(|v| v.is_finite()) { + tally.unplaced += 1; + return None; + } + // Its page: where QGIS saves it as on its page (`positionOnPage`, its reference point there), + // the page starting where the two differ; else the one its top left corner (turned) is on. + let on_page = read("positionOnPage").map(|(_, oy)| py - oy + 0.5).filter(|v| v.is_finite()); + let corner = cy - (w / 2.0) * sin - (h / 2.0) * cos; + let Some((number, page, top)) = pages.at(on_page.unwrap_or(corner)).and_then(|(i, s)| Some((i, s.layout?, s.page.as_ref()?.top))) + else { + tally.off_pages += 1; + return None; + }; + Some(Placed { page, number, pages: pages.total, dpi, x, y: y - top, w: w.max(0.0), h: h.max(0.0), turn }) +} + +fn read_item( + item: Node, + pages: &Pages, + layouts: &mut [ProjectLayout], + multiframes: &std::collections::HashMap<&str, &str>, + dir: &str, + dpi: f64, + tally: &mut Tally, +) { + let kind = item.attribute("type").unwrap_or_default(); + match kind { + PAGE => return, + LEGEND => { + tally.legends += 1; + return; + } + SCALE_BAR => { + tally.scale_bars += 1; + return; + } + GROUP => { + tally.groups += 1; + return; + } + MARKER => { + tally.markers += 1; + return; + } + FRAME => { + let of = item.attribute("multiFrame").unwrap_or_default(); + match multiframes.get(of).copied() { + Some(HTML) => tally.html += 1, + Some(ATTRIBUTE_TABLE) => tally.tables += 1, + _ => tally.other += 1, + } + return; + } + MAP | PICTURE | LABEL | SHAPE | POLYGON | POLYLINE => {} + other => { + tally.other += 1; + if !other.is_empty() && tally.other_kinds.len() < 8 && !tally.other_kinds.iter().any(|k| k == other) { + tally.other_kinds.push(other.chars().take(20).collect()); + } + return; + } + } + let Some(place) = placed(item, pages, dpi, tally) else { return }; + let Some(target) = layouts.get_mut(place.page) else { + tally.unplaced += 1; + return; + }; + // A picture is counted where it would come in (one that can't is said as such). + if kind != PICTURE && target.layout.elements.len() >= MAX_ELEMENTS { + tally.over += elements_needed(item, kind); + return; + } + let opacity = num(item, "opacity").unwrap_or(1.0).clamp(0.0, 1.0); + let blended = num(item, "blendMode").is_some_and(|b| b != 0.0); + let data_defined = child(item, "LayoutObject").is_some_and(|o| { + o.descendants().any(|d| d.has_tag_name("Option") && d.attribute("name") == Some("active") && d.attribute("value") == Some("true")) + }); + let shown = item.attribute("visibility") != Some("0"); + let exported = item.attribute("excludeFromExports") != Some("1"); + let fade = |c: Rgba| c.with_alpha((f64::from(c.a()) * opacity).round() as u8); + let first = target.layout.elements.len(); + let given = item.attribute("id").map(str::trim).filter(|i| !i.is_empty()); + let id_cut = given.is_some_and(|i| i.chars().nth(MAX_ELEMENT_NAME).is_some()); + let id = given.map(|i| i.chars().take(MAX_ELEMENT_NAME).collect::()); + match kind { + MAP => map_item(item, &place, id, target, tally), + LABEL => label_item(item, &place, (id, &pages.name), fade, target, tally), + PICTURE => picture_item(item, &place, id, dir, fade, target, tally), + SHAPE => shape_item(item, &place, id, fade, target, tally), + _ => line_item(item, kind, &place, id, fade, target, tally), + } + // Counted for what came in: a picture's said by the engine once its image reads. + let added = target.layout.elements.len() > first; + let pixels = item.attribute("position").is_some_and(|p| p.ends_with(",px")); + // A layout's elements are at most 5 m a side: a larger one is cut to it. + let oversized = place.w > MAX_SIDE || place.h > MAX_SIDE; + // Narrower than an element can be across or down: widened to it (a line's edges are counted + // as they are drawn). + let tiny = !matches!(kind, POLYLINE | POLYGON) && (place.w < crate::layout::MIN_ELEMENT_MM || place.h < crate::layout::MIN_ELEMENT_MM); + let counts = [ + (id_cut, &mut tally.cut_names, "pictures' ids longer than 100 characters, cut to fit"), + (pixels, &mut tally.pixels, "picture positions in pixels, read at the layout's print resolution"), + (oversized, &mut tally.oversized, "pictures larger than 5 m a side, cut to it"), + (tiny, &mut tally.tiny, "pictures less than 0.05 mm across or down, widened to it"), + (blended, &mut tally.blended, "pictures' blending modes, drawn normally"), + (data_defined, &mut tally.data_defined, "pictures with settings set by expressions, drawn as set"), + (opacity < 1.0 && matches!(kind, MAP | PICTURE), &mut tally.translucent, "translucent pictures, drawn opaque"), + (shown && !exported, &mut tally.not_exported, "pictures left out of exports, kept hidden"), + ]; + for (set, count, picture_note) in counts { + if !(added && set) { + continue; + } + if kind == PICTURE { + if let Some(p) = target.pictures.last_mut() { + p.notes.push(picture_note); + } + } else { + *count += 1; + } + } + // A hidden item, and one QGIS leaves out of its exports, is kept hidden. + let locked = item.attribute("positionLock") == Some("true"); + for e in target.layout.elements.iter_mut().skip(first) { + e.visible = shown && exported; + e.locked = locked; + } +} + +/// The elements `item` comes in as (a line one an edge, a label with a background two), counted +/// when a full layout leaves it out. +fn elements_needed(item: Node, kind: &str) -> usize { + match kind { + // The edges `line_item` would draw: of the vertices it reads, closed as it closes them. + POLYLINE | POLYGON => { + // One whose vertices don't read counts as the one item left out; one of a single point + // repeated draws nothing, so leaves nothing out. + let (points, _) = outline(item, kind); + if points.len() < 2 { 1 } else { points.windows(2).filter(|w| drawn(w[0], w[1])).count() } + } + SHAPE if item.attribute("shapeType") == Some("2") => 3, + LABEL => { + // As `backdrop` reads it: a background or frame with its colour. + let boxed = (item.attribute("background") == Some("true") && child(item, "BackgroundColor").and_then(rgba_of).is_some()) + || (item.attribute("frame") == Some("true") && child(item, "FrameColor").and_then(rgba_of).is_some()); + 1 + usize::from(boxed && num(item, "itemRotation").is_none_or(|r| r.rem_euclid(360.0) == 0.0)) + } + _ => 1, + } +} + +/// The background and frame QGIS draws for an item (`background`, `frame`), as an element's. +fn backdrop(item: Node, fill_too: bool, dpi: f64, fade: &impl Fn(Rgba) -> Rgba) -> Option { + let fill = (fill_too && item.attribute("background") == Some("true")).then(|| rgba_of(child(item, "BackgroundColor")?)).flatten(); + let frame = (item.attribute("frame") == Some("true")).then(|| rgba_of(child(item, "FrameColor")?)).flatten(); + let width = item.attribute("outlineWidthM").and_then(|m| length(m, dpi)).unwrap_or(0.3) * crate::layout::PT_PER_MM; + if fill.is_none() && frame.is_none() { + return None; + } + let none = Rgba::new(0, 0, 0, 0); + Some( + Background { + fill: fill.map_or(none, fade), + outline: frame.map_or(none, fade), + width: if frame.is_some() { width } else { 0.0 }, + radius: 0.0, + padding: 0.0, + } + .clamped(), + ) +} + +/// A colour element's `red`, `green`, `blue` and `alpha`. +fn rgba_of(n: Node) -> Option { + let c = |k: &str| n.attribute(k).and_then(|v| v.trim().parse::().ok()); + Some(Rgba::new(c("red")?, c("green")?, c("blue")?, c("alpha").unwrap_or(255))) +} + +fn name_or(id: Option, kind: &str) -> String { + id.unwrap_or_else(|| kind.to_string()) +} + +fn map_item(item: Node, place: &Placed, id: Option, target: &mut ProjectLayout, tally: &mut Tally) { + if place.turn.rem_euclid(360.0) != 0.0 { + tally.turned_items += 1; + } + let extent = child(item, "Extent").and_then(|e| { + let v = |k: &str| num(e, k); + let x = [v("xmin")?, v("ymin")?, v("xmax")?, v("ymax")?]; + (x[0] < x[2] && x[1] < x[3]).then_some(x) + }); + let Some(extent) = extent else { + tally.unplaced += 1; + return; + }; + let crs = child(item, "crs").and_then(super::crs_of); + tally.own_crs += usize::from(crs.is_some()); + for c in item.children() { + let shown = c.attribute("show") != Some("0"); + if c.has_tag_name("ComposerMapGrid") && shown { + tally.grids += 1; + } else if c.has_tag_name("ComposerMapOverview") && shown { + tally.overviews += 1; + } + } + if item.attribute("keepLayerSet") == Some("true") || item.attribute("followPreset") == Some("true") { + tally.locked_layers += 1; + } + let framed = item.attribute("frame") == Some("true"); + let border_color = child(item, "FrameColor").and_then(rgba_of).filter(|_| framed).unwrap_or(FRAME_BORDER_COLOR); + let border_width = if framed { + item.attribute("outlineWidthM").and_then(|m| length(m, place.dpi)).unwrap_or(0.3) * crate::layout::PT_PER_MM + } else { + 0.0 + }; + let bearing = crate::layout::rotation(-num(item, "mapRotation").unwrap_or(0.0)); + let kind = ElementKind::MapFrame { + map: String::new(), + center: rustgis_geom::Coord::new(0.0, 0.0), + scale: 1.0, + shape: Default::default(), + grid: None, + sections: Vec::new(), + extent_of: None, + extent_color: INDICATOR_COLOR, + extent_width: INDICATOR_WIDTH, + border_color, + border_width, + bearing, + pitch: 0.0, + more_extents: Vec::new(), + extent_numbers: false, + }; + // Its background shows only where the map draws nothing: a frame draws its map's own. + let white = Rgba::rgb(255, 255, 255); + if item.attribute("background") == Some("true") + && child(item, "BackgroundColor").and_then(rgba_of).is_some_and(|c| c.a() > 0 && c != white) + { + tally.map_backgrounds += 1; + } + let element = target.layout.add(name_or(id, "Map"), (place.x, place.y, place.w, place.h), kind); + target.frames.push(LayoutFrame { element, extent, crs }); +} + +/// A label, `id` its name and `layout` its QGIS layout's. +fn label_item( + item: Node, + place: &Placed, + (id, layout): (Option, &str), + fade: impl Fn(Rgba) -> Rgba, + target: &mut ProjectLayout, + tally: &mut Tally, +) { + // Both or neither: the text with the rectangle under it. Decided first, so a label left out + // counts for nothing else. + let backdrop = backdrop(item, true, place.dpi, &fade); + let turned = place.turn.rem_euclid(360.0) != 0.0; + let needs = 1 + usize::from(backdrop.is_some() && !turned); + if target.layout.elements.len() + needs > MAX_ELEMENTS { + tally.over += needs; + return; + } + let raw = item.attribute("labelText").unwrap_or_default(); + let html = item.attribute("htmlState") == Some("1"); + tally.html_labels += usize::from(html); + let plain = if html { annotation::plain(raw) } else { raw.to_string() }; + let titles = tally.project_title; + tally.stopped = false; + let text = tokens(&plain, tally, (place.number, place.pages), layout); + let (titles, stopped) = (tally.project_title - titles, tally.stopped); + // Counted once per label, however many times it shows the title. + tally.project_title -= titles.saturating_sub(1); + // A label showing the title is cut (and said) once its page is known to have a map or not. + let cut: String = text.chars().take(MAX_TEXT).collect(); + let whole = if titles > 0 { + Some(text) + } else { + tally.cut_texts += usize::from(stopped || text.chars().nth(MAX_TEXT).is_some()); + None + }; + let text = cut; + let style = child(item, "text-style"); + let (size, color, bold, italic, spacing, font) = match style { + Some(s) => { + let unit = s.attribute("fontSizeUnit").unwrap_or("Point"); + let size = labels::points(num(s, "fontSize").unwrap_or(10.0), unit, "label sizes", "", &mut tally.notes); + let opacity = num(s, "textOpacity").unwrap_or(1.0).clamp(0.0, 1.0); + let c = s.attribute("textColor").and_then(color).unwrap_or(Rgba::rgb(0, 0, 0)); + let c = c.with_alpha((f64::from(c.a()) * opacity).round() as u8); + let (mut bold, mut italic) = labels::bold_italic(s); + bold |= s.attribute("forcedBold") == Some("1"); + italic |= s.attribute("forcedItalic") == Some("1"); + let spacing = num(s, "fontLetterSpacing") + .filter(|v| *v != 0.0) + .map_or(0.0, |v| labels::points(v, unit, "letter spacing", "", &mut tally.notes)); + let font = s.attribute("fontFamily").map(str::trim).filter(|f| !f.is_empty() && !annotation::generic(f)).map(str::to_string); + let unread = [ + (s.attribute("capitalization").is_some_and(|c| c != "0"), "capitalisation"), + (s.attribute("fontUnderline") == Some("1"), "underlines"), + (s.attribute("fontStrikeout") == Some("1"), "strikeouts"), + (child(s, "background").is_some_and(|n| n.attribute("shapeDraw") == Some("1")), "backgrounds"), + (child(s, "shadow").is_some_and(|n| n.attribute("shadowDraw") == Some("1")), "shadows"), + (child(s, "text-buffer").is_some_and(|n| n.attribute("bufferDraw") == Some("1")), "buffers"), + ]; + tally.unread_texts += usize::from(unread.iter().any(|(set, _)| *set)); + for (set, what) in unread { + if set && !tally.unread_text.contains(&what) { + tally.unread_text.push(what); + } + } + (size, c, bold, italic, spacing, font) + } + None => older_style(item, tally), + }; + // Qt's alignment flags: across left 1, right 2, centre 4, justified 8; down top 32, bottom 64, + // centre 128. + let h = num(item, "halign").map_or(1, |a| a as i64); + tally.justified += usize::from(h & 8 != 0); + let align = match h & 0xF { + 2 => TextAlign::Right, + 4 => TextAlign::Center, + _ => TextAlign::Left, + }; + let valign = match num(item, "valign").map_or(32, |a| a as i64) & 0xE0 { + 64 => TextVAlign::Bottom, + 128 => TextVAlign::Middle, + _ => TextVAlign::Top, + }; + let kept = size.clamp(1.0, 400.0); + let mut kind = ElementKind::text(text, kept, fade(color), bold); + if let ElementKind::Text { italic: i, align: a, valign: v, letter_spacing, font_name, rotation, wrap, .. } = &mut kind { + *i = italic; + *a = align; + *v = valign; + *letter_spacing = spacing; + *font_name = font; + *rotation = crate::layout::rotation(place.turn); + // QGIS breaks a label's lines to fit its box. + *wrap = true; + } + // Its margins inside its box, on both sides; its background and frame fill the whole box: + // a rectangle under it, or, turned, its own background (a rectangle doesn't turn), reaching + // the smaller margin past it. + let (mx, my) = (num(item, "marginX").unwrap_or(0.0).max(0.0), num(item, "marginY").unwrap_or(0.0).max(0.0)); + let (mx, my) = (mx.min(place.w / 2.0), my.min(place.h / 2.0)); + let name = name_or(id, "Text"); + if let Some(b) = backdrop.filter(|_| !turned) { + let kind = ElementKind::Rectangle { fill: b.fill, outline: b.outline, width: b.width, radius: 0.0, dash: None }; + target.layout.add(format!("{name} background"), (place.x, place.y, place.w, place.h), kind); + } + let (px, py) = if turned && backdrop.is_some() { (mx.min(my), mx.min(my)) } else { (mx, my) }; + tally.turned_backgrounds += usize::from(turned && backdrop.is_some() && (mx - my).abs() > 1e-9); + let (tw, th) = (place.w - 2.0 * mx, place.h - 2.0 * my); + // Per side: a side too small itself is counted with the other items. + let min = crate::layout::MIN_ELEMENT_MM; + tally.tiny_text += usize::from((tw < min && place.w >= min) || (th < min && place.h >= min)); + let element = target.layout.add(name, (place.x + mx, place.y + my, tw, th), kind); + tally.label_sizes += usize::from(kept != size); + if titles > 0 { + tally.titled.push((place.page, element, titles, whole.unwrap_or_default(), stopped)); + } + if turned && let Some(e) = target.layout.element_mut(element) { + e.background = backdrop.map(|b| Background { padding: px.min(py), ..b }.clamped()); + } +} + +/// A label's style as QGIS 3 wrote it before `text-style` (`LabelFont`, Qt's font description, +/// and `FontColor`): its size, colour, bold, italic, letter spacing and font. A size that doesn't +/// read is 10 pt, counted. +fn older_style(item: Node, tally: &mut Tally) -> (f64, Rgba, bool, bool, f64, Option) { + let c = child(item, "FontColor").and_then(rgba_of).unwrap_or(Rgba::rgb(0, 0, 0)); + let Some(font) = child(item, "LabelFont").and_then(|f| f.attribute("description")) else { + return (10.0, c, false, false, 0.0, None); + }; + // Family, size in points, size in pixels, style hint, weight, italic, … + let parts: Vec<&str> = font.split(',').map(str::trim).collect(); + let family = parts.first().filter(|f| !f.is_empty() && !annotation::generic(f)).map(|f| f.to_string()); + let size = parts.get(1).and_then(|v| v.parse::().ok()).filter(|v| v.is_finite() && *v > 0.0); + tally.font_sizes += usize::from(size.is_none()); + // Bold from demibold: 63 on Qt 5's scale (to 99), 600 on Qt 6's. + let weight = parts.get(4).and_then(|v| v.parse::().ok()).unwrap_or(50); + let bold = (63..=99).contains(&weight) || weight >= 600; + let italic = parts.get(5) == Some(&"1"); + // Underline and strikeout, which RustGIS's text lacks: said. + let unread = [(parts.get(6) == Some(&"1"), "underlines"), (parts.get(7) == Some(&"1"), "strikeouts")]; + tally.unread_texts += usize::from(unread.iter().any(|(set, _)| *set)); + for (set, what) in unread { + if set && !tally.unread_text.contains(&what) { + tally.unread_text.push(what); + } + } + (size.unwrap_or(10.0), c, bold, italic, 0.0, family) +} + +/// A label's text with its `[% … %]` expressions as RustGIS's layout tokens where one prints +/// the same (its QGIS layout's name, `layout`, as written, its braces as parentheses, counted), or +/// in RustGIS's format (counted); +/// the others kept as written, counted. Its own words keep their braces as parentheses (counted), +/// so only the tokens put here are read as RustGIS's. +pub(super) fn tokens(text: &str, tally: &mut Tally, (page, pages): (usize, usize), layout: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut rest = text; + // The layout's name as written, made once a label prints it. + let mut name: Option = None; + // Its titles (`{map}`), as many bytes as the title a page without a map writes for each. + let mut titles = 0usize; + // The bytes of `out` whose characters are counted, and how many. + let mut seen = (0usize, 0usize); + while let Some(open) = rest.find("[%") { + // Past what a text holds (its characters at most 4 bytes) on a page with a map and on one + // without (its titles written out): it is cut there anyway, and said. + let written_out = out.len().saturating_sub(5 * titles).saturating_add(titles.saturating_mul(tally.title_len)); + if out.len().min(written_out) > 4 * MAX_TEXT { + tally.stopped = true; + return out; + } + written(&mut out, &rest[..open], tally); + let after = &rest[open + 2..]; + let Some(close) = after.find("%]") else { + written(&mut out, &rest[open..], tally); + return out; + }; + let expr = after[..close].trim(); + let compact: String = expr.chars().filter(|c| !c.is_whitespace()).collect::().to_ascii_lowercase(); + // A layout of several pages is a layout a page: its page's number, and how many. + let (number, count) = ((page + 1).to_string(), pages.to_string()); + let token = match compact.as_str() { + "@layout_page" => Some(if pages > 1 { number.as_str() } else { "{page}" }), + "@layout_numpages" => Some(if pages > 1 { count.as_str() } else { "{pages}" }), + "@layout_name" => { + // Written out within what an import writes of names and titles, charged for the + // part a text keeps (its characters before this at least those of `out` without + // its titles); past it, left out. + seen.1 += out[seen.0..].chars().count(); + seen.0 = out.len(); + let room = MAX_TEXT.saturating_sub(seen.1.saturating_sub(5 * titles)); + let name = name.get_or_insert_with(|| as_written(layout)); + let cost = name.char_indices().nth(room).map_or(name.len(), |(i, _)| i); + if tally.title_bytes.saturating_add(cost) > MAX_TITLE_TEXT { + tally.names_left += 1; + Some("") + } else { + tally.title_bytes += cost; + tally.braces += usize::from(name != layout); + Some(name.as_str()) + } + } + "@atlas_pagename" => Some("{pageName}"), + "@map_scale" => { + tally.formats += 1; + Some("{scale}") + } + // The map's coordinate system by its name, where QGIS prints the project's code. + "@project_crs" => { + tally.formats += 1; + Some("{crs}") + } + "@project_title" => { + // The map an import makes is named for the project's title. + tally.project_title += 1; + titles += 1; + Some("{map}") + } + "now()" => { + tally.formats += 1; + Some("{date} {time}") + } + "to_date(now())" => { + tally.formats += 1; + Some("{date}") + } + // A date in a format of its own (the whole expression): RustGIS's date, noted. + e if e.strip_prefix("format_date(now(),'").and_then(|f| f.strip_suffix("')")).is_some_and(|f| !f.contains('\'')) => { + tally.date_formats += 1; + Some("{date}") + } + _ => None, + }; + match token { + Some(t) => out.push_str(t), + None => { + tally.expressions += 1; + written(&mut out, &rest[open..open + 2 + close + 2], tally); + } + } + rest = &after[close + 2..]; + } + written(&mut out, rest, tally); + out +} + +/// `text`, a label's own words, pushed onto `out` as it reads ([`as_written`]): a brace in it is +/// counted, as RustGIS would read it as the start of a token. +fn written(out: &mut String, text: &str, tally: &mut Tally) { + if text.contains(['{', '}']) { + tally.braces += 1; + out.push_str(&as_written(text)); + } else { + out.push_str(text); + } +} + +fn picture_item( + item: Node, + place: &Placed, + id: Option, + dir: &str, + fade: impl Fn(Rgba) -> Rgba, + target: &mut ProjectLayout, + tally: &mut Tally, +) { + let file = item.attribute("file").map(str::trim).unwrap_or_default(); + if item.attribute("mapUuid").is_some_and(|m| !m.trim().is_empty()) && item.attribute("northMode").is_some() { + tally.north_arrows += 1; + return; + } + if file.is_empty() { + tally.no_picture += 1; + return; + } + if file.to_ascii_lowercase().ends_with(".svg") || file.to_ascii_lowercase().ends_with(".svgz") { + tally.svg += 1; + return; + } + let source = match super::source::local_image_source(file, dir) { + Ok(super::source::ImageSource::Base64) => file.to_string(), + Ok(super::source::ImageSource::File(path)) => path, + Err(why) => { + tally.bad_pictures += 1; + if tally.bad_picture.len() < 8 { + tally.bad_picture.push(format!("{}: {why}", picture_named(file))); + } + return; + } + }; + if target.layout.elements.len() >= MAX_ELEMENTS { + tally.over += 1; + return; + } + let mut notes = Vec::new(); + if place.turn.rem_euclid(360.0) != 0.0 || num(item, "pictureRotation").is_some_and(|r| r.rem_euclid(360.0) != 0.0) { + notes.push("turned pictures, drawn upright"); + } + // Resize modes: zoom 0 and zoom-and-resize-frame 3 fit it keeping its aspect, as RustGIS + // draws a picture; stretch 1, clip 2 and frame-to-image-size 4 don't. + let mode = num(item, "resizeMode").unwrap_or(0.0); + if mode == 1.0 || mode == 2.0 || mode == 4.0 { + notes.push("pictures stretched, clipped or sized to their image, drawn fitted in their box"); + } else if mode == 0.0 && num(item, "anchorPoint").is_some_and(|a| a != 4.0) { + // Zoom fits it keeping its aspect at its anchor (QGIS's default the top left); RustGIS + // centres it, which moves one whose aspect isn't its box's. + notes.push("pictures fitted at a corner or side of their box, drawn centred in it"); + } + let element = target.layout.add( + name_or(id, "Picture"), + (place.x, place.y, place.w, place.h), + ElementKind::Picture { image: String::new(), source: None }, + ); + if let Some(e) = target.layout.element_mut(element) { + e.background = backdrop(item, true, place.dpi, &fade); + } + target.pictures.push(LayoutPicture { element, source, notes }); +} + +/// A picture's file as a note names it: its file name, cut to 80 characters; never a web or +/// `file:` address, nor where an attachment or a folder is, which may hold a login or a user's name. +pub fn picture_named(file: &str) -> String { + let file = file.trim(); + let attachment = file.get(..11).is_some_and(|p| p.eq_ignore_ascii_case("attachment:")); + let host = file.starts_with("//") || file.starts_with("\\\\"); + if !attachment && (file.contains("://") || host || file.get(..5).is_some_and(|p| p.eq_ignore_ascii_case("file:"))) { + return "an address".to_string(); + } + // An attachment's address may hold a login (`user:pass@`) or a host before its name: one + // that holds `@` or a further `:` is not named. + if attachment && file.get(11..).is_some_and(|rest| rest.contains(['@', ':'])) { + return "an attachment".to_string(); + } + // Its name (the last part of its path), without a query or fragment (which may hold a key). + let name = file.rsplit(['/', '\\', ':']).next().unwrap_or(file); + let name = name.split(['?', '#']).next().unwrap_or_default(); + name.chars().take(80).collect() +} + +/// A fill symbol's fill, outline and outline width (points), and its outline's dash. +fn fill_of(item: Node, fade: &impl Fn(Rgba) -> Rgba, notes: &mut Report) -> (Rgba, Rgba, f64, Option) { + match item.children().find(|c| c.has_tag_name("symbol")) { + Some(s) => { + let c = symbol::read(s, None, false, "", notes); + let dash = c.strokes.first().and_then(|st| st.dash); + (fade(c.symbol.fill), fade(c.symbol.stroke), f64::from(c.symbol.stroke_width), dash) + } + None => (fade(Rgba::rgb(255, 255, 255)), fade(Rgba::rgb(0, 0, 0)), 0.3 * crate::layout::PT_PER_MM, None), + } +} + +fn shape_item(item: Node, place: &Placed, id: Option, fade: impl Fn(Rgba) -> Rgba, target: &mut ProjectLayout, tally: &mut Tally) { + let (fill, outline, width, dash) = fill_of(item, &fade, &mut tally.notes); + let (x, y, w, h) = (place.x, place.y, place.w, place.h); + let shape = item.attribute("shapeType").unwrap_or("1"); + // A triangle's edges turn with it; a rectangle or an ellipse is drawn upright. + tally.turned_items += usize::from(shape != "2" && place.turn.rem_euclid(360.0) != 0.0); + match shape { + "0" => { + target.layout.add(name_or(id, "Ellipse"), (x, y, w, h), ElementKind::Ellipse { fill, outline, width, dash }); + } + "2" => { + // A triangle: its point at the top's middle. + if fill.a() > 0 { + tally.polygon_fills += 1; + } + let corners = [(w / 2.0, 0.0), (w, h), (0.0, h), (w / 2.0, 0.0)]; + edges(&corners, place, id, outline, width, dash, (false, false), target, tally); + } + _ => { + let radius = item.attribute("cornerRadiusMeasure").and_then(|m| length(m, place.dpi)).unwrap_or(0.0).max(0.0); + target.layout.add(name_or(id, "Rectangle"), (x, y, w, h), ElementKind::Rectangle { fill, outline, width, radius, dash }); + } + } +} + +fn line_item( + item: Node, + kind: &str, + place: &Placed, + id: Option, + fade: impl Fn(Rgba) -> Rgba, + target: &mut ProjectLayout, + tally: &mut Tally, +) { + let (points, cut) = outline(item, kind); + tally.cut_lines += usize::from(cut); + if points.len() < 2 { + tally.unplaced += 1; + return; + } + let (color, width, dash) = if kind == POLYLINE { + match item.children().find(|c| c.has_tag_name("symbol")) { + Some(s) => { + let c = symbol::read(s, None, false, "", &mut tally.notes); + let dash = c.strokes.first().and_then(|st| st.dash); + (fade(c.symbol.stroke), f64::from(c.symbol.stroke_width), dash) + } + None => (fade(Rgba::rgb(0, 0, 0)), 0.3 * crate::layout::PT_PER_MM, None), + } + } else { + let (fill, outline, width, dash) = fill_of(item, &fade, &mut tally.notes); + if fill.a() > 0 { + tally.polygon_fills += 1; + } + (outline, width, dash) + }; + tally.joined_lines += usize::from(points.len() > 2); + // Arrowheads (QGIS's marker modes: 1 an arrowhead; 2 an SVG, drawn as one). + let heads = ( + kind == POLYLINE && num(item, "startMarkerMode").is_some_and(|m| m > 0.0), + kind == POLYLINE && num(item, "markerMode").is_some_and(|m| m > 0.0), + ); + edges(&points, place, id, color, width, dash, heads, target, tally); +} + +/// A line or polygon item's vertices (in its own box), the first [`MAX_NODES`] that read, a polygon +/// closed unless cut short (its last edge would cross it); and whether it was cut. +fn outline(item: Node, kind: &str) -> (Vec<(f64, f64)>, bool) { + let all = child(item, "nodes").map_or(0, |n| n.children().filter(|c| c.has_tag_name("node")).count()); + let cut = all > MAX_NODES; + let mut points: Vec<(f64, f64)> = child(item, "nodes") + .map(|n| { + n.children().filter(|c| c.has_tag_name("node")).filter_map(|c| Some((num(c, "x")?, num(c, "y")?))).take(MAX_NODES).collect() + }) + .unwrap_or_default(); + if kind == POLYGON + && !cut + && points.len() >= 2 + && let Some(first) = points.first().copied() + && points.last() != Some(&first) + { + points.push(first); + } + (points, cut) +} + +/// Whether the edge from `a` to `b` (in an item's own box) is drawn: not of no length. +fn drawn(a: (f64, f64), b: (f64, f64)) -> bool { + (b.0 - a.0).abs() >= 1e-9 || (b.1 - a.1).abs() >= 1e-9 +} + +/// Straight lines along `points` (in the item's own box), turned with it, the start's head on +/// the first edge drawn and the end's on the last. +#[expect(clippy::too_many_arguments, reason = "one edge's look, place and heads, and where it goes")] +fn edges( + points: &[(f64, f64)], + place: &Placed, + id: Option, + color: Rgba, + width: f64, + dash: Option, + (start_head, end_head): (bool, bool), + target: &mut ProjectLayout, + tally: &mut Tally, +) { + let name = name_or(id, "Line"); + // The heads go on the first and last edges drawn (an edge of no length isn't). + let first = points.windows(2).position(|w| drawn(w[0], w[1])); + let last = points.windows(2).rposition(|w| drawn(w[0], w[1])); + for (i, pair) in points.windows(2).enumerate() { + if target.layout.elements.len() >= MAX_ELEMENTS { + // This edge and those after it that would be drawn. + tally.over += points.windows(2).skip(i).filter(|w| drawn(w[0], w[1])).count(); + return; + } + let [(u0, v0), (u1, v1)] = pair else { continue }; + if !drawn((*u0, *v0), (*u1, *v1)) { + continue; + } + let ((x0, y0), (x1, y1)) = (place.at(*u0, *v0), place.at(*u1, *v1)); + let (dx, dy) = (x1 - x0, y1 - y0); + let flat = dy.abs() < 1e-6 * dx.abs().max(1.0) || dy.abs() < 1e-3; + let upright = dx.abs() < 1e-3; + // The line's own way across its box, and whether this edge runs against it. + let (dir, against) = if flat { + (LineDir::Horizontal, dx < 0.0) + } else if upright { + (LineDir::Vertical, dy < 0.0) + } else if (dx > 0.0) == (dy > 0.0) { + (LineDir::Falling, dx < 0.0) + } else { + (LineDir::Rising, dx < 0.0) + }; + let (start, end) = (start_head && Some(i) == first, end_head && Some(i) == last); + let (start, end) = if against { (end, start) } else { (start, end) }; + let head = match (start, end) { + (true, true) => LineHead::Both, + (true, false) => LineHead::Start, + (false, true) => LineHead::End, + (false, false) => LineHead::None, + }; + // A box at least as thick as the line, so a flat or upright one has room. + let thick = (width / crate::layout::PT_PER_MM).max(crate::layout::MIN_ELEMENT_MM); + let (bx, bw) = if upright { (x0 - thick / 2.0, thick) } else { (x0.min(x1), dx.abs()) }; + let (by, bh) = if flat { (y0 - thick / 2.0, thick) } else { (y0.min(y1), dy.abs()) }; + // A side under what an element holds is widened to it when added: said. + tally.thin_edges += usize::from(bw < crate::layout::MIN_ELEMENT_MM || bh < crate::layout::MIN_ELEMENT_MM); + // A hairline (width 0) is drawn thinnest, as QGIS draws one a pixel wide. + let width = width.max(0.1); + target.layout.add(name.clone(), (bx, by, bw, bh), ElementKind::Line { color, width, dir, head, dash }); + } +} + +impl Tally { + pub(super) fn say(&self, report: &mut Report) { + let skipped = [ + (self.legends, "legends"), + (self.scale_bars, "scale bars"), + (self.north_arrows, "north arrows (pictures turned with a map)"), + (self.tables, "attribute tables"), + (self.html, "HTML frames"), + (self.markers, "marker items"), + (self.grids, "map grids"), + (self.overviews, "map overviews"), + (self.atlases, "atlases"), + (self.svg, "SVG pictures (RustGIS's pictures are PNG or JPEG)"), + (self.no_picture, "pictures that name no file"), + (self.unplaced, "items whose place or shape doesn't read"), + (self.no_pages, "layouts with no page that reads, given an A4 page"), + (self.pages_left, &format!("pages past the first {MAX_PAGES} of a layout, or whose size doesn't read")), + (self.off_pages, "items on those pages"), + (self.over, &format!("elements past the {MAX_ELEMENTS} a layout keeps")), + (self.pages_past, &format!("pages past the {MAX_LAYOUTS} layouts an import makes (a page a layout)")), + ( + self.titles_left, + &format!( + "labels showing the project's title past the {} MiB of titles and layout names an import writes out, left without it", + MAX_TITLE_TEXT >> 20 + ), + ), + ( + self.names_left, + &format!( + "layout names past the {} MiB of titles and layout names an import writes out, left out of their labels", + MAX_TITLE_TEXT >> 20 + ), + ), + ]; + for (n, what) in skipped { + if n > 0 { + report.skipped("", format!("its print layouts' {what} ({n})")); + } + } + if self.other > 0 { + let kinds = if self.other_kinds.is_empty() { String::new() } else { format!(": types {}", self.other_kinds.join(", ")) }; + report.skipped("", format!("its print layouts' items of other kinds ({}{kinds})", self.other)); + } + if !self.bad_picture.is_empty() { + let first = + if self.bad_pictures > self.bad_picture.len() { format!("the first {}: ", self.bad_picture.len()) } else { String::new() }; + report.skipped( + "", + format!("its print layouts' pictures that can't be read ({}; {first}{})", self.bad_pictures, self.bad_picture.join("; ")), + ); + } + let approximated = [ + (self.groups, "item groups, their items kept on their own"), + (self.map_backgrounds, "map items' background colours, drawn as the map's own"), + (self.locked_layers, "map items showing a set of layers or a map theme of their own, showing the map's layers"), + (self.turned_items, "turned maps and shapes, drawn upright"), + (self.blended, "items' blending modes, drawn normally"), + (self.translucent, "translucent maps, drawn opaque"), + (self.data_defined, "items with settings set by expressions, drawn as set"), + (self.not_exported, "items left out of exports, kept hidden"), + (self.expressions, "label expressions with no RustGIS counterpart, kept as written"), + (self.project_title, "labels showing the project's title, which show the name of the map the import makes"), + (self.html_labels, "labels in HTML, as their plain text"), + (self.justified, "justified labels, aligned left"), + (self.polygon_fills, "filled polygons and triangles, drawn as their outlines"), + (self.joined_lines, "lines and polygons of several edges, drawn as straight lines that don't join"), + (self.pixels, "item positions in pixels, read at the layout's print resolution"), + (self.oversized, "items larger than 5 m a side, cut to it"), + (self.own_crs, "map items in a coordinate system of their own, showing their extent in the map's"), + ( + self.turned_backgrounds, + "turned labels with a background, whose margins differ across and down, the background reaching the smaller past them", + ), + (self.cut_lines, &format!("lines and polygons of more than {MAX_NODES} vertices, cut there (a polygon left open)")), + (self.cut_texts, &format!("labels longer than {MAX_TEXT} characters, cut there")), + (self.tiny, &format!("items less than {} mm across or down, widened to it", crate::layout::MIN_ELEMENT_MM)), + ( + self.tiny_text, + &format!( + "labels whose margins leave their text less than {} mm across or down, its box widened to it", + crate::layout::MIN_ELEMENT_MM + ), + ), + ( + self.thin_edges, + &format!("edges of lines and polygons less than {} mm across or down, widened to it", crate::layout::MIN_ELEMENT_MM), + ), + ( + self.cut_names, + &format!( + "layout names longer than {MAX_LAYOUT_NAME} characters (a later page's with its number) and item ids longer than {MAX_ELEMENT_NAME}, cut to fit" + ), + ), + (self.date_formats, "dates in a format of their own, in RustGIS's"), + ( + self.formats, + "label expressions printing a date, a time, the map's scale or the map's coordinate system (its name, nothing on a page without a map), in RustGIS's format", + ), + (self.font_sizes, "labels in QGIS 3's older style whose font size doesn't read, drawn at 10 pt"), + (self.label_sizes, "label sizes outside 1 to 400 pt, drawn at the nearest"), + ( + self.braces, + "pieces of labels' text, layout names and project titles with braces, written as parentheses (a brace starts a RustGIS token)", + ), + ]; + for (n, what) in approximated { + if n > 0 { + report.approximated("", format!("its print layouts' {what} ({n})")); + } + } + // What their symbols and sizes noted, as theirs. + report.merge_as("print layouts", &self.notes); + if self.unread_texts > 0 { + report.skipped("", format!("its print layouts' labels' {} ({})", self.unread_text.join(", "), self.unread_texts)); + } + } +} + +/// A number attribute. +fn num(n: Node, k: &str) -> Option { + n.attribute(k).and_then(|v| v.trim().parse::().ok()).filter(|v| v.is_finite()) +} + +/// `x,y,unit` (a position or a size) in millimetres. +fn pair(s: &str, dpi: f64) -> Option<(f64, f64)> { + let mut parts = s.split(',').map(str::trim); + let (x, y, unit) = (parts.next()?.parse::().ok()?, parts.next()?.parse::().ok()?, parts.next().unwrap_or("mm")); + let k = unit_mm(unit, dpi)?; + let (x, y) = (x * k, y * k); + (x.is_finite() && y.is_finite() && x.abs() <= 1e6 && y.abs() <= 1e6).then_some((x, y)) +} + +/// `value,unit` (a measurement) in millimetres. +fn length(s: &str, dpi: f64) -> Option { + let mut parts = s.split(',').map(str::trim); + let (v, unit) = (parts.next()?.parse::().ok()?, parts.next().unwrap_or("mm")); + let v = v * unit_mm(unit, dpi)?; + (v.is_finite() && v.abs() <= 1e6).then_some(v) +} + +/// Millimetres in one of QGIS's layout units. +fn unit_mm(unit: &str, dpi: f64) -> Option { + Some(match unit { + "mm" => 1.0, + "cm" => 10.0, + "m" => 1000.0, + "in" => 25.4, + "ft" => 304.8, + "pt" => 25.4 / 72.0, + "pi" => 25.4 / 6.0, + "px" => 25.4 / dpi, + _ => return None, + }) +} diff --git a/crates/map/src/qgis/layout_tests.rs b/crates/map/src/qgis/layout_tests.rs new file mode 100644 index 0000000000..a4954a6677 --- /dev/null +++ b/crates/map/src/qgis/layout_tests.rs @@ -0,0 +1,1003 @@ +//! QGIS print layouts as RustGIS layouts (piece 12a of #882): the generated map sheets of the +//! corpus, and items written by hand in the shapes QGIS writes them. + +use super::*; +use crate::layout::{ElementKind, LineDir, LineHead, PT_PER_MM, TextAlign, TextVAlign}; + +fn read(text: &str, report: &mut Report) -> Project { + super::read_project(text, "/data/proj", &mut |_, _| Err((super::IMAGE_UNOPENED, false)), report).unwrap() +} + +fn sheets() -> (Project, Report) { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("testdata/qgis/generated/qgs"); + let text = std::fs::read_to_string(root.join("layout-sheets.qgs")).unwrap(); + let mut report = Report::default(); + let p = super::read_project(&text, &root.to_string_lossy(), &mut |_, _| Err((super::IMAGE_UNOPENED, false)), &mut report).unwrap(); + (p, report) +} + +fn near(a: f64, b: f64) -> bool { + (a - b).abs() < 1e-3 +} + +fn text_of<'a>(l: &'a ProjectLayout, text: &str) -> &'a crate::layout::Element { + l.layout.elements.iter().find(|e| matches!(&e.kind, ElementKind::Text { text: t, .. } if t == text)).unwrap() +} + +fn said(report: &Report, part: &str) -> bool { + report.notes.iter().any(|n| n.text.contains(part)) +} + +/// The corpus's A4 sheet of two pages and its Letter sheet, as QGIS 4.4 wrote them: each page a +/// layout, each item where QGIS draws it. +#[test] +fn qgis_map_sheets_come_in_as_layouts() { + let (p, report) = sheets(); + let names: Vec<&str> = p.layouts.iter().map(|l| l.layout.name.as_str()).collect(); + assert_eq!(names, ["Sheet A4", "Sheet A4 (page 2)", "Sheet Letter"]); + let a4 = &p.layouts[0]; + assert!(near(a4.layout.width, 297.0) && near(a4.layout.height, 210.0)); + let letter = &p.layouts[2]; + assert!(near(letter.layout.width, 215.9) && near(letter.layout.height, 279.4), "{} {}", letter.layout.width, letter.layout.height); + + // The map item, bottom of the drawing order (its `zValue` is the lowest), framed and turned. + let map = &a4.layout.elements[0]; + assert!((near(map.x, 10.0), near(map.y, 25.0), near(map.w, 200.0), near(map.h, 150.0)) == (true, true, true, true), "{map:?}"); + let ElementKind::MapFrame { bearing, border_color, border_width, .. } = &map.kind else { panic!("{:?}", map.kind) }; + assert!(near(*bearing, -10.0)); + assert_eq!(*border_color, Rgba::rgb(40, 40, 120)); + assert!(near(*border_width, 0.6 * PT_PER_MM)); + assert_eq!(a4.frames.len(), 1); + assert_eq!(a4.frames[0].element, map.id); + assert_eq!(a4.frames[0].extent, [2696300.0, 1261200.0, 2698000.0, 1262475.0]); + assert_eq!(a4.frames[0].crs, None); + + // The title: bold, coloured, centred across and down. + let title = text_of(a4, "Sample sheet"); + let ElementKind::Text { size, color, bold, align, valign, wrap, font_name, rotation, .. } = &title.kind else { + panic!("not the kind expected") + }; + assert!(near(*size, 20.0) && *bold && *wrap && near(*rotation, 0.0)); + assert_eq!((*color, *align, *valign), (Rgba::rgb(20, 60, 140), TextAlign::Center, TextVAlign::Middle)); + assert_eq!(font_name.as_deref(), Some("DejaVu Sans")); + // In centimetres, its margins inside its box; its expressions as tokens. + let made = text_of(a4, "Made {date} for {map}"); + assert!(near(made.x, 216.0) && near(made.y, 201.5) && near(made.w, 68.0) && near(made.h, 7.0), "{made:?}"); + assert!(matches!(made.kind, ElementKind::Text { align: TextAlign::Right, .. })); + // Turned about its centre: its box the unturned one, where it was placed. + let note = text_of(a4, "Turned note"); + assert!(near(note.x, 230.0) && near(note.y, 120.0) && near(note.w, 50.0) && near(note.h, 10.0), "{note:?}"); + assert!(matches!(note.kind, ElementKind::Text { rotation, .. } if near(rotation, -30.0))); + let b = note.background.unwrap(); + assert_eq!((b.fill, b.outline), (Rgba::rgb(255, 250, 200), Rgba::rgb(160, 120, 0))); + assert!(near(b.width, 0.3 * PT_PER_MM)); + + // The picture, in inches, from its file beside the project. + assert_eq!(a4.pictures.len(), 1); + let pic = a4.layout.element(a4.pictures[0].element).unwrap(); + assert!(near(pic.x, 8.9 * 25.4) && near(pic.y, 0.4 * 25.4) && near(pic.w, 1.6 * 25.4), "{pic:?}"); + assert!(a4.pictures[0].source.replace('\\', "/").ends_with("data/picture.png"), "{}", a4.pictures[0].source); + + // The rounded rectangle in points; the half-transparent ellipse. + let rect = a4.layout.elements.iter().find(|e| matches!(e.kind, ElementKind::Rectangle { .. })).unwrap(); + assert!(near(rect.x, 650.0 * 25.4 / 72.0) && near(rect.w, 150.0 * 25.4 / 72.0)); + let ElementKind::Rectangle { fill, outline, width, radius, .. } = rect.kind else { panic!("not the kind expected") }; + assert_eq!((fill, outline), (Rgba::rgb(255, 230, 200), Rgba::rgb(200, 100, 0))); + assert!(near(radius, 3.0) && near(width, 0.8 * 96.0 / 25.4), "{width}"); + let ellipse = a4.layout.elements.iter().find(|e| matches!(e.kind, ElementKind::Ellipse { .. })).unwrap(); + assert!(matches!(ellipse.kind, ElementKind::Ellipse { fill, .. } if fill == Rgba::new(120, 200, 120, 128))); + + // The triangle's three edges; the polyline's two, dashed, falling to the right. + let lines: Vec<_> = a4.layout.elements.iter().filter(|e| matches!(e.kind, ElementKind::Line { .. })).collect(); + assert_eq!(lines.len(), 5); + let red: Vec<_> = lines.iter().filter(|e| matches!(e.kind, ElementKind::Line { color, .. } if color == Rgba::rgb(200, 0, 0))).collect(); + assert_eq!(red.len(), 2); + assert!(matches!(red[0].kind, ElementKind::Line { dir: LineDir::Horizontal, head: LineHead::None, dash: Some(_), .. })); + assert!(near(red[0].x, 10.0) && near(red[0].w, 110.0), "{:?}", red[0]); + assert!(matches!(red[1].kind, ElementKind::Line { dir: LineDir::Falling, .. })); + assert!(near(red[1].x, 120.0) && near(red[1].y, 182.0) && near(red[1].w, 20.0) && near(red[1].h, 13.0), "{:?}", red[1]); + + // Hidden, and left out of exports: kept hidden. Grouped: kept. + assert!(!text_of(a4, "Hidden").visible && !text_of(a4, "Not exported").visible); + assert!(text_of(a4, "Grouped A").visible && text_of(a4, "Grouped B").visible); + // The second page's label, on its own page. + let second = text_of(&p.layouts[1], "Second page"); + assert!(near(second.x, 10.0) && near(second.y, 0.0)); + + for part in [ + "print layouts of several pages, each page a layout of its own (1: Sheet A4)", + "item groups, their items kept on their own (1)", + "items left out of exports, kept hidden (1)", + "labels showing the project's title", + "filled polygons and triangles, drawn as their outlines (1)", + "map items' background colours", + ] { + assert!(said(&report, part), "{part}: {:?}", report.notes); + } + assert!(!said(&report, "print layouts (") && !said(&report, "label expressions"), "{:?}", report.notes); +} + +/// The corpus's layout of every item: what a RustGIS layout has no place for is noted, kind by +/// kind. +#[test] +fn qgis_layout_items_without_a_place_are_noted() { + let root = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("testdata/qgis/generated/qgs"); + let text = std::fs::read_to_string(root.join("layout-every-item-atlas.qgs")).unwrap(); + let mut report = Report::default(); + let p = super::read_project(&text, &root.to_string_lossy(), &mut |_, _| Err((super::IMAGE_UNOPENED, false)), &mut report).unwrap(); + assert_eq!(p.layouts.len(), 1); + for part in [ + "legends (1)", + "scale bars (1)", + "north arrows (pictures turned with a map) (1)", + "attribute tables (1)", + "HTML frames (1)", + "marker items (1)", + "atlases (1)", + "labels showing the project's title", + ] { + assert!(said(&report, part), "{part}: {:?}", report.notes); + } +} + +const PLAIN: &str = r#"T + EPSG:2056 + + + + + + + + + + + + "#; + +/// A layout QGIS draws as RustGIS does says nothing; one with items RustGIS can't carry over says +/// what (never silent, both ways). +#[test] +fn a_plain_layout_comes_in_without_a_note() { + let mut report = Report::default(); + let p = read(PLAIN, &mut report); + assert_eq!(p.layouts.len(), 1); + assert_eq!(p.layouts[0].layout.elements.len(), 2); + assert!(report.notes.is_empty(), "{:?}", report.notes); + let lossy = PLAIN + .replace(r#"zValue="2""#, r#"zValue="2" blendMode="6" itemRotation="0""#) + .replace("labelText=\"Plan\"", "labelText=\"Plan [% @atlas_featurenumber %]\""); + let mut report = Report::default(); + read(&lossy, &mut report); + assert!(said(&report, "blending modes, drawn normally (1)"), "{:?}", report.notes); + assert!(said(&report, "label expressions with no RustGIS counterpart, kept as written (1)"), "{:?}", report.notes); +} + +/// Expressions printing what a RustGIS token prints become that token; others are kept. +#[test] +fn label_expressions_become_tokens() { + let mut tally = layout::Tally::default(); + let text = "p [% @layout_page %]/[%@layout_numpages%] [% @map_scale %] [% now() %] [% 1+1 %] [% unclosed"; + let t = layout::tokens(text, &mut tally, (0, 1), "Plan"); + assert_eq!(t, "p {page}/{pages} {scale} {date} {time} [% 1+1 %] [% unclosed"); + assert_eq!(tally.expressions, 1); + // A layout of several pages is a layout a page: its own number, and how many there were; its + // name the QGIS layout's on each. + assert_eq!( + layout::tokens("[% @layout_page %] of [% @layout_numpages %] of [% @layout_name %]", &mut tally, (1, 3), "Plan"), + "2 of 3 of Plan" + ); + // What prints in RustGIS's format (a date and time, a scale) is said; the page tokens print + // the same, unsaid. + let mut report = Report::default(); + tally.say(&mut report); + assert!( + said( + &report, + "the map's scale or the map's coordinate system (its name, nothing on a page without a map), in RustGIS's format (2)" + ), + "{:?}", + report.notes + ); + let mut tally = layout::Tally::default(); + layout::tokens("[% @layout_page %] [% @layout_name %]", &mut tally, (0, 1), "Plan"); + let mut report = Report::default(); + tally.say(&mut report); + assert!(report.notes.is_empty(), "{:?}", report.notes); +} + +/// QGIS places an item by its reference point after its turn: the box it comes in as is the +/// unturned one with the same centre, whichever point it is placed by. +#[test] +fn a_turned_item_is_placed_by_its_reference_point() { + for (r, (px, py)) in [(0, (0.0, 0.0)), (4, (25.0, 5.0)), (8, (50.0, 10.0))] { + // A 50 × 10 box at 100, 100, turned 90° clockwise about its centre (125, 105). + let (sin, cos) = 90f64.to_radians().sin_cos(); + let (dx, dy) = (px - 25.0, py - 5.0); + let (x, y) = (125.0 + dx * cos - dy * sin, 105.0 + dx * sin + dy * cos); + let qgs = PLAIN.replace( + r#"position="10,165,mm" size="190,10,mm""#, + &format!(r#"position="{x},{y},mm" size="50,10,mm" itemRotation="90" referencePoint="{r}""#), + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + let e = text_of(&p.layouts[0], "Plan"); + assert!(near(e.x, 100.0) && near(e.y, 100.0), "{r}: {e:?}"); + assert!(matches!(e.kind, ElementKind::Text { rotation, .. } if near(rotation, 90.0))); + } +} + +/// An item on a later page is on that page's layout, placed on it; a layout without pages is A4. +#[test] +fn items_land_on_their_page() { + let qgs = PLAIN + .replace(r#""#, r#""#) + .replace(r#"position="10,165,mm""#, r#"position="10,320,mm""#); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + assert_eq!(p.layouts.len(), 2); + assert!(near(p.layouts[1].layout.width, 297.0)); + assert!(near(text_of(&p.layouts[1], "Plan").y, 13.0)); + assert!(p.layouts[0].layout.elements.iter().all(|e| !matches!(e.kind, ElementKind::Text { .. }))); + let mut report = Report::default(); + let p = read(r#""#, &mut report); + assert_eq!(p.layouts.len(), 1); + assert_eq!(p.layouts[0].layout.name, "Layout"); + assert!(near(p.layouts[0].layout.width, 210.0)); + assert!(said(&report, "print composers of QGIS 2 (1)"), "{:?}", report.notes); +} + +/// Hostile layouts: numbers that aren't, units that aren't, huge counts, no panics and bounded +/// output. +#[test] +fn hostile_layouts_are_bounded() { + let mut items = String::new(); + for i in 0..700 { + items.push_str(&format!(r#""#)); + } + items.push_str(r#""#); + items.push_str(r#""#); + items.push_str(r#""#); + items.push_str(r#""#); + let qgs = format!( + r#"{items}"# + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + assert!(p.layouts.iter().all(|l| l.layout.elements.len() <= layout::MAX_ELEMENTS)); + assert!(said(&report, "elements past the 500 a layout keeps"), "{:?}", report.notes); + assert!(said(&report, "items whose place or shape doesn't read (3)"), "{:?}", report.notes); + assert!(said(&report, "items of other kinds (1: types 99999)"), "{:?}", report.notes); +} + +/// What the layouts cut or read in part is said: a long label, a line of too many vertices (a +/// polygon cut so left open), the pages past those read and their items, a map in a coordinate +/// system of its own, and what reading a shape's symbol notes. A picture left out counts for +/// nothing else. +#[test] +fn what_a_layout_cuts_is_said() { + let long = "x".repeat(6_000); + let nodes: String = (0..201).map(|i| format!(r#""#, i % 7, i % 5)).collect(); + let mut pages = String::new(); + for i in 0..52 { + pages.push_str(&format!(r#""#, i * 307)); + } + let qgs = format!( + r#"{pages} + + {nodes} + + + EPSG:4326 + + + + "#, + far = 51 * 307 + 10 + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + assert_eq!(p.layouts.len(), 50); + let first = &p.layouts[0]; + assert!(first.layout.elements.iter().any(|e| matches!(&e.kind, ElementKind::Text { text, .. } if text.chars().count() == 5_000))); + let lines = first.layout.elements.iter().filter(|e| matches!(e.kind, ElementKind::Line { .. })).count(); + assert_eq!(lines, 199, "200 vertices kept, the polygon left open"); + for part in [ + "labels longer than 5000 characters, cut there (1)", + "lines and polygons of more than 200 vertices, cut there (a polygon left open) (1)", + "pages past the first 50 of a layout, or whose size doesn't read (2)", + "items on those pages (1)", + "map items in a coordinate system of their own", + "SVG pictures", + ] { + assert!(said(&report, part), "{part}: {:?}", report.notes); + } + assert!(report.notes.iter().any(|n| n.layer == "print layouts"), "the shape's symbol notes: {:?}", report.notes); + assert!(!said(&report, "translucent") && !said(&report, "left out of exports"), "{:?}", report.notes); +} + +/// An upright label's background and frame fill its whole box, under its margins: a rectangle +/// under the text, which sits inside its margins. +#[test] +fn a_labels_background_fills_its_box() { + let qgs = PLAIN.replace( + r#"halign="1" valign="32">"#, + r#"halign="1" valign="32" marginX="0" marginY="4" background="true" frame="true" opacity="0.5" outlineWidthM="0.5,mm">"#, + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + let l = &p.layouts[0].layout; + let back = l.elements.iter().find(|e| matches!(e.kind, ElementKind::Rectangle { .. })).unwrap(); + assert!(near(back.x, 10.0) && near(back.y, 165.0) && near(back.w, 190.0) && near(back.h, 10.0), "{back:?}"); + let ElementKind::Rectangle { fill, outline, width, .. } = back.kind else { panic!("not the kind expected") }; + assert_eq!((fill, outline), (Rgba::new(255, 255, 0, 128), Rgba::new(0, 0, 255, 128)), "faded with the item"); + assert!(near(width, 0.5 * PT_PER_MM)); + let text = text_of(&p.layouts[0], "Plan"); + assert!(near(text.x, 10.0) && near(text.y, 169.0) && near(text.h, 2.0) && text.background.is_none(), "{text:?}"); + let back_at = l.elements.iter().position(|e| e.id == back.id).unwrap(); + let text_at = l.elements.iter().position(|e| e.id == text.id).unwrap(); + assert!(back_at < text_at, "under it"); +} + +/// The page count a label prints is the QGIS layout's, though the pages past those read are left +/// out; names and ids too long are cut and said; page entries past those looked at are said. +#[test] +fn page_counts_and_names_are_kept_or_said() { + let mut pages = String::new(); + for i in 0..52 { + pages.push_str(&format!(r#""#, i * 307)); + } + let long = "N".repeat(201); + let id = "i".repeat(101); + let qgs = format!( + r#"{pages} + + "# + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + assert!(text_of(&p.layouts[0], "1 of 52").name.chars().count() == 100); + assert_eq!(p.layouts[0].layout.name.chars().count(), 200); + // The name, the id, and the 49 later pages' names cut to fit their page numbers. + assert!( + said( + &report, + "layout names longer than 200 characters (a later page's with its number) and item ids longer than 100, cut to fit (51)" + ), + "{:?}", + report.notes + ); + let mut many = String::new(); + for _ in 0..10_001 { + many.push_str(r#""#); + } + let mut report = Report::default(); + read(&format!(r#"{many}"#), &mut report); + assert!(said(&report, "pages past the first 50 of a layout, or whose size doesn't read (9951)"), "{:?}", report.notes); +} + +/// A label that would come in as a rectangle under its text takes both or neither when the +/// layout is nearly full; a line cut off there counts the edges it loses. +#[test] +fn a_full_layout_counts_what_it_leaves_out() { + let mut items = String::new(); + for i in 0..499 { + items.push_str(&format!(r#""#)); + } + items.push_str(r#""#); + let qgs = format!(r#"{items}"#); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + let l = &p.layouts[0].layout; + assert_eq!(l.elements.len(), 499); + assert!(l.elements.iter().all(|e| !matches!(e.kind, ElementKind::Rectangle { .. })), "no background without its text"); + assert!(said(&report, "elements past the 500 a layout keeps (2)"), "{:?}", report.notes); + let mut items = String::new(); + for i in 0..495 { + items.push_str(&format!(r#""#)); + } + let nodes: String = (0..11).map(|i| format!(r#""#, i, i % 2)).collect(); + items.push_str(&format!(r#"{nodes}"#)); + let mut report = Report::default(); + read(&format!(r#"{items}"#), &mut report); + assert!(said(&report, "elements past the 500 a layout keeps (5)"), "{:?}", report.notes); + // A line arriving at a full layout counts its edges. + let nodes: String = (0..11).map(|i| format!(r#""#, i, i % 2)).collect(); + let mut items = String::new(); + for i in 0..500 { + items.push_str(&format!(r#""#)); + } + items.push_str(&format!(r#"{nodes}"#)); + let mut report = Report::default(); + read(&format!(r#"{items}"#), &mut report); + assert!(said(&report, "elements past the 500 a layout keeps (10)"), "{:?}", report.notes); + // A label left out counts for nothing else: not its title, length or size. + let mut items = String::new(); + for i in 0..500 { + items.push_str(&format!(r#""#)); + } + let long = "x".repeat(5001); + items.push_str(&format!(r#""#)); + let mut report = Report::default(); + read(&format!(r#"T{items}"#), &mut report); + assert!(said(&report, "elements past the 500 a layout keeps (1)"), "{:?}", report.notes); + for part in ["labels longer than", "larger than 5 m", "project's title", "RustGIS's format", "braces"] { + assert!(!said(&report, part), "{part}: {:?}", report.notes); + } +} + +/// A page left out still counts in the page numbers labels print: the third page is page 3. +#[test] +fn a_page_number_is_the_qgis_pages() { + let qgs = r#" + + + + + "#; + let mut report = Report::default(); + let p = read(qgs, &mut report); + assert_eq!(p.layouts.len(), 2); + text_of(&p.layouts[1], "3 of 3"); + // Named for its place among the QGIS layout's pages, as its label numbers it. + assert_eq!(p.layouts[1].layout.name, "P (page 3)"); +} + +/// What reading the items' symbols notes is said once a kind, with how many items said it. +#[test] +fn symbol_notes_keep_their_count() { + let shape = r#""#; + let qgs = format!(r#"{shape}{shape}"#); + let mut report = Report::default(); + read(&qgs, &mut report); + let notes: Vec<_> = report.notes.iter().filter(|n| n.layer == "print layouts").collect(); + assert!(!notes.is_empty() && notes.iter().all(|n| n.count == 2), "{:?}", report.notes); +} + +/// A date in a format of its own is RustGIS's date, said; a date joined to more is kept. +#[test] +fn only_a_whole_date_expression_becomes_the_date() { + let mut tally = layout::Tally::default(); + assert_eq!(layout::tokens("[% format_date(now(), 'dd.MM.yyyy') %]", &mut tally, (0, 1), "L"), "{date}"); + let kept = "[% format_date(now(),'yyyy') || ' report' %]"; + assert_eq!(layout::tokens(kept, &mut tally, (0, 1), "L"), kept); + assert_eq!(tally.expressions, 1); +} + +/// An item larger than a layout's elements are (5 m a side) is cut to it, said; nine unreadable +/// pictures are counted, the first eight named. +#[test] +fn oversized_items_and_unread_pictures_are_counted() { + let mut items = String::from(r#""#); + for i in 0..9 { + items.push_str(&format!(r#""#)); + } + let mut report = Report::default(); + let p = read(&format!(r#"{items}"#), &mut report); + assert!(near(text_of(&p.layouts[0], "Wide").w, 5000.0)); + assert!(said(&report, "items larger than 5 m a side, cut to it (1)"), "{:?}", report.notes); + assert!(said(&report, "pictures that can't be read (9; the first 8: "), "{:?}", report.notes); + // A web address is never quoted (it may hold a login), a folder's path neither. + let qgs = r#""#; + let mut report = Report::default(); + read(qgs, &mut report); + assert!(said(&report, "an address: whose image is at a web address"), "{:?}", report.notes); + assert!(said(&report, "pic.png: whose image is kept inside the .qgz"), "{:?}", report.notes); + assert!(report.notes.iter().all(|n| !n.text.contains("s3cret") && !n.text.contains("someone")), "{:?}", report.notes); + // Nor one given without its scheme, nor a query on a file's name. + let qgs = r#""#; + let mut report = Report::default(); + read(qgs, &mut report); + assert!(report.notes.iter().all(|n| !n.text.contains("s3cret") && !n.text.contains("cdn.")), "{:?}", report.notes); + // A folder whose name holds a `?` or `#` is never named either. + assert_eq!(layout::picture_named("/home/bob?x/logo.png"), "logo.png"); + assert_eq!(layout::picture_named(r"C:\Users\bob#1\logo.png?k=1"), "logo.png"); + // An attachment's address with a login or a host is not named; one of its own name is. + for a in ["attachment://user:pw@example.invalid/p.png", "attachment:user@example.invalid"] { + let named = layout::picture_named(a); + assert!(!named.contains("pw") && !named.contains("example.invalid"), "{named}"); + } + assert_eq!(layout::picture_named("attachment:///abc_logo.png"), "abc_logo.png"); +} + +/// Notes merged into a report past its cap count every occurrence in its closing note. +#[test] +fn merged_notes_keep_their_count_past_the_cap() { + let mut report = Report::default(); + for i in 0..5000 { + report.skipped("", format!("note {i}")); + } + let mut other = Report::default(); + for _ in 0..40 { + other.skipped("", "late"); + } + report.merge_as("print layouts", &other); + let closing = report.notes.last().unwrap(); + assert_eq!(closing.count, 40, "{closing:?}"); + assert!(closing.text.contains("40 more note(s) not listed"), "{closing:?}"); + // A report merged past its own cap: its closing note is counted in this one's, not listed. + let mut report = Report::default(); + report.skipped("", "mine"); + let mut other = Report::default(); + for i in 0..5003 { + other.skipped("", format!("note {i}")); + } + report.merge_as("print layouts", &other); + assert!(report.notes.iter().all(|n| n.layer.is_empty() || !n.text.contains("not listed")), "{:?}", report.notes.last()); + let closing = report.notes.last().unwrap(); + // 4,999 of `other`'s listed notes fit beside "mine"; its last listed one and its 3 past the cap don't. + assert_eq!((closing.count, closing.text.as_str()), (4, "4 more note(s) not listed"), "{closing:?}"); +} + +/// Pictures that never come in as elements (north arrows, SVGs, no file, a path that doesn't +/// check) aren't counted past a full layout: they are said as what they are; a picture that +/// would come in is. +#[test] +fn a_full_layout_counts_only_pictures_that_would_come_in() { + let mut items = String::new(); + for i in 0..500 { + items.push_str(&format!(r#""#)); + } + for _ in 0..3 { + items.push_str( + r#""#, + ); + } + items.push_str(r#""#); + items.push_str(r#""#); + items.push_str( + r#""#, + ); + let page = r#""#; + let qgs = format!(r#"{page}{items}"#); + let mut report = Report::default(); + read(&qgs, &mut report); + assert!(!said(&report, "elements past the 500"), "{:?}", report.notes); + assert!(said(&report, "north arrows (pictures turned with a map) (3)"), "{:?}", report.notes); + assert!(said(&report, "pictures that can't be read (1;"), "{:?}", report.notes); + // What doesn't come in isn't said as drawn otherwise. + assert!(!said(&report, "blending modes"), "{:?}", report.notes); + let one = items + r#""#; + let mut report = Report::default(); + read(&format!(r#"{page}{one}"#), &mut report); + assert!(said(&report, "elements past the 500 a layout keeps (1)"), "{:?}", report.notes); +} + +/// A layout with no page that reads is given an A4 page, said; one with its page says nothing. +#[test] +fn a_layout_without_a_page_is_given_a4_said() { + let label = r#""#; + let mut report = Report::default(); + let p = read(&format!(r#"{label}"#), &mut report); + assert!(near(p.layouts[0].layout.width, 210.0) && near(p.layouts[0].layout.height, 297.0)); + assert!(said(&report, "layouts with no page that reads, given an A4 page (1)"), "{:?}", report.notes); + // A collection whose only page doesn't read is given one too, and keeps its label. + let unread = r#""#; + let mut report = Report::default(); + let p = read(&format!(r#"{unread}{label}"#), &mut report); + assert!(near(p.layouts[0].layout.width, 210.0) && near(p.layouts[0].layout.height, 297.0)); + text_of(&p.layouts[0], "A"); + assert!(said(&report, "layouts with no page that reads, given an A4 page (1)"), "{:?}", report.notes); + assert!(said(&report, "or whose size doesn't read (1)"), "{:?}", report.notes); + let page = r#""#; + let mut report = Report::default(); + read(&format!(r#"{page}{label}"#), &mut report); + assert!(report.notes.is_empty(), "{:?}", report.notes); +} + +/// `@layout_name` prints the QGIS layout's whole name, though the layout's own is cut to 200. +#[test] +fn a_label_prints_the_whole_layout_name() { + let long = "N".repeat(201); + let qgs = format!( + r#""# + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + assert_eq!(p.layouts[0].layout.name.chars().count(), 200); + text_of(&p.layouts[0], &long); +} + +/// The pages of all the layouts together make no more than the layouts an import keeps: six +/// layouts of 45 pages make 200, the 25 pages past them and the layout with none left said. +#[test] +fn pages_past_the_layouts_an_import_makes_are_said() { + let pages: String = (0..45).map(|i| format!(r#""#, i * 307)).collect(); + let layouts: String = (0..6).map(|i| format!(r#"{pages}"#)).collect(); + let mut report = Report::default(); + let p = read(&format!("{layouts}"), &mut report); + assert_eq!(p.layouts.len(), layout::MAX_LAYOUTS); + assert!(said(&report, "pages past the 200 layouts an import makes (a page a layout) (25)"), "{:?}", report.notes); + assert!(said(&report, "its print layouts past the 200 layouts an import makes (a page a layout) (1)"), "{:?}", report.notes); +} + +/// The project's title written out on pages without a map stops at what an import writes out of +/// it (4 MiB): the labels past it are left without it, said, and the text kept stays within it. +#[test] +fn written_out_titles_are_bounded_over_the_import() { + let title = "T".repeat(5000); + let labels: String = + (0..500).map(|_| r#""#).collect(); + let layouts: String = (0..2).map(|i| format!(r#"{labels}"#)).collect(); + let mut report = Report::default(); + let p = read(&format!("{title}{layouts}"), &mut report); + let kept: usize = p + .layouts + .iter() + .flat_map(|l| &l.layout.elements) + .map(|e| if let ElementKind::Text { text, .. } = &e.kind { text.len() } else { 0 }) + .sum(); + assert!(kept <= 4 << 20, "{kept}"); + // 838 labels of 5,000 bytes fit in 4 MiB; the other 162 are left without it. + assert!(said(&report, "past the 4 MiB of titles and layout names an import writes out, left without it (162)"), "{:?}", report.notes); + // A layout's name printed in each label is bounded the same way, charged for what the label + // keeps: printed four times, only the first fits in a text, so it costs as much as once. + let name = "N".repeat(4999); + for (times, left) in [(1, 162), (4, 162 * 4)] { + let printed = "[% @layout_name %]".repeat(times); + let labels: String = + (0..500).map(|_| format!(r#""#)).collect(); + let layouts: String = (0..2).map(|i| format!(r#"{labels}"#)).collect(); + let mut report = Report::default(); + let p = read(&format!("{layouts}"), &mut report); + let kept: usize = p + .layouts + .iter() + .flat_map(|l| &l.layout.elements) + .map(|e| if let ElementKind::Text { text, .. } = &e.kind { text.len() } else { 0 }) + .sum(); + assert!(kept <= 4 << 20, "{kept}"); + // 5,000 bytes a label: 838 fit in 4 MiB, 162 are left out (each of their names). + let note = + format!("layout names past the 4 MiB of titles and layout names an import writes out, left out of their labels ({left})"); + assert!(said(&report, ¬e), "{times}: {:?}", report.notes); + } +} + +/// A polygon cut at 200 vertices is left open, so a full layout counts the 199 edges it would +/// draw; an ordinary unclosed ring counts its closing edge. +#[test] +fn a_full_layout_counts_the_edges_a_polygon_would_draw() { + let full: String = + (0..500).map(|i| format!(r#""#)).collect(); + for (n, edges) in [(201, 199), (4, 4)] { + let nodes: String = (0..n).map(|i| format!(r#""#, i, i % 2)).collect(); + let polygon = + format!(r#"{nodes}"#); + let mut report = Report::default(); + read(&format!(r#"{full}{polygon}"#), &mut report); + assert!(said(&report, &format!("elements past the 500 a layout keeps ({edges})")), "{n}: {:?}", report.notes); + } + // A polygon of one point repeated draws nothing, so a full layout leaves nothing out for it. + let polygon = r#""#; + let mut report = Report::default(); + read(&format!(r#"{full}{polygon}"#), &mut report); + assert!(!said(&report, "elements past the 500"), "{:?}", report.notes); +} + +/// A line's arrowheads go on its first and last edges drawn, past a repeated vertex at either end. +#[test] +fn arrowheads_go_on_the_edges_drawn() { + let qgs = r#""#; + let mut report = Report::default(); + let p = read(qgs, &mut report); + let heads: Vec = p.layouts[0] + .layout + .elements + .iter() + .filter_map(|e| if let ElementKind::Line { head, .. } = e.kind { Some(head) } else { None }) + .collect(); + assert_eq!(heads, vec![LineHead::Both]); +} + +/// An item narrower than an element can be is widened to it, and said; one of a usual size isn't. +#[test] +fn tiny_items_are_said() { + for (w, said) in [("0", true), ("20", false)] { + let qgs = format!( + r#""# + ); + let mut report = Report::default(); + read(&qgs, &mut report); + let noted = report.notes.iter().any(|n| n.text.contains("items less than 0.05 mm across or down, widened to it (1)")); + assert_eq!(noted, said, "{w}: {:?}", report.notes); + } +} + +/// A label whose margins fill its box has its text box widened to an element's least size, and +/// said; margins that leave room say nothing. +#[test] +fn labels_filled_by_their_margins_are_said() { + // A label too narrow itself, filled down by its margins, says both. + for (margin, size, said) in [("10", "20,5", true), ("9.99", "20,5", true), ("2", "20,5", false), ("0\" marginY=\"10", "0.04,20", true)] + { + let qgs = format!( + r#""# + ); + let mut report = Report::default(); + read(&qgs, &mut report); + let noted = report + .notes + .iter() + .any(|n| n.text.contains("labels whose margins leave their text less than 0.05 mm across or down, its box widened to it (1)")); + assert_eq!(noted, said, "{margin}: {:?}", report.notes); + let small = report.notes.iter().any(|n| n.text.contains("items less than")); + assert_eq!(small, size.starts_with("0.04"), "{margin}: {:?}", report.notes); + } +} + +/// A slanted edge whose box is thinner than an element can be is widened to it, and said; a +/// clean line says nothing. +#[test] +fn thin_slanted_edges_are_said() { + for (y, said) in [("0.02", true), ("5", false)] { + let qgs = format!( + r#""# + ); + let mut report = Report::default(); + read(&qgs, &mut report); + let noted = report.notes.iter().any(|n| n.text.contains("less than 0.05 mm across or down, widened to it (1)")); + assert_eq!(noted, said, "{y}: {:?}", report.notes); + } +} + +/// A picture fitted at a corner of its box (QGIS's zoom mode) is drawn centred, noted with it; +/// one fitted at its centre is not. +#[test] +fn a_pictures_anchor_is_said() { + for (anchor, noted) in [("0", true), ("4", false)] { + let qgs = format!( + r#""# + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + // Said by the engine once the picture reads (one that doesn't is left out, so isn't). + let notes = &p.layouts[0].pictures[0].notes; + assert_eq!(notes.contains(&"pictures fitted at a corner or side of their box, drawn centred in it"), noted, "{anchor}: {notes:?}"); + } +} + +/// An item is on the page QGIS saves it on (`positionOnPage`), or, without it, the one its top +/// left corner is on: a tall label from the foot of page 1 stays there, hanging past its foot. +#[test] +fn an_item_is_on_the_page_its_top_is_on() { + let pages = r#""#; + for on_page in [r#" positionOnPage="10,285,mm""#, ""] { + let label = format!(r#""#); + let mut report = Report::default(); + let p = read(&format!(r#"{pages}{label}"#), &mut report); + let tall = text_of(&p.layouts[0], "Tall"); + assert!(near(tall.y, 285.0), "{on_page}: {tall:?}"); + assert!(p.layouts[1].layout.elements.is_empty()); + } + // Saved on page 2 (its top 307 mm down): there, though its box starts a little above it. + let label = r#""#; + let mut report = Report::default(); + let p = read(&format!(r#"{pages}{label}"#), &mut report); + assert!(near(text_of(&p.layouts[1], "Second").y, -0.5)); +} + +/// Each page takes its own paper, else its collection's; white is no paper. +#[test] +fn each_page_takes_its_own_paper() { + let fill = |c: &str| { + format!( + r#""# + ) + }; + let qgs = format!( + r#"{}{}{}"#, + fill("255,255,200,255"), + fill("0,0,255,255"), + fill("255,255,255,255") + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + let papers: Vec> = p.layouts.iter().map(|l| l.layout.paper).collect(); + assert_eq!(papers, [Some(Rgba::rgb(255, 255, 200)), Some(Rgba::rgb(0, 0, 255)), None]); +} + +/// A label in QGIS 3's older style (`LabelFont`, `FontColor`) keeps its font, size and colour; a +/// size that doesn't read is 10 pt, said. +#[test] +fn a_label_in_the_older_style_keeps_its_font() { + let page = r#""#; + let label = |font: &str| { + format!( + r#"{page}"# + ) + }; + for font in ["Serif Name,24,-1,5,75,1,0,0,0,0", "Serif Name,24,-1,5,700,1,0,0,0,0,0,0,0,0,0,1"] { + let mut report = Report::default(); + let p = read(&label(font), &mut report); + let ElementKind::Text { size, color, bold, italic, font_name, .. } = &text_of(&p.layouts[0], "Old").kind else { + panic!("not text") + }; + assert!(near(*size, 24.0) && *bold && *italic, "{font}"); + assert_eq!(*color, Rgba::rgb(200, 0, 0)); + assert_eq!(font_name.as_deref(), Some("Serif Name")); + assert!(report.notes.is_empty(), "{:?}", report.notes); + } + let mut report = Report::default(); + let p = read(&label("Serif Name,-1,32,5,50,0,0,0,0,0"), &mut report); + let ElementKind::Text { size, bold, .. } = &text_of(&p.layouts[0], "Old").kind else { panic!("not text") }; + assert!(near(*size, 10.0) && !*bold); + assert!(said(&report, "older style whose font size doesn't read, drawn at 10 pt (1)"), "{:?}", report.notes); +} + +/// The project's title on a page with a map is its map's name (the import names the map for +/// it); on a page without one, the title as written. +#[test] +fn the_project_title_without_a_map_is_written_out() { + let pages = r#""#; + let qgs = format!( + r#"Valley{pages} + + + + "# + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + text_of(&p.layouts[0], "{map} {map}"); + text_of(&p.layouts[1], "Cover: Valley Valley"); + // Counted per label, not per time it shows the title. + assert!(said(&report, "labels showing the project's title, which show the name of the map the import makes (1)"), "{:?}", report.notes); +} + +/// A later page's name keeps its page number when the layout's name is as long as a name goes. +#[test] +fn a_long_layout_name_keeps_its_page_number() { + let long = "N".repeat(200); + let pages = r#""#; + let mut report = Report::default(); + let p = read(&format!(r#"{pages}"#), &mut report); + assert_eq!(p.layouts[0].layout.name, long); + let second = &p.layouts[1].layout.name; + assert_eq!(second.chars().count(), 200); + assert!(second.ends_with("N (page 2)"), "{second}"); + assert!(said(&report, "cut to fit (1)"), "{:?}", report.notes); + // A cut that ends in a space leaves none before the number. + let spaced = format!("{} M", "N".repeat(190)); + let mut report = Report::default(); + let p = read(&format!(r#"{pages}"#), &mut report); + assert_eq!(p.layouts[1].layout.name, format!("{} (page 2)", "N".repeat(190))); +} + +/// A long title written out on pages without a map, and a long layout name in many labels, stay +/// within a text's characters, cut and said once. +#[test] +fn written_out_names_stay_within_a_text() { + let page = r#""#; + let title = "T".repeat(1_000_000); + let label = "[% @project_title %]".repeat(1000); + let qgs = format!( + r#"{title}{page}"# + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + let ElementKind::Text { text, .. } = &p.layouts[0].layout.elements[0].kind else { panic!("not text") }; + assert_eq!(text.chars().count(), crate::layout::MAX_TEXT_CHARS); + assert!(said(&report, "labels longer than 5000 characters, cut there (1)"), "{:?}", report.notes); + let mut tally = layout::Tally::default(); + let name = "N".repeat(200); + let out = layout::tokens(&"[%@layout_name%]".repeat(100_000), &mut tally, (0, 1), &name); + assert!(out.len() <= 4 * crate::layout::MAX_TEXT_CHARS + 200, "{}", out.len()); +} + +/// An older label's underline and strikeout, which RustGIS's text lacks, are said. +#[test] +fn an_older_labels_underline_is_said() { + let page = r#""#; + let qgs = format!( + r#"{page}"# + ); + let mut report = Report::default(); + read(&qgs, &mut report); + assert!(said(&report, "labels' underlines, strikeouts (1)"), "{:?}", report.notes); +} + +/// A label size past what a text takes (1 to 400 pt) is drawn at the nearest, said; a 12 pt one +/// says nothing. +#[test] +fn a_label_size_past_a_texts_is_said() { + let page = r#""#; + let label = |pt: u32| { + format!( + r#"{page}"# + ) + }; + let mut report = Report::default(); + let p = read(&label(500), &mut report); + let ElementKind::Text { size, .. } = &text_of(&p.layouts[0], "Big").kind else { panic!("not text") }; + assert!(near(*size, 400.0)); + assert!(said(&report, "label sizes outside 1 to 400 pt, drawn at the nearest (1)"), "{:?}", report.notes); + let mut report = Report::default(); + read(&label(12), &mut report); + assert!(report.notes.is_empty(), "{:?}", report.notes); +} + +/// A layout name or title written into a label keeps its words, its braces as parentheses (a +/// brace starts a RustGIS token), said. +#[test] +fn braces_written_into_a_label_are_parentheses() { + let page = r#""#; + let qgs = format!( + r#"Plan {{date}}{page} + "# + ); + let mut report = Report::default(); + let p = read(&qgs, &mut report); + text_of(&p.layouts[0], "Plan (date) / Sheet (scale)"); + assert!(said(&report, "with braces, written as parentheses (a brace starts a RustGIS token) (2)"), "{:?}", report.notes); +} + +/// A label's own words keep their braces as parentheses, around its expressions, in an unclosed +/// one and in one kept as written: only the tokens put in are read as RustGIS's. The map's +/// coordinate system prints by its name, where QGIS prints the project's code, said. +#[test] +fn a_labels_own_braces_are_parentheses() { + let mut tally = layout::Tally::default(); + let t = layout::tokens("Scale {scale} [% @map_scale %] [% '{x}' %] [% @project_crs %] {date [% {y}", &mut tally, (0, 1), "Plan"); + assert_eq!(t, "Scale (scale) {scale} [% '(x)' %] {crs} (date [% (y)"); + let mut report = Report::default(); + tally.say(&mut report); + assert!(said(&report, "with braces, written as parentheses (a brace starts a RustGIS token) (4)"), "{:?}", report.notes); + assert!(said(&report, "without a map), in RustGIS's format (2)"), "{:?}", report.notes); + // Words without braces are unchanged and unsaid. + let mut tally = layout::Tally::default(); + assert_eq!(layout::tokens("Plan (A) [% @layout_page %]", &mut tally, (0, 1), "Plan"), "Plan (A) {page}"); + let mut report = Report::default(); + tally.say(&mut report); + assert!(report.notes.is_empty(), "{:?}", report.notes); +} + +/// A label showing the title on a page without a map is cut after the title is written out, so +/// what follows short titles stays; a title longer than a text is said when written out. +#[test] +fn a_written_out_title_is_cut_after_it_is_written() { + let page = r#""#; + let label = format!("{} Footer", "[% @project_title %]".repeat(1000)); + let qgs = |title: &str| { + format!( + r#"{title}{page}"# + ) + }; + let mut report = Report::default(); + let p = read(&qgs("T"), &mut report); + text_of(&p.layouts[0], &format!("{} Footer", "T".repeat(1000))); + assert!(!said(&report, "labels longer than"), "{:?}", report.notes); + let single = format!( + r#"{}{page}"#, + "T".repeat(5001) + ); + let mut report = Report::default(); + read(&single, &mut report); + assert!(said(&report, "labels longer than 5000 characters, cut there (1)"), "{:?}", report.notes); + let exact = single.replace(&"T".repeat(5001), &"T".repeat(5000)); + let mut report = Report::default(); + read(&exact, &mut report); + assert!(report.notes.is_empty(), "{:?}", report.notes); +} + +/// A label whose expressions are read only so far (past what a text holds) is said as cut, even +/// when the title it then writes out is shorter than its token. +#[test] +fn a_label_read_short_is_said_cut() { + let page = r#""#; + let label = format!("{} Footer", "[% @project_title %]".repeat(4500)); + let qgs = |title: &str| { + format!( + r#"{title}{page}"# + ) + }; + // Its titles written out fit: read whole, the footer kept. + let mut report = Report::default(); + let p = read(&qgs("T"), &mut report); + text_of(&p.layouts[0], &format!("{} Footer", "T".repeat(4500))); + assert!(!said(&report, "labels longer than"), "{:?}", report.notes); + // They don't: cut, said. + let mut report = Report::default(); + read(&qgs("TT"), &mut report); + assert!(said(&report, "labels longer than 5000 characters, cut there (1)"), "{:?}", report.notes); +} diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index ad7da7bfb5..04ce836d93 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -13,6 +13,9 @@ mod annotation; mod diagram; mod expr; mod labels; +mod layout; +#[cfg(test)] +mod layout_tests; mod raster; mod renderer; mod source; @@ -31,6 +34,7 @@ use crate::effects::Blend; use crate::symbology::{Labeling, LineStroke, MarkerRotation, Renderer}; pub use annotation::{Annotation, MAX_ITEMS as MAX_ANNOTATIONS}; pub use expr::{reads_measure, to_sql}; +pub use layout::{LayoutFrame, LayoutPicture, MAX_LAYOUTS, ProjectLayout, picture_named}; use rustgis_data::loss::LossCode; pub use source::{ ImageSource, MAX_MEMORY_FIELDS, Source, VirtualFrom, WebOptions, check_resolved_image_source, is_drive_relative, is_relative, @@ -137,6 +141,21 @@ impl Report { self.note_coded(layer, kind, None, text.into()); } + /// Takes `other`'s notes as notes about `layer`, each with its count and loss code. + /// `other`'s closing notes (past its cap) are counted in this report's, never listed. + pub(crate) fn merge_as(&mut self, layer: &str, other: &Report) { + for (i, n) in other.notes.iter().enumerate() { + if other.closing.get(&(n.kind, n.loss)) == Some(&i) { + self.count_past_cap(n.kind, n.loss, other.more.get(&(n.kind, n.loss)).copied().unwrap_or(n.count)); + continue; + } + // Once per occurrence, so a note past the cap is counted in the closing note too. + for _ in 0..n.count { + self.note_coded(layer, n.kind, n.loss, n.text.clone()); + } + } + } + fn note_coded(&mut self, layer: &str, kind: NoteKind, loss: Option, text: String) { let key: NoteKey = (layer.to_string(), kind, loss, text); if let Some(n) = self.index.get(&key).and_then(|&i| self.notes.get_mut(i)) { @@ -146,23 +165,30 @@ impl Report { let (layer, kind, loss, text) = key; self.notes.push(Note { layer, kind, text, count: 1, loss }); } else { - // Past the cap, a new note is counted in the one closing note of its kind and code, - // never listed itself (a loss keeps its code there). - let at = (kind, loss); - let more = self.more.get(&at).copied().unwrap_or(0).saturating_add(1); - let text = format!("{more} more note(s) not listed"); - match self.closing.get(&at).copied().and_then(|i| self.notes.get_mut(i)) { - Some(closing) => { - closing.text = text; - closing.count = closing.count.saturating_add(1); - } - None => { - self.notes.push(Note { layer: String::new(), kind, text, count: 1, loss }); - self.closing.insert(at, self.notes.len() - 1); - } + self.count_past_cap(kind, loss, 1); + } + } + + /// Past the cap, `n` new notes are counted in the one closing note of their kind and code, + /// never listed themselves (a loss keeps its code there). + fn count_past_cap(&mut self, kind: NoteKind, loss: Option, n: usize) { + if n == 0 { + return; + } + let at = (kind, loss); + let more = self.more.get(&at).copied().unwrap_or(0).saturating_add(n); + let text = format!("{more} more note(s) not listed"); + match self.closing.get(&at).copied().and_then(|i| self.notes.get_mut(i)) { + Some(closing) => { + closing.text = text; + closing.count = closing.count.saturating_add(n); + } + None => { + self.notes.push(Note { layer: String::new(), kind, text, count: n, loss }); + self.closing.insert(at, self.notes.len() - 1); } - self.more.insert(at, more); } + self.more.insert(at, more); } pub fn approximated(&mut self, layer: &str, text: impl Into) { @@ -563,6 +589,8 @@ pub struct Project { pub bookmarks: Vec, /// Its relations between layers. pub relations: Vec, + /// Its print layouts, each page a layout of its own ([`layout`]). + pub layouts: Vec, } /// A group of a QGIS project's layer tree. @@ -642,11 +670,13 @@ pub fn read_project(text: &str, dir: &str, images: &mut ReadImage, report: &mut rotation: 0.0, bookmarks: Vec::new(), relations: Vec::new(), + layouts: Vec::new(), }; // The layer tree (QGIS 2's legend before it): the order layers draw in (top first), which // are checked, and their groups. let mut tree = Tree::read(root); project_notes(root, report); + project.layouts = layout::read_layouts(root, dir, &project.title, report); // The map's rotation: one that doesn't read faces north, noted. if let Some(r) = canvas.and_then(|c| child(c, "rotation")).and_then(|r| r.text()).map(str::trim).filter(|r| !r.is_empty()) { match r.parse::().ok().filter(|r| r.is_finite()) { @@ -1099,14 +1129,10 @@ fn layer_notes(node: Node, layer: &str, report: &mut Report) { } } -/// Notes the project's parts RustGIS has no place for: print layouts, annotations of QGIS's -/// older kind and map themes. +/// Notes the project's parts RustGIS has no place for: annotations of QGIS's older kind and map +/// themes (print layouts: [`layout::read_layouts`]). fn project_notes(root: Node, report: &mut Report) { let count = |list: &str, item: &str| child(root, list).map_or(0, |l| l.children().filter(|c| c.has_tag_name(item)).count()); - let layouts = count("Layouts", "Layout") + root.children().filter(|c| c.has_tag_name("Composer")).count(); - if layouts > 0 { - report.skipped("", format!("its print layouts ({layouts})")); - } // QGIS 3's older annotations, kept beside the annotation layers (form, HTML, SVG and text // balloons). let balloons = child(root, "Annotations").map_or(0, |a| a.children().filter(Node::is_element).count()); diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 0ca8ac1f0a..6ed04a936c 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -764,9 +764,10 @@ fn what_rustgis_has_no_place_for_is_noted() { ); let mut report = Report::default(); let p = read_project(&qgs, "", &mut report).unwrap(); + // Its layout comes in (an empty A4 page: it has no pages of its own). + assert_eq!(p.layouts.len(), 1); let said = |layer: &str, part: &str| report.notes.iter().any(|n| n.layer == layer && n.text.contains(part)); for part in [ - "print layouts (1)", "annotations of QGIS's older kind (1", "bookmarks whose place doesn't read (1: Here)", "map themes (1)", @@ -1151,7 +1152,7 @@ fn every_corpus_file_reads() { } } let projects = files("generated/qgs", &["qgs", "qgz"]); - assert_eq!(projects.len(), 38, "project corpus changed: {projects:?}"); + assert_eq!(projects.len(), 39, "project corpus changed: {projects:?}"); for path in &projects { let bytes = std::fs::read(path).unwrap(); let text = if path.extension().is_some_and(|e| e == "qgz") { diff --git a/crates/map/testdata/qgis/README.md b/crates/map/testdata/qgis/README.md index 7aabae6406..61cd186d22 100644 --- a/crates/map/testdata/qgis/README.md +++ b/crates/map/testdata/qgis/README.md @@ -10,7 +10,7 @@ no specification of these formats, so the corpus stands in for one: `every_corpu | Folder | What | Licence | |---|---|---| | `generated/qml/` | 126 styles written through QGIS's API (4.2.3; the SVG marker ones 4.4.0), each varying one thing: every symbol layer type with its defaults, raster image markers (a PNG and a JPEG, in a file and embedded; sizes in each unit, rotation, an offset, anchor points, a fixed aspect ratio, opacity, and along a line), SVG markers (an SVG with `param(…)` colours and outline width and one without, in a file and embedded, one from QGIS's own library, which isn't copied here; colours with alpha; sizes in each unit, rotation, an offset, anchor points, a fixed aspect ratio, opacity, and along a line), every renderer (categorized and graduated by expression, rule-based with nested and else rules), every paint effect, data-defined size, angle and colour, labels (every placement, buffer, background, shadow, font, wrap, expression text, offsets, data-defined settings, scale ranges, curved labels, each callout, rule-based labels), layer settings (opacity, blend mode, scale range, reference scale, subset), diagrams (pie, by fields and expressions, a histogram, a stacked bar and a text diagram, two of them sized between two values) and raster renderers (grey, pseudocolour interpolated, discrete and exact, multiband, paletted, hillshade, contour) | Apache-2.0, like RustGIS: made by Dominik Strebel ([@pick2510](https://github.com/pick2510)) for the RustGIS project | -| `generated/qgs/` | 38 projects: one per provider (OGR, GDAL, memory, delimited text by x/y and WKT, SpatiaLite, virtual (on a file, on another layer, and grouping), WMS, WMTS, XYZ, raster MBTiles, WFS (also with a filter), OGC API Features, WCS, ArcGIS feature, map, image and vector tile services, vector tiles by address, with a MapLibre style, from MBTiles and from PMTiles, PostGIS, SQL Server, GPX waypoints and tracks); project structure (groups, a mutually exclusive group, a map theme, a bookmark, a variable, a relation, a join, a virtual field, time from a field, two styles on a layer); groups nested, hidden, collapsed, empty and drawn as one (a group layer with its opacity and blending); bookmarks (turned, in a group, in degrees), relations (on one pair of fields, on two, a composition, a polymorphic one) and time settings (a span of months; time from a field, from a field for a duration, a fixed range); a layout with every item and an atlas; the annotation layer with every item; annotations with their settings (styled marks, lines and a polygon with a hole, text aligned, turned, in HTML and with a buffer, rectangle text with a background and frame or of a fixed size, a picture file and an SVG, text along a line, one switched off, z order, the main annotation layer); `all-styles.qgz`, every style above on its own layer (written before the diagrams were added); `raster-markers.qgs`, each raster image marker style on its own layer, its image files named relative to it; `svg-markers.qgs`, the same for each SVG marker style, written by QGIS 4.4.0 | Apache-2.0 | +| `generated/qgs/` | 39 projects: one per provider (OGR, GDAL, memory, delimited text by x/y and WKT, SpatiaLite, virtual (on a file, on another layer, and grouping), WMS, WMTS, XYZ, raster MBTiles, WFS (also with a filter), OGC API Features, WCS, ArcGIS feature, map, image and vector tile services, vector tiles by address, with a MapLibre style, from MBTiles and from PMTiles, PostGIS, SQL Server, GPX waypoints and tracks); project structure (groups, a mutually exclusive group, a map theme, a bookmark, a variable, a relation, a join, a virtual field, time from a field, two styles on a layer); groups nested, hidden, collapsed, empty and drawn as one (a group layer with its opacity and blending); bookmarks (turned, in a group, in degrees), relations (on one pair of fields, on two, a composition, a polymorphic one) and time settings (a span of months; time from a field, from a field for a duration, a fixed range); a layout with every item and an atlas; `layout-sheets.qgs`, print layouts as map sheets (an A4 landscape sheet of two pages with a framed, turned map, a title and a note with an expression, a turned label with a background and frame, a picture, a rounded rectangle, a translucent ellipse, a triangle and a dashed line, items placed in mm, cm, in and pt, a hidden item, one left out of exports and two grouped; and a Letter portrait sheet in inches), written by QGIS 4.4.0; the annotation layer with every item; annotations with their settings (styled marks, lines and a polygon with a hole, text aligned, turned, in HTML and with a buffer, rectangle text with a background and frame or of a fixed size, a picture file and an SVG, text along a line, one switched off, z order, the main annotation layer); `all-styles.qgz`, every style above on its own layer (written before the diagrams were added); `raster-markers.qgs`, each raster image marker style on its own layer, its image files named relative to it; `svg-markers.qgs`, the same for each SVG marker style, written by QGIS 4.4.0 | Apache-2.0 | | `generated/data/` | The data those files use: `sample.gpkg` (layers `points`, `lines` and `polygons`, 9 made-up features each, fields `id`, `name`, `kind`, `value`, `angle`, `day`), `dem.tif` (3 bands of a linear surface), two CSVs, a GPX file, `picture.png` (a red 40 × 20 picture), `marker.png` (32 × 16, a red square and a blue bar) and `marker.jpg` (24 × 24, green with a yellow corner), the raster image markers' images; `icon.svg` (the same square and bar) and `marker.svg` (a triangle and a rectangle in `param(…)` colours), the SVG markers' images | Apache-2.0 | | `generated/generate.py`, `scrub.py` | The generator, and the step that removes the user's name and absolute paths from what QGIS writes | Apache-2.0 | | `generated/types.txt` | The element types QGIS 4.2.3 knows (symbol layers, renderers, providers, label placements, callouts, annotation and layout items, paint effects): the checklist the corpus was made from. A few have no file yet: the single-colour raster renderer, and the text table, fixed table, elevation profile and chart layout items | Apache-2.0 | @@ -39,7 +39,8 @@ no specification of these formats, so the corpus stands in for one: `every_corpu QGIS 4.2.3 wrote the corpus, and 4.4.0 the SVG marker files. The command runs whichever QGIS is installed (here the Flathub Flatpak, whose `/tmp` is private, so it writes under `~/.cache`) and writes the whole corpus again, so copy only the files you mean to replace: for the SVG markers, -`data/icon.svg`, `data/marker.svg`, `qml/symbol-svg-marker-*.qml` and `qgs/svg-markers.qgs`. +`data/icon.svg`, `data/marker.svg`, `qml/symbol-svg-marker-*.qml` and `qgs/svg-markers.qgs`; for the map sheets, +`qgs/layout-sheets.qgs`. ```sh mkdir -p ~/.cache/qgis-corpus @@ -47,7 +48,8 @@ flatpak run --env=PYTHONPATH=/app/share/qgis/python --env=QT_QPA_PLATFORM=offscr --command=python3 org.qgis.qgis generated/generate.py ~/.cache/qgis-corpus/out ``` -It writes `data/`, `qml/`, `qgs/`, `types.txt` and `log.txt` (what was written, and what this +It writes `data/`, `qml/`, `qgs/`, `types.txt`, `log.txt` and `renders/` (QGIS's own PNG export of +each map sheet at 96 dpi, for comparing RustGIS's import with it; not part of the corpus) (what was written, and what this QGIS couldn't write) into the output folder, then runs `scrub.py` on the projects. QGIS may crash on exit, after writing everything. When replacing the whole corpus, copy the files here without `log.txt`, `sample.sqlite`, `dem.tif.aux.xml`, `all-styles.qgs` (the `.qgz` holds it) and the diff --git a/crates/map/testdata/qgis/generated/generate.py b/crates/map/testdata/qgis/generated/generate.py index 27c411d32e..1e4c21cfdd 100644 --- a/crates/map/testdata/qgis/generated/generate.py +++ b/crates/map/testdata/qgis/generated/generate.py @@ -5,9 +5,11 @@ qml/ one style per symbol layer type, renderer, paint effect, label setting, data-defined property and raster renderer qgs/ projects: every provider, project structure (groups, themes, bookmarks, variables, - relations, joins, virtual fields, time), a layout with every item, annotations + relations, joins, virtual fields, time), a layout with every item, map sheets, + annotations types.txt the element types this QGIS knows (the inventory to cover) log.txt what was written, and what failed + renders/ QGIS's PNG export of each map sheet, for comparing (not part of the corpus) The projects are then scrubbed of the user's name and absolute paths (scrub.py). @@ -29,7 +31,7 @@ QgsVectorLayerJoinInfo, QgsPrintLayout, QgsLayoutItemMap, QgsLayoutItemLabel, QgsLayoutItemLegend, QgsLayoutItemScaleBar, QgsLayoutItemPicture, QgsLayoutItemShape, QgsLayoutItemPolygon, QgsLayoutItemPolyline, QgsLayoutItemAttributeTable, QgsLayoutFrame, - QgsLayoutItemHtml, QgsLayoutItemMarker, QgsLayoutPoint, QgsLayoutSize, QgsUnitTypes, + QgsLayoutItemHtml, QgsLayoutItemMarker, QgsLayoutPoint, QgsLayoutSize, QgsUnitTypes, QgsLayoutMeasurement, QgsAnnotationLayer, QgsAnnotationPointTextItem, QgsAnnotationMarkerItem, QgsAnnotationLineItem, QgsAnnotationPolygonItem, QgsAnnotationPictureItem, QgsAnnotationRectangleTextItem, QgsAnnotationLineTextItem, QgsPoint, QgsLineString, @@ -1005,6 +1007,128 @@ def layouts(): attempt("layouts", layouts) +# Print layouts as map sheets (piece 12a): an A4 landscape sheet of two pages with a framed map +# turned 10°, a title and a note (fonts, colours, alignment, margins, a turned one, an expression), +# a picture, a rounded rectangle, an ellipse, a triangle and a line, items placed in cm, in and pt, +# a hidden item, one excluded from exports, two grouped and a translucent one; and a Letter +# portrait sheet in inches. Each is also exported to `renders/` as a PNG at 96 dpi, for comparing +# RustGIS's import with QGIS's own drawing (not part of the corpus). +def layout_sheets(): + from qgis.core import QgsLayoutItemPage, QgsLayoutItemGroup, QgsLayoutExporter, QgsTextFormat, QgsFillSymbol, QgsLineSymbol + from qgis.PyQt.QtGui import QPolygonF, QFont + from qgis.PyQt.QtCore import QPointF, Qt + mm, cm, inch, pt = (Qgis.LayoutUnit.Millimeters, Qgis.LayoutUnit.Centimeters, Qgis.LayoutUnit.Inches, Qgis.LayoutUnit.Points) + p = new_project() + # (Clearing the project keeps an earlier project's polymorphic relations.) + p.relationManager().setPolymorphicRelations([]) + p.setTitle("Sheets") + pts, polys = layer("points"), layer("polygons") + p.addMapLayers([pts, polys]) + + def label(lay, text, x, y, w, h, unit=mm, size=12, bold=False, color=QColor(0, 0, 0), halign=Qt.AlignmentFlag.AlignLeft, valign=Qt.AlignmentFlag.AlignTop, rotation=0, margin=None): + lbl = QgsLayoutItemLabel(lay) + lbl.setText(text) + fmt = QgsTextFormat() + font = QFont("DejaVu Sans") + font.setBold(bold) + fmt.setFont(font) + fmt.setSize(size) + fmt.setColor(color) + lbl.setTextFormat(fmt) + lbl.setHAlign(halign) + lbl.setVAlign(valign) + if margin is not None: + lbl.setMarginX(margin[0]) + lbl.setMarginY(margin[1]) + lay.addLayoutItem(lbl) + lbl.attemptMove(QgsLayoutPoint(x, y, unit)) + lbl.attemptResize(QgsLayoutSize(w, h, unit)) + lbl.setItemRotation(rotation) + return lbl + + lay = QgsPrintLayout(p) + lay.initializeDefaults() + lay.setName("Sheet A4") + lay.pageCollection().page(0).setPageSize("A4", QgsLayoutItemPage.Orientation.Landscape) + second = QgsLayoutItemPage(lay) + second.setPageSize("A4", QgsLayoutItemPage.Orientation.Landscape) + lay.pageCollection().addPage(second) + m = QgsLayoutItemMap(lay) + lay.addLayoutItem(m) + m.attemptMove(QgsLayoutPoint(10, 25, mm)) + m.attemptResize(QgsLayoutSize(200, 150, mm)) + m.setExtent(QgsRectangle(2696300, 1261200, 2698000, 1262475)) + m.setMapRotation(10) + m.setFrameEnabled(True) + m.setFrameStrokeColor(QColor(40, 40, 120)) + m.setFrameStrokeWidth(QgsLayoutMeasurement(0.6, mm)) + m.setBackgroundColor(QColor(235, 245, 255)) + label(lay, "Sample sheet", 10, 5, 200, 15, size=20, bold=True, color=QColor(20, 60, 140), halign=Qt.AlignmentFlag.AlignHCenter, valign=Qt.AlignmentFlag.AlignVCenter) + label(lay, "Made [% format_date(now(), 'yyyy-MM-dd') %] for [% @project_title %]", 21.5, 20.1, 7, 0.8, unit=cm, size=9, color=QColor(90, 90, 90), halign=Qt.AlignmentFlag.AlignRight, margin=(1, 0.5)) + note = label(lay, "Turned note", 230, 120, 50, 10, size=11, rotation=-30) + note.setBackgroundEnabled(True) + note.setBackgroundColor(QColor(255, 250, 200)) + note.setFrameEnabled(True) + note.setFrameStrokeColor(QColor(160, 120, 0)) + pic = QgsLayoutItemPicture(lay) + pic.setPicturePath(os.path.join(OUT, "data", "picture.png")) + pic.setResizeMode(QgsLayoutItemPicture.ResizeMode.ZoomResizeFrame) + lay.addLayoutItem(pic) + pic.attemptMove(QgsLayoutPoint(8.9, 0.4, inch)) + pic.attemptResize(QgsLayoutSize(1.6, 0.8, inch)) + rect = QgsLayoutItemShape(lay) + rect.setShapeType(QgsLayoutItemShape.Shape.Rectangle) + rect.setCornerRadius(QgsLayoutMeasurement(3, mm)) + rect.setSymbol(QgsFillSymbol.createSimple({"color": "255,230,200,255", "outline_color": "200,100,0,255", "outline_width": "0.8", "outline_width_unit": "MM"})) + lay.addLayoutItem(rect) + rect.attemptMove(QgsLayoutPoint(650, 100, pt)) + rect.attemptResize(QgsLayoutSize(150, 70, pt)) + ell = QgsLayoutItemShape(lay) + ell.setShapeType(QgsLayoutItemShape.Shape.Ellipse) + ell.setSymbol(QgsFillSymbol.createSimple({"color": "120,200,120,255", "outline_color": "0,90,0,255", "outline_width": "0.4"})) + lay.addLayoutItem(ell) + ell.attemptMove(QgsLayoutPoint(225, 140, mm)) + ell.attemptResize(QgsLayoutSize(40, 25, mm)) + ell.setItemOpacity(0.5) + tri = QgsLayoutItemPolygon(QPolygonF([QPointF(240, 175), QPointF(280, 175), QPointF(260, 200)]), lay) + tri.setSymbol(QgsFillSymbol.createSimple({"color": "200,200,255,255", "outline_color": "0,0,160,255", "outline_width": "0.5"})) + lay.addLayoutItem(tri) + line = QgsLayoutItemPolyline(QPolygonF([QPointF(10, 182), QPointF(120, 182), QPointF(140, 195)]), lay) + line.setSymbol(QgsLineSymbol.createSimple({"line_color": "200,0,0,255", "line_width": "1.2", "line_style": "dash"})) + lay.addLayoutItem(line) + hidden = label(lay, "Hidden", 150, 190, 30, 8) + hidden.setVisibility(False) + kept_out = label(lay, "Not exported", 185, 190, 30, 8) + kept_out.setExcludeFromExports(True) + a = label(lay, "Grouped A", 230, 20, 40, 8) + b = label(lay, "Grouped B", 230, 30, 40, 8) + group = QgsLayoutItemGroup(lay) + group.addItem(a) + group.addItem(b) + lay.addLayoutItem(group) + label(lay, "Second page", 10, 220, 100, 12, size=16) + p.layoutManager().addLayout(lay) + + letter = QgsPrintLayout(p) + letter.initializeDefaults() + letter.setName("Sheet Letter") + letter.pageCollection().page(0).setPageSize("Letter", QgsLayoutItemPage.Orientation.Portrait) + lm = QgsLayoutItemMap(letter) + letter.addLayoutItem(lm) + lm.attemptMove(QgsLayoutPoint(0.5, 1.2, inch)) + lm.attemptResize(QgsLayoutSize(7.5, 6, inch)) + lm.setExtent(QgsRectangle(2696300, 1261000, 2698100, 1262440)) + label(letter, "Letter sheet", 0.5, 0.4, 7.5, 0.6, unit=inch, size=18, halign=Qt.AlignmentFlag.AlignHCenter) + p.layoutManager().addLayout(letter) + save_project(p, "layout-sheets") + os.makedirs(os.path.join(OUT, "renders"), exist_ok=True) + for l in (lay, letter): + settings = QgsLayoutExporter.ImageExportSettings() + settings.dpi = 96 + QgsLayoutExporter(l).exportToImage(os.path.join(OUT, "renders", l.name().replace(" ", "-") + ".png"), settings) + + + # The annotation layer with each item type. def annotations(): p = new_project() @@ -1261,6 +1385,8 @@ def __exit__(self, *a): return False +# (After the annotations, which write `picture.png`.) +attempt("layout sheets", layout_sheets) attempt("all styles project", all_styles) diff --git a/crates/map/testdata/qgis/generated/qgs/layout-sheets.qgs b/crates/map/testdata/qgis/generated/qgs/layout-sheets.qgs new file mode 100644 index 0000000000..9c482b4675 --- /dev/null +++ b/crates/map/testdata/qgis/generated/qgs/layout-sheets.qgs @@ -0,0 +1,2342 @@ + + + + Sheets + + + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + + + 0 + 0 + + + + + false + + + + + + + + + + + + + + + + points_c5b6a8c2_c1fd_4734_8250_c6e0afc039d0 + polygons_bb530542_361d_42e4_a37c_c57cadd0ab1c + + + + + + + + + + + + Annotations_216dc097_323d_434b_ac73_b0dea4b656d4 + + Annotations + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + + + + + + + + + + + + + + 0 + 0 + + + + + false + + + + + + + 1 + 1 + 1 + 0 + + + + 1 + 0 + + + + + + 2696500 + 1261500 + 2697700 + 1261740 + + + 8.71934207087455881 + 47.49699490745601338 + 8.73531785937520233 + 47.49933040928209493 + + points_c5b6a8c2_c1fd_4734_8250_c6e0afc039d0 + ../data/sample.gpkg|layername=points + points + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + + + dataset + + + + + + + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + ogr + + + + + + + + + + 1 + 1 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + 0 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + generatedlayout + + + + + + + + + + + 2696500 + 1261500 + 2697820 + 1261830 + + + 8.71934207087455881 + 47.49697706140925391 + 8.73692999718656971 + 47.50013975136437949 + + polygons_bb530542_361d_42e4_a37c_c57cadd0ab1c + ../data/sample.gpkg|layername=polygons + polygons + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + + + dataset + + + + + + + + + PROJCRS["CH1903+ / LV95",BASEGEOGCRS["CH1903+",DATUM["CH1903+",ELLIPSOID["Bessel 1841",6377397.155,299.1528128,LENGTHUNIT["metre",1]]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],ID["EPSG",4150]],CONVERSION["Swiss Oblique Mercator 1995",METHOD["Hotine Oblique Mercator (variant B)",ID["EPSG",9815]],PARAMETER["Latitude of projection centre",46.9524055555556,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8811]],PARAMETER["Longitude of projection centre",7.43958333333333,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8812]],PARAMETER["Azimuth at projection centre",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8813]],PARAMETER["Angle from Rectified to Skew Grid",90,ANGLEUNIT["degree",0.0174532925199433],ID["EPSG",8814]],PARAMETER["Scale factor at projection centre",1,SCALEUNIT["unity",1],ID["EPSG",8815]],PARAMETER["Easting at projection centre",2600000,LENGTHUNIT["metre",1],ID["EPSG",8816]],PARAMETER["Northing at projection centre",1200000,LENGTHUNIT["metre",1],ID["EPSG",8817]]],CS[Cartesian,2],AXIS["(E)",east,ORDER[1],LENGTHUNIT["metre",1]],AXIS["(N)",north,ORDER[2],LENGTHUNIT["metre",1]],USAGE[SCOPE["Cadastre, engineering survey, topographic mapping (large and medium scale)."],AREA["Liechtenstein; Switzerland."],BBOX[45.81,5.95,47.81,10.5]],ID["EPSG",2056]] + +proj=somerc +lat_0=46.9524055555556 +lon_0=7.43958333333333 +k_0=1 +x_0=2600000 +y_0=1200000 +ellps=bessel +towgs84=674.374,15.056,405.346,0,0,0,0 +units=m +no_defs + 47 + 2056 + EPSG:2056 + CH1903+ / LV95 + somerc + EPSG:7004 + false + + + + + ogr + + + + + + + + + + 1 + 1 + 1 + 0 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + 0 + 1 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + 0 + + + 0 + generatedlayout + + + + + + + + + + + + + + + + + 0 + 0 + + + 0 + 0 + + + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 0 + 0 + 255 + 255 + 255 + 255 + + + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 0 + 0 + 255 + 255 + 255 + 255 + + + m2 + m2 + meters + meters + HorizontalMiddle + HorizontalMiddle + + + m2 + m2 + meters + meters + HorizontalMiddle + HorizontalMiddle + + + 5 + 5 + 2.5 + 2.5 + false + false + false + false + false + false + 1 + 1 + 0 + 0 + false + false + false + false + true + true + 0 + 0 + 255,0,0,255,rgb:1,0,0,1 + 255,0,0,255,rgb:1,0,0,1 + + + 5 + 5 + 2.5 + 2.5 + false + false + false + false + false + false + 1 + 1 + 0 + 0 + false + false + false + false + true + true + 0 + 0 + 255,0,0,255,rgb:1,0,0,1 + 255,0,0,255,rgb:1,0,0,1 + + + false + false + + + false + false + + + true + true + 2 + 2 + + + true + true + 2 + 2 + + + 1 + 1 + + + 1 + 1 + + + 0 + 0 + + + 0 + 0 + + + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 0 + 0 + 255 + 255 + 255 + 255 + + + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 255 + 0 + 0 + 255 + 255 + 255 + 255 + + + m2 + m2 + meters + meters + HorizontalMiddle + HorizontalMiddle + + + m2 + m2 + meters + meters + HorizontalMiddle + HorizontalMiddle + + + 5 + 5 + 2.5 + 2.5 + false + false + false + false + false + false + 1 + 1 + 0 + 0 + false + false + false + false + true + true + 0 + 0 + 255,0,0,255,rgb:1,0,0,1 + 255,0,0,255,rgb:1,0,0,1 + + + 5 + 5 + 2.5 + 2.5 + false + false + false + false + false + false + 1 + 1 + 0 + 0 + false + false + false + false + true + true + 0 + 0 + 255,0,0,255,rgb:1,0,0,1 + 255,0,0,255,rgb:1,0,0,1 + + + false + false + + + false + false + + + true + true + 2 + 2 + + + true + true + 2 + 2 + + + 1 + 1 + + + 1 + 1 + + + + + + + + + + + + + Sheets + + + + + + Unknown + 2026-11-30T09:58:20 + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + GEOGCRS["WGS 84",ENSEMBLE["World Geodetic System 1984 ensemble",MEMBER["World Geodetic System 1984 (Transit)"],MEMBER["World Geodetic System 1984 (G730)"],MEMBER["World Geodetic System 1984 (G873)"],MEMBER["World Geodetic System 1984 (G1150)"],MEMBER["World Geodetic System 1984 (G1674)"],MEMBER["World Geodetic System 1984 (G1762)"],MEMBER["World Geodetic System 1984 (G2139)"],MEMBER["World Geodetic System 1984 (G2296)"],ELLIPSOID["WGS 84",6378137,298.257223563,LENGTHUNIT["metre",1]],ENSEMBLEACCURACY[2.0]],PRIMEM["Greenwich",0,ANGLEUNIT["degree",0.0174532925199433]],CS[ellipsoidal,2],AXIS["geodetic latitude (Lat)",north,ORDER[1],ANGLEUNIT["degree",0.0174532925199433]],AXIS["geodetic longitude (Lon)",east,ORDER[2],ANGLEUNIT["degree",0.0174532925199433]],USAGE[SCOPE["Horizontal component of 3D system."],AREA["World."],BBOX[-90,-180,90,180]],ID["EPSG",4326]] + +proj=longlat +datum=WGS84 +no_defs + 3452 + 4326 + EPSG:4326 + WGS 84 + longlat + EPSG:7030 + true + + + + + + + diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index b394f960fd..381e67a9c4 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -426,6 +426,28 @@ does a line of several strokes. They apply to every feature, so a layer whose cl ones (or one with a class switched off) leaves them out, noted. One using a function or variable it lacks, or a field the layer hasn't, is noted and left out. +The project's print layouts come in as [layouts](layouts.md) of the project, each page a layout of +its own (a second page as `Plan (page 2)`), named as QGIS names them (numbered when the project has +a layout of that name). Their items are placed where QGIS draws them, from any of QGIS's units, in +QGIS's drawing order: map items as map frames showing the map the import makes, at the extent and +turn each shows; labels as text, with their font, size, colour, alignment, margins and turn, and +`[% … %]` expressions as the tokens that print the same (`@layout_page` as `{page}`, the layout's +name as written, the project's title as `{map}`, the map's name, or as written on a page without a +map), or in RustGIS's format, noted (`now()` as `{date} {time}`, `@map_scale` as `{scale}`, +`@project_crs` as `{crs}`, the map's coordinate system by its name, nothing on a page without a +map); braces in a label's own words become parentheses, noted, so they don't print as tokens; +older QGIS 3 labels keep their font and colour too; a page keeps its paper's colour; pictures from +their PNG or JPEG files, or kept in the project as written (a picture kept inside a `.qgz` +isn't read, noted: save it as a file beside the project and point the item at it); rectangles +and ellipses with their fill, outline and rounded corners; and lines and polygons as straight +lines along their edges, with arrowheads. Labels' and pictures' backgrounds and frames, a map's +frame, hidden items and locked ones carry over. What a layout can't hold is +noted: scale bars, legends, north arrows, tables, HTML and other items, map grids, overviews and +the atlas, SVG pictures, groups (their items kept on their own), turned maps, shapes and pictures +(drawn upright), stretched or clipped pictures, a polygon's fill, a map's background colour, label +styling RustGIS's text lacks (underlines, buffers, shadows), blending, and settings set by +expressions. + QGIS filter expressions (a layer's filter, label and renderer rules) carry over: those that are SQL (fields compared with values, `LIKE`, `IN`, `IS NULL`, joined by `AND`, `OR` and `NOT`) as before, the rest (functions, arithmetic, `CASE`, `@map_scale`) as they are, for the @@ -459,7 +481,7 @@ alone, events lasting a fixed time shown at their date, a layer accumulating its settings, draw effects, label callouts, contours and other raster renderers RustGIS has no match for, PostGIS and SQL Server tables, WFS and other sources RustGIS doesn't read, virtual layers with other queries, histogram, stacked bar and text diagrams, joins, virtual fields, a layer's other styles, -time from an expression, a fixed range or redrawn as the time changes, a raster's or a service's time, and the project's print layouts, QGIS 3's older annotation balloons, map themes, +time from an expression, a fixed range or redrawn as the time changes, a raster's or a service's time, the print layout items above, QGIS 2's print composers, QGIS 3's older annotation balloons, map themes, bookmark groups and bookmarks the map's projection doesn't reach, polymorphic relations and its time span and steps). A database password in a project never reaches the notes.