diff --git a/crates/render/src/layout/legend.rs b/crates/render/src/layout/legend.rs index db195e0464..884c6d9a10 100644 --- a/crates/render/src/layout/legend.rs +++ b/crates/render/src/layout/legend.rs @@ -982,23 +982,6 @@ pub fn class_row_labels(l: &rustgis_map::Layer) -> Vec { entries.into_iter().map(|e| e.label).collect() } -/// Whether [`class_row_labels`] lists any row for a layer, without making a classed layer's rows: -/// asked for every row of a legend's Layers section on every frame (#3306), where making a Unique -/// Values layer's would sort and merge all its classes. A raster's are made, few and from kept -/// statistics. -pub fn has_class_rows(l: &rustgis_map::Layer) -> bool { - if !legend_lists(l) { - return false; - } - if l.is_raster() { - return !every_class(l).is_empty(); - } - // Every renderer but a single symbol lists a row, even with no class: Unique Values its - // fallback, Proportional its sizes, Graduated Colors its "No data". - let classed = !matches!(l.renderer, rustgis_map::Renderer::Single(_)); - classed || !l.with_size_legend(Vec::new()).is_empty() || l.diagram.as_ref().is_some_and(|d| !d.categories.is_empty()) -} - /// The rows of the legend of a frame's map. With `drawn` (from [`shown_legends`]) it shows what the /// frame draws: only the layers listed there, with their classes. Without, every class of every /// visible layer. `opts` leaves out `` and the layers it names, either way, and diff --git a/crates/render/src/layout/tests.rs b/crates/render/src/layout/tests.rs index 433cb02d45..936823445a 100644 --- a/crates/render/src/layout/tests.rs +++ b/crates/render/src/layout/tests.rs @@ -8780,9 +8780,6 @@ fn a_legend_labels_a_layers_classes_itself() { }; assert_eq!(labels_of(&legend_rows(&map, None, &opts(&listed, false))), ["c0", "c1", "c99"]); assert_eq!(class_row_labels(&map.layers[0]), ["c0", "c1", "c99"]); - for l in &map.layers { - assert_eq!(has_class_rows(l), !class_row_labels(l).is_empty(), "{}", l.name); - } // Graduated Colors with no class, as an imported style can bring: its "No data" row is one. let mut empty = rows_map(1); let l = &mut empty.layers[0]; @@ -8799,10 +8796,9 @@ fn a_legend_labels_a_layers_classes_itself() { class_fills: Default::default(), }; assert_eq!(class_row_labels(l), ["No data"]); - assert!(has_class_rows(l)); // One symbol: no row of its own until a diagram brings its categories. l.renderer = rustgis_map::Renderer::Single(rustgis_map::Symbol::default_for(GeometryType::Point, 0)); - assert!(class_row_labels(l).is_empty() && !has_class_rows(l)); + assert!(class_row_labels(l).is_empty()); l.diagram = Some(rustgis_map::DiagramSettings { kind: rustgis_map::DiagramKind::Pie, categories: vec![rustgis_map::DiagramCategory { field: "g".into(), colour: Rgba::rgb(255, 0, 0) }], @@ -8814,7 +8810,6 @@ fn a_legend_labels_a_layers_classes_itself() { labels: rustgis_map::DiagramLabel::None, }); assert_eq!(class_row_labels(l), ["g"]); - assert!(has_class_rows(l)); let mut own = ClassLabels::default(); own.by_layer.insert( "PTS".into(), diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index 26bf4c0153..e3582119a3 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -8,7 +8,7 @@ use crate::RustGisApp; use crate::theme::{Tokens, regular, semibold}; use egui::{Align2, Color32, CornerRadius, Pos2, Rect, Sense, Stroke, Ui, pos2, vec2}; use rustgis_engine::map::layout::{ElementKind, Layout, PT_PER_MM, frame_camera, line_length}; -use serde_json::{Value, json}; +use serde_json::json; mod actions; mod format; @@ -175,13 +175,13 @@ pub struct LayoutView { sketch: Vec<(f64, f64)>, /// Text being typed into the element properties, by (layout, element, field): kept here so /// keystrokes survive the frame, and saved when the field loses focus or stops being shown. - typing: std::collections::HashMap<(usize, u32, &'static str), String>, + typing: std::collections::HashMap, /// The layouts (their [`Layout::instance_id`]), in their order, when `typing` last followed /// them ([`follow_project`]). typing_order: Vec, /// Text a field sent to its element, by the same key: shown while the element still has the /// value it was typed over, so a refused text stays to be corrected (#3348). - sent: std::collections::HashMap<(usize, u32, &'static str), format::Sent>, + sent: std::collections::HashMap, /// The layout shown, shared between frames until the project changes (layouts can hold /// megabytes of pictures, too much to copy every frame), keyed by layout and revision. shown: Option<(usize, u64, std::rc::Rc)>, @@ -267,7 +267,7 @@ pub(crate) fn follow_project(app: &mut RustGisApp) { if !app.layout.typing_order.iter().copied().eq(layouts.iter().map(Layout::instance_id)) { let was = std::mem::replace(&mut app.layout.typing_order, layouts.iter().map(Layout::instance_id).collect()); let now = &app.layout.typing_order; - let follow = |(l, id, field): (usize, u32, &'static str)| Some((now.iter().position(|m| Some(m) == was.get(l))?, id, field)); + let follow = |(l, id, field): format::DraftKey| Some((now.iter().position(|m| Some(m) == was.get(l))?, id, field)); let typing = std::mem::take(&mut app.layout.typing); app.layout.typing = typing.into_iter().filter_map(|(key, text)| Some((follow(key)?, text))).collect(); // What a field sent goes with it, so a refused text isn't sent as new. @@ -725,7 +725,9 @@ pub fn page_info(app: &mut RustGisApp, li: usize) -> rustgis_engine::render::lay /// Saves the text typed into fields the Format pane didn't draw this frame: the selection or the /// layout changed, or the pane was closed or hidden, before the field could notice it lost focus. -/// A text kept after a refusal is dropped with its field. +/// A text kept after a refusal is dropped with its field. A legend's label box goes only with its +/// legend, as its row can be closed or filtered out while the legend stays shown, and its text is +/// kept while the legend's is still the one it was typed over, so an accepted one isn't (#3436). /// Runs once a frame, after the panes and the view. pub(crate) fn save_drafts(app: &mut RustGisApp) { follow_project(app); @@ -733,34 +735,66 @@ pub(crate) fn save_drafts(app: &mut RustGisApp) { save_typed(app, shown); // What save_typed has no value for goes with an element no longer shown. app.layout.typing.retain(|(l, id, _), _| Some((*l, *id)) == shown); - // A refused text goes with the field that showed it: not drawn this frame (another element, - // mode or pane), it is dropped, never sent again, one just saved for such an element too. - app.layout.sent.retain(|(l, id, _), sent| std::mem::take(&mut sent.drawn) && Some((*l, *id)) == shown); + // A refused text goes with the field that showed it, a legend label's with its legend: then it + // is dropped, never sent again, one just saved for such an element too. + let layouts = &app.session.project.layouts; + app.layout.sent.retain(|(l, id, field), sent| { + let drawn = std::mem::take(&mut sent.drawn); + let kept = match field { + format::Field::Own(_) => drawn, + format::Field::Label { layer, class } => layouts + .get(*l) + .and_then(|x| x.element(*id)) + .is_some_and(|e| format::legend_text(&e.kind, layer, class.as_deref()) == sent.was), + }; + kept && Some((*l, *id)) == shown + }); } /// Saves the text typed into the fields of every element but `shown` (all of them when `shown` is /// `None`), as far as their values are known here. fn save_typed(app: &mut RustGisApp, shown: Option<(usize, u32)>) { - let stale: Vec<_> = app.layout.typing.keys().filter(|(l, id, _)| Some((*l, *id)) != shown).copied().collect(); - for key in stale { - let (l, id, field) = key; - let current = app.session.project.layouts.get(l).and_then(|x| x.element(id)).and_then(|e| match (field, &e.kind) { - ("name", _) => Some(e.name.clone()), - ("text", ElementKind::Text { text, .. }) => Some(text.clone()), - ("title", ElementKind::Legend { title, .. } | ElementKind::Colorbar { title, .. }) => Some(title.clone()), - ("subtitle", ElementKind::Legend { subtitle, .. }) => Some(subtitle.clone()), - ("title", ElementKind::Chart { title, .. }) => title.clone(), - ("unitLabel", ElementKind::ScaleBar { unit_label, .. }) => Some(unit_label.clone().unwrap_or_default()), + let stale = app.layout.typing.keys().filter(|(l, id, _)| Some((*l, *id)) != shown).cloned().collect(); + save_fields(app, stale); +} + +/// Saves the text typed into the label boxes of legend `id` that aren't in `drawn`: a row closed +/// or filtered out takes its boxes while the legend stays shown (#3436). +fn save_hidden_labels(app: &mut RustGisApp, li: usize, id: u32, drawn: &std::collections::HashSet) { + let hidden = app + .layout + .typing + .keys() + .filter(|(l, i, field)| (*l, *i) == (li, id) && matches!(field, format::Field::Label { .. }) && !drawn.contains(field)) + .cloned() + .collect(); + save_fields(app, hidden); +} + +/// Saves the text typed into the fields `keys`, as far as their values are known here. +fn save_fields(app: &mut RustGisApp, keys: Vec) { + use format::Field; + for key in keys { + let (l, id, field) = &key; + let current = app.session.project.layouts.get(*l).and_then(|x| x.element(*id)).and_then(|e| match (field, &e.kind) { + (Field::Own("name"), _) => Some(e.name.clone()), + (Field::Own("text"), ElementKind::Text { text, .. }) => Some(text.clone()), + (Field::Own("title"), ElementKind::Legend { title, .. } | ElementKind::Colorbar { title, .. }) => Some(title.clone()), + (Field::Own("subtitle"), ElementKind::Legend { subtitle, .. }) => Some(subtitle.clone()), + (Field::Own("title"), ElementKind::Chart { title, .. }) => title.clone(), + (Field::Own("unitLabel"), ElementKind::ScaleBar { unit_label, .. }) => Some(unit_label.clone().unwrap_or_default()), + (Field::Label { layer, class }, kind @ ElementKind::Legend { .. }) => Some(format::legend_text(kind, layer, class.as_deref())), _ => None, }); // A field with no value here (a section line's name, a grid's CRS, a chart's automatic // title) stays being typed. let Some(current) = current else { continue }; let Some(text) = app.layout.typing.remove(&key) else { continue }; - if let Some(text) = format::send(app, key, ¤t, text) { - // An emptied unit label gives the unit's abbreviation back, as the field does. - let value = if field == "unitLabel" && text.is_empty() { Value::Null } else { json!(text) }; - let _ = app.run("layout.update", json!({"layout": l, "element": id, field: value})); + if let Some(text) = format::send(app, &key, ¤t, text) { + let mut p = format::field_change(&key.2, text); + p["layout"] = json!(key.0); + p["element"] = json!(key.1); + let _ = app.run("layout.update", p); } } } diff --git a/crates/ui-egui/src/layoutview/format.rs b/crates/ui-egui/src/layoutview/format.rs index c2b9a3cef8..b31c628ce7 100644 --- a/crates/ui-egui/src/layoutview/format.rs +++ b/crates/ui-egui/src/layoutview/format.rs @@ -30,6 +30,7 @@ use rustgis_engine::map::symbology::Dash; use scalebar::*; use serde_json::{Value, json}; use shapes::*; +use std::sync::Arc; use table::*; use text::*; @@ -48,46 +49,92 @@ pub(super) fn orientation_row(ui: &mut Ui, current: Orientation) -> Option<&'sta picked } +/// A field text is typed into. +#[derive(Clone, Debug, PartialEq, Eq, Hash)] +pub(super) enum Field { + /// One of the element's own, by its command key. + Own(&'static str), + /// A legend's own text for a layer, or for one of that layer's classes (#3436). + Label { layer: Arc, class: Option> }, +} + +impl From<&'static str> for Field { + fn from(key: &'static str) -> Self { + Field::Own(key) + } +} + +/// A field's text, by the layout's place, the element and the field. +pub(super) type DraftKey = (usize, u32, Field); + +/// The text a legend has of its own for a layer or a class of it; empty without one, or on any +/// other element. +pub(super) fn legend_text(kind: &ElementKind, layer: &str, class: Option<&str>) -> String { + let ElementKind::Legend { labels, class_labels, .. } = kind else { return String::new() }; + let text = match class { + Some(class) => class_labels.of(layer).and_then(|own| own.get(class)), + // By its name in any case, as the legend draws it. + None => labels.get(layer).or_else(|| labels.iter().find(|(n, _)| n.eq_ignore_ascii_case(layer)).map(|(_, l)| l)), + }; + text.cloned().unwrap_or_default() +} + +/// The `layout.update` parameters giving `field` the text `text`. +pub(super) fn field_change(field: &Field, text: String) -> Value { + match field { + // An emptied unit label gives the unit's abbreviation back. + Field::Own("unitLabel") if text.is_empty() => json!({"unitLabel": Value::Null}), + Field::Own(key) => json!({*key: text}), + Field::Label { layer, class: None } => json!({"labels": {&**layer: text}}), + Field::Label { layer, class: Some(class) } => json!({"classLabels": {&**layer: {&**class: text}}}), + } +} + /// A text a field sent to its element ([`send`]). pub(super) struct Sent { /// The value the element had: another one drops the text. - was: String, + pub(super) was: String, text: String, - /// Set when its field was drawn or saved this frame; [`super::save_drafts`] keeps the text - /// only for a drawn field of the element shown. + /// Set when its field was drawn or saved this frame. [`super::save_drafts`] keeps the text of + /// the element shown: an own field's while drawn, a legend label's while its value is `was`. pub(super) drawn: bool, } /// What a text field holding `current` shows: the text being typed, else the one it sent while the /// element still has the value it was typed over (so the command refused it, #3348), else `current`. -pub(super) fn draft(app: &mut RustGisApp, key: (usize, u32, &'static str), current: &str) -> String { +pub(super) fn draft(app: &mut RustGisApp, key: &DraftKey, current: &str) -> String { // A value set since, by this text or from elsewhere, drops what was sent. - if app.layout.sent.get(&key).is_some_and(|s| s.was != current) { - app.layout.sent.remove(&key); + if app.layout.sent.get(key).is_some_and(|s| s.was != current) { + app.layout.sent.remove(key); } - let kept = app.layout.sent.get_mut(&key).map(|s| { + let kept = app.layout.sent.get_mut(key).map(|s| { s.drawn = true; s.text.clone() }); - app.layout.typing.remove(&key).or(kept).unwrap_or_else(|| current.to_string()) + app.layout.typing.remove(key).or(kept).unwrap_or_else(|| current.to_string()) } /// What a text field gives its element on losing focus: `text`, when it differs from `current` /// and wasn't sent already, kept for [`draft`] in case it is refused. A field is left more than /// once with the same refused text (egui says so again, the user clicks in and out): it is said /// once. -pub(super) fn send(app: &mut RustGisApp, key: (usize, u32, &'static str), current: &str, text: String) -> Option { +pub(super) fn send(app: &mut RustGisApp, key: &DraftKey, current: &str, text: String) -> Option { // A name is trimmed by its command: spaces alone around it change nothing. A blank element // name is ignored without a word, so it isn't kept either. - let name = key.2 == "name" || SECTION_NAMES.contains(&key.2); - if text == current || (name && text.trim() == current) || (key.2 == "name" && text.trim().is_empty()) { - app.layout.sent.remove(&key); + // A blank label where the legend has none of its own changes nothing either. + let unchanged = match &key.2 { + Field::Own("name") => text.trim() == current || text.trim().is_empty(), + Field::Own(f) => SECTION_NAMES.contains(f) && text.trim() == current, + Field::Label { .. } => current.is_empty() && text.trim().is_empty(), + }; + if text == current || unchanged { + app.layout.sent.remove(key); return None; } - if app.layout.sent.get(&key).is_some_and(|s| s.was == current && s.text == text) { + if app.layout.sent.get(key).is_some_and(|s| s.was == current && s.text == text) { return None; } - app.layout.sent.insert(key, Sent { was: current.to_string(), text: text.clone(), drawn: true }); + app.layout.sent.insert(key.clone(), Sent { was: current.to_string(), text: text.clone(), drawn: true }); Some(text) } @@ -114,7 +161,8 @@ pub(super) fn hinted_text_field( hint: Option<&str>, label_id: egui::Id, ) -> Option { - let mut buf = draft(app, key, current); + let key = (key.0, key.1, Field::Own(key.2)); + let mut buf = draft(app, &key, current); let mut edit = if multiline { egui::TextEdit::multiline(&mut buf).desired_rows(3).desired_width(240.0) } else { @@ -125,7 +173,7 @@ pub(super) fn hinted_text_field( } let r = ui.add(edit).labelled_by(label_id); if r.lost_focus() { - return send(app, key, current, buf); + return send(app, &key, current, buf); } if r.has_focus() { app.layout.typing.insert(key, buf); @@ -315,7 +363,7 @@ pub(super) fn properties(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, li: ); }); text_section(app, ui, layout, li, &e, &update); - legend_layers(app, ui, layout, &e, &update); + legend_layers(app, ui, layout, li, &e, &update); frame_sections(app, ui, layout, li, &e, &update); // Its background (#2257): a box behind its content, which a map frame, drawing its own paper, // doesn't take. diff --git a/crates/ui-egui/src/layoutview/format/chart.rs b/crates/ui-egui/src/layoutview/format/chart.rs index 749bb63d68..bb616578ca 100644 --- a/crates/ui-egui/src/layoutview/format/chart.rs +++ b/crates/ui-egui/src/layoutview/format/chart.rs @@ -156,7 +156,7 @@ pub(super) fn chart_rows( }; // Its own title being typed is dropped, so the field losing its // focus, now or with the selection, doesn't bring it back. - app.layout.typing.remove(&(li, id, "title")); + app.layout.typing.remove(&(li, id, Field::Own("title"))); update(app, json!({"title": value})); } } diff --git a/crates/ui-egui/src/layoutview/format/frame.rs b/crates/ui-egui/src/layoutview/format/frame.rs index 7c69f676b8..7b4361ddee 100644 --- a/crates/ui-egui/src/layoutview/format/frame.rs +++ b/crates/ui-egui/src/layoutview/format/frame.rs @@ -62,11 +62,11 @@ fn section_rows( egui::Grid::new("section_place").num_columns(2).spacing(vec2(8.0, 6.0)).show(ui, |ui| { let label = ui.label(tl!("Name")); // Sections are capped at MAX_SECTIONS on load and on add: the clamp only guards the index. - let key = (li, id, SECTION_NAMES[i.min(MAX_SECTIONS - 1)]); - let mut name = draft(app, key, &s.name); + let key = (li, id, Field::Own(SECTION_NAMES[i.min(MAX_SECTIONS - 1)])); + let mut name = draft(app, &key, &s.name); let r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(60.0)).labelled_by(label.id); if r.lost_focus() { - if let Some(name) = send(app, key, &s.name, name) { + if let Some(name) = send(app, &key, &s.name, name) { set(app, json!({"section": {"newName": name}})); } } else if r.has_focus() { @@ -355,9 +355,9 @@ fn grid_properties(app: &mut RustGisApp, ui: &mut Ui, grid: Option<&Grid>, li: u /// field is left; empty is the map's when projected, else the UTM zone at the frame's centre. fn crs_row(app: &mut RustGisApp, ui: &mut Ui, g: &Grid, li: usize, id: u32, set: &dyn Fn(&mut RustGisApp, Value)) { let input_label = ui.label(tl!("Coordinate system")); - let key = (li, id, "crs"); + let key = (li, id, Field::Own("crs")); let current = g.crs.clone().unwrap_or_default(); - let mut buf = draft(app, key, ¤t); + let mut buf = draft(app, &key, ¤t); let (hint, help) = if g.mgrs { ( tl!("The map's UTM zone, else the frame's"), @@ -374,7 +374,7 @@ fn crs_row(app: &mut RustGisApp, ui: &mut Ui, g: &Grid, li: usize, id: u32, set: let r = ui.add(egui::TextEdit::singleline(&mut buf).hint_text(hint).desired_width(150.0)).labelled_by(input_label.id).on_hover_text(help); if r.lost_focus() { - if let Some(crs) = send(app, key, ¤t, buf.trim().to_string()) { + if let Some(crs) = send(app, &key, ¤t, buf.trim().to_string()) { set(app, json!({"crs": crs})); } } else if r.has_focus() { diff --git a/crates/ui-egui/src/layoutview/format/legend.rs b/crates/ui-egui/src/layoutview/format/legend.rs index e58d790d4d..c0281636f9 100644 --- a/crates/ui-egui/src/layoutview/format/legend.rs +++ b/crates/ui-egui/src/layoutview/format/legend.rs @@ -6,8 +6,10 @@ use crate::widgets::Dragged; use egui::{Ui, vec2}; use rustgis_engine::map::Drawn; use rustgis_engine::map::layout::{Element, ElementKind, Layout, LegendFit, LegendSizes, MAX_LEGEND_COLUMNS}; -use rustgis_engine::render::layout::{class_row_labels, has_class_rows, legend_lists, legend_place}; +use rustgis_engine::render::layout::{class_row_labels, legend_lists, legend_place}; use serde_json::{Value, json}; +use std::collections::HashSet; +use std::sync::Arc; /// A legend's rows in the grid. pub(super) fn legend_property_rows(app: &mut RustGisApp, ui: &mut Ui, li: usize, e: &Element, update: &dyn Fn(&mut RustGisApp, Value)) { @@ -136,6 +138,9 @@ const FILTER_OVER: usize = 8; /// The height its rows scroll in, in points. const LAYERS_HEIGHT: f32 = 320.0; +/// The share of a label box's row its caption takes. +const CAPTION_WIDTH: f32 = 0.4; + /// `text` as the Layers filter compares it: lower case a character at a time, as /// `str::to_lowercase` turns a capital sigma into one letter or another by its place, and the final /// sigma as the other. @@ -143,17 +148,47 @@ fn folded(text: &str) -> String { text.chars().flat_map(char::to_lowercase).map(|c| if c == 'ς' { 'σ' } else { c }).collect() } +/// A box holding the legend's own text for a layer or one of its classes, `hint` (the text shown +/// without one) while it's empty. What it sends is saved as any Format box's is (#3348). +fn label_box(app: &mut RustGisApp, ui: &mut Ui, key: &DraftKey, current: &str, hint: &str, name: &str) -> Option { + let mut buf = draft(app, key, current); + // No limit of its own: a text too long is refused and stays here, never cut. + let edit = egui::TextEdit::singleline(&mut buf).id_salt("label").hint_text(hint).desired_width(f32::INFINITY); + let r = ui.add(edit); + // Named for its layer and class, so the boxes tell apart to a screen reader. + r.widget_info(|| egui::WidgetInfo::labeled(egui::Role::TextInput, true, name)); + // The hint is gone once the box holds a text. + let r = r.on_hover_text(hint); + if r.lost_focus() { + return send(app, key, current, buf); + } + if r.has_focus() { + app.layout.typing.insert(key.clone(), buf); + } + None +} + /// The layers a legend lists, below the grid. -pub(super) fn legend_layers(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, e: &Element, update: &dyn Fn(&mut RustGisApp, Value)) { +pub(super) fn legend_layers( + app: &mut RustGisApp, + ui: &mut Ui, + layout: &Layout, + li: usize, + e: &Element, + update: &dyn Fn(&mut RustGisApp, Value), +) { let id = e.id; + // The label boxes drawn: text typed into any other is saved. + let mut drawn = HashSet::new(); // 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, layer_order, class_labels, .. } = &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)), + if let ElementKind::Legend { frame, exclude, layer_order, .. } = &e.kind { + let frame_map = layout.element(*frame).and_then(|f| match &f.kind { + ElementKind::MapFrame { map, .. } => Some(map), _ => None, }); + let map = frame_map.and_then(|name| app.session.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(name))); let names: Vec = map .map(|m| { // Once each: layers may share a name, and the legend leaves names out. @@ -180,8 +215,9 @@ pub(super) fn legend_layers(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, let kept: Vec = 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(); - // What a row or button asks for, sent once the map is no longer read. + // What a row or button asks for, sent once the map is no longer read, as a box's text is. let mut change = None; + let mut texts = Vec::new(); // With none to list, still there to reset the legend's own order or the names left out. if !names.is_empty() || !layer_order.is_empty() || !kept.is_empty() { ui.add_space(4.0); @@ -204,7 +240,8 @@ pub(super) fn legend_layers(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, ui.data_mut(|d| d.insert_temp(key, text)); } // The places in `names` of the rows shown. - let shown: Vec = names.iter().enumerate().filter(|(_, n)| folded(n).contains(&needle)).map(|(i, _)| i).collect(); + let found = |n: &str| folded(n).contains(&needle) || folded(&legend_text(&e.kind, n, None)).contains(&needle); + let shown: Vec = names.iter().enumerate().filter(|(_, n)| found(n)).map(|(i, _)| i).collect(); if !needle.is_empty() && shown.is_empty() { ui.label(tl!("No layers match your search.")); } @@ -244,16 +281,13 @@ pub(super) fn legend_layers(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, for (k, (i, n)) in shown.iter().filter_map(|&i| names.get(i).map(|n| (i, n))).enumerate() { let above = k.checked_sub(1).and_then(|k| shown.get(k)).copied(); let below = shown.get(k + 1).copied(); - // The map's layers of this name: a web layer has no classes. - let layers = || map.into_iter().flat_map(|m| &m.layers).filter(|l| l.name.eq_ignore_ascii_case(n)); - let classed = layers().any(has_class_rows); // Ids from the layer, not the row's place (`push_id` would mix it in), so // the keyboard's focus and the row's expansion move 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| { - let mut classes = egui::collapsing_header::CollapsingState::load_with_default_open( + let mut labels = egui::collapsing_header::CollapsingState::load_with_default_open( ui.ctx(), - row_id.with("classes"), + row_id.with("labels"), false, ); // The arrows on the right, the name in what they leave. @@ -275,25 +309,23 @@ pub(super) fn legend_layers(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, } ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| { ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - let open = classes.is_open(); + let open = labels.is_open(); let (glyph, hover, label) = if open { - ("▾", tl!("Hide classes"), crate::i18n::fmt("Hide the classes of {name}", &args)) + ("▾", tl!("Hide labels"), crate::i18n::fmt("Hide the labels of {name}", &args)) } else { - ("▸", tl!("Show classes"), crate::i18n::fmt("Show the classes of {name}", &args)) + ("▸", tl!("Show labels"), crate::i18n::fmt("Show the labels of {name}", &args)) }; - // Drawn unseen without classes, so the checkboxes line up. - let toggle = ui.add_visible(classed, egui::Button::new(glyph).small().frame(false)); - if classed { - toggle.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &label)); - if toggle.on_hover_text(hover).clicked() { - classes.toggle(ui); - } + let toggle = ui.add(egui::Button::new(glyph).small().frame(false)); + toggle.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, &label)); + if toggle.on_hover_text(hover).clicked() { + labels.toggle(ui); } 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() + // By the legend's own text for it, still naming its layer: + // to a screen reader, the keyboard and among equal texts. + let own = legend_text(&e.kind, n, None); + let text = if own.is_empty() || own == *n { n.clone() } else { format!("{own} ({n})") }; + if ui.checkbox(&mut listed, text).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 { @@ -303,17 +335,53 @@ pub(super) fn legend_layers(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, } }); }); - if classed && classes.is_open() { - // As the legend labels them: its own text for a class, else the layer's. - let own = class_labels.of(n); - ui.indent("classes", |ui| { - ui.style_mut().wrap_mode = Some(egui::TextWrapMode::Truncate); - for label in layers().flat_map(class_row_labels) { - ui.label(own.and_then(|o| o.get(&label)).unwrap_or(&label)); + if labels.is_open() { + let args = [("name", n.as_str())]; + let layer: Arc = n.as_str().into(); + // The classes of the map's layers of this name (a web layer + // has none), read before a box changes the app. + let classes: Vec = frame_map + .and_then(|name| app.session.project.maps.iter().find(|m| m.name.eq_ignore_ascii_case(name))) + .into_iter() + .flat_map(|m| &m.layers) + .filter(|l| l.name.eq_ignore_ascii_case(n)) + .flat_map(class_row_labels) + .collect(); + let mut entry = |ui: &mut Ui, class: Option<&str>, hint: &str, name: String| { + let field = Field::Label { layer: layer.clone(), class: class.map(Arc::from) }; + let current = legend_text(&e.kind, n, class); + drawn.insert(field.clone()); + let key = (li, id, field); + ui.horizontal(|ui| { + // Its caption, in a column of one width: a class's + // always, as a box holding any text shows no hint. + let column = vec2(ui.available_width() * CAPTION_WIDTH, ui.spacing().interact_size.y); + ui.allocate_ui_with_layout( + column, + egui::Layout::left_to_right(egui::Align::Center), + |ui| { + ui.set_min_width(column.x); + ui.add(egui::Label::new(class.unwrap_or(tl!("Label"))).truncate()); + }, + ); + if let Some(text) = label_box(app, ui, &key, ¤t, hint, &name) { + texts.push(field_change(&key.2, text)); + } + }); + }; + ui.indent("labels", |ui| { + entry(ui, None, n, crate::i18n::fmt("Label of {name}", &args)); + // One box a label: classes that share one share its text. + let mut seen = HashSet::new(); + for class in classes.iter().filter(|c| seen.insert(c.as_str())) { + let args = [("class", class.as_str()), ("name", n.as_str())]; + ui.push_id(class, |ui| { + entry(ui, Some(class), class, crate::i18n::fmt("Label of {class} in {name}", &args)); + }); } }); } - classes.store(ui.ctx()); + labels.store(ui.ctx()); }); } }); @@ -333,8 +401,9 @@ pub(super) fn legend_layers(app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, } }); } - if let Some(change) = change { + for change in texts.into_iter().chain(change) { update(app, change); } } + super::super::save_hidden_labels(app, li, id, &drawn); } diff --git a/crates/ui-egui/src/layoutview/format/scalebar.rs b/crates/ui-egui/src/layoutview/format/scalebar.rs index c68ce1f298..405ff88312 100644 --- a/crates/ui-egui/src/layoutview/format/scalebar.rs +++ b/crates/ui-egui/src/layoutview/format/scalebar.rs @@ -157,10 +157,10 @@ pub(super) fn scale_bar_rows( // The label being typed is dropped, so the field losing its focus // doesn't write it back; hidden, it is the text kept, unless the command // would refuse it: that one is sent, to say why (once). - let key = (li, id, "unitLabel"); + let key = (li, id, Field::Own("unitLabel")); let mut dropped = app.layout.typing.remove(&key); if let Some(long) = dropped.take_if(|t| t.chars().count() > MAX_UNIT_LABEL_CHARS) - && let Some(long) = send(app, key, unit_label.as_deref().unwrap_or(""), long) + && let Some(long) = send(app, &key, unit_label.as_deref().unwrap_or(""), long) { update(app, json!({"unitLabel": long})); } diff --git a/crates/ui-egui/src/layoutview/format/text.rs b/crates/ui-egui/src/layoutview/format/text.rs index 3059aec8cc..3655ce9421 100644 --- a/crates/ui-egui/src/layoutview/format/text.rs +++ b/crates/ui-egui/src/layoutview/format/text.rs @@ -62,8 +62,8 @@ pub(super) fn text_section( .. } = &e.kind { - let key = (li, id, "text"); - let mut buf = draft(app, key, text); + let key = (li, id, Field::Own("text")); + let mut buf = draft(app, &key, text); let (mut sz, mut c, mut bb) = (*size, crate::theme::c32(*color), *bold); let (mut it, mut al, mut ls, mut fam, mut named) = (*italic, *align, *letter_spacing, *font, font_name.clone()); let (mut wr, mut va, mut line_sp, mut cs) = (*wrap, valign.kept(), *line_spacing, case.kept()); @@ -100,7 +100,7 @@ pub(super) fn text_section( if settled.typing { app.layout.typing.insert(key, buf); } else if settled.text - && let Some(new_text) = send(app, key, text, buf) + && let Some(new_text) = send(app, &key, text, buf) { update(app, json!({"text": new_text})); } diff --git a/crates/ui-egui/src/layoutview/tests.rs b/crates/ui-egui/src/layoutview/tests.rs index 7bd8057c04..2b963c9172 100644 --- a/crates/ui-egui/src/layoutview/tests.rs +++ b/crates/ui-egui/src/layoutview/tests.rs @@ -1828,7 +1828,7 @@ fn a_scale_bar_takes_its_details_in_the_format_pane() { for (draft, expected) in [("Miles", Some("Miles")), ("", None)] { h.state_mut().layout.selected = Some(bar); h.run_steps(2); - h.state_mut().layout.typing.insert((li, bar, "unitLabel"), draft.into()); + h.state_mut().layout.typing.insert((li, bar, "unitLabel".into()), draft.into()); h.state_mut().layout.selected = None; h.run_steps(3); assert!(h.state().layout.typing.is_empty(), "{draft:?}"); @@ -2508,7 +2508,7 @@ fn legend_tree(extra: u32, params: serde_json::Value) -> (egui_kittest::Harness< ); h.run_steps(3); // An order or a layer left out opens it already. - if h.query_by_role_and_label(egui::accesskit::Role::CheckBox, "Rivers").is_none() { + if h.query_by_role_and_label(egui::accesskit::Role::CheckBox, "Cities").is_none() { h.get_by_label("Layers").click(); h.run_steps(10); } @@ -2677,10 +2677,10 @@ fn a_legends_layers_reset_to_the_map() { } } -/// A layer drawn by classes expands to the classes as the legend labels them, and stays expanded -/// when moved; a layer drawn in one symbol has no arrow, nor a web layer (#3306). +/// Every layer's row opens on its labels: the layer's own box and, drawn by classes, a box per +/// class holding the legend's text; it stays open when moved (#3306, #3436). #[test] -fn a_legends_layers_expand_to_their_classes() { +fn a_legends_layers_expand_to_their_labels() { use egui_kittest::kittest::Queryable; let (mut h, ..) = legend_tree(0, json!({})); let mut web = rustgis_engine::map::TileLayer::new("Walls", rustgis_engine::map::TileKind::Raster, "https://h/{z}/{x}/{y}.png"); @@ -2690,22 +2690,31 @@ fn a_legends_layers_expand_to_their_classes() { let countries = h.state().session.map().layers.iter().find(|l| l.name == "Countries").unwrap(); let classes = rustgis_engine::render::layout::class_row_labels(countries); assert!(classes.len() > 2, "{classes:?}"); - assert!(h.query_by_label("Show the classes of Countries").is_some()); - assert!(h.query_by_label("Show the classes of Cities").is_some(), "sized in proportion: it has rows"); - for none in ["Rivers", "Lakes", "Walls"] { - assert!(h.query_by_label(&format!("Show the classes of {none}")).is_none(), "{none}"); + for every in ["Countries", "Cities", "Rivers", "Lakes", "Walls"] { + assert!(h.query_by_label(&format!("Show the labels of {every}")).is_some(), "{every}"); + } + let class_box = |c: &str| format!("Label of {c} in Countries"); + assert!(h.query_by_label("Label of Countries").is_none(), "closed at first"); + // A layer drawn in one symbol, and a web layer, have their own box alone. + for one in ["Rivers", "Walls"] { + h.get_by_label(&format!("Show the labels of {one}")).click(); + h.run_steps(3); + assert!(h.query_by_label(&format!("Label of {one}")).is_some(), "{one}"); + assert_eq!(h.query_all_by_label_contains(&format!(" in {one}")).count(), 0, "{one}"); + h.get_by_label(&format!("Hide the labels of {one}")).click(); + h.run_steps(3); } - assert!(h.query_by_label(&classes[0]).is_none(), "closed at first"); let legend = h.state().layout.selected.unwrap(); h.state_mut() .run("layout.update", json!({"element": legend, "classLabels": {"Countries": {classes[0].clone(): "Renamed here"}}})) .unwrap(); h.run_steps(2); - h.get_by_label("Show the classes of Countries").click(); + h.get_by_label("Show the labels of Countries").click(); h.run_steps(3); - assert!(h.query_by_label("Renamed here").is_some()); - assert!(h.query_by_label(&classes[0]).is_none(), "the legend's text in its place"); - let rows: Vec = classes[1..].iter().map(|c| h.get_by_label(c).rect().min.y).collect(); + assert_eq!(box_text(&h, "Label of Countries"), ""); + assert_eq!(box_text(&h, &class_box(&classes[0])), "Renamed here"); + assert_eq!(box_text(&h, &class_box(&classes[1])), "", "the label the layer shows for it as its hint"); + let rows: Vec = classes.iter().map(|c| h.get_by_label(&class_box(c)).rect().min.y).collect(); assert!(rows.windows(2).all(|w| w[0] < w[1]), "in the legend's order: {classes:?}"); let way = if h.query_by_label("Move Countries up").is_some_and(|n| !egui_kittest::kittest::NodeT::accesskit_node(&n).is_disabled()) { "up" @@ -2714,11 +2723,296 @@ fn a_legends_layers_expand_to_their_classes() { }; h.get_by_label(&format!("Move Countries {way}")).click(); h.run_steps(3); - assert!(h.query_by_label("Hide the classes of Countries").is_some(), "still expanded in its new place"); - assert!(h.query_by_label("Renamed here").is_some()); - h.get_by_label("Hide the classes of Countries").click(); + assert!(h.query_by_label("Hide the labels of Countries").is_some(), "still expanded in its new place"); + assert_eq!(box_text(&h, &class_box(&classes[0])), "Renamed here"); + h.get_by_label("Hide the labels of Countries").click(); + h.run_steps(3); + assert!(h.query_by_label("Label of Countries").is_none()); +} + +/// What the box labelled `label` holds. +fn box_text(h: &egui_kittest::Harness<'_, RustGisApp>, label: &str) -> String { + use egui_kittest::kittest::Queryable; + h.get_by_label(label).value().unwrap_or_default() +} + +/// Focuses the box labelled `label` and types `text` in place of what it holds, without leaving it. +fn type_label(h: &mut egui_kittest::Harness<'_, RustGisApp>, label: &str, text: &str) { + use egui_kittest::kittest::Queryable; + h.get_by_label(label).focus(); + h.run_steps(2); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.key_press(Key::Backspace); + h.run_steps(2); + h.get_by_label(label).type_text(text); + h.run_steps(3); +} + +fn leave_box(h: &mut egui_kittest::Harness<'_, RustGisApp>) { + h.key_press(Key::Enter); + h.run_steps(3); +} + +/// A legend's own texts, for layers and for Countries' classes. +fn legend_texts(app: &RustGisApp, li: usize, legend: u32) -> (serde_json::Value, serde_json::Value) { + let kind = serde_json::to_value(&app.session.project.layouts[li].element(legend).unwrap().kind).unwrap(); + (kind["Legend"]["labels"].clone(), kind["Legend"]["class_labels"]["Countries"].clone()) +} + +/// A legend with Countries' labels open. +fn countries_open(extra: u32, params: serde_json::Value) -> (egui_kittest::Harness<'static, RustGisApp>, usize, u32) { + use egui_kittest::kittest::Queryable; + let (mut h, li, legend) = legend_tree(extra, params); + h.get_by_label("Show the labels of Countries").click(); + h.run_steps(5); + (h, li, legend) +} + +/// Leaving a layer's or a class's box sets the legend's own text in one undo step; emptied, it +/// shows the original again; unchanged, it sends nothing (#3436). +#[test] +fn a_legends_labels_are_set_in_its_boxes() { + use egui_kittest::kittest::Queryable; + for (label, shown) in [("Label of Countries", "Países"), ("Label of Africa in Countries", "África")] { + let (mut h, li, legend) = countries_open(0, json!({"layerOrder": ["Countries"]})); + let before = legend_texts(h.state(), li, legend); + let (depth, symbology) = (h.state().session.undo_depth(), format!("{:?}", h.state().session.map().layers[0].renderer)); + h.get_by_label(label).focus(); + h.run_steps(2); + leave_box(&mut h); + assert_eq!(h.state().session.undo_depth(), depth, "{label}: unchanged"); + type_label(&mut h, label, " "); + leave_box(&mut h); + assert_eq!(h.state().session.undo_depth(), depth, "{label}: blank over none"); + assert_eq!(box_text(&h, label), "", "{label}"); + + type_label(&mut h, label, shown); + assert_eq!(h.state().session.undo_depth(), depth, "{label}: nothing while typing"); + leave_box(&mut h); + assert_eq!(h.state().session.undo_depth(), depth + 1, "{label}"); + assert_eq!(box_text(&h, label), shown); + let (layers, classes) = legend_texts(h.state(), li, legend); + if label == "Label of Countries" { + assert_eq!(layers, json!({"Countries": shown})); + let row = format!("{shown} (Countries)"); + assert!(h.query_by_role_and_label(egui::accesskit::Role::CheckBox, &row).is_some(), "the row shows it"); + } else { + assert_eq!(classes, json!({"Africa": shown})); + } + assert_eq!(format!("{:?}", h.state().session.map().layers[0].renderer), symbology, "the layer is left as it was"); + + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(box_text(&h, label), "", "{label}: undone"); + assert_eq!(legend_texts(h.state(), li, legend), before); + h.state_mut().run("edit.redo", json!({})).unwrap(); + h.run_steps(3); + for emptied in ["", " "] { + type_label(&mut h, label, emptied); + leave_box(&mut h); + assert_eq!(legend_texts(h.state(), li, legend), before, "{label} {emptied:?}"); + assert_eq!(box_text(&h, label), ""); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(box_text(&h, label), shown); + } + } +} + +/// Text typed into a label box is saved when the box stops being shown before it loses focus: +/// another element picked, the pane closed, its row closed or filtered out, a command that draws +/// the page first (#3436). +#[test] +fn a_legends_typed_label_is_saved_when_its_box_goes() { + use egui_kittest::kittest::Queryable; + for exit in ["element", "pane", "row", "filter", "section", "command"] { + for label in ["Label of Countries", "Label of Africa in Countries"] { + let (mut h, li, legend) = countries_open(8, json!({"layerOrder": ["Countries"]})); + let depth = h.state().session.undo_depth(); + type_label(&mut h, label, "Typed"); + match exit { + "element" => h.state_mut().layout.selected = None, + "pane" => h.state_mut().ui.right = None, + "row" => h.get_by_label("Hide the labels of Countries").click(), + "filter" => type_layer_filter(&mut h, "rivers"), + "section" => h.get_by_label("Layers").click(), + _ => super::commit_drafts(h.state_mut()), + } + h.run_steps(10); + let (layers, classes) = legend_texts(h.state(), li, legend); + let saved = if label == "Label of Countries" { &layers["Countries"] } else { &classes["Africa"] }; + assert_eq!(saved, "Typed", "{exit}: {label}"); + assert_eq!(h.state().session.undo_depth(), depth + 1, "{exit}: {label}"); + // A box still focused after a command goes on being typed into. + assert!(exit == "command" || h.state().layout.typing.is_empty(), "{exit}: {label}"); + } + } +} + +/// A label the command refuses, too long or one too many, stays in its box to be corrected (#3436). +#[test] +fn a_legends_refused_label_stays_in_its_box() { + use rustgis_engine::map::layout::{MAX_LEGEND_LABEL_CHARS, MAX_LEGEND_LABELS}; + let (mut h, li, legend) = countries_open(0, json!({"layerOrder": ["Countries"]})); + let long = "a".repeat(MAX_LEGEND_LABEL_CHARS + 1); + for label in ["Label of Countries", "Label of Africa in Countries"] { + let (before, mark) = (legend_texts(h.state(), li, legend), h.state().session.notice_mark()); + let depth = h.state().session.undo_depth(); + type_label(&mut h, label, &long); + leave_box(&mut h); + assert_eq!(legend_texts(h.state(), li, legend), before, "{label}: refused, never cut"); + assert_eq!(box_text(&h, label), long, "{label}: kept to be corrected"); + assert_eq!(h.state().session.undo_depth(), depth, "{label}"); + assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.error).count(), 1, "{label}"); + } + type_label(&mut h, "Label of Countries", &long[1..]); + leave_box(&mut h); + assert_eq!(legend_texts(h.state(), li, legend).0, json!({"Countries": &long[1..]})); + // A legend with all the labels it keeps refuses another layer's. + let element = h.state_mut().session.project.layouts[li].element_mut(legend).unwrap(); + let ElementKind::Legend { labels, .. } = &mut element.kind else { panic!("a legend") }; + *labels = (0..MAX_LEGEND_LABELS).map(|i| (format!("gone {i}"), "x".to_string())).collect(); + // A command, so the view reads the layout again. + h.state_mut().run("layout.update", json!({"element": legend, "subtitle": "Full"})).unwrap(); + h.run_steps(3); + assert_eq!(box_text(&h, "Label of Countries"), ""); + let (depth, mark) = (h.state().session.undo_depth(), h.state().session.notice_mark()); + type_label(&mut h, "Label of Countries", "One more"); + leave_box(&mut h); + assert_eq!(h.state().session.undo_depth(), depth); + assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.error).count(), 1); + assert_eq!(box_text(&h, "Label of Countries"), "One more", "kept to be corrected"); +} + +/// A refused label stays to be corrected when its box is hidden while its legend stays shown, and +/// is said once; a value set meanwhile takes its place (#3436). +#[test] +fn a_legends_refused_label_outlives_its_hidden_box() { + use egui_kittest::kittest::Queryable; + use rustgis_engine::map::layout::MAX_LEGEND_LABEL_CHARS; + let long = "a".repeat(MAX_LEGEND_LABEL_CHARS + 1); + // Hidden with the text still being typed, or once it is refused. + for refused_first in [false, true] { + for exit in ["row", "filter", "section"] { + for label in ["Label of Countries", "Label of Africa in Countries"] { + let case = format!("{exit}, {label}, refused first: {refused_first}"); + let (mut h, li, legend) = countries_open(8, json!({"layerOrder": ["Countries"]})); + let before = legend_texts(h.state(), li, legend); + let (depth, mark) = (h.state().session.undo_depth(), h.state().session.notice_mark()); + type_label(&mut h, label, &long); + if refused_first { + leave_box(&mut h); + } + for shown in [false, true] { + match exit { + "row" if shown => h.get_by_label("Show the labels of Countries").click(), + "row" => h.get_by_label("Hide the labels of Countries").click(), + "filter" => type_layer_filter(&mut h, if shown { "" } else { "rivers" }), + _ => h.get_by_label("Layers").click(), + } + h.run_steps(10); + } + assert_eq!(box_text(&h, label), long, "{case}"); + assert_eq!(legend_texts(h.state(), li, legend), before, "{case}"); + assert_eq!(h.state().session.undo_depth(), depth, "{case}"); + assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.error).count(), 1, "{case}"); + } + } + } + let (mut h, li, legend) = countries_open(0, json!({"layerOrder": ["Countries"]})); + type_label(&mut h, "Label of Countries", &long); + h.get_by_label("Hide the labels of Countries").click(); + h.run_steps(5); + h.state_mut().run("layout.update", json!({"layout": li, "element": legend, "labels": {"Countries": "Elsewhere"}})).unwrap(); + h.get_by_label("Show the labels of Countries").click(); + h.run_steps(5); + assert_eq!(box_text(&h, "Label of Countries"), "Elsewhere"); +} + +/// A label the command takes leaves nothing kept, its box shown or hidden: undone, the box shows +/// the legend's text again, and the same text can be set again (#3436). +#[test] +fn a_legends_accepted_label_is_not_kept() { + use egui_kittest::kittest::Queryable; + // Left in its box, or saved as its row closes. + for hidden_first in [false, true] { + for label in ["Label of Countries", "Label of Africa in Countries"] { + let case = format!("{label}, hidden first: {hidden_first}"); + let (mut h, li, legend) = countries_open(0, json!({"layerOrder": ["Countries"]})); + let before = legend_texts(h.state(), li, legend); + type_label(&mut h, label, "Typed"); + if !hidden_first { + leave_box(&mut h); + } + h.get_by_label("Hide the labels of Countries").click(); + h.run_steps(5); + let set = legend_texts(h.state(), li, legend); + assert_ne!(set, before, "{case}"); + assert!(h.state().layout.sent.is_empty(), "{case}"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.get_by_label("Show the labels of Countries").click(); + h.run_steps(5); + assert_eq!(box_text(&h, label), "", "{case}"); + type_label(&mut h, label, "Typed"); + leave_box(&mut h); + assert_eq!(legend_texts(h.state(), li, legend), set, "{case}"); + } + } +} + +/// A row with the legend's own text still names its layer, so two given one text tell apart, and a +/// class box names its class beside it, empty, being typed, refused or filled (#3436). +#[test] +fn a_legends_own_texts_still_say_what_they_rename() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let (h, ..) = countries_open( + 0, + json!({"layerOrder": ["Countries"], "labels": {"Rivers": "Water", "Lakes": "Water", "Cities": "Cities"}, + "classLabels": {"Countries": {"Africa": "Asia"}}}), + ); + for row in ["Water (Rivers)", "Water (Lakes)", "Countries", "Cities"] { + assert!(h.query_by_role_and_label(Role::CheckBox, row).is_some(), "{row}"); + } + let mut h = h; + let long = "a".repeat(rustgis_engine::map::layout::MAX_LEGEND_LABEL_CHARS + 1); + let beside = |h: &egui_kittest::Harness<'_, RustGisApp>, class: &str| { + let name = h.get_by_label(class).rect(); + let held = h.get_by_label(&format!("Label of {class} in Countries")).rect(); + assert!(name.max.x <= held.min.x && (name.center().y - held.center().y).abs() < 4.0, "{class}: {name:?} {held:?}"); + held + }; + // Filled, and empty. + let filled = beside(&h, "Africa"); + let empty = beside(&h, "Europe"); + // The boxes line up under the layer's, whatever their classes' names measure. + assert_eq!(filled.min.x, empty.min.x); + assert_eq!(h.get_by_label("Label of Countries").rect().min.x, empty.min.x); + // Being typed, the box stays where it was; refused, it still says its class. + type_label(&mut h, "Label of Europe in Countries", &long); + assert_eq!(beside(&h, "Europe").min.x, empty.min.x); + leave_box(&mut h); + beside(&h, "Europe"); + assert_eq!(box_text(&h, "Label of Europe in Countries"), long); +} + +/// The filter finds a layer by the legend's own text for it as by its name (#3436). +#[test] +fn a_legends_layer_filter_finds_its_own_text() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let (mut h, li, legend) = legend_tree(8, json!({"labels": {"Rivers": "Waterways"}, "layerOrder": ["Rivers"]})); + for typed in ["waterw", "river"] { + type_layer_filter(&mut h, typed); + assert!(h.query_by_role_and_label(Role::CheckBox, "Waterways (Rivers)").is_some(), "{typed}"); + assert!(h.query_by_role_and_label(Role::CheckBox, "Cities").is_none(), "{typed}"); + } + // The layer keeps its name for every legend and command, so its box sets `labels` under it. + h.get_by_label("Show the labels of Rivers").click(); h.run_steps(3); - assert!(h.query_by_label("Renamed here").is_none()); + type_label(&mut h, "Label of Rivers", "Streams"); + leave_box(&mut h); + assert_eq!(legend_texts(h.state(), li, legend).0, json!({"Rivers": "Streams"})); } /// A hundred layers scroll in a box of their own, so what follows the list stays near (#3306). @@ -2749,7 +3043,7 @@ fn a_legends_layer_filter_is_its_layouts_own() { use egui::accesskit::Role; use egui_kittest::kittest::Queryable; let (mut h, _, legend) = legend_tree(8, json!({"layerOrder": ["Rivers", "Countries"]})); - h.get_by_label("Show the classes of Countries").click(); + h.get_by_label("Show the labels of Countries").click(); h.run_steps(3); layer_filter(&h).unwrap().focus(); h.run_steps(2); @@ -2764,7 +3058,7 @@ fn a_legends_layer_filter_is_its_layouts_own() { h.state_mut().layout.selected = Some(other); h.run_steps(10); assert!(h.query_by_role_and_label(Role::CheckBox, "Lakes").is_some()); - assert!(h.query_by_label("Show the classes of Countries").is_some(), "and its classes closed"); + assert!(h.query_by_label("Show the labels of Countries").is_some(), "and its labels closed"); } /// The filter finds a name in any case, a Greek sigma too, whose lower case depends on its place @@ -3233,7 +3527,7 @@ fn a_capture_keeps_the_text_being_typed() { app.run("layout.new", json!({"name": "Typing"})).unwrap(); let li = app.session.active_layout.unwrap(); let title = app.session.project.layouts[li].elements.iter().find(|e| e.name == "Title").unwrap().id; - app.layout.typing.insert((li, title, "text"), "Typed".into()); + app.layout.typing.insert((li, title, "text".into()), "Typed".into()); // The pane drew this field last frame and it still has focus. app.layout.drawn = Some((li, title)); app.run("ui.captureLayout", json!(null)).unwrap(); @@ -3267,7 +3561,7 @@ fn a_draft_follows_its_layout_when_the_layouts_change_places() { let (title, before) = title_of(&app, "A"); assert_eq!(title, title_of(&app, "C").0, "the same id in both layouts"); super::follow_project(&mut app); - app.layout.typing.insert((place(&app, "A"), title, "text"), "Typed for A".into()); + app.layout.typing.insert((place(&app, "A"), title, "text".into()), "Typed for A".into()); let to_front = json!({"name": "C", "to": 0}); if by_agent { app.session.run("layout.move", &to_front).unwrap(); @@ -3286,7 +3580,7 @@ fn a_draft_follows_its_layout_when_the_layouts_change_places() { } let (title, before) = title_of(&app, "B"); super::follow_project(&mut app); - app.layout.typing.insert((place(&app, "A"), title, "text"), "Typed for A".into()); + app.layout.typing.insert((place(&app, "A"), title, "text".into()), "Typed for A".into()); app.session.run("layout.remove", &json!({"name": "A"})).unwrap(); super::save_drafts(&mut app); assert_eq!(title_of(&app, "B").1, before); @@ -3296,7 +3590,7 @@ fn a_draft_follows_its_layout_when_the_layouts_change_places() { app.run("layout.new", json!({"name": "C"})).unwrap(); let (_, before_c) = title_of(&app, "C"); super::follow_project(&mut app); - app.layout.typing.insert((place(&app, "B"), title, "text"), "Typed for B".into()); + app.layout.typing.insert((place(&app, "B"), title, "text".into()), "Typed for B".into()); app.session.run("layout.remove", &json!({"name": "B"})).unwrap(); app.session.run("layout.new", &json!({"name": "D"})).unwrap(); super::save_drafts(&mut app); @@ -3307,7 +3601,7 @@ fn a_draft_follows_its_layout_when_the_layouts_change_places() { for name in ["F", "E"] { app.run("layout.new", json!({"name": "E"})).unwrap(); super::follow_project(&mut app); - app.layout.typing.insert((place(&app, "E"), title, "text"), "Typed for E".into()); + app.layout.typing.insert((place(&app, "E"), title, "text".into()), "Typed for E".into()); app.session.run("layout.remove", &json!({"name": "E"})).unwrap(); app.session.run("layout.new", &json!({"name": name})).unwrap(); super::save_drafts(&mut app); @@ -3317,21 +3611,21 @@ fn a_draft_follows_its_layout_when_the_layouts_change_places() { } // Renamed, by an agent between frames: the draft stays with it. super::follow_project(&mut app); - app.layout.typing.insert((place(&app, "C"), title, "text"), "Typed for C".into()); + app.layout.typing.insert((place(&app, "C"), title, "text".into()), "Typed for C".into()); app.session.run("layout.rename", &json!({"name": "C", "newName": "X"})).unwrap(); super::save_drafts(&mut app); assert_eq!(title_of(&app, "X").1, "Typed for C"); // Renamed, and its old name given to another, in one go: the draft stays with its own // layout, not the one now called what it was. super::follow_project(&mut app); - app.layout.typing.insert((place(&app, "D"), title, "text"), "Typed for D".into()); + app.layout.typing.insert((place(&app, "D"), title, "text".into()), "Typed for D".into()); app.session.run("layout.rename", &json!({"name": "D", "newName": "Q"})).unwrap(); app.session.run("layout.rename", &json!({"name": "X", "newName": "D"})).unwrap(); super::save_drafts(&mut app); assert_eq!((title_of(&app, "Q").1, title_of(&app, "D").1), ("Typed for D".to_string(), "Typed for C".to_string())); // Copied: the draft is the original's, not the copy's. super::follow_project(&mut app); - app.layout.typing.insert((place(&app, "Q"), title, "text"), "Typed again".into()); + app.layout.typing.insert((place(&app, "Q"), title, "text".into()), "Typed again".into()); app.session.run("layout.duplicate", &json!({"name": "Q", "newName": "Q2"})).unwrap(); super::save_drafts(&mut app); assert_eq!((title_of(&app, "Q").1, title_of(&app, "Q2").1), ("Typed again".to_string(), "Typed for D".to_string())); diff --git a/docs/user-guide/layouts.md b/docs/user-guide/layouts.md index 1263f5b1c7..ac61b133f7 100644 --- a/docs/user-guide/layouts.md +++ b/docs/user-guide/layouts.md @@ -543,7 +543,7 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu a fit, leaves its layer names off or has more than three columns can't be opened by an older RustGIS, and a layout file (`.rgislayout`) with such a legend lists that in its header, so an older RustGIS refuses it as well. - - **Class labels** (`"classLabels"`, commands and scripts only): the legend's own text for a + - **Class labels** (`"classLabels"`, or the boxes in the Layers section): the legend's own text for a class, leaving the layer, the Layers pane and every other legend as they are: `layout.update {"element": 3, "classLabels": {"Roads": {"Primary": "Main roads"}}}`. A class is named by the label the layer shows for it, a range or `` included; @@ -600,10 +600,14 @@ Layouts open as tabs next to the maps; while one is open, its groups lead the Pu place, each move one undo step. **Select All** and **Select None** tick or untick every layer shown, and **Reset** lists every layer again in the map's order, keeping the legend's own texts; each is one undo step. The rows scroll in a box of their own, and over eight layers - **Filter layers** keeps those whose name contains the text, in any case; **Select All** and - **Select None** then act on those alone, and ▲ and ▼ swap a layer with the nearest one shown. - The arrow beside a layer drawn by classes shows its classes as the legend labels them, every - one it can list, to read only. + **Filter layers** keeps those whose name, or the legend's own text for it, contains the text, + in any case; **Select All** and **Select None** then act on those alone, and ▲ and ▼ swap a + layer with the nearest one shown. The arrow beside a layer opens its labels: a **Label** box + for the legend's own text for the layer (the layer's name while empty; with a text, the row + shows it followed by the name) and, for a layer drawn by classes, a box for each class it can + list, beside the label the layer shows for it (also the box's hint while empty). Leaving a box + sets that text, one undo step, and emptying it shows the original again, as `"labels"` and + `"classLabels"` do. - **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