From 03e8d4c93a02153670745724629f301f862cc0b7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Wed, 25 Nov 2026 22:48:01 -0500 Subject: [PATCH 01/23] feat(ui): the Script pane finds and replaces text, with Ctrl+F (#2996) Ctrl+F (Cmd+F) in the Script box opens a find bar over its top right, as a code editor does: a field with Match Case and Match Whole Word inside it, the count, previous, next and close buttons, and an arrow that shows the Replace row. Every match is highlighted and the current one is stronger. Enter and Shift+Enter, or F3 and Shift+F3, go round the matches; Ctrl+H opens the Replace row; Esc in the bar's fields closes it with the current match selected in the box. Replace and Replace All are one undo step of the box and wait for a run to finish. The bar is drawn with completion::popup, and widgets gains flat_icon_button and text_origin for the editor's next bars. --- crates/ui-egui/src/analysispane.rs | 280 ++++++++++++- crates/ui-egui/src/icons.rs | 21 + crates/ui-egui/src/lib.rs | 1 + crates/ui-egui/src/scriptfind.rs | 641 +++++++++++++++++++++++++++++ crates/ui-egui/src/widgets.rs | 25 ++ docs/user-guide/analysis.md | 13 + 6 files changed, 976 insertions(+), 5 deletions(-) create mode 100644 crates/ui-egui/src/scriptfind.rs diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index bddb2fe3f5..cbe72a1180 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -2022,11 +2022,16 @@ fn clear_keeping_undo(app: &mut RustGisApp, ui: &Ui, box_id: egui::Id) { /// The Script box's script kept as an undo step of the box, its cursor at the start, before /// something else replaces it (Clear, Open in Script Pane). fn keep_for_undo(app: &RustGisApp, ctx: &egui::Context, box_id: egui::Id) { + keep_for_undo_of(ctx, box_id, &app.workflow.script); +} + +/// [`keep_for_undo`] for the script `script` (what the find bar replaces in). +pub(crate) fn keep_for_undo_of(ctx: &egui::Context, box_id: egui::Id, script: &str) { use egui::text::{CCursor, CCursorRange}; let mut state = egui::widgets::text_edit::TextEditState::load(ctx, box_id).unwrap_or_default(); let mut undoer = state.undoer(); - let end = CCursorRange::one(CCursor::new(app.workflow.script.chars().count())); - undoer.add_undo(&(state.cursor.char_range().unwrap_or(end), app.workflow.script.clone())); + let end = CCursorRange::one(CCursor::new(script.chars().count())); + undoer.add_undo(&(state.cursor.char_range().unwrap_or(end), script.to_string())); state.set_undoer(undoer); state.cursor.set_char_range(Some(CCursorRange::one(CCursor::new(0)))); state.store(ctx, box_id); @@ -2277,8 +2282,11 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) { } // Braces, brackets and quotes closing themselves (#662): what the box does with the keys, // followed through after it. - let before = crate::completion::before(ui, box_id, &app.workflow.script); let stopped = stopped_at(app); + // The find bar (#2996), above the box: Ctrl+F opens it; a replace changes the script here. + let running = script_running(app); + let found = crate::scriptfind::prepare(ui, box_id, &app.workflow.script); + let before = crate::completion::before(ui, box_id, &app.workflow.script); let out = egui::ScrollArea::vertical().id_salt("script_box").max_height(room).auto_shrink([false, true]).show(ui, |ui| { let out = egui::TextEdit::multiline(&mut app.workflow.script) .id(box_id) @@ -2289,6 +2297,9 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) { .desired_width(f32::INFINITY) .hint_text("map.goToXY {\"lon\": 2.35, \"lat\": 48.85, \"scale\": 5000000}\nselect.byAttributes {\"layer\": \"Cities\", \"where\": \"pop_max > 1000000\"}") .show(ui); + if let Some(shown) = &found { + crate::scriptfind::paint(ui, &out, shown); + } // Asked by a click on the error, taken every frame: one that doesn't show the stop (a key // typed) drops it, rather than leaving it for a later stop. let go = ui.data_mut(|d| d.remove_temp::(box_id.with("go_to_stopped"))).is_some(); @@ -2298,7 +2309,7 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) { // Once, inside this scroll, which takes it as it ends. The box scrolls to its cursor // only when the cursor moves within it. if go { - let origin = (out.galley_pos - vec2(out.galley.rect.left(), 0.0)).to_vec2(); + let origin = crate::widgets::text_origin(&out); let cursor = out.galley.pos_from_cursor(stopped_cursor(at.index)).translate(origin); ui.scroll_to_rect(cursor, Some(egui::Align::Center)); } @@ -2314,6 +2325,9 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) { } else { crate::scriptcomplete::braces(ui, before, &out.inner, &mut app.workflow.script); } + // Over the box's top right, once it is laid out; a replace it makes comes after the box's own + // keys, so it is not read as what a key did. + crate::scriptfind::show(ui, box_id, &mut app.workflow.script, running, out.inner_rect); // Where the box's cursor is (#2831), focused or not, on the right of a row of its own: the // row of buttons has no room for it in a narrow pane. The row is there before the box has a // cursor too, so nothing below moves when it gets one. Read from the box's state as it is @@ -2447,7 +2461,7 @@ fn line_col(script: &str, index: usize) -> (usize, usize) { /// paints its own background over anything drawn before it. fn paint_stopped(ui: &Ui, out: &egui::text_edit::TextEditOutput, at: StoppedAt) { let galley = &out.galley; - let origin = (out.galley_pos - vec2(galley.rect.left(), 0.0)).to_vec2(); + let origin = crate::widgets::text_origin(out); let clip = out.text_clip_rect; let painter = ui.painter().with_clip_rect(clip.intersect(ui.clip_rect())); let mut line = 1; @@ -3195,6 +3209,262 @@ mod tests { assert_eq!(cursor(&h), before); } + /// Ctrl+F opens the find bar on the box's selection (#2996): it counts the matches, Enter and + /// Shift+Enter go round them, and Escape closes it with the cursor on the current one. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn ctrl_f_finds_in_the_script_and_escape_leaves_the_cursor_on_the_match() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + let script = "layer.rename {\"layer\": \"Cities\"}\nmap.zoomFull\n# Cities again"; + app.workflow.script = script.to_string(); + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(900.0, 800.0)) + .build_ui_state(|ui, app: &mut RustGisApp| script_pane(app, ui, &Tokens::light()), app); + h.run(); + let box_id = egui::Id::unique("script_text"); + let cursor = |h: &egui_kittest::Harness<'_, RustGisApp>| { + crate::widgets::cursor_range(&h.ctx, box_id).map(|r| (r.secondary.index.0, r.primary.index.0)) + }; + let first = script.find("Cities").unwrap(); + let second = script.rfind("Cities").unwrap(); + // Ctrl+F in the box with nothing selected: a bar with an empty field, and no count. + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + assert!(h.query_by_label("Close (Esc)").is_none(), "closed until asked"); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + h.get_by_label("Close (Esc)"); + h.event(Event::Text("cities".into())); + h.run(); + h.get_by_label("1 of 2"); + // Enter goes on, Shift+Enter back; both round. + h.key_press(Key::Enter); + h.run(); + h.get_by_label("2 of 2"); + h.key_press(Key::Enter); + h.run(); + h.get_by_label("1 of 2"); + h.key_press_modifiers(Modifiers::SHIFT, Key::Enter); + h.run(); + h.get_by_label("2 of 2"); + // Escape closes the bar, the box has the focus and the current match selected. + h.key_press(Key::Escape); + h.run(); + assert!(h.query_by_label("Close (Esc)").is_none(), "closed"); + assert_eq!(cursor(&h), Some((second, second + "Cities".len()))); + assert!(h.ctx.memory(|m| m.has_focus(box_id))); + assert_eq!(h.state().workflow.script, script, "finding changes nothing"); + // Opened on a selection, it looks for it, and the first match from there is current. + crate::widgets::set_cursor_range( + &h.ctx, + box_id, + egui::text::CCursorRange::two(egui::text::CCursor::new(first), egui::text::CCursor::new(first + 6)), + ); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + h.get_by_label("1 of 2"); + // Match Whole Word: "Citi" is in both places as a prefix, and in neither as a word. + h.event(Event::Text("Citi".into())); + h.run(); + h.get_by_label("1 of 2"); + h.get_by_label("Match Whole Word").click(); + h.run(); + h.get_by_label("No results"); + h.get_by_label("Match Whole Word").click(); + h.run(); + h.get_by_label("1 of 2"); + // Typing goes on in the field after a toggle was clicked ("Citix" is nowhere). + h.event(Event::Text("x".into())); + h.run(); + h.get_by_label("No results"); + h.key_press(Key::Backspace); + h.run(); + h.get_by_label("1 of 2"); + // Text typed in the box, with the bar open, ahead of the current match: the matches shift, + // so the current one is the first from the cursor, not the one that now holds its index. + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + crate::widgets::set_cursor_range(&h.ctx, box_id, egui::text::CCursorRange::one(egui::text::CCursor::new(0))); + h.event(Event::Text("cities cities ".into())); + h.run(); + h.get_by_label("3 of 4"); + } + + /// The editor shortcuts around the find bar (#2996): Ctrl+H opens it with the Replace row, F3 and + /// Shift+F3 go to the next and the previous match. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_find_shortcuts_of_a_code_editor_work_in_the_script_box() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + let script = "alpha\nbeta cities\ngamma\ncities delta\ncities"; + app.workflow.script = script.to_string(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + // The icons draw letters: the fonts first, as the other pane tests do. + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + script_pane(app, ui, &Tokens::light()); + }, + app, + ); + h.run(); + let box_id = egui::Id::unique("script_text"); + // Ctrl+H: the bar with its Replace row open. Typed text is the query, the first match from the cursor current; F3 and Shift+F3 step. + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::H); + h.run(); + h.get_by_label("Replace All"); + h.event(Event::Text("cities".into())); + h.run(); + h.get_by_label("1 of 3"); + // Three matches, so that backwards is not the same place as forwards: 1 → 2 → 1 → 3 (round). + h.key_press(Key::F3); + h.run(); + h.get_by_label("2 of 3"); + h.key_press_modifiers(Modifiers::SHIFT, Key::F3); + h.run(); + h.get_by_label("1 of 3"); + h.key_press_modifiers(Modifiers::SHIFT, Key::F3); + h.run(); + h.get_by_label("3 of 3"); + // The same with Enter in the field, which has the focus again after the shortcuts. + h.ctx.memory_mut(|m| m.request_focus(box_id.with("find_query"))); + h.run(); + h.key_press(Key::Enter); + h.run(); + h.get_by_label("1 of 3"); + h.key_press_modifiers(Modifiers::SHIFT, Key::Enter); + h.run(); + h.get_by_label("3 of 3"); + h.key_press_modifiers(Modifiers::SHIFT, Key::Enter); + h.run(); + h.get_by_label("2 of 3"); + } + + /// Replace All changes every match as one step of the box's Undo, Replace the current one, and + /// neither while a run is under way (#2996). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn replacing_in_the_script_is_one_undo_step_and_waits_for_a_run() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = RustGisApp::with_sample(); + let script = "a Cities b\nCities c"; + app.workflow.script = script.to_string(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + // The icons draw letters: the fonts first, as the other pane tests do. + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + script_pane(app, ui, &Tokens::light()); + }, + app, + ); + h.run(); + let box_id = egui::Id::unique("script_text"); + let replace_id = box_id.with("find_replace"); + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + h.event(Event::Text("Cities".into())); + h.run(); + // The Replace row opens from the arrow at the bar's left. + h.get_by_label("Toggle Replace").click(); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(replace_id)); + h.run(); + h.event(Event::Text("Towns".into())); + h.run(); + // Waiting for a run: nothing to press. + let opened = h.state().session.opened; + h.state_mut().workflow.script_started.push_back(ScriptStart { + at: 0, + asked: web_time::Instant::now(), + opened, + script: script.into(), + }); + h.run(); + assert!(h.get_by_label("Replace All").accesskit_node().is_disabled()); + assert!(h.get_by_label("Replace (Enter)").accesskit_node().is_disabled()); + h.state_mut().workflow.script_started.clear(); + h.run(); + // The current match, the first; the cursor goes after it, the next is current. + h.get_by_label("Replace (Enter)").click(); + h.run(); + assert_eq!(h.state().workflow.script, "a Towns b\nCities c"); + h.get_by_label("1 of 1"); + // Undo brings it back, then Replace All does both and Undo brings both back. + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::Z); + h.run(); + assert_eq!(h.state().workflow.script, script, "one undo step"); + h.get_by_label("Replace All").click(); + h.run(); + assert_eq!(h.state().workflow.script, "a Towns b\nTowns c"); + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::Z); + h.run(); + assert_eq!(h.state().workflow.script, script, "Replace All is one undo step"); + } + + /// The highlight goes over every row of a script that wraps, and a find with nothing in it, a + /// query that is a letter and a script past the cap do no harm (#2996). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn finding_in_a_wrapped_long_script_holds() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::{NodeT, Queryable}; + let mut app = RustGisApp::with_sample(); + app.workflow.script = format!("# {}\n", "ab ".repeat(40)).repeat(600); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 600.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + // The icons draw letters: the fonts first, as the other pane tests do. + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + script_pane(app, ui, &Tokens::dark()); + }, + app, + ); + h.run(); + let box_id = egui::Id::unique("script_text"); + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + h.event(Event::Text("a".into())); + h.run(); + // More matches than the bar keeps: the count says so, and Replace All is off. + h.get_by_label("1 of 10000+"); + h.key_press(Key::Enter); + h.run(); + h.get_by_label("2 of 10000+"); + h.get_by_label("Toggle Replace").click(); + h.run(); + assert!(h.get_by_label("Replace All").accesskit_node().is_disabled()); + h.key_press(Key::Escape); + h.run(); + } + /// A stop's column at the start of a wrapped row belongs to that row, not to the end of the one /// above (#2940): the cursor [`stopped_cursor`] makes lands on the second row, where a plain /// one lands on the first, and a column inside a row is the same either way. diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 76d9d470fa..fa590268e9 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -878,6 +878,25 @@ pub fn paint(painter: &Painter, r: Rect, name: &str, ink: Color32, accent: Color p.line(&[(12.0, 8.0), (12.0, 15.0)], 1.8, p.acc); p.line(&[(9.2, 12.4), (12.0, 15.2), (14.8, 12.4)], 1.8, p.acc); } + "replace" | "replace_all" => { + // The word and what takes its place: the old one as a bare letter, the new one in a box of the + // accent, as the other icons draw a thing (a box, its outline), and the action in green, as Export and Add + // draw theirs. The arrow alone for Replace (this match), with an asterisk for Replace All. + // Regular weight, not the semibold the other icons' letters take: it is the plain word. + painter.text(p.pt(6.0, 5.5), egui::Align2::CENTER_CENTER, "a", egui::FontId::proportional(14.0 * p.s()), ink); + if name == "replace_all" { + // An asterisk in the free corner: every match, as a code editor's pattern marks it. + for deg in [90.0_f32, 30.0, 150.0] { + let (s, c) = deg.to_radians().sin_cos(); + p.line(&[(19.0 - 3.4 * c, 6.0 - 3.4 * s), (19.0 + 3.4 * c, 6.0 + 3.4 * s)], 1.7, green); + } + } + p.rect(9.5, 11.5, 14.0, 11.0, Some(accent), Some((1.3, ink)), 1.5); + p.text(16.5, 17.0, "b", 10.0, Color32::WHITE); + // From the old word down and over to the new one. + p.line(&[(6.0, 10.0), (6.0, 17.0), (7.2, 17.0)], 1.7, green); + p.fill(&[(6.8, 15.0), (9.3, 17.0), (6.8, 19.0)], green); + } "up" => p.line(&[(6.0, 15.0), (12.0, 9.0), (18.0, 15.0)], 1.8, ink), "down" => p.line(&[(6.0, 9.0), (12.0, 15.0), (18.0, 9.0)], 1.8, ink), "logo" => { @@ -1398,6 +1417,8 @@ pub const ALL: &[&str] = &[ "run", "up", "down", + "replace", + "replace_all", "logo", "point_layer", "line_layer", diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index b5f8fa0d35..4be011196b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -113,6 +113,7 @@ mod s3ui; mod saveprompt; mod scriptcolor; mod scriptcomplete; +mod scriptfind; mod searchbox; mod serviceui; mod sessionlog; diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs new file mode 100644 index 0000000000..d7a3879e80 --- /dev/null +++ b/crates/ui-egui/src/scriptfind.rs @@ -0,0 +1,641 @@ +//! Find and replace in the Script pane (#2996): what the find bar looks for in the script, and the +//! text a replace leaves. Positions are characters, as the box's cursor counts them. The matching +//! is plain text (no patterns), and worked out apart from the box so it is tested on its own. + +use std::ops::Range; + +/// The most matches kept: a script this long with this many hits is not read by eye, and the +/// highlight is laid out each time the text changes. +pub const MAX_MATCHES: usize = 10_000; + +/// Where `query` is in a script. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Found { + /// Each match, in characters, in order and apart from each other. + pub ranges: Vec>, + /// More than [`MAX_MATCHES`] hits: the rest are not kept. + pub capped: bool, +} + +/// Every place `query` is in `text`, from the start, a match taken before the next is looked for +/// (so `aa` is twice in `aaaa`). `case`: capitals count; otherwise a letter is its lower case. +/// `whole`: only a match with no letter, digit or `_` against it on either side (a whole word, as a +/// code editor's Match Whole Word takes it). An empty query is nowhere. +pub fn matches(text: &str, query: &str, case: bool, whole: bool) -> Found { + // A letter whose lower case is several characters (`İ`) stays as it is, so it matches only + // itself and the positions stay the text's. + let fold = |c: char| { + let mut lower = c.to_lowercase(); + match (lower.next(), lower.next()) { + (Some(l), None) if !case => l, + _ => c, + } + }; + let text: Vec = text.chars().map(fold).collect(); + let query: Vec = query.chars().map(fold).collect(); + let mut found = Found::default(); + if query.is_empty() { + return found; + } + let mut i = 0; + while i + query.len() <= text.len() { + let word = |c: Option<&char>| c.is_some_and(|c| c.is_alphanumeric() || *c == '_'); + let apart = !whole || (!word(i.checked_sub(1).and_then(|b| text.get(b))) && !word(text.get(i + query.len()))); + if apart && text.get(i..i + query.len()) == Some(&query[..]) { + if found.ranges.len() == MAX_MATCHES { + found.capped = true; + break; + } + found.ranges.push(i..i + query.len()); + i += query.len(); + } else { + i += 1; + } + } + found +} + +/// The match after (or, `back`, before) `current` of `len`, going round at the ends; the first +/// (the last, `back`) when none is current. None when there are no matches. +pub fn step(len: usize, current: Option, back: bool) -> Option { + let last = len.checked_sub(1)?; + Some(match (current, back) { + (None, false) => 0, + (None, true) => last, + (Some(c), false) => { + if c.min(last) == last { + 0 + } else { + c + 1 + } + } + (Some(c), true) => { + if c.min(last) == 0 { + last + } else { + c.min(last) - 1 + } + } + }) +} + +/// The index of the first match at or after the character `from`, else the first (it goes round). +pub fn first_from(found: &Found, from: usize) -> Option { + let at = found.ranges.iter().position(|r| r.start >= from); + at.or(if found.ranges.is_empty() { None } else { Some(0) }) +} + +/// `text` with the characters in `range` replaced by `with`. +pub fn replace_one(text: &str, range: Range, with: &str) -> String { + let n = text.chars().count(); + let (start, end) = (range.start.min(n), range.end.min(n)); + let end = end.max(start); + text.chars().take(start).chain(with.chars()).chain(text.chars().skip(end)).collect() +} + +/// `text` with every match of `found` replaced by `with`. +pub fn replace_all(text: &str, found: &Found, with: &str) -> String { + let mut out = String::with_capacity(text.len()); + let mut chars = text.chars(); + let mut at = 0; + for r in &found.ranges { + out.extend(chars.by_ref().take(r.start.saturating_sub(at))); + out.push_str(with); + // The matched characters are skipped. + chars.by_ref().take(r.end.saturating_sub(r.start)).for_each(drop); + at = r.end.max(r.start); + } + out.extend(chars); + out +} + +/// The find bar's state, kept in the context under the box's id: it isn't saved with the project. +#[derive(Clone, Default)] +struct Bar { + open: bool, + query: String, + replace: String, + case: bool, + /// Only whole words match. + whole: bool, + /// The match the next and previous go from, an index of `found`. + current: Option, + /// Where a new search starts picking its match: the cursor when the bar opened, the match last + /// stepped to, or the end of a replacement. + anchor: usize, + /// Pick the match at the anchor when the matches are next worked out. + reseek: bool, + /// Scroll the current match into view in the box's next frame. + scroll: bool, + /// Put the focus in the query field, its text selected. + focus_query: bool, + /// The Replace row is shown. + replace_open: bool, + found: std::sync::Arc, + /// What `found` was worked out for: the script's hash, the query and the case. + key: Option<(u64, String, bool, bool)>, +} + +impl Bar { + /// The matches again, if the script, the query or the case changed, and the current one picked. + /// `cursor`: the box's cursor, where a current match lost to an edit of the text is picked again. + fn refresh(&mut self, script: &str, cursor: usize) { + let key = (egui::util::hash(script), self.query.clone(), self.case, self.whole); + if self.key.as_ref() != Some(&key) { + self.found = std::sync::Arc::new(matches(script, &self.query, self.case, self.whole)); + self.key = Some(key); + if !self.reseek { + // The text changed under the bar (typed in the box): the matches shifted, so the + // current one is the first from the cursor, where the edit is. Not scrolled to. + self.current = first_from(&self.found, cursor); + } + } + if self.reseek { + self.current = first_from(&self.found, self.anchor); + self.scroll = self.current.is_some(); + self.reseek = false; + } + } + + /// The bar moved to the match `at` of the found ones. + fn go(&mut self, at: Option) { + self.current = at; + if let Some(r) = at.and_then(|i| self.found.ranges.get(i)) { + self.anchor = r.start; + self.scroll = true; + } + } +} + +/// What the box draws of the bar: the matches, the current one and whether to scroll to it. +pub struct Shown { + pub found: std::sync::Arc, + pub current: Option, + pub scroll: bool, +} + +enum Action { + Next, + Previous, + Replace, + ReplaceAll, + Close, +} + +/// The room the bar leaves at the box's edges, and the widths it takes: a button's side, what the +/// count takes, the toggle that shows Replace, and the least and most the bar is wide (a narrower +/// box has the bar as wide as it is). +const EDGE: f32 = 8.0; +const COUNT_WIDTH: f32 = 52.0; +const TOGGLE_WIDTH: f32 = 16.0; +const MIN_BAR: f32 = 230.0; +const MAX_BAR: f32 = 380.0; +const GAP: f32 = 4.0; + +/// The most characters of a selection that fill the query when the bar opens: a longer one is a +/// passage, not a word to look for. +const PREFILL_MAX: usize = 200; + +/// Before the box: Ctrl+F (⌘F) in the box or in the bar opens it, with the selection in its field; +/// the matches are worked out, and what the box has to draw of them is returned, None while the bar +/// is closed. The bar itself is drawn over the box once it has been laid out ([`show`]). +pub fn prepare(ui: &egui::Ui, box_id: egui::Id, script: &str) -> Option { + let id = box_id.with("find"); + let (query_id, replace_id) = (box_id.with("find_query"), box_id.with("find_replace")); + let mut bar: Bar = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); + let in_box = ui.memory(|m| m.has_focus(box_id)); + let in_bar = ui.memory(|m| m.has_focus(query_id) || m.has_focus(replace_id)); + // Ctrl+F (⌘F) opens the bar; Ctrl+H (⌥⌘F on a Mac, where ⌘H hides the app) opens it with the + // Replace row, as a code editor's do. + let find = (in_box || in_bar) && ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F)); + let replace = (in_box || in_bar) + && ui.input_mut(|i| { + i.consume_key(egui::Modifiers::COMMAND, egui::Key::H) + || i.consume_key(egui::Modifiers::COMMAND | egui::Modifiers::ALT, egui::Key::F) + }); + if find || replace { + if in_box && let Some(r) = crate::widgets::cursor_range(ui.ctx(), box_id) { + let (a, b) = (r.primary.index.0.min(r.secondary.index.0), r.primary.index.0.max(r.secondary.index.0)); + let picked: String = script.chars().skip(a).take(b - a).collect(); + if !picked.is_empty() && picked.chars().count() <= PREFILL_MAX && !picked.contains(['\n', '\r']) { + bar.query = picked; + } + bar.anchor = a; + } + bar.open = true; + bar.replace_open |= replace; + bar.reseek = true; + bar.focus_query = true; + } + if !bar.open { + ui.data_mut(|d| d.insert_temp(id, bar)); + return None; + } + let cursor = crate::widgets::cursor_range(ui.ctx(), box_id).map_or(bar.anchor, |r| r.primary.index.0); + bar.refresh(script, cursor); + // F3 and Shift+F3, as in a code editor: the next and the previous match, with the focus where it was. + // Shift first: a pattern without Shift may take a press that has it. + if (in_box || in_bar) && ui.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::F3)) { + bar.go(step(bar.found.ranges.len(), bar.current, true)); + } else if (in_box || in_bar) && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::F3)) { + bar.go(step(bar.found.ranges.len(), bar.current, false)); + } + let shown = Shown { found: bar.found.clone(), current: bar.current, scroll: std::mem::take(&mut bar.scroll) }; + ui.data_mut(|d| d.insert_temp(id, bar)); + Some(shown) +} + +/// The toggles inside the right end of the query field `input`, as in a code editor: Match Case +/// (`Aa`) and Match Whole Word (`ab` under a bracket). Each is `on` or off; the one clicked is +/// returned. +fn field_toggles(ui: &mut egui::Ui, id: egui::Id, input: egui::Rect, case: bool, whole: bool) -> Option { + let t = crate::theme::Tokens::get(ui.ctx()); + let mut clicked = None; + let toggles = [(Toggle::Word, whole, tl!("Match Whole Word")), (Toggle::Case, case, tl!("Match Case"))]; + for (k, (toggle, on, label)) in toggles.into_iter().enumerate() { + let r = + egui::Rect::from_min_size(egui::pos2(input.right() - 26.0 - 24.0 * k as f32, input.center().y - 9.0), egui::vec2(22.0, 18.0)); + let resp = ui.interact(r, id.with(k), egui::Sense::click()); + if on { + ui.painter().rect_filled(r, egui::CornerRadius::same(3), t.accent.gamma_multiply(0.3)); + ui.painter().rect_stroke(r, egui::CornerRadius::same(3), egui::Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); + } else if resp.hovered() { + ui.painter().rect_filled(r, egui::CornerRadius::same(3), t.hover); + } + let ink = if on { t.text } else { t.text_dim }; + let c = r.center(); + match toggle { + Toggle::Case => { + ui.painter().text(c, egui::Align2::CENTER_CENTER, "Aa", egui::FontId::proportional(12.0), ink); + } + Toggle::Word => { + ui.painter().text(c - egui::vec2(0.0, 1.5), egui::Align2::CENTER_CENTER, "ab", egui::FontId::proportional(11.0), ink); + // A bracket under the word, as a code editor draws it. + let (y, stroke) = (c.y + 6.0, egui::Stroke::new(1.2, ink)); + let (l, rr) = (c.x - 7.0, c.x + 7.0); + ui.painter().line_segment([egui::pos2(l, y - 2.5), egui::pos2(l, y)], stroke); + ui.painter().line_segment([egui::pos2(l, y), egui::pos2(rr, y)], stroke); + ui.painter().line_segment([egui::pos2(rr, y), egui::pos2(rr, y - 2.5)], stroke); + } + } + resp.widget_info(|| egui::WidgetInfo::selected(egui::Role::CheckBox, true, on, label.to_string())); + if resp.on_hover_text(label).clicked() { + clicked = Some(toggle); + } + } + clicked +} + +/// A toggle inside the query field. +#[derive(Clone, Copy)] +enum Toggle { + Case, + Word, +} + +/// The find bar, drawn over the top right of the box (`area`, as laid out), as in a code editor: a +/// field with Match case inside it, the count and the previous, next and close buttons; and, +/// under the arrow at its left, a field for what to replace with and the Replace and Replace All +/// buttons. Does what it's asked: a replace changes `script` as one undo step of the box, which +/// `running` forbids. +pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: bool, area: egui::Rect) { + use egui::text::{CCursor, CCursorRange}; + let id = box_id.with("find"); + let (query_id, replace_id) = (box_id.with("find_query"), box_id.with("find_replace")); + let mut bar: Bar = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); + if !bar.open { + return; + } + let total = bar.found.ranges.len(); + let capped = bar.found.capped; + let width = (area.width() - 2.0 * EDGE).clamp(MIN_BAR, MAX_BAR); + let pos = egui::pos2((area.right() - EDGE - width).max(area.left()), area.top() + EDGE); + // The popup's own margin (`Frame::popup`) and its stroke. + let margin = 6.0; + let field = width - 2.0 * margin - 2.0 - TOGGLE_WIDTH - COUNT_WIDTH - 3.0 * crate::widgets::FLAT_BUTTON - 5.0 * GAP; + let mut todo = None; + crate::completion::popup(ui, box_id.with("find_area"), pos, area.height(), |ui| { + ui.set_width(width - 2.0 * margin - 2.0); + ui.spacing_mut().item_spacing = egui::vec2(GAP, GAP); + ui.horizontal_top(|ui| { + // The arrow that shows or hides the Replace row, as tall as the rows it covers. + let tall = if bar.replace_open { 2.0 * crate::widgets::FLAT_BUTTON + GAP } else { crate::widgets::FLAT_BUTTON }; + let (r, toggle) = ui.allocate_exact_size(egui::vec2(TOGGLE_WIDTH, tall), egui::Sense::click()); + let t = crate::theme::Tokens::get(ui.ctx()); + if toggle.hovered() { + ui.painter().rect_filled(r, egui::CornerRadius::same(3), t.hover); + } + let icon = if bar.replace_open { "chevron_down" } else { "chevron_right" }; + let box_ = + egui::Rect::from_center_size(r.center_top() + egui::vec2(0.0, crate::widgets::FLAT_BUTTON / 2.0), egui::vec2(14.0, 14.0)); + crate::icons::paint(ui.painter(), box_, icon, t.text, t.accent); + toggle.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, bar.replace_open, tl!("Toggle Replace"))); + if toggle.on_hover_text(tl!("Toggle Replace")).clicked() { + bar.replace_open = !bar.replace_open; + } + ui.vertical(|ui| { + ui.horizontal(|ui| { + let query = ui.add( + egui::TextEdit::singleline(&mut bar.query) + .id(query_id) + .desired_width(field) + .margin(egui::Margin { left: 6, right: 54, top: 3, bottom: 3 }) + .hint_text(tl!("Find")), + ); + let toggled = field_toggles(ui, query_id.with("toggle"), query.rect, bar.case, bar.whole); + match toggled { + Some(Toggle::Case) => bar.case = !bar.case, + Some(Toggle::Word) => bar.whole = !bar.whole, + None => {} + } + bar.reseek |= toggled.is_some(); + if toggled.is_some() { + // As in a code editor, typing goes on in the field. + ui.memory_mut(|m| m.request_focus(query_id)); + } + if std::mem::take(&mut bar.focus_query) { + ui.memory_mut(|m| m.request_focus(query_id)); + let end = CCursor::new(bar.query.chars().count()); + crate::widgets::set_cursor_range(ui.ctx(), query_id, CCursorRange::two(CCursor::new(0), end)); + } + if query.changed() { + bar.reseek = true; + } + let shift = ui.input(|i| i.modifiers.shift); + if query.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + // A one-line box lets go of the focus on Enter: keep it for the next. + ui.memory_mut(|m| m.request_focus(query_id)); + todo = Some(if shift { Action::Previous } else { Action::Next }); + } + let place = match (bar.query.is_empty(), bar.current) { + (true, _) => String::new(), + (false, _) if total == 0 => tl!("No results").to_string(), + (false, current) => { + let (n, all) = (current.map_or(0, |c| c + 1).to_string(), format!("{total}{}", if capped { "+" } else { "" })); + crate::i18n::fmt("{n} of {all}", &[("n", &n), ("all", &all)]) + } + }; + ui.add_sized( + [COUNT_WIDTH, crate::widgets::FLAT_BUTTON], + egui::Label::new(egui::RichText::new(place).small().weak()).truncate(), + ); + let (prev, next) = (tl!("Previous match (Shift+Enter)").to_string(), tl!("Next match (Enter)").to_string()); + if crate::widgets::flat_icon_button(ui, "up", &prev, &prev, total > 0).clicked() { + todo = Some(Action::Previous); + } + if crate::widgets::flat_icon_button(ui, "down", &next, &next, total > 0).clicked() { + todo = Some(Action::Next); + } + let close = tl!("Close (Esc)").to_string(); + if crate::widgets::flat_icon_button(ui, "close", &close, &close, true).clicked() { + todo = Some(Action::Close); + } + // Escape in either field closes the bar (the field gives the focus up on it). + let escaped = ui.input(|i| i.key_pressed(egui::Key::Escape)); + if escaped && (query.has_focus() || query.lost_focus() || ui.memory(|m| m.has_focus(replace_id))) { + todo = Some(Action::Close); + } + }); + if bar.replace_open { + ui.horizontal(|ui| { + let replace = ui.add( + egui::TextEdit::singleline(&mut bar.replace) + .id(replace_id) + .desired_width(field) + .margin(egui::Margin { left: 6, right: 6, top: 3, bottom: 3 }) + .hint_text(tl!("Replace")), + ); + // Under the count, the Replace buttons: one match, and all of them. + ui.add_space(COUNT_WIDTH + GAP); + let can = !running && bar.current.is_some(); + let wait = tl!("Wait for the run to finish").to_string(); + let (one_say, all_say) = (tl!("Replace (Enter)").to_string(), tl!("Replace All").to_string()); + let one_hover = if running { &wait } else { &one_say }; + let all_hover = if running { + wait.clone() + } else if capped { + crate::i18n::fmt("Too many matches to replace at once (more than {n})", &[("n", &MAX_MATCHES.to_string())]) + } else { + tl!("Replace every match (one step of Undo)").to_string() + }; + if crate::widgets::flat_icon_button(ui, "replace", &one_say, one_hover, can).clicked() { + todo = Some(Action::Replace); + } else if replace.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) && can { + // A one-line box lets go of the focus on Enter: keep it, for the next replace. + ui.memory_mut(|m| m.request_focus(replace_id)); + todo = Some(Action::Replace); + } + if crate::widgets::flat_icon_button(ui, "replace_all", &all_say, &all_hover, !running && total > 0 && !capped) + .clicked() + { + todo = Some(Action::ReplaceAll); + } + if (replace.has_focus() || replace.lost_focus()) && ui.input(|i| i.key_pressed(egui::Key::Escape)) { + todo = Some(Action::Close); + } + }); + } + }); + }); + }); + let found = bar.found.clone(); + // What was found is of the script as it was when the matches were worked out: a key typed in the + // box since, in this frame, leaves them for the next. + let current_text = bar.key.as_ref().is_some_and(|k| k.0 == egui::util::hash(&*script)); + match todo { + Some(Action::Next) => bar.go(step(total, bar.current, false)), + Some(Action::Previous) => bar.go(step(total, bar.current, true)), + Some(Action::Replace) if current_text => { + if let Some(r) = bar.current.and_then(|i| found.ranges.get(i)).filter(|_| !running) { + crate::analysispane::keep_for_undo_of(ui.ctx(), box_id, script); + *script = replace_one(script, r.clone(), &bar.replace); + let after = r.start + bar.replace.chars().count(); + crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::one(CCursor::new(after))); + bar.anchor = after; + bar.reseek = true; + } + } + Some(Action::ReplaceAll) if current_text => { + if !running && !found.capped && !found.ranges.is_empty() { + crate::analysispane::keep_for_undo_of(ui.ctx(), box_id, script); + *script = replace_all(script, &found, &bar.replace); + crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::one(CCursor::new(0))); + bar.anchor = 0; + bar.reseek = true; + } + } + Some(Action::Close) => { + bar.open = false; + // What it found goes with it (up to 10,000 ranges), and is worked out again on opening. + bar.found = Default::default(); + bar.key = None; + // The cursor where the search was: the current match, selected, in the box. + if let Some(r) = bar.current.and_then(|i| found.ranges.get(i)) { + crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::two(CCursor::new(r.start), CCursor::new(r.end))); + } + ui.memory_mut(|m| m.request_focus(box_id)); + } + _ => {} + } + if todo.is_some() || bar.reseek || !current_text { + // What was asked, or a key typed in the box this frame, shows in the box on the next frame. + ui.ctx().request_repaint(); + } + ui.data_mut(|d| d.insert_temp(id, bar)); +} + +/// The fill of a match, and of the current one: amber over the text, translucent, as the stop's +/// mark is, the current one stronger and outlined too, so it isn't told by its colour alone. +const MATCH: egui::Color32 = egui::Color32::from_rgba_premultiplied(90, 70, 0, 90); +const CURRENT: egui::Color32 = egui::Color32::from_rgba_premultiplied(160, 80, 0, 170); + +/// Paints the matches over the rows of the laid-out box that show, and, for `scroll`, brings the +/// current one into view in the enclosing scroll. +pub fn paint(ui: &egui::Ui, out: &egui::text_edit::TextEditOutput, shown: &Shown) { + use egui::text::{CCursor, CharIndex}; + let galley = &out.galley; + let origin = crate::widgets::text_origin(out); + let painter = ui.painter().with_clip_rect(out.text_clip_rect.intersect(ui.clip_rect())); + let seen = painter.clip_rect(); + let ranges = &shown.found.ranges; + let mut start = 0; + for row in &galley.rows { + let shown_chars = row.glyphs.len(); + let y = row.rect().translate(origin).y_range(); + if y.max >= seen.top() && y.min <= seen.bottom() { + // The first match that doesn't end before this row, then each one that starts in it. + let first = ranges.partition_point(|r| r.end <= start); + for (i, r) in ranges.iter().enumerate().skip(first).take_while(|(_, r)| r.start < start + shown_chars) { + let (a, b) = (r.start.max(start) - start, r.end.min(start + shown_chars) - start); + let x = |c: usize| row.pos.x + row.x_offset(CharIndex(c)) + origin.x; + let rect = egui::Rect::from_x_y_ranges(x(a)..=x(b), y); + if shown.current == Some(i) { + painter.rect_filled(rect, 2.0, CURRENT); + painter.rect_stroke(rect, 2.0, egui::Stroke::new(1.0, CURRENT), egui::StrokeKind::Outside); + } else { + painter.rect_filled(rect, 2.0, MATCH); + } + } + } + start += row.char_count_including_newline().0; + } + if shown.scroll + && let Some(r) = shown.current.and_then(|i| ranges.get(i)) + { + let at = egui::text::CCursor { prefer_next_row: true, ..CCursor::new(r.start) }; + ui.scroll_to_rect(galley.pos_from_cursor(at).translate(origin), Some(egui::Align::Center)); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn at(text: &str, query: &str, case: bool) -> Vec<(usize, usize)> { + matches(text, query, case, false).ranges.into_iter().map(|r| (r.start, r.end)).collect() + } + + #[test] + fn an_empty_query_is_nowhere() { + assert_eq!(at("abc", "", true), []); + assert_eq!(at("", "a", true), []); + } + + #[test] + fn matches_come_in_order_and_do_not_overlap() { + assert_eq!(at("map.zoomFull\nmap.zoomIn", "map.", true), [(0, 4), (13, 17)]); + assert_eq!(at("aaaa", "aa", true), [(0, 2), (2, 4)]); + } + + #[test] + fn case_counts_only_when_asked() { + assert_eq!(at("Cities cities CITIES", "cities", false), [(0, 6), (7, 13), (14, 20)]); + assert_eq!(at("Cities cities CITIES", "cities", true), [(7, 13)]); + } + + #[test] + fn a_whole_word_has_no_letter_digit_or_underscore_against_it() { + let whole = |text: &str, query: &str| -> Vec<(usize, usize)> { + matches(text, query, true, true).ranges.into_iter().map(|r| (r.start, r.end)).collect() + }; + // Punctuation, spaces and the ends of the text are boundaries; letters, digits and `_` are not. + assert_eq!(whole("city, (city) city_x xcity city2 city", "city"), [(0, 4), (7, 11), (32, 36)]); + // A word that is not ASCII, and a query that is not a word at all. + assert_eq!(whole("école écoles", "école"), [(0, 5)]); + assert_eq!(whole("a.b a.bc", "a.b"), [(0, 3)]); + // Without it, every one counts. + assert_eq!(matches("city cityx", "city", true, false).ranges.len(), 2); + // A refused place doesn't hide the next one inside it. + assert_eq!(whole("aaa a", "a"), [(4, 5)]); + } + + #[test] + fn positions_are_characters_not_bytes() { + // "é" is two bytes, one character; the match after it is at 3, not 4. + assert_eq!(at("é\"ab\"", "ab", true), [(2, 4)]); + assert_eq!(at("ÉCOLE école", "école", false), [(0, 5), (6, 11)]); + } + + #[test] + fn a_letter_whose_lower_case_is_longer_keeps_the_positions() { + // "İ" lower-cases to two characters; folding must not shift what comes after it. + assert_eq!(at("İx x", "x", false), [(1, 2), (3, 4)]); + // And it is not an `i`: it matches itself only. + assert_eq!(at("İ i", "i", false), [(2, 3)]); + assert_eq!(at("İ i", "İ", false), [(0, 1)]); + } + + #[test] + fn only_the_first_matches_are_kept() { + let text = "a".repeat(MAX_MATCHES + 5); + let found = matches(&text, "a", true, false); + assert_eq!(found.ranges.len(), MAX_MATCHES); + assert!(found.capped); + assert!(!matches("aaa", "a", true, false).capped); + } + + #[test] + fn stepping_goes_round() { + assert_eq!(step(0, None, false), None); + assert_eq!(step(3, None, false), Some(0)); + assert_eq!(step(3, None, true), Some(2)); + assert_eq!(step(3, Some(2), false), Some(0)); + assert_eq!(step(3, Some(0), true), Some(2)); + assert_eq!(step(3, Some(1), false), Some(2)); + assert_eq!(step(3, Some(1), true), Some(0)); + // A current one past the end (the text got shorter) is taken as the last. + assert_eq!(step(2, Some(9), false), Some(0)); + } + + #[test] + fn the_first_match_from_a_cursor() { + let found = matches("ab ab ab", "ab", true, false); + assert_eq!(first_from(&found, 0), Some(0)); + assert_eq!(first_from(&found, 1), Some(1)); + assert_eq!(first_from(&found, 6), Some(2)); + // Past the last: round to the first. + assert_eq!(first_from(&found, 7), Some(0)); + assert_eq!(first_from(&matches("x", "y", true, false), 0), None); + } + + #[test] + fn a_replace_leaves_the_rest_alone() { + assert_eq!(replace_one("a Cities b", 2..8, "Towns"), "a Towns b"); + assert_eq!(replace_one("é Cities", 2..8, "Ü"), "é Ü"); + // An empty range is an insertion. + assert_eq!(replace_one("abc", 1..1, "X"), "aXbc"); + // A range past the end is cut to it, not a panic. + assert_eq!(replace_one("abc", 2..9, "X"), "abX"); + assert_eq!(replace_one("abc", 7..9, "X"), "abcX"); + } + + #[test] + fn replace_all_takes_every_match_and_not_what_it_adds() { + let text = "Cities, Cities\nCities"; + let found = matches(text, "Cities", true, false); + assert_eq!(replace_all(text, &found, "Cities2"), "Cities2, Cities2\nCities2"); + assert_eq!(replace_all(text, &found, ""), ", \n"); + assert_eq!(replace_all("é a é", &matches("é a é", "é", true, false), "ee"), "ee a ee"); + assert_eq!(replace_all("abc", &Found::default(), "X"), "abc"); + } +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 56c5db9efe..651de369ba 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -152,6 +152,31 @@ pub(crate) fn set_cursor_range(ctx: &egui::Context, id: egui::Id, range: egui::t state.store(ctx, id); } +/// Where a text box's laid-out text is drawn from: add its galley's own coordinates to this to get +/// screen ones (the Script box's marks and highlights are painted over its rows with it). +pub(crate) fn text_origin(out: &egui::text_edit::TextEditOutput) -> egui::Vec2 { + (out.galley_pos - egui::vec2(out.galley.rect.left(), 0.0)).to_vec2() +} + +/// A flat icon button for a code editor's own bars (find, and what comes next): `size` square, no +/// border, its icon drawn in code and a hover fill. `label` is what a screen +/// reader says; `hover` the tooltip. Off, it takes no click. +pub(crate) fn flat_icon_button(ui: &mut Ui, icon: &str, label: &str, hover: &str, enabled: bool) -> Response { + let t = Tokens::get(ui.ctx()); + let sense = if enabled { Sense::click() } else { Sense::hover() }; + let (r, resp) = ui.allocate_exact_size(vec2(FLAT_BUTTON, FLAT_BUTTON), sense); + if enabled && resp.hovered() { + ui.painter().rect_filled(r, CornerRadius::same(4), t.hover); + } + let ink = if enabled { t.text } else { t.text_dim.gamma_multiply(0.6) }; + icons::paint(ui.painter(), r.shrink(2.0), icon, ink, t.accent); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, enabled, label)); + resp.on_hover_text(hover) +} + +/// The side of a [`flat_icon_button`]. +pub(crate) const FLAT_BUTTON: f32 = 22.0; + pub fn text_w(ui: &Ui, s: &str, font: egui::FontId) -> f32 { ui.ctx().fonts_mut(|f| f.layout_no_wrap(s.to_string(), font, egui::Color32::WHITE).size().x) } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 39b726b1d5..1823dd78d3 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1895,6 +1895,19 @@ before the same one steps over it, as does a `"` typed before the quote that end Backspace in an empty `{}`, `[]` or `""` deletes both. The lists open in a quote that closed itself, and accepting keeps that quote. Pasting adds nothing. +Ctrl+F (⌘+F on macOS) in the Script box opens a find bar over the box's top right, as a code editor +does, with the selected text, if it is one line of up to 200 characters, in its field. Every match +is highlighted in the box, the current one stronger and outlined, and the bar says which it is (`3 +of 12`, or `No results`). Enter and Shift+Enter (or F3 and Shift+F3), or the up and down arrows, go +to the next and the previous match, round the ends, and scroll it into view. Two toggles inside the +field make capitals count (**Aa**) and match only whole words (**ab** under a bracket: no letter, +digit or `_` against the match); the search is plain text, without patterns. The arrow at the bar's +left (or Ctrl+H, ⌥⌘F on macOS) shows a second field, for what to replace with, and two buttons: +Replace changes the current match and Replace All every one, each as one step of the box's Undo +(Ctrl+Z); both are off while a run is under way, and Replace All is off too when there are more +matches than the bar keeps (10,000). Escape in its fields, or the close button, closes the bar and +leaves the current match selected in the box. + ## ModelBuilder
From 20872f825ede41ba122ecacfa785d10309db5166 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 09:50:21 -0500 Subject: [PATCH 02/23] fix(ui): Ctrl+F and Ctrl+H in the Script box leave AltGr alone (#2996) Ctrl+Alt is AltGr outside a Mac, and egui's Ctrl+F pattern also took AltGr+F, which types a letter on many layouts, as the find shortcut. The bar's shortcuts now ignore a press with Alt held, and Alt+Cmd+F opens the Replace row only on a Mac. --- crates/ui-egui/src/analysispane.rs | 7 +++++++ crates/ui-egui/src/scriptfind.rs | 14 +++++++++----- 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index cbe72a1180..afc269bd95 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3317,6 +3317,13 @@ mod tests { ); h.run(); let box_id = egui::Id::unique("script_text"); + // Ctrl+Alt+F is AltGr+F on many layouts, a letter to type, outside a Mac, where it is ⌥⌘F: it + // opens nothing (the key event has `command` set as a platform's has). + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + h.key_press_modifiers(Modifiers { ctrl: true, alt: true, command: true, ..Default::default() }, Key::F); + h.run(); + assert!(h.query_by_label("Close (Esc)").is_none(), "AltGr+F opens no bar"); // Ctrl+H: the bar with its Replace row open. Typed text is the query, the first match from the cursor current; F3 and Shift+F3 step. h.ctx.memory_mut(|m| m.request_focus(box_id)); h.run(); diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index d7a3879e80..c1691fc9af 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -206,12 +206,16 @@ pub fn prepare(ui: &egui::Ui, box_id: egui::Id, script: &str) -> Option { let in_box = ui.memory(|m| m.has_focus(box_id)); let in_bar = ui.memory(|m| m.has_focus(query_id) || m.has_focus(replace_id)); // Ctrl+F (⌘F) opens the bar; Ctrl+H (⌥⌘F on a Mac, where ⌘H hides the app) opens it with the - // Replace row, as a code editor's do. - let find = (in_box || in_bar) && ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F)); - let replace = (in_box || in_bar) + // Replace row, as a code editor's do. Not with Alt held, but on a Mac for ⌥⌘F: elsewhere + // Ctrl+Alt is AltGr, and AltGr+F types a letter on many layouts, which egui's Ctrl+F + // pattern would otherwise take as its own. + let (here, mac) = (in_box || in_bar, ui.ctx().os().is_mac()); + let alt = ui.input(|i| i.modifiers.alt); + let find = here && !alt && ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F)); + let replace = here && ui.input_mut(|i| { - i.consume_key(egui::Modifiers::COMMAND, egui::Key::H) - || i.consume_key(egui::Modifiers::COMMAND | egui::Modifiers::ALT, egui::Key::F) + (!alt && i.consume_key(egui::Modifiers::COMMAND, egui::Key::H)) + || (mac && alt && i.consume_key(egui::Modifiers::COMMAND | egui::Modifiers::ALT, egui::Key::F)) }); if find || replace { if in_box && let Some(r) = crate::widgets::cursor_range(ui.ctx(), box_id) { From 45d45e6b4c2a74d85da0e280ac91c3479c3dbcdf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 10:09:42 -0500 Subject: [PATCH 03/23] fix(ui): the Script find query has a length limit and Enter keeps the Replace field (#2996) The query field takes 200 characters at most, so a pasted one cannot make each change of the script cost its length times the script's. Enter in the Replace field keeps the focus when there is nothing to replace or a run is under way, and the Replace button says why it is off. --- crates/ui-egui/src/analysispane.rs | 31 ++++++++++++++++++++++++++++++ crates/ui-egui/src/scriptfind.rs | 31 +++++++++++++++++++++--------- docs/user-guide/analysis.md | 22 ++++++++++----------- 3 files changed, 64 insertions(+), 20 deletions(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index afc269bd95..cc6582ecc4 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3292,6 +3292,30 @@ mod tests { h.get_by_label("3 of 4"); } + /// The query has a length limit, so a pasted one cannot make each change of the script cost its + /// length times the script's (#2996): the field takes 200 characters and no more. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_find_query_is_limited_in_length() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.workflow.script = "a".repeat(400); + let mut h = egui_kittest::Harness::builder() + .with_size(vec2(900.0, 800.0)) + .build_ui_state(|ui, app: &mut RustGisApp| script_pane(app, ui, &Tokens::light()), app); + h.run(); + let box_id = egui::Id::unique("script_text"); + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + h.event(Event::Text("a".repeat(400))); + h.run(); + // 200 characters in a script of 400: two matches. All 400 would be one. + h.get_by_label("1 of 2"); + } + /// The editor shortcuts around the find bar (#2996): Ctrl+H opens it with the Replace row, F3 and /// Shift+F3 go to the next and the previous match. #[cfg(not(target_arch = "wasm32"))] @@ -3407,6 +3431,13 @@ mod tests { h.run(); assert!(h.get_by_label("Replace All").accesskit_node().is_disabled()); assert!(h.get_by_label("Replace (Enter)").accesskit_node().is_disabled()); + // Enter in the Replace field then does nothing, and keeps the focus there. + h.ctx.memory_mut(|m| m.request_focus(replace_id)); + h.run(); + h.key_press(Key::Enter); + h.run(); + assert!(h.ctx.memory(|m| m.has_focus(replace_id)), "the field keeps the focus"); + assert_eq!(h.state().workflow.script, script, "and nothing was replaced"); h.state_mut().workflow.script_started.clear(); h.run(); // The current match, the first; the cursor goes after it, the next is current. diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index c1691fc9af..1b7f67a781 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -192,9 +192,10 @@ const MIN_BAR: f32 = 230.0; const MAX_BAR: f32 = 380.0; const GAP: f32 = 4.0; -/// The most characters of a selection that fill the query when the bar opens: a longer one is a -/// passage, not a word to look for. -const PREFILL_MAX: usize = 200; +/// The most characters of a query: what the field takes, and so of a selection that fills it when +/// the bar opens (a longer one is a passage, not a word to look for). Each change of the script or +/// the query costs the script's length times the query's, on the UI thread. +const QUERY_MAX: usize = 200; /// Before the box: Ctrl+F (⌘F) in the box or in the bar opens it, with the selection in its field; /// the matches are worked out, and what the box has to draw of them is returned, None while the bar @@ -214,14 +215,14 @@ pub fn prepare(ui: &egui::Ui, box_id: egui::Id, script: &str) -> Option { let find = here && !alt && ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F)); let replace = here && ui.input_mut(|i| { - (!alt && i.consume_key(egui::Modifiers::COMMAND, egui::Key::H)) + (!alt && !mac && i.consume_key(egui::Modifiers::COMMAND, egui::Key::H)) || (mac && alt && i.consume_key(egui::Modifiers::COMMAND | egui::Modifiers::ALT, egui::Key::F)) }); if find || replace { if in_box && let Some(r) = crate::widgets::cursor_range(ui.ctx(), box_id) { let (a, b) = (r.primary.index.0.min(r.secondary.index.0), r.primary.index.0.max(r.secondary.index.0)); let picked: String = script.chars().skip(a).take(b - a).collect(); - if !picked.is_empty() && picked.chars().count() <= PREFILL_MAX && !picked.contains(['\n', '\r']) { + if !picked.is_empty() && picked.chars().count() <= QUERY_MAX && !picked.contains(['\n', '\r']) { bar.query = picked; } bar.anchor = a; @@ -343,6 +344,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b egui::TextEdit::singleline(&mut bar.query) .id(query_id) .desired_width(field) + .char_limit(QUERY_MAX) .margin(egui::Margin { left: 6, right: 54, top: 3, bottom: 3 }) .hint_text(tl!("Find")), ); @@ -414,7 +416,15 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b let can = !running && bar.current.is_some(); let wait = tl!("Wait for the run to finish").to_string(); let (one_say, all_say) = (tl!("Replace (Enter)").to_string(), tl!("Replace All").to_string()); - let one_hover = if running { &wait } else { &one_say }; + // Off, the hover says why: a run, or nothing to replace. + let nothing = tl!("Nothing to replace").to_string(); + let one_hover = if running { + &wait + } else if !can { + ¬hing + } else { + &one_say + }; let all_hover = if running { wait.clone() } else if capped { @@ -424,10 +434,13 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b }; if crate::widgets::flat_icon_button(ui, "replace", &one_say, one_hover, can).clicked() { todo = Some(Action::Replace); - } else if replace.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) && can { - // A one-line box lets go of the focus on Enter: keep it, for the next replace. + } else if replace.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { + // A one-line box lets go of the focus on Enter: keep it, for the next replace, + // which is made only when there is one to make. ui.memory_mut(|m| m.request_focus(replace_id)); - todo = Some(Action::Replace); + if can { + todo = Some(Action::Replace); + } } if crate::widgets::flat_icon_button(ui, "replace_all", &all_say, &all_hover, !running && total > 0 && !capped) .clicked() diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 1823dd78d3..26855f2f90 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1896,17 +1896,17 @@ Backspace in an empty `{}`, `[]` or `""` deletes both. The lists open in a quote itself, and accepting keeps that quote. Pasting adds nothing. Ctrl+F (⌘+F on macOS) in the Script box opens a find bar over the box's top right, as a code editor -does, with the selected text, if it is one line of up to 200 characters, in its field. Every match -is highlighted in the box, the current one stronger and outlined, and the bar says which it is (`3 -of 12`, or `No results`). Enter and Shift+Enter (or F3 and Shift+F3), or the up and down arrows, go -to the next and the previous match, round the ends, and scroll it into view. Two toggles inside the -field make capitals count (**Aa**) and match only whole words (**ab** under a bracket: no letter, -digit or `_` against the match); the search is plain text, without patterns. The arrow at the bar's -left (or Ctrl+H, ⌥⌘F on macOS) shows a second field, for what to replace with, and two buttons: -Replace changes the current match and Replace All every one, each as one step of the box's Undo -(Ctrl+Z); both are off while a run is under way, and Replace All is off too when there are more -matches than the bar keeps (10,000). Escape in its fields, or the close button, closes the bar and -leaves the current match selected in the box. +does, with the selected text, if it is one line of up to 200 characters (the most the field takes), +in its field. Every match is highlighted in the box, the current one stronger and outlined, and the +bar says which it is (`3 of 12`, or `No results`). Enter and Shift+Enter (or F3 and Shift+F3), or +the up and down arrows, go to the next and the previous match, round the ends, and scroll it into +view. Two toggles inside the field make capitals count (**Aa**) and match only whole words (**ab** +under a bracket: no letter, digit or `_` against the match); the search is plain text, without +patterns. The arrow at the bar's left (or Ctrl+H, ⌥⌘F on macOS) shows a second field, for what to +replace with, and two buttons: Replace changes the current match and Replace All every one, each as +one step of the box's Undo (Ctrl+Z); both are off while a run is under way, and Replace All is off +too when there are more matches than the bar keeps (10,000). Escape in its fields, or the close +button, closes the bar and leaves the current match selected in the box. ## ModelBuilder From cb6a3d2291d9f8ad3b8a79e77c6a1cc961328940 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 12:10:13 -0500 Subject: [PATCH 04/23] fix(ui): the Script find limits the replacement, guards the whole search and keeps its chords from the browser (#2996) The Replace field takes 200 characters at most, as the query does: Replace All writes it once per match. A replace is made only while the matches are those of the script, the query and the toggles as they are now. In the browser, Ctrl+F and Ctrl+H are kept from its Find and History while the Script box or the bar has the focus. Replace All says there is nothing to replace when it is off for that. --- apps/rustgis-web/src/web.rs | 16 ++++--- crates/ui-egui/src/analysispane.rs | 72 ++++++++++++++++++++++++++++-- crates/ui-egui/src/lib.rs | 7 +++ crates/ui-egui/src/scriptfind.rs | 56 ++++++++++++++++++++--- docs/user-guide/analysis.md | 2 +- 5 files changed, 136 insertions(+), 17 deletions(-) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index e0c7628e58..41c237b210 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -344,8 +344,9 @@ struct WebShell { embed: Option, /// The app's Ctrl (⌘) shortcuts, kept current for [`keep_app_shortcuts`]. taken: TakenKeys, - /// [`RustGisApp::shortcuts_fingerprint`] when `taken` was last filled. - taken_print: Option, + /// [`RustGisApp::shortcuts_fingerprint`] and the length of [`RustGisApp::script_find_keys`] + /// when `taken` was last filled. + taken_print: Option<(u64, usize)>, } /// The app's Ctrl (⌘) shortcuts as (Alt, Shift, key): [`RustGisApp::command_keys`], shared with @@ -482,12 +483,15 @@ impl eframe::App for WebShell { } self.app.logic(ctx); self.dirty.set(self.app.session.dirty()); - // The shortcuts can be changed in the app: the key listener follows, rebuilt only when - // the keymap changed. - let print = self.app.shortcuts_fingerprint(); + // The shortcuts can be changed in the app, and the Script box takes its find chords only + // while it has the focus: the key listener follows, rebuilt only when one of them changed. + let find = RustGisApp::script_find_keys(ctx); + let print = (self.app.shortcuts_fingerprint(), find.len()); if self.taken_print != Some(print) { self.taken_print = Some(print); - *self.taken.borrow_mut() = self.app.command_keys(); + let mut keys = self.app.command_keys(); + keys.extend_from_slice(find); + *self.taken.borrow_mut() = keys; } } diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index cc6582ecc4..daaba782ba 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3301,9 +3301,19 @@ mod tests { use egui_kittest::kittest::Queryable; let mut app = RustGisApp::with_sample(); app.workflow.script = "a".repeat(400); - let mut h = egui_kittest::Harness::builder() - .with_size(vec2(900.0, 800.0)) - .build_ui_state(|ui, app: &mut RustGisApp| script_pane(app, ui, &Tokens::light()), app); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + // The icons draw letters: the fonts first, as the other pane tests do. + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + script_pane(app, ui, &Tokens::light()); + }, + app, + ); h.run(); let box_id = egui::Id::unique("script_text"); h.ctx.memory_mut(|m| m.request_focus(box_id)); @@ -3314,6 +3324,62 @@ mod tests { h.run(); // 200 characters in a script of 400: two matches. All 400 would be one. h.get_by_label("1 of 2"); + // The Replace field takes no more either: Replace All writes it once per match, so a long + // paste would make the script the matches times its length. + h.get_by_label("Toggle Replace").click(); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(box_id.with("find_replace"))); + h.run(); + h.event(Event::Text("b".repeat(400))); + h.run(); + h.get_by_label("Replace All").click(); + h.run(); + assert_eq!(h.state().workflow.script, "b".repeat(400), "200 characters for each of the two matches"); + } + + /// In a browser the find shortcuts are kept from the browser's own (#2996): while the box or a + /// field of the bar has the focus, and no longer. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_find_chords_are_taken_from_the_browser_while_the_box_or_bar_has_the_focus() { + use egui::{Key, Modifiers}; + let mut app = RustGisApp::with_sample(); + app.workflow.script = "map.zoomFull".to_string(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + // The icons draw letters: the fonts first, as the other pane tests do. + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + script_pane(app, ui, &Tokens::light()); + }, + app, + ); + h.run(); + let box_id = egui::Id::unique("script_text"); + let taken = |h: &egui_kittest::Harness<'_, RustGisApp>, key: &str, code: &str| { + RustGisApp::takes_browser_key(crate::scriptfind::browser_keys(&h.ctx), key, code, true, false, false) + }; + assert!(!taken(&h, "f", "KeyF"), "the browser keeps them with the focus elsewhere"); + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + assert!(taken(&h, "f", "KeyF") && taken(&h, "h", "KeyH"), "taken in the box"); + assert!(!taken(&h, "d", "KeyD"), "and only these"); + // On a Mac ⌘H hides the app and the box doesn't take it: only ⌘F (⌥⌘F with it). + let os = h.ctx.os(); + h.ctx.set_os(egui::os::OperatingSystem::Mac); + assert!(taken(&h, "f", "KeyF") && !taken(&h, "h", "KeyH"), "⌘H is not ours"); + h.ctx.set_os(os); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + assert!(h.ctx.memory(|m| m.has_focus(box_id.with("find_query")))); + assert!(taken(&h, "f", "KeyF") && taken(&h, "h", "KeyH"), "and in the bar"); + h.ctx.memory_mut(|m| m.surrender_focus(box_id.with("find_query"))); + h.run(); + assert!(!taken(&h, "f", "KeyF"), "given back when the focus leaves"); } /// The editor shortcuts around the find bar (#2996): Ctrl+H opens it with the Replace row, F3 and diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 4be011196b..d73c694108 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1662,6 +1662,13 @@ impl RustGisApp { keys } + /// The Ctrl (⌘) chords the Script box and its find bar take while one of them has the focus, as + /// (Alt, Shift, key), none otherwise: with [`Self::command_keys`], what the web app keeps from + /// the browser's own shortcuts. + pub fn script_find_keys(ctx: &egui::Context) -> &'static [(bool, bool, egui::Key)] { + scriptfind::browser_keys(ctx) + } + /// The keyboard shortcuts of a command run without parameters, in the keymap's order, for a /// native menu to show (the macOS menu bar). pub fn shortcuts_of(&self, command: &str) -> Vec { diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 1b7f67a781..66f36e8151 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -157,6 +157,14 @@ impl Bar { } } + /// Whether `found` is what `script`, the query and the toggles say now. + fn is_current(&self, script: &str) -> bool { + let hash = egui::util::hash(script); + self.key + .as_ref() + .is_some_and(|(h, query, case, whole)| *h == hash && *query == self.query && *case == self.case && *whole == self.whole) + } + /// The bar moved to the match `at` of the found ones. fn go(&mut self, at: Option) { self.current = at; @@ -192,10 +200,11 @@ const MIN_BAR: f32 = 230.0; const MAX_BAR: f32 = 380.0; const GAP: f32 = 4.0; -/// The most characters of a query: what the field takes, and so of a selection that fills it when -/// the bar opens (a longer one is a passage, not a word to look for). Each change of the script or -/// the query costs the script's length times the query's, on the UI thread. -const QUERY_MAX: usize = 200; +/// The most characters of a query, and of a replacement: what each field takes, and so of a +/// selection that fills the query when the bar opens (a longer one is a passage, not a word to look +/// for). Each change of the script or the query costs the script's length times the query's, on the +/// UI thread, and Replace All writes the replacement once per match, up to [`MAX_MATCHES`]. +const FIELD_MAX: usize = 200; /// Before the box: Ctrl+F (⌘F) in the box or in the bar opens it, with the selection in its field; /// the matches are worked out, and what the box has to draw of them is returned, None while the bar @@ -222,7 +231,7 @@ pub fn prepare(ui: &egui::Ui, box_id: egui::Id, script: &str) -> Option { if in_box && let Some(r) = crate::widgets::cursor_range(ui.ctx(), box_id) { let (a, b) = (r.primary.index.0.min(r.secondary.index.0), r.primary.index.0.max(r.secondary.index.0)); let picked: String = script.chars().skip(a).take(b - a).collect(); - if !picked.is_empty() && picked.chars().count() <= QUERY_MAX && !picked.contains(['\n', '\r']) { + if !picked.is_empty() && picked.chars().count() <= FIELD_MAX && !picked.contains(['\n', '\r']) { bar.query = picked; } bar.anchor = a; @@ -344,7 +353,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b egui::TextEdit::singleline(&mut bar.query) .id(query_id) .desired_width(field) - .char_limit(QUERY_MAX) + .char_limit(FIELD_MAX) .margin(egui::Margin { left: 6, right: 54, top: 3, bottom: 3 }) .hint_text(tl!("Find")), ); @@ -408,6 +417,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b egui::TextEdit::singleline(&mut bar.replace) .id(replace_id) .desired_width(field) + .char_limit(FIELD_MAX) .margin(egui::Margin { left: 6, right: 6, top: 3, bottom: 3 }) .hint_text(tl!("Replace")), ); @@ -429,6 +439,8 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b wait.clone() } else if capped { crate::i18n::fmt("Too many matches to replace at once (more than {n})", &[("n", &MAX_MATCHES.to_string())]) + } else if total == 0 { + nothing.clone() } else { tl!("Replace every match (one step of Undo)").to_string() }; @@ -458,7 +470,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b let found = bar.found.clone(); // What was found is of the script as it was when the matches were worked out: a key typed in the // box since, in this frame, leaves them for the next. - let current_text = bar.key.as_ref().is_some_and(|k| k.0 == egui::util::hash(&*script)); + let current_text = bar.is_current(script); match todo { Some(Action::Next) => bar.go(step(total, bar.current, false)), Some(Action::Previous) => bar.go(step(total, bar.current, true)), @@ -501,6 +513,19 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b ui.data_mut(|d| d.insert_temp(id, bar)); } +/// The chords the Script box and its find bar take while one of them has the focus, as (Alt, Shift, +/// key) with Ctrl or ⌘ held, for the web app to keep from the browser's own Find and History. +pub fn browser_keys(ctx: &egui::Context) -> &'static [(bool, bool, egui::Key)] { + let box_id = egui::Id::unique("script_text"); + let ours = [box_id, box_id.with("find_query"), box_id.with("find_replace")]; + if ctx.memory(|m| m.focused()).is_some_and(|f| ours.contains(&f)) { + // On a Mac, ⌥⌘F (the Replace there) is a ⌘F with Alt more, and ⌘H isn't ours. + if ctx.os().is_mac() { &[(false, false, egui::Key::F)] } else { &[(false, false, egui::Key::F), (false, false, egui::Key::H)] } + } else { + &[] + } +} + /// The fill of a match, and of the current one: amber over the text, translucent, as the stop's /// mark is, the current one stronger and outlined too, so it isn't told by its colour alone. const MATCH: egui::Color32 = egui::Color32::from_rgba_premultiplied(90, 70, 0, 90); @@ -552,6 +577,23 @@ mod tests { matches(text, query, case, false).ranges.into_iter().map(|r| (r.start, r.end)).collect() } + #[test] + fn matches_of_another_script_query_or_toggle_are_not_current() { + let mut bar = Bar { query: "cat".into(), ..Bar::default() }; + bar.refresh("cat dog", 0); + assert!(bar.is_current("cat dog")); + assert!(!bar.is_current("cat dogs"), "the script changed"); + // Typed or toggled after the matches were worked out, in the same frame. + bar.query.push('s'); + assert!(!bar.is_current("cat dog"), "the query changed"); + bar.query.pop(); + bar.case = true; + assert!(!bar.is_current("cat dog"), "Match Case changed"); + bar.case = false; + bar.whole = true; + assert!(!bar.is_current("cat dog"), "Match Whole Word changed"); + } + #[test] fn an_empty_query_is_nowhere() { assert_eq!(at("abc", "", true), []); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 26855f2f90..a735c102c8 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1896,7 +1896,7 @@ Backspace in an empty `{}`, `[]` or `""` deletes both. The lists open in a quote itself, and accepting keeps that quote. Pasting adds nothing. Ctrl+F (⌘+F on macOS) in the Script box opens a find bar over the box's top right, as a code editor -does, with the selected text, if it is one line of up to 200 characters (the most the field takes), +does, with the selected text, if it is one line of up to 200 characters (the most each field takes), in its field. Every match is highlighted in the box, the current one stronger and outlined, and the bar says which it is (`3 of 12`, or `No results`). Enter and Shift+Enter (or F3 and Shift+F3), or the up and down arrows, go to the next and the previous match, round the ends, and scroll it into From bb51dc977b80fe9dea2e968ed8fa8da3a0fa17b4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 12:36:53 -0500 Subject: [PATCH 05/23] fix(web): the Script find chords leave Ctrl+Alt to the browser (#2996) The web key listener matched the find chords as it matches the keymap's, with any extra Alt, and so kept Ctrl+Alt+F and Ctrl+Alt+H from the browser although the Script box takes neither. They now need Alt as the chord says, with Alt+Cmd+F still taken on a Mac. --- apps/rustgis-web/src/web.rs | 15 ++++++++------- crates/ui-egui/src/analysispane.rs | 8 ++++++-- crates/ui-egui/src/lib.rs | 8 ++++++++ crates/ui-egui/src/scriptfind.rs | 8 ++++++-- 4 files changed, 28 insertions(+), 11 deletions(-) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 41c237b210..281ab02ddc 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -349,9 +349,9 @@ struct WebShell { taken_print: Option<(u64, usize)>, } -/// The app's Ctrl (⌘) shortcuts as (Alt, Shift, key): [`RustGisApp::command_keys`], shared with -/// the page's key listener. -type TakenKeys = Rc>>; +/// The app's Ctrl (⌘) shortcuts as (Alt, Shift, key), [`RustGisApp::command_keys`], and the Script +/// box's find chords, [`RustGisApp::script_find_keys`], shared with the page's key listener. +type TakenKeys = Rc, &'static [(bool, bool, egui::Key)])>>; /// The link to the page that embeds the app (`?embed`; see `embed.rs`). struct Embed { @@ -489,9 +489,7 @@ impl eframe::App for WebShell { let print = (self.app.shortcuts_fingerprint(), find.len()); if self.taken_print != Some(print) { self.taken_print = Some(print); - let mut keys = self.app.command_keys(); - keys.extend_from_slice(find); - *self.taken.borrow_mut() = keys; + *self.taken.borrow_mut() = (self.app.command_keys(), find); } } @@ -1506,7 +1504,10 @@ fn keep_app_shortcuts(taken: TakenKeys) -> Result<(), String> { // As eframe reads it, Ctrl or ⌘ is egui's command on every platform, so the app's // shortcut runs on either and the browser's is kept from both. let command = e.ctrl_key() || e.meta_key(); - if RustGisApp::takes_browser_key(&taken.borrow(), &e.key(), &e.code(), command, e.alt_key(), e.shift_key()) { + let (keys, find) = &*taken.borrow(); + if RustGisApp::takes_browser_key(keys, &e.key(), &e.code(), command, e.alt_key(), e.shift_key()) + || RustGisApp::takes_find_key(find, &e.key(), &e.code(), command, e.alt_key()) + { e.prevent_default(); } }); diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index daaba782ba..fe2403781d 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3360,18 +3360,22 @@ mod tests { ); h.run(); let box_id = egui::Id::unique("script_text"); - let taken = |h: &egui_kittest::Harness<'_, RustGisApp>, key: &str, code: &str| { - RustGisApp::takes_browser_key(crate::scriptfind::browser_keys(&h.ctx), key, code, true, false, false) + let pressed = |h: &egui_kittest::Harness<'_, RustGisApp>, key: &str, code: &str, alt: bool| { + RustGisApp::takes_find_key(crate::scriptfind::browser_keys(&h.ctx), key, code, true, alt) }; + let taken = |h: &egui_kittest::Harness<'_, RustGisApp>, key: &str, code: &str| pressed(h, key, code, false); assert!(!taken(&h, "f", "KeyF"), "the browser keeps them with the focus elsewhere"); h.ctx.memory_mut(|m| m.request_focus(box_id)); h.run(); assert!(taken(&h, "f", "KeyF") && taken(&h, "h", "KeyH"), "taken in the box"); assert!(!taken(&h, "d", "KeyD"), "and only these"); + // With Alt they are the browser's: the box takes neither. + assert!(!pressed(&h, "f", "KeyF", true) && !pressed(&h, "h", "KeyH", true), "Ctrl+Alt is not ours"); // On a Mac ⌘H hides the app and the box doesn't take it: only ⌘F (⌥⌘F with it). let os = h.ctx.os(); h.ctx.set_os(egui::os::OperatingSystem::Mac); assert!(taken(&h, "f", "KeyF") && !taken(&h, "h", "KeyH"), "⌘H is not ours"); + assert!(pressed(&h, "f", "KeyF", true), "⌥⌘F opens the Replace row"); h.ctx.set_os(os); h.key_press_modifiers(Modifiers::COMMAND, Key::F); h.run(); diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index d73c694108..c9558a170e 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1669,6 +1669,14 @@ impl RustGisApp { scriptfind::browser_keys(ctx) } + /// Whether a browser key press (its `key` and `code`, Ctrl or ⌘ held, Alt) is one of the find + /// chords [`Self::script_find_keys`] gives. Alt must be as the chord says, unlike + /// [`Self::takes_browser_key`]: the box takes no Ctrl+Alt+F or Ctrl+Alt+H, so the browser keeps + /// them. Shift is free, as egui matches these. + pub fn takes_find_key(keys: &[(bool, bool, egui::Key)], key: &str, code: &str, command: bool, alt: bool) -> bool { + command && keymap::browser_key(key, code).is_some_and(|k| keys.iter().any(|&(a, _, bound)| bound == k && a == alt)) + } + /// The keyboard shortcuts of a command run without parameters, in the keymap's order, for a /// native menu to show (the macOS menu bar). pub fn shortcuts_of(&self, command: &str) -> Vec { diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 66f36e8151..d81f318fee 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -519,8 +519,12 @@ pub fn browser_keys(ctx: &egui::Context) -> &'static [(bool, bool, egui::Key)] { let box_id = egui::Id::unique("script_text"); let ours = [box_id, box_id.with("find_query"), box_id.with("find_replace")]; if ctx.memory(|m| m.focused()).is_some_and(|f| ours.contains(&f)) { - // On a Mac, ⌥⌘F (the Replace there) is a ⌘F with Alt more, and ⌘H isn't ours. - if ctx.os().is_mac() { &[(false, false, egui::Key::F)] } else { &[(false, false, egui::Key::F), (false, false, egui::Key::H)] } + // On a Mac, ⌥⌘F is the Replace, and ⌘H isn't ours. + if ctx.os().is_mac() { + &[(false, false, egui::Key::F), (true, false, egui::Key::F)] + } else { + &[(false, false, egui::Key::F), (false, false, egui::Key::H)] + } } else { &[] } From f8cfa6b6d1a7357d447d6ed766495793230eca75 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 13:51:55 -0500 Subject: [PATCH 06/23] fix(web): refresh the Script find chords after the UI pass too (#2996) The key listener's shortcuts were refreshed only in logic, which runs before the UI pass. A focus moved into the Script box during that pass was seen one frame later, so a Ctrl+F pressed in between went to the browser. --- apps/rustgis-web/src/web.rs | 26 ++++++++++++++++++-------- 1 file changed, 18 insertions(+), 8 deletions(-) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 281ab02ddc..dc21d590fb 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -452,6 +452,20 @@ impl Embed { } } +impl WebShell { + /// Keeps the key listener's shortcuts current: the shortcuts can be changed in the app, and + /// the Script box takes its find chords only while it has the focus. Rebuilt only when one of + /// them changed. + fn follow_keys(&mut self, ctx: &egui::Context) { + let find = RustGisApp::script_find_keys(ctx); + let print = (self.app.shortcuts_fingerprint(), find.len()); + if self.taken_print != Some(print) { + self.taken_print = Some(print); + *self.taken.borrow_mut() = (self.app.command_keys(), find); + } + } +} + impl eframe::App for WebShell { fn logic(&mut self, ctx: &egui::Context, frame: &mut eframe::Frame) { // The GPU map backend draws inside egui's wgpu pass; hand over the render state. @@ -483,18 +497,14 @@ impl eframe::App for WebShell { } self.app.logic(ctx); self.dirty.set(self.app.session.dirty()); - // The shortcuts can be changed in the app, and the Script box takes its find chords only - // while it has the focus: the key listener follows, rebuilt only when one of them changed. - let find = RustGisApp::script_find_keys(ctx); - let print = (self.app.shortcuts_fingerprint(), find.len()); - if self.taken_print != Some(print) { - self.taken_print = Some(print); - *self.taken.borrow_mut() = (self.app.command_keys(), find); - } + self.follow_keys(ctx); } fn ui(&mut self, ui: &mut egui::Ui, _frame: &mut eframe::Frame) { self.app.ui(ui); + // The pass may have moved the focus into the Script box, or out of it: a key pressed + // before the next frame's `logic` is judged by where the focus is now. + self.follow_keys(ui.ctx()); } } From 78d9243d62f87e912d41a619a10daf786808a388 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 14:11:45 -0500 Subject: [PATCH 07/23] fix(ui): the Script find says what a longer paste leaves out (#2996) The Find and Replace fields cut a paste past 200 characters without a word, against the rule that a truncation says what and how much. The bar now says how many characters were left out under the fields, and Messages gets it once while it repeats. --- crates/ui-egui/src/analysispane.rs | 44 ++++++++++++++++++++++- crates/ui-egui/src/scriptfind.rs | 57 +++++++++++++++++++++++++++--- docs/user-guide/analysis.md | 23 ++++++------ 3 files changed, 108 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index fe2403781d..12ccbb4fe3 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -2327,7 +2327,9 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) { } // Over the box's top right, once it is laid out; a replace it makes comes after the box's own // keys, so it is not read as what a key did. - crate::scriptfind::show(ui, box_id, &mut app.workflow.script, running, out.inner_rect); + if let Some(cut) = crate::scriptfind::show(ui, box_id, &mut app.workflow.script, running, out.inner_rect) { + app.session.notify(cut, false); + } // Where the box's cursor is (#2831), focused or not, on the right of a row of its own: the // row of buttons has no room for it in a narrow pane. The row is there before the box has a // cursor too, so nothing below moves when it gets one. Read from the box's state as it is @@ -3324,6 +3326,10 @@ mod tests { h.run(); // 200 characters in a script of 400: two matches. All 400 would be one. h.get_by_label("1 of 2"); + // What was left out is said, under the fields and in Messages. + let cut = "The Find field takes 200 characters: 200 left out"; + h.get_by_label(cut); + assert!(h.state().session.notices.iter().any(|n| n.text == cut), "{:?}", h.state().session.notices); // The Replace field takes no more either: Replace All writes it once per match, so a long // paste would make the script the matches times its length. h.get_by_label("Toggle Replace").click(); @@ -3332,6 +3338,9 @@ mod tests { h.run(); h.event(Event::Text("b".repeat(400))); h.run(); + let cut = "The Replace field takes 200 characters: 200 left out"; + h.get_by_label(cut); + assert!(h.state().session.notices.iter().any(|n| n.text == cut), "{:?}", h.state().session.notices); h.get_by_label("Replace All").click(); h.run(); assert_eq!(h.state().workflow.script, "b".repeat(400), "200 characters for each of the two matches"); @@ -3386,6 +3395,39 @@ mod tests { assert!(!taken(&h, "f", "KeyF"), "given back when the focus leaves"); } + /// What fits the fields is neither cut nor said (#2996). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_find_query_that_fits_says_nothing() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let mut app = RustGisApp::with_sample(); + app.workflow.script = "a".repeat(400); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + // The icons draw letters: the fonts first, as the other pane tests do. + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + script_pane(app, ui, &Tokens::light()); + }, + app, + ); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("script_text"))); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + h.event(Event::Text("a".repeat(200))); + h.run(); + h.get_by_label("1 of 2"); + assert!(h.query_by_label_contains("left out").is_none()); + assert!(!h.state().session.notices.iter().any(|n| n.text.contains("left out"))); + } + /// The editor shortcuts around the find bar (#2996): Ctrl+H opens it with the Replace row, F3 and /// Shift+F3 go to the next and the previous match. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index d81f318fee..1ace772d71 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -131,6 +131,8 @@ struct Bar { focus_query: bool, /// The Replace row is shown. replace_open: bool, + /// What the last change of a field left out of it, said under the fields. + cut: Option, found: std::sync::Arc, /// What `found` was worked out for: the script's hash, the query and the case. key: Option<(u64, String, bool, bool)>, @@ -312,14 +314,16 @@ enum Toggle { /// under the arrow at its left, a field for what to replace with and the Replace and Replace All /// buttons. Does what it's asked: a replace changes `script` as one undo step of the box, which /// `running` forbids. -pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: bool, area: egui::Rect) { +pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: bool, area: egui::Rect) -> Option { use egui::text::{CCursor, CCursorRange}; let id = box_id.with("find"); let (query_id, replace_id) = (box_id.with("find_query"), box_id.with("find_replace")); let mut bar: Bar = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); if !bar.open { - return; + return None; } + // What a field lost this frame, for Messages too. + let mut said = None; let total = bar.found.ranges.len(); let capped = bar.found.capped; let width = (area.width() - 2.0 * EDGE).clamp(MIN_BAR, MAX_BAR); @@ -353,7 +357,6 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b egui::TextEdit::singleline(&mut bar.query) .id(query_id) .desired_width(field) - .char_limit(FIELD_MAX) .margin(egui::Margin { left: 6, right: 54, top: 3, bottom: 3 }) .hint_text(tl!("Find")), ); @@ -375,6 +378,13 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } if query.changed() { bar.reseek = true; + let cut = cap(&mut bar.query).map(|n| { + crate::i18n::fmt( + "The Find field takes {max} characters: {n} left out", + &[("max", &FIELD_MAX.to_string()), ("n", &n.to_string())], + ) + }); + said = say_once(&mut bar.cut, cut); } let shift = ui.input(|i| i.modifiers.shift); if query.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { @@ -417,12 +427,20 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b egui::TextEdit::singleline(&mut bar.replace) .id(replace_id) .desired_width(field) - .char_limit(FIELD_MAX) .margin(egui::Margin { left: 6, right: 6, top: 3, bottom: 3 }) .hint_text(tl!("Replace")), ); // Under the count, the Replace buttons: one match, and all of them. ui.add_space(COUNT_WIDTH + GAP); + if replace.changed() { + let cut = cap(&mut bar.replace).map(|n| { + crate::i18n::fmt( + "The Replace field takes {max} characters: {n} left out", + &[("max", &FIELD_MAX.to_string()), ("n", &n.to_string())], + ) + }); + said = say_once(&mut bar.cut, cut); + } let can = !running && bar.current.is_some(); let wait = tl!("Wait for the run to finish").to_string(); let (one_say, all_say) = (tl!("Replace (Enter)").to_string(), tl!("Replace All").to_string()); @@ -464,6 +482,9 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } }); } + if let Some(cut) = &bar.cut { + ui.label(egui::RichText::new(cut).small().color(ui.visuals().warn_fg_color)); + } }); }); }); @@ -511,6 +532,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b ui.ctx().request_repaint(); } ui.data_mut(|d| d.insert_temp(id, bar)); + said } /// The chords the Script box and its find bar take while one of them has the focus, as (Alt, Shift, @@ -530,6 +552,22 @@ pub fn browser_keys(ctx: &egui::Context) -> &'static [(bool, bool, egui::Key)] { } } +/// Cuts `text` to [`FIELD_MAX`] characters, and says how many it left out, if any. +fn cap(text: &mut String) -> Option { + let (end, _) = text.char_indices().nth(FIELD_MAX)?; + let left = text[end..].chars().count(); + text.truncate(end); + Some(left) +} + +/// Keeps `cut` as the bar's note, and gives it back when it is news: a key held past the limit +/// says it once, in Messages too, not once a keystroke. +fn say_once(note: &mut Option, cut: Option) -> Option { + let news = cut.clone().filter(|c| note.as_ref() != Some(c)); + *note = cut; + news +} + /// The fill of a match, and of the current one: amber over the text, translucent, as the stop's /// mark is, the current one stronger and outlined too, so it isn't told by its colour alone. const MATCH: egui::Color32 = egui::Color32::from_rgba_premultiplied(90, 70, 0, 90); @@ -598,6 +636,17 @@ mod tests { assert!(!bar.is_current("cat dog"), "Match Whole Word changed"); } + #[test] + fn a_cut_is_said_once_while_it_repeats() { + let mut note = None; + let cut = || Some("1 left out".to_string()); + assert_eq!(say_once(&mut note, cut()), cut()); + assert_eq!(say_once(&mut note, cut()), None, "held past the limit"); + assert_eq!(say_once(&mut note, None), None); + assert_eq!(note, None, "a change that fits takes the note away"); + assert_eq!(say_once(&mut note, cut()), cut(), "said again after"); + } + #[test] fn an_empty_query_is_nowhere() { assert_eq!(at("abc", "", true), []); diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index a735c102c8..7b0fcbcc1f 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1896,17 +1896,18 @@ Backspace in an empty `{}`, `[]` or `""` deletes both. The lists open in a quote itself, and accepting keeps that quote. Pasting adds nothing. Ctrl+F (⌘+F on macOS) in the Script box opens a find bar over the box's top right, as a code editor -does, with the selected text, if it is one line of up to 200 characters (the most each field takes), -in its field. Every match is highlighted in the box, the current one stronger and outlined, and the -bar says which it is (`3 of 12`, or `No results`). Enter and Shift+Enter (or F3 and Shift+F3), or -the up and down arrows, go to the next and the previous match, round the ends, and scroll it into -view. Two toggles inside the field make capitals count (**Aa**) and match only whole words (**ab** -under a bracket: no letter, digit or `_` against the match); the search is plain text, without -patterns. The arrow at the bar's left (or Ctrl+H, ⌥⌘F on macOS) shows a second field, for what to -replace with, and two buttons: Replace changes the current match and Replace All every one, each as -one step of the box's Undo (Ctrl+Z); both are off while a run is under way, and Replace All is off -too when there are more matches than the bar keeps (10,000). Escape in its fields, or the close -button, closes the bar and leaves the current match selected in the box. +does, with the selected text, if it is one line of up to 200 characters (the most each field takes: +a longer paste is cut, and the bar and Messages say how many characters were left out), in its +field. Every match is highlighted in the box, the current one stronger and outlined, and the bar +says which it is (`3 of 12`, or `No results`). Enter and Shift+Enter (or F3 and Shift+F3), or the up +and down arrows, go to the next and the previous match, round the ends, and scroll it into view. Two +toggles inside the field make capitals count (**Aa**) and match only whole words (**ab** under a +bracket: no letter, digit or `_` against the match); the search is plain text, without patterns. The +arrow at the bar's left (or Ctrl+H, ⌥⌘F on macOS) shows a second field, for what to replace with, +and two buttons: Replace changes the current match and Replace All every one, each as one step of +the box's Undo (Ctrl+Z); both are off while a run is under way, and Replace All is off too when +there are more matches than the bar keeps (10,000). Escape in its fields, or the close button, +closes the bar and leaves the current match selected in the box. ## ModelBuilder From 1115a6e41081ae90744fb6d914ff001b336a977e Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 14:31:58 -0500 Subject: [PATCH 08/23] fix(ui): each Script find field keeps its own note of what was cut (#2996) Both fields wrote one note, so a change of the Replace field that fits took the Find field's note away while its text stayed cut. --- crates/ui-egui/src/analysispane.rs | 10 ++++++++++ crates/ui-egui/src/scriptfind.rs | 12 +++++++----- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 12ccbb4fe3..d409e2fd30 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3340,10 +3340,20 @@ mod tests { h.run(); let cut = "The Replace field takes 200 characters: 200 left out"; h.get_by_label(cut); + // Each field keeps its own note: the Find one stays while its text stays cut, whatever + // the Replace field is given. + h.get_by_label("The Find field takes 200 characters: 200 left out"); assert!(h.state().session.notices.iter().any(|n| n.text == cut), "{:?}", h.state().session.notices); h.get_by_label("Replace All").click(); h.run(); assert_eq!(h.state().workflow.script, "b".repeat(400), "200 characters for each of the two matches"); + // A change that fits takes that field's note away, and only that one. + h.ctx.memory_mut(|m| m.request_focus(box_id.with("find_replace"))); + h.run(); + h.key_press(Key::Backspace); + h.run(); + assert!(h.query_by_label(cut).is_none(), "the Replace note went"); + h.get_by_label("The Find field takes 200 characters: 200 left out"); } /// In a browser the find shortcuts are kept from the browser's own (#2996): while the box or a diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 1ace772d71..1c1e0c73d2 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -131,8 +131,10 @@ struct Bar { focus_query: bool, /// The Replace row is shown. replace_open: bool, - /// What the last change of a field left out of it, said under the fields. - cut: Option, + /// What the last change of each field left out of it, said under the fields: each its own, so + /// one field's note stays while its text is cut, whatever the other is given. + query_cut: Option, + replace_cut: Option, found: std::sync::Arc, /// What `found` was worked out for: the script's hash, the query and the case. key: Option<(u64, String, bool, bool)>, @@ -384,7 +386,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b &[("max", &FIELD_MAX.to_string()), ("n", &n.to_string())], ) }); - said = say_once(&mut bar.cut, cut); + said = say_once(&mut bar.query_cut, cut); } let shift = ui.input(|i| i.modifiers.shift); if query.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { @@ -439,7 +441,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b &[("max", &FIELD_MAX.to_string()), ("n", &n.to_string())], ) }); - said = say_once(&mut bar.cut, cut); + said = say_once(&mut bar.replace_cut, cut); } let can = !running && bar.current.is_some(); let wait = tl!("Wait for the run to finish").to_string(); @@ -482,7 +484,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } }); } - if let Some(cut) = &bar.cut { + for cut in [&bar.query_cut, &bar.replace_cut].into_iter().flatten() { ui.label(egui::RichText::new(cut).small().color(ui.visuals().warn_fg_color)); } }); From be0fe8e19485354d530a31baa0b5d5e5000f6ecf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 15:16:12 -0500 Subject: [PATCH 09/23] fix(ui): a selection that fills the Script find query drops the old cut note (#2996) Opening the bar on a selection replaced the query and kept the note about characters left out of the previous one. --- crates/ui-egui/src/analysispane.rs | 18 +++++++++++++++++- crates/ui-egui/src/scriptfind.rs | 4 ++++ 2 files changed, 21 insertions(+), 1 deletion(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index d409e2fd30..9f44d024e4 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3353,7 +3353,23 @@ mod tests { h.key_press(Key::Backspace); h.run(); assert!(h.query_by_label(cut).is_none(), "the Replace note went"); - h.get_by_label("The Find field takes 200 characters: 200 left out"); + let found = "The Find field takes 200 characters: 200 left out"; + h.get_by_label(found); + // Reopened with nothing picked, the query and its note stay; opened on a selection, the + // query is the selection's and the note about the cut text goes with the old one. + h.key_press(Key::Escape); + h.run(); + let range = |a, b| egui::text::CCursorRange::two(egui::text::CCursor::new(a), egui::text::CCursor::new(b)); + crate::widgets::set_cursor_range(&h.ctx, box_id, range(0, 0)); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + h.get_by_label(found); + h.key_press(Key::Escape); + h.run(); + crate::widgets::set_cursor_range(&h.ctx, box_id, range(0, 3)); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + assert!(h.query_by_label(found).is_none(), "the note was about the old query"); } /// In a browser the find shortcuts are kept from the browser's own (#2996): while the box or a diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 1c1e0c73d2..3fda1600f6 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -236,6 +236,10 @@ pub fn prepare(ui: &egui::Ui, box_id: egui::Id, script: &str) -> Option { let (a, b) = (r.primary.index.0.min(r.secondary.index.0), r.primary.index.0.max(r.secondary.index.0)); let picked: String = script.chars().skip(a).take(b - a).collect(); if !picked.is_empty() && picked.chars().count() <= FIELD_MAX && !picked.contains(['\n', '\r']) { + // A query the selection changes leaves the note about the cut text behind. + if bar.query != picked { + bar.query_cut = None; + } bar.query = picked; } bar.anchor = a; From 99c730599229329cb27dd72bae3b519ca49f36c4 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 15:19:57 -0500 Subject: [PATCH 10/23] fix(ui): the Script find keeps the keyboard, starts over with the project and stays over its box (#2996) An audit of everything that changes the find bar's state: - a click on its buttons took the keyboard from the fields, so Enter, F3 and the shortcuts stopped working; it goes back to the field; - another project left the old query, replacement and notes; the bar starts over, as the pane does; - the Replace note showed with its row hidden; - with the box scrolled out of the pane the bar floated over the window. --- crates/ui-egui/src/analysispane.rs | 104 ++++++++++++++++++++++++++++- crates/ui-egui/src/scriptfind.rs | 66 ++++++++++++++++-- docs/user-guide/analysis.md | 3 +- 3 files changed, 167 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 9f44d024e4..ba0f93de94 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -2285,7 +2285,7 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) { let stopped = stopped_at(app); // The find bar (#2996), above the box: Ctrl+F opens it; a replace changes the script here. let running = script_running(app); - let found = crate::scriptfind::prepare(ui, box_id, &app.workflow.script); + let found = crate::scriptfind::prepare(ui, box_id, &app.workflow.script, app.session.opened); let before = crate::completion::before(ui, box_id, &app.workflow.script); let out = egui::ScrollArea::vertical().id_salt("script_box").max_height(room).auto_shrink([false, true]).show(ui, |ui| { let out = egui::TextEdit::multiline(&mut app.workflow.script) @@ -3454,6 +3454,108 @@ mod tests { assert!(!h.state().session.notices.iter().any(|n| n.text.contains("left out"))); } + /// A click on one of the bar's buttons leaves the keyboard in the bar, as in a code editor, so + /// Enter, F3 and the shortcuts go on working (#2996). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_find_buttons_leave_the_keyboard_in_the_bar() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let mut h = find_harness("cities cities cities"); + let box_id = egui::Id::unique("script_text"); + let (query_id, replace_id) = (box_id.with("find_query"), box_id.with("find_replace")); + let focused = |h: &egui_kittest::Harness<'_, RustGisApp>, id| h.ctx.memory(|m| m.has_focus(id)); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + h.event(Event::Text("cities".into())); + h.run(); + for button in ["Next match (Enter)", "Previous match (Shift+Enter)", "Toggle Replace"] { + h.get_by_label(button).click(); + h.run(); + assert!(focused(&h, query_id), "{button}"); + } + h.ctx.memory_mut(|m| m.request_focus(replace_id)); + h.run(); + h.event(Event::Text("towns".into())); + h.run(); + for button in ["Replace (Enter)", "Replace All"] { + h.get_by_label(button).click(); + h.run(); + assert!(focused(&h, replace_id), "{button}"); + } + } + + /// The Replace field's note is shown with its row, not while the row is hidden (#2996). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_replace_note_shows_with_its_row() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let mut h = find_harness("a"); + let replace_id = egui::Id::unique("script_text").with("find_replace"); + h.key_press_modifiers(Modifiers::COMMAND, Key::H); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(replace_id)); + h.run(); + h.event(Event::Text("b".repeat(300))); + h.run(); + let cut = "The Replace field takes 200 characters: 100 left out"; + h.get_by_label(cut); + h.get_by_label("Toggle Replace").click(); + h.run(); + assert!(h.query_by_label(cut).is_none(), "the row is hidden"); + h.get_by_label("Toggle Replace").click(); + h.run(); + h.get_by_label(cut); + } + + /// Another project starts the bar over, as it starts the pane over: no query, replacement or + /// note of the old one (#2996). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn another_project_starts_the_find_bar_over() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let mut h = find_harness("map.zoomFull"); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + h.event(Event::Text("map".into())); + h.run(); + h.get_by_label("1 of 1"); + h.state_mut().run("project.new", Value::Null).unwrap(); + h.run(); + assert!(h.query_by_label("Close (Esc)").is_none(), "closed"); + h.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("script_text"))); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + assert!(h.query_by_label("1 of 1").is_none() && h.query_by_label("No results").is_none(), "an empty field"); + } + + /// The pane with `script` in it, its fonts installed first (the icons draw letters), and the + /// focus in the box. + #[cfg(not(target_arch = "wasm32"))] + fn find_harness(script: &str) -> egui_kittest::Harness<'static, RustGisApp> { + let mut app = RustGisApp::with_sample(); + app.workflow.script = script.to_string(); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( + move |ui, app: &mut RustGisApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + script_pane(app, ui, &Tokens::light()); + }, + app, + ); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("script_text"))); + h.run(); + h + } + /// The editor shortcuts around the find bar (#2996): Ctrl+H opens it with the Replace row, F3 and /// Shift+F3 go to the next and the previous match. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 3fda1600f6..59d57b0d8a 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -112,6 +112,8 @@ pub fn replace_all(text: &str, found: &Found, with: &str) -> String { /// The find bar's state, kept in the context under the box's id: it isn't saved with the project. #[derive(Clone, Default)] struct Bar { + /// The project it was used in ([`rustgis_engine::Session::opened`]): another starts it over. + project: Option, open: bool, query: String, replace: String, @@ -213,10 +215,14 @@ const FIELD_MAX: usize = 200; /// Before the box: Ctrl+F (⌘F) in the box or in the bar opens it, with the selection in its field; /// the matches are worked out, and what the box has to draw of them is returned, None while the bar /// is closed. The bar itself is drawn over the box once it has been laid out ([`show`]). -pub fn prepare(ui: &egui::Ui, box_id: egui::Id, script: &str) -> Option { +pub fn prepare(ui: &egui::Ui, box_id: egui::Id, script: &str, project: u64) -> Option { let id = box_id.with("find"); let (query_id, replace_id) = (box_id.with("find_query"), box_id.with("find_replace")); let mut bar: Bar = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); + // Another project starts the bar over, as it starts the pane over. + if bar.project != Some(project) { + bar = Bar { project: Some(project), ..Bar::default() }; + } let in_box = ui.memory(|m| m.has_focus(box_id)); let in_bar = ui.memory(|m| m.has_focus(query_id) || m.has_focus(replace_id)); // Ctrl+F (⌘F) opens the bar; Ctrl+H (⌥⌘F on a Mac, where ⌘H hides the app) opens it with the @@ -325,7 +331,10 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b let id = box_id.with("find"); let (query_id, replace_id) = (box_id.with("find_query"), box_id.with("find_replace")); let mut bar: Bar = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); - if !bar.open { + // Over the box only while it shows: scrolled out of the pane, the bar would float over what is + // there instead. + let seen = ui.clip_rect(); + if !bar.open || !seen.intersects(area) { return None; } // What a field lost this frame, for Messages too. @@ -333,11 +342,13 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b let total = bar.found.ranges.len(); let capped = bar.found.capped; let width = (area.width() - 2.0 * EDGE).clamp(MIN_BAR, MAX_BAR); - let pos = egui::pos2((area.right() - EDGE - width).max(area.left()), area.top() + EDGE); + let pos = egui::pos2((area.right() - EDGE - width).max(area.left()), area.top().max(seen.top()) + EDGE); // The popup's own margin (`Frame::popup`) and its stroke. let margin = 6.0; let field = width - 2.0 * margin - 2.0 - TOGGLE_WIDTH - COUNT_WIDTH - 3.0 * crate::widgets::FLAT_BUTTON - 5.0 * GAP; let mut todo = None; + // The arrow was clicked: the keyboard stays in the query field, as in a code editor. + let mut keep_query = false; crate::completion::popup(ui, box_id.with("find_area"), pos, area.height(), |ui| { ui.set_width(width - 2.0 * margin - 2.0); ui.spacing_mut().item_spacing = egui::vec2(GAP, GAP); @@ -356,6 +367,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b toggle.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, bar.replace_open, tl!("Toggle Replace"))); if toggle.on_hover_text(tl!("Toggle Replace")).clicked() { bar.replace_open = !bar.replace_open; + keep_query = true; } ui.vertical(|ui| { ui.horizontal(|ui| { @@ -366,6 +378,10 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b .margin(egui::Margin { left: 6, right: 54, top: 3, bottom: 3 }) .hint_text(tl!("Find")), ); + // After the field: it gives the focus up on a click elsewhere, the arrow's too. + if keep_query { + ui.memory_mut(|m| m.request_focus(query_id)); + } let toggled = field_toggles(ui, query_id.with("toggle"), query.rect, bar.case, bar.whole); match toggled { Some(Toggle::Case) => bar.case = !bar.case, @@ -488,7 +504,8 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } }); } - for cut in [&bar.query_cut, &bar.replace_cut].into_iter().flatten() { + let replace_cut = bar.replace_cut.as_ref().filter(|_| bar.replace_open); + for cut in bar.query_cut.iter().chain(replace_cut) { ui.label(egui::RichText::new(cut).small().color(ui.visuals().warn_fg_color)); } }); @@ -498,6 +515,16 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b // What was found is of the script as it was when the matches were worked out: a key typed in the // box since, in this frame, leaves them for the next. let current_text = bar.is_current(script); + // A click on a button takes the keyboard from the field: give it back, as a code editor keeps + // it, so Enter, F3 and the shortcuts go on working. + let field_for = match todo { + Some(Action::Next | Action::Previous) => Some(query_id), + Some(Action::Replace | Action::ReplaceAll) => Some(replace_id), + _ => None, + }; + if let Some(field) = field_for { + ui.memory_mut(|m| m.request_focus(field)); + } match todo { Some(Action::Next) => bar.go(step(total, bar.current, false)), Some(Action::Previous) => bar.go(step(total, bar.current, true)), @@ -642,6 +669,37 @@ mod tests { assert!(!bar.is_current("cat dog"), "Match Whole Word changed"); } + /// Scrolled out of the pane, the box has no bar floating where it was. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_bar_is_not_drawn_over_a_box_out_of_view() { + use egui_kittest::kittest::Queryable; + let box_id = egui::Id::unique("script_text"); + let mut fonts = false; + let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(400.0, 300.0)).build_ui_state( + move |ui, area: &mut egui::Rect| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + let open = Bar { open: true, project: Some(0), ..Bar::default() }; + if ui.data(|d| d.get_temp::(box_id.with("find"))).is_none() { + ui.data_mut(|d| d.insert_temp(box_id.with("find"), open)); + } + let mut script = String::new(); + prepare(ui, box_id, &script, 0); + show(ui, box_id, &mut script, false, *area); + }, + egui::Rect::from_min_size(egui::pos2(0.0, 20.0), egui::vec2(380.0, 100.0)), + ); + h.run(); + h.get_by_label("Close (Esc)"); + *h.state_mut() = egui::Rect::from_min_size(egui::pos2(0.0, -600.0), egui::vec2(380.0, 100.0)); + h.run(); + assert!(h.query_by_label("Close (Esc)").is_none()); + } + #[test] fn a_cut_is_said_once_while_it_repeats() { let mut note = None; diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 7b0fcbcc1f..a31f3cb173 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1817,7 +1817,8 @@ browser's file picker. A file that isn't UTF-8 text, or is over 1 MB, is refused naming it, and the script stays. Opening a project (New, Open, the sample, a template, or the same one again), from the app, a script, the assistant or an agent, starts the pane blank: the script, its results, the count and the Details -window go with the old project. A script that opens a project itself stays, with its results, as +window go with the old project, and the find bar closes, forgetting what was in it. A script that +opens a project itself stays, with its results, as the new project's Run #1. On the desktop, a script's tools, models and batches, with selections, layer renames and definition queries, the environment, the projection and spectral zones between them, are worked out in the background first, so the map and the rest of the window stay in use: the status bar shows From 06093574688224dee4c430faf818cec4ae66a1a1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 15:44:55 -0500 Subject: [PATCH 11/23] refactor(ui): the Script find fixes each family of faults at its root (#2996) Review findings kept coming from the same causes, so each is removed: - matches worked out before the box and used after it: they are worked out where they are used, and the guard and extra repaint go; - a field's limit and its note kept apart from its text: one Field type cuts after any write and carries the count the note is drawn from; - five places asking for the keyboard back: one rule after the bar is drawn; - the shortcuts written three times: one list for the box and the browser; - the bar's state apart from the pane's: it lives with it and starts over with it for another project. --- apps/rustgis-web/src/web.rs | 14 +- crates/ui-egui/src/analysispane.rs | 38 ++- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/scriptfind.rs | 525 +++++++++++++++-------------- 4 files changed, 308 insertions(+), 271 deletions(-) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index dc21d590fb..62efa04aaa 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -344,14 +344,14 @@ struct WebShell { embed: Option, /// The app's Ctrl (⌘) shortcuts, kept current for [`keep_app_shortcuts`]. taken: TakenKeys, - /// [`RustGisApp::shortcuts_fingerprint`] and the length of [`RustGisApp::script_find_keys`] - /// when `taken` was last filled. - taken_print: Option<(u64, usize)>, + /// [`RustGisApp::shortcuts_fingerprint`] and [`RustGisApp::script_find_keys`] when `taken` + /// was last filled. + taken_print: Option<(u64, Vec<(bool, bool, egui::Key)>)>, } /// The app's Ctrl (⌘) shortcuts as (Alt, Shift, key), [`RustGisApp::command_keys`], and the Script /// box's find chords, [`RustGisApp::script_find_keys`], shared with the page's key listener. -type TakenKeys = Rc, &'static [(bool, bool, egui::Key)])>>; +type TakenKeys = Rc, Vec<(bool, bool, egui::Key)>)>>; /// The link to the page that embeds the app (`?embed`; see `embed.rs`). struct Embed { @@ -458,10 +458,10 @@ impl WebShell { /// them changed. fn follow_keys(&mut self, ctx: &egui::Context) { let find = RustGisApp::script_find_keys(ctx); - let print = (self.app.shortcuts_fingerprint(), find.len()); - if self.taken_print != Some(print) { + let print = (self.app.shortcuts_fingerprint(), find); + if self.taken_print.as_ref() != Some(&print) { + *self.taken.borrow_mut() = (self.app.command_keys(), print.1.clone()); self.taken_print = Some(print); - *self.taken.borrow_mut() = (self.app.command_keys(), find); } } } diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index ba0f93de94..a7fd7e5c59 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -64,6 +64,8 @@ pub struct Workflow { script_asking: bool, /// When the last Script pane run landed: one waiting behind it started then, not when asked. script_landed: Option, + /// The Script box's find and replace bar. + pub(crate) script_find: crate::scriptfind::Bar, /// The project the Script pane's script, results and count are for /// ([`rustgis_engine::Session::opened`]); `None` until the pane first shows. script_project: Option, @@ -2006,6 +2008,8 @@ fn start_over_in_another_project(app: &mut RustGisApp) { let opened = app.session.opened; if app.workflow.script_project.is_some_and(|p| p != opened) { clear_script(app); + // The find bar too: its query and replacement were typed for what was closed. + app.workflow.script_find = Default::default(); } app.workflow.script_project = Some(opened); } @@ -2285,7 +2289,7 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) { let stopped = stopped_at(app); // The find bar (#2996), above the box: Ctrl+F opens it; a replace changes the script here. let running = script_running(app); - let found = crate::scriptfind::prepare(ui, box_id, &app.workflow.script, app.session.opened); + crate::scriptfind::keys(ui, box_id, &app.workflow.script, &mut app.workflow.script_find); let before = crate::completion::before(ui, box_id, &app.workflow.script); let out = egui::ScrollArea::vertical().id_salt("script_box").max_height(room).auto_shrink([false, true]).show(ui, |ui| { let out = egui::TextEdit::multiline(&mut app.workflow.script) @@ -2297,9 +2301,7 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) { .desired_width(f32::INFINITY) .hint_text("map.goToXY {\"lon\": 2.35, \"lat\": 48.85, \"scale\": 5000000}\nselect.byAttributes {\"layer\": \"Cities\", \"where\": \"pop_max > 1000000\"}") .show(ui); - if let Some(shown) = &found { - crate::scriptfind::paint(ui, &out, shown); - } + crate::scriptfind::paint(ui, &out, &app.workflow.script, &mut app.workflow.script_find); // Asked by a click on the error, taken every frame: one that doesn't show the stop (a key // typed) drops it, rather than leaving it for a later stop. let go = ui.data_mut(|d| d.remove_temp::(box_id.with("go_to_stopped"))).is_some(); @@ -2327,7 +2329,8 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) { } // Over the box's top right, once it is laid out; a replace it makes comes after the box's own // keys, so it is not read as what a key did. - if let Some(cut) = crate::scriptfind::show(ui, box_id, &mut app.workflow.script, running, out.inner_rect) { + let w = &mut app.workflow; + for cut in crate::scriptfind::show(ui, box_id, &mut w.script, running, out.inner_rect, &mut w.script_find) { app.session.notify(cut, false); } // Where the box's cursor is (#2831), focused or not, on the right of a row of its own: the @@ -3396,7 +3399,7 @@ mod tests { h.run(); let box_id = egui::Id::unique("script_text"); let pressed = |h: &egui_kittest::Harness<'_, RustGisApp>, key: &str, code: &str, alt: bool| { - RustGisApp::takes_find_key(crate::scriptfind::browser_keys(&h.ctx), key, code, true, alt) + RustGisApp::takes_find_key(&crate::scriptfind::browser_keys(&h.ctx), key, code, true, alt) }; let taken = |h: &egui_kittest::Harness<'_, RustGisApp>, key: &str, code: &str| pressed(h, key, code, false); assert!(!taken(&h, "f", "KeyF"), "the browser keeps them with the focus elsewhere"); @@ -3469,20 +3472,33 @@ mod tests { h.run(); h.event(Event::Text("cities".into())); h.run(); - for button in ["Next match (Enter)", "Previous match (Shift+Enter)", "Toggle Replace"] { + for button in ["Match Case", "Match Whole Word", "Next match (Enter)", "Previous match (Shift+Enter)", "Toggle Replace"] { h.get_by_label(button).click(); h.run(); assert!(focused(&h, query_id), "{button}"); } + h.key_press(Key::Enter); + h.run(); + assert!(focused(&h, query_id), "Enter in the query"); h.ctx.memory_mut(|m| m.request_focus(replace_id)); h.run(); h.event(Event::Text("towns".into())); h.run(); + h.key_press(Key::Enter); + h.run(); + assert!(focused(&h, replace_id), "Enter in the replacement"); for button in ["Replace (Enter)", "Replace All"] { h.get_by_label(button).click(); h.run(); assert!(focused(&h, replace_id), "{button}"); } + // With nothing left to replace, Enter keeps the field too; Close gives the keyboard to the box. + h.key_press(Key::Enter); + h.run(); + assert!(focused(&h, replace_id), "Enter with nothing to replace"); + h.get_by_label("Close (Esc)").click(); + h.run(); + assert!(focused(&h, box_id), "Close"); } /// The Replace field's note is shown with its row, not while the row is hidden (#2996). @@ -3530,6 +3546,14 @@ mod tests { h.key_press_modifiers(Modifiers::COMMAND, Key::F); h.run(); assert!(h.query_by_label("1 of 1").is_none() && h.query_by_label("No results").is_none(), "an empty field"); + // And through Open in Script Pane, which starts the pane over before it is next drawn. + h.event(Event::Text("zoom".into())); + h.run(); + h.state_mut().run("project.new", Value::Null).unwrap(); + let ctx = h.ctx.clone(); + open_script(h.state_mut(), &ctx, "map.zoomFull".into()); + h.run(); + assert!(h.query_by_label("Close (Esc)").is_none(), "closed again"); } /// The pane with `script` in it, its fonts installed first (the icons draw letters), and the diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index c9558a170e..e32afe994b 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1665,7 +1665,7 @@ impl RustGisApp { /// The Ctrl (⌘) chords the Script box and its find bar take while one of them has the focus, as /// (Alt, Shift, key), none otherwise: with [`Self::command_keys`], what the web app keeps from /// the browser's own shortcuts. - pub fn script_find_keys(ctx: &egui::Context) -> &'static [(bool, bool, egui::Key)] { + pub fn script_find_keys(ctx: &egui::Context) -> Vec<(bool, bool, egui::Key)> { scriptfind::browser_keys(ctx) } diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 59d57b0d8a..e0b25920a0 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -109,14 +109,57 @@ pub fn replace_all(text: &str, found: &Found, with: &str) -> String { out } -/// The find bar's state, kept in the context under the box's id: it isn't saved with the project. +/// The most characters of a query, and of a replacement: what each field takes, and so of a +/// selection that fills the query when the bar opens (a longer one is a passage, not a word to look +/// for). Each change of the script or the query costs the script's length times the query's, on the +/// UI thread, and Replace All writes the replacement once per match, up to [`MAX_MATCHES`]. +const FIELD_MAX: usize = 200; + +/// A field of the bar: its text, never over [`FIELD_MAX`], and what the last write of it left out. #[derive(Clone, Default)] -struct Bar { - /// The project it was used in ([`rustgis_engine::Session::opened`]): another starts it over. - project: Option, +struct Field { + text: String, + left_out: usize, +} + +impl Field { + /// After any write of the text (typed, pasted or filled from a selection): cut to what the field + /// takes, keeping how many characters that left out. Given back when it is news, so a key held + /// past the limit is said once, not once a keystroke. + fn written(&mut self) -> Option { + let before = self.left_out; + self.left_out = 0; + if let Some((end, _)) = self.text.char_indices().nth(FIELD_MAX) { + self.left_out = self.text[end..].chars().count(); + self.text.truncate(end); + } + Some(self.left_out).filter(|n| *n > 0 && *n != before) + } +} + +/// Which field, to say what it left out. +#[derive(Clone, Copy)] +enum Which { + Find, + Replace, +} + +/// What a field left out of a longer text, as the bar and Messages say it. +fn left_out(which: Which, n: usize) -> String { + let sentence = match which { + Which::Find => "The Find field takes {max} characters: {n} left out", + Which::Replace => "The Replace field takes {max} characters: {n} left out", + }; + crate::i18n::fmt(sentence, &[("max", &FIELD_MAX.to_string()), ("n", &n.to_string())]) +} + +/// The find bar's state, kept with the Script pane's (and started over with it for another +/// project): it isn't saved with the project. +#[derive(Default)] +pub struct Bar { open: bool, - query: String, - replace: String, + query: Field, + replace: Field, case: bool, /// Only whole words match. whole: bool, @@ -127,28 +170,27 @@ struct Bar { anchor: usize, /// Pick the match at the anchor when the matches are next worked out. reseek: bool, - /// Scroll the current match into view in the box's next frame. + /// Scroll the current match into view when it is next painted. scroll: bool, /// Put the focus in the query field, its text selected. focus_query: bool, /// The Replace row is shown. replace_open: bool, - /// What the last change of each field left out of it, said under the fields: each its own, so - /// one field's note stays while its text is cut, whatever the other is given. - query_cut: Option, - replace_cut: Option, - found: std::sync::Arc, - /// What `found` was worked out for: the script's hash, the query and the case. + /// The matches [`Bar::refresh`] last worked out: read only after it. + found: Found, + /// What `found` was worked out for: the script's hash, the query and the toggles. key: Option<(u64, String, bool, bool)>, } impl Bar { - /// The matches again, if the script, the query or the case changed, and the current one picked. - /// `cursor`: the box's cursor, where a current match lost to an edit of the text is picked again. + /// The matches of `script`, worked out again if it, the query or a toggle changed since, and the + /// current one picked: called wherever the matches are used, so they are never of an older + /// text. `cursor`: the box's cursor, where a current match lost to an edit of the text is + /// picked again. fn refresh(&mut self, script: &str, cursor: usize) { - let key = (egui::util::hash(script), self.query.clone(), self.case, self.whole); + let key = (egui::util::hash(script), self.query.text.clone(), self.case, self.whole); if self.key.as_ref() != Some(&key) { - self.found = std::sync::Arc::new(matches(script, &self.query, self.case, self.whole)); + self.found = matches(script, &self.query.text, self.case, self.whole); self.key = Some(key); if !self.reseek { // The text changed under the bar (typed in the box): the matches shifted, so the @@ -163,14 +205,6 @@ impl Bar { } } - /// Whether `found` is what `script`, the query and the toggles say now. - fn is_current(&self, script: &str) -> bool { - let hash = egui::util::hash(script); - self.key - .as_ref() - .is_some_and(|(h, query, case, whole)| *h == hash && *query == self.query && *case == self.case && *whole == self.whole) - } - /// The bar moved to the match `at` of the found ones. fn go(&mut self, at: Option) { self.current = at; @@ -181,13 +215,7 @@ impl Bar { } } -/// What the box draws of the bar: the matches, the current one and whether to scroll to it. -pub struct Shown { - pub found: std::sync::Arc, - pub current: Option, - pub scroll: bool, -} - +#[derive(Clone, Copy, PartialEq)] enum Action { Next, Previous, @@ -196,83 +224,125 @@ enum Action { Close, } -/// The room the bar leaves at the box's edges, and the widths it takes: a button's side, what the -/// count takes, the toggle that shows Replace, and the least and most the bar is wide (a narrower -/// box has the bar as wide as it is). -const EDGE: f32 = 8.0; -const COUNT_WIDTH: f32 = 52.0; -const TOGGLE_WIDTH: f32 = 16.0; -const MIN_BAR: f32 = 230.0; -const MAX_BAR: f32 = 380.0; -const GAP: f32 = 4.0; +/// What a key of the box and its bar does. +#[derive(Clone, Copy, PartialEq, Debug)] +enum Does { + Find, + FindAndReplace, + Next, + Previous, +} -/// The most characters of a query, and of a replacement: what each field takes, and so of a -/// selection that fills the query when the bar opens (a longer one is a passage, not a word to look -/// for). Each change of the script or the query costs the script's length times the query's, on the -/// UI thread, and Replace All writes the replacement once per match, up to [`MAX_MATCHES`]. -const FIELD_MAX: usize = 200; +/// A shortcut of the box and its bar: Ctrl or ⌘ held (`command`), Alt as given, and the key. +/// A letter takes Shift or not; F3 takes it as given. +struct Chord { + command: bool, + alt: bool, + shift: bool, + key: egui::Key, + does: Does, +} -/// Before the box: Ctrl+F (⌘F) in the box or in the bar opens it, with the selection in its field; -/// the matches are worked out, and what the box has to draw of them is returned, None while the bar -/// is closed. The bar itself is drawn over the box once it has been laid out ([`show`]). -pub fn prepare(ui: &egui::Ui, box_id: egui::Id, script: &str, project: u64) -> Option { - let id = box_id.with("find"); - let (query_id, replace_id) = (box_id.with("find_query"), box_id.with("find_replace")); - let mut bar: Bar = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); - // Another project starts the bar over, as it starts the pane over. - if bar.project != Some(project) { - bar = Bar { project: Some(project), ..Bar::default() }; - } - let in_box = ui.memory(|m| m.has_focus(box_id)); - let in_bar = ui.memory(|m| m.has_focus(query_id) || m.has_focus(replace_id)); - // Ctrl+F (⌘F) opens the bar; Ctrl+H (⌥⌘F on a Mac, where ⌘H hides the app) opens it with the - // Replace row, as a code editor's do. Not with Alt held, but on a Mac for ⌥⌘F: elsewhere - // Ctrl+Alt is AltGr, and AltGr+F types a letter on many layouts, which egui's Ctrl+F - // pattern would otherwise take as its own. - let (here, mac) = (in_box || in_bar, ui.ctx().os().is_mac()); - let alt = ui.input(|i| i.modifiers.alt); - let find = here && !alt && ui.input_mut(|i| i.consume_key(egui::Modifiers::COMMAND, egui::Key::F)); - let replace = here - && ui.input_mut(|i| { - (!alt && !mac && i.consume_key(egui::Modifiers::COMMAND, egui::Key::H)) - || (mac && alt && i.consume_key(egui::Modifiers::COMMAND | egui::Modifiers::ALT, egui::Key::F)) - }); - if find || replace { - if in_box && let Some(r) = crate::widgets::cursor_range(ui.ctx(), box_id) { +const fn chord(command: bool, alt: bool, shift: bool, key: egui::Key, does: Does) -> Chord { + Chord { command, alt, shift, key, does } +} + +/// The shortcuts of a code editor, the one list the box takes its keys from and the web app keeps +/// from the browser: Ctrl+F (⌘F) finds; Ctrl+H, ⌥⌘F on a Mac (where ⌘H hides the app), finds with +/// the Replace row; F3 and Shift+F3 step. Alt is as listed: elsewhere than a Mac, Ctrl+Alt is +/// AltGr, and AltGr+F types a letter on many layouts. +fn chords(mac: bool) -> [Chord; 4] { + use egui::Key; + let replace = + if mac { chord(true, true, false, Key::F, Does::FindAndReplace) } else { chord(true, false, false, Key::H, Does::FindAndReplace) }; + [ + chord(true, false, false, Key::F, Does::Find), + replace, + // Shift first: the plain one doesn't take it. + chord(false, false, true, Key::F3, Does::Previous), + chord(false, false, false, Key::F3, Does::Next), + ] +} + +impl Chord { + fn is_pressed_with(&self, m: egui::Modifiers) -> bool { + let shift = self.key != egui::Key::F3 || m.shift == self.shift; + m.command == self.command && m.alt == self.alt && shift + } + + /// Takes this chord's presses out of the frame's events, so nothing else sees them. + fn take(&self, ui: &egui::Ui) -> bool { + ui.input_mut(|i| { + let before = i.events.len(); + i.events.retain(|e| { + !matches!(e, egui::Event::Key { key, pressed: true, modifiers, .. } + if *key == self.key && self.is_pressed_with(*modifiers)) + }); + before != i.events.len() + }) + } +} + +/// The focus is in the Script box or in a field of its bar: where the shortcuts work. +fn here(ctx: &egui::Context, box_id: egui::Id) -> bool { + let ours = [box_id, box_id.with("find_query"), box_id.with("find_replace")]; + ctx.memory(|m| m.focused()).is_some_and(|f| ours.contains(&f)) +} + +/// Before the box: the shortcuts pressed in the box or the bar ([`chords`]). Finding opens the bar, +/// with the selection in its field; the next and previous match move an open one. +pub fn keys(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { + if !here(ui.ctx(), box_id) { + return; + } + for chord in chords(ui.ctx().os().is_mac()) { + let stepping = matches!(chord.does, Does::Next | Does::Previous); + if (stepping && !bar.open) || !chord.take(ui) { + continue; + } + let range = crate::widgets::cursor_range(ui.ctx(), box_id); + if stepping { + bar.refresh(script, range.map_or(bar.anchor, |r| r.primary.index.0)); + bar.go(step(bar.found.ranges.len(), bar.current, chord.does == Does::Previous)); + continue; + } + if let Some(r) = range.filter(|_| ui.memory(|m| m.has_focus(box_id))) { let (a, b) = (r.primary.index.0.min(r.secondary.index.0), r.primary.index.0.max(r.secondary.index.0)); let picked: String = script.chars().skip(a).take(b - a).collect(); - if !picked.is_empty() && picked.chars().count() <= FIELD_MAX && !picked.contains(['\n', '\r']) { - // A query the selection changes leaves the note about the cut text behind. - if bar.query != picked { - bar.query_cut = None; - } - bar.query = picked; + let word = !picked.is_empty() && picked.chars().count() <= FIELD_MAX && !picked.contains(['\n', '\r']); + // The same query keeps what it left out of a longer one. + if word && bar.query.text != picked { + bar.query.text = picked; + bar.query.written(); } bar.anchor = a; } bar.open = true; - bar.replace_open |= replace; + bar.replace_open |= chord.does == Does::FindAndReplace; bar.reseek = true; bar.focus_query = true; } - if !bar.open { - ui.data_mut(|d| d.insert_temp(id, bar)); - return None; +} + +/// The chords with Ctrl or ⌘ the box and its bar take while one of them has the focus, as (Alt, +/// Shift, key), for the web app to keep from the browser's own Find and History. +pub fn browser_keys(ctx: &egui::Context) -> Vec<(bool, bool, egui::Key)> { + if !here(ctx, egui::Id::unique("script_text")) { + return Vec::new(); } - let cursor = crate::widgets::cursor_range(ui.ctx(), box_id).map_or(bar.anchor, |r| r.primary.index.0); - bar.refresh(script, cursor); - // F3 and Shift+F3, as in a code editor: the next and the previous match, with the focus where it was. - // Shift first: a pattern without Shift may take a press that has it. - if (in_box || in_bar) && ui.input_mut(|i| i.consume_key(egui::Modifiers::SHIFT, egui::Key::F3)) { - bar.go(step(bar.found.ranges.len(), bar.current, true)); - } else if (in_box || in_bar) && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::F3)) { - bar.go(step(bar.found.ranges.len(), bar.current, false)); - } - let shown = Shown { found: bar.found.clone(), current: bar.current, scroll: std::mem::take(&mut bar.scroll) }; - ui.data_mut(|d| d.insert_temp(id, bar)); - Some(shown) + chords(ctx.os().is_mac()).iter().filter(|c| c.command).map(|c| (c.alt, c.shift, c.key)).collect() } +/// The room the bar leaves at the box's edges, and the widths it takes: what the count takes, the +/// toggle that shows Replace, and the least and most the bar is wide (egui keeps it on screen when +/// the box is narrower). +const EDGE: f32 = 8.0; +const COUNT_WIDTH: f32 = 52.0; +const TOGGLE_WIDTH: f32 = 16.0; +const MIN_BAR: f32 = 230.0; +const MAX_BAR: f32 = 380.0; +const GAP: f32 = 4.0; + /// The toggles inside the right end of the query field `input`, as in a code editor: Match Case /// (`Aa`) and Match Whole Word (`ab` under a bracket). Each is `on` or off; the one clicked is /// returned. @@ -325,20 +395,20 @@ enum Toggle { /// field with Match case inside it, the count and the previous, next and close buttons; and, /// under the arrow at its left, a field for what to replace with and the Replace and Replace All /// buttons. Does what it's asked: a replace changes `script` as one undo step of the box, which -/// `running` forbids. -pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: bool, area: egui::Rect) -> Option { +/// `running` forbids. Returns what a field left out of a longer text, for Messages. +pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: bool, area: egui::Rect, bar: &mut Bar) -> Vec { use egui::text::{CCursor, CCursorRange}; - let id = box_id.with("find"); let (query_id, replace_id) = (box_id.with("find_query"), box_id.with("find_replace")); - let mut bar: Bar = ui.data_mut(|d| d.get_temp(id)).unwrap_or_default(); + // What a field lost this frame, for Messages too. + let mut said = Vec::new(); // Over the box only while it shows: scrolled out of the pane, the bar would float over what is // there instead. let seen = ui.clip_rect(); if !bar.open || !seen.intersects(area) { - return None; + return said; } - // What a field lost this frame, for Messages too. - let mut said = None; + let cursor = crate::widgets::cursor_range(ui.ctx(), box_id).map_or(bar.anchor, |r| r.primary.index.0); + bar.refresh(script, cursor); let total = bar.found.ranges.len(); let capped = bar.found.capped; let width = (area.width() - 2.0 * EDGE).clamp(MIN_BAR, MAX_BAR); @@ -347,8 +417,8 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b let margin = 6.0; let field = width - 2.0 * margin - 2.0 - TOGGLE_WIDTH - COUNT_WIDTH - 3.0 * crate::widgets::FLAT_BUTTON - 5.0 * GAP; let mut todo = None; - // The arrow was clicked: the keyboard stays in the query field, as in a code editor. - let mut keep_query = false; + // A widget of the bar was used, or a field changed. + let (mut used, mut edited) = (false, false); crate::completion::popup(ui, box_id.with("find_area"), pos, area.height(), |ui| { ui.set_width(width - 2.0 * margin - 2.0); ui.spacing_mut().item_spacing = egui::vec2(GAP, GAP); @@ -367,21 +437,17 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b toggle.widget_info(|| egui::WidgetInfo::selected(egui::Role::Button, true, bar.replace_open, tl!("Toggle Replace"))); if toggle.on_hover_text(tl!("Toggle Replace")).clicked() { bar.replace_open = !bar.replace_open; - keep_query = true; + used = true; } ui.vertical(|ui| { ui.horizontal(|ui| { let query = ui.add( - egui::TextEdit::singleline(&mut bar.query) + egui::TextEdit::singleline(&mut bar.query.text) .id(query_id) .desired_width(field) .margin(egui::Margin { left: 6, right: 54, top: 3, bottom: 3 }) .hint_text(tl!("Find")), ); - // After the field: it gives the focus up on a click elsewhere, the arrow's too. - if keep_query { - ui.memory_mut(|m| m.request_focus(query_id)); - } let toggled = field_toggles(ui, query_id.with("toggle"), query.rect, bar.case, bar.whole); match toggled { Some(Toggle::Case) => bar.case = !bar.case, @@ -389,32 +455,21 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b None => {} } bar.reseek |= toggled.is_some(); - if toggled.is_some() { - // As in a code editor, typing goes on in the field. - ui.memory_mut(|m| m.request_focus(query_id)); - } + used |= toggled.is_some(); if std::mem::take(&mut bar.focus_query) { ui.memory_mut(|m| m.request_focus(query_id)); - let end = CCursor::new(bar.query.chars().count()); + let end = CCursor::new(bar.query.text.chars().count()); crate::widgets::set_cursor_range(ui.ctx(), query_id, CCursorRange::two(CCursor::new(0), end)); } if query.changed() { - bar.reseek = true; - let cut = cap(&mut bar.query).map(|n| { - crate::i18n::fmt( - "The Find field takes {max} characters: {n} left out", - &[("max", &FIELD_MAX.to_string()), ("n", &n.to_string())], - ) - }); - said = say_once(&mut bar.query_cut, cut); + (bar.reseek, edited) = (true, true); + said.extend(bar.query.written().map(|n| left_out(Which::Find, n))); } let shift = ui.input(|i| i.modifiers.shift); if query.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { - // A one-line box lets go of the focus on Enter: keep it for the next. - ui.memory_mut(|m| m.request_focus(query_id)); todo = Some(if shift { Action::Previous } else { Action::Next }); } - let place = match (bar.query.is_empty(), bar.current) { + let place = match (bar.query.text.is_empty(), bar.current) { (true, _) => String::new(), (false, _) if total == 0 => tl!("No results").to_string(), (false, current) => { @@ -446,7 +501,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b if bar.replace_open { ui.horizontal(|ui| { let replace = ui.add( - egui::TextEdit::singleline(&mut bar.replace) + egui::TextEdit::singleline(&mut bar.replace.text) .id(replace_id) .desired_width(field) .margin(egui::Margin { left: 6, right: 6, top: 3, bottom: 3 }) @@ -455,13 +510,8 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b // Under the count, the Replace buttons: one match, and all of them. ui.add_space(COUNT_WIDTH + GAP); if replace.changed() { - let cut = cap(&mut bar.replace).map(|n| { - crate::i18n::fmt( - "The Replace field takes {max} characters: {n} left out", - &[("max", &FIELD_MAX.to_string()), ("n", &n.to_string())], - ) - }); - said = say_once(&mut bar.replace_cut, cut); + edited = true; + said.extend(bar.replace.written().map(|n| left_out(Which::Replace, n))); } let can = !running && bar.current.is_some(); let wait = tl!("Wait for the run to finish").to_string(); @@ -487,9 +537,8 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b if crate::widgets::flat_icon_button(ui, "replace", &one_say, one_hover, can).clicked() { todo = Some(Action::Replace); } else if replace.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { - // A one-line box lets go of the focus on Enter: keep it, for the next replace, - // which is made only when there is one to make. - ui.memory_mut(|m| m.request_focus(replace_id)); + // Made only when there is one to make. + used = true; if can { todo = Some(Action::Replace); } @@ -504,44 +553,44 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } }); } - let replace_cut = bar.replace_cut.as_ref().filter(|_| bar.replace_open); - for cut in bar.query_cut.iter().chain(replace_cut) { + // Each note with its field: the Replace one only while its row shows. + let replace = Some(&bar.replace).filter(|_| bar.replace_open); + let notes = [(Which::Find, Some(&bar.query)), (Which::Replace, replace)]; + for (which, field) in notes { + let Some(n) = field.map(|f| f.left_out).filter(|n| *n > 0) else { continue }; + let cut = left_out(which, n); ui.label(egui::RichText::new(cut).small().color(ui.visuals().warn_fg_color)); } }); }); }); - let found = bar.found.clone(); - // What was found is of the script as it was when the matches were worked out: a key typed in the - // box since, in this frame, leaves them for the next. - let current_text = bar.is_current(script); - // A click on a button takes the keyboard from the field: give it back, as a code editor keeps - // it, so Enter, F3 and the shortcuts go on working. - let field_for = match todo { - Some(Action::Next | Action::Previous) => Some(query_id), - Some(Action::Replace | Action::ReplaceAll) => Some(replace_id), - _ => None, - }; - if let Some(field) = field_for { + // As in a code editor, the keyboard stays in the bar after any of it was used: a click takes + // the focus from a field, and so does Enter. Asked here, after the fields are drawn. + if (used || todo.is_some()) && todo != Some(Action::Close) { + let replacing = matches!(todo, Some(Action::Replace | Action::ReplaceAll)); + let from_replace = replacing || ui.memory(|m| m.had_focus_last_frame(replace_id)); + let field = if from_replace && bar.replace_open { replace_id } else { query_id }; ui.memory_mut(|m| m.request_focus(field)); } + // What was typed in the fields this frame, before it is acted on. + bar.refresh(script, cursor); match todo { - Some(Action::Next) => bar.go(step(total, bar.current, false)), - Some(Action::Previous) => bar.go(step(total, bar.current, true)), - Some(Action::Replace) if current_text => { - if let Some(r) = bar.current.and_then(|i| found.ranges.get(i)).filter(|_| !running) { + Some(Action::Next) => bar.go(step(bar.found.ranges.len(), bar.current, false)), + Some(Action::Previous) => bar.go(step(bar.found.ranges.len(), bar.current, true)), + Some(Action::Replace) => { + if let Some(r) = bar.current.and_then(|i| bar.found.ranges.get(i)).cloned().filter(|_| !running) { crate::analysispane::keep_for_undo_of(ui.ctx(), box_id, script); - *script = replace_one(script, r.clone(), &bar.replace); - let after = r.start + bar.replace.chars().count(); + *script = replace_one(script, r.clone(), &bar.replace.text); + let after = r.start + bar.replace.text.chars().count(); crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::one(CCursor::new(after))); bar.anchor = after; bar.reseek = true; } } - Some(Action::ReplaceAll) if current_text => { - if !running && !found.capped && !found.ranges.is_empty() { + Some(Action::ReplaceAll) => { + if !running && !bar.found.capped && !bar.found.ranges.is_empty() { crate::analysispane::keep_for_undo_of(ui.ctx(), box_id, script); - *script = replace_all(script, &found, &bar.replace); + *script = replace_all(script, &bar.found, &bar.replace.text); crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::one(CCursor::new(0))); bar.anchor = 0; bar.reseek = true; @@ -549,72 +598,42 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } Some(Action::Close) => { bar.open = false; - // What it found goes with it (up to 10,000 ranges), and is worked out again on opening. - bar.found = Default::default(); - bar.key = None; // The cursor where the search was: the current match, selected, in the box. - if let Some(r) = bar.current.and_then(|i| found.ranges.get(i)) { + if let Some(r) = bar.current.and_then(|i| bar.found.ranges.get(i)) { crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::two(CCursor::new(r.start), CCursor::new(r.end))); } + // What it found goes with it (up to 10,000 ranges), and is worked out again on opening. + bar.found = Found::default(); + bar.key = None; ui.memory_mut(|m| m.request_focus(box_id)); } - _ => {} + None => {} } - if todo.is_some() || bar.reseek || !current_text { - // What was asked, or a key typed in the box this frame, shows in the box on the next frame. + if todo.is_some() || edited || used { + // The box was painted before the bar: it shows what changed on the next frame. ui.ctx().request_repaint(); } - ui.data_mut(|d| d.insert_temp(id, bar)); said } -/// The chords the Script box and its find bar take while one of them has the focus, as (Alt, Shift, -/// key) with Ctrl or ⌘ held, for the web app to keep from the browser's own Find and History. -pub fn browser_keys(ctx: &egui::Context) -> &'static [(bool, bool, egui::Key)] { - let box_id = egui::Id::unique("script_text"); - let ours = [box_id, box_id.with("find_query"), box_id.with("find_replace")]; - if ctx.memory(|m| m.focused()).is_some_and(|f| ours.contains(&f)) { - // On a Mac, ⌥⌘F is the Replace, and ⌘H isn't ours. - if ctx.os().is_mac() { - &[(false, false, egui::Key::F), (true, false, egui::Key::F)] - } else { - &[(false, false, egui::Key::F), (false, false, egui::Key::H)] - } - } else { - &[] - } -} - -/// Cuts `text` to [`FIELD_MAX`] characters, and says how many it left out, if any. -fn cap(text: &mut String) -> Option { - let (end, _) = text.char_indices().nth(FIELD_MAX)?; - let left = text[end..].chars().count(); - text.truncate(end); - Some(left) -} - -/// Keeps `cut` as the bar's note, and gives it back when it is news: a key held past the limit -/// says it once, in Messages too, not once a keystroke. -fn say_once(note: &mut Option, cut: Option) -> Option { - let news = cut.clone().filter(|c| note.as_ref() != Some(c)); - *note = cut; - news -} - /// The fill of a match, and of the current one: amber over the text, translucent, as the stop's /// mark is, the current one stronger and outlined too, so it isn't told by its colour alone. const MATCH: egui::Color32 = egui::Color32::from_rgba_premultiplied(90, 70, 0, 90); const CURRENT: egui::Color32 = egui::Color32::from_rgba_premultiplied(160, 80, 0, 170); -/// Paints the matches over the rows of the laid-out box that show, and, for `scroll`, brings the -/// current one into view in the enclosing scroll. -pub fn paint(ui: &egui::Ui, out: &egui::text_edit::TextEditOutput, shown: &Shown) { +/// Paints the matches over the rows of the laid-out box that show, and, once asked, brings the +/// current one into view in the enclosing scroll. `script`: the text the box has just laid out. +pub fn paint(ui: &egui::Ui, out: &egui::text_edit::TextEditOutput, script: &str, bar: &mut Bar) { use egui::text::{CCursor, CharIndex}; + if !bar.open { + return; + } + bar.refresh(script, out.cursor_range.map_or(bar.anchor, |r| r.primary.index.0)); let galley = &out.galley; let origin = crate::widgets::text_origin(out); let painter = ui.painter().with_clip_rect(out.text_clip_rect.intersect(ui.clip_rect())); let seen = painter.clip_rect(); - let ranges = &shown.found.ranges; + let ranges = &bar.found.ranges; let mut start = 0; for row in &galley.rows { let shown_chars = row.glyphs.len(); @@ -626,7 +645,7 @@ pub fn paint(ui: &egui::Ui, out: &egui::text_edit::TextEditOutput, shown: &Shown let (a, b) = (r.start.max(start) - start, r.end.min(start + shown_chars) - start); let x = |c: usize| row.pos.x + row.x_offset(CharIndex(c)) + origin.x; let rect = egui::Rect::from_x_y_ranges(x(a)..=x(b), y); - if shown.current == Some(i) { + if bar.current == Some(i) { painter.rect_filled(rect, 2.0, CURRENT); painter.rect_stroke(rect, 2.0, egui::Stroke::new(1.0, CURRENT), egui::StrokeKind::Outside); } else { @@ -636,8 +655,8 @@ pub fn paint(ui: &egui::Ui, out: &egui::text_edit::TextEditOutput, shown: &Shown } start += row.char_count_including_newline().0; } - if shown.scroll - && let Some(r) = shown.current.and_then(|i| ranges.get(i)) + if std::mem::take(&mut bar.scroll) + && let Some(r) = bar.current.and_then(|i| ranges.get(i)) { let at = egui::text::CCursor { prefer_next_row: true, ..CCursor::new(r.start) }; ui.scroll_to_rect(galley.pos_from_cursor(at).translate(origin), Some(egui::Align::Center)); @@ -653,62 +672,56 @@ mod tests { } #[test] - fn matches_of_another_script_query_or_toggle_are_not_current() { - let mut bar = Bar { query: "cat".into(), ..Bar::default() }; - bar.refresh("cat dog", 0); - assert!(bar.is_current("cat dog")); - assert!(!bar.is_current("cat dogs"), "the script changed"); - // Typed or toggled after the matches were worked out, in the same frame. - bar.query.push('s'); - assert!(!bar.is_current("cat dog"), "the query changed"); - bar.query.pop(); + fn the_matches_are_of_the_text_the_query_and_the_toggles_as_they_are() { + let mut bar = Bar { open: true, ..Bar::default() }; + bar.query.text = "cat".into(); + let count = |bar: &mut Bar, script: &str| { + bar.refresh(script, 0); + bar.found.ranges.len() + }; + assert_eq!(count(&mut bar, "cat Cat cats"), 3); + assert_eq!(count(&mut bar, "cat"), 1, "the script changed"); + bar.query.text.push('s'); + assert_eq!(count(&mut bar, "cat Cat cats"), 1, "the query changed"); + bar.query.text.pop(); bar.case = true; - assert!(!bar.is_current("cat dog"), "Match Case changed"); - bar.case = false; + assert_eq!(count(&mut bar, "cat Cat cats"), 2, "Match Case"); bar.whole = true; - assert!(!bar.is_current("cat dog"), "Match Whole Word changed"); + assert_eq!(count(&mut bar, "cat Cat cats"), 1, "Match Whole Word"); } - /// Scrolled out of the pane, the box has no bar floating where it was. - #[cfg(not(target_arch = "wasm32"))] #[test] - fn the_bar_is_not_drawn_over_a_box_out_of_view() { - use egui_kittest::kittest::Queryable; - let box_id = egui::Id::unique("script_text"); - let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(egui::vec2(400.0, 300.0)).build_ui_state( - move |ui, area: &mut egui::Rect| { - if !fonts { - crate::theme::install_fonts(ui.ctx(), &[], None); - fonts = true; - return; - } - let open = Bar { open: true, project: Some(0), ..Bar::default() }; - if ui.data(|d| d.get_temp::(box_id.with("find"))).is_none() { - ui.data_mut(|d| d.insert_temp(box_id.with("find"), open)); - } - let mut script = String::new(); - prepare(ui, box_id, &script, 0); - show(ui, box_id, &mut script, false, *area); - }, - egui::Rect::from_min_size(egui::pos2(0.0, 20.0), egui::vec2(380.0, 100.0)), - ); - h.run(); - h.get_by_label("Close (Esc)"); - *h.state_mut() = egui::Rect::from_min_size(egui::pos2(0.0, -600.0), egui::vec2(380.0, 100.0)); - h.run(); - assert!(h.query_by_label("Close (Esc)").is_none()); + fn a_field_cuts_what_it_cannot_take_and_says_it_once() { + let mut field = Field::default(); + field.text = "é".repeat(FIELD_MAX); + assert_eq!((field.written(), field.left_out), (None, 0), "what fits says nothing"); + field.text.push_str("ab"); + assert_eq!((field.written(), field.text.chars().count()), (Some(2), FIELD_MAX)); + field.text.push_str("cd"); + assert_eq!((field.written(), field.left_out), (None, 2), "held past the limit: said once"); + field.text.push('c'); + assert_eq!(field.written(), Some(1), "another count is news"); + field.text.pop(); + assert_eq!((field.written(), field.left_out), (None, 0), "a change that fits takes the note away"); } #[test] - fn a_cut_is_said_once_while_it_repeats() { - let mut note = None; - let cut = || Some("1 left out".to_string()); - assert_eq!(say_once(&mut note, cut()), cut()); - assert_eq!(say_once(&mut note, cut()), None, "held past the limit"); - assert_eq!(say_once(&mut note, None), None); - assert_eq!(note, None, "a change that fits takes the note away"); - assert_eq!(say_once(&mut note, cut()), cut(), "said again after"); + fn the_chords_are_one_list_for_the_box_and_the_browser() { + use egui::{Key, Modifiers}; + let command = Modifiers { command: true, ctrl: true, ..Modifiers::default() }; + let altgr = Modifiers { alt: true, ..command }; + for mac in [false, true] { + let does = |key: Key, m: Modifiers| chords(mac).iter().find(|c| c.key == key && c.is_pressed_with(m)).map(|c| c.does); + assert_eq!(does(Key::F, command), Some(Does::Find)); + assert_eq!(does(Key::F, command | Modifiers::SHIFT), Some(Does::Find), "a letter takes Shift"); + assert_eq!(does(Key::F, altgr), mac.then_some(Does::FindAndReplace), "AltGr types a letter"); + assert_eq!(does(Key::H, command), (!mac).then_some(Does::FindAndReplace), "⌘H hides the app"); + assert_eq!(does(Key::H, altgr), None); + assert_eq!(does(Key::F3, Modifiers::NONE), Some(Does::Next)); + assert_eq!(does(Key::F3, Modifiers::SHIFT), Some(Does::Previous)); + assert_eq!(does(Key::F3, command), None); + assert_eq!(does(Key::F, Modifiers::NONE), None, "typing an f"); + } } #[test] From 9a3a63fc76d636720954255a48fda4fead9c89f1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 15:54:08 -0500 Subject: [PATCH 12/23] fix(ui): the Script find says a cut once and Replace All keeps the script within its limit (#2996) A field's cut goes to Messages as the field goes from fitting to cut, not on each change of the count. A Replace All that would make the script larger than a script file may be replaces nothing and says so. --- crates/ui-egui/src/analysispane.rs | 25 ++++++++++++++++++++ crates/ui-egui/src/scriptfind.rs | 37 +++++++++++++++++++----------- docs/user-guide/analysis.md | 5 ++-- 3 files changed, 51 insertions(+), 16 deletions(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index a7fd7e5c59..f76a7128c8 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3501,6 +3501,31 @@ mod tests { assert!(focused(&h, box_id), "Close"); } + /// Replace All that would make the script larger than a script file may be is refused, and + /// said (#2996): each run could add up to the matches times the replacement. + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn replace_all_does_not_grow_the_script_past_its_limit() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let script = "a ".repeat(6000); + let mut h = find_harness(&script); + let box_id = egui::Id::unique("script_text"); + h.key_press_modifiers(Modifiers::COMMAND, Key::H); + h.run(); + h.event(Event::Text("a".into())); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(box_id.with("find_replace"))); + h.run(); + h.event(Event::Text("b".repeat(200))); + h.run(); + h.get_by_label("Replace All").click(); + h.run(); + assert!(h.state().workflow.script == script, "6000 × 200 characters is over 1 MB"); + let said = "Replace All would make the script larger than 1 MB: nothing was replaced"; + assert!(h.state().session.notices.iter().any(|n| n.text == said), "{:?}", h.state().session.notices); + } + /// The Replace field's note is shown with its row, not while the row is hidden (#2996). #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index e0b25920a0..2884b0b4d7 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -124,8 +124,8 @@ struct Field { impl Field { /// After any write of the text (typed, pasted or filled from a selection): cut to what the field - /// takes, keeping how many characters that left out. Given back when it is news, so a key held - /// past the limit is said once, not once a keystroke. + /// takes, keeping how many characters that left out. Given back as the field goes from fitting + /// to cut, for one notice, not one a keystroke while it stays over; the bar's note counts on. fn written(&mut self) -> Option { let before = self.left_out; self.left_out = 0; @@ -133,7 +133,7 @@ impl Field { self.left_out = self.text[end..].chars().count(); self.text.truncate(end); } - Some(self.left_out).filter(|n| *n > 0 && *n != before) + (before == 0 && self.left_out > 0).then_some(self.left_out) } } @@ -258,7 +258,6 @@ fn chords(mac: bool) -> [Chord; 4] { [ chord(true, false, false, Key::F, Does::Find), replace, - // Shift first: the plain one doesn't take it. chord(false, false, true, Key::F3, Does::Previous), chord(false, false, false, Key::F3, Does::Next), ] @@ -395,7 +394,8 @@ enum Toggle { /// field with Match case inside it, the count and the previous, next and close buttons; and, /// under the arrow at its left, a field for what to replace with and the Replace and Replace All /// buttons. Does what it's asked: a replace changes `script` as one undo step of the box, which -/// `running` forbids. Returns what a field left out of a longer text, for Messages. +/// `running` forbids. Returns what to say in Messages: what a field left out of a longer text, or +/// why a replace was refused. pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: bool, area: egui::Rect, bar: &mut Bar) -> Vec { use egui::text::{CCursor, CCursorRange}; let (query_id, replace_id) = (box_id.with("find_query"), box_id.with("find_replace")); @@ -554,7 +554,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b }); } // Each note with its field: the Replace one only while its row shows. - let replace = Some(&bar.replace).filter(|_| bar.replace_open); + let replace = bar.replace_open.then_some(&bar.replace); let notes = [(Which::Find, Some(&bar.query)), (Which::Replace, replace)]; for (which, field) in notes { let Some(n) = field.map(|f| f.left_out).filter(|n| *n > 0) else { continue }; @@ -589,11 +589,18 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } Some(Action::ReplaceAll) => { if !running && !bar.found.capped && !bar.found.ranges.is_empty() { - crate::analysispane::keep_for_undo_of(ui.ctx(), box_id, script); - *script = replace_all(script, &bar.found, &bar.replace.text); - crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::one(CCursor::new(0))); - bar.anchor = 0; - bar.reseek = true; + let new = replace_all(script, &bar.found, &bar.replace.text); + // It may not grow the script past what a script file may be: a run adds up to the + // matches times the replacement. One already larger may still shrink. + if new.len() > crate::SCRIPT_FILE_MAX_BYTES && new.len() > script.len() { + said.push(tl!("Replace All would make the script larger than 1 MB: nothing was replaced").to_string()); + } else { + crate::analysispane::keep_for_undo_of(ui.ctx(), box_id, script); + *script = new; + crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::one(CCursor::new(0))); + bar.anchor = 0; + bar.reseek = true; + } } } Some(Action::Close) => { @@ -692,17 +699,19 @@ mod tests { #[test] fn a_field_cuts_what_it_cannot_take_and_says_it_once() { - let mut field = Field::default(); - field.text = "é".repeat(FIELD_MAX); + let mut field = Field { text: "é".repeat(FIELD_MAX), ..Field::default() }; assert_eq!((field.written(), field.left_out), (None, 0), "what fits says nothing"); field.text.push_str("ab"); assert_eq!((field.written(), field.text.chars().count()), (Some(2), FIELD_MAX)); field.text.push_str("cd"); assert_eq!((field.written(), field.left_out), (None, 2), "held past the limit: said once"); field.text.push('c'); - assert_eq!(field.written(), Some(1), "another count is news"); + assert_eq!((field.written(), field.left_out), (None, 1), "still cut: the note counts, Messages was told"); field.text.pop(); assert_eq!((field.written(), field.left_out), (None, 0), "a change that fits takes the note away"); + // The pop left room for one: two more are over again by one. + field.text.push_str("cd"); + assert_eq!(field.written(), Some(1), "cut again after fitting: said again"); } #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index a31f3cb173..7a91ce9406 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1907,8 +1907,9 @@ bracket: no letter, digit or `_` against the match); the search is plain text, w arrow at the bar's left (or Ctrl+H, ⌥⌘F on macOS) shows a second field, for what to replace with, and two buttons: Replace changes the current match and Replace All every one, each as one step of the box's Undo (Ctrl+Z); both are off while a run is under way, and Replace All is off too when -there are more matches than the bar keeps (10,000). Escape in its fields, or the close button, -closes the bar and leaves the current match selected in the box. +there are more matches than the bar keeps (10,000); one that would make the script larger than 1 MB +replaces nothing and says so in Messages. Escape in its fields, or the close button, closes the bar +and leaves the current match selected in the box. ## ModelBuilder From d7746aea54b2186491d1dbb4b69ddbe0d5b41e15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 16:16:45 -0500 Subject: [PATCH 13/23] perf(ui): the Script find reads the script once, whatever the query holds (#2996) Trying the query at every place cost the script's length times the query's on each change, about 2e8 comparisons for a long query against a long run of one letter. The search is now Knuth, Morris and Pratt, linear in both, with the same matches: a test compares it with trying every place. --- crates/ui-egui/src/scriptfind.rs | 78 ++++++++++++++++++++++++++++---- 1 file changed, 68 insertions(+), 10 deletions(-) diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 2884b0b4d7..c67a52bd71 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -37,19 +37,40 @@ pub fn matches(text: &str, query: &str, case: bool, whole: bool) -> Found { if query.is_empty() { return found; } - let mut i = 0; - while i + query.len() <= text.len() { - let word = |c: Option<&char>| c.is_some_and(|c| c.is_alphanumeric() || *c == '_'); - let apart = !whole || (!word(i.checked_sub(1).and_then(|b| text.get(b))) && !word(text.get(i + query.len()))); - if apart && text.get(i..i + query.len()) == Some(&query[..]) { + let word = |c: Option<&char>| c.is_some_and(|c| c.is_alphanumeric() || *c == '_'); + // Knuth, Morris and Pratt (1977): each character of the text is read once, whatever the two + // hold, so a long query against a long run of one letter costs no more than any other. + // `back[k]`: how much of the query still matches when its character after `k + 1` doesn't. + let mut back = Vec::with_capacity(query.len()); + let mut matched = 0; + for (k, c) in query.iter().enumerate() { + while matched > 0 && query.get(matched) != Some(c) { + matched = back.get(matched - 1).copied().unwrap_or(0); + } + matched += usize::from(k > 0 && query.get(matched) == Some(c)); + back.push(matched); + } + let mut matched = 0; + for (i, c) in text.iter().enumerate() { + while matched > 0 && query.get(matched) != Some(c) { + matched = back.get(matched - 1).copied().unwrap_or(0); + } + matched += usize::from(query.get(matched) == Some(c)); + if matched < query.len() { + continue; + } + let at = i + 1 - query.len(); + if !whole || (!word(at.checked_sub(1).and_then(|b| text.get(b))) && !word(text.get(i + 1))) { if found.ranges.len() == MAX_MATCHES { found.capped = true; break; } - found.ranges.push(i..i + query.len()); - i += query.len(); + found.ranges.push(at..i + 1); + // The next is looked for after this one. + matched = 0; } else { - i += 1; + // Not a whole word: one that overlaps it may still be. + matched = back.last().copied().unwrap_or(0); } } found @@ -111,8 +132,7 @@ pub fn replace_all(text: &str, found: &Found, with: &str) -> String { /// The most characters of a query, and of a replacement: what each field takes, and so of a /// selection that fills the query when the bar opens (a longer one is a passage, not a word to look -/// for). Each change of the script or the query costs the script's length times the query's, on the -/// UI thread, and Replace All writes the replacement once per match, up to [`MAX_MATCHES`]. +/// for). Replace All writes the replacement once per match, up to [`MAX_MATCHES`]. const FIELD_MAX: usize = 200; /// A field of the bar: its text, never over [`FIELD_MAX`], and what the last write of it left out. @@ -733,6 +753,44 @@ mod tests { } } + /// Every text of up to seven of `a`, `b` and a space against every query of up to four: the + /// matches are those of trying each place in turn, the plainest way to say what they are. + #[test] + fn matches_are_those_of_trying_every_place() { + let words = |most: usize| { + let mut all = vec![String::new()]; + let mut last = all.clone(); + for _ in 0..most { + last = last.iter().flat_map(|w| ['a', 'b', ' '].map(|c| format!("{w}{c}"))).collect(); + all.extend(last.clone()); + } + all + }; + let tried = |text: &str, query: &str, whole: bool| { + let (t, q): (Vec, Vec) = (text.chars().collect(), query.chars().collect()); + let word = |i: usize| t.get(i).is_some_and(|c| c.is_alphanumeric()); + let (mut at, mut found) = (0, Vec::new()); + while !q.is_empty() && at + q.len() <= t.len() { + let apart = !whole || (!at.checked_sub(1).is_some_and(word) && !word(at + q.len())); + if apart && t.get(at..at + q.len()) == Some(&q[..]) { + found.push(at..at + q.len()); + at += q.len(); + } else { + at += 1; + } + } + found + }; + let texts = words(7); + for query in words(4) { + for text in &texts { + for whole in [false, true] { + assert_eq!(matches(text, &query, true, whole).ranges, tried(text, &query, whole), "{text:?} {query:?} {whole}"); + } + } + } + } + #[test] fn an_empty_query_is_nowhere() { assert_eq!(at("abc", "", true), []); From 63e5868603731d36ea406e61808d5c164b8dbfac Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 16:35:39 -0500 Subject: [PATCH 14/23] fix(ui): the Script find cut notes are literals where they are formatted (#2996) The two sentences reached i18n::fmt through a variable, so they were not literals for the translators to find. Also corrects the flat icon button's doc, which named a size parameter it doesn't have. --- crates/ui-egui/src/scriptfind.rs | 12 +++++++----- crates/ui-egui/src/widgets.rs | 2 +- 2 files changed, 8 insertions(+), 6 deletions(-) diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index c67a52bd71..cec3837ba8 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -166,11 +166,13 @@ enum Which { /// What a field left out of a longer text, as the bar and Messages say it. fn left_out(which: Which, n: usize) -> String { - let sentence = match which { - Which::Find => "The Find field takes {max} characters: {n} left out", - Which::Replace => "The Replace field takes {max} characters: {n} left out", - }; - crate::i18n::fmt(sentence, &[("max", &FIELD_MAX.to_string()), ("n", &n.to_string())]) + let (max, n) = (FIELD_MAX.to_string(), n.to_string()); + let args = [("max", max.as_str()), ("n", n.as_str())]; + // Each sentence a literal where it is formatted, for the translators to find. + match which { + Which::Find => crate::i18n::fmt("The Find field takes {max} characters: {n} left out", &args), + Which::Replace => crate::i18n::fmt("The Replace field takes {max} characters: {n} left out", &args), + } } /// The find bar's state, kept with the Script pane's (and started over with it for another diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 651de369ba..cbdf55473d 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -158,7 +158,7 @@ pub(crate) fn text_origin(out: &egui::text_edit::TextEditOutput) -> egui::Vec2 { (out.galley_pos - egui::vec2(out.galley.rect.left(), 0.0)).to_vec2() } -/// A flat icon button for a code editor's own bars (find, and what comes next): `size` square, no +/// A flat icon button for a code editor's own bars (find, and what comes next): [`FLAT_BUTTON`] square, no /// border, its icon drawn in code and a hover fill. `label` is what a screen /// reader says; `hover` the tooltip. Off, it takes no click. pub(crate) fn flat_icon_button(ui: &mut Ui, icon: &str, label: &str, hover: &str, enabled: bool) -> Response { From 769ebe8c6a58d6128a1cecf76662a847468ba50f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 17:21:45 -0500 Subject: [PATCH 15/23] fix(ui): the browser keeps none of the Script find's keys, and its fields stay readable (#2996) The web app took only the chords with Ctrl or Cmd, so F3 and Shift+F3 still opened the browser's Find. It now gets every chord the box takes at that moment, F3 only with the bar open, matched by the box's own rule. In a narrow pane the query field shrank to a couple of points of text; the fields keep a floor and what doesn't fit wraps below them. --- apps/rustgis-web/src/web.rs | 10 +++--- crates/ui-egui/src/analysispane.rs | 31 ++++++++++++++++- crates/ui-egui/src/lib.rs | 18 +++------- crates/ui-egui/src/scriptfind.rs | 53 +++++++++++++++++++++++------- 4 files changed, 81 insertions(+), 31 deletions(-) diff --git a/apps/rustgis-web/src/web.rs b/apps/rustgis-web/src/web.rs index 62efa04aaa..bfbd99220d 100644 --- a/apps/rustgis-web/src/web.rs +++ b/apps/rustgis-web/src/web.rs @@ -6,7 +6,7 @@ use std::collections::HashMap; use std::rc::Rc; use rustgis_ui_egui::rustgis_engine::{data::diagnostics::Capture, sources::message_with_address}; -use rustgis_ui_egui::{Inbox, RustGisApp, Services, Slot}; +use rustgis_ui_egui::{FindChords, Inbox, RustGisApp, Services, Slot}; use crate::parts::Notes; use wasm_bindgen::JsCast as _; @@ -346,12 +346,12 @@ struct WebShell { taken: TakenKeys, /// [`RustGisApp::shortcuts_fingerprint`] and [`RustGisApp::script_find_keys`] when `taken` /// was last filled. - taken_print: Option<(u64, Vec<(bool, bool, egui::Key)>)>, + taken_print: Option<(u64, FindChords)>, } /// The app's Ctrl (⌘) shortcuts as (Alt, Shift, key), [`RustGisApp::command_keys`], and the Script /// box's find chords, [`RustGisApp::script_find_keys`], shared with the page's key listener. -type TakenKeys = Rc, Vec<(bool, bool, egui::Key)>)>>; +type TakenKeys = Rc, FindChords)>>; /// The link to the page that embeds the app (`?embed`; see `embed.rs`). struct Embed { @@ -457,7 +457,7 @@ impl WebShell { /// the Script box takes its find chords only while it has the focus. Rebuilt only when one of /// them changed. fn follow_keys(&mut self, ctx: &egui::Context) { - let find = RustGisApp::script_find_keys(ctx); + let find = self.app.script_find_keys(ctx); let print = (self.app.shortcuts_fingerprint(), find); if self.taken_print.as_ref() != Some(&print) { *self.taken.borrow_mut() = (self.app.command_keys(), print.1.clone()); @@ -1516,7 +1516,7 @@ fn keep_app_shortcuts(taken: TakenKeys) -> Result<(), String> { let command = e.ctrl_key() || e.meta_key(); let (keys, find) = &*taken.borrow(); if RustGisApp::takes_browser_key(keys, &e.key(), &e.code(), command, e.alt_key(), e.shift_key()) - || RustGisApp::takes_find_key(find, &e.key(), &e.code(), command, e.alt_key()) + || find.takes(&e.key(), &e.code(), command, e.alt_key(), e.shift_key()) { e.prevent_default(); } diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index f76a7128c8..c408e39261 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3399,7 +3399,7 @@ mod tests { h.run(); let box_id = egui::Id::unique("script_text"); let pressed = |h: &egui_kittest::Harness<'_, RustGisApp>, key: &str, code: &str, alt: bool| { - RustGisApp::takes_find_key(&crate::scriptfind::browser_keys(&h.ctx), key, code, true, alt) + h.state().script_find_keys(&h.ctx).takes(key, code, true, alt, false) }; let taken = |h: &egui_kittest::Harness<'_, RustGisApp>, key: &str, code: &str| pressed(h, key, code, false); assert!(!taken(&h, "f", "KeyF"), "the browser keeps them with the focus elsewhere"); @@ -3415,8 +3415,16 @@ mod tests { assert!(taken(&h, "f", "KeyF") && !taken(&h, "h", "KeyH"), "⌘H is not ours"); assert!(pressed(&h, "f", "KeyF", true), "⌥⌘F opens the Replace row"); h.ctx.set_os(os); + let f3 = |h: &egui_kittest::Harness<'_, RustGisApp>| { + let taken = h.state().script_find_keys(&h.ctx); + // Shift+F3 too, and with Ctrl neither: that one stays the browser's. + assert!(!taken.takes("F3", "F3", true, false, false)); + taken.takes("F3", "F3", false, false, false) && taken.takes("F3", "F3", false, false, true) + }; + assert!(!f3(&h), "F3 is the browser's while the bar is closed"); h.key_press_modifiers(Modifiers::COMMAND, Key::F); h.run(); + assert!(f3(&h), "and the bar's once open"); assert!(h.ctx.memory(|m| m.has_focus(box_id.with("find_query")))); assert!(taken(&h, "f", "KeyF") && taken(&h, "h", "KeyH"), "and in the bar"); h.ctx.memory_mut(|m| m.surrender_focus(box_id.with("find_query"))); @@ -3526,6 +3534,27 @@ mod tests { assert!(h.state().session.notices.iter().any(|n| n.text == said), "{:?}", h.state().session.notices); } + /// In a narrow pane the query field keeps room to read what is typed: the buttons wrap below + /// it rather than squeeze it (#2996). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_narrow_pane_keeps_the_find_query_readable() { + use egui::{Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let mut h = find_harness("map.zoomFull"); + h.set_size(vec2(240.0, 600.0)); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::H); + h.run(); + h.run(); + let box_id = egui::Id::unique("script_text"); + for field in ["find_query", "find_replace"] { + let width = h.ctx.read_response(box_id.with(field)).map(|r| r.rect.width()); + assert!(width.is_some_and(|w| w >= 100.0), "{field}: {width:?}"); + } + h.get_by_label("Close (Esc)"); + } + /// The Replace field's note is shown with its row, not while the row is hidden (#2996). #[cfg(not(target_arch = "wasm32"))] #[test] diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index e32afe994b..7675bb8888 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -114,6 +114,7 @@ mod saveprompt; mod scriptcolor; mod scriptcomplete; mod scriptfind; +pub use scriptfind::FindChords; mod searchbox; mod serviceui; mod sessionlog; @@ -1662,19 +1663,10 @@ impl RustGisApp { keys } - /// The Ctrl (⌘) chords the Script box and its find bar take while one of them has the focus, as - /// (Alt, Shift, key), none otherwise: with [`Self::command_keys`], what the web app keeps from - /// the browser's own shortcuts. - pub fn script_find_keys(ctx: &egui::Context) -> Vec<(bool, bool, egui::Key)> { - scriptfind::browser_keys(ctx) - } - - /// Whether a browser key press (its `key` and `code`, Ctrl or ⌘ held, Alt) is one of the find - /// chords [`Self::script_find_keys`] gives. Alt must be as the chord says, unlike - /// [`Self::takes_browser_key`]: the box takes no Ctrl+Alt+F or Ctrl+Alt+H, so the browser keeps - /// them. Shift is free, as egui matches these. - pub fn takes_find_key(keys: &[(bool, bool, egui::Key)], key: &str, code: &str, command: bool, alt: bool) -> bool { - command && keymap::browser_key(key, code).is_some_and(|k| keys.iter().any(|&(a, _, bound)| bound == k && a == alt)) + /// The chords the Script box and its find bar take now, none while neither has the focus: with + /// [`Self::command_keys`], what the web app keeps from the browser's own shortcuts. + pub fn script_find_keys(&self, ctx: &egui::Context) -> FindChords { + scriptfind::browser_keys(ctx, self.workflow.script_find.is_open()) } /// The keyboard shortcuts of a command run without parameters, in the keymap's order, for a diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index cec3837ba8..e4ded44b44 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -150,7 +150,7 @@ impl Field { let before = self.left_out; self.left_out = 0; if let Some((end, _)) = self.text.char_indices().nth(FIELD_MAX) { - self.left_out = self.text[end..].chars().count(); + self.left_out = self.text.get(end..).map_or(0, |rest| rest.chars().count()); self.text.truncate(end); } (before == 0 && self.left_out > 0).then_some(self.left_out) @@ -205,6 +205,11 @@ pub struct Bar { } impl Bar { + /// Whether the bar shows, so F3 and Shift+F3 are its keys. + pub(crate) fn is_open(&self) -> bool { + self.open + } + /// The matches of `script`, worked out again if it, the query or a toggle changed since, and the /// current one picked: called wherever the matches are used, so they are never of an older /// text. `cursor`: the box's cursor, where a current match lost to an edit of the text is @@ -257,6 +262,7 @@ enum Does { /// A shortcut of the box and its bar: Ctrl or ⌘ held (`command`), Alt as given, and the key. /// A letter takes Shift or not; F3 takes it as given. +#[derive(Clone, Copy, PartialEq)] struct Chord { command: bool, alt: bool, @@ -310,17 +316,22 @@ fn here(ctx: &egui::Context, box_id: egui::Id) -> bool { ctx.memory(|m| m.focused()).is_some_and(|f| ours.contains(&f)) } +/// The chords the box and its bar take now: the next and previous match only with the bar `open`. +fn taken_now(mac: bool, open: bool) -> impl Iterator { + chords(mac).into_iter().filter(move |c| open || !matches!(c.does, Does::Next | Does::Previous)) +} + /// Before the box: the shortcuts pressed in the box or the bar ([`chords`]). Finding opens the bar, /// with the selection in its field; the next and previous match move an open one. pub fn keys(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { if !here(ui.ctx(), box_id) { return; } - for chord in chords(ui.ctx().os().is_mac()) { - let stepping = matches!(chord.does, Does::Next | Does::Previous); - if (stepping && !bar.open) || !chord.take(ui) { + for chord in taken_now(ui.ctx().os().is_mac(), bar.open) { + if !chord.take(ui) { continue; } + let stepping = matches!(chord.does, Does::Next | Does::Previous); let range = crate::widgets::cursor_range(ui.ctx(), box_id); if stepping { bar.refresh(script, range.map_or(bar.anchor, |r| r.primary.index.0)); @@ -345,13 +356,26 @@ pub fn keys(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { } } -/// The chords with Ctrl or ⌘ the box and its bar take while one of them has the focus, as (Alt, -/// Shift, key), for the web app to keep from the browser's own Find and History. -pub fn browser_keys(ctx: &egui::Context) -> Vec<(bool, bool, egui::Key)> { +/// The chords the Script box and its bar take at one moment, none while neither has the focus: +/// what the web app keeps from the browser's own Find and History. +#[derive(Clone, Default, PartialEq)] +pub struct FindChords(Vec); + +impl FindChords { + /// Whether a browser key press (its `key` and `code`, Ctrl or ⌘ held, Alt, Shift) is one of + /// them, read as the box reads it ([`Chord::is_pressed_with`]). + pub fn takes(&self, key: &str, code: &str, command: bool, alt: bool, shift: bool) -> bool { + let held = egui::Modifiers { command, alt, shift, ..egui::Modifiers::default() }; + crate::keymap::browser_key(key, code).is_some_and(|k| self.0.iter().any(|c| c.key == k && c.is_pressed_with(held))) + } +} + +/// [`FindChords`] as they are now, the bar `open` or not. +pub fn browser_keys(ctx: &egui::Context, open: bool) -> FindChords { if !here(ctx, egui::Id::unique("script_text")) { - return Vec::new(); + return FindChords::default(); } - chords(ctx.os().is_mac()).iter().filter(|c| c.command).map(|c| (c.alt, c.shift, c.key)).collect() + FindChords(taken_now(ctx.os().is_mac(), open).collect()) } /// The room the bar leaves at the box's edges, and the widths it takes: what the count takes, the @@ -363,6 +387,8 @@ const TOGGLE_WIDTH: f32 = 16.0; const MIN_BAR: f32 = 230.0; const MAX_BAR: f32 = 380.0; const GAP: f32 = 4.0; +/// The least a field is wide: its margins and the toggles inside it, and some forty points of text. +const MIN_FIELD: f32 = 100.0; /// The toggles inside the right end of the query field `input`, as in a code editor: Match Case /// (`Aa`) and Match Whole Word (`ab` under a bracket). Each is `on` or off; the one clicked is @@ -437,7 +463,10 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b let pos = egui::pos2((area.right() - EDGE - width).max(area.left()), area.top().max(seen.top()) + EDGE); // The popup's own margin (`Frame::popup`) and its stroke. let margin = 6.0; - let field = width - 2.0 * margin - 2.0 - TOGGLE_WIDTH - COUNT_WIDTH - 3.0 * crate::widgets::FLAT_BUTTON - 5.0 * GAP; + // The fields take what the count and buttons leave, but never less than can be read: what then + // doesn't fit wraps below them. + let left = width - 2.0 * margin - 2.0 - TOGGLE_WIDTH - COUNT_WIDTH - 3.0 * crate::widgets::FLAT_BUTTON - 5.0 * GAP; + let field = left.max(MIN_FIELD); let mut todo = None; // A widget of the bar was used, or a field changed. let (mut used, mut edited) = (false, false); @@ -462,7 +491,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b used = true; } ui.vertical(|ui| { - ui.horizontal(|ui| { + ui.horizontal_wrapped(|ui| { let query = ui.add( egui::TextEdit::singleline(&mut bar.query.text) .id(query_id) @@ -521,7 +550,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } }); if bar.replace_open { - ui.horizontal(|ui| { + ui.horizontal_wrapped(|ui| { let replace = ui.add( egui::TextEdit::singleline(&mut bar.replace.text) .id(replace_id) From 1ee7104b9b2b3b79b26c76d872c9934b4c5dcd5b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 17:38:40 -0500 Subject: [PATCH 16/23] fix(ui): the Script find takes its exact shortcuts, and no empty Undo step (#2996) Letters took Shift or not, so Ctrl+Shift+F and Ctrl+Shift+H opened the bar and were kept from the browser. Shift is now as listed for every chord. Replacing text with itself recorded an Undo step that changed nothing; a replace now writes only when the script changes. --- crates/ui-egui/src/analysispane.rs | 22 ++++++++++++++++++++++ crates/ui-egui/src/scriptfind.rs | 28 +++++++++++++++++----------- 2 files changed, 39 insertions(+), 11 deletions(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index c408e39261..9eb71dfaf2 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3777,6 +3777,28 @@ mod tests { h.key_press_modifiers(Modifiers::COMMAND, Key::Z); h.run(); assert_eq!(h.state().workflow.script, script, "Replace All is one undo step"); + // Replacing a match with the same text records no step: one Undo still goes back past it. + h.get_by_label("Replace All").click(); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(replace_id)); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.event(Event::Text("Towns".into())); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(box_id.with("find_query"))); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + h.event(Event::Text("Towns".into())); + h.run(); + h.get_by_label("Replace (Enter)").click(); + h.run(); + h.get_by_label("Replace All").click(); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::Z); + h.run(); + assert_eq!(h.state().workflow.script, script, "no step that changes nothing"); } /// The highlight goes over every row of a script that wraps, and a find with nothing in it, a diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index e4ded44b44..65fa05a77a 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -114,6 +114,14 @@ pub fn replace_one(text: &str, range: Range, with: &str) -> String { text.chars().take(start).chain(with.chars()).chain(text.chars().skip(end)).collect() } +/// `new` in place of `script`, as one step of the box's Undo; the same text records none. +fn write(ctx: &egui::Context, box_id: egui::Id, script: &mut String, new: String) { + if new != *script { + crate::analysispane::keep_for_undo_of(ctx, box_id, script); + *script = new; + } +} + /// `text` with every match of `found` replaced by `with`. pub fn replace_all(text: &str, found: &Found, with: &str) -> String { let mut out = String::with_capacity(text.len()); @@ -260,8 +268,8 @@ enum Does { Previous, } -/// A shortcut of the box and its bar: Ctrl or ⌘ held (`command`), Alt as given, and the key. -/// A letter takes Shift or not; F3 takes it as given. +/// A shortcut of the box and its bar: Ctrl or ⌘ held (`command`), Alt and Shift, as given, and the +/// key. #[derive(Clone, Copy, PartialEq)] struct Chord { command: bool, @@ -277,8 +285,8 @@ const fn chord(command: bool, alt: bool, shift: bool, key: egui::Key, does: Does /// The shortcuts of a code editor, the one list the box takes its keys from and the web app keeps /// from the browser: Ctrl+F (⌘F) finds; Ctrl+H, ⌥⌘F on a Mac (where ⌘H hides the app), finds with -/// the Replace row; F3 and Shift+F3 step. Alt is as listed: elsewhere than a Mac, Ctrl+Alt is -/// AltGr, and AltGr+F types a letter on many layouts. +/// the Replace row; F3 and Shift+F3 step. Alt and Shift are as listed: elsewhere than a Mac, +/// Ctrl+Alt is AltGr, and AltGr+F types a letter on many layouts. fn chords(mac: bool) -> [Chord; 4] { use egui::Key; let replace = @@ -293,8 +301,7 @@ fn chords(mac: bool) -> [Chord; 4] { impl Chord { fn is_pressed_with(&self, m: egui::Modifiers) -> bool { - let shift = self.key != egui::Key::F3 || m.shift == self.shift; - m.command == self.command && m.alt == self.alt && shift + m.command == self.command && m.alt == self.alt && m.shift == self.shift } /// Takes this chord's presses out of the frame's events, so nothing else sees them. @@ -630,8 +637,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b Some(Action::Previous) => bar.go(step(bar.found.ranges.len(), bar.current, true)), Some(Action::Replace) => { if let Some(r) = bar.current.and_then(|i| bar.found.ranges.get(i)).cloned().filter(|_| !running) { - crate::analysispane::keep_for_undo_of(ui.ctx(), box_id, script); - *script = replace_one(script, r.clone(), &bar.replace.text); + write(ui.ctx(), box_id, script, replace_one(script, r.clone(), &bar.replace.text)); let after = r.start + bar.replace.text.chars().count(); crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::one(CCursor::new(after))); bar.anchor = after; @@ -646,8 +652,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b if new.len() > crate::SCRIPT_FILE_MAX_BYTES && new.len() > script.len() { said.push(tl!("Replace All would make the script larger than 1 MB: nothing was replaced").to_string()); } else { - crate::analysispane::keep_for_undo_of(ui.ctx(), box_id, script); - *script = new; + write(ui.ctx(), box_id, script, new); crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::one(CCursor::new(0))); bar.anchor = 0; bar.reseek = true; @@ -773,7 +778,8 @@ mod tests { for mac in [false, true] { let does = |key: Key, m: Modifiers| chords(mac).iter().find(|c| c.key == key && c.is_pressed_with(m)).map(|c| c.does); assert_eq!(does(Key::F, command), Some(Does::Find)); - assert_eq!(does(Key::F, command | Modifiers::SHIFT), Some(Does::Find), "a letter takes Shift"); + assert_eq!(does(Key::F, command | Modifiers::SHIFT), None, "Ctrl+Shift+F is not this box's"); + assert_eq!(does(Key::H, command | Modifiers::SHIFT), None); assert_eq!(does(Key::F, altgr), mac.then_some(Does::FindAndReplace), "AltGr types a letter"); assert_eq!(does(Key::H, command), (!mac).then_some(Does::FindAndReplace), "⌘H hides the app"); assert_eq!(does(Key::H, altgr), None); From bdcd029666657d862a4c415f20451da5204f878c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 17:50:52 -0500 Subject: [PATCH 17/23] perf(ui): the Script find reads the script without copying it (#2996) The box takes a script of any size, and each recompute copied it whole to search it. The search reads it as it goes; the ranges are the same. Ctrl+F on a large selection copied it all only to refuse it as a query; it now takes one character past the field's limit. --- crates/ui-egui/src/scriptfind.rs | 20 +++++++++++++++----- 1 file changed, 15 insertions(+), 5 deletions(-) diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 65fa05a77a..454809d7aa 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -31,13 +31,12 @@ pub fn matches(text: &str, query: &str, case: bool, whole: bool) -> Found { _ => c, } }; - let text: Vec = text.chars().map(fold).collect(); let query: Vec = query.chars().map(fold).collect(); let mut found = Found::default(); if query.is_empty() { return found; } - let word = |c: Option<&char>| c.is_some_and(|c| c.is_alphanumeric() || *c == '_'); + let word = |c: Option| c.map(fold).is_some_and(|c| c.is_alphanumeric() || c == '_'); // Knuth, Morris and Pratt (1977): each character of the text is read once, whatever the two // hold, so a long query against a long run of one letter costs no more than any other. // `back[k]`: how much of the query still matches when its character after `k + 1` doesn't. @@ -51,7 +50,12 @@ pub fn matches(text: &str, query: &str, case: bool, whole: bool) -> Found { back.push(matched); } let mut matched = 0; - for (i, c) in text.iter().enumerate() { + // The script is read as it goes, never copied (the box takes any size): `rest` is read once, and + // `behind`, which only moves forward, gives the character before a match. + let mut rest = text.chars().enumerate().peekable(); + let (mut behind, mut passed) = (text.chars(), 0); + while let Some((i, c)) = rest.next() { + let c = &fold(c); while matched > 0 && query.get(matched) != Some(c) { matched = back.get(matched - 1).copied().unwrap_or(0); } @@ -60,7 +64,12 @@ pub fn matches(text: &str, query: &str, case: bool, whole: bool) -> Found { continue; } let at = i + 1 - query.len(); - if !whole || (!word(at.checked_sub(1).and_then(|b| text.get(b))) && !word(text.get(i + 1))) { + let before = at.checked_sub(1).filter(|_| whole).and_then(|b| { + let c = behind.nth(b.saturating_sub(passed)); + passed = b + 1; + c + }); + if !whole || (!word(before) && !word(rest.peek().map(|&(_, c)| c))) { if found.ranges.len() == MAX_MATCHES { found.capped = true; break; @@ -347,7 +356,8 @@ pub fn keys(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { } if let Some(r) = range.filter(|_| ui.memory(|m| m.has_focus(box_id))) { let (a, b) = (r.primary.index.0.min(r.secondary.index.0), r.primary.index.0.max(r.secondary.index.0)); - let picked: String = script.chars().skip(a).take(b - a).collect(); + // No more of a selection than tells whether it fits the field. + let picked: String = script.chars().skip(a).take((b - a).min(FIELD_MAX + 1)).collect(); let word = !picked.is_empty() && picked.chars().count() <= FIELD_MAX && !picked.contains(['\n', '\r']); // The same query keeps what it left out of a longer one. if word && bar.query.text != picked { From cc6356a72efff393af002bd227aff3d11d987f71 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 18:36:10 -0500 Subject: [PATCH 18/23] fix(ui): Escape in the Script box closes the find bar (#2996) Only the bar's fields read Escape, so with the cursor in the box it dropped the focus and left the bar open. The box now keeps Escape while the bar is open; a list or help over the box takes its own first. --- crates/ui-egui/src/analysispane.rs | 34 +++++++++++++++++++++++++++++- crates/ui-egui/src/scriptfind.rs | 20 +++++++++++++----- docs/user-guide/analysis.md | 6 +++--- 3 files changed, 51 insertions(+), 9 deletions(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 9eb71dfaf2..2023c59d12 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -2291,11 +2291,14 @@ fn script(app: &mut RustGisApp, ui: &mut Ui, t: &Tokens, fit: bool) { let running = script_running(app); crate::scriptfind::keys(ui, box_id, &app.workflow.script, &mut app.workflow.script_find); let before = crate::completion::before(ui, box_id, &app.workflow.script); + // With the find bar open the box keeps Escape too, to close it, rather than drop the focus. + let mut filter = crate::scriptcomplete::filter(ui, box_id); + filter.escape |= app.workflow.script_find.is_open(); let out = egui::ScrollArea::vertical().id_salt("script_box").max_height(room).auto_shrink([false, true]).show(ui, |ui| { let out = egui::TextEdit::multiline(&mut app.workflow.script) .id(box_id) .code_editor() - .event_filter(crate::scriptcomplete::filter(ui, box_id)) + .event_filter(filter) .layouter(&mut layouter) .desired_rows(SCRIPT_MIN_ROWS) .desired_width(f32::INFINITY) @@ -3610,6 +3613,35 @@ mod tests { assert!(h.query_by_label("Close (Esc)").is_none(), "closed again"); } + /// Escape in the box closes the bar, after the list open over the box has taken its own; the box + /// keeps the focus and its cursor (#2996). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn escape_in_the_box_closes_the_find_bar_after_the_list() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let mut h = find_harness(""); + let box_id = egui::Id::unique("script_text"); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + // Typing a command opens the list: the first Escape is its own. + h.event(Event::Text("map.zo".into())); + h.run(); + h.run(); + h.key_press(Key::Escape); + h.run(); + h.get_by_label("Close (Esc)"); + assert!(h.ctx.memory(|m| m.has_focus(box_id))); + let cursor = crate::widgets::cursor_range(&h.ctx, box_id); + h.key_press(Key::Escape); + h.run(); + assert!(h.query_by_label("Close (Esc)").is_none(), "closed"); + assert!(h.ctx.memory(|m| m.has_focus(box_id)), "the box keeps the focus"); + assert_eq!(crate::widgets::cursor_range(&h.ctx, box_id), cursor); + } + /// The pane with `script` in it, its fonts installed first (the icons draw letters), and the /// focus in the box. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 454809d7aa..29ee15bcba 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -249,6 +249,14 @@ impl Bar { } } + /// The bar closed. What it found goes with it (up to 10,000 ranges), and is worked out again on + /// opening. + fn close(&mut self) { + self.open = false; + self.found = Found::default(); + self.key = None; + } + /// The bar moved to the match `at` of the found ones. fn go(&mut self, at: Option) { self.current = at; @@ -338,7 +346,7 @@ fn taken_now(mac: bool, open: bool) -> impl Iterator { } /// Before the box: the shortcuts pressed in the box or the bar ([`chords`]). Finding opens the bar, -/// with the selection in its field; the next and previous match move an open one. +/// with the selection in its field; the next and previous match move an open one; Escape closes it. pub fn keys(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { if !here(ui.ctx(), box_id) { return; @@ -371,6 +379,11 @@ pub fn keys(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { bar.reseek = true; bar.focus_query = true; } + // Escape in the box closes an open bar too, after a list or the help over the box took its own + // (read before this); the cursor stays where it is. + if bar.open && ui.memory(|m| m.has_focus(box_id)) && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + bar.close(); + } } /// The chords the Script box and its bar take at one moment, none while neither has the focus: @@ -670,14 +683,11 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } } Some(Action::Close) => { - bar.open = false; // The cursor where the search was: the current match, selected, in the box. if let Some(r) = bar.current.and_then(|i| bar.found.ranges.get(i)) { crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::two(CCursor::new(r.start), CCursor::new(r.end))); } - // What it found goes with it (up to 10,000 ranges), and is worked out again on opening. - bar.found = Found::default(); - bar.key = None; + bar.close(); ui.memory_mut(|m| m.request_focus(box_id)); } None => {} diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 7a91ce9406..6a3d9449c4 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1818,8 +1818,7 @@ naming it, and the script stays. Opening a project (New, Open, the sample, a template, or the same one again), from the app, a script, the assistant or an agent, starts the pane blank: the script, its results, the count and the Details window go with the old project, and the find bar closes, forgetting what was in it. A script that -opens a project itself stays, with its results, as -the new project's Run #1. On the desktop, a script's tools, models and batches, with selections, layer +opens a project itself stays, with its results, as the new project's Run #1. On the desktop, a script's tools, models and batches, with selections, layer renames and definition queries, the environment, the projection and spectral zones between them, are worked out in the background first, so the map and the rest of the window stay in use: the status bar shows **Run Script** and **Cancel**, and the results say **Running…** until the run is added. From the @@ -1909,7 +1908,8 @@ and two buttons: Replace changes the current match and Replace All every one, ea the box's Undo (Ctrl+Z); both are off while a run is under way, and Replace All is off too when there are more matches than the bar keeps (10,000); one that would make the script larger than 1 MB replaces nothing and says so in Messages. Escape in its fields, or the close button, closes the bar -and leaves the current match selected in the box. +and leaves the current match selected in the box. Escape in the box closes it too, once no list or +help is open over the box, and the cursor stays where it is. ## ModelBuilder From e00567c20939d196f74a6c0d74edb2c689801dd9 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 18:43:13 -0500 Subject: [PATCH 19/23] fix(ui): the Script find bar owns its keys wherever the keyboard is in it (#2996) In the app, Escape in the bar's fields picked the Pan tool and left the bar open: egui drops the focus first, and the app's shortcut took the key. The app now leaves it to the bar, as it does for its search box and tables. On the bar's buttons and toggles Escape, F3, Ctrl+F and Ctrl+H did nothing; the bar now remembers which of its widgets has the keyboard, and one place reads Escape for the bar and the box. --- crates/ui-egui/src/analysispane.rs | 89 ++++++++++++++++++++++++++++++ crates/ui-egui/src/chrome.rs | 8 ++- crates/ui-egui/src/lib.rs | 2 +- crates/ui-egui/src/scriptfind.rs | 85 ++++++++++++++++++---------- docs/user-guide/analysis.md | 7 ++- 5 files changed, 156 insertions(+), 35 deletions(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 2023c59d12..966c0c6ce3 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3642,6 +3642,95 @@ mod tests { assert_eq!(crate::widgets::cursor_range(&h.ctx, box_id), cursor); } + /// The bar's keys work wherever the keyboard is in it, its buttons and toggles too, reached with + /// Tab: Escape closes it back to the box, F3 steps, Ctrl+F returns to the query (#2996). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn the_find_keys_work_on_every_button_of_the_bar() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let box_id = egui::Id::unique("script_text"); + let (query_id, replace_id) = (box_id.with("find_query"), box_id.with("find_replace")); + // Tab stops after each field: the toggles and buttons. + for (field, tabs) in [(query_id, 1..=5), (replace_id, 1..=2)] { + for n in tabs { + let on_button = || { + let mut h = find_harness("a Cities b\nCities c\nCities d"); + h.key_press_modifiers(Modifiers::COMMAND, Key::H); + h.run(); + h.event(Event::Text("Cities".into())); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(field)); + h.run(); + for _ in 0..n { + h.key_press(Key::Tab); + h.run(); + } + let focus = h.ctx.memory(|m| m.focused()); + assert!(focus.is_some_and(|f| ![box_id, query_id, replace_id].contains(&f)), "{n}: on a button"); + h + }; + let mut h = on_button(); + assert!(h.state().script_find_keys(&h.ctx).takes("f", "KeyF", true, false, false), "{n}: the browser's Find"); + h.key_press(Key::F3); + h.run(); + h.get_by_label("2 of 3"); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + assert!(h.ctx.memory(|m| m.has_focus(query_id)), "{n}: Ctrl+F"); + let mut h = on_button(); + h.key_press(Key::Escape); + h.run(); + assert!(h.query_by_label("Close (Esc)").is_none(), "{n}: Escape closes"); + assert!(h.ctx.memory(|m| m.has_focus(box_id)), "{n}: back in the box"); + } + } + } + + /// In the whole app, where Escape also picks the Pan tool, the Escape pressed in the find bar + /// is the bar's: it closes, and the tool stays (#2996). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn in_the_app_escape_in_the_find_bar_is_not_the_tool_shortcut() { + use egui::{Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let box_id = egui::Id::unique("script_text"); + for tabs in [0, 3] { + let mut app = RustGisApp::with_sample(); + app.run("ui.pane.script", serde_json::json!({})).unwrap(); + app.session.tool = rustgis_engine::Tool::Measure; + let mut fonts = false; + let builder = egui_kittest::Harness::builder().with_size(vec2(1400.0, 900.0)).with_max_steps(100); + let mut h = builder.build_ui_state( + move |ui, app: &mut RustGisApp| { + if !fonts { + crate::theme::install_fonts(ui.ctx(), &[], None); + fonts = true; + return; + } + let ctx = ui.ctx().clone(); + app.logic(&ctx); + app.ui(ui); + }, + app, + ); + h.run(); + h.ctx.memory_mut(|m| m.request_focus(box_id)); + h.run(); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + for _ in 0..tabs { + h.key_press(Key::Tab); + h.run(); + } + h.get_by_label("Close (Esc)"); + h.key_press(Key::Escape); + h.run(); + assert!(h.query_by_label("Close (Esc)").is_none(), "{tabs}: closed"); + assert_eq!(h.state().session.tool, rustgis_engine::Tool::Measure, "{tabs}: the tool stays"); + } + } + /// The pane with `script` in it, its fonts installed first (the icons draw letters), and the /// focus in the box. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index ab4f70631f..53d9f2c090 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -849,15 +849,17 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { app.ui.history_jump = None; } crate::modelbuilder::shortcuts(app, ctx); - // The search box (or a table cell) was typed in until egui took its focus away on Escape: - // that Escape clears the box (leaves the cell as it was), not the tool. An open list (a + // The search box (or a table cell, or the Script pane's find bar) had the focus until egui + // took it away on Escape: that Escape clears the box (leaves the cell as it was, closes the + // bar), not the tool. An open list (a // clause's Functions) keeps the same keys as a box, those without Ctrl (⌘): Escape closes it. let pass = ctx.cumulative_pass_nr(); let typing = ctx.egui_wants_keyboard_input() || crate::completion::menu_is_open(ctx) || crate::crspicker::list_is_open(ctx) || crate::searchbox::had_focus(&app.ui.search, pass) - || crate::table::had_focus(&app.table, pass); + || crate::table::had_focus(&app.table, pass) + || app.workflow.script_find.had_focus(pass); // A text field focused, not any widget (a button reached with Tab): it has an undo of its own. let text_field = ctx.text_edit_focused(); // An element selected in the open layout, for the layout's own keys. diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7675bb8888..f969708998 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -1666,7 +1666,7 @@ impl RustGisApp { /// The chords the Script box and its find bar take now, none while neither has the focus: with /// [`Self::command_keys`], what the web app keeps from the browser's own shortcuts. pub fn script_find_keys(&self, ctx: &egui::Context) -> FindChords { - scriptfind::browser_keys(ctx, self.workflow.script_find.is_open()) + scriptfind::browser_keys(ctx, &self.workflow.script_find) } /// The keyboard shortcuts of a command run without parameters, in the keymap's order, for a diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 29ee15bcba..14e53122e9 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -213,6 +213,10 @@ pub struct Bar { scroll: bool, /// Put the focus in the query field, its text selected. focus_query: bool, + /// The widget of the bar (a field, a button, a toggle) the keyboard was on when the bar was + /// last drawn, with that pass's number, none when it was elsewhere: where the bar's keys work, + /// besides the box. + focus: Option<(egui::Id, u64)>, /// The Replace row is shown. replace_open: bool, /// The matches [`Bar::refresh`] last worked out: read only after it. @@ -222,11 +226,18 @@ pub struct Bar { } impl Bar { - /// Whether the bar shows, so F3 and Shift+F3 are its keys. + /// Whether the bar shows, so F3, Shift+F3 and Escape are its keys. pub(crate) fn is_open(&self) -> bool { self.open } + /// Whether the keyboard was on a widget of the bar in the pass before `pass`: the app's + /// shortcuts then leave Escape to the bar, though egui has taken the focus away by now. Stale + /// when the bar isn't drawn (its pane closed), so nothing is held off by a bar not shown. + pub(crate) fn had_focus(&self, pass: u64) -> bool { + self.focus.is_some_and(|(_, p)| p + 1 == pass) + } + /// The matches of `script`, worked out again if it, the query or a toggle changed since, and the /// current one picked: called wherever the matches are used, so they are never of an older /// text. `cursor`: the box's cursor, where a current match lost to an edit of the text is @@ -253,6 +264,7 @@ impl Bar { /// opening. fn close(&mut self) { self.open = false; + self.focus = None; self.found = Found::default(); self.key = None; } @@ -334,10 +346,32 @@ impl Chord { } } -/// The focus is in the Script box or in a field of its bar: where the shortcuts work. -fn here(ctx: &egui::Context, box_id: egui::Id) -> bool { - let ours = [box_id, box_id.with("find_query"), box_id.with("find_replace")]; - ctx.memory(|m| m.focused()).is_some_and(|f| ours.contains(&f)) +/// The keyboard is in the Script box or on a widget of its bar: where the shortcuts work. +fn here(ctx: &egui::Context, box_id: egui::Id, bar: &Bar) -> bool { + ctx.memory(|m| m.focused()).is_some_and(|f| f == box_id || bar.focus.is_some_and(|(w, _)| w == f)) +} + +/// The bar closed from itself (`select`: the cursor goes where the search was, the current match +/// selected, in the box) or from the box, whose cursor stays; the keyboard goes to the box. +fn dismiss(ctx: &egui::Context, box_id: egui::Id, bar: &mut Bar, select: bool) { + if let Some(r) = bar.current.and_then(|i| bar.found.ranges.get(i)).filter(|_| select) { + use egui::text::{CCursor, CCursorRange}; + crate::widgets::set_cursor_range(ctx, box_id, CCursorRange::two(CCursor::new(r.start), CCursor::new(r.end))); + } + bar.close(); + ctx.memory_mut(|m| m.request_focus(box_id)); +} + +/// Escape closes an open bar, from the box (after a list or the help over it took its own, read +/// before this) or from any widget of the bar, which egui has taken the focus off by now. +fn escape(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { + let focused = ui.memory(|m| m.focused()); + let boxed = focused == Some(box_id); + let barred = bar.focus.is_some_and(|(w, _)| focused.is_none_or(|f| f == w)); + if bar.open && (boxed || barred) && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { + bar.refresh(script, bar.anchor); + dismiss(ui.ctx(), box_id, bar, !boxed); + } } /// The chords the box and its bar take now: the next and previous match only with the bar `open`. @@ -348,7 +382,8 @@ fn taken_now(mac: bool, open: bool) -> impl Iterator { /// Before the box: the shortcuts pressed in the box or the bar ([`chords`]). Finding opens the bar, /// with the selection in its field; the next and previous match move an open one; Escape closes it. pub fn keys(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { - if !here(ui.ctx(), box_id) { + escape(ui, box_id, script, bar); + if !here(ui.ctx(), box_id, bar) { return; } for chord in taken_now(ui.ctx().os().is_mac(), bar.open) { @@ -379,11 +414,6 @@ pub fn keys(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { bar.reseek = true; bar.focus_query = true; } - // Escape in the box closes an open bar too, after a list or the help over the box took its own - // (read before this); the cursor stays where it is. - if bar.open && ui.memory(|m| m.has_focus(box_id)) && ui.input_mut(|i| i.consume_key(egui::Modifiers::NONE, egui::Key::Escape)) { - bar.close(); - } } /// The chords the Script box and its bar take at one moment, none while neither has the focus: @@ -400,12 +430,12 @@ impl FindChords { } } -/// [`FindChords`] as they are now, the bar `open` or not. -pub fn browser_keys(ctx: &egui::Context, open: bool) -> FindChords { - if !here(ctx, egui::Id::unique("script_text")) { +/// [`FindChords`] as they are now. +pub fn browser_keys(ctx: &egui::Context, bar: &Bar) -> FindChords { + if !here(ctx, egui::Id::unique("script_text"), bar) { return FindChords::default(); } - FindChords(taken_now(ctx.os().is_mac(), open).collect()) + FindChords(taken_now(ctx.os().is_mac(), bar.open).collect()) } /// The room the bar leaves at the box's edges, and the widths it takes: what the count takes, the @@ -483,6 +513,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b // there instead. let seen = ui.clip_rect(); if !bar.open || !seen.intersects(area) { + bar.focus = None; return said; } let cursor = crate::widgets::cursor_range(ui.ctx(), box_id).map_or(bar.anchor, |r| r.primary.index.0); @@ -500,9 +531,11 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b let mut todo = None; // A widget of the bar was used, or a field changed. let (mut used, mut edited) = (false, false); + let mut layer = None; crate::completion::popup(ui, box_id.with("find_area"), pos, area.height(), |ui| { ui.set_width(width - 2.0 * margin - 2.0); ui.spacing_mut().item_spacing = egui::vec2(GAP, GAP); + layer = Some(ui.layer_id()); ui.horizontal_top(|ui| { // The arrow that shows or hides the Replace row, as tall as the rows it covers. let tall = if bar.replace_open { 2.0 * crate::widgets::FLAT_BUTTON + GAP } else { crate::widgets::FLAT_BUTTON }; @@ -573,11 +606,6 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b if crate::widgets::flat_icon_button(ui, "close", &close, &close, true).clicked() { todo = Some(Action::Close); } - // Escape in either field closes the bar (the field gives the focus up on it). - let escaped = ui.input(|i| i.key_pressed(egui::Key::Escape)); - if escaped && (query.has_focus() || query.lost_focus() || ui.memory(|m| m.has_focus(replace_id))) { - todo = Some(Action::Close); - } }); if bar.replace_open { ui.horizontal_wrapped(|ui| { @@ -645,6 +673,10 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b }); }); }); + // The widget of the bar with the keyboard, asked of the bar's layer. Before the focus goes back + // to a field below: reading a widget's response after that would take it off again on a click. + let focused = ui.memory(|m| m.focused()); + let mut focus = focused.filter(|f| ui.ctx().read_response(*f).is_some_and(|r| Some(r.layer_id) == layer)); // As in a code editor, the keyboard stays in the bar after any of it was used: a click takes // the focus from a field, and so does Enter. Asked here, after the fields are drawn. if (used || todo.is_some()) && todo != Some(Action::Close) { @@ -652,6 +684,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b let from_replace = replacing || ui.memory(|m| m.had_focus_last_frame(replace_id)); let field = if from_replace && bar.replace_open { replace_id } else { query_id }; ui.memory_mut(|m| m.request_focus(field)); + focus = Some(field); } // What was typed in the fields this frame, before it is acted on. bar.refresh(script, cursor); @@ -682,20 +715,16 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } } } - Some(Action::Close) => { - // The cursor where the search was: the current match, selected, in the box. - if let Some(r) = bar.current.and_then(|i| bar.found.ranges.get(i)) { - crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::two(CCursor::new(r.start), CCursor::new(r.end))); - } - bar.close(); - ui.memory_mut(|m| m.request_focus(box_id)); - } + Some(Action::Close) => dismiss(ui.ctx(), box_id, bar, true), None => {} } if todo.is_some() || edited || used { // The box was painted before the bar: it shows what changed on the next frame. ui.ctx().request_repaint(); } + // Where the keyboard is now, for the next frame's keys. + let pass = ui.ctx().cumulative_pass_nr(); + bar.focus = focus.filter(|_| bar.open).map(|f| (f, pass)); said } diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 6a3d9449c4..0f68e020da 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1907,9 +1907,10 @@ arrow at the bar's left (or Ctrl+H, ⌥⌘F on macOS) shows a second field, for and two buttons: Replace changes the current match and Replace All every one, each as one step of the box's Undo (Ctrl+Z); both are off while a run is under way, and Replace All is off too when there are more matches than the bar keeps (10,000); one that would make the script larger than 1 MB -replaces nothing and says so in Messages. Escape in its fields, or the close button, closes the bar -and leaves the current match selected in the box. Escape in the box closes it too, once no list or -help is open over the box, and the cursor stays where it is. +replaces nothing and says so in Messages. The bar's shortcuts work from its fields, its buttons and +the box. Escape in the bar, or the close button, closes it and leaves the current match selected in +the box. Escape in the box closes it too, once no list or help is open over the box, and the cursor +stays where it is. ## ModelBuilder From ee43a7cf54f742a454ca9e5d05c2b3b58d67b993 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 18:51:36 -0500 Subject: [PATCH 20/23] refactor(ui): the Script find holds its current match once, with one list of actions (#2996) The current match is the first from one anchor, in place of an index kept beside it and a flag to work it out again. Keys and buttons share one list of actions, one function replaces one match or all, working on the bytes, and the pane's tests share their harness. A dead second reader of Escape goes. --- crates/ui-egui/src/analysispane.rs | 111 ++-------------- crates/ui-egui/src/scriptfind.rs | 203 +++++++++++++---------------- 2 files changed, 101 insertions(+), 213 deletions(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 966c0c6ce3..6e2a1cf389 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3224,13 +3224,8 @@ mod tests { fn ctrl_f_finds_in_the_script_and_escape_leaves_the_cursor_on_the_match() { use egui::{Event, Key, Modifiers}; use egui_kittest::kittest::Queryable; - let mut app = RustGisApp::with_sample(); let script = "layer.rename {\"layer\": \"Cities\"}\nmap.zoomFull\n# Cities again"; - app.workflow.script = script.to_string(); - let mut h = egui_kittest::Harness::builder() - .with_size(vec2(900.0, 800.0)) - .build_ui_state(|ui, app: &mut RustGisApp| script_pane(app, ui, &Tokens::light()), app); - h.run(); + let mut h = find_harness(script); let box_id = egui::Id::unique("script_text"); let cursor = |h: &egui_kittest::Harness<'_, RustGisApp>| { crate::widgets::cursor_range(&h.ctx, box_id).map(|r| (r.secondary.index.0, r.primary.index.0)) @@ -3307,22 +3302,7 @@ mod tests { fn the_find_query_is_limited_in_length() { use egui::{Event, Key, Modifiers}; use egui_kittest::kittest::Queryable; - let mut app = RustGisApp::with_sample(); - app.workflow.script = "a".repeat(400); - let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( - move |ui, app: &mut RustGisApp| { - // The icons draw letters: the fonts first, as the other pane tests do. - if !fonts { - crate::theme::install_fonts(ui.ctx(), &[], None); - fonts = true; - return; - } - script_pane(app, ui, &Tokens::light()); - }, - app, - ); - h.run(); + let mut h = find_harness(&"a".repeat(400)); let box_id = egui::Id::unique("script_text"); h.ctx.memory_mut(|m| m.request_focus(box_id)); h.run(); @@ -3384,27 +3364,14 @@ mod tests { #[test] fn the_find_chords_are_taken_from_the_browser_while_the_box_or_bar_has_the_focus() { use egui::{Key, Modifiers}; - let mut app = RustGisApp::with_sample(); - app.workflow.script = "map.zoomFull".to_string(); - let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( - move |ui, app: &mut RustGisApp| { - // The icons draw letters: the fonts first, as the other pane tests do. - if !fonts { - crate::theme::install_fonts(ui.ctx(), &[], None); - fonts = true; - return; - } - script_pane(app, ui, &Tokens::light()); - }, - app, - ); - h.run(); + let mut h = find_harness("map.zoomFull"); let box_id = egui::Id::unique("script_text"); let pressed = |h: &egui_kittest::Harness<'_, RustGisApp>, key: &str, code: &str, alt: bool| { h.state().script_find_keys(&h.ctx).takes(key, code, true, alt, false) }; let taken = |h: &egui_kittest::Harness<'_, RustGisApp>, key: &str, code: &str| pressed(h, key, code, false); + h.ctx.memory_mut(|m| m.surrender_focus(box_id)); + h.run(); assert!(!taken(&h, "f", "KeyF"), "the browser keeps them with the focus elsewhere"); h.ctx.memory_mut(|m| m.request_focus(box_id)); h.run(); @@ -3441,22 +3408,7 @@ mod tests { fn a_find_query_that_fits_says_nothing() { use egui::{Event, Key, Modifiers}; use egui_kittest::kittest::Queryable; - let mut app = RustGisApp::with_sample(); - app.workflow.script = "a".repeat(400); - let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( - move |ui, app: &mut RustGisApp| { - // The icons draw letters: the fonts first, as the other pane tests do. - if !fonts { - crate::theme::install_fonts(ui.ctx(), &[], None); - fonts = true; - return; - } - script_pane(app, ui, &Tokens::light()); - }, - app, - ); - h.run(); + let mut h = find_harness(&"a".repeat(400)); h.ctx.memory_mut(|m| m.request_focus(egui::Id::unique("script_text"))); h.run(); h.key_press_modifiers(Modifiers::COMMAND, Key::F); @@ -3762,23 +3714,8 @@ mod tests { fn the_find_shortcuts_of_a_code_editor_work_in_the_script_box() { use egui::{Event, Key, Modifiers}; use egui_kittest::kittest::Queryable; - let mut app = RustGisApp::with_sample(); let script = "alpha\nbeta cities\ngamma\ncities delta\ncities"; - app.workflow.script = script.to_string(); - let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( - move |ui, app: &mut RustGisApp| { - // The icons draw letters: the fonts first, as the other pane tests do. - if !fonts { - crate::theme::install_fonts(ui.ctx(), &[], None); - fonts = true; - return; - } - script_pane(app, ui, &Tokens::light()); - }, - app, - ); - h.run(); + let mut h = find_harness(script); let box_id = egui::Id::unique("script_text"); // Ctrl+Alt+F is AltGr+F on many layouts, a letter to type, outside a Mac, where it is ⌥⌘F: it // opens nothing (the key event has `command` set as a platform's has). @@ -3827,23 +3764,8 @@ mod tests { fn replacing_in_the_script_is_one_undo_step_and_waits_for_a_run() { use egui::{Event, Key, Modifiers}; use egui_kittest::kittest::{NodeT, Queryable}; - let mut app = RustGisApp::with_sample(); let script = "a Cities b\nCities c"; - app.workflow.script = script.to_string(); - let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(vec2(900.0, 800.0)).build_ui_state( - move |ui, app: &mut RustGisApp| { - // The icons draw letters: the fonts first, as the other pane tests do. - if !fonts { - crate::theme::install_fonts(ui.ctx(), &[], None); - fonts = true; - return; - } - script_pane(app, ui, &Tokens::light()); - }, - app, - ); - h.run(); + let mut h = find_harness(script); let box_id = egui::Id::unique("script_text"); let replace_id = box_id.with("find_replace"); h.ctx.memory_mut(|m| m.request_focus(box_id)); @@ -3929,21 +3851,8 @@ mod tests { fn finding_in_a_wrapped_long_script_holds() { use egui::{Event, Key, Modifiers}; use egui_kittest::kittest::{NodeT, Queryable}; - let mut app = RustGisApp::with_sample(); - app.workflow.script = format!("# {}\n", "ab ".repeat(40)).repeat(600); - let mut fonts = false; - let mut h = egui_kittest::Harness::builder().with_size(vec2(260.0, 600.0)).build_ui_state( - move |ui, app: &mut RustGisApp| { - // The icons draw letters: the fonts first, as the other pane tests do. - if !fonts { - crate::theme::install_fonts(ui.ctx(), &[], None); - fonts = true; - return; - } - script_pane(app, ui, &Tokens::dark()); - }, - app, - ); + let mut h = find_harness(&format!("# {}\n", "ab ".repeat(40)).repeat(600)); + h.set_size(vec2(260.0, 600.0)); h.run(); let box_id = egui::Id::unique("script_text"); h.ctx.memory_mut(|m| m.request_focus(box_id)); diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 14e53122e9..a10fb13d69 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -89,38 +89,44 @@ pub fn matches(text: &str, query: &str, case: bool, whole: bool) -> Found { /// (the last, `back`) when none is current. None when there are no matches. pub fn step(len: usize, current: Option, back: bool) -> Option { let last = len.checked_sub(1)?; - Some(match (current, back) { - (None, false) => 0, - (None, true) => last, - (Some(c), false) => { - if c.min(last) == last { - 0 - } else { - c + 1 - } - } - (Some(c), true) => { - if c.min(last) == 0 { + Some(match current.map(|c| c.min(last)) { + None => { + if back { last } else { - c.min(last) - 1 + 0 } } + Some(c) => (c + if back { last } else { 1 }) % len, }) } /// The index of the first match at or after the character `from`, else the first (it goes round). pub fn first_from(found: &Found, from: usize) -> Option { - let at = found.ranges.iter().position(|r| r.start >= from); - at.or(if found.ranges.is_empty() { None } else { Some(0) }) + let at = found.ranges.partition_point(|r| r.start < from); + (!found.ranges.is_empty()).then_some(if at < found.ranges.len() { at } else { 0 }) } -/// `text` with the characters in `range` replaced by `with`. -pub fn replace_one(text: &str, range: Range, with: &str) -> String { - let n = text.chars().count(); - let (start, end) = (range.start.min(n), range.end.min(n)); - let end = end.max(start); - text.chars().take(start).chain(with.chars()).chain(text.chars().skip(end)).collect() +/// `text` with the characters of each of `ranges` (in order, apart from each other) replaced by +/// `with`. +pub fn replace(text: &str, ranges: &[Range], with: &str) -> String { + /// `s` cut after its first `n` characters. + fn after(s: &str, n: usize) -> (&str, &str) { + let byte = s.char_indices().nth(n).map_or(s.len(), |(byte, _)| byte); + s.split_at_checked(byte).unwrap_or((s, "")) + } + let mut out = String::with_capacity(text.len()); + // What is left of the text, and the character it starts at. + let (mut rest, mut at) = (text, 0); + for r in ranges { + let (kept, from) = after(rest, r.start.saturating_sub(at)); + out.push_str(kept); + out.push_str(with); + rest = after(from, r.end.saturating_sub(r.start)).1; + at = r.end.max(r.start); + } + out.push_str(rest); + out } /// `new` in place of `script`, as one step of the box's Undo; the same text records none. @@ -131,22 +137,6 @@ fn write(ctx: &egui::Context, box_id: egui::Id, script: &mut String, new: String } } -/// `text` with every match of `found` replaced by `with`. -pub fn replace_all(text: &str, found: &Found, with: &str) -> String { - let mut out = String::with_capacity(text.len()); - let mut chars = text.chars(); - let mut at = 0; - for r in &found.ranges { - out.extend(chars.by_ref().take(r.start.saturating_sub(at))); - out.push_str(with); - // The matched characters are skipped. - chars.by_ref().take(r.end.saturating_sub(r.start)).for_each(drop); - at = r.end.max(r.start); - } - out.extend(chars); - out -} - /// The most characters of a query, and of a replacement: what each field takes, and so of a /// selection that fills the query when the bar opens (a longer one is a passage, not a word to look /// for). Replace All writes the replacement once per match, up to [`MAX_MATCHES`]. @@ -202,13 +192,10 @@ pub struct Bar { case: bool, /// Only whole words match. whole: bool, - /// The match the next and previous go from, an index of `found`. - current: Option, - /// Where a new search starts picking its match: the cursor when the bar opened, the match last - /// stepped to, or the end of a replacement. + /// The current match is the first from this character: where the cursor was when the bar + /// opened or the script was last edited, the match last stepped to, or the end of a + /// replacement. anchor: usize, - /// Pick the match at the anchor when the matches are next worked out. - reseek: bool, /// Scroll the current match into view when it is next painted. scroll: bool, /// Put the focus in the query field, its text selected. @@ -238,28 +225,26 @@ impl Bar { self.focus.is_some_and(|(_, p)| p + 1 == pass) } - /// The matches of `script`, worked out again if it, the query or a toggle changed since, and the - /// current one picked: called wherever the matches are used, so they are never of an older - /// text. `cursor`: the box's cursor, where a current match lost to an edit of the text is - /// picked again. + /// The matches of `script`, worked out again if it, the query or a toggle changed since: + /// called wherever the matches are used, so they are never of an older text. `cursor`: the + /// box's cursor, where the current match is picked from once the script is edited. fn refresh(&mut self, script: &str, cursor: usize) { let key = (egui::util::hash(script), self.query.text.clone(), self.case, self.whole); if self.key.as_ref() != Some(&key) { + // The text changed under the bar (typed in the box): the matches shifted. + if self.key.as_ref().is_some_and(|old| old.0 != key.0) { + self.anchor = cursor; + } self.found = matches(script, &self.query.text, self.case, self.whole); self.key = Some(key); - if !self.reseek { - // The text changed under the bar (typed in the box): the matches shifted, so the - // current one is the first from the cursor, where the edit is. Not scrolled to. - self.current = first_from(&self.found, cursor); - } - } - if self.reseek { - self.current = first_from(&self.found, self.anchor); - self.scroll = self.current.is_some(); - self.reseek = false; } } + /// The match the next and previous go from, an index of `found`. + fn current(&self) -> Option { + first_from(&self.found, self.anchor) + } + /// The bar closed. What it found goes with it (up to 10,000 ranges), and is worked out again on /// opening. fn close(&mut self) { @@ -271,7 +256,6 @@ impl Bar { /// The bar moved to the match `at` of the found ones. fn go(&mut self, at: Option) { - self.current = at; if let Some(r) = at.and_then(|i| self.found.ranges.get(i)) { self.anchor = r.start; self.scroll = true; @@ -279,8 +263,11 @@ impl Bar { } } -#[derive(Clone, Copy, PartialEq)] +/// What a key or a button of the box and its bar does. +#[derive(Clone, Copy, PartialEq, Debug)] enum Action { + Find, + FindAndReplace, Next, Previous, Replace, @@ -288,15 +275,6 @@ enum Action { Close, } -/// What a key of the box and its bar does. -#[derive(Clone, Copy, PartialEq, Debug)] -enum Does { - Find, - FindAndReplace, - Next, - Previous, -} - /// A shortcut of the box and its bar: Ctrl or ⌘ held (`command`), Alt and Shift, as given, and the /// key. #[derive(Clone, Copy, PartialEq)] @@ -305,10 +283,10 @@ struct Chord { alt: bool, shift: bool, key: egui::Key, - does: Does, + does: Action, } -const fn chord(command: bool, alt: bool, shift: bool, key: egui::Key, does: Does) -> Chord { +const fn chord(command: bool, alt: bool, shift: bool, key: egui::Key, does: Action) -> Chord { Chord { command, alt, shift, key, does } } @@ -318,13 +296,16 @@ const fn chord(command: bool, alt: bool, shift: bool, key: egui::Key, does: Does /// Ctrl+Alt is AltGr, and AltGr+F types a letter on many layouts. fn chords(mac: bool) -> [Chord; 4] { use egui::Key; - let replace = - if mac { chord(true, true, false, Key::F, Does::FindAndReplace) } else { chord(true, false, false, Key::H, Does::FindAndReplace) }; + let replace = if mac { + chord(true, true, false, Key::F, Action::FindAndReplace) + } else { + chord(true, false, false, Key::H, Action::FindAndReplace) + }; [ - chord(true, false, false, Key::F, Does::Find), + chord(true, false, false, Key::F, Action::Find), replace, - chord(false, false, true, Key::F3, Does::Previous), - chord(false, false, false, Key::F3, Does::Next), + chord(false, false, true, Key::F3, Action::Previous), + chord(false, false, false, Key::F3, Action::Next), ] } @@ -354,7 +335,7 @@ fn here(ctx: &egui::Context, box_id: egui::Id, bar: &Bar) -> bool { /// The bar closed from itself (`select`: the cursor goes where the search was, the current match /// selected, in the box) or from the box, whose cursor stays; the keyboard goes to the box. fn dismiss(ctx: &egui::Context, box_id: egui::Id, bar: &mut Bar, select: bool) { - if let Some(r) = bar.current.and_then(|i| bar.found.ranges.get(i)).filter(|_| select) { + if let Some(r) = bar.current().and_then(|i| bar.found.ranges.get(i)).filter(|_| select) { use egui::text::{CCursor, CCursorRange}; crate::widgets::set_cursor_range(ctx, box_id, CCursorRange::two(CCursor::new(r.start), CCursor::new(r.end))); } @@ -376,7 +357,7 @@ fn escape(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { /// The chords the box and its bar take now: the next and previous match only with the bar `open`. fn taken_now(mac: bool, open: bool) -> impl Iterator { - chords(mac).into_iter().filter(move |c| open || !matches!(c.does, Does::Next | Does::Previous)) + chords(mac).into_iter().filter(move |c| open || !matches!(c.does, Action::Next | Action::Previous)) } /// Before the box: the shortcuts pressed in the box or the bar ([`chords`]). Finding opens the bar, @@ -390,11 +371,11 @@ pub fn keys(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { if !chord.take(ui) { continue; } - let stepping = matches!(chord.does, Does::Next | Does::Previous); + let stepping = matches!(chord.does, Action::Next | Action::Previous); let range = crate::widgets::cursor_range(ui.ctx(), box_id); if stepping { bar.refresh(script, range.map_or(bar.anchor, |r| r.primary.index.0)); - bar.go(step(bar.found.ranges.len(), bar.current, chord.does == Does::Previous)); + bar.go(step(bar.found.ranges.len(), bar.current(), chord.does == Action::Previous)); continue; } if let Some(r) = range.filter(|_| ui.memory(|m| m.has_focus(box_id))) { @@ -410,8 +391,8 @@ pub fn keys(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { bar.anchor = a; } bar.open = true; - bar.replace_open |= chord.does == Does::FindAndReplace; - bar.reseek = true; + bar.replace_open |= chord.does == Action::FindAndReplace; + bar.scroll = true; bar.focus_query = true; } } @@ -568,7 +549,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b Some(Toggle::Word) => bar.whole = !bar.whole, None => {} } - bar.reseek |= toggled.is_some(); + bar.scroll |= toggled.is_some(); used |= toggled.is_some(); if std::mem::take(&mut bar.focus_query) { ui.memory_mut(|m| m.request_focus(query_id)); @@ -576,14 +557,14 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b crate::widgets::set_cursor_range(ui.ctx(), query_id, CCursorRange::two(CCursor::new(0), end)); } if query.changed() { - (bar.reseek, edited) = (true, true); + (bar.scroll, edited) = (true, true); said.extend(bar.query.written().map(|n| left_out(Which::Find, n))); } let shift = ui.input(|i| i.modifiers.shift); if query.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { todo = Some(if shift { Action::Previous } else { Action::Next }); } - let place = match (bar.query.text.is_empty(), bar.current) { + let place = match (bar.query.text.is_empty(), bar.current()) { (true, _) => String::new(), (false, _) if total == 0 => tl!("No results").to_string(), (false, current) => { @@ -622,7 +603,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b edited = true; said.extend(bar.replace.written().map(|n| left_out(Which::Replace, n))); } - let can = !running && bar.current.is_some(); + let can = !running && bar.current().is_some(); let wait = tl!("Wait for the run to finish").to_string(); let (one_say, all_say) = (tl!("Replace (Enter)").to_string(), tl!("Replace All").to_string()); // Off, the hover says why: a run, or nothing to replace. @@ -657,9 +638,6 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b { todo = Some(Action::ReplaceAll); } - if (replace.has_focus() || replace.lost_focus()) && ui.input(|i| i.key_pressed(egui::Key::Escape)) { - todo = Some(Action::Close); - } }); } // Each note with its field: the Replace one only while its row shows. @@ -689,20 +667,20 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b // What was typed in the fields this frame, before it is acted on. bar.refresh(script, cursor); match todo { - Some(Action::Next) => bar.go(step(bar.found.ranges.len(), bar.current, false)), - Some(Action::Previous) => bar.go(step(bar.found.ranges.len(), bar.current, true)), + Some(Action::Next) => bar.go(step(bar.found.ranges.len(), bar.current(), false)), + Some(Action::Previous) => bar.go(step(bar.found.ranges.len(), bar.current(), true)), Some(Action::Replace) => { - if let Some(r) = bar.current.and_then(|i| bar.found.ranges.get(i)).cloned().filter(|_| !running) { - write(ui.ctx(), box_id, script, replace_one(script, r.clone(), &bar.replace.text)); + if let Some(r) = bar.current().and_then(|i| bar.found.ranges.get(i)).cloned().filter(|_| !running) { + write(ui.ctx(), box_id, script, replace(script, std::slice::from_ref(&r), &bar.replace.text)); let after = r.start + bar.replace.text.chars().count(); crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::one(CCursor::new(after))); bar.anchor = after; - bar.reseek = true; + bar.scroll = true; } } Some(Action::ReplaceAll) => { if !running && !bar.found.capped && !bar.found.ranges.is_empty() { - let new = replace_all(script, &bar.found, &bar.replace.text); + let new = replace(script, &bar.found.ranges, &bar.replace.text); // It may not grow the script past what a script file may be: a run adds up to the // matches times the replacement. One already larger may still shrink. if new.len() > crate::SCRIPT_FILE_MAX_BYTES && new.len() > script.len() { @@ -711,12 +689,12 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b write(ui.ctx(), box_id, script, new); crate::widgets::set_cursor_range(ui.ctx(), box_id, CCursorRange::one(CCursor::new(0))); bar.anchor = 0; - bar.reseek = true; + bar.scroll = true; } } } Some(Action::Close) => dismiss(ui.ctx(), box_id, bar, true), - None => {} + _ => {} } if todo.is_some() || edited || used { // The box was painted before the bar: it shows what changed on the next frame. @@ -745,6 +723,7 @@ pub fn paint(ui: &egui::Ui, out: &egui::text_edit::TextEditOutput, script: &str, let origin = crate::widgets::text_origin(out); let painter = ui.painter().with_clip_rect(out.text_clip_rect.intersect(ui.clip_rect())); let seen = painter.clip_rect(); + let current = bar.current(); let ranges = &bar.found.ranges; let mut start = 0; for row in &galley.rows { @@ -757,7 +736,7 @@ pub fn paint(ui: &egui::Ui, out: &egui::text_edit::TextEditOutput, script: &str, let (a, b) = (r.start.max(start) - start, r.end.min(start + shown_chars) - start); let x = |c: usize| row.pos.x + row.x_offset(CharIndex(c)) + origin.x; let rect = egui::Rect::from_x_y_ranges(x(a)..=x(b), y); - if bar.current == Some(i) { + if current == Some(i) { painter.rect_filled(rect, 2.0, CURRENT); painter.rect_stroke(rect, 2.0, egui::Stroke::new(1.0, CURRENT), egui::StrokeKind::Outside); } else { @@ -768,7 +747,7 @@ pub fn paint(ui: &egui::Ui, out: &egui::text_edit::TextEditOutput, script: &str, start += row.char_count_including_newline().0; } if std::mem::take(&mut bar.scroll) - && let Some(r) = bar.current.and_then(|i| ranges.get(i)) + && let Some(r) = bar.current().and_then(|i| ranges.get(i)) { let at = egui::text::CCursor { prefer_next_row: true, ..CCursor::new(r.start) }; ui.scroll_to_rect(galley.pos_from_cursor(at).translate(origin), Some(egui::Align::Center)); @@ -826,14 +805,14 @@ mod tests { let altgr = Modifiers { alt: true, ..command }; for mac in [false, true] { let does = |key: Key, m: Modifiers| chords(mac).iter().find(|c| c.key == key && c.is_pressed_with(m)).map(|c| c.does); - assert_eq!(does(Key::F, command), Some(Does::Find)); + assert_eq!(does(Key::F, command), Some(Action::Find)); assert_eq!(does(Key::F, command | Modifiers::SHIFT), None, "Ctrl+Shift+F is not this box's"); assert_eq!(does(Key::H, command | Modifiers::SHIFT), None); - assert_eq!(does(Key::F, altgr), mac.then_some(Does::FindAndReplace), "AltGr types a letter"); - assert_eq!(does(Key::H, command), (!mac).then_some(Does::FindAndReplace), "⌘H hides the app"); + assert_eq!(does(Key::F, altgr), mac.then_some(Action::FindAndReplace), "AltGr types a letter"); + assert_eq!(does(Key::H, command), (!mac).then_some(Action::FindAndReplace), "⌘H hides the app"); assert_eq!(does(Key::H, altgr), None); - assert_eq!(does(Key::F3, Modifiers::NONE), Some(Does::Next)); - assert_eq!(does(Key::F3, Modifiers::SHIFT), Some(Does::Previous)); + assert_eq!(does(Key::F3, Modifiers::NONE), Some(Action::Next)); + assert_eq!(does(Key::F3, Modifiers::SHIFT), Some(Action::Previous)); assert_eq!(does(Key::F3, command), None); assert_eq!(does(Key::F, Modifiers::NONE), None, "typing an f"); } @@ -962,22 +941,22 @@ mod tests { #[test] fn a_replace_leaves_the_rest_alone() { - assert_eq!(replace_one("a Cities b", 2..8, "Towns"), "a Towns b"); - assert_eq!(replace_one("é Cities", 2..8, "Ü"), "é Ü"); + assert_eq!(replace("a Cities b", std::slice::from_ref(&(2..8)), "Towns"), "a Towns b"); + assert_eq!(replace("é Cities", std::slice::from_ref(&(2..8)), "Ü"), "é Ü"); // An empty range is an insertion. - assert_eq!(replace_one("abc", 1..1, "X"), "aXbc"); + assert_eq!(replace("abc", std::slice::from_ref(&(1..1)), "X"), "aXbc"); // A range past the end is cut to it, not a panic. - assert_eq!(replace_one("abc", 2..9, "X"), "abX"); - assert_eq!(replace_one("abc", 7..9, "X"), "abcX"); + assert_eq!(replace("abc", std::slice::from_ref(&(2..9)), "X"), "abX"); + assert_eq!(replace("abc", std::slice::from_ref(&(7..9)), "X"), "abcX"); } #[test] fn replace_all_takes_every_match_and_not_what_it_adds() { let text = "Cities, Cities\nCities"; let found = matches(text, "Cities", true, false); - assert_eq!(replace_all(text, &found, "Cities2"), "Cities2, Cities2\nCities2"); - assert_eq!(replace_all(text, &found, ""), ", \n"); - assert_eq!(replace_all("é a é", &matches("é a é", "é", true, false), "ee"), "ee a ee"); - assert_eq!(replace_all("abc", &Found::default(), "X"), "abc"); + assert_eq!(replace(text, &found.ranges, "Cities2"), "Cities2, Cities2\nCities2"); + assert_eq!(replace(text, &found.ranges, ""), ", \n"); + assert_eq!(replace("é a é", &matches("é a é", "é", true, false).ranges, "ee"), "ee a ee"); + assert_eq!(replace("abc", &[], "X"), "abc"); } } From 23b571f985d6949c6b27977f0dfcfe4a17f2af37 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 19:01:08 -0500 Subject: [PATCH 21/23] fix(ui): every long paste into the Script find says what it left out (#2996) A paste into a field already cut left out more without telling Messages. A write that leaves out more than one character is now told; a key typed while the field is over the limit stays quiet. --- crates/ui-egui/src/scriptfind.rs | 14 ++++++++------ docs/user-guide/analysis.md | 5 +++-- 2 files changed, 11 insertions(+), 8 deletions(-) diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index a10fb13d69..dcad1e057c 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -151,8 +151,9 @@ struct Field { impl Field { /// After any write of the text (typed, pasted or filled from a selection): cut to what the field - /// takes, keeping how many characters that left out. Given back as the field goes from fitting - /// to cut, for one notice, not one a keystroke while it stays over; the bar's note counts on. + /// takes, keeping how many characters that left out. Given back, for a notice, as the field + /// goes from fitting to cut and whenever a write leaves out more than one character (a paste); + /// not for each key typed while it stays over. fn written(&mut self) -> Option { let before = self.left_out; self.left_out = 0; @@ -160,7 +161,7 @@ impl Field { self.left_out = self.text.get(end..).map_or(0, |rest| rest.chars().count()); self.text.truncate(end); } - (before == 0 && self.left_out > 0).then_some(self.left_out) + (self.left_out > 1 || (before == 0 && self.left_out == 1)).then_some(self.left_out) } } @@ -787,15 +788,16 @@ mod tests { assert_eq!((field.written(), field.left_out), (None, 0), "what fits says nothing"); field.text.push_str("ab"); assert_eq!((field.written(), field.text.chars().count()), (Some(2), FIELD_MAX)); - field.text.push_str("cd"); - assert_eq!((field.written(), field.left_out), (None, 2), "held past the limit: said once"); field.text.push('c'); - assert_eq!((field.written(), field.left_out), (None, 1), "still cut: the note counts, Messages was told"); + assert_eq!((field.written(), field.left_out), (None, 1), "a key typed while over: the note counts, Messages was told"); field.text.pop(); assert_eq!((field.written(), field.left_out), (None, 0), "a change that fits takes the note away"); // The pop left room for one: two more are over again by one. field.text.push_str("cd"); assert_eq!(field.written(), Some(1), "cut again after fitting: said again"); + // Another long paste over a field already cut leaves out more than a keystroke does. + field.text.push_str(&"x".repeat(30)); + assert_eq!(field.written(), Some(30), "a paste's cut is said, whatever was cut before"); } #[test] diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 0f68e020da..a58548e81c 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1818,8 +1818,9 @@ naming it, and the script stays. Opening a project (New, Open, the sample, a template, or the same one again), from the app, a script, the assistant or an agent, starts the pane blank: the script, its results, the count and the Details window go with the old project, and the find bar closes, forgetting what was in it. A script that -opens a project itself stays, with its results, as the new project's Run #1. On the desktop, a script's tools, models and batches, with selections, layer -renames and definition queries, the environment, the projection and spectral zones between them, are worked out +opens a project itself stays, with its results, as the new project's Run #1. On the desktop, a +script's tools, models and batches, with selections, layer renames and definition queries, the +environment, the projection and spectral zones between them, are worked out in the background first, so the map and the rest of the window stay in use: the status bar shows **Run Script** and **Cancel**, and the results say **Running…** until the run is added. From the first line of any other kind (an edit, Add Data, a save, an export, a style or a zoom, a plugin From 2d1ca3230c3af5fc678741cf7642fec8f7a9f0ad Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 19:13:36 -0500 Subject: [PATCH 22/23] fix(ui): a huge paste into the Script find is cut before the field takes it (#2996) The fields laid out a whole paste before cutting it to 200 characters: 10 MB took 9 s and 2.3 GB. What is pasted or typed into a field is now cut in the frame's input, and what that dropped is added to what the note and Messages say was left out. --- crates/ui-egui/src/analysispane.rs | 18 ++++++++ crates/ui-egui/src/chrome.rs | 4 +- crates/ui-egui/src/scriptfind.rs | 68 ++++++++++++++++++++++++------ 3 files changed, 76 insertions(+), 14 deletions(-) diff --git a/crates/ui-egui/src/analysispane.rs b/crates/ui-egui/src/analysispane.rs index 6e2a1cf389..57924cbf09 100644 --- a/crates/ui-egui/src/analysispane.rs +++ b/crates/ui-egui/src/analysispane.rs @@ -3683,6 +3683,24 @@ mod tests { } } + /// What a huge paste into a field leaves out is counted whole, with what the field already held + /// (#2996). + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_huge_paste_into_a_find_field_is_counted_whole() { + use egui::{Event, Key, Modifiers}; + use egui_kittest::kittest::Queryable; + let mut h = find_harness("a"); + h.key_press_modifiers(Modifiers::COMMAND, Key::F); + h.run(); + h.event(Event::Text("a".repeat(150))); + h.run(); + h.event(Event::Paste("b".repeat(300_000))); + h.run(); + // 150 held and 300,000 pasted, 200 kept. + h.get_by_label("The Find field takes 200 characters: 299950 left out"); + } + /// The pane with `script` in it, its fonts installed first (the icons draw letters), and the /// focus in the box. #[cfg(not(target_arch = "wasm32"))] diff --git a/crates/ui-egui/src/chrome.rs b/crates/ui-egui/src/chrome.rs index 53d9f2c090..dfd1212e4c 100644 --- a/crates/ui-egui/src/chrome.rs +++ b/crates/ui-egui/src/chrome.rs @@ -851,8 +851,8 @@ pub fn shortcuts(app: &mut RustGisApp, ctx: &egui::Context) { crate::modelbuilder::shortcuts(app, ctx); // The search box (or a table cell, or the Script pane's find bar) had the focus until egui // took it away on Escape: that Escape clears the box (leaves the cell as it was, closes the - // bar), not the tool. An open list (a - // clause's Functions) keeps the same keys as a box, those without Ctrl (⌘): Escape closes it. + // bar), not the tool. An open list (a clause's Functions) keeps the same keys as a box, those + // without Ctrl (⌘): Escape closes it. let pass = ctx.cumulative_pass_nr(); let typing = ctx.egui_wants_keyboard_input() || crate::completion::menu_is_open(ctx) diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index dcad1e057c..90965c222e 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -150,15 +150,36 @@ struct Field { } impl Field { + /// Before the field `id` is drawn: what is pasted or typed into it is cut to the most it could + /// take, so a huge clipboard is never laid out in it. How many characters that dropped, for + /// [`Self::written`]. + fn cut_incoming(ui: &egui::Ui, id: egui::Id) -> usize { + if !ui.memory(|m| m.has_focus(id)) { + return 0; + } + ui.input_mut(|i| { + let mut dropped = 0; + for event in &mut i.events { + if let egui::Event::Paste(text) | egui::Event::Text(text) = event + && let Some((end, _)) = text.char_indices().nth(FIELD_MAX) + { + dropped += text.get(end..).map_or(0, |rest| rest.chars().count()); + text.truncate(end); + } + } + dropped + }) + } + /// After any write of the text (typed, pasted or filled from a selection): cut to what the field /// takes, keeping how many characters that left out. Given back, for a notice, as the field /// goes from fitting to cut and whenever a write leaves out more than one character (a paste); /// not for each key typed while it stays over. - fn written(&mut self) -> Option { + fn written(&mut self, dropped: usize) -> Option { let before = self.left_out; - self.left_out = 0; + self.left_out = dropped; if let Some((end, _)) = self.text.char_indices().nth(FIELD_MAX) { - self.left_out = self.text.get(end..).map_or(0, |rest| rest.chars().count()); + self.left_out += self.text.get(end..).map_or(0, |rest| rest.chars().count()); self.text.truncate(end); } (self.left_out > 1 || (before == 0 && self.left_out == 1)).then_some(self.left_out) @@ -387,7 +408,7 @@ pub fn keys(ui: &egui::Ui, box_id: egui::Id, script: &str, bar: &mut Bar) { // The same query keeps what it left out of a longer one. if word && bar.query.text != picked { bar.query.text = picked; - bar.query.written(); + bar.query.written(0); } bar.anchor = a; } @@ -537,6 +558,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } ui.vertical(|ui| { ui.horizontal_wrapped(|ui| { + let dropped = Field::cut_incoming(ui, query_id); let query = ui.add( egui::TextEdit::singleline(&mut bar.query.text) .id(query_id) @@ -559,7 +581,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b } if query.changed() { (bar.scroll, edited) = (true, true); - said.extend(bar.query.written().map(|n| left_out(Which::Find, n))); + said.extend(bar.query.written(dropped).map(|n| left_out(Which::Find, n))); } let shift = ui.input(|i| i.modifiers.shift); if query.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) { @@ -591,6 +613,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b }); if bar.replace_open { ui.horizontal_wrapped(|ui| { + let dropped = Field::cut_incoming(ui, replace_id); let replace = ui.add( egui::TextEdit::singleline(&mut bar.replace.text) .id(replace_id) @@ -602,7 +625,7 @@ pub fn show(ui: &mut egui::Ui, box_id: egui::Id, script: &mut String, running: b ui.add_space(COUNT_WIDTH + GAP); if replace.changed() { edited = true; - said.extend(bar.replace.written().map(|n| left_out(Which::Replace, n))); + said.extend(bar.replace.written(dropped).map(|n| left_out(Which::Replace, n))); } let can = !running && bar.current().is_some(); let wait = tl!("Wait for the run to finish").to_string(); @@ -785,19 +808,40 @@ mod tests { #[test] fn a_field_cuts_what_it_cannot_take_and_says_it_once() { let mut field = Field { text: "é".repeat(FIELD_MAX), ..Field::default() }; - assert_eq!((field.written(), field.left_out), (None, 0), "what fits says nothing"); + assert_eq!((field.written(0), field.left_out), (None, 0), "what fits says nothing"); field.text.push_str("ab"); - assert_eq!((field.written(), field.text.chars().count()), (Some(2), FIELD_MAX)); + assert_eq!((field.written(0), field.text.chars().count()), (Some(2), FIELD_MAX)); field.text.push('c'); - assert_eq!((field.written(), field.left_out), (None, 1), "a key typed while over: the note counts, Messages was told"); + assert_eq!((field.written(0), field.left_out), (None, 1), "a key typed while over: the note counts, Messages was told"); field.text.pop(); - assert_eq!((field.written(), field.left_out), (None, 0), "a change that fits takes the note away"); + assert_eq!((field.written(0), field.left_out), (None, 0), "a change that fits takes the note away"); // The pop left room for one: two more are over again by one. field.text.push_str("cd"); - assert_eq!(field.written(), Some(1), "cut again after fitting: said again"); + assert_eq!(field.written(0), Some(1), "cut again after fitting: said again"); // Another long paste over a field already cut leaves out more than a keystroke does. field.text.push_str(&"x".repeat(30)); - assert_eq!(field.written(), Some(30), "a paste's cut is said, whatever was cut before"); + assert_eq!(field.written(0), Some(30), "a paste's cut is said, whatever was cut before"); + } + + /// A paste bound for a focused field is cut before the field sees it, so none of the rest is + /// ever laid out; one bound elsewhere is left whole. + #[test] + fn a_paste_is_cut_before_the_field_takes_it() { + let (ctx, id) = (egui::Context::default(), egui::Id::unique("field")); + for focused in [true, false] { + let input = egui::RawInput { events: vec![egui::Event::Paste("é".repeat(1000))], ..Default::default() }; + let mut got = None; + let mut frame = ctx.run_ui(input, |ui| { + ui.memory_mut(|m| if focused { m.request_focus(id) } else { m.surrender_focus(id) }); + let dropped = Field::cut_incoming(ui, id); + let kept = + ui.input(|i| i.events.iter().find_map(|e| if let egui::Event::Paste(t) = e { Some(t.chars().count()) } else { None })); + got = Some((dropped, kept)); + }); + // Nothing is painted here: the font textures are let go. + frame.textures_delta.clear(); + assert_eq!(got, Some(if focused { (800, Some(FIELD_MAX)) } else { (0, Some(1000)) }), "focused: {focused}"); + } } #[test] From 89c3889a21d293af2c40411ee153aed86d741bc1 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jorge=20Gregorio=20Rinc=C3=B3n?= Date: Thu, 26 Nov 2026 19:24:11 -0500 Subject: [PATCH 23/23] fix(ui): the Script find's note counts every character a field left out (#2996) A key typed over a field already cut replaced the note's count with 1. It now adds to it; a paste shows its own count, and a write that fits clears it. --- crates/ui-egui/src/scriptfind.rs | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/crates/ui-egui/src/scriptfind.rs b/crates/ui-egui/src/scriptfind.rs index 90965c222e..c85d336736 100644 --- a/crates/ui-egui/src/scriptfind.rs +++ b/crates/ui-egui/src/scriptfind.rs @@ -172,17 +172,18 @@ impl Field { } /// After any write of the text (typed, pasted or filled from a selection): cut to what the field - /// takes, keeping how many characters that left out. Given back, for a notice, as the field - /// goes from fitting to cut and whenever a write leaves out more than one character (a paste); - /// not for each key typed while it stays over. + /// takes, keeping how many characters that left out: a paste's own count, one more for each key + /// typed while the field stays over, none once a write fits. Given back, for a notice, as the + /// field goes from fitting to cut and for each paste; not for those keys. fn written(&mut self, dropped: usize) -> Option { let before = self.left_out; - self.left_out = dropped; + let mut now = dropped; if let Some((end, _)) = self.text.char_indices().nth(FIELD_MAX) { - self.left_out += self.text.get(end..).map_or(0, |rest| rest.chars().count()); + now += self.text.get(end..).map_or(0, |rest| rest.chars().count()); self.text.truncate(end); } - (self.left_out > 1 || (before == 0 && self.left_out == 1)).then_some(self.left_out) + self.left_out = if now == 1 { before + 1 } else { now }; + (now > 1 || (now == 1 && before == 0)).then_some(self.left_out) } } @@ -812,7 +813,7 @@ mod tests { field.text.push_str("ab"); assert_eq!((field.written(0), field.text.chars().count()), (Some(2), FIELD_MAX)); field.text.push('c'); - assert_eq!((field.written(0), field.left_out), (None, 1), "a key typed while over: the note counts, Messages was told"); + assert_eq!((field.written(0), field.left_out), (None, 3), "a key typed while over adds to the note, Messages was told"); field.text.pop(); assert_eq!((field.written(0), field.left_out), (None, 0), "a change that fits takes the note away"); // The pop left room for one: two more are over again by one.