From 32a8b4893e0e9726b56941a81aa43972657de0da Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 07:12:22 -0500 Subject: [PATCH 1/6] feat(labels): a label class removes duplicate labels of the same text within a distance (#2847) --- crates/engine/command-surface.txt | 2 +- crates/engine/src/cmd/labels.rs | 30 ++++- crates/engine/src/project.rs | 1 + crates/engine/src/project_capabilities.rs | 31 +++++- crates/engine/src/project_label_losses.rs | 19 +++- crates/engine/src/tests.rs | 124 +++++++++++++++++++++ crates/map/src/qgis/labels.rs | 1 + crates/map/src/symbology.rs | 23 ++++ crates/render/src/lib.rs | 129 ++++++++++++++++++++++ crates/tiles/src/symbols.rs | 5 + crates/ui-egui/src/labelpane.rs | 97 +++++++++++++++- docs/maintaining.md | 4 + docs/user-guide/cartography.md | 12 +- schema/fixtures/label_duplicates.rgis | 1 + schema/project.schema.json | 6 +- 15 files changed, 473 insertions(+), 12 deletions(-) create mode 100644 schema/fixtures/label_duplicates.rgis diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index a2d195a995..a015192392 100644 --- a/crates/engine/command-surface.txt +++ b/crates/engine/command-surface.txt @@ -207,7 +207,7 @@ labels.fonts search? labels.lock on? labels.move layer? class? feature to labels.pause on? -labels.placement layer? class? position? to? side? offset? repeat? lineOffset? otherPositions? fit? abbreviations? showAll? weight? clearance? callout? guide? +labels.placement layer? class? position? to? side? offset? repeat? lineOffset? otherPositions? fit? abbreviations? showAll? weight? clearance? removeDuplicates? callout? guide? labels.resetMoved layer? class? all? labels.scaleRange layer? class? min? max? clear? labels.style layer? class? size? color? halo? haloColor? haloWidth? spacing? stretch? bold? italic? font? background? wrapChar? wrapLength? lineAlign? diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index 58338f2696..fb1320bcde 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -143,14 +143,14 @@ pub fn commands() -> Vec { // A position that isn't a placement name is refused, not dropped for the others (null: // none, as for the other keys). None if p.get("position").is_some_and(|v| !v.is_null()) => return Err("position must be a placement name".into()), - None if ["offset", "repeat", "lineOffset", "otherPositions", "showAll", "weight", "clearance", "callout", "to", "side", "fit", "abbreviations", "guide"] + None if ["offset", "repeat", "lineOffset", "otherPositions", "showAll", "weight", "clearance", "removeDuplicates", "callout", "to", "side", "fit", "abbreviations", "guide"] .iter() .any(|k| p.get(k).is_some()) => { None } None => { - return Err("position is required (or an offset, a repeat, a lineOffset, otherPositions, showAll, a weight, a clearance, a callout, to, side, fit, abbreviations or a guide)".into()); + return Err("position is required (or an offset, a repeat, a lineOffset, otherPositions, showAll, a weight, a clearance, removeDuplicates, a callout, to, side, fit, abbreviations or a guide)".into()); } }; // Along a line placed curved, the label fitted to the room the line gives (#2265). @@ -222,6 +222,15 @@ pub fn commands() -> Vec { }; let clearance_asked = clearance.filter(|c| !rustgis_map::symbology::LABEL_CLEARANCE.contains(c)); let clearance = clearance.map(rustgis_map::symbology::label_clearance); + // Duplicates removed within so far (#2847): 1 to 2000 points, false or null off. A + // number out of range is held to it, and says so. + let remove_duplicates = match p.get("removeDuplicates") { + None => None, + Some(Value::Null | Value::Bool(false)) => Some(None), + Some(v) => Some(Some(number(v).ok_or("removeDuplicates must be a number of points from 1 to 2000 (false or null: off)")?)), + }; + let duplicates_asked = remove_duplicates.flatten().filter(|d| !rustgis_map::symbology::LABEL_DUPLICATES.contains(d)); + let remove_duplicates = remove_duplicates.map(|d| d.and_then(rustgis_map::symbology::label_duplicates)); // Every label shown, over the others where they crowd. let show_all = match p.get("showAll") { None => None, @@ -311,6 +320,9 @@ pub fn commands() -> Vec { if let Some(r) = clearance { c.clearance = r; } + if let Some(d) = remove_duplicates { + c.remove_duplicates = d; + } if let Some(f) = fit { c.fit = f; } @@ -400,12 +412,24 @@ pub fn commands() -> Vec { false, ); } + if let Some(asked) = duplicates_asked { + let name = s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(); + let kept = rustgis_map::symbology::label_duplicates(asked).unwrap_or_default(); + let asked = if asked.abs() < 1e6 { asked.to_string() } else { format!("{asked:e}") }; + s.notify_text( + NoticeText::format( + "{name}: removeDuplicates {asked} adjusted to {kept} (duplicates are removed within 1 to 2000 points)", + [("name", name.into()), ("asked", asked.into()), ("kept", kept.to_string().into())], + ), + false, + ); + } Ok(done) }).roles(&[]).effects(crate::policy::Effects::NONE) .inputs(super::Inputs::single_layer) .when(need_feature_layer) .params( - r#"{"layer"?, "class"?: name (none: the Default class, by whatever name it has), "position"?: "auto"|"center"|"above"|"below"|"left"|"right"|"aboveRight"|"aboveLeft"|"belowRight"|"belowLeft"|"parallel" (along a line, straight)|"curved" (along a line, following its bends)|"perpendicular" (a point's, square to the nearest line of `to`, starting at the point; none that near: as auto) (required without offset, repeat, lineOffset, otherPositions, showAll, weight, clearance, callout, to, side, fit, abbreviations or guide), "to"?: {"layer": a line or polygon layer's name, "within"?: points (1 to 500; 20)} | null, "side"?: "away" (the side of the line the point isn't on; the default)|"left"|"right" (as the line runs), "offset"?: [right, down] points (-200 to 200 each) the label moves from where its position puts it ([0, 0]: none; perpendicular: [out along the normal, down as the text reads]; a label along a line isn't moved), "repeat"?: points (10 to 10000) between a line's labels, spaced out from the one at its middle, at most 32 a line (0 or null: the one at its middle; parallel and curved only), "lineOffset"?: points (-200 to 200) between a line and its label's nearest edge, above the line as the text reads, negative below it (0 or null: on the line; parallel and curved only), "otherPositions"?: bool (a label whose place is taken tries others: a point's round the point, corners first; a line's along the line, nearest its middle first, placed parallel or curved without a repeat; true is refused for any other line label and on polygons), "fit"?: "auto"|"off" (curved along a line: "auto" abbreviates a name that can't follow the line, sets one longer than a third of it on its straightest stretch, and spreads one over labels.style's stretch of a line more than three times its length; "off" or null: as placed), "abbreviations"?: {word: abbreviation} (whole words a fitted label puts short, ignoring case, over the built-in English, Portuguese and Spanish list, as {"Creek": "Cr.", "Córrego": "Cór."}; null or {}: the built-in list alone), "showAll"?: bool (every label drawn, over the others where they crowd), "weight"?: 0 to 10 (where labels compete for a place, the heavier class's wins, whatever its layer's place; equal weights: the layer above, then the class listed first; a fraction rounded; null: 5), "clearance"?: points (0 to 100: the room the class's labels keep free of other labels, two labels keeping both their clearances apart; null: 2), "callout"?: true|false|points (5 to 500: a label crowded off its spot moves to a free one nearby, a line drawn back to its feature at most this long; true keeps its length, or 40; false, 0 or null: none; not labels along a line or with an icon), "guide"?: {"layer": a line layer's name (as ridge or valley lines; not drawn by this), "field"?: a field both layers have} | null (points and polygons, not perpendicular ones: each label curved along its guide line, the one with the feature's value in field, else the longest in view under the label inside its polygon, or the nearest to its point within the text's width; a feature with none its text fits along is labelled as without a guide; null: none)}"#, + r#"{"layer"?, "class"?: name (none: the Default class, by whatever name it has), "position"?: "auto"|"center"|"above"|"below"|"left"|"right"|"aboveRight"|"aboveLeft"|"belowRight"|"belowLeft"|"parallel" (along a line, straight)|"curved" (along a line, following its bends)|"perpendicular" (a point's, square to the nearest line of `to`, starting at the point; none that near: as auto) (required without offset, repeat, lineOffset, otherPositions, showAll, weight, clearance, removeDuplicates, callout, to, side, fit, abbreviations or guide), "to"?: {"layer": a line or polygon layer's name, "within"?: points (1 to 500; 20)} | null, "side"?: "away" (the side of the line the point isn't on; the default)|"left"|"right" (as the line runs), "offset"?: [right, down] points (-200 to 200 each) the label moves from where its position puts it ([0, 0]: none; perpendicular: [out along the normal, down as the text reads]; a label along a line isn't moved), "repeat"?: points (10 to 10000) between a line's labels, spaced out from the one at its middle, at most 32 a line (0 or null: the one at its middle; parallel and curved only), "lineOffset"?: points (-200 to 200) between a line and its label's nearest edge, above the line as the text reads, negative below it (0 or null: on the line; parallel and curved only), "otherPositions"?: bool (a label whose place is taken tries others: a point's round the point, corners first; a line's along the line, nearest its middle first, placed parallel or curved without a repeat; true is refused for any other line label and on polygons), "fit"?: "auto"|"off" (curved along a line: "auto" abbreviates a name that can't follow the line, sets one longer than a third of it on its straightest stretch, and spreads one over labels.style's stretch of a line more than three times its length; "off" or null: as placed), "abbreviations"?: {word: abbreviation} (whole words a fitted label puts short, ignoring case, over the built-in English, Portuguese and Spanish list, as {"Creek": "Cr.", "Córrego": "Cór."}; null or {}: the built-in list alone), "showAll"?: bool (every label drawn, over the others where they crowd), "weight"?: 0 to 10 (where labels compete for a place, the heavier class's wins, whatever its layer's place; equal weights: the layer above, then the class listed first; a fraction rounded; null: 5), "clearance"?: points (0 to 100: the room the class's labels keep free of other labels, two labels keeping both their clearances apart; null: 2), "removeDuplicates"?: points (1 to 2000: a label is left out within this distance of one placed before it for another feature of its layer and class with the same text; a label moved by hand always shows; false or null: off), "callout"?: true|false|points (5 to 500: a label crowded off its spot moves to a free one nearby, a line drawn back to its feature at most this long; true keeps its length, or 40; false, 0 or null: none; not labels along a line or with an icon), "guide"?: {"layer": a line layer's name (as ridge or valley lines; not drawn by this), "field"?: a field both layers have} | null (points and polygons, not perpendicular ones: each label curved along its guide line, the one with the feature's value in field, else the longest in view under the label inside its polygon, or the nearest to its point within the text's width; a feature with none its text fits along is labelled as without a guide; null: none)}"#, ), // Labels moved by hand (the Move Label tool, as QGIS's): kept by their feature's id. C::new("labels.move", "Move Label", "Labeling › Label Placement", |s, p| { diff --git a/crates/engine/src/project.rs b/crates/engine/src/project.rs index 90993f023d..77b370e3ff 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -115,6 +115,7 @@ pub const CAPABILITIES: &[&str] = &[ PROJECT_CRS, "dggs-system", "label-clearance", + "label-duplicates", ]; /// An offline area keeping the versions that lost a sync or a Bring Back /// (`OfflineArea::conflicts`, #2468): an older reader would save it again without them. diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index 5b3590e0ed..c431193f43 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -72,6 +72,11 @@ impl Project { { required.push("label-clearance"); } + // And whether they remove duplicates (#2847), for the same reason. + if !required.contains(&"label-duplicates") && self.styles.iter().any(|s| s.labels.in_order().any(|c| c.remove_duplicates.is_some())) + { + required.push("label-duplicates"); + } let commands: Vec<&'static str> = COMMAND_CAPABILITIES.iter().filter_map(|&(name, uses)| self.uses_commands(uses).then_some(name)).collect(); required.extend(commands.into_iter().filter(|name| !required.contains(name)).collect::>()); @@ -149,8 +154,22 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("dggs-system", command_uses_dggs_system), ("label-weight", command_weighs_labels), ("label-clearance", command_clears_labels), + ("label-duplicates", command_removes_duplicate_labels), ]; +/// 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. +fn command_removes_duplicate_labels(id: &str, params: &Value) -> bool { + match id { + "labels.placement" => { + params.get("removeDuplicates").and_then(crate::cmd::labels::number).and_then(rustgis_map::symbology::label_duplicates).is_some() + } + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_removes_duplicate_labels)), + _ => false, + } +} + /// A saved `labels.placement` that gives a class a clearance other than 2, read as the command /// reads it (#2828): an older reader runs it without the key, saying nothing, so the labels would /// keep 2 points apart as before. 2 or null is what an older reader keeps. @@ -600,6 +619,12 @@ fn label_clearance(layer: &Layer) -> bool { layer.labels.in_order().any(|c| c.clearance != rustgis_map::symbology::DEFAULT_LABEL_CLEARANCE) } +/// Whether a layer's label classes remove duplicates (#2847): an older reader would drop the +/// setting, and place and save every label. +fn removes_duplicate_labels(layer: &Layer) -> bool { + layer.labels.in_order().any(|c| c.remove_duplicates.is_some()) +} + /// The capabilities a layer needs, in [`map_capabilities`]'s order. fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { [ @@ -611,6 +636,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { (label_guide(layer), "label-guide"), (label_weight(layer), "label-weight"), (label_clearance(layer), "label-clearance"), + (removes_duplicate_labels(layer), "label-duplicates"), (held_natively(&layer.dataset), super::NATIVE_COORDINATES), ] .into_iter() @@ -637,7 +663,8 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static mut grid_color, ) = (false, false, false, false, false, false, false, false, false, false, false, false, false, false, false); let mut polygon = false; - let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared) = (false, false, 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); for map in maps { offline_area_id |= map.offline_area_id.is_some(); // A blank basemap's paper colour (#2532), which an older reader would draw and save white. @@ -645,6 +672,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static guided |= map.layers.iter().any(label_guide); weighed |= map.layers.iter().any(label_weight); cleared |= map.layers.iter().any(label_clearance); + deduped |= map.layers.iter().any(removes_duplicate_labels); // An older reader doesn't know the MGRS graticule (#1042 piece 8): it refuses the // project by name rather than failing to read the type. mgrs |= map.graticule_type == rustgis_map::graticule::GraticuleType::Mgrs; @@ -692,6 +720,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (guided, "label-guide"), (weighed, "label-weight"), (cleared, "label-clearance"), + (deduped, "label-duplicates"), (offline_area_id, "offline-map-area-id"), (paper, "blank-paper"), (native, super::NATIVE_COORDINATES), diff --git a/crates/engine/src/project_label_losses.rs b/crates/engine/src/project_label_losses.rs index 0efe0572a8..e9db2504b3 100644 --- a/crates/engine/src/project_label_losses.rs +++ b/crates/engine/src/project_label_losses.rs @@ -83,6 +83,8 @@ struct Class { #[serde(default)] clearance: Option, #[serde(default)] + remove_duplicates: Option, + #[serde(default)] stretch: Option, } @@ -104,6 +106,8 @@ struct Labels { #[serde(default)] clearance: Option, #[serde(default)] + remove_duplicates: Option, + #[serde(default)] square_to: Option, #[serde(default)] guide: Option, @@ -172,6 +176,12 @@ fn adjusted_clearance(value: Option<&serde_json::Value>) -> bool { value.is_some_and(|v| !v.is_null() && v.as_f64().is_none_or(|n| !rustgis_map::symbology::LABEL_CLEARANCE.contains(&n))) } +/// A distance to remove duplicate labels within (#2847) that isn't a number from 1 to 2000 (held to +/// it, or off when it isn't a number); null is off. +fn adjusted_duplicates(value: Option<&serde_json::Value>) -> bool { + value.is_some_and(|v| !v.is_null() && v.as_f64().is_none_or(|n| !rustgis_map::symbology::LABEL_DUPLICATES.contains(&n))) +} + /// How much of its line a fitted label is spread over (#2265) that isn't a number (read as the /// default) or is out of its range (held to it); null is the default. fn adjusted_stretch(value: Option<&serde_json::Value>) -> bool { @@ -266,7 +276,7 @@ fn count<'a>( let name = crate::project::short_name(name); let mut classes = ClassLosses::default(); let (mut moves, mut callouts, mut offsets, mut flags, mut squares, mut stretches) = (0usize, 0usize, 0usize, 0usize, 0usize, 0usize); - let (mut guides, mut weights, mut clearances) = (0usize, 0usize, 0usize); + let (mut guides, mut weights, mut clearances, mut duplicates) = (0usize, 0usize, 0usize, 0usize); let mut diagrams = rustgis_map::diagram::DiagramAudit::default(); for layer in raw { diagrams = diagrams.plus(layer.diagram); @@ -278,6 +288,7 @@ fn count<'a>( flags = flags.saturating_add(usize::from(damaged_flag(labels.show_all.as_ref()))); weights = weights.saturating_add(usize::from(adjusted_weight(labels.weight.as_ref()))); clearances = clearances.saturating_add(usize::from(adjusted_clearance(labels.clearance.as_ref()))); + duplicates = duplicates.saturating_add(usize::from(adjusted_duplicates(labels.remove_duplicates.as_ref()))); squares = squares.saturating_add(usize::from(adjusted_square_to(labels.square_to.as_ref()))); guides = guides.saturating_add(usize::from(dropped_guide(labels.guide.as_ref()))); stretches = stretches.saturating_add(usize::from(adjusted_stretch(labels.stretch.as_ref()))); @@ -288,6 +299,7 @@ fn count<'a>( flags = flags.saturating_add(usize::from(damaged_flag(class.show_all.as_ref()))); weights = weights.saturating_add(usize::from(adjusted_weight(class.weight.as_ref()))); clearances = clearances.saturating_add(usize::from(adjusted_clearance(class.clearance.as_ref()))); + duplicates = duplicates.saturating_add(usize::from(adjusted_duplicates(class.remove_duplicates.as_ref()))); squares = squares.saturating_add(usize::from(adjusted_square_to(class.square_to.as_ref()))); guides = guides.saturating_add(usize::from(dropped_guide(class.guide.as_ref()))); stretches = stretches.saturating_add(usize::from(adjusted_stretch(class.stretch.as_ref()))); @@ -316,6 +328,11 @@ fn count<'a>( if clearances > 0 { messages.push(format!("{name}: {clearances} label clearance(s) not a number from 0 to 100 points adjusted while opening {what}")); } + if duplicates > 0 { + messages.push(format!( + "{name}: {duplicates} label duplicate distance(s) not a number from 1 to 2000 points adjusted or turned off while opening {what}" + )); + } if squares > 0 { messages.push(format!( "{name}: {squares} perpendicular label line setting(s) dropped (labelled as auto) or adjusted while opening {what}" diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8f095d2e4d..8ddfc1562e 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9410,6 +9410,130 @@ fn saved_label_clearances_are_required_by_name() { assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["label-clearance"])); } +/// A label class removes its duplicates within some points (#2847), 1 to 2000, off by default. A +/// fraction is kept; a number out of range is held and said, junk refused, false or null turns it +/// off. It undoes in one step, keeps a lock, is saved only when on, and then requires +/// `label-duplicates`, which an older reader refuses rather than drop. +#[test] +fn a_label_class_removes_duplicates_within_a_distance() { + let mut s = world(); + let id = s.map().layer_by_name("Cities").unwrap().id; + let within = |s: &Session| { + let l = &s.map().layer(id).unwrap().labels; + (l.default.remove_duplicates, l.classes.first().map(|c| c.remove_duplicates)) + }; + let said = |s: &Session, mark| s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>(); + assert_eq!(within(&s), (None, None)); + let mark = s.notice_mark(); + s.run("labels.placement", &json!({"layer": "Cities", "removeDuplicates": 200})).unwrap(); + assert_eq!(within(&s), (Some(200.0), None)); + assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); + s.run("edit.undo", &json!({})).unwrap(); + assert_eq!(within(&s), (None, None), "undoes"); + // A fraction is kept, as a text number is read. + s.run("labels.placement", &json!({"layer": "Cities", "removeDuplicates": 2.5})).unwrap(); + assert_eq!(within(&s).0, Some(2.5)); + s.run("labels.placement", &json!({"layer": "Cities", "removeDuplicates": "300"})).unwrap(); + assert_eq!(within(&s).0, Some(300.0)); + for (given, kept, note) in + [(json!(5000), 2000.0, "removeDuplicates 5000 adjusted to 2000"), (json!(0), 1.0, "removeDuplicates 0 adjusted to 1")] + { + let mark = s.notice_mark(); + s.run("labels.placement", &json!({"layer": "Cities", "removeDuplicates": given})).unwrap(); + assert_eq!(within(&s).0, Some(kept), "{given}"); + let notes = said(&s, mark); + assert!(notes.iter().any(|n| n.contains(note)), "{given}: {notes:?}"); + } + for bad in [json!("near"), json!(true), json!([1])] { + let err = s.run("labels.placement", &json!({"layer": "Cities", "removeDuplicates": bad})).unwrap_err(); + assert!(err.contains("removeDuplicates must be a number of points from 1 to 2000 (false or null: off)"), "{bad}: {err}"); + } + for off in [json!(false), json!(null)] { + s.run("labels.placement", &json!({"layer": "Cities", "removeDuplicates": 50})).unwrap(); + s.run("labels.placement", &json!({"layer": "Cities", "removeDuplicates": off})).unwrap(); + assert_eq!(within(&s), (None, None), "{off}: off"); + } + // The class named, not Default. + s.run("labels.class.add", &json!({"layer": "Cities", "name": "Big"})).unwrap(); + s.run("labels.placement", &json!({"layer": "Cities", "class": "Big", "removeDuplicates": 120})).unwrap(); + assert_eq!(within(&s), (None, Some(Some(120.0)))); + // A lock holds: the labels it keeps stay where they are. + let key = (id, 0, 0, 0); + s.map_mut().label_lock = Some(vec![(key, rustgis_map::LockedPlace { place: 0, callout: None })]); + s.run("labels.placement", &json!({"layer": "Cities", "class": "Big", "removeDuplicates": 150})).unwrap(); + assert!(s.map().label_lock.is_some(), "removing duplicates keeps the lock"); + // Saved, it requires `label-duplicates`, and reads back. + let saved = serde_json::to_value(&s.project).unwrap(); + assert_eq!(saved["requires"], json!(["label-duplicates"])); + let read = Project::from_json(&saved.to_string()).unwrap(); + let layer = read.maps[0].layers.iter().find(|l| l.id == id).unwrap(); + assert_eq!(layer.labels.classes[0].remove_duplicates, Some(150.0)); + // Off everywhere: nothing to require, and nothing saved. + s.run("labels.placement", &json!({"layer": "Cities", "class": "Big", "removeDuplicates": false})).unwrap(); + let saved = serde_json::to_value(&s.project).unwrap(); + assert!(saved.get("requires").is_none()); + assert!(!saved.to_string().contains("remove_duplicates"), "off isn't written"); + // The fixture (`label_duplicates.rgis`) reads back as saved, saying nothing. + let mut fixture = Project::from_json(include_str!("../../../schema/fixtures/label_duplicates.rgis")).unwrap(); + assert_eq!(fixture.maps[0].layers[0].labels.default.remove_duplicates, Some(150.0)); + assert!(fixture.take_read_notices(&crate::project::ALL_PARTS).is_empty()); + assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["label-duplicates"])); + // A distance out of range or junk in a file is held or dropped, and said once. + let mut damaged = serde_json::to_value(&world().project).unwrap(); + damaged["maps"][0]["layers"][0]["labels"]["remove_duplicates"] = json!(9999); + damaged["maps"][0]["layers"][1]["labels"]["remove_duplicates"] = json!("x"); + let read = Session::new(Project::from_json(&damaged.to_string()).unwrap()); + assert_eq!(read.map().layers[0].labels.default.remove_duplicates, Some(2000.0)); + assert_eq!(read.map().layers[1].labels.default.remove_duplicates, None); + let notes: Vec<_> = read.notices.iter().filter(|n| n.text.contains("duplicate")).map(|n| n.text.clone()).collect(); + assert!(notes.len() == 1 && notes[0].contains("2 label duplicate distance(s)"), "{notes:?}"); +} + +/// Removing duplicates saved in a task, a model's step or a script, or in a saved style, also +/// requires `label-duplicates`: an older reader would run the step, or apply the style, without +/// it, saying nothing (#2847). False or null needs nothing: that is what an older reader keeps. +#[test] +fn saved_label_duplicate_removal_is_required_by_name() { + let s = world(); + let with_task = |params: Value| { + let mut project = s.project.clone(); + project.tasks = vec![ + serde_json::from_value( + json!({"name": "Dedupe", "steps": [{"title": "Dedupe", "command": "labels.placement", "params": params}]}), + ) + .unwrap(), + ]; + serde_json::to_value(&project).unwrap().get("requires").cloned() + }; + for within in [json!(200), json!("200"), json!(2.5), json!(0), json!(5000)] { + assert_eq!( + with_task(json!({"layer": "Cities", "position": "above", "removeDuplicates": within})), + Some(json!(["label-duplicates"])), + "{within}" + ); + } + for nothing in [ + json!({"layer": "Cities", "removeDuplicates": false}), + json!({"layer": "Cities", "removeDuplicates": null}), + json!({"layer": "Cities", "position": "above"}), + ] { + assert_eq!(with_task(nothing.clone()), None, "{nothing}"); + } + // In a script, too. + let script = json!({"script": "labels.placement {\"layer\": \"Cities\", \"removeDuplicates\": 90}"}); + let mut project = s.project.clone(); + project.tasks = vec![ + serde_json::from_value(json!({"name": "Script", "steps": [{"title": "Run", "command": "script.run", "params": script}]})).unwrap(), + ]; + assert_eq!(serde_json::to_value(&project).unwrap()["requires"], json!(["label-duplicates"])); + // A saved style keeps the setting its layer had. + let mut s = world(); + s.run("labels.placement", &json!({"layer": "Cities", "removeDuplicates": 200})).unwrap(); + s.run("style.new", &json!({"layer": "Cities", "name": "Deduped"})).unwrap(); + s.run("labels.placement", &json!({"layer": "Cities", "removeDuplicates": null})).unwrap(); + assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["label-duplicates"])); +} + /// A label class takes an offset with its placement and a background with its text symbol; junk /// is refused, numbers kept within their ranges, and each change undoes. #[test] diff --git a/crates/map/src/qgis/labels.rs b/crates/map/src/qgis/labels.rs index f536f3c22f..7132b95ded 100644 --- a/crates/map/src/qgis/labels.rs +++ b/crates/map/src/qgis/labels.rs @@ -322,6 +322,7 @@ fn class( show_all: false, weight: crate::symbology::DEFAULT_LABEL_WEIGHT, clearance: crate::symbology::DEFAULT_LABEL_CLEARANCE, + remove_duplicates: None, callout: None, square_to: None, guide: None, diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index f3f67ae048..5af978e666 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -2675,6 +2675,11 @@ pub struct LabelClass { skip_serializing_if = "is_default_label_clearance" )] pub clearance: f32, + /// Duplicates removed (#2847): within this many points (within [`LABEL_DUPLICATES`]) of a + /// label of another feature of its layer and class with the same text, a label is left out; + /// the one placed first stays. None keeps every label. + #[serde(default, deserialize_with = "de_label_duplicates", skip_serializing_if = "Option::is_none")] + pub remove_duplicates: Option, /// Callouts: a label crowded off its spot moves to a free one nearby, a line drawn from its /// feature to it at most this long (points, within [`CALLOUT_REACH`]), as QGIS's callouts; /// none keeps every label in its spot. Labels along lines aren't moved. @@ -3048,6 +3053,23 @@ fn is_default_label_clearance(c: &f32) -> bool { *c == DEFAULT_LABEL_CLEARANCE } +/// How far apart (points) two labels of one text must be for neither to be removed as the +/// other's duplicate (#2847). +pub const LABEL_DUPLICATES: std::ops::RangeInclusive = 1.0..=2000.0; + +/// The distance a class removes duplicates within when it is turned on in the Labeling pane. +pub const DEFAULT_LABEL_DUPLICATES: f32 = 200.0; + +/// A distance to remove duplicates within: held to [`LABEL_DUPLICATES`]; one that isn't a number +/// turns it off. +pub fn label_duplicates(v: f64) -> Option { + v.is_finite().then(|| v.clamp(*LABEL_DUPLICATES.start(), *LABEL_DUPLICATES.end()) as f32) +} + +fn de_label_duplicates<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { + Ok(lenient::(d)?.and_then(label_duplicates)) +} + fn is_no_offset(o: &[f32; 2]) -> bool { *o == [0.0; 2] } @@ -3467,6 +3489,7 @@ impl LabelClass { show_all: false, weight: DEFAULT_LABEL_WEIGHT, clearance: DEFAULT_LABEL_CLEARANCE, + remove_duplicates: None, callout: None, square_to: None, guide: None, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 434d958eb8..ebdb632188 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6447,6 +6447,8 @@ fn render_frame( collide: rustgis_tiles::Collide { // Its class's room kept free of other labels (#2828). text_padding: class.clearance, + // Its class's duplicates removed within so far (#2847). + remove_duplicates: class.remove_duplicates.unwrap_or(0.0), // Shown all: over the other labels where they crowd. text_allow_overlap: class.show_all, // Callouts: a label set by its feature (not along a line, @@ -8248,6 +8250,7 @@ fn place_labels_with_previews( // Same work bound as 20,000 heads with eight positions, shared across all bands. let mut layouts_left: usize = 20_000 * 8; let mut placed_groups = std::collections::HashSet::new(); + let mut placed_texts = PlacedTexts::default(); let mut unplaced = Vec::new(); for mut head in cands.into_iter().take(20_000) { let fallbacks = head.line.as_mut().map(|line| std::mem::take(&mut line.fallbacks)).unwrap_or_default(); @@ -8367,6 +8370,17 @@ fn place_labels_with_previews( l.collide.callout = Some(relative(&l, line)); } } + // Its class removes duplicates (#2847): near a label of another feature of its layer and + // class with the same text, placed before it, it is left out. It takes no room and isn't + // shown as unplaced, as it wasn't short of room. One moved by hand always shows. + let dedupe = collide.source.filter(|_| has_text && collide.remove_duplicates > 0.0); + let centre = [l.center_x(), l.y]; + if let Some(source) = dedupe + && !collide.pinned + && placed_texts.near(source, &l.text, centre, collide.remove_duplicates) + { + continue; + } if !show_text && !show_icon { if show_unplaced && has_text && unplaced.len() < 2000 && pending.is_none() { pending = @@ -8377,6 +8391,9 @@ fn place_labels_with_previews( if show_text && !collide.text_ignore_placement { text.iter().for_each(|b| grid.insert(*b)); } + if let Some(source) = dedupe.filter(|_| show_text) { + placed_texts.insert(source, &l.text, centre, collide.remove_duplicates); + } if show_icon && !collide.icon_ignore_placement { icon.iter().for_each(|b| grid.insert(*b)); } @@ -8410,6 +8427,36 @@ fn place_labels_with_previews( out } +/// The labels placed so far of classes that remove duplicates (#2847): by text, then layer, class +/// and a cell as wide as the class's distance, each feature's id and centre, so a label is checked +/// against the nine cells round its own, not every label. [`LabelGrid`] holds boxes, with no text +/// or class to tell a duplicate by. +#[derive(Default)] +struct PlacedTexts(std::collections::HashMap>>); + +impl PlacedTexts { + fn cell([x, y]: [f32; 2], within: f32) -> (i64, i64) { + ((x / within).floor() as i64, (y / within).floor() as i64) + } + + /// Whether a label of `text` at `at` of another feature of `source`'s layer and class is + /// closer than `within` points. + fn near(&self, (layer, feature, class): (u32, u64, u32), text: &str, at: [f32; 2], within: f32) -> bool { + let Some(cells) = self.0.get(text) else { return false }; + let (cx, cy) = Self::cell(at, within); + (-1..=1).flat_map(|dx| (-1..=1).map(move |dy| (cx + dx, cy + dy))).any(|(x, y)| { + cells + .get(&(layer, class, x, y)) + .is_some_and(|placed| placed.iter().any(|&(f, [px, py])| f != feature && (px - at[0]).hypot(py - at[1]) < within)) + }) + } + + fn insert(&mut self, (layer, feature, class): (u32, u64, u32), text: &str, at: [f32; 2], within: f32) { + let (x, y) = Self::cell(at, within); + self.0.entry(text.to_owned()).or_default().entry((layer, class, x, y)).or_default().push((feature, at)); + } +} + /// Which of a label's text and icon show with their boxes `text` and `icon` where they are, as /// MapLibre has it: each where it fits, or may overlap, and a part that isn't optional only with /// the other. @@ -10457,6 +10504,88 @@ mod tests { assert_eq!(moved.collide.text_padding, 9.0); } + /// A class that removes duplicates within some points (#2847) draws one label of a text, the + /// one placed first, where another feature of its layer and class has the same text closer + /// than that: the other takes no room and isn't shown as unplaced. Another text, class, layer + /// or the same feature (a line's repeats) is no duplicate; a label moved by hand always shows, + /// and Show All brings no duplicate back. + #[test] + fn a_class_removes_its_duplicates_within_a_distance() { + // A label of `text` centred `x` points in, for feature `fid` of layer `lid`'s class `ci`. + let dup = |text: &str, x: f32, (lid, fid, ci): (u32, u64, u32), within: f32| -> Candidate { + let mut l = label(text, x, None, 0.0); + l.collide.source = Some((lid, fid, ci)); + l.collide.remove_duplicates = within; + (l, 0.0, (lid, fid, ci as usize, 0)).into() + }; + let place = |c: Vec| place_labels_with_previews(c, Vec::new(), 2000.0, 40.0, false, true); + let shown = |p: &Placement| p.labels.iter().map(|l| (l.text.clone(), l.center_x().round() as i32)).collect::>(); + let main = |x: f32, fid: u64, within: f32| dup("Main", x, (1, fid, 0), within); + // Off (0): both, as before. + assert_eq!(shown(&place(vec![main(100.0, 1, 0.0), main(250.0, 2, 0.0)])), [("Main".into(), 100), ("Main".into(), 250)]); + // Within 200: the one placed first, the other not shown as unplaced either. + let p = place(vec![main(100.0, 1, 200.0), main(250.0, 2, 200.0)]); + assert_eq!(shown(&p), [("Main".into(), 100)]); + assert!(p.unplaced.is_empty(), "a duplicate isn't a label with no room"); + // Closer than the distance only. + assert_eq!(shown(&place(vec![main(100.0, 1, 200.0), main(299.5, 2, 200.0)])).len(), 1); + assert_eq!(shown(&place(vec![main(100.0, 1, 200.0), main(300.5, 2, 200.0)])).len(), 2); + // Another text (case too), class or layer: no duplicate. + for (text, key) in [("Oak", (1, 2, 0)), ("main", (1, 2, 0)), ("Main", (1, 2, 1)), ("Main", (2, 2, 0))] { + assert_eq!(shown(&place(vec![main(100.0, 1, 200.0), dup(text, 250.0, key, 200.0)])).len(), 2, "{text} {key:?}"); + } + // The same feature's labels (a line's repeats): no duplicates. + let repeat = Candidate { key: (1, 1, 0, 1), ..main(250.0, 1, 200.0) }; + assert_eq!(shown(&place(vec![main(100.0, 1, 200.0), repeat])).len(), 2, "a line's repeats stay"); + // Moved by hand: placed first and shown; an unmoved duplicate near it goes, a moved one stays. + let pinned = |x: f32, fid: u64| { + let mut c = main(x, fid, 200.0); + c.label.collide.pinned = true; + Candidate { weight: PLACED_FIRST, ..c } + }; + assert_eq!(shown(&place(vec![main(100.0, 1, 200.0), pinned(250.0, 2)])), [("Main".into(), 250)]); + assert_eq!(shown(&place(vec![pinned(100.0, 1), pinned(250.0, 2)])).len(), 2, "both moved by hand"); + // Show All draws over the others, not a duplicate. + let all = |x: f32, fid: u64| { + let mut c = main(x, fid, 200.0); + c.label.collide.text_allow_overlap = true; + c + }; + assert_eq!(shown(&place(vec![all(100.0, 1), all(250.0, 2)])).len(), 1, "Show All brings no duplicate back"); + // A removed duplicate takes no room: a label placed after it shows where it would have been. + let elm = || Candidate { priority: -1.0, ..dup("Elm", 250.0, (3, 1, 0), 0.0) }; + assert_eq!(shown(&place(vec![main(100.0, 1, 0.0), main(250.0, 2, 0.0), elm()])).len(), 2, "kept, it hides Elm"); + let p = place(vec![main(100.0, 1, 200.0), main(250.0, 2, 200.0), elm()]); + assert_eq!(shown(&p), [("Main".into(), 100), ("Elm".into(), 250)]); + } + + /// A class's setting reaches its labels (#2847): two features of one layer with the same name + /// 150 points apart draw both labels, and one once the class removes duplicates within 200. + #[test] + fn a_label_class_draws_one_of_its_duplicates() { + let camera = Camera { center: lonlat_to_merc(Coord::new(2.35, 48.85)), res: 5000.0, bearing: 0.0, pitch: 0.0 }; + let view = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera, sky: false }; + let map = |within: Option| { + let mut m = Map::new("Map"); + let mut d = Dataset::new("streets", GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + for dx in [0.0, 150.0] { + let at = rustgis_geom::merc_to_lonlat(Coord::new(camera.center.x + dx * camera.res, camera.center.y)); + d.push(Some(Geometry::Point(at)), vec![Value::Text("Main".into())]); + } + let id = m.add_dataset(d); + let l = m.layer_mut(id).unwrap(); + l.labels.enabled = true; + l.labels.default.field = "name".into(); + l.labels.default.placement = rustgis_map::LabelPlacement::Center; + l.labels.default.remove_duplicates = within; + m + }; + assert_eq!(render(&mut map(None), &view).unwrap().labels.len(), 2, "off: both, as before"); + let one = render(&mut map(Some(200.0)), &view).unwrap().labels; + assert_eq!(one.len(), 1); + assert_eq!(one[0].collide.remove_duplicates, 200.0); + } + /// A tile style's label still comes after every layer's own, the lightest included (#2803). #[test] fn tile_labels_come_after_the_lightest_layer_label() { diff --git a/crates/tiles/src/symbols.rs b/crates/tiles/src/symbols.rs index 84c244d322..c3ce6a24ee 100644 --- a/crates/tiles/src/symbols.rs +++ b/crates/tiles/src/symbols.rs @@ -106,6 +106,10 @@ pub struct Collide { /// What it labels, for moving it by hand: its layer's id, its feature's id and its label /// class (in the layer's labeling order). None for labels not of a layer's features. pub source: Option<(u32, u64, u32)>, + /// Its class removes duplicates (#2847): left out within this many points of a label of + /// another feature of its [`source`](Self::source)'s layer and class with the same text; 0 + /// keeps every label. + pub remove_duplicates: f32, } impl Default for Collide { @@ -125,6 +129,7 @@ impl Default for Collide { callout_offset: None, pinned: false, source: None, + remove_duplicates: 0.0, } } } diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index f4d8d487a0..c4558c5e37 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -967,10 +967,14 @@ fn square_to(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { /// Where labels crowd: every one shown, over the others, rather than some left out; the class's /// weight, the heavier winning where labels compete; its clearance, the room its labels keep free -/// of others; and callouts, which move a crowded label to a free spot nearby with a line back to -/// its feature, no longer than so far. +/// of others; whether it removes duplicates, one label of a text where its features lie closer than +/// so far (#2847); and callouts, which move a crowded label to a free spot nearby with a line back +/// to its feature, no longer than so far. fn crowding(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { - use rustgis_engine::map::symbology::{CALLOUT_REACH, LABEL_CLEARANCE, LABEL_WEIGHT, callout_reach, label_clearance, label_weight}; + use rustgis_engine::map::symbology::{ + CALLOUT_REACH, DEFAULT_LABEL_DUPLICATES, LABEL_CLEARANCE, LABEL_DUPLICATES, LABEL_WEIGHT, callout_reach, label_clearance, + label_duplicates, label_weight, + }; let id = l.id; grid(ui, "crowding", |ui| { let input_label = ui.label(tl!("Show all labels")); @@ -1020,6 +1024,41 @@ fn crowding(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { } }); ui.end_row(); + let input_label = ui.label(tl!("Remove duplicates")); + ui.horizontal(|ui| { + let mut on = c.it.remove_duplicates.is_some(); + if ui + .checkbox(&mut on, "") + .labelled_by(input_label.id) + .on_hover_text(tl!("Draw one label of a text where features of this class with the same text lie closer than this.")) + .changed() + { + let within = if on { json!(DEFAULT_LABEL_DUPLICATES) } else { json!(false) }; + run(app, "labels.placement", c.params(json!({"removeDuplicates": within}))); + } + let Some(within) = c.it.remove_duplicates else { return }; + // As the clearance: scoped to its layer and class, written when let go (#2847). + ui.push_id(("label_duplicates", l.instance_id(), c.name), |ui| { + let mut v = f64::from(within); + let drag = crate::widgets::Dragged::lend(ui, egui::Id::unique(("label_duplicates_drag", l.instance_id(), c.name)), &mut v); + let r = ui + .add( + egui::DragValue::new(&mut v) + .update_while_editing(false) + .range(LABEL_DUPLICATES) + .speed(1.0) + .max_decimals(0) + .prefix(format!("{} ", tl!("within"))) + .suffix(" pt"), + ) + .labelled_by(input_label.id) + .on_hover_text(tl!("How close two labels of one text may be before the one placed later is left out.")); + if drag.settled(ui, &r, &mut v) && label_duplicates(v) != Some(within) { + run(app, "labels.placement", c.params(json!({"removeDuplicates": label_duplicates(v)}))); + } + }); + }); + ui.end_row(); let input_label = ui.label(tl!("Callouts")); ui.horizontal(|ui| { let mut on = c.it.callout.is_some(); @@ -1773,6 +1812,58 @@ mod tests { assert_eq!(h.state().session.undo_depth(), steps, "nothing to undo"); } + /// A label class removes its duplicates from Position, under Clearance (#2847): ticked, within + /// 200 points; a distance typed, or dragged and let go in one step; unticked, off again. + #[test] + fn duplicate_labels_are_removed_from_the_pane() { + use egui::accesskit::Role; + let mut h = harness(with_cities()); + h.run(); + let cities = layer_id(h.state(), "Cities"); + h.state_mut().session.run("layer.select", &json!({"layer": cities})).unwrap(); + h.run(); + open_tab(&mut h, "Position"); + let within = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.state().session.map().layer_by_name("Cities").unwrap().labels.default.remove_duplicates + }; + assert_eq!(within(&h), None); + assert!(h.query_by_role_and_label(Role::SpinButton, "Remove duplicates").is_none(), "no distance while off"); + h.get_by_role_and_label(Role::CheckBox, "Remove duplicates").click(); + h.run(); + assert_eq!(within(&h), Some(200.0), "ticked: within 200 points"); + h.get_by_role_and_label(Role::SpinButton, "Remove duplicates").focus(); + h.run(); + h.get_by_role_and_label(Role::SpinButton, "Remove duplicates").type_text("350"); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(within(&h), Some(350.0)); + // Dragged right over several frames, then let go: more, in one step. + let steps = h.state().session.undo_depth(); + let at = h.get_by_role_and_label(Role::SpinButton, "Remove duplicates").rect().center(); + let button = |pos, pressed| egui::Event::PointerButton { + pos, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }; + h.event(egui::Event::PointerMoved(at)); + h.step(); + h.event(button(at, true)); + h.step(); + for i in 1..=10 { + h.event(egui::Event::PointerMoved(at + egui::vec2(4.0 * i as f32, 0.0))); + h.step(); + } + h.event(button(at + egui::vec2(40.0, 0.0), false)); + h.step(); + h.run(); + assert!(within(&h).is_some_and(|d| d > 350.0), "dragged further: {:?}", within(&h)); + assert_eq!(h.state().session.undo_depth(), steps + 1, "a drag is one step"); + h.get_by_role_and_label(Role::CheckBox, "Remove duplicates").click(); + h.run(); + assert_eq!(within(&h), None, "unticked: off"); + } + /// A line layer's labels can try other places along the line (#1187): the box is there for a /// placement along the line without a repeat, and hiding it leaves what it was set to. #[test] diff --git a/docs/maintaining.md b/docs/maintaining.md index 316d103338..96fe274b8b 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -174,6 +174,10 @@ Likewise a label class keeping other than 2 points free round its labels (`label step: an older reader would place the labels 2 points apart and save them again without the clearances, or run the step without it. +A label class removing duplicates (`labels.placement` with a `removeDuplicates` distance) requires +`label-duplicates`, in a layer, a saved style or a saved `labels.placement` step: an older reader +would place and save every label, or run the step without it. + Projects with an ink on a legend, colorbar, table or chart (`color` on those elements) require `layout-element-ink`, so an older reader refuses them instead of drawing those elements in dark grey and saving them again without it. Saved `layout.addElement` and `layout.update` commands diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 7f52afe621..31ad46a6b5 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -659,6 +659,15 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: only, not an icon; vector tile labels keep their style's own padding (`labels.placement={"layer": "Rivers", "clearance": 10}`; a number past 0 or 100 is brought to it, with a notice; `null` is 2). +- **Remove duplicates** (Labeling pane › Position): one label of a text where features of a class + with the same text lie closer than a distance, in points (1 to 2000, 200 when ticked). A street + split into many features gets one name in that distance rather than one per piece. The label + placed first stays (the heavier class's, then the layer above); the others take no room, so + other labels can use it, and View Unplaced doesn't show them. Only labels of the same layer and + class are compared, by their text as drawn (case counts); a line's repeated labels aren't + duplicates, and a label moved by hand always shows (`labels.placement={"layer": "Streets", + "removeDuplicates": 300}`; a number past 1 or 2000 is brought to it, with a notice; `false` or + `null` turns it off). - **Callouts** (Labeling pane › Position): a label crowded off its spot moves to the nearest free spot nearby, and a line is drawn from its feature to the text, as QGIS's callouts. **at most** sets how long the line may be (5 to 500 points, 40 to start with): a label with no free spot @@ -679,7 +688,8 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: and undo restoration. Opening a project, importing a map or styles, or adding a layer file reports invalid, duplicate or excess moved-label entries that were ignored, callout lengths that were adjusted, label weights that were not a whole number from 0 to 10, label clearances that - were not a number from 0 to 100 points, and Show all labels settings that were not true or + were not a number from 0 to 100 points, label duplicate distances that were not a number from 1 + to 2000 points, and Show all labels settings that were not true or false. A callout length given to `labels.placement` outside 5 to 500 points is brought within range with a notice. Clean settings give no such notice. diff --git a/schema/fixtures/label_duplicates.rgis b/schema/fixtures/label_duplicates.rgis new file mode 100644 index 0000000000..ea87b19a76 --- /dev/null +++ b/schema/fixtures/label_duplicates.rgis @@ -0,0 +1 @@ +{"requires":["label-duplicates"],"format":2,"name":"Label duplicates","maps":[{"name":"Map","layers":[{"id":2,"name":"picos","visible":true,"dataset":{"name":"picos","geometry_type":"Point","fields":[{"name":"nome","ty":"Text","alias":null}],"features":[{"id":1,"geometry":{"Point":{"x":-41.0,"y":-20.37}},"attrs":[{"Text":"Ribeirão Santo Antônio"}]}],"source":null},"renderer":{"Single":{"fill":[224,123,57,255],"stroke":[224,123,57,255],"stroke_width":1.6,"size":0.0,"marker":"Circle"}},"labels":{"enabled":true,"field":"nome","size":8.0,"color":[43,43,43,255],"halo":true,"bold":false,"min_scale":null,"max_scale":null,"closest":null,"farthest":null,"placement":"Auto","italic":true,"remove_duplicates":150.0},"transparency":0.0,"min_scale":null,"max_scale":null,"definition_query":null,"selection":[],"expanded":true,"selectable":true,"graphics":false,"blend":"Normal","mask":null,"display_filters":[],"aggregation":null,"extrusion":null,"priority":0,"geometry_rev":0},{"id":1,"name":"rios","visible":true,"dataset":{"name":"rios","geometry_type":"Polyline","fields":[{"name":"nome","ty":"Text","alias":null}],"features":[{"id":1,"geometry":{"Line":[[{"x":-41.1,"y":-20.4},{"x":-41.0,"y":-20.38},{"x":-40.9,"y":-20.35}]]},"attrs":[{"Text":"Ribeirão Santo Antônio"}]}],"source":null},"renderer":{"Single":{"fill":[224,123,57,255],"stroke":[224,123,57,255],"stroke_width":1.6,"size":0.0,"marker":"Circle"}},"labels":{"enabled":false,"field":"nome","size":8.0,"color":[43,43,43,255],"halo":true,"bold":false,"min_scale":null,"max_scale":null,"closest":null,"farthest":null,"placement":"Auto","italic":true},"transparency":0.0,"min_scale":null,"max_scale":null,"definition_query":null,"selection":[],"expanded":true,"selectable":true,"graphics":false,"blend":"Normal","mask":null,"display_filters":[],"aggregation":null,"extrusion":null,"priority":0,"geometry_rev":0}],"basemap":"Paper","camera":{"center":{"x":-4564099.122524217,"y":-2317508.4417822156},"res":20.779638281411025,"bearing":0.0,"pitch":0.0},"bookmarks":[],"graticule":true,"projection":"WebMercator","popup_mode":"Topmost","label_display":{"paused":false,"locked":false,"show_unplaced":false},"editing":{"relationships":[],"snapping":{"enabled":false,"tolerance_px":10.0,"vertex":true,"edge":true,"end":true},"topology":[],"settings":{"enabled":true,"show_vertices":true,"elevation":"None","ground_to_grid":null}},"swipe":null,"view":{"effects":{"stars":true,"sun_time":null,"weather":"None","vignette":false,"edges":false,"tilt_shift":false,"grain":false,"brightness":0.0,"contrast":0.0,"saturation":0.0,"sepia":0.0},"wireframe":false,"clip_distance":null,"terrain":null},"animation":[],"next_layer_id":3}],"active_map":0,"tables":[],"next_table_id":1,"gp_history":[],"layouts":[],"folders":[],"styles":[],"ramps":[],"tasks":[],"gp_env":{"extent":null,"cell_size":null},"models":[],"workspaces":[],"link_views":false,"jobs":[],"offline_areas":[],"reports":[],"presentations":[],"notebooks":[],"dl_models":[],"shared":[],"data_stores":[]} diff --git a/schema/project.schema.json b/schema/project.schema.json index 69ecfcd3a9..f305d0fc47 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1278,7 +1278,8 @@ "label-weight", "project-crs", "dggs-system", - "label-clearance" + "label-clearance", + "label-duplicates" ], "type": "string" }, @@ -1385,7 +1386,8 @@ "label-weight", "project-crs", "dggs-system", - "label-clearance" + "label-clearance", + "label-duplicates" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2 From 1594ad67ffa229f5775eebc42ac7db2e9f597bfa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 07:36:13 -0500 Subject: [PATCH 2/6] refactor(labels): duplicate removal rides on the label candidate, measured only when on, and a removed line label shows in no band (#2847) --- crates/engine/src/cmd/labels.rs | 4 +- crates/engine/src/project_capabilities.rs | 4 +- crates/engine/src/project_label_losses.rs | 7 +- crates/engine/src/tests.rs | 3 + crates/map/src/symbology.rs | 12 ++-- crates/render/src/lib.rs | 81 ++++++++++++++++------- crates/render/src/line_positions_tests.rs | 1 + crates/tiles/src/symbols.rs | 5 -- crates/ui-egui/src/labelpane.rs | 2 +- 9 files changed, 77 insertions(+), 42 deletions(-) diff --git a/crates/engine/src/cmd/labels.rs b/crates/engine/src/cmd/labels.rs index fb1320bcde..e561bbbca6 100644 --- a/crates/engine/src/cmd/labels.rs +++ b/crates/engine/src/cmd/labels.rs @@ -230,7 +230,7 @@ pub fn commands() -> Vec { Some(v) => Some(Some(number(v).ok_or("removeDuplicates must be a number of points from 1 to 2000 (false or null: off)")?)), }; let duplicates_asked = remove_duplicates.flatten().filter(|d| !rustgis_map::symbology::LABEL_DUPLICATES.contains(d)); - let remove_duplicates = remove_duplicates.map(|d| d.and_then(rustgis_map::symbology::label_duplicates)); + let remove_duplicates = remove_duplicates.map(|d| d.map(rustgis_map::symbology::label_duplicates)); // Every label shown, over the others where they crowd. let show_all = match p.get("showAll") { None => None, @@ -414,7 +414,7 @@ pub fn commands() -> Vec { } if let Some(asked) = duplicates_asked { let name = s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(); - let kept = rustgis_map::symbology::label_duplicates(asked).unwrap_or_default(); + let kept = rustgis_map::symbology::label_duplicates(asked); let asked = if asked.abs() < 1e6 { asked.to_string() } else { format!("{asked:e}") }; s.notify_text( NoticeText::format( diff --git a/crates/engine/src/project_capabilities.rs b/crates/engine/src/project_capabilities.rs index c431193f43..99deb8c779 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -162,9 +162,7 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ /// False or null is what an older reader keeps. fn command_removes_duplicate_labels(id: &str, params: &Value) -> bool { match id { - "labels.placement" => { - params.get("removeDuplicates").and_then(crate::cmd::labels::number).and_then(rustgis_map::symbology::label_duplicates).is_some() - } + "labels.placement" => params.get("removeDuplicates").and_then(crate::cmd::labels::number).is_some(), "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_removes_duplicate_labels)), _ => false, } diff --git a/crates/engine/src/project_label_losses.rs b/crates/engine/src/project_label_losses.rs index e9db2504b3..0e74efa62c 100644 --- a/crates/engine/src/project_label_losses.rs +++ b/crates/engine/src/project_label_losses.rs @@ -177,9 +177,12 @@ fn adjusted_clearance(value: Option<&serde_json::Value>) -> bool { } /// A distance to remove duplicate labels within (#2847) that isn't a number from 1 to 2000 (held to -/// it, or off when it isn't a number); null is off. +/// it, or off when it isn't a number); null and false are off, as the command has them. fn adjusted_duplicates(value: Option<&serde_json::Value>) -> bool { - value.is_some_and(|v| !v.is_null() && v.as_f64().is_none_or(|n| !rustgis_map::symbology::LABEL_DUPLICATES.contains(&n))) + value.is_some_and(|v| { + !matches!(v, serde_json::Value::Null | serde_json::Value::Bool(false)) + && v.as_f64().is_none_or(|n| !rustgis_map::symbology::LABEL_DUPLICATES.contains(&n)) + }) } /// How much of its line a fitted label is spread over (#2265) that isn't a number (read as the diff --git a/crates/engine/src/tests.rs b/crates/engine/src/tests.rs index 8ddfc1562e..99fb5d646c 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9482,9 +9482,12 @@ fn a_label_class_removes_duplicates_within_a_distance() { let mut damaged = serde_json::to_value(&world().project).unwrap(); damaged["maps"][0]["layers"][0]["labels"]["remove_duplicates"] = json!(9999); damaged["maps"][0]["layers"][1]["labels"]["remove_duplicates"] = json!("x"); + // False is off, as the command has it: nothing to say. + damaged["maps"][0]["layers"][2]["labels"]["remove_duplicates"] = json!(false); let read = Session::new(Project::from_json(&damaged.to_string()).unwrap()); assert_eq!(read.map().layers[0].labels.default.remove_duplicates, Some(2000.0)); assert_eq!(read.map().layers[1].labels.default.remove_duplicates, None); + assert_eq!(read.map().layers[2].labels.default.remove_duplicates, None); let notes: Vec<_> = read.notices.iter().filter(|n| n.text.contains("duplicate")).map(|n| n.text.clone()).collect(); assert!(notes.len() == 1 && notes[0].contains("2 label duplicate distance(s)"), "{notes:?}"); } diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index 5af978e666..ef6e600c61 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -3060,14 +3060,16 @@ pub const LABEL_DUPLICATES: std::ops::RangeInclusive = 1.0..=2000.0; /// The distance a class removes duplicates within when it is turned on in the Labeling pane. pub const DEFAULT_LABEL_DUPLICATES: f32 = 200.0; -/// A distance to remove duplicates within: held to [`LABEL_DUPLICATES`]; one that isn't a number -/// turns it off. -pub fn label_duplicates(v: f64) -> Option { - v.is_finite().then(|| v.clamp(*LABEL_DUPLICATES.start(), *LABEL_DUPLICATES.end()) as f32) +/// A distance to remove duplicates within: held to [`LABEL_DUPLICATES`]; NaN or infinity (which no +/// JSON number holds) is [`DEFAULT_LABEL_DUPLICATES`]. A file's value that isn't a number at all +/// turns it off before it gets here ([`de_label_duplicates`]). +pub fn label_duplicates(v: f64) -> f32 { + if v.is_finite() { v.clamp(*LABEL_DUPLICATES.start(), *LABEL_DUPLICATES.end()) as f32 } else { DEFAULT_LABEL_DUPLICATES } } +/// Off when it isn't a number (or is null). fn de_label_duplicates<'de, D: serde::Deserializer<'de>>(d: D) -> Result, D::Error> { - Ok(lenient::(d)?.and_then(label_duplicates)) + Ok(lenient::(d)?.map(label_duplicates)) } fn is_no_offset(o: &[f32; 2]) -> bool { diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index ebdb632188..c2bccc118f 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -2682,6 +2682,9 @@ struct Candidate { /// Offered row hint (a streamed chunk's row), verified against the feature id before use; /// `usize::MAX` when no row is known. row: usize, + /// Its class removes duplicates (#2847): left out within this many points of a label placed + /// before it for another feature of its layer and class with the same text. None keeps it. + remove_duplicates: Option, } impl Candidate { @@ -2776,7 +2779,17 @@ impl LabelPlace { impl From<(PlacedLabel, f64, rustgis_map::LabelKey)> for Candidate { fn from((label, priority, key): (PlacedLabel, f64, rustgis_map::LabelKey)) -> Candidate { let weight = rustgis_map::symbology::DEFAULT_LABEL_WEIGHT; - Candidate { label, weight, priority, key, alternatives: Vec::new(), curves: None, line: None, row: usize::MAX } + Candidate { + label, + weight, + priority, + key, + alternatives: Vec::new(), + curves: None, + line: None, + row: usize::MAX, + remove_duplicates: None, + } } } @@ -6447,8 +6460,6 @@ fn render_frame( collide: rustgis_tiles::Collide { // Its class's room kept free of other labels (#2828). text_padding: class.clearance, - // Its class's duplicates removed within so far (#2847). - remove_duplicates: class.remove_duplicates.unwrap_or(0.0), // Shown all: over the other labels where they crowd. text_allow_overlap: class.show_all, // Callouts: a label set by its feature (not along a line, @@ -6480,6 +6491,7 @@ fn render_frame( curves: curves.take(), line: line_places.take(), row, + remove_duplicates: class.remove_duplicates, }); } } @@ -8256,7 +8268,7 @@ fn place_labels_with_previews( let fallbacks = head.line.as_mut().map(|line| std::mem::take(&mut line.fallbacks)).unwrap_or_default(); // Siblings are contiguous: hold just one temporary preview until the group finishes. let mut pending = None; - for Candidate { label: mut l, key, alternatives, curves, line, .. } in std::iter::once(head).chain(fallbacks) { + for Candidate { label: mut l, key, alternatives, curves, line, remove_duplicates, .. } in std::iter::once(head).chain(fallbacks) { let c = l.collide; let feature = c.callout_anchor.map(|[ax, ay]| [l.x + ax, l.y + ay]); let grouped = line.as_ref().is_some_and(|line| line.deduplicate); @@ -8373,12 +8385,15 @@ fn place_labels_with_previews( // Its class removes duplicates (#2847): near a label of another feature of its layer and // class with the same text, placed before it, it is left out. It takes no room and isn't // shown as unplaced, as it wasn't short of room. One moved by hand always shows. - let dedupe = collide.source.filter(|_| has_text && collide.remove_duplicates > 0.0); - let centre = [l.center_x(), l.y]; - if let Some(source) = dedupe + let dedupe = remove_duplicates.filter(|_| has_text).map(|within| (within, [l.center_x(), l.y])); + if let Some((within, centre)) = dedupe && !collide.pinned - && placed_texts.near(source, &l.text, centre, collide.remove_duplicates) + && placed_texts.near(key, &l.text, centre, within) { + // A tilted view's other bands are places of the same label: none of them shows. + if grouped { + placed_groups.insert(key); + } continue; } if !show_text && !show_icon { @@ -8391,8 +8406,8 @@ fn place_labels_with_previews( if show_text && !collide.text_ignore_placement { text.iter().for_each(|b| grid.insert(*b)); } - if let Some(source) = dedupe.filter(|_| show_text) { - placed_texts.insert(source, &l.text, centre, collide.remove_duplicates); + if let Some((within, centre)) = dedupe.filter(|_| show_text) { + placed_texts.insert(key, &l.text, centre, within); } if show_icon && !collide.icon_ignore_placement { icon.iter().for_each(|b| grid.insert(*b)); @@ -8432,16 +8447,16 @@ fn place_labels_with_previews( /// against the nine cells round its own, not every label. [`LabelGrid`] holds boxes, with no text /// or class to tell a duplicate by. #[derive(Default)] -struct PlacedTexts(std::collections::HashMap>>); +struct PlacedTexts(std::collections::HashMap>>); impl PlacedTexts { fn cell([x, y]: [f32; 2], within: f32) -> (i64, i64) { ((x / within).floor() as i64, (y / within).floor() as i64) } - /// Whether a label of `text` at `at` of another feature of `source`'s layer and class is - /// closer than `within` points. - fn near(&self, (layer, feature, class): (u32, u64, u32), text: &str, at: [f32; 2], within: f32) -> bool { + /// Whether a label of `text` at `at` of another feature of `key`'s layer and class is closer + /// than `within` points. + fn near(&self, (layer, feature, class, _): rustgis_map::LabelKey, text: &str, at: [f32; 2], within: f32) -> bool { let Some(cells) = self.0.get(text) else { return false }; let (cx, cy) = Self::cell(at, within); (-1..=1).flat_map(|dx| (-1..=1).map(move |dy| (cx + dx, cy + dy))).any(|(x, y)| { @@ -8451,9 +8466,15 @@ impl PlacedTexts { }) } - fn insert(&mut self, (layer, feature, class): (u32, u64, u32), text: &str, at: [f32; 2], within: f32) { + fn insert(&mut self, (layer, feature, class, _): rustgis_map::LabelKey, text: &str, at: [f32; 2], within: f32) { let (x, y) = Self::cell(at, within); - self.0.entry(text.to_owned()).or_default().entry((layer, class, x, y)).or_default().push((feature, at)); + // The text copied only the first time it is placed. + if !self.0.contains_key(text) { + self.0.insert(text.to_owned(), Default::default()); + } + if let Some(cells) = self.0.get_mut(text) { + cells.entry((layer, class, x, y)).or_default().push((feature, at)); + } } } @@ -9467,6 +9488,7 @@ mod tests { curves: None, line: None, row: 0, + remove_duplicates: None, }; let at = |p: &Placement| p.labels.iter().map(|l| (l.text.clone(), l.x, l.y)).collect::>(); // None: left out, as before. @@ -9509,6 +9531,7 @@ mod tests { curves: None, line: None, row: 0, + remove_duplicates: None, alternatives: vec![other.clone()], }; let blocker = label("Blocker", 100.0, None, 0.0); @@ -9547,6 +9570,7 @@ mod tests { curves: None, line: None, row: 0, + remove_duplicates: None, alternatives: vec![alternative.clone()], }; let projected = tilt_candidate(c, &|x, y| (y > 50.0).then_some((2.0 * x + 10.0, 2.0 * y))).unwrap(); @@ -9574,6 +9598,7 @@ mod tests { curves: None, line: None, row: 0, + remove_duplicates: None, }; let c = tilt_candidate(offer((10.0, 50.0), vec![(10.0, 60.0), (10.0, 150.0), (20.0, 160.0)]), &at).unwrap(); assert_eq!((c.label.x, c.label.y), (1010.0, 150.0)); @@ -9630,6 +9655,7 @@ mod tests { curves: None, line: None, row: usize::MAX, + remove_duplicates: None, } }) .collect() @@ -10512,11 +10538,9 @@ mod tests { #[test] fn a_class_removes_its_duplicates_within_a_distance() { // A label of `text` centred `x` points in, for feature `fid` of layer `lid`'s class `ci`. - let dup = |text: &str, x: f32, (lid, fid, ci): (u32, u64, u32), within: f32| -> Candidate { - let mut l = label(text, x, None, 0.0); - l.collide.source = Some((lid, fid, ci)); - l.collide.remove_duplicates = within; - (l, 0.0, (lid, fid, ci as usize, 0)).into() + let dup = |text: &str, x: f32, (lid, fid, ci): (u32, u64, usize), within: f32| -> Candidate { + let c: Candidate = (label(text, x, None, 0.0), 0.0, (lid, fid, ci, 0)).into(); + Candidate { remove_duplicates: (within > 0.0).then_some(within), ..c } }; let place = |c: Vec| place_labels_with_previews(c, Vec::new(), 2000.0, 40.0, false, true); let shown = |p: &Placement| p.labels.iter().map(|l| (l.text.clone(), l.center_x().round() as i32)).collect::>(); @@ -10557,6 +10581,17 @@ mod tests { assert_eq!(shown(&place(vec![main(100.0, 1, 0.0), main(250.0, 2, 0.0), elm()])).len(), 2, "kept, it hides Elm"); let p = place(vec![main(100.0, 1, 200.0), main(250.0, 2, 200.0), elm()]); assert_eq!(shown(&p), [("Main".into(), 100), ("Elm".into(), 250)]); + // In a tilted view a line's label has a place in each band: removed as a duplicate, none + // of them shows, as a flat view has the label once. + let banded = |x: f32| { + let c = main(x, 2, 200.0); + Candidate { line: Some(LinePlaces { deduplicate: true, ..Default::default() }), ..c } + }; + let mut head = banded(250.0); + if let Some(line) = head.line.as_mut() { + line.fallbacks = vec![banded(600.0)]; + } + assert_eq!(shown(&place(vec![main(100.0, 1, 200.0), head])), [("Main".into(), 100)], "no other band brings it back"); } /// A class's setting reaches its labels (#2847): two features of one layer with the same name @@ -10581,9 +10616,7 @@ mod tests { m }; assert_eq!(render(&mut map(None), &view).unwrap().labels.len(), 2, "off: both, as before"); - let one = render(&mut map(Some(200.0)), &view).unwrap().labels; - assert_eq!(one.len(), 1); - assert_eq!(one[0].collide.remove_duplicates, 200.0); + assert_eq!(render(&mut map(Some(200.0)), &view).unwrap().labels.len(), 1); } /// A tile style's label still comes after every layer's own, the lightest included (#2803). diff --git a/crates/render/src/line_positions_tests.rs b/crates/render/src/line_positions_tests.rs index 137e0068c6..a9df044b9b 100644 --- a/crates/render/src/line_positions_tests.rs +++ b/crates/render/src/line_positions_tests.rs @@ -13,6 +13,7 @@ fn curved(line: &[(f32, f32)]) -> Candidate { weight: 5, priority: 1.0, row: 0, + remove_duplicates: None, key: (1, 0, 0, 0), alternatives: Vec::new(), line: Some(LinePlaces::default()), diff --git a/crates/tiles/src/symbols.rs b/crates/tiles/src/symbols.rs index c3ce6a24ee..84c244d322 100644 --- a/crates/tiles/src/symbols.rs +++ b/crates/tiles/src/symbols.rs @@ -106,10 +106,6 @@ pub struct Collide { /// What it labels, for moving it by hand: its layer's id, its feature's id and its label /// class (in the layer's labeling order). None for labels not of a layer's features. pub source: Option<(u32, u64, u32)>, - /// Its class removes duplicates (#2847): left out within this many points of a label of - /// another feature of its [`source`](Self::source)'s layer and class with the same text; 0 - /// keeps every label. - pub remove_duplicates: f32, } impl Default for Collide { @@ -129,7 +125,6 @@ impl Default for Collide { callout_offset: None, pinned: false, source: None, - remove_duplicates: 0.0, } } } diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index c4558c5e37..21d83e16a9 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -1053,7 +1053,7 @@ fn crowding(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { ) .labelled_by(input_label.id) .on_hover_text(tl!("How close two labels of one text may be before the one placed later is left out.")); - if drag.settled(ui, &r, &mut v) && label_duplicates(v) != Some(within) { + if drag.settled(ui, &r, &mut v) && label_duplicates(v) != within { run(app, "labels.placement", c.params(json!({"removeDuplicates": label_duplicates(v)}))); } }); From 7ebf518e9c5a9fc218e61e56df8ba7f3b708829d Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 10:04:49 -0500 Subject: [PATCH 3/6] fix(labels): a removed duplicate gives back the searches it spent, and unticking mid-edit leaves removal off (#2847) A label removed as a duplicate gives back the curve layouts and callout searches it spent, so later labels keep theirs. In the Labeling pane, a typed distance that ends in the frame the Remove duplicates box changes yields to the box. PlacedTexts::insert looks the text up once. --- crates/render/src/lib.rs | 34 ++++++++++++++++++++++---- crates/ui-egui/src/labelpane.rs | 43 ++++++++++++++++++++++++++++++--- 2 files changed, 68 insertions(+), 9 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index c2bccc118f..059fae6be5 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -8280,6 +8280,8 @@ fn place_labels_with_previews( // Its own place, else the first alternative where all of it shows (the text moves there; // an icon stays). let mut at = None; + // What its curve layouts and callout search spend, given back if it goes as a duplicate. + let budgets = (layouts_left, searches, spots); let count = curves.as_ref().map_or(1 + alternatives.len(), |curves| curves.positions.len()); let original = LabelPlace::take(&mut l); // A failed curve at the middle still appears there once in View Unplaced. @@ -8394,6 +8396,8 @@ fn place_labels_with_previews( if grouped { placed_groups.insert(key); } + // It is drawn nowhere, so what it spent stays for the later labels. + (layouts_left, searches, spots) = budgets; continue; } if !show_text && !show_icon { @@ -8468,12 +8472,12 @@ impl PlacedTexts { fn insert(&mut self, (layer, feature, class, _): rustgis_map::LabelKey, text: &str, at: [f32; 2], within: f32) { let (x, y) = Self::cell(at, within); - // The text copied only the first time it is placed. - if !self.0.contains_key(text) { - self.0.insert(text.to_owned(), Default::default()); - } + let placed = (feature, at); if let Some(cells) = self.0.get_mut(text) { - cells.entry((layer, class, x, y)).or_default().push((feature, at)); + cells.entry((layer, class, x, y)).or_default().push(placed); + } else { + // The text copied only the first time it is placed. + self.0.insert(text.to_owned(), std::collections::HashMap::from([((layer, class, x, y), vec![placed])])); } } } @@ -10594,6 +10598,26 @@ mod tests { assert_eq!(shown(&place(vec![main(100.0, 1, 200.0), head])), [("Main".into(), 100)], "no other band brings it back"); } + /// A label removed as a duplicate gives back the callout searches it spent (#2847): with more + /// crowded duplicates than a placement has searches, a later label still moves to a free spot. + #[test] + fn a_removed_duplicate_gives_back_its_callout_searches() { + let crowded = |text: &str, fid: u64, priority: f64| { + let mut l = label(text, 100.0, None, 0.0); + l.collide.callout_reach = 40.0; + l.collide.callout_anchor = Some([0.0, 0.0]); + Candidate { remove_duplicates: Some(200.0), ..(l, priority, (1, fid, 0, 0)).into() } + }; + // One "Main", then more duplicates on top of it than there are searches, each moved by its + // callout and then removed; "Oak" comes last, crowded too. + let mut cands: Vec = (1..=MAX_CALLOUT_SEARCHES as u64 + 1).map(|fid| crowded("Main", fid, 0.0)).collect(); + cands.push(crowded("Oak", 10_000, -1.0)); + let placed = place_labels_with_previews(cands, Vec::new(), 2000.0, 200.0, false, true); + let oak = placed.labels.iter().find(|l| l.text == "Oak"); + assert!(oak.is_some_and(|l| l.collide.callout.is_some()), "Oak moved to a free spot with its line"); + assert_eq!(placed.labels.iter().filter(|l| l.text == "Main").count(), 1); + } + /// A class's setting reaches its labels (#2847): two features of one layer with the same name /// 150 points apart draw both labels, and one once the class removes duplicates within 200. #[test] diff --git a/crates/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 21d83e16a9..8ce46d8495 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -1027,12 +1027,12 @@ fn crowding(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { let input_label = ui.label(tl!("Remove duplicates")); ui.horizontal(|ui| { let mut on = c.it.remove_duplicates.is_some(); - if ui + let toggled = ui .checkbox(&mut on, "") .labelled_by(input_label.id) .on_hover_text(tl!("Draw one label of a text where features of this class with the same text lie closer than this.")) - .changed() - { + .changed(); + if toggled { let within = if on { json!(DEFAULT_LABEL_DUPLICATES) } else { json!(false) }; run(app, "labels.placement", c.params(json!({"removeDuplicates": within}))); } @@ -1053,7 +1053,8 @@ fn crowding(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { ) .labelled_by(input_label.id) .on_hover_text(tl!("How close two labels of one text may be before the one placed later is left out.")); - if drag.settled(ui, &r, &mut v) && label_duplicates(v) != within { + // An edit that ends in the frame the box changes yields to the box (#2847). + if drag.settled(ui, &r, &mut v) && !toggled && label_duplicates(v) != within { run(app, "labels.placement", c.params(json!({"removeDuplicates": label_duplicates(v)}))); } }); @@ -1864,6 +1865,40 @@ mod tests { assert_eq!(within(&h), None, "unticked: off"); } + /// Unticked while a typed distance is still being edited (#2847): the click that ends the edit + /// leaves removal off, not back on at the typed distance. + #[test] + fn unticking_remove_duplicates_mid_edit_leaves_it_off() { + use egui::accesskit::Role; + let mut h = harness(with_cities()); + h.run(); + let cities = layer_id(h.state(), "Cities"); + h.state_mut().session.run("layer.select", &json!({"layer": cities})).unwrap(); + h.state_mut().session.run("labels.placement", &json!({"layer": cities, "removeDuplicates": 200})).unwrap(); + h.run(); + open_tab(&mut h, "Position"); + h.get_by_role_and_label(Role::SpinButton, "Remove duplicates").focus(); + h.run(); + h.get_by_role_and_label(Role::SpinButton, "Remove duplicates").type_text("350"); + h.run(); + // The box pressed and let go in one frame: the edit ends in the frame the box changes. + let at = h.get_by_role_and_label(Role::CheckBox, "Remove duplicates").rect().center(); + let button = |pressed| egui::Event::PointerButton { + pos: at, + button: egui::PointerButton::Primary, + pressed, + modifiers: egui::Modifiers::NONE, + }; + h.event(egui::Event::PointerMoved(at)); + h.step(); + h.event(button(true)); + h.event(button(false)); + h.step(); + h.run(); + let within = h.state().session.map().layer_by_name("Cities").unwrap().labels.default.remove_duplicates; + assert_eq!(within, None, "unticked: off"); + } + /// A line layer's labels can try other places along the line (#1187): the box is there for a /// placement along the line without a repeat, and hiding it leaves what it was set to. #[test] From 5df29a8c77d875d99cb57dde287b79404b70bf93 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 10:12:25 -0500 Subject: [PATCH 4/6] perf(labels): a duplicate where it is spends no callout search, so the search caps hold (#2847) Giving a removed duplicate's budgets back lifted the caps on callout searches and curve layouts: crowded duplicates could run them without end. A label that is a duplicate where it is now goes without searching for a callout spot; one moved by its callout is still checked where it ends up. Nothing is given back, and the caps hold. --- crates/render/src/lib.rs | 34 +++++++++++++++++----------------- 1 file changed, 17 insertions(+), 17 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index f307b1d2ba..dc120a2c35 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -8286,8 +8286,6 @@ fn place_labels_with_previews( // Its own place, else the first alternative where all of it shows (the text moves there; // an icon stays). let mut at = None; - // What its curve layouts and callout search spend, given back if it goes as a duplicate. - let budgets = (layouts_left, searches, spots); let count = curves.as_ref().map_or(1 + alternatives.len(), |curves| curves.positions.len()); let original = LabelPlace::take(&mut l); // A failed curve at the middle still appears there once in View Unplaced. @@ -8349,6 +8347,13 @@ fn place_labels_with_previews( l.collide.callout = None; let relative = |l: &PlacedLabel, line: [f32; 4]| [line[0] - l.x, line[1] - l.y, line[2] - l.x, line[3] - l.y]; let mut moved_by = None; + // Its class removes duplicates (#2847): near a label of another feature of its layer and + // class with the same text, placed before it, it is left out. One moved by hand always shows. + let duplicate = |l: &PlacedLabel| { + remove_duplicates + .filter(|_| has_text && !collide.pinned) + .is_some_and(|within| placed_texts.near(key, &l.text, [l.center_x(), l.y], within)) + }; if let (true, Some([dx, dy])) = (locked && !collide.pinned, collide.callout_offset) { // Locked after a callout moved it: there again, with its line. moved_by = Some([dx, dy]); @@ -8372,6 +8377,8 @@ fn place_labels_with_previews( && has_text && text.iter().any(|b| grid.hits(b)) && searches > 0 + // A duplicate where it is goes rather than moving away from its twin: no search spent. + && !duplicate(&l) { // A callout: crowded where it is and at its alternatives, the label moves to the // nearest free spot within its reach, a line drawn back to its feature. With no such @@ -8390,20 +8397,13 @@ fn place_labels_with_previews( l.collide.callout = Some(relative(&l, line)); } } - // Its class removes duplicates (#2847): near a label of another feature of its layer and - // class with the same text, placed before it, it is left out. It takes no room and isn't - // shown as unplaced, as it wasn't short of room. One moved by hand always shows. - let dedupe = remove_duplicates.filter(|_| has_text).map(|within| (within, [l.center_x(), l.y])); - if let Some((within, centre)) = dedupe - && !collide.pinned - && placed_texts.near(key, &l.text, centre, within) - { + // Checked where it ends up, after a callout moved it: a duplicate takes no room and isn't + // shown as unplaced, as it wasn't short of room. + if duplicate(&l) { // A tilted view's other bands are places of the same label: none of them shows. if grouped { placed_groups.insert(key); } - // It is drawn nowhere, so what it spent stays for the later labels. - (layouts_left, searches, spots) = budgets; continue; } if !show_text && !show_icon { @@ -8416,8 +8416,8 @@ fn place_labels_with_previews( if show_text && !collide.text_ignore_placement { text.iter().for_each(|b| grid.insert(*b)); } - if let Some((within, centre)) = dedupe.filter(|_| show_text) { - placed_texts.insert(key, &l.text, centre, within); + if let Some(within) = remove_duplicates.filter(|_| show_text && has_text) { + placed_texts.insert(key, &l.text, [l.center_x(), l.y], within); } if show_icon && !collide.icon_ignore_placement { icon.iter().for_each(|b| grid.insert(*b)); @@ -10604,10 +10604,10 @@ mod tests { assert_eq!(shown(&place(vec![main(100.0, 1, 200.0), head])), [("Main".into(), 100)], "no other band brings it back"); } - /// A label removed as a duplicate gives back the callout searches it spent (#2847): with more - /// crowded duplicates than a placement has searches, a later label still moves to a free spot. + /// A label that is a duplicate where it is spends no callout search (#2847): with more crowded + /// duplicates than a placement has searches, a later label still moves to a free spot. #[test] - fn a_removed_duplicate_gives_back_its_callout_searches() { + fn a_duplicate_spends_no_callout_search() { let crowded = |text: &str, fid: u64, priority: f64| { let mut l = label(text, 100.0, None, 0.0); l.collide.callout_reach = 40.0; From 1a4dfba32ec7d34efe30a0b3dfdf8ddd41b4c462 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 11:19:23 -0500 Subject: [PATCH 5/6] fix(labels): locked labels all show again, also where zooming out brings two within the distance (#2847) Replaying a lock took a locked label out as a duplicate when zooming out brought it within the distance of its twin. Duplicates are left out when the lock is taken; replaying it shows every locked label, as for any other placement rule. --- crates/render/src/lib.rs | 21 +++++++++++++++++++-- docs/user-guide/cartography.md | 3 ++- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index dc120a2c35..dbc87465e4 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -8348,10 +8348,11 @@ fn place_labels_with_previews( let relative = |l: &PlacedLabel, line: [f32; 4]| [line[0] - l.x, line[1] - l.y, line[2] - l.x, line[3] - l.y]; let mut moved_by = None; // Its class removes duplicates (#2847): near a label of another feature of its layer and - // class with the same text, placed before it, it is left out. One moved by hand always shows. + // class with the same text, placed before it, it is left out. One moved by hand always shows, + // as do the labels of a lock, which was taken with duplicates already left out. let duplicate = |l: &PlacedLabel| { remove_duplicates - .filter(|_| has_text && !collide.pinned) + .filter(|_| has_text && !collide.pinned && !locked) .is_some_and(|within| placed_texts.near(key, &l.text, [l.center_x(), l.y], within)) }; if let (true, Some([dx, dy])) = (locked && !collide.pinned, collide.callout_offset) { @@ -10604,6 +10605,22 @@ mod tests { assert_eq!(shown(&place(vec![main(100.0, 1, 200.0), head])), [("Main".into(), 100)], "no other band brings it back"); } + /// Locked labels all show again (#2847): two labels of one text locked 300 points apart, then + /// 150 apart after zooming out, both stay; removing duplicates applies when the lock is taken. + #[test] + fn locked_labels_keep_their_duplicates() { + let twins = || { + [(100.0, 1), (250.0, 2)] + .map(|(x, fid)| Candidate { remove_duplicates: Some(200.0), ..(label("Main", x, None, 0.0), 0.0, (1, fid, 0, 0)).into() }) + }; + let count = |locked| { + let placed = place_labels_with_previews(twins(), Vec::new(), 2000.0, 200.0, locked, true); + placed.labels.iter().filter(|l| l.text == "Main").count() + }; + assert_eq!(count(false), 1, "taking the lock: one"); + assert_eq!(count(true), 2, "replaying the lock: both"); + } + /// A label that is a duplicate where it is spends no callout search (#2847): with more crowded /// duplicates than a placement has searches, a later label still moves to a free spot. #[test] diff --git a/docs/user-guide/cartography.md b/docs/user-guide/cartography.md index 38145b6824..3210d4a2e6 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -665,7 +665,8 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: placed first stays (the heavier class's, then the layer above); the others take no room, so other labels can use it, and View Unplaced doesn't show them. Only labels of the same layer and class are compared, by their text as drawn (case counts); a line's repeated labels aren't - duplicates, and a label moved by hand always shows (`labels.placement={"layer": "Streets", + duplicates, and a label moved by hand always shows. With labels locked, the locked labels all + show again, also where zooming out brings two of them closer (`labels.placement={"layer": "Streets", "removeDuplicates": 300}`; a number past 1 or 2000 is brought to it, with a notice; `false` or `null` turns it off). - **Callouts** (Labeling pane › Position): a label crowded off its spot moves to the nearest free From 5406f2126941335597aa5a81b95450a5a81b2f53 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Tue, 24 Nov 2026 11:41:23 -0500 Subject: [PATCH 6/6] docs(labels): a duplicate that was also short of room isn't shown as unplaced either (#2847) --- crates/render/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index dbc87465e4..4d3288ccac 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -8399,7 +8399,7 @@ fn place_labels_with_previews( } } // Checked where it ends up, after a callout moved it: a duplicate takes no room and isn't - // shown as unplaced, as it wasn't short of room. + // shown as unplaced, even when it was also short of room, as being a duplicate comes first. if duplicate(&l) { // A tilted view's other bands are places of the same label: none of them shows. if grouped {