diff --git a/crates/ui-egui/src/layoutview.rs b/crates/ui-egui/src/layoutview.rs index ae35f1a33c..26bf4c0153 100644 --- a/crates/ui-egui/src/layoutview.rs +++ b/crates/ui-egui/src/layoutview.rs @@ -14,6 +14,8 @@ mod actions; mod format; mod handles; mod interact; +#[cfg(test)] +mod refused_tests; mod section; mod snap; #[cfg(test)] @@ -177,6 +179,9 @@ pub struct LayoutView { /// 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>, /// 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)>, @@ -224,9 +229,10 @@ impl LayoutView { } } -/// Forgets the selection, the text typed into its fields and the layouts' page views once another -/// project has replaced the one they were for: its elements and layouts may have the same ids and -/// names. Run after every command, after what agents and scripts sent, and before drafts are saved. +/// Forgets the selection, the text typed into its fields or kept after a refusal, and the +/// layouts' page views once another project has replaced the one they were for: its elements and +/// layouts may have the same ids and names. Run after every command, after what agents and scripts +/// sent, and before drafts are saved. pub(crate) fn follow_project(app: &mut RustGisApp) { let opened = app.session.opened; if app.layout.project.is_some_and(|p| p != opened) { @@ -234,6 +240,7 @@ pub(crate) fn follow_project(app: &mut RustGisApp) { app.layout.formatted = None; app.layout.drawn = None; app.layout.typing.clear(); + app.layout.sent.clear(); app.layout.viewed = None; app.layout.text_warning = None; app.layout.section_warning = None; @@ -260,11 +267,12 @@ 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 typing = std::mem::take(&mut app.layout.typing); - app.layout.typing = typing - .into_iter() - .filter_map(|((l, id, field), text)| Some(((now.iter().position(|m| Some(m) == was.get(l))?, id, field), text))) - .collect(); + 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. + let sent = std::mem::take(&mut app.layout.sent); + app.layout.sent = sent.into_iter().filter_map(|(key, text)| Some((follow(key)?, text))).collect(); } } @@ -717,13 +725,24 @@ 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. /// Runs once a frame, after the panes and the view. pub(crate) fn save_drafts(app: &mut RustGisApp) { follow_project(app); let shown = app.layout.drawn.take(); + 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); +} + +/// 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 Some(text) = app.layout.typing.remove(&key) else { continue }; 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()), @@ -734,7 +753,11 @@ pub(crate) fn save_drafts(app: &mut RustGisApp) { ("unitLabel", ElementKind::ScaleBar { unit_label, .. }) => Some(unit_label.clone().unwrap_or_default()), _ => None, }); - if current.is_some_and(|c| c != text) { + // 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})); @@ -742,9 +765,11 @@ pub(crate) fn save_drafts(app: &mut RustGisApp) { } } -/// Saves all text being typed, the field the Format pane shows included: for a command that -/// draws the page before the pane runs this frame (the ribbon is drawn first). +/// Saves the text being typed, the field the Format pane shows included, for a command that +/// draws the page before the pane runs this frame (the ribbon is drawn first). A section line's +/// name, a grid's CRS and a chart's automatic title have no value in [`save_typed`] and stay +/// being typed. pub(crate) fn commit_drafts(app: &mut RustGisApp) { - app.layout.drawn = None; - save_drafts(app); + follow_project(app); + save_typed(app, None); } diff --git a/crates/ui-egui/src/layoutview/format.rs b/crates/ui-egui/src/layoutview/format.rs index 0136291473..49cabce452 100644 --- a/crates/ui-egui/src/layoutview/format.rs +++ b/crates/ui-egui/src/layoutview/format.rs @@ -48,8 +48,51 @@ pub(super) fn orientation_row(ui: &mut Ui, current: Orientation) -> Option<&'sta picked } +/// 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, + 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. + 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 { + // 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); + } + 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()) +} + +/// 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 { + // 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); + return None; + } + 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 }); + Some(text) +} + /// A text field whose typing is kept in the view's state while it has focus. Returns the new text -/// when the field loses focus with a change. +/// when the field loses focus with a change; one the element doesn't take stays in the field. pub(super) fn text_field( app: &mut RustGisApp, ui: &mut Ui, @@ -71,7 +114,7 @@ pub(super) fn hinted_text_field( hint: Option<&str>, label_id: egui::Id, ) -> Option { - let mut buf = app.layout.typing.remove(&key).unwrap_or_else(|| current.to_string()); + 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 { @@ -82,7 +125,7 @@ pub(super) fn hinted_text_field( } let r = ui.add(edit).labelled_by(label_id); if r.lost_focus() { - return (buf != current).then_some(buf); + return send(app, key, current, buf); } if r.has_focus() { app.layout.typing.insert(key, buf); diff --git a/crates/ui-egui/src/layoutview/format/frame.rs b/crates/ui-egui/src/layoutview/format/frame.rs index 123ec66c6f..7c69f676b8 100644 --- a/crates/ui-egui/src/layoutview/format/frame.rs +++ b/crates/ui-egui/src/layoutview/format/frame.rs @@ -10,6 +10,36 @@ use rustgis_engine::map::layout::{ }; use serde_json::{Value, json}; +/// Each section line's name box in [`LayoutView`]'s typing, by its place among the frame's. +pub(super) const SECTION_NAMES: [&str; MAX_SECTIONS] = [ + "section A", + "section B", + "section C", + "section D", + "section E", + "section F", + "section G", + "section H", + "section I", + "section J", + "section K", + "section L", + "section M", + "section N", + "section O", + "section P", + "section Q", + "section R", + "section S", + "section T", + "section U", + "section V", + "section W", + "section X", + "section Y", + "section Z", +]; + /// A map frame's section lines (#2863), each with its name, direction, place and look, why it isn't /// drawn when it isn't, and Remove; below them, the buttons that add one, whose direction is given /// back when one is clicked. `update` sends a change. @@ -17,6 +47,7 @@ fn section_rows( app: &mut RustGisApp, ui: &mut Ui, layout: &Layout, + li: usize, id: u32, sections: &[Section], update: &dyn Fn(&mut RustGisApp, Value), @@ -30,17 +61,16 @@ fn section_rows( ui.push_id(("section", id, i), |ui| { egui::Grid::new("section_place").num_columns(2).spacing(vec2(8.0, 6.0)).show(ui, |ui| { let label = ui.label(tl!("Name")); - // Typing is kept with the view until the field is left. - let key = egui::Id::unique(("section_name", id, i)); - let mut name = ui.data_mut(|d| d.get_temp::(key)).unwrap_or_else(|| s.name.clone()); + // 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 r = ui.add(egui::TextEdit::singleline(&mut name).desired_width(60.0)).labelled_by(label.id); - if r.has_focus() { - ui.data_mut(|d| d.insert_temp(key, name)); - } else { - ui.data_mut(|d| d.remove::(key)); - if r.lost_focus() && name.trim() != s.name { + if r.lost_focus() { + if let Some(name) = send(app, key, &s.name, name) { set(app, json!({"section": {"newName": name}})); } + } else if r.has_focus() { + app.layout.typing.insert(key, name); } ui.end_row(); let label = ui.label(tl!("Direction")); @@ -108,7 +138,7 @@ fn section_rows( } /// A map frame's grid options; `set` sends the changed ones (`false` removes the grid). -fn grid_properties(app: &mut RustGisApp, ui: &mut Ui, grid: Option<&Grid>, id: u32, set: &dyn Fn(&mut RustGisApp, Value)) { +fn grid_properties(app: &mut RustGisApp, ui: &mut Ui, grid: Option<&Grid>, li: usize, id: u32, set: &dyn Fn(&mut RustGisApp, Value)) { let mut on = grid.is_some(); if ui.checkbox(&mut on, tl!("Show grid")).changed() { set(app, json!(on)); @@ -133,7 +163,7 @@ fn grid_properties(app: &mut RustGisApp, ui: &mut Ui, grid: Option<&Grid>, id: u .labelled_by(input_label.id); ui.end_row(); if measured { - crs_row(app, ui, g, id, set); + crs_row(app, ui, g, li, id, set); } let input_label = ui.label(tl!("Interval")); let mut step = g.step; @@ -323,11 +353,11 @@ fn grid_properties(app: &mut RustGisApp, ui: &mut Ui, grid: Option<&Grid>, id: u /// A measured grid's coordinate system, typed (EPSG:25832, WKT or a PROJ string) and set when the /// 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, id: u32, set: &dyn Fn(&mut RustGisApp, Value)) { +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 = egui::Id::unique(("grid_crs", id)); + let key = (li, id, "crs"); let current = g.crs.clone().unwrap_or_default(); - let mut buf = ui.data(|d| d.get_temp::(key)).unwrap_or_else(|| current.clone()); + let mut buf = draft(app, key, ¤t); let (hint, help) = if g.mgrs { ( tl!("The map's UTM zone, else the frame's"), @@ -343,13 +373,12 @@ fn crs_row(app: &mut RustGisApp, ui: &mut Ui, g: &Grid, id: u32, set: &dyn Fn(&m }; 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.has_focus() { - ui.data_mut(|d| d.insert_temp(key, buf)); - } else { - ui.data_mut(|d| d.remove::(key)); - if r.lost_focus() && buf.trim() != current { - set(app, json!({"crs": buf.trim()})); + if r.lost_focus() { + if let Some(crs) = send(app, key, ¤t, buf.trim().to_string()) { + set(app, json!({"crs": crs})); } + } else if r.has_focus() { + app.layout.typing.insert(key, buf); } ui.end_row(); } @@ -421,7 +450,7 @@ pub(super) fn frame_sections( if let ElementKind::MapFrame { grid, .. } = &e.kind { ui.add_space(4.0); egui::CollapsingHeader::new(tl!("Grid")).id_salt(("frame_grid", id)).default_open(grid.is_some()).show(ui, |ui| { - grid_properties(app, ui, grid.as_ref(), id, &|app, g| update(app, json!({"grid": g}))); + grid_properties(app, ui, grid.as_ref(), li, id, &|app, g| update(app, json!({"grid": g}))); }); } if let ElementKind::MapFrame { sections, .. } = &e.kind { @@ -429,7 +458,7 @@ pub(super) fn frame_sections( egui::CollapsingHeader::new(tl!("Section Lines")).id_salt(("frame_sections", id)).default_open(!sections.is_empty()).show( ui, |ui| { - if let Some(direction) = section_rows(app, ui, layout, id, sections, &update) { + if let Some(direction) = section_rows(app, ui, layout, li, id, sections, &update) { let _ = app.run("layout.addElement", json!({"layout": li, "kind": "section", "frame": id, "direction": direction})); } }, diff --git a/crates/ui-egui/src/layoutview/format/scalebar.rs b/crates/ui-egui/src/layoutview/format/scalebar.rs index 34ee99aaf0..c68ce1f298 100644 --- a/crates/ui-egui/src/layoutview/format/scalebar.rs +++ b/crates/ui-egui/src/layoutview/format/scalebar.rs @@ -5,8 +5,8 @@ use crate::RustGisApp; use crate::widgets::Dragged; use egui::Ui; use rustgis_engine::map::layout::{ - Element, ElementKind, Layout, MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS, ScaleBarFit, - ScaleBarStyle, ScaleLabelPosition, ScaleUnits, UnitLabelPosition, + Element, ElementKind, Layout, MAX_SCALE_BEFORE_ZERO, MAX_SCALE_DECIMALS, MAX_SCALE_DIVISIONS, MAX_SCALE_SUBDIVISIONS, + MAX_UNIT_LABEL_CHARS, ScaleBarFit, ScaleBarStyle, ScaleLabelPosition, ScaleUnits, UnitLabelPosition, }; use serde_json::{Value, json}; @@ -155,8 +155,15 @@ pub(super) fn scale_bar_rows( // gets this one's text; a renamed layout forgets it. let kept = egui::Id::unique(("scale_unit_label_kept", app.session.opened, li, layout.name.as_str(), id)); // The label being typed is dropped, so the field losing its focus - // doesn't write it back; hidden, it is the text kept. - let draft = app.layout.typing.remove(&(li, id, "unitLabel")); + // 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 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) + { + update(app, json!({"unitLabel": long})); + } if on { // Read, not taken: a show that is undone can be shown again. let typed = ui.ctx().data(|d| d.get_temp::(kept)).filter(|t| !t.is_empty()); @@ -164,7 +171,7 @@ pub(super) fn scale_bar_rows( } else { // Every hide keeps the text hidden now, and forgets an older one // once the label is back to the abbreviation. - match draft.or_else(|| unit_label.clone()).filter(|t| !t.is_empty()) { + match dropped.or_else(|| unit_label.clone()).filter(|t| !t.is_empty()) { Some(text) => { ui.ctx().data_mut(|d| d.insert_temp(kept, text)); } diff --git a/crates/ui-egui/src/layoutview/format/text.rs b/crates/ui-egui/src/layoutview/format/text.rs index fbfe7bdeb4..3059aec8cc 100644 --- a/crates/ui-egui/src/layoutview/format/text.rs +++ b/crates/ui-egui/src/layoutview/format/text.rs @@ -63,7 +63,7 @@ pub(super) fn text_section( } = &e.kind { let key = (li, id, "text"); - let mut buf = app.layout.typing.remove(&key).unwrap_or_else(|| text.clone()); + 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()); @@ -99,8 +99,10 @@ pub(super) fn text_section( .unwrap_or_default(); if settled.typing { app.layout.typing.insert(key, buf); - } else if settled.text && buf != *text { - update(app, json!({"text": buf})); + } else if settled.text + && let Some(new_text) = send(app, key, text, buf) + { + update(app, json!({"text": new_text})); } if settled.size { update(app, json!({"size": sz})); diff --git a/crates/ui-egui/src/layoutview/refused_tests.rs b/crates/ui-egui/src/layoutview/refused_tests.rs new file mode 100644 index 0000000000..b6245c903a --- /dev/null +++ b/crates/ui-egui/src/layoutview/refused_tests.rs @@ -0,0 +1,402 @@ +//! Tests of the text a Format box keeps when its command refuses it (#3348). + +use crate::RustGisApp; +use egui::{Key, Modifiers, vec2}; +use rustgis_engine::map::layout::ElementKind; +use serde_json::json; + +/// The Format pane of element `id` of layout `li`, run as the app does: the pane, then the end of +/// the frame ([`super::save_drafts`]). +fn format_harness(mut app: RustGisApp, li: usize, id: u32) -> egui_kittest::Harness<'static, RustGisApp> { + app.layout.selected = Some(id); + let mut h = egui_kittest::Harness::builder().with_size(vec2(420.0, 1600.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + let layout = app.session.project.layouts[li].clone(); + egui::ScrollArea::vertical().show(ui, |ui| super::properties(app, ui, &layout, li)); + app.layout.drawn = app.layout.selected.map(|id| (li, id)); + super::save_drafts(app); + }, + app, + ); + h.run_steps(2); + h +} + +/// A new layout with one element added by `params`: its place and the element's id. +fn layout_with(params: serde_json::Value) -> (RustGisApp, usize, u32) { + let mut app = RustGisApp::with_sample(); + app.run("layout.new", json!({"name": "Refused"})).unwrap(); + let li = app.session.active_layout.unwrap(); + let mut p = params; + p["layout"] = json!(li); + let id = app.run("layout.addElement", p).unwrap()["element"].as_u64().unwrap() as u32; + (app, li, id) +} + +/// Types `text` after what the box labelled `label` holds, and leaves the box. +fn type_and_leave(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.get_by_label(label).type_text(text); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); +} + +fn box_value(h: &egui_kittest::Harness<'_, RustGisApp>, label: &str) -> String { + use egui_kittest::kittest::Queryable; + h.get_by_label(label).value().unwrap_or_default() +} + +fn subtitle_of(app: &RustGisApp, li: usize, id: u32) -> String { + match &app.session.project.layouts[li].element(id).unwrap().kind { + ElementKind::Legend { subtitle, .. } => subtitle.clone(), + k => panic!("{k:?}"), + } +} + +/// A box whose text the command refuses keeps it, to be corrected, and applies it once it fits +/// (#3348). +#[test] +fn a_refused_subtitle_stays_in_its_box_until_it_fits() { + let (app, li, id) = layout_with(json!({"kind": "legend"})); + let mut h = format_harness(app, li, id); + let (depth, mark) = (h.state().session.undo_depth(), h.state().session.notice_mark()); + let long = "a".repeat(201); + type_and_leave(&mut h, "Subtitle", &long); + assert_eq!(subtitle_of(h.state(), li, id), "", "refused"); + assert_eq!(box_value(&h, "Subtitle"), long, "kept to be corrected"); + assert_eq!(h.state().session.undo_depth(), depth); + let errors = h.state().session.notices_since(mark).iter().filter(|n| n.error).count(); + assert_eq!(errors, 1, "said once: {:?}", h.state().session.notices_since(mark).iter().map(|n| &n.text).collect::>()); + // One character less: it applies, and nothing is left kept. + { + use egui_kittest::kittest::Queryable; + h.get_by_label("Subtitle").focus(); + } + h.run_steps(2); + h.key_press(Key::End); + h.key_press(Key::Backspace); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); + assert_eq!(subtitle_of(h.state(), li, id), "a".repeat(200)); + assert!(h.state().layout.sent.is_empty()); +} + +/// A text the command takes leaves nothing kept (#3348). +#[test] +fn an_accepted_title_is_not_kept() { + use egui_kittest::kittest::Queryable; + let (app, li, id) = layout_with(json!({"kind": "legend", "title": "Mine"})); + let mut h = format_harness(app, li, id); + let mark = h.state().session.notice_mark(); + type_and_leave(&mut h, "Title", " 2"); + assert!( + matches!(&h.state().session.project.layouts[li].element(id).unwrap().kind, ElementKind::Legend { title, .. } if title == "Mine 2") + ); + assert_eq!(box_value(&h, "Title"), "Mine 2"); + assert!(h.state().layout.sent.is_empty()); + // Spaces alone around a name change nothing: the box shows the name again. + let name = box_value(&h, "Name"); + type_and_leave(&mut h, "Name", " "); + assert_eq!(box_value(&h, "Name"), name); + assert!(h.state().layout.sent.is_empty()); + // A blank name is ignored by the command: the box shows the name again too. + h.get_by_label("Name").focus(); + h.run_steps(2); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.key_press(Key::Backspace); + h.run_steps(2); + assert_eq!(box_value(&h, "Name"), "", "emptied"); + h.key_press(Key::Enter); + h.run_steps(3); + assert_eq!(box_value(&h, "Name"), name); + assert!(h.state().layout.sent.is_empty()); + assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.error).count(), 0); +} + +/// The kept text gives way to a value set elsewhere, to another element's selection and to another +/// project (#3348). +#[test] +fn a_refused_text_gives_way_to_a_new_value_selection_or_project() { + use egui_kittest::kittest::Queryable; + let long = "a".repeat(201); + // Set elsewhere: a script, an agent, an undo. + let (app, li, id) = layout_with(json!({"kind": "legend"})); + let mut h = format_harness(app, li, id); + type_and_leave(&mut h, "Subtitle", &long); + h.state_mut().run("layout.update", json!({"layout": li, "element": id, "subtitle": "Elsewhere"})).unwrap(); + h.run_steps(2); + assert_eq!(box_value(&h, "Subtitle"), "Elsewhere"); + assert!(h.state().layout.sent.is_empty()); + // Another element selected: the refused text is dropped, never sent again. + let (mut app, li, id) = layout_with(json!({"kind": "legend"})); + let p = json!({"layout": li, "kind": "text", "text": "Other"}); + let other = app.run("layout.addElement", p).unwrap()["element"].as_u64().unwrap() as u32; + let mut h = format_harness(app, li, id); + type_and_leave(&mut h, "Subtitle", &long); + let mark = h.state().session.notice_mark(); + h.state_mut().layout.selected = Some(other); + h.run_steps(3); + h.state_mut().layout.selected = Some(id); + h.run_steps(3); + assert_eq!(h.get_by_label("Subtitle").value().unwrap_or_default(), ""); + assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.error).count(), 0); + // A capture saves the text still being typed: refused, it stays in its box. + h.get_by_label("Subtitle").focus(); + h.run_steps(2); + h.get_by_label("Subtitle").type_text(&long); + h.run_steps(2); + h.state_mut().run("ui.captureLayout", json!(null)).unwrap(); + h.run_steps(2); + assert_eq!(h.get_by_label("Subtitle").value().unwrap_or_default(), long); + h.key_press(Key::Enter); + h.run_steps(3); + // Another project. + type_and_leave(&mut h, "Subtitle", &long); + assert!(!h.state().layout.sent.is_empty()); + h.state_mut().run("project.new", json!({})).unwrap(); + assert!(h.state().layout.sent.is_empty()); +} + +/// The text element's box and a box with a hint keep a refused text too (#3348). +#[test] +fn a_refused_text_and_unit_label_stay_in_their_boxes() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let (app, li, id) = layout_with(json!({"kind": "text", "text": "a".repeat(rustgis_engine::map::layout::MAX_TEXT_CHARS)})); + let mut h = format_harness(app, li, id); + let text_box = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.query_all_by_role(Role::MultilineTextInput).next().unwrap().value().unwrap_or_default() + }; + h.query_all_by_role(Role::MultilineTextInput).next().unwrap().focus(); + h.run_steps(2); + h.query_all_by_role(Role::MultilineTextInput).next().unwrap().type_text("b"); + h.run_steps(2); + // Enter adds a line in this box: leave it by focusing the Name box. + h.get_by_label("Name").focus(); + h.run_steps(3); + assert_eq!(text_box(&h).chars().count(), rustgis_engine::map::layout::MAX_TEXT_CHARS + 1, "kept to be corrected"); + assert!( + matches!(&h.state().session.project.layouts[li].element(id).unwrap().kind, ElementKind::Text { text, .. } if *text == "a".repeat(rustgis_engine::map::layout::MAX_TEXT_CHARS)) + ); + + let (mut app, li, _) = layout_with(json!({"kind": "text"})); + let p = json!({"layout": li, "kind": "scaleBar"}); + let bar = app.run("layout.addElement", p).unwrap()["element"].as_u64().unwrap() as u32; + let mut h = format_harness(app, li, bar); + let long = "u".repeat(101); + type_and_leave(&mut h, "Unit label", &long); + assert_eq!(box_value(&h, "Unit label"), long); + assert!(matches!(&h.state().session.project.layouts[li].element(bar).unwrap().kind, ElementKind::ScaleBar { unit_label: None, .. })); +} + +/// A refused text goes with the field that showed it: a mode that hides the field drops it, so it +/// doesn't come back with a value like the one it was typed over (#3348). +#[test] +fn a_refused_text_goes_with_the_field_that_showed_it() { + use egui_kittest::kittest::Queryable; + let (app, li, id) = layout_with(json!({"kind": "scaleBar"})); + let mut h = format_harness(app, li, id); + type_and_leave(&mut h, "Unit label", &"u".repeat(101)); + assert!(!h.state().layout.sent.is_empty()); + for _ in 0..2 { + h.get_by_label("Show unit label").click(); + h.run_steps(3); + } + assert_eq!(box_value(&h, "Unit label"), ""); +} + +/// A section line's name box and the grid's coordinate system box keep a refused text too (#3348). +#[test] +fn a_refused_section_name_and_grid_crs_stay_in_their_boxes() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.run("layout.new", json!({"name": "Refused"})).unwrap(); + let li = app.session.active_layout.unwrap(); + let elements = &app.session.project.layouts[li].elements; + let id = elements.iter().find(|e| matches!(e.kind, ElementKind::MapFrame { .. })).unwrap().id; + for direction in ["horizontal", "vertical"] { + app.run("layout.addElement", json!({"layout": li, "kind": "section", "frame": id, "direction": direction})).unwrap(); + } + app.run("layout.update", json!({"layout": li, "element": id, "grid": {"type": "measured"}})).unwrap(); + let mut h = format_harness(app, li, id); + // The second line's box: each has its own. + let names = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.query_all_by_role_and_label(Role::TextInput, "Name").map(|n| n.value().unwrap_or_default()).collect::>() + }; + let before = names(&h); + h.query_all_by_role_and_label(Role::TextInput, "Name").last().unwrap().focus(); + h.run_steps(2); + h.query_all_by_role_and_label(Role::TextInput, "Name").last().unwrap().type_text(&"s".repeat(21)); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); + let after = names(&h); + assert_eq!(after.len(), before.len()); + assert_eq!(&after[..after.len() - 1], &before[..before.len() - 1], "the other boxes show their own"); + assert_eq!(after.last().unwrap(), &format!("{}{}", before.last().unwrap(), "s".repeat(21)), "kept to be corrected"); + h.get_by_role_and_label(Role::TextInput, "Coordinate system").focus(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, "Coordinate system").type_text("not a system"); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); + assert_eq!(h.get_by_role_and_label(Role::TextInput, "Coordinate system").value().unwrap_or_default(), "not a system"); + assert!( + matches!(&h.state().session.project.layouts[li].element(id).unwrap().kind, ElementKind::MapFrame { grid: Some(g), .. } if g.crs.is_none()) + ); +} + +/// A text refused as it is saved for an element no longer shown is not kept at all: showing the +/// element again, the next frame, shows its value (#3348). +#[test] +fn a_text_refused_after_its_element_is_left_is_not_kept() { + use egui_kittest::kittest::Queryable; + let (mut app, li, id) = layout_with(json!({"kind": "legend"})); + let p = json!({"layout": li, "kind": "text", "text": "Other"}); + let other = app.run("layout.addElement", p).unwrap()["element"].as_u64().unwrap() as u32; + let mut h = format_harness(app, li, id); + h.get_by_label("Subtitle").focus(); + h.run_steps(2); + h.get_by_label("Subtitle").type_text(&"a".repeat(201)); + h.run_steps(2); + let mark = h.state().session.notice_mark(); + h.state_mut().layout.selected = Some(other); + h.run_steps(1); + assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.error).count(), 1, "sent and refused"); + assert!(h.state().layout.sent.is_empty()); +} + +/// A refused text whose box is focused again and left by selecting another element is not sent, or +/// said, a second time (#3348). +#[test] +fn a_refused_text_left_by_selecting_another_element_is_said_once() { + use egui_kittest::kittest::Queryable; + let (mut app, li, id) = layout_with(json!({"kind": "legend"})); + let p = json!({"layout": li, "kind": "text", "text": "Other"}); + let other = app.run("layout.addElement", p).unwrap()["element"].as_u64().unwrap() as u32; + let mut h = format_harness(app, li, id); + type_and_leave(&mut h, "Subtitle", &"a".repeat(201)); + h.get_by_label("Subtitle").focus(); + h.run_steps(2); + assert!(!h.state().layout.typing.is_empty(), "focused again, unchanged"); + let mark = h.state().session.notice_mark(); + h.state_mut().layout.selected = Some(other); + h.run_steps(3); + assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.error).count(), 0); + assert!(h.state().layout.typing.is_empty() && h.state().layout.sent.is_empty()); +} + +/// A refused text follows its layout when the layouts change, as the text being typed does: left +/// again, it isn't sent or said a second time (#3348). +#[test] +fn a_refused_text_follows_its_layout_when_the_layouts_change() { + use egui_kittest::kittest::Queryable; + let (app, li, id) = layout_with(json!({"kind": "legend"})); + let mut h = format_harness(app, li, id); + let long = "a".repeat(201); + type_and_leave(&mut h, "Subtitle", &long); + h.get_by_label("Subtitle").focus(); + h.run_steps(2); + let mark = h.state().session.notice_mark(); + // As an agent or a script does, through the session: the pane keeps showing the element. + h.state_mut().session.run("layout.new", &json!({"name": "Another"})).unwrap(); + h.run_steps(2); + h.key_press(Key::Enter); + h.run_steps(3); + assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.error).count(), 0); + assert_eq!(box_value(&h, "Subtitle"), long); +} + +/// A capture leaves a section line's name and a grid's coordinate system being typed in their +/// boxes, to be saved when they are left (#3348). +#[test] +fn a_capture_leaves_a_section_name_and_grid_crs_being_typed() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.run("layout.new", json!({"name": "Capture"})).unwrap(); + let li = app.session.active_layout.unwrap(); + let elements = &app.session.project.layouts[li].elements; + let id = elements.iter().find(|e| matches!(e.kind, ElementKind::MapFrame { .. })).unwrap().id; + app.run("layout.addElement", json!({"layout": li, "kind": "section", "frame": id})).unwrap(); + app.run("layout.update", json!({"layout": li, "element": id, "grid": {"type": "measured"}})).unwrap(); + let mut h = format_harness(app, li, id); + let section = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.query_all_by_role_and_label(Role::TextInput, "Name").last().unwrap().value().unwrap_or_default() + }; + let before = section(&h); + h.query_all_by_role_and_label(Role::TextInput, "Name").last().unwrap().focus(); + h.run_steps(2); + h.query_all_by_role_and_label(Role::TextInput, "Name").last().unwrap().type_text("x"); + h.run_steps(2); + h.state_mut().run("ui.captureLayout", json!(null)).unwrap(); + h.run_steps(2); + assert_eq!(section(&h), format!("{before}x"), "still being typed"); + h.key_press(Key::Enter); + h.run_steps(3); + assert_eq!(section(&h), format!("{before}x"), "saved"); + let crs = |h: &egui_kittest::Harness<'_, RustGisApp>| { + h.get_by_role_and_label(Role::TextInput, "Coordinate system").value().unwrap_or_default() + }; + h.get_by_role_and_label(Role::TextInput, "Coordinate system").focus(); + h.run_steps(2); + h.get_by_role_and_label(Role::TextInput, "Coordinate system").type_text("EPSG:32632"); + h.run_steps(2); + h.state_mut().run("ui.captureLayout", json!(null)).unwrap(); + h.run_steps(2); + assert_eq!(crs(&h), "EPSG:32632", "still being typed"); + h.key_press(Key::Enter); + h.run_steps(3); + assert!( + matches!(&h.state().session.project.layouts[li].element(id).unwrap().kind, ElementKind::MapFrame { grid: Some(g), .. } if g.crs.as_deref() == Some("EPSG:32632")) + ); +} + +/// Hiding the unit label while its box holds a refused text keeps the label the bar had, so it can +/// be shown again (#3348). +#[test] +fn hiding_a_unit_label_never_keeps_a_refused_text() { + use egui_kittest::kittest::Queryable; + let (app, li, id) = layout_with(json!({"kind": "scaleBar", "unitLabel": "Kilometres"})); + let mut h = format_harness(app, li, id); + let label = |h: &egui_kittest::Harness<'_, RustGisApp>| match &h.state().session.project.layouts[li].element(id).unwrap().kind { + ElementKind::ScaleBar { unit_label, .. } => unit_label.clone(), + k => panic!("{k:?}"), + }; + type_and_leave(&mut h, "Unit label", &"u".repeat(101)); + // Focused again, unchanged, and hidden from there. + h.get_by_label("Unit label").focus(); + h.run_steps(2); + for shown in [Some(String::new()), Some("Kilometres".to_string())] { + h.get_by_label("Show unit label").click(); + h.run_steps(3); + assert_eq!(label(&h), shown); + } +} + +/// A unit label over its limit, hidden before its box is left, is refused with its reason, once +/// (#3348). +#[test] +fn hiding_an_unsent_unit_label_over_its_limit_says_why() { + use egui_kittest::kittest::Queryable; + let (app, li, id) = layout_with(json!({"kind": "scaleBar", "unitLabel": "Kilometres"})); + let mut h = format_harness(app, li, id); + h.get_by_label("Unit label").focus(); + h.run_steps(2); + h.get_by_label("Unit label").type_text(&"u".repeat(101)); + h.run_steps(2); + let mark = h.state().session.notice_mark(); + h.get_by_label("Show unit label").click(); + h.run_steps(3); + assert_eq!(h.state().session.notices_since(mark).iter().filter(|n| n.error).count(), 1); + assert!( + matches!(&h.state().session.project.layouts[li].element(id).unwrap().kind, + ElementKind::ScaleBar { unit_label: Some(label), .. } if label.is_empty()), + "hidden all the same" + ); +}