diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 2945912d34..63be6b449d 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -347,12 +347,12 @@ pub fn commands() -> Vec { C::new("layer.lineStrokes", "Line Strokes", "Style › Drawing", line_strokes).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_lines_or_points) .params( - r##"{"layer"?, "strokes": [{"color"?: "#RRGGBB"|"#RRGGBBAA"|null (null: the renderer's line colour), "width"?: points|null (null: the renderer's width), "offset"?: points (positive: right of the line's direction, negative: left), "cap"?: "round"|"flat"|"square", "join"?: "round"|"miter"|"bevel", "level"?: 0..255|null (with layer.strokeLevels: the level it draws at; null: its place in the stack), "dash"?: [points, …]|null (dash, gap, … in turn, at most 8; null: solid), "markers"?: {"mark"?: "circle"|"square"|"triangle"|"diamond"|"star"|"character"|"image"|"hash" (a mark across the line), "char"?: text (a character of a font as the marker instead of a shape), "font"?: text (the installed family it is drawn from; none: the label font), "image"?: text (a PNG or JPEG image as base64 of at most 2 MiB, as the marker instead of a shape: as wide as its size, as tall as its proportions make it; the stroke's colour and the outline don't show), "size"?: points (a marker's size, a hash mark's length; default 4), "at"?: "interval"|"vertices"|"innerVertices"|"first"|"last"|"middle"|"segmentMiddles" or a list of them (default "interval"), "interval"?: points (default 12), "offsetAlong"?: points (from the start, back from the end, on from the middle), "rotate"?: bool (turned with the line; default true), "averageAngle"?: points (the stretch of line a marker at an interval turns with; 0: its segment), "angle"?: degrees clockwise (a hash mark at 0 crosses the line square), "outline"?: "#RRGGBB"|"#RRGGBBAA" (the markers' outline, as wide as the stroke)}|null (markers or hash marks along the line in the stroke's colour, instead of a line; cap, join and dash don't apply)}] (drawn bottom first; [] goes back to the single stroke, or for a class to the layer's strokes; on a point layer they are its marks: each stroke's markers drawn at the point in place of the symbol's, "offsetAlong" shifting a mark right and "offset" down, both turned with its "angle", and "rotate" turning it by layer.markerRotation's field), "value"?: text|number (a Unique Values class's own strokes), "index"?: number (a Graduated Colors class's, 0 = the lowest), "other"?: true (Unique Values' )}"##, + r##"{"layer"?, "strokes": [{"color"?: "#RRGGBB"|"#RRGGBBAA"|null (null: the renderer's line colour), "width"?: points|null (null: the renderer's width), "offset"?: points (positive: right of the line's direction, negative: left), "cap"?: "round"|"flat"|"square", "join"?: "round"|"miter"|"bevel", "level"?: 0..255|null (with layer.strokeLevels: the level it draws at; null: its place in the stack), "dash"?: [points, …]|null (dash, gap, … in turn, at most 8; null: solid), "markers"?: {"mark"?: "circle"|"square"|"triangle"|"diamond"|"star"|"character"|"image"|"hash" (a mark across the line), "char"?: text (a character of a font as the marker instead of a shape), "font"?: text (the installed family it is drawn from; none: the label font), "image"?: text (a PNG or JPEG image as base64 of at most 2 MiB and 2048 × 2048 pixels, as the marker instead of a shape: as wide as its size, as tall as its proportions make it; the stroke's colour and the outline don't show), "size"?: points (a marker's size, a hash mark's length; default 4), "at"?: "interval"|"vertices"|"innerVertices"|"first"|"last"|"middle"|"segmentMiddles" or a list of them (default "interval"), "interval"?: points (default 12), "offsetAlong"?: points (from the start, back from the end, on from the middle), "rotate"?: bool (turned with the line; default true), "averageAngle"?: points (the stretch of line a marker at an interval turns with; 0: its segment), "angle"?: degrees clockwise (a hash mark at 0 crosses the line square), "outline"?: "#RRGGBB"|"#RRGGBBAA" (the markers' outline, as wide as the stroke)}|null (markers or hash marks along the line in the stroke's colour, instead of a line; cap, join and dash don't apply)}] (drawn bottom first; [] goes back to the single stroke, or for a class to the layer's strokes; on a point layer they are its marks: each stroke's markers drawn at the point in place of the symbol's, "offsetAlong" shifting a mark right and "offset" down, both turned with its "angle", and "rotate" turning it by layer.markerRotation's field), "value"?: text|number (a Unique Values class's own strokes), "index"?: number (a Graduated Colors class's, 0 = the lowest), "other"?: true (Unique Values' )}"##, ), C::new("layer.fillLayers", "Fill Layers", "Style › Drawing", fill_layers).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_polygon_features) .params( - r##"{"layer"?, "value"?|"index"?|"other"?: a class of Unique Values (its value, or other: true) or Graduated Colors (its index) to set its own fills (none: the layer's), "fills": [{"color"?: "#RRGGBB"|"#RRGGBBAA"|null (null: the feature's fill colour, so the fills follow the classes), "pattern"?: "solid" (default)|"hatch" (parallel lines)|"dots" (markers on a grid)|"gradient" (from color to color2 across the feature)|"shapeburst" (from color at the edge to color2 inside), "angle"?: degrees anticlockwise from east (hatch), "spacing"?: points between lines (hatch, 1 to 500; default 8) or points across and down between markers, a number or [across, down] (dots), "width"?: a hatch line's width in points (0 to 50; default 1), "offset"?: points across the lines (hatch) or [across, down] (dots), "marker"?: "circle"|"square"|"triangle"|"diamond"|"star"|"image" (dots), "char"?: text (dots: a character of a font as the marker instead of a shape), "font"?: text (the installed family it is drawn from; none: the label font), "image"?: text (dots: a PNG or JPEG image as base64 of at most 2 MiB, as the marker instead of a shape: as wide as its size, as tall as its proportions make it; the colour and the outline don't show), "size"?: a marker's size in points (default 3), "outline"?: a marker's outline colour or null, "outlineWidth"?: points, "displacement"?: [across, down] points every other row and column are shifted by (dots), "color2"?: "#RRGGBB"|"#RRGGBBAA" (gradient, shapeburst: the second colour; default white), "stops"?: [[0..1, "#RRGGBB"|"#RRGGBBAA"], …] (gradient, shapeburst: colours between the two, at most 16), "discrete"?: bool (each colour held until the next stop), "shape"?: "linear" (default)|"radial"|"conical" (gradient), "from"?: [across, down]|"centroid" (gradient: where color is, 0..1 in the feature's box; default [0.5, 0], the top middle), "to"?: [across, down]|"centroid" (where color2 is; default [0.5, 1]), "spread"?: "pad" (default)|"reflect"|"repeat" (gradient: past its points), "angle"?: degrees anticlockwise (gradient: turned round its box's middle), "inView"?: bool (gradient: from and to in the map view's box, not the feature's), "distance"?: points|null (shapeburst: how deep it shades; null or none: to the point deepest inside), "blur"?: 0..17 (shapeburst: pixels), "ignoreRings"?: bool (shapeburst: holes' edges left out)}] (bottom first, at most 8; [] for the symbol's single fill; the outline is drawn over them)}"##, + r##"{"layer"?, "value"?|"index"?|"other"?: a class of Unique Values (its value, or other: true) or Graduated Colors (its index) to set its own fills (none: the layer's), "fills": [{"color"?: "#RRGGBB"|"#RRGGBBAA"|null (null: the feature's fill colour, so the fills follow the classes), "pattern"?: "solid" (default)|"hatch" (parallel lines)|"dots" (markers on a grid)|"gradient" (from color to color2 across the feature)|"shapeburst" (from color at the edge to color2 inside), "angle"?: degrees anticlockwise from east (hatch), "spacing"?: points between lines (hatch, 1 to 500; default 8) or points across and down between markers, a number or [across, down] (dots), "width"?: a hatch line's width in points (0 to 50; default 1), "offset"?: points across the lines (hatch) or [across, down] (dots), "marker"?: "circle"|"square"|"triangle"|"diamond"|"star"|"image" (dots), "char"?: text (dots: a character of a font as the marker instead of a shape), "font"?: text (the installed family it is drawn from; none: the label font), "image"?: text (dots: a PNG or JPEG image as base64 of at most 2 MiB and 2048 × 2048 pixels, as the marker instead of a shape: as wide as its size, as tall as its proportions make it; the colour and the outline don't show), "size"?: a marker's size in points (default 3), "outline"?: a marker's outline colour or null, "outlineWidth"?: points, "displacement"?: [across, down] points every other row and column are shifted by (dots), "color2"?: "#RRGGBB"|"#RRGGBBAA" (gradient, shapeburst: the second colour; default white), "stops"?: [[0..1, "#RRGGBB"|"#RRGGBBAA"], …] (gradient, shapeburst: colours between the two, at most 16), "discrete"?: bool (each colour held until the next stop), "shape"?: "linear" (default)|"radial"|"conical" (gradient), "from"?: [across, down]|"centroid" (gradient: where color is, 0..1 in the feature's box; default [0.5, 0], the top middle), "to"?: [across, down]|"centroid" (where color2 is; default [0.5, 1]), "spread"?: "pad" (default)|"reflect"|"repeat" (gradient: past its points), "angle"?: degrees anticlockwise (gradient: turned round its box's middle), "inView"?: bool (gradient: from and to in the map view's box, not the feature's), "distance"?: points|null (shapeburst: how deep it shades; null or none: to the point deepest inside), "blur"?: 0..17 (shapeburst: pixels), "ignoreRings"?: bool (shapeburst: holes' edges left out)}] (bottom first, at most 8; [] for the symbol's single fill; the outline is drawn over them)}"##, ), C::new("layer.markerRotation", "Marker Rotation", "Style › Drawing", |s, p| { let field = match p.get("field") { @@ -415,7 +415,11 @@ pub fn commands() -> Vec { let id = s.layer_id(p)?; s.map().layer(id).ok_or("no such layer")?; // Decoded here, on the UI thread, as any command runs: at most 2 MiB of base64, whose - // declared size is checked before the decoder, capped in memory, runs. + // declared pixels are checked before the decoder runs (`render::MARKER_PIXELS` each, + // some 80 ms; `render::RUN_MARKER_PIXELS` in all until RustGIS restarts, some 5 s, the + // most any number of calls can take). A call refused after the check sets none of its + // images on the layer, but their decoding stays charged, and the decoded copies kept: + // it took the time it stands for. let mut new = Vec::new(); let mut image = picture(p, &mut new)?; keep_pictures(image.iter_mut(), new)?; @@ -444,7 +448,7 @@ pub fn commands() -> Vec { }) }).roles(&[]).effects(crate::policy::Effects::NONE) .when(need_feature_layer) - .params(r#"{"layer"?, "shape"?: "circle"|"square"|"triangle"|"diamond"|"star", "char"?: text (a character of a font as the marker, its first; sized by the font's em), "font"?: text (the installed family the character is drawn from; "" or one not installed: the label font), "image"?: text (a PNG or JPEG image as base64 of at most 2 MiB, as the marker: as wide as the size, as tall as its proportions make it; its fill and outline don't show), "size"?: number}"#), + .params(r#"{"layer"?, "shape"?: "circle"|"square"|"triangle"|"diamond"|"star", "char"?: text (a character of a font as the marker, its first; sized by the font's em), "font"?: text (the installed family the character is drawn from; "" or one not installed: the label font), "image"?: text (a PNG or JPEG image as base64 of at most 2 MiB and 2048 × 2048 pixels, as the marker: as wide as the size, as tall as its proportions make it; its fill and outline don't show), "size"?: number}"#), C::new("layer.transparency", "Transparency", "Style › Effects", |s, p| { let t = f(p, "value").ok_or("value (0–100) is required")?.clamp(0.0, 100.0) as f32; with(s, p, |l| l.transparency = t) @@ -1651,11 +1655,12 @@ fn not_empty(image: Option<&Value>) -> Result<(), String> { } /// An `image` (`layer.marker`'s, a line marker's, a dot fill's): a PNG or JPEG image as base64, -/// which must decode. One kept already is returned; a new one is only checked, its base64 put in -/// `new` and an empty picture returned in its place, for [`keep_pictures`] to keep once the whole -/// call is checked: a call refused for a later stroke or fill keeps none of its images. +/// which must decode. One kept already is returned where it draws; a new one is only checked, its +/// base64 put in `new` and an empty picture returned in its place, for [`keep_pictures`] to keep +/// once the whole call is checked: a call refused for a later stroke or fill keeps none of its +/// images. fn picture<'a>(p: &'a Value, new: &mut Vec<&'a str>) -> Result, String> { - const WHAT: &str = "image is a PNG or JPEG image as base64"; + const WHAT: &str = "image is a PNG or JPEG image as base64, of at most 2048 × 2048 pixels"; let b64 = match p.get("image") { None | Some(Value::Null) => return Ok(None), Some(Value::String(b64)) => b64.trim(), @@ -1664,14 +1669,20 @@ fn picture<'a>(p: &'a Value, new: &mut Vec<&'a str>) -> Result, if b64.len() > rustgis_map::symbology::MAX_PICTURE_BYTES { return Err(format!("image is at most {} MiB of base64", rustgis_map::symbology::MAX_PICTURE_BYTES >> 20)); } - // One given again (the editor sends a stroke's or a fill's image with every change, a slider - // every frame) is found where it's kept, and decoded once into the drawing's cache. + // Checking decodes an image once for the run: one given again (the editor sends a stroke's or + // a fill's image with every change, a slider every frame) is found decoded. One met earlier in + // the call was checked then. + let refused = |why: rustgis_render::MarkerRefusal| format!("{WHAT}: this one {}", why.what()); if let Some(kept) = Picture::kept(b64) { - return if rustgis_render::picture_marker_draws(kept) { Ok(Some(kept)) } else { Err(WHAT.into()) }; + // One refused only for what the run has spent is kept as it is, drawn as a circle until a + // restart, so an edit that sends it again (a script's) isn't refused for it. + return match rustgis_render::picture_marker_kept_refusal(kept) { + Some(why) => Err(refused(why)), + None => Ok(Some(kept)), + }; } - // One met earlier in the call was checked then: an image decodes once per call. - if !new.contains(&b64) && !rustgis_render::picture_marker_readable(b64) { - return Err(WHAT.into()); + if !new.contains(&b64) { + rustgis_render::picture_marker_check(b64).map_err(refused)?; } new.push(b64); Ok(Some(Picture::default())) diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 5a2141144e..c0d1c92024 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -81,13 +81,14 @@ fn marker_images() -> impl FnMut(&str) -> Result<(String, f32), &'static str> { /// within what a picture marker keeps (`symbology::MAX_PICTURE_BYTES` of base64, 2 MiB), checked /// as `layer.marker` checks an image; with its height over its width. Its base64's length is added /// to `read`, or for a file that doesn't read (past the limit, or failing part way) what was read -/// of it, so the import's bound overshoots by one file at most. Checking it decodes it, at most -/// 20,000 pixels a side within 512 MiB, as `layer.marker` does. +/// of it, so the import's bound overshoots by one file at most. Checking it decodes it, within +/// `render::MARKER_PIXELS` and what the run has left of `render::RUN_MARKER_PIXELS`, as +/// `layer.marker` does. fn marker_image(source: &str, read: &mut usize) -> Result<(String, f32), &'static str> { use base64::Engine; use rustgis_map::symbology::MAX_PICTURE_BYTES; const TOO_LARGE: &str = "whose image is past 2 MiB of base64"; - const NOT_AN_IMAGE: &str = "whose image isn't a PNG or JPEG RustGIS reads"; + const NOT_AN_IMAGE: &str = rustgis_render::MarkerRefusal::NotAnImage.whose(); let b64 = match source.strip_prefix("base64:") { // Past the limit, refused before it is copied, and charged as a file past it is. Some(b64) if b64.trim().len() > MAX_PICTURE_BYTES => { @@ -119,15 +120,9 @@ fn marker_image(source: &str, read: &mut usize) -> Result<(String, f32), &'stati if b64.len() > MAX_PICTURE_BYTES { return Err(TOO_LARGE); } - // As `layer.marker` checks one: one kept already decodes into the drawing's cache. - let readable = match rustgis_map::Picture::kept(&b64) { - Some(kept) => rustgis_render::picture_marker_draws(kept), - None => rustgis_render::picture_marker_readable(&b64), - }; - match rustgis_render::picture_size(&b64) { - Some((w, h)) if readable && w > 0 && h > 0 => Ok((b64, h as f32 / w as f32)), - _ => Err(NOT_AN_IMAGE), - } + // As `layer.marker` checks one, decoded once for the run, where drawing it finds it. + let aspect = rustgis_render::picture_marker_check(&b64).map_err(rustgis_render::MarkerRefusal::whose)?; + Ok((b64, aspect)) } /// The most bytes of a QGIS file read (a `.qgz` can carry data files beside its project). diff --git a/crates/engine/src/cmd/service.rs b/crates/engine/src/cmd/service.rs index 84fc34d5b9..ee08d3e183 100644 --- a/crates/engine/src/cmd/service.rs +++ b/crates/engine/src/cmd/service.rs @@ -478,12 +478,9 @@ fn added_layers(r: &Value) -> Vec { /// otherwise (#2080). pub(crate) fn apply_drawing_info(s: &mut Session, r: &Value, name: &str, drawing: &Value) { let mut notes = rustgis_map::arcgis_style::Notes::default(); - // As `layer.marker` checks an image: one kept already decodes into the drawing's cache, - // a new one is decoded once before it is kept. - let readable = |b64: &str| match rustgis_map::Picture::kept(b64) { - Some(kept) => rustgis_render::picture_marker_draws(kept), - None => rustgis_render::picture_marker_readable(b64), - }; + // A new image is checked as `layer.marker` checks one: decoded once for the run, in its + // store, before it is kept. + let readable = |b64: &str| rustgis_render::picture_marker_check(b64).map(|_| ()).map_err(rustgis_render::MarkerRefusal::whose); for id in added_layers(r) { if let Some(l) = s.map_mut().layer_mut(id) { rustgis_map::arcgis_style::apply(l, drawing, &readable, &mut notes); diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 9b0be74856..e5510ac466 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -1925,24 +1925,57 @@ fn empty_map() -> &'static Map { pub const MAX_ITEMS: usize = 1000; /// What a read made of the image markers of `layers` and saved `styles` (by name): those not -/// kept, which saving loses, and those that aren't a PNG or JPEG image that decodes (each image -/// decoded once); both are drawn as circles. +/// kept, which saving loses, and those the renderer draws as circles, by why (not a PNG or JPEG +/// that decodes, past `render::MARKER_PIXELS`, or past what the run has left of +/// `render::RUN_MARKER_PIXELS`; each image checked once); both are drawn as circles. Checking +/// decodes each new image, on the UI thread: at most what the run decodes, once. pub(crate) fn picture_notices<'a>( layers: impl IntoIterator, styles: impl IntoIterator, +) -> Vec { + picture_notices_by(layers, styles, &|p| rustgis_render::picture_marker_kept_check(p).err()) +} + +/// [`picture_notices`], each kept image's refusal given by `check` (the renderer's; a test's own, +/// to say what a run past its budget says without spending the process's). +pub(crate) fn picture_notices_by<'a>( + layers: impl IntoIterator, + styles: impl IntoIterator, + check: &dyn Fn(rustgis_map::Picture) -> Option, ) -> Vec { use rustgis_map::Picture; use rustgis_map::symbology::{MAX_PICTURE_BYTES, MAX_PICTURES, MAX_PICTURES_BYTES}; + use rustgis_render::MarkerRefusal; let seen = std::cell::RefCell::new(std::collections::HashMap::new()); - let unreadable = - |p: Picture| !p.is_default() && !*seen.borrow_mut().entry(p).or_insert_with(|| rustgis_render::picture_marker_draws(p)); - let (mut dropped, mut bad) = (Vec::new(), Vec::new()); + let refused = |p: Picture| { + if p.is_default() { + return None; + } + *seen.borrow_mut().entry(p).or_insert_with(|| check(p)) + }; + // The names with an image refused so, by each refusal in `WHY`, in the order their notices go. + const WHY: [MarkerRefusal; 3] = [MarkerRefusal::NotAnImage, MarkerRefusal::TooManyPixels, MarkerRefusal::PastRunPixels]; + let (mut dropped, mut bad) = (Vec::new(), [Vec::new(), Vec::new(), Vec::new()]); let mut note = |name: &'a str, any: &dyn Fn(&dyn Fn(Picture) -> bool) -> bool| { if any(&Picture::is_dropped) { dropped.push(name); } - if any(&unreadable) { - bad.push(name); + // One walk of the symbols (answering no to see them all), noting each refusal met. + let met = std::cell::Cell::new([false; 3]); + any(&|p| { + if let Some(why) = refused(p) + && let Some(i) = WHY.iter().position(|w| *w == why) + { + let mut seen = met.get(); + seen[i] = true; + met.set(seen); + } + false + }); + for (names, met) in bad.iter_mut().zip(met.get()) { + if met { + names.push(name); + } } }; for l in layers { @@ -1963,10 +1996,27 @@ pub(crate) fn picture_notices<'a>( ], )); } - if !bad.is_empty() { + let [not_images, too_large, past_run] = &bad; + if !not_images.is_empty() { notices.push(NoticeText::format( "Image markers in {names} aren't PNG or JPEG images and are drawn as circles", - [("names", picture_names(&bad))], + [("names", picture_names(not_images))], + )); + } + if !too_large.is_empty() { + notices.push(NoticeText::format( + "Image markers in {names} have more pixels than {side} × {side} and are drawn as circles", + [("names", picture_names(too_large)), ("side", rustgis_render::MARKER_PIXELS_SIDE.to_string().into())], + )); + } + if !past_run.is_empty() { + notices.push(NoticeText::format( + "Image markers in {names} are past what RustGIS decodes of marker images until it restarts ({mpx} megapixels, {mib} MiB) and are drawn as circles", + [ + ("names", picture_names(past_run)), + ("mpx", (rustgis_render::RUN_MARKER_PIXELS / 1_000_000).to_string().into()), + ("mib", (rustgis_render::RUN_MARKER_BYTES >> 20).to_string().into()), + ], )); } notices diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index a65189680e..8408a23a01 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -2129,6 +2129,67 @@ fn gif_base64() -> String { base64::engine::general_purpose::STANDARD.encode(&gif) } +/// A PNG of a few kilobytes, one pixel wider than a marker's image takes (2048 × 2048). +fn too_many_pixels_png() -> Vec { + let mut png = Vec::new(); + image::GrayImage::from_pixel(2049, 2048, image::Luma([90])) + .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png) + .unwrap(); + png +} + +/// An image marker past the pixels a marker's image takes is said with why, apart from one that +/// isn't an image, and drawn as a circle. +#[test] +fn an_image_marker_past_its_pixels_is_said_with_why() { + use base64::Engine; + let many = too_many_pixels_png(); + let picture = rustgis_map::Picture::new(&base64::engine::general_purpose::STANDARD.encode(&many)); + let mut s = world(); + let id = s.map().layer_by_name("Cities").unwrap().id; + s.map_mut().layer_mut(id).unwrap().renderer.map_symbols(|sym| sym.marker = rustgis_map::Marker::Picture(picture)); + let said: Vec = crate::project::picture_notices([s.map().layer(id).unwrap()], []).iter().map(|n| n.english()).collect(); + assert_eq!(said, ["Image markers in \"Cities\" have more pixels than 2048 × 2048 and are drawn as circles"]); + assert!(!rustgis_render::picture_marker_draws(picture)); +} + +/// A saved image marker whose image declares more pixels than a marker's takes opens said, with +/// why, and drawn as a circle; its image kept for saving. +#[test] +fn a_large_picture_marker_fixture_opens_said_as_a_circle() { + let text = include_str!("../../../schema/fixtures/picture_markers_large.rgis"); + let mut s = Session::new(Project::default()); + let mark = s.notice_mark(); + s.run("project.openText", &json!({"text": text})).unwrap(); + let said: Vec = s.notices_since(mark).iter().map(|n| n.text.clone()).collect(); + assert!( + said.iter().any(|n| n == "Image markers in \"Schools\" have more pixels than 2048 × 2048 and are drawn as circles"), + "{said:?}" + ); + let rustgis_map::Renderer::Single(symbol) = &s.project.styles[0].renderer else { panic!("a single symbol") }; + let rustgis_map::Marker::Picture(picture) = symbol.marker else { panic!("an image marker") }; + assert!(picture.base64().starts_with("iVBORw0KGgo") && !rustgis_render::picture_marker_draws(picture)); +} + +/// An image marker past what the run decodes is said with both of the run's caps, and as no +/// other refusal (the renderer's check stood in for, the process's budget left alone). +#[test] +fn an_image_marker_past_the_runs_budget_is_said_with_its_caps() { + let mut s = world(); + let id = s.map().layer_by_name("Cities").unwrap().id; + let picture = rustgis_map::Picture::new(&base64::Engine::encode(&base64::engine::general_purpose::STANDARD, b"\x89PNG")); + s.map_mut().layer_mut(id).unwrap().renderer.map_symbols(|sym| sym.marker = rustgis_map::Marker::Picture(picture)); + let spent = |_| Some(rustgis_render::MarkerRefusal::PastRunPixels); + let said: Vec = + crate::project::picture_notices_by([s.map().layer(id).unwrap()], [], &spent).iter().map(|n| n.english()).collect(); + assert_eq!( + said, + [ + "Image markers in \"Cities\" are past what RustGIS decodes of marker images until it restarts (256 megapixels, 128 MiB) and are drawn as circles" + ] + ); +} + /// A saved image marker that is a GIF (which the desktop's decoder reads and the web's doesn't) /// opens said and drawn as a circle on every platform, its image kept for saving. #[test] @@ -2157,6 +2218,12 @@ fn an_image_is_a_marker_kept_in_the_project_file_that_an_older_reader_refuses() .unwrap(); let b64 = base64::engine::general_purpose::STANDARD.encode(&png); let depth = s.undo_depth(); + // One past the pixels a marker's image takes is refused, saying so, and changes nothing. + let many = too_many_pixels_png(); + let e = + s.run("layer.marker", &json!({"layer": "Cities", "image": base64::engine::general_purpose::STANDARD.encode(&many)})).unwrap_err(); + assert!(e.to_string().ends_with("this one has more pixels than 2048 × 2048"), "{e}"); + assert_eq!((marker(&s), s.undo_depth()), (Marker::Circle, depth)); s.run("layer.marker", &json!({"layer": "Cities", "image": format!(" {b64}\n"), "size": 20})).unwrap(); assert_eq!(marker(&s), Marker::Picture(Picture::new(&b64))); assert_eq!(s.undo_depth(), depth + 1); @@ -3082,6 +3149,8 @@ fn qgis_raster_image_markers_read_their_files_from_the_style_folder() { let mut big = std::fs::read(dir.join("pins/pin.png")).unwrap(); big.resize(1600 << 10, 0); std::fs::write(dir.join("pins/big.png"), big).unwrap(); + // A few kilobytes, past the pixels a marker's image takes. + std::fs::write(dir.join("pins/many.png"), too_many_pixels_png()).unwrap(); let qml = |file: &str| { format!( r#" @@ -3105,6 +3174,7 @@ fn qgis_raster_image_markers_read_their_files_from_the_style_folder() { ("pins/pin.gif", "raster image markers whose image isn't a PNG or JPEG RustGIS reads, drawn as circles"), ("pins/gone.png", "raster image markers whose image file doesn't open, drawn as circles"), ("pins/big.png", "raster image markers whose image is past 2 MiB of base64, drawn as circles"), + ("pins/many.png", "raster image markers whose image has more pixels than 2048 × 2048, drawn as circles"), ] { let path = dir.join("pins.qml"); std::fs::write(&path, qml(file)).unwrap(); diff --git a/crates/map/src/arcgis_style.rs b/crates/map/src/arcgis_style.rs index ef9a5b7395..a58c3d18bd 100644 --- a/crates/map/src/arcgis_style.rs +++ b/crates/map/src/arcgis_style.rs @@ -2,6 +2,7 @@ //! it) translated onto a feature layer just added from its service (#2080). use serde_json::Value; +use std::borrow::Cow; use std::collections::{BTreeMap, BTreeSet, HashMap}; use crate::symbology::{ClassMethod, Dash, LineStroke, MAX_PICTURE_BYTES, MAX_STROKE_WIDTH, Marker, OTHER_FILL, Picture, normalize_label}; @@ -20,10 +21,11 @@ const PICTURE_FILL: Rgba = Rgba::rgb(0x80, 0x80, 0x80); /// What of a service's symbology was drawn differently or left out, each with how many symbols it /// came up for, in the order first met. #[derive(Clone, Debug, Default, PartialEq)] -pub struct Notes(Vec<(&'static str, usize)>); +pub struct Notes(Vec<(Cow<'static, str>, usize)>); impl Notes { - fn add(&mut self, text: &'static str) { + fn add(&mut self, text: impl Into>) { + let text = text.into(); match self.0.iter_mut().find(|(t, _)| *t == text) { Some((_, n)) => *n = n.saturating_add(1), None => self.0.push((text, 1)), @@ -36,57 +38,61 @@ impl Notes { /// The notes as one sentence's list: `"hatched fills, drawn solid (3 symbols); …"`. pub fn text(&self) -> String { - self.0.iter().map(|(t, n)| if *n > 1 { format!("{t} ({n} symbols)") } else { (*t).to_string() }).collect::>().join("; ") + self.0.iter().map(|(t, n)| if *n > 1 { format!("{t} ({n} symbols)") } else { t.to_string() }).collect::>().join("; ") } } /// Picture markers' images (`imageData`) as a service gives them, each checked and kept once, /// however many classes show it. struct Pictures<'r> { - /// Whether an image decodes as a picture marker's must (a PNG or JPEG): the check - /// `layer.marker` makes, which is the renderer's, so that what draws here draws there. - readable: &'r dyn Fn(&str) -> bool, + /// Whether an image is one a picture marker draws, or why not after "whose image" + /// (`render::MarkerRefusal::whose`): the check `layer.marker` makes, which is the renderer's, + /// so that what draws here draws there. + readable: &'r dyn Fn(&str) -> Result<(), &'static str>, /// Each image met, with its picture or why it isn't drawn. - met: HashMap>, + met: HashMap>>, } impl Pictures<'_> { /// A picture marker's image as a picture, or the note saying why it is drawn as a circle. - fn of(&mut self, s: &Value) -> Result { + fn of(&mut self, s: &Value) -> Result> { let Some(b64) = s.get("imageData").and_then(Value::as_str).map(str::trim).filter(|b| !b.is_empty()) else { // RustGIS doesn't fetch a marker's image from its `url`. return Err(if s.get("url").and_then(Value::as_str).is_some_and(|u| !u.trim().is_empty()) { - "picture markers whose image is only at a URL, drawn as circles" + "picture markers whose image is only at a URL, drawn as circles".into() } else { - "picture markers with no image, drawn as circles" + "picture markers with no image, drawn as circles".into() }); }; // Looked up first, so that classes sharing an image don't each copy it. if let Some(met) = self.met.get(b64) { - return *met; + return met.clone(); } - *self.met.entry(b64.to_owned()).or_insert_with(|| { - // Too long to keep is said before decoding it. What is decoded is bounded by the - // description's own cap (`DESCRIPTION_MAX`, 4 MiB), as `layer.marker` decodes one. - if b64.len() > MAX_PICTURE_BYTES { - return Err("picture markers past 2 MiB of base64, drawn as circles"); - } - if !(self.readable)(b64) { - return Err("picture markers whose image isn't a PNG or JPEG RustGIS reads, drawn as circles"); - } - // Past the images a run keeps (from a crafted service), it isn't kept. - Some(Picture::new(b64)).filter(|p| !p.is_default()).ok_or("picture markers past the images RustGIS keeps, drawn as circles") - }) + self.met + .entry(b64.to_owned()) + .or_insert_with(|| { + // Too long to keep is said before decoding it. What is decoded is bounded by the + // description's own cap (`DESCRIPTION_MAX`, 4 MiB), as `layer.marker` decodes one. + if b64.len() > MAX_PICTURE_BYTES { + return Err("picture markers past 2 MiB of base64, drawn as circles".into()); + } + (self.readable)(b64).map_err(|why| format!("picture markers {why}, drawn as circles"))?; + // Past the images a run keeps (from a crafted service), it isn't kept. + Some(Picture::new(b64)) + .filter(|p| !p.is_default()) + .ok_or("picture markers past the images RustGIS keeps, drawn as circles".into()) + }) + .clone() } } /// Gives `layer`, a feature layer just added from an ArcGIS service, the symbology its /// description's `drawingInfo` sets: its renderer, when RustGIS draws its kind (a simple one, by /// unique values of a field or by class breaks), and its transparency. A picture marker draws its -/// image when `readable` (the renderer's check) says it decodes. What can't be drawn as the -/// service draws it is noted, its labels too; a renderer RustGIS doesn't read leaves the layer's -/// own. Anything but an object changes nothing. -pub fn apply(layer: &mut Layer, drawing_info: &Value, readable: &dyn Fn(&str) -> bool, notes: &mut Notes) { +/// image when `readable` (the renderer's check) takes it, else says why after "whose image". +/// What can't be drawn as the service draws it is noted, its labels too; a renderer RustGIS +/// doesn't read leaves the layer's own. Anything but an object changes nothing. +pub fn apply(layer: &mut Layer, drawing_info: &Value, readable: &dyn Fn(&str) -> Result<(), &'static str>, notes: &mut Notes) { if !drawing_info.is_object() || layer.is_raster() { return; } @@ -653,8 +659,8 @@ mod tests { } /// The renderer's check stood in for (`map` doesn't decode images): a PNG's base64 begins so. - fn png(b64: &str) -> bool { - b64.starts_with("iVBORw0KGgo") + fn png(b64: &str) -> Result<(), &'static str> { + if b64.starts_with("iVBORw0KGgo") { Ok(()) } else { Err("whose image isn't a PNG or JPEG RustGIS reads") } } fn styled(g: GeometryType, info: Value) -> (Layer, Notes) { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 8a6ba48050..e78f814184 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -594,20 +594,36 @@ pub fn picture_size(b64: &str) -> Option<(u32, u32)> { picture::size(b64) } -/// Whether a base64 PNG or JPEG image decodes, as a picture marker's must. -pub fn picture_marker_readable(b64: &str) -> bool { - picture::readable(b64) +pub use picture::{MARKER_PIXELS, MARKER_PIXELS_SIDE, MarkerRefusal, RUN_MARKER_BYTES, RUN_MARKER_PIXELS}; + +/// Base64 `b64` as a picture marker's image (one kept already, or one before it is set): its +/// height for its width when it draws (a PNG or JPEG within [`MARKER_PIXELS`] and what the run has +/// left of [`RUN_MARKER_PIXELS`] and [`RUN_MARKER_BYTES`], that decodes), or why it would be drawn +/// as a circle. Decoded once for the run, where drawing it finds it. +pub fn picture_marker_check(b64: &str) -> Result { + picture::check(b64) +} + +/// [`picture_marker_check`] for picture marker `p` (one a file gives). +pub fn picture_marker_kept_check(p: rustgis_map::Picture) -> Result { + picture::marker_drawn(p) +} + +/// Why kept picture marker `p` can't be given again, by command or by a symbol editor: a refusal +/// for the image itself. `None` where it draws, or is drawn as a circle only until a restart (past +/// what the run decodes), and is kept as it is. +pub fn picture_marker_kept_refusal(p: rustgis_map::Picture) -> Option { + picture::marker_kept_refusal(p) } -/// Whether picture marker `p` (one a file gives) decodes, so it draws rather than a circle; -/// decoded into this thread's cache of markers, where drawing on it finds it. +/// Whether picture marker `p` draws rather than a circle ([`picture_marker_kept_check`]). pub fn picture_marker_draws(p: rustgis_map::Picture) -> bool { - picture::marker_aspect(p).is_some() + picture_marker_kept_check(p).is_ok() } /// Picture marker `p`'s image at most `side` pixels per side (a preview's), and its height for its -/// width from before it was scaled down; `None` where the map draws a circle. Decoded on every -/// call: the caller keeps it. +/// width from before it was scaled down; `None` where the map draws a circle. Scaled from the +/// run's decoded copy on every call: the caller keeps it. pub fn picture_marker_image(p: rustgis_map::Picture, side: u32) -> Option<(Pixmap, f32)> { picture::marker_image(p, side) } diff --git a/crates/render/src/picture.rs b/crates/render/src/picture.rs index c008d1369e..e221ed3d24 100644 --- a/crates/render/src/picture.rs +++ b/crates/render/src/picture.rs @@ -3,8 +3,8 @@ use std::cell::RefCell; use std::collections::HashMap; -use std::hash::{Hash, Hasher}; -use std::sync::Arc; +use std::hash::{BuildHasher, Hash, Hasher, RandomState}; +use std::sync::{Arc, Mutex, OnceLock}; use crate::Canvas; use crate::vector::Pixels; @@ -25,10 +25,81 @@ const CACHE_BYTES: usize = 256 << 20; /// Picture markers are drawn from at most this many pixels per side: an 80 pt marker printed at /// 600 dpi. const MARKER_SIDE: u32 = 700; -/// Decoded picture markers kept between frames, and the most pixel memory they may hold together. -/// As many as a layer's classes can show ([`rustgis_map::symbology::MAX_PICTURES`] are kept). -const MARKERS: usize = 1024; -const MARKERS_BYTES: usize = 128 << 20; +/// The most pixels a picture marker's image may declare (2048 × 2048, by area, so a long strip +/// passes): past it, it isn't decoded and is drawn as a circle. What a marker costs to check and +/// draw is its pixels (decoding and scaling one takes some 19 ns a pixel), not its bytes: a PNG of +/// a few kilobytes can declare hundreds of megapixels. So the cap is set by that cost, one at it +/// taking some 80 ms; a marker is drawn from at most [`MARKER_SIDE`] pixels a side whatever its +/// image's size. +pub const MARKER_PIXELS: u64 = MARKER_PIXELS_SIDE as u64 * MARKER_PIXELS_SIDE as u64; +/// The side of the square [`MARKER_PIXELS`] is, for messages (theirs, written out, a test pins). +pub const MARKER_PIXELS_SIDE: u32 = 2048; +/// The most pixels of different picture markers' images a run decodes, about 5 s of decoding; +/// with [`RUN_MARKER_BYTES`], past either, a new one is drawn as a circle. A run is the process, +/// until RustGIS restarts, as the images it keeps ([`Picture`]) are. A cap per image +/// alone isn't enough: a run keeps [`rustgis_map::symbology::MAX_PICTURES`] images, and that many +/// at [`MARKER_PIXELS`] take some 80 s. Each image is decoded once for the whole run, on whichever +/// thread meets it first, and kept ([`Store`]): none is decoded again, however many threads, frames +/// or checks meet it, so these bound all the decoding markers do. As many images as a run keeps +/// fit when each is at most 177 × 177 pixels once decoded (a larger one is scaled down to +/// [`MARKER_SIDE`]). +pub const RUN_MARKER_PIXELS: u64 = 256_000_000; +/// The most memory picture markers' images hold decoded before a new one is drawn as a circle. +/// Their copies compressed for vector exports are charged to it too, leaving less for new images, +/// but never refused ([`Decoded::packed`]): at most about as much again, some 256 MiB in all. +pub const RUN_MARKER_BYTES: u64 = 128 << 20; +/// What each image is charged at least (an icon's decoding costs about the same whatever its +/// size), so the images charged are at most [`RUN_MARKER_PIXELS`] / this many. +const MARKER_CHARGE: u64 = 64 * 64; + +/// Why a picture marker's image is drawn as a circle. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum MarkerRefusal { + /// It isn't a PNG or JPEG image that decodes. + NotAnImage, + /// It declares more than [`MARKER_PIXELS`]. + TooManyPixels, + /// It would take the run past [`RUN_MARKER_PIXELS`] or [`RUN_MARKER_BYTES`]. + PastRunPixels, +} + +impl MarkerRefusal { + /// Whether it lasts whatever the run: the image itself is the reason, not what the run spent + /// before meeting it ([`MarkerRefusal::PastRunPixels`], which a restart clears). An image kept + /// already and refused only for the run is kept as it is, drawn as a circle meanwhile. + pub const fn lasts(self) -> bool { + !matches!(self, MarkerRefusal::PastRunPixels) + } +} + +/// Each refusal's phrase, written once for both its forms. +macro_rules! refusal_phrases { + ($($refusal:ident => $what:literal),* $(,)?) => { + impl MarkerRefusal { + /// What is wrong with the image, after "the image" or "this one": + /// `"has more pixels than 2048 × 2048"`. + pub const fn what(self) -> &'static str { + match self { + $(MarkerRefusal::$refusal => $what),* + } + } + + /// [`MarkerRefusal::what`] after "whose image", for a list of what an import couldn't + /// carry over. + pub const fn whose(self) -> &'static str { + match self { + $(MarkerRefusal::$refusal => concat!("whose image ", $what)),* + } + } + } + }; +} + +refusal_phrases! { + NotAnImage => "isn't a PNG or JPEG RustGIS reads", + TooManyPixels => "has more pixels than 2048 × 2048", + PastRunPixels => "is past what RustGIS decodes of marker images until it restarts (256 megapixels, 128 MiB)", +} /// 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). @@ -39,23 +110,165 @@ struct Cache { order: std::collections::VecDeque, } -/// Decoded picture markers (none: the image doesn't decode), by the [`Picture`] (where its image -/// is kept, so a hit compares no bytes), the pixel memory they hold, and their pictures oldest -/// first (for eviction). +thread_local! { + static DECODED: RefCell = RefCell::new(Cache::default()); + /// 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. + static MARKERS_MET: RefCell> = RefCell::new(HashMap::new()); +} + +/// A picture marker's image, decoded once for the run and shared by every thread. +struct Decoded { + /// At most [`MARKER_SIDE`] pixels a side. Shared, so a frame drawn in bands keeps it, not a + /// copy ([`Canvas::draw_shared`]). + image: Arc, + /// Its height for its width, from before it was scaled down (a one-pixel side can't keep a very + /// narrow image's). + aspect: f32, + /// The image compressed for recording canvases (vector exports), the first time one records + /// it: every point then shares it, and a writer keeps it once. Charged to the run's bytes + /// ([`pack`]), leaving less for new images, but never refused: without it each place would + /// compress a copy of its own. At most about as much again as the decoded copies. + packed: OnceLock>>, +} + +/// A picture marker's decoded image, or why it is drawn as a circle. +type Marker = Result, MarkerRefusal>; + +/// What the run has decoded of picture markers' images: the pixels they declared and the bytes +/// they hold, decoded or compressed ([`RUN_MARKER_PIXELS`], [`RUN_MARKER_BYTES`]: compressed +/// copies can take the bytes past it). #[derive(Default)] -struct Markers { - /// Each image as drawn, and its height for its width. - images: HashMap, f32)>>, - /// The images compressed, for recording canvases (vector exports), done the first time one - /// records it: every point then shares them, and a writer keeps them once. - packed: HashMap>>, - bytes: usize, - order: std::collections::VecDeque, +struct Budget { + pixels: u64, + bytes: u64, } -thread_local! { - static DECODED: RefCell = RefCell::new(Cache::default()); - static MARKERS_DECODED: RefCell = RefCell::new(Markers::default()); +impl Budget { + /// Charges an image declaring `pixels` (at least [`MARKER_CHARGE`]) and holding `bytes` + /// decoded, within `limits`; refused, charging nothing, past either. + fn take(&mut self, pixels: u64, bytes: u64, (max_pixels, max_bytes): (u64, u64)) -> Result<(), MarkerRefusal> { + let pixels = pixels.max(MARKER_CHARGE); + if self.pixels.saturating_add(pixels) > max_pixels || self.bytes.saturating_add(bytes) > max_bytes { + return Err(MarkerRefusal::PastRunPixels); + } + self.pixels += pixels; + self.bytes += bytes; + Ok(()) + } + + /// Charges `bytes` more held for an image already charged (its compressed copy), whatever is + /// left: they then leave less for new images. + fn hold(&mut self, bytes: u64) { + self.bytes = self.bytes.saturating_add(bytes); + } +} + +/// The picture markers' images decoded this run, by their whole base64 ([`content_id`]): each one +/// charged to the [`Budget`], decoded or not, so it is never decoded again. One kept +/// ([`Picture`]) and one only checked (before a command keeps it) are the same image here. +#[derive(Default)] +struct Store { + images: HashMap, + /// What each kept picture met so far came to, by where it is kept: found with no hashing of + /// its image. A frame drawn in bands runs on threads made for that frame + /// ([`crate::bands`]), whose [`MARKERS_MET`] start empty, so each thread's first look at a + /// picture comes here, every frame. At most the pictures a run keeps. A refusal is kept too: a + /// picture past the run's budget stays a circle for the run, even if a later image that + /// doesn't decode gives back bytes, so a map doesn't change with what else was met. + pictures: HashMap, + budget: Budget, +} + +/// The [`Store`]. Its lock is held while an image is decoded, so two threads meeting the same new +/// image decode it once; another waits at most one image's decoding (80 ms at [`MARKER_PIXELS`]). +fn store() -> std::sync::MutexGuard<'static, Store> { + static STORE: OnceLock> = OnceLock::new(); + STORE.get_or_init(Default::default).lock().unwrap_or_else(|e| e.into_inner()) +} + +/// Base64 `b64`'s identity in the [`Store`]: two hashes of all of it with different keys, 128 bits +/// together. Not the cheap [`key`] of the graphics' cache, which a crafted image could share with +/// one decoded already to pass free; and not a single 64-bit hash, in reach of a birthday search +/// where the keys are known (the web build may not randomize them; two keys still take 2^64). +fn content_id(b64: &str) -> u128 { + static HASHERS: OnceLock<(RandomState, RandomState)> = OnceLock::new(); + let (a, b) = HASHERS.get_or_init(|| (RandomState::new(), RandomState::new())); + (u128::from(a.hash_one(b64)) << 64) | u128::from(b.hash_one(b64)) +} + +/// Picture marker image `b64` from the [`Store`], decoded there the first time; or why it is drawn +/// as a circle: not a PNG or JPEG, past [`MARKER_PIXELS`] or what the run has left of +/// [`RUN_MARKER_PIXELS`] or [`RUN_MARKER_BYTES`], or one that doesn't decode. Every path to a +/// marker's image (checking one, drawing it, a preview's) comes here, so the caps hold for all of +/// them; graphics' pictures ([`decode`]) keep their own. What is refused before decoding (from its +/// first bytes or its header) isn't kept: finding that again costs as little. +/// +/// Commands and a project's read check images on the UI thread. One image takes at most ~80 ms +/// ([`MARKER_PIXELS`] at ~19 ns a pixel); everything a run decodes, ~5 s ([`RUN_MARKER_PIXELS`]), +/// once: one call or file can spend it all, and after that a new image is refused from its header. +/// Kept on the UI thread for that bound: the check answers whether the command is taken. +fn marker(b64: &str) -> Marker { + marker_in(&mut store(), b64) +} + +/// [`marker`] in `store`, locked. +fn marker_in(store: &mut Store, b64: &str) -> Marker { + use MarkerRefusal::*; + let b64 = b64.trim(); + if !png_or_jpeg(b64) { + return Err(NotAnImage); + } + let id = content_id(b64); + if let Some(found) = store.images.get(&id) { + return found.clone(); + } + let bytes = base64::engine::general_purpose::STANDARD.decode(b64).map_err(|_| NotAnImage)?; + let (w, h) = declared(&bytes).ok_or(NotAnImage)?; + let pixels = u64::from(w) * u64::from(h); + if pixels > MARKER_PIXELS { + return Err(TooManyPixels); + } + // What it holds once decoded, scaled down to fit `MARKER_SIDE` as `decode_bytes` does (settled + // below to what it does hold, should the data not be what the header says). + let (fw, fh) = fitted(w, h, MARKER_SIDE); + let held = u64::from(fw) * u64::from(fh) * 4; + store.budget.take(pixels, held, (RUN_MARKER_PIXELS, RUN_MARKER_BYTES))?; + let found = decode_bytes(&bytes, MARKER_SIDE) + .map(|(image, aspect)| Arc::new(Decoded { image: Arc::new(image), aspect, packed: OnceLock::new() })) + .ok_or(NotAnImage); + // Settled to what it holds: nothing for one that doesn't decode. Its pixels stay charged: one + // can fail at its last row, having taken the time they stand for, and charging less would let + // such images take that time again and again. One that fails sooner charges as much, as a + // valid image declaring as many pixels would; the cap bounds the time either way. + let holds = found.as_ref().map_or(0, |d| d.image.data().len() as u64); + store.budget.bytes = store.budget.bytes.saturating_sub(held).saturating_add(holds); + store.images.insert(id, found.clone()); + found +} + +/// Picture marker `p` as this thread met it ([`MARKERS_MET`]), from the [`Store`] the first time. +fn marker_met(p: Picture) -> Marker { + if p.is_default() { + return Err(MarkerRefusal::NotAnImage); + } + if let Some(found) = MARKERS_MET.with(|met| met.borrow().get(&p).cloned()) { + return found; + } + let found = { + let mut store = store(); + match store.pictures.get(&p) { + Some(found) => found.clone(), + None => { + let found = marker_in(&mut store, p.base64()); + store.pictures.insert(p, found.clone()); + found + } + } + }; + MARKERS_MET.with(|met| met.borrow_mut().insert(p, found.clone())); + found } /// A cheap key for a picture: its length and its first and last bytes (hashing megabytes of @@ -69,39 +282,53 @@ fn key(b64: &str) -> u64 { h.finish() } -/// The pixel size of base64 PNG or JPEG bytes, read from the header without decoding the image. +/// The pixel size of base64 PNG or JPEG bytes, read from the header without decoding the image; +/// `None` if it doesn't say, or says 0. pub fn size(b64: &str) -> Option<(u32, u32)> { - let bytes = base64::engine::general_purpose::STANDARD.decode(b64.trim()).ok()?; - image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok() + declared(&base64::engine::general_purpose::STANDARD.decode(b64.trim()).ok()?) } -/// Decodes base64 PNG or JPEG bytes into a premultiplied pixmap. Pictures come from project -/// files, so their declared size is checked before decoding and the decoder's memory is capped. +/// Decodes base64 PNG or JPEG bytes into a premultiplied pixmap, scaled down to at most +/// [`MAX_SIDE`] pixels per side. Pictures come from project files, so their declared size is +/// checked before decoding and the decoder's memory is capped. pub fn decode(b64: &str) -> Option { - decode_within(b64, MAX_SIDE) + let bytes = base64::engine::general_purpose::STANDARD.decode(b64.trim()).ok()?; + let (w, h) = declared(&bytes)?; + if w > MAX_DECLARED || h > MAX_DECLARED { + return None; + } + decode_bytes(&bytes, MAX_SIDE).map(|(pm, _)| pm) } -/// [`decode`], scaled down to at most `side` pixels per side. -fn decode_within(b64: &str, side: u32) -> Option { - decode_sized(b64, side).map(|(pm, _)| pm) +/// The pixel size image `bytes` declare, from their header; `None` if they don't say or say 0. +fn declared(bytes: &[u8]) -> Option<(u32, u32)> { + let (w, h) = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?.into_dimensions().ok()?; + (w > 0 && h > 0).then_some((w, h)) } -/// [`decode_within`], with the image's height for its width before it was scaled down (a -/// thumbnail's one-pixel side can't keep a very narrow image's). -fn decode_sized(b64: &str, side: u32) -> Option<(Pixmap, f32)> { - let bytes = base64::engine::general_purpose::STANDARD.decode(b64.trim()).ok()?; - let reader = || image::ImageReader::new(std::io::Cursor::new(&bytes)).with_guessed_format().ok(); - let (w, h) = reader()?.into_dimensions().ok()?; - if w == 0 || h == 0 || w > MAX_DECLARED || h > MAX_DECLARED { - return None; +/// The size `w` × `h` pixels scale down to so neither side passes `side`, keeping their +/// proportions (each side at least one pixel); the same where they fit. +fn fitted(w: u32, h: u32, side: u32) -> (u32, u32) { + if w <= side && h <= side { + return (w, h); } - let mut r = reader()?; + let (long, short) = (u64::from(w.max(h)), u64::from(w.min(h))); + let short = ((short * u64::from(side) + long / 2) / long).clamp(1, u64::from(side.max(1))) as u32; + if w >= h { (side, short) } else { (short, side) } +} + +/// Decodes image `bytes`, whose declared size the caller has checked, scaled down to at most +/// `side` pixels per side ([`fitted`], which a marker's charge is reckoned with), with their height +/// for their width from before. +fn decode_bytes(bytes: &[u8], side: u32) -> Option<(Pixmap, f32)> { + let mut r = image::ImageReader::new(std::io::Cursor::new(bytes)).with_guessed_format().ok()?; let mut limits = image::Limits::default(); limits.max_alloc = Some(MAX_ALLOC); r.limits(limits); let img = r.decode().ok()?; let aspect = img.height() as f32 / img.width().max(1) as f32; - let img = if img.width() > side || img.height() > side { img.thumbnail(side, side) } else { img }; + let (w, h) = fitted(img.width(), img.height(), side); + let img = if (w, h) != (img.width(), img.height()) { img.thumbnail_exact(w, h) } else { img }; let rgba = img.to_rgba8(); let (w, h) = rgba.dimensions(); let mut pm = Pixmap::new(w, h)?; @@ -142,60 +369,60 @@ pub fn draw(pm: &mut Canvas, ds: &Dataset, row: usize, (x0, y0, x1, y1): (f32, f } /// Runs `f` on picture marker `p`'s decoded image, its height for its width and, with `pack`, the -/// image compressed (see [`Markers::packed`]); `None` if it has none or it doesn't decode. -fn with_marker(p: Picture, pack: bool, f: impl FnOnce(&Arc, f32, Option<&Arc>) -> R) -> Option { - if p.is_default() { - return None; - } - MARKERS_DECODED.with(|cache| { - let mut cache = cache.borrow_mut(); - let cache = &mut *cache; - if !cache.images.contains_key(&p) { - let img = marker_image(p, MARKER_SIDE).map(|(i, aspect)| (Arc::new(i), aspect)); - let size = img.as_ref().map_or(0, |(i, _)| i.data().len()); - // Evict the oldest (not all of them) to stay within the count and memory budget. - while cache.images.len() >= MARKERS || (cache.bytes + size > MARKERS_BYTES && !cache.images.is_empty()) { - let Some(old) = cache.order.pop_front() else { break }; - if let Some(Some((gone, _))) = cache.images.remove(&old) { - cache.bytes = cache.bytes.saturating_sub(gone.data().len()); - } - if let Some(Some(gone)) = cache.packed.remove(&old) { - cache.bytes = cache.bytes.saturating_sub(gone.cost()); - } - } - cache.bytes += size; - cache.images.insert(p, img); - cache.order.push_back(p); - } - let (img, aspect) = cache.images.get(&p)?.as_ref()?; - let packed = if pack { - cache - .packed - .entry(p) - .or_insert_with(|| { - let px = Pixels::new(Pixmap::as_ref(img)).map(Arc::new); - cache.bytes += px.as_ref().map_or(0, |px| px.cost()); - px - }) - .as_ref() - } else { - None - }; - Some(f(img, *aspect, packed)) - }) +/// image compressed (see [`Decoded::packed`]); or why it is drawn as a circle. +fn with_marker(p: Picture, pack: bool, f: impl FnOnce(&Arc, f32, Option<&Arc>) -> R) -> Result { + let found = marker_met(p)?; + let charge = |bytes| store().budget.hold(bytes); + let packed = if pack { found.packed.get_or_init(|| self::pack(&found.image, charge)).as_ref() } else { None }; + Ok(f(&found.image, found.aspect, packed)) +} + +/// Marker image `image` compressed ([`Decoded::packed`]) and its bytes charged with `charge` +/// (after compressing, so the [`Store`] isn't held meanwhile); `None` where it can't be. +fn pack(image: &Pixmap, charge: impl FnOnce(u64)) -> Option> { + let packed = Pixels::new(image.as_ref())?; + charge(packed.cost() as u64); + Some(Arc::new(packed)) } -/// Picture marker `p`'s image at most `side` pixels per side, and its height for its width; `None` -/// where it's drawn as a circle (no image, whose base64 is empty, not a PNG or JPEG, or one that -/// doesn't decode). +/// Picture marker `p`'s image at most `side` pixels per side (a preview's), and its height for its +/// width; `None` where it's drawn as a circle. Scaled from the run's decoded copy by averaging +/// (the image isn't decoded again), so a much smaller side doesn't alias; a new copy each call. pub(crate) fn marker_image(p: Picture, side: u32) -> Option<(Pixmap, f32)> { - png_or_jpeg(p.base64()).then(|| decode_sized(p.base64(), side)).flatten() + let found = marker_met(p).ok()?; + let (w, h) = (found.image.width(), found.image.height()); + if w <= side && h <= side { + return Some(((*found.image).clone(), found.aspect)); + } + let scale = side.max(1) as f32 / w.max(h) as f32; + let (sw, sh) = (((w as f32 * scale).round() as u32).max(1), ((h as f32 * scale).round() as u32).max(1)); + // Averaging premultiplied pixels keeps them premultiplied. + let view = image::ImageBuffer::, &[u8]>::from_raw(w, h, found.image.data())?; + let small = image::imageops::thumbnail(&view, sw, sh); + let pm = Pixmap::from_vec(small.into_raw(), tiny_skia::IntSize::from_wh(sw, sh)?)?; + Some((pm, found.aspect)) +} + +/// Picture marker `p`'s height for its width; or why it is drawn as a circle. +pub(crate) fn marker_drawn(p: Picture) -> Result { + marker_met(p).map(|found| found.aspect) +} + +/// Why kept picture marker `p` can't be given again: a refusal that lasts whatever the run +/// ([`MarkerRefusal::lasts`]). One drawn as a circle only for what the run has spent is kept as it +/// is, to draw after a restart. Commands and the symbol editors alike go by this. +pub(crate) fn marker_kept_refusal(p: Picture) -> Option { + lasting(&marker_met(p)) +} + +/// [`marker_kept_refusal`] of what a picture met came to. +fn lasting(found: &Marker) -> Option { + found.as_ref().err().copied().filter(|why| why.lasts()) } -/// Picture marker `p`'s height for its width; `None` if its image doesn't decode (it's drawn as a -/// circle). +/// [`marker_drawn`], `None` where it is drawn as a circle. pub(crate) fn marker_aspect(p: Picture) -> Option { - with_marker(p, false, |_, aspect, _| aspect) + marker_drawn(p).ok() } /// Draws picture marker `p` `width` pixels wide (as tall as its proportions make it), centred at @@ -209,12 +436,17 @@ pub(crate) fn draw_marker(pm: &mut Canvas, p: Picture, width: f32, t: Transform, let paint = PixmapPaint { opacity, quality: FilterQuality::Bilinear, ..PixmapPaint::default() }; pm.draw_shared(img, packed, &paint, at); }) - .is_some() + .is_ok() } -/// Whether base64 `b64` is a PNG or JPEG image that decodes (a picture marker's, before it's set). -pub fn readable(b64: &str) -> bool { - png_or_jpeg(b64) && decode_within(b64, MARKER_SIDE).is_some() +/// Base64 `b64` as a picture marker's image (one already kept, or one before it's set): its +/// height for its width, or why it would be drawn as a circle. Decoded into the run's store, where +/// drawing it finds it. +pub fn check(b64: &str) -> Result { + match Picture::kept(b64) { + Some(kept) => marker_drawn(kept), + None => marker(b64).map(|found| found.aspect), + } } /// Whether base64 `b64` starts as a PNG or a JPEG does. Picture markers take only those, on every @@ -244,11 +476,11 @@ mod tests { }; let (png, jpeg) = (encoded(image::ImageFormat::Png), encoded(image::ImageFormat::Jpeg)); assert!(png_or_jpeg(&png) && png_or_jpeg(&format!(" {jpeg}\n"))); - assert!(readable(&png) && readable(&jpeg)); + assert!(check(&png).is_ok() && check(&jpeg).is_ok()); // A 1x1 GIF; a multi-byte character where the signature is read; text; base64 of text. let gif = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; for not in [gif, "iVBORw0KGgoAAAAé", "", "%%%", "bm90IGFuIGltYWdl"] { - assert!(!png_or_jpeg(not) && !readable(not), "{not}"); + assert!(!png_or_jpeg(not) && check(not) == Err(MarkerRefusal::NotAnImage), "{not}"); } } @@ -271,6 +503,170 @@ mod tests { } } + fn png(w: u32, h: u32) -> String { + let mut bytes = Vec::new(); + image::GrayImage::from_pixel(w, h, image::Luma([90])) + .write_to(&mut std::io::Cursor::new(&mut bytes), image::ImageFormat::Png) + .unwrap(); + base64::engine::general_purpose::STANDARD.encode(&bytes) + } + + /// A one-pixel PNG whose header says `w` × `h`: the size of a crafted image whose few bytes + /// would decode to far more. + fn declaring(w: u32, h: u32) -> String { + let mut bytes = base64::engine::general_purpose::STANDARD.decode(png(1, 1)).unwrap(); + // The header chunk: its length, "IHDR", width and height, …, and its CRC over type and data. + bytes[16..20].copy_from_slice(&w.to_be_bytes()); + bytes[20..24].copy_from_slice(&h.to_be_bytes()); + let crc = bytes[12..29].iter().fold(!0u32, |mut c, &b| { + c ^= u32::from(b); + for _ in 0..8 { + c = if c & 1 == 1 { (c >> 1) ^ 0xEDB8_8320 } else { c >> 1 }; + } + c + }); + bytes[29..33].copy_from_slice(&(!crc).to_be_bytes()); + base64::engine::general_purpose::STANDARD.encode(&bytes) + } + + /// A marker's image is taken up to 2048 × 2048 pixels by area (a long strip too), and one past + /// it is refused from its header, before it is decoded: one declaring 11,000 × 11,000 with a + /// pixel's bytes says so, not that it doesn't decode. Graphics' pictures keep their own limit. + #[test] + fn a_marker_image_past_its_pixels_is_refused_before_it_is_decoded() { + assert_eq!(check(&png(2048, 2048)), Ok(1.0)); + assert_eq!(check(&png(4096, 1024)), Ok(0.25)); + assert_eq!(check(&png(2049, 2048)), Err(MarkerRefusal::TooManyPixels)); + let crafted = declaring(11_000, 11_000); + assert_eq!(size(&crafted), Some((11_000, 11_000))); + assert_eq!(check(&crafted), Err(MarkerRefusal::TooManyPixels)); + assert!(marker_image(Picture::new(&crafted), 64).is_none()); + // A picture graphic as large is still drawn. + assert_eq!(decode(&png(2049, 2048)).map(|p| (p.width(), p.height())), Some((2049, 2048))); + } + + /// The run's budget: an image charged at least an icon's worth, refused (charging nothing) past + /// its pixels or its bytes, so a smaller one still fits. + #[test] + fn a_run_decodes_marker_images_within_its_pixels_and_bytes() { + let mut b = Budget::default(); + let limits = (10 * MARKER_CHARGE, 1000); + assert_eq!(b.take(8 * MARKER_CHARGE, 100, limits), Ok(())); + assert_eq!(b.take(3 * MARKER_CHARGE, 100, limits), Err(MarkerRefusal::PastRunPixels)); + assert_eq!(b.take(MARKER_CHARGE, 901, limits), Err(MarkerRefusal::PastRunPixels), "past its bytes"); + assert_eq!((b.pixels, b.bytes), (8 * MARKER_CHARGE, 100), "a refused one charges nothing"); + // Two icons of a pixel are charged an icon's worth each, the second filling the run. + assert_eq!(b.take(1, 4, limits), Ok(())); + assert_eq!(b.take(1, 4, limits), Ok(())); + assert_eq!(b.take(1, 4, limits), Err(MarkerRefusal::PastRunPixels)); + // What a run keeps fits, at 177 × 177 each. + let keeps = rustgis_map::symbology::MAX_PICTURES as u64; + assert!(keeps * 177 * 177 <= RUN_MARKER_PIXELS && keeps * 177 * 177 * 4 <= RUN_MARKER_BYTES); + // A compressed copy is charged on top, even past the bytes, leaving none for new images. + b.hold(8); + b.hold(2000); + assert_eq!(b.bytes, 2116); + assert_eq!(b.take(1, 4, limits), Err(MarkerRefusal::PastRunPixels)); + } + + /// An image is charged what it holds once scaled down, with its proportions: a wide one is + /// charged its strip, not a square, so as many fit as hold the run's bytes. + #[test] + fn a_marker_image_is_charged_what_it_holds_scaled_down() { + assert_eq!(fitted(1400, 700, 700), (700, 350)); + assert_eq!(fitted(700, 2048, 700), (239, 700)); + assert_eq!(fitted(4096, 1, 700), (700, 1)); + // 31.5 rows, rounded up here and by the decoding alike. + assert_eq!(fitted(2000, 90, 700), (700, 32)); + assert_eq!(fitted(300, 200, 700), (300, 200)); + let mut store = Store::default(); + let wide = png(1400, 700); + let found = marker_in(&mut store, &wide).unwrap(); + assert_eq!((found.image.width(), found.image.height()), (700, 350)); + assert_eq!(store.budget.bytes, 700 * 350 * 4); + // It fits where only its strip is left, which a square's charge wouldn't. + let mut store = Store::default(); + store.budget.bytes = RUN_MARKER_BYTES - 700 * 350 * 4; + assert!(marker_in(&mut store, &wide).is_ok()); + assert_eq!(store.budget.bytes, RUN_MARKER_BYTES); + // So does one whose height rounds at half a pixel: decoded the size it was charged. + let mut store = Store::default(); + store.budget.bytes = RUN_MARKER_BYTES - 700 * 32 * 4; + let found = marker_in(&mut store, &png(2000, 90)).unwrap(); + assert_eq!((found.image.width(), found.image.height()), (700, 32)); + assert_eq!(store.budget.bytes, RUN_MARKER_BYTES); + } + + /// A marker image's compressed copy is charged to the run's bytes, and kept past them (each + /// place would otherwise compress its own). + #[test] + fn a_marker_image_compressed_is_charged_to_the_run() { + let mut image = Pixmap::new(64, 64).unwrap(); + image.fill(tiny_skia::Color::from_rgba8(200, 30, 30, 255)); + let mut budget = Budget::default(); + let packed = pack(&image, |b| budget.hold(b)).expect("compressed"); + assert_eq!(budget.bytes, packed.cost() as u64); + budget.bytes = RUN_MARKER_BYTES; + assert!(pack(&image, |b| budget.hold(b)).is_some()); + assert_eq!(budget.bytes, RUN_MARKER_BYTES + packed.cost() as u64); + } + + /// Only the run's refusal passes with a restart: an image kept already keeps it. + #[test] + fn only_the_runs_refusal_passes() { + use MarkerRefusal::*; + assert_eq!([NotAnImage, TooManyPixels, PastRunPixels].map(MarkerRefusal::lasts), [true, true, false]); + // A kept image the run's spent budget refuses is kept as it is; one refused for itself + // isn't; one that draws is. + let mut store = Store::default(); + let fine = png(8, 8); + assert_eq!(lasting(&marker_in(&mut store, &fine)), None); + assert_eq!(lasting(&marker_in(&mut store, "bm90IGFuIGltYWdl")), Some(NotAnImage)); + assert_eq!(lasting(&marker_in(&mut store, &declaring(2049, 2048))), Some(TooManyPixels)); + store.budget.pixels = RUN_MARKER_PIXELS; + let spent = marker_in(&mut store, &png(9, 9)); + assert_eq!((spent.as_ref().err(), lasting(&spent)), (Some(&PastRunPixels), None)); + } + + /// A marker's image is decoded once for the run: the same image met on another thread, or + /// checked as base64, is the same decoded copy, and a preview is scaled from it. + #[test] + fn a_marker_image_is_decoded_once_for_every_thread() { + let p = Picture::new(&png(300, 150)); + let here = marker_met(p).unwrap(); + let there = std::thread::spawn(move || marker_met(p).unwrap()).join().unwrap(); + assert!(Arc::ptr_eq(&here, &there)); + assert!(Arc::ptr_eq(&here, &marker(p.base64()).unwrap())); + assert_eq!(marker_image(p, 96).map(|(i, a)| (i.width(), i.height(), a)), Some((96, 48, 0.5))); + } + + /// An image whose header is fine but whose data doesn't decode keeps its pixels charged (its + /// decoding took that time) and gives back its bytes (it holds none); met again, it is found + /// refused, charging nothing more. + #[test] + fn a_marker_image_that_does_not_decode_gives_back_its_bytes() { + let mut store = Store::default(); + // A pixel's data under a header saying 100 × 100. + let broken = declaring(100, 100); + assert!(marker_in(&mut store, &broken).is_err_and(|r| r == MarkerRefusal::NotAnImage)); + assert_eq!((store.budget.pixels, store.budget.bytes), (100 * 100, 0)); + assert!(marker_in(&mut store, &broken).is_err()); + assert_eq!(store.budget.pixels, 100 * 100, "found, not charged again"); + let fine = png(100, 50); + assert_eq!(marker_in(&mut store, &fine).map(|m| m.aspect), Ok(0.5)); + assert_eq!(store.budget.bytes, 100 * 50 * 4); + } + + /// The refusals' phrases name the caps they are about. + #[test] + fn refusals_name_their_caps() { + let side = MARKER_PIXELS_SIDE.to_string(); + assert!(MarkerRefusal::TooManyPixels.what().contains(&format!("{side} × {side}"))); + let run = format!("({} megapixels, {} MiB)", RUN_MARKER_PIXELS / 1_000_000, RUN_MARKER_BYTES >> 20); + assert!(MarkerRefusal::PastRunPixels.what().contains(&run)); + assert_eq!(MarkerRefusal::NotAnImage.whose(), "whose image isn't a PNG or JPEG RustGIS reads"); + } + /// Graphics' pictures don't check the signature: they keep what the decoder reads. #[test] fn graphics_pictures_still_decode_what_the_decoder_reads() { @@ -284,6 +680,6 @@ mod tests { // drawn as a graphic, though not taken as a marker. let gif = "R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7"; assert_eq!(decode(gif).is_some(), image::ImageFormat::Gif.reading_enabled()); - assert!(!readable(gif)); + assert!(check(gif).is_err()); } } diff --git a/crates/ui-egui/src/markerimages.rs b/crates/ui-egui/src/markerimages.rs index b3b1f18704..ad9deaaaf1 100644 --- a/crates/ui-egui/src/markerimages.rs +++ b/crates/ui-egui/src/markerimages.rs @@ -60,9 +60,9 @@ pub(crate) fn image(ctx: &egui::Context, m: Marker) -> Option { if let Some(kept) = ctx.data_mut(|d| d.get_temp_mut_or_default::(id).0.get(&pic).cloned()) { return kept; } - // Decoded again at this size, not scaled from the map's 700-pixel copy in render's marker - // cache, which in one step would alias; once a run for an icon. Loaded outside `data_mut`: - // the context's data is locked inside it. + // Scaled by averaging from the copy render decodes once for the run (so it doesn't alias, and + // the image isn't decoded again); once a run for an icon. Loaded outside `data_mut`: the + // context's data is locked inside it. let image = rustgis_engine::render::picture_marker_image(pic, SIDE).map(|(pm, aspect)| { let pixels = egui::ColorImage::from_rgba_premultiplied([pm.width() as usize, pm.height() as usize], pm.data()); Image { texture: ctx.load_texture("picture-marker", pixels, TextureOptions::LINEAR), aspect } diff --git a/crates/ui-egui/src/markerpick.rs b/crates/ui-egui/src/markerpick.rs index c3835169b6..b847e2e677 100644 --- a/crates/ui-egui/src/markerpick.rs +++ b/crates/ui-egui/src/markerpick.rs @@ -75,15 +75,26 @@ impl MarkerImage { // The size first, so a file too large isn't decoded. let b64 = (bytes.len() <= crate::MARKER_FILE_MAX_BYTES).then(|| base64::engine::general_purpose::STANDARD.encode(bytes)); let refused = match &b64 { - None => Some(marker_file_too_large()), - Some(b64) if !rustgis_engine::render::picture_marker_readable(b64) => { - Some(tl!("This image can't be a marker: it isn't a readable PNG or JPEG of at most 20,000 px per side")) + None => Some(marker_file_too_large().to_string()), + Some(b64) => { + use rustgis_engine::render::MarkerRefusal; + // One phrase per refusal, whole, for translation. + rustgis_engine::render::picture_marker_check(b64).err().map(|why| match why { + MarkerRefusal::NotAnImage => tl!("This image can't be a marker: it isn't a readable PNG or JPEG").to_string(), + MarkerRefusal::TooManyPixels => crate::i18n::fmt( + "This image can't be a marker: it has more pixels than {side} × {side}; make it smaller", + &[("side", &rustgis_engine::render::MARKER_PIXELS_SIDE.to_string())], + ), + MarkerRefusal::PastRunPixels => tl!( + "This image can't be a marker: RustGIS has decoded as many marker images as it does until it restarts; restart it to use another" + ) + .to_string(), + }) } - Some(_) => None, }; if let Some(e) = refused { - app.session.notify(e, true); - return Err(e.to_string()); + app.session.notify(e.clone(), true); + return Err(e); } // A layer that left the map while the file came, or a mark no longer in the list (it // can't be, from the editor), runs nothing. @@ -179,7 +190,7 @@ mod tests { } /// The notice for a file that isn't a readable PNG or JPEG the marker can take. - const UNREADABLE: &str = "This image can't be a marker: it isn't a readable PNG or JPEG of at most 20,000 px per side"; + const UNREADABLE: &str = "This image can't be a marker: it isn't a readable PNG or JPEG"; /// «Image…» makes the file the marker of a point symbol, of one mark in a stack of strokes /// (the others as they were) and of a dot fill, on the layer it was clicked for even when @@ -232,8 +243,20 @@ mod tests { big.resize(crate::MARKER_FILE_MAX_BYTES + 1, 0); let large = dir.path().join("large.png"); std::fs::write(&large, &big).unwrap(); + // Small in bytes, past the pixels a marker takes. + let mut wide = Vec::new(); + image::GrayImage::from_pixel(2049, 2048, image::Luma([90])) + .write_to(&mut std::io::Cursor::new(&mut wide), image::ImageFormat::Png) + .unwrap(); + let many = dir.path().join("many.png"); + std::fs::write(&many, &wide).unwrap(); let steps = app.session.undo_depth(); - let refusals = [(&gif, UNREADABLE), (&broken, UNREADABLE), (&large, "This image is too large for a marker: at most about 1.5 MiB")]; + let refusals = [ + (&gif, UNREADABLE), + (&broken, UNREADABLE), + (&large, "This image is too large for a marker: at most about 1.5 MiB"), + (&many, "This image can't be a marker: it has more pixels than 2048 × 2048; make it smaller"), + ]; for (file, said) in refusals { pick_file(&mut app, file, MarkerImage::symbol(cities)); assert_eq!(layer(&app, "Cities").renderer.base_symbol(), before); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 9a38c6b5a9..b8c936575e 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -5828,11 +5828,13 @@ pub(crate) fn stroke_image(layer: u32, class: Option<&ClassRef>, strokes: &[Line } /// A marker as an editor sends it back: an image that can't be drawn (one a file gave that wasn't -/// kept, or that doesn't decode) becomes the circle it is drawn as, which the command takes where -/// it refuses the image. Whether it was replaced. +/// kept, that doesn't decode or that has too many pixels) becomes the circle it is drawn as, which +/// the command takes where it refuses the image. One drawn as a circle only for what the run has +/// spent is sent as it is, to draw after a restart. Whether it was replaced. pub(crate) fn drawn_marker(m: Marker) -> (Marker, bool) { + let lost = |p| rustgis_engine::render::picture_marker_kept_refusal(p).is_some(); match m { - Marker::Picture(p) if !rustgis_engine::render::picture_marker_draws(p) => (Marker::Circle, true), + Marker::Picture(p) if lost(p) => (Marker::Circle, true), m => (m, false), } } @@ -7804,6 +7806,19 @@ pub(crate) fn layout_menu(app: &mut RustGisApp, ui: &mut Ui, n: &str) { mod tests { use super::*; + /// An editor sends back an image that draws as it is, and one refused for itself (not an + /// image) as the circle it is drawn as, counted. The rule is render's + /// `picture_marker_kept_refusal`, whose tests cover one refused only until a restart. + #[test] + fn an_editor_sends_an_image_that_cant_draw_as_its_circle() { + let png = + "iVBORw0KGgoAAAANSUhEUgAAABgAAAAMCAYAAAB4MH11AAAAIElEQVR4nGO4ICPznxQsE3OBJMwwasGoBaMWjFpAGAMALk9r//PjorkAAAAASUVORK5CYII="; + let fine = Marker::Picture(rustgis_engine::map::Picture::new(png)); + assert_eq!(drawn_marker(fine), (fine, false)); + let broken = Marker::Picture(rustgis_engine::map::Picture::new("bm90IGFuIGltYWdl")); + assert_eq!(drawn_marker(broken), (Marker::Circle, true)); + } + /// A point layer given an image by `layer.marker` shows it in its patch (the Layers row and the /// symbol editor's swatch), and a stroke's image marker shows on the stroke editor's line, not /// circles (#2266). diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index a76869151a..5bf79cb103 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -96,8 +96,15 @@ layer.marker={"layer":"Peaks","char":"▲","font":"DejaVu Sans","size":12} A marker can also be an **image**: a PNG or JPEG, picked with **Image…** at the end of **Shape** (choose it again for another image), or given by command as base64 (at most 2 MiB of base64 text, -an image of about 1.5 MiB). Other formats, such as GIF, aren't taken: a file in another format, -one too large, or one that doesn't decode is said in a notice and leaves the marker as it was. +an image of about 1.5 MiB) and of at most 2048 × 2048 pixels (by area: a 4096 × 1024 strip is +taken). Other formats, such as GIF, aren't taken: a file in another format, one too large, or one +that doesn't decode is said in a notice and leaves the marker as it was. Each image is decoded +once until RustGIS restarts, and kept decoded, at most 700 pixels a side: in all at most +256 megapixels of different marker images and 128 MiB once decoded (as many images as it keeps, +at 177 × 177 each), so that a crafted file can't hold it for minutes; past it a new image is +refused, or drawn as a circle, with a notice saying so, until RustGIS is restarted. A vector +export keeps a compressed copy of each image it draws, at most about as much again (some 256 MiB +in all), which counts too and leaves less for new images. Its size is its width, and it is as tall as its proportions make it, as QGIS draws a raster image marker; the symbol's fill and outline don't show. It turns with **Rotation**, is ringed when selected, and is kept in the project file. A project that has one opens only in a RustGIS that @@ -348,11 +355,12 @@ line** turns each mark with the line's direction; the **Angle** turns it further take the stroke's colour, its width as a hash mark's line (or a marker's outline, by command), and its offset to either side. Stack them with line strokes: a casing, a core and ticks across it. A marker can also be an image, with **Image…** under **Shape** or by command (`"image"`, a PNG or -JPEG as base64 of at most 2 MiB): as wide as its **Size** and as tall as its proportions make -it, turned with the line, the stroke's colour and outline left out; selected, each is framed. An -image a file gave that can't be drawn -(too large to keep, or one that doesn't decode) shows as a circle; changing the strokes in the -pane makes it the circle, and says so. By command, `"markers"` on a stroke: +JPEG as base64 of at most 2 MiB and 2048 × 2048 pixels): as wide as its **Size** and as tall as +its proportions make it, turned with the line, the stroke's colour and outline left out; selected, +each is framed. An image a file gave that can't be drawn (too large to keep, one that doesn't +decode or that has too many pixels) shows as a circle; changing the strokes in the pane makes it +the circle, and says so. One past what RustGIS decodes until it restarts shows as a circle and is +kept as it is. By command, `"markers"` on a stroke: ```text layer.lineStrokes={"layer":"Railways","strokes":[{"color":"#333333","width":1.5},{"color":"#333333","width":1,"markers":{"mark":"hash","size":6,"interval":10}}]} diff --git a/docs/user-guide/data-formats.md b/docs/user-guide/data-formats.md index 19063fea3d..8d49ffac4c 100644 --- a/docs/user-guide/data-formats.md +++ b/docs/user-guide/data-formats.md @@ -329,7 +329,7 @@ Scripts use `service.import {"url":"…","name":"My OGC Layer"}` and | OGC API Features | Collections | Their items downloaded as GeoJSON, following the service's `next` pages up to 100,000 features, or more on a computer with more memory (see Environments in the analysis guide; a command such as `service.add` waits a minute at most) | | OGC API Tiles | Collections' map and vector tiles; a landing page's dataset map tiles | A tile layer in WebMercatorQuad, from the tile template the tileset advertises (its `item` link; `…/tiles/WebMercatorQuad/{z}/{y}/{x}`, the usual path, when that can't be read), keeping the tiles link's query (a token), map tiles in the server's image format, vector tiles drawn layer by layer in colours of their own | | WCS 1.0 / 2.0 (a 1.1 service is asked in 1.0) | Coverages, with their bounds | A raster: GetCoverage of the map's view within the coverage's bounds (or its whole extent: `"bbox": "full"`), as a GeoTIFF in EPSG:4326, at most 2048 pixels on a side | -| ArcGIS REST | FeatureServer and MapServer layers; a MapServer's map; an ImageServer; a VectorTileServer | Layers queried as GeoJSON, or in protocol buffers (`f=pbf`, smaller and quicker to read) when the layer's description lists them and names its record limit (the description read first, or given up on after 15 seconds; a first protocol buffer page that can't be fetched or read has the layer read in GeoJSON, with a notice saying why), page by page past the server's record limit (`resultOffset`) up to 100,000 features or more on a computer with more memory (in protocol buffers, also no more than a quarter of the computer's memory once read, from 512 MB, the web app's limit, up to 3 GB; a later page past it ends the read with a notice, and the first page is always kept, within the reader's own limits for a page) (a command such as `service.add` waits a minute at most for the features), where the layer supports paging (ArcGIS Server 10.3 and later; otherwise up to the record limit); a layer comes in drawn as its description's `drawingInfo` says when its renderer is a simple one (fill, line and marker symbols, dashes), by the unique values of one field (as Unique Values, with the service's labels and its default symbol for the rest) or by class breaks (as Graduated Colors with the service's bounds and labels), others keeping RustGIS's symbol with a notice; a picture marker draws its image at its width, its height following the image's own proportion (without a width, its height is taken as its width, with a notice), and one whose image isn't in its description, or isn't a PNG or JPEG of at most 2 MiB of base64 that RustGIS can decode, is a circle, grey or, among classes, in a ramp's colours, with a notice; and with its transparency whatever its renderer (a description that can't be read, or a query asking for its own `resultOffset` or `resultRecordCount`, which skips it, keeps RustGIS's symbol with a notice saying why); a map as its tile cache when it is Web Mercator's pyramid, else exported images; an ImageServer as exported images; a VectorTileServer as its MapLibre style | +| ArcGIS REST | FeatureServer and MapServer layers; a MapServer's map; an ImageServer; a VectorTileServer | Layers queried as GeoJSON, or in protocol buffers (`f=pbf`, smaller and quicker to read) when the layer's description lists them and names its record limit (the description read first, or given up on after 15 seconds; a first protocol buffer page that can't be fetched or read has the layer read in GeoJSON, with a notice saying why), page by page past the server's record limit (`resultOffset`) up to 100,000 features or more on a computer with more memory (in protocol buffers, also no more than a quarter of the computer's memory once read, from 512 MB, the web app's limit, up to 3 GB; a later page past it ends the read with a notice, and the first page is always kept, within the reader's own limits for a page) (a command such as `service.add` waits a minute at most for the features), where the layer supports paging (ArcGIS Server 10.3 and later; otherwise up to the record limit); a layer comes in drawn as its description's `drawingInfo` says when its renderer is a simple one (fill, line and marker symbols, dashes), by the unique values of one field (as Unique Values, with the service's labels and its default symbol for the rest) or by class breaks (as Graduated Colors with the service's bounds and labels), others keeping RustGIS's symbol with a notice; a picture marker draws its image at its width, its height following the image's own proportion (without a width, its height is taken as its width, with a notice), and one whose image isn't in its description, or isn't a PNG or JPEG of at most 2 MiB of base64 and 2048 × 2048 pixels that RustGIS can decode (within the pixels and memory of marker images it decodes until it restarts), is a circle, grey or, among classes, in a ramp's colours, with a notice; and with its transparency whatever its renderer (a description that can't be read, or a query asking for its own `resultOffset` or `resultRecordCount`, which skips it, keeps RustGIS's symbol with a notice saying why); a map as its tile cache when it is Web Mercator's pyramid, else exported images; an ImageServer as exported images; a VectorTileServer as its MapLibre style | A long list stops at its first 2,000 layers, and a note says how many the service has. An OGC API service stops at its first 2,000 collections instead, and each can make up to three layers diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 3b6c909d3b..bc9c0e8dfe 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -413,7 +413,8 @@ near as it can, or left out, and said: the import's notes list, layer by layer, approximated (vector tile styles, a memory layer's fields of kinds RustGIS hasn't as text, gradient and shapeburst fills' offsets left out and colour ramps other than gradients drawn from their first colour to their last, SVG, raster and random fills and dense brushes as a tint of their colour, SVG markers as circles, raster image markers whose image RustGIS can't use as circles (one at a web address, which it doesn't fetch, or kept inside a `.qgz`; a file that doesn't open or isn't a PNG or JPEG; one past -2 MiB of base64 or the images it keeps), those of a fixed aspect ratio in their image's own, +2 MiB of base64, 2048 × 2048 pixels, the images it keeps or the pixels or memory of marker images it decodes +until it restarts), those of a fixed aspect ratio in their image's own, see-through ones opaque and those anchored off their centre along lines centred, dashed polygon outlines solid, label halos with sharp corners drawn round and blended ones drawn over the map, label backgrounds of other shapes drawn as rectangles, label distances from lines diff --git a/schema/fixtures/picture_markers_large.rgis b/schema/fixtures/picture_markers_large.rgis new file mode 100644 index 0000000000..ed7d942847 --- /dev/null +++ b/schema/fixtures/picture_markers_large.rgis @@ -0,0 +1 @@ +{"format":2,"name":"Picture markers past their pixels","maps":[{"name":"Map","layers":[],"basemap":"Paper","camera":{"center":{"x":0.0,"y":2000000.0},"res":30000.0,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":1}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[],"folders":[],"styles":[{"name":"Schools","geometry":"Point","renderer":{"Single":{"fill":[30,90,168,255],"stroke":[255,255,255,255],"stroke_width":0.0,"size":16.0,"marker":{"Picture":"iVBORw0KGgoAAAANSUhEUgAACAEAAAgACAYAAABdZbgOAAAADUlEQVR4nGMQSNjwHwADxAIgjkrKRgAAAABJRU5ErkJggg=="}}},"labels":{"enabled":false,"field":"","size":10.0,"color":[0,0,0,255],"halo":true,"bold":false},"transparency":0.0}],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[],"requires":["picture-markers"]}