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
79 changes: 70 additions & 9 deletions crates/engine/src/project_capabilities.rs
Original file line number Diff line number Diff line change
Expand Up @@ -306,23 +306,28 @@ 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
/// A saved `style.add`, `style.import`, `layer.addLayerFile`, `map.import` or `project.openText`
/// whose inline style, layer, map or project (`text` or `data`) keeps Unique Values classes in
/// their order (#3319): an older reader would take the renderer with the classes sorted. One read
/// from a `"path"` is a file, whose header requires what it uses. 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)
.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))),
"style.add" | "style.import" | "layer.addLayerFile" | "map.import" => {
crate::cmd::items::inline_text(params).ok().flatten().is_some_and(|t| text_keeps_class_order(&t))
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
}
// It opens its `text` only, whatever else the step holds.
"project.openText" => params.get("text").and_then(Value::as_str).is_some_and(text_keeps_class_order),
"script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_adds_kept_class_order)),
_ => false,
}
}

/// Whether saved JSON text holds a Unique Values renderer that keeps its class order.
fn text_keeps_class_order(text: &str) -> bool {
(text.contains("keep_order") || text.contains('\\')) && serde_json::from_str::<Value>(text).is_ok_and(|v| holds_kept_class_order(&v))
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
}

/// 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 @@ -1257,6 +1262,21 @@ fn removes_duplicate_labels(layer: &Layer) -> bool {
/// A Unique Values class order kept as listed (#3319).
const UNIQUE_KEEP_ORDER: &str = "unique-keep-order";

/// Whether saved JSON holds a Unique Values renderer that keeps its class order, wherever it is
/// (a style's, a layer's, a map's or a project's), in JSON text a string carries too (a saved
/// step's inline project).
fn holds_kept_class_order(v: &Value) -> bool {
match v {
Value::Object(o) => {
o.get("Unique").and_then(|u| u.get("keep_order")).and_then(Value::as_bool).unwrap_or(false)
|| o.values().any(holds_kept_class_order)
}
Value::Array(a) => a.iter().any(holds_kept_class_order),
Value::String(s) => s.contains("keep_order") && text_keeps_class_order(s),
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
_ => false,
}
}

/// 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 {
Expand Down Expand Up @@ -2041,6 +2061,47 @@ mod tests {
assert!(needs(json!({"text": sorted})).is_empty());
}

/// So does a saved `style.import`, `layer.addLayerFile`, `map.import` or `project.openText`
/// whose inline layer, map or project keeps one, a file without its header included: an older
/// reader would take the renderer with the classes sorted (#3367 and #3385 reviews).
#[test]
fn a_saved_import_of_a_kept_class_order_requires_it() {
let text = include_str!("../../../schema/fixtures/unique_keep_order.rgis");
let project: Value = serde_json::from_str(text).unwrap();
let layer = project["maps"][0]["layers"][0].to_string();
let map = project["maps"][0].to_string();
let needs = |tool: &str, text: &str| model_capabilities(&[ModelStep { tool: tool.into(), params: json!({"text": text}) }], None);
let imports = [
("style.import", text),
("style.import", &map),
("style.import", &layer),
("layer.addLayerFile", &layer),
("map.import", &map),
("map.import", text),
("project.openText", text),
];
for (tool, text) in imports {
assert_eq!(needs(tool, text), ["unique-keep-order"], "{tool} {}", &text[..40]);
assert!(needs(tool, &text.replace("\"keep_order\":true", "\"keep_order\":false")).is_empty(), "{tool}");
}
// `project.openText` opens its `text`, whatever `data` holds (#3385 review).
let sorted = text.replace("\"keep_order\":true", "\"keep_order\":false");
let data = {
use base64::Engine;
base64::engine::general_purpose::STANDARD.encode(&sorted)
};
let both = |text: &str| {
let params = json!({"text": text, "data": data});
model_capabilities(&[ModelStep { tool: "project.openText".into(), params }], None)
};
assert_eq!(both(text), ["unique-keep-order"]);
assert!(both(&sorted).is_empty());
// A project that opens another one from its own saved step requires what that one keeps.
let mut outer: Value = serde_json::from_str(&sorted).unwrap();
outer["tasks"] = json!([{"name": "Open", "steps": [{"title": "Open", "command": "project.openText", "params": {"text": text}}]}]);
assert_eq!(needs("project.openText", &outer.to_string()), ["unique-keep-order"]);
}

/// `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
26 changes: 24 additions & 2 deletions crates/map/src/symbology.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2183,10 +2183,17 @@ impl Renderer {
/// Recolours every class from a ramp, preserving each polygon fill's opacity.
pub fn apply_ramp(&mut self, ramp: Ramp, g: GeometryType) {
match self {
Renderer::Unique { classes, ramp: r, .. } => {
Renderer::Unique { classes, ramp: r, keep_order, .. } => {
let n = classes.len();
// Classes kept in an order of their own take the colour of their place by value,
// as Classify gave it and as `carry_edits_from` reads it (#3319).
let mut by_value: Vec<String> = classes.iter().map(|(k, _)| k.clone()).collect();
if *keep_order {
rustgis_data::value::sort_class_values(&mut by_value);
}
for (k, c) in classes.iter_mut().enumerate() {
c.1 = c.1.with_ramp_fill(ramp.pick(k, n), g);
let place = if *keep_order { by_value.iter().position(|v| *v == c.0).unwrap_or(k) } else { k };
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
c.1 = c.1.with_ramp_fill(ramp.pick(place, n), g);
}
*r = ramp;
}
Expand Down Expand Up @@ -5304,6 +5311,21 @@ mod tests {
let Renderer::Unique { classes, .. } = &again else { panic!("unique renderer expected") };
let fresh: Vec<Rgba> = (0..3).map(|k| Ramp::Ember.pick(k, 3)).collect();
assert_eq!(classes.iter().map(|c| c.1.fill).collect::<Vec<_>>(), fresh);

// Moved, then given another scheme: classifying again with a value more gives each class
// the scheme's colour at its place by value, none of them edited (#3367 review).
let mut old = ramped(&["a", "b"]);
old.order_classes(Some(&["b".into()])).unwrap();
old.apply_ramp(Ramp::Harbour, g);
let n = 3;
let classes: Vec<(&str, Symbol)> =
["a", "b", "c"].iter().enumerate().map(|(k, v)| (*v, base.with_fill(Ramp::Harbour.pick(k, n), g))).collect();
let mut again = unique(&classes, base, Ramp::Harbour);
again.carry_edits_from(&old, g);
let Renderer::Unique { classes, .. } = &again else { panic!("unique renderer expected") };
let by_value = |k| Ramp::Harbour.pick(k, n);
let got: Vec<(&str, Rgba)> = classes.iter().map(|c| (c.0.as_str(), c.1.fill)).collect();
assert_eq!(got, [("b", by_value(1)), ("a", by_value(0)), ("c", by_value(2))]);
}

/// Past [`MAX_UNIQUE`] values, the classes are the smallest numbers and the features past
Expand Down
129 changes: 125 additions & 4 deletions crates/ui-egui/src/panes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4883,9 +4883,14 @@ fn symbology(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens) {
}
ramp_picker_with(app, ui, ramp, t, !l.graphics);
ui.add_space(6.0);
ui.label(
egui::RichText::new(crate::i18n::fmt("{n} classes", &[("n", &classes.len().to_string())])).size(11.5).color(t.text_dim),
);
// The count, and on its line the order the list keeps (#3319), so the list starts
// where it did.
ui.horizontal(|ui| {
ui.label(
egui::RichText::new(crate::i18n::fmt("{n} classes", &[("n", &classes.len().to_string())])).size(11.5).color(t.text_dim),
);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| class_order_choice(app, ui, &l, t));
});
legend_list(app, ui, &l, t);
}
Renderer::Graduated { field, breaks, ramp, method, min, .. } => {
Expand Down Expand Up @@ -5501,6 +5506,43 @@ fn apply_class_color_drag(app: &mut RustGisApp, drag: ClassColorDrag) {
run_class_style(app, drag.params);
}

/// Unique Values' values in the order the class list shows them, each once (#3319).
fn listed_values(r: &Renderer) -> Vec<String> {
let Renderer::Unique { classes, .. } = r else { return Vec::new() };
let mut once = std::collections::HashSet::new();
r.class_order().into_iter().filter_map(|i| classes.get(i)).map(|(k, _)| k.clone()).filter(|k| once.insert(k.clone())).collect()
}

/// Unique Values classes listed by name (or number), or kept in the order given, which ▲/▼ in the
/// class list then change (#3319). Drawn right to left; nothing for fewer than two classes.
fn class_order_choice(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) {
let listed = listed_values(&l.renderer);
if listed.len() < 2 {
return;
}
let kept = matches!(&l.renderer, Renderer::Unique { keep_order: true, .. });
// As tall as the count beside it, so the pane below keeps its place.
ui.spacing_mut().button_padding.y = 0.0;
ui.spacing_mut().interact_size.y = 0.0;
let text = |s: &str| egui::RichText::new(s).size(11.5);
let as_listed = ui.selectable_label(kept, text(tl!("As listed")));
if as_listed.on_hover_text(tl!("Kept in the order you give them, with ▲ and ▼")).clicked() && !kept {
run_order_classes(app, json!({"layer": l.id, "values": listed}));
}
let by_name = ui.selectable_label(!kept, text(tl!("By name")));
if by_name.on_hover_text(tl!("Sorted by name, or by number when the values are numbers")).clicked() && kept {
run_order_classes(app, json!({"layer": l.id, "by": "name"}));
}
ui.label(egui::RichText::new(tl!("Order")).size(11.5).color(t.text));
}

/// Runs a layer.orderClasses from the pane (#3319); a refusal shows as a notice.
fn run_order_classes(app: &mut RustGisApp, params: Value) {
if let Err(e) = app.run("layer.orderClasses", params) {
app.session.notify(e, true);
}
}

/// Runs a layer.classStyle from the pane; a refusal (the class is gone, say) shows as a notice.
fn run_class_style(app: &mut RustGisApp, params: Value) {
if let Err(e) = app.run("layer.classStyle", params) {
Expand All @@ -5511,7 +5553,8 @@ fn run_class_style(app: &mut RustGisApp, params: Value) {
/// The renderer's legend rows. A Unique Values or Graduated Colors class can be edited in place
/// (#314): its colour button and its legend label, which applies when the field loses focus and
/// goes back to the value or range when cleared. Unique Values classes can also be ticked and,
/// two or more of them, grouped into one legend entry (#3308).
/// two or more of them, grouped into one legend entry (#3308), and, kept as listed, moved with
/// ▲/▼ ([`class_order_choice`], #3319).
fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) {
// Each row's class, as layer.classStyle names it (and as the renderer does); none for
// renderers without classes.
Expand All @@ -5533,6 +5576,10 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) {
// Unique Values legends sort their classes (by value or by label): row i shows class `order[i]`,
// and the rows past them (`<all other values>`) keep their place.
let order = l.renderer.class_order();
// Unique Values classes sorted by name (or number), or kept in the order given (#3319):
// the values as shown, each once, are what a move sends.
let kept = matches!(&l.renderer, Renderer::Unique { keep_order: true, .. });
let listed = listed_values(&l.renderer);
// As many classes as can be drawn from an expression or a QGIS rule style
// (MAX_EXPRESSION_CLASSES), then Unique Values' `<all other values>`, the legend's
// last row, whatever their number. A categorized style import can bring more: how
Expand Down Expand Up @@ -5590,6 +5637,25 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) {
if on {
ticked.push(v.clone());
}
// As listed, a class moves one place up or down: one command, one undo step.
if kept && let Some(at) = listed.iter().position(|k| k == v) {
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
let mut moved = None;
if ui.add_enabled(at > 0, egui::Button::new("▲").small()).on_hover_text(tl!("Move up")).clicked() {
moved = Some(at - 1);
}
if ui
.add_enabled(at + 1 < listed.len(), egui::Button::new("▼").small())
Comment thread
elpidioassinaturas marked this conversation as resolved.
Resolved
.on_hover_text(tl!("Move down"))
.clicked()
{
moved = Some(at + 1);
}
if let Some(to) = moved {
let mut values = listed.clone();
values.swap(at, to);
run_order_classes(app, json!({"layer": l.id, "values": values}));
}
}
}
// A fill No Fill hides shows the opacity Restore Fill gives back, so a colour
// picked here is drawn (#2308).
Expand Down Expand Up @@ -10212,6 +10278,61 @@ pub(crate) mod tests {
assert!(h.query_by_label("Group").is_none(), "the ticks are cleared");
}

/// The class list keeps Unique Values classes as listed, moves one with ▲/▼, and sorts them by
/// name again: one command and one undo step each (#3319).
#[test]
fn the_class_list_keeps_and_moves_the_classes_as_listed() {
use egui_kittest::kittest::Queryable;

let mut app = RustGisApp::with_sample();
app.run("layer.symbology", json!({"layer": "Countries", "type": "unique", "field": "continent"})).unwrap();
let id = layer(&app, "Countries");
let labels =
|app: &RustGisApp| app.session.map().layer(id).unwrap().renderer.legend().into_iter().map(|e| e.label).collect::<Vec<_>>();
let kept = |app: &RustGisApp| matches!(app.session.map().layer(id).unwrap().renderer, Renderer::Unique { keep_order: true, .. });
let sorted = labels(&app);
// The app's fonts draw ▲ and ▼.
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(vec2(600.0, 900.0)).with_max_steps(8).build_ui_state(
move |ui, app: &mut RustGisApp| {
if !fonts {
crate::theme::install_fonts(ui.ctx(), &[], None);
fonts = true;
return;
}
let layer = app.session.map().layer(id).unwrap().clone();
ui.horizontal(|ui| class_order_choice(app, ui, &layer, &Tokens::light()));
legend_list(app, ui, &layer, &Tokens::light());
},
app,
);
h.run_steps(2);
assert!(h.query_by_label("▲").is_none(), "sorted by name: nothing to move");
let depth = h.state().session.undo_depth();
h.get_by_label("As listed").click();
h.run_steps(2);
assert!(kept(h.state()));
assert_eq!(labels(h.state()), sorted, "the order shown is the one kept");
assert_eq!(h.state().session.undo_depth(), depth + 1);
// One ▲ and one ▼ on each class; the first can't go up, the last can't go down.
let classes = sorted.len() - 1;
assert_eq!(h.query_all_by_label("▼").count(), classes);
h.query_all_by_label("▼").next().unwrap().click();
h.run_steps(2);
let mut moved = sorted.clone();
moved.swap(0, 1);
assert_eq!(labels(h.state()), moved);
assert_eq!(h.state().session.undo_depth(), depth + 2);
h.query_all_by_label("▲").nth(1).unwrap().click();
h.run_steps(2);
assert_eq!(labels(h.state()), sorted, "moved back up");
h.get_by_label("By name").click();
h.run_steps(2);
assert!(!kept(h.state()));
assert!(h.query_by_label("▲").is_none());
assert_eq!(labels(h.state()), sorted);
}

/// Layer ids repeat across maps and projects: the ticks made on one layer aren't another's.
#[test]
fn class_ticks_stay_with_their_map() {
Expand Down
4 changes: 2 additions & 2 deletions docs/maintaining.md
Original file line number Diff line number Diff line change
Expand Up @@ -119,8 +119,8 @@ diagram cut to a circle or to polygons), `terrain-block-polygon` (one cut to pol
`layer-raster-mask` (a layer masked by a raster's values, stored as `raster_mask` or set by a saved
`layer.mask` step whose `"mask"` is an object),
`unique-keep-order` (Unique Values classes kept in the order they are listed in, stored as
`keep_order` on a layer or in a saved style, or added by a saved `style.add` step whose style
has it),
`keep_order` on a layer or in a saved style, or brought by a saved `style.add`, `style.import`,
`layer.addLayerFile`, `map.import` or `project.openText` step whose inline text has it),
`shaded-relief-effects` (cast shadows, sky visibility, fill light or rock colour),
`shaded-relief-light` (a Shaded Relief's ambient or balanced light),
`shaded-relief-shadow-softness` (a softness stored for a Shaded Relief's cast shadows, or set by a saved step;
Expand Down
Loading
Loading