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: 8 additions & 1 deletion crates/render/src/layout/legend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,13 @@ pub fn legend_lists(l: &rustgis_map::Layer) -> bool {
!l.graphics && l.raster.as_ref().is_none_or(|r| r.style.renderer.draws_classes())
}

/// Where a legend ordering its layers `layer_order` (#3279) lists the layer `name`: its place in
/// the order, or after every layer the order names. A stable sort of the map's stack by it gives
/// the legend's order, as it draws it and as its Layers section lists it (#3294).
pub fn legend_place(layer_order: &[String], name: &str) -> usize {
layer_order.iter().position(|o| o.eq_ignore_ascii_case(name)).unwrap_or(usize::MAX)
}

/// What a layer a legend lists draws at 1:`scale` ([`rustgis_map::Layer::shown_legend`]); for a
/// classified raster, the classes it holds ([`raster_classes`]). `None` when it draws nothing
/// there.
Expand Down Expand Up @@ -1021,7 +1028,7 @@ pub(super) fn legend_rows_missing<'a>(
rustgis_map::Drawn::Layer(i) => map.layers.get(i).map(|l| &l.name),
rustgis_map::Drawn::Tile(i) => map.tiles.get(i).map(|t| &t.name),
};
name.and_then(|n| opts.layer_order.iter().position(|o| o.eq_ignore_ascii_case(n))).unwrap_or(usize::MAX)
name.map_or(usize::MAX, |n| legend_place(opts.layer_order, n))
});
}
for item in stack {
Expand Down
92 changes: 68 additions & 24 deletions crates/ui-egui/src/layoutview/format/legend.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@
use super::*;
use crate::RustGisApp;
use crate::widgets::Dragged;
use egui::Ui;
use egui::{Ui, vec2};
use rustgis_engine::map::Drawn;
use rustgis_engine::map::layout::{Element, ElementKind, Layout, LegendFit, MAX_LEGEND_COLUMNS};
use rustgis_engine::render::layout::{legend_lists, legend_place};
use serde_json::{Value, json};

/// A legend's rows in the grid.
Expand Down Expand Up @@ -103,7 +105,7 @@ pub(super) fn legend_layers(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout,
// The layers a legend lists: a checkbox for each vector layer of its frame's map, each raster
// drawn by classes (#1679) and each WMS or WMTS layer with a legend, ticked when listed. Names
// gone from the map drop out of the list as it's written back.
if let ElementKind::Legend { frame, exclude, .. } = &e.kind {
if let ElementKind::Legend { frame, exclude, layer_order, .. } = &e.kind {
let map = layout.element(*frame).and_then(|f| match &f.kind {
ElementKind::MapFrame { map, .. } => app.session.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(map)),
_ => None,
Expand All @@ -112,39 +114,81 @@ pub(super) fn legend_layers(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout,
.map(|m| {
// Once each: layers may share a name, and the legend leaves names out.
let mut names: Vec<String> = Vec::new();
let listed = m.layers.iter().filter(|l| rustgis_engine::render::layout::legend_lists(l)).map(|l| &l.name);
for name in listed.chain(m.tiles.iter().filter(|t| !t.legends.is_empty()).map(|t| &t.name)) {
let listed = m.stack().into_iter().filter_map(|d| match d {
Drawn::Layer(i) => m.layers.get(i).filter(|l| legend_lists(l)).map(|l| &l.name),
Drawn::Tile(i) => m.tiles.get(i).filter(|t| !t.legends.is_empty()).map(|t| &t.name),
});
for name in listed {
if !names.iter().any(|n| n.eq_ignore_ascii_case(name)) {
names.push(name.clone());
}
}
// As the legend draws them.
names.sort_by_cached_key(|n| legend_place(layer_order, n));
names
})
.unwrap_or_default();
let on_map = |x: &str| {
map.is_some_and(|m| m.layers.iter().map(|l| &l.name).chain(m.tiles.iter().map(|t| &t.name)).any(|n| n.eq_ignore_ascii_case(x)))
};
// The names left out that the map still has, those not listed here (a raster's on a ramp)
// too.
let kept: Vec<String> = exclude
.iter()
.filter(|x| {
map.is_some_and(|m| {
m.layers.iter().map(|l| &l.name).chain(m.tiles.iter().map(|t| &t.name)).any(|n| n.eq_ignore_ascii_case(x))
})
})
.cloned()
.collect();
if !names.is_empty() {
let kept: Vec<String> = exclude.iter().filter(|x| on_map(x)).cloned().collect();
// The same for the names ordered that aren't listed here.
let unlisted: Vec<&String> = layer_order.iter().filter(|x| on_map(x) && !names.iter().any(|n| n.eq_ignore_ascii_case(x))).collect();
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
// With none to list, still there to drop the legend's own order.
if !names.is_empty() || !layer_order.is_empty() {
ui.add_space(4.0);
egui::CollapsingHeader::new(tl!("Layers")).id_salt(("legend_layers", id)).default_open(!exclude.is_empty()).show(ui, |ui| {
let open = !exclude.is_empty() || !layer_order.is_empty();
egui::CollapsingHeader::new(tl!("Layers")).id_salt(("legend_layers", id)).default_open(open).show(ui, |ui| {
let left_out = |n: &str| exclude.iter().any(|x| x.eq_ignore_ascii_case(n));
for n in &names {
let mut listed = !left_out(n);
if ui.checkbox(&mut listed, n.as_str()).on_hover_text(tl!("List this layer in the legend")).changed() {
let mut next: Vec<&String> = kept.iter().filter(|x| !x.eq_ignore_ascii_case(n)).collect();
if !listed {
next.push(n);
}
update(app, json!({"exclude": next}));
}
// The place a row moves with, up or down.
let mut swap = None;
for (i, n) in names.iter().enumerate() {
// Ids from the layer, not the row's place (`push_id` would mix it in), so the
// keyboard's focus moves with its layer.
let row_id = ui.make_persistent_id(n.to_ascii_lowercase());
ui.scope_builder(egui::UiBuilder::new().scope_id(row_id), |ui| {
// The arrows on the right, the name in what they leave.
let row = vec2(ui.available_width(), ui.spacing().interact_size.y);
ui.allocate_ui_with_layout(row, egui::Layout::right_to_left(egui::Align::Center), |ui| {
// Named for its layer, so each row's arrows tell apart to a screen reader.
let arrow = |ui: &mut Ui, glyph: &str, on: bool, hover: &str, label: String| {
let r = ui.add_enabled(on, egui::Button::new(glyph).small());
r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, on, &label));
r.on_hover_text(hover).clicked()
};
let args = [("name", n.as_str())];
if arrow(ui, "▼", i + 1 < names.len(), tl!("Move down"), crate::i18n::fmt("Move {name} down", &args)) {
swap = Some((i, i + 1));
}
if arrow(ui, "▲", i > 0, tl!("Move up"), crate::i18n::fmt("Move {name} up", &args)) {
swap = Some((i - 1, i));
}
ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate);
let mut listed = !left_out(n);
if ui.checkbox(&mut listed, n.as_str()).on_hover_text(tl!("List this layer in the legend")).changed() {
let mut next: Vec<&String> = kept.iter().filter(|x| !x.eq_ignore_ascii_case(n)).collect();
if !listed {
next.push(n);
}
update(app, json!({"exclude": next}));
}
});
});
});
}
if let Some((a, b)) = swap {
let mut next: Vec<&String> = names.iter().collect();
next.swap(a, b);
// Those ordered but not listed stay ordered, after these.
next.extend(&unlisted);
update(app, json!({"layerOrder": next}));
Comment thread
jgregoriorincon marked this conversation as resolved.
Resolved
}
if !layer_order.is_empty() && ui.button(tl!("Map order")).on_hover_text(tl!("List the layers in the map's order")).clicked()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
{
update(app, json!({"layerOrder": []}));
}
});
}
Expand Down
191 changes: 191 additions & 0 deletions crates/ui-egui/src/layoutview/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2161,6 +2161,197 @@ fn a_legend_leaves_out_the_layers_unticked() {
assert_eq!(left_out(&h), ["Cities"]);
}

/// A legend's Layers section lists them as the legend draws them, moves one a place up or down
/// in one undo step, and goes back to the map's order (#3294).
#[test]
fn a_legends_layers_are_moved_in_the_format_pane() {
use egui::accesskit::Role;
use egui_kittest::kittest::{NodeT, Queryable};
use rustgis_engine::map::layout::ElementKind;
let mut app = RustGisApp::with_sample();
app.run("layout.new", json!({"name": "Legend"})).unwrap();
let li = app.session.active_layout.unwrap();
let legend = app.session.project.layouts[li].elements.iter().find(|e| matches!(e.kind, ElementKind::Legend { .. })).unwrap().id;
// A web layer with a legend, over the first vector layer: not the last of the list.
let mut web = rustgis_engine::map::TileLayer::new("Walls", rustgis_engine::map::TileKind::Raster, "https://h/{z}/{x}/{y}.png");
web.legends = vec![Default::default()];
web.over = Some(app.session.map().layers[0].id);
app.session.map_mut().tiles.push(web);
let map = app.session.map();
let drawn: Vec<String> = map
.stack()
.into_iter()
.map(|d| match d {
rustgis_engine::map::Drawn::Layer(i) => map.layers[i].name.clone(),
rustgis_engine::map::Drawn::Tile(i) => map.tiles[i].name.clone(),
})
.collect();
assert_eq!(drawn[0], "Walls");
let last = drawn.len() - 1;
assert!(last >= 2, "{drawn:?}");
app.layout.selected = Some(legend);
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 1400.0)).build_ui_state(
move |ui, app: &mut RustGisApp| {
if !fonts {
crate::theme::install_fonts(ui.ctx(), &[], None);
fonts = true;
return;
}
with_format(app, ui);
},
app,
);
h.run_steps(3);
h.get_by_label("Layers").click();
h.run_steps(10);
let order = |h: &egui_kittest::Harness<'_, RustGisApp>| match &h.state().session.project.layouts[li].element(legend).unwrap().kind {
ElementKind::Legend { layer_order, .. } => layer_order.clone(),
_ => panic!("a legend"),
};
let listed = |h: &egui_kittest::Harness<'_, RustGisApp>| {
let mut rows: Vec<(f32, String)> =
drawn.iter().map(|n| (h.get_by_role_and_label(Role::CheckBox, n).rect().min.y, n.clone())).collect();
rows.sort_by(|a, b| a.0.total_cmp(&b.0));
rows.into_iter().map(|(_, n)| n).collect::<Vec<_>>()
};
// Each row's arrows are named for its layer.
let disabled = |h: &egui_kittest::Harness<'_, RustGisApp>, way: &str| {
listed(h).iter().map(|n| h.get_by_label(&format!("Move {n} {way}")).accesskit_node().is_disabled()).collect::<Vec<_>>()
};
let press = |h: &mut egui_kittest::Harness<'_, RustGisApp>, way: &str, row: usize| {
let name = listed(h)[row].clone();
h.get_by_label(&format!("Move {name} {way}")).click();
h.run_steps(3);
};
assert_eq!(listed(&h), drawn);
assert!(h.query_by_label("Map order").is_none(), "no order of its own");
let ends = |end: usize| (0..=last).map(|i| i == end).collect::<Vec<_>>();
assert_eq!(disabled(&h, "up"), ends(0));
assert_eq!(disabled(&h, "down"), ends(last));
// Down from the first row: the whole list written, the first two swapped.
let depth = h.state().session.undo_depth();
press(&mut h, "down", 0);
let mut down = drawn.clone();
down.swap(0, 1);
assert_eq!(order(&h), down);
assert_eq!(listed(&h), down);
assert_eq!(h.state().session.undo_depth(), depth + 1);
h.state_mut().run("edit.undo", json!({})).unwrap();
h.run_steps(3);
assert!(order(&h).is_empty());
assert_eq!(listed(&h), drawn);
// Up from the last row.
press(&mut h, "up", last);
let mut up = drawn.clone();
up.swap(last - 1, last);
assert_eq!(order(&h), up);
// A layer left out moves as any other and stays left out.
h.get_by_role_and_label(Role::CheckBox, &up[0]).click();
h.run_steps(3);
press(&mut h, "down", 0);
let mut moved = up.clone();
moved.swap(0, 1);
assert_eq!(order(&h), moved);
match &h.state().session.project.layouts[li].element(legend).unwrap().kind {
ElementKind::Legend { exclude, .. } => assert_eq!(exclude, &[up[0].clone()]),
_ => panic!("a legend"),
}
h.get_by_label("Map order").click();
h.run_steps(3);
assert!(order(&h).is_empty());
assert_eq!(listed(&h), drawn);
assert!(h.query_by_label("Map order").is_none(), "and its button gone");
// The keyboard's focus goes with the layer it moves: Enter twice moves it two places.
h.get_by_label(&format!("Move {} up", drawn[last])).focus();
h.run_steps(2);
for _ in 0..2 {
h.key_press(egui::Key::Enter);
h.run_steps(3);
}
let mut twice = drawn.clone();
twice[last - 2..].rotate_right(1);
assert_eq!(order(&h), twice);
}

/// An order made before opens the section in it; a layer it doesn't name follows those it
/// does, and a move puts an ordered layer the section doesn't list after those it lists.
#[test]
fn a_legends_layers_section_opens_in_the_legends_order() {
use egui::accesskit::Role;
use egui_kittest::kittest::Queryable;
use rustgis_engine::map::layout::ElementKind;
let mut app = RustGisApp::with_sample();
app.run("layout.new", json!({"name": "Legend"})).unwrap();
let li = app.session.active_layout.unwrap();
let legend = app.session.project.layouts[li].elements.iter().find(|e| matches!(e.kind, ElementKind::Legend { .. })).unwrap().id;
app.run("layout.update", json!({"element": legend, "layerOrder": ["Rivers", "Cities"]})).unwrap();
app.session.map_mut().layers.iter_mut().find(|l| l.name == "Cities").unwrap().graphics = true;
app.layout.selected = Some(legend);
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 1400.0)).build_ui_state(
move |ui, app: &mut RustGisApp| {
if !fonts {
crate::theme::install_fonts(ui.ctx(), &[], None);
fonts = true;
return;
}
with_format(app, ui);
},
app,
);
h.run_steps(3);
assert!(h.query_by_label("Map order").is_some());
assert!(h.query_by_role_and_label(Role::CheckBox, "Cities").is_none());
let rivers = h.get_by_role_and_label(Role::CheckBox, "Rivers").rect().min.y;
let countries = h.get_by_role_and_label(Role::CheckBox, "Countries").rect().min.y;
assert!(rivers < countries, "ordered first, though the map draws it elsewhere");
h.get_by_label("Move Rivers down").click();
h.run_steps(3);
let ordered = match &h.state().session.project.layouts[li].element(legend).unwrap().kind {
ElementKind::Legend { layer_order, .. } => layer_order.clone(),
_ => panic!("a legend"),
};
assert_eq!(ordered.last().map(String::as_str), Some("Cities"), "{ordered:?}");
assert!(ordered.iter().position(|n| n == "Rivers") == Some(1), "{ordered:?}");
}

/// An order of its own can be dropped in the pane though no layer it names is listed there.
#[test]
fn a_legend_listing_no_layer_still_goes_back_to_the_maps_order() {
use egui_kittest::kittest::Queryable;
use rustgis_engine::map::layout::ElementKind;
let mut app = RustGisApp::with_sample();
app.run("layout.new", json!({"name": "Legend"})).unwrap();
let li = app.session.active_layout.unwrap();
let legend = app.session.project.layouts[li].elements.iter().find(|e| matches!(e.kind, ElementKind::Legend { .. })).unwrap().id;
app.run("layout.update", json!({"element": legend, "layerOrder": ["Rivers"]})).unwrap();
for l in &mut app.session.map_mut().layers {
l.graphics = true;
}
app.layout.selected = Some(legend);
let mut fonts = false;
let mut h = egui_kittest::Harness::builder().with_size(vec2(1200.0, 1400.0)).build_ui_state(
move |ui, app: &mut RustGisApp| {
if !fonts {
crate::theme::install_fonts(ui.ctx(), &[], None);
fonts = true;
return;
}
with_format(app, ui);
},
app,
);
h.run_steps(3);
h.get_by_label("Map order").click();
h.run_steps(3);
match &h.state().session.project.layouts[li].element(legend).unwrap().kind {
ElementKind::Legend { layer_order, .. } => assert!(layer_order.is_empty(), "{layer_order:?}"),
_ => panic!("a legend"),
}
assert!(h.query_by_label("Layers").is_none(), "nothing left to list");
}

/// A legend's Fit and Layer names in the Format pane: shown at their defaults on opening and
/// sending nothing then, each change one undo step, picking the current fit none, and a column
/// count past six set at six.
Expand Down
6 changes: 4 additions & 2 deletions docs/user-guide/layouts.md
Original file line number Diff line number Diff line change
Expand Up @@ -541,8 +541,10 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu
layer with a legend): untick one to leave it out of the legend while the map still draws it
(a mask, a highlight, a basemap-like layer). Scripts give the same with
`"exclude": ["Graticule"]` on `layout.addElement` or `layout.update` (`[]` lists every layer
again); a renamed layer stays left out.
- **Layer order** (`"layerOrder"`, commands and scripts only): a legend lists its layers as the
again); a renamed layer stays left out. The section lists the layers in the order the legend
draws them; ▲ and ▼ move one a place, each move one undo step, and **Map order** returns to
the map's order.
- **Layer order** (`"layerOrder"`, or ▲ and ▼ in the Layers section): a legend lists its layers as the
map draws them, top first, unless it is given its own order:
`layout.update {"element": 3, "layerOrder": ["Rivers", "Roads"]}` lists those layers first, in
that order, and the others after them as the map draws them, a layer added to the map later
Expand Down
Loading