diff --git a/crates/engine/command-surface.txt b/crates/engine/command-surface.txt index fd716f98be..66997b4fcb 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? callout? guide? +labels.placement layer? class? position? to? side? offset? repeat? lineOffset? otherPositions? fit? abbreviations? showAll? weight? clearance? 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 9a649c19d7..58338f2696 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", "callout", "to", "side", "fit", "abbreviations", "guide"] + None if ["offset", "repeat", "lineOffset", "otherPositions", "showAll", "weight", "clearance", "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 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, 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). @@ -213,6 +213,15 @@ pub fn commands() -> Vec { }; let weight_asked = weight.filter(|w| w.fract() != 0.0 || !rustgis_map::symbology::LABEL_WEIGHT.contains(w)); let weight = weight.map(rustgis_map::symbology::label_weight); + // The room its labels keep free of other labels (#2828): 0 to 100 points, null back to + // 2. A number out of range is held to it, and says so. + let clearance = match p.get("clearance") { + None => None, + Some(Value::Null) => Some(f64::from(rustgis_map::symbology::DEFAULT_LABEL_CLEARANCE)), + Some(v) => Some(number(v).ok_or("clearance must be a number of points from 0 to 100 (null: 2)")?), + }; + let clearance_asked = clearance.filter(|c| !rustgis_map::symbology::LABEL_CLEARANCE.contains(c)); + let clearance = clearance.map(rustgis_map::symbology::label_clearance); // Every label shown, over the others where they crowd. let show_all = match p.get("showAll") { None => None, @@ -299,6 +308,9 @@ pub fn commands() -> Vec { if let Some(w) = weight { c.weight = w; } + if let Some(r) = clearance { + c.clearance = r; + } if let Some(f) = fit { c.fit = f; } @@ -376,12 +388,24 @@ pub fn commands() -> Vec { false, ); } + if let Some(asked) = clearance_asked { + let name = s.map().layer(id).map(|l| l.name.clone()).unwrap_or_default(); + let kept = rustgis_map::symbology::label_clearance(asked); + let asked = if asked.abs() < 1e6 { asked.to_string() } else { format!("{asked:e}") }; + s.notify_text( + NoticeText::format( + "{name}: clearance {asked} adjusted to {kept} (a label's clearance is from 0 to 100 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, 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), "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, 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)}"#, ), // 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 d35873f884..692f811739 100644 --- a/crates/engine/src/project.rs +++ b/crates/engine/src/project.rs @@ -113,6 +113,7 @@ pub const CAPABILITIES: &[&str] = &[ "label-weight", PROJECT_CRS, "dggs-system", + "label-clearance", ]; /// 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 a386007591..edc7198d00 100644 --- a/crates/engine/src/project_capabilities.rs +++ b/crates/engine/src/project_capabilities.rs @@ -66,6 +66,12 @@ impl Project { { required.push("label-weight"); } + // And their clearances (#2828), for the same reason. + if !required.contains(&"label-clearance") + && self.styles.iter().any(|s| s.labels.in_order().any(|c| c.clearance != rustgis_map::symbology::DEFAULT_LABEL_CLEARANCE)) + { + required.push("label-clearance"); + } 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::>()); @@ -141,8 +147,23 @@ const COMMAND_CAPABILITIES: &[(&str, CommandCheck)] = &[ ("layout-text-size", command_uses_text_size), ("dggs-system", command_uses_dggs_system), ("label-weight", command_weighs_labels), + ("label-clearance", command_clears_labels), ]; +/// 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. +fn command_clears_labels(id: &str, params: &Value) -> bool { + match id { + "labels.placement" => params + .get("clearance") + .and_then(crate::cmd::labels::number) + .is_some_and(|c| rustgis_map::symbology::label_clearance(c) != rustgis_map::symbology::DEFAULT_LABEL_CLEARANCE), + "script.run" => params.get("script").and_then(Value::as_str).is_some_and(|s| script_uses(s, command_clears_labels)), + _ => false, + } +} + /// A saved `labels.placement` that gives a class a weight other than 5, read as the command reads /// it (#2803): an older reader runs it without the key, saying nothing, so the labels would compete /// as before. 5 or null is what an older reader keeps. @@ -546,6 +567,12 @@ fn label_weight(layer: &Layer) -> bool { layer.labels.in_order().any(|c| c.weight != rustgis_map::symbology::DEFAULT_LABEL_WEIGHT) } +/// Whether a layer's label classes keep other than the default room free (#2828): an older reader +/// would drop the clearances, and place and save the labels as without them. +fn label_clearance(layer: &Layer) -> bool { + layer.labels.in_order().any(|c| c.clearance != rustgis_map::symbology::DEFAULT_LABEL_CLEARANCE) +} + /// The capabilities a layer needs, in [`map_capabilities`]'s order. fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { [ @@ -556,6 +583,7 @@ fn layer_capabilities(layer: &Layer) -> Vec<&'static str> { (zarr_window(layer), "zarr-window"), (label_guide(layer), "label-guide"), (label_weight(layer), "label-weight"), + (label_clearance(layer), "label-clearance"), (held_natively(&layer.dataset), super::NATIVE_COORDINATES), ] .into_iter() @@ -582,13 +610,14 @@ 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) = (false, false, false, false, false); + let (mut offline_area_id, mut paper, mut native, mut guided, mut weighed, mut cleared) = (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. paper |= map.paper.is_some(); guided |= map.layers.iter().any(label_guide); weighed |= map.layers.iter().any(label_weight); + cleared |= map.layers.iter().any(label_clearance); // 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; @@ -635,6 +664,7 @@ fn map_capabilities<'a>(maps: impl IntoIterator) -> Vec<&'static (zarr, "zarr-window"), (guided, "label-guide"), (weighed, "label-weight"), + (cleared, "label-clearance"), (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 4f36d42006..0efe0572a8 100644 --- a/crates/engine/src/project_label_losses.rs +++ b/crates/engine/src/project_label_losses.rs @@ -81,6 +81,8 @@ struct Class { #[serde(default)] weight: Option, #[serde(default)] + clearance: Option, + #[serde(default)] stretch: Option, } @@ -100,6 +102,8 @@ struct Labels { #[serde(default)] weight: Option, #[serde(default)] + clearance: Option, + #[serde(default)] square_to: Option, #[serde(default)] guide: Option, @@ -162,6 +166,12 @@ fn adjusted_weight(value: Option<&serde_json::Value>) -> bool { value.is_some_and(|v| !v.is_null() && v.as_f64().is_none_or(|n| n.fract() != 0.0 || !rustgis_map::symbology::LABEL_WEIGHT.contains(&n))) } +/// A label clearance (#2828) that isn't a number from 0 to 100 (held to it, or 2 when it isn't a +/// number); null is 2. +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))) +} + /// 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 { @@ -256,7 +266,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) = (0usize, 0usize); + let (mut guides, mut weights, mut clearances) = (0usize, 0usize, 0usize); let mut diagrams = rustgis_map::diagram::DiagramAudit::default(); for layer in raw { diagrams = diagrams.plus(layer.diagram); @@ -267,6 +277,7 @@ fn count<'a>( offsets = offsets.saturating_add(usize::from(adjusted_line_offset(labels.line_offset.as_ref()))); 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()))); 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()))); @@ -276,6 +287,7 @@ fn count<'a>( offsets = offsets.saturating_add(usize::from(adjusted_line_offset(class.line_offset.as_ref()))); 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()))); 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()))); @@ -301,6 +313,9 @@ fn count<'a>( if weights > 0 { messages.push(format!("{name}: {weights} label weight(s) not a whole number from 0 to 10 adjusted while opening {what}")); } + if clearances > 0 { + messages.push(format!("{name}: {clearances} label clearance(s) not a number from 0 to 100 points adjusted 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 a6684e6da3..d38d6042ca 100644 --- a/crates/engine/src/tests.rs +++ b/crates/engine/src/tests.rs @@ -9238,6 +9238,126 @@ fn saved_label_weights_are_required_by_name() { assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["label-weight"])); } +/// A label class takes a clearance (#2828): the points kept free of other labels round its +/// labels, 0 to 100, 2 by default. A fraction is kept; a number out of range is held and said, +/// junk refused, null back to 2. It undoes in one step, keeps a lock, is saved only when it isn't +/// 2, and then requires `label-clearance`, which an older reader refuses rather than drop. +#[test] +fn a_label_class_takes_a_clearance() { + let mut s = world(); + let id = s.map().layer_by_name("Cities").unwrap().id; + let clearances = |s: &Session| { + let l = &s.map().layer(id).unwrap().labels; + (l.default.clearance, l.classes.first().map(|c| c.clearance)) + }; + let said = |s: &Session, mark| s.notices_since(mark).iter().map(|n| n.text.clone()).collect::>(); + assert_eq!(clearances(&s), (2.0, None)); + let mark = s.notice_mark(); + s.run("labels.placement", &json!({"layer": "Cities", "clearance": 10})).unwrap(); + assert_eq!(clearances(&s), (10.0, None)); + assert!(said(&s, mark).is_empty(), "{:?}", said(&s, mark)); + s.run("edit.undo", &json!({})).unwrap(); + assert_eq!(clearances(&s), (2.0, None), "undoes"); + // A fraction is kept, as a text number is read. + s.run("labels.placement", &json!({"layer": "Cities", "clearance": 2.5})).unwrap(); + assert_eq!(clearances(&s).0, 2.5); + s.run("labels.placement", &json!({"layer": "Cities", "clearance": "0"})).unwrap(); + assert_eq!(clearances(&s).0, 0.0); + for (given, kept, note) in [(json!(500), 100.0, "clearance 500 adjusted to 100"), (json!(-3), 0.0, "clearance -3 adjusted to 0")] { + let mark = s.notice_mark(); + s.run("labels.placement", &json!({"layer": "Cities", "clearance": given})).unwrap(); + assert_eq!(clearances(&s).0, kept, "{given}"); + let notes = said(&s, mark); + assert!(notes.iter().any(|n| n.contains(note)), "{given}: {notes:?}"); + } + for bad in [json!("wide"), json!(true), json!([1])] { + let err = s.run("labels.placement", &json!({"layer": "Cities", "clearance": bad})).unwrap_err(); + assert!(err.contains("clearance must be a number of points from 0 to 100 (null: 2)"), "{bad}: {err}"); + } + s.run("labels.placement", &json!({"layer": "Cities", "clearance": null})).unwrap(); + assert_eq!(clearances(&s), (2.0, None), "null: back to 2"); + // 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", "clearance": 12})).unwrap(); + assert_eq!(clearances(&s), (2.0, Some(12.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", "clearance": 6})).unwrap(); + assert!(s.map().label_lock.is_some(), "a clearance keeps the lock"); + // Saved, it requires `label-clearance`, and reads back. + let saved = serde_json::to_value(&s.project).unwrap(); + assert_eq!(saved["requires"], json!(["label-clearance"])); + 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].clearance, 6.0); + // Back to 2 everywhere: nothing to require, and nothing saved. + s.run("labels.placement", &json!({"layer": "Cities", "class": "Big", "clearance": 2})).unwrap(); + let saved = serde_json::to_value(&s.project).unwrap(); + assert!(saved.get("requires").is_none()); + assert!(!saved.to_string().contains("clearance"), "a clearance of 2 isn't written"); + // The fixture (`label_clearance.rgis`) reads back as saved, saying nothing. + let mut fixture = Project::from_json(include_str!("../../../schema/fixtures/label_clearance.rgis")).unwrap(); + assert_eq!(fixture.maps[0].layers[0].labels.default.clearance, 6.5); + assert!(fixture.take_read_notices(&crate::project::ALL_PARTS).is_empty()); + assert_eq!(serde_json::to_value(&fixture).unwrap()["requires"], json!(["label-clearance"])); + // A clearance out of range or junk in a file is held, and said once. + let mut damaged = serde_json::to_value(&world().project).unwrap(); + damaged["maps"][0]["layers"][0]["labels"]["clearance"] = json!(999); + damaged["maps"][0]["layers"][1]["labels"]["clearance"] = json!("x"); + let read = Session::new(Project::from_json(&damaged.to_string()).unwrap()); + assert_eq!(read.map().layers[0].labels.default.clearance, 100.0); + assert_eq!(read.map().layers[1].labels.default.clearance, 2.0); + let notes: Vec<_> = read.notices.iter().filter(|n| n.text.contains("label clearance")).map(|n| n.text.clone()).collect(); + assert!(notes.len() == 1 && notes[0].contains("2 label clearance(s)"), "{notes:?}"); +} + +/// A clearance other than 2 saved in a task, a model's step or a script, or in a saved style, also +/// requires `label-clearance`: an older reader would run the step, or apply the style, without +/// it, saying nothing (#2828). A clearance of 2 or null needs nothing: that is what an older +/// reader keeps. +#[test] +fn saved_label_clearances_are_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": "Clear", "steps": [{"title": "Clear", "command": "labels.placement", "params": params}]}), + ) + .unwrap(), + ]; + serde_json::to_value(&project).unwrap().get("requires").cloned() + }; + for clearance in [json!(8), json!(0), json!("8"), json!(2.5), json!(500)] { + assert_eq!( + with_task(json!({"layer": "Cities", "position": "above", "clearance": clearance})), + Some(json!(["label-clearance"])), + "{clearance}" + ); + } + for nothing in [ + json!({"layer": "Cities", "clearance": 2}), + json!({"layer": "Cities", "clearance": 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\", \"clearance\": 9}"}); + 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-clearance"])); + // A saved style keeps the clearance its layer had. + let mut s = world(); + s.run("labels.placement", &json!({"layer": "Cities", "clearance": 7})).unwrap(); + s.run("style.new", &json!({"layer": "Cities", "name": "Roomy"})).unwrap(); + s.run("labels.placement", &json!({"layer": "Cities", "clearance": 2})).unwrap(); + assert_eq!(serde_json::to_value(&s.project).unwrap()["requires"], json!(["label-clearance"])); +} + /// 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 0baf947360..f536f3c22f 100644 --- a/crates/map/src/qgis/labels.rs +++ b/crates/map/src/qgis/labels.rs @@ -321,6 +321,7 @@ fn class( line_offset: 0.0, show_all: false, weight: crate::symbology::DEFAULT_LABEL_WEIGHT, + clearance: crate::symbology::DEFAULT_LABEL_CLEARANCE, callout: None, square_to: None, guide: None, diff --git a/crates/map/src/symbology.rs b/crates/map/src/symbology.rs index da292b2e86..f3f67ae048 100644 --- a/crates/map/src/symbology.rs +++ b/crates/map/src/symbology.rs @@ -2667,6 +2667,14 @@ pub struct LabelClass { /// equal weights keep the layer above and the class listed first ahead. #[serde(default = "default_label_weight", deserialize_with = "de_label_weight", skip_serializing_if = "is_default_label_weight")] pub weight: u8, + /// The room (points, within [`LABEL_CLEARANCE`], [`DEFAULT_LABEL_CLEARANCE`] by default) its + /// labels' text keeps free of other labels; two labels keep both their clearances apart. + #[serde( + default = "default_label_clearance", + deserialize_with = "de_label_clearance", + skip_serializing_if = "is_default_label_clearance" + )] + pub clearance: f32, /// 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. @@ -3016,6 +3024,30 @@ fn is_default_label_weight(w: &u8) -> bool { *w == DEFAULT_LABEL_WEIGHT } +/// The room a label's text keeps free of other labels (#2828), in points. +pub const LABEL_CLEARANCE: std::ops::RangeInclusive = 0.0..=100.0; + +/// The clearance of a class that sets none, and of every label before clearances: the padding +/// every label kept. +pub const DEFAULT_LABEL_CLEARANCE: f32 = 2.0; + +/// A label's clearance: within [`LABEL_CLEARANCE`]; one that isn't a number is the default. +pub fn label_clearance(v: f64) -> f32 { + if v.is_finite() { v.clamp(*LABEL_CLEARANCE.start(), *LABEL_CLEARANCE.end()) as f32 } else { DEFAULT_LABEL_CLEARANCE } +} + +fn de_label_clearance<'de, D: serde::Deserializer<'de>>(d: D) -> Result { + Ok(lenient::(d)?.map_or(DEFAULT_LABEL_CLEARANCE, label_clearance)) +} + +fn default_label_clearance() -> f32 { + DEFAULT_LABEL_CLEARANCE +} + +fn is_default_label_clearance(c: &f32) -> bool { + *c == DEFAULT_LABEL_CLEARANCE +} + fn is_no_offset(o: &[f32; 2]) -> bool { *o == [0.0; 2] } @@ -3434,6 +3466,7 @@ impl LabelClass { line_offset: 0.0, show_all: false, weight: DEFAULT_LABEL_WEIGHT, + clearance: DEFAULT_LABEL_CLEARANCE, callout: None, square_to: None, guide: None, diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 881b210697..1506ebbdb9 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -6423,6 +6423,8 @@ fn render_frame( line_align: class.line_align, angle, collide: rustgis_tiles::Collide { + // Its class's room kept free of other labels (#2828). + text_padding: class.clearance, // 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, @@ -7975,10 +7977,17 @@ const MAX_CALLOUT_SEARCHES: usize = 500; /// Spots a placement tries for its callouts at most, all its searches together. const MAX_CALLOUT_SPOTS: usize = 200_000; -/// A label's text's extent (points, `[x0, y0, x1, y1]`), as placement keeps it clear of the -/// others: what the Move Label tool picks it by. +/// A label's text's extent (points, `[x0, y0, x1, y1]`): what the Move Label tool picks it by. pub fn label_extent(l: &PlacedLabel) -> Option<[f32; 4]> { - boxes_extent(&label_boxes(l).0) + boxes_extent(&text_edges(l)) +} + +/// A label's text's boxes as its callout's line and the Move Label tool see them: with the room +/// every label kept before clearances, whatever its class keeps clear of the others (#2828), so a +/// clearance moves the others off without leaving the line short of the text or widening the pick. +fn text_edges(l: &PlacedLabel) -> Vec<[f32; 4]> { + let text_padding = rustgis_map::symbology::DEFAULT_LABEL_CLEARANCE; + label_boxes(&PlacedLabel { collide: rustgis_tiles::Collide { text_padding, ..l.collide }, ..l.clone() }).0 } /// The extent of boxes (`[x0, y0, x1, y1]` each); none for none. @@ -7994,7 +8003,7 @@ fn boxes_extent(boxes: &[[f32; 4]]) -> Option<[f32; 4]> { /// For showing a label being moved by hand. pub fn callout_to(l: &PlacedLabel) -> Option<[f32; 4]> { let [ax, ay] = l.collide.callout_anchor.filter(|_| l.collide.callout_reach > 0.0)?; - let line = callout_line(&label_boxes(l).0, [l.x + ax, l.y + ay])?; + let line = callout_line(&text_edges(l), [l.x + ax, l.y + ay])?; Some([line[0] - l.x, line[1] - l.y, line[2] - l.x, line[3] - l.y]) } @@ -8010,11 +8019,13 @@ fn callout_line(text: &[[f32; 4]], anchor: [f32; 2]) -> Option<[f32; 4]> { } /// Where a crowded label with a callout goes: the nearest free spot for its text's boxes, inside -/// the view, whose line from its feature at `anchor` to the nearest edge of its text is at most -/// `reach` long (points), and which doesn't cover the feature. The offset that moves it there and -/// that line (from, to), or none. +/// the view, whose line from its feature at `anchor` to the nearest edge of its text (`edges`, +/// [`text_edges`]) is at most `reach` long (points), and which doesn't cover the feature. The +/// offset that moves it there and that line (from, to), or none. +#[expect(clippy::too_many_arguments, reason = "the boxes that collide and the edges its line ends at, besides where and how far it may go")] fn callout_spot( text: &[[f32; 4]], + edges: &[[f32; 4]], anchor: [f32; 2], reach: f32, free: impl Fn(&[f32; 4]) -> bool, @@ -8022,7 +8033,7 @@ fn callout_spot( h: f32, spots: &mut usize, ) -> Option<(f32, f32, [f32; 4])> { - let ext = boxes_extent(text)?; + let ext = boxes_extent(edges)?; if !(anchor[0].is_finite() && anchor[1].is_finite() && reach.is_finite()) { return None; } @@ -8187,7 +8198,7 @@ fn place_labels_with_previews( // Locked after a callout moved it: there again, with its line. moved_by = Some([dx, dy]); if let Some(f) = feature.filter(|_| collide.callout_reach > 0.0) - && let Some(line) = callout_line(&text, f) + && let Some(line) = callout_line(&text_edges(&l), f) { l.collide.callout = Some(relative(&l, line)); } @@ -8195,7 +8206,7 @@ fn place_labels_with_previews( // Moved by hand: where it was put, a callout's line back to its feature when its class // has callouts (however long: it was put there). if let Some(f) = feature.filter(|_| collide.callout_reach > 0.0) - && let Some(line) = callout_line(&text, f) + && let Some(line) = callout_line(&text_edges(&l), f) { l.collide.callout = Some(relative(&l, line)); } @@ -8211,7 +8222,9 @@ fn place_labels_with_previews( // nearest free spot within its reach, a line drawn back to its feature. With no such // spot it stays, and is left out, or shown over the others when its class shows all. searches -= 1; - if let Some((dx, dy, line)) = callout_spot(&text, f, collide.callout_reach, |b| !grid.hits(b), w, h, &mut spots) { + if let Some((dx, dy, line)) = + callout_spot(&text, &text_edges(&l), f, collide.callout_reach, |b| !grid.hits(b), w, h, &mut spots) + { moved_by = Some([dx, dy]); l.x += dx; l.y += dy; @@ -8302,6 +8315,9 @@ fn label_boxes(l: &PlacedLabel) -> (Vec<[f32; 4]>, Vec<[f32; 4]>) { // padding across, and up and down. let halo = text::drawn_halo_reach(l); let [across, up_down] = text::background_reach(l).map(|r| l.collide.text_padding.clamp(0.0, 100.0) + halo.max(r)); + // A class's clearance (#2828) reaches here as the padding, held to 100 points as a tile + // style's `text-padding` always was: at 100 a curved label's square is some 200 points + // across, about 7 × 7 grid cells, the bound placement already had for tile labels. let p = across.max(up_down); let cx = l.center_x(); if !l.glyphs.is_empty() { @@ -8996,6 +9012,49 @@ mod tests { assert!(p.labels[1].collide.callout.is_some()); } + /// A class's clearance keeps other labels off (#2828), not its callout's line or the Move Label + /// tool: the line still ends at the text's edge, a crowded label's reach still counts to it, and + /// the label is still picked by its text, whatever the clearance. + #[test] + fn a_clearance_keeps_others_off_but_not_the_callout_or_the_pick() { + use rustgis_tiles::Collide; + let pinned = |padding: f32| PlacedLabel { + y: 50.0, + collide: Collide { + text_padding: padding, + pinned: true, + callout_reach: 40.0, + callout_anchor: Some([-80.0, 0.0]), + ..Default::default() + }, + ..label("Moved", 150.0, None, 0.0) + }; + let (plain, clear) = (pinned(2.0), pinned(12.0)); + assert_eq!(label_extent(&clear), label_extent(&plain), "picked by its text, not its clearance"); + assert_eq!(callout_to(&clear), callout_to(&plain), "a drag's line ends at the text"); + let line = + |l: PlacedLabel| place_labels(vec![(l, 1e15, (u32::MAX, 1, 0, 0))], Vec::new(), 300.0, 120.0, false).labels[0].collide.callout; + assert_eq!(line(clear), line(plain), "a moved label's line ends at the text"); + // Crowded off its spot: moved, its line from its feature to its text's nearest edge. + let at = |text: &str, collide: Collide| PlacedLabel { + y: 50.0, + collide: Collide { callout_anchor: Some([0.0, 10.0]), ..collide }, + ..label(text, 100.0, None, 0.0) + }; + let cands = vec![ + (at("First", Collide::default()), 2.0, (u32::MAX, 0, 0, 0)), + (at("Second", Collide { text_padding: 12.0, callout_reach: 40.0, ..Default::default() }), 1.0, (u32::MAX, 1, 0, 0)), + ]; + let p = place_labels(cands, Vec::new(), 300.0, 120.0, false); + let second = p.labels.iter().find(|l| l.text == "Second").expect("moved, not left out"); + let [x0, y0, x1, y1] = second.collide.callout.expect("a callout's line"); + let e = label_extent(second).unwrap(); + let (fx, fy) = (second.x + x0, second.y + y0); + let to = [fx.clamp(e[0], e[2]), fy.clamp(e[1], e[3])]; + assert!(((second.x + x1) - to[0]).abs() < 1e-3 && ((second.y + y1) - to[1]).abs() < 1e-3, "to the text's edge"); + assert!((x1 - x0).hypot(y1 - y0) <= 40.0, "within its reach, counted to the text"); + } + /// A callout's line is drawn from its feature to the text, in the label's colour. #[test] fn a_callout_line_is_drawn() { @@ -9997,15 +10056,16 @@ mod tests { // A small text by its feature at (100, 100); only spots 200 points right of it are free. let text = [[95.0, 98.0, 105.0, 102.0]]; let free = |b: &[f32; 4]| b[0] > 300.0; - let (dx, _, [x0, y0, x1, y1]) = callout_spot(&text, [100.0, 100.0], 300.0, free, 1000.0, 200.0, &mut 100_000).expect("a spot"); + let (dx, _, [x0, y0, x1, y1]) = + callout_spot(&text, &text, [100.0, 100.0], 300.0, free, 1000.0, 200.0, &mut 100_000).expect("a spot"); assert!(dx > 195.0); let len = (x1 - x0).hypot(y1 - y0); assert!((150.0..=300.0).contains(&len), "{len} points"); // Beyond its reach, none. - assert!(callout_spot(&text, [100.0, 100.0], 100.0, free, 1000.0, 200.0, &mut 100_000).is_none()); + assert!(callout_spot(&text, &text, [100.0, 100.0], 100.0, free, 1000.0, 200.0, &mut 100_000).is_none()); // The placement's spots used up: it stops looking, and says how many it tried. let mut spots = 5; - assert!(callout_spot(&text, [100.0, 100.0], 300.0, free, 1000.0, 200.0, &mut spots).is_none()); + assert!(callout_spot(&text, &text, [100.0, 100.0], 300.0, free, 1000.0, 200.0, &mut spots).is_none()); assert_eq!(spots, 0); } @@ -10205,6 +10265,66 @@ mod tests { assert_eq!(shown(&mut m).len(), 2, "Show All draws every label whatever its weight"); } + /// A class's clearance is the room its labels keep free of other labels (#2828): two labels + /// keep both their clearances apart, as the fixed padding did, a fraction honoured; 0 lets + /// them come as close as their halos allow. A label moved by hand keeps its class's. + #[test] + fn a_label_class_keeps_its_clearance_free_of_other_labels() { + let center = Coord::new(2.35, 48.85); + let camera = Camera { center: lonlat_to_merc(center), 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 }; + // Two point layers, "Aaaa" above, "Bbbb" `apart` points to its right, with these + // clearances. + let map = |apart: f32, [ca, cb]: [f32; 2]| { + let mut m = Map::new("Map"); + for (name, dx, clearance) in [("Bbbb", apart, cb), ("Aaaa", 0.0, ca)] { + let mut d = Dataset::new(name, GeometryType::Point, vec![Field::new("name", FieldType::Text)]); + let at = rustgis_geom::merc_to_lonlat(Coord::new(camera.center.x + f64::from(dx) * camera.res, camera.center.y)); + d.push(Some(Geometry::Point(at)), vec![Value::Text(name.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.clearance = clearance; + } + m + }; + let drawn = |m: &mut Map| render(m, &view).unwrap().labels; + let shown = |m: &mut Map| { + let mut v: Vec = drawn(m).into_iter().map(|l| l.text).collect(); + v.sort(); + v + }; + // Far apart, how wide the texts are and how far their halos reach. + let far = drawn(&mut map(300.0, [2.0, 2.0])); + assert_eq!(far.len(), 2); + assert!(far.iter().all(|l| l.collide.text_padding == 2.0), "2 to start with, as before"); + let reach = |l: &PlacedLabel| text::label_width(l) / 2.0 + text::drawn_halo_reach(l); + let (a, b) = (far.iter().find(|l| l.text == "Aaaa").unwrap(), far.iter().find(|l| l.text == "Bbbb").unwrap()); + // Centres so far apart that `room` points lie between the halos. + let apart = |room: f32| reach(a) + reach(b) + room; + // Six points between them: 2 + 2 leave both in, as before. + assert_eq!(shown(&mut map(apart(6.0), [2.0, 2.0])), ["Aaaa", "Bbbb"]); + // Either one's clearance grown to 5 (5 + 2 > 6): the layer above keeps its place. + assert_eq!(shown(&mut map(apart(6.0), [5.0, 2.0])), ["Aaaa"], "the upper label's clearance"); + assert_eq!(shown(&mut map(apart(6.0), [2.0, 5.0])), ["Aaaa"], "the lower label's clearance"); + // A fraction is honoured: 3.9 + 2 < 6. + assert_eq!(shown(&mut map(apart(6.0), [3.9, 2.0])), ["Aaaa", "Bbbb"]); + // A point between them: 2 + 2 keep one out, 0 + 0 let both in. + assert_eq!(shown(&mut map(apart(1.0), [2.0, 2.0])), ["Aaaa"]); + let close = drawn(&mut map(apart(1.0), [0.0, 0.0])); + assert_eq!(close.len(), 2, "no clearance: only the halos keep them apart"); + assert!(close.iter().all(|l| l.collide.text_padding == 0.0)); + // Moved by hand, a label keeps its class's clearance. + let mut m = map(300.0, [9.0, 2.0]); + let id = m.layers.iter().find(|l| l.name == "Aaaa").unwrap().id; + let fid = m.layer(id).unwrap().dataset.features[0].id; + m.layer_mut(id).unwrap().labels.default.moved = vec![rustgis_map::symbology::MovedLabel { id: fid, at: [center.x, center.y] }]; + let moved = drawn(&mut m).into_iter().find(|l| l.text == "Aaaa").unwrap(); + assert_eq!(moved.collide.text_padding, 9.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/ui-egui/src/labelpane.rs b/crates/ui-egui/src/labelpane.rs index 2e6fdb6426..f4d8d487a0 100644 --- a/crates/ui-egui/src/labelpane.rs +++ b/crates/ui-egui/src/labelpane.rs @@ -966,10 +966,11 @@ 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; and callouts, which move a crowded label to a -/// free spot nearby with a line back to its feature, no longer than so far. +/// 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. fn crowding(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { - use rustgis_engine::map::symbology::{CALLOUT_REACH, LABEL_WEIGHT, callout_reach, label_weight}; + use rustgis_engine::map::symbology::{CALLOUT_REACH, LABEL_CLEARANCE, LABEL_WEIGHT, callout_reach, label_clearance, label_weight}; let id = l.id; grid(ui, "crowding", |ui| { let input_label = ui.label(tl!("Show all labels")); @@ -998,6 +999,27 @@ fn crowding(app: &mut RustGisApp, ui: &mut Ui, l: &Layer, c: &Class) { } }); ui.end_row(); + let input_label = ui.label(tl!("Clearance")); + // As the weight: scoped to its layer and class, written when let go (#2828). + ui.push_id(("label_clearance", l.instance_id(), c.name), |ui| { + let mut v = f64::from(c.it.clearance); + let drag = crate::widgets::Dragged::lend(ui, egui::Id::unique(("label_clearance_drag", l.instance_id(), c.name)), &mut v); + let r = ui + .add( + egui::DragValue::new(&mut v) + .update_while_editing(false) + .range(LABEL_CLEARANCE) + .speed(0.1) + .max_decimals(1) + .suffix(" pt"), + ) + .labelled_by(input_label.id) + .on_hover_text(tl!("The room this class's labels keep free of other labels.")); + if drag.settled(ui, &r, &mut v) && label_clearance(v) != c.it.clearance { + run(app, "labels.placement", c.params(json!({"clearance": label_clearance(v)}))); + } + }); + ui.end_row(); let input_label = ui.label(tl!("Callouts")); ui.horizontal(|ui| { let mut on = c.it.callout.is_some(); @@ -1678,6 +1700,79 @@ mod tests { assert_eq!(h.state().session.undo_depth(), steps, "nothing to undo"); } + /// A label class's clearance (#2828) is shown and set in Position, under Weight: typed, a + /// fraction kept; dragged, one step when let go; another layer chosen mid-drag, nothing. + #[test] + fn a_label_clearance_is_set_in_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.state_mut().session.run("labels.placement", &json!({"layer": cities, "clearance": 7})).unwrap(); + h.run(); + open_tab(&mut h, "Position"); + let clearance = + |h: &egui_kittest::Harness<'_, RustGisApp>| h.state().session.map().layer_by_name("Cities").unwrap().labels.default.clearance; + let shown = h.get_by_role_and_label(Role::SpinButton, "Clearance").accesskit_node().numeric_value(); + assert_eq!(shown, Some(7.0), "the class's clearance"); + h.get_by_role_and_label(Role::SpinButton, "Clearance").focus(); + h.run(); + h.get_by_role_and_label(Role::SpinButton, "Clearance").type_text("9.5"); + h.key_press(egui::Key::Enter); + h.run(); + assert_eq!(clearance(&h), 9.5); + // Dragged slowly left over several frames, then let go: four less, in one step. + h.state_mut().session.run("labels.placement", &json!({"layer": cities, "clearance": 7})).unwrap(); + h.run(); + let steps = h.state().session.undo_depth(); + let at = h.get_by_role_and_label(Role::SpinButton, "Clearance").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(); + // (A few points of the first move start the drag, so not quite four.) + assert!((2.5..4.0).contains(&clearance(&h)), "each frame's part of the drag counts: {}", clearance(&h)); + assert_eq!(h.state().session.undo_depth(), steps + 1, "a drag is one step"); + // Another layer chosen mid-drag: the drag is dropped, neither layer's clearance changed + // and nothing to undo. + let rivers = layer_id(h.state(), "Rivers"); + let before = clearance(&h); + let steps = h.state().session.undo_depth(); + h.event(egui::Event::PointerMoved(at)); + h.step(); + h.event(button(at, true)); + h.step(); + for i in 1..=5 { + h.event(egui::Event::PointerMoved(at + egui::vec2(8.0 * i as f32, 0.0))); + h.step(); + } + h.state_mut().session.run("layer.select", &json!({"layer": rivers})).unwrap(); + for i in 6..=10 { + h.event(egui::Event::PointerMoved(at + egui::vec2(8.0 * i as f32, 0.0))); + h.step(); + } + h.event(button(at + egui::vec2(80.0, 0.0), false)); + h.step(); + h.run(); + let m = h.state().session.map(); + assert_eq!((m.layer(cities).unwrap().labels.default.clearance, m.layer(rivers).unwrap().labels.default.clearance), (before, 2.0)); + assert_eq!(h.state().session.undo_depth(), steps, "nothing to undo"); + } + /// 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 ed74f6591d..86b3eb3031 100644 --- a/docs/maintaining.md +++ b/docs/maintaining.md @@ -169,6 +169,11 @@ a saved style, or a saved `labels.placement` step (in a task, a model or a scrip other than 5: an older reader would apply the style, or run the step, without the weight, saying nothing. +Likewise a label class keeping other than 2 points free round its labels (`labels.placement` with a +`clearance`) requires `label-clearance`, in a layer, a saved style or a saved `labels.placement` +step: an older reader would place the labels 2 points apart and save them again without the +clearances, 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 0060749504..50296bc590 100644 --- a/docs/user-guide/cartography.md +++ b/docs/user-guide/cartography.md @@ -650,6 +650,14 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: win over the towns' without moving the river layer above them, which would change what draws on top (`labels.placement={"layer": "Rivers", "weight": 8}`; a fraction is rounded and a number past 0 or 10 brought to it, with a notice; `null` is 5). +- **Clearance** (Labeling pane › Position): the room, in points, a class's labels keep free of + other labels (0 to 100, 2 to start with, the room every label kept before). Two labels keep + both their clearances apart: a river's name with 10 keeps a town's with 2 at least 12 points + away, so some labels that fitted before are left out or try their other places. 0 lets the + class's labels come as close as their halos and backgrounds allow. It counts round the text + 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). - **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 @@ -669,8 +677,9 @@ Turn labels on per layer (Labeling › Labels › **Label**), then: moves and old label locks because replacement data can reuse feature ids, with a counted notice 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, and Show all labels - settings that were not true or false. A callout length given + 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 + 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. - **Font**: the labels' font family, any installed on the computer (Labeling pane › Symbol diff --git a/schema/fixtures/label_clearance.rgis b/schema/fixtures/label_clearance.rgis new file mode 100644 index 0000000000..35ed08c784 --- /dev/null +++ b/schema/fixtures/label_clearance.rgis @@ -0,0 +1 @@ +{"requires":["label-clearance"],"format":2,"name":"Label clearance","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,"clearance":6.5},"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 c62f548873..36ea36d0a8 100644 --- a/schema/project.schema.json +++ b/schema/project.schema.json @@ -1276,7 +1276,8 @@ "label-guide", "label-weight", "project-crs", - "dggs-system" + "dggs-system", + "label-clearance" ], "type": "string" }, @@ -1381,7 +1382,8 @@ "label-guide", "label-weight", "project-crs", - "dggs-system" + "dggs-system", + "label-clearance" ], "x-rustgis-reads-format": 2, "x-rustgis-writes-format": 2