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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions crates/data/src/geometry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -310,6 +310,15 @@ impl Geometry {
false
}

/// The part of a polygon [`label_point`](Self::label_point) places its point in: the largest
/// valid one. `None` for other geometries.
pub fn label_part(&self) -> Option<&Vec<Vec<Coord>>> {
match self {
Geometry::Polygon(polys) => largest_part(polys),
_ => None,
}
}

/// A point for a label or a pop-up: the point itself, the middle vertex of the longest line
/// part, or the centroid of the largest valid polygon (moved inside it if the centroid falls out).
///
Expand Down
35 changes: 20 additions & 15 deletions crates/engine/src/cmd/labels.rs
Original file line number Diff line number Diff line change
Expand Up @@ -275,7 +275,8 @@ pub fn commands() -> Vec<C> {
// `to: null`: this call takes the line away.
let clears = matches!(to, Some(None));
let id = s.layer_id(p)?;
let (points, lines) = points_and_lines(s.map().layer(id).ok_or("no such layer")?);
let held = held_geometries(s.map().layer(id).ok_or("no such layer")?);
let (_, lines, _) = held;
let guide = label_guide(s, p, s.map().layer(id).ok_or("no such layer")?)?;
// A repeat or line offset given where it does nothing (not along a line), kept for
// when the class is placed along one, and said (#2639).
Expand Down Expand Up @@ -344,8 +345,8 @@ pub fn commands() -> Vec<C> {
}
// Asked of the class as this call leaves it, so a position or a repeat given with
// it counts. On where it would do nothing is refused; off is taken anywhere.
if others == Some(true) && !tries_other_places(points, lines, c) {
return Err("otherPositions is for points, and for lines placed parallel or curved without a repeat".into());
if others == Some(true) && !tries_other_places(held, c) {
return Err("otherPositions is for points, for polygons whose labels aren't curved or along a guide, and for lines placed parallel or curved without a repeat".into());
}
if !(lines && c.placement.along_line()) {
if repeat.is_some_and(|r| r.is_some()) {
Expand Down Expand Up @@ -429,7 +430,7 @@ pub fn commands() -> Vec<C> {
.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, 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)}"#,
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; a polygon's goes first where its shape fits best inside it, then where it goes without this; true is refused for any other line label, and on polygons for a curved label or one along a guide), "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| {
Expand Down Expand Up @@ -598,10 +599,10 @@ pub fn commands() -> Vec<C> {
]
}

/// Whether the layer holds points and lines: declared so, or among its features, as the renderer
/// Whether the layer holds points, lines and polygons: declared so, or among its features, as the renderer
/// goes by each feature's geometry.
fn points_and_lines(l: &Layer) -> (bool, bool) {
(l.has_geometry(GeometryType::Point), l.has_geometry(GeometryType::Polyline))
fn held_geometries(l: &Layer) -> (bool, bool, bool) {
(l.has_geometry(GeometryType::Point), l.has_geometry(GeometryType::Polyline), l.has_geometry(GeometryType::Polygon))
}

/// `labels.placement`'s `to`: the line or polygon layer a perpendicular label is square to, by
Expand Down Expand Up @@ -665,11 +666,12 @@ fn label_guide(s: &Session, p: &Value, labelled: &Layer) -> Result<Option<Option
Ok(Some(Some(LabelGuide { layer: layer.name.clone(), field })))
}

/// Whether a class on a layer holding these has other places to try when its label's own is taken:
/// round a point at any position (#1011), or along a line for a label at its middle (#1187). Each
/// Whether a class on a layer holding these (points, lines, polygons) has other places to try when
/// its label's own is taken: round a point at any position (#1011), along a line for a label at its
/// middle (#1187), or inside a polygon for a label neither curved nor along a guide (#3268). Each
/// repeat is already a place of its own, so repeats get none.
fn tries_other_places(points: bool, lines: bool, c: &LabelClass) -> bool {
points || (lines && c.placement.along_line() && c.repeat.is_none())
fn tries_other_places((points, lines, polygons): (bool, bool, bool), c: &LabelClass) -> bool {
points || (lines && c.placement.along_line() && c.repeat.is_none()) || (polygons && c.places_inside_polygons())
}

/// `labels.by`: sets a label class's expressions, each checked against the layer's fields.
Expand Down Expand Up @@ -776,21 +778,24 @@ pub(crate) fn lock_holds(l: &Layer, b: &Labeling) -> bool {

/// Whether the layer's classes and those of `b` (listed alike) put their labels in the same places.
/// A lock names the place round its point or along its line a label took by its number among its
/// class's (#1011, #1187), so another position, or trying the others turned on or off, locks the
/// class's (#1011, #1187, #3268), so another position, or trying the others turned on or off, locks the
/// labels again; with no class trying them a new position keeps the lock, as before. The flag only
/// counts where it has an effect: kept on a line's class at a position off the line, or with a
/// repeat, it does nothing ([`tries_other_places`]). Along a line, off it, each place is tried on
/// both sides, the label's own first: its number says which, so the other side, or a distance
/// where there was none, locks the labels again too; another distance on the same side doesn't.
fn same_places(l: &Layer, b: &Labeling) -> bool {
let (points, lines) = points_and_lines(l);
let held = held_geometries(l);
let (_, lines, _) = held;
let classes = |labels: &Labeling| {
let tries = |c: &LabelClass| c.other_positions && tries_other_places(points, lines, c);
let tries = |c: &LabelClass| c.other_positions && tries_other_places(held, c);
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
// -1 below, 1 above, 0 on the line (-0.0 too).
let side = |c: &LabelClass| {
if lines && c.placement.along_line() { i8::from(c.line_offset > 0.0) - i8::from(c.line_offset < 0.0) } else { 0 }
};
labels.classes.iter().chain([&labels.default]).map(|c| (c.placement, tries(c), c.repeat.is_some(), side(c))).collect::<Vec<_>>()
// A repeat counts only along a line, where it places labels.
let repeats = |c: &LabelClass| lines && c.placement.along_line() && c.repeat.is_some();
labels.classes.iter().chain([&labels.default]).map(|c| (c.placement, tries(c), repeats(c), side(c))).collect::<Vec<_>>()
};
classes(&l.labels).into_iter().zip(classes(b)).all(|(x, y)| x == y || !(x.1 || y.1))
}
Expand Down
64 changes: 53 additions & 11 deletions crates/engine/src/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9564,8 +9564,8 @@ fn converting_labels_along_lines_says_what_they_lose() {

/// A point label class tries the other places round its point when told to (#1011): alone it keeps
/// the position, junk is refused (in it or in the position) and so is turning it on for lines at a
/// position off them and for polygons, it undoes, the project keeps it, and turning it on or off
/// while the labels are locked locks them again (the places they took no longer stand).
/// position off them, it undoes, the project keeps it, and turning it on or off while the labels
/// are locked locks them again (the places they took no longer stand).
#[test]
fn labels_take_other_positions_round_points() {
use crate::render::View;
Expand All @@ -9591,12 +9591,11 @@ fn labels_take_other_positions_round_points() {
assert!(!class(&s).0);
s.run("labels.placement", &json!({"layer": "Cities", "position": null, "otherPositions": false})).unwrap();
assert_eq!(class(&s), (false, placement), "null is no position");
// Only a point's label goes round it: on is refused for a line off its line (along it, see
// labels_take_other_positions_along_lines) and for polygons, off taken anywhere.
for layer in ["Rivers", "Countries"] {
assert!(s.run("labels.placement", &json!({"layer": layer, "otherPositions": true})).is_err(), "{layer}");
s.run("labels.placement", &json!({"layer": layer, "otherPositions": false})).unwrap();
}
// On is refused for a line off its line (along it, see
// labels_take_other_positions_along_lines; polygons, labels_take_other_positions_in_polygons),
// off taken anywhere.
assert!(s.run("labels.placement", &json!({"layer": "Rivers", "otherPositions": true})).is_err());
s.run("labels.placement", &json!({"layer": "Rivers", "otherPositions": false})).unwrap();
s.run("labels.placement", &json!({"layer": "Cities", "otherPositions": true})).unwrap();
let text = serde_json::to_string(&s.project).unwrap();
assert!(Session::new(serde_json::from_str(&text).unwrap()).map().layer_by_name("Cities").unwrap().labels.default.other_positions);
Expand All @@ -9614,6 +9613,52 @@ fn labels_take_other_positions_round_points() {
assert!(s.map().label_lock.is_none(), "turned on: locked again");
}

/// A polygon label class tries its pole of inaccessibility when told to (#3268): at any position
/// but curved, and without a guide. A refusal changes nothing, it undoes, the project keeps it, and
/// turning it on or off locks the labels again.
#[test]
fn labels_take_other_positions_in_polygons() {
use crate::render::View;
let mut s = world();
let id = s.map().layer_by_name("Countries").unwrap().id;
let on = |s: &Session| s.map().layer(id).unwrap().labels.default.other_positions;
assert!(!on(&s));
s.run("labels.placement", &json!({"layer": id, "otherPositions": true})).unwrap();
assert!(on(&s));
s.run("edit.undo", &json!({})).unwrap();
assert!(!on(&s), "undoes");
for position in ["center", "above", "parallel"] {
s.run("labels.placement", &json!({"layer": id, "position": position, "otherPositions": true})).unwrap();
s.run("labels.placement", &json!({"layer": id, "otherPositions": false})).unwrap();
}
s.run("labels.placement", &json!({"layer": id, "position": "auto"})).unwrap();
assert!(s.run("labels.placement", &json!({"layer": id, "position": "curved", "otherPositions": true})).is_err());
let guide = json!({"layer": "Rivers"});
assert!(s.run("labels.placement", &json!({"layer": id, "guide": guide, "otherPositions": true})).is_err());
let class = &s.map().layer(id).unwrap().labels.default;
assert!(!class.other_positions && class.guide.is_none() && class.placement == rustgis_map::LabelPlacement::Auto, "nothing changes");
for position in ["curved", "auto"] {
s.run("labels.placement", &json!({"layer": id, "position": position, "otherPositions": false})).unwrap();
}
s.run("labels.placement", &json!({"layer": id, "otherPositions": true})).unwrap();
let text = serde_json::to_string(&s.project).unwrap();
assert!(on(&Session::new(serde_json::from_str(&text).unwrap())));
s.run("labels.enable", &json!({"layer": id, "on": true})).unwrap();
let v = View { width: 800.0, height: 600.0, pixels_per_point: 1.0, camera: s.map().camera, sky: false };
// A repeat does nothing on a polygon, so it keeps the lock.
s.run("labels.lock", &json!({"on": true})).unwrap();
crate::render::render(s.map_mut(), &v).unwrap();
s.run("labels.placement", &json!({"layer": id, "repeat": 144})).unwrap();
assert!(s.map().label_lock.is_some(), "a repeat moves no polygon label");
for turn in [false, true] {
s.run("labels.lock", &json!({"on": true})).unwrap();
crate::render::render(s.map_mut(), &v).unwrap();
assert!(s.map().label_lock.is_some());
s.run("labels.placement", &json!({"layer": id, "otherPositions": turn})).unwrap();
assert!(s.map().label_lock.is_none(), "turned {turn}: locked again");
}
}

/// A line label class tries other places along its line when told to (#1187): only placed parallel
/// or curved and without a repeat, judged on what the call leaves, in the class it names. A refusal
/// changes nothing, a later position or repeat keeps the flag, it undoes, the project keeps it, and
Expand Down Expand Up @@ -9654,9 +9699,6 @@ fn labels_take_other_positions_along_lines() {
for bad in [json!("yes"), json!(1), Value::Null] {
assert!(s.run("labels.placement", &json!({"layer": "Rivers", "otherPositions": bad})).is_err(), "{bad}");
}
// Polygons have no such places, even placed parallel.
assert!(s.run("labels.placement", &json!({"layer": "Countries", "position": "parallel", "otherPositions": true})).is_err());
s.run("labels.placement", &json!({"layer": "Countries", "otherPositions": false})).unwrap();
// Judged in the class named, not in Default; a class that isn't there is refused.
s.run("labels.placement", &json!({"layer": "Rivers", "position": "above", "otherPositions": false})).unwrap();
s.run("labels.class.add", &json!({"layer": "Rivers", "name": "Big"})).unwrap();
Expand Down
3 changes: 2 additions & 1 deletion crates/map/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2232,7 +2232,8 @@ pub struct Map {
/// drawn while the lock holds, there, wherever the map moves. Filled by the renderer.
#[serde(skip)]
pub label_lock: Option<Vec<(LabelKey, LockedPlace)>>,
/// Geographic anchors of locked non-repeated line labels. Render cache only, never saved.
/// Geographic anchors of locked non-repeated line labels, and of polygon labels trying places
/// inside. Render cache only, never saved.
#[serde(skip)]
pub label_lock_line_anchors: std::collections::HashMap<LabelKey, Coord>,
/// Relationships, snapping, topology rules and edit settings.
Expand Down
Loading
Loading