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
1 change: 1 addition & 0 deletions crates/engine/command-surface.txt
Original file line number Diff line number Diff line change
Expand Up @@ -258,6 +258,7 @@ layer.move layer? to
layer.moveDown layer?
layer.moveUp layer?
layer.noFill layer?
layer.orderClasses layer? values? by?
layer.outdent layer?
layer.outline layer? color? width?
layer.paste map? group? to?
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/cmd/embeddings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -513,6 +513,7 @@ pub(crate) fn style_points(s: &mut Session, id: u32) {
class_fills: Default::default(),
other_fills: Vec::new(),
expression: None,
keep_order: false,
};
}

Expand Down
38 changes: 38 additions & 0 deletions crates/engine/src/cmd/layer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -234,6 +234,11 @@ pub fn commands() -> Vec<C> {
.params(
r##"{"layer"?, "values": [text|number, …] (two or more Unique Values classes; they take the symbol, strokes and fills of the first of them in the class list's order, and one label, so a legend lists them as one entry), "label"?: text (default, or when empty: the values joined with ", "; cut to 200 characters)}"##,
),
C::new("layer.orderClasses", "Order Classes", "Style › Drawing", order_classes).roles(&[]).effects(crate::policy::Effects::NONE)
.when(need_feature_layer)
.params(
r##"{"layer"?, "values"?: [text|number, …] (Unique Values classes, listed first in this order and kept so; the others follow in their order), "by"?: "name" (back to the sort by name, or by number when the values are numbers)}"##,
),
C::new("layer.color", "Symbol Color", "Style › Drawing", |s, p| {
let hex = s_req(p, "color")?;
let c = Rgba::from_hex(hex).ok_or("color must be #RRGGBB or #RRGGBBAA")?;
Expand Down Expand Up @@ -3171,6 +3176,7 @@ fn apply_styles(s: &mut Session, id: u32, styles: &[(String, rustgis_data::kml::
class_fills: Default::default(),
other_fills: Vec::new(),
expression: None,
keep_order: false,
};
}

Expand Down Expand Up @@ -8549,6 +8555,38 @@ fn group_classes(s: &mut Session, p: &Value) -> CmdResult {
Ok(json!({"label": group.label, "values": group.values}))
}

/// `layer.orderClasses`: Unique Values classes kept in the order given (#3319), or sorted again.
fn order_classes(s: &mut Session, p: &Value) -> CmdResult {
let values = match (p.get("values"), p.get("by")) {
(Some(_), Some(_)) => return Err("give values or by, not both".into()),
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
(None, Some(by)) if by.as_str() == Some("name") => None,
(Some(Value::Array(v)), None) if !v.is_empty() => Some(v.iter().map(class_value).collect::<Result<Vec<_>, _>>()?),
_ => return Err("values is a list of Unique Values classes, or by is \"name\"".into()),
};
let id = s.layer_id(p)?;
let l = s.map_mut().layer_mut(id).ok_or("no such layer")?;
let (missing, moved) = l.renderer.order_classes(values.as_deref())?;
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
// The opacities No Fill saved are by symbol, while they still match them: they move too.
if let Some(h) = l.hidden_fills.as_mut().filter(|h| h.alphas.len() == moved.len() + 1) {
let mut alphas: Vec<u8> = moved.iter().filter_map(|&i| h.alphas.get(i).copied()).collect();
alphas.extend(h.alphas.last().copied());
h.alphas = alphas;
}
let listed = match &l.renderer {
Renderer::Unique { classes, .. } => {
l.renderer.class_order().into_iter().filter_map(|i| classes.get(i).map(|c| c.0.clone())).collect()
}
_ => Vec::new(),
};
if !missing.is_empty() {
s.notify(
format!("No class with the value(s) {}; skipped", missing.iter().map(|v| format!("'{v}'")).collect::<Vec<_>>().join(", ")),
false,
);
}
Ok(json!({"classes": listed, "skipped": missing}))
}

/// These loaders interpret `layer` inside an external file/database, never as a map layer.
/// The selector remains frozen with its path/address, including the loader's empty default.
pub(crate) fn external_dataset_selector(command: &str) -> bool {
Expand Down
1 change: 1 addition & 0 deletions crates/engine/src/project.rs
Original file line number Diff line number Diff line change
Expand Up @@ -135,6 +135,7 @@ pub const CAPABILITIES: &[&str] = &[
"svg-markers",
"label-duplicates",
"layer-raster-mask",
"unique-keep-order",
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
"tile-resampling",
"layout-page-color",
"layout-text-statistics",
Expand Down
70 changes: 69 additions & 1 deletion crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,10 @@ impl Project {
if !required.contains(&"svg-markers") && self.styles.iter().any(|s| s.renderer.any_picture(svg_picture)) {
required.push("svg-markers");
}
// And its class order (#3319): an older reader would apply the style with the classes sorted.
if !required.contains(&UNIQUE_KEEP_ORDER) && self.styles.iter().any(|s| keeps_class_order(&s.renderer)) {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
required.push(UNIQUE_KEEP_ORDER);
}
// And its labels' weights (#2803): an older reader would apply the style without them.
if !required.contains(&"label-weight")
&& self.styles.iter().any(|s| s.labels.in_order().any(|c| c.weight != rustgis_map::symbology::DEFAULT_LABEL_WEIGHT))
Expand Down Expand Up @@ -184,6 +188,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[
("label-clearance", command_clears_labels),
("label-duplicates", command_removes_duplicate_labels),
("layer-raster-mask", command_masks_by_raster),
(UNIQUE_KEEP_ORDER, command_adds_kept_class_order),
("tile-resampling", command_resamples_tiles),
("layout-page-color", command_colours_the_page),
("layout-text-statistics", command_uses_text_statistics),
Expand Down Expand Up @@ -301,6 +306,23 @@ fn command_masks_by_raster(id: &str, params: &Value) -> bool {
}
}

/// A saved `style.add` whose style keeps its Unique Values classes in their order (#3319), from
/// `text` or `data` (a style read from a `"path"` is a file, whose header requires what it uses):
/// an older reader would add the style with the classes sorted. Read only when the text names
/// `keep_order` (or escapes, which could hide it).
fn command_adds_kept_class_order(id: &str, params: &Value) -> bool {
match id {
"style.add" => crate::cmd::items::inline_text(params)
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
.ok()
.flatten()
.filter(|t| t.contains("keep_order") || t.contains('\\'))
.and_then(|t| serde_json::from_str::<Vec<crate::project::StyleItem>>(&t).ok())
.is_some_and(|items| items.iter().any(|i| keeps_class_order(&i.renderer))),
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_adds_kept_class_order)),
_ => false,
}
}

/// A saved `labels.placement` that has a class remove duplicates, read as the command reads it
/// (#2847): an older reader runs it without the key, saying nothing, so every label would show.
/// False or null is what an older reader keeps.
Expand Down Expand Up @@ -1232,6 +1254,15 @@ fn removes_duplicate_labels(layer: &Layer) -> bool {
layer.labels.in_order().any(|c| c.remove_duplicates.is_some())
}

/// A Unique Values class order kept as listed (#3319).
const UNIQUE_KEEP_ORDER: &str = "unique-keep-order";

/// Whether Unique Values classes keep the order they are listed in (#3319): an older reader would
/// list them sorted, and save them so.
fn keeps_class_order(renderer: &rustgis_map::Renderer) -> bool {
matches!(renderer, rustgis_map::Renderer::Unique { keep_order: true, .. })
}

/// The capabilities a layer needs, in [`map_capabilities`]'s order.
fn layer_capabilities(layer: &Layer) -> Vec<&'static str> {
[
Expand All @@ -1247,6 +1278,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> {
(zarr_window(layer), "zarr-window"),
// Masked by a raster's values (#3147): an older reader would draw it whole and save it so.
(layer.raster_mask.is_some(), "layer-raster-mask"),
(keeps_class_order(&layer.renderer), UNIQUE_KEEP_ORDER),
(label_guide(layer), "label-guide"),
(label_weight(layer), "label-weight"),
(label_clearance(layer), "label-clearance"),
Expand Down Expand Up @@ -1276,7 +1308,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
mut on_top,
mut grid_color,
) = (false, false, false, false, false, false, false, false, false, false, false, false, false, false, false);
let (mut polygon, mut svg, mut raster_mask) = (false, false, false);
let (mut polygon, mut svg, mut raster_mask, mut class_order) = (false, false, false, false);
let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared, mut deduped) =
(false, false, false, false, false, false, false);
let (mut crisp, mut bed, mut walls_top, mut soft, mut aerial, mut terrain_type, mut flats) =
Expand Down Expand Up @@ -1327,6 +1359,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
zarr |= map.layers.iter().any(zarr_window);
native |= map.layers.iter().any(|layer| held_natively(&layer.dataset));
raster_mask |= map.layers.iter().any(|layer| layer.raster_mask.is_some());
class_order |= map.layers.iter().any(|layer| keeps_class_order(&layer.renderer));
legends |= map.tiles.iter().any(|tile| {
tile.legends.iter().any(|legend| rustgis_data::login_address::inner(&legend.url).len() > rustgis_map::tiles::MAX_LEGEND_URL)
});
Expand All @@ -1353,6 +1386,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator<Item = &'a Map>) -> Vec<&'static
(svg, "svg-markers"),
(zarr, "zarr-window"),
(raster_mask, "layer-raster-mask"),
(class_order, UNIQUE_KEEP_ORDER),
(guided, "label-guide"),
(weighed, "label-weight"),
(cleared, "label-clearance"),
Expand Down Expand Up @@ -1857,6 +1891,7 @@ mod tests {
(&["dggs-system"], "a5Grid", json!({"system": "H3"})),
(&["dggs-system"], "a5Aggregate", json!({"system": "S2"})),
(&["label-weight"], "labels.placement", json!({"weight": 9})),
(&["unique-keep-order"], "style.add", json!({"text": kept_order_style()})),
(&["label-clearance"], "labels.placement", json!({"clearance": 9})),
(&["label-duplicates"], "labels.placement", json!({"removeDuplicates": 20})),
(&["tile-resampling"], "map.addTiles", json!({"resampling": "nearest"})),
Expand Down Expand Up @@ -1951,6 +1986,39 @@ mod tests {
}
}

/// A style file whose Unique Values classes keep their order (#3319), from the fixture.
fn kept_order_style() -> String {
let p = Project::from_json(include_str!("../../../schema/fixtures/unique_keep_order.rgis")).unwrap();
let l = &p.maps[0].layers[0];
let item = crate::project::StyleItem {
name: "Ordered".into(),
geometry: l.geometry_type(),
renderer: l.renderer.clone(),
labels: l.labels.clone(),
transparency: 0.0,
};
serde_json::to_string(&[item]).unwrap()
}

/// A saved `style.add` whose style keeps its class order requires `unique-keep-order`, by
/// `text`, by `data` or in a script line; one that sorts its classes needs nothing (#3367
/// review): an older reader would add the style with the classes sorted.
#[test]
fn a_saved_style_add_that_keeps_a_class_order_requires_it() {
use base64::Engine;
let needs = |params: Value| model_capabilities(&[ModelStep { tool: "style.add".into(), params }], None);
let style = kept_order_style();
let data = base64::engine::general_purpose::STANDARD.encode(&style);
assert_eq!(needs(json!({"text": style})), ["unique-keep-order"]);
assert_eq!(needs(json!({"data": data})), ["unique-keep-order"]);
let line = format!("style.add={}", json!({"text": style}));
let script = model_capabilities(&[ModelStep { tool: "script.run".into(), params: json!({"script": line}) }], None);
assert_eq!(script, ["unique-keep-order"]);
let sorted = style.replace("\"keep_order\":true", "\"keep_order\":false");
assert_ne!(sorted, style);
assert!(needs(json!({"text": sorted})).is_empty());
}

/// `report.existingTemplate` imports a layout file as `layout.import` does, so a step of it
/// requires what a `layout.import` of the same file does (#3226), by `text` or by `data`. Every
/// `layout_*` fixture is walked, so a capability added with one and read for `layout.import`
Expand Down
112 changes: 112 additions & 0 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12759,6 +12759,118 @@ fn layer_group_classes_makes_one_legend_entry() {
assert!(s.run("layer.groupClasses", &json!({"layer": "Countries", "values": ["a", "b"]})).is_err());
}

/// `layer.orderClasses`: the classes keep the order given (#3319); one undo brings the sort back.
#[test]
fn layer_order_classes_keeps_the_order_given() {
let mut s = world();
s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap();
let renderer = |s: &Session| s.map().layer_by_name("Countries").unwrap().renderer.clone();
let legend = |s: &Session| renderer(s).legend().into_iter().map(|e| e.label).collect::<Vec<_>>();
let before = legend(&s);
assert_eq!(before[..2], ["Africa", "Antarctica"]);
let r = s.run("layer.orderClasses", &json!({"layer": "Countries", "values": ["Oceania", "Atlantis", "Asia"]})).unwrap();
assert_eq!(r["skipped"], json!(["Atlantis"]));
assert_eq!(r["classes"].as_array().unwrap()[..3], [json!("Oceania"), json!("Asia"), json!("Africa")]);
assert!(s.notices.iter().any(|n| n.text.contains("'Atlantis'")));
let ordered = legend(&s);
assert_eq!(ordered[..3], ["Oceania", "Asia", "Africa"]);
assert_eq!(ordered.last().map(String::as_str), Some("<all other values>"));
// Saved with the project.
let saved = serde_json::to_string(s.map()).unwrap();
let opened: rustgis_map::Map = serde_json::from_str(&saved).unwrap();
assert_eq!(opened.layer_by_name("Countries").unwrap().renderer, renderer(&s));
// Classify again: the classes keep their places.
s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap();
assert_eq!(legend(&s), ordered);
// One undo each.
s.run("edit.undo", &Value::Null).unwrap();
assert_eq!(legend(&s), ordered);
s.run("edit.undo", &Value::Null).unwrap();
assert_eq!(legend(&s), before);
s.run("edit.redo", &Value::Null).unwrap();
assert_eq!(legend(&s), ordered);
s.run("layer.orderClasses", &json!({"layer": "Countries", "by": "name"})).unwrap();
assert_eq!(legend(&s), before);
let rustgis_map::Renderer::Unique { keep_order, .. } = renderer(&s) else { panic!("unique renderer expected") };
assert!(!keep_order);
let sorted = renderer(&s);
for bad in [
json!({"layer": "Countries"}),
json!({"layer": "Countries", "values": []}),
json!({"layer": "Countries", "values": "Asia"}),
json!({"layer": "Countries", "values": [true]}),
json!({"layer": "Countries", "by": "count"}),
json!({"layer": "Countries", "values": ["Asia"], "by": "name"}),
] {
assert!(s.run("layer.orderClasses", &bad).is_err(), "{bad}");
}
assert_eq!(renderer(&s), sorted);
// An opacity No Fill saved stays with its class.
s.run("layer.classStyle", &json!({"layer": "Countries", "value": "Asia", "color": "#FF000080"})).unwrap();
s.run("layer.noFill", &json!({"layer": "Countries"})).unwrap();
s.run("layer.orderClasses", &json!({"layer": "Countries", "values": ["Oceania", "Asia"]})).unwrap();
s.run("layer.restoreFill", &json!({"layer": "Countries"})).unwrap();
let rustgis_map::Renderer::Unique { classes, .. } = renderer(&s) else { panic!("unique renderer expected") };
let alpha = |v: &str| classes.iter().find(|c| c.0 == v).map(|c| c.1.fill.a());
assert_eq!(alpha("Asia"), Some(0x80));
assert_ne!(alpha("Oceania"), Some(0x80));
// Only Unique Values has classes to order.
s.run("layer.symbology", &json!({"layer": "Countries", "type": "graduated", "field": "pop_est", "classes": 3})).unwrap();
assert!(s.run("layer.orderClasses", &json!({"layer": "Countries", "by": "name"})).is_err());
}

/// A call that names no class changes nothing: no order kept, no undo step (#3367 review).
#[test]
fn layer_order_classes_that_names_no_class_is_refused() {
let mut s = world();
s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap();
let renderer = |s: &Session| s.map().layer_by_name("Countries").unwrap().renderer.clone();
let before = renderer(&s);
let err = s.run("layer.orderClasses", &json!({"layer": "Countries", "values": ["Atlantis", "Lemuria"]})).unwrap_err();
assert!(err.contains("'Atlantis'") && err.contains("'Lemuria'"), "{err}");
assert_eq!(renderer(&s), before);
// A `by` that isn't text is refused, beside values too.
assert!(s.run("layer.orderClasses", &json!({"layer": "Countries", "values": ["Asia"], "by": 5})).is_err());
assert_eq!(renderer(&s), before);
// A value named twice is skipped once.
s.run("layer.orderClasses", &json!({"layer": "Countries", "values": ["Asia", "Atlantis", "Atlantis"]})).unwrap();
assert_eq!(s.notices.last().map(|n| n.text.matches("Atlantis").count()), Some(1));
}

/// A class order kept in a project or a saved style requires `unique-keep-order`, so an older
/// reader refuses it rather than open it and save the classes sorted again (#3367 review).
#[test]
fn a_kept_class_order_requires_a_reader_that_keeps_it() {
let mut s = world();
s.run("layer.symbology", &json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap();
let requires = |s: &mut Session| {
let (text, _) = s.project.saved_text(None).unwrap();
serde_json::from_str::<Value>(&text).unwrap().get("requires").cloned()
};
assert_eq!(requires(&mut s), None);
s.run("layer.orderClasses", &json!({"layer": "Countries", "values": ["Oceania"]})).unwrap();
assert_eq!(requires(&mut s), Some(json!(["unique-keep-order"])));
let (_, bytes) = crate::cmd::items::item_bytes(&mut s, "layer", &json!({"layer": "Countries"})).unwrap();
assert_eq!(serde_json::from_slice::<Value>(&bytes).unwrap()["requires"], json!(["unique-keep-order"]));
let item = crate::project::StyleItem {
name: "Ordered".into(),
geometry: rustgis_data::GeometryType::Polygon,
renderer: s.map().layer_by_name("Countries").unwrap().renderer.clone(),
labels: s.map().layer_by_name("Countries").unwrap().labels.clone(),
transparency: 0.0,
};
s.run("layer.orderClasses", &json!({"layer": "Countries", "by": "name"})).unwrap();
assert_eq!(requires(&mut s), None);
s.project.styles.push(item);
assert_eq!(requires(&mut s), Some(json!(["unique-keep-order"])));
// The fixture (`unique_keep_order.rgis`) reads back as saved, saying nothing.
let mut fixture = Project::from_json(include_str!("../../../schema/fixtures/unique_keep_order.rgis")).unwrap();
assert!(fixture.take_read_notices(&crate::project::ALL_PARTS).is_empty());
let legend: Vec<String> = fixture.maps[0].layers[0].renderer.legend().into_iter().map(|e| e.label).collect();
assert_eq!(legend, ["Alta", "Média", "Baixa", "<all other values>"]);
assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["unique-keep-order"]));
}

/// Grouping says how many classes lost strokes or fills of their own, shown or hidden by No Fill,
/// and nothing when none did.
#[test]
Expand Down
1 change: 1 addition & 0 deletions crates/map/src/arcgis_style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,6 +229,7 @@ fn unique(layer: &mut Layer, r: &Value, g: GeometryType, pictures: &mut Pictures
class_fills: BTreeMap::new(),
other_fills: Vec::new(),
expression: None,
keep_order: false,
};
layer.line_strokes = Vec::new();
}
Expand Down
1 change: 1 addition & 0 deletions crates/map/src/geolibre/style.rs
Original file line number Diff line number Diff line change
Expand Up @@ -65,6 +65,7 @@ pub fn apply(layer: &mut Layer, record: &Value, report: &mut Report) {
class_fills: Default::default(),
other_fills: Vec::new(),
expression: None,
keep_order: false,
};
} else if mode == "graduated" {
let mut pairs: Vec<_> =
Expand Down
Loading
Loading