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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12495,7 +12495,7 @@ fn layer_class_style_edits_one_class() {
let rustgis_map::Renderer::Unique { classes, .. } = &r else { panic!("unique renderer expected") };
let i = classes.iter().position(|(k, _)| *k == value).unwrap();
let row = r.class_order().into_iter().position(|o| o == i).unwrap();
r.legend().into_iter().nth(row).unwrap()
r.class_entries().into_iter().nth(row).unwrap()
};
let r = s.run("layer.classStyle", &json!({"layer": "Countries", "value": value, "color": "#123456", "label": "Rich"})).unwrap();
assert_eq!(r["label"], "Rich");
Expand Down
2 changes: 2 additions & 0 deletions crates/map/src/qgis/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -341,6 +341,8 @@ fn merged_categories_and_dashes_carry_over() {
let Some(Renderer::Unique { classes, class_strokes, class_labels, other, .. }) = &s.renderer else { panic!("{:?}", s.renderer) };
let values: Vec<&str> = classes.iter().map(|c| c.0.as_str()).collect();
assert_eq!(values, ["a", "c", "d"], "both values of the merged category, not \"all others\"");
let listed: Vec<String> = s.renderer.as_ref().unwrap().legend().into_iter().map(|e| e.label).collect();
assert_eq!(listed, ["a", "c or d", crate::symbology::OTHER_VALUES], "one legend row for the merged category");
assert_eq!((classes[1].1.stroke, classes[2].1.stroke), (Rgba::rgb(20, 0, 0), Rgba::rgb(20, 0, 0)));
assert_eq!(other.stroke, Rgba::rgb(30, 0, 0));
assert_eq!(class_labels.get("c").map(String::as_str), Some("c or d"));
Expand Down
174 changes: 168 additions & 6 deletions crates/map/src/symbology.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1033,6 +1033,36 @@ impl LegendEntry {
}
}

/// `entries` with the classes that share their label, symbol, strokes and fills put in one row, in
/// the first one's place, with the features of all of them counted (#3298): nothing in a legend
/// tells them apart. `<all other values>` keeps its own row.
fn merge_alike(entries: Vec<LegendEntry>) -> Vec<LegendEntry> {
let mut merged: Vec<LegendEntry> = Vec::with_capacity(entries.len());
// The rows kept so far under each label and symbol: an imported style can bring thousands of
// classes, and only rows that share these are compared (their stacked strokes and fills then).
let mut by_look = std::collections::HashMap::<_, Vec<usize>>::new();
// A float's bits, with one zero: 0.0 and -0.0 compare equal, so they must share a bucket.
let bits = |x: f32| if x == 0.0 { 0 } else { x.to_bits() };
for e in entries {
if !e.fallback {
let s = e.symbol;
let look = (e.label.clone(), s.fill, s.stroke, bits(s.stroke_width), bits(s.size), s.marker);
let kept = by_look.entry(look).or_default();
let alike = kept
.iter()
.copied()
.find(|&i| merged.get(i).is_some_and(|m| m.symbol == e.symbol && m.strokes == e.strokes && m.fills == e.fills));
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
if let Some(m) = alike.and_then(|i| merged.get_mut(i)) {
m.count = m.count.zip(e.count).map(|(a, b)| a.saturating_add(b));
continue;
}
kept.push(merged.len());
}
merged.push(e);
}
merged
}

/// 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
Expand Down Expand Up @@ -1816,7 +1846,7 @@ impl Renderer {
count: None,
});
}
v
merge_alike(v)
}

/// Whether Unique Values' fallback draws something on `ds`; false for the other renderers.
Expand Down Expand Up @@ -1908,11 +1938,11 @@ impl Renderer {
/// Unique Values by expression too large to class ([`Renderer::too_many_to_class`]). `ds` gives
/// the geometry family alone.
pub(crate) fn counted_entries(&self, ds: &Dataset, counts: Option<&[u64]>, all: bool) -> Vec<LegendEntry> {
let mut entries = self.legend();
let mut entries = self.class_entries();
match self {
Renderer::Unique { classes, .. } => {
if let Some(counts) = counts {
// `legend()` lists the classes in `class_order`, then the fallback: so do these.
// `class_entries()` lists the classes in `class_order`, then the fallback: so do these.
let slots = self.class_order().into_iter().chain([classes.len()]);
for (e, slot) in entries.iter_mut().zip(slots) {
e.count = Some(counts.get(slot).copied().unwrap_or(0));
Expand All @@ -1924,6 +1954,9 @@ impl Renderer {
let visible = self.fallback_draws(ds);
entries.retain(|e| e.count != Some(0) && (!e.fallback || visible));
}
// After the rows with no feature are out: a merged row stands where the first
// listed one does.
entries = merge_alike(entries);
}
Renderer::Graduated { .. } => {
if let Some(counts) = counts {
Expand Down Expand Up @@ -1975,8 +2008,18 @@ impl Renderer {
}

/// Every row of its legend, whatever the features: the classes, then a Unique Values'
/// `<all other values>`; none for a single symbol.
/// `<all other values>`; none for a single symbol. Unique Values classes that look alike and
/// share a label are one row ([`merge_alike`]).
pub fn legend(&self) -> Vec<LegendEntry> {
match self {
Renderer::Unique { .. } => merge_alike(self.class_entries()),
_ => self.class_entries(),
}
}

/// [`Renderer::legend`] with a row for each class, as an editor of the classes lists them:
/// Unique Values' in [`Renderer::class_order`].
pub fn class_entries(&self) -> Vec<LegendEntry> {
match self {
Renderer::Single(_) => Vec::new(),
Renderer::Unique {
Expand Down Expand Up @@ -2127,7 +2170,8 @@ impl Renderer {
/// Sets one class's colour, outline colour and legend label (#314). A line class takes the
/// colour as its line colour; a polygon class gets a matching outline unless `outline` names
/// one. Colours include their alpha unless `preserve_fill_alpha` requests the polygon's
/// legacy translucency for RGB-only input. Returns the class's legend row as it now is.
/// legacy translucency for RGB-only input. Returns the class's row as it now is
/// ([`Renderer::class_entries`]: its own, whatever a legend lists it with).
pub fn set_class_style(&mut self, class: &ClassRef, style: &ClassStyle, g: GeometryType) -> Result<LegendEntry, String> {
let label = style.label.as_deref().map(normalize_label);
let restyle = |s: &mut Symbol| {
Expand Down Expand Up @@ -2195,7 +2239,7 @@ impl Renderer {
(Renderer::Graduated { .. }, _) => return Err("Graduated Colors classes are numbered from 0, the lowest".into()),
_ => return Err("only Unique Values and Graduated Colors have classes to style".into()),
};
self.legend().into_iter().nth(row).ok_or_else(|| "the class has no legend row".into())
self.class_entries().into_iter().nth(row).ok_or_else(|| "the class has no legend row".into())
}

/// Carries hand-made class edits over from `old` when the symbology is applied again (#314).
Expand Down Expand Up @@ -5170,6 +5214,124 @@ mod tests {
assert_eq!(keys, vec!["2", "1000"]);
}

/// Polygons whose field `g` holds `values`.
fn valued(values: &[&str]) -> Dataset {
let mut d = Dataset::new("t", GeometryType::Polygon, vec![Field::new("g", FieldType::Text)]);
for g in values {
d.push(None, vec![Value::Text((*g).into())]);
}
d
}

/// `unique` with each class's legend label set by hand.
fn labelled(classes: &[(&str, Symbol, &str)], other: Symbol) -> Renderer {
let pairs: Vec<(&str, Symbol)> = classes.iter().map(|(k, s, _)| (*k, *s)).collect();
let mut r = unique(&pairs, other, Ramp::Ember);
if let Renderer::Unique { class_labels, .. } = &mut r {
class_labels.extend(classes.iter().map(|(k, _, l)| (k.to_string(), l.to_string())));
}
r
}

fn rows(entries: Vec<LegendEntry>) -> Vec<(String, Option<u64>)> {
entries.into_iter().map(|e| (e.label, e.count)).collect()
}

fn named(labels: &[&str]) -> Vec<(String, Option<u64>)> {
labels.iter().map(|l| (l.to_string(), None)).collect()
}

/// Classes that share their label and everything drawn are one legend row (#3298).
#[test]
fn classes_that_look_alike_and_share_a_label_are_one_legend_row() {
let s = |c| Symbol::default_for(GeometryType::Polygon, c);
let r = labelled(&[("c", s(0), "c or d"), ("d", s(0), "c or d")], s(3));
assert_eq!(rows(r.legend()), named(&["c or d", OTHER_VALUES]));
assert_eq!(rows(r.legend_for(&valued(&["c", "d"]), &[])), named(&["c or d"]));
// Only the later value has features.
assert_eq!(rows(r.legend_for(&valued(&["d"]), &[])), named(&["c or d"]));
// Its count is that of all its values, with and without every class listed.
let d = valued(&["c", "d", "d", "zz"]);
for all in [false, true] {
let counted = rows(r.counted_entries(&d, Some(&[1, 2, 1]), all));
assert_eq!(counted, [("c or d".into(), Some(3)), (OTHER_VALUES.into(), Some(1))], "all {all}");
}
assert_eq!(rows(r.counted_entries(&d, Some(&[0, 2, 0]), false)), [("c or d".into(), Some(2))]);
// Too large to count: still one row, with no number.
assert_eq!(rows(r.counted_entries(&d, None, true)), named(&["c or d", OTHER_VALUES]));
}

/// Any difference in label, symbol, stacked strokes or fills keeps two rows.
#[test]
fn classes_that_differ_keep_their_own_legend_rows() {
let s = |c| Symbol::default_for(GeometryType::Polygon, c);
let colours = labelled(&[("c", s(0), "x"), ("d", s(1), "x")], s(3));
assert_eq!(rows(colours.legend()), named(&["x", "x", OTHER_VALUES]));
let names = labelled(&[("c", s(0), "c"), ("d", s(0), "d")], s(3));
assert_eq!(rows(names.legend()), named(&["c", "d", OTHER_VALUES]));
let base = labelled(&[("c", s(0), "x"), ("d", s(0), "x")], s(3));
let mut stroked = base.clone();
if let Renderer::Unique { class_strokes, .. } = &mut stroked {
class_strokes.insert("d".into(), vec![LineStroke::default()]);
}
assert_eq!(rows(stroked.legend()), named(&["x", "x", OTHER_VALUES]));
let mut filled = base;
if let Renderer::Unique { class_fills, .. } = &mut filled {
class_fills.insert("d".into(), vec![FillLayer::default()]);
}
assert_eq!(rows(filled.legend()), named(&["x", "x", OTHER_VALUES]));
}

/// The row takes the first one's place, and `<all other values>` stays apart.
#[test]
fn a_merged_legend_row_keeps_the_first_place_and_leaves_other_values_apart() {
let s = |c| Symbol::default_for(GeometryType::Polygon, c);
let r = labelled(&[("1", s(0), "odd"), ("3", s(1), "three"), ("5", s(0), "odd")], s(2));
assert_eq!(rows(r.legend()), named(&["odd", "three", OTHER_VALUES]));
// With no feature in the first of them, the row is the next one's, in its place.
let r = labelled(&[("1", s(0), "odd"), ("3", s(1), "three"), ("5", s(0), "odd")], s(2));
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
let counted = rows(r.counted_entries(&valued(&[]), Some(&[0, 1, 2, 0]), false));
assert_eq!(counted, [("three".into(), Some(1)), ("odd".into(), Some(2))]);
// 0.0 and -0.0 are one width and one size.
let width = Symbol { stroke_width: 0.0, ..s(0) };
let size = Symbol { size: 0.0, ..s(0) };
for (a, b) in [(width, Symbol { stroke_width: -0.0, ..width }), (size, Symbol { size: -0.0, ..size })] {
let r = labelled(&[("c", a, "x"), ("d", b, "x")], s(3));
assert_eq!(rows(r.legend()), named(&["x", OTHER_VALUES]), "{b:?}");
}
let r = labelled(&[("c", s(2), OTHER_VALUES)], s(2));
assert_eq!(rows(r.legend()), named(&[OTHER_VALUES, OTHER_VALUES]));
}

/// The class editor and `layer.classStyle` still see each value on its own.
#[test]
fn every_class_of_a_merged_row_is_listed_and_styled_on_its_own() {
let s = |c| Symbol::default_for(GeometryType::Polygon, c);
let mut r = labelled(&[("c", s(0), "c or d"), ("d", s(0), "c or d")], s(3));
assert_eq!(rows(r.class_entries()), named(&["c or d", "c or d", OTHER_VALUES]));
let style = ClassStyle { label: Some("D".into()), ..Default::default() };
let row = r.set_class_style(&ClassRef::Value("d".into()), &style, GeometryType::Polygon).unwrap();
assert_eq!(row.label, "D");
assert_eq!(rows(r.legend()), named(&["c or d", "D", OTHER_VALUES]));
// `<all other values>` comes after every class, merged or not.
let mut r = labelled(&[("c", s(0), "c or d"), ("d", s(0), "c or d")], s(3));
let style = ClassStyle { label: Some("Rest".into()), ..Default::default() };
let row = r.set_class_style(&ClassRef::Other, &style, GeometryType::Polygon).unwrap();
assert_eq!((row.label.as_str(), row.fallback), ("Rest", true));
}

/// Graduated Colors' ranges are never merged.
#[test]
fn graduated_ranges_that_look_alike_keep_their_rows() {
let s = Symbol::default_for(GeometryType::Polygon, 0);
let mut r = graduated(&[5.0, 10.0], &[s, s], Ramp::Ember);
if let Renderer::Graduated { class_labels, .. } = &mut r {
class_labels.extend([(0, "x".to_string()), (1, "x".to_string())]);
}
assert_eq!(rows(r.legend()), named(&["x", "x"]));
assert_eq!(r.class_entries(), r.legend());
}

fn unique(classes: &[(&str, Symbol)], other: Symbol, ramp: Ramp) -> Renderer {
Renderer::Unique {
field: "g".into(),
Expand Down
17 changes: 17 additions & 0 deletions crates/render/src/layout/legend/count_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,23 @@ fn a_streamed_layers_classes_count_the_whole_source() {
}
}

/// Classes that look alike and share a label are one row, counting the features of all of them
/// (#3298), on a layer held whole or read in place.
#[test]
fn classes_listed_as_one_count_all_their_features() {
for streamed in [false, true] {
let mut map = classed(&VALUES);
if let Renderer::Unique { class_labels, .. } = &mut map.layers[0].renderer {
class_labels.extend([("a".to_string(), "ab".to_string()), ("b".to_string(), "ab".to_string())]);
}
if streamed {
in_place(&mut map.layers[0], FILE);
}
assert_eq!(counted(&mut map, false, false), ["pts", "ab (5)", "<all other values> (1)"], "streamed {streamed}");
assert_eq!(counted(&mut map, true, false), ["pts", "ab (5)", "c (0)", "<all other values> (1)"], "streamed {streamed}");
}
}

#[test]
fn a_streamed_layer_of_one_symbol_counts_the_whole_source() {
let mut map = classed(&VALUES);
Expand Down
36 changes: 35 additions & 1 deletion crates/ui-egui/src/panes.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5504,7 +5504,8 @@ fn legend_list(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, t: &Tokens) {
ui,
|ui| {
ui.set_width(ui.available_width());
let legend = interface_legend(&l.renderer, l.renderer.legend());
// A row for each class: values that a legend lists as one are edited each on its own.
let legend = interface_legend(&l.renderer, l.renderer.class_entries());
// 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();
Expand Down Expand Up @@ -10013,6 +10014,39 @@ pub(crate) mod tests {
assert!(h.query_by_label_contains("1 more class isn't listed").is_some());
}

/// Values a legend lists as one entry keep a row each in the class editor (#3298).
#[test]
fn the_class_editor_lists_each_value_of_a_merged_legend_row() {
use egui::accesskit::Role;
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 mut classes_len = 0;
if let Some(l) = app.session.map_mut().layer_mut(id)
&& let Renderer::Unique { classes, class_labels, .. } = &mut l.renderer
{
let first = classes[0].1;
for (value, symbol) in classes.iter_mut() {
*symbol = first;
class_labels.insert(value.clone(), "Land".into());
}
classes_len = classes.len();
}
assert!(classes_len > 1);
assert_eq!(app.session.map().layer(id).unwrap().renderer.legend().len(), 2, "one legend row and the other values");
let mut h = egui_kittest::Harness::builder().with_size(vec2(600.0, 600.0)).with_max_steps(8).build_ui_state(
move |ui, app: &mut RustGisApp| {
let layer = app.session.map().layer(id).unwrap().clone();
legend_list(app, ui, &layer, &Tokens::light());
},
app,
);
h.run_steps(2);
assert_eq!(h.query_all_by_role(Role::TextInput).count(), classes_len + 1);
}

/// Editing opacity must not turn a transparent red or a near-transparent colour into black.
/// Exercise the real class picker and command, including one-step undo after the edit.
#[test]
Expand Down
4 changes: 3 additions & 1 deletion docs/user-guide/cartography.md
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,9 @@ Select a layer in Layers and open **Style › Symbology** (or the Symbology pane
(by character, so `B` before `a`). Features with a value past them draw as
`<all other values>`, and a notice says how many and in which order the classes were taken. The
legend lists the classes by number when every class is a number, a class renamed by hand in its
value's place, and otherwise by label without regard to case. The Layers pane and layout
value's place, and otherwise by label without regard to case. Classes that share their label,
symbol, stacked strokes and stacked fills are one legend entry, in the place of the first of them
listed, with the features of all of them counted. The Layers pane and layout
legends list only the classes that drawn features use (after the definition query and display filters);
`<all other values>` appears only when a drawn feature falls outside the classes and its symbol
is not fully transparent. A layout legend can leave it out with **Hide other values** (see
Expand Down
Loading