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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 21 additions & 4 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3467,8 +3467,16 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult {
if expression.is_some() && !matches!(kind.as_str(), "unique" | "uniquevalues") {
return Err("only Unique Values class by an expression".into());
}
// Applied again by the layer's own expression, as many classes as it has (an imported rule
// style's may pass the first MAX_UNIQUE values).
let mut keep = rustgis_map::symbology::MAX_UNIQUE;
let expression = match (p.get("expression"), p.get("field")) {
(None, None) => l.renderer.expression().map(str::to_string),
(None, None) => {
if let Renderer::Unique { classes, expression: Some(_), .. } = &l.renderer {
keep = keep.max(classes.len()).min(rustgis_map::symbology::MAX_EXPRESSION_CLASSES);
}
l.renderer.expression().map(str::to_string)
}
_ => expression,
};
// Features past the first values an expression's classes keep.
Expand All @@ -3477,7 +3485,7 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult {
"single" | "singlesymbol" => Renderer::Single(base),
"unique" | "uniquevalues" => match &expression {
Some(e) => {
let (mut r, n) = Renderer::unique_by_counted(&l.dataset, &rows()?, e, ramp.unwrap_or(Ramp::Harbour), base)?;
let (mut r, n) = Renderer::unique_by_up_to(&l.dataset, &rows()?, e, ramp.unwrap_or(Ramp::Harbour), base, keep)?;
rest = n;
// (Clearing the expression goes back to the field it had.)
if let (Renderer::Unique { field, .. }, Some(last)) = (&mut r, last_field) {
Expand Down Expand Up @@ -3516,15 +3524,24 @@ fn symbology(s: &mut Session, p: &Value) -> CmdResult {
r.map_symbols(show_fill);
}
let name = l.name.clone();
// Classes are the values given with no map scale: one given only at some scales never is.
let by_scale = r.expression().is_some_and(rustgis_map::qgis::reads_scale);
Comment thread
pick2510 marked this conversation as resolved.
Resolved
Comment thread
pick2510 marked this conversation as resolved.
Resolved
let out = with(s, p, |l| {
l.renderer = r;
take_no_fill(l);
})?;
if rest > 0 {
s.notify(
format!(
"{name}: {rest} features whose value is past the first {} values the expression gives (in text order) are drawn as <all other values>",
rustgis_map::symbology::MAX_UNIQUE
"{name}: {rest} features whose value is past the first {keep} values the expression gives (in text order) are drawn as <all other values>"
),
false,
);
}
if by_scale {
Comment thread
pick2510 marked this conversation as resolved.
Resolved
s.notify(
format!(
"{name}: its classes are the values the expression gives without a map scale; values it gives only at some scales, if any, are drawn as <all other values>"
),
false,
);
Expand Down
2 changes: 1 addition & 1 deletion crates/engine/src/cmd/service_group.rs
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ fn refresh(s: &mut Session, p: &Value) -> CmdResult {
if !singled.is_empty() {
s.notify(
format!(
"layers whose classes read fields the refreshed service no longer has, or no longer read as numbers, are drawn with a single symbol ({}: {})",
"layers whose classes read fields the refreshed service no longer has, or no longer read as numbers, or whose class expression no longer reads, are drawn with a single symbol ({}: {})",
singled.len(),
singled.join(", ")
),
Expand Down
73 changes: 73 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -811,6 +811,66 @@ fn a_symbol_is_set_by_expressions() {
assert_eq!(s.map().layer_by_name("Cities").unwrap().symbol_by.angle.as_deref(), Some("45"));
}

/// Applied again by its own expression, an imported rule style keeps as many classes as it has
/// (past the first 64 values, up to the 200 an import makes); classes by an expression reading the map's scale are said to be
/// the values given without one.
#[test]
fn unique_values_by_expression_keep_their_classes_and_say_scales() {
let mut s = world();
let mut ds = rustgis_data::Dataset::new(
"many",
rustgis_data::GeometryType::Point,
vec![rustgis_data::Field::new("v", rustgis_data::FieldType::Integer)],
);
let n = rustgis_map::symbology::MAX_EXPRESSION_CLASSES as i64;
for i in 0..n {
ds.push(Some(rustgis_data::Geometry::Point(rustgis_geom::Coord::new(i as f64 / 10.0, 1.0))), vec![rustgis_data::Value::Int(i)]);
}
let many = s.map_mut().add_dataset(ds);
let rules: String =
(0..n).map(|i| format!(r#"<rule filter="&quot;v&quot; = {i} AND &quot;v&quot; &gt;= 0" symbol="0" label="R{i:03}"/>"#)).collect();
let qml = format!(
r#"<qgis version="3.40.0"><renderer-v2 type="RuleRenderer"><rules key="r">{rules}</rules><symbols><symbol type="marker" name="0"><layer class="SimpleMarker" enabled="1"/></symbol></symbols></renderer-v2></qgis>"#
);
s.run("style.importQgis", &json!({"layer": many, "text": qml})).unwrap();
let classes = |s: &Session| match &s.map().layer(many).unwrap().renderer {
rustgis_map::Renderer::Unique { classes, expression: Some(_), .. } => classes.len(),
r => panic!("{r:?}"),
};
assert_eq!(classes(&s), n as usize);
let mark = s.notice_mark();
s.run("layer.symbology", &json!({"layer": many, "type": "unique", "ramp": "Ember"})).unwrap();
assert_eq!(classes(&s), n as usize, "every rule keeps its class, up to the limit");
let said = |s: &Session, what: &str| s.notices_since(mark).iter().any(|n| n.text.contains(what));
assert!(!said(&s, "past the first"), "{:?}", s.notices_since(mark));
assert!(!said(&s, "without a map scale"));
// An expression of its own keeps the first 64, and says so.
s.run("layer.symbology", &json!({"layer": many, "type": "unique", "expression": "'k' || (1000 + v)"})).unwrap();
assert_eq!(classes(&s), rustgis_map::symbology::MAX_UNIQUE);
assert!(said(&s, "past the first 64"));
// One reading the map's scale is classed without one, and says so.
let mark = s.notice_mark();
s.run(
"layer.symbology",
&json!({"layer": many, "type": "unique", "expression": "CASE WHEN @map_scale < 50000 THEN 'detail' ELSE 'overview' END"}),
)
.unwrap();
assert!(s.notices_since(mark).iter().any(|n| n.text.contains("without a map scale")), "{:?}", s.notices_since(mark));
Comment thread
pick2510 marked this conversation as resolved.
Resolved
// Its classes are what it gives with no scale: 'detail' only at some scales isn't one.
let rustgis_map::Renderer::Unique { classes: kept, .. } = &s.map().layer(many).unwrap().renderer else { panic!() };
assert_eq!(kept.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(), ["overview"]);
// So too with the scale written right after a word, which the expression still reads.
let mark = s.notice_mark();
s.run(
"layer.symbology",
&json!({"layer": many, "type": "unique", "expression": "CASE WHEN@map_scale < 50000 THEN 'detail' ELSE 'overview' END"}),
)
.unwrap();
assert!(s.notices_since(mark).iter().any(|n| n.text.contains("without a map scale")), "{:?}", s.notices_since(mark));
let rustgis_map::Renderer::Unique { classes: kept, .. } = &s.map().layer(many).unwrap().renderer else { panic!() };
assert_eq!(kept.iter().map(|c| c.0.as_str()).collect::<Vec<_>>(), ["overview"]);
}

#[test]
fn unique_values_class_by_an_expression() {
let mut s = world();
Expand Down Expand Up @@ -846,6 +906,11 @@ fn unique_values_class_by_an_expression() {
assert_eq!(s.map().layer_by_name("Cities").unwrap().renderer.field(), Some(by.as_str()), "back to the field it had");
s.undo();
assert_eq!(expression(&s).as_deref(), Some(e));
s.run("layer.symbology", &json!({"layer": "Cities", "type": "unique", "expression": " "})).unwrap();
assert!(expression(&s).is_none(), "blank text goes back to the field too");
assert_eq!(s.map().layer_by_name("Cities").unwrap().renderer.field(), Some(by.as_str()));
s.undo();
assert_eq!(expression(&s).as_deref(), Some(e));
// A style shared to the web says it draws one symbol; a map draws the classes.
let dir = std::env::temp_dir().join(format!("rustgis-unique-by-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
Expand Down Expand Up @@ -18338,6 +18403,14 @@ fn ogc_refresh_reconciles_fields_and_preserves_compatible_settings() {
s.run("service.refresh", &target).unwrap();
let singled = |s: &Session| s.notices.iter().filter(|n| n.text.contains("drawn with a single symbol (1: Places)")).count();
assert_eq!(singled(&s), 0);
// Classes by an expression that still reads are kept too.
s.run("layer.symbology", &json!({"layer":layer, "type":"unique", "expression":"value || ''"})).unwrap();
let by_expression = s.map().layer(layer).unwrap().renderer.clone();
s.run("service.refresh", &target).unwrap();
assert_eq!(s.map().layer(layer).unwrap().renderer, by_expression);
assert_eq!(singled(&s), 0);
s.run("edit.undo", &Value::Null).unwrap();
s.run("edit.undo", &Value::Null).unwrap();
let l = s.map().layer(layer).unwrap();
assert_eq!(l.renderer, style);
assert_eq!(l.labels, labels);
Expand Down
14 changes: 11 additions & 3 deletions crates/map/src/qgis/expr.rs
Original file line number Diff line number Diff line change
Expand Up @@ -75,8 +75,9 @@ fn map_vars(expr: &str, f: impl Fn(char, &str) -> Option<String>) -> String {
let end =
(i + 1..=chars.len()).find(|j| !chars.get(*j).is_some_and(|d| d.is_alphanumeric() || *d == '_')).unwrap_or(chars.len());
let name: String = chars.get(i + 1..end).unwrap_or_default().iter().collect();
let after_word = i > 0 && chars.get(i - 1).is_some_and(|d| d.is_alphanumeric() || *d == '_');
match f(c, &name).filter(|_| !after_word) {
// (Right after a word too: `WHEN@map_scale` reads the scale, in QGIS and in RustGIS,
// whose names hold neither `@` nor `$`.)
match f(c, &name) {
Some(with) => out.push_str(&with),
None => {
out.push(c);
Expand Down Expand Up @@ -272,8 +273,15 @@ mod tests {
assert_eq!(to_sql("@map_scale < 5000").as_deref(), Some(format!("(@map_scale / {k}) < 5000").as_str()));
assert_eq!(
super::rustgis_scales("$scale > 1 AND \"@map_scale\" = '$scale' AND @map_scales = 2 AND a$scale"),
format!("(@map_scale / {k}) > 1 AND \"@map_scale\" = '$scale' AND @map_scales = 2 AND a$scale")
format!("(@map_scale / {k}) > 1 AND \"@map_scale\" = '$scale' AND @map_scales = 2 AND a(@map_scale / {k})")
);
assert_eq!(to_sql(&"a".repeat(MAX_LEN + 1)), None);
// A scale right after a word is read and converted too, as the expression reads it.
assert_eq!(
to_sql("CASE WHEN@map_scale < 5 THEN 'a' END").as_deref(),
Some(format!("CASE WHEN(@map_scale / {k}) < 5 THEN 'a' END").as_str())
);
assert!(super::reads_scale("CASE WHEN@map_scale < 5 THEN 'a' END") && super::reads_scale("a$scale"));
assert!(!super::reads_scale("\"@map_scale\" = '$scale' AND @map_scales = 2"));
}
}
2 changes: 1 addition & 1 deletion crates/map/src/qgis/renderer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -436,7 +436,7 @@ fn unique(
}

/// The most rules classed by expression: one `WHEN` each.
const MAX_RULE_CLASSES: usize = 200;
const MAX_RULE_CLASSES: usize = crate::symbology::MAX_EXPRESSION_CLASSES;

/// The rules as Unique Values by an expression ([`super::rules_expression`]): `CASE WHEN <rule
/// 1> THEN 'Rule 1' … END`, each rule's condition its filters and its parents', an else rule's
Expand Down
23 changes: 20 additions & 3 deletions crates/map/src/symbology.rs
Original file line number Diff line number Diff line change
Expand Up @@ -765,6 +765,9 @@ pub struct LegendEntry {

/// Most unique-value classes created automatically.
pub const MAX_UNIQUE: usize = 64;
/// The most classes by an expression: a QGIS rule-based style's rules (one class each), kept when
/// its classes are made again from the expression.
pub const MAX_EXPRESSION_CLASSES: usize = 200;

/// The colour of a new Unique Values renderer's `<all other values>` class.
pub const OTHER_FILL: Rgba = Rgba::rgb(0xB0, 0xB0, 0xB0);
Expand Down Expand Up @@ -915,13 +918,27 @@ impl Renderer {
/// [`Renderer::unique_by`], and how many kept features with a geometry have a value past the
/// first [`MAX_UNIQUE`] (in text order), drawn as `<all other values>`.
pub fn unique_by_counted(ds: &Dataset, rows: &[bool], expression: &str, ramp: Ramp, base: Symbol) -> Result<(Renderer, usize), String> {
Self::unique_by_up_to(ds, rows, expression, ramp, base, MAX_UNIQUE)
}

/// [`Renderer::unique_by_counted`] keeping up to `max` values (at most
/// [`MAX_EXPRESSION_CLASSES`]), and how many features have a value past them.
pub fn unique_by_up_to(
ds: &Dataset,
rows: &[bool],
expression: &str,
ramp: Ramp,
base: Symbol,
max: usize,
) -> Result<(Renderer, usize), String> {
let max = max.clamp(1, MAX_EXPRESSION_CLASSES);
let text = expression.trim();
if text.chars().count() > rustgis_data::query::MAX_LEN {
return Err(format!("the expression is longer than {} characters", rustgis_data::query::MAX_LEN));
}
let e = rustgis_data::query::parse(text, ds)?;
let env = rustgis_data::query::Env::default();
// The first values in order, never more than MAX_UNIQUE kept, each with its features: one
// The first values in order, never more than `max` kept, each with its features: one
// put out of the first can't come back (any later one is past the last kept), so its
// features and every later one past the last kept are counted as the rest.
let mut kept: BTreeMap<String, usize> = BTreeMap::new();
Expand All @@ -934,12 +951,12 @@ impl Renderer {
};
// (A feature without a geometry draws nothing, so it isn't counted.)
let drawn = usize::from(ds.features.get(r).is_some_and(|f| f.geometry.is_some()));
if kept.len() >= MAX_UNIQUE && kept.last_key_value().is_some_and(|(last, _)| v > *last) {
if kept.len() >= max && kept.last_key_value().is_some_and(|(last, _)| v > *last) {
rest += drawn;
continue;
}
*kept.entry(v).or_insert(0) += drawn;
if kept.len() > MAX_UNIQUE {
if kept.len() > max {
rest += kept.pop_last().map_or(0, |(_, n)| n);
}
}
Expand Down
Loading