From 9d39c45c225d6d22a167e5f02a1d255e3e51a5db Mon Sep 17 00:00:00 2001 From: strebdom Date: Fri, 30 Oct 2026 15:10:12 +0100 Subject: [PATCH 1/4] feat(symbology): symbol size, colours, outline width and angle by expression (#882 pieces 6+7, part 2) A layer's symbol takes its marker size, fill and outline colours, outline width and marker angle per feature from expressions in the language of queries (`Layer.symbol_by`, stored as text, compiled once per drawing by `Layer::styler`). A point's marks scale with its size. `layer.symbolBy` sets them; the Symbology pane has a By Expression section; QGIS styles' data-defined size, colours, outline width and angle carry over. The CSS colour parser moves from the tiles crate to `rustgis_data::color`. --- GEOLIBRE_PARITY.md | 6 +- crates/data/src/color.rs | 217 ++++++++++++++++++ crates/data/src/lib.rs | 1 + crates/engine/src/cmd/layer.rs | 41 ++++ crates/engine/src/cmd/qgis.rs | 17 ++ crates/engine/src/cmd/sharing.rs | 7 +- crates/engine/src/tests.rs | 69 ++++++ crates/map/src/lib.rs | 13 ++ crates/map/src/qgis/mod.rs | 10 + crates/map/src/qgis/renderer.rs | 16 +- crates/map/src/qgis/symbol.rs | 122 +++++++++- crates/map/src/qgis/tests.rs | 123 +++++++++- crates/map/src/symbol_by.rs | 374 +++++++++++++++++++++++++++++++ crates/render/src/lib.rs | 88 ++++++-- crates/tiles/src/style.rs | 178 +-------------- crates/ui-egui/src/panes.rs | 106 +++++++++ docs/comparison/geolibre.md | 3 +- docs/user-guide/cartography.md | 22 ++ docs/user-guide/expressions.md | 4 +- docs/user-guide/workspace.md | 9 +- 20 files changed, 1215 insertions(+), 211 deletions(-) create mode 100644 crates/data/src/color.rs create mode 100644 crates/map/src/symbol_by.rs diff --git a/GEOLIBRE_PARITY.md b/GEOLIBRE_PARITY.md index 907e16353e..9878351445 100644 --- a/GEOLIBRE_PARITY.md +++ b/GEOLIBRE_PARITY.md @@ -110,8 +110,10 @@ _GeoLibre: docs/features.md › Map workspace, Rendering engines and 3D globe; d _GeoLibre: docs/features.md › Layers, styling, and labels; docs/user-guide/styling.md_ - [x] **Layer groups**. -- [ ] **Rule-based and expression renderers**: nested rules with scale ranges. Missing; display - filters are per-scale SQL only (_Roadmap: expressions and cartography_). +- [ ] **Rule-based and expression renderers**: nested rules with scale ranges. Partial: a symbol's + size, colours, outline width and marker angle by expression (Symbology › By Expression, + `layer.symbolBy`); display filters are per-scale clauses; rule renderers are missing + (_Roadmap: expressions and cartography_). - [ ] **Heatmap and point-clustering renderers**. Partial: hexagon/square aggregation; kernel density is implemented as an analysis tool, while dynamic heatmap and point-clustering renderers remain outstanding (_Roadmap: expressions and cartography_). diff --git a/crates/data/src/color.rs b/crates/data/src/color.rs new file mode 100644 index 0000000000..aaa696a8ea --- /dev/null +++ b/crates/data/src/color.rs @@ -0,0 +1,217 @@ +//! Colours written as text: CSS colours (`#rrggbb`, `rgb()`, `hsl()`, named) and the +//! `r,g,b[,a]` text expressions give (`color_rgb`, `color_rgba`). + +/// Straight (not premultiplied) RGBA. +pub type Rgba = [u8; 4]; + +/// A colour as an expression gives it: `r,g,b` or `r,g,b,a` (0–255 each, as `color_rgb` and +/// `color_rgba` write it), else a CSS colour ([`parse`]). +pub fn parse_value(s: &str) -> Option { + let t = s.trim(); + if t.len() <= 64 && t.contains(',') && !t.contains('(') { + let parts: Vec<&str> = t.split(',').map(str::trim).collect(); + if (3..=4).contains(&parts.len()) { + let ch = |p: &&str| p.parse::().ok().filter(|v| v.is_finite()).map(|v| v.clamp(0.0, 255.0).round() as u8); + let mut c = [255u8; 4]; + for (slot, p) in c.iter_mut().zip(&parts) { + *slot = ch(p)?; + } + return Some(c); + } + return None; + } + parse(t) +} + +/// Parses a CSS color: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb[a]()`, `hsl[a]()` (comma or space syntax, +/// `/ alpha`, `%` alpha), `transparent` and the 148 CSS named colors. Case-insensitive. +pub fn parse(s: &str) -> Option { + let s = s.trim(); + if s.is_empty() || s.len() > 128 { + return None; + } + let lower = s.to_ascii_lowercase(); + if let Some(hex) = lower.strip_prefix('#') { + return parse_hex(hex); + } + if let Some((name, rest)) = lower.split_once('(') { + let inner = rest.trim_end().strip_suffix(')')?; + let parts: Vec<&str> = inner.split(|c: char| c == ',' || c == '/' || c.is_whitespace()).filter(|p| !p.is_empty()).collect(); + if !(3..=4).contains(&parts.len()) { + return None; + } + let alpha = match parts.get(3) { + Some(a) => alpha_u8(a)?, + None => 255, + }; + let (a, b, c) = (parts.first()?, parts.get(1)?, parts.get(2)?); + return match name.trim() { + "rgb" | "rgba" => Some([channel(a)?, channel(b)?, channel(c)?, alpha]), + "hsl" | "hsla" => { + let [r, g, b] = hsl_to_rgb(hue(a)?, pct(b)?, pct(c)?); + Some([r, g, b, alpha]) + } + _ => None, + }; + } + if lower == "transparent" { + return Some([0, 0, 0, 0]); + } + let i = NAMED_COLORS.binary_search_by(|(n, _)| (*n).cmp(lower.as_str())).ok()?; + let [_, r, g, b] = NAMED_COLORS.get(i)?.1.to_be_bytes(); + Some([r, g, b, 255]) +} + +fn parse_hex(h: &str) -> Option { + if !h.bytes().all(|b| b.is_ascii_hexdigit()) { + return None; + } + let digit = |i: usize, n: usize| h.get(i..i + n).and_then(|d| u8::from_str_radix(d, 16).ok()); + let mut c = [255u8; 4]; + match h.len() { + 3 | 4 => { + for (i, slot) in c.iter_mut().enumerate().take(h.len()) { + *slot = digit(i, 1)? * 17; + } + } + 6 | 8 => { + for (i, slot) in c.iter_mut().enumerate().take(h.len() / 2) { + *slot = digit(i * 2, 2)?; + } + } + _ => return None, + } + Some(c) +} + +fn css_num(s: &str) -> Option { + s.parse::().ok().filter(|v| v.is_finite()) +} + +/// A fraction 0..1 as a channel 0..255. +pub fn unit_u8(v: f64) -> u8 { + (v * 255.0).clamp(0.0, 255.0).round() as u8 +} + +fn channel(s: &str) -> Option { + let v = match s.strip_suffix('%') { + Some(p) => css_num(p)? / 100.0, + None => css_num(s)? / 255.0, + }; + Some(unit_u8(v)) +} + +fn alpha_u8(s: &str) -> Option { + let v = match s.strip_suffix('%') { + Some(p) => css_num(p)? / 100.0, + None => css_num(s)?, + }; + Some(unit_u8(v)) +} + +fn hue(s: &str) -> Option { + Some(css_num(s.strip_suffix("deg").unwrap_or(s))?.rem_euclid(360.0)) +} + +fn pct(s: &str) -> Option { + Some((css_num(s.strip_suffix('%').unwrap_or(s))? / 100.0).clamp(0.0, 1.0)) +} + +fn hsl_to_rgb(h: f64, s: f64, l: f64) -> [u8; 3] { + let c = (1.0 - (2.0 * l - 1.0).abs()) * s; + let hp = h / 60.0; + let x = c * (1.0 - (hp % 2.0 - 1.0).abs()); + let (r, g, b) = match hp as u32 { + 0 => (c, x, 0.0), + 1 => (x, c, 0.0), + 2 => (0.0, c, x), + 3 => (0.0, x, c), + 4 => (x, 0.0, c), + _ => (c, 0.0, x), + }; + let m = l - c / 2.0; + [unit_u8(r + m), unit_u8(g + m), unit_u8(b + m)] +} + +/// CSS named colors, sorted by name, as 0xRRGGBB. +#[rustfmt::skip] +static NAMED_COLORS: [(&str, u32); 148] = [ + ("aliceblue", 0xf0f8ff), ("antiquewhite", 0xfaebd7), ("aqua", 0x00ffff), ("aquamarine", 0x7fffd4), ("azure", 0xf0ffff), + ("beige", 0xf5f5dc), ("bisque", 0xffe4c4), ("black", 0x000000), ("blanchedalmond", 0xffebcd), ("blue", 0x0000ff), + ("blueviolet", 0x8a2be2), ("brown", 0xa52a2a), ("burlywood", 0xdeb887), ("cadetblue", 0x5f9ea0), ("chartreuse", 0x7fff00), + ("chocolate", 0xd2691e), ("coral", 0xff7f50), ("cornflowerblue", 0x6495ed), ("cornsilk", 0xfff8dc), ("crimson", 0xdc143c), + ("cyan", 0x00ffff), ("darkblue", 0x00008b), ("darkcyan", 0x008b8b), ("darkgoldenrod", 0xb8860b), ("darkgray", 0xa9a9a9), + ("darkgreen", 0x006400), ("darkgrey", 0xa9a9a9), ("darkkhaki", 0xbdb76b), ("darkmagenta", 0x8b008b), ("darkolivegreen", 0x556b2f), + ("darkorange", 0xff8c00), ("darkorchid", 0x9932cc), ("darkred", 0x8b0000), ("darksalmon", 0xe9967a), ("darkseagreen", 0x8fbc8f), + ("darkslateblue", 0x483d8b), ("darkslategray", 0x2f4f4f), ("darkslategrey", 0x2f4f4f), ("darkturquoise", 0x00ced1), + ("darkviolet", 0x9400d3), ("deeppink", 0xff1493), ("deepskyblue", 0x00bfff), ("dimgray", 0x696969), ("dimgrey", 0x696969), + ("dodgerblue", 0x1e90ff), ("firebrick", 0xb22222), ("floralwhite", 0xfffaf0), ("forestgreen", 0x228b22), ("fuchsia", 0xff00ff), + ("gainsboro", 0xdcdcdc), ("ghostwhite", 0xf8f8ff), ("gold", 0xffd700), ("goldenrod", 0xdaa520), ("gray", 0x808080), + ("green", 0x008000), ("greenyellow", 0xadff2f), ("grey", 0x808080), ("honeydew", 0xf0fff0), ("hotpink", 0xff69b4), + ("indianred", 0xcd5c5c), ("indigo", 0x4b0082), ("ivory", 0xfffff0), ("khaki", 0xf0e68c), ("lavender", 0xe6e6fa), + ("lavenderblush", 0xfff0f5), ("lawngreen", 0x7cfc00), ("lemonchiffon", 0xfffacd), ("lightblue", 0xadd8e6), + ("lightcoral", 0xf08080), ("lightcyan", 0xe0ffff), ("lightgoldenrodyellow", 0xfafad2), ("lightgray", 0xd3d3d3), + ("lightgreen", 0x90ee90), ("lightgrey", 0xd3d3d3), ("lightpink", 0xffb6c1), ("lightsalmon", 0xffa07a), ("lightseagreen", 0x20b2aa), + ("lightskyblue", 0x87cefa), ("lightslategray", 0x778899), ("lightslategrey", 0x778899), ("lightsteelblue", 0xb0c4de), + ("lightyellow", 0xffffe0), ("lime", 0x00ff00), ("limegreen", 0x32cd32), ("linen", 0xfaf0e6), ("magenta", 0xff00ff), + ("maroon", 0x800000), ("mediumaquamarine", 0x66cdaa), ("mediumblue", 0x0000cd), ("mediumorchid", 0xba55d3), + ("mediumpurple", 0x9370db), ("mediumseagreen", 0x3cb371), ("mediumslateblue", 0x7b68ee), ("mediumspringgreen", 0x00fa9a), + ("mediumturquoise", 0x48d1cc), ("mediumvioletred", 0xc71585), ("midnightblue", 0x191970), ("mintcream", 0xf5fffa), + ("mistyrose", 0xffe4e1), ("moccasin", 0xffe4b5), ("navajowhite", 0xffdead), ("navy", 0x000080), ("oldlace", 0xfdf5e6), + ("olive", 0x808000), ("olivedrab", 0x6b8e23), ("orange", 0xffa500), ("orangered", 0xff4500), ("orchid", 0xda70d6), + ("palegoldenrod", 0xeee8aa), ("palegreen", 0x98fb98), ("paleturquoise", 0xafeeee), ("palevioletred", 0xdb7093), + ("papayawhip", 0xffefd5), ("peachpuff", 0xffdab9), ("peru", 0xcd853f), ("pink", 0xffc0cb), ("plum", 0xdda0dd), + ("powderblue", 0xb0e0e6), ("purple", 0x800080), ("rebeccapurple", 0x663399), ("red", 0xff0000), ("rosybrown", 0xbc8f8f), + ("royalblue", 0x4169e1), ("saddlebrown", 0x8b4513), ("salmon", 0xfa8072), ("sandybrown", 0xf4a460), ("seagreen", 0x2e8b57), + ("seashell", 0xfff5ee), ("sienna", 0xa0522d), ("silver", 0xc0c0c0), ("skyblue", 0x87ceeb), ("slateblue", 0x6a5acd), + ("slategray", 0x708090), ("slategrey", 0x708090), ("snow", 0xfffafa), ("springgreen", 0x00ff7f), ("steelblue", 0x4682b4), + ("tan", 0xd2b48c), ("teal", 0x008080), ("thistle", 0xd8bfd8), ("tomato", 0xff6347), ("turquoise", 0x40e0d0), ("violet", 0xee82ee), + ("wheat", 0xf5deb3), ("white", 0xffffff), ("whitesmoke", 0xf5f5f5), ("yellow", 0xffff00), ("yellowgreen", 0x9acd32), +]; + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn colors() { + assert_eq!(parse("#f00"), Some([255, 0, 0, 255])); + assert_eq!(parse("#F008"), Some([255, 0, 0, 136])); + assert_eq!(parse("#12ab3C"), Some([0x12, 0xab, 0x3c, 255])); + assert_eq!(parse("#12ab3c80"), Some([0x12, 0xab, 0x3c, 0x80])); + assert_eq!(parse("#12ab3"), None); + assert_eq!(parse("#ggg"), None); + assert_eq!(parse("rgb(255, 128, 0)"), Some([255, 128, 0, 255])); + assert_eq!(parse("rgba( 10 , 20 , 30 , 0.5 )"), Some([10, 20, 30, 128])); + assert_eq!(parse("rgba(10,20,30,50%)"), Some([10, 20, 30, 128])); + assert_eq!(parse("rgb(10 20 30 / 0.25)"), Some([10, 20, 30, 64])); + assert_eq!(parse("rgb(100%, 0%, 50%)"), Some([255, 0, 128, 255])); + assert_eq!(parse("hsl(0, 100%, 50%)"), Some([255, 0, 0, 255])); + assert_eq!(parse("hsl(120,100%,25%)"), Some([0, 128, 0, 255])); + assert_eq!(parse("hsla(240, 100%, 50%, 0.5)"), Some([0, 0, 255, 128])); + assert_eq!(parse("hsl(240deg 100% 50% / 50%)"), Some([0, 0, 255, 128])); + assert_eq!(parse("hsla(0,3%,85%,0.84)"), Some([218, 216, 216, 214])); + assert_eq!(parse("Red"), Some([255, 0, 0, 255])); + assert_eq!(parse("rebeccapurple"), Some([0x66, 0x33, 0x99, 255])); + assert_eq!(parse("yellowgreen"), Some([0x9a, 0xcd, 0x32, 255])); + assert_eq!(parse(" transparent "), Some([0, 0, 0, 0])); + for bad in ["", "rgb(1,2)", "rgb(1,2,3,4,5)", "foo(1,2,3)", "rgb(a,b,c)", "nocolor", "rgb(1,2,3", "#"] { + assert_eq!(parse(bad), None, "{bad}"); + } + assert!(NAMED_COLORS.windows(2).all(|w| w[0].0 < w[1].0), "table sorted"); + assert!(NAMED_COLORS.iter().all(|(n, _)| parse(n).is_some())); + } + + #[test] + fn expression_colours() { + assert_eq!(parse_value("255,0,0"), Some([255, 0, 0, 255])); + assert_eq!(parse_value(" 10, 20 ,30, 128 "), Some([10, 20, 30, 128])); + assert_eq!(parse_value("300,-4,1.6"), Some([255, 0, 2, 255])); + assert_eq!(parse_value("#00ff00"), Some([0, 255, 0, 255])); + assert_eq!(parse_value("rgb(1, 2, 3)"), Some([1, 2, 3, 255])); + assert_eq!(parse_value("navy"), Some([0, 0, 128, 255])); + for bad in ["", "1,2", "1,2,3,4,5", "a,b,c", "1,2,NaN", "1,,3", "red,green,blue"] { + assert_eq!(parse_value(bad), None, "{bad}"); + } + } +} diff --git a/crates/data/src/lib.rs b/crates/data/src/lib.rs index 36f2459241..0899e4149d 100644 --- a/crates/data/src/lib.rs +++ b/crates/data/src/lib.rs @@ -4,6 +4,7 @@ //! bad features are skipped and counted in [`ReadReport`]. #![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)] +pub mod color; mod dbf; pub mod dirs; pub mod dxf; diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index a1f03eca9a..025e415662 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -230,6 +230,9 @@ pub fn commands() -> Vec { }) .when(need_points) .params(r#"{"layer"?, "field": numeric field name|null (each point's marker turned by the angle in it, in degrees; null: not turned), "counterclockwise"?: bool (the angles run counterclockwise, as in mathematics; default clockwise, as on a compass)}"#), + C::new("layer.symbolBy", "Symbol by Expression", "Style › Drawing", symbol_by) + .when(need_feature_layer) + .params(r#"{"layer"?, "size"?: expression|null (a point's marker size in points), "fill"?: expression|null (the fill colour: '#RRGGBB', a CSS colour name or 'r,g,b[,a]' as color_rgb gives it), "stroke"?: expression|null (the outline colour, a line's colour), "strokeWidth"?: expression|null (the outline's width in points, a line's width), "angle"?: expression|null (point layers: each marker turned by it, in degrees clockwise, in place of layer.markerRotation's field)} (each expression in the language of queries, per feature, @map_scale the map's scale; a key left out keeps its expression, null or "" removes it; where an expression gives null the symbol's own value is drawn)"#), C::new("layer.strokeLevels", "Stroke Levels", "Style › Drawing", |s, p| { let on = b(p, "on").ok_or("on is true or false")?; let id = s.layer_id(p)?; @@ -540,6 +543,44 @@ fn need_lines(s: &Session) -> Option<&'static str> { } } +/// `layer.symbolBy`: sets (or removes) the expressions a layer's symbol takes per feature, each +/// checked against its fields first. +fn symbol_by(s: &mut Session, p: &Value) -> CmdResult { + const KEYS: [&str; 5] = ["size", "fill", "stroke", "strokeWidth", "angle"]; + let id = s.layer_id(p)?; + let l = s.map_mut().layer_mut(id).ok_or("no such layer")?; + if l.is_raster() || l.graphics { + return Err("this works on feature layers".into()); + } + let mut by = l.symbol_by.clone(); + for key in KEYS { + let text = match p.get(key) { + None => continue, + Some(Value::Null) => None, + Some(Value::String(t)) if t.trim().is_empty() => None, + Some(Value::String(t)) => Some(t.clone()), + Some(_) => return Err(format!("{key} is an expression's text, or null for none")), + }; + if let Some(t) = &text { + if key == "angle" && l.geometry_type() != GeometryType::Point { + return Err("angle works on point layers".into()); + } + rustgis_data::query::parse(t, &l.dataset).map_err(|e| format!("{key}: {e}"))?; + } + let slot = match key { + "size" => &mut by.size, + "fill" => &mut by.fill, + "stroke" => &mut by.stroke, + "strokeWidth" => &mut by.stroke_width, + _ => &mut by.angle, + }; + *slot = text; + } + l.symbol_by = by; + let b = &l.symbol_by; + Ok(json!({"size": b.size, "fill": b.fill, "stroke": b.stroke, "strokeWidth": b.stroke_width, "angle": b.angle})) +} + /// `layer.lineStrokes`: sets a line layer's stacked strokes, or one class's own. fn line_strokes(s: &mut Session, p: &Value) -> CmdResult { let class = class_ref(p)?; diff --git a/crates/engine/src/cmd/qgis.rs b/crates/engine/src/cmd/qgis.rs index 5c6e70d6ae..73b23136f6 100644 --- a/crates/engine/src/cmd/qgis.rs +++ b/crates/engine/src/cmd/qgis.rs @@ -251,6 +251,23 @@ fn check_fields(l: &mut rustgis_map::Layer, name: &str, report: &mut Report) { if let Some(f) = field.filter(|f| l.dataset.field_index(f).is_none()) { report.approximated(name, format!("classes by the field {f}, which the layer hasn't: every feature draws as the rest")); } + // The symbol's data-defined settings: an expression that doesn't read here (a QGIS function + // or variable RustGIS lacks, a field the layer hasn't) is left out. + let by = &mut l.symbol_by; + for (what, slot) in [ + ("size", &mut by.size), + ("fill colour", &mut by.fill), + ("outline colour", &mut by.stroke), + ("outline width", &mut by.stroke_width), + ("angle", &mut by.angle), + ] { + if let Some(text) = slot.as_deref() + && let Err(e) = rustgis_data::query::parse(text, &l.dataset) + { + report.skipped(name, format!("its data-defined symbol {what} `{text}` ({e})")); + *slot = None; + } + } } /// Gives what a QGIS web layer was added as the layer's visibility, opacity and blending mode. diff --git a/crates/engine/src/cmd/sharing.rs b/crates/engine/src/cmd/sharing.rs index 2111e691f9..410a1e2859 100644 --- a/crates/engine/src/cmd/sharing.rs +++ b/crates/engine/src/cmd/sharing.rs @@ -445,6 +445,8 @@ fn styled_features(l: &Layer, budget: &mut usize) -> Vec { let rows = l.visible_rows(); let opacity = 1.0 - f64::from(l.transparency.clamp(0.0, 100.0)) / 100.0; let mut out = Vec::new(); + // Its symbol by expression (no map scale: the page zooms on its own). + let styler = l.styler(None); for (row, ft) in l.dataset.features.iter().enumerate() { if *budget == 0 { break; @@ -453,7 +455,7 @@ fn styled_features(l: &Layer, budget: &mut usize) -> Vec { continue; } let Some(g) = &ft.geometry else { continue }; - let sym = l.symbol(row); + let sym = styler.symbol(row); let props: serde_json::Map = l.dataset.fields.iter().enumerate().map(|(i, f)| (f.name.clone(), json!(l.dataset.value(row, i).to_string()))).collect(); out.push(json!({ @@ -879,6 +881,7 @@ fn gltf(m: &Map, view: (f64, f64)) -> Result, String> { let hf = ex.and_then(|e| e.field.as_deref()).and_then(|f| l.dataset.field_index(f)); let (base_h, factor) = ex.map_or((0.0, 0.0), |e| (e.height, e.factor)); let rows = l.visible_rows(); + let styler = l.styler(Some(m.scale())); // The bytes built so far: a feature only adds to its own colour, so each step adds what // the last feature's colour grew by. let size = |tri: &std::collections::BTreeMap<[u8; 4], (Vec<[f32; 3]>, Vec)>, @@ -901,7 +904,7 @@ fn gltf(m: &Map, view: (f64, f64)) -> Result, String> { if buffer.len() + built > MAX_SCENE_BYTES { return Err("the scene would be too large; share fewer features".into()); } - let sym = l.symbol(row); + let sym = styler.symbol(row); let h = (hf.and_then(|fi| l.dataset.value(row, fi).as_f64()).filter(|v| v.is_finite()).unwrap_or(base_h) * factor) .clamp(0.0, 1e6) as f32; let key = [sym.fill.r(), sym.fill.g(), sym.fill.b(), sym.fill.a()]; diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 0973ecaa57..edd02058fc 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -769,6 +769,75 @@ fn a_point_takes_stacked_marks_and_turns_by_a_field() { assert!(s.map().layer_by_name("Cities").unwrap().marker_rotation.is_none()); } +#[test] +fn a_symbol_is_set_by_expressions() { + let mut s = world(); + let r = s + .run("layer.symbolBy", &json!({"layer": "Cities", "size": "scale_linear(pop_max, 0, 2e7, 4, 20)", "fill": "if(pop_max > 1e7, '#ff0000', NULL)", "angle": "45"})) + .unwrap(); + assert_eq!(r["angle"], "45"); + let l = s.map().layer_by_name("Cities").unwrap(); + let fi = l.dataset.field_index("pop_max").unwrap(); + let big = (0..l.dataset.features.len()).find(|r| l.dataset.value(*r, fi).as_f64().is_some_and(|v| v > 1e7)).unwrap(); + let st = l.styler(None); + assert_eq!(st.symbol(big).fill, rustgis_map::Rgba::new(255, 0, 0, 255)); + assert!(st.symbol(big).size > 4.0); + assert_eq!(st.marker_turn(big), 45.0); + // Drawn in an export. + let dir = std::env::temp_dir().join(format!("rustgis-symbol-by-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + s.run("share.exportMap", &json!({"path": dir.join("map.png").display().to_string(), "width": 320, "height": 200})).unwrap(); + std::fs::remove_dir_all(&dir).ok(); + let depth = s.undo_depth(); + for (bad, says) in [ + (json!({"layer": "Cities", "size": "nosuch + 1"}), "size: "), + (json!({"layer": "Cities", "fill": "'red' ||"}), "fill: "), + (json!({"layer": "Cities", "stroke": 3}), "stroke is an expression"), + (json!({"layer": "Rivers", "angle": "10"}), "angle works on point layers"), + ] { + let err = s.run("layer.symbolBy", &bad).unwrap_err(); + assert!(err.contains(says), "{bad}: {err}"); + } + assert_eq!(s.undo_depth(), depth); + // A line's width by expression; the Cities keep theirs. + s.run("layer.symbolBy", &json!({"layer": "Rivers", "strokeWidth": "2.5"})).unwrap(); + assert_eq!(s.map().layer_by_name("Cities").unwrap().symbol_by.angle.as_deref(), Some("45")); + // A key left out is kept; null removes one, and undo brings it back. + s.run("layer.symbolBy", &json!({"layer": "Cities", "angle": null, "fill": ""})).unwrap(); + let by = &s.map().layer_by_name("Cities").unwrap().symbol_by; + assert!(by.size.is_some() && by.fill.is_none() && by.angle.is_none()); + s.undo(); + assert_eq!(s.map().layer_by_name("Cities").unwrap().symbol_by.angle.as_deref(), Some("45")); +} + +#[test] +fn a_qgis_styles_data_defined_settings_are_kept_where_they_read() { + let mut s = world(); + // Size by a field Cities has; fill by a QGIS function RustGIS lacks; outline by a field it hasn't. + let dd = |name: &str, expr: &str| { + format!( + r#""# + ) + }; + let qml = format!( + r#" + + + "#, + dd("size", ""pop_max" / 1e6"), + dd("fillColor", "set_color_part(@symbol_color, 'value', 40)"), + dd("outlineColor", ""nosuch""), + ); + let out = s.run("style.importQgis", &json!({"layer": "Cities", "text": qml})).unwrap(); + let by = &s.map().layer_by_name("Cities").unwrap().symbol_by; + assert_eq!((by.size.as_deref(), &by.fill, &by.stroke), (Some(r#""pop_max" / 1e6"#), &None, &None), "{by:?}"); + let notes = serde_json::to_string(&out["notes"]).unwrap(); + assert!( + notes.contains("data-defined symbol fill colour `set_color_part") && notes.contains("outline colour `\\\"nosuch\\\"`"), + "{notes}" + ); +} + #[test] fn a_stroke_is_dashed_by_command() { let mut s = world(); diff --git a/crates/map/src/lib.rs b/crates/map/src/lib.rs index a06abca246..975e4a5749 100644 --- a/crates/map/src/lib.rs +++ b/crates/map/src/lib.rs @@ -22,6 +22,7 @@ pub mod qgis; pub mod raster; pub mod report; pub mod source; +pub mod symbol_by; pub mod symbology; pub mod tiles; pub mod time; @@ -166,6 +167,10 @@ pub struct Layer { /// field, as QGIS's data-defined symbol angle does. #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "symbology::de_marker_rotation")] pub marker_rotation: Option, + /// Its symbol's size, colours, outline width and marker angle per feature, each by an + /// expression (none set: the renderer's symbol alone); drawn through [`Layer::styler`]. + #[serde(default, skip_serializing_if = "symbol_by::SymbolBy::is_empty", deserialize_with = "symbol_by::de_symbol_by")] + pub symbol_by: symbol_by::SymbolBy, /// The scale (1:N) its symbol and label sizes are set for: drawn at another scale they grow /// and shrink with the map, as on paper (QGIS's reference scale). `None`: they keep their /// size on screen. @@ -372,6 +377,7 @@ impl Layer { fill_layers: Vec::new(), stroke_levels: false, marker_rotation: None, + symbol_by: Default::default(), reference_scale: None, priority: 0, design: design::Design::default(), @@ -574,6 +580,13 @@ impl Layer { r.turn(&self.dataset, row) } + /// Its per-row style for one drawing at the map scale 1:`map_scale` (none: no map, as in an + /// export of the features): [`Layer::symbol`] and the rest with [`Layer::symbol_by`]'s + /// expressions applied, compiled once here. + pub fn styler(&self, map_scale: Option) -> symbol_by::Styler<'_> { + symbol_by::Styler::new(self, map_scale) + } + /// The stacked strokes a line feature row is drawn with: its class's own /// ([`Renderer::strokes_for`]), else the layer's `line_strokes`; none (the single stroke) for /// a graphics layer. diff --git a/crates/map/src/qgis/mod.rs b/crates/map/src/qgis/mod.rs index 3b51594a05..69cfdec789 100644 --- a/crates/map/src/qgis/mod.rs +++ b/crates/map/src/qgis/mod.rs @@ -108,6 +108,9 @@ pub struct Style { pub stroke_levels: Option, /// Point markers turned by a field (`Some(None)`: not turned). pub marker_rotation: Option>, + /// Its data-defined size, colours, outline width and angle, as expressions (`Some` of an + /// empty one: none). + pub symbol_by: Option, pub reference_scale: Option, pub labels: Option, /// 0 opaque to 100 invisible. @@ -161,6 +164,13 @@ impl Style { if let Some(r) = &self.marker_rotation { layer.marker_rotation = r.clone().filter(|_| layer.geometry_type() == rustgis_data::GeometryType::Point); } + if let Some(by) = &self.symbol_by { + layer.symbol_by = by.clone(); + // Only a point layer's markers turn. + if layer.geometry_type() != rustgis_data::GeometryType::Point { + layer.symbol_by.angle = None; + } + } if let Some(r) = self.reference_scale { layer.reference_scale = Some(r); } diff --git a/crates/map/src/qgis/renderer.rs b/crates/map/src/qgis/renderer.rs index 3510248e21..315d390767 100644 --- a/crates/map/src/qgis/renderer.rs +++ b/crates/map/src/qgis/renderer.rs @@ -49,6 +49,8 @@ fn read_depth(r: Node, layer: &str, style: &mut Style, report: &mut Report, dept // The first symbol turned by a field turns the layer's markers. let rotation = std::cell::RefCell::new(None); let turned = symbols.values().any(|n| symbol::turns_by_field(*n)); + // Every symbol's data-defined expressions: the first that has any are the layer's. + let by: std::cell::RefCell> = std::cell::RefCell::new(Vec::new()); let read = |n: Node, report: &mut Report| { let c = symbol::read(n, reference, turned, layer, report); if let (Some(r), Ok(mut had)) = (&c.rotation, rotation.try_borrow_mut()) @@ -56,6 +58,11 @@ fn read_depth(r: Node, layer: &str, style: &mut Style, report: &mut Report, dept { report.approximated(layer, "marker layers turned by different fields, all turned by the first"); } + if let Ok(mut all) = by.try_borrow_mut() + && !all.contains(&c.by) + { + all.push(c.by.clone()); + } c }; let sym = |name: Option<&str>, report: &mut Report| -> Option { symbols.get(name?).map(|n| read(*n, report)) }; @@ -91,6 +98,13 @@ fn read_depth(r: Node, layer: &str, style: &mut Style, report: &mut Report, dept matches!(kind, "pointCluster" | "pointDisplacement" | "invertedPolygonRenderer" | "mergedFeatureRenderer" | "25dRenderer"); if style.renderer.is_some() && !wrapper { style.marker_rotation = Some(rotation.try_borrow().ok().and_then(|r| r.clone())); + let all = by.try_borrow().map(|b| b.clone()).unwrap_or_default(); + let first = all.iter().find(|b| !b.is_empty()).cloned().unwrap_or_default(); + // Classes with other expressions, or none, are drawn with the first's. + if !first.is_empty() && all.len() > 1 { + report.approximated(layer, "symbols with different data-defined settings, all drawn with the first's"); + } + style.symbol_by = Some(first); } } @@ -108,7 +122,7 @@ fn field_of(attr: &str, layer: &str, report: &mut Report) -> Option { /// A switched-off class (`render="false"`): it draws nothing. fn switched_off() -> Converted { - Converted { symbol: symbol::hidden(), strokes: Vec::new(), rotation: None, fills: Vec::new() } + Converted { symbol: symbol::hidden(), strokes: Vec::new(), rotation: None, by: Default::default(), fills: Vec::new() } } type SymbolOf<'a> = dyn Fn(Option<&str>, &mut Report) -> Option + 'a; diff --git a/crates/map/src/qgis/symbol.rs b/crates/map/src/qgis/symbol.rs index 32faca3b53..a7a2f3908e 100644 --- a/crates/map/src/qgis/symbol.rs +++ b/crates/map/src/qgis/symbol.rs @@ -8,6 +8,7 @@ use roxmltree::Node; use super::{Report, color, data_defined_on, has_effect, points, prop, props, signed_points}; use crate::Rgba; use crate::fills::{FillLayer, FillPattern, GradientPoint, GradientShape, Spread, Stop, Stops}; +use crate::symbol_by::SymbolBy; use crate::symbology::{ Dash, Glyph, LineCap, LineJoin, LineMark, LineMarkers, LineStroke, MAX_DASH_STEPS, MAX_STROKES, Marker, MarkerRotation, Placements, Symbol, @@ -28,6 +29,8 @@ pub(super) struct Converted { pub strokes: Vec, /// A marker symbol turned by a field (its data-defined angle). pub rotation: Option, + /// Its data-defined size, colours, outline width and angle, as expressions. + pub by: SymbolBy, /// A fill symbol's stacked fills, bottom first: empty when its one fill is a colour (the /// symbol's own), as before patterns were read. pub fills: Vec, @@ -68,11 +71,19 @@ pub(super) fn read(sym: Node, reference: Option, turned: bool, layer: &str, .take(64) .map(|l| (l, settings(l, unit))) .collect(); - // A marker symbol's angle from a field turns the layer's markers; other data-defined settings - // are noted. + // A marker symbol's angle from a field turns the layer's markers; its size, colours, outline + // width and other angles become expressions; other data-defined settings are noted. let is_marker = !matches!(sym.attribute("type"), Some("fill") | Some("line")); let mut rotation = None; - for node in std::iter::once(sym).chain(layers.iter().map(|(l, _)| *l)) { + let mut by = SymbolBy::default(); + // The size (in points) of the layer whose size expression was taken. + let mut sized_layer: Option = None; + // How many of its layers are sized by expression. + let mut sized_layers = 0; + // A marker of several layers draws as marks scaled with its size: the top layer's is read first. + let marks = is_marker && layers.len() > 1; + let order: Vec<&(Node, Props)> = if marks { layers.iter().rev().collect() } else { layers.iter().collect() }; + for (node, p) in std::iter::once((sym, None)).chain(order.into_iter().map(|(l, p)| (*l, Some(p.as_slice())))) { let active = active_properties(node); // A layout `active_properties` doesn't read (QGIS 2's `dd_properties`) is still noted. if active.is_empty() && data_defined_on(node) { @@ -82,10 +93,27 @@ pub(super) fn read(sym: Node, reference: Option, turned: bool, layer: &str, match field_angle(property).filter(|_| is_marker && name == "angle") { Some(r) if rotation.as_ref().is_none_or(|had| *had == r) => rotation = Some(r), Some(_) => report.approximated(layer, "marker layers turned by different fields, all turned by the first"), + // A lower layer's size: the marks scale with the top one's. + None if marks && name == "size" && by.size.is_some() => sized_layers += usize::from(p.is_some()), + None if by_expression(sym.attribute("type"), name, property, p, reference, &mut by, layer, report) => { + // (A size on the symbol itself scales the whole symbol: nothing to turn.) + if name == "size" && p.is_some() { + sized_layers += 1; + sized_layer = p.and_then(|p| size(p, "size", reference, layer, report)).or(Some(2.0 * 96.0 / 25.4)); + } + if !(marks && name == "size") && layers.len() > 1 { + report.approximated(layer, "data-defined settings of one symbol layer, applied to the whole symbol"); + } + } None => report.skipped(layer, "data-defined symbol settings (from fields or expressions)"), } } } + // Each layer sized by expression scales as QGIS scales them together; a layer of a fixed size + // scales with the rest. + if marks && by.size.is_some() && sized_layers < layers.len() { + report.approximated(layer, "the layers of a marker sized by expression, all scaled with its size"); + } for (l, _) in &layers { if has_effect(*l) { report.skipped(layer, "draw effects (shadows, glows, blurs and the like)"); @@ -97,6 +125,33 @@ pub(super) fn read(sym: Node, reference: Option, turned: bool, layer: &str, _ => marker(&layers, reference, turned && rotation.is_none(), layer, report), }; out.rotation = rotation; + let drawn_as_marks = is_marker && !out.strokes.is_empty(); + // Marks keep their own colours and outlines. + if drawn_as_marks && (by.fill.is_some() || by.stroke.is_some() || by.stroke_width.is_some()) { + report.skipped(layer, "data-defined colours and outline widths of a marker drawn as marks"); + (by.fill, by.stroke, by.stroke_width) = (None, None, None); + } + // Marks scale with the symbol's size, its largest layer's: the expression, taken from one + // layer, is turned into the size it gives that one, so every mark scales as that layer does. + if let (true, Some(text), Some(own)) = (drawn_as_marks, by.size.as_ref(), sized_layer.map(|s| s.clamp(0.0, 200.0))) + && own > 0.0 + && out.symbol.size > 0.0 + && (out.symbol.size / own - 1.0).abs() > 1e-6 + { + let k = (f64::from(out.symbol.size / own)).clamp(1e-3, 1e3); + let scaled = format!("({text}) * {}", (k * 1e6).round() / 1e6); + if scaled.len() <= rustgis_data::query::MAX_LEN { + by.size = Some(scaled); + } else { + report.skipped(layer, "a data-defined marker size too long to read"); + by.size = None; + } + } + // (An expression's colour is drawn as it is: the symbol's opacity doesn't fade it.) + if alpha < 1.0 && (by.fill.is_some() || by.stroke.is_some()) { + report.approximated(layer, "data-defined colours of a see-through symbol, drawn opaque"); + } + out.by = by; out.symbol.fill = fade(out.symbol.fill); out.symbol.stroke = fade(out.symbol.stroke); for s in &mut out.strokes { @@ -371,7 +426,7 @@ fn fill(layers: &[(Node, Props)], reference: Option, layer: &str, report: & } let symbol = Symbol { fill: fill.unwrap_or(none), stroke: stroke.unwrap_or(none), stroke_width: width, size: 0.0, marker: Marker::Circle }; - Converted { symbol, strokes: Vec::new(), rotation: None, fills: stack } + Converted { symbol, strokes: Vec::new(), rotation: None, by: SymbolBy::default(), fills: stack } } /// A gradient fill's (or a shapeburst fill's, `burst`) first colour and the rest of it: its two @@ -537,7 +592,7 @@ fn line(layers: &[(Node, Props)], reference: Option, layer: &str, report: & } None => hidden(), }; - Converted { symbol, strokes, rotation: None, fills: Vec::new() } + Converted { symbol, strokes, rotation: None, by: SymbolBy::default(), fills: Vec::new() } } /// A marker line (`hash` false) or hashed line as strokes of markers or hash marks along the line: @@ -793,7 +848,7 @@ fn marker(layers: &[(Node, Props)], reference: Option, still: bool, layer: && marks.len() <= 1 && marks.iter().all(|m| m.offset == 0.0 && m.markers.is_some_and(|k| k.offset_along == 0.0 && k.angle == 0.0)); let strokes = if alone { Vec::new() } else { marks.into_iter().map(LineStroke::clamped).collect() }; - Converted { symbol, strokes, rotation: None, fills: Vec::new() } + Converted { symbol, strokes, rotation: None, by: SymbolBy::default(), fills: Vec::new() } } /// A point marker layer's offset (`offset`, "x,y" in its unit: right and down) in points, its @@ -839,6 +894,61 @@ fn active_properties<'a, 'i>(node: Node<'a, 'i>) -> Vec<(&'a str, Node<'a, 'i>)> out } +/// A data-defined property's expression: a field's (`type` 2) quoted, or the expression's own +/// (`type` 3); `None` for a fixed value or text too long to read. +fn property_text(property: Node) -> Option { + let named = |name: &str| { + property.children().find(|c| c.has_tag_name("Option") && c.attribute("name") == Some(name)).and_then(|o| o.attribute("value")) + }; + let text = match named("type").map(str::trim) { + Some("2") => format!("\"{}\"", named("field")?.trim().replace('"', "\"\"")), + Some("3") => named("expression")?.trim().to_string(), + _ => return None, + }; + Some(text).filter(|t| !t.is_empty() && t != "\"\"" && t.len() <= rustgis_data::query::MAX_LEN - 32) +} + +/// Takes the data-defined property `name` of a symbol layer (its settings `p`) of a `kind` +/// symbol into `by` when RustGIS draws it by expression: a marker's size and angle, the fill and +/// outline colours and the outline's (a line's) width, sizes turned from the layer's unit into +/// points. False for one it doesn't. A second symbol layer's for the same keeps the first's (noted). +#[allow(clippy::too_many_arguments)] +fn by_expression( + kind: Option<&str>, + name: &str, + property: Node, + p: Option<&[(String, String)]>, + reference: Option, + by: &mut SymbolBy, + layer: &str, + report: &mut Report, +) -> bool { + let (marker, fill, line) = (!matches!(kind, Some("fill" | "line")), kind == Some("fill"), kind == Some("line")); + let sized = |key: &str, text: String, report: &mut Report| { + let unit = p.and_then(|p| prop(p, &format!("{key}_unit")).or(prop(p, SYMBOL_UNIT))); + let k = super::in_points(1.0, unit, reference, layer, report); + if (k - 1.0).abs() < 1e-9 || !k.is_finite() { text } else { format!("({text}) * {}", (k * 1e6).round() / 1e6) } + }; + let Some(text) = property_text(property) else { return false }; + let (slot, text) = match name { + "size" if marker => (&mut by.size, sized("size", text, report)), + "fillColor" if marker || fill => (&mut by.fill, text), + "outlineColor" => (&mut by.stroke, text), + "outlineWidth" if line => (&mut by.stroke_width, sized("line_width", text, report)), + "outlineWidth" => (&mut by.stroke_width, sized("outline_width", text, report)), + "angle" if marker => (&mut by.angle, text), + _ => return false, + }; + match slot { + Some(had) if *had != text => { + report.approximated(layer, "symbol layers with different data-defined settings, drawn with the first's") + } + Some(_) => {} + None => *slot = Some(text), + } + true +} + /// A data-defined angle that is a field's value (a field property, or the expression `"field"`, /// `- "field"`): the rotation it gives. `None` for any other expression. fn field_angle(property: Node) -> Option { diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 013b9d6626..77e485dfa0 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -1060,12 +1060,13 @@ fn marker_symbols_of_several_layers_carry_over_as_marks_turned_by_their_field() let Some(Renderer::Single(sym)) = &s.renderer else { panic!() }; assert_eq!(sym.marker, Marker::Star); - // An angle from any other expression is noted, and turns nothing. + // An angle from any other expression turns the markers by that expression. let other = qml.replace("", &format!("{}", dd(""A" * 2"))); let mut report = Report::default(); let s = read_style(&other, "Signs", &mut report).unwrap(); assert_eq!(s.marker_rotation, Some(None)); - assert!(report.notes.iter().any(|n| n.text.contains("data-defined")), "{:?}", report.notes); + assert_eq!(s.symbol_by.and_then(|b| b.angle).as_deref(), Some(r#""A" * 2"#)); + assert!(!report.notes.iter().any(|n| n.text.contains("data-defined")), "{:?}", report.notes); // Classes of one layer: an antenna that keeps still where a cliff turns by the field. The // antenna's single plain character becomes a mark that doesn't turn; the cliff's turns. @@ -1205,3 +1206,121 @@ fn gradient_and_shapeburst_fills_carry_over() { let (fills, _) = read(&burst.replace(r#""#, "")); assert!(matches!(fills[0].pattern, FillPattern::Shapeburst { distance: None, .. }), "{fills:?}"); } + +/// Data-defined size, colours, outline width and angle carry over as the layer's expressions: +/// a field's quoted, sizes in millimetres turned into points; an angle that is a field still +/// turns the markers by it, as before. +#[test] +fn data_defined_symbol_settings_carry_over_as_expressions() { + let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("testdata/qgis/generated/qml/datadefined-size-angle-color.qml"); + let text = std::fs::read_to_string(path).unwrap(); + let mut report = Report::default(); + let s = read_style(&text, "points", &mut report).unwrap(); + let by = s.symbol_by.clone().unwrap(); + assert_eq!(by.size.as_deref(), Some(r#"("value") * 3.779528"#)); + assert_eq!(by.fill.as_deref(), Some(r#"CASE WHEN "kind" = 'a' THEN '#ff0000' ELSE '#0000ff' END"#)); + assert_eq!(by.angle, None, "a field's angle turns by the field"); + assert_eq!(s.marker_rotation.clone().flatten().map(|r| r.field), Some("angle".into())); + assert!(!report.notes.iter().any(|n| n.text.contains("data-defined")), "{:?}", report.notes); + // Applied to a point layer with those fields, each reads and draws per feature. + let fields = ["value", "angle"].map(|f| rustgis_data::Field::new(f, rustgis_data::FieldType::Double)); + let mut ds = rustgis_data::Dataset::new("points", rustgis_data::GeometryType::Point, fields.to_vec()); + ds.fields.push(rustgis_data::Field::new("kind", rustgis_data::FieldType::Text)); + ds.push( + Some(rustgis_data::Geometry::Point(rustgis_geom::Coord::new(0.0, 0.0))), + vec![rustgis_data::Value::Float(2.0), rustgis_data::Value::Float(0.0), rustgis_data::Value::Text("a".into())], + ); + let mut layer = crate::Layer::new(1, ds); + s.apply(&mut layer); + let sym = layer.styler(None).symbol(0); + assert!((sym.size - 2.0 * 96.0 / 25.4).abs() < 1e-3 && sym.fill == Rgba::rgb(255, 0, 0), "{sym:?}"); + + // A line's colour and width; an outline width in points; what isn't drawn by expression is noted. + let dd = |props: &[(&str, &str)]| { + let one = |(name, expr): &(&str, &str)| { + format!( + r#""# + ) + }; + format!( + r#" + "#, + props.iter().map(one).collect::() + ) + }; + let line = format!( + r#" + {} + "#, + dd(&[("outlineWidth", "if(@map_scale < 4656581, 1.0, 0)"), ("outlineColor", "color_rgb(255, 0, 0)")]) + ); + let mut report = Report::default(); + let s = read_style(&line, "roads", &mut report).unwrap(); + let by = s.symbol_by.unwrap(); + assert_eq!(by.stroke_width.as_deref(), Some("(if(@map_scale < 4656581, 1.0, 0)) * 1.333333"), "{by:?}"); + assert_eq!(by.stroke.as_deref(), Some("color_rgb(255, 0, 0)")); + assert!(report.notes.is_empty(), "{:?}", report.notes); + // Classes: one sized by expression, one not; the other's drawn with the first's, said. A + // see-through symbol's expression colour is drawn opaque, said. + let marker = |name: &str, props: &str| { + format!( + r#""# + ) + }; + let classes = format!( + r#" + + {}{}"#, + marker("0", &dd(&[("size", ""v""), ("fillColor", "'red'")])), + marker("1", "") + ); + let mut report = Report::default(); + let s = read_style(&classes, "points", &mut report).unwrap(); + assert_eq!(s.symbol_by.unwrap().size.as_deref(), Some(r#"("v") * 3.779528"#)); + let said = |t: &str| report.notes.iter().any(|n| n.text.contains(t)); + assert!(said("different data-defined settings") && said("see-through symbol"), "{:?}", report.notes); + // A marker of two layers (the Training Manual's world places): a white disc sized by + // expression, a black dot sized in proportion on top. The marks scale with the top layer's + // size; their colours stay their own, the outline colour by expression is left out. + let layer_of = |color: &str, size: &str, props: &[(&str, &str)]| { + format!( + r#"{}"#, + dd(props) + ) + }; + let places = format!( + r#"{}{}"#, + layer_of( + "255,255,255,255", + "2.4", + &[ + ("outlineColor", "IF(pop_max > 5000000, color_rgb(255,0,0), color_rgb(0,0,0))"), + ("size", "scale_linear(pop_max, 7026, 35676000, 8, 18)") + ] + ), + layer_of("0,0,0,255", "0.5", &[("size", "0.208333*(scale_linear(pop_max, 7026, 35676000, 8, 18))")]) + ); + let mut report = Report::default(); + let s = read_style(&places, "places", &mut report).unwrap(); + let by = s.symbol_by.unwrap(); + // Turned into the largest layer's (the symbol's) size: 2.4 / 0.5 times the dot's. + assert_eq!(by.size.as_deref(), Some("((0.208333*(scale_linear(pop_max, 7026, 35676000, 8, 18))) * 3.779528) * 4.8")); + assert!(by.stroke.is_none(), "{by:?}"); + assert_eq!(s.line_strokes.map(|m| m.len()), Some(2)); + let said = |t: &str| report.notes.iter().any(|n| n.text.contains(t)); + // Both layers sized by expression scale together as QGIS scales them: nothing to say of that. + assert!(!said("scaled with its size") && said("colours and outline widths of a marker drawn as marks"), "{:?}", report.notes); + // A layer of a fixed size scales with the rest: said. + let fixed = places.replace(&dd(&[("size", "0.208333*(scale_linear(pop_max, 7026, 35676000, 8, 18))")]), ""); + let mut report = Report::default(); + read_style(&fixed, "places", &mut report).unwrap(); + assert!(report.notes.iter().any(|n| n.text.contains("scaled with its size")), "{:?}", report.notes); + assert!(!said("drawn with the first's"), "{:?}", report.notes); + + let dashed = line.replace("outlineColor", "customDash"); + let mut report = Report::default(); + let s = read_style(&dashed, "roads", &mut report).unwrap(); + assert!(s.symbol_by.unwrap().stroke.is_none()); + assert!(report.notes.iter().any(|n| n.text.contains("data-defined")), "{:?}", report.notes); +} diff --git a/crates/map/src/symbol_by.rs b/crates/map/src/symbol_by.rs new file mode 100644 index 0000000000..f9c779bf20 --- /dev/null +++ b/crates/map/src/symbol_by.rs @@ -0,0 +1,374 @@ +//! A layer's symbol set per feature by expressions ([`crate::Layer::symbol_by`]): its size, +//! fill and outline colour, outline width and marker angle, each from an expression in the +//! language of [`rustgis_data::query`] (`"pop" / 1e6 + 4`, `CASE WHEN … END`, +//! `scale_linear(…)`). The text is stored; it is compiled against the layer's fields once per +//! drawing ([`Layer::styler`]), so a project never holds a parsed tree. + +use crate::fills::FillLayer; +use crate::symbology::{LineStroke, Symbol}; +use crate::{Layer, Rgba}; +use rustgis_data::query::{self, Env, Expr}; +use rustgis_data::{Dataset, Value}; +use serde::{Deserialize, Serialize}; + +/// The largest marker size an expression gives, in points. +pub const MAX_SIZE: f32 = 400.0; +/// The widest outline an expression gives, in points. +pub const MAX_WIDTH: f32 = 100.0; + +/// Expressions setting a layer's symbol per feature; none set: the renderer's symbol alone. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +pub struct SymbolBy { + /// The marker's size in points. + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_text")] + pub size: Option, + /// The fill colour (a point's marker, a polygon's inside): `'#rrggbb'`, a CSS colour or + /// `'r,g,b[,a]'` as `color_rgb` gives it. + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_text")] + pub fill: Option, + /// The outline colour, a line's colour on a line layer. + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_text")] + pub stroke: Option, + /// The outline's width in points, a line's width on a line layer. + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_text")] + pub stroke_width: Option, + /// A point's marker turned by this angle in degrees clockwise, in place of + /// [`Layer::marker_rotation`]'s (where it gives none, that one's). + #[serde(default, skip_serializing_if = "Option::is_none", deserialize_with = "de_text")] + pub angle: Option, +} + +impl SymbolBy { + pub fn is_empty(&self) -> bool { + self.size.is_none() && self.fill.is_none() && self.stroke.is_none() && self.stroke_width.is_none() && self.angle.is_none() + } +} + +/// Reads one expression leniently: text up to [`query::MAX_LEN`], blank or anything else none. +fn de_text<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + Ok(match serde_json::Value::deserialize(d)? { + serde_json::Value::String(s) if !s.trim().is_empty() && s.len() <= query::MAX_LEN => Some(s), + _ => None, + }) +} + +/// Reads a layer's expressions leniently: a crafted file's that aren't are none, and the rest of +/// the layer still reads. +pub fn de_symbol_by<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + let v = serde_json::Value::deserialize(d)?; + Ok(serde_json::from_value(v).unwrap_or_default()) +} + +/// A layer's expressions compiled against its fields for one drawing. +#[derive(Clone, Debug)] +struct Compiled { + size: Option, + fill: Option, + stroke: Option, + stroke_width: Option, + angle: Option, + env: Env, + /// A point layer's: a marker sized 0 or less draws nothing. + points: bool, + /// The last text each colour expression gave and the colour it read as: most layers colour + /// many features alike, and the text needn't be read again for each. + seen: [std::cell::RefCell)>>; 2], +} + +impl Compiled { + /// None where nothing parses against the dataset (an expression naming a field since + /// removed draws as if it weren't set). + fn new(by: &SymbolBy, ds: &Dataset, env: Env, points: bool) -> Option { + let one = |t: &Option| t.as_deref().and_then(|t| query::parse(t, ds).ok()); + let c = Compiled { + size: one(&by.size), + fill: one(&by.fill), + stroke: one(&by.stroke), + stroke_width: one(&by.stroke_width), + angle: one(&by.angle), + env, + points, + seen: Default::default(), + }; + let any = c.size.is_some() || c.fill.is_some() || c.stroke.is_some() || c.stroke_width.is_some() || c.angle.is_some(); + any.then_some(c) + } + + fn number(&self, e: &Option, ds: &Dataset, row: usize) -> Option { + query::value(e.as_ref()?, ds, row, &self.env).as_f64().filter(|v| v.is_finite()) + } + + fn color(&self, e: &Option, slot: usize, ds: &Dataset, row: usize) -> Option { + let Value::Text(t) = query::value(e.as_ref()?, ds, row, &self.env) else { return None }; + let Some(seen) = self.seen.get(slot) else { return rustgis_data::color::parse_value(&t).map(Rgba) }; + let Ok(mut seen) = seen.try_borrow_mut() else { return rustgis_data::color::parse_value(&t).map(Rgba) }; + match &*seen { + Some((had, c)) if *had == t => *c, + _ => { + let c = rustgis_data::color::parse_value(&t).map(Rgba); + *seen = Some((t, c)); + c + } + } + } + + /// The symbol with what the expressions give for the row; a value that is null or isn't a + /// number (a colour) keeps the symbol's own. + fn apply(&self, ds: &Dataset, row: usize, mut sym: Symbol) -> Symbol { + if let Some(v) = self.number(&self.size, ds, row) { + sym.size = (v as f32).clamp(0.0, MAX_SIZE); + // As QGIS draws a marker of no size: not even its outline. + if self.points && sym.size == 0.0 { + let none = Rgba([0, 0, 0, 0]); + return Symbol { fill: none, stroke: none, stroke_width: 0.0, ..sym }; + } + } + if let Some(v) = self.number(&self.stroke_width, ds, row) { + sym.stroke_width = (v as f32).clamp(0.0, MAX_WIDTH); + } + if let Some(c) = self.color(&self.fill, 0, ds, row) { + sym.fill = c; + } + if let Some(c) = self.color(&self.stroke, 1, ds, row) { + sym.stroke = c; + } + sym + } + + /// The row's angle in degrees clockwise, none where the expression gives no number. + fn turn(&self, ds: &Dataset, row: usize) -> Option { + self.number(&self.angle, ds, row).map(|v| v.rem_euclid(360.0) as f32) + } +} + +/// A layer's per-row style for one drawing: [`Layer::symbol`], [`Layer::style`], +/// [`Layer::style_and_fills`] and [`Layer::marker_turn`] with its [`Layer::symbol_by`] +/// expressions applied (compiled once, at [`Layer::styler`]). +#[derive(Clone, Debug)] +pub struct Styler<'a> { + layer: &'a Layer, + by: Option, +} + +impl<'a> Styler<'a> { + pub(crate) fn new(layer: &'a Layer, map_scale: Option) -> Styler<'a> { + let by = if layer.graphics || layer.symbol_by.is_empty() { + None + } else { + let env = Env { map_scale: map_scale.filter(|s| s.is_finite() && *s > 0.0) }; + Compiled::new(&layer.symbol_by, &layer.dataset, env, layer.geometry_type() == rustgis_data::GeometryType::Point) + }; + Styler { layer, by } + } + + /// Whether no expression applies: every row draws as the layer's own methods give it. + pub fn is_plain(&self) -> bool { + self.by.is_none() + } + + fn apply(&self, row: usize, sym: Symbol) -> Symbol { + match &self.by { + Some(b) => b.apply(&self.layer.dataset, row, sym), + None => sym, + } + } + + pub fn symbol(&self, row: usize) -> Symbol { + self.apply(row, self.layer.symbol(row)) + } + + pub fn style(&self, row: usize) -> (Symbol, &'a [LineStroke]) { + let (sym, strokes) = self.layer.style(row); + (self.apply(row, sym), strokes) + } + + pub fn style_and_fills(&self, row: usize) -> (Symbol, &'a [LineStroke], &'a [FillLayer]) { + let (sym, strokes, fills) = self.layer.style_and_fills(row); + (self.apply(row, sym), strokes, fills) + } + + /// A point's marks (`strokes`, as [`Styler::style`] gives them) scaled with the size its + /// expression gives, against the symbol's own, as QGIS scales a marker of several layers: their + /// sizes and offsets. None at size 0. The marks as they are without a size expression. + pub fn marks(&self, row: usize, strokes: &'a [LineStroke]) -> std::borrow::Cow<'a, [LineStroke]> { + use std::borrow::Cow; + let Some(b) = self.by.as_ref().filter(|b| b.points && !strokes.is_empty()) else { return Cow::Borrowed(strokes) }; + let Some(size) = b.number(&b.size, &self.layer.dataset, row) else { return Cow::Borrowed(strokes) }; + // The size the marks are drawn for: a Proportional renderer's base symbol's (it sizes the + // symbol per feature, not the marks), else the feature's class's. + let base = match &self.layer.renderer { + crate::Renderer::Proportional { .. } => self.layer.renderer.base_symbol().size, + _ => self.layer.symbol(row).size, + }; + if base.is_nan() || base <= 0.0 { + return Cow::Borrowed(strokes); + } + let k = (size as f32).clamp(0.0, MAX_SIZE) / base; + if k == 0.0 { + return Cow::Owned(Vec::new()); + } + Cow::Owned( + strokes + .iter() + .map(|st| { + let mut st = *st; + st.offset *= k; + if let Some(m) = &mut st.markers { + m.size *= k; + m.offset_along *= k; + } + st.clamped() + }) + .collect(), + ) + } + + pub fn marker_turn(&self, row: usize) -> f32 { + match self.by.as_ref().and_then(|b| b.turn(&self.layer.dataset, row)) { + Some(a) => a, + None => self.layer.marker_turn(row), + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::symbology::MarkerRotation; + use rustgis_data::{Field, FieldType, Geometry, GeometryType}; + use rustgis_geom::Coord; + + fn points() -> Layer { + let fields = vec![Field::new("pop", FieldType::Double), Field::new("kind", FieldType::Text), Field::new("deg", FieldType::Double)]; + let mut l = Layer::new(1, Dataset::new("p", GeometryType::Point, fields)); + for (pop, kind, deg) in [(Value::Float(2e6), "a", 90.0), (Value::Null, "b", 450.0), (Value::Float(5e5), "c", -30.0)] { + l.dataset.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![pop, Value::Text(kind.into()), Value::Float(deg)]); + } + l + } + + #[test] + fn expressions_set_the_symbol_per_feature() { + let mut l = points(); + let base = l.symbol(0); + assert!(l.styler(None).is_plain()); + l.symbol_by = SymbolBy { + size: Some(r#""pop" / 1e5"#.into()), + fill: Some("CASE WHEN kind = 'a' THEN '#ff0000' WHEN kind = 'b' THEN color_rgba(0, 0, 255, 128) ELSE 'nocolour' END".into()), + stroke: Some("'green'".into()), + stroke_width: Some("@map_scale / 1000".into()), + angle: Some("deg".into()), + }; + let st = l.styler(Some(4000.0)); + assert!(!st.is_plain()); + let (a, b, c) = (st.symbol(0), st.symbol(1), st.symbol(2)); + assert_eq!((a.size, a.fill, a.stroke, a.stroke_width), (20.0, Rgba([255, 0, 0, 255]), Rgba([0, 128, 0, 255]), 4.0)); + // Null (no population) and what isn't a colour keep the symbol's own. + assert_eq!((b.size, b.fill), (base.size, Rgba([0, 0, 255, 128]))); + assert_eq!((c.size, c.fill), (5.0, base.fill)); + assert_eq!((st.marker_turn(0), st.marker_turn(1), st.marker_turn(2)), (90.0, 90.0, 330.0)); + // The styled symbol comes with the strokes the layer's own style gives. + assert_eq!(st.style(0).0, a); + // Without a map, @map_scale is null: the width is the symbol's. + assert_eq!(l.styler(None).symbol(0).stroke_width, base.stroke_width); + } + + #[test] + fn values_are_kept_in_range() { + let mut l = points(); + l.symbol_by = + SymbolBy { size: Some("pop".into()), stroke_width: Some("-5".into()), angle: Some("1 / 0".into()), ..Default::default() }; + let st = l.styler(None); + assert_eq!((st.symbol(0).size, st.symbol(0).stroke_width), (MAX_SIZE, 0.0)); + // A point sized 0 or less draws nothing, its outline neither. + let mut zero = points(); + zero.symbol_by.size = Some("pop - 1e6".into()); + let gone = zero.styler(None).symbol(2); + assert_eq!((gone.size, gone.fill.a(), gone.stroke.a(), gone.stroke_width), (0.0, 0, 0, 0.0)); + // No number from the angle: the field rotation's, or none. + assert_eq!(st.marker_turn(0), 0.0); + l.marker_rotation = Some(MarkerRotation { field: "deg".into(), counterclockwise: false }); + assert_eq!(l.styler(None).marker_turn(1), 90.0); + } + + #[test] + fn a_points_marks_scale_with_its_size() { + use crate::symbology::{LineMark, LineMarkers, Marker}; + let mut l = points(); + let base = l.symbol(0).size; + let mark = |size: f32, along: f32| LineStroke { + markers: Some(LineMarkers { mark: LineMark::Marker(Marker::Circle), size, offset_along: along, ..LineMarkers::default() }), + offset: 1.0, + ..LineStroke::default() + }; + l.line_strokes = vec![mark(10.0, 0.0), mark(2.0, 3.0)]; + // Without a size expression, the marks as they are. + assert!(matches!(l.styler(None).marks(0, &l.line_strokes), std::borrow::Cow::Borrowed(_))); + l.symbol_by.size = Some(format!("{} * 2", base)); + let st = l.styler(None); + let (_, strokes) = st.style(0); + let m = st.marks(0, strokes); + let sizes: Vec<_> = m.iter().map(|s| (s.markers.unwrap().size, s.markers.unwrap().offset_along, s.offset)).collect(); + assert_eq!(sizes, vec![(20.0, 0.0, 2.0), (4.0, 6.0, 2.0)]); + // Sized 0: none. + l.symbol_by.size = Some("0".into()); + assert!(l.styler(None).marks(0, &l.line_strokes).is_empty()); + // Proportional symbols size the symbol per feature, not the marks: they scale against the + // renderer's base size. + let base_sym = l.symbol(0); + l.renderer = crate::Renderer::Proportional { + field: "pop".into(), + base: Symbol { size: 10.0, ..base_sym }, + min_size: 5.0, + max_size: 40.0, + min: 0.0, + max: 2e6, + }; + l.symbol_by.size = Some("20".into()); + let st = l.styler(None); + assert_ne!(l.symbol(0).size, 10.0, "sized per feature"); + assert_eq!(st.marks(0, &l.line_strokes).first().and_then(|m| m.markers).map(|m| m.size), Some(20.0)); + } + + #[test] + fn what_no_longer_parses_draws_as_unset() { + let mut l = points(); + let base = l.symbol(0); + l.symbol_by = SymbolBy { size: Some("gone * 2".into()), fill: Some("'red' ||".into()), ..Default::default() }; + let st = l.styler(Some(1e4)); + assert!(st.is_plain()); + assert_eq!(st.symbol(0), base); + // A graphics layer's features carry their own style. + l.symbol_by.size = Some("pop".into()); + l.graphics = true; + assert!(l.styler(None).is_plain()); + } + + #[test] + fn kept_in_a_project_and_read_leniently() { + let mut l = points(); + // None isn't written: an older RustGIS reads the layer as before. + assert!(serde_json::to_value(&l).unwrap().get("symbol_by").is_none()); + l.symbol_by = SymbolBy { fill: Some("'#00ff00'".into()), angle: Some("deg + 5".into()), ..Default::default() }; + let v = serde_json::to_value(&l).unwrap(); + assert_eq!(v["symbol_by"], serde_json::json!({"fill": "'#00ff00'", "angle": "deg + 5"})); + let back: Layer = serde_json::from_value(v.clone()).unwrap(); + assert_eq!(back.symbol_by, l.symbol_by); + for junk in [ + serde_json::json!(5), + serde_json::json!("size"), + serde_json::json!({"fill": 3, "angle": ["deg"]}), + serde_json::json!({"size": "", "fill": "x".repeat(query::MAX_LEN + 1)}), + ] { + let mut v = v.clone(); + v["symbol_by"] = junk.clone(); + let read: Layer = serde_json::from_value(v).unwrap(); + assert!(read.symbol_by.is_empty(), "{junk}"); + } + // One bad key leaves the others. + let mut v = v.clone(); + v["symbol_by"] = serde_json::json!({"size": 7, "stroke": "'red'"}); + let read: Layer = serde_json::from_value(v).unwrap(); + assert_eq!(read.symbol_by, SymbolBy { stroke: Some("'red'".into()), ..Default::default() }); + } +} diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 2e1080f4cf..a5a2d63a74 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2269,6 +2269,7 @@ pub fn gpu_may_turn(map: &Map, view: &View) -> bool { && !l.has_strokes() && !l.has_fills() && l.marker_rotation.is_none() + && l.symbol_by.is_empty() && (l.extrusion.is_none() || view.camera.pitch != 0.0) && !(view.camera.pitch != 0.0 && l.renderer.has_char_markers() && stands_up(map, l)) }) @@ -2370,6 +2371,7 @@ pub fn extruded_shapes(map: &mut Map, view: &View) -> Vec { let rows = layer.drawn_rows(scale); layer.thinned_in(&flat, &key, tol); let layer: &rustgis_map::Layer = layer; + let styler = layer.styler(Some(scale)); let extents = layer.projected_extents(); for (row, g) in layer.thinned_cache(tol).iter().enumerate() { let Some(Geometry::Polygon(polys)) = g else { continue }; @@ -2387,7 +2389,7 @@ pub fn extruded_shapes(map: &mut Map, view: &View) -> Vec { } let roof = mesh::fill_polygon(polys, [origin.x, origin.y], [0.0; 4], view.camera.res * 0.5, mesh::NO_LIMIT); let Ok(Some((verts, indices))) = roof else { continue }; - let sym = layer.symbol(row); + let sym = styler.symbol(row); let pts: Vec = polys.iter().filter_map(|p| p.first()).flatten().copied().filter(|c| c.is_finite()).collect(); let n = pts.len().max(1) as f64; let center = Coord::new(pts.iter().map(|c| c.x).sum::() / n, pts.iter().map(|c| c.y).sum::() / n); @@ -2519,6 +2521,7 @@ fn stands_up(map: &Map, layer: &rustgis_map::Layer) -> bool { // Marks and turned markers stay on the ground, drawn as the flat map draws them. && !layer.has_strokes() && layer.marker_rotation.is_none() + && layer.symbol_by.angle.is_none() && rows.is_some_and(|n| n <= MAX_UPRIGHT_POINTS as u64) } @@ -2621,6 +2624,7 @@ pub fn upright_markers(map: &mut Map, view: &View, margin: f64) -> Vec = Vec::new(); for (row, g) in layer.projected_cache().iter().enumerate() { if rows.get(row) != Some(&true) { @@ -2638,7 +2642,7 @@ pub fn upright_markers(map: &mut Map, view: &View, margin: f64) -> Vec> = layer.projected_cache().iter().map(Option::as_ref).collect(); - effects::extrude_tilted(pm, view, &layer.dataset, &geoms, &rows, &x, |c| flat.ground_per_unit(c) * body, fog, |r| layer.symbol(r)); + effects::extrude_tilted(pm, view, &layer.dataset, &geoms, &rows, &x, |c| flat.ground_per_unit(c) * body, fog, |r| styler.symbol(r)); } } @@ -3275,6 +3280,8 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac } // Everything below only reads the layer: borrow rather than copy its data each frame. let layer: &rustgis_map::Layer = layer; + // Its symbol by expression, compiled once for the drawing (none: the layer's own). + let styler = layer.styler(Some(scale)); let label_row = |row: usize| if complete_source { layer.dataset.features.get(row).map_or(row, |f| f.id as usize) } else { row }; let (labels, selection, ds_ptr) = (&layer.labels, &layer.selection, &layer.dataset); // The globe draws the lon/lat geometry itself; the flat map its Web Mercator copy. @@ -3329,6 +3336,8 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac && !layer.has_strokes() && !layer.has_fills() && layer.marker_rotation.is_none() + // Symbols by expression are styled per feature on the CPU. + && layer.symbol_by.is_empty() && !upright.contains(&layer.id); // Lyon refuses degenerate geometry tiny-skia draws fine, a layer too dense to mesh // (`MAX_LAYER_VERTICES`) is quicker splatted, and zoomed in far, features reaching too @@ -3382,9 +3391,9 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac } else if let Some(x) = extrude.filter(|_| !matches!(labels_to, Labels::Shared)) { let px_per_m = view.pixels_per_point / (map_ground_res(view, &flat) * body); if let Some(spool) = &mut extrusions { - spool.add(ctx, ds_ptr, &geoms, &rows, x, px_per_m, |r| layer.symbol(r))?; + spool.add(ctx, ds_ptr, &geoms, &rows, x, px_per_m, |r| styler.symbol(r))?; } else { - effects::extrude(dest, ctx, ds_ptr, &geoms, &rows, x, px_per_m, |r| layer.symbol(r)); + effects::extrude(dest, ctx, ds_ptr, &geoms, &rows, x, px_per_m, |r| styler.symbol(r)); } } else { let mut stroke_paths = stroke_paths::Paths::default(); @@ -3402,12 +3411,13 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac if globe.is_some() || !matches!(g, Geometry::Point(_) | Geometry::MultiPoint(_)) { return false; } - let (sym, strokes) = layer.style(row); - if strokes.is_empty() { + let (sym, strokes) = styler.style(row); + let marks = styler.marks(row, strokes); + if marks.is_empty() { return false; } // In the layer's pixels (`ctx` is scaled by its size factor). - let r = f64::from(point_marks::reach(&sym, strokes) * ctx.ppp) * map_per_px; + let r = f64::from(point_marks::reach(&sym, &marks) * ctx.ppp) * map_per_px; Extent::new(e.min_x - r, e.min_y - r, e.max_x + r, e.max_y + r).intersects(&ctx.cull) }; if rows.get(row) != Some(&true) || !(visible(&e) || marked_in()) { @@ -3429,9 +3439,9 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac // polygon's stacked fills too (none in wireframe, which draws outlines only), // the feature classed once for all. let (sym, strokes, fills) = if has_fills && !ctx.wireframe && matches!(g, Geometry::Polygon(_)) { - layer.style_and_fills(row) + styler.style_and_fills(row) } else { - let (sym, strokes) = layer.style(row); + let (sym, strokes) = styler.style(row); (sym, strokes, &[] as &[rustgis_map::fills::FillLayer]) }; // A feature under a pixel across: blend its coverage into the pixels it touches @@ -3448,12 +3458,17 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac { continue; } - // A point's marks, or its marker turned by a field. - let turn = layer.marker_turn(row); + // A point's marks (sized with an expression's size), or its marker turned by a + // field or an expression. + let turn = styler.marker_turn(row); + let marks = match g { + Geometry::Point(_) | Geometry::MultiPoint(_) => styler.marks(row, strokes), + _ => std::borrow::Cow::Borrowed(strokes), + }; match g { - Geometry::Point(c) if !point_marks::plain(strokes, turn) => ctx.marks(dest, *c, &sym, strokes, turn, None), - Geometry::MultiPoint(v) if !point_marks::plain(strokes, turn) => { - v.iter().for_each(|c| ctx.marks(dest, *c, &sym, strokes, turn, None)) + Geometry::Point(c) if !point_marks::plain(&marks, turn) => ctx.marks(dest, *c, &sym, &marks, turn, None), + Geometry::MultiPoint(v) if !point_marks::plain(&marks, turn) => { + v.iter().for_each(|c| ctx.marks(dest, *c, &sym, &marks, turn, None)) } Geometry::Line(parts) if !strokes.is_empty() && levels => stacked.push((parts, sym, strokes)), Geometry::Line(parts) if !strokes.is_empty() => stroke_paths.draw(ctx, dest, parts, &sym, strokes), @@ -3503,13 +3518,13 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac // draw over it (the CPU path draws highlights over the layer). if complete_source { let rank = ds_ptr.features.get(*row).and_then(|f| selected_order.get(&f.id)).copied().unwrap_or(usize::MAX); - let (symbol, strokes) = layer.style(*row); - highlights.push((rank, (**g).clone(), symbol, strokes.to_vec(), layer.marker_turn(*row))); - } else if gpu_done && mesh::collect_highlight(&mut cmds, g, &layer.symbol(*row), ctx.ppp, map_per_px).is_ok() { + let (symbol, strokes) = styler.style(*row); + highlights.push((rank, (**g).clone(), symbol, styler.marks(*row, strokes).to_vec(), styler.marker_turn(*row))); + } else if gpu_done && mesh::collect_highlight(&mut cmds, g, &styler.symbol(*row), ctx.ppp, map_per_px).is_ok() { // highlight tessellated into the scene, right after its layer } else { - let (symbol, strokes) = layer.style(*row); - ctx.highlight(&mut pm, g, &symbol, strokes, layer.marker_turn(*row)); + let (symbol, strokes) = styler.style(*row); + ctx.highlight(&mut pm, g, &symbol, &styler.marks(*row, strokes), styler.marker_turn(*row)); cpu_dirty = true; } } @@ -3605,7 +3620,7 @@ fn render_frame(map: &mut Map, view: &View, full_res_rasters: bool, backend: Bac // A line's longest part on the screen, for the classes placed along it: worked // out once (its path each way too), for the first that asks. let mut screen_line: Option> = None; - let marker = if is_point { layer.symbol(row).size } else { 0.0 }; + let marker = if is_point { styler.symbol(row).size } else { 0.0 }; // Bigger polygons get priority. let area = match g { Geometry::Polygon(_) => { @@ -7399,6 +7414,37 @@ mod tests { assert!(!cmd_kinds(&scene).contains(&"points"), "turned alone, too"); } + #[test] + fn a_marker_sized_and_coloured_by_expression_draws_on_the_cpu() { + use rustgis_map::symbol_by::SymbolBy; + // One point at the centre of a 200 px view, 40 in field "a". + let mut m = Map::new("Map"); + m.basemap = rustgis_map::Basemap::Blank; + let mut d = Dataset::new("p", GeometryType::Point, vec![rustgis_data::Field::new("a", rustgis_data::FieldType::Double)]); + d.push(Some(Geometry::Point(Coord::new(0.0, 0.0))), vec![rustgis_data::Value::Float(40.0)]); + let id = m.add_dataset(d); + let camera = Camera { center: lonlat_to_merc(Coord::new(0.0, 0.0)), res: 1500.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 200.0, height: 200.0, pixels_per_point: 1.0, camera, sky: false }; + let is_green = |r: &Rendered, x: u32, y: u32| r.pixmap.pixel(x, y).is_some_and(|p| (p.red(), p.green(), p.blue()) == (0, 255, 0)); + let r = render(&mut m, &view).unwrap(); + assert!(!is_green(&r, 115, 100), "a 7 pt marker"); + let scale = m.ground_res_at(&camera) / rustgis_geom::PIXEL_M; + m.layer_mut(id).unwrap().symbol_by = SymbolBy { + size: Some("a".into()), + fill: Some(format!("CASE WHEN @map_scale BETWEEN {} AND {} THEN '#00ff00' END", scale * 0.9, scale * 1.1)), + ..Default::default() + }; + let r = render(&mut m, &view).unwrap(); + assert!(is_green(&r, 115, 100) && is_green(&r, 100, 85), "40 pt across, green at this scale"); + // Zoomed out the fill is the symbol's own. + let out = View { camera: Camera { res: camera.res * 4.0, ..camera }, ..view }; + let r = render(&mut m, &out).unwrap(); + assert!(!is_green(&r, 110, 100) && r.pixmap.pixel(110, 100).is_some_and(|p| p.alpha() == 255), "still 40 pt, not green"); + let Some(RenderOutput::Gpu(scene)) = render_backend(&mut m, &view, Backend::Gpu) else { panic!("gpu scene") }; + let kinds = cmd_kinds(&scene); + assert!(kinds.contains(&"image") && !kinds.contains(&"points"), "{kinds:?}"); + } + #[test] fn a_character_marker_draws_its_character_where_qgis_does_and_on_the_cpu() { use ab_glyph::Font; diff --git a/crates/tiles/src/style.rs b/crates/tiles/src/style.rs index 9b21739bf2..6b9f4581a2 100644 --- a/crates/tiles/src/style.rs +++ b/crates/tiles/src/style.rs @@ -9,6 +9,10 @@ use serde_json::{Map, Value as Json}; use std::cmp::Ordering; use std::collections::HashMap; +/// Parses a CSS color (moved to [`rustgis_data::color::parse`], which the expression language shares). +pub use rustgis_data::color::parse as parse_color; +use rustgis_data::color::unit_u8; + /// Straight (not premultiplied) RGBA. pub type Rgba = [u8; 4]; @@ -27,115 +31,6 @@ const MAX_DASHES: usize = 64; // Colors // --------------------------------------------------------------------------------------------------------------- -/// Parses a CSS color: `#rgb`, `#rgba`, `#rrggbb`, `#rrggbbaa`, `rgb[a]()`, `hsl[a]()` (comma or space syntax, -/// `/ alpha`, `%` alpha), `transparent` and the 148 CSS named colors. Case-insensitive. -pub fn parse_color(s: &str) -> Option { - let s = s.trim(); - if s.is_empty() || s.len() > 128 { - return None; - } - let lower = s.to_ascii_lowercase(); - if let Some(hex) = lower.strip_prefix('#') { - return parse_hex(hex); - } - if let Some((name, rest)) = lower.split_once('(') { - let inner = rest.trim_end().strip_suffix(')')?; - let parts: Vec<&str> = inner.split(|c: char| c == ',' || c == '/' || c.is_whitespace()).filter(|p| !p.is_empty()).collect(); - if !(3..=4).contains(&parts.len()) { - return None; - } - let alpha = match parts.get(3) { - Some(a) => alpha_u8(a)?, - None => 255, - }; - let (a, b, c) = (parts.first()?, parts.get(1)?, parts.get(2)?); - return match name.trim() { - "rgb" | "rgba" => Some([channel(a)?, channel(b)?, channel(c)?, alpha]), - "hsl" | "hsla" => { - let [r, g, b] = hsl_to_rgb(hue(a)?, pct(b)?, pct(c)?); - Some([r, g, b, alpha]) - } - _ => None, - }; - } - if lower == "transparent" { - return Some([0, 0, 0, 0]); - } - let i = NAMED_COLORS.binary_search_by(|(n, _)| (*n).cmp(lower.as_str())).ok()?; - let [_, r, g, b] = NAMED_COLORS.get(i)?.1.to_be_bytes(); - Some([r, g, b, 255]) -} - -fn parse_hex(h: &str) -> Option { - if !h.bytes().all(|b| b.is_ascii_hexdigit()) { - return None; - } - let digit = |i: usize, n: usize| h.get(i..i + n).and_then(|d| u8::from_str_radix(d, 16).ok()); - let mut c = [255u8; 4]; - match h.len() { - 3 | 4 => { - for (i, slot) in c.iter_mut().enumerate().take(h.len()) { - *slot = digit(i, 1)? * 17; - } - } - 6 | 8 => { - for (i, slot) in c.iter_mut().enumerate().take(h.len() / 2) { - *slot = digit(i * 2, 2)?; - } - } - _ => return None, - } - Some(c) -} - -fn css_num(s: &str) -> Option { - s.parse::().ok().filter(|v| v.is_finite()) -} - -fn unit_u8(v: f64) -> u8 { - (v * 255.0).clamp(0.0, 255.0).round() as u8 -} - -fn channel(s: &str) -> Option { - let v = match s.strip_suffix('%') { - Some(p) => css_num(p)? / 100.0, - None => css_num(s)? / 255.0, - }; - Some(unit_u8(v)) -} - -fn alpha_u8(s: &str) -> Option { - let v = match s.strip_suffix('%') { - Some(p) => css_num(p)? / 100.0, - None => css_num(s)?, - }; - Some(unit_u8(v)) -} - -fn hue(s: &str) -> Option { - Some(css_num(s.strip_suffix("deg").unwrap_or(s))?.rem_euclid(360.0)) -} - -fn pct(s: &str) -> Option { - Some((css_num(s.strip_suffix('%').unwrap_or(s))? / 100.0).clamp(0.0, 1.0)) -} - -fn hsl_to_rgb(h: f64, s: f64, l: f64) -> [u8; 3] { - let c = (1.0 - (2.0 * l - 1.0).abs()) * s; - let hp = h / 60.0; - let x = c * (1.0 - (hp % 2.0 - 1.0).abs()); - let (r, g, b) = match hp as u32 { - 0 => (c, x, 0.0), - 1 => (x, c, 0.0), - 2 => (0.0, c, x), - 3 => (0.0, x, c), - 4 => (x, 0.0, c), - _ => (c, 0.0, x), - }; - let m = l - c / 2.0; - [unit_u8(r + m), unit_u8(g + m), unit_u8(b + m)] -} - /// Interpolates in premultiplied space so fades to/from `transparent` don't darken. fn lerp_color(p: Rgba, q: Rgba, t: f64) -> Rgba { let pm = |[r, g, b, a]: Rgba| { @@ -154,42 +49,6 @@ fn lerp_color(p: Rgba, q: Rgba, t: f64) -> Rgba { [c(r), c(g), c(b), unit_u8(a)] } -/// CSS named colors, sorted by name, as 0xRRGGBB. -#[rustfmt::skip] -static NAMED_COLORS: [(&str, u32); 148] = [ - ("aliceblue", 0xf0f8ff), ("antiquewhite", 0xfaebd7), ("aqua", 0x00ffff), ("aquamarine", 0x7fffd4), ("azure", 0xf0ffff), - ("beige", 0xf5f5dc), ("bisque", 0xffe4c4), ("black", 0x000000), ("blanchedalmond", 0xffebcd), ("blue", 0x0000ff), - ("blueviolet", 0x8a2be2), ("brown", 0xa52a2a), ("burlywood", 0xdeb887), ("cadetblue", 0x5f9ea0), ("chartreuse", 0x7fff00), - ("chocolate", 0xd2691e), ("coral", 0xff7f50), ("cornflowerblue", 0x6495ed), ("cornsilk", 0xfff8dc), ("crimson", 0xdc143c), - ("cyan", 0x00ffff), ("darkblue", 0x00008b), ("darkcyan", 0x008b8b), ("darkgoldenrod", 0xb8860b), ("darkgray", 0xa9a9a9), - ("darkgreen", 0x006400), ("darkgrey", 0xa9a9a9), ("darkkhaki", 0xbdb76b), ("darkmagenta", 0x8b008b), ("darkolivegreen", 0x556b2f), - ("darkorange", 0xff8c00), ("darkorchid", 0x9932cc), ("darkred", 0x8b0000), ("darksalmon", 0xe9967a), ("darkseagreen", 0x8fbc8f), - ("darkslateblue", 0x483d8b), ("darkslategray", 0x2f4f4f), ("darkslategrey", 0x2f4f4f), ("darkturquoise", 0x00ced1), - ("darkviolet", 0x9400d3), ("deeppink", 0xff1493), ("deepskyblue", 0x00bfff), ("dimgray", 0x696969), ("dimgrey", 0x696969), - ("dodgerblue", 0x1e90ff), ("firebrick", 0xb22222), ("floralwhite", 0xfffaf0), ("forestgreen", 0x228b22), ("fuchsia", 0xff00ff), - ("gainsboro", 0xdcdcdc), ("ghostwhite", 0xf8f8ff), ("gold", 0xffd700), ("goldenrod", 0xdaa520), ("gray", 0x808080), - ("green", 0x008000), ("greenyellow", 0xadff2f), ("grey", 0x808080), ("honeydew", 0xf0fff0), ("hotpink", 0xff69b4), - ("indianred", 0xcd5c5c), ("indigo", 0x4b0082), ("ivory", 0xfffff0), ("khaki", 0xf0e68c), ("lavender", 0xe6e6fa), - ("lavenderblush", 0xfff0f5), ("lawngreen", 0x7cfc00), ("lemonchiffon", 0xfffacd), ("lightblue", 0xadd8e6), - ("lightcoral", 0xf08080), ("lightcyan", 0xe0ffff), ("lightgoldenrodyellow", 0xfafad2), ("lightgray", 0xd3d3d3), - ("lightgreen", 0x90ee90), ("lightgrey", 0xd3d3d3), ("lightpink", 0xffb6c1), ("lightsalmon", 0xffa07a), ("lightseagreen", 0x20b2aa), - ("lightskyblue", 0x87cefa), ("lightslategray", 0x778899), ("lightslategrey", 0x778899), ("lightsteelblue", 0xb0c4de), - ("lightyellow", 0xffffe0), ("lime", 0x00ff00), ("limegreen", 0x32cd32), ("linen", 0xfaf0e6), ("magenta", 0xff00ff), - ("maroon", 0x800000), ("mediumaquamarine", 0x66cdaa), ("mediumblue", 0x0000cd), ("mediumorchid", 0xba55d3), - ("mediumpurple", 0x9370db), ("mediumseagreen", 0x3cb371), ("mediumslateblue", 0x7b68ee), ("mediumspringgreen", 0x00fa9a), - ("mediumturquoise", 0x48d1cc), ("mediumvioletred", 0xc71585), ("midnightblue", 0x191970), ("mintcream", 0xf5fffa), - ("mistyrose", 0xffe4e1), ("moccasin", 0xffe4b5), ("navajowhite", 0xffdead), ("navy", 0x000080), ("oldlace", 0xfdf5e6), - ("olive", 0x808000), ("olivedrab", 0x6b8e23), ("orange", 0xffa500), ("orangered", 0xff4500), ("orchid", 0xda70d6), - ("palegoldenrod", 0xeee8aa), ("palegreen", 0x98fb98), ("paleturquoise", 0xafeeee), ("palevioletred", 0xdb7093), - ("papayawhip", 0xffefd5), ("peachpuff", 0xffdab9), ("peru", 0xcd853f), ("pink", 0xffc0cb), ("plum", 0xdda0dd), - ("powderblue", 0xb0e0e6), ("purple", 0x800080), ("rebeccapurple", 0x663399), ("red", 0xff0000), ("rosybrown", 0xbc8f8f), - ("royalblue", 0x4169e1), ("saddlebrown", 0x8b4513), ("salmon", 0xfa8072), ("sandybrown", 0xf4a460), ("seagreen", 0x2e8b57), - ("seashell", 0xfff5ee), ("sienna", 0xa0522d), ("silver", 0xc0c0c0), ("skyblue", 0x87ceeb), ("slateblue", 0x6a5acd), - ("slategray", 0x708090), ("slategrey", 0x708090), ("snow", 0xfffafa), ("springgreen", 0x00ff7f), ("steelblue", 0x4682b4), - ("tan", 0xd2b48c), ("teal", 0x008080), ("thistle", 0xd8bfd8), ("tomato", 0xff6347), ("turquoise", 0x40e0d0), ("violet", 0xee82ee), - ("wheat", 0xf5deb3), ("white", 0xffffff), ("whitesmoke", 0xf5f5f5), ("yellow", 0xffff00), ("yellowgreen", 0x9acd32), -]; - // --------------------------------------------------------------------------------------------------------------- // Values and feature context // --------------------------------------------------------------------------------------------------------------- @@ -1703,35 +1562,6 @@ mod tests { Val::Str(v.into()) } - #[test] - fn colors() { - assert_eq!(parse_color("#f00"), Some([255, 0, 0, 255])); - assert_eq!(parse_color("#F008"), Some([255, 0, 0, 136])); - assert_eq!(parse_color("#12ab3C"), Some([0x12, 0xab, 0x3c, 255])); - assert_eq!(parse_color("#12ab3c80"), Some([0x12, 0xab, 0x3c, 0x80])); - assert_eq!(parse_color("#12ab3"), None); - assert_eq!(parse_color("#ggg"), None); - assert_eq!(parse_color("rgb(255, 128, 0)"), Some([255, 128, 0, 255])); - assert_eq!(parse_color("rgba( 10 , 20 , 30 , 0.5 )"), Some([10, 20, 30, 128])); - assert_eq!(parse_color("rgba(10,20,30,50%)"), Some([10, 20, 30, 128])); - assert_eq!(parse_color("rgb(10 20 30 / 0.25)"), Some([10, 20, 30, 64])); - assert_eq!(parse_color("rgb(100%, 0%, 50%)"), Some([255, 0, 128, 255])); - assert_eq!(parse_color("hsl(0, 100%, 50%)"), Some([255, 0, 0, 255])); - assert_eq!(parse_color("hsl(120,100%,25%)"), Some([0, 128, 0, 255])); - assert_eq!(parse_color("hsla(240, 100%, 50%, 0.5)"), Some([0, 0, 255, 128])); - assert_eq!(parse_color("hsl(240deg 100% 50% / 50%)"), Some([0, 0, 255, 128])); - assert_eq!(parse_color("hsla(0,3%,85%,0.84)"), Some([218, 216, 216, 214])); - assert_eq!(parse_color("Red"), Some([255, 0, 0, 255])); - assert_eq!(parse_color("rebeccapurple"), Some([0x66, 0x33, 0x99, 255])); - assert_eq!(parse_color("yellowgreen"), Some([0x9a, 0xcd, 0x32, 255])); - assert_eq!(parse_color(" transparent "), Some([0, 0, 0, 0])); - for bad in ["", "rgb(1,2)", "rgb(1,2,3,4,5)", "foo(1,2,3)", "rgb(a,b,c)", "nocolor", "rgb(1,2,3", "#"] { - assert_eq!(parse_color(bad), None, "{bad}"); - } - assert!(NAMED_COLORS.windows(2).all(|w| w[0].0 < w[1].0), "table sorted"); - assert!(NAMED_COLORS.iter().all(|(n, _)| parse_color(n).is_some())); - } - #[test] fn lookups_and_comparisons() { let p = props(&[("name", s("Main St")), ("rank", n(3.0)), ("oneway", Value::Bool(true)), ("name:latin", s("Roma"))]); diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 291d0d68b0..90c2950422 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -4025,6 +4025,10 @@ fn symbology(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) { ui.add_space(8.0); crate::fill_editor::fills_editor(app, ui, &l, t); } + if !l.graphics { + ui.add_space(8.0); + symbol_by_editor(app, ui, &l, t); + } ui.add_space(10.0); ui.separator(); ui.label(egui::RichText::new(tl!("Layer")).size(11.5).color(t.text_dim)); @@ -4917,6 +4921,108 @@ fn marker_rotation_row(app: &mut RustGisApp, ui: &mut Ui, l: &rustgis_engine::ma }); } +/// The By Expression section: the symbol's size, colors, outline width and (on points) angle per +/// feature, each from an expression (`layer.symbolBy`). An expression applies when its box loses +/// focus; one that doesn't read shows why as it is typed, and stays in its box unapplied until +/// it is fixed or Escape drops it. +fn symbol_by_editor(app: &mut RustGisApp, ui: &mut Ui, l: &rustgis_engine::map::Layer, t: &Tokens) { + let g = l.geometry_type(); + let by = &l.symbol_by; + let mut rows: Vec<(&str, &str, &Option)> = Vec::new(); + match g { + GeometryType::Point => rows.extend([ + ("size", tl!("Size"), &by.size), + ("fill", tl!("Fill"), &by.fill), + ("stroke", tl!("Outline"), &by.stroke), + ("strokeWidth", tl!("Outline width"), &by.stroke_width), + ("angle", tl!("Angle"), &by.angle), + ]), + GeometryType::Polyline => rows.extend([("stroke", tl!("Color"), &by.stroke), ("strokeWidth", tl!("Width"), &by.stroke_width)]), + _ => rows.extend([ + ("fill", tl!("Fill"), &by.fill), + ("stroke", tl!("Outline"), &by.stroke), + ("strokeWidth", tl!("Outline width"), &by.stroke_width), + ]), + } + egui::Frame::NONE.fill(t.pane_header).corner_radius(CornerRadius::same(8)).inner_margin(egui::Margin::same(10)).show(ui, |ui| { + ui.set_width(ui.available_width()); + ui.label(egui::RichText::new(tl!("By Expression")).font(semibold(12.5))); + ui.label( + egui::RichText::new(tl!( + "Set per feature from an expression, e.g. \"pop\" / 1e5 or CASE WHEN … END; colors as '#RRGGBB'. Empty: the symbol's own." + )) + .small() + .weak(), + ); + for (key, label, cur) in rows { + let cur = cur.clone().unwrap_or_default(); + let id = egui::Id::unique(("symbol_by", l.id, key)); + let (typing, failed) = (id.with("typing"), id.with("failed")); + let focused = ui.memory(|m| m.has_focus(id)); + // Each kept with the expression it was typed over: one set meanwhile (by undo or a + // command) drops it. Typing left over from a box that stopped being drawn while + // focused is dropped too. + let over = |d: &mut egui::util::IdTypeMap, key: egui::Id| { + let v = d.get_temp::<(String, String)>(key); + if v.as_ref().is_some_and(|(was, _)| *was != cur) { + d.remove::<(String, String)>(key); + } + v.filter(|(was, _)| *was == cur).map(|(_, text)| text) + }; + if !focused { + ui.data_mut(|d| d.remove::<(String, String)>(typing)); + } + // Text that didn't read, kept until it is changed or dropped. + let kept = ui.data_mut(|d| over(d, failed)); + let mut buf = match focused { + true => ui.data_mut(|d| over(d, typing)).or_else(|| kept.clone()).unwrap_or_else(|| cur.clone()), + false => kept.clone().unwrap_or_else(|| cur.clone()), + }; + let r = ui + .horizontal(|ui| { + let input_label = ui + .allocate_ui_with_layout(egui::vec2(96.0, 18.0), egui::Layout::left_to_right(egui::Align::Center), |ui| { + ui.set_min_width(96.0); + ui.label(label) + }) + .inner; + ui.add( + egui::TextEdit::singleline(&mut buf) + .id(id) + .hint_text(tl!("None")) + .char_limit(rustgis_engine::data::query::MAX_LEN) + .font(egui::TextStyle::Monospace) + .desired_width(f32::INFINITY), + ) + .labelled_by(input_label.id) + }) + .inner; + // Checked here, as Calculate Field checks it, only while it differs from what is set. + let text = buf.trim(); + let error = + (text != cur.trim() && !text.is_empty()).then(|| rustgis_engine::data::query::parse(text, &l.dataset).err()).flatten(); + if r.lost_focus() { + ui.data_mut(|d| d.remove::<(String, String)>(typing)); + if ui.input(|i| i.key_pressed(egui::Key::Escape)) { + ui.data_mut(|d| d.remove::<(String, String)>(failed)); + } else if error.is_some() { + ui.data_mut(|d| d.insert_temp(failed, (cur.clone(), buf.clone()))); + } else { + ui.data_mut(|d| d.remove::<(String, String)>(failed)); + if text != cur.trim() { + let _ = app.run("layer.symbolBy", json!({ key: text })); + } + } + } else if r.has_focus() { + ui.data_mut(|d| d.insert_temp(typing, (cur.clone(), buf.clone()))); + } + if let Some(e) = error.filter(|_| focused || r.lost_focus() || kept.is_some()) { + ui.label(egui::RichText::new(crate::i18n::fmt("Invalid: {error}", &[("error", &e)])).small().color(t.red)); + } + } + }); +} + /// The Strokes section of a line layer's symbology: strokes stacked in one symbol, each with /// its own colour, width, sideways offset, cap and join. Listed top first, as they are seen. A /// layer with classes can stack strokes for one class of its own, picked at the top. A point diff --git a/docs/comparison/geolibre.md b/docs/comparison/geolibre.md index cfc7646ee0..a568a2b335 100644 --- a/docs/comparison/geolibre.md +++ b/docs/comparison/geolibre.md @@ -66,7 +66,8 @@ differences in the short answer, in platform, technology and focus, are the ones clustering, diagrams, blend modes, layer groups, a data-defined label engine, and style interchange with SLD, QGIS QML and Mapbox GL JSON. RustGIS covers the common renderers and SQL-filtered label classes, stacked line symbols, symbol levels, blend modes and layer groups, - but not rule-based renderers or general data-defined styling. + symbol size, colours, outline width and angle by expression, but not rule-based renderers or + data-defined labels. - **3D.** GeoLibre has a Cesium globe with terrain, 3D Tiles, I3S, Gaussian splats, CZML and Google Photorealistic 3D Tiles. RustGIS has a globe, terrain-draped tilted views, 2.5D extrusion and LiDAR point layers. diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index a170201426..afff03d698 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -64,6 +64,28 @@ layer.markerRotation={"layer":"Signs","field":"angle","counterclockwise":true} layer.lineStrokes={"layer":"Signs","strokes":[{"color":"#FFFFFF","markers":{"mark":"circle","size":14}},{"color":"#000000","markers":{"mark":"character","char":"▲","size":10,"offsetAlong":0}}]} ``` +### Symbols by expression + +**By Expression**, under the symbol in the Symbology pane, sets parts of the symbol per feature +from an [expression](expressions.md): a point's **Size** (points), the **Fill** and **Outline** +colours (a line's **Color**), the **Outline width** (a line's **Width**, in points) and a point's +**Angle** (degrees clockwise, in place of the **Rotation** field; where it gives null, the field's). A colour is text: `'#d7301f'`, +a CSS colour name such as `'navy'`, or `'r,g,b[,a]'` as `color_rgb()` and `color_rgba()` give it. +A point with **Marks** scales them all with its **Size**, their sizes and offsets in proportion to +the symbol's own size (each mark keeps its colours); a size of 0 or less draws nothing. Where an +expression gives null (or, for a colour, text that isn't one), the feature takes the symbol's own, so a `CASE` without `ELSE` changes only the features it names. `@map_scale` is the +scale the map is drawn at, so a width can change with the zoom (in a shared web map, whose +reader zooms freely, it is null). They apply on top of the +renderer: a Unique Values class's colour, then the expression's. An expression applies when its +box loses focus; one that doesn't read shows why and isn't applied. A layer styled by expression +is drawn on the CPU; points drawn as counted bins (aggregation) keep the bins' own symbol. By command: + +```text +layer.symbolBy={"layer":"Cities","size":"scale_linear(pop_max, 0, 2e7, 4, 24)","fill":"CASE WHEN pop_max > 1e7 THEN '#d7301f' END"} +layer.symbolBy={"layer":"Rivers","strokeWidth":"if(@map_scale < 5e6, 2, 0.5)"} +layer.symbolBy={"layer":"Cities","fill":null} +``` + Pick a colour scheme from the pane's swatches, listed in groups: **Perceptually Uniform** (Viridis, Plasma, Inferno, Magma, Cividis, Batlow and Aurora: even steps in lightness, so they read in greyscale and for colour-blind viewers), **Sequential**, **Diverging** (Red–Blue, Vik, Roma, diff --git a/docs/user-guide/expressions.md b/docs/user-guide/expressions.md index 84ecc75cb9..a4ce8ce1e9 100644 --- a/docs/user-guide/expressions.md +++ b/docs/user-guide/expressions.md @@ -7,6 +7,8 @@ One expression language serves every place that reads values from features: matches when the expression is true. - **Calculate Field** and calculation attribute rules use an expression as a value, stored in the field after conversion to the field's type. +- [Symbols by expression](cartography.md#symbols-by-expression) take a value per feature: a + marker's size, the fill and outline colours, the outline width and a marker's angle. ```sql pop_est > 100000000 AND continent = 'Asia' @@ -65,7 +67,7 @@ operator: write `a < b AND b < c`, not `a < b < c`. | `'text'`, `'it''s'` | Text in single quotes; two quotes stand for one | | `TRUE`, `FALSE`, `NULL` | Booleans and the missing value | | `pop_est`, `"Pop Est"`, `!Pop Est!` | A field, by name, ignoring letter case; quote a name with spaces, punctuation or the name of a keyword (`"OR"`, `"null"`) | -| `@map_scale`, `$scale` | The scale denominator of the map being drawn; reserved for settings evaluated while drawing, null everywhere today | +| `@map_scale`, `$scale` | The scale denominator of the map being drawn: set in [symbols by expression](cartography.md#symbols-by-expression), null in queries and Calculate Field | | `@row_number` | The feature's position in the layer, from 1 | | `$id` | The feature's id | diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index c3f996799e..2f31a439ce 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -165,7 +165,14 @@ Each layer keeps its look: Projects and styles from QGIS 1 and 2 read too: their legend gives the layers' order, and the older names of the same settings are read. -QGIS expressions carry over where they are SQL: fields compared with values, `LIKE`, `IN`, +A symbol's data-defined size, fill and outline colours, outline width and marker angle carry over +as the layer's [symbol expressions](cartography.md#symbols-by-expression), sizes turned from the +symbol's unit (millimetres, points, pixels, inches; map units at the reference scale) into points, where RustGIS's [expression language](expressions.md) reads them. A marker of several layers +scales them all with the size one of its layers takes; a marker drawn as marks (several layers, +or one shifted or turned) leaves its colours and outline widths by expression out, noted. One using a +function or variable it lacks, or a field the layer hasn't, is noted and left out. + +QGIS filter expressions carry over where they are SQL: fields compared with values, `LIKE`, `IN`, `IS NULL`, joined by `AND`, `OR` and `NOT`. What RustGIS doesn't draw as QGIS does is drawn as near as it can, or left out, and said: the import's notes list, layer by layer, what was approximated (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, From 5cef065564ffcf5051bf483bfc73e7015d729fb5 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 30 Oct 2026 16:22:21 +0100 Subject: [PATCH 2/4] fix(symbology): size by expression on point layers only; a size of 0 hides a point's marks; drafts kept per map; saved expressions counted in characters; the guide says a MapLibre style leaves expressions out --- crates/engine/src/cmd/layer.rs | 4 ++-- crates/engine/src/tests.rs | 1 + crates/map/src/qgis/tests.rs | 2 +- crates/map/src/symbol_by.rs | 11 ++++++----- crates/ui-egui/src/labelpane.rs | 2 +- crates/ui-egui/src/panes.rs | 4 +++- docs/user-guide/cartography.md | 4 +++- 7 files changed, 17 insertions(+), 11 deletions(-) diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 025e415662..04e3e059a4 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -562,8 +562,8 @@ fn symbol_by(s: &mut Session, p: &Value) -> CmdResult { Some(_) => return Err(format!("{key} is an expression's text, or null for none")), }; if let Some(t) = &text { - if key == "angle" && l.geometry_type() != GeometryType::Point { - return Err("angle works on point layers".into()); + if matches!(key, "size" | "angle") && l.geometry_type() != GeometryType::Point { + return Err(format!("{key} works on point layers")); } rustgis_data::query::parse(t, &l.dataset).map_err(|e| format!("{key}: {e}"))?; } diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index edd02058fc..cfb047fd1b 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -794,6 +794,7 @@ fn a_symbol_is_set_by_expressions() { (json!({"layer": "Cities", "fill": "'red' ||"}), "fill: "), (json!({"layer": "Cities", "stroke": 3}), "stroke is an expression"), (json!({"layer": "Rivers", "angle": "10"}), "angle works on point layers"), + (json!({"layer": "Rivers", "size": "4"}), "size works on point layers"), ] { let err = s.run("layer.symbolBy", &bad).unwrap_err(); assert!(err.contains(says), "{bad}: {err}"); diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 77e485dfa0..f9bbf3c14d 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -1316,7 +1316,7 @@ fn data_defined_symbol_settings_carry_over_as_expressions() { let mut report = Report::default(); read_style(&fixed, "places", &mut report).unwrap(); assert!(report.notes.iter().any(|n| n.text.contains("scaled with its size")), "{:?}", report.notes); - assert!(!said("drawn with the first's"), "{:?}", report.notes); + assert!(!report.notes.iter().any(|n| n.text.contains("drawn with the first's")), "{:?}", report.notes); let dashed = line.replace("outlineColor", "customDash"); let mut report = Report::default(); diff --git a/crates/map/src/symbol_by.rs b/crates/map/src/symbol_by.rs index f9c779bf20..b07cdfc918 100644 --- a/crates/map/src/symbol_by.rs +++ b/crates/map/src/symbol_by.rs @@ -47,7 +47,7 @@ impl SymbolBy { /// Reads one expression leniently: text up to [`query::MAX_LEN`], blank or anything else none. fn de_text<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { Ok(match serde_json::Value::deserialize(d)? { - serde_json::Value::String(s) if !s.trim().is_empty() && s.len() <= query::MAX_LEN => Some(s), + serde_json::Value::String(s) if !s.trim().is_empty() && s.chars().count() <= query::MAX_LEN => Some(s), _ => None, }) } @@ -194,6 +194,10 @@ impl<'a> Styler<'a> { use std::borrow::Cow; let Some(b) = self.by.as_ref().filter(|b| b.points && !strokes.is_empty()) else { return Cow::Borrowed(strokes) }; let Some(size) = b.number(&b.size, &self.layer.dataset, row) else { return Cow::Borrowed(strokes) }; + let size = (size as f32).clamp(0.0, MAX_SIZE); + if size == 0.0 { + return Cow::Owned(Vec::new()); + } // The size the marks are drawn for: a Proportional renderer's base symbol's (it sizes the // symbol per feature, not the marks), else the feature's class's. let base = match &self.layer.renderer { @@ -203,10 +207,7 @@ impl<'a> Styler<'a> { if base.is_nan() || base <= 0.0 { return Cow::Borrowed(strokes); } - let k = (size as f32).clamp(0.0, MAX_SIZE) / base; - if k == 0.0 { - return Cow::Owned(Vec::new()); - } + let k = size / base; Cow::Owned( strokes .iter() diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index fb64a077f2..afe5cd6939 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -199,7 +199,7 @@ fn shown(c: &Class) -> String { /// `l` as a layer of this map of this project: another map, or another project, may reuse its id. /// A map goes by its place and its name, as Define Projection's does: deleting a map moves the /// next one into its place, and a copy keeps its layer ids. -fn layer_key(app: &RustGisApp, l: &Layer) -> egui::Id { +pub(crate) fn layer_key(app: &RustGisApp, l: &Layer) -> egui::Id { egui::Id::unique((app.session.opened, app.session.project.active_map, app.session.map().name.as_str(), l.id)) } diff --git a/crates/ui-egui/src/panes.rs b/crates/ui-egui/src/panes.rs index 90c2950422..668eca59ca 100644 --- a/crates/ui-egui/src/panes.rs +++ b/crates/ui-egui/src/panes.rs @@ -4944,6 +4944,8 @@ fn symbol_by_editor(app: &mut RustGisApp, ui: &mut Ui, l: &rustgis_engine::map:: ("strokeWidth", tl!("Outline width"), &by.stroke_width), ]), } + // A layer's id is its map's: a draft left on one map's layer isn't another's. + let scope = crate::labelpane::layer_key(app, l); egui::Frame::NONE.fill(t.pane_header).corner_radius(CornerRadius::same(8)).inner_margin(egui::Margin::same(10)).show(ui, |ui| { ui.set_width(ui.available_width()); ui.label(egui::RichText::new(tl!("By Expression")).font(semibold(12.5))); @@ -4956,7 +4958,7 @@ fn symbol_by_editor(app: &mut RustGisApp, ui: &mut Ui, l: &rustgis_engine::map:: ); for (key, label, cur) in rows { let cur = cur.clone().unwrap_or_default(); - let id = egui::Id::unique(("symbol_by", l.id, key)); + let id = egui::Id::unique(("symbol_by", scope, key)); let (typing, failed) = (id.with("typing"), id.with("failed")); let focused = ui.memory(|m| m.has_focus(id)); // Each kept with the expression it was typed over: one set meanwhile (by undo or a diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index afff03d698..c338e8782b 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -78,7 +78,9 @@ scale the map is drawn at, so a width can change with the zoom (in a shared web reader zooms freely, it is null). They apply on top of the renderer: a Unique Values class's colour, then the expression's. An expression applies when its box loses focus; one that doesn't read shows why and isn't applied. A layer styled by expression -is drawn on the CPU; points drawn as counted bins (aggregation) keep the bins' own symbol. By command: +is drawn on the CPU; points drawn as counted bins (aggregation) keep the bins' own symbol. A +shared web map draws each feature as styled; a layer's MapLibre style (a web layer's, or one +exported alone) carries the renderer's symbol, without the expressions. By command: ```text layer.symbolBy={"layer":"Cities","size":"scale_linear(pop_max, 0, 2e7, 4, 24)","fill":"CASE WHEN pop_max > 1e7 THEN '#d7301f' END"} From e708daf9c18ded89f683ba8559fe3e64bb97c283 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 30 Oct 2026 17:16:59 +0100 Subject: [PATCH 3/4] fix(symbology): a QGIS line of several strokes leaves its colour and width expressions out, said; the guide says what a shared web map and stacked strokes draw --- crates/map/src/qgis/symbol.rs | 5 +++++ crates/map/src/qgis/tests.rs | 7 +++++++ docs/user-guide/cartography.md | 8 +++++--- 3 files changed, 17 insertions(+), 3 deletions(-) diff --git a/crates/map/src/qgis/symbol.rs b/crates/map/src/qgis/symbol.rs index a7a2f3908e..a187a5f8fb 100644 --- a/crates/map/src/qgis/symbol.rs +++ b/crates/map/src/qgis/symbol.rs @@ -131,6 +131,11 @@ pub(super) fn read(sym: Node, reference: Option, turned: bool, layer: &str, report.skipped(layer, "data-defined colours and outline widths of a marker drawn as marks"); (by.fill, by.stroke, by.stroke_width) = (None, None, None); } + // A line of stacked strokes draws each with its own colour and width. + if sym.attribute("type") == Some("line") && out.stacked() && (by.stroke.is_some() || by.stroke_width.is_some()) { + report.skipped(layer, "data-defined colours and widths of a line of several strokes"); + (by.stroke, by.stroke_width) = (None, None); + } // Marks scale with the symbol's size, its largest layer's: the expression, taken from one // layer, is turned into the size it gives that one, so every mark scales as that layer does. if let (true, Some(text), Some(own)) = (drawn_as_marks, by.size.as_ref(), sized_layer.map(|s| s.clamp(0.0, 200.0))) diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index f9bbf3c14d..358c243c28 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -1261,6 +1261,13 @@ fn data_defined_symbol_settings_carry_over_as_expressions() { assert_eq!(by.stroke_width.as_deref(), Some("(if(@map_scale < 4656581, 1.0, 0)) * 1.333333"), "{by:?}"); assert_eq!(by.stroke.as_deref(), Some("color_rgb(255, 0, 0)")); assert!(report.notes.is_empty(), "{:?}", report.notes); + // A line of two strokes draws each with its own: left out, said. + let stroke = r#""#; + let doubled = line.replace("", &format!("{stroke}{stroke}")); + let mut report = Report::default(); + let s = read_style(&doubled, "roads", &mut report).unwrap(); + assert!(s.symbol_by.is_none_or(|b| b.stroke.is_none() && b.stroke_width.is_none())); + assert!(report.notes.iter().any(|n| n.text.contains("line of several strokes")), "{:?}", report.notes); // Classes: one sized by expression, one not; the other's drawn with the first's, said. A // see-through symbol's expression colour is drawn opaque, said. let marker = |name: &str, props: &str| { diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index c338e8782b..33c1bb41e9 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -78,9 +78,11 @@ scale the map is drawn at, so a width can change with the zoom (in a shared web reader zooms freely, it is null). They apply on top of the renderer: a Unique Values class's colour, then the expression's. An expression applies when its box loses focus; one that doesn't read shows why and isn't applied. A layer styled by expression -is drawn on the CPU; points drawn as counted bins (aggregation) keep the bins' own symbol. A -shared web map draws each feature as styled; a layer's MapLibre style (a web layer's, or one -exported alone) carries the renderer's symbol, without the expressions. By command: +is drawn on the CPU; points drawn as counted bins (aggregation) keep the bins' own symbol, and +a line's stacked strokes keep the colour and width each sets. A shared web map draws each +feature's colours, outline width and size as styled (points as circles, without their angle or +marks); a layer's MapLibre style (a web layer's, or one exported alone) carries the renderer's +symbol, without the expressions. By command: ```text layer.symbolBy={"layer":"Cities","size":"scale_linear(pop_max, 0, 2e7, 4, 24)","fill":"CASE WHEN pop_max > 1e7 THEN '#d7301f' END"} From 0e6755d0408657f8e2421c3806919083ee0969a2 Mon Sep 17 00:00:00 2001 From: Dominik Strebel Date: Fri, 30 Oct 2026 18:17:44 +0100 Subject: [PATCH 4/4] fix(symbology): QGIS class expressions carry over only when every class has the same and none is switched off; formatting --- crates/map/src/qgis/renderer.rs | 26 +++++++++++++++++++------- crates/map/src/qgis/tests.rs | 25 ++++++++++++++++++++----- docs/user-guide/workspace.md | 4 +++- 3 files changed, 42 insertions(+), 13 deletions(-) diff --git a/crates/map/src/qgis/renderer.rs b/crates/map/src/qgis/renderer.rs index 315d390767..2cbd057e22 100644 --- a/crates/map/src/qgis/renderer.rs +++ b/crates/map/src/qgis/renderer.rs @@ -10,6 +10,7 @@ use roxmltree::Node; use super::symbol::{self, Converted}; use super::{QGIS_SCALE, Report, Style, child, expr, has_effect}; use crate::color::Ramp; +use crate::symbol_by::SymbolBy; use crate::symbology::{ClassMethod, LineStroke, Renderer, Symbol}; /// The most classes a renderer is imported with: every feature is matched against them. @@ -50,7 +51,7 @@ fn read_depth(r: Node, layer: &str, style: &mut Style, report: &mut Report, dept let rotation = std::cell::RefCell::new(None); let turned = symbols.values().any(|n| symbol::turns_by_field(*n)); // Every symbol's data-defined expressions: the first that has any are the layer's. - let by: std::cell::RefCell> = std::cell::RefCell::new(Vec::new()); + let by: std::cell::RefCell> = std::cell::RefCell::new(Vec::new()); let read = |n: Node, report: &mut Report| { let c = symbol::read(n, reference, turned, layer, report); if let (Some(r), Ok(mut had)) = (&c.rotation, rotation.try_borrow_mut()) @@ -98,13 +99,24 @@ fn read_depth(r: Node, layer: &str, style: &mut Style, report: &mut Report, dept matches!(kind, "pointCluster" | "pointDisplacement" | "invertedPolygonRenderer" | "mergedFeatureRenderer" | "25dRenderer"); if style.renderer.is_some() && !wrapper { style.marker_rotation = Some(rotation.try_borrow().ok().and_then(|r| r.clone())); - let all = by.try_borrow().map(|b| b.clone()).unwrap_or_default(); - let first = all.iter().find(|b| !b.is_empty()).cloned().unwrap_or_default(); - // Classes with other expressions, or none, are drawn with the first's. - if !first.is_empty() && all.len() > 1 { - report.approximated(layer, "symbols with different data-defined settings, all drawn with the first's"); + let mut all = by.try_borrow().map(|b| b.clone()).unwrap_or_default(); + // A switched-off class draws nothing: expressions applied to every feature would paint it. + let off = + r.descendants().any(|n| (n.has_tag_name("category") || n.has_tag_name("range")) && n.attribute("render") == Some("false")); + if off && !all.iter().any(SymbolBy::is_empty) { + all.push(SymbolBy::default()); } - style.symbol_by = Some(first); + // The expressions apply to every feature: kept only when every symbol has the same. + let one = match all.as_slice() { + [one] => one.clone(), + _ => { + if all.iter().any(|b| !b.is_empty()) { + report.skipped(layer, "data-defined settings that differ between its classes (or a class switched off)"); + } + SymbolBy::default() + } + }; + style.symbol_by = Some(one); } } diff --git a/crates/map/src/qgis/tests.rs b/crates/map/src/qgis/tests.rs index 358c243c28..554b98293a 100644 --- a/crates/map/src/qgis/tests.rs +++ b/crates/map/src/qgis/tests.rs @@ -1262,14 +1262,15 @@ fn data_defined_symbol_settings_carry_over_as_expressions() { assert_eq!(by.stroke.as_deref(), Some("color_rgb(255, 0, 0)")); assert!(report.notes.is_empty(), "{:?}", report.notes); // A line of two strokes draws each with its own: left out, said. - let stroke = r#""#; + let stroke = + r#""#; let doubled = line.replace("", &format!("{stroke}{stroke}")); let mut report = Report::default(); let s = read_style(&doubled, "roads", &mut report).unwrap(); assert!(s.symbol_by.is_none_or(|b| b.stroke.is_none() && b.stroke_width.is_none())); assert!(report.notes.iter().any(|n| n.text.contains("line of several strokes")), "{:?}", report.notes); - // Classes: one sized by expression, one not; the other's drawn with the first's, said. A - // see-through symbol's expression colour is drawn opaque, said. + // Classes: one sized by expression, one not; left out (applied to every feature, they would + // change the other's), said. A see-through symbol's expression colour is drawn opaque, said. let marker = |name: &str, props: &str| { format!( r#""# @@ -1284,9 +1285,23 @@ fn data_defined_symbol_settings_carry_over_as_expressions() { ); let mut report = Report::default(); let s = read_style(&classes, "points", &mut report).unwrap(); - assert_eq!(s.symbol_by.unwrap().size.as_deref(), Some(r#"("v") * 3.779528"#)); + assert!(s.symbol_by.is_none_or(|b| b.is_empty())); let said = |t: &str| report.notes.iter().any(|n| n.text.contains(t)); - assert!(said("different data-defined settings") && said("see-through symbol"), "{:?}", report.notes); + assert!(said("differ between its classes") && said("see-through symbol"), "{:?}", report.notes); + // Both classes alike: theirs. With a class switched off besides, which they would paint: left + // out, said. + let same = dd(&[("size", ""v"")]); + let alike = + classes.replace(&marker("1", ""), &marker("1", &same)).replace(&dd(&[("size", ""v""), ("fillColor", "'red'")]), &same); + let mut report = Report::default(); + let s = read_style(&alike, "points", &mut report).unwrap(); + assert_eq!(s.symbol_by.unwrap().size.as_deref(), Some(r#"("v") * 3.779528"#)); + assert!(report.notes.is_empty(), "{:?}", report.notes); + let off = alike.replace("", r#""#); + let mut report = Report::default(); + let s = read_style(&off, "points", &mut report).unwrap(); + assert!(s.symbol_by.is_none_or(|b| b.is_empty())); + assert!(report.notes.iter().any(|n| n.text.contains("a class switched off")), "{:?}", report.notes); // A marker of two layers (the Training Manual's world places): a white disc sized by // expression, a black dot sized in proportion on top. The marks scale with the top layer's // size; their colours stay their own, the outline colour by expression is left out. diff --git a/docs/user-guide/workspace.md b/docs/user-guide/workspace.md index 2f31a439ce..367d533e44 100644 --- a/docs/user-guide/workspace.md +++ b/docs/user-guide/workspace.md @@ -169,7 +169,9 @@ A symbol's data-defined size, fill and outline colours, outline width and marker as the layer's [symbol expressions](cartography.md#symbols-by-expression), sizes turned from the symbol's unit (millimetres, points, pixels, inches; map units at the reference scale) into points, where RustGIS's [expression language](expressions.md) reads them. A marker of several layers scales them all with the size one of its layers takes; a marker drawn as marks (several layers, -or one shifted or turned) leaves its colours and outline widths by expression out, noted. One using a +or one shifted or turned) leaves its colours and outline widths by expression out, noted, and so +does a line of several strokes. They apply to every feature, so a layer whose classes set different +ones (or one with a class switched off) leaves them out, noted. One using a function or variable it lacks, or a field the layer hasn't, is noted and left out. QGIS filter expressions carry over where they are SQL: fields compared with values, `LIKE`, `IN`,