diff --git a/crates/assistant/skills/print-layout/SKILL.md b/crates/assistant/skills/print-layout/SKILL.md index 3eb6c356e8..f0b62327f3 100644 --- a/crates/assistant/skills/print-layout/SKILL.md +++ b/crates/assistant/skills/print-layout/SKILL.md @@ -29,11 +29,12 @@ description: Make a printable page layout — map frame, title, legend, north ar text or add columns to fit its box), `"subtitle"` (one line under its title), `"sizes": "nested"` (a point layer's marker sizes one inside another on a common base), `"showCounts": true` (each class row ends in its number of features; none for a layer read from a database, over the web or a view at a time from other files), `"showLayerNames": false`, `"layerOrder": [""]` (those layers first, the map unchanged) and `"classLabels"` (`{"": {"": ""}}`: its own text for a class, the layer keeping its label). - A `"text"` or `"dynamicText"` can take + 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", "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. diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index c3d917b6e3..af5ded0e13 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -305,7 +305,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? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? labels? classLabels? columns? textSize? showLayerNames? sizes? showCounts? 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? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? 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? subtitle? allClasses? hideOther? showNoData? exclude? layerOrder? labels? classLabels? columns? textSize? showLayerNames? sizes? showCounts? 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? band? side? gap? thickness? unit? lineColor? lineWidth? min? guides? 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..de5b9e43a7 100644 --- a/crates/engine/src/cmd/graphics.rs +++ b/crates/engine/src/cmd/graphics.rs @@ -401,13 +401,22 @@ 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, 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. 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. +pub(crate) fn checked_picture(b64: String) -> Result { if b64.len() > MAX_PICTURE / 3 * 4 + 4 { return Err("the picture is too large".into()); } @@ -417,7 +426,8 @@ pub(crate) fn picture(p: &Value) -> 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), @@ -436,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(), } } @@ -449,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.rs b/crates/engine/src/cmd/layout.rs index 38c3e29c04..ec2776aaa2 100644 --- a/crates/engine/src/cmd/layout.rs +++ b/crates/engine/src/cmd/layout.rs @@ -45,6 +45,10 @@ use legend::*; pub(crate) use legend::{ legend_columns_param, legend_counts_param, legend_fit_param, legend_names_param, legend_sizes_param, legend_subtitle_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::*; mod profile; @@ -232,7 +236,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 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; profile: a raster layer held whole, not read in place, default the top one shown), "##, 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), "##, @@ -393,6 +397,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, 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/elements.rs b/crates/engine/src/cmd/layout/elements.rs index f8b1ca8c53..6301dccfea 100644 --- a/crates/engine/src/cmd/layout/elements.rs +++ b/crates/engine/src/cmd/layout/elements.rs @@ -266,6 +266,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")?; // A profile reads its own keys (#2863 part 2), several of them other kinds' too. if kind == "profile" { @@ -391,7 +392,9 @@ pub(in crate::cmd::layout) fn add_element(s: &mut Session, p: &Value) -> CmdResu BackgroundParam::Absent | BackgroundParam::Remove => None, }; 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 { @@ -510,7 +513,8 @@ 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() }) + 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)?; @@ -734,6 +738,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); + } let mut held = held_to_limits(p, Shape::of_name(kind)); if kind == "table" { held.extend(held_rows(p)); diff --git a/crates/engine/src/cmd/layout/export.rs b/crates/engine/src/cmd/layout/export.rs index 6883e3fc53..ca729ff4f3 100644 --- a/crates/engine/src/cmd/layout/export.rs +++ b/crates/engine/src/cmd/layout/export.rs @@ -61,7 +61,7 @@ fn layout_bytes_for( /// 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, -/// charts' notices. +/// pictures drawn as a grey box, charts' notices. 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) { @@ -83,6 +83,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 mut profiles: ProfileNotes = rustgis_render::layout::profiles_not_drawn(&layout, &s.project.maps).into_iter().map(|n| (n, 1)).collect(); if let Some(r) = region { @@ -111,6 +115,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, ""); for note in rustgis_render::layout::profiles_notice(&profiles, 1) { s.warn(note); } @@ -318,6 +323,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), ""); for note in rustgis_render::layout::profiles_notice(&profiles, pages.len()) { s.warn(note); } @@ -555,6 +562,7 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd 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 profiles: ProfileNotes = rustgis_render::layout::profiles_not_drawn(layout, &s.project.maps).into_iter().map(|n| (n, 1)).collect(); let ((drawn, unfitted), charts) = rustgis_render::layout::drawn_charts(|| { rustgis_render::layout::unfitted_legends(|| { @@ -568,6 +576,7 @@ fn layout_svg(s: &mut Session, li: usize, dpi: f64, download: Option<(crate::cmd for note in [note, rustgis_render::layout::sections_notice(&gaps, 1)].into_iter().flatten() { s.warn(note); } + say_pictures_not_drawn(s, &grey, ""); for note in rustgis_render::layout::profiles_notice(&profiles, 1) { s.warn(note); } diff --git a/crates/engine/src/cmd/layout/picture.rs b/crates/engine/src/cmd/layout/picture.rs new file mode 100644 index 0000000000..a7beea6403 --- /dev/null +++ b/crates/engine/src/cmd/layout/picture.rs @@ -0,0 +1,159 @@ +//! 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 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"; +/// 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"; + +/// 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 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 or direction characters, over {} bytes or \ + without a file name isn't kept", + rustgis_map::layout::MAX_PICTURE_SOURCE + ) +} + +/// 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) { + 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. + 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, + /// 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 +/// 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()), + } +} + +/// 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. 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, 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 +/// (`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() { + return Err(PICTURE_BOTH.into()); + } + let picture = match (given("image"), picture_path_param(p)?) { + (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)) => { + // 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 } + } + (None, None) => return Ok(None), + }; + if !rustgis_render::layout::picture_draws(&picture.image) { + return Err(picture_undrawn()); + } + Ok(Some(picture)) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// In the browser a path is refused before anything is read, saying why and what to give + /// instead; elsewhere it is taken as given. Blank, null and the wrong kind answer as anywhere. + #[test] + fn a_path_is_refused_in_the_browser_before_it_is_read() { + let browser = "a picture's path can't be read in the browser, which has no file paths: give its image"; + for path in ["logo.png", "/no/such/folder/logo.png", "https://example.invalid/logo.png"] { + let p = serde_json::json!({"path": path}); + assert_eq!(picture_path_param_in(&p, true), Err(browser.to_string()), "{path}"); + } + assert_eq!(picture_path_param_in(&serde_json::json!({"path": "logo.png"}), false), Ok(Some("logo.png"))); + for web in [true, false] { + assert_eq!(picture_path_param_in(&serde_json::json!({"path": null}), web), Ok(None)); + assert_eq!(picture_path_param_in(&serde_json::json!({}), web), Ok(None)); + for blank in [serde_json::json!(" "), serde_json::json!(5)] { + assert_eq!(picture_path_param_in(&serde_json::json!({"path": blank}), web), Err(PICTURE_PATH.to_string())); + } + } + } +} diff --git a/crates/engine/src/cmd/layout/update.rs b/crates/engine/src/cmd/layout/update.rs index 72b30bf8b6..bbdd617ed5 100644 --- a/crates/engine/src/cmd/layout/update.rs +++ b/crates/engine/src/cmd/layout/update.rs @@ -508,6 +508,17 @@ 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); + // 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 @@ -784,6 +795,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 @@ -791,6 +807,12 @@ 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 forgotten { + s.notify(PICTURE_FORGOTTEN, false); + } if fit { say_legend_fit(s, li, id); } diff --git a/crates/engine/src/cmd/presentation.rs b/crates/engine/src/cmd/presentation.rs index 7526c486b5..a5d1bbc059 100644 --- a/crates/engine/src/cmd/presentation.rs +++ b/crates/engine/src/cmd/presentation.rs @@ -430,7 +430,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/cmd/report.rs b/crates/engine/src/cmd/report.rs index 44acf215e4..f364af07bb 100644 --- a/crates/engine/src/cmd/report.rs +++ b/crates/engine/src/cmd/report.rs @@ -1220,6 +1220,7 @@ fn report_pages_bytes( say_report_charts(s, &charts); say_report_clipped(s, &clipped); say_sections_not_drawn(s, pages, 1); + say_report_pictures(s, pages, 1); let png = super::exports::held_to(download, |limit| rustgis_render::png::within(&img, limit))?; return Ok((png, pages.len())); } @@ -1257,6 +1258,7 @@ fn report_pages_bytes( say_report_clipped(s, &clipped); super::layout::pictured_notices(s, &frames_pictured, &pages_pictured); say_sections_not_drawn(s, pages, n); + say_report_pictures(s, pages, n); let pdf = super::exports::held_to(download, |limit| rustgis_render::pdf::write_within(&out, &doc.title, limit))?; Ok((pdf, pages.len())) } @@ -1308,6 +1310,27 @@ fn say_profiles_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.layout = Some(layout.name.clone()); + gaps.push(gap); + } + } + super::layout::say_pictures_not_drawn(s, &gaps, "The report: "); +} + /// Runs `f`, and returns its result with the legends it drew under a fit still cut and the charts /// it drew. fn listing(f: impl FnOnce() -> T) -> (T, Vec, Vec) { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index eb8c134718..8ba86d42a4 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -128,6 +128,7 @@ pub const CAPABILITIES: &[&str] = &[ "layout-legend-subtitle", "layout-legend-nested-sizes", "layout-legend-order", + "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 c9a87a52d2..9805dc9de6 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -178,6 +178,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-legend-subtitle", command_uses_legend_subtitle), ("layout-legend-nested-sizes", command_uses_legend_nested_sizes), ("layout-legend-order", command_uses_legend_order), + ("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), @@ -611,6 +612,31 @@ fn legend_subtitle_features(e: &rustgis_map::layout::Element) -> bool { e.kind.legend_subtitle_features() } +/// 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. @@ -1498,6 +1524,7 @@ fn layout_capabilities(layouts: &[rustgis_map::layout::Layout]) -> Vec<&'static (elements().any(legend_subtitle_features), "layout-legend-subtitle"), (elements().any(legend_nested_sizes_features), "layout-legend-nested-sizes"), (elements().any(legend_orders_layers), "layout-legend-order"), + (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"), @@ -1876,6 +1903,7 @@ mod tests { (&["layout-legend-nested-sizes"], "layout.update", json!({"element": 1, "sizes": "nested"})), (&["layout-legend-subtitle"], "layout.update", json!({"element": 1, "subtitle": "a"})), (&["layout-legend-order"], "layout.update", json!({"element": 1, "layerOrder": ["a"]})), + (&["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})), @@ -2745,6 +2773,78 @@ 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_within(&fixture.layouts[1], Output::UNLIMITED) + .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.rs b/crates/engine/src/tests.rs index 7a4ebb2263..cb8f85b0f9 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -116,6 +116,8 @@ mod elevation_tiles; #[path = "tests/layout_files.rs"] mod layout_files; +#[path = "tests/layout_pictures.rs"] +mod layout_pictures; #[path = "tests/layout_profiles.rs"] mod layout_profiles; #[path = "tests/layout_sections.rs"] diff --git a/crates/engine/src/tests/layout_files.rs b/crates/engine/src/tests/layout_files.rs index b71d2a153b..e7a6fdefb8 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(); @@ -133,6 +140,7 @@ fn a_saved_layout_file_requires_what_its_elements_use_and_reads_back_the_same() ("legend-subtitle", include_str!("../../../../schema/fixtures/layout_legend_subtitle.rgis")), ("legend-nested-sizes", include_str!("../../../../schema/fixtures/layout_legend_nested_sizes.rgis")), ("legend-order", include_str!("../../../../schema/fixtures/layout_legend_order.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")), @@ -211,6 +219,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 new file mode 100644 index 0000000000..95dc3e9274 --- /dev/null +++ b/crates/engine/src/tests/layout_pictures.rs @@ -0,0 +1,805 @@ +//! 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: 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 _; + 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()) +} + +/// 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"))] +const PIN_PNG: &str = concat!( + "iVBORw0KGgoAAAANSUhEUgAAACgAAAAUCAYAAAD/Rn+7AAAAWElEQVR4nO3VMQ2AUBAE0WHzfYAoSnAD1khQdUig", + "uYQpeAIm2+2Yt6NodK9XZ44gF+SCXJALckEuyAW5IDdVVeuTdBvLfrYG7//qZIJckAtyQS7I5esBbx4rIwruG4R9", + "JwAAAABJRU5ErkJggg==", +); + +/// 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"))] +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; 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; 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, 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() { + 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; + } + 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 backed = json!({"fill": "#FFF3D6", "outline": "#222222", "width": 1, "padding": 2}); + let mut added = Vec::new(); + for p in [ + 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}), + ] { + 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_within(&s.project.layouts[li], crate::cmd::exports::Output::UNLIMITED).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!({"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 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(); + let mut said = |route: &str, s: &mut Session, run: &dyn Fn(&mut Session)| { + let mark = s.notice_mark(); + 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 + // 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(PIN_PNG).unwrap(); + let pixels = bytes.windows(4).position(|w| w == b"IDAT").unwrap() + 4; + base64::engine::general_purpose::STANDARD.encode(&bytes[..pixels + 4]) + }; + 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(); + 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"), (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 too large (over 20000 pixels a side, or over 512 MB once decoded)"; + 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 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!("")), "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 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"), + ("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), + ]; + 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) => 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. 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 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)", + ), + ] { + 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 {:?}", marked(e, &path).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")); +} + +/// 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(); + // 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; + 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"}}} + ]}); + 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 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 [ + // 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), + (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 an 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"); + } + // 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 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"); + } + } + // 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"); + } + let depth = s.undo_depth(); + s.run("layout.update", &json!({"element": text, "path": null, "image": null})).unwrap(); + 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); + 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": "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 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"), + ] { + 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 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 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]), + (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]), + // 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]), + ]; + 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] +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"); + // 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(); + 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 +/// 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": crate::project::FORMAT, + "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}"); + } +} + +/// 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 "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:?}"); + // 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:?}"); + } +} + +/// 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/crates/map/src/layout.rs b/crates/map/src/layout.rs index 7c052fa979..848691d9de 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 profile; mod scale_bar; mod section; @@ -36,6 +37,7 @@ pub use grid::*; pub use legend::*; pub use lines::*; pub use north::*; +pub use picture::*; pub use profile::*; pub use scale_bar::*; pub use section::*; @@ -521,7 +523,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 @@ -717,13 +719,19 @@ 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, ElementKind::Profile(p) => cut |= p.clamp(), _ => {} } // 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 a43112b99a..3866020def 100644 --- a/crates/map/src/layout/elements.rs +++ b/crates/map/src/layout/elements.rs @@ -249,6 +249,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..ab50110a97 --- /dev/null +++ b/crates/map/src/layout/picture.rs @@ -0,0 +1,290 @@ +//! 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 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.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) +} + +/// 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 `\`, 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`, `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 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(); + // 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 }; + 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(['/', '\\']).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`), +/// 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); + } + + /// 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() { + 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)); + 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(), + ]; + 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)))); + } + + /// 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 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; 20] = [ + "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", + "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", + "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 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 { + 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", + "data:image/png;base64,AAAA", + "logos/me@host:/a.png", + "/data/user@host:/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", + "me@corp/a.png", + "C:me@corp.png", + "a:b@2x.png", + "./ab:c@2x.png", + "", + ] { + assert!(!picture_path_is_address(path), "{path:?}"); + } + } + + /// 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 + Some(json!("user:secret@example.invalid:/logo.png")), // 10: an address + ]; + 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..=10 { + assert_eq!(source(id), None, "{id}"); + } + 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. + 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 c0541597bd..a577188ca2 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 profile; mod scale_bar; mod section; @@ -44,6 +45,7 @@ pub use grid::*; pub use legend::*; pub use losses::*; use north::*; +pub use picture::*; pub use profile::*; pub use scale_bar::*; pub use section::*; @@ -661,8 +663,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); @@ -670,15 +672,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 { @@ -1107,6 +1108,106 @@ 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: 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 _; + 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() +} + +/// 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")))] +pub(crate) const PIN_PNG: &str = concat!( + "iVBORw0KGgoAAAANSUhEUgAAACgAAAAUCAYAAAD/Rn+7AAAAWElEQVR4nO3VMQ2AUBAE0WHzfYAoSnAD1khQdUig", + "uYQpeAIm2+2Yt6NodK9XZ44gF+SCXJALckEuyAW5IDdVVeuTdBvLfrYG7//qZIJckAtyQS7I5esBbx4rIwruG4R9", + "JwAAAABJRU5ErkJggg==", +); + +/// 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")))] +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, [`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, 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); + for (image, at) in pictures { + l.add("Picture", *at, ElementKind::Picture { image: (*image).to_string(), source: None }); + } + 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))]), + page(&[(png, (10.0, 10.0, 0.6, 0.3))]), + ] + .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/picture.rs b/crates/render/src/layout/picture.rs new file mode 100644 index 0000000000..9257ef4eb7 --- /dev/null +++ b/crates/render/src/layout/picture.rs @@ -0,0 +1,386 @@ +//! 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; +/// 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 "…". +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() +} + +/// 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 +/// 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 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) { + 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); + } + } +} + +/// 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 too large (over [`PICTURE_MAX_DECLARED`] pixels a side, + /// or over [`PICTURE_MAX_DECODED_MB`] MiB once decoded). + 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 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, +} + +/// 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 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| { + 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(), layout: None, 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(), + } +} + +/// 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 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\" (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 +/// 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() + .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| { + 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 { + 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 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}; {WAY_BACK}")) + }) + .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), 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(); + 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()); + // 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. + #[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")); + } + + /// 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() { + let mut gaps: Vec = (1..=12) + .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(), 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); "; + 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 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()); + } + + /// 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] + 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/layout/tests.rs b/crates/render/src/layout/tests.rs index 14402cc912..547d9bd1db 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -6246,6 +6246,80 @@ 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; then a map graphic's picture twice. +#[cfg(not(target_arch = "wasm32"))] +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 + 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) + 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 + 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: thirteen drawings. Then a map graphic's picture as a map draws it +/// (`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"))] +#[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)))); + } + } + 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")); +} + /// 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/lib.rs b/crates/render/src/lib.rs index c8defdf88c..772b85dd34 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -630,9 +630,17 @@ 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())) +} + +/// 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}; diff --git a/crates/render/src/picture.rs b/crates/render/src/picture.rs index e3c070d4df..492f00aad3 100644 --- a/crates/render/src/picture.rs +++ b/crates/render/src/picture.rs @@ -20,10 +20,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. +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; const CACHE_BYTES: usize = 256 << 20; /// Picture markers are drawn from at most this many pixels per side: an 80 pt marker printed at @@ -152,7 +153,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`]). @@ -162,6 +163,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. @@ -485,25 +489,87 @@ 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, 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) +} + +/// [`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.as_str()) { - // 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 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); } - if cache.images.insert(key, (b64.clone(), decode(b64).map(Arc::new))).is_none() { - cache.order.push_back(key); + #[cfg(test)] + DECODES.with(|n| n.set(n.get() + 1)); + 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); } - 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); - }); + if !hit { + fit(&mut cache, key, budget); + } + cache.images.get(&key).and_then(|(_, img)| img.clone()) + }) +} + +/// 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 }; + 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() +} + +/// How many pictures [`decoded`] has decoded on this thread. +#[cfg(test)] +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 { + DECODED.with(|cache| held(&cache.borrow())) } /// Runs `f` on picture marker `p`'s decoded image, its height for its width and, with `pack`, the @@ -1083,4 +1149,63 @@ 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; 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(|| { + 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"); + // 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(); + } + + /// 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(); + } } diff --git a/crates/render/src/svg.rs b/crates/render/src/svg.rs index 02e8454cfa..b1d5d75f72 100644 --- a/crates/render/src/svg.rs +++ b/crates/render/src/svg.rs @@ -630,7 +630,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; @@ -1046,4 +1046,68 @@ 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; 11] = [ + 0x4942_1842_02a6_e13c, // 1: the PNG in a wider box + 0xa7c0_17e7_a596_aa3d, // 2: the PNG in a taller box + 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) + 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 + 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; 11] = [ + 0x200d_c9c7_cd54_9cbd, // 1: the PNG in a wider box + 0xe045_9691_934f_1fe9, // 2: the PNG in a taller box + 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) + 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 + 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: 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() { + 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")); + } } diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index aca784b454..ae35f1a33c 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -61,6 +61,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 @@ -119,6 +135,12 @@ 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 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 last notices of the profiles the page doesn't draw, or draws from fewer samples than /// cells or with gaps (#2863). profile_warning: Vec, @@ -215,9 +237,13 @@ 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.pictures_checked = None; 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 @@ -293,6 +319,8 @@ impl LayoutView { } self.text_warning = None; self.section_warning = None; + self.picture_warning = None; + self.pictures_checked = None; self.profile_warning.clear(); self.text_losses = None; if let Some(old) = self.viewed.replace(name.to_string()) { @@ -435,6 +463,10 @@ pub fn show(app: &mut RustGisApp, ui: &mut Ui) { } app.layout.section_warning = note; } + if app.layout.pictures_checked != Some((li, key.0)) { + say_pictures_not_drawn(app, &layout); + app.layout.pictures_checked = Some((li, key.0)); + } // From what the drawing read, not read again. let notes = pending.profiles.into_iter().map(|n| (n, 1)).collect(); let said = rustgis_engine::render::layout::profiles_notice(¬es, 1); diff --git a/crates/ui-egui/src/layoutview/format.rs b/crates/ui-egui/src/layoutview/format.rs index 596412bd4e..0136291473 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, FrameShape, INK, LAYOUT_TEXT_SIZE, Layout, MAX_BACKGROUND_PADDING, MAX_BACKGROUND_RADIUS, MAX_BACKGROUND_WIDTH, Orientation, @@ -235,6 +237,7 @@ 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), @@ -412,7 +415,7 @@ fn hides(e: &Element, (x, y): (f64, f64)) -> bool { let (dx, dy) = (x - e.x - e.w / 2.0, y - e.y - e.h / 2.0); let in_box = (0.0..=1.0).contains(&u) && (0.0..=1.0).contains(&v); match &e.kind { - ElementKind::Picture { image } => { + ElementKind::Picture { image, .. } => { in_box && rustgis_engine::render::picture_drawn_size(image).is_none_or(|(iw, ih)| { let s = (e.w / f64::from(iw)).min(e.h / f64::from(ih)); 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..0db3b2fb44 --- /dev/null +++ b/crates/ui-egui/src/layoutview/format/picture.rs @@ -0,0 +1,35 @@ +//! 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 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 { .. }) { + 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().show_tooltip_when_elided(false)).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 d5566fabfe..fbae489fee 100644 --- a/crates/ui-egui/src/layoutview/tests.rs +++ b/crates/ui-egui/src/layoutview/tests.rs @@ -138,7 +138,7 @@ fn ink_reads_each_shape_as_drawn() { fn ink_reads_no_map_or_picture() { let picture = |rect| { move |l: &mut Layout| { - l.add("Picture", rect, ElementKind::Picture { image: String::new() }); + l.add("Picture", rect, ElementKind::Picture { image: String::new(), source: None }); } }; let map = |rect, shape: FrameShape| { @@ -170,7 +170,7 @@ fn ink_reads_no_map_or_picture() { // tall, and leaving it bare in one 100 mm tall. let image = |h: f64, data: &'static str| { move |l: &mut Layout| { - l.add("Picture", (0.0, 0.0, 100.0, h), ElementKind::Picture { image: data.into() }); + l.add("Picture", (0.0, 0.0, 100.0, h), ElementKind::Picture { image: data.into(), source: None }); } }; let wide = "iVBORw0KGgoAAAANSUhEUgAAAAQAAAABCAIAAAB2XpiaAAAAC0lEQVR4nGP4jwQATb8L9davaZUAAAAASUVORK5CYII="; @@ -3361,3 +3361,191 @@ 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 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; + 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 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)); + 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); +} + +/// 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))); +} diff --git a/docs/maintaining.md b/docs/maintaining.md index 909088e08b..93c6155e21 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -366,6 +366,16 @@ draws them and saving the legend again without its order (#3279). Saved `layout. list need nothing. A saved `layout.import` or `report.existingTemplate` carrying 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, 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 (`subdivisions`, `divisions_before_zero`, `label_position`, `unit_label`, `unit_label_position`, diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index fd7b665337..76b6e10fcd 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -782,7 +782,23 @@ 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 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, + 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, 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 + the file, and a script's `"path"` is refused before anything is read: give its `"image"`. - **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 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 70b00a394d..45526b82eb 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1287,6 +1287,7 @@ "layout-legend-subtitle", "layout-legend-nested-sizes", "layout-legend-order", + "layout-picture-source", "layout-scale-bar-details", "label-guide", "label-weight", @@ -1421,6 +1422,7 @@ "layout-legend-subtitle", "layout-legend-nested-sizes", "layout-legend-order", + "layout-picture-source", "layout-scale-bar-details", "label-guide", "label-weight",