Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -211,7 +211,7 @@ And alongside it:
([#995](https://github.com/opengeos/RustGIS/issues/995)); line labels that try other places
along the line (an offset above or below it is done) ([#1187](https://github.com/opengeos/RustGIS/issues/1187)).
- Kernel density (heat map) as a renderer; point clustering.
- SVG markers (PNG and JPEG pictures are done,
- QGIS SVG markers brought in by the style importer (PNG, JPEG and SVG pictures are done,
[#2266](https://github.com/opengeos/RustGIS/issues/2266)), image fill patterns and a symbol
library.
- A legend and colour bar on the map (layouts have both).
Expand Down
4 changes: 3 additions & 1 deletion apps/rustgis-web/src/web.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1405,7 +1405,9 @@ fn services(inbox: Inbox, font_inbox: Inbox, notes: Notes, ctx: egui::Context, e
} else if purpose == "assistantPicture" {
rfd::AsyncFileDialog::new()
.add_filter(rustgis_ui_egui::tl!("Pictures"), rustgis_ui_egui::rustgis_assistant::attach::EXTENSIONS)
} else if purpose == "picture" || marker.is_some() {
} else if marker.is_some() {
rfd::AsyncFileDialog::new().add_filter(rustgis_ui_egui::tl!("Pictures"), rustgis_ui_egui::MARKER_EXTENSIONS)
} else if purpose == "picture" {
rfd::AsyncFileDialog::new().add_filter(rustgis_ui_egui::tl!("Pictures"), &["png", "jpg", "jpeg"])
} else {
rfd::AsyncFileDialog::new().add_filter(
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -115,6 +115,7 @@ pub const CAPABILITIES: &[&str] = &[
PROJECT_CRS,
"dggs-system",
"label-clearance",
"svg-markers",
];
/// An offline area keeping the versions that lost a sync or a Bring Back
/// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them.
Expand Down
74 changes: 69 additions & 5 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ impl Project {
if !required.contains(&"picture-markers") && self.styles.iter().any(|s| s.renderer.has_picture_markers()) {
required.push("picture-markers");
}
if !required.contains(&"svg-markers") && self.styles.iter().any(|s| s.renderer.any_picture(svg_picture)) {
required.push("svg-markers");
}
// And its labels' weights (#2803): an older reader would apply the style without them.
if !required.contains(&"label-weight")
&& self.styles.iter().any(|s| s.labels.in_order().any(|c| c.weight != rustgis_map::symbology::DEFAULT_LABEL_WEIGHT))
Expand Down Expand Up @@ -133,6 +136,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
("tabulate-intersection-empty-zones", command_uses_tabulate_empty_zones),
("layout-element-background", command_uses_element_background),
("picture-markers", command_uses_picture_marker),
("svg-markers", command_uses_svg_marker),
("graticule-mgrs", command_draws_mgrs_graticule),
("graticule-on-top", command_puts_graticule_on_top),
("graticule-color", command_colors_graticule),
Expand Down Expand Up @@ -533,18 +537,37 @@ fn tool_uses(tools: &[&str], id: &str, params: &Value, uses: fn(&Value) -> bool)
/// `layer.marker`, a line stroke's markers or a dot fill given an image: an older reader would
/// leave its `image` out and keep the marker it had, or refuse `"image"` as a mark.
fn command_uses_picture_marker(id: &str, params: &Value) -> bool {
let any = |list: &str, image: fn(&Value) -> Option<&Value>| {
params.get(list).and_then(Value::as_array).is_some_and(|l| l.iter().any(|v| image(v).is_some_and(Value::is_string)))
command_sets_marker_image(id, params, |_| true)
}

/// [`command_uses_picture_marker`] with an SVG (#2266 part E1b): a reader of PNG and JPEG markers
/// only would refuse the command.
fn command_uses_svg_marker(id: &str, params: &Value) -> bool {
command_sets_marker_image(id, params, rustgis_render::picture_marker_is_svg)
}

/// Whether command `id` gives a marker an image (base64) that `image` holds true for.
fn command_sets_marker_image(id: &str, params: &Value, image: fn(&str) -> bool) -> bool {
let any = |list: &str, at: fn(&Value) -> Option<&Value>| {
params.get(list).and_then(Value::as_array).is_some_and(|l| l.iter().any(|v| at(v).and_then(Value::as_str).is_some_and(image)))
};
match id {
"layer.marker" => params.get("image").is_some_and(Value::is_string),
"layer.marker" => params.get("image").and_then(Value::as_str).is_some_and(image),
"layer.lineStrokes" => any("strokes", |st| st.get("markers")?.get("image")),
"layer.fillLayers" => any("fills", |f| f.get("image")),
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_uses_picture_marker)),
"script.run" => params
.get("script")
.and_then(Value::as_str)
.is_some_and(|s| script_uses(s, |id, params| command_sets_marker_image(id, params, image))),
_ => false,
}
}

/// Whether marker image `p` is an SVG ([`command_uses_svg_marker`]'s reason, for saved symbology).
fn svg_picture(p: rustgis_map::Picture) -> bool {
rustgis_render::picture_marker_is_svg(p.base64())
}

/// Use the executor's line grammar; comments/invalid lines are not executable commands, and
/// script_line refuses nested scripts, so this check cannot recurse through script.run.
fn script_uses(script: &str, uses: impl Fn(&str, &Value) -> bool) -> bool {
Expand Down Expand Up @@ -607,6 +630,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> {
(relief_light(layer), "shaded-relief-light"),
(layer.size_by.is_some(), super::SIZE_BY_CAPABILITY),
(layer.has_picture_markers(), "picture-markers"),
(layer.any_picture(svg_picture), "svg-markers"),
(zarr_window(layer), "zarr-window"),
(label_guide(layer), "label-guide"),
(label_weight(layer), "label-weight"),
Expand Down Expand Up @@ -636,7 +660,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
mut on_top,
mut grid_color,
) = (false, false, false, false, false, false, false, false, false, false, false, false, false, false, false);
let mut polygon = false;
let (mut polygon, mut svg) = (false, false);
let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared) = (false, false, false, false, false, false);
for map in maps {
offline_area_id |= map.offline_area_id.is_some();
Expand Down Expand Up @@ -669,6 +693,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
light |= map.layers.iter().any(relief_light);
sized |= map.layers.iter().any(|layer| layer.size_by.is_some());
pictures |= map.layers.iter().any(Layer::has_picture_markers);
svg |= map.layers.iter().any(|layer| layer.any_picture(svg_picture));
zarr |= map.layers.iter().any(zarr_window);
native |= map.layers.iter().any(|layer| held_natively(&layer.dataset));
legends |= map.tiles.iter().any(|tile| {
Expand All @@ -688,6 +713,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
(legends, "normalized-legend-urls"),
(sized, super::SIZE_BY_CAPABILITY),
(pictures, "picture-markers"),
(svg, "svg-markers"),
(zarr, "zarr-window"),
(guided, "label-guide"),
(weighed, "label-weight"),
Expand Down Expand Up @@ -888,6 +914,44 @@ mod tests {
assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["dggs-system"]));
}

/// A saved command that sets an SVG as a marker's image requires `svg-markers` as well as
/// `picture-markers`, in every replayable container: a reader of PNG and JPEG markers only
/// would refuse the command when it replays. A PNG requires `picture-markers` alone, and an
/// image that is neither is refused by the command anyway (#2266 part E1b).
#[test]
fn a_saved_command_setting_an_svg_marker_requires_svg_markers() {
use base64::Engine;
let svg = base64::engine::general_purpose::STANDARD.encode(r#"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 4"/>"#);
let png = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR4nGNgYGD4DwABBAEAwS2OUAAAAABJRU5ErkJggg==";
let base = serde_json::to_value(Project::default()).unwrap();
for (image, expected) in [(png.to_string(), vec!["picture-markers"]), (svg, vec!["picture-markers", "svg-markers"])] {
for (command, params) in [
("layer.marker", json!({"layer": "Cities", "image": image})),
("layer.lineStrokes", json!({"layer": "Rivers", "strokes": [{"width": 1}, {"markers": {"image": image}}]})),
("layer.fillLayers", json!({"layer": "Lakes", "fills": [{"pattern": "dots", "image": image}]})),
] {
let script = format!("# Icons\n{command} {params}");
for (field, value) in [
("tasks", json!([{"name": "Task", "steps": [{"title": "Icon", "command": command, "params": params}]}])),
(
"tasks",
json!([{"name": "Script", "steps": [{"title": "Icon", "command": "script.run", "params": {"script": script}}]}]),
),
("notebooks", json!([{"name": "Notebook", "cells": [{"kind": "code", "source": script}]}])),
(
"gp_history",
json!([{"tool": "Marker", "params": {}, "command": [command, params], "ok": true, "messages": [], "millis": 0}]),
),
] {
let mut document = base.clone();
document[field] = value;
let project = Project::from_json(&document.to_string()).unwrap();
assert_eq!(serde_json::to_value(&project).unwrap()["requires"], json!(expected), "{field} {command} {image}");
}
}
}
}

/// All replayable project containers require non-default options only when requested.
/// Selection of executable notebook cells follows the notebook runner's language boundary.
#[test]
Expand Down
79 changes: 78 additions & 1 deletion crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2738,6 +2738,83 @@ fn an_svg_picture_marker_fixture_opens_drawn_or_said() {
};
assert!(rustgis_render::picture_marker_draws(picture(0)));
assert!(picture(1).base64().starts_with("PHN2Zy") && !rustgis_render::picture_marker_draws(picture(1)));
// Saving names the SVGs for a reader of PNG and JPEG markers only to refuse (#2266 part E1b).
assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["picture-markers", "svg-markers"]));
}

/// An SVG image marker requires `svg-markers` as well as `picture-markers` wherever it is saved:
/// a symbol's, a stroke's markers, a dot fill, what No Fill hid and a saved style, in a project, a
/// map file and a layer file. A reader of PNG and JPEG markers only would draw it as a circle. A
/// PNG, or text that doesn't start as XML, requires `picture-markers` alone; text that starts as
/// XML counts as an SVG, as the renderer tells one, without reading it (#2266 part E1b).
#[test]
#[cfg(not(target_arch = "wasm32"))]
fn an_svg_image_marker_requires_svg_markers_wherever_it_is_saved() {
use base64::Engine;
let b64 = |bytes: &[u8]| base64::engine::general_purpose::STANDARD.encode(bytes);
let svg = b64(br##"<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 8 4"><rect width="8" height="4" fill="#c81e1e"/></svg>"##);
let mut png = Vec::new();
image::RgbaImage::from_pixel(8, 4, image::Rgba([200, 30, 30, 255]))
.write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
.unwrap();
let png = b64(&png);
let pictures = json!(["picture-markers"]);
let both = json!(["picture-markers", "svg-markers"]);
let requires = |p: &Project| serde_json::to_value(p).unwrap()["requires"].clone();
// Removed however the test ends, and its own each run (the process id alone can repeat).
struct Dir(std::path::PathBuf);
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
let nanos = std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_nanos());
let dir = Dir(std::env::temp_dir().join(format!("rustgis-svg-markers-{}-{nanos}", std::process::id())));
std::fs::create_dir_all(&dir.0).unwrap();
let file = |s: &mut Session, command: &str, mut params: Value, name: &str| {
let path = dir.0.join(name);
params["path"] = json!(path.display().to_string());
s.run(command, &params).unwrap();
serde_json::from_slice::<Value>(&std::fs::read(&path).unwrap()).unwrap()["requires"].clone()
};
// `<html>`: XML that isn't an SVG, which the renderer refuses when it reads it.
for (image, expected) in [(png.as_str(), &pictures), (svg.as_str(), &both), ("bm90IGFuIGltYWdl", &pictures), ("PGh0bWw+", &both)] {
// A symbol's (set directly: the command refuses an image that is neither), in the
// project, a map file and a layer file.
let mut s = world();
let cities = s.map().layer_by_name("Cities").unwrap().id;
let picture = rustgis_map::Marker::Picture(rustgis_map::Picture::new(image));
s.map_mut().layer_mut(cities).unwrap().renderer.map_symbols(|sym| sym.marker = picture);
assert_eq!(&requires(&s.project), expected, "symbol {image}");
assert_eq!(&file(&mut s, "map.save", json!({}), "map.rgismap"), expected, "map file {image}");
assert_eq!(&file(&mut s, "layer.save", json!({"layer": "Cities"}), "cities.rgislayer"), expected, "layer file {image}");
// And the map file a map package holds, for a computer and for a phone.
for mobile in [false, true] {
let pkg = dir.0.join("map.rgismpk");
s.run("map.package", &json!({"path": pkg.display().to_string(), "mobile": mobile})).unwrap();
let entries = rustgis_data::zip::read_matching(&std::fs::read(&pkg).unwrap(), |n| n.ends_with(".rgismap")).unwrap();
let packed: Value = serde_json::from_slice(&entries[0].1).unwrap();
assert_eq!(&packed["requires"], expected, "package {image}, mobile: {mobile}");
}
// A saved style keeps it once the layer no longer does.
s.run("style.new", &json!({"layer": "Cities", "name": "Icons"})).unwrap();
s.run("layer.marker", &json!({"layer": "Cities", "shape": "circle"})).unwrap();
assert_eq!(&requires(&s.project), expected, "style {image}");
}
for (image, expected) in [(&png, &pictures), (&svg, &both)] {
// A stroke's markers.
let mut s = world();
s.run("layer.lineStrokes", &json!({"layer": "Rivers", "strokes": [{"width": 1}, {"markers": {"image": image}}]})).unwrap();
assert_eq!(&requires(&s.project), expected, "stroke");
assert_eq!(&file(&mut s, "layer.save", json!({"layer": "Rivers"}), "rivers.rgislayer"), expected, "stroke layer file");
// A dot fill, and what No Fill hid of it.
let (mut s, id) = no_fill_layer(false);
s.run("layer.fillLayers", &json!({"layer": id, "fills": [{"pattern": "dots", "image": image}]})).unwrap();
assert_eq!(&requires(&s.project), expected, "dot fill");
s.run("layer.noFill", &Value::Null).unwrap();
assert!(s.map().layer(id).unwrap().hidden_fills.is_some());
assert_eq!(&requires(&s.project), expected, "hidden by No Fill");
}
}

/// A saved image marker that is a GIF (which the desktop's decoder reads and the web's doesn't)
Expand Down Expand Up @@ -26477,7 +26554,7 @@ fn an_arcgis_services_picture_markers_draw_their_images() {
let texts: Vec<_> = s.notices.iter().map(|n| n.text.as_str()).collect();
let said = "Places: the service's symbology came in, except: picture markers whose image isn't a PNG, JPEG or SVG RustGIS reads, drawn as circles";
assert!(texts.contains(&said), "{texts:?}");
assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["picture-markers"]));
assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["picture-markers", "svg-markers"]));
}

/// An ArcGIS layer's description, read before its features, doesn't count against their budget:
Expand Down
6 changes: 6 additions & 0 deletions crates/render/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -630,6 +630,12 @@ pub fn picture_marker_kept_refusal(p: rustgis_map::Picture) -> Option<MarkerRefu
picture::marker_kept_refusal(p)
}

/// Whether base64 `b64`, a picture marker's image, starts as an SVG does (whether or not it then
/// reads): what a reader of PNG and JPEG markers only can't draw.
pub fn picture_marker_is_svg(b64: &str) -> bool {
picture::is_svg(b64)
}

/// 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_kept_check(p).is_ok()
Expand Down
5 changes: 5 additions & 0 deletions crates/render/src/picture.rs
Original file line number Diff line number Diff line change
Expand Up @@ -564,6 +564,11 @@ enum Format {
Svg,
}

/// Whether base64 `b64` starts as an SVG would, as [`format`] tells it.
pub(crate) fn is_svg(b64: &str) -> bool {
format(b64) == Some(Format::Svg)
}

/// What base64 `b64` starts as, if a picture marker may be one. Picture markers take PNG, JPEG and
/// SVG alone, on every platform: the desktop's decoder also reads GIF (the engine's `gif` feature,
/// for raster files), the web's doesn't, so a GIF marker would draw on one and not the other.
Expand Down
4 changes: 4 additions & 0 deletions crates/ui-egui/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -227,6 +227,10 @@ pub const ASSISTANT_FILE_MAX_BYTES: usize = rustgis_assistant::attach::MAX_FILE_
/// refuse a larger one before reading it.
pub const MARKER_FILE_MAX_BYTES: usize = rustgis_engine::map::symbology::MAX_PICTURE_BYTES / 4 * 3;

/// The files «Image…» lists for a marker, on the computer and in the browser (the phone's picker
/// lists every file).
pub const MARKER_EXTENSIONS: &[&str] = &["png", "jpg", "jpeg", "svg"];

/// The largest script file the Script pane's Load… reads, as the assistant's command file; the
/// browser's shell refuses a larger one before reading it.
pub const SCRIPT_FILE_MAX_BYTES: usize = 1024 * 1024;
Expand Down
Loading
Loading