From 385bc445115523f62586875b69c9e3ae585896ed Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 16:40:43 -0600 Subject: [PATCH 01/38] test(render): pin how a layout picture draws and exports, and what pictures save and say A picture is pinned by hashes of main's drawing of ten pages, their SVG and their PDF, and main's saved layouts, layout file and export notices for pictures that draw, in the built-in face in a child process, before pictures remember their file. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/tests.rs | 2 + crates/engine/src/tests/layout_pictures.rs | 231 +++++++++++++++++++++ crates/render/src/layout.rs | 89 ++++++++ crates/render/src/layout/tests.rs | 57 +++++ crates/render/src/svg.rs | 62 ++++++ 5 files changed, 441 insertions(+) create mode 100644 crates/engine/src/tests/layout_pictures.rs diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index e218d05f2a..8b8dd93d72 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -99,6 +99,8 @@ mod elevation_tiles; #[path = "tests/layout_files.rs"] mod layout_files; +#[path = "tests/layout_pictures.rs"] +mod layout_pictures; #[path = "tests/layout_sections.rs"] mod layout_sections; diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs new file mode 100644 index 0000000000..54b8846e37 --- /dev/null +++ b/crates/engine/src/tests/layout_pictures.rs @@ -0,0 +1,231 @@ +//! Layout pictures and the files they were read from: what they draw, say, save and require. + +#[cfg(not(target_arch = "wasm32"))] +use crate::Session; +#[cfg(not(target_arch = "wasm32"))] +use serde_json::{Value, json}; + +/// A `w` x `h` PNG, each pixel the opaque colour `colours` gives it, as base64. +#[cfg(not(target_arch = "wasm32"))] +fn png_b64(w: u32, h: u32, colours: impl Fn(u32, u32) -> [u8; 3]) -> String { + use base64::Engine as _; + let mut pm = tiny_skia::Pixmap::new(w, h).unwrap(); + for (i, px) in pm.pixels_mut().iter_mut().enumerate() { + let i = i as u32; + let [r, g, b] = colours(i % w, i / w); + *px = tiny_skia::ColorU8::from_rgba(r, g, b, 255).premultiply(); + } + base64::engine::general_purpose::STANDARD.encode(pm.encode_png().unwrap()) +} + +/// A 32 x 32 RGB JPEG of a diagonal gradient at quality 80, as base64. +#[cfg(not(target_arch = "wasm32"))] +fn jpeg_b64() -> String { + use base64::Engine as _; + let rgb: Vec = (0..32u32 * 32).flat_map(|i| [((i % 32 + i / 32) * 4) as u8, 120, (255 - (i % 32 + i / 32) * 4) as u8]).collect(); + let mut jpeg = Vec::new(); + image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 80).encode(&rgb, 32, 32, image::ExtendedColorType::Rgb8).unwrap(); + base64::engine::general_purpose::STANDARD.encode(jpeg) +} + +/// The PNG the render pins draw: 40 x 20, its left half `#1F5C84`, its right half `#E8B04A`, a +/// white line one pixel high across the middle. +#[cfg(not(target_arch = "wasm32"))] +fn pin_png() -> String { + png_b64(40, 20, |x, y| match (x, y) { + (_, 10) => [0xFF, 0xFF, 0xFF], + (0..20, _) => [0x1F, 0x5C, 0x84], + _ => [0xE8, 0xB0, 0x4A], + }) +} + +/// What [`pictures_save_and_say_as_before`] saved before pictures remembered their file, in turn. +#[cfg(not(target_arch = "wasm32"))] +const PINNED_PICTURE_SAVES: [u64; 2] = [ + 0xc7c7_77d9_64d6_2abc, // the project's layouts + 0x5d70_a4b1_1043_607d, // the layout's own file +]; +/// What each export of its layout said, in the order of the routes: where it wrote the file, and +/// nothing of its pictures. +#[cfg(not(target_arch = "wasm32"))] +const PINNED_PICTURE_NOTICES: [u64; 6] = [ + 0x91fe_c13a_e3f0_46f7, // layout.export png: "Exported /p.png" + 0x91dc_c03a_e3d3_5ede, // layout.export pdf: "Exported /p.pdf" + 0xaba9_5c3a_f262_802e, // layout.export svg: "Exported /p.svg" + 0xcbf2_9ce4_8422_2325, // the Assistant's view: nothing at all + 0x39f5_2536_3dfd_3cbd, // report.export png: "Exported /r.png" + 0x39e0_3436_3dea_fa30, // report.export pdf: "Exported /r.pdf" +]; + +/// What main saves for pictures not read from a file, and says when a layout of pictures that draw +/// is exported every way, before pictures remembered their file; in the built-in face, in a process +/// of its own. The layout is an older file's, imported (a hidden picture with no image, which only +/// a file holds), with a PNG, a JPEG and the PNG on a background added to it. The saves, each +/// pinned on its own: the project's layouts as JSON, and the layout's own file (header and all). +/// The exports, each pinned on its own: PNG, PDF and SVG by `layout.export`, the Assistant's view +/// of the layout, and a report of it as PNG and as PDF. The test's folder is taken out of what is +/// said before it is hashed. Then what `layout.addElement` answers for a picture's `image` and +/// `path`, case by case, word for word. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn pictures_save_and_say_as_before() { + use base64::Engine as _; + if std::env::var_os("RUSTGIS_PICTURE_NOTICE_PIN_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "tests::layout_pictures::pictures_save_and_say_as_before", "--nocapture"]) + .env("RUSTGIS_PICTURE_NOTICE_PIN_CHILD", "1") + .env("RUSTGIS_BUILTIN_FONTS", "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process"); + return; + } + // Each hash that isn't its pinned one, named, with both values and all of them to pin. + let mismatches = |what: &str, got: &[(String, u64)], pinned: &[u64]| { + let mut wrong: Vec = got + .iter() + .zip(pinned) + .filter(|((_, g), p)| g != *p) + .map(|((name, g), p)| format!("{what} {name}: got {g:#018x}, pinned {p:#018x}")) + .collect(); + if got.len() != pinned.len() || !wrong.is_empty() { + let all: Vec = got.iter().map(|(name, g)| format!("{g:#018x}, // {name}")).collect(); + wrong.push(format!("{what}s, {} of {} pinned, all:\n{}", got.len(), pinned.len(), all.join("\n"))); + } + wrong + }; + /// Removed however the test ends. + struct Dir(std::path::PathBuf); + impl Drop for Dir { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).ok(); + } + } + let dir = Dir(std::env::temp_dir().join(format!("rustgis-pictures-save-and-say-{}", std::process::id()))); + std::fs::create_dir_all(&dir.0).unwrap(); + let at = |file: &str| dir.0.join(file).display().to_string(); + // The folder, as said before a file's name in it: taken out of what is said, so the same + // text is pinned on every system. + let folder = format!("{}{}", dir.0.display(), std::path::MAIN_SEPARATOR); + let mut s = super::world(); + // An older file's layout, A4 upright: a hidden picture with no image. + let old = json!({"name": "Pictures", "width": 210.0, "height": 297.0, "elements": [ + {"id": 1, "name": "Old picture", "x": 10.0, "y": 10.0, "w": 40.0, "h": 20.0, "visible": false, "kind": {"Picture": {"image": ""}}} + ]}); + s.run("layout.import", &json!({"text": old.to_string()})).unwrap(); + let (png, jpeg) = (pin_png(), jpeg_b64()); + let backed = json!({"fill": "#FFF3D6", "outline": "#222222", "width": 1, "padding": 2}); + for p in [ + json!({"kind": "picture", "image": png, "x": 20, "y": 40, "w": 60, "h": 30}), + json!({"kind": "picture", "image": jpeg, "x": 100, "y": 40, "w": 40, "h": 40}), + json!({"kind": "picture", "image": png, "x": 20, "y": 100, "w": 60, "h": 30, "background": backed}), + ] { + s.run("layout.addElement", &p).unwrap(); + } + let li = s.project.layouts.len() - 1; + let name = s.project.layouts[li].name.clone(); + assert_eq!((s.project.layouts.len(), name.as_str(), s.project.layouts[li].elements.len()), (1, "Pictures", 4)); + let saves = [ + ("layouts".to_string(), super::fnv_bytes(serde_json::to_string(&s.project.layouts).unwrap().as_bytes())), + ("layout file".to_string(), super::fnv_bytes(&crate::project::layout_file_bytes(&s.project.layouts[li]).unwrap())), + ]; + s.run("report.new", &json!({"layer": "Countries", "name": "R", "fields": ["name"], "where": "name LIKE 'F%'"})).unwrap(); + s.run("report.existingTemplate", &json!({"report": "R", "layout": name})).unwrap(); + let export = |path: String, dpi: Option| { + move |s: &mut Session| { + let mut p = json!({"layout": li, "path": path}); + if let Some(dpi) = dpi { + p["dpi"] = json!(dpi); + } + s.run("layout.export", &p).unwrap(); + } + }; + let report = + |path: String| move |s: &mut Session| drop(s.run("report.export", &json!({"report": "R", "path": path, "dpi": 36})).unwrap()); + let routes: Vec<(&str, Box)> = vec![ + // route: layout.export as PNG + ("layout.export png", Box::new(export(at("p.png"), Some(72.0)))), + // route: layout.export as PDF + ("layout.export pdf", Box::new(export(at("p.pdf"), None))), + // route: layout.export as SVG + ("layout.export svg", Box::new(export(at("p.svg"), None))), + // route: the Assistant's view of the layout + ("the Assistant's view", Box::new(move |s: &mut Session| drop(crate::cmd::layout::layout_png(s, li, 72.0, None).unwrap()))), + // route: report.export as PNG + ("report.export png", Box::new(report(at("r.png")))), + // route: report.export as PDF + ("report.export pdf", Box::new(report(at("r.pdf")))), + ]; + let mut notices = Vec::new(); + for (route, run) in &routes { + let mark = s.notice_mark(); + run(&mut s); + let texts: Vec = s.notices_since(mark).iter().map(|n| n.text.replace(&folder, "/")).collect(); + let text = texts.join("\n"); + assert!(!text.contains(&*dir.0.to_string_lossy()), "{route}: the folder is said in another form: {text}"); + notices.push((format!("{route}: {text:?}"), super::fnv_bytes(text.as_bytes()))); + } + let mut wrong = mismatches("save", &saves, &PINNED_PICTURE_SAVES); + wrong.extend(mismatches("notice", ¬ices, &PINNED_PICTURE_NOTICES)); + // What `layout.addElement` answers for each picture given, word for word, the folder taken out: + // a refusal, or what it added. + let huge = png_b64(30_000, 1, |_, _| [0x1F, 0x5C, 0x84]); + // The PNG cut four bytes into its pixels: its size reads, its pixels don't. + let damaged = { + let bytes = base64::engine::general_purpose::STANDARD.decode(&png).unwrap(); + let pixels = bytes.windows(4).position(|w| w == b"IDAT").unwrap() + 4; + base64::engine::general_purpose::STANDARD.encode(&bytes[..pixels + 4]) + }; + std::fs::write(dir.0.join("note.png"), "not a picture").unwrap(); + std::fs::create_dir_all(dir.0.join("folder.png")).unwrap(); + // What the system says of a file that isn't there, which differs between systems. + let not_found = std::fs::metadata(dir.0.join("missing.png")).unwrap_err().to_string(); + let too_large = "A".repeat((16 << 20) / 3 * 4 + 8); + let images = [(&png, "the PNG"), (&huge, "the 30000 x 1 PNG"), (&damaged, "the damaged PNG")]; + let rectangle = |key: &str, v: Value| { + let mut p = json!({"kind": "rectangle", "x": 10, "y": 10, "w": 20, "h": 20}); + p[key] = v; + p + }; + let cases: Vec<(&str, Value, String)> = vec![ + ("neither an image nor a path", json!({"kind": "picture"}), "a picture needs an image or a path".into()), + ( + "an image that isn't one", + json!({"kind": "picture", "image": "bm90IGFuIGltYWdl"}), + "the picture isn't a PNG or JPEG image".into(), + ), + ("an empty image", json!({"kind": "picture", "image": ""}), "the picture isn't a PNG or JPEG image".into()), + ("an image over 16 MiB", json!({"kind": "picture", "image": too_large}), "the picture is too large".into()), + ("a path to a missing file", json!({"kind": "picture", "path": at("missing.png")}), format!("/missing.png: {not_found}")), + ("a path to a folder", json!({"kind": "picture", "path": at("folder.png")}), "/folder.png: not a regular file".into()), + ("a path to a text file", json!({"kind": "picture", "path": at("note.png")}), "the picture isn't a PNG or JPEG image".into()), + // Task 4 changes this to "path is the path of a PNG or JPEG file". + ("a path that isn't text", json!({"kind": "picture", "path": 5}), "a picture needs an image or a path".into()), + // Task 4 refuses this ("give a picture an image or a path, not both"); main uses the image. + ("both an image and a path", json!({"kind": "picture", "image": png, "path": at("note.png")}), "added a picture of the PNG".into()), + // Task 4 refuses these two (their image can't be drawn); main adds each as a grey box. + ("an image over 20000 pixels a side", json!({"kind": "picture", "image": huge}), "added a picture of the 30000 x 1 PNG".into()), + ("an image whose pixels don't read", json!({"kind": "picture", "image": damaged}), "added a picture of the damaged PNG".into()), + // Task 4 refuses these two ("only pictures take an image or a path"); main ignores the key. + ("an image on a rectangle", rectangle("image", json!(png)), "added a rectangle".into()), + ("a path on a rectangle", rectangle("path", json!(at("missing.png"))), "added a rectangle".into()), + ]; + for (case, p, pinned) in &cases { + let got = match s.run("layout.addElement", p) { + Err(e) => e.replace(&folder, "/"), + Ok(r) => match s.project.layouts[li].element(r["element"].as_u64().unwrap() as u32).map(|e| &e.kind) { + Some(rustgis_map::layout::ElementKind::Picture { image }) => { + let which = images.iter().find(|(i, _)| *i == image).map_or("another image", |(_, n)| n); + format!("added a picture of {which}") + } + Some(k) => format!("added a {}", k.code()), + None => "added nothing".into(), + }, + }; + if got != *pinned { + wrong.push(format!("layout.addElement with {case}: got {got:?}, pinned {pinned:?}")); + } + } + assert!(wrong.is_empty(), "{}", wrong.join("\n")); +} diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 1212e657e3..4148f3a14c 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1061,6 +1061,95 @@ pub(crate) fn legend_pin_pages() -> Vec<(Layout, Vec)> { pages } +/// A `w` x `h` PNG, each pixel the opaque colour `colours` gives it, as base64. +#[cfg(all(test, not(target_arch = "wasm32")))] +fn png_b64(w: u32, h: u32, colours: impl Fn(u32, u32) -> [u8; 3]) -> String { + use base64::Engine as _; + let Some(mut pm) = Pixmap::new(w, h) else { return String::new() }; + for (i, px) in pm.pixels_mut().iter_mut().enumerate() { + let i = i as u32; + let [r, g, b] = colours(i % w, i / w); + *px = tiny_skia::ColorU8::from_rgba(r, g, b, 255).premultiply(); + } + pm.encode_png().map(|png| base64::engine::general_purpose::STANDARD.encode(png)).unwrap_or_default() +} + +/// A 32 x 32 RGB JPEG of a diagonal gradient at quality 80, as base64. +#[cfg(all(test, not(target_arch = "wasm32")))] +fn jpeg_b64() -> String { + use base64::Engine as _; + let rgb: Vec = (0..32u32 * 32).flat_map(|i| [((i % 32 + i / 32) * 4) as u8, 120, (255 - (i % 32 + i / 32) * 4) as u8]).collect(); + let mut jpeg = Vec::new(); + let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 80); + match encoder.encode(&rgb, 32, 32, image::ExtendedColorType::Rgb8) { + Ok(()) => base64::engine::general_purpose::STANDARD.encode(jpeg), + Err(_) => String::new(), + } +} + +/// The 40 x 20 PNG the picture pins draw: its left half `#1F5C84`, its right half `#E8B04A`, a +/// white line one pixel high across the middle (row 10). +#[cfg(all(test, not(target_arch = "wasm32")))] +fn pin_png() -> String { + png_b64(40, 20, |x, y| match (x, y) { + (_, 10) => [0xFF, 0xFF, 0xFF], + (0..20, _) => [0x1F, 0x5C, 0x84], + _ => [0xE8, 0xB0, 0x4A], + }) +} + +/// Pages of 100 x 80 mm, no maps, one picture each (no file to it, as main has none) unless +/// said: 1, the PNG of [`pin_png`] in (10, 10, 60, 30), a wider box (bars left and right); 2, the +/// PNG in (10, 10, 20, 60), a taller box (bars above and below); 3, the JPEG of [`jpeg_b64`] in +/// (10, 10, 40, 40); 4, an empty image in (10, 10, 40, 20), a grey box with "Picture"; 5, base64 +/// that isn't an image in (10, 10, 40, 20); 6, a 30000 x 1 PNG (it declares more than 20000 pixels +/// a side) in (10, 10, 40, 20), a grey box; 7, an empty image in a box smaller than its word, (10, +/// 10, 6, 4); 8, the PNG in (10, 10, 60, 30) on a background (fill `#FFF3D6`, outline `#222222` +/// 1 pt wide, padding 2 mm); 9, a hidden picture with an empty image at (10, 10, 40, 20) and the +/// PNG visible at (55, 10, 40, 20); 10, the PNG in a box across the page's right edge, (80, 10, +/// 40, 20). Pictures have no turn of their own. +#[cfg(all(test, not(target_arch = "wasm32")))] +pub(crate) fn picture_pin_pages() -> Vec<(Layout, Vec)> { + let (png, jpeg) = (pin_png(), jpeg_b64()); + let huge = png_b64(30_000, 1, |_, _| [0x1F, 0x5C, 0x84]); + let page = |pictures: &[(&str, (f64, f64, f64, f64))]| { + let mut l = Layout::new("Pictures", 100.0, 80.0); + for (image, at) in pictures { + l.add("Picture", *at, ElementKind::Picture { image: (*image).to_string() }); + } + l + }; + let (wide, small) = ((10.0, 10.0, 60.0, 30.0), (10.0, 10.0, 40.0, 20.0)); + let mut backed = page(&[(&png, wide)]); + if let Some(e) = backed.elements.first_mut() { + e.background = Some(rustgis_map::layout::Background { + outline: Rgba::rgb(0x22, 0x22, 0x22), + width: 1.0, + padding: 2.0, + ..rustgis_map::layout::Background::filled(Rgba::rgb(0xFF, 0xF3, 0xD6)) + }); + } + let mut hidden = page(&[("", small), (&png, (55.0, 10.0, 40.0, 20.0))]); + if let Some(e) = hidden.elements.first_mut() { + e.visible = false; + } + [ + page(&[(&png, wide)]), + page(&[(&png, (10.0, 10.0, 20.0, 60.0))]), + page(&[(&jpeg, (10.0, 10.0, 40.0, 40.0))]), + page(&[("", small)]), + page(&[("bm90IGFuIGltYWdl", small)]), + page(&[(&huge, small)]), + page(&[("", (10.0, 10.0, 6.0, 4.0))]), + backed, + hidden, + page(&[(&png, (80.0, 10.0, 40.0, 20.0))]), + ] + .into_iter() + .map(|l| (l, Vec::new())) + .collect() +} + /// Each of `got`'s hashes that isn't its `pinned` one, named for its page (and resolution), with /// both values, and the whole of `got` to pin when the change is meant; one more line when the /// counts differ. `what` names the output compared. diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 1d86fdd957..d8039f096d 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -5845,6 +5845,63 @@ fn legends_draw_as_before() { assert!(wrong.is_empty(), "{}", wrong.join("\n")); } +/// How [`pictures_draw_as_before`]'s pages drew before pictures remembered their file, in the +/// built-in face, page by page: each page of [`crate::layout::picture_pin_pages`] at 96 dpi, pages +/// 1 and 4 at 300 dpi after it. +#[cfg(not(target_arch = "wasm32"))] +const PINNED_PICTURE_PIXELS: [u64; 12] = [ + 0x9fa9_ca57_1c69_af27, // 1: the PNG in a wider box, 96 dpi + 0x5752_b48f_072b_54d4, // 1: 300 dpi + 0x7b3e_df0e_9fd1_f709, // 2: the PNG in a taller box + 0x49d8_734d_a88a_2ae0, // 3: the JPEG + 0x3440_95a3_d3dc_fb42, // 4: an empty image, a grey box with its word, 96 dpi + 0xb771_eb09_bba9_f366, // 4: 300 dpi + 0x3440_95a3_d3dc_fb42, // 5: not an image (page 4's: the same grey box in the same box) + 0x3440_95a3_d3dc_fb42, // 6: declared too large (page 4's, as page 5) + 0xd777_e3ef_447b_0fa6, // 7: an empty image in a box smaller than its word + 0xe553_615c_19b6_2150, // 8: the PNG on a background + 0xfa6f_1910_01a5_a96b, // 9: a hidden empty picture beside the PNG + 0x6af5_c5c4_f5ee_41fa, // 10: the PNG across the page's right edge +]; + +/// A picture draws exactly as main drew it, page by page ([`crate::layout::picture_pin_pages`]): +/// every page at 96 dpi, and pages 1 (a PNG in a wider box) and 4 (an empty image's grey box and +/// its word) at 300 dpi too, which holds the scaling of the image and of the grey box's outline and +/// word with the resolution: twelve drawings. In a process of its own, told to use the built-in +/// face before any text. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn pictures_draw_as_before() { + if std::env::var_os("RUSTGIS_PICTURE_PIN_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "layout::tests::pictures_draw_as_before", "--nocapture"]) + .env("RUSTGIS_PICTURE_PIN_CHILD", "1") + .env("RUSTGIS_BUILTIN_FONTS", "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process"); + return; + } + let info = PageInfo::default(); + let mut drawn = Vec::new(); + for (i, (l, mut maps)) in crate::layout::picture_pin_pages().into_iter().enumerate() { + let page = i + 1; + // Pages 4 to 7 hold no picture that draws: their grey box is what is pinned. + let draws = l + .elements + .iter() + .any(|e| e.visible && matches!(&e.kind, ElementKind::Picture { image } if crate::picture::decode(image).is_some())); + assert_eq!(draws, !(4..=7).contains(&page), "page {page}"); + for dpi in if page == 1 || page == 4 { &[96.0, 300.0][..] } else { &[96.0][..] } { + let pm = render(&l, &mut maps, *dpi, &info).unwrap(); + drawn.push((format!("page {page} at {dpi} dpi"), fnv(std::slice::from_ref(&pm)))); + } + } + let wrong = crate::layout::pin_mismatches("drawing", &drawn, &PINNED_PICTURE_PIXELS); + assert!(wrong.is_empty(), "{}", wrong.join("\n")); +} + /// How [`scale_bars_without_details_draw_as_before`]'s bars drew before scale bars had details, /// their labels in the built-in face. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 7620ceb1c4..55e6bac47f 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -938,4 +938,66 @@ mod tests { wrong.extend(crate::layout::pin_mismatches("PDF", &pdf, &PINNED_LEGEND_PDF)); assert!(wrong.is_empty(), "{}", wrong.join("\n")); } + + /// How [`pictures_export_as_before`]'s pages were written as SVG and as a vector PDF before + /// pictures remembered their file, in the built-in face: each page of + /// [`crate::layout::picture_pin_pages`] in turn. + #[cfg(not(target_arch = "wasm32"))] + const PINNED_PICTURE_SVG: [u64; 10] = [ + 0x4942_1842_02a6_e13c, // 1: the PNG in a wider box + 0xa7c0_17e7_a596_aa3d, // 2: the PNG in a taller box + 0x485b_5dbb_83f7_a658, // 3: the JPEG + 0xfc56_9f71_2ee2_878b, // 4: an empty image, a grey box with its word + 0xfc56_9f71_2ee2_878b, // 5: not an image (page 4's: the same grey box in the same box) + 0xfc56_9f71_2ee2_878b, // 6: declared too large (page 4's, as page 5) + 0x472a_6b1c_6e32_0e7e, // 7: an empty image in a box smaller than its word + 0xc1f2_7486_0200_c97e, // 8: the PNG on a background + 0x067f_181a_d41a_c8ad, // 9: a hidden empty picture beside the PNG + 0xf235_0cfd_309c_1f51, // 10: the PNG across the page's right edge + ]; + #[cfg(not(target_arch = "wasm32"))] + const PINNED_PICTURE_PDF: [u64; 10] = [ + 0x200d_c9c7_cd54_9cbd, // 1: the PNG in a wider box + 0xe045_9691_934f_1fe9, // 2: the PNG in a taller box + 0xeed1_410f_5a3c_0369, // 3: the JPEG + 0x0eb3_c651_f3e1_54ba, // 4: an empty image, a grey box with its word + 0x0eb3_c651_f3e1_54ba, // 5: not an image (page 4's: the same grey box in the same box) + 0x0eb3_c651_f3e1_54ba, // 6: declared too large (page 4's, as page 5) + 0xea75_a4d8_57fc_3e36, // 7: an empty image in a box smaller than its word + 0x1879_7c0e_152d_9db0, // 8: the PNG on a background + 0x043b_262a_8f1a_11a8, // 9: a hidden empty picture beside the PNG + 0xf03a_ae65_baa2_25d1, // 10: the PNG across the page's right edge + ]; + + /// A picture's SVG (at 72 dpi, its pictures drawn at that resolution) and vector PDF (at 150 + /// dpi) are byte for byte main's, page by page: ten pages each. In a process of its own, told + /// to use the built-in face before any text. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn pictures_export_as_before() { + if std::env::var_os("RUSTGIS_PICTURE_EXPORT_PIN_CHILD").is_none() { + let output = std::process::Command::new(std::env::current_exe().unwrap()) + .args(["--exact", "svg::tests::pictures_export_as_before", "--nocapture"]) + .env("RUSTGIS_PICTURE_EXPORT_PIN_CHILD", "1") + .env("RUSTGIS_BUILTIN_FONTS", "1") + .output() + .unwrap(); + assert!(output.status.success(), "{}\n{}", String::from_utf8_lossy(&output.stdout), String::from_utf8_lossy(&output.stderr)); + assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process"); + return; + } + let info = PageInfo::default(); + let (mut svg, mut pdf) = (Vec::new(), Vec::new()); + for (i, (l, mut maps)) in crate::layout::picture_pin_pages().into_iter().enumerate() { + let page = format!("page {}", i + 1); + let written = layout_svg(&l, &mut maps, 72.0, &info).unwrap().0.into_bytes(); + svg.push((page.clone(), fnv(&written))); + let (drawing, _) = crate::layout::render_drawing(&l, &mut maps, 150.0, &info).unwrap(); + let bytes = crate::pdf::write(&[crate::pdf::Page::drawing(drawing, l.width, l.height)], "Pictures"); + pdf.push((page, fnv(&bytes))); + } + let mut wrong = crate::layout::pin_mismatches("SVG", &svg, &PINNED_PICTURE_SVG); + wrong.extend(crate::layout::pin_mismatches("PDF", &pdf, &PINNED_PICTURE_PDF)); + assert!(wrong.is_empty(), "{}", wrong.join("\n")); + } } From b4ab52f2dd93ecab953fd75074c66618eae655a7 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 18:15:12 -0600 Subject: [PATCH 02/38] test(render): pin pictures from frozen images, and every answer a picture's file gets today The pinned PNG and JPEG are base64 constants, so an encoder's new output can't move a pin; the JPEG is flat in every 8 x 8 block and 4:4:4, so every decoder path decodes it alike. Pinned too: a picture in a box two pixels across, a map graphic's picture, what the saved project requires, the Assistant's view of a region with and without a picture, a map series' PDF, and what layout.addElement and layout.update answer for every image and path a later change treats differently. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/tests/layout_pictures.rs | 303 +++++++++++++-------- crates/render/src/layout.rs | 85 +++--- crates/render/src/layout/tests.rs | 27 +- crates/render/src/svg.rs | 14 +- 4 files changed, 271 insertions(+), 158 deletions(-) diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 54b8846e37..308e6a7f06 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -5,7 +5,8 @@ use crate::Session; #[cfg(not(target_arch = "wasm32"))] use serde_json::{Value, json}; -/// A `w` x `h` PNG, each pixel the opaque colour `colours` gives it, as base64. +/// A `w` x `h` PNG, each pixel the opaque colour `colours` gives it, as base64: made when the test +/// runs, for a picture whose declared size alone decides what it is answered. #[cfg(not(target_arch = "wasm32"))] fn png_b64(w: u32, h: u32, colours: impl Fn(u32, u32) -> [u8; 3]) -> String { use base64::Engine as _; @@ -18,54 +19,96 @@ fn png_b64(w: u32, h: u32, colours: impl Fn(u32, u32) -> [u8; 3]) -> String { base64::engine::general_purpose::STANDARD.encode(pm.encode_png().unwrap()) } -/// A 32 x 32 RGB JPEG of a diagonal gradient at quality 80, as base64. +/// The PNG the render pins draw (a copy of `rustgis_render`'s), frozen so an encoder's new output +/// can't move a pin: 40 x 20, its left half (columns 0 to 19) `#1F5C84`, its right half +/// `#E8B04A`, row 10 white; written by `tiny_skia::Pixmap::encode_png` (8-bit RGBA, opaque) and +/// base64 (standard) once. #[cfg(not(target_arch = "wasm32"))] -fn jpeg_b64() -> String { - use base64::Engine as _; - let rgb: Vec = (0..32u32 * 32).flat_map(|i| [((i % 32 + i / 32) * 4) as u8, 120, (255 - (i % 32 + i / 32) * 4) as u8]).collect(); - let mut jpeg = Vec::new(); - image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 80).encode(&rgb, 32, 32, image::ExtendedColorType::Rgb8).unwrap(); - base64::engine::general_purpose::STANDARD.encode(jpeg) -} +const PIN_PNG: &str = concat!( + "iVBORw0KGgoAAAANSUhEUgAAACgAAAAUCAYAAAD/Rn+7AAAAWElEQVR4nO3VMQ2AUBAE0WHzfYAoSnAD1khQdUig", + "uYQpeAIm2+2Yt6NodK9XZ44gF+SCXJALckEuyAW5IDdVVeuTdBvLfrYG7//qZIJckAtyQS7I5esBbx4rIwruG4R9", + "JwAAAABJRU5ErkJggg==", +); -/// The PNG the render pins draw: 40 x 20, its left half `#1F5C84`, its right half `#E8B04A`, a -/// white line one pixel high across the middle. +/// The JPEG the render pins draw (a copy of `rustgis_render`'s), frozen as the PNG is: 32 x 32, +/// sixteen 8 x 8 blocks each of one colour, block (bx, by) RGB (40 + 60 bx, 40 + 60 by, 200 - 20 +/// (bx + by)); written once by the `image` crate's `JpegEncoder` at quality 80, which writes it +/// 4:4:4 (every component sampled 1 x 1). #[cfg(not(target_arch = "wasm32"))] -fn pin_png() -> String { - png_b64(40, 20, |x, y| match (x, y) { - (_, 10) => [0xFF, 0xFF, 0xFF], - (0..20, _) => [0x1F, 0x5C, 0x84], - _ => [0xE8, 0xB0, 0x4A], - }) -} +const PIN_JPEG: &str = concat!( + "/9j/4AAQSkZJRgABAgAAAQABAAD/wAARCAAgACADAREAAhEBAxEB/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoU", + "Dg8MEBcUGBgXFBYWGh0lHxobIxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgo", + "KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8QAHwAAAQUBAQEBAQEAAAAAAAAA", + "AAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAk", + "M2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKT", + "lJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QA", + "HwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdh", + "cRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hp", + "anN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk", + "5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDyKv1s4DVryT6U1a8g+jNSvIPpTNr6I/nc1a8g+kNSvIPpTVry", + "T6Mza+iP54NWvIPpTUryD6M1a8g+lM2voz+eDVryD6Q1K8g+kNWvIPpD/9k=", +); /// What [`pictures_save_and_say_as_before`] saved before pictures remembered their file, in turn. #[cfg(not(target_arch = "wasm32"))] -const PINNED_PICTURE_SAVES: [u64; 2] = [ - 0xc7c7_77d9_64d6_2abc, // the project's layouts - 0x5d70_a4b1_1043_607d, // the layout's own file +const PINNED_PICTURE_SAVES: [u64; 3] = [ + 0xa9fd_f881_3487_56d3, // the project's layouts + 0x9595_ade9_9651_60a0, // the layout's own file + 0xdf18_dc46_0b16_30e7, // what the project requires: ["layout-element-background"] ]; /// What each export of its layout said, in the order of the routes: where it wrote the file, and /// nothing of its pictures. #[cfg(not(target_arch = "wasm32"))] -const PINNED_PICTURE_NOTICES: [u64; 6] = [ +const PINNED_PICTURE_NOTICES: [u64; 9] = [ 0x91fe_c13a_e3f0_46f7, // layout.export png: "Exported /p.png" 0x91dc_c03a_e3d3_5ede, // layout.export pdf: "Exported /p.pdf" 0xaba9_5c3a_f262_802e, // layout.export svg: "Exported /p.svg" 0xcbf2_9ce4_8422_2325, // the Assistant's view: nothing at all 0x39f5_2536_3dfd_3cbd, // report.export png: "Exported /r.png" 0x39e0_3436_3dea_fa30, // report.export pdf: "Exported /r.pdf" + 0xcbf2_9ce4_8422_2325, // the Assistant's view of a region with a picture: nothing + 0xcbf2_9ce4_8422_2325, // the Assistant's view of a region without one: nothing + 0xa900_a1bc_27c1_480f, // the series' PDF of every page: "Exported /series.pdf" ]; +/// Each hash that isn't its pinned one, named, with both values and all of them to pin. +#[cfg(not(target_arch = "wasm32"))] +fn mismatches(what: &str, got: &[(String, u64)], pinned: &[u64]) -> Vec { + let mut wrong: Vec = got + .iter() + .zip(pinned) + .filter(|((_, g), p)| g != *p) + .map(|((name, g), p)| format!("{what} {name}: got {g:#018x}, pinned {p:#018x}")) + .collect(); + if got.len() != pinned.len() || !wrong.is_empty() { + let all: Vec = got.iter().map(|(name, g)| format!("{g:#018x}, // {name}")).collect(); + wrong.push(format!("{what}s, {} of {} pinned, all:\n{}", got.len(), pinned.len(), all.join("\n"))); + } + wrong +} + +/// Removed however the test ends. +#[cfg(not(target_arch = "wasm32"))] +struct Dir(std::path::PathBuf); + +#[cfg(not(target_arch = "wasm32"))] +impl Drop for Dir { + fn drop(&mut self) { + std::fs::remove_dir_all(&self.0).ok(); + } +} + /// What main saves for pictures not read from a file, and says when a layout of pictures that draw /// is exported every way, before pictures remembered their file; in the built-in face, in a process /// of its own. The layout is an older file's, imported (a hidden picture with no image, which only /// a file holds), with a PNG, a JPEG and the PNG on a background added to it. The saves, each -/// pinned on its own: the project's layouts as JSON, and the layout's own file (header and all). -/// The exports, each pinned on its own: PNG, PDF and SVG by `layout.export`, the Assistant's view -/// of the layout, and a report of it as PNG and as PDF. The test's folder is taken out of what is -/// said before it is hashed. Then what `layout.addElement` answers for a picture's `image` and -/// `path`, case by case, word for word. +/// pinned on its own: the project's layouts as JSON, the layout's own file (header and all), and +/// what the saved project requires. The exports, each pinned on its own: PNG, PDF and SVG by +/// `layout.export`, the Assistant's view of the layout whole, of a region holding a picture and of +/// one holding none, a report of it as PNG and as PDF, and every page of a map series' PDF of a +/// layout with a picture. The test's folder is taken out of what is said before it is hashed. Then +/// what `layout.addElement` answers for a picture's `image` and `path`, and what `layout.update` +/// does with them on a picture, case by case, word for word. #[cfg(not(target_arch = "wasm32"))] #[test] fn pictures_save_and_say_as_before() { @@ -81,27 +124,6 @@ fn pictures_save_and_say_as_before() { assert!(String::from_utf8_lossy(&output.stdout).contains("1 passed"), "the test didn't run in the child process"); return; } - // Each hash that isn't its pinned one, named, with both values and all of them to pin. - let mismatches = |what: &str, got: &[(String, u64)], pinned: &[u64]| { - let mut wrong: Vec = got - .iter() - .zip(pinned) - .filter(|((_, g), p)| g != *p) - .map(|((name, g), p)| format!("{what} {name}: got {g:#018x}, pinned {p:#018x}")) - .collect(); - if got.len() != pinned.len() || !wrong.is_empty() { - let all: Vec = got.iter().map(|(name, g)| format!("{g:#018x}, // {name}")).collect(); - wrong.push(format!("{what}s, {} of {} pinned, all:\n{}", got.len(), pinned.len(), all.join("\n"))); - } - wrong - }; - /// Removed however the test ends. - struct Dir(std::path::PathBuf); - impl Drop for Dir { - fn drop(&mut self) { - std::fs::remove_dir_all(&self.0).ok(); - } - } let dir = Dir(std::env::temp_dir().join(format!("rustgis-pictures-save-and-say-{}", std::process::id()))); std::fs::create_dir_all(&dir.0).unwrap(); let at = |file: &str| dir.0.join(file).display().to_string(); @@ -114,27 +136,35 @@ fn pictures_save_and_say_as_before() { {"id": 1, "name": "Old picture", "x": 10.0, "y": 10.0, "w": 40.0, "h": 20.0, "visible": false, "kind": {"Picture": {"image": ""}}} ]}); s.run("layout.import", &json!({"text": old.to_string()})).unwrap(); - let (png, jpeg) = (pin_png(), jpeg_b64()); let backed = json!({"fill": "#FFF3D6", "outline": "#222222", "width": 1, "padding": 2}); + let mut added = Vec::new(); for p in [ - json!({"kind": "picture", "image": png, "x": 20, "y": 40, "w": 60, "h": 30}), - json!({"kind": "picture", "image": jpeg, "x": 100, "y": 40, "w": 40, "h": 40}), - json!({"kind": "picture", "image": png, "x": 20, "y": 100, "w": 60, "h": 30, "background": backed}), + json!({"kind": "picture", "image": PIN_PNG, "x": 20, "y": 40, "w": 60, "h": 30}), + json!({"kind": "picture", "image": PIN_JPEG, "x": 100, "y": 40, "w": 40, "h": 40}), + json!({"kind": "picture", "image": PIN_PNG, "x": 20, "y": 100, "w": 60, "h": 30, "background": backed}), ] { - s.run("layout.addElement", &p).unwrap(); + added.push(s.run("layout.addElement", &p).unwrap()["element"].clone()); } let li = s.project.layouts.len() - 1; let name = s.project.layouts[li].name.clone(); assert_eq!((s.project.layouts.len(), name.as_str(), s.project.layouts[li].elements.len()), (1, "Pictures", 4)); + let requires = serde_json::to_value(&s.project).unwrap()["requires"].to_string(); let saves = [ ("layouts".to_string(), super::fnv_bytes(serde_json::to_string(&s.project.layouts).unwrap().as_bytes())), ("layout file".to_string(), super::fnv_bytes(&crate::project::layout_file_bytes(&s.project.layouts[li]).unwrap())), + (format!("project requires {requires}"), super::fnv_bytes(requires.as_bytes())), ]; s.run("report.new", &json!({"layer": "Countries", "name": "R", "fields": ["name"], "where": "name LIKE 'F%'"})).unwrap(); s.run("report.existingTemplate", &json!({"report": "R", "layout": name})).unwrap(); + // A map series of a layout with a picture, in a session of its own: its frame drawn at each + // lake in turn. + let mut series = super::world(); + series.run("layout.new", &json!({"name": "Series", "page": "a4", "orientation": "landscape"})).unwrap(); + series.run("layout.addElement", &json!({"kind": "picture", "image": PIN_PNG, "x": 200, "y": 20, "w": 40, "h": 20})).unwrap(); + series.run("layout.series", &json!({"layer": "Lakes"})).unwrap(); let export = |path: String, dpi: Option| { move |s: &mut Session| { - let mut p = json!({"layout": li, "path": path}); + let mut p = json!({"path": path}); if let Some(dpi) = dpi { p["dpi"] = json!(dpi); } @@ -143,89 +173,142 @@ fn pictures_save_and_say_as_before() { }; let report = |path: String| move |s: &mut Session| drop(s.run("report.export", &json!({"report": "R", "path": path, "dpi": 36})).unwrap()); - let routes: Vec<(&str, Box)> = vec![ - // route: layout.export as PNG - ("layout.export png", Box::new(export(at("p.png"), Some(72.0)))), - // route: layout.export as PDF - ("layout.export pdf", Box::new(export(at("p.pdf"), None))), - // route: layout.export as SVG - ("layout.export svg", Box::new(export(at("p.svg"), None))), - // route: the Assistant's view of the layout - ("the Assistant's view", Box::new(move |s: &mut Session| drop(crate::cmd::layout::layout_png(s, li, 72.0, None).unwrap()))), - // route: report.export as PNG - ("report.export png", Box::new(report(at("r.png")))), - // route: report.export as PDF - ("report.export pdf", Box::new(report(at("r.pdf")))), - ]; + let view = |region: Option<[f64; 4]>| move |s: &mut Session| drop(crate::cmd::layout::layout_png(s, li, 72.0, region).unwrap()); let mut notices = Vec::new(); - for (route, run) in &routes { + let mut said = |route: &str, s: &mut Session, run: &dyn Fn(&mut Session)| { let mark = s.notice_mark(); - run(&mut s); + run(s); let texts: Vec = s.notices_since(mark).iter().map(|n| n.text.replace(&folder, "/")).collect(); let text = texts.join("\n"); assert!(!text.contains(&*dir.0.to_string_lossy()), "{route}: the folder is said in another form: {text}"); notices.push((format!("{route}: {text:?}"), super::fnv_bytes(text.as_bytes()))); - } + }; + // route: layout.export as PNG + said("layout.export png", &mut s, &export(at("p.png"), Some(72.0))); + // route: layout.export as PDF + said("layout.export pdf", &mut s, &export(at("p.pdf"), None)); + // route: layout.export as SVG + said("layout.export svg", &mut s, &export(at("p.svg"), None)); + // route: the Assistant's view of the layout + said("the Assistant's view", &mut s, &view(None)); + // route: report.export as PNG + said("report.export png", &mut s, &report(at("r.png"))); + // route: report.export as PDF + said("report.export pdf", &mut s, &report(at("r.pdf"))); + // route: the Assistant's view of a region holding the PNG at (20, 40) + said("the Assistant's view of a region with a picture", &mut s, &view(Some([15.0, 35.0, 70.0, 40.0]))); + // route: the Assistant's view of a region holding no picture + said("the Assistant's view of a region without one", &mut s, &view(Some([150.0, 200.0, 40.0, 40.0]))); + // route: layout.export of the map series as a PDF of every page + said("the series' PDF of every page", &mut series, &export(at("series.pdf"), Some(36.0))); let mut wrong = mismatches("save", &saves, &PINNED_PICTURE_SAVES); wrong.extend(mismatches("notice", ¬ices, &PINNED_PICTURE_NOTICES)); - // What `layout.addElement` answers for each picture given, word for word, the folder taken out: - // a refusal, or what it added. + + // What `layout.addElement` answers for each picture given, word for word, the folder taken out + // and the system's own words for a file it can't find marked: a refusal, or what it added. let huge = png_b64(30_000, 1, |_, _| [0x1F, 0x5C, 0x84]); // The PNG cut four bytes into its pixels: its size reads, its pixels don't. let damaged = { - let bytes = base64::engine::general_purpose::STANDARD.decode(&png).unwrap(); + let bytes = base64::engine::general_purpose::STANDARD.decode(PIN_PNG).unwrap(); let pixels = bytes.windows(4).position(|w| w == b"IDAT").unwrap() + 4; base64::engine::general_purpose::STANDARD.encode(&bytes[..pixels + 4]) }; - std::fs::write(dir.0.join("note.png"), "not a picture").unwrap(); + let file = |name: &str, bytes: &[u8]| { + std::fs::write(dir.0.join(name), bytes).unwrap(); + at(name) + }; + let b64 = |s: &str| base64::engine::general_purpose::STANDARD.decode(s).unwrap(); + let note = file("note.png", b"not a picture"); + let huge_file = file("huge.png", &b64(&huge)); + let damaged_file = file("damaged.png", &b64(&damaged)); + let over = file("over.png", &vec![0u8; (16 << 20) + 1]); std::fs::create_dir_all(dir.0.join("folder.png")).unwrap(); - // What the system says of a file that isn't there, which differs between systems. - let not_found = std::fs::metadata(dir.0.join("missing.png")).unwrap_err().to_string(); - let too_large = "A".repeat((16 << 20) / 3 * 4 + 8); - let images = [(&png, "the PNG"), (&huge, "the 30000 x 1 PNG"), (&damaged, "the damaged PNG")]; + let address = "http://example.invalid/a.png"; + // What the system says of a path it can't open, which differs between systems: marked. + let marked = |text: String, path: &str| match std::fs::metadata(path) { + Err(e) => text.replace(&e.to_string(), ""), + Ok(_) => text, + }; + let images = [(PIN_PNG, "the PNG"), (huge.as_str(), "the 30000 x 1 PNG"), (damaged.as_str(), "the damaged PNG")]; let rectangle = |key: &str, v: Value| { let mut p = json!({"kind": "rectangle", "x": 10, "y": 10, "w": 20, "h": 20}); p[key] = v; p }; - let cases: Vec<(&str, Value, String)> = vec![ - ("neither an image nor a path", json!({"kind": "picture"}), "a picture needs an image or a path".into()), - ( - "an image that isn't one", - json!({"kind": "picture", "image": "bm90IGFuIGltYWdl"}), - "the picture isn't a PNG or JPEG image".into(), - ), - ("an empty image", json!({"kind": "picture", "image": ""}), "the picture isn't a PNG or JPEG image".into()), - ("an image over 16 MiB", json!({"kind": "picture", "image": too_large}), "the picture is too large".into()), - ("a path to a missing file", json!({"kind": "picture", "path": at("missing.png")}), format!("/missing.png: {not_found}")), - ("a path to a folder", json!({"kind": "picture", "path": at("folder.png")}), "/folder.png: not a regular file".into()), - ("a path to a text file", json!({"kind": "picture", "path": at("note.png")}), "the picture isn't a PNG or JPEG image".into()), - // Task 4 changes this to "path is the path of a PNG or JPEG file". - ("a path that isn't text", json!({"kind": "picture", "path": 5}), "a picture needs an image or a path".into()), - // Task 4 refuses this ("give a picture an image or a path, not both"); main uses the image. - ("both an image and a path", json!({"kind": "picture", "image": png, "path": at("note.png")}), "added a picture of the PNG".into()), - // Task 4 refuses these two (their image can't be drawn); main adds each as a grey box. - ("an image over 20000 pixels a side", json!({"kind": "picture", "image": huge}), "added a picture of the 30000 x 1 PNG".into()), - ("an image whose pixels don't read", json!({"kind": "picture", "image": damaged}), "added a picture of the damaged PNG".into()), - // Task 4 refuses these two ("only pictures take an image or a path"); main ignores the key. - ("an image on a rectangle", rectangle("image", json!(png)), "added a rectangle".into()), - ("a path on a rectangle", rectangle("path", json!(at("missing.png"))), "added a rectangle".into()), + let picture = |key: &str, v: Value| { + let mut p = json!({"kind": "picture"}); + p[key] = v; + p + }; + let cases: Vec<(&str, Value, &str)> = vec![ + ("neither an image nor a path", json!({"kind": "picture"}), "a picture needs an image or a path"), + ("an image that isn't one", picture("image", json!("bm90IGFuIGltYWdl")), "the picture isn't a PNG or JPEG image"), + ("an empty image", picture("image", json!("")), "the picture isn't a PNG or JPEG image"), + ("an image over 16 MiB", picture("image", json!("A".repeat((16 << 20) / 3 * 4 + 8))), "the picture is too large"), + // An image that isn't text is read as no image. + ("an image that is a number", picture("image", json!(5)), "a picture needs an image or a path"), + ("a path to a missing file", picture("path", json!(at("missing.png"))), "/missing.png: "), + ("an empty path", picture("path", json!("")), ": "), + ("a path that is an address", picture("path", json!(address)), "http://example.invalid/a.png: "), + ("a path to a folder", picture("path", json!(at("folder.png"))), "/folder.png: not a regular file"), + ("a path to a text file", picture("path", json!(note)), "the picture isn't a PNG or JPEG image"), + ("a path to a file of 16 MiB and a byte", picture("path", json!(over)), "the picture is too large"), + // A path that isn't text is read as no path. + ("a path that is a number", picture("path", json!(5)), "a picture needs an image or a path"), + // Given both, the image is used and the path is never read. + ("both an image and a path", json!({"kind": "picture", "image": PIN_PNG, "path": note}), "added a picture of the PNG"), + // These four are added, and each draws as the grey box: their size reads, but their pixels + // can't be drawn (declared over 20000 pixels a side, or cut short). + ("an image over 20000 pixels a side", picture("image", json!(huge)), "added a picture of the 30000 x 1 PNG"), + ("an image whose pixels don't read", picture("image", json!(damaged)), "added a picture of the damaged PNG"), + ("a path to a PNG over 20000 pixels a side", picture("path", json!(huge_file)), "added a picture of the 30000 x 1 PNG"), + ("a path to a PNG whose pixels don't read", picture("path", json!(damaged_file)), "added a picture of the damaged PNG"), + // Other kinds of element ignore `image` and `path`. + ("an image on a rectangle", rectangle("image", json!(PIN_PNG)), "added a rectangle"), + ("a path on a rectangle", rectangle("path", json!(at("missing.png"))), "added a rectangle"), ]; + let which = |s: &Session, id: &Value| match s.project.layouts[li].element(id.as_u64().unwrap() as u32).map(|e| &e.kind) { + Some(rustgis_map::layout::ElementKind::Picture { image }) => { + format!("a picture of {}", images.iter().find(|(i, _)| *i == image.as_str()).map_or("another image", |(_, n)| n)) + } + Some(k) => format!("a {}", k.code()), + None => "nothing".into(), + }; for (case, p, pinned) in &cases { + let path = p.get("path").and_then(Value::as_str).unwrap_or(""); let got = match s.run("layout.addElement", p) { - Err(e) => e.replace(&folder, "/"), - Ok(r) => match s.project.layouts[li].element(r["element"].as_u64().unwrap() as u32).map(|e| &e.kind) { - Some(rustgis_map::layout::ElementKind::Picture { image }) => { - let which = images.iter().find(|(i, _)| *i == image).map_or("another image", |(_, n)| n); - format!("added a picture of {which}") - } - Some(k) => format!("added a {}", k.code()), - None => "added nothing".into(), - }, + Err(e) => marked(e, path).replace(&folder, "/"), + Ok(r) => format!("added {}", which(&s, &r["element"])), }; if got != *pinned { wrong.push(format!("layout.addElement with {case}: got {got:?}, pinned {pinned:?}")); } } + // What `layout.update` does with `path` and `image` on a picture (the PNG first added): its + // answer, the picture afterwards, and the Undo steps it leaves. It takes neither key: the + // picture is left as it was, the file never read, and one Undo step is left all the same. + let png_picture = &added[0]; + for (case, key, v, pinned) in [ + ( + "a path to the JPEG's file", + "path", + json!(file("jpeg.jpg", &b64(PIN_JPEG))), + "answered null; a picture of the PNG after; 1 Undo step(s)", + ), + ("the JPEG as an image", "image", json!(PIN_JPEG), "answered null; a picture of the PNG after; 1 Undo step(s)"), + ("a path to a missing file", "path", json!(at("missing.png")), "answered null; a picture of the PNG after; 1 Undo step(s)"), + ] { + let depth = s.undo_depth(); + let mut p = json!({"layout": li, "element": png_picture}); + p[key] = v; + let answer = match s.run("layout.update", &p) { + Ok(r) => format!("answered {r}"), + Err(e) => format!("refused {:?}", e.replace(&folder, "/")), + }; + let got = format!("{answer}; {} after; {} Undo step(s)", which(&s, png_picture), s.undo_depth() - depth); + if got != pinned { + wrong.push(format!("layout.update with {case}: got {got:?}, pinned {pinned:?}")); + } + } assert!(wrong.is_empty(), "{}", wrong.join("\n")); } diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 4148f3a14c..2e533a5d90 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -1061,7 +1061,8 @@ pub(crate) fn legend_pin_pages() -> Vec<(Layout, Vec)> { pages } -/// A `w` x `h` PNG, each pixel the opaque colour `colours` gives it, as base64. +/// A `w` x `h` PNG, each pixel the opaque colour `colours` gives it, as base64: made when the pins +/// run, for a picture whose declared size alone decides what is drawn. #[cfg(all(test, not(target_arch = "wasm32")))] fn png_b64(w: u32, h: u32, colours: impl Fn(u32, u32) -> [u8; 3]) -> String { use base64::Engine as _; @@ -1074,43 +1075,52 @@ fn png_b64(w: u32, h: u32, colours: impl Fn(u32, u32) -> [u8; 3]) -> String { pm.encode_png().map(|png| base64::engine::general_purpose::STANDARD.encode(png)).unwrap_or_default() } -/// A 32 x 32 RGB JPEG of a diagonal gradient at quality 80, as base64. +/// The PNG the picture pins draw, frozen so an encoder's new output can't move a pin: 40 x 20, +/// its left half (columns 0 to 19) `#1F5C84`, its right half `#E8B04A`, row 10 white; written by +/// `tiny_skia::Pixmap::encode_png` (8-bit RGBA, opaque) and base64 (standard) once. #[cfg(all(test, not(target_arch = "wasm32")))] -fn jpeg_b64() -> String { - use base64::Engine as _; - let rgb: Vec = (0..32u32 * 32).flat_map(|i| [((i % 32 + i / 32) * 4) as u8, 120, (255 - (i % 32 + i / 32) * 4) as u8]).collect(); - let mut jpeg = Vec::new(); - let mut encoder = image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 80); - match encoder.encode(&rgb, 32, 32, image::ExtendedColorType::Rgb8) { - Ok(()) => base64::engine::general_purpose::STANDARD.encode(jpeg), - Err(_) => String::new(), - } -} +pub(crate) const PIN_PNG: &str = concat!( + "iVBORw0KGgoAAAANSUhEUgAAACgAAAAUCAYAAAD/Rn+7AAAAWElEQVR4nO3VMQ2AUBAE0WHzfYAoSnAD1khQdUig", + "uYQpeAIm2+2Yt6NodK9XZ44gF+SCXJALckEuyAW5IDdVVeuTdBvLfrYG7//qZIJckAtyQS7I5esBbx4rIwruG4R9", + "JwAAAABJRU5ErkJggg==", +); -/// The 40 x 20 PNG the picture pins draw: its left half `#1F5C84`, its right half `#E8B04A`, a -/// white line one pixel high across the middle (row 10). +/// The JPEG the picture pins draw, frozen as the PNG is: 32 x 32, sixteen 8 x 8 blocks each of one +/// colour, block (bx, by) RGB (40 + 60 bx, 40 + 60 by, 200 - 20 (bx + by)); written once by the +/// `image` crate's `JpegEncoder` at quality 80, which writes it 4:4:4 (every component sampled +/// 1 x 1). Each block is flat, so it holds only its DC coefficient, and every decoder path (wide +/// registers or none) decodes it with the same one-coefficient transform and the same colour +/// conversion: the pinned pixels are the same on every machine, while the page still tests a JPEG +/// decoded, placed and scaled. #[cfg(all(test, not(target_arch = "wasm32")))] -fn pin_png() -> String { - png_b64(40, 20, |x, y| match (x, y) { - (_, 10) => [0xFF, 0xFF, 0xFF], - (0..20, _) => [0x1F, 0x5C, 0x84], - _ => [0xE8, 0xB0, 0x4A], - }) -} +pub(crate) const PIN_JPEG: &str = concat!( + "/9j/4AAQSkZJRgABAgAAAQABAAD/wAARCAAgACADAREAAhEBAxEB/9sAQwAGBAUGBQQGBgUGBwcGCAoQCgoJCQoU", + "Dg8MEBcUGBgXFBYWGh0lHxobIxwWFiAsICMmJykqKRkfLTAtKDAlKCko/9sAQwEHBwcKCAoTCgoTKBoWGigoKCgo", + "KCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo/8QAHwAAAQUBAQEBAQEAAAAAAAAA", + "AAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAk", + "M2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKT", + "lJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QA", + "HwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdh", + "cRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hp", + "anN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk", + "5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDyKv1s4DVryT6U1a8g+jNSvIPpTNr6I/nc1a8g+kNSvIPpTVry", + "T6Mza+iP54NWvIPpTUryD6M1a8g+lM2voz+eDVryD6Q1K8g+kNWvIPpD/9k=", +); /// Pages of 100 x 80 mm, no maps, one picture each (no file to it, as main has none) unless -/// said: 1, the PNG of [`pin_png`] in (10, 10, 60, 30), a wider box (bars left and right); 2, the -/// PNG in (10, 10, 20, 60), a taller box (bars above and below); 3, the JPEG of [`jpeg_b64`] in -/// (10, 10, 40, 40); 4, an empty image in (10, 10, 40, 20), a grey box with "Picture"; 5, base64 -/// that isn't an image in (10, 10, 40, 20); 6, a 30000 x 1 PNG (it declares more than 20000 pixels -/// a side) in (10, 10, 40, 20), a grey box; 7, an empty image in a box smaller than its word, (10, -/// 10, 6, 4); 8, the PNG in (10, 10, 60, 30) on a background (fill `#FFF3D6`, outline `#222222` -/// 1 pt wide, padding 2 mm); 9, a hidden picture with an empty image at (10, 10, 40, 20) and the -/// PNG visible at (55, 10, 40, 20); 10, the PNG in a box across the page's right edge, (80, 10, -/// 40, 20). Pictures have no turn of their own. +/// said: 1, [`PIN_PNG`] in (10, 10, 60, 30), a wider box (bars left and right); 2, the PNG in (10, +/// 10, 20, 60), a taller box (bars above and below); 3, [`PIN_JPEG`] in (10, 10, 40, 40); 4, an +/// empty image in (10, 10, 40, 20), a grey box with "Picture"; 5, base64 that isn't an image in +/// (10, 10, 40, 20); 6, a 30000 x 1 PNG (it declares more than 20000 pixels a side) in (10, 10, +/// 40, 20), a grey box; 7, an empty image in a box smaller than its word, (10, 10, 6, 4); 8, the +/// PNG in (10, 10, 60, 30) on a background (fill `#FFF3D6`, outline `#222222` 1 pt wide, padding +/// 2 mm); 9, a hidden picture with an empty image at (10, 10, 40, 20) and the PNG visible at (55, +/// 10, 40, 20); 10, the PNG in a box across the page's right edge, (80, 10, 40, 20); 11, the PNG +/// in a box about two pixels by one at 96 dpi, (10, 10, 0.6, 0.3). Pictures have no turn of their +/// own. #[cfg(all(test, not(target_arch = "wasm32")))] pub(crate) fn picture_pin_pages() -> Vec<(Layout, Vec)> { - let (png, jpeg) = (pin_png(), jpeg_b64()); + let (png, jpeg) = (PIN_PNG, PIN_JPEG); let huge = png_b64(30_000, 1, |_, _| [0x1F, 0x5C, 0x84]); let page = |pictures: &[(&str, (f64, f64, f64, f64))]| { let mut l = Layout::new("Pictures", 100.0, 80.0); @@ -1120,7 +1130,7 @@ pub(crate) fn picture_pin_pages() -> Vec<(Layout, Vec)> { l }; let (wide, small) = ((10.0, 10.0, 60.0, 30.0), (10.0, 10.0, 40.0, 20.0)); - let mut backed = page(&[(&png, wide)]); + let mut backed = page(&[(png, wide)]); if let Some(e) = backed.elements.first_mut() { e.background = Some(rustgis_map::layout::Background { outline: Rgba::rgb(0x22, 0x22, 0x22), @@ -1129,21 +1139,22 @@ pub(crate) fn picture_pin_pages() -> Vec<(Layout, Vec)> { ..rustgis_map::layout::Background::filled(Rgba::rgb(0xFF, 0xF3, 0xD6)) }); } - let mut hidden = page(&[("", small), (&png, (55.0, 10.0, 40.0, 20.0))]); + let mut hidden = page(&[("", small), (png, (55.0, 10.0, 40.0, 20.0))]); if let Some(e) = hidden.elements.first_mut() { e.visible = false; } [ - page(&[(&png, wide)]), - page(&[(&png, (10.0, 10.0, 20.0, 60.0))]), - page(&[(&jpeg, (10.0, 10.0, 40.0, 40.0))]), + page(&[(png, wide)]), + page(&[(png, (10.0, 10.0, 20.0, 60.0))]), + page(&[(jpeg, (10.0, 10.0, 40.0, 40.0))]), page(&[("", small)]), page(&[("bm90IGFuIGltYWdl", small)]), page(&[(&huge, small)]), page(&[("", (10.0, 10.0, 6.0, 4.0))]), backed, hidden, - page(&[(&png, (80.0, 10.0, 40.0, 20.0))]), + page(&[(png, (80.0, 10.0, 40.0, 20.0))]), + page(&[(png, (10.0, 10.0, 0.6, 0.3))]), ] .into_iter() .map(|l| (l, Vec::new())) diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index d8039f096d..8ec2b5d0b7 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -5847,13 +5847,13 @@ fn legends_draw_as_before() { /// How [`pictures_draw_as_before`]'s pages drew before pictures remembered their file, in the /// built-in face, page by page: each page of [`crate::layout::picture_pin_pages`] at 96 dpi, pages -/// 1 and 4 at 300 dpi after it. +/// 1 and 4 at 300 dpi after it; then a map graphic's picture twice. #[cfg(not(target_arch = "wasm32"))] -const PINNED_PICTURE_PIXELS: [u64; 12] = [ +const PINNED_PICTURE_PIXELS: [u64; 15] = [ 0x9fa9_ca57_1c69_af27, // 1: the PNG in a wider box, 96 dpi 0x5752_b48f_072b_54d4, // 1: 300 dpi 0x7b3e_df0e_9fd1_f709, // 2: the PNG in a taller box - 0x49d8_734d_a88a_2ae0, // 3: the JPEG + 0x2def_df1a_abf3_c4ac, // 3: the JPEG 0x3440_95a3_d3dc_fb42, // 4: an empty image, a grey box with its word, 96 dpi 0xb771_eb09_bba9_f366, // 4: 300 dpi 0x3440_95a3_d3dc_fb42, // 5: not an image (page 4's: the same grey box in the same box) @@ -5862,13 +5862,18 @@ const PINNED_PICTURE_PIXELS: [u64; 12] = [ 0xe553_615c_19b6_2150, // 8: the PNG on a background 0xfa6f_1910_01a5_a96b, // 9: a hidden empty picture beside the PNG 0x6af5_c5c4_f5ee_41fa, // 10: the PNG across the page's right edge + 0x418c_7184_49ad_1074, // 11: the PNG in a box about two pixels by one + 0xebae_b1dc_c19e_9c2a, // a map graphic's PNG + 0x6275_1960_a4b9_de0d, // a map graphic's JPEG at half opacity ]; /// A picture draws exactly as main drew it, page by page ([`crate::layout::picture_pin_pages`]): /// every page at 96 dpi, and pages 1 (a PNG in a wider box) and 4 (an empty image's grey box and /// its word) at 300 dpi too, which holds the scaling of the image and of the grey box's outline and -/// word with the resolution: twelve drawings. In a process of its own, told to use the built-in -/// face before any text. +/// word with the resolution: thirteen drawings. Then a map graphic's picture as a map draws it +/// (`picture::draw`, which keeps decoded pictures as the layout's will): the PNG stretched over 60 +/// x 30 pixels, and the JPEG at half opacity over 20 x 40. In a process of its own, told to use the +/// built-in face before any text. #[cfg(not(target_arch = "wasm32"))] #[test] fn pictures_draw_as_before() { @@ -5898,6 +5903,18 @@ fn pictures_draw_as_before() { drawn.push((format!("page {page} at {dpi} dpi"), fnv(std::slice::from_ref(&pm)))); } } + for (name, image, (w, h), opacity) in [ + ("a map graphic's PNG", crate::layout::PIN_PNG, (60.0, 30.0), 1.0), + ("a map graphic's JPEG at half opacity", crate::layout::PIN_JPEG, (20.0, 40.0), 0.5), + ] { + use rustgis_data::{Dataset, Field, FieldType, GeometryType, Value}; + let mut ds = Dataset::new("Graphics", GeometryType::Point, vec![Field::new("image", FieldType::Text)]); + ds.push(None, vec![Value::Text(image.into())]); + let mut pm = Pixmap::new(80, 50).unwrap(); + pm.fill(tiny_skia::Color::WHITE); + crate::canvas::with_canvas(&mut pm, |c| crate::picture::draw(c, &ds, 0, (10.0, 5.0, 10.0 + w, 5.0 + h), opacity)); + drawn.push((name.to_string(), fnv(std::slice::from_ref(&pm)))); + } let wrong = crate::layout::pin_mismatches("drawing", &drawn, &PINNED_PICTURE_PIXELS); assert!(wrong.is_empty(), "{}", wrong.join("\n")); } diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 55e6bac47f..2d70609657 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -943,10 +943,10 @@ mod tests { /// pictures remembered their file, in the built-in face: each page of /// [`crate::layout::picture_pin_pages`] in turn. #[cfg(not(target_arch = "wasm32"))] - const PINNED_PICTURE_SVG: [u64; 10] = [ + const PINNED_PICTURE_SVG: [u64; 11] = [ 0x4942_1842_02a6_e13c, // 1: the PNG in a wider box 0xa7c0_17e7_a596_aa3d, // 2: the PNG in a taller box - 0x485b_5dbb_83f7_a658, // 3: the JPEG + 0x41f7_fd60_cf87_2ee9, // 3: the JPEG 0xfc56_9f71_2ee2_878b, // 4: an empty image, a grey box with its word 0xfc56_9f71_2ee2_878b, // 5: not an image (page 4's: the same grey box in the same box) 0xfc56_9f71_2ee2_878b, // 6: declared too large (page 4's, as page 5) @@ -954,12 +954,13 @@ mod tests { 0xc1f2_7486_0200_c97e, // 8: the PNG on a background 0x067f_181a_d41a_c8ad, // 9: a hidden empty picture beside the PNG 0xf235_0cfd_309c_1f51, // 10: the PNG across the page's right edge + 0x104a_db18_31a6_159a, // 11: the PNG in a box about two pixels by one ]; #[cfg(not(target_arch = "wasm32"))] - const PINNED_PICTURE_PDF: [u64; 10] = [ + const PINNED_PICTURE_PDF: [u64; 11] = [ 0x200d_c9c7_cd54_9cbd, // 1: the PNG in a wider box 0xe045_9691_934f_1fe9, // 2: the PNG in a taller box - 0xeed1_410f_5a3c_0369, // 3: the JPEG + 0xdcea_057d_62df_50cf, // 3: the JPEG 0x0eb3_c651_f3e1_54ba, // 4: an empty image, a grey box with its word 0x0eb3_c651_f3e1_54ba, // 5: not an image (page 4's: the same grey box in the same box) 0x0eb3_c651_f3e1_54ba, // 6: declared too large (page 4's, as page 5) @@ -967,11 +968,12 @@ mod tests { 0x1879_7c0e_152d_9db0, // 8: the PNG on a background 0x043b_262a_8f1a_11a8, // 9: a hidden empty picture beside the PNG 0xf03a_ae65_baa2_25d1, // 10: the PNG across the page's right edge + 0x31f9_97d3_9884_916c, // 11: the PNG in a box about two pixels by one ]; /// A picture's SVG (at 72 dpi, its pictures drawn at that resolution) and vector PDF (at 150 - /// dpi) are byte for byte main's, page by page: ten pages each. In a process of its own, told - /// to use the built-in face before any text. + /// dpi) are byte for byte main's, page by page: eleven pages each. In a process of its own, + /// told to use the built-in face before any text. #[cfg(not(target_arch = "wasm32"))] #[test] fn pictures_export_as_before() { From c71b1ee5f3aaedf192e2924cd0961869f56a9ad3 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:23:49 -0600 Subject: [PATCH 03/38] feat(layout): a layout picture remembers the file it was read from Saved only when kept, so a picture saved before saves byte for byte. A path is kept when it isn't blank, an address, over 4096 bytes or holding control characters; a hand-edited one that isn't loads as none and is counted. A picture shows its file's name, never its folders. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout/elements.rs | 8 +- crates/engine/src/cmd/presentation.rs | 6 +- crates/engine/src/tests/layout_pictures.rs | 2 +- crates/map/src/layout.rs | 11 +- crates/map/src/layout/elements.rs | 5 + crates/map/src/layout/picture.rs | 159 +++++++++++++++++++++ crates/render/src/layout.rs | 4 +- crates/render/src/layout/tests.rs | 2 +- crates/render/src/svg.rs | 2 +- crates/ui-egui/src/layoutview/tests.rs | 2 +- 10 files changed, 189 insertions(+), 12 deletions(-) create mode 100644 crates/map/src/layout/picture.rs diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index 0cdcdd3fcf..a59f68334b 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -441,9 +441,11 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu }; (if kind == "text" { "Text" } else { "Dynamic Text" }, place(p, l, (15.0, 12.0, 120.0, (size * 0.5).max(8.0)))?, k) } - "picture" => { - ("Picture", place(p, l, (pw - 60.0, ph - 50.0, 45.0, 35.0))?, ElementKind::Picture { image: image.unwrap_or_default() }) - } + "picture" => ( + "Picture", + place(p, l, (pw - 60.0, ph - 50.0, 45.0, 35.0))?, + ElementKind::Picture { image: image.unwrap_or_default(), source: None }, + ), "table" => { let frame = frame_of(l, p)?; let layer = frame_layer_name(s, l, frame, p)?; diff --git a/crates/engine/src/cmd/presentation.rs b/crates/engine/src/cmd/presentation.rs index 083fa2a31c..fe8dbe5f8b 100644 --- a/crates/engine/src/cmd/presentation.rs +++ b/crates/engine/src/cmd/presentation.rs @@ -429,7 +429,11 @@ pub fn page_layout(s: &Session, pres: &Presentation, page: &Page) -> Layout { let k = (bw / iw.max(1) as f64).min(bh / ih.max(1) as f64); (iw as f64 * k, ih as f64 * k) }); - l.add("Picture", (m + (bw - pw) / 2.0, top + (bh - ph) / 2.0, pw, ph), ElementKind::Picture { image: image.clone() }); + l.add( + "Picture", + (m + (bw - pw) / 2.0, top + (bh - ph) / 2.0, pw, ph), + ElementKind::Picture { image: image.clone(), source: None }, + ); if let PageKind::Video { source, .. } = &page.kind { l.add( "Play", diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 308e6a7f06..d8477e70f8 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -268,7 +268,7 @@ fn pictures_save_and_say_as_before() { ("a path on a rectangle", rectangle("path", json!(at("missing.png"))), "added a rectangle"), ]; let which = |s: &Session, id: &Value| match s.project.layouts[li].element(id.as_u64().unwrap() as u32).map(|e| &e.kind) { - Some(rustgis_map::layout::ElementKind::Picture { image }) => { + Some(rustgis_map::layout::ElementKind::Picture { image, .. }) => { format!("a picture of {}", images.iter().find(|(i, _)| *i == image.as_str()).map_or("another image", |(_, n)| n)) } Some(k) => format!("a {}", k.code()), diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index 4bdaef3f04..f006d6734b 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -22,6 +22,7 @@ mod grid; mod legend; mod lines; mod north; +mod picture; mod scale_bar; mod section; mod stats; @@ -35,6 +36,7 @@ pub use grid::*; pub use legend::*; pub use lines::*; pub use north::*; +pub use picture::*; pub use scale_bar::*; pub use section::*; pub use stats::*; @@ -494,7 +496,7 @@ impl Layout { let mut before = Element { name: e.name.clone(), kind: match &e.kind { - ElementKind::Picture { .. } => ElementKind::Picture { image: String::new() }, + ElementKind::Picture { source, .. } => ElementKind::Picture { image: String::new(), source: source.clone() }, kind => kind.clone(), }, ..*e @@ -662,12 +664,17 @@ impl Layout { *width = finite_or(*width, 1.0).clamp(0.0, 50.0) } ElementKind::Line { width, .. } => *width = finite_or(*width, 1.0).clamp(0.1, 50.0), + // A picture's file `picture_source_kept` doesn't keep (only a hand-edited one) is dropped. + ElementKind::Picture { source, .. } if source.as_deref().is_some_and(|s| !picture_source_kept(s)) => *source = None, _ => {} } // A map frame draws its map and its paper itself: a background on one (a hand-edited // file) is dropped. e.background = e.background.filter(|_| e.kind.takes_background()).map(Background::clamped); - let kind_changed = !matches!(e.kind, ElementKind::Picture { .. }) && e.kind != before.kind; + let kind_changed = match (&e.kind, &before.kind) { + (ElementKind::Picture { source, .. }, ElementKind::Picture { source: was, .. }) => source != was, + (kind, was) => kind != was, + }; changed.push(( kind_changed || e.background != before.background diff --git a/crates/map/src/layout/elements.rs b/crates/map/src/layout/elements.rs index 4cfaca88c9..aa742b4e51 100644 --- a/crates/map/src/layout/elements.rs +++ b/crates/map/src/layout/elements.rs @@ -227,6 +227,11 @@ pub enum ElementKind { Picture { /// Base64 PNG or JPEG. image: String, + /// The file it was read from, as the command was given it, when [`picture_source_kept`] + /// keeps it: a picture whose image is missing names it, and can be read from it again. + /// Left out when none, so layouts saved before keep their bytes. + #[serde(default, deserialize_with = "de_picture_source", skip_serializing_if = "picture_source_unkept")] + source: Option, }, /// The attribute table of a layer in a frame's map. Table { diff --git a/crates/map/src/layout/picture.rs b/crates/map/src/layout/picture.rs new file mode 100644 index 0000000000..e256c811ac --- /dev/null +++ b/crates/map/src/layout/picture.rs @@ -0,0 +1,159 @@ +//! A layout picture's file: which path it keeps, and what of it it shows. + +use super::*; + +/// The most bytes of a picture's file path kept: a longer one is dropped, never cut (a cut path +/// names another file). +pub const MAX_PICTURE_SOURCE: usize = 4096; + +/// Whether a picture keeps `path` as its file: when it isn't blank, holds no `://` (an address, +/// which could carry a login), no control character and none of U+202A–U+202E or U+2066–U+2069 +/// (which turn the direction of text), and is at most [`MAX_PICTURE_SOURCE`] bytes. A kept path is +/// kept exactly as given, neither trimmed nor resolved. A name holding a colon (`a:b.png`) is kept. +pub fn picture_source_kept(path: &str) -> bool { + !path.trim().is_empty() + && path.len() <= MAX_PICTURE_SOURCE + && !path.contains("://") + && !path.chars().any(|c| c.is_control() || matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')) +} + +/// The name a picture shows of its file `source`: its last part after `/` or `\` that isn't blank, +/// trimmed; none when every part is blank. The folders are never shown. +pub fn picture_file_name(source: &str) -> Option<&str> { + source.rsplit(['/', '\\']).map(str::trim).find(|part| !part.is_empty()) +} + +/// A picture's file as a file holds it: text as it is (whether it is kept is for `Layout::clamp`), +/// null as none, anything else (a number, a flag, a list, an object) as a blank, which +/// [`picture_source_kept`] never keeps. +pub(crate) fn de_picture_source<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + let v: Option = Deserialize::deserialize(d)?; + Ok(match v { + None | Some(serde_json::Value::Null) => None, + Some(serde_json::Value::String(s)) => Some(s), + Some(_) => Some(String::new()), + }) +} + +/// Whether a save leaves a picture's file out: none, or one [`picture_source_kept`] doesn't keep. +pub(crate) fn picture_source_unkept(s: &Option) -> bool { + !s.as_deref().is_some_and(picture_source_kept) +} + +impl ElementKind { + /// A picture's file, when it has one [`picture_source_kept`] keeps; none for anything else. + pub fn picture_source(&self) -> Option<&str> { + match self { + ElementKind::Picture { source, .. } => source.as_deref().filter(|s| picture_source_kept(s)), + _ => None, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use serde_json::json; + + /// A picture saved before keeps its bytes; one with a file writes it after its image and reads + /// it back. + #[test] + fn pictures_without_a_file_save_as_before() { + for plain in [r#"{"Picture":{"image":""}}"#, r#"{"Picture":{"image":"iVBORw0KGgo="}}"#] { + let k: ElementKind = serde_json::from_str(plain).unwrap(); + assert_eq!(serde_json::to_string(&k).unwrap(), plain); + assert_eq!(k.picture_source(), None); + } + let with = r#"{"Picture":{"image":"","source":"/data/logos/north.png"}}"#; + let k: ElementKind = serde_json::from_str(with).unwrap(); + assert_eq!(k.picture_source(), Some("/data/logos/north.png")); + assert_eq!(serde_json::to_string(&k).unwrap(), with); + } + + /// What of a path is kept: not blank, not an address, no control or direction-override + /// characters, at most MAX_PICTURE_SOURCE bytes; a POSIX name with a colon is kept. + #[test] + fn a_pictures_file_is_kept_only_when_it_is_a_plain_path() { + for kept in ["/data/logos/north.png", r"\\server\share\logo.jpg", "logo.png", "a:b.png", " spaced .png", "logo@2x.png"] { + assert!(picture_source_kept(kept), "{kept}"); + } + let long = format!("/{}", "d".repeat(MAX_PICTURE_SOURCE)); + for not in [ + "", + " ", + "https://user:secret@example.invalid/logo.png", + "file:///data/x.png", + "a\u{7}b.png", + "a\nb.png", + "x\u{202E}gnp.png", + long.as_str(), + ] { + assert!(!picture_source_kept(not), "{not:?}"); + } + assert!(picture_source_kept(&format!("/{}", "d".repeat(MAX_PICTURE_SOURCE - 1)))); + } + + /// The name a picture shows of its file: the last part, never the folders. + #[test] + fn picture_file_names_hide_their_folders() { + for (source, name) in [ + ("/data/logos/north.png", Some("north.png")), + (r"\\server\share\logo.jpg", Some("logo.jpg")), + (r"C:\maps\inset.png", Some("inset.png")), + ("logo.png", Some("logo.png")), + ("dir/", Some("dir")), + (" /x/ name.png ", Some("name.png")), + ("///", None), + ("", None), + ] { + assert_eq!(picture_file_name(source), name, "{source}"); + } + } + + /// A hand-edited file's source of the wrong kind, blank, an address, too long or with control + /// characters loads as none, counted once per element; the others are kept or none and not + /// counted; nothing dropped is written back. + #[test] + fn a_pictures_file_is_saved_when_kept_and_read_into_range() { + let long = format!("/{}", "d".repeat(5000)); + let sources = [ + Some(json!("/data/logos/north.png")), // 1: kept + Some(json!(5)), // 2: the wrong kind, dropped and counted + Some(json!(["a.png"])), // 3: the wrong kind, dropped and counted + Some(json!("")), // 4: blank, dropped and counted + Some(json!("https://user:secret@example.invalid/a.png")), // 5: an address + Some(json!(long)), // 6: too long, dropped and counted + Some(json!("a\u{7}b.png")), // 7: a control character, dropped and counted + Some(serde_json::Value::Null), // 8: none, not counted + None, // 9: absent, none, not counted + ]; + let elements: Vec<_> = sources + .iter() + .enumerate() + .map(|(i, source)| { + let mut picture = json!({"image": ""}); + if let Some(s) = source { + picture.as_object_mut().unwrap().insert("source".into(), s.clone()); + } + json!({"id": i + 1, "name": "p", "x": 0, "y": 0, "w": 50, "h": 50, "kind": {"Picture": picture}}) + }) + .collect(); + let mut l: Layout = serde_json::from_value(json!({"name": "x", "width": 297, "height": 210, "elements": elements})).unwrap(); + let repairs = l.clamp(); + let source = |id| match &l.element(id).unwrap().kind { + ElementKind::Picture { source, .. } => source.clone(), + k => panic!("{k:?}"), + }; + assert_eq!(source(1).as_deref(), Some("/data/logos/north.png")); + for id in 2..=9 { + assert_eq!(source(id), None, "{id}"); + } + assert_eq!((repairs.elements_adjusted, repairs.elements_cut), (6, 0)); + let saved = serde_json::to_string(&l).unwrap(); + assert!(saved.matches("\"source\"").count() == 1 && !saved.contains("secret"), "{saved}"); + // An unclamped junk source writes nothing. + let junk: ElementKind = serde_json::from_str(r#"{"Picture":{"image":"","source":7}}"#).unwrap(); + assert_eq!(serde_json::to_string(&junk).unwrap(), r#"{"Picture":{"image":""}}"#); + assert_eq!(junk.picture_source(), None); + } +} diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 2e533a5d90..2e26a36151 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -629,7 +629,7 @@ fn draw_page( }); } } - ElementKind::Picture { image } => { + ElementKind::Picture { image, .. } => { if let Some(img) = crate::picture::decode(image) { let (iw, ih) = (img.width() as f32, img.height() as f32); let s = (ew / iw).min(eh / ih); @@ -1125,7 +1125,7 @@ pub(crate) fn picture_pin_pages() -> Vec<(Layout, Vec)> { let page = |pictures: &[(&str, (f64, f64, f64, f64))]| { let mut l = Layout::new("Pictures", 100.0, 80.0); for (image, at) in pictures { - l.add("Picture", *at, ElementKind::Picture { image: (*image).to_string() }); + l.add("Picture", *at, ElementKind::Picture { image: (*image).to_string(), source: None }); } l }; diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 8ec2b5d0b7..484ac90f2d 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -5896,7 +5896,7 @@ fn pictures_draw_as_before() { let draws = l .elements .iter() - .any(|e| e.visible && matches!(&e.kind, ElementKind::Picture { image } if crate::picture::decode(image).is_some())); + .any(|e| e.visible && matches!(&e.kind, ElementKind::Picture { image, .. } if crate::picture::decode(image).is_some())); assert_eq!(draws, !(4..=7).contains(&page), "page {page}"); for dpi in if page == 1 || page == 4 { &[96.0, 300.0][..] } else { &[96.0][..] } { let pm = render(&l, &mut maps, *dpi, &info).unwrap(); diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 2d70609657..fc861ca41f 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -592,7 +592,7 @@ mod tests { #[test] fn cropped_images_use_their_actual_pixel_bounds() { let (mut layout, mut maps, _) = page(); - let id = layout.add("Picture", (-5.3, 70.2, 20.7, 20.0), ElementKind::Picture { image: String::new() }); + let id = layout.add("Picture", (-5.3, 70.2, 20.7, 20.0), ElementKind::Picture { image: String::new(), source: None }); let info = PageInfo::default(); let (pm, bounds) = render_element(&layout, id, &mut maps, 36.0, (&info, &Default::default()), &mut None).unwrap().unwrap(); let [x, y, w, h] = bounds; diff --git a/crates/ui-egui/src/layoutview/tests.rs b/crates/ui-egui/src/layoutview/tests.rs index e56de03380..4720df8a01 100644 --- a/crates/ui-egui/src/layoutview/tests.rs +++ b/crates/ui-egui/src/layoutview/tests.rs @@ -136,7 +136,7 @@ fn ink_reads_each_shape_as_drawn() { #[test] fn ink_reads_no_map_or_picture() { let picture = |l: &mut Layout| { - l.add("Picture", (0.0, 0.0, 100.0, 100.0), ElementKind::Picture { image: String::new() }); + l.add("Picture", (0.0, 0.0, 100.0, 100.0), ElementKind::Picture { image: String::new(), source: None }); }; assert_eq!(inked(PAGE, None, picture, nothing), INK); assert_eq!(inked(NAVY, None, picture, nothing), PAGE); From 979903007eee75168ec8d1e1fb2958ef124e9ebd Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 19:43:22 -0600 Subject: [PATCH 04/38] feat(render): a layout picture without an image names its file in its grey box A picture with no file draws the word Picture as before; one with a file draws the file's name, cut to its box, never its folders. Layout pictures share the decoded-picture cache, so the page, its checks and the commands decode one once while it is unchanged. One function tells which pictures draw as a grey box, and one words the notice. Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout.rs | 13 +- crates/render/src/layout/picture.rs | 279 ++++++++++++++++++++++++++++ crates/render/src/picture.rs | 46 ++++- 3 files changed, 322 insertions(+), 16 deletions(-) create mode 100644 crates/render/src/layout/picture.rs diff --git a/crates/render/src/layout.rs b/crates/render/src/layout.rs index 2e26a36151..8a0c2f3e91 100644 --- a/crates/render/src/layout.rs +++ b/crates/render/src/layout.rs @@ -28,6 +28,7 @@ mod grid; mod legend; mod losses; mod north; +mod picture; mod scale_bar; mod section; mod swatch; @@ -43,6 +44,7 @@ pub use grid::*; pub use legend::*; pub use losses::*; use north::*; +pub use picture::*; pub use scale_bar::*; pub use section::*; use swatch::*; @@ -629,8 +631,8 @@ fn draw_page( }); } } - ElementKind::Picture { image, .. } => { - if let Some(img) = crate::picture::decode(image) { + ElementKind::Picture { image, source } => match crate::picture::decoded(image) { + Some(img) => { let (iw, ih) = (img.width() as f32, img.height() as f32); let s = (ew / iw).min(eh / ih); let (dw, dh) = (iw * s, ih * s); @@ -638,15 +640,14 @@ fn draw_page( pm.draw_pixmap( 0, 0, - img.as_ref(), + img.as_ref().as_ref(), &PixmapPaint { quality: tiny_skia::FilterQuality::Bilinear, ..PixmapPaint::default() }, t, None, ); - } else { - placeholder(&mut pm, r, "Picture", ppp); } - } + None => draw_picture_box(&mut pm, r, source.as_deref(), ppp), + }, ElementKind::Table { frame: f, layer, rows, color } => { let ds = frame(*f).and_then(|fr| maps.get(fr.1)).and_then(|m| m.layer_by_name(layer)).map(|l| &l.dataset); match ds { diff --git a/crates/render/src/layout/picture.rs b/crates/render/src/layout/picture.rs new file mode 100644 index 0000000000..370896a919 --- /dev/null +++ b/crates/render/src/layout/picture.rs @@ -0,0 +1,279 @@ +//! A layout picture that draws no image: its grey box, named for its file, which pictures draw +//! one, and the notices that say so. + +use super::*; +use rustgis_map::layout::{picture_file_name, picture_source_kept}; + +/// The most pixels a side a layout picture's image may declare and still be drawn. +pub const PICTURE_MAX_DECLARED: u32 = crate::picture::MAX_DECLARED; + +/// Layout pictures named in a notice, before "and N more"; and the characters of a picture's +/// name or file name a notice shows before cutting it with "…". +const NAMED: usize = 10; +const NAME_CHARS: usize = 100; + +/// Whether a layout picture's image draws: the answer the page, its notices and the commands go +/// by. Decoded once while it is unchanged, through the cache the page draws from. +pub fn picture_draws(image: &str) -> bool { + crate::picture::decoded(image).is_some() +} + +/// What a picture's grey box says: the name of its file when it has one it keeps (never its +/// folders), else "Picture". +fn picture_label(source: Option<&str>) -> &str { + source.filter(|s| picture_source_kept(s)).and_then(picture_file_name).unwrap_or("Picture") +} + +/// `name` as it fits in `room`, measured by [`text::measure`] at `size`: whole when it fits, else +/// the longest start of it, whole characters, that fits with "…" after it, else "…" alone. +fn fitted_name(name: &str, room: f32, size: f32) -> String { + let fits = |s: &str| text::measure(s, size, false) <= room; + if fits(name) { + return name.to_string(); + } + // The byte offset each start of `n` characters ends at; found by halving over the count. + let ends: Vec = name.char_indices().map(|(i, _)| i).collect(); + let with_dots = |n: usize| format!("{}…", ends.get(n).and_then(|&end| name.get(..end)).unwrap_or(name)); + let (mut lo, mut hi) = (0, ends.len().saturating_sub(1)); + while lo < hi { + let mid = lo + (hi - lo).div_ceil(2); + if fits(&with_dots(mid)) { lo = mid } else { hi = mid - 1 } + } + with_dots(lo) +} + +/// A picture's grey box with no image to draw: "Picture" in it as [`placeholder`] draws it for a +/// picture with no file, else its file's name ([`picture_label`]) cut to the box, 2 pt in from +/// each side. +pub(super) fn draw_picture_box(pm: &mut Canvas, r: Rect, source: Option<&str>, ppp: f64) { + let label = picture_label(source); + if label == "Picture" { + placeholder(pm, r, "Picture", ppp); + } else { + // `placeholder` draws its label 10 × 1.33 × `ppp` pixels tall, which text::measure + // measures at 10 × `ppp`. + let room = r.width() - 4.0 * ppp as f32; + placeholder(pm, r, &fitted_name(label, room, 10.0 * ppp as f32), ppp); + } +} + +/// Why a layout picture is drawn as a grey box. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub enum PictureLoss { + /// Its image is empty. + NoImage, + /// Its image doesn't draw: damaged, or larger than [`PICTURE_MAX_DECLARED`] pixels a side. + Undrawable, +} + +/// A layout picture [`pictures_not_drawn`] finds drawn as a grey box. +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct PictureGap { + pub id: u32, + pub name: String, + /// The name of the file it was read from, when it keeps one; never its folders. + pub file: Option, + pub why: PictureLoss, +} + +/// The visible pictures of `layout` whose image doesn't draw ([`picture_draws`]), drawn as a grey +/// box, in the order of its elements. A hidden picture draws nothing and isn't listed. +pub fn pictures_not_drawn(layout: &Layout) -> Vec { + let gaps = layout.elements.iter().filter(|e| e.visible).filter_map(|e| { + let ElementKind::Picture { image, .. } = &e.kind else { return None }; + if picture_draws(image) { + return None; + } + let why = if image.trim().is_empty() { PictureLoss::NoImage } else { PictureLoss::Undrawable }; + let file = e.kind.picture_source().and_then(picture_file_name).map(String::from); + Some(PictureGap { id: e.id, name: e.name.clone(), file, why }) + }); + gaps.collect() +} + +/// `s` as a notice shows it: its first [`NAME_CHARS`] characters, with "…" after them when it +/// has more. +fn notice_cut(s: &str) -> String { + match s.char_indices().nth(NAME_CHARS) { + Some((end, _)) => format!("{}…", s.get(..end).unwrap_or(s)), + None => s.to_string(), + } +} + +/// What is said of `gaps`: one notice for each [`PictureLoss`] among them, in its order, with the +/// pictures counted and the first ten named, each with its file's name when it has one. +pub fn pictures_notices(gaps: &[PictureGap]) -> Vec { + [PictureLoss::NoImage, PictureLoss::Undrawable] + .into_iter() + .filter_map(|why| { + let these: Vec<&PictureGap> = gaps.iter().filter(|g| g.why == why).collect(); + if these.is_empty() { + return None; + } + let named = these.iter().take(NAMED).map(|g| match &g.file { + Some(file) => format!("{} ({}, {})", notice_cut(&g.name), g.id, notice_cut(file)), + None => format!("{} ({})", notice_cut(&g.name), g.id), + }); + let mut named = named.collect::>().join("; "); + if these.len() > NAMED { + named.push_str(&format!("; and {} more", these.len() - NAMED)); + } + let n = these.len(); + let what = match why { + PictureLoss::NoImage => "have no image".to_string(), + PictureLoss::Undrawable => { + format!("have an image that can't be drawn (damaged, or larger than {PICTURE_MAX_DECLARED} pixels a side)") + } + }; + Some(format!( + "{n} layout picture(s) {what} and are drawn as a grey box: {named}; read one from its file again with \ + layout.update and \"path\" (Choose File… in the Format pane)" + )) + }) + .collect() +} + +#[cfg(all(test, not(target_arch = "wasm32")))] +mod tests { + use super::*; + + /// A 100 x 80 mm page with one picture, of `image` and from file `source`, in (10, 10, 60, 20). + fn one_picture_page(image: &str, source: Option<&str>) -> Layout { + let mut l = Layout::new("Pictures", 100.0, 80.0); + l.add("Picture", (10.0, 10.0, 60.0, 20.0), ElementKind::Picture { image: image.to_string(), source: source.map(String::from) }); + l + } + + /// A picture without an image draws its grey box with its file's name in it; without a file, + /// the word Picture, as before. + #[test] + fn a_picture_without_an_image_is_labelled_with_its_file_name() { + assert_eq!(picture_label(None), "Picture"); + assert_eq!(picture_label(Some("")), "Picture"); + assert_eq!(picture_label(Some("/data/logos/north.png")), "north.png"); + assert_eq!(picture_label(Some(r"\\server\share\logo.jpg")), "logo.jpg"); + assert_eq!(picture_label(Some("https://example.invalid/north.png")), "Picture"); + // Drawn: a named box differs from the plain one, and from one named otherwise. + let page = |source: Option<&str>| one_picture_page("", source); + let draw = |l: Layout| render(&l, &mut Vec::new(), 96.0, &PageInfo::default()).unwrap(); + let (plain, north, south) = + (draw(page(None)), draw(page(Some("/data/logos/north.png"))), draw(page(Some("/data/logos/south.png")))); + assert_ne!(plain.data(), north.data()); + assert_ne!(north.data(), south.data()); + // A source the rule doesn't keep draws as none. + assert_eq!(draw(page(Some("https://example.invalid/north.png"))).data(), plain.data()); + } + + /// Only the file's name reaches the page, the SVG and the PDF: two folders, the same drawing. + #[test] + fn the_grey_box_names_the_file_not_its_folders() { + let (a, b) = (one_picture_page("", Some("/home/someone/logos/north.png")), one_picture_page("", Some(r"\\server\share\north.png"))); + let info = PageInfo::default(); + assert_eq!(render(&a, &mut Vec::new(), 96.0, &info).unwrap().data(), render(&b, &mut Vec::new(), 96.0, &info).unwrap().data()); + let svg = |l: &Layout| crate::svg::layout_svg(l, &mut Vec::new(), 72.0, &info).unwrap().0; + let (sa, sb) = (svg(&a), svg(&b)); + assert_eq!(sa, sb); + assert!(!sa.contains("someone") && !sa.contains("server")); + let pdf = |l: &Layout| { + let (drawing, _) = render_drawing(l, &mut Vec::new(), 150.0, &info).unwrap(); + crate::pdf::write(&[crate::pdf::Page::drawing(drawing, l.width, l.height)], "P") + }; + assert_eq!(pdf(&a), pdf(&b)); + } + + /// A name too long for its box is cut to the box with "…"; one that fits is kept whole. + #[test] + fn a_long_file_name_is_cut_to_its_box() { + let px = 13.3; + let name = "a-very-long-picture-file-name-from-the-survey-office.png"; + let whole = crate::text::measure(name, px, false); + assert_eq!(fitted_name(name, whole + 1.0, px), name); + let cut = fitted_name(name, whole / 2.0, px); + assert!(cut.ends_with('…') && name.starts_with(cut.trim_end_matches('…')), "{cut}"); + assert!(crate::text::measure(&cut, px, false) <= whole / 2.0, "{cut}"); + assert_eq!(fitted_name(name, 0.0, px), "…"); + assert_eq!(fitted_name(&"ü".repeat(300), 40.0, px).chars().last(), Some('…')); + } + + /// The visible pictures drawn as a grey box, each with why and only its file's name; a + /// picture that draws, or a hidden one, isn't listed. + #[test] + fn pictures_not_drawn_lists_each_picture_drawn_as_a_grey_box() { + let huge = png_b64(30_000, 1, |_, _| [0x1F, 0x5C, 0x84]); + let mut l = Layout::new("Pictures", 100.0, 80.0); + let pictures: [(&str, Option<&str>); 6] = [ + (PIN_PNG, None), + ("", Some("/data/logos/north.png")), + ("", None), + ("bm90IGFuIGltYWdl", None), + (&huge, None), + ("", Some("/data/logos/south.png")), + ]; + for (image, source) in pictures { + let kind = ElementKind::Picture { image: image.to_string(), source: source.map(String::from) }; + l.add("Picture", (10.0, 10.0, 40.0, 20.0), kind); + } + if let Some(e) = l.elements.last_mut() { + e.visible = false; + } + assert_eq!(l.elements.iter().map(|e| e.id).collect::>(), [1, 2, 3, 4, 5, 6]); + let gaps = pictures_not_drawn(&l); + let listed: Vec<(u32, PictureLoss, Option)> = gaps.iter().map(|g| (g.id, g.why, g.file.clone())).collect(); + assert_eq!( + listed, + [ + (2, PictureLoss::NoImage, Some("north.png".to_string())), + (3, PictureLoss::NoImage, None), + (4, PictureLoss::Undrawable, None), + (5, PictureLoss::Undrawable, None), + ] + ); + assert!(gaps.iter().all(|g| g.name == "Picture")); + } + + /// One notice per kind, counted, the first ten named with their file's name, never a folder. + #[test] + fn the_picture_notices_count_and_name_each_kind() { + let mut gaps: Vec = (1..=12) + .map(|id| PictureGap { id, name: format!("Logo {id}"), file: Some("north.png".to_string()), why: PictureLoss::NoImage }) + .collect(); + gaps.push(PictureGap { id: 13, name: "Inset".to_string(), file: None, why: PictureLoss::Undrawable }); + let said = pictures_notices(&gaps); + assert_eq!(said.len(), 2, "{said:?}"); + let head = "12 layout picture(s) have no image and are drawn as a grey box: Logo 1 (1, north.png); "; + assert!(said[0].starts_with(head), "{}", said[0]); + assert!(said[0].contains("Logo 10 (10, north.png); and 2 more; read one"), "{}", said[0]); + assert!(!said[0].contains("Logo 11"), "{}", said[0]); + assert!(said[0].contains("; and 2 more; read one from its file again with layout.update and \"path\""), "{}", said[0]); + let undrawable = "1 layout picture(s) have an image that can't be drawn (damaged, or larger than 20000 pixels a side)"; + assert!(said[1].starts_with(undrawable), "{}", said[1]); + assert!(said[1].contains("drawn as a grey box: Inset (13); read one"), "{}", said[1]); + assert!(pictures_notices(&[]).is_empty()); + } + + /// A picture is decoded once while it is unchanged, however often its page is drawn and + /// checked. + #[test] + fn a_layout_picture_is_decoded_once_while_it_is_unchanged() { + // Colours no other test draws, so no other picture is this one. + let first = png_b64(23, 17, |x, y| [0x3A, (x * 7) as u8, (y * 11) as u8]); + let mut l = one_picture_page(&first, None); + let info = PageInfo::default(); + let before = crate::picture::decodes(); + for _ in 0..3 { + render(&l, &mut Vec::new(), 96.0, &info).unwrap(); + } + assert!(pictures_not_drawn(&l).is_empty()); + assert!(pictures_not_drawn(&l).is_empty()); + assert!(picture_draws(&first)); + assert_eq!(crate::picture::decodes() - before, 1); + // The image changed to another PNG: one more. + let second = png_b64(23, 17, |x, y| [0x3B, (y * 5) as u8, (x * 9) as u8]); + if let Some(e) = l.elements.first_mut() { + e.kind = ElementKind::Picture { image: second, source: None }; + } + render(&l, &mut Vec::new(), 96.0, &info).unwrap(); + assert!(pictures_not_drawn(&l).is_empty()); + assert_eq!(crate::picture::decodes() - before, 2); + } +} diff --git a/crates/render/src/picture.rs b/crates/render/src/picture.rs index 6bf4648622..446f3c450a 100644 --- a/crates/render/src/picture.rs +++ b/crates/render/src/picture.rs @@ -19,10 +19,11 @@ use tiny_skia::{FilterQuality, Pixmap, PixmapPaint, Transform}; /// Pictures are drawn from at most this many pixels per side (bigger ones are scaled down). const MAX_SIDE: u32 = 4096; /// Pictures declaring more pixels per side than this aren't decoded at all. -const MAX_DECLARED: u32 = 20_000; +pub(crate) const MAX_DECLARED: u32 = 20_000; /// Most memory a picture's decoder may allocate. const MAX_ALLOC: u64 = 512 << 20; -/// Decoded pictures kept between frames, and the most pixel memory they may hold together. +/// Decoded pictures kept between frames, and the most memory they may hold together (their pixels +/// and the base64 each keeps). const CACHE: usize = 32; const CACHE_BYTES: usize = 256 << 20; /// Picture markers are drawn from at most this many pixels per side: an 80 pt marker printed at @@ -160,6 +161,9 @@ struct Cache { thread_local! { static DECODED: RefCell = RefCell::new(Cache::default()); + /// The pictures [`decoded`] has decoded on this thread ([`decodes`]). + #[cfg(test)] + static DECODES: std::cell::Cell = const { std::cell::Cell::new(0) }; /// The picture markers this thread has met, each with its image in the [`Store`] or why it is /// drawn as a circle, so a frame finds it with no lock. Never emptied: only pictures a run keeps /// ([`rustgis_map::symbology::MAX_PICTURES`]) are met, and each entry shares the store's image. @@ -483,25 +487,47 @@ pub fn draw(pm: &mut Canvas, ds: &Dataset, row: usize, (x0, y0, x1, y1): (f32, f if !(w.is_finite() && h.is_finite()) || w < 1.0 || h < 1.0 || w > 1e5 || h > 1e5 { return; } + let Some(img) = decoded(b64) else { return }; + let t = Transform::from_row(w / img.width() as f32, 0.0, 0.0, h / img.height() as f32, x0.min(x1), y0.min(y1)); + let paint = PixmapPaint { opacity, quality: FilterQuality::Bilinear, ..PixmapPaint::default() }; + pm.draw_shared(&img, None, &paint, t); +} + +/// Base64 PNG or JPEG bytes decoded ([`decode`]), from this thread's cache of decoded pictures: +/// decoded on the first look, and again only after the cache let it go. The cache keeps each +/// picture's base64 with its pixels, or with none for one that doesn't decode (so that one isn't +/// tried again either), at most [`CACHE`] of them and, oldest let go first, at most about +/// [`CACHE_BYTES`] held ([`held`]: the base64 kept counts with the pixels). Graphics pictures +/// and layout pictures share it. +pub(crate) fn decoded(b64: &str) -> Option> { let key = key(b64); DECODED.with(|cache| { let mut cache = cache.borrow_mut(); - if cache.images.get(&key).is_none_or(|(src, _)| src.as_str() != b64.as_str()) { + if cache.images.get(&key).is_none_or(|(src, _)| src.as_str() != b64) { // Evict the oldest pictures (not all of them) to stay within the count and memory budget. - let held = |c: &Cache| c.images.values().filter_map(|(_, p)| p.as_ref()).map(|p| p.data().len()).sum::(); while cache.images.len() >= CACHE || (!cache.images.is_empty() && held(&cache) > CACHE_BYTES) { let Some(old) = cache.order.pop_front() else { break }; cache.images.remove(&old); } - if cache.images.insert(key, (b64.clone(), decode(b64).map(Arc::new))).is_none() { + #[cfg(test)] + DECODES.with(|n| n.set(n.get() + 1)); + if cache.images.insert(key, (b64.to_string(), decode(b64).map(Arc::new))).is_none() { cache.order.push_back(key); } } - let Some((_, Some(img))) = cache.images.get(&key) else { return }; - let t = Transform::from_row(w / img.width() as f32, 0.0, 0.0, h / img.height() as f32, x0.min(x1), y0.min(y1)); - let paint = PixmapPaint { opacity, quality: FilterQuality::Bilinear, ..PixmapPaint::default() }; - pm.draw_shared(img, None, &paint, t); - }); + cache.images.get(&key).and_then(|(_, img)| img.clone()) + }) +} + +/// The bytes `cache` holds: each picture's pixels and the base64 it keeps. +fn held(cache: &Cache) -> usize { + cache.images.values().map(|(b64, img)| b64.len() + img.as_ref().map_or(0, |p| p.data().len())).sum() +} + +/// How many pictures [`decoded`] has decoded on this thread. +#[cfg(test)] +pub(crate) fn decodes() -> usize { + DECODES.with(std::cell::Cell::get) } /// Runs `f` on picture marker `p`'s decoded image, its height for its width and, with `pack`, the From bc9ac746fdc8100cb84e586da03ce3e961d0db4a Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:05:32 -0600 Subject: [PATCH 05/38] feat(layout): a picture remembers its file through layout.addElement and is read again with layout.update One reader for both commands: a missing, unreadable, too large, undrawable or not-a-picture file, an address, or a path of the wrong kind is refused before anything changes. layout.update takes path and image on a picture and refuses them elsewhere. Capability layout-picture-source. Co-Authored-By: Claude Fable 5.2 --- crates/engine/command-surface.txt | 2 +- crates/engine/src/cmd/graphics.rs | 24 +- crates/engine/src/cmd/layout.rs | 7 +- crates/engine/src/cmd/layout/elements.rs | 21 +- crates/engine/src/cmd/layout/picture.rs | 87 +++++++ crates/engine/src/cmd/layout/update.rs | 20 ++ crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 96 +++++++ crates/engine/src/tests/layout_files.rs | 25 ++ crates/engine/src/tests/layout_pictures.rs | 284 +++++++++++++++++++-- docs/maintaining.md | 10 + schema/fixtures/layout_picture_source.rgis | 32 +++ schema/project.schema.json | 2 + 13 files changed, 572 insertions(+), 39 deletions(-) create mode 100644 crates/engine/src/cmd/layout/picture.rs create mode 100644 schema/fixtures/layout_picture_source.rgis diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index 79cb794fea..32881a42b6 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -304,7 +304,7 @@ layout.save layout? path layout.series layout? layer nameField? frame? margin? off? layout.seriesPage layout? page layout.seriesRefresh layout? -layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? labels? columns? textSize? showLayerNames? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? barOutline? hideLabels? rows? background? +layout.update layout? element x? y? w? h? name? visible? locked? text? size? color? bold? italic? align? letterSpacing? rotation? wrap? valign? lineSpacing? case? font? fallback? title? allClasses? hideOther? showNoData? exclude? labels? columns? textSize? showLayerNames? orientation? ticks? tickSide? reverse? style? fill? outline? radius? width? dash? dir? head? angle? length? units? divisions? subdivisions? divisionsBeforeZero? labelPosition? unitLabel? unitLabelPosition? fit? map? scale? center? bearing? pitch? grid? extentIndicator? border? section? layer? field? label? group? statistic? order? bars? other? stack? values? decimals? barColor? classes? labelAlign? mirror? max? barOutline? hideLabels? rows? image? path? background? locator.find locator? text limit? zoom? map.activate name map.addTiles url kind? name? bounds? attribution? minZoom? maxZoom? tileSize? singleImage? tms? subdomains? layers? styleLayers? opacity? blend? resampling? overlay? top? replace? id? view? start? end? unit? interval? dates? legend? connection? diff --git a/crates/engine/src/cmd/graphics.rs b/crates/engine/src/cmd/graphics.rs index 7259f51bca..802922a339 100644 --- a/crates/engine/src/cmd/graphics.rs +++ b/crates/engine/src/cmd/graphics.rs @@ -401,13 +401,23 @@ fn color(p: &Value, k: &str) -> Result, String> { /// The picture's bytes as base64, from `image` or a file `path`. pub(crate) fn picture(p: &Value) -> Result { - let b64 = match (ps(p, "image"), ps(p, "path")) { - (Some(b), _) => b.trim().to_string(), - (None, Some(path)) => { - base64::engine::general_purpose::STANDARD.encode(read_picture_file(path, MAX_PICTURE).map_err(PictureFileError::message)?) - } - (None, None) => return Err("a picture needs an image or a path".into()), - }; + match (ps(p, "image"), ps(p, "path")) { + (Some(b), _) => checked_picture(b.trim().to_string()), + (None, Some(path)) => picture_file(path), + (None, None) => Err("a picture needs an image or a path".into()), + } +} + +/// The bytes of the picture file at `path` as base64: read by [`read_picture_file`], at most +/// 16 MiB, and a PNG or JPEG. +pub(crate) fn picture_file(path: &str) -> Result { + checked_picture( + base64::engine::general_purpose::STANDARD.encode(read_picture_file(path, MAX_PICTURE).map_err(PictureFileError::message)?), + ) +} + +/// `b64` when it is at most 16 MiB of a PNG or JPEG image. +fn checked_picture(b64: String) -> Result { if b64.len() > MAX_PICTURE / 3 * 4 + 4 { return Err("the picture is too large".into()); } diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index f0f3186ee0..7f97c41af4 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -41,6 +41,9 @@ mod legend; pub(in crate::cmd) use legend::say_unfitted_legends_in; use legend::*; pub(crate) use legend::{legend_columns_param, legend_fit_param, legend_names_param}; +mod picture; +pub(crate) use picture::gives_picture; +use picture::*; mod page; use page::*; mod publication; @@ -219,7 +222,7 @@ pub fn commands() -> Vec { r##""angle"?: degrees anticlockwise from pointing right, centred on the page unless x or y is given (line, arrow; it sets the box and the direction, so w, h and dir are not used with it), "##, r##""length"?: mm (line, arrow), "##, r##""image"?: base64, "##, - r##""path"?: picture file, "##, + r##""path"?: picture file (picture: read, and remembered as its file, so a picture whose image goes missing names it and layout.update can read it again; an address is refused, and image and path together; refused for other kinds), "##, r##""layer"?: (table, chart; colorbar: a raster layer, default the top visible raster with a colour scale, not drawn by classes, which a legend lists), "##, r##""field"?: (chart: a numeric field, default the layer's first; any field when it groups and counts, default then the field it groups by), "##, r##""label"?: a field (chart: each bar's label when not grouped), "##, @@ -356,6 +359,8 @@ pub fn commands() -> Vec { r##""barOutline"?: {"color"?, "width"?: points, 0 to 5, a wider one held to 5, the keys not given keeping the outline's}|null (null or a width of 0 for none), "##, r##""hideLabels"?: bool (chart, as in layout.addElement: null leaves each other one as it is; refused for other elements unless null), "##, r##""rows"?, "##, + r##""image"?: base64 (picture: its new image, its file no longer remembered), "##, + r##""path"?: a PNG or JPEG file (picture: read again, its image replacing the one it has, and remembered as its file; a file missing, over 16 MB, not a PNG or JPEG, or one that can't be drawn is refused and the picture left as it was; image and path together are refused; null leaves each as it is; refused for other elements), "##, r##""background"?: {"fill"?, "outline"?, "width"?, "radius"?, "padding"?, as in layout.addElement, the keys not given keeping theirs} | null (removes it); a map frame takes none}"##, ), diff --git a/crates/engine/src/cmd/layout/elements.rs b/crates/engine/src/cmd/layout/elements.rs index a59f68334b..51d69c7a1a 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -236,6 +236,7 @@ pub(crate) fn color(p: &Value, k: &str, d: Rgba) -> Result { } pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResult { + const NO_PICTURE: &str = "a picture needs an image or a path"; let kind = ps(p, "kind").ok_or("kind is required")?; if kind != "legend" && kind != "scaleBar" && p.get("textSize").is_some_and(|v| !v.is_null()) { return Err(ONLY_LAYOUT_TEXT_SIZE.into()); @@ -336,8 +337,14 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu BackgroundParam::Set(b) => Some(b), BackgroundParam::Absent | BackgroundParam::Remove => None, }; + // Refused before any file is read. + if kind != "picture" && gives_picture(p) { + return Err(ONLY_PICTURE_FILE.into()); + } let i = index(s, p)?; - let image = if kind == "picture" { Some(crate::cmd::graphics::picture(p)?) } else { None }; + // A picture's image, read and checked to draw before anything is added. + let picture = if kind == "picture" { Some(picture_given(p)?.ok_or(NO_PICTURE)?) } else { None }; + let unremembered = picture.as_ref().is_some_and(|g| g.unremembered); let l = s.project.layouts.get(i).ok_or("no layout")?; let (pw, ph) = (l.width, l.height); let (name, rect, k) = match kind { @@ -441,11 +448,10 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu }; (if kind == "text" { "Text" } else { "Dynamic Text" }, place(p, l, (15.0, 12.0, 120.0, (size * 0.5).max(8.0)))?, k) } - "picture" => ( - "Picture", - place(p, l, (pw - 60.0, ph - 50.0, 45.0, 35.0))?, - ElementKind::Picture { image: image.unwrap_or_default(), source: None }, - ), + "picture" => { + let GivenPicture { image, source, .. } = picture.ok_or(NO_PICTURE)?; + ("Picture", place(p, l, (pw - 60.0, ph - 50.0, 45.0, 35.0))?, ElementKind::Picture { image, source }) + } "table" => { let frame = frame_of(l, p)?; let layer = frame_layer_name(s, l, frame, p)?; @@ -668,6 +674,9 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu if let Some(said) = empty_colorbar { s.warn(said); } + if unremembered { + s.notify(picture_unremembered(), false); + } say_held(s, "Add Element", held_to_limits(p, Shape::of_name(kind))); say_name_ignored(s, p, kind); let mut out = json!({"element": id}); diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs new file mode 100644 index 0000000000..dd96bc0ef6 --- /dev/null +++ b/crates/engine/src/cmd/layout/picture.rs @@ -0,0 +1,87 @@ +//! A layout picture's image and the file it is read from: the one reader both commands use, and +//! what they refuse. + +use super::*; + +/// `image` or `path` given to an element that isn't a picture. +pub(in crate::cmd::layout) const ONLY_PICTURE_FILE: &str = "only pictures take an image or a path"; +/// A `path` that isn't text, or is blank. +pub(in crate::cmd::layout) const PICTURE_PATH: &str = "path is the path of a PNG or JPEG file"; +/// An `image` that isn't text. +pub(in crate::cmd::layout) const PICTURE_IMAGE: &str = "image is a PNG or JPEG image in base64"; +/// A `path` that is an address, which is never tried as a file nor fetched, and never repeated +/// (it could carry a login). +pub(in crate::cmd::layout) const PICTURE_ADDRESS: &str = "a picture is read from a file on this computer, not a web address"; +/// Both `image` and `path` given. +pub(in crate::cmd::layout) const PICTURE_BOTH: &str = "give a picture an image or a path, not both"; + +/// A picture whose header reads but whose image can't be drawn. +pub(in crate::cmd::layout) fn picture_undrawn() -> String { + format!( + "the picture can't be drawn: its image is damaged or larger than {} pixels a side", + rustgis_render::layout::PICTURE_MAX_DECLARED + ) +} + +/// A picture read from a file whose path isn't kept as its file. +pub(in crate::cmd::layout) fn picture_unremembered() -> String { + format!( + "the picture is read, but its file isn't remembered: a path with control characters or over {} bytes isn't kept", + rustgis_map::layout::MAX_PICTURE_SOURCE + ) +} + +/// A picture's image as a command gives it, and the file it was read from. +pub(crate) struct GivenPicture { + /// The image, base64, checked to draw. + pub image: String, + /// The path it was read from, when [`rustgis_map::layout::picture_source_kept`] keeps it. + pub source: Option, + /// Read from a file whose path isn't kept: said once by the command. + pub unremembered: bool, +} + +/// A command's `path`: none when absent or null, as given when it is text that isn't blank and +/// isn't an address; refused otherwise. +pub(crate) fn picture_path_param(p: &Value) -> Result, String> { + match p.get("path") { + None | Some(Value::Null) => Ok(None), + Some(Value::String(path)) if path.trim().is_empty() => Err(PICTURE_PATH.into()), + Some(Value::String(path)) if path.contains("://") => Err(PICTURE_ADDRESS.into()), + Some(Value::String(path)) => Ok(Some(path)), + Some(_) => Err(PICTURE_PATH.into()), + } +} + +/// Whether a command gives a picture an `image` or a `path` (present and not null). +pub(crate) fn gives_picture(p: &Value) -> bool { + ["image", "path"].iter().any(|k| p.get(*k).is_some_and(|v| !v.is_null())) +} + +/// The picture a command's `image` or `path` gives, none when it gives neither; refused when both +/// are given, either is of the wrong kind, the file can't be read or isn't a PNG or JPEG of at most +/// 16 MiB, or the image can't be drawn. Reads the file on the command's thread, as +/// `layout.addElement` always has: at most 16 MiB, then decoded once to check that it draws (the +/// decoded copy is kept for the page). +pub(in crate::cmd::layout) fn picture_given(p: &Value) -> Result, String> { + let given = |k: &str| p.get(k).filter(|v| !v.is_null()); + if given("image").is_some() && given("path").is_some() { + return Err(PICTURE_BOTH.into()); + } + let picture = match (given("image"), picture_path_param(p)?) { + (Some(Value::String(image)), _) => { + GivenPicture { image: crate::cmd::graphics::picture(&json!({"image": image}))?, source: None, unremembered: false } + } + (Some(_), _) => return Err(PICTURE_IMAGE.into()), + (None, Some(path)) => { + let image = crate::cmd::graphics::picture_file(path)?; + let kept = rustgis_map::layout::picture_source_kept(path); + GivenPicture { image, source: kept.then(|| path.to_string()), unremembered: !kept } + } + (None, None) => return Ok(None), + }; + if !rustgis_render::layout::picture_draws(&picture.image) { + return Err(picture_undrawn()); + } + Ok(Some(picture)) +} diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 918ef9e35b..f021374ed9 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -459,6 +459,18 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { if new_columns.is_some() && !is_legend { return Err(ONLY_LEGEND_COLUMNS.into()); } + // A picture's new image, or its file read again, before anything changes; refused before any + // file is read on another element. + let new_picture = match kind_now { + Some(ElementKind::Picture { .. }) => picture_given(p)?, + _ if gives_picture(p) => return Err(ONLY_PICTURE_FILE.into()), + _ => None, + }; + let unremembered = new_picture.as_ref().is_some_and(|g| g.unremembered); + // Nothing given that changes anything (every key null, or none): no step to undo. + if !changes && p.get("locked").is_none_or(Value::is_null) { + s.request_only = true; + } let l = active(s, p)?; let e = l.element_mut(id).ok_or_else(|| format!("no element {id}"))?; // A text or scale bar with no ink isn't measured: given a colour that shows it, it is told @@ -715,6 +727,11 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { *field = f; } } + ElementKind::Picture { image, source } => { + if let Some(g) = new_picture { + (*image, *source) = (g.image, g.source); + } + } _ => {} } // Told what it leaves out, or whether it lists every class, it says again which rasters it @@ -722,6 +739,9 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { let excluding = matches!(&e.kind, ElementKind::Legend { .. }) && (p.get("exclude").is_some_and(|v| !v.is_null()) || b(p, "allClasses").is_some()); let fit = tells_legend_fit(&e.kind, p); + if unremembered { + s.notify(picture_unremembered(), false); + } if fit { say_legend_fit(s, li, id); } diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 21cfbf715f..f5d54c46d5 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -116,6 +116,7 @@ pub const CAPABILITIES: &[&str] = &[ NATIVE_COORDINATES, "layout-text-size", "layout-legend-fit", + "layout-picture-source", "layout-scale-bar-details", "label-guide", "label-weight", diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 52e0b26cd8..4dd4a1208e 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -177,6 +177,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-section", command_uses_section), ("layout-text-size", command_uses_text_size), ("layout-legend-fit", command_uses_legend_fit), + ("layout-picture-source", command_uses_picture_source), ("layout-scale-bar-details", command_uses_scale_bar_details), ("dggs-system", command_uses_dggs_system), ("label-weight", command_weighs_labels), @@ -420,6 +421,31 @@ fn command_uses_legend_fit(id: &str, params: &Value) -> bool { } } +/// Whether a layout element is a picture that keeps the file it was read from: an older reader +/// would draw it without its file, the word Picture where it has no image, and save it again +/// without the file. +fn pictures_with_files(e: &rustgis_map::layout::Element) -> bool { + e.kind.picture_source().is_some() +} + +/// A layout command that gives a picture an image or a path, or brings in one that keeps its file: +/// a saved `layout.update` with `image` or `path` given and not null, which an older reader +/// ignores, leaving the picture as it was (judged by presence alone, +/// [`crate::cmd::layout::gives_picture`]: a value the command refuses changes nothing, so it only +/// asks for the capability sooner, never misses it); a `layout.import` or `report.existingTemplate` +/// whose layout has a picture with a file the kept rule keeps, so a junk one needs nothing; and a +/// script with such a line. A `layout.addElement` with a `path` needs nothing: an older reader adds +/// the same picture, only without remembering its file. +fn command_uses_picture_source(id: &str, params: &Value) -> bool { + match id { + "layout.update" => crate::cmd::layout::gives_picture(params), + // A layout file, read as `layout.import` reads it, which `report.existingTemplate` also does. + "layout.import" | "report.existingTemplate" => imported_layout_uses(params, &["\"source\""], pictures_with_files), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_picture_source)), + _ => false, + } +} + /// A layout command that changes a map frame's border (#2557): an older reader warns that it /// ignores `border` and draws the default one. `null` only gives the default back, which an older /// reader's frames always have. @@ -1141,6 +1167,7 @@ fn layout_capabilities(layouts: &[rustgis_map::layout::Layout]) -> Vec<&'static (elements().any(|e| e.kind.has_sections()), "layout-section"), (elements().any(|e| e.kind.has_custom_text_size()), "layout-text-size"), (elements().any(legends_fitting), "layout-legend-fit"), + (elements().any(pictures_with_files), "layout-picture-source"), (elements().any(bar_details), "layout-scale-bar-details"), (layouts.iter().any(|l| l.paper.is_some()), "layout-page-color"), (elements().any(text_statistics), "layout-text-statistics"), @@ -1438,6 +1465,7 @@ mod tests { (&["layout-section"], "layout.update", json!({"element": 1, "section": {"name": "A", "y": 0}})), (&["layout-text-size"], "layout.update", json!({"element": 1, "textSize": 12})), (&["layout-legend-fit"], "layout.update", json!({"element": 1, "fit": "adjustSize"})), + (&["layout-picture-source"], "layout.update", json!({"element": 1, "path": "logo.png"})), (&["dggs-system"], "a5Grid", json!({"system": "H3"})), (&["dggs-system"], "a5Aggregate", json!({"system": "S2"})), (&["label-weight"], "labels.placement", json!({"weight": 9})), @@ -2169,6 +2197,74 @@ mod tests { } } + /// A picture that keeps its file requires the capability in a project and a layout file; a saved + /// `layout.update` giving a picture an image or a path does, an `addElement` doesn't, and a + /// `layout.import`, `report.existingTemplate` or script line does when its layout keeps one. + #[test] + fn picture_source_capability_follows_saved_layouts_and_commands() { + use rustgis_map::layout::ElementKind; + let fixture = Project::from_json(include_str!("../../../schema/fixtures/layout_picture_source.rgis")).unwrap(); + let saved = serde_json::to_value(&fixture).unwrap(); + assert_eq!(saved["requires"], json!(["layout-picture-source"])); + let reread = Project::from_json(&saved.to_string()).unwrap(); + let sources: Vec> = reread.layouts.iter().map(|l| l.elements[0].kind.picture_source()).collect(); + assert_eq!(sources, [Some("/data/logos/north.png"), Some("/data/logos/inset.png")]); + assert_eq!(layout_file_bytes(&fixture.layouts[1]).map(|b| String::from_utf8_lossy(&b).contains("layout-picture-source")), Ok(true)); + // Each picture's file on its own is required. + for one in 0..2 { + let mut alone = fixture.clone(); + alone.layouts.remove(1 - one); + assert_eq!(serde_json::to_value(&alone).unwrap()["requires"], json!(["layout-picture-source"]), "{one}"); + } + let mut clean = fixture; + for l in &mut clean.layouts { + if let ElementKind::Picture { source, .. } = &mut l.elements[0].kind { + *source = None; + } + } + let base = serde_json::to_value(&clean).unwrap(); + assert!(base.get("requires").is_none(), "pictures without a file need nothing: {base}"); + let layout_text = saved["layouts"][0].to_string(); + let mut junk = saved["layouts"][0].clone(); + junk["elements"][0]["kind"]["Picture"]["source"] = json!("https://user:secret@example.invalid/a.png"); + let script = "layout.update {\"element\": 1, \"path\": \"a.png\"}"; + for (id, params, required) in [ + ("layout.update", json!({"element": 1, "path": "/data/logos/north.png"}), true), + ("layout.update", json!({"element": 1, "image": "iVBORw0KGgo="}), true), + // Refused by the command, which changes nothing: an over-count, never a missing one. + ("layout.update", json!({"element": 1, "path": 5}), true), + ("layout.update", json!({"element": 1, "path": null, "image": null}), false), + ("layout.update", json!({"element": 1, "x": 5}), false), + ("layout.addElement", json!({"kind": "picture", "path": "/data/logos/north.png"}), false), + ("layout.addElement", json!({"kind": "picture", "image": "iVBORw0KGgo="}), false), + ("layout.import", json!({"text": layout_text}), true), + ("layout.import", json!({"text": junk.to_string()}), false), + ("layout.import", json!({"text": base["layouts"][0].to_string()}), false), + ("layout.import", json!({"path": "pictures.rgislayout"}), false), + ("report.existingTemplate", json!({"report": "R", "text": layout_text}), true), + ("report.existingTemplate", json!({"report": "R", "text": junk.to_string()}), false), + ("script.run", json!({"script": script}), true), + ("script.run", json!({"script": "layout.update {\"element\": 1, \"x\": 5}"}), false), + ] { + let mut steps = vec![json!([{"name": "Task", "steps": [{"title": "Picture", "command": id, "params": params}]}])]; + // A script holds no script.run line. + if id != "script.run" { + let line = format!("{id} {params}"); + steps.push( + json!([{"name": "Script", "steps": [{"title": "Picture", "command": "script.run", "params": {"script": line}}]}]), + ); + } + for value in steps { + let mut document = base.clone(); + document["tasks"] = value; + let saved = serde_json::to_value(Project::from_json(&document.to_string()).unwrap()).unwrap(); + let requires = saved.get("requires").and_then(Value::as_array).cloned().unwrap_or_default(); + let expected: Vec = if required { vec![json!("layout-picture-source")] } else { vec![] }; + assert_eq!(requires, expected, "{id} {params}"); + } + } + } + /// A text with a block setting is required where it is saved, so an older reader refuses the /// project instead of drawing it at the top, at the usual spacing, as typed, and saving it again /// without them; so is a saved command that sets one. The defaults, null and values read as diff --git a/crates/engine/src/tests/layout_files.rs b/crates/engine/src/tests/layout_files.rs index 90dea2eb91..2df1df28af 100644 --- a/crates/engine/src/tests/layout_files.rs +++ b/crates/engine/src/tests/layout_files.rs @@ -205,6 +205,31 @@ fn a_layout_file_with_a_fitted_legend_says_so_in_its_header() { assert!(s.project.layouts[1].elements.iter().any(|e| e.kind.legend_uses_fit())); } +/// A layout file with a picture that remembers its file requires `layout-picture-source`, so an +/// older RustGIS refuses it instead of saving the picture again without its file; one whose +/// pictures have no file requires nothing. +#[test] +fn a_layout_file_with_a_remembered_picture_says_so_in_its_header() { + let (mut s, _) = with_layout(); + let image = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg=="; + s.run("layout.addElement", &json!({"kind": "picture", "image": image})).unwrap(); + let (_, plain) = saved_file(&mut s, 0, "plain-picture"); + assert_eq!(plain["format"], json!(crate::project::FORMAT)); + assert!(plain.get("requires").is_none(), "{plain}"); + // A picture an older file holds with no image, only its file, and one with both. + let remembered = json!({"name": "Logos", "width": 200, "height": 100, "elements": [ + {"id": 1, "name": "North", "x": 5, "y": 5, "w": 40, "h": 20, "kind": {"Picture": {"image": "", "source": "/data/logos/north.png"}}}, + {"id": 2, "name": "Inset", "x": 50, "y": 5, "w": 20, "h": 20, "kind": {"Picture": {"image": image, "source": "/data/logos/inset.png"}}} + ]}); + s.run("layout.import", &json!({"text": remembered.to_string()})).unwrap(); + let (text, kept) = saved_file(&mut s, 1, "remembered-picture"); + assert_eq!(kept["requires"], json!(["layout-picture-source"])); + // This RustGIS reads it back. + s.run("layout.import", &json!({"text": text})).unwrap(); + let sources: Vec> = s.project.layouts[2].elements.iter().map(|e| e.kind.picture_source()).collect(); + assert_eq!(sources, [Some("/data/logos/north.png"), Some("/data/logos/inset.png")]); +} + /// A layout file with a text placed down its box, spaced or cased requires `layout-text-block`, so /// an older RustGIS refuses it instead of drawing the text at the top, at the usual spacing and as /// typed; a plain text's file requires nothing. diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index d8477e70f8..18245abad7 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -229,7 +229,9 @@ fn pictures_save_and_say_as_before() { Err(e) => text.replace(&e.to_string(), ""), Ok(_) => text, }; - let images = [(PIN_PNG, "the PNG"), (huge.as_str(), "the 30000 x 1 PNG"), (damaged.as_str(), "the damaged PNG")]; + let images = + [(PIN_PNG, "the PNG"), (PIN_JPEG, "the JPEG"), (huge.as_str(), "the 30000 x 1 PNG"), (damaged.as_str(), "the damaged PNG")]; + const UNDRAWN: &str = "the picture can't be drawn: its image is damaged or larger than 20000 pixels a side"; let rectangle = |key: &str, v: Value| { let mut p = json!({"kind": "rectangle", "x": 10, "y": 10, "w": 20, "h": 20}); p[key] = v; @@ -245,27 +247,30 @@ fn pictures_save_and_say_as_before() { ("an image that isn't one", picture("image", json!("bm90IGFuIGltYWdl")), "the picture isn't a PNG or JPEG image"), ("an empty image", picture("image", json!("")), "the picture isn't a PNG or JPEG image"), ("an image over 16 MiB", picture("image", json!("A".repeat((16 << 20) / 3 * 4 + 8))), "the picture is too large"), - // An image that isn't text is read as no image. - ("an image that is a number", picture("image", json!(5)), "a picture needs an image or a path"), + ("an image that is a number", picture("image", json!(5)), "image is a PNG or JPEG image in base64"), ("a path to a missing file", picture("path", json!(at("missing.png"))), "/missing.png: "), - ("an empty path", picture("path", json!("")), ": "), - ("a path that is an address", picture("path", json!(address)), "http://example.invalid/a.png: "), + ("an empty path", picture("path", json!("")), "path is the path of a PNG or JPEG file"), + // Never tried as a file, and not repeated. + ("a path that is an address", picture("path", json!(address)), "a picture is read from a file on this computer, not a web address"), ("a path to a folder", picture("path", json!(at("folder.png"))), "/folder.png: not a regular file"), ("a path to a text file", picture("path", json!(note)), "the picture isn't a PNG or JPEG image"), ("a path to a file of 16 MiB and a byte", picture("path", json!(over)), "the picture is too large"), - // A path that isn't text is read as no path. - ("a path that is a number", picture("path", json!(5)), "a picture needs an image or a path"), - // Given both, the image is used and the path is never read. - ("both an image and a path", json!({"kind": "picture", "image": PIN_PNG, "path": note}), "added a picture of the PNG"), - // These four are added, and each draws as the grey box: their size reads, but their pixels - // can't be drawn (declared over 20000 pixels a side, or cut short). - ("an image over 20000 pixels a side", picture("image", json!(huge)), "added a picture of the 30000 x 1 PNG"), - ("an image whose pixels don't read", picture("image", json!(damaged)), "added a picture of the damaged PNG"), - ("a path to a PNG over 20000 pixels a side", picture("path", json!(huge_file)), "added a picture of the 30000 x 1 PNG"), - ("a path to a PNG whose pixels don't read", picture("path", json!(damaged_file)), "added a picture of the damaged PNG"), - // Other kinds of element ignore `image` and `path`. - ("an image on a rectangle", rectangle("image", json!(PIN_PNG)), "added a rectangle"), - ("a path on a rectangle", rectangle("path", json!(at("missing.png"))), "added a rectangle"), + ("a path that is a number", picture("path", json!(5)), "path is the path of a PNG or JPEG file"), + // Given both, neither is read. + ( + "both an image and a path", + json!({"kind": "picture", "image": PIN_PNG, "path": note}), + "give a picture an image or a path, not both", + ), + // These four are refused: their size reads, but their pixels can't be drawn (declared over + // 20000 pixels a side, or cut short). + ("an image over 20000 pixels a side", picture("image", json!(huge)), UNDRAWN), + ("an image whose pixels don't read", picture("image", json!(damaged)), UNDRAWN), + ("a path to a PNG over 20000 pixels a side", picture("path", json!(huge_file)), UNDRAWN), + ("a path to a PNG whose pixels don't read", picture("path", json!(damaged_file)), UNDRAWN), + // Other kinds of element refuse `image` and `path`, before any file is read. + ("an image on a rectangle", rectangle("image", json!(PIN_PNG)), "only pictures take an image or a path"), + ("a path on a rectangle", rectangle("path", json!(at("missing.png"))), "only pictures take an image or a path"), ]; let which = |s: &Session, id: &Value| match s.project.layouts[li].element(id.as_u64().unwrap() as u32).map(|e| &e.kind) { Some(rustgis_map::layout::ElementKind::Picture { image, .. }) => { @@ -285,25 +290,31 @@ fn pictures_save_and_say_as_before() { } } // What `layout.update` does with `path` and `image` on a picture (the PNG first added): its - // answer, the picture afterwards, and the Undo steps it leaves. It takes neither key: the - // picture is left as it was, the file never read, and one Undo step is left all the same. + // answer, the picture afterwards, and the Undo steps it leaves. Each is taken as one Undo step; + // a file it can't read is refused, the picture left as it was and no step left. let png_picture = &added[0]; for (case, key, v, pinned) in [ ( "a path to the JPEG's file", "path", json!(file("jpeg.jpg", &b64(PIN_JPEG))), - "answered null; a picture of the PNG after; 1 Undo step(s)", + "answered null; a picture of the JPEG after; 1 Undo step(s)", + ), + ("the JPEG as an image", "image", json!(PIN_JPEG), "answered null; a picture of the JPEG after; 1 Undo step(s)"), + ( + "a path to a missing file", + "path", + json!(at("missing.png")), + "refused \"/missing.png: \"; a picture of the JPEG after; 0 Undo step(s)", ), - ("the JPEG as an image", "image", json!(PIN_JPEG), "answered null; a picture of the PNG after; 1 Undo step(s)"), - ("a path to a missing file", "path", json!(at("missing.png")), "answered null; a picture of the PNG after; 1 Undo step(s)"), ] { let depth = s.undo_depth(); + let path = v.as_str().filter(|_| key == "path").unwrap_or("").to_string(); let mut p = json!({"layout": li, "element": png_picture}); p[key] = v; let answer = match s.run("layout.update", &p) { Ok(r) => format!("answered {r}"), - Err(e) => format!("refused {:?}", e.replace(&folder, "/")), + Err(e) => format!("refused {:?}", marked(e, &path).replace(&folder, "/")), }; let got = format!("{answer}; {} after; {} Undo step(s)", which(&s, png_picture), s.undo_depth() - depth); if got != pinned { @@ -312,3 +323,228 @@ fn pictures_save_and_say_as_before() { } assert!(wrong.is_empty(), "{}", wrong.join("\n")); } + +/// A folder of the test's own, removed however it ends, and a session with a layout "L". +#[cfg(not(target_arch = "wasm32"))] +fn picture_world(test: &str) -> (Dir, Session) { + let dir = Dir(std::env::temp_dir().join(format!("rustgis-{test}-{}", std::process::id()))); + std::fs::create_dir_all(&dir.0).unwrap(); + let mut s = super::world(); + s.run("layout.new", &json!({"name": "L"})).unwrap(); + (dir, s) +} + +/// A `w` x `h` PNG of one colour written to `name` in `dir`: its path, and its image as base64. +#[cfg(not(target_arch = "wasm32"))] +fn png_file(dir: &Dir, name: &str, (w, h): (u32, u32), colour: [u8; 3]) -> (String, String) { + use base64::Engine as _; + let b64 = png_b64(w, h, |_, _| colour); + let path = dir.0.join(name); + std::fs::write(&path, base64::engine::general_purpose::STANDARD.decode(&b64).unwrap()).unwrap(); + (path.display().to_string(), b64) +} + +/// The image and file of picture `id` in the layout named `layout`. +#[cfg(not(target_arch = "wasm32"))] +fn picture_in(s: &Session, layout: &str, id: &Value) -> (String, Option) { + let l = s.project.layouts.iter().find(|l| l.name == layout).unwrap(); + match &l.element(id.as_u64().unwrap() as u32).unwrap().kind { + rustgis_map::layout::ElementKind::Picture { image, source } => (image.clone(), source.clone()), + k => panic!("not a picture: {k:?}"), + } +} + +/// A picture added from a file remembers it as given; one added from an image has none; no answer +/// carries the path. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_picture_added_from_a_file_remembers_it() { + let (dir, mut s) = picture_world("a-picture-added-from-a-file-remembers-it"); + let (first, first_b64) = png_file(&dir, "first.png", (40, 20), [0x1F, 0x5C, 0x84]); + let added = s.run("layout.addElement", &json!({"kind": "picture", "path": first})).unwrap(); + assert!(!added.to_string().contains("first.png"), "{added}"); + let id = added["element"].clone(); + assert_eq!(picture_in(&s, "L", &id), (first_b64.clone(), Some(first.clone()))); + let bare = s.run("layout.addElement", &json!({"kind": "picture", "image": first_b64})).unwrap()["element"].clone(); + assert_eq!(picture_in(&s, "L", &bare), (first_b64, None)); + let l = s.project.layouts.iter().find(|l| l.name == "L").unwrap(); + let listed = json!(crate::cmd::layout::element_list(l)).to_string(); + assert!(!listed.contains("first.png"), "{listed}"); +} + +/// `layout.update` with a path reads the file again and remembers it; with an image, takes it and +/// forgets the file. Each is one undo step, undone as one. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_picture_is_read_again_from_a_file_and_relinked() { + let (dir, mut s) = picture_world("a-picture-is-read-again-from-a-file-and-relinked"); + let (first, first_b64) = png_file(&dir, "first.png", (40, 20), [0x1F, 0x5C, 0x84]); + let (second, second_b64) = png_file(&dir, "second.png", (30, 30), [0xE8, 0xB0, 0x4A]); + let third_b64 = png_b64(10, 20, |_, _| [0x22, 0x88, 0x22]); + let id = s.run("layout.addElement", &json!({"kind": "picture", "path": first})).unwrap()["element"].clone(); + let depth = s.undo_depth(); + assert_eq!(s.run("layout.update", &json!({"element": id, "path": second})).unwrap(), Value::Null); + assert_eq!(picture_in(&s, "L", &id), (second_b64.clone(), Some(second.clone()))); + assert_eq!(s.undo_depth(), depth + 1); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(picture_in(&s, "L", &id), (first_b64, Some(first))); + s.run("layout.update", &json!({"element": id, "image": third_b64})).unwrap(); + assert_eq!(picture_in(&s, "L", &id), (third_b64.clone(), None)); + let (before, depth) = (serde_json::to_value(&s.project).unwrap(), s.undo_depth()); + s.run("layout.update", &json!({"element": id, "path": null, "image": null})).unwrap(); + assert_eq!((serde_json::to_value(&s.project).unwrap(), s.undo_depth()), (before, depth), "null changes nothing"); + assert_eq!(picture_in(&s, "L", &id), (third_b64, None)); + // A picture an older file holds with no image, only its file, relinked: it draws again. + let imported = json!({"name": "Imported", "width": 210.0, "height": 297.0, "elements": [ + {"id": 1, "name": "Logo", "x": 10.0, "y": 10.0, "w": 40.0, "h": 20.0, "kind": {"Picture": {"image": "", "source": "/data/logos/north.png"}}} + ]}); + s.run("layout.import", &json!({"text": imported.to_string()})).unwrap(); + let layout = |s: &Session| s.project.layouts.iter().find(|l| l.name == "Imported").unwrap().clone(); + assert_eq!(rustgis_render::layout::pictures_not_drawn(&layout(&s)).len(), 1); + s.run("layout.update", &json!({"layout": "Imported", "element": 1, "path": second})).unwrap(); + assert_eq!(picture_in(&s, "Imported", &json!(1)), (second_b64, Some(second))); + assert!(rustgis_render::layout::pictures_not_drawn(&layout(&s)).is_empty()); +} + +/// A missing, unreadable, too large, undrawable or not-a-picture file, or a path of the wrong kind, +/// is refused, even beside a valid key, and the picture is left as it was, with no undo step. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { + let (dir, mut s) = picture_world("a-bad-file-is-refused-and-the-picture-left-as-it-was"); + let (first, first_b64) = png_file(&dir, "first.png", (40, 20), [0x1F, 0x5C, 0x84]); + let (second, _) = png_file(&dir, "second.png", (30, 30), [0xE8, 0xB0, 0x4A]); + let (huge, _) = png_file(&dir, "huge.png", (30_000, 1), [0x1F, 0x5C, 0x84]); + let id = s.run("layout.addElement", &json!({"kind": "picture", "path": first})).unwrap()["element"].clone(); + s.run("layout.update", &json!({"element": id, "path": second})).unwrap(); + let at = |name: &str| dir.0.join(name).display().to_string(); + std::fs::write(at("note.png"), b"not a picture").unwrap(); + std::fs::write(at("big.png"), vec![0u8; (16 << 20) + 1]).unwrap(); + std::fs::create_dir_all(at("sub")).unwrap(); + // The picture, its place, the project, and the Undo steps and unsaved state. + let state = |s: &Session| { + let l = s.project.layouts.iter().find(|l| l.name == "L").unwrap(); + let x = l.element(id.as_u64().unwrap() as u32).unwrap().x; + (picture_in(s, "L", &id), x, serde_json::to_value(&s.project).unwrap(), s.undo_depth(), s.dirty()) + }; + let before = state(&s); + let undrawn = "the picture can't be drawn: its image is damaged or larger than 20000 pixels a side"; + let not_a_path = "path is the path of a PNG or JPEG file"; + for (path, said) in [ + // `read_picture_file`'s own "{path}: …". + (json!(at("gone.png")), "gone.png"), + (json!(at("note.png")), "the picture isn't a PNG or JPEG image"), + (json!(huge), undrawn), + (json!(at("big.png")), "the picture is too large"), + (json!(at("sub")), "not a regular file"), + (json!("https://user:secret@example.invalid/logo.png"), "a picture is read from a file on this computer, not a web address"), + (json!(5), not_a_path), + (json!(""), not_a_path), + (json!(" "), not_a_path), + (json!(["a.png"]), not_a_path), + ] { + let e = s.run("layout.update", &json!({"element": id, "path": path, "x": 5})).unwrap_err(); + assert!(e.contains(said) && !e.contains("secret") && !e.contains("example.invalid"), "{path}: {e}"); + assert!(state(&s) == before, "{path} changed the picture"); + } + for (p, said) in [ + (json!({"element": id, "image": 5, "x": 5}), "image is a PNG or JPEG image in base64"), + (json!({"element": id, "image": first_b64, "path": first, "x": 5}), "give a picture an image or a path, not both"), + (json!({"element": id, "image": "bm90IGFuIGltYWdl", "x": 5}), "the picture isn't a PNG or JPEG image"), + (json!({"element": id, "image": png_b64(30_000, 1, |_, _| [9, 9, 9]), "x": 5}), undrawn), + ] { + let e = s.run("layout.update", &p).unwrap_err(); + assert_eq!(e, said); + assert!(state(&s) == before, "{said}: the picture changed"); + } + // On another kind of element, refused before any file is read; null is not given. + let l = s.project.layouts.iter().find(|l| l.name == "L").unwrap(); + let text = l.elements.iter().find(|e| e.kind.code() == "text").unwrap().id; + let before = state(&s); + for key in ["path", "image"] { + let e = s.run("layout.update", &json!({"element": text, key: first})).unwrap_err(); + assert_eq!(e, "only pictures take an image or a path"); + assert!(state(&s) == before, "{key} on a text changed it"); + } + s.run("layout.update", &json!({"element": text, "path": null, "image": null})).unwrap(); + // Locked, it is refused before its file is read. + s.run("layout.update", &json!({"element": id, "locked": true})).unwrap(); + let before = state(&s); + let e = s.run("layout.update", &json!({"element": id, "path": first})).unwrap_err(); + assert!(e.contains("locked"), "{e}"); + assert!(state(&s) == before, "a locked picture changed"); + // Adding: refused, and no element added. + let count = |s: &Session| s.project.layouts.iter().find(|l| l.name == "L").unwrap().elements.len(); + let (n, depth, dirty) = (count(&s), s.undo_depth(), s.dirty()); + for (p, said) in [ + (json!({"kind": "text", "text": "T", "path": first}), "only pictures take an image or a path"), + (json!({"kind": "rectangle", "image": first_b64}), "only pictures take an image or a path"), + (json!({"kind": "picture", "path": huge}), undrawn), + (json!({"kind": "picture", "image": first_b64, "path": first}), "give a picture an image or a path, not both"), + ( + json!({"kind": "picture", "path": "https://user:secret@example.invalid/logo.png"}), + "a picture is read from a file on this computer, not a web address", + ), + (json!({"kind": "picture"}), "a picture needs an image or a path"), + (json!({"kind": "picture", "path": null, "image": null}), "a picture needs an image or a path"), + ] { + assert_eq!(s.run("layout.addElement", &p).unwrap_err(), said, "{p}"); + assert_eq!((count(&s), s.undo_depth(), s.dirty()), (n, depth, dirty), "{p}"); + } +} + +/// A path the rule doesn't keep: the picture is read, its file not remembered, and that is said. +#[cfg(all(unix, not(target_arch = "wasm32")))] +#[test] +fn a_path_that_is_not_kept_is_read_and_said() { + let (dir, mut s) = picture_world("a-path-that-is-not-kept-is-read-and-said"); + let (first, _) = png_file(&dir, "first.png", (40, 20), [0x1F, 0x5C, 0x84]); + let (odd, odd_b64) = png_file(&dir, "logo\u{7}.png", (20, 20), [0x22, 0x88, 0x22]); + let unremembered = |s: &Session, mark| s.notices_since(mark).iter().filter(|n| n.text.contains("isn't remembered")).count(); + let mark = s.notice_mark(); + let id = s.run("layout.addElement", &json!({"kind": "picture", "path": odd})).unwrap()["element"].clone(); + assert_eq!(picture_in(&s, "L", &id), (odd_b64.clone(), None)); + assert_eq!(unremembered(&s, mark), 1); + let kept = s.run("layout.addElement", &json!({"kind": "picture", "path": first})).unwrap()["element"].clone(); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": kept, "path": odd})).unwrap(); + assert_eq!(picture_in(&s, "L", &kept), (odd_b64, None)); + assert_eq!(unremembered(&s, mark), 1); +} + +/// A project whose pictures' files are of the wrong kind, blank, an address, too long or with +/// control characters opens, says it repaired them, and saves without them and without the +/// capability. +#[test] +fn a_project_with_a_damaged_picture_file_opens_and_says_so() { + let sources = [ + serde_json::json!(5), + serde_json::json!(""), + serde_json::json!("https://user:secret@example.invalid/a.png"), + serde_json::json!(format!("/{}", "d".repeat(5000))), + serde_json::json!("a\u{7}b.png"), + ]; + let elements: Vec = sources + .iter() + .enumerate() + .map(|(i, source)| { + let picture = serde_json::json!({"Picture": {"image": "", "source": source}}); + serde_json::json!({"id": i + 1, "name": "p", "x": 0, "y": 0, "w": 50, "h": 50, "kind": picture}) + }) + .collect(); + let document = serde_json::json!({ + "format": 2, + "name": "Damaged pictures", + "active_map": 0, + "maps": [{"name": "Map", "layers": [], "basemap": "Paper", "camera": {"center": {"x": 0, "y": 0}, "res": 30000}}], + "layouts": [{"name": "Pictures", "width": 297, "height": 210, "elements": elements}] + }); + let mut p = crate::Project::from_json(&document.to_string()).unwrap(); + let said: Vec = p.take_read_notices(&crate::project::ALL_PARTS).iter().map(|n| n.english()).collect(); + assert_eq!(said.iter().filter(|n| n.contains("5 layout element(s) with a value out of range")).count(), 1, "{said:?}"); + assert!(p.layouts[0].elements.iter().all(|e| e.kind.picture_source().is_none())); + let saved = serde_json::to_string(&p).unwrap(); + for absent in ["\"source\"", "secret", "layout-picture-source"] { + assert!(!saved.contains(absent), "{absent} in {saved}"); + } +} diff --git a/docs/maintaining.md b/docs/maintaining.md index b08ba33105..04e7a99167 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -304,6 +304,16 @@ Saved `layout.addElement` and `layout.update` commands that set one require it t `fit` values need nothing. A saved `layout.import` whose `text` has such a legend requires it as well, and a layout file (`.rgislayout`) with one lists it in its header. +Projects with a layout picture that remembers the file it was read from (`source` on a picture +element) require `layout-picture-source`, so an older reader refuses them instead of drawing the +word Picture for a picture with no image and saving it again without its file. A saved +`layout.update` that gives a picture an `image` or a `path` requires it too, since an older reader +ignores both; `layout.addElement` with a `path` needs nothing (an older reader adds the same +picture), and `null` needs nothing. A saved `layout.import` or `report.existingTemplate` whose +`text` has such a picture requires it as well, and a layout file (`.rgislayout`) with one lists it +in its header. A source that is blank, an address, over 4096 bytes or holding control characters +isn't kept, so it needs nothing. + Projects with a scale bar that has subdivisions, divisions before zero, labels below, a unit label of its own or placed elsewhere, decimals or a fit other than the defaults (`subdivisions`, `divisions_before_zero`, `label_position`, `unit_label`, `unit_label_position`, diff --git a/schema/fixtures/layout_picture_source.rgis b/schema/fixtures/layout_picture_source.rgis new file mode 100644 index 0000000000..a34191d1b8 --- /dev/null +++ b/schema/fixtures/layout_picture_source.rgis @@ -0,0 +1,32 @@ +{ + "format": 2, + "name": "Picture files", + "requires": ["layout-picture-source"], + "active_map": 0, + "maps": [ + { + "name": "Map", + "layers": [], + "basemap": "Paper", + "camera": {"center": {"x": 0, "y": 0}, "res": 30000} + } + ], + "layouts": [ + { + "name": "Logo", + "width": 200, + "height": 100, + "elements": [ + {"id": 1, "name": "North", "x": 5, "y": 5, "w": 40, "h": 20, "kind": {"Picture": {"image": "", "source": "/data/logos/north.png"}}} + ] + }, + { + "name": "Inset", + "width": 200, + "height": 100, + "elements": [ + {"id": 1, "name": "Inset", "x": 5, "y": 5, "w": 20, "h": 20, "kind": {"Picture": {"image": "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8BQDwAEhQGAhKmMIQAAAABJRU5ErkJggg==", "source": "/data/logos/inset.png"}}} + ] + } + ] +} diff --git a/schema/project.schema.json b/schema/project.schema.json index 208b6e7b25..77c477cebd 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1278,6 +1278,7 @@ "native-coordinates", "layout-text-size", "layout-legend-fit", + "layout-picture-source", "layout-scale-bar-details", "label-guide", "label-weight", @@ -1396,6 +1397,7 @@ "native-coordinates", "layout-text-size", "layout-legend-fit", + "layout-picture-source", "layout-scale-bar-details", "label-guide", "label-weight", From 0be0acff30b5c33c94a075e4060ab3d8713eb973 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 21:31:02 -0600 Subject: [PATCH 06/38] fix(layout): only an update of empty picture keys leaves no Undo step A layout.update that gives only image or path, each null, changes nothing and leaves no Undo step; every other update keeps its step as before. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout/update.rs | 8 ++++++-- crates/engine/src/tests/layout_files.rs | 8 ++++++++ crates/engine/src/tests/layout_pictures.rs | 9 +++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index f021374ed9..df409ba842 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -467,8 +467,12 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { _ => None, }; let unremembered = new_picture.as_ref().is_some_and(|g| g.unremembered); - // Nothing given that changes anything (every key null, or none): no step to undo. - if !changes && p.get("locked").is_none_or(Value::is_null) { + // Only a picture's image or path, each null: nothing is given, so there is no step to undo. + let only_null_picture = p.as_object().is_some_and(|o| { + o.keys().any(|k| matches!(k.as_str(), "image" | "path")) + && o.iter().all(|(k, v)| matches!(k.as_str(), "layout" | "element") || (matches!(k.as_str(), "image" | "path") && v.is_null())) + }); + if only_null_picture { s.request_only = true; } let l = active(s, p)?; diff --git a/crates/engine/src/tests/layout_files.rs b/crates/engine/src/tests/layout_files.rs index 2df1df28af..4ca2e8f5c5 100644 --- a/crates/engine/src/tests/layout_files.rs +++ b/crates/engine/src/tests/layout_files.rs @@ -88,6 +88,13 @@ fn a_layout_file_requiring_legend_fit_opens() { assert_eq!(s.project.layouts.len(), 2); } +#[test] +fn a_layout_file_requiring_picture_source_opens() { + let (mut s, bare) = with_layout(); + s.run("layout.import", &json!({"text": headed(&bare, 2, json!(["layout-picture-source"]))})).unwrap(); + assert_eq!(s.project.layouts.len(), 2); +} + #[test] fn a_layout_file_requiring_text_block_opens() { let (mut s, bare) = with_layout(); @@ -127,6 +134,7 @@ fn a_saved_layout_file_requires_what_its_elements_use_and_reads_back_the_same() ("section", include_str!("../../../../schema/fixtures/layout_section.rgis")), ("legend-text", include_str!("../../../../schema/fixtures/layout_legend_text.rgis")), ("legend-fit", include_str!("../../../../schema/fixtures/layout_legend_fit.rgis")), + ("picture-source", include_str!("../../../../schema/fixtures/layout_picture_source.rgis")), ("scale-grid-text", include_str!("../../../../schema/fixtures/layout_scale_grid_text.rgis")), ("page-color", include_str!("../../../../schema/fixtures/layout_page_color.rgis")), ("plain", include_str!("../../../../schema/fixtures/layout_no_data.rgis")), diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 18245abad7..0d76ef2a5d 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -394,6 +394,14 @@ fn a_picture_is_read_again_from_a_file_and_relinked() { s.run("layout.update", &json!({"element": id, "path": null, "image": null})).unwrap(); assert_eq!((serde_json::to_value(&s.project).unwrap(), s.undo_depth()), (before, depth), "null changes nothing"); assert_eq!(picture_in(&s, "L", &id), (third_b64, None)); + // Any other update keeps its Undo step, as it always has, even one that changes nothing. + let x = |s: &Session| s.project.layouts.iter().find(|l| l.name == "L").unwrap().element(id.as_u64().unwrap() as u32).unwrap().x; + for p in [json!({"element": id}), json!({"element": id, "text": null}), json!({"element": id, "path": null, "x": 12.0})] { + let depth = s.undo_depth(); + s.run("layout.update", &p).unwrap(); + assert_eq!(s.undo_depth(), depth + 1, "{p}"); + } + assert_eq!(x(&s), 12.0); // A picture an older file holds with no image, only its file, relinked: it draws again. let imported = json!({"name": "Imported", "width": 210.0, "height": 297.0, "elements": [ {"id": 1, "name": "Logo", "x": 10.0, "y": 10.0, "w": 40.0, "h": 20.0, "kind": {"Picture": {"image": "", "source": "/data/logos/north.png"}}} @@ -467,6 +475,7 @@ fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { assert!(state(&s) == before, "{key} on a text changed it"); } s.run("layout.update", &json!({"element": text, "path": null, "image": null})).unwrap(); + assert!(state(&s) == before, "null picture keys on a text changed it"); // Locked, it is refused before its file is read. s.run("layout.update", &json!({"element": id, "locked": true})).unwrap(); let before = state(&s); From 5aac0b6b16c90bfc75bc0d9b4566e0fd97ac5758 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:03:32 -0600 Subject: [PATCH 07/38] feat(layout): every export says the pictures it draws as a grey box Layout PNG, PDF and SVG exports, the Assistant's view of a layout and report exports say, once a kind, the visible pictures with no image or one that can't be drawn, by element and file name, never the file's folders, with the way to read one again. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout.rs | 1 + crates/engine/src/cmd/layout/export.rs | 9 ++ crates/engine/src/cmd/layout/picture.rs | 8 ++ crates/engine/src/cmd/report.rs | 23 ++++ crates/engine/src/tests/layout_pictures.rs | 120 +++++++++++++++++++++ 5 files changed, 161 insertions(+) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 7f97c41af4..af8f4ddf1c 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -43,6 +43,7 @@ use legend::*; pub(crate) use legend::{legend_columns_param, legend_fit_param, legend_names_param}; mod picture; pub(crate) use picture::gives_picture; +pub(in crate::cmd) use picture::say_pictures_not_drawn; use picture::*; mod page; use page::*; diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index d48463674a..bbd0843cc7 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -66,6 +66,10 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> if let Some(r) = region { gaps.retain(|g, _| layout.element(g.frame).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); } + let mut grey = rustgis_render::layout::pictures_not_drawn(&layout); + if let Some(r) = region { + grey.retain(|g| layout.element(g.id).is_some_and(|e| rustgis_render::layout::meets(e, r, 0.0))); + } let (img, mut unfitted) = rustgis_render::layout::unfitted_legends(|| { crate::cmd::share::saying_shadows(s, "The layout", |s| match region { Some(r) => rustgis_render::layout::render_region(&layout, &mut s.project.maps, dpi, &info, r), @@ -83,6 +87,7 @@ pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]> if let Some(note) = rustgis_render::layout::sections_notice(&gaps, 1) { s.warn(note); } + say_pictures_not_drawn(s, &grey, ""); img.encode_png().map_err(|e| e.to_string()) } @@ -231,6 +236,8 @@ pub(in crate::cmd::layout) fn layout_bytes_inner( if let Some(note) = rustgis_render::layout::sections_notice(&gaps, pages.len()) { s.warn(note); } + // A series' pages move its frame only: its pictures are the same on every page. + say_pictures_not_drawn(s, &rustgis_render::layout::pictures_not_drawn(&saved), ""); say_unfitted_legends(s, &unfitted); pictured_notices(s, &frames_pictured, &pages_pictured); georeference_notices(s, &left_out, &by_corners, pages.len()); @@ -455,12 +462,14 @@ pub(in crate::cmd::layout) fn layout_svg(s: &mut Session, li: usize, dpi: f64) - let clipped = rustgis_render::layout::clipped_text(layout, &s.project.maps, dpi, &info); let note = rustgis_render::layout::clipped_text_notice(layout, &clipped); let gaps = rustgis_render::layout::sections_not_drawn(layout, &s.project.maps).into_iter().map(|g| (g, 1)).collect(); + let grey = rustgis_render::layout::pictures_not_drawn(layout); let (drawn, unfitted) = rustgis_render::layout::unfitted_legends(|| rustgis_render::svg::layout_svg(layout, &mut s.project.maps, dpi, &info)); let (text, pictured) = drawn?; for note in [note, rustgis_render::layout::sections_notice(&gaps, 1)].into_iter().flatten() { s.warn(note); } + say_pictures_not_drawn(s, &grey, ""); say_unfitted_legends(s, &unfitted); pictured_notices(s, &pictured, &[]); Ok(text) diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs index dd96bc0ef6..9095dc09ca 100644 --- a/crates/engine/src/cmd/layout/picture.rs +++ b/crates/engine/src/cmd/layout/picture.rs @@ -31,6 +31,14 @@ pub(in crate::cmd::layout) fn picture_unremembered() -> String { ) } +/// Says each of [`rustgis_render::layout::pictures_notices`] of `gaps`, the pictures an export +/// draws as a grey box, with `prefix` before it. +pub(in crate::cmd) fn say_pictures_not_drawn(s: &mut Session, gaps: &[rustgis_render::layout::PictureGap], prefix: &str) { + for note in rustgis_render::layout::pictures_notices(gaps) { + s.warn(format!("{prefix}{note}")); + } +} + /// A picture's image as a command gives it, and the file it was read from. pub(crate) struct GivenPicture { /// The image, base64, checked to draw. diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 1f5f869d84..18943e9f2a 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1185,6 +1185,7 @@ fn report_pages_bytes( keep_unfitted(&mut unfitted, page_layout, listed); say_report_unfitted(s, &unfitted); say_sections_not_drawn(s, pages, 1); + say_report_pictures(s, pages, 1); return Ok((img.encode_png().map_err(|e| e.to_string())?, pages.len())); } let (drawn, listed) = rustgis_render::layout::unfitted_legends(|| { @@ -1213,6 +1214,7 @@ fn report_pages_bytes( say_report_unfitted(s, &unfitted); super::layout::pictured_notices(s, &frames_pictured, &pages_pictured); say_sections_not_drawn(s, pages, n); + say_report_pictures(s, pages, n); Ok((rustgis_render::pdf::write(&out, &doc.title), pages.len())) } @@ -1239,6 +1241,27 @@ fn say_sections_not_drawn(s: &mut Session, pages: &[rustgis_render::report::Page } } +/// Says the pictures the layouts of the first `n` of `pages` draw as a grey box, as the layout's +/// own export says them: once a kind however many layouts hold one, each picture named with its +/// layout, and a layout on several pages counted once. +fn say_report_pictures(s: &mut Session, pages: &[rustgis_render::report::Page], n: usize) { + let mut seen = Vec::new(); + let mut gaps = Vec::new(); + for page in pages.iter().take(n) { + let rustgis_render::report::Page::Layout(li) = page else { continue }; + if seen.contains(li) { + continue; + } + seen.push(*li); + let Some(layout) = s.project.layouts.get(*li) else { continue }; + for mut gap in rustgis_render::layout::pictures_not_drawn(layout) { + gap.name = format!("{} in layout '{}'", gap.name, layout.name); + gaps.push(gap); + } + } + super::layout::say_pictures_not_drawn(s, &gaps, "The report: "); +} + /// Keeps the legends `listed` as cut on a page that draws the layout `layout` (by its index), each /// with that layout: the ids are a layout's own, so two layouts' legends sharing one are two. Only /// an exact repeat (the same legend of the same layout, cut the same way) is dropped: the page diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 0d76ef2a5d..0ca9c48b0a 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -557,3 +557,123 @@ fn a_project_with_a_damaged_picture_file_opens_and_says_so() { assert!(!saved.contains(absent), "{absent} in {saved}"); } } + +/// A session holding layout "L": the sample's map in a frame, and the pictures "Logo" (no image, +/// from `/home/someone/logos/north.png`), "Blank" (no image, no file), "Broken" (an image that +/// isn't one), "Hidden" (no image, not visible) and "Fine" (a PNG), as an older file holds them. +#[cfg(not(target_arch = "wasm32"))] +fn grey_pictures() -> Session { + let mut s = super::world(); + s.run("layout.new", &json!({"name": "L", "page": "a4", "orientation": "portrait", "template": "map"})).unwrap(); + let mut layout = serde_json::to_value(&s.project.layouts[0]).unwrap(); + s.project.layouts.clear(); + let picture = |id: u32, name: &str, x: f64, y: f64, kind: Value, visible: bool| json!({"id": id, "name": name, "x": x, "y": y, "w": 30.0, "h": 15.0, "visible": visible, "kind": {"Picture": kind}}); + let fine = png_b64(20, 10, |_, _| [0x1F, 0x5C, 0x84]); + let elements = layout["elements"].as_array_mut().unwrap(); + elements.extend([ + picture(101, "Logo", 10.0, 10.0, json!({"image": "", "source": "/home/someone/logos/north.png"}), true), + picture(102, "Blank", 50.0, 10.0, json!({"image": ""}), true), + picture(103, "Broken", 90.0, 10.0, json!({"image": "bm90IGFuIGltYWdl"}), true), + picture(104, "Hidden", 130.0, 10.0, json!({"image": ""}), false), + picture(105, "Fine", 150.0, 250.0, json!({"image": fine}), true), + ]); + s.run("layout.import", &json!({"text": layout.to_string()})).unwrap(); + assert_eq!((s.project.layouts.len(), s.project.layouts[0].name.as_str()), (1, "L")); + s +} + +/// Pictures drawn as a grey box are said by every export, once a kind, named by their file's name, +/// never its folders; a hidden one or one that draws isn't; a map series says them once; after a +/// relink, nothing is said. (A layout whose pictures all draw says nothing new at any export: +/// `pictures_save_and_say_as_before` pins that.) +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_picture_drawn_as_a_grey_box_is_said_by_every_export() { + let dir = Dir(std::env::temp_dir().join(format!("rustgis-a-picture-drawn-as-a-grey-box-{}", std::process::id()))); + std::fs::create_dir_all(&dir.0).unwrap(); + let at = |file: &str| dir.0.join(file).display().to_string(); + let mut s = grey_pictures(); + // The report places the layout on two pages: it is said once all the same. + s.run("report.new", &json!({"layer": "Countries", "name": "R", "fields": ["name"], "where": "name LIKE 'F%'"})).unwrap(); + s.run("report.existingTemplate", &json!({"report": "R", "layout": "L"})).unwrap(); + s.run("report.existingTemplate", &json!({"report": "R", "layout": "L", "end": true})).unwrap(); + // What a route says of layout pictures. + let said = |s: &mut Session, run: &dyn Fn(&mut Session)| -> Vec { + let mark = s.notice_mark(); + run(s); + s.notices_since(mark).iter().map(|n| n.text.clone()).filter(|t| t.contains("layout picture(s)")).collect() + }; + let export = |file: &'static str| { + let path = at(file); + Box::new(move |s: &mut Session| drop(s.run("layout.export", &json!({"path": path, "dpi": 36})).unwrap())) + as Box + }; + let report = |file: &'static str| { + let path = at(file); + Box::new(move |s: &mut Session| drop(s.run("report.export", &json!({"report": "R", "path": path, "dpi": 36})).unwrap())) + as Box + }; + let view: Box = Box::new(|s| drop(crate::cmd::layout::layout_png(s, 0, 36.0, None).unwrap())); + let routes: Vec<(&str, bool, Box)> = vec![ + ("layout.export png", false, export("p.png")), + ("layout.export pdf", false, export("p.pdf")), + ("layout.export svg", false, export("p.svg")), + ("the Assistant's view", false, view), + ("report.export png", true, report("r.png")), + ("report.export pdf", true, report("r.pdf")), + ]; + for (route, in_report, run) in &routes { + let said = said(&mut s, run.as_ref()); + assert_eq!(said.len(), 2, "{route}: {said:?}"); + let (logo, blank, broken) = if *in_report { + ("Logo in layout 'L' (", "Blank in layout 'L' (", "Broken in layout 'L' (") + } else { + ("Logo (", "Blank (", "Broken (") + }; + assert!( + said[0].contains("2 layout picture(s) have no image") + && said[0].contains(logo) + && said[0].contains("north.png") + && said[0].contains(blank), + "{route}: {said:?}" + ); + assert!(said[1].contains("1 layout picture(s) have an image that can't be drawn") && said[1].contains(broken), "{route}: {said:?}"); + assert!( + said.iter().all(|n| !n.contains("someone") && !n.contains("logos") && !n.contains("Hidden") && !n.contains("Fine")), + "{route}: {said:?}" + ); + assert!(said.iter().all(|n| n.starts_with("The report: ") == *in_report), "{route}: {said:?}"); + } + // The Assistant's view of a region holding only "Fine" says nothing of pictures. + let fine = said(&mut s, &|s| drop(crate::cmd::layout::layout_png(s, 0, 36.0, Some([145.0, 245.0, 40.0, 25.0])).unwrap())); + assert!(fine.is_empty(), "{fine:?}"); + // A map series over three countries: the PDF of all its pages says each kind once. + let mut series = grey_pictures(); + for layer in &mut series.map_mut().layers { + if layer.name == "Countries" { + layer.dataset.features.truncate(3); + } + } + series.run("layout.series", &json!({"layout": "L", "layer": "Countries"})).unwrap(); + assert_eq!(crate::cmd::layout::series_pages(&series, 0).map(|p| p.len()), Some(3)); + let pages = said(&mut series, export("series.pdf").as_ref()); + assert_eq!(pages.len(), 2, "{pages:?}"); + assert!(pages[0].contains("2 layout picture(s) have no image"), "{pages:?}"); + assert!(pages[1].contains("1 layout picture(s) have an image that can't be drawn"), "{pages:?}"); + // Relinked, or removed: no route says anything of pictures. + let png = dir.0.join("north.png"); + std::fs::write(&png, { + use base64::Engine as _; + base64::engine::general_purpose::STANDARD.decode(png_b64(20, 10, |_, _| [0xE8, 0xB0, 0x4A])).unwrap() + }) + .unwrap(); + for id in [101, 103] { + s.run("layout.update", &json!({"layout": "L", "element": id, "path": png.display().to_string()})).unwrap(); + } + s.run("layout.removeElement", &json!({"layout": "L", "element": 102})).unwrap(); + assert!(rustgis_render::layout::pictures_not_drawn(&s.project.layouts[0]).is_empty()); + for (route, _, run) in &routes { + let said = said(&mut s, run.as_ref()); + assert!(said.is_empty(), "{route}: {said:?}"); + } +} From c090ee96af559b04ca31cdbfef5b9fdc151499e1 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:38:48 -0600 Subject: [PATCH 08/38] =?UTF-8?q?feat(ui):=20a=20picture's=20file=20in=20t?= =?UTF-8?q?he=20Format=20pane,=20and=20Choose=20File=E2=80=A6=20to=20read?= =?UTF-8?q?=20it=20again?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A picture's Format rows show the name of the file it remembers (its whole path only on hover) or "No file", and, on the desktop, Choose File…, which reads the picked file into the picture with layout.update in one Undo step; cancelled, nothing is sent, and a refused file leaves the picture as it was. The layout view says the pictures it draws as a grey box once, again only when what it says changes, and forgets it once none is left. Co-Authored-By: Claude Fable 5.2 --- crates/ui-egui/src/layoutview.rs | 21 +++ crates/ui-egui/src/layoutview/format.rs | 4 +- .../ui-egui/src/layoutview/format/picture.rs | 34 ++++ crates/ui-egui/src/layoutview/tests.rs | 153 ++++++++++++++++++ 4 files changed, 211 insertions(+), 1 deletion(-) create mode 100644 crates/ui-egui/src/layoutview/format/picture.rs diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index c104b97f8b..4104c00e12 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -59,6 +59,22 @@ pub(crate) fn say_frame_shadows(app: &mut RustGisApp, said: &rustgis_engine::ren } } +/// Says the pictures of `layout` drawn as a grey box (see +/// [`rustgis_engine::render::layout::pictures_not_drawn`]), each kind once, again only when what +/// is said of them changes, and forgets it once none is left. Their images are decoded through the +/// cache the page draws from. +pub(crate) fn say_pictures_not_drawn(app: &mut RustGisApp, layout: &Layout) { + use rustgis_engine::render::layout::{pictures_not_drawn, pictures_notices}; + let notices = pictures_notices(&pictures_not_drawn(layout)); + let note = Some(notices.join("\n")).filter(|n| !n.is_empty()); + if note != app.layout.picture_warning { + for notice in notices { + app.session.warn(notice); + } + app.layout.picture_warning = note; + } +} + /// The key a preview drawn for `base` is kept under: with the tile cache's generation read before /// it was drawn (`drawn_at`) when its frames drew without cast shadows still being worked out (on /// the interface's thread, which doesn't wait for them), so it is drawn again as they land, even @@ -117,6 +133,8 @@ pub struct LayoutView { text_warning: Option, /// The last notice of the section lines the page's frames don't draw. section_warning: Option, + /// The last notice of the pictures the page draws as a grey box. + picture_warning: Option, /// The texts of the layout drawn (by its index) cut off on its page, with their lines left /// out of their box, as the Format pane tells them (#2346). text_losses: Option<(usize, Vec)>, @@ -210,6 +228,7 @@ pub(crate) fn follow_project(app: &mut RustGisApp) { app.layout.viewed = None; app.layout.text_warning = None; app.layout.section_warning = None; + app.layout.picture_warning = None; app.layout.text_losses = None; app.layout.views.clear(); } @@ -287,6 +306,7 @@ impl LayoutView { } self.text_warning = None; self.section_warning = None; + self.picture_warning = None; self.text_losses = None; if let Some(old) = self.viewed.replace(name.to_string()) { self.views.insert(old, (self.zoom, self.pan)); @@ -428,6 +448,7 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { } app.layout.section_warning = note; } + say_pictures_not_drawn(app, &layout); // The Format pane is drawn before the page: a count that changed shows on the next // frame, without waiting for an input event. let losses = Some((li, losses)); diff --git a/crates/ui-egui/src/layoutview/format.rs b/crates/ui-egui/src/layoutview/format.rs index 10984d2164..f18e12225c 100644 --- a/crates/ui-egui/src/layoutview/format.rs +++ b/crates/ui-egui/src/layoutview/format.rs @@ -5,6 +5,7 @@ mod colorbar; mod frame; mod legend; mod north; +mod picture; mod scalebar; mod shapes; mod table; @@ -20,6 +21,7 @@ use egui::{Color32, Ui, vec2}; use frame::*; use legend::*; use north::*; +use picture::*; use rustgis_engine::map::layout::{ Element, ElementKind, INK, LAYOUT_TEXT_SIZE, Layout, MAX_BACKGROUND_PADDING, MAX_BACKGROUND_RADIUS, MAX_BACKGROUND_WIDTH, Orientation, }; @@ -234,12 +236,12 @@ pub(super) fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: ElementKind::Colorbar { .. } => colorbar_rows(app, ui, layout, li, &e, &update), ElementKind::MapFrame { .. } => frame_rows(app, ui, li, &e, &update), ElementKind::NorthArrow { .. } => north_arrow_rows(app, ui, &e, &update), + ElementKind::Picture { .. } => picture_rows(app, ui, &e, &update), ElementKind::ScaleBar { .. } => scale_bar_rows(app, ui, layout, li, &e, &update), ElementKind::Chart { .. } => chart_rows(app, ui, layout, li, &e, &update), ElementKind::Table { .. } => table_rows(app, ui, li, &e, &update), ElementKind::Rectangle { .. } | ElementKind::Ellipse { .. } => shape_rows(app, ui, li, &e, &update), ElementKind::Line { .. } => line_rows(app, ui, li, &e, &update), - _ => {} } // A legend's, colorbar's, table's or chart's ink (#2257), on and off as a background // is: off is the default dark grey, which isn't the same as a dark grey ink (a table diff --git a/crates/ui-egui/src/layoutview/format/picture.rs b/crates/ui-egui/src/layoutview/format/picture.rs new file mode 100644 index 0000000000..dc19188753 --- /dev/null +++ b/crates/ui-egui/src/layoutview/format/picture.rs @@ -0,0 +1,34 @@ +//! A picture's Format rows: the file its image was read from, and Choose File… to read one. + +use crate::RustGisApp; +use egui::Ui; +use rustgis_engine::map::layout::{Element, ElementKind, picture_file_name}; +use serde_json::Value; + +/// A picture's rows in the grid: File, the name of the file it remembers (its whole path on +/// hover) or "No file"; and, on the desktop, Choose File…, which reads the file picked into the +/// picture through `update`. Nothing is sent until a file is picked. +#[cfg_attr(target_arch = "wasm32", expect(unused_variables, reason = "the browser has no file paths to read a picture from"))] +pub(super) fn picture_rows(app: &mut RustGisApp, ui: &mut Ui, e: &Element, update: &dyn Fn(&mut RustGisApp, Value)) { + if !matches!(e.kind, ElementKind::Picture { .. }) { + return; + } + let source = e.kind.picture_source(); + ui.label(tl!("File")); + match source.and_then(|s| Some((s, picture_file_name(s)?))) { + Some((path, name)) => ui.add(egui::Label::new(name).truncate()).on_hover_text(path), + None => ui.label(tl!("No file")), + }; + ui.end_row(); + #[cfg(not(target_arch = "wasm32"))] + { + ui.label(""); + let hint = tl!("Read the picture from a PNG or JPEG file, and remember the file"); + if ui.button(tl!("Choose File…")).on_hover_text(hint).clicked() + && let Some(path) = crate::dialogs::pick_open(&["png", "jpg", "jpeg"], tl!("Pictures")) + { + update(app, serde_json::json!({"path": path})); + } + ui.end_row(); + } +} diff --git a/crates/ui-egui/src/layoutview/tests.rs b/crates/ui-egui/src/layoutview/tests.rs index 4720df8a01..4fe729c32d 100644 --- a/crates/ui-egui/src/layoutview/tests.rs +++ b/crates/ui-egui/src/layoutview/tests.rs @@ -2528,3 +2528,156 @@ fn number_key_is_one_per_layout_element_and_field() { assert_ne!(super::number_key(1, 7, "rows"), super::number_key(1, 8, "rows")); assert_ne!(super::number_key(1, 7, "rows"), super::number_key(1, 7, "columns")); } + +/// A 4 x 4 PNG of one opaque colour, as the bytes of its file. +fn png_bytes([r, g, b]: [u8; 3]) -> Vec { + let mut png = std::io::Cursor::new(Vec::new()); + image::RgbaImage::from_pixel(4, 4, image::Rgba([r, g, b, 255])).write_to(&mut png, image::ImageFormat::Png).unwrap(); + png.into_inner() +} + +/// The layout view with the Format pane beside it, drawn after a first frame that installs the +/// fonts. +fn format_harness(app: RustGisApp) -> egui_kittest::Harness<'static, RustGisApp> { + let mut fonts = false; + egui_kittest::Harness::builder().with_size(vec2(1200.0, 900.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + with_format(app, ui); + }, + app, + ) +} + +/// A picture's file in the Format pane: its name shown (the folders only on hover), opening sends +/// nothing, Choose File… cancelled sends nothing, a file picked is read and remembered in one undo +/// step, and a file that isn't a picture changes nothing. +#[test] +fn a_pictures_file_is_shown_and_chosen_again_in_one_undo_step() { + use egui_kittest::kittest::Queryable; + let dir = tempfile::tempdir().unwrap(); + let at = |name: &str| dir.path().join(name).display().to_string(); + let (first, second, note) = (at("first.png"), at("second.png"), at("note.png")); + std::fs::write(&first, png_bytes([0x1F, 0x5C, 0x84])).unwrap(); + std::fs::write(&second, png_bytes([0xE8, 0xB0, 0x4A])).unwrap(); + std::fs::write(¬e, "a note, not a picture").unwrap(); + crate::dialogs::PICKED.with(|p| *p.borrow_mut() = None); + let mut app = RustGisApp::with_sample(); + app.run("layout.new", json!({"name": "Logo"})).unwrap(); + let li = app.session.active_layout.unwrap(); + let added = app.run("layout.addElement", json!({"layout": li, "kind": "picture", "path": first})).unwrap(); + let id = added["element"].as_u64().unwrap() as u32; + app.layout.selected = Some(id); + // The picture's kept file and its image. + let picture = |app: &RustGisApp| { + let kind = &app.session.project.layouts[li].element(id).unwrap().kind; + let ElementKind::Picture { image, .. } = kind else { panic!("{kind:?}") }; + (kind.picture_source().map(String::from), image.clone()) + }; + let mut h = format_harness(app); + let depth = h.state().session.undo_depth(); + h.run_steps(3); + assert_eq!(h.state().session.undo_depth(), depth, "opening the pane changed nothing"); + let (source, first_image) = picture(h.state()); + assert_eq!(source.as_deref(), Some(first.as_str())); + h.get_by_label("first.png"); + assert!(h.query_by_label(&first).is_none(), "the folders show only on hover"); + // Choose File… once the dialog has answered `picked` (cancelled when `None`). + let choose = |h: &mut egui_kittest::Harness<'_, RustGisApp>, picked: Option<&str>| { + crate::dialogs::PICKED.with(|p| *p.borrow_mut() = picked.map(String::from)); + h.get_by_label("Choose File…").click(); + h.run_steps(3); + assert!(crate::dialogs::PICKED.with(|p| p.borrow().is_none()), "the dialog was asked"); + }; + choose(&mut h, None); + assert_eq!(h.state().session.undo_depth(), depth, "a cancelled dialog sends nothing"); + assert_eq!(picture(h.state()), (Some(first.clone()), first_image.clone())); + choose(&mut h, Some(&second)); + let (source, second_image) = picture(h.state()); + assert_eq!(source.as_deref(), Some(second.as_str())); + assert_ne!(second_image, first_image, "the picked file is read"); + assert_eq!(h.state().session.undo_depth(), depth + 1, "one step"); + h.get_by_label("second.png"); + assert!(h.query_by_label("first.png").is_none()); + let mark = h.state().session.notice_mark(); + choose(&mut h, Some(¬e)); + assert_eq!(picture(h.state()), (Some(second.clone()), second_image), "a file that isn't a picture changes nothing"); + assert_eq!(h.state().session.undo_depth(), depth + 1, "a refused file is no step"); + let refused: Vec = h.state().session.notices_since(mark).iter().filter(|n| n.error).map(|n| n.text.clone()).collect(); + assert!(refused.iter().any(|t| t.contains("isn't a PNG or JPEG image")), "{refused:?}"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(picture(h.state()), (Some(first.clone()), first_image)); + // A picture added from an image has no file. + use base64::Engine as _; + let image = base64::engine::general_purpose::STANDARD.encode(png_bytes([0x30, 0x90, 0x40])); + let added = h.state_mut().run("layout.addElement", json!({"layout": li, "kind": "picture", "image": image})).unwrap(); + h.state_mut().layout.selected = added["element"].as_u64().map(|v| v as u32); + h.run_steps(3); + h.get_by_label("No file"); + assert!(h.query_by_label("first.png").is_none()); + crate::dialogs::PICKED.with(|p| *p.borrow_mut() = None); +} + +/// A text element has no picture rows. +#[test] +fn a_text_element_has_no_picture_rows() { + use egui_kittest::kittest::Queryable; + crate::dialogs::PICKED.with(|p| *p.borrow_mut() = None); + let mut app = RustGisApp::with_sample(); + app.run("layout.new", json!({"name": "Words"})).unwrap(); + let li = app.session.active_layout.unwrap(); + let added = app.run("layout.addElement", json!({"layout": li, "kind": "text", "text": "Title"})).unwrap(); + app.layout.selected = added["element"].as_u64().map(|v| v as u32); + let mut h = format_harness(app); + h.run_steps(3); + h.get_by_label("Name"); + assert!(h.query_by_label("Choose File…").is_none()); + assert!(h.query_by_label("No file").is_none()); +} + +/// The layout view says the pictures it draws as a grey box once, again only when that changes, +/// and forgets it when none is left. +#[test] +fn the_layout_view_says_a_picture_drawn_as_a_grey_box_once() { + let dir = tempfile::tempdir().unwrap(); + let logo = dir.path().join("logo.png").display().to_string(); + std::fs::write(&logo, png_bytes([0x1F, 0x5C, 0x84])).unwrap(); + let mut app = RustGisApp::with_sample(); + let mut grey = Layout::new("Grey", 297.0, 210.0); + let source = Some("/data/logos/north.png".to_string()); + grey.add("North", (10.0, 10.0, 30.0, 15.0), ElementKind::Picture { image: String::new(), source }); + app.run("layout.import", json!({"text": serde_json::to_string(&grey).unwrap()})).unwrap(); + let li = app.session.project.layouts.iter().position(|l| l.name == "Grey").unwrap(); + // What the view says of the layout's pictures when its page is drawn twice as it is. + let said = |app: &mut RustGisApp| -> Vec { + let mark = app.session.notice_mark(); + let layout = app.session.project.layouts[li].clone(); + super::say_pictures_not_drawn(app, &layout); + super::say_pictures_not_drawn(app, &layout); + let notices = app.session.notices_since(mark); + notices.iter().map(|n| n.text.clone()).filter(|t| t.contains("layout picture(s)")).collect() + }; + let first = said(&mut app); + assert_eq!(first.len(), 1, "{first:?}"); + assert!(first[0].starts_with("1 layout picture(s) have no image") && first[0].contains("north.png"), "{first:?}"); + assert!(!first[0].contains("/data/logos"), "never the folders: {first:?}"); + assert!(app.layout.picture_warning.is_some()); + // A second grey picture: the text changes, so it is said again, once. + app.session.project.layouts[li].add("Blank", (50.0, 10.0, 30.0, 15.0), ElementKind::Picture { image: String::new(), source: None }); + let second = said(&mut app); + assert_eq!(second.len(), 1, "{second:?}"); + assert!(second[0].starts_with("2 layout picture(s) have no image"), "{second:?}"); + // Both read from a file again: nothing more is said, and the notice is forgotten. + let pictures: Vec = + app.session.project.layouts[li].elements.iter().filter(|e| matches!(e.kind, ElementKind::Picture { .. })).map(|e| e.id).collect(); + assert_eq!(pictures.len(), 2); + for id in pictures { + app.run("layout.update", json!({"layout": li, "element": id, "path": logo})).unwrap(); + } + assert_eq!(said(&mut app), Vec::::new()); + assert_eq!(app.layout.picture_warning, None); +} From 5aba35be27c39c92cd18b119698b25bdf848bbc7 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:47:14 -0600 Subject: [PATCH 09/38] fix(ui): the layout view checks its pictures once a change, not on every redraw The check of the pictures drawn as a grey box can decode pictures, so the view runs it once per layout and revision, not again for a zoom or a resize. A cut file name's hover shows its path alone. Co-Authored-By: Claude Fable 5.2 --- crates/ui-egui/src/layoutview.rs | 11 ++++- .../ui-egui/src/layoutview/format/picture.rs | 9 ++-- crates/ui-egui/src/layoutview/tests.rs | 43 +++++++++++++++++-- 3 files changed, 54 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index 4104c00e12..0881cc0833 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -135,6 +135,10 @@ pub struct LayoutView { section_warning: Option, /// The last notice of the pictures the page draws as a grey box. picture_warning: Option, + /// The layout (by its index) and the project revision its pictures were last checked at + /// ([`say_pictures_not_drawn`]): the check can decode pictures, so it runs once per layout and + /// revision, not on every redraw of the page for a zoom or a resize. + pictures_checked: Option<(usize, u64)>, /// The texts of the layout drawn (by its index) cut off on its page, with their lines left /// out of their box, as the Format pane tells them (#2346). text_losses: Option<(usize, Vec)>, @@ -229,6 +233,7 @@ pub(crate) fn follow_project(app: &mut RustGisApp) { app.layout.text_warning = None; app.layout.section_warning = None; app.layout.picture_warning = None; + app.layout.pictures_checked = None; app.layout.text_losses = None; app.layout.views.clear(); } @@ -307,6 +312,7 @@ impl LayoutView { self.text_warning = None; self.section_warning = None; self.picture_warning = None; + self.pictures_checked = None; self.text_losses = None; if let Some(old) = self.viewed.replace(name.to_string()) { self.views.insert(old, (self.zoom, self.pan)); @@ -448,7 +454,10 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { } app.layout.section_warning = note; } - say_pictures_not_drawn(app, &layout); + if app.layout.pictures_checked != Some((li, key.0)) { + say_pictures_not_drawn(app, &layout); + app.layout.pictures_checked = Some((li, key.0)); + } // The Format pane is drawn before the page: a count that changed shows on the next // frame, without waiting for an input event. let losses = Some((li, losses)); diff --git a/crates/ui-egui/src/layoutview/format/picture.rs b/crates/ui-egui/src/layoutview/format/picture.rs index dc19188753..0db3b2fb44 100644 --- a/crates/ui-egui/src/layoutview/format/picture.rs +++ b/crates/ui-egui/src/layoutview/format/picture.rs @@ -5,9 +5,10 @@ use egui::Ui; use rustgis_engine::map::layout::{Element, ElementKind, picture_file_name}; use serde_json::Value; -/// A picture's rows in the grid: File, the name of the file it remembers (its whole path on -/// hover) or "No file"; and, on the desktop, Choose File…, which reads the file picked into the -/// picture through `update`. Nothing is sent until a file is picked. +/// A picture's rows in the grid: File, the name of the file it remembers or "No file", its +/// folders never in the label's text, only on hover and as its description for screen readers; +/// and, on the desktop, Choose File…, which reads the file picked into the picture through +/// `update`. Nothing is sent until a file is picked. #[cfg_attr(target_arch = "wasm32", expect(unused_variables, reason = "the browser has no file paths to read a picture from"))] pub(super) fn picture_rows(app: &mut RustGisApp, ui: &mut Ui, e: &Element, update: &dyn Fn(&mut RustGisApp, Value)) { if !matches!(e.kind, ElementKind::Picture { .. }) { @@ -16,7 +17,7 @@ pub(super) fn picture_rows(app: &mut RustGisApp, ui: &mut Ui, e: &Element, updat let source = e.kind.picture_source(); ui.label(tl!("File")); match source.and_then(|s| Some((s, picture_file_name(s)?))) { - Some((path, name)) => ui.add(egui::Label::new(name).truncate()).on_hover_text(path), + Some((path, name)) => ui.add(egui::Label::new(name).truncate().show_tooltip_when_elided(false)).on_hover_text(path), None => ui.label(tl!("No file")), }; ui.end_row(); diff --git a/crates/ui-egui/src/layoutview/tests.rs b/crates/ui-egui/src/layoutview/tests.rs index 4fe729c32d..16cc0d82ca 100644 --- a/crates/ui-egui/src/layoutview/tests.rs +++ b/crates/ui-egui/src/layoutview/tests.rs @@ -2553,9 +2553,10 @@ fn format_harness(app: RustGisApp) -> egui_kittest::Harness<'static, RustGisApp> ) } -/// A picture's file in the Format pane: its name shown (the folders only on hover), opening sends -/// nothing, Choose File… cancelled sends nothing, a file picked is read and remembered in one undo -/// step, and a file that isn't a picture changes nothing. +/// A picture's file in the Format pane: its name shown (the folders never in the label's text, only +/// on hover and as its description for screen readers), opening sends nothing, Choose File… +/// cancelled sends nothing, a file picked is read and remembered in one undo step, and a file +/// that isn't a picture changes nothing. #[test] fn a_pictures_file_is_shown_and_chosen_again_in_one_undo_step() { use egui_kittest::kittest::Queryable; @@ -2585,7 +2586,7 @@ fn a_pictures_file_is_shown_and_chosen_again_in_one_undo_step() { let (source, first_image) = picture(h.state()); assert_eq!(source.as_deref(), Some(first.as_str())); h.get_by_label("first.png"); - assert!(h.query_by_label(&first).is_none(), "the folders show only on hover"); + assert!(h.query_by_label(&first).is_none(), "the folders are never the label's text"); // Choose File… once the dialog has answered `picked` (cancelled when `None`). let choose = |h: &mut egui_kittest::Harness<'_, RustGisApp>, picked: Option<&str>| { crate::dialogs::PICKED.with(|p| *p.borrow_mut() = picked.map(String::from)); @@ -2681,3 +2682,37 @@ fn the_layout_view_says_a_picture_drawn_as_a_grey_box_once() { assert_eq!(said(&mut app), Vec::::new()); assert_eq!(app.layout.picture_warning, None); } + +/// The layout view checks its pictures once a layout and revision: a zoom draws the page again +/// without checking them again, and a change to the layout checks them again. +#[test] +fn the_layout_view_checks_its_pictures_once_a_change() { + let mut app = RustGisApp::with_sample(); + let mut grey = Layout::new("Grey", 297.0, 210.0); + let source = Some("/data/logos/north.png".to_string()); + grey.add("North", (10.0, 10.0, 30.0, 15.0), ElementKind::Picture { image: String::new(), source }); + app.run("layout.import", json!({"text": serde_json::to_string(&grey).unwrap()})).unwrap(); + let li = app.session.project.layouts.iter().position(|l| l.name == "Grey").unwrap(); + let id = app.session.project.layouts[li].elements.iter().find(|e| e.name == "North").unwrap().id; + app.session.active_layout = Some(li); + let mark = app.session.notice_mark(); + // How often the view has said the layout's grey pictures. + let said = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.state().session.notices_since(mark).iter().filter(|n| n.text.contains("layout picture(s)")).count() + }; + let mut h = format_harness(app); + h.run_steps(3); + assert_eq!(said(&h), 1, "the page drawn says its grey picture"); + assert_eq!(h.state().layout.pictures_checked, Some((li, h.state().session.revision))); + let drawn = h.state().layout.key; + // Forgotten by hand: only a check would say it again. + h.state_mut().layout.picture_warning = None; + h.state_mut().layout.zoom = 2.0; + h.run_steps(3); + assert_ne!(h.state().layout.key, drawn, "the zoomed page was drawn again"); + assert_eq!(said(&h), 1, "a zoom at the same revision doesn't check the pictures again"); + h.state_mut().run("layout.update", json!({"layout": li, "element": id, "name": "Arrow"})).unwrap(); + h.run_steps(3); + assert_eq!(said(&h), 2, "a change checks them again"); + assert_eq!(h.state().layout.pictures_checked, Some((li, h.state().session.revision))); +} From c9fe044b80343f11de2e9b25363f0c8855ce1946 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 22:56:22 -0600 Subject: [PATCH 10/38] docs(layout): pictures that remember their file in the user guide and the print-layout skill The guide says what a picture remembers, what is drawn and said when it has no image, how to read its file again and what scripts give layout.update; the skill names a picture's path and image. Co-Authored-By: Claude Fable 5.2 --- crates/assistant/skills/print-layout/SKILL.md | 6 ++++-- docs/user-guide/layouts.md | 17 ++++++++++++++++- 2 files changed, 20 insertions(+), 3 deletions(-) diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index 0c6ce92bab..d6a6ff2e32 100644 --- a/crates/assistant/skills/print-layout/SKILL.md +++ b/crates/assistant/skills/print-layout/SKILL.md @@ -26,11 +26,13 @@ description: Make a printable page layout — map frame, title, legend, north ar (`"auto"`, the default, or 0–3 fixed with the thousands set apart, as a chart's), `"textSize"` (4–100 pt, its labels' size) and `"fit"` (`"adjustDivisionValue"`, `"adjustDivision"`, `"adjustWidth"`). A `"legend"` can take `"columns"` (1–6), `"fit"` (`"manual"`, `"adjustSize"`, `"adjustColumns"`, `"adjustColumnsAndSize"`: shrink its - text or add columns to fit its box) and `"showLayerNames": false`. A `"text"` or `"dynamicText"` can take + text or add columns to fit its box) and `"showLayerNames": false`. A `"picture"` takes a `"path"` (a PNG or JPEG + file; it remembers the file) or an `"image"` (base64); `layout.update` with `"path"` reads it again. A `"text"` + or `"dynamicText"` can take `"valign"` (`"top"`, `"middle"`, `"bottom"`), `"lineSpacing"` (0.5–3, default 1) and `"case"` (`"none"`, `"upper"`, `"lower"`; applied when drawn, the text kept as typed). `"grid"` adds a graticule to the frame (`"style": "ticks"` for neatline ticks, `"format": "dms"`, `"edges"`). -5. Adjust with `layout.update` (`{"element": id, "x", "y", "w", "h", "text", "size", "bold", "valign", "lineSpacing", "case"}`). The ids come from the +5. Adjust with `layout.update` (`{"element": id, "x", "y", "w", "h", "text", "size", "bold", "valign", "lineSpacing", "case", "path"}`). The ids come from the results of the earlier calls. 6. `layout.export` `{"path": "map.pdf"}`, or `.png` with a `dpi` (300 for print). Exporting writes a file, so the user is asked first. `layout.close` goes back to the map. diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index dc66a3d538..ae669b492c 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -649,7 +649,22 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu a setting put back to its default is no longer saved. A project that uses them can't be opened by an older RustGIS, and a layout file (`.rgislayout`) with such a text lists them in its header, so an older RustGIS refuses it as well. - **Picture** places a PNG or JPEG. + **Picture** places a PNG or JPEG. A picture added from a file remembers the file. Its image is + kept in the project, so the page doesn't need the file; but a picture that has no image (a + layout another program wrote without one, say) is drawn as a grey box with its file's name in + it, and its file can be read again: select it and use **Choose File…** in the **Format** pane, + which shows the file's name under **File** (the whole path when you hold the pointer over it). + Choosing a file again also brings a picture up to date when its file has changed. Only the + file's name is ever drawn or said, never its folders. A picture that has no image or one that + can't be drawn is drawn as a grey box, and the layout view and every export (PNG, PDF, SVG, + reports, and the Assistant's view of the layout) say so, naming it. A picture is never read from + its file by itself: not when a project or layout opens, nor when it is exported. Scripts give + `layout.update` a picture's `"path"` to read it again (a missing file, one over 16 MB, not a PNG + or JPEG, or one that can't be drawn is refused and the picture left as it was) or its `"image"` + (its file is then no longer remembered); `null` leaves each as it is. Each change is one undo + step. A project with a picture that remembers its file can't be opened by an older RustGIS, and + a layout file with one lists it in its header. In the browser, which has no file paths, a + picture is added from the file's contents and doesn't remember the file. - **Map Series**: one page per feature of an index layer; see [Map series](#map-series) for setup, page names, scales and a locator. - Click an element to select it, drag to move, drag its handles to resize, and edit it in the From ac1d420e319d31d16f450037e4f087bd86278016 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:27:17 -0600 Subject: [PATCH 11/38] fix(layout): a picture's file needs a file name, and an address or a direction mark is never kept MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A picture's file shows only its last part, and none when that part is blank, "." or "..", so a path ending in a folder never shows the folder's name; such a path isn't kept either. One test tells an address from a path, for the kept rule and for the commands' "path": "://" anywhere, or a scheme of two or more characters, a colon and a slash or backslash ("https:/…", "https:\…"). A path holding any character a notice flattens (a control character, a line or paragraph separator, or a mark that turns the direction of text) isn't kept; zero-width characters and the byte-order mark are. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout/picture.rs | 4 +- crates/engine/src/tests/layout_pictures.rs | 11 ++ crates/map/src/layout/picture.rs | 157 +++++++++++++++++---- 3 files changed, 139 insertions(+), 33 deletions(-) diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs index 9095dc09ca..786f0d8e57 100644 --- a/crates/engine/src/cmd/layout/picture.rs +++ b/crates/engine/src/cmd/layout/picture.rs @@ -50,12 +50,12 @@ pub(crate) struct GivenPicture { } /// A command's `path`: none when absent or null, as given when it is text that isn't blank and -/// isn't an address; refused otherwise. +/// isn't an address ([`rustgis_map::layout::picture_path_is_address`]); refused otherwise. pub(crate) fn picture_path_param(p: &Value) -> Result, String> { match p.get("path") { None | Some(Value::Null) => Ok(None), Some(Value::String(path)) if path.trim().is_empty() => Err(PICTURE_PATH.into()), - Some(Value::String(path)) if path.contains("://") => Err(PICTURE_ADDRESS.into()), + Some(Value::String(path)) if rustgis_map::layout::picture_path_is_address(path) => Err(PICTURE_ADDRESS.into()), Some(Value::String(path)) => Ok(Some(path)), Some(_) => Err(PICTURE_PATH.into()), } diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 0ca9c48b0a..34297af2c0 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -465,6 +465,17 @@ fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { assert_eq!(e, said); assert!(state(&s) == before, "{said}: the picture changed"); } + // An address with one slash or with backslashes is refused by both commands, never echoed. + for path in [r"https:\\user:pw@host\x.png", "https:/user:pw@host/x.png"] { + for (command, p) in + [("layout.update", json!({"element": id, "path": path})), ("layout.addElement", json!({"kind": "picture", "path": path}))] + { + let e = s.run(command, &p).unwrap_err(); + assert_eq!(e, "a picture is read from a file on this computer, not a web address", "{command} {path}"); + assert!(!e.contains("pw") && !e.contains("host"), "{command}: {e}"); + assert!(state(&s) == before, "{command} {path} changed the layout"); + } + } // On another kind of element, refused before any file is read; null is not given. let l = s.project.layouts.iter().find(|l| l.name == "L").unwrap(); let text = l.elements.iter().find(|e| e.kind.code() == "text").unwrap().id; diff --git a/crates/map/src/layout/picture.rs b/crates/map/src/layout/picture.rs index e256c811ac..db64407222 100644 --- a/crates/map/src/layout/picture.rs +++ b/crates/map/src/layout/picture.rs @@ -6,21 +6,44 @@ use super::*; /// names another file). pub const MAX_PICTURE_SOURCE: usize = 4096; -/// Whether a picture keeps `path` as its file: when it isn't blank, holds no `://` (an address, -/// which could carry a login), no control character and none of U+202A–U+202E or U+2066–U+2069 -/// (which turn the direction of text), and is at most [`MAX_PICTURE_SOURCE`] bytes. A kept path is -/// kept exactly as given, neither trimmed nor resolved. A name holding a colon (`a:b.png`) is kept. +/// Whether a picture keeps `path` as its file: when it names a file ([`picture_file_name`]; a path +/// ending in a folder doesn't), isn't an address ([`picture_path_is_address`]; one could carry a +/// login), holds no character [`rustgis_data::io::dbf_notice_char`] flattens in a notice (a control +/// character, U+2028 or U+2029, which break a line, or U+061C, U+200E, U+200F, U+202A–U+202E or +/// U+2066–U+2069, which turn the direction of text), and is at most [`MAX_PICTURE_SOURCE`] bytes. +/// Zero-width characters (U+200B–U+200D) and U+FEFF are kept: they are part of real file names, +/// and none of them breaks a line or reorders text. A kept path is kept exactly as given, neither +/// trimmed nor resolved. A name holding a colon (`a:b.png`) is kept. pub fn picture_source_kept(path: &str) -> bool { - !path.trim().is_empty() - && path.len() <= MAX_PICTURE_SOURCE - && !path.contains("://") - && !path.chars().any(|c| c.is_control() || matches!(c, '\u{202A}'..='\u{202E}' | '\u{2066}'..='\u{2069}')) + path.len() <= MAX_PICTURE_SOURCE + && picture_file_name(path).is_some() + && !picture_path_is_address(path) + && path.chars().all(|c| rustgis_data::io::dbf_notice_char(c) == c) } -/// The name a picture shows of its file `source`: its last part after `/` or `\` that isn't blank, -/// trimmed; none when every part is blank. The folders are never shown. +/// Whether `path` reads as an address, not a file: it holds `://` anywhere, or begins (after +/// leading blanks) with a scheme of two or more characters (a letter, then letters, digits, `+`, +/// `-` or `.`), a colon and a `/` or `\`. One letter is a drive (`C:\a.png`), and a name with a +/// colon and no separator after it (`a:b.png`) is a file. A relative path whose first folder +/// ends in a colon reads as an address: give it as `./folder:/a.png`. `mailto:a@b`, +/// `data:image/png;base64,…` and `user:pw@host:/a.png` are left as paths: no rule tells them from +/// a file name holding a colon, and none opens as a file unless it is one. +pub fn picture_path_is_address(path: &str) -> bool { + if path.contains("://") { + return true; + } + let Some((scheme, rest)) = path.trim_start().split_once(':') else { return false }; + let mut chars = scheme.chars(); + scheme.len() >= 2 + && chars.next().is_some_and(|c| c.is_ascii_alphabetic()) + && chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.')) + && rest.starts_with(['/', '\\']) +} + +/// The name a picture shows of its file `source`: its last part after `/` or `\`, trimmed; none +/// when that is blank, `.` or `..` (the path ends in a folder). The folders are never shown. pub fn picture_file_name(source: &str) -> Option<&str> { - source.rsplit(['/', '\\']).map(str::trim).find(|part| !part.is_empty()) + source.rsplit(['/', '\\']).next().map(str::trim).filter(|n| !matches!(*n, "" | "." | "..")) } /// A picture's file as a file holds it: text as it is (whether it is kept is for `Layout::clamp`), @@ -70,43 +93,115 @@ mod tests { assert_eq!(serde_json::to_string(&k).unwrap(), with); } - /// What of a path is kept: not blank, not an address, no control or direction-override - /// characters, at most MAX_PICTURE_SOURCE bytes; a POSIX name with a colon is kept. + /// The paths a picture keeps as its file: each with a file name; a POSIX name with a colon and + /// a zero-width character or byte-order mark are kept; a blank, an address, a folder, a control + /// or direction character, or more than MAX_PICTURE_SOURCE bytes isn't. #[test] fn a_pictures_file_is_kept_only_when_it_is_a_plain_path() { - for kept in ["/data/logos/north.png", r"\\server\share\logo.jpg", "logo.png", "a:b.png", " spaced .png", "logo@2x.png"] { - assert!(picture_source_kept(kept), "{kept}"); + let kept = [ + "/data/logos/north.png", + r"\\server\share\logo.jpg", + "logo.png", + "a:b.png", + " spaced .png", + "logo@2x.png", + "\u{fc}.png", + "a\u{200D}b.png", + "a\u{200C}b.png", + "a\u{200B}b.png", + "\u{FEFF}logo.png", + ]; + for path in kept.into_iter().chain(NAMED.iter().map(|(path, _)| *path)) { + assert!(picture_source_kept(path), "{path:?}"); } let long = format!("/{}", "d".repeat(MAX_PICTURE_SOURCE)); - for not in [ - "", - " ", + let not = [ "https://user:secret@example.invalid/logo.png", "file:///data/x.png", "a\u{7}b.png", "a\nb.png", "x\u{202E}gnp.png", + "a\u{061C}b.png", + "a\u{200E}b.png", + "a\u{200F}b.png", + "logo\u{2028}b.png", + "logo\u{2029}b.png", + "a\u{2066}b.png", long.as_str(), - ] { - assert!(!picture_source_kept(not), "{not:?}"); + ]; + for path in not.into_iter().chain(UNNAMED).chain(ADDRESSES) { + assert!(!picture_source_kept(path), "{path:?}"); } assert!(picture_source_kept(&format!("/{}", "d".repeat(MAX_PICTURE_SOURCE - 1)))); } - /// The name a picture shows of its file: the last part, never the folders. + /// Paths, and the name a picture shows of each. + const NAMED: [(&str, &str); 9] = [ + ("/data/logos/north.png", "north.png"), + (r"C:\maps\inset.png", "inset.png"), + (r"\\server\share\logo.jpg", "logo.jpg"), + ("logo.png", "logo.png"), + (" /x/ name.png ", "name.png"), + ("a:b.png", "a:b.png"), + ("C:inset.png", "C:inset.png"), + ("a.png:stream", "a.png:stream"), + ("...", "..."), + ]; + /// Paths that end in a folder or in nothing: no name is shown, and none is kept. + const UNNAMED: [&str; 10] = ["/home/someone/", r"C:\maps\", "dir/", "///", "", " ", "/data/logos/..", "x/.", "/x/ ", ".."]; + + /// The name a picture shows of its file: the last part, never the folders, and none when the + /// last part is blank, `.` or `..`. #[test] fn picture_file_names_hide_their_folders() { - for (source, name) in [ - ("/data/logos/north.png", Some("north.png")), - (r"\\server\share\logo.jpg", Some("logo.jpg")), - (r"C:\maps\inset.png", Some("inset.png")), - ("logo.png", Some("logo.png")), - ("dir/", Some("dir")), - (" /x/ name.png ", Some("name.png")), - ("///", None), - ("", None), + for (source, name) in NAMED { + assert_eq!(picture_file_name(source), Some(name), "{source:?}"); + } + for source in UNNAMED { + assert_eq!(picture_file_name(source), None, "{source:?}"); + } + } + + /// Paths that read as an address. + const ADDRESSES: [&str; 9] = [ + "https://user:pw@host/a.png", + "file:///data/x.png", + "/vsicurl/https://host/a.png", + r"https:\\user:pw@host\x.png", + r"https:\user:pw@host\x", + "https:/user:pw@host/x.png", + "file:/data/x.png", + " s3:/bucket/a.png", + "ab:/c.png", + ]; + + /// An address is `://` anywhere, or a scheme of two or more characters, a colon and a + /// separator; a drive, a share, a name with a colon, and the forms no rule can tell from a + /// file name, are paths. + #[test] + fn an_address_is_told_from_a_path() { + for path in ADDRESSES { + assert!(picture_path_is_address(path), "{path:?}"); + } + for path in [ + r"C:\a.png", + "C:/a.png", + r"c:\\maps\\a.png", + r"\\server\share\a.png", + "//server/share/a.png", + r"\\?\C:\a.png", + "/data/a:b/c.png", + "logos/x:y/a.png", + "a:b.png", + "ab:c.png", + "logo@2x.png", + "./folder:/a.png", + "mailto:a@b", + "data:image/png;base64,AAAA", + "user:pw@host:/a.png", + "", ] { - assert_eq!(picture_file_name(source), name, "{source}"); + assert!(!picture_path_is_address(path), "{path:?}"); } } From 3805a7887317953ee2d3868d6fc72159b523064e Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:36:54 -0600 Subject: [PATCH 12/38] fix(layout): say why a picture's file isn't remembered or its image can't be drawn An image refused or noticed as one that can't be drawn may be damaged, declare more than 20000 pixels a side, or need more than the decoder's 512 MB once decoded: each refusal and notice now names all three. A picture read from a file whose path isn't kept says the path's characters, its length or its missing file name may be why. In the browser, which has no file paths, the grey-box notice says to give a picture its image again rather than to read its file. A command's image is checked once, without copying it into a JSON value. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/graphics.rs | 2 +- crates/engine/src/cmd/layout/picture.rs | 13 ++++++----- crates/engine/src/tests/layout_pictures.rs | 5 +++-- crates/render/src/layout/picture.rs | 25 ++++++++++++++++------ crates/render/src/picture.rs | 2 +- 5 files changed, 31 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/graphics.rs b/crates/engine/src/cmd/graphics.rs index 802922a339..c05f565a2a 100644 --- a/crates/engine/src/cmd/graphics.rs +++ b/crates/engine/src/cmd/graphics.rs @@ -417,7 +417,7 @@ pub(crate) fn picture_file(path: &str) -> Result { } /// `b64` when it is at most 16 MiB of a PNG or JPEG image. -fn checked_picture(b64: String) -> Result { +pub(crate) fn checked_picture(b64: String) -> Result { if b64.len() > MAX_PICTURE / 3 * 4 + 4 { return Err("the picture is too large".into()); } diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs index 786f0d8e57..69e93fdd94 100644 --- a/crates/engine/src/cmd/layout/picture.rs +++ b/crates/engine/src/cmd/layout/picture.rs @@ -15,18 +15,21 @@ pub(in crate::cmd::layout) const PICTURE_ADDRESS: &str = "a picture is read from /// Both `image` and `path` given. pub(in crate::cmd::layout) const PICTURE_BOTH: &str = "give a picture an image or a path, not both"; -/// A picture whose header reads but whose image can't be drawn. +/// A picture whose header reads but whose image can't be drawn: damaged, declaring too many +/// pixels a side, or needing more memory once decoded than the decoder may take. pub(in crate::cmd::layout) fn picture_undrawn() -> String { format!( - "the picture can't be drawn: its image is damaged or larger than {} pixels a side", - rustgis_render::layout::PICTURE_MAX_DECLARED + "the picture can't be drawn: its image is damaged, or too large (over {} pixels a side, or over {} MB once decoded)", + rustgis_render::layout::PICTURE_MAX_DECLARED, + rustgis_render::layout::PICTURE_MAX_DECODED_MB ) } /// A picture read from a file whose path isn't kept as its file. pub(in crate::cmd::layout) fn picture_unremembered() -> String { format!( - "the picture is read, but its file isn't remembered: a path with control characters or over {} bytes isn't kept", + "the picture is read, but its file isn't remembered: a path with control or direction characters, over {} bytes or \ + without a file name isn't kept", rustgis_map::layout::MAX_PICTURE_SOURCE ) } @@ -78,7 +81,7 @@ pub(in crate::cmd::layout) fn picture_given(p: &Value) -> Result { - GivenPicture { image: crate::cmd::graphics::picture(&json!({"image": image}))?, source: None, unremembered: false } + GivenPicture { image: crate::cmd::graphics::checked_picture(image.trim().to_string())?, source: None, unremembered: false } } (Some(_), _) => return Err(PICTURE_IMAGE.into()), (None, Some(path)) => { diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 34297af2c0..3a525e0ce1 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -231,7 +231,8 @@ fn pictures_save_and_say_as_before() { }; let images = [(PIN_PNG, "the PNG"), (PIN_JPEG, "the JPEG"), (huge.as_str(), "the 30000 x 1 PNG"), (damaged.as_str(), "the damaged PNG")]; - const UNDRAWN: &str = "the picture can't be drawn: its image is damaged or larger than 20000 pixels a side"; + const UNDRAWN: &str = + "the picture can't be drawn: its image is damaged, or too large (over 20000 pixels a side, or over 512 MB once decoded)"; let rectangle = |key: &str, v: Value| { let mut p = json!({"kind": "rectangle", "x": 10, "y": 10, "w": 20, "h": 20}); p[key] = v; @@ -436,7 +437,7 @@ fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { (picture_in(s, "L", &id), x, serde_json::to_value(&s.project).unwrap(), s.undo_depth(), s.dirty()) }; let before = state(&s); - let undrawn = "the picture can't be drawn: its image is damaged or larger than 20000 pixels a side"; + let undrawn = "the picture can't be drawn: its image is damaged, or too large (over 20000 pixels a side, or over 512 MB once decoded)"; let not_a_path = "path is the path of a PNG or JPEG file"; for (path, said) in [ // `read_picture_file`'s own "{path}: …". diff --git a/crates/render/src/layout/picture.rs b/crates/render/src/layout/picture.rs index 370896a919..a7e6636d98 100644 --- a/crates/render/src/layout/picture.rs +++ b/crates/render/src/layout/picture.rs @@ -6,6 +6,8 @@ use rustgis_map::layout::{picture_file_name, picture_source_kept}; /// The most pixels a side a layout picture's image may declare and still be drawn. pub const PICTURE_MAX_DECLARED: u32 = crate::picture::MAX_DECLARED; +/// The most memory, in MiB, a layout picture's image may take once decoded and still be drawn. +pub const PICTURE_MAX_DECODED_MB: u64 = crate::picture::MAX_ALLOC >> 20; /// Layout pictures named in a notice, before "and N more"; and the characters of a picture's /// name or file name a notice shows before cutting it with "…". @@ -62,7 +64,8 @@ pub(super) fn draw_picture_box(pm: &mut Canvas, r: Rect, source: Option<&str>, p pub enum PictureLoss { /// Its image is empty. NoImage, - /// Its image doesn't draw: damaged, or larger than [`PICTURE_MAX_DECLARED`] pixels a side. + /// Its image doesn't draw: damaged, or too large (over [`PICTURE_MAX_DECLARED`] pixels a side, + /// or over [`PICTURE_MAX_DECODED_MB`] MiB once decoded). Undrawable, } @@ -100,6 +103,14 @@ fn notice_cut(s: &str) -> String { } } +/// How a notice says to give a picture its image again: in the browser, which has no file paths, +/// by its image; elsewhere, from its file. +const WAY_BACK: &str = if cfg!(target_arch = "wasm32") { + "give one its image again with layout.update and \"image\"" +} else { + "read one from its file again with layout.update and \"path\" (Choose File… in the Format pane)" +}; + /// What is said of `gaps`: one notice for each [`PictureLoss`] among them, in its order, with the /// pictures counted and the first ten named, each with its file's name when it has one. pub fn pictures_notices(gaps: &[PictureGap]) -> Vec { @@ -122,13 +133,13 @@ pub fn pictures_notices(gaps: &[PictureGap]) -> Vec { let what = match why { PictureLoss::NoImage => "have no image".to_string(), PictureLoss::Undrawable => { - format!("have an image that can't be drawn (damaged, or larger than {PICTURE_MAX_DECLARED} pixels a side)") + format!( + "have an image that can't be drawn (damaged, or too large: over {PICTURE_MAX_DECLARED} pixels a side \ + or over {PICTURE_MAX_DECODED_MB} MB once decoded)" + ) } }; - Some(format!( - "{n} layout picture(s) {what} and are drawn as a grey box: {named}; read one from its file again with \ - layout.update and \"path\" (Choose File… in the Format pane)" - )) + Some(format!("{n} layout picture(s) {what} and are drawn as a grey box: {named}; {WAY_BACK}")) }) .collect() } @@ -245,7 +256,7 @@ mod tests { assert!(said[0].contains("Logo 10 (10, north.png); and 2 more; read one"), "{}", said[0]); assert!(!said[0].contains("Logo 11"), "{}", said[0]); assert!(said[0].contains("; and 2 more; read one from its file again with layout.update and \"path\""), "{}", said[0]); - let undrawable = "1 layout picture(s) have an image that can't be drawn (damaged, or larger than 20000 pixels a side)"; + let undrawable = "1 layout picture(s) have an image that can't be drawn (damaged, or too large: over 20000 pixels a side or over 512 MB once decoded)"; assert!(said[1].starts_with(undrawable), "{}", said[1]); assert!(said[1].contains("drawn as a grey box: Inset (13); read one"), "{}", said[1]); assert!(pictures_notices(&[]).is_empty()); diff --git a/crates/render/src/picture.rs b/crates/render/src/picture.rs index 446f3c450a..e89ba8cc68 100644 --- a/crates/render/src/picture.rs +++ b/crates/render/src/picture.rs @@ -21,7 +21,7 @@ const MAX_SIDE: u32 = 4096; /// Pictures declaring more pixels per side than this aren't decoded at all. pub(crate) const MAX_DECLARED: u32 = 20_000; /// Most memory a picture's decoder may allocate. -const MAX_ALLOC: u64 = 512 << 20; +pub(crate) const MAX_ALLOC: u64 = 512 << 20; /// Decoded pictures kept between frames, and the most memory they may hold together (their pixels /// and the base64 each keeps). const CACHE: usize = 32; From c9411a9e1173ba5c42132567ce8558cda0c33d9d Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:41:23 -0600 Subject: [PATCH 13/38] fix(layout): every layout.update leaves its Undo step An update that gives a picture only a null image or path leaves one Undo step, as every other update does, including one whose keys are all null. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout/update.rs | 8 -------- crates/engine/src/tests/layout_pictures.rs | 8 ++++++-- 2 files changed, 6 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index df409ba842..e2dd5c8fbe 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -467,14 +467,6 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { _ => None, }; let unremembered = new_picture.as_ref().is_some_and(|g| g.unremembered); - // Only a picture's image or path, each null: nothing is given, so there is no step to undo. - let only_null_picture = p.as_object().is_some_and(|o| { - o.keys().any(|k| matches!(k.as_str(), "image" | "path")) - && o.iter().all(|(k, v)| matches!(k.as_str(), "layout" | "element") || (matches!(k.as_str(), "image" | "path") && v.is_null())) - }); - if only_null_picture { - s.request_only = true; - } let l = active(s, p)?; let e = l.element_mut(id).ok_or_else(|| format!("no element {id}"))?; // A text or scale bar with no ink isn't measured: given a colour that shows it, it is told diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 3a525e0ce1..bed8f1a3f1 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -393,7 +393,8 @@ fn a_picture_is_read_again_from_a_file_and_relinked() { assert_eq!(picture_in(&s, "L", &id), (third_b64.clone(), None)); let (before, depth) = (serde_json::to_value(&s.project).unwrap(), s.undo_depth()); s.run("layout.update", &json!({"element": id, "path": null, "image": null})).unwrap(); - assert_eq!((serde_json::to_value(&s.project).unwrap(), s.undo_depth()), (before, depth), "null changes nothing"); + // Null changes nothing, and leaves its Undo step as every update does. + assert_eq!((serde_json::to_value(&s.project).unwrap(), s.undo_depth()), (before, depth + 1), "null changes nothing"); assert_eq!(picture_in(&s, "L", &id), (third_b64, None)); // Any other update keeps its Undo step, as it always has, even one that changes nothing. let x = |s: &Session| s.project.layouts.iter().find(|l| l.name == "L").unwrap().element(id.as_u64().unwrap() as u32).unwrap().x; @@ -486,8 +487,11 @@ fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { assert_eq!(e, "only pictures take an image or a path"); assert!(state(&s) == before, "{key} on a text changed it"); } + let depth = s.undo_depth(); s.run("layout.update", &json!({"element": text, "path": null, "image": null})).unwrap(); - assert!(state(&s) == before, "null picture keys on a text changed it"); + let after = state(&s); + assert!((&after.0, after.1, &after.2) == (&before.0, before.1, &before.2), "null picture keys on a text changed it"); + assert_eq!(s.undo_depth(), depth + 1); // Locked, it is refused before its file is read. s.run("layout.update", &json!({"element": id, "locked": true})).unwrap(); let before = state(&s); From ac3f2574751c6c2bebe877256968bd7d0f974978 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:49:53 -0600 Subject: [PATCH 14/38] fix(layout): a report's picture notice keeps its layout's name A picture a report draws as a grey box is named with its layout as a part of its own, so a long element name is cut by itself and the layout is still named. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/report.rs | 2 +- crates/render/src/layout/picture.rs | 50 +++++++++++++++++++++++++---- 2 files changed, 44 insertions(+), 8 deletions(-) diff --git a/crates/engine/src/cmd/report.rs b/crates/engine/src/cmd/report.rs index 18943e9f2a..7f4532cdcc 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1255,7 +1255,7 @@ fn say_report_pictures(s: &mut Session, pages: &[rustgis_render::report::Page], seen.push(*li); let Some(layout) = s.project.layouts.get(*li) else { continue }; for mut gap in rustgis_render::layout::pictures_not_drawn(layout) { - gap.name = format!("{} in layout '{}'", gap.name, layout.name); + gap.layout = Some(layout.name.clone()); gaps.push(gap); } } diff --git a/crates/render/src/layout/picture.rs b/crates/render/src/layout/picture.rs index a7e6636d98..276f76c67d 100644 --- a/crates/render/src/layout/picture.rs +++ b/crates/render/src/layout/picture.rs @@ -74,6 +74,8 @@ pub enum PictureLoss { pub struct PictureGap { pub id: u32, pub name: String, + /// The name of the layout it is in, when a notice names it (a report's, which draws several). + pub layout: Option, /// The name of the file it was read from, when it keeps one; never its folders. pub file: Option, pub why: PictureLoss, @@ -89,7 +91,7 @@ pub fn pictures_not_drawn(layout: &Layout) -> Vec { } let why = if image.trim().is_empty() { PictureLoss::NoImage } else { PictureLoss::Undrawable }; let file = e.kind.picture_source().and_then(picture_file_name).map(String::from); - Some(PictureGap { id: e.id, name: e.name.clone(), file, why }) + Some(PictureGap { id: e.id, name: e.name.clone(), layout: None, file, why }) }); gaps.collect() } @@ -112,7 +114,8 @@ const WAY_BACK: &str = if cfg!(target_arch = "wasm32") { }; /// What is said of `gaps`: one notice for each [`PictureLoss`] among them, in its order, with the -/// pictures counted and the first ten named, each with its file's name when it has one. +/// pictures counted and the first ten named, each with its layout's name and its file's name when it +/// has them. pub fn pictures_notices(gaps: &[PictureGap]) -> Vec { [PictureLoss::NoImage, PictureLoss::Undrawable] .into_iter() @@ -121,9 +124,15 @@ pub fn pictures_notices(gaps: &[PictureGap]) -> Vec { if these.is_empty() { return None; } - let named = these.iter().take(NAMED).map(|g| match &g.file { - Some(file) => format!("{} ({}, {})", notice_cut(&g.name), g.id, notice_cut(file)), - None => format!("{} ({})", notice_cut(&g.name), g.id), + let named = these.iter().take(NAMED).map(|g| { + let name = match &g.layout { + Some(layout) => format!("{} in layout '{}'", notice_cut(&g.name), notice_cut(layout)), + None => notice_cut(&g.name), + }; + match &g.file { + Some(file) => format!("{name} ({}, {})", g.id, notice_cut(file)), + None => format!("{name} ({})", g.id), + } }); let mut named = named.collect::>().join("; "); if these.len() > NAMED { @@ -246,9 +255,15 @@ mod tests { #[test] fn the_picture_notices_count_and_name_each_kind() { let mut gaps: Vec = (1..=12) - .map(|id| PictureGap { id, name: format!("Logo {id}"), file: Some("north.png".to_string()), why: PictureLoss::NoImage }) + .map(|id| PictureGap { + id, + name: format!("Logo {id}"), + layout: None, + file: Some("north.png".to_string()), + why: PictureLoss::NoImage, + }) .collect(); - gaps.push(PictureGap { id: 13, name: "Inset".to_string(), file: None, why: PictureLoss::Undrawable }); + gaps.push(PictureGap { id: 13, name: "Inset".to_string(), layout: None, file: None, why: PictureLoss::Undrawable }); let said = pictures_notices(&gaps); assert_eq!(said.len(), 2, "{said:?}"); let head = "12 layout picture(s) have no image and are drawn as a grey box: Logo 1 (1, north.png); "; @@ -262,6 +277,27 @@ mod tests { assert!(pictures_notices(&[]).is_empty()); } + /// A long name is cut to 100 characters and "…"; in a report, the name and its layout's are + /// each cut, so the layout is still named. + #[test] + fn a_long_picture_name_is_cut_and_keeps_its_layout() { + let long = "n".repeat(150); + let gap = |layout: Option<&str>| PictureGap { + id: 4, + name: long.clone(), + layout: layout.map(String::from), + file: Some("north.png".to_string()), + why: PictureLoss::NoImage, + }; + let alone = pictures_notices(&[gap(None)]); + let cut = format!(": {}… (4, north.png);", "n".repeat(100)); + assert!(alone[0].contains(&cut), "{}", alone[0]); + let in_report = pictures_notices(&[gap(Some("L"))]); + assert!(in_report[0].contains(&format!("{}… in layout 'L' (4, north.png);", "n".repeat(100))), "{}", in_report[0]); + let long_layout = pictures_notices(&[PictureGap { layout: Some("l".repeat(150)), ..gap(None) }]); + assert!(long_layout[0].contains(&format!(" in layout '{}…' (4, north.png);", "l".repeat(100))), "{}", long_layout[0]); + } + /// A picture is decoded once while it is unchanged, however often its page is drawn and /// checked. #[test] From 3a33d6b65e519573a70c95362e628f0df60f20b2 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:54:01 -0600 Subject: [PATCH 15/38] test(layout): a region's grey picture, a duplicated picture's file, and a file not kept on every platform The Assistant's view of a region holding one grey picture says it and only it. A duplicated picture keeps its file, and a project holding only the copy still requires the capability. A picture read from a file whose name holds a direction override is read and its file not remembered on every system; a name with a bell is a second case where the system allows it. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/tests/layout_pictures.rs | 49 ++++++++++++++++------ 1 file changed, 37 insertions(+), 12 deletions(-) diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index bed8f1a3f1..7d0a6ccbe7 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -519,22 +519,42 @@ fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { } /// A path the rule doesn't keep: the picture is read, its file not remembered, and that is said. -#[cfg(all(unix, not(target_arch = "wasm32")))] +#[cfg(not(target_arch = "wasm32"))] #[test] fn a_path_that_is_not_kept_is_read_and_said() { let (dir, mut s) = picture_world("a-path-that-is-not-kept-is-read-and-said"); - let (first, _) = png_file(&dir, "first.png", (40, 20), [0x1F, 0x5C, 0x84]); - let (odd, odd_b64) = png_file(&dir, "logo\u{7}.png", (20, 20), [0x22, 0x88, 0x22]); + // A direction override is a file name every system allows; a bell, only some. + let names: &[&str] = if cfg!(unix) { &["logo\u{202E}.png", "logo\u{7}.png"] } else { &["logo\u{202E}.png"] }; let unremembered = |s: &Session, mark| s.notices_since(mark).iter().filter(|n| n.text.contains("isn't remembered")).count(); - let mark = s.notice_mark(); - let id = s.run("layout.addElement", &json!({"kind": "picture", "path": odd})).unwrap()["element"].clone(); - assert_eq!(picture_in(&s, "L", &id), (odd_b64.clone(), None)); - assert_eq!(unremembered(&s, mark), 1); - let kept = s.run("layout.addElement", &json!({"kind": "picture", "path": first})).unwrap()["element"].clone(); - let mark = s.notice_mark(); - s.run("layout.update", &json!({"element": kept, "path": odd})).unwrap(); - assert_eq!(picture_in(&s, "L", &kept), (odd_b64, None)); - assert_eq!(unremembered(&s, mark), 1); + for (i, name) in names.iter().enumerate() { + let (first, _) = png_file(&dir, &format!("first{i}.png"), (40, 20), [0x1F, 0x5C, 0x84]); + let (odd, odd_b64) = png_file(&dir, name, (20, 20), [0x22, 0x88, 0x22]); + let mark = s.notice_mark(); + let id = s.run("layout.addElement", &json!({"kind": "picture", "path": odd})).unwrap()["element"].clone(); + assert_eq!(picture_in(&s, "L", &id), (odd_b64.clone(), None), "{name:?}"); + assert_eq!(unremembered(&s, mark), 1, "{name:?}"); + let kept = s.run("layout.addElement", &json!({"kind": "picture", "path": first})).unwrap()["element"].clone(); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": kept, "path": odd})).unwrap(); + assert_eq!(picture_in(&s, "L", &kept), (odd_b64, None), "{name:?}"); + assert_eq!(unremembered(&s, mark), 1, "{name:?}"); + } +} + +/// A duplicated picture keeps its file, and a project holding only the copy still requires the +/// capability. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_duplicated_picture_keeps_its_file() { + let (dir, mut s) = picture_world("a-duplicated-picture-keeps-its-file"); + let (first, first_b64) = png_file(&dir, "first.png", (40, 20), [0x1F, 0x5C, 0x84]); + let id = s.run("layout.addElement", &json!({"kind": "picture", "path": first})).unwrap()["element"].clone(); + let copy = s.run("layout.duplicateElement", &json!({"element": id})).unwrap()["element"].clone(); + assert_ne!(copy, id); + assert_eq!(picture_in(&s, "L", ©), (first_b64, Some(first))); + s.run("layout.removeElement", &json!({"element": id})).unwrap(); + let requires = serde_json::to_value(&s.project).unwrap()["requires"].clone(); + assert!(requires.as_array().is_some_and(|r| r.contains(&json!("layout-picture-source"))), "{requires}"); } /// A project whose pictures' files are of the wrong kind, blank, an address, too long or with @@ -660,6 +680,11 @@ fn a_picture_drawn_as_a_grey_box_is_said_by_every_export() { ); assert!(said.iter().all(|n| n.starts_with("The report: ") == *in_report), "{route}: {said:?}"); } + // The Assistant's view of a region holding only "Logo" says it, and only it. + let logo = said(&mut s, &|s| drop(crate::cmd::layout::layout_png(s, 0, 36.0, Some([5.0, 5.0, 40.0, 25.0])).unwrap())); + assert_eq!(logo.len(), 1, "{logo:?}"); + assert!(logo[0].starts_with("1 layout picture(s) have no image") && logo[0].contains("Logo ("), "{logo:?}"); + assert!(!logo[0].contains("Blank") && !logo[0].contains("Broken"), "{logo:?}"); // The Assistant's view of a region holding only "Fine" says nothing of pictures. let fine = said(&mut s, &|s| drop(crate::cmd::layout::layout_png(s, 0, 36.0, Some([145.0, 245.0, 40.0, 25.0])).unwrap())); assert!(fine.is_empty(), "{fine:?}"); From 8b6b7957a6cd2ca85076a0026fa510c140aa915f Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Fri, 27 Nov 2026 23:54:45 -0600 Subject: [PATCH 16/38] docs(layout): what a picture's file keeps and shows The developer notes name every source that isn't kept: blank, an address, over 4096 bytes, without a file name, or holding control or direction characters. The user guide says the file's name is what the page and the picture's notices show, never its folders. The Assistant's view of a layout says it names pictures drawn as a grey box. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout/export.rs | 3 ++- crates/map/src/layout.rs | 3 ++- crates/render/src/layout/tests.rs | 2 +- docs/maintaining.md | 4 ++-- docs/user-guide/layouts.md | 22 +++++++++++----------- 5 files changed, 18 insertions(+), 16 deletions(-) diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index bbd0843cc7..55c7f7f9a3 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -44,7 +44,8 @@ pub fn layout_bytes_with( /// Layout `li`'s current page as a PNG at `dpi`, or only its part in `region` (`[x, y, w, h]` in /// millimetres from the page's top left), drawn at that `dpi` rather than cut out of the whole /// page: what the assistant's `view_map` shows of a layout. It says what exporting the page says -/// of it: texts cut off, named fonts still being read, frames drawn without their cast shadows. +/// of it: texts cut off, named fonts still being read, frames drawn without their cast shadows, +/// pictures drawn as a grey box. pub fn layout_png(s: &mut Session, li: usize, dpi: f64, region: Option<[f64; 4]>) -> Result, String> { let layout = s.project.layouts.get(li).ok_or("no layout")?.clone(); if let Some(note) = named_fonts_unread(&layout) { diff --git a/crates/map/src/layout.rs b/crates/map/src/layout.rs index f006d6734b..25dc4fc7e8 100644 --- a/crates/map/src/layout.rs +++ b/crates/map/src/layout.rs @@ -664,7 +664,8 @@ impl Layout { *width = finite_or(*width, 1.0).clamp(0.0, 50.0) } ElementKind::Line { width, .. } => *width = finite_or(*width, 1.0).clamp(0.1, 50.0), - // A picture's file `picture_source_kept` doesn't keep (only a hand-edited one) is dropped. + // A picture's file `picture_source_kept` doesn't keep (only a hand-edited one) is + // dropped. ElementKind::Picture { source, .. } if source.as_deref().is_some_and(|s| !picture_source_kept(s)) => *source = None, _ => {} } diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 484ac90f2d..0b5345f289 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -5871,7 +5871,7 @@ const PINNED_PICTURE_PIXELS: [u64; 15] = [ /// every page at 96 dpi, and pages 1 (a PNG in a wider box) and 4 (an empty image's grey box and /// its word) at 300 dpi too, which holds the scaling of the image and of the grey box's outline and /// word with the resolution: thirteen drawings. Then a map graphic's picture as a map draws it -/// (`picture::draw`, which keeps decoded pictures as the layout's will): the PNG stretched over 60 +/// (`picture::draw`, which keeps decoded pictures as a layout's are): the PNG stretched over 60 /// x 30 pixels, and the JPEG at half opacity over 20 x 40. In a process of its own, told to use the /// built-in face before any text. #[cfg(not(target_arch = "wasm32"))] diff --git a/docs/maintaining.md b/docs/maintaining.md index 04e7a99167..4998383244 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -311,8 +311,8 @@ word Picture for a picture with no image and saving it again without its file. A ignores both; `layout.addElement` with a `path` needs nothing (an older reader adds the same picture), and `null` needs nothing. A saved `layout.import` or `report.existingTemplate` whose `text` has such a picture requires it as well, and a layout file (`.rgislayout`) with one lists it -in its header. A source that is blank, an address, over 4096 bytes or holding control characters -isn't kept, so it needs nothing. +in its header. A source that is blank, an address, over 4096 bytes, without a file name, or holding +control or direction characters isn't kept, so it needs nothing. Projects with a scale bar that has subdivisions, divisions before zero, labels below, a unit label of its own or placed elsewhere, decimals or a fit other than the defaults diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index ae669b492c..bef187ab78 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -654,17 +654,17 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu layout another program wrote without one, say) is drawn as a grey box with its file's name in it, and its file can be read again: select it and use **Choose File…** in the **Format** pane, which shows the file's name under **File** (the whole path when you hold the pointer over it). - Choosing a file again also brings a picture up to date when its file has changed. Only the - file's name is ever drawn or said, never its folders. A picture that has no image or one that - can't be drawn is drawn as a grey box, and the layout view and every export (PNG, PDF, SVG, - reports, and the Assistant's view of the layout) say so, naming it. A picture is never read from - its file by itself: not when a project or layout opens, nor when it is exported. Scripts give - `layout.update` a picture's `"path"` to read it again (a missing file, one over 16 MB, not a PNG - or JPEG, or one that can't be drawn is refused and the picture left as it was) or its `"image"` - (its file is then no longer remembered); `null` leaves each as it is. Each change is one undo - step. A project with a picture that remembers its file can't be opened by an older RustGIS, and - a layout file with one lists it in its header. In the browser, which has no file paths, a - picture is added from the file's contents and doesn't remember the file. + Choosing a file again also brings a picture up to date when its file has changed. Only the file's + name is drawn on the page or named in a notice about the picture, never its folders. A picture + that has no image or one that can't be drawn is drawn as a grey box, and the layout view and every + export (PNG, PDF, SVG, reports, and the Assistant's view of the layout) say so, naming it. A + picture is never read from its file by itself: not when a project or layout opens, nor when it is + exported. Scripts give `layout.update` a picture's `"path"` to read it again (a missing file, one + over 16 MB, not a PNG or JPEG, or one that can't be drawn is refused and the picture left as it + was) or its `"image"` (its file is then no longer remembered); `null` leaves each as it is. Each + change is one undo step. A project with a picture that remembers its file can't be opened by an + older RustGIS, and a layout file with one lists it in its header. In the browser, which has no + file paths, a picture is added from the file's contents and doesn't remember the file. - **Map Series**: one page per feature of an index layer; see [Map series](#map-series) for setup, page names, scales and a locator. - Click an element to select it, drag to move, drag its handles to resize, and edit it in the From 7d52c8a2238fd4121106eefec00fa0b2e6809bd4 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:32:17 -0600 Subject: [PATCH 17/38] docs(layout): wrap the picture notices' doc comment at 100 columns Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout/picture.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/render/src/layout/picture.rs b/crates/render/src/layout/picture.rs index 276f76c67d..41d0157d50 100644 --- a/crates/render/src/layout/picture.rs +++ b/crates/render/src/layout/picture.rs @@ -114,8 +114,8 @@ const WAY_BACK: &str = if cfg!(target_arch = "wasm32") { }; /// What is said of `gaps`: one notice for each [`PictureLoss`] among them, in its order, with the -/// pictures counted and the first ten named, each with its layout's name and its file's name when it -/// has them. +/// pictures counted and the first ten named, each with its layout's name and its file's name +/// when it has them. pub fn pictures_notices(gaps: &[PictureGap]) -> Vec { [PictureLoss::NoImage, PictureLoss::Undrawable] .into_iter() From 0ff0927c448d34c192b6106571a9820b24bdbc26 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 00:58:09 -0600 Subject: [PATCH 18/38] perf(render): the size a layout picture is drawn from is read off its decoded copy The Format pane asks it of a picture under the element it edits; the page has already decoded that picture, so it isn't decoded again. Co-Authored-By: Claude Fable 5.2 --- crates/render/src/lib.rs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 70f8841bd1..ca59fff727 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -619,9 +619,10 @@ pub fn picture_size(b64: &str) -> Option<(u32, u32)> { } /// The pixel size a base64 picture is drawn from, `None` when a layout draws a placeholder instead. -/// Decodes the whole image, as drawing it does: [`picture_size`] reads only the header. +/// Decodes the whole image, as drawing it does, or finds the copy drawing it decoded: +/// [`picture_size`] reads only the header. pub fn picture_drawn_size(b64: &str) -> Option<(u32, u32)> { - picture::decode(b64).map(|pm| (pm.width(), pm.height())) + picture::decoded(b64).map(|pm| (pm.width(), pm.height())) } pub use picture::{MARKER_PIXELS, MARKER_PIXELS_SIDE, MarkerRefusal, RUN_MARKER_BYTES, RUN_MARKER_PIXELS, SVG_DEPTH, SVG_XML_NODES}; From d50ef3055b757c47e1359178698d0beb877ecbd8 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 03:35:51 -0600 Subject: [PATCH 19/38] fix(layout): a picture with none of its box on the page isn't said to be a grey box pictures_not_drawn listed every visible picture whose image doesn't draw, so a picture wholly off the page (or only touching its edge) was named in the layout view's and every export's notice although the page shows none of its grey box. It now keeps only pictures with some of their box on the page, by the test a legend's pictures are waited by (on_page); one partly on the page is still listed. Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout/picture.rs | 54 +++++++++++++++++++++++++++-- docs/user-guide/layouts.md | 19 +++++----- 2 files changed, 62 insertions(+), 11 deletions(-) diff --git a/crates/render/src/layout/picture.rs b/crates/render/src/layout/picture.rs index 41d0157d50..5cfeca92b2 100644 --- a/crates/render/src/layout/picture.rs +++ b/crates/render/src/layout/picture.rs @@ -82,9 +82,11 @@ pub struct PictureGap { } /// The visible pictures of `layout` whose image doesn't draw ([`picture_draws`]), drawn as a grey -/// box, in the order of its elements. A hidden picture draws nothing and isn't listed. +/// box, in the order of its elements. A hidden picture draws nothing and isn't listed, nor is one +/// with none of its box on the page ([`on_page`], the test a legend's pictures are waited by): +/// the page shows none of its grey box. pub fn pictures_not_drawn(layout: &Layout) -> Vec { - let gaps = layout.elements.iter().filter(|e| e.visible).filter_map(|e| { + let gaps = layout.elements.iter().filter(|e| e.visible && on_page(layout, e)).filter_map(|e| { let ElementKind::Picture { image, .. } = &e.kind else { return None }; if picture_draws(image) { return None; @@ -251,6 +253,54 @@ mod tests { assert!(gaps.iter().all(|g| g.name == "Picture")); } + /// Only a picture whose box has some of the page under it is listed: one partly on the page + /// draws part of its grey box; one wholly off it, or only touching its edge, draws none. + #[test] + fn a_picture_off_the_page_is_not_listed() { + // Each box, whether it is listed, and whether it is far enough from the page's edge for + // the page to show its grey box just when it is listed (the box's outline is drawn + // across its edge, so half of it reaches the page from a box only touching it). + let boxes: [((f64, f64, f64, f64), bool, bool); 15] = [ + ((10.0, 10.0, 20.0, 10.0), true, true), + ((90.0, 10.0, 20.0, 10.0), true, true), + ((-10.0, -5.0, 20.0, 10.0), true, true), + ((10.0, 75.0, 20.0, 10.0), true, true), + ((100.0, 10.0, 20.0, 10.0), false, false), + ((-20.0, 10.0, 20.0, 10.0), false, false), + ((10.0, 80.0, 20.0, 10.0), false, false), + ((10.0, -10.0, 20.0, 10.0), false, false), + ((110.0, 10.0, 20.0, 10.0), false, true), + ((-40.0, 10.0, 20.0, 10.0), false, true), + ((10.0, 90.0, 20.0, 10.0), false, true), + ((10.0, -30.0, 20.0, 10.0), false, true), + // Sizes only a hand-edited file has, before `Layout::clamp`: none, or turned back. + ((10.0, 10.0, 0.0, 0.0), true, false), + ((10.0, 10.0, -5.0, 10.0), true, false), + ((10.0, 10.0, f64::NAN, 10.0), false, false), + ]; + let page = |at: (f64, f64, f64, f64)| { + let mut l = Layout::new("Pictures", 100.0, 80.0); + l.add("Picture", (10.0, 10.0, 20.0, 10.0), ElementKind::Picture { image: String::new(), source: None }); + if let Some(e) = l.elements.first_mut() { + (e.x, e.y, e.w, e.h) = at; + } + l + }; + let draw = |l: &Layout| render(l, &mut Vec::new(), 96.0, &PageInfo::default()).unwrap(); + let blank = draw(&Layout::new("Pictures", 100.0, 80.0)); + for (at, listed, clear) in boxes { + let l = page(at); + assert_eq!(pictures_not_drawn(&l).len(), usize::from(listed), "{at:?}"); + if clear { + assert_eq!(draw(&l).data() != blank.data(), listed, "{at:?}"); + } + } + // `Layout::clamp`, which every layout read or edited goes through, gives a box a size. + let mut l = page((10.0, 10.0, f64::NAN, 10.0)); + l.clamp(); + assert_eq!(pictures_not_drawn(&l).len(), 1); + } + /// One notice per kind, counted, the first ten named with their file's name, never a folder. #[test] fn the_picture_notices_count_and_name_each_kind() { diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 10fd86d1c5..9eb9ac7150 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -678,15 +678,16 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu which shows the file's name under **File** (the whole path when you hold the pointer over it). Choosing a file again also brings a picture up to date when its file has changed. Only the file's name is drawn on the page or named in a notice about the picture, never its folders. A picture - that has no image or one that can't be drawn is drawn as a grey box, and the layout view and every - export (PNG, PDF, SVG, reports, and the Assistant's view of the layout) say so, naming it. A - picture is never read from its file by itself: not when a project or layout opens, nor when it is - exported. Scripts give `layout.update` a picture's `"path"` to read it again (a missing file, one - over 16 MB, not a PNG or JPEG, or one that can't be drawn is refused and the picture left as it - was) or its `"image"` (its file is then no longer remembered); `null` leaves each as it is. Each - change is one undo step. A project with a picture that remembers its file can't be opened by an - older RustGIS, and a layout file with one lists it in its header. In the browser, which has no - file paths, a picture is added from the file's contents and doesn't remember the file. + on the page that has no image or one that can't be drawn is drawn as a grey box, and the layout + view and every export (PNG, PDF, SVG, reports, and the Assistant's view of the layout) say so, + naming it. A picture is never read from its file by itself: not when a project or layout opens, + nor when it is exported. Scripts give `layout.update` a picture's `"path"` to read it again (a + missing file, one over 16 MB, not a PNG or JPEG, or one that can't be drawn is refused and the + picture left as it was) or its `"image"` (its file is then no longer remembered); `null` leaves + each as it is. Each change is one undo step. A project with a picture that remembers its file + can't be opened by an older RustGIS, and a layout file with one lists it in its header. In the + browser, which has no file paths, a picture is added from the file's contents and doesn't remember + the file. - **Map Series**: one page per feature of an index layer; see [Map series](#map-series) for setup, page names, scales and a locator. - Click an element to select it, drag to move, drag its handles to resize, and edit it in the From 357f7bded64bc9a70cc75aa4487f0a82649208c4 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 05:21:50 -0600 Subject: [PATCH 20/38] docs(layout): a picture's file limit is 16 MiB Co-Authored-By: Claude Fable 5.2 --- docs/user-guide/layouts.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 7b92f03b68..faa6e5dc15 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -682,7 +682,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu view and every export (PNG, PDF, SVG, reports, and the Assistant's view of the layout) say so, naming it. A picture is never read from its file by itself: not when a project or layout opens, nor when it is exported. Scripts give `layout.update` a picture's `"path"` to read it again (a - missing file, one over 16 MB, not a PNG or JPEG, or one that can't be drawn is refused and the + missing file, one over 16 MiB, not a PNG or JPEG, or one that can't be drawn is refused and the picture left as it was) or its `"image"` (its file is then no longer remembered); `null` leaves each as it is. Each change is one undo step. A project with a picture that remembers its file can't be opened by an older RustGIS, and a layout file with one lists it in its header. In the From f164db3e6ed936c2419799d98aabbd96f0b42c52 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 08:59:12 -0600 Subject: [PATCH 21/38] docs(layout): say why a picture's image is decoded on the command's thread Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout/picture.rs | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs index 69e93fdd94..2637c82279 100644 --- a/crates/engine/src/cmd/layout/picture.rs +++ b/crates/engine/src/cmd/layout/picture.rs @@ -71,9 +71,18 @@ pub(crate) fn gives_picture(p: &Value) -> bool { /// The picture a command's `image` or `path` gives, none when it gives neither; refused when both /// are given, either is of the wrong kind, the file can't be read or isn't a PNG or JPEG of at most -/// 16 MiB, or the image can't be drawn. Reads the file on the command's thread, as -/// `layout.addElement` always has: at most 16 MiB, then decoded once to check that it draws (the -/// decoded copy is kept for the page). +/// 16 MiB, or the image can't be drawn. +/// +/// Runs on the command's thread (the UI thread in the app): bounded work, not work that grows with +/// a layer. The file is read whole, as `layout.addElement` always read it, at most 16 MiB +/// (`graphics::MAX_PICTURE`). The image is then decoded once, here, because whether it draws +/// decides whether the command is taken: one that can't be drawn is refused, the layout left as it +/// was, rather than added or kept as a grey box. The decoder doesn't start on an image declaring +/// over [`rustgis_render::layout::PICTURE_MAX_DECLARED`] pixels a side and allocates at most +/// [`rustgis_render::layout::PICTURE_MAX_DECODED_MB`] MiB. The decoded copy stays in the cache of +/// decoded pictures of the thread that decoded it ([`rustgis_render::layout::picture_draws`]): the +/// Layout view draws on the same thread and finds it there; an export the app writes on another +/// thread decodes it again, once, on that thread. pub(in crate::cmd::layout) fn picture_given(p: &Value) -> Result, String> { let given = |k: &str| p.get(k).filter(|v| !v.is_null()); if given("image").is_some() && given("path").is_some() { From 65c499f2bbf57cdd8450053d64228a942bdb4f9b Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:11:51 -0600 Subject: [PATCH 22/38] fix(layout): refuse a picture's path in the browser before reading it Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout.rs | 4 +-- crates/engine/src/cmd/layout/picture.rs | 37 ++++++++++++++++++++++++- docs/user-guide/layouts.md | 2 +- 3 files changed, 39 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index 92b6498e20..a812f8f571 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -226,7 +226,7 @@ pub fn commands() -> Vec { r##""angle"?: degrees anticlockwise from pointing right, centred on the page unless x or y is given (line, arrow; it sets the box and the direction, so w, h and dir are not used with it), "##, r##""length"?: mm (line, arrow), "##, r##""image"?: base64, "##, - r##""path"?: picture file (picture: read, and remembered as its file, so a picture whose image goes missing names it and layout.update can read it again; an address is refused, and image and path together; refused for other kinds), "##, + r##""path"?: picture file (picture: read, and remembered as its file, so a picture whose image goes missing names it and layout.update can read it again; an address is refused, and image and path together; refused in the browser, which has no file paths: give its image; refused for other kinds), "##, r##""layer"?: (table, chart; colorbar: a raster layer, default the top visible raster with a colour scale, not drawn by classes, which a legend lists), "##, r##""field"?: (chart: a numeric field, default the layer's first; any field when it groups and counts, default then the field it groups by), "##, r##""label"?: a field (chart: each bar's label when not grouped), "##, @@ -365,7 +365,7 @@ pub fn commands() -> Vec { r##""hideLabels"?: bool (chart, as in layout.addElement: null leaves each other one as it is; refused for other elements unless null), "##, r##""rows"?, "##, r##""image"?: base64 (picture: its new image, its file no longer remembered), "##, - r##""path"?: a PNG or JPEG file (picture: read again, its image replacing the one it has, and remembered as its file; a file missing, over 16 MB, not a PNG or JPEG, or one that can't be drawn is refused and the picture left as it was; image and path together are refused; null leaves each as it is; refused for other elements), "##, + r##""path"?: a PNG or JPEG file (picture: read again, its image replacing the one it has, and remembered as its file; a file missing, over 16 MB, not a PNG or JPEG, or one that can't be drawn is refused and the picture left as it was; image and path together are refused; refused in the browser, which has no file paths: give its image; null leaves each as it is; refused for other elements), "##, r##""background"?: {"fill"?, "outline"?, "width"?, "radius"?, "padding"?, as in layout.addElement, the keys not given keeping theirs} | null (removes it); a map frame takes none}"##, ), diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs index 2637c82279..10f987122a 100644 --- a/crates/engine/src/cmd/layout/picture.rs +++ b/crates/engine/src/cmd/layout/picture.rs @@ -12,6 +12,9 @@ pub(in crate::cmd::layout) const PICTURE_IMAGE: &str = "image is a PNG or JPEG i /// A `path` that is an address, which is never tried as a file nor fetched, and never repeated /// (it could carry a login). pub(in crate::cmd::layout) const PICTURE_ADDRESS: &str = "a picture is read from a file on this computer, not a web address"; +/// A `path` given in the browser. +pub(in crate::cmd::layout) const PICTURE_PATH_IN_BROWSER: &str = + "a picture's path can't be read in the browser, which has no file paths: give its image"; /// Both `image` and `path` given. pub(in crate::cmd::layout) const PICTURE_BOTH: &str = "give a picture an image or a path, not both"; @@ -53,11 +56,19 @@ pub(crate) struct GivenPicture { } /// A command's `path`: none when absent or null, as given when it is text that isn't blank and -/// isn't an address ([`rustgis_map::layout::picture_path_is_address`]); refused otherwise. +/// isn't an address ([`rustgis_map::layout::picture_path_is_address`]); refused otherwise, and +/// in the browser, which has no file paths, refused before anything is read +/// ([`PICTURE_PATH_IN_BROWSER`]). pub(crate) fn picture_path_param(p: &Value) -> Result, String> { + picture_path_param_in(p, cfg!(target_arch = "wasm32")) +} + +/// [`picture_path_param`] in the browser (`web`) or elsewhere. +fn picture_path_param_in(p: &Value, web: bool) -> Result, String> { match p.get("path") { None | Some(Value::Null) => Ok(None), Some(Value::String(path)) if path.trim().is_empty() => Err(PICTURE_PATH.into()), + Some(Value::String(_)) if web => Err(PICTURE_PATH_IN_BROWSER.into()), Some(Value::String(path)) if rustgis_map::layout::picture_path_is_address(path) => Err(PICTURE_ADDRESS.into()), Some(Value::String(path)) => Ok(Some(path)), Some(_) => Err(PICTURE_PATH.into()), @@ -105,3 +116,27 @@ pub(in crate::cmd::layout) fn picture_given(p: &Value) -> Result Date: Sat, 28 Nov 2026 09:11:51 -0600 Subject: [PATCH 23/38] fix(layout): say when an image given to a picture forgets its file Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout.rs | 2 +- crates/engine/src/cmd/layout/picture.rs | 14 ++++++-- crates/engine/src/cmd/layout/update.rs | 6 ++++ crates/engine/src/tests/layout_pictures.rs | 38 ++++++++++++++++++++++ docs/user-guide/layouts.md | 2 +- 5 files changed, 58 insertions(+), 4 deletions(-) diff --git a/crates/engine/src/cmd/layout.rs b/crates/engine/src/cmd/layout.rs index a812f8f571..e187b2cdb0 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -364,7 +364,7 @@ pub fn commands() -> Vec { r##""barOutline"?: {"color"?, "width"?: points, 0 to 5, a wider one held to 5, the keys not given keeping the outline's}|null (null or a width of 0 for none), "##, r##""hideLabels"?: bool (chart, as in layout.addElement: null leaves each other one as it is; refused for other elements unless null), "##, r##""rows"?, "##, - r##""image"?: base64 (picture: its new image, its file no longer remembered), "##, + r##""image"?: base64 (picture: its new image, its file no longer remembered, which is said when it had one), "##, r##""path"?: a PNG or JPEG file (picture: read again, its image replacing the one it has, and remembered as its file; a file missing, over 16 MB, not a PNG or JPEG, or one that can't be drawn is refused and the picture left as it was; image and path together are refused; refused in the browser, which has no file paths: give its image; null leaves each as it is; refused for other elements), "##, r##""background"?: {"fill"?, "outline"?, "width"?, "radius"?, "padding"?, as in layout.addElement, the keys not given keeping theirs} | null (removes it); a map frame takes none}"##, ), diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs index 10f987122a..23ed055aae 100644 --- a/crates/engine/src/cmd/layout/picture.rs +++ b/crates/engine/src/cmd/layout/picture.rs @@ -37,6 +37,9 @@ pub(in crate::cmd::layout) fn picture_unremembered() -> String { ) } +/// A picture that remembered its file given an image by `layout.update`: the file is forgotten. +pub(in crate::cmd::layout) const PICTURE_FORGOTTEN: &str = "the picture's file is no longer remembered: its image was given directly"; + /// Says each of [`rustgis_render::layout::pictures_notices`] of `gaps`, the pictures an export /// draws as a grey box, with `prefix` before it. pub(in crate::cmd) fn say_pictures_not_drawn(s: &mut Session, gaps: &[rustgis_render::layout::PictureGap], prefix: &str) { @@ -53,6 +56,8 @@ pub(crate) struct GivenPicture { pub source: Option, /// Read from a file whose path isn't kept: said once by the command. pub unremembered: bool, + /// Given as an image, not read from a file: a picture that remembered its file forgets it. + pub given_image: bool, } /// A command's `path`: none when absent or null, as given when it is text that isn't blank and @@ -101,13 +106,18 @@ pub(in crate::cmd::layout) fn picture_given(p: &Value) -> Result { - GivenPicture { image: crate::cmd::graphics::checked_picture(image.trim().to_string())?, source: None, unremembered: false } + GivenPicture { + image: crate::cmd::graphics::checked_picture(image.trim().to_string())?, + source: None, + unremembered: false, + given_image: true, + } } (Some(_), _) => return Err(PICTURE_IMAGE.into()), (None, Some(path)) => { let image = crate::cmd::graphics::picture_file(path)?; let kept = rustgis_map::layout::picture_source_kept(path); - GivenPicture { image, source: kept.then(|| path.to_string()), unremembered: !kept } + GivenPicture { image, source: kept.then(|| path.to_string()), unremembered: !kept, given_image: false } } (None, None) => return Ok(None), }; diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 0681bb9512..890c1ceb08 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -489,6 +489,9 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { _ => None, }; let unremembered = new_picture.as_ref().is_some_and(|g| g.unremembered); + // Given an image, a picture that remembered its file forgets it, which is said. + let forgotten = matches!(kind_now, Some(ElementKind::Picture { source: Some(_), .. })) + && new_picture.as_ref().is_some_and(|g| g.given_image); let l = active(s, p)?; let e = l.element_mut(id).ok_or_else(|| format!("no element {id}"))?; // A text or scale bar with no ink isn't measured: given a colour that shows it, it is told @@ -764,6 +767,9 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { if unremembered { s.notify(picture_unremembered(), false); } + if forgotten { + s.notify(PICTURE_FORGOTTEN, false); + } if fit { say_legend_fit(s, li, id); } diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 2a154782a3..840e887a52 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -708,3 +708,41 @@ fn a_picture_drawn_as_a_grey_box_is_said_by_every_export() { assert!(said.is_empty(), "{route}: {said:?}"); } } + +/// Given an image, a picture that remembered its file forgets it and says so once, naming neither +/// the file nor its folders; Undo brings the file back. A picture with no file, or one read from a +/// file again, says nothing of it. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn an_image_given_to_a_picture_with_a_file_says_the_file_is_forgotten() { + let (dir, mut s) = picture_world("an-image-given-to-a-picture-with-a-file-says-the-file-is-forgotten"); + let (first, first_b64) = png_file(&dir, "first.png", (40, 20), [0x1F, 0x5C, 0x84]); + let (second, second_b64) = png_file(&dir, "second.png", (30, 30), [0xE8, 0xB0, 0x4A]); + let third_b64 = png_b64(10, 20, |_, _| [0x22, 0x88, 0x22]); + let forgotten = "the picture's file is no longer remembered: its image was given directly"; + let said = |s: &Session, mark| s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>(); + let id = s.run("layout.addElement", &json!({"kind": "picture", "path": first})).unwrap()["element"].clone(); + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "image": third_b64})).unwrap(); + let notes = said(&s, mark); + assert_eq!(notes.iter().filter(|n| n.as_str() == forgotten).count(), 1, "{notes:?}"); + let folder = dir.0.display().to_string(); + assert!(notes.iter().all(|n| !n.contains("first") && !n.contains(&folder)), "{notes:?}"); + assert_eq!(picture_in(&s, "L", &id), (third_b64.clone(), None)); + s.run("edit.undo", &Value::Null).unwrap(); + assert_eq!(picture_in(&s, "L", &id), (first_b64, Some(first))); + // Read from a file again: the new file is remembered, and nothing is said of the old one. + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": id, "path": second})).unwrap(); + assert!(!said(&s, mark).iter().any(|n| n.contains("no longer remembered")), "{:?}", said(&s, mark)); + assert_eq!(picture_in(&s, "L", &id), (second_b64.clone(), Some(second))); + // With no file to forget: nothing said, whether it never had one or has just forgotten it. + s.run("layout.update", &json!({"element": id, "image": third_b64})).unwrap(); + let bare = s.run("layout.addElement", &json!({"kind": "picture", "image": second_b64})).unwrap()["element"].clone(); + for target in [id, bare] { + let mark = s.notice_mark(); + s.run("layout.update", &json!({"element": target, "image": third_b64})).unwrap(); + assert!(!said(&s, mark).iter().any(|n| n.contains("no longer remembered")), "{target}: {:?}", said(&s, mark)); + assert_eq!(picture_in(&s, "L", &target), (third_b64.clone(), None)); + } +} diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 6fe53712e7..4102b5fe59 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -701,7 +701,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu naming it. A picture is never read from its file by itself: not when a project or layout opens, nor when it is exported. Scripts give `layout.update` a picture's `"path"` to read it again (a missing file, one over 16 MiB, not a PNG or JPEG, or one that can't be drawn is refused and the - picture left as it was) or its `"image"` (its file is then no longer remembered); `null` leaves + picture left as it was) or its `"image"` (its file is then no longer remembered, which is said); `null` leaves each as it is. Each change is one undo step. A project with a picture that remembers its file can't be opened by an older RustGIS, and a layout file with one lists it in its header. In the browser, which has no file paths, a picture is added from the file's contents and doesn't remember From 6eb9d7235fca989547322bf5b4c1babff051c208 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:11:51 -0600 Subject: [PATCH 24/38] fix(layout): fit a file named Picture in its grey box as any name Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout/picture.rs | 48 +++++++++++++++++------------ 1 file changed, 29 insertions(+), 19 deletions(-) diff --git a/crates/render/src/layout/picture.rs b/crates/render/src/layout/picture.rs index 5cfeca92b2..aea3362a9b 100644 --- a/crates/render/src/layout/picture.rs +++ b/crates/render/src/layout/picture.rs @@ -20,10 +20,10 @@ pub fn picture_draws(image: &str) -> bool { crate::picture::decoded(image).is_some() } -/// What a picture's grey box says: the name of its file when it has one it keeps (never its -/// folders), else "Picture". -fn picture_label(source: Option<&str>) -> &str { - source.filter(|s| picture_source_kept(s)).and_then(picture_file_name).unwrap_or("Picture") +/// The file name a picture's grey box says, when it has a file it keeps (never its folders); +/// none, and the box says "Picture", otherwise. +fn picture_label(source: Option<&str>) -> Option<&str> { + source.filter(|s| picture_source_kept(s)).and_then(picture_file_name) } /// `name` as it fits in `room`, measured by [`text::measure`] at `size`: whole when it fits, else @@ -45,17 +45,17 @@ fn fitted_name(name: &str, room: f32, size: f32) -> String { } /// A picture's grey box with no image to draw: "Picture" in it as [`placeholder`] draws it for a -/// picture with no file, else its file's name ([`picture_label`]) cut to the box, 2 pt in from -/// each side. +/// picture with no file name ([`picture_label`]), else its file's name cut to the box, 2 pt in +/// from each side, whatever the name. pub(super) fn draw_picture_box(pm: &mut Canvas, r: Rect, source: Option<&str>, ppp: f64) { - let label = picture_label(source); - if label == "Picture" { - placeholder(pm, r, "Picture", ppp); - } else { - // `placeholder` draws its label 10 × 1.33 × `ppp` pixels tall, which text::measure - // measures at 10 × `ppp`. - let room = r.width() - 4.0 * ppp as f32; - placeholder(pm, r, &fitted_name(label, room, 10.0 * ppp as f32), ppp); + match picture_label(source) { + None => placeholder(pm, r, "Picture", ppp), + Some(name) => { + // `placeholder` draws its label 10 × 1.33 × `ppp` pixels tall, which text::measure + // measures at 10 × `ppp`. + let room = r.width() - 4.0 * ppp as f32; + placeholder(pm, r, &fitted_name(name, room, 10.0 * ppp as f32), ppp); + } } } @@ -170,11 +170,11 @@ mod tests { /// the word Picture, as before. #[test] fn a_picture_without_an_image_is_labelled_with_its_file_name() { - assert_eq!(picture_label(None), "Picture"); - assert_eq!(picture_label(Some("")), "Picture"); - assert_eq!(picture_label(Some("/data/logos/north.png")), "north.png"); - assert_eq!(picture_label(Some(r"\\server\share\logo.jpg")), "logo.jpg"); - assert_eq!(picture_label(Some("https://example.invalid/north.png")), "Picture"); + assert_eq!(picture_label(None), None); + assert_eq!(picture_label(Some("")), None); + assert_eq!(picture_label(Some("/data/logos/north.png")), Some("north.png")); + assert_eq!(picture_label(Some(r"\\server\share\logo.jpg")), Some("logo.jpg")); + assert_eq!(picture_label(Some("https://example.invalid/north.png")), None); // Drawn: a named box differs from the plain one, and from one named otherwise. let page = |source: Option<&str>| one_picture_page("", source); let draw = |l: Layout| render(&l, &mut Vec::new(), 96.0, &PageInfo::default()).unwrap(); @@ -184,6 +184,16 @@ mod tests { assert_ne!(north.data(), south.data()); // A source the rule doesn't keep draws as none. assert_eq!(draw(page(Some("https://example.invalid/north.png"))).data(), plain.data()); + // A file named Picture is fitted to its box as any name is: in a box too narrow for the + // word, it is cut, where a picture with no file draws the word whole. + let narrow = |source: Option<&str>| { + let mut l = Layout::new("Pictures", 100.0, 80.0); + let kind = ElementKind::Picture { image: String::new(), source: source.map(String::from) }; + l.add("Picture", (10.0, 10.0, 6.0, 4.0), kind); + draw(l) + }; + assert_eq!(picture_label(Some("/data/logos/Picture")), Some("Picture")); + assert_ne!(narrow(Some("/data/logos/Picture")).data(), narrow(None).data()); } /// Only the file's name reaches the page, the SVG and the PDF: two folders, the same drawing. From 434ad0c3182872c55df377afe203a0587143c86d Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 09:12:57 -0600 Subject: [PATCH 25/38] style(layout): format the forgotten-file notice's code Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout/picture.rs | 14 ++++++-------- crates/engine/src/cmd/layout/update.rs | 4 ++-- 2 files changed, 8 insertions(+), 10 deletions(-) diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs index 23ed055aae..612c14b0fb 100644 --- a/crates/engine/src/cmd/layout/picture.rs +++ b/crates/engine/src/cmd/layout/picture.rs @@ -105,14 +105,12 @@ pub(in crate::cmd::layout) fn picture_given(p: &Value) -> Result { - GivenPicture { - image: crate::cmd::graphics::checked_picture(image.trim().to_string())?, - source: None, - unremembered: false, - given_image: true, - } - } + (Some(Value::String(image)), _) => GivenPicture { + image: crate::cmd::graphics::checked_picture(image.trim().to_string())?, + source: None, + unremembered: false, + given_image: true, + }, (Some(_), _) => return Err(PICTURE_IMAGE.into()), (None, Some(path)) => { let image = crate::cmd::graphics::picture_file(path)?; diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 890c1ceb08..3652ccadf1 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -490,8 +490,8 @@ pub(in crate::cmd::layout) fn update(s: &mut Session, p: &Value) -> CmdResult { }; let unremembered = new_picture.as_ref().is_some_and(|g| g.unremembered); // Given an image, a picture that remembered its file forgets it, which is said. - let forgotten = matches!(kind_now, Some(ElementKind::Picture { source: Some(_), .. })) - && new_picture.as_ref().is_some_and(|g| g.given_image); + let forgotten = + matches!(kind_now, Some(ElementKind::Picture { source: Some(_), .. })) && new_picture.as_ref().is_some_and(|g| g.given_image); let l = active(s, p)?; let e = l.element_mut(id).ok_or_else(|| format!("no element {id}"))?; // A text or scale bar with no ink isn't measured: given a colour that shows it, it is told From 9a212a2cbf6732ee65d1391d0b3f5c946a2fa25e Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:23:40 -0600 Subject: [PATCH 26/38] fix(render): keep decoded pictures within the budget or the newest alone The cache's byte budget was checked only before a new picture was decoded, so a large picture could join the others past it. After each insert the oldest other pictures are now let go while the cache holds more than the budget; the newest is kept even alone past it. Co-Authored-By: Claude Fable 5.2 --- crates/render/src/picture.rs | 65 +++++++++++++++++++++++++++++++++--- 1 file changed, 60 insertions(+), 5 deletions(-) diff --git a/crates/render/src/picture.rs b/crates/render/src/picture.rs index e89ba8cc68..8c578a3777 100644 --- a/crates/render/src/picture.rs +++ b/crates/render/src/picture.rs @@ -496,29 +496,48 @@ pub fn draw(pm: &mut Canvas, ds: &Dataset, row: usize, (x0, y0, x1, y1): (f32, f /// Base64 PNG or JPEG bytes decoded ([`decode`]), from this thread's cache of decoded pictures: /// decoded on the first look, and again only after the cache let it go. The cache keeps each /// picture's base64 with its pixels, or with none for one that doesn't decode (so that one isn't -/// tried again either), at most [`CACHE`] of them and, oldest let go first, at most about -/// [`CACHE_BYTES`] held ([`held`]: the base64 kept counts with the pixels). Graphics pictures -/// and layout pictures share it. +/// tried again either), at most [`CACHE`] of them, oldest let go first. It holds at most +/// [`CACHE_BYTES`] ([`held`]: the base64 kept counts with the pixels), or the newest picture alone +/// where that one holds more, so a picture past the budget isn't decoded on every draw. Graphics +/// pictures and layout pictures share it. pub(crate) fn decoded(b64: &str) -> Option> { + decoded_within(b64, CACHE_BYTES) +} + +/// [`decoded`], the cache holding at most `budget` bytes or the newest picture alone. +fn decoded_within(b64: &str, budget: usize) -> Option> { let key = key(b64); DECODED.with(|cache| { let mut cache = cache.borrow_mut(); if cache.images.get(&key).is_none_or(|(src, _)| src.as_str() != b64) { - // Evict the oldest pictures (not all of them) to stay within the count and memory budget. - while cache.images.len() >= CACHE || (!cache.images.is_empty() && held(&cache) > CACHE_BYTES) { + // The oldest pictures let go (not all of them) to make room within the count, and a + // picture held alone past the budget before this one is decoded. + while cache.images.len() >= CACHE || (!cache.images.is_empty() && held(&cache) > budget) { let Some(old) = cache.order.pop_front() else { break }; cache.images.remove(&old); } #[cfg(test)] DECODES.with(|n| n.set(n.get() + 1)); + // A picture under a key already kept (whose base64 differs) keeps that key's place. if cache.images.insert(key, (b64.to_string(), decode(b64).map(Arc::new))).is_none() { cache.order.push_back(key); } + fit(&mut cache, key, budget); } cache.images.get(&key).and_then(|(_, img)| img.clone()) }) } +/// Lets the oldest pictures but `newest` go while `cache` holds more than `budget` bytes. +fn fit(cache: &mut Cache, newest: u64, budget: usize) { + while held(cache) > budget { + let Some(i) = cache.order.iter().position(|k| *k != newest) else { break }; + if let Some(old) = cache.order.remove(i) { + cache.images.remove(&old); + } + } +} + /// The bytes `cache` holds: each picture's pixels and the base64 it keeps. fn held(cache: &Cache) -> usize { cache.images.values().map(|(b64, img)| b64.len() + img.as_ref().map_or(0, |p| p.data().len())).sum() @@ -530,6 +549,12 @@ pub(crate) fn decodes() -> usize { DECODES.with(std::cell::Cell::get) } +/// The bytes this thread's cache of decoded pictures holds ([`held`]). +#[cfg(test)] +fn held_here() -> usize { + DECODED.with(|cache| held(&cache.borrow())) +} + /// Runs `f` on picture marker `p`'s decoded image, its height for its width and, with `pack`, the /// image compressed (see [`Decoded::packed`]); or why it is drawn as a circle. fn with_marker(p: Picture, pack: bool, f: impl FnOnce(&Arc, f32, Option<&Arc>) -> R) -> Result { @@ -1083,4 +1108,34 @@ mod tests { assert_eq!(decode(gif).is_some(), image::ImageFormat::Gif.reading_enabled()); assert!(check(gif).is_err()); } + + /// The decoded pictures' cache holds at most its budget, or the newest picture alone where that + /// one holds more: under the budget none is let go early; a picture past it is kept alone, and + /// let go when the next is decoded. Told with a small budget, on a thread of its own. + #[test] + fn decoded_pictures_are_kept_within_the_budget_or_the_newest_alone() { + std::thread::spawn(|| { + let size = |b64: &str| b64.len() + decode(b64).unwrap().data().len(); + let (a, b, c, big) = (png(4, 4), png(5, 5), png(6, 6), png(40, 40)); + let budget = size(&a) + size(&b) + size(&c); + assert!(size(&big) > budget); + for p in [&a, &b, &c] { + assert!(decoded_within(p, budget).is_some()); + } + assert_eq!(held_here(), budget); + let n = decodes(); + for p in [&a, &b, &c] { + assert!(decoded_within(p, budget).is_some()); + } + assert_eq!(decodes(), n, "under the budget, none let go"); + assert!(decoded_within(&big, budget).is_some()); + assert_eq!(held_here(), size(&big), "the others let go, the large one kept alone"); + assert!(decoded_within(&big, budget).is_some()); + assert_eq!(decodes(), n + 1, "the large one drawn again isn't decoded again"); + assert!(decoded_within(&a, budget).is_some()); + assert_eq!((held_here(), decodes()), (size(&a), n + 2), "the large one let go for the next"); + }) + .join() + .unwrap(); + } } From f3c947ad9f3acd7b13582f5dc250ed933e2f13fb Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 10:31:42 -0600 Subject: [PATCH 27/38] docs(assistant): list a picture's image among layout.update's keys Co-Authored-By: Claude Fable 5.2 --- crates/assistant/skills/print-layout/SKILL.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index b4f5a88654..078757cffc 100644 --- a/crates/assistant/skills/print-layout/SKILL.md +++ b/crates/assistant/skills/print-layout/SKILL.md @@ -33,7 +33,7 @@ description: Make a printable page layout — map frame, title, legend, north ar `"valign"` (`"top"`, `"middle"`, `"bottom"`), `"lineSpacing"` (0.5–3, default 1) and `"case"` (`"none"`, `"upper"`, `"lower"`; applied when drawn, the text kept as typed). `"grid"` adds a graticule to the frame (`"style": "ticks"` for neatline ticks, `"format": "dms"`, `"edges"`). -5. Adjust with `layout.update` (`{"element": id, "x", "y", "w", "h", "text", "size", "bold", "valign", "lineSpacing", "case", "path"}`). The ids come from the +5. Adjust with `layout.update` (`{"element": id, "x", "y", "w", "h", "text", "size", "bold", "valign", "lineSpacing", "case", "path", "image"}`). The ids come from the results of the earlier calls. 6. `layout.export` `{"path": "map.pdf"}`, or `.png` with a `dpi` (300 for print). Exporting writes a file, so the user is asked first. `layout.close` goes back to the map. From 3d7e6962702ff2f47e61e0086260911714d5c83e Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 14:58:06 -0600 Subject: [PATCH 28/38] fix(layout): a login before a host and a colon reads as an address, never as a picture's file `user:pw@host:/a.png` (the scp and rsync form) had no `://` and no scheme before a separator, so it was tried as a file and its error repeated the login. A path whose first part holds an `@` and, after it, a colon now reads as an address: the commands refuse it without echoing it, and a picture never keeps it as its file. A relative path whose first part has such an `@` and colon is given as `./...`. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/tests/layout_pictures.rs | 7 +-- crates/map/src/layout/picture.rs | 56 ++++++++++++++++------ 2 files changed, 45 insertions(+), 18 deletions(-) diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 840e887a52..af7549d5dc 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -459,14 +459,15 @@ fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { assert_eq!(e, said); assert!(state(&s) == before, "{said}: the picture changed"); } - // An address with one slash or with backslashes is refused by both commands, never echoed. - for path in [r"https:\\user:pw@host\x.png", "https:/user:pw@host/x.png"] { + // An address with one slash or with backslashes, or a login before a host and a colon, is + // refused by both commands, never echoed. + for path in [r"https:\\user:pw@host\x.png", "https:/user:pw@host/x.png", "user:secret@example.invalid:/logo.png"] { for (command, p) in [("layout.update", json!({"element": id, "path": path})), ("layout.addElement", json!({"kind": "picture", "path": path}))] { let e = s.run(command, &p).unwrap_err(); assert_eq!(e, "a picture is read from a file on this computer, not a web address", "{command} {path}"); - assert!(!e.contains("pw") && !e.contains("host"), "{command}: {e}"); + assert!(["pw", "host", "secret", "example"].iter().all(|w| !e.contains(w)), "{command}: {e}"); assert!(state(&s) == before, "{command} {path} changed the layout"); } } diff --git a/crates/map/src/layout/picture.rs b/crates/map/src/layout/picture.rs index db64407222..2bd4c3f3dd 100644 --- a/crates/map/src/layout/picture.rs +++ b/crates/map/src/layout/picture.rs @@ -21,18 +21,29 @@ pub fn picture_source_kept(path: &str) -> bool { && path.chars().all(|c| rustgis_data::io::dbf_notice_char(c) == c) } -/// Whether `path` reads as an address, not a file: it holds `://` anywhere, or begins (after -/// leading blanks) with a scheme of two or more characters (a letter, then letters, digits, `+`, -/// `-` or `.`), a colon and a `/` or `\`. One letter is a drive (`C:\a.png`), and a name with a -/// colon and no separator after it (`a:b.png`) is a file. A relative path whose first folder -/// ends in a colon reads as an address: give it as `./folder:/a.png`. `mailto:a@b`, -/// `data:image/png;base64,…` and `user:pw@host:/a.png` are left as paths: no rule tells them from -/// a file name holding a colon, and none opens as a file unless it is one. +/// Whether `path` reads as an address, not a file. It does when it holds `://` anywhere, or when, +/// after leading blanks, it begins with a scheme of two or more characters (a letter, then letters, +/// digits, `+`, `-` or `.`), a colon and a `/` or `\` (`s3:/bucket/a.png`), or its first part +/// (all before the first `/` or `\`) holds an `@` and, after that `@`, a colon: a login before a +/// host (`user:pw@host:/a.png`, `git@host:logos/a.png`), which could carry a password. +/// +/// These stay files: a drive (`C:\a.png`; one letter is never a scheme), a share +/// (`\\server\share\a.png`), a name with a colon and no separator after it (`a:b.png`), and a +/// name with an `@` and no colon after it in the first part (`logo@2x.png`, `me@corp/a.png`). +/// `mailto:a@b` and `data:image/png;base64,…` are left as paths: no rule tells them from a file +/// name holding a colon, and none opens as a file unless it is one. The cost: a relative path whose +/// first folder ends in a colon, or whose first part holds an `@` followed by a colon, reads as an +/// address; give it as `./…` (`./folder:/a.png`, `./me@host:/a.png`). pub fn picture_path_is_address(path: &str) -> bool { if path.contains("://") { return true; } - let Some((scheme, rest)) = path.trim_start().split_once(':') else { return false }; + let path = path.trim_start(); + let first = path.split(['/', '\\']).next().unwrap_or_default(); + if first.split_once('@').is_some_and(|(_, host)| host.contains(':')) { + return true; + } + let Some((scheme, rest)) = path.split_once(':') else { return false }; let mut chars = scheme.chars(); scheme.len() >= 2 && chars.next().is_some_and(|c| c.is_ascii_alphabetic()) @@ -163,7 +174,7 @@ mod tests { } /// Paths that read as an address. - const ADDRESSES: [&str; 9] = [ + const ADDRESSES: [&str; 16] = [ "https://user:pw@host/a.png", "file:///data/x.png", "/vsicurl/https://host/a.png", @@ -173,11 +184,18 @@ mod tests { "file:/data/x.png", " s3:/bucket/a.png", "ab:/c.png", + "user:pw@host:/a.png", + "user@host:/a.png", + "user:pw@host:a.png", + "user@host:a.png", + "git@example.invalid:logos/a.png", + " user:pw@host:/a.png", + r"user:pw@host:\a.png", ]; - /// An address is `://` anywhere, or a scheme of two or more characters, a colon and a - /// separator; a drive, a share, a name with a colon, and the forms no rule can tell from a - /// file name, are paths. + /// An address is `://` anywhere, a scheme of two or more characters, a colon and a separator, + /// or a login before a host and a colon in the first part; a drive, a share, a name with a + /// colon or an `@`, and the forms no rule can tell from a file name, are paths. #[test] fn an_address_is_told_from_a_path() { for path in ADDRESSES { @@ -198,7 +216,14 @@ mod tests { "./folder:/a.png", "mailto:a@b", "data:image/png;base64,AAAA", - "user:pw@host:/a.png", + "logos/me@host:/a.png", + "/data/user@host:/a.png", + r"C:\Users\me@corp\a.png", + "C:/me@corp:x/a.png", + r"\\server\share\me@corp:x\a.png", + "./user@host:/a.png", + "me@corp/a.png", + "a:b@2x.png", "", ] { assert!(!picture_path_is_address(path), "{path:?}"); @@ -221,6 +246,7 @@ mod tests { Some(json!("a\u{7}b.png")), // 7: a control character, dropped and counted Some(serde_json::Value::Null), // 8: none, not counted None, // 9: absent, none, not counted + Some(json!("user:secret@example.invalid:/logo.png")), // 10: an address ]; let elements: Vec<_> = sources .iter() @@ -240,10 +266,10 @@ mod tests { k => panic!("{k:?}"), }; assert_eq!(source(1).as_deref(), Some("/data/logos/north.png")); - for id in 2..=9 { + for id in 2..=10 { assert_eq!(source(id), None, "{id}"); } - assert_eq!((repairs.elements_adjusted, repairs.elements_cut), (6, 0)); + assert_eq!((repairs.elements_adjusted, repairs.elements_cut), (7, 0)); let saved = serde_json::to_string(&l).unwrap(); assert!(saved.matches("\"source\"").count() == 1 && !saved.contains("secret"), "{saved}"); // An unclamped junk source writes nothing. From cdc4c6e1e99351564465f8f7822c2aedf3f32232 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 15:00:50 -0600 Subject: [PATCH 29/38] test(layout): a drive path with an at sign under a plain folder Co-Authored-By: Claude Fable 5.2 --- crates/map/src/layout/picture.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/map/src/layout/picture.rs b/crates/map/src/layout/picture.rs index 2bd4c3f3dd..6b4dc6485b 100644 --- a/crates/map/src/layout/picture.rs +++ b/crates/map/src/layout/picture.rs @@ -218,7 +218,7 @@ mod tests { "data:image/png;base64,AAAA", "logos/me@host:/a.png", "/data/user@host:/a.png", - r"C:\Users\me@corp\a.png", + r"C:\maps\me@corp\a.png", "C:/me@corp:x/a.png", r"\\server\share\me@corp:x\a.png", "./user@host:/a.png", From 001833525bcecb2ad03aefa91c1c78df3721260a Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:00:10 -0600 Subject: [PATCH 30/38] fix(layout): a refused picture file is named by its name, never the path given layout.addElement and layout.update named a picture file they couldn't read by the whole path given, so its folders, or a login in a path that isn't an address, reached the refusal. The reader now gives its reasons without the path and its caller names the file: a layout picture by its file name ("the picture's file" when the path has none), map graphics by the path given, as before. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/graphics.rs | 27 +++++----- crates/engine/src/cmd/layout/picture.rs | 9 +++- crates/engine/src/tests/layout_pictures.rs | 59 ++++++++++++++++++++-- docs/user-guide/layouts.md | 2 +- 4 files changed, 77 insertions(+), 20 deletions(-) diff --git a/crates/engine/src/cmd/graphics.rs b/crates/engine/src/cmd/graphics.rs index c05f565a2a..de5b9e43a7 100644 --- a/crates/engine/src/cmd/graphics.rs +++ b/crates/engine/src/cmd/graphics.rs @@ -403,17 +403,16 @@ fn color(p: &Value, k: &str) -> Result, String> { pub(crate) fn picture(p: &Value) -> Result { match (ps(p, "image"), ps(p, "path")) { (Some(b), _) => checked_picture(b.trim().to_string()), - (None, Some(path)) => picture_file(path), + (None, Some(path)) => picture_file(path, path), (None, None) => Err("a picture needs an image or a path".into()), } } /// The bytes of the picture file at `path` as base64: read by [`read_picture_file`], at most -/// 16 MiB, and a PNG or JPEG. -pub(crate) fn picture_file(path: &str) -> Result { - checked_picture( - base64::engine::general_purpose::STANDARD.encode(read_picture_file(path, MAX_PICTURE).map_err(PictureFileError::message)?), - ) +/// 16 MiB, and a PNG or JPEG. A file that doesn't open or read is called `named` in the refusal. +pub(crate) fn picture_file(path: &str, named: &str) -> Result { + let bytes = read_picture_file(path, MAX_PICTURE).map_err(|e| e.message(named))?; + checked_picture(base64::engine::general_purpose::STANDARD.encode(bytes)) } /// `b64` when it is at most 16 MiB of a PNG or JPEG image. @@ -427,7 +426,8 @@ pub(crate) fn checked_picture(b64: String) -> Result { Ok(b64) } -/// Why [`read_picture_file`] gave no picture, with how many of its bytes were read. +/// Why [`read_picture_file`] gave no picture, with how many of its bytes were read. The reasons +/// never hold the path: [`PictureFileError::message`] names the file as its caller chooses. pub(crate) enum PictureFileError { /// It isn't a regular file, or doesn't open: none read. Unopened(String), @@ -446,10 +446,10 @@ impl PictureFileError { } } - /// What a command says of it. - pub(crate) fn message(self) -> String { + /// What a command says of it, the file called `named` where it is the file's fault. + pub(crate) fn message(self, named: &str) -> String { match self { - Self::Unopened(why) | Self::Unread(why, _) => why, + Self::Unopened(why) | Self::Unread(why, _) => format!("{named}: {why}"), Self::TooLarge(_) => "the picture is too large".into(), } } @@ -459,13 +459,14 @@ impl PictureFileError { /// or endless file is too), its provenance kept. Only a regular file is opened: opening a named /// pipe or a device (`/dev/stdin`) waits for a writer, and this runs on the command's thread. pub(crate) fn read_picture_file(path: &str, max: usize) -> Result, PictureFileError> { - let unopened = |e: std::io::Error| PictureFileError::Unopened(format!("{path}: {e}")); + // The system's own words for an error (`std::io::Error`'s display) don't hold the path. + let unopened = |e: std::io::Error| PictureFileError::Unopened(e.to_string()); if !std::fs::metadata(path).map_err(unopened)?.is_file() { - return Err(PictureFileError::Unopened(format!("{path}: not a regular file"))); + return Err(PictureFileError::Unopened("not a regular file".into())); } let file = rustgis_data::provenance::open(path).map_err(unopened)?; let bytes = read_within(&file, max).map_err(|(e, n)| match e { - Some(e) => PictureFileError::Unread(format!("{path}: {e}"), n), + Some(e) => PictureFileError::Unread(e.to_string(), n), None => PictureFileError::TooLarge(n), })?; rustgis_data::provenance::buffer(std::path::Path::new(path), &file, &bytes); diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs index 612c14b0fb..d42c45d813 100644 --- a/crates/engine/src/cmd/layout/picture.rs +++ b/crates/engine/src/cmd/layout/picture.rs @@ -15,6 +15,8 @@ pub(in crate::cmd::layout) const PICTURE_ADDRESS: &str = "a picture is read from /// A `path` given in the browser. pub(in crate::cmd::layout) const PICTURE_PATH_IN_BROWSER: &str = "a picture's path can't be read in the browser, which has no file paths: give its image"; +/// What a refusal calls a file that can't be read when its path has no file name. +pub(in crate::cmd::layout) const PICTURE_FILE_UNNAMED: &str = "the picture's file"; /// Both `image` and `path` given. pub(in crate::cmd::layout) const PICTURE_BOTH: &str = "give a picture an image or a path, not both"; @@ -87,7 +89,9 @@ pub(crate) fn gives_picture(p: &Value) -> bool { /// The picture a command's `image` or `path` gives, none when it gives neither; refused when both /// are given, either is of the wrong kind, the file can't be read or isn't a PNG or JPEG of at most -/// 16 MiB, or the image can't be drawn. +/// 16 MiB, or the image can't be drawn. A file that can't be read is named in the refusal by its +/// name ([`rustgis_map::layout::picture_file_name`]), never by the path given, which could hold +/// folders or a login; a path without a name says [`PICTURE_FILE_UNNAMED`]. /// /// Runs on the command's thread (the UI thread in the app): bounded work, not work that grows with /// a layer. The file is read whole, as `layout.addElement` always read it, at most 16 MiB @@ -113,7 +117,8 @@ pub(in crate::cmd::layout) fn picture_given(p: &Value) -> Result return Err(PICTURE_IMAGE.into()), (None, Some(path)) => { - let image = crate::cmd::graphics::picture_file(path)?; + let named = rustgis_map::layout::picture_file_name(path).unwrap_or(PICTURE_FILE_UNNAMED); + let image = crate::cmd::graphics::picture_file(path, named)?; let kept = rustgis_map::layout::picture_source_kept(path); GivenPicture { image, source: kept.then(|| path.to_string()), unremembered: !kept, given_image: false } } diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index af7549d5dc..8b00878417 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -244,11 +244,11 @@ fn pictures_save_and_say_as_before() { ("an empty image", picture("image", json!("")), "the picture isn't a PNG or JPEG image"), ("an image over 16 MiB", picture("image", json!("A".repeat((16 << 20) / 3 * 4 + 8))), "the picture is too large"), ("an image that is a number", picture("image", json!(5)), "image is a PNG or JPEG image in base64"), - ("a path to a missing file", picture("path", json!(at("missing.png"))), "/missing.png: "), + ("a path to a missing file", picture("path", json!(at("missing.png"))), "missing.png: "), ("an empty path", picture("path", json!("")), "path is the path of a PNG or JPEG file"), // Never tried as a file, and not repeated. ("a path that is an address", picture("path", json!(address)), "a picture is read from a file on this computer, not a web address"), - ("a path to a folder", picture("path", json!(at("folder.png"))), "/folder.png: not a regular file"), + ("a path to a folder", picture("path", json!(at("folder.png"))), "folder.png: not a regular file"), ("a path to a text file", picture("path", json!(note)), "the picture isn't a PNG or JPEG image"), ("a path to a file of 16 MiB and a byte", picture("path", json!(over)), "the picture is too large"), ("a path that is a number", picture("path", json!(5)), "path is the path of a PNG or JPEG file"), @@ -298,7 +298,7 @@ fn pictures_save_and_say_as_before() { "a path to a missing file", "path", json!(at("missing.png")), - "refused \"/missing.png: \"; a picture of the JPEG after; 0 Undo step(s)", + "refused \"missing.png: \"; a picture of the JPEG after; 0 Undo step(s)", ), ] { let depth = s.undo_depth(); @@ -433,7 +433,7 @@ fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { let undrawn = "the picture can't be drawn: its image is damaged, or too large (over 20000 pixels a side, or over 512 MB once decoded)"; let not_a_path = "path is the path of a PNG or JPEG file"; for (path, said) in [ - // `read_picture_file`'s own "{path}: …". + // Named by the file's name: "gone.png: …". (json!(at("gone.png")), "gone.png"), (json!(at("note.png")), "the picture isn't a PNG or JPEG image"), (json!(huge), undrawn), @@ -509,6 +509,57 @@ fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { } } +/// A file the layout picture commands can't read is named by its name, never by the path given: +/// not its folders, and not a login-shaped path that isn't an address. Each other refusal says +/// what it said. Map graphics still name the path given. +#[cfg(not(target_arch = "wasm32"))] +#[test] +fn a_refused_picture_file_is_named_by_its_name_never_the_path_given() { + let (dir, mut s) = picture_world("a-refused-picture-file-is-named-by-its-name"); + let (first, _) = png_file(&dir, "first.png", (40, 20), [0x1F, 0x5C, 0x84]); + let id = s.run("layout.addElement", &json!({"kind": "picture", "path": first})).unwrap()["element"].clone(); + std::fs::create_dir_all(dir.0.join("logos").join("folder.png")).unwrap(); + std::fs::write(dir.0.join("logos").join("note.png"), b"not a picture").unwrap(); + std::fs::write(dir.0.join("logos").join("big.png"), vec![0u8; (16 << 20) + 1]).unwrap(); + let (huge, _) = png_file(&dir, "huge.png", (30_000, 1), [0x1F, 0x5C, 0x84]); + let at = |name: &str| dir.0.join("logos").join(name).display().to_string(); + let temp = dir.0.display().to_string(); + // What the system says of a path it can't open. + let system = |path: &str| std::fs::metadata(path).unwrap_err().to_string(); + let undrawn = "the picture can't be drawn: its image is damaged, or too large (over 20000 pixels a side, or over 512 MB once decoded)"; + let no_name = format!("{temp}{}", std::path::MAIN_SEPARATOR); + let cases: Vec<(String, String, Vec<&str>)> = vec![ + (at("missing.png"), format!("missing.png: {}", system(&at("missing.png"))), vec!["logos", &temp]), + (at("folder.png"), "folder.png: not a regular file".into(), vec!["logos", &temp]), + (at("note.png"), "the picture isn't a PNG or JPEG image".into(), vec!["logos", &temp]), + (at("big.png"), "the picture is too large".into(), vec!["logos", &temp]), + (huge.clone(), undrawn.into(), vec![&temp]), + (no_name.clone(), "the picture's file: not a regular file".into(), vec![&temp]), + ( + "user:secret@example.invalid/x.png".into(), + format!("x.png: {}", system("user:secret@example.invalid/x.png")), + vec!["secret", "user", "example"], + ), + ("https:user:pw@host/x.png".into(), format!("x.png: {}", system("https:user:pw@host/x.png")), vec!["pw@", "user", "host/"]), + ]; + let state = |s: &Session| (serde_json::to_value(&s.project).unwrap(), s.undo_depth(), s.dirty()); + let before = state(&s); + for (path, said, never) in &cases { + for (command, p) in + [("layout.update", json!({"element": id, "path": path})), ("layout.addElement", json!({"kind": "picture", "path": path}))] + { + let e = s.run(command, &p).unwrap_err(); + assert_eq!(&e, said, "{command} {path}"); + assert!(never.iter().all(|w| !e.contains(w)), "{command}: {e}"); + assert!(state(&s) == before, "{command} {path} changed the layout"); + } + } + // Map graphics name the path given, as they always have. + let missing = at("missing.png"); + let e = s.run("graphics.add", &json!({"shape": "picture", "points": [[0, 0], [1, 1]], "path": missing})).unwrap_err(); + assert_eq!(e, format!("{missing}: {}", system(&missing))); +} + /// A path the rule doesn't keep: the picture is read, its file not remembered, and that is said. #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index f6df97e217..4e66450b0f 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -709,7 +709,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu it, and its file can be read again: select it and use **Choose File…** in the **Format** pane, which shows the file's name under **File** (the whole path when you hold the pointer over it). Choosing a file again also brings a picture up to date when its file has changed. Only the file's - name is drawn on the page or named in a notice about the picture, never its folders. A picture + name is drawn or said (on the page, in a notice, in a refusal), never its folders. A picture on the page that has no image or one that can't be drawn is drawn as a grey box, and the layout view and every export (PNG, PDF, SVG, reports, and the Assistant's view of the layout) say so, naming it. A picture is never read from its file by itself: not when a project or layout opens, From b861d482db1a673e40e77a483c00141c91814f8e Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:32:33 -0600 Subject: [PATCH 31/38] fix(layout): an address refused as a picture's path is called an address The refusal covers a login before a host as well as a web address. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout/picture.rs | 2 +- crates/engine/src/tests/layout_pictures.rs | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs index d42c45d813..47727377fa 100644 --- a/crates/engine/src/cmd/layout/picture.rs +++ b/crates/engine/src/cmd/layout/picture.rs @@ -11,7 +11,7 @@ pub(in crate::cmd::layout) const PICTURE_PATH: &str = "path is the path of a PNG pub(in crate::cmd::layout) const PICTURE_IMAGE: &str = "image is a PNG or JPEG image in base64"; /// A `path` that is an address, which is never tried as a file nor fetched, and never repeated /// (it could carry a login). -pub(in crate::cmd::layout) const PICTURE_ADDRESS: &str = "a picture is read from a file on this computer, not a web address"; +pub(in crate::cmd::layout) const PICTURE_ADDRESS: &str = "a picture is read from a file on this computer, not an address"; /// A `path` given in the browser. pub(in crate::cmd::layout) const PICTURE_PATH_IN_BROWSER: &str = "a picture's path can't be read in the browser, which has no file paths: give its image"; diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 8b00878417..2d2ecf267c 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -247,7 +247,7 @@ fn pictures_save_and_say_as_before() { ("a path to a missing file", picture("path", json!(at("missing.png"))), "missing.png: "), ("an empty path", picture("path", json!("")), "path is the path of a PNG or JPEG file"), // Never tried as a file, and not repeated. - ("a path that is an address", picture("path", json!(address)), "a picture is read from a file on this computer, not a web address"), + ("a path that is an address", picture("path", json!(address)), "a picture is read from a file on this computer, not an address"), ("a path to a folder", picture("path", json!(at("folder.png"))), "folder.png: not a regular file"), ("a path to a text file", picture("path", json!(note)), "the picture isn't a PNG or JPEG image"), ("a path to a file of 16 MiB and a byte", picture("path", json!(over)), "the picture is too large"), @@ -439,7 +439,7 @@ fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { (json!(huge), undrawn), (json!(at("big.png")), "the picture is too large"), (json!(at("sub")), "not a regular file"), - (json!("https://user:secret@example.invalid/logo.png"), "a picture is read from a file on this computer, not a web address"), + (json!("https://user:secret@example.invalid/logo.png"), "a picture is read from a file on this computer, not an address"), (json!(5), not_a_path), (json!(""), not_a_path), (json!(" "), not_a_path), @@ -466,7 +466,7 @@ fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { [("layout.update", json!({"element": id, "path": path})), ("layout.addElement", json!({"kind": "picture", "path": path}))] { let e = s.run(command, &p).unwrap_err(); - assert_eq!(e, "a picture is read from a file on this computer, not a web address", "{command} {path}"); + assert_eq!(e, "a picture is read from a file on this computer, not an address", "{command} {path}"); assert!(["pw", "host", "secret", "example"].iter().all(|w| !e.contains(w)), "{command}: {e}"); assert!(state(&s) == before, "{command} {path} changed the layout"); } @@ -499,7 +499,7 @@ fn a_bad_file_is_refused_and_the_picture_left_as_it_was() { (json!({"kind": "picture", "image": first_b64, "path": first}), "give a picture an image or a path, not both"), ( json!({"kind": "picture", "path": "https://user:secret@example.invalid/logo.png"}), - "a picture is read from a file on this computer, not a web address", + "a picture is read from a file on this computer, not an address", ), (json!({"kind": "picture"}), "a picture needs an image or a path"), (json!({"kind": "picture", "path": null, "image": null}), "a picture needs an image or a path"), From 9cbbfa203462e6ecf6982e41e6cf26d32fe6a813 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:50:41 -0600 Subject: [PATCH 32/38] perf(render): a decoded picture drawn again is the last to be let go A hit in the decoded-picture cache now moves its key to the back of the order, so the count and byte limits let go the picture drawn longest ago rather than the one decoded first. A picture drawn on every frame stays decoded however many others are decoded between its draws. Co-Authored-By: Claude Fable 5.2 --- crates/render/src/picture.rs | 55 ++++++++++++++++++++++++++++-------- 1 file changed, 43 insertions(+), 12 deletions(-) diff --git a/crates/render/src/picture.rs b/crates/render/src/picture.rs index 7948e9e61f..62fa728545 100644 --- a/crates/render/src/picture.rs +++ b/crates/render/src/picture.rs @@ -152,7 +152,7 @@ refusal_phrases! { } /// Decoded pictures (with the base64 they came from, compared on every hit so pictures whose -/// cheap keys collide never swap), and their keys oldest first (for eviction). +/// cheap keys collide never swap), and their keys drawn longest ago first (for eviction). #[derive(Default)] struct Cache { /// Shared, so a frame drawn in bands keeps the picture, not a copy ([`Canvas::draw_shared`]). @@ -497,10 +497,10 @@ pub fn draw(pm: &mut Canvas, ds: &Dataset, row: usize, (x0, y0, x1, y1): (f32, f /// Base64 PNG or JPEG bytes decoded ([`decode`]), from this thread's cache of decoded pictures: /// decoded on the first look, and again only after the cache let it go. The cache keeps each /// picture's base64 with its pixels, or with none for one that doesn't decode (so that one isn't -/// tried again either), at most [`CACHE`] of them, oldest let go first. It holds at most -/// [`CACHE_BYTES`] ([`held`]: the base64 kept counts with the pixels), or the newest picture alone -/// where that one holds more, so a picture past the budget isn't decoded on every draw. Graphics -/// pictures and layout pictures share it. +/// tried again either), at most [`CACHE`] of them, the one drawn longest ago let go first. It +/// holds at most [`CACHE_BYTES`] ([`held`]: the base64 kept counts with the pixels), or the newest +/// picture alone where that one holds more, so a picture past the budget isn't decoded on every +/// draw. Graphics pictures and layout pictures share it. pub(crate) fn decoded(b64: &str) -> Option> { decoded_within(b64, CACHE_BYTES) } @@ -510,26 +510,35 @@ fn decoded_within(b64: &str, budget: usize) -> Option> { let key = key(b64); DECODED.with(|cache| { let mut cache = cache.borrow_mut(); - if cache.images.get(&key).is_none_or(|(src, _)| src.as_str() != b64) { - // The oldest pictures let go (not all of them) to make room within the count, and a - // picture held alone past the budget before this one is decoded. + let hit = cache.images.get(&key).is_some_and(|(src, _)| src.as_str() == b64); + if !hit { + // The pictures drawn longest ago let go (not all of them) to make room within the + // count, and a picture held alone past the budget before this one is decoded. while cache.images.len() >= CACHE || (!cache.images.is_empty() && held(&cache) > budget) { let Some(old) = cache.order.pop_front() else { break }; cache.images.remove(&old); } #[cfg(test)] DECODES.with(|n| n.set(n.get() + 1)); - // A picture under a key already kept (whose base64 differs) keeps that key's place. - if cache.images.insert(key, (b64.to_string(), decode(b64).map(Arc::new))).is_none() { - cache.order.push_back(key); + cache.images.insert(key, (b64.to_string(), decode(b64).map(Arc::new))); + } + // The picture drawn now is the last to be let go, also where it replaced another picture + // under its key. + if cache.order.back() != Some(&key) { + if let Some(i) = cache.order.iter().position(|k| *k == key) { + cache.order.remove(i); } + cache.order.push_back(key); + } + if !hit { fit(&mut cache, key, budget); } cache.images.get(&key).and_then(|(_, img)| img.clone()) }) } -/// Lets the oldest pictures but `newest` go while `cache` holds more than `budget` bytes. +/// Lets the pictures drawn longest ago, but `newest`, go while `cache` holds more than `budget` +/// bytes. fn fit(cache: &mut Cache, newest: u64, budget: usize) { while held(cache) > budget { let Some(i) = cache.order.iter().position(|k| *k != newest) else { break }; @@ -1154,4 +1163,26 @@ mod tests { .join() .unwrap(); } + + /// A picture drawn between each of more pictures than the cache holds is decoded once: the + /// one drawn longest ago is let go, not the one decoded first. On a thread of its own. + #[test] + fn a_picture_drawn_again_is_the_last_to_be_let_go() { + std::thread::spawn(|| { + let (kept, untouched) = (png(3, 3), png(4, 4)); + let others: Vec = (1..=CACHE as u32 + 1).map(|w| png(w, 1)).collect(); + let n = decodes(); + assert!(decoded(&untouched).is_some()); + assert!(decoded(&kept).is_some()); + for other in &others { + assert!(decoded(other).is_some()); + assert!(decoded(&kept).is_some()); + } + assert_eq!(decodes(), n + 2 + others.len(), "the picture drawn again decoded once"); + assert!(decoded(&untouched).is_some()); + assert_eq!(decodes(), n + 3 + others.len(), "the picture not drawn again let go"); + }) + .join() + .unwrap(); + } } From 22b63e4873fb2f2660f1ba17fdc880691caa08a6 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 16:50:41 -0600 Subject: [PATCH 33/38] test(layout): read the project format from its constant Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/tests/layout_pictures.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 2d2ecf267c..64dd5e2b98 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -620,7 +620,7 @@ fn a_project_with_a_damaged_picture_file_opens_and_says_so() { }) .collect(); let document = serde_json::json!({ - "format": 2, + "format": crate::project::FORMAT, "name": "Damaged pictures", "active_map": 0, "maps": [{"name": "Map", "layers": [], "basemap": "Paper", "camera": {"center": {"x": 0, "y": 0}, "res": 30000}}], From 999f132555010694a219c6664db7ecf64b45e54e Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sat, 28 Nov 2026 21:05:58 -0600 Subject: [PATCH 34/38] fix(layout): a refused picture file whose name would break the refusal isn't named A name holding a control or direction character is called the picture's file, as a path with no name is. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/cmd/layout/picture.rs | 10 +++++++--- crates/engine/src/tests/layout_pictures.rs | 3 +++ 2 files changed, 10 insertions(+), 3 deletions(-) diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs index 47727377fa..a7beea6403 100644 --- a/crates/engine/src/cmd/layout/picture.rs +++ b/crates/engine/src/cmd/layout/picture.rs @@ -15,7 +15,7 @@ pub(in crate::cmd::layout) const PICTURE_ADDRESS: &str = "a picture is read from /// A `path` given in the browser. pub(in crate::cmd::layout) const PICTURE_PATH_IN_BROWSER: &str = "a picture's path can't be read in the browser, which has no file paths: give its image"; -/// What a refusal calls a file that can't be read when its path has no file name. +/// What a refusal calls a file that can't be read when its path has no file name it can say. pub(in crate::cmd::layout) const PICTURE_FILE_UNNAMED: &str = "the picture's file"; /// Both `image` and `path` given. pub(in crate::cmd::layout) const PICTURE_BOTH: &str = "give a picture an image or a path, not both"; @@ -91,7 +91,8 @@ pub(crate) fn gives_picture(p: &Value) -> bool { /// are given, either is of the wrong kind, the file can't be read or isn't a PNG or JPEG of at most /// 16 MiB, or the image can't be drawn. A file that can't be read is named in the refusal by its /// name ([`rustgis_map::layout::picture_file_name`]), never by the path given, which could hold -/// folders or a login; a path without a name says [`PICTURE_FILE_UNNAMED`]. +/// folders or a login; a path without a name, or with a name holding a control or direction +/// character, says [`PICTURE_FILE_UNNAMED`]. /// /// Runs on the command's thread (the UI thread in the app): bounded work, not work that grows with /// a layer. The file is read whole, as `layout.addElement` always read it, at most 16 MiB @@ -117,7 +118,10 @@ pub(in crate::cmd::layout) fn picture_given(p: &Value) -> Result return Err(PICTURE_IMAGE.into()), (None, Some(path)) => { - let named = rustgis_map::layout::picture_file_name(path).unwrap_or(PICTURE_FILE_UNNAMED); + // A name with a control or direction character would break or reorder the refusal. + let named = rustgis_map::layout::picture_file_name(path) + .filter(|name| name.chars().all(|c| rustgis_data::io::dbf_notice_char(c) == c)) + .unwrap_or(PICTURE_FILE_UNNAMED); let image = crate::cmd::graphics::picture_file(path, named)?; let kept = rustgis_map::layout::picture_source_kept(path); GivenPicture { image, source: kept.then(|| path.to_string()), unremembered: !kept, given_image: false } diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index 64dd5e2b98..825cd59474 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -541,6 +541,9 @@ fn a_refused_picture_file_is_named_by_its_name_never_the_path_given() { vec!["secret", "user", "example"], ), ("https:user:pw@host/x.png".into(), format!("x.png: {}", system("https:user:pw@host/x.png")), vec!["pw@", "user", "host/"]), + // A name that would break a line or reorder the refusal isn't said either. + (at("a\u{202E}gnp.png"), format!("the picture's file: {}", system(&at("a\u{202E}gnp.png"))), vec!["logos", "gnp", &temp]), + (at("a\u{2028}b.png"), format!("the picture's file: {}", system(&at("a\u{2028}b.png"))), vec!["logos", "b.png", &temp]), ]; let state = |s: &Session| (serde_json::to_value(&s.project).unwrap(), s.undo_depth(), s.dirty()); let before = state(&s); From 78d1018edbccbe103f0d4b040d58c18826c9bd4c Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sun, 29 Nov 2026 01:42:36 -0600 Subject: [PATCH 35/38] fix(layout): the grey-box notice says its button is the app's The notice also reaches the command line, Python and the Assistant, which have no Format pane. Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout/picture.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/crates/render/src/layout/picture.rs b/crates/render/src/layout/picture.rs index aea3362a9b..898d0ac151 100644 --- a/crates/render/src/layout/picture.rs +++ b/crates/render/src/layout/picture.rs @@ -108,11 +108,11 @@ fn notice_cut(s: &str) -> String { } /// How a notice says to give a picture its image again: in the browser, which has no file paths, -/// by its image; elsewhere, from its file. +/// by its image; elsewhere, from its file, by the command and, for the app's user, by its button. const WAY_BACK: &str = if cfg!(target_arch = "wasm32") { "give one its image again with layout.update and \"image\"" } else { - "read one from its file again with layout.update and \"path\" (Choose File… in the Format pane)" + "read one from its file again with layout.update and \"path\" (in the app, Choose File… in the Format pane)" }; /// What is said of `gaps`: one notice for each [`PictureLoss`] among them, in its order, with the From e6815c994c02043b2747ee9671dd9cd0fade93dd Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:46:09 -0600 Subject: [PATCH 36/38] perf(render): let go the decoded pictures of a project that is gone The layout view forgets the thread's decoded pictures when it follows another project, so a closed project's pictures aren't held until others replace them. Co-Authored-By: Claude Fable 5.2 --- crates/render/src/lib.rs | 7 +++++++ crates/render/src/picture.rs | 15 ++++++++++++++- crates/ui-egui/src/layoutview.rs | 2 ++ 3 files changed, 23 insertions(+), 1 deletion(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 5f6593653b..03611e052f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -630,6 +630,13 @@ pub fn picture_drawn_size(b64: &str) -> Option<(u32, u32)> { picture::decoded(b64).map(|pm| (pm.width(), pm.height())) } +/// Lets go the decoded pictures the calling thread keeps for layouts and map graphics, up to +/// the cache's budget: for when the project they were drawn for is gone. One drawn again is +/// decoded again, once. +pub fn forget_decoded_pictures() { + picture::forget_decoded(); +} + pub use picture::{MARKER_PIXELS, MARKER_PIXELS_SIDE, MarkerRefusal, RUN_MARKER_BYTES, RUN_MARKER_PIXELS, SVG_DEPTH, SVG_XML_NODES}; /// Base64 `b64` as a picture marker's image (one kept already, or one before it is set): its diff --git a/crates/render/src/picture.rs b/crates/render/src/picture.rs index 79dd0ae7d5..492f00aad3 100644 --- a/crates/render/src/picture.rs +++ b/crates/render/src/picture.rs @@ -560,6 +560,12 @@ pub(crate) fn decodes() -> usize { DECODES.with(std::cell::Cell::get) } +/// Lets go every decoded picture this thread keeps ([`decoded`]): a picture drawn again is +/// decoded again, once. +pub(crate) fn forget_decoded() { + DECODED.with(|cache| *cache.borrow_mut() = Cache::default()); +} + /// The bytes this thread's cache of decoded pictures holds ([`held`]). #[cfg(test)] fn held_here() -> usize { @@ -1146,7 +1152,8 @@ mod tests { /// The decoded pictures' cache holds at most its budget, or the newest picture alone where that /// one holds more: under the budget none is let go early; a picture past it is kept alone, and - /// let go when the next is decoded. Told with a small budget, on a thread of its own. + /// let go when the next is decoded; forgetting them lets all go. Told with a small budget, on a + /// thread of its own. #[test] fn decoded_pictures_are_kept_within_the_budget_or_the_newest_alone() { std::thread::spawn(|| { @@ -1169,6 +1176,12 @@ mod tests { assert_eq!(decodes(), n + 1, "the large one drawn again isn't decoded again"); assert!(decoded_within(&a, budget).is_some()); assert_eq!((held_here(), decodes()), (size(&a), n + 2), "the large one let go for the next"); + // Forgotten, as when their project is gone: nothing is held, and one drawn again is + // decoded again. + forget_decoded(); + assert_eq!(held_here(), 0); + assert!(decoded_within(&a, budget).is_some()); + assert_eq!((held_here(), decodes()), (size(&a), n + 3)); }) .join() .unwrap(); diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index 4a2920757a..f88feafe42 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -242,6 +242,8 @@ pub(crate) fn follow_project(app: &mut RustGisApp) { app.layout.profile_warning.clear(); app.layout.text_losses = None; app.layout.views.clear(); + // The pictures decoded for the project that is gone aren't kept for this one. + rustgis_engine::render::forget_decoded_pictures(); } app.layout.project = Some(opened); // A page view stays with its layout: one removed or renamed leaves none for a new layout From 570a4592619ec17368ef828aa6125f6b1d7e7191 Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sun, 29 Nov 2026 09:03:03 -0600 Subject: [PATCH 37/38] docs(render): say which test a picture off the page is told by Co-Authored-By: Claude Fable 5.2 --- crates/render/src/layout/picture.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/render/src/layout/picture.rs b/crates/render/src/layout/picture.rs index 898d0ac151..9257ef4eb7 100644 --- a/crates/render/src/layout/picture.rs +++ b/crates/render/src/layout/picture.rs @@ -83,7 +83,7 @@ pub struct PictureGap { /// The visible pictures of `layout` whose image doesn't draw ([`picture_draws`]), drawn as a grey /// box, in the order of its elements. A hidden picture draws nothing and isn't listed, nor is one -/// with none of its box on the page ([`on_page`], the test a legend's pictures are waited by): +/// with none of its box on the page ([`on_page`], the test legend pictures are checked by): /// the page shows none of its grey box. pub fn pictures_not_drawn(layout: &Layout) -> Vec { let gaps = layout.elements.iter().filter(|e| e.visible && on_page(layout, e)).filter_map(|e| { From e19286b2b0f7caefdf633e96ded122cac93e1f5c Mon Sep 17 00:00:00 2001 From: m-hollis-1 <207106921+m-hollis-1@users.noreply.github.com> Date: Sun, 29 Nov 2026 13:27:58 -0600 Subject: [PATCH 38/38] fix(layout): a login and a host in a path's first part read as an address An at sign and a colon together before the first separator (a drive's own colon aside) are a login and a host, with or without a file after them, so they are refused without being repeated and never kept as a picture's file. Co-Authored-By: Claude Fable 5.2 --- crates/engine/src/tests/layout_pictures.rs | 11 +++---- crates/map/src/layout/picture.rs | 36 ++++++++++++++-------- 2 files changed, 28 insertions(+), 19 deletions(-) diff --git a/crates/engine/src/tests/layout_pictures.rs b/crates/engine/src/tests/layout_pictures.rs index ead7f8a04d..95dc3e9274 100644 --- a/crates/engine/src/tests/layout_pictures.rs +++ b/crates/engine/src/tests/layout_pictures.rs @@ -531,6 +531,7 @@ fn a_refused_picture_file_is_named_by_its_name_never_the_path_given() { let system = |path: &str| std::fs::metadata(path).unwrap_err().to_string(); let undrawn = "the picture can't be drawn: its image is damaged, or too large (over 20000 pixels a side, or over 512 MB once decoded)"; let no_name = format!("{temp}{}", std::path::MAIN_SEPARATOR); + let address = "a picture is read from a file on this computer, not an address"; let cases: Vec<(String, String, Vec<&str>)> = vec![ (at("missing.png"), format!("missing.png: {}", system(&at("missing.png"))), vec!["logos", &temp]), (at("folder.png"), "folder.png: not a regular file".into(), vec!["logos", &temp]), @@ -538,12 +539,10 @@ fn a_refused_picture_file_is_named_by_its_name_never_the_path_given() { (at("big.png"), "the picture is too large".into(), vec!["logos", &temp]), (huge.clone(), undrawn.into(), vec![&temp]), (no_name.clone(), "the picture's file: not a regular file".into(), vec![&temp]), - ( - "user:secret@example.invalid/x.png".into(), - format!("x.png: {}", system("user:secret@example.invalid/x.png")), - vec!["secret", "user", "example"], - ), - ("https:user:pw@host/x.png".into(), format!("x.png: {}", system("https:user:pw@host/x.png")), vec!["pw@", "user", "host/"]), + // A login and a host in the first part read as an address, with or without a file after. + ("user:secret@example.invalid/x.png".into(), address.into(), vec!["secret", "user", "example"]), + ("user:secret@example.invalid".into(), address.into(), vec!["secret", "user", "example"]), + ("https:user:pw@host/x.png".into(), address.into(), vec!["pw@", "user", "host/"]), // A name that would break a line or reorder the refusal isn't said either. (at("a\u{202E}gnp.png"), format!("the picture's file: {}", system(&at("a\u{202E}gnp.png"))), vec!["logos", "gnp", &temp]), (at("a\u{2028}b.png"), format!("the picture's file: {}", system(&at("a\u{2028}b.png"))), vec!["logos", "b.png", &temp]), diff --git a/crates/map/src/layout/picture.rs b/crates/map/src/layout/picture.rs index 6b4dc6485b..ab50110a97 100644 --- a/crates/map/src/layout/picture.rs +++ b/crates/map/src/layout/picture.rs @@ -24,23 +24,27 @@ pub fn picture_source_kept(path: &str) -> bool { /// Whether `path` reads as an address, not a file. It does when it holds `://` anywhere, or when, /// after leading blanks, it begins with a scheme of two or more characters (a letter, then letters, /// digits, `+`, `-` or `.`), a colon and a `/` or `\` (`s3:/bucket/a.png`), or its first part -/// (all before the first `/` or `\`) holds an `@` and, after that `@`, a colon: a login before a -/// host (`user:pw@host:/a.png`, `git@host:logos/a.png`), which could carry a password. +/// (all before the first `/` or `\`, a drive's letter and colon set aside) holds both an `@` and +/// a colon: a login and a host (`user:pw@host`, `user:pw@host:/a.png`, `git@host:logos/a.png`, +/// `mailto:a@b`), which could carry a password. /// -/// These stay files: a drive (`C:\a.png`; one letter is never a scheme), a share +/// These stay files: a drive (`C:\a.png`, `C:me@corp.png`; one letter is never a scheme), a share /// (`\\server\share\a.png`), a name with a colon and no separator after it (`a:b.png`), and a -/// name with an `@` and no colon after it in the first part (`logo@2x.png`, `me@corp/a.png`). -/// `mailto:a@b` and `data:image/png;base64,…` are left as paths: no rule tells them from a file -/// name holding a colon, and none opens as a file unless it is one. The cost: a relative path whose -/// first folder ends in a colon, or whose first part holds an `@` followed by a colon, reads as an -/// address; give it as `./…` (`./folder:/a.png`, `./me@host:/a.png`). +/// name with an `@` and no colon in the first part (`logo@2x.png`, `me@corp/a.png`). +/// `data:image/png;base64,…` is left as a path: no rule tells it from a file name holding a colon, +/// and it doesn't open as a file unless it is one. The cost: a relative path whose first folder +/// ends in a colon, or whose first part holds both an `@` and a colon, reads as an address; give +/// it as `./…` (`./folder:/a.png`, `./ab:c@2x.png`). pub fn picture_path_is_address(path: &str) -> bool { if path.contains("://") { return true; } let path = path.trim_start(); let first = path.split(['/', '\\']).next().unwrap_or_default(); - if first.split_once('@').is_some_and(|(_, host)| host.contains(':')) { + // A drive's letter and colon aren't a login's. + let drive = first.as_bytes().first().is_some_and(u8::is_ascii_alphabetic) && first.as_bytes().get(1) == Some(&b':'); + let login = if drive { first.get(2..).unwrap_or_default() } else { first }; + if login.contains('@') && login.contains(':') { return true; } let Some((scheme, rest)) = path.split_once(':') else { return false }; @@ -174,7 +178,7 @@ mod tests { } /// Paths that read as an address. - const ADDRESSES: [&str; 16] = [ + const ADDRESSES: [&str; 20] = [ "https://user:pw@host/a.png", "file:///data/x.png", "/vsicurl/https://host/a.png", @@ -191,11 +195,16 @@ mod tests { "git@example.invalid:logos/a.png", " user:pw@host:/a.png", r"user:pw@host:\a.png", + "user:pw@host", + "user:pw@host/x.png", + "mailto:a@b", + "ab:c@2x.png", ]; /// An address is `://` anywhere, a scheme of two or more characters, a colon and a separator, - /// or a login before a host and a colon in the first part; a drive, a share, a name with a - /// colon or an `@`, and the forms no rule can tell from a file name, are paths. + /// or an `@` and a colon together in the first part (a login and a host); a drive, a share, + /// a name with a colon or an `@` alone, and the form no rule can tell from a file name, are + /// paths. #[test] fn an_address_is_told_from_a_path() { for path in ADDRESSES { @@ -214,7 +223,6 @@ mod tests { "ab:c.png", "logo@2x.png", "./folder:/a.png", - "mailto:a@b", "data:image/png;base64,AAAA", "logos/me@host:/a.png", "/data/user@host:/a.png", @@ -223,7 +231,9 @@ mod tests { r"\\server\share\me@corp:x\a.png", "./user@host:/a.png", "me@corp/a.png", + "C:me@corp.png", "a:b@2x.png", + "./ab:c@2x.png", "", ] { assert!(!picture_path_is_address(path), "{path:?}");