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
37 changes: 30 additions & 7 deletions crates/map/src/diagram.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,10 +9,11 @@
//! always in range, and read from a project through [`de_diagram`], which takes a malformed one
//! (a hostile file) as `None` and leaves the rest of the layer reading.

use rustgis_data::Dataset;
use rustgis_data::{Dataset, GeometryType};
use serde::{Deserialize, Serialize};

use crate::color::Rgba;
use crate::fills::{FillLayer, FillPattern};
use crate::symbology::{LegendEntry, LineMark, LineMarkers, LineStroke, Marker, Symbol};

/// The most categories one diagram lists (each is a slice or a bar).
Expand Down Expand Up @@ -256,9 +257,11 @@ impl DiagramSettings {
}

/// The legend rows of its categories: one per category, in draw order, its field the label.
/// On a line layer the colour goes in the stroke, which is what a line's swatch draws; else it
/// is the fill, with a white outline.
pub fn legend(&self, line: bool) -> Vec<LegendEntry> {
/// Each row carries its colour in a stack of its own, or it would take the layer's stacked
/// strokes or fills and every category would look the same: on a line layer one stroke, on a
/// polygon layer one fill (with a white outline), on a point layer its mark.
pub fn legend(&self, g: GeometryType) -> Vec<LegendEntry> {
let line = g == GeometryType::Polyline;
self.categories
.iter()
.map(|c| LegendEntry {
Expand All @@ -270,7 +273,15 @@ impl DiagramSettings {
size: 7.0,
marker: Marker::Circle,
},
strokes: vec![category_mark(c.colour)],
strokes: match g {
GeometryType::Point => vec![category_mark(c.colour)],
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
GeometryType::Polyline => vec![LineStroke { color: Some(c.colour), width: Some(1.0), ..LineStroke::default() }],
_ => Vec::new(),
},
fills: match g {
GeometryType::Polygon => vec![FillLayer { color: Some(c.colour), pattern: FillPattern::Solid }],
_ => Vec::new(),
},
fallback: false,
})
.collect()
Expand Down Expand Up @@ -510,14 +521,26 @@ mod tests {

#[test]
fn legend_lists_one_row_per_category() {
let l = settings().legend(false);
let l = settings().legend(GeometryType::Point);
assert_eq!(l.iter().map(|e| e.label.as_str()).collect::<Vec<_>>(), ["pop_male", "pop_female"]);
assert_eq!(l[0].symbol.fill, CATEGORY_COLORS[0]);
assert_eq!(l[0].symbol.stroke, Rgba::rgb(0xFF, 0xFF, 0xFF), "a white outline on a polygon or point layer");
assert!(l.iter().all(|e| !e.fallback));
assert_eq!(l[0].strokes[0].color, Some(CATEGORY_COLORS[0]), "its own mark, not the layer's stacked ones");
let line = settings().legend(true);
let line = settings().legend(GeometryType::Polyline);
assert_eq!(line[0].symbol.stroke, CATEGORY_COLORS[0], "a line's swatch draws its stroke, so the colour is there");
assert_eq!(
line[0].strokes,
[LineStroke { color: Some(CATEGORY_COLORS[0]), width: Some(1.0), ..LineStroke::default() }],
"one stroke, not the layer's"
);
let area = settings().legend(GeometryType::Polygon);
assert_eq!(
area[0].fills,
[FillLayer { color: Some(CATEGORY_COLORS[0]), pattern: FillPattern::Solid }],
"one fill, not the layer's"
);
assert!(area[0].strokes.is_empty());
}

#[test]
Expand Down
1 change: 1 addition & 0 deletions crates/map/src/symbol_by.rs
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,7 @@ impl SizeBy {
label: format!("{} {}", self.field, crate::symbology::fmt_num(v)),
symbol: hide_zero(Symbol { size, ..like }),
strokes: scaled_marks(strokes, k),
fills: Vec::new(),
fallback: false,
}
})
Expand Down
51 changes: 32 additions & 19 deletions crates/map/src/symbology.rs
Original file line number Diff line number Diff line change
Expand Up @@ -993,15 +993,28 @@ pub struct LegendEntry {
pub symbol: Symbol,
/// The stacked strokes its class has of its own; empty, it takes the layer's `line_strokes`.
pub strokes: Vec<LineStroke>,
/// The stacked fills its class has of its own; empty, it takes the layer's `fill_layers`.
pub fills: Vec<FillLayer>,
/// The Unique Values fallback row (`<all other values>`), told apart from a class whatever
/// its label: a legend can leave it out without touching a class that bears the same name.
pub fallback: bool,
}

impl LegendEntry {
/// A class's row, with the stacked strokes it has of its own, if any.
fn class(label: String, symbol: Symbol, strokes: Option<&Vec<LineStroke>>) -> Self {
LegendEntry { label, symbol, strokes: strokes.cloned().unwrap_or_default(), fallback: false }
/// A class's row, with the stacked strokes and fills it has of its own, if any.
fn class(label: String, symbol: Symbol, strokes: Option<&Vec<LineStroke>>, fills: Option<&Vec<FillLayer>>) -> Self {
LegendEntry {
label,
symbol,
strokes: strokes.cloned().unwrap_or_default(),
fills: fills.cloned().unwrap_or_default(),
fallback: false,
}
}

/// A row with no stacked strokes or fills of its own.
pub fn plain(label: String, symbol: Symbol) -> Self {
LegendEntry { label, symbol, strokes: Vec::new(), fills: Vec::new(), fallback: false }
}
}

Expand Down Expand Up @@ -1703,6 +1716,7 @@ impl Renderer {
other_fills,
other_strokes,
class_strokes,
class_fills,
..
} = self
else {
Expand Down Expand Up @@ -1766,13 +1780,14 @@ impl Renderer {
.into_iter()
.filter(|i| used.get(*i).copied().unwrap_or(false))
.filter_map(|i| classes.get(i))
.map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k)))
.map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k), class_fills.get(k)))
.collect();
if other_used && visible {
v.push(LegendEntry {
label: other_label.clone().unwrap_or_else(|| OTHER_VALUES.into()),
symbol: *other,
strokes: other_strokes.clone(),
fills: other_fills.clone(),
fallback: true,
});
}
Expand Down Expand Up @@ -1813,31 +1828,34 @@ impl Renderer {
let used = rows.is_none_or(|rows| {
(0..ds.features.len()).any(|r| rows.get(r).copied().unwrap_or(true) && fi.and_then(|fi| ds.value(r, fi).as_f64()).is_none())
});
used.then(|| LegendEntry { label: "No data".into(), symbol: self.symbol_in(ds, 0, None), strokes: Vec::new(), fallback: false })
used.then(|| LegendEntry::plain("No data".into(), self.symbol_in(ds, 0, None)))
}

/// Every row of its legend, whatever the features: the classes, then a Unique Values'
/// `<all other values>`; none for a single symbol.
pub fn legend(&self) -> Vec<LegendEntry> {
match self {
Renderer::Single(_) => Vec::new(),
Renderer::Unique { classes, other, class_labels, other_label, class_strokes, other_strokes, .. } => {
Renderer::Unique {
classes, other, class_labels, other_label, class_strokes, other_strokes, class_fills, other_fills, ..
} => {
// Keep symbols attached to their classes in `class_order` and the fallback at the end.
let mut v: Vec<LegendEntry> = self
.class_order()
.into_iter()
.filter_map(|i| classes.get(i))
.map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k)))
.map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k), class_fills.get(k)))
.collect();
v.push(LegendEntry {
label: other_label.clone().unwrap_or_else(|| OTHER_VALUES.into()),
symbol: *other,
strokes: other_strokes.clone(),
fills: other_fills.clone(),
fallback: true,
});
v
}
Renderer::Graduated { breaks, symbols, min, class_labels, class_strokes, .. } => {
Renderer::Graduated { breaks, symbols, min, class_labels, class_strokes, class_fills, .. } => {
let mut lo = *min;
breaks
.iter()
Expand All @@ -1846,19 +1864,14 @@ impl Renderer {
.map(|(i, (b, s))| {
let label = class_labels.get(&i).cloned().unwrap_or_else(|| range_label(lo, *b));
lo = *b;
LegendEntry::class(label, *s, class_strokes.get(&i))
LegendEntry::class(label, *s, class_strokes.get(&i), class_fills.get(&i))
})
.collect()
}
Renderer::Proportional { base, min_size, max_size, min, max, .. } => vec![
LegendEntry { label: fmt_num(*min), symbol: Symbol { size: *min_size, ..*base }, strokes: Vec::new(), fallback: false },
LegendEntry {
label: fmt_num((min + max) / 2.0),
symbol: Symbol { size: min_size + (max_size - min_size) * 0.707, ..*base },
strokes: Vec::new(),
fallback: false,
},
LegendEntry { label: fmt_num(*max), symbol: Symbol { size: *max_size, ..*base }, strokes: Vec::new(), fallback: false },
LegendEntry::plain(fmt_num(*min), Symbol { size: *min_size, ..*base }),
LegendEntry::plain(fmt_num((min + max) / 2.0), Symbol { size: min_size + (max_size - min_size) * 0.707, ..*base }),
LegendEntry::plain(fmt_num(*max), Symbol { size: *max_size, ..*base }),
],
}
}
Expand Down Expand Up @@ -1987,7 +2000,7 @@ impl Renderer {
// The class's row in `legend()`, which lists the classes and then `other`. Unique Values
// rows are sorted by label, so that class's row is built here rather than looked up.
let row = match (&mut *self, class) {
(Renderer::Unique { classes, class_labels, class_strokes, .. }, ClassRef::Value(v)) => {
(Renderer::Unique { classes, class_labels, class_strokes, class_fills, .. }, ClassRef::Value(v)) => {
let i = classes.iter().position(|(k, _)| k == v).ok_or_else(|| format!("no class with the value '{v}'"))?;
if let Some((k, s)) = classes.get_mut(i) {
restyle(s);
Expand All @@ -2004,7 +2017,7 @@ impl Renderer {
}
return classes
.get(i)
.map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k)))
.map(|(k, s)| LegendEntry::class(unique_label(class_labels, k), *s, class_strokes.get(k), class_fills.get(k)))
.ok_or_else(|| "the class has no legend row".into());
}
(Renderer::Unique { classes, other, other_label, .. }, ClassRef::Other) => {
Expand Down
Loading
Loading