diff --git a/crates/ui-egui/src/completion.rs b/crates/ui-egui/src/completion.rs index 985e8127a0..cfcfdbdc15 100644 --- a/crates/ui-egui/src/completion.rs +++ b/crates/ui-egui/src/completion.rs @@ -99,6 +99,25 @@ fn around(anchor: egui::Rect, size: egui::Vec2, screen: egui::Rect, min: f32, si /// size, the part scrolled out of view included, for `place` to choose a side next frame by what /// it holds, not by what last fit (it would stay on a side too short for it). pub(crate) fn popup(ui: &Ui, id: Id, corner: egui::Pos2, room: f32, content: impl FnOnce(&mut Ui)) -> (egui::Rect, egui::Vec2) { + footed(ui, id, corner, room, content, None::) +} + +/// `popup`, with a `footer` under its content that stays in view while that scrolls. +fn footed( + ui: &Ui, + id: Id, + corner: egui::Pos2, + room: f32, + content: impl FnOnce(&mut Ui), + footer: Option, +) -> (egui::Rect, egui::Vec2) { + // A button as tall as the popup's own style draws it (its text and padding), and the gap. + let under = footer.as_ref().map_or(0.0, |_| { + let style = ui.ctx().global_style(); + let s = &style.spacing; + (ui.text_style_height(&egui::TextStyle::Button) + 2.0 * s.button_padding.y).max(s.interact_size.y) + s.item_spacing.y + }); + let room = (room - under).max(0.0); let area = egui::Area::new(id).order(egui::Order::Foreground).fixed_pos(corner).show(ui.ctx(), |ui| { egui::Frame::popup(ui.style()) .show(ui, |ui| { @@ -107,6 +126,9 @@ pub(crate) fn popup(ui: &Ui, id: Id, corner: egui::Pos2, room: f32, content: imp // it scrolls, as Command Search does (#255). Short content still shrinks it to fit. let out = egui::ScrollArea::vertical().max_height(room).min_scrolled_height(room).auto_shrink([true, true]).show(ui, content); + if let Some(footer) = footer { + footer(ui); + } (out.content_size.y - out.inner_rect.height()).max(0.0) }) .inner @@ -208,12 +230,33 @@ impl Worked { } } +/// A press on a popup floating over a box, which takes the focus from the box once the button +/// is up (a click elsewhere): it goes back to the box then. +#[derive(Clone, Copy, Default)] +struct Press(bool); + +impl Press { + /// Each frame the popup may be pressed: `on`, whether the pointer is over it. + fn give_back(&mut self, ui: &Ui, on: bool, id: Id) { + if on && ui.input(|i| i.pointer.any_pressed()) { + self.0 = true; + ui.ctx().request_repaint(); + } else if self.0 && ui.input(|i| !i.pointer.any_down()) { + self.0 = false; + ui.memory_mut(|m| m.request_focus(id)); + ui.ctx().request_repaint(); + } + } +} + /// Help floating by a box's cursor while it's in something the help is about (a command's /// braces, a function's call), so it stays in view while that is typed: beside the box's panel /// when it has one with room next to it (`beside`), level with the line where that starts, so the /// box stays in view; else by the cursor's line, which it doesn't cover, and anchored sideways at /// where that starts, so it doesn't slide with each key typed. Escape closes it until the cursor -/// leaves what it was about (its key, `K`). +/// leaves what it was about (its key, `K`). Help with a short form, with no room beside the +/// panel, shows that one, with More under it for the whole help and Less to go back (or +/// Ctrl+Shift+Space for either), until the cursor leaves what it was about. #[derive(Clone)] pub(crate) struct Tip { /// What it shows the help about: what Escape acts on. @@ -222,11 +265,17 @@ pub(crate) struct Tip { dismissed: Option, /// Its whole size last frame, scroll aside (`popup`): where it goes. size: Option, + /// What More showed the whole help of. + expanded: Option, + /// With More or Less shown: where the whole popup was drawn and the cursor it was for, to + /// keep it while a press anywhere on it takes the focus from the box. + popup: Option<(egui::Rect, usize)>, + press: Press, } impl Default for Tip { fn default() -> Self { - Self { shown: None, dismissed: None, size: None } + Self { shown: None, dismissed: None, size: None, expanded: None, popup: None, press: Press::default() } } } @@ -236,6 +285,40 @@ impl Tip { self.shown.is_some() } + /// The cursor the help is kept for while its More or Less is pressed: the box may have no + /// focus then, nor a cursor of its own. + pub fn held(&self, ui: &Ui) -> Option { + let (rect, at) = self.popup?; + ui.input(|i| { + let pressed = i.pointer.any_pressed() && i.pointer.interact_pos().is_some_and(|p| rect.contains(p)); + (i.focused && (self.press.0 || pressed)).then_some(at) + }) + } + + /// Before the box (its id `id`) sees the keys, with More or Less shown and the box focused: + /// Ctrl+Shift+Space does what that button does. Whether it did. Read before Ctrl+Space + /// (`Asked::keys`), which takes the key with Shift down too. + pub fn toggle_keys(&mut self, ui: &Ui, id: Id) -> bool { + let shortcut = Modifiers::CTRL | Modifiers::SHIFT; + if self.popup.is_none() || !ui.memory(|m| m.has_focus(id)) || !ui.input_mut(|i| i.consume_key(shortcut, Key::Space)) { + return false; + } + self.toggle(); + true + } + + /// The whole help shown, or the short one again. + fn toggle(&mut self) { + self.expanded = if self.expanded == self.shown { None } else { self.shown.clone() }; + } + + /// Nothing shown: where it goes and its button start over. + fn gone(&mut self) { + self.size = None; + self.popup = None; + self.press = Press::default(); + } + /// Before the box (its id `id`) sees the keys, with the help shown and the box focused: /// Escape closes it (and the box keeps the focus). Whether the keys were its to read. pub fn keys(&mut self, ui: &Ui, id: Id) -> bool { @@ -244,7 +327,8 @@ impl Tip { } if ui.input_mut(|i| i.consume_key(Modifiers::NONE, Key::Escape)) { self.dismissed = self.shown.take(); - self.size = None; + self.expanded = None; + self.gone(); } true } @@ -256,14 +340,18 @@ impl Tip { if here != self.dismissed.as_ref() { self.dismissed = None; } + if here != self.expanded.as_ref() { + self.expanded = None; + } self.shown = None; - self.size = None; + self.gone(); } /// After the box (`out`): the help `found` for the cursor at char `at` (None: no cursor, or /// none to show it by, such as a list open over it), as what it's about and the char where - /// that starts, drawn by `draw` (given the width it takes), `rows` monospace lines high at - /// first guess; beside `pane` (the panel the box is in) with room there, else on side `side` + /// that starts, drawn by `draw` (given the width it takes, and whether to draw it whole: + /// false only when it has a `short` form and no room beside the pane), `rows` monospace lines + /// high at first guess; beside `pane` (the panel the box is in) with room there, else on side `side` /// of the cursor's line when it fits there. Not with the cursor out of the box's view /// (`visible`) or what Escape closed. pub fn show( @@ -277,7 +365,8 @@ impl Tip { rows: usize, side: Side, pane: Option, - draw: impl FnOnce(&mut Ui, f32), + short: bool, + draw: impl FnOnce(&mut Ui, f32, bool), ) { // Out of what Escape closed (in nothing, or straight into something else), it may show // again next time. Only with a cursor to show it by: with none (the window left, text @@ -286,6 +375,9 @@ impl Tip { if at.is_some() && here != self.dismissed.as_ref() { self.dismissed = None; } + if at.is_some() && here != self.expanded.as_ref() { + self.expanded = None; + } let galley_rect = |i: usize| out.galley.pos_from_cursor(CCursor::new(i)).translate(out.galley_pos.to_vec2()); let shown = found.filter(|(k, _)| self.dismissed.as_ref() != Some(k)).and_then(|(k, start)| { let cursor = galley_rect(at?); @@ -295,7 +387,7 @@ impl Tip { }); let Some((anchor, start, k)) = shown else { self.shown = None; - self.size = None; + self.gone(); return; }; let row = ui.text_style_height(&egui::TextStyle::Monospace) + ui.spacing().item_spacing.y + 4.0; @@ -305,11 +397,31 @@ impl Tip { // Beside the pane it's level with the line `start` is on, which stays put as the cursor // moves down a wrapped line; with that line scrolled out over the box, with the box's top. let level = start.translate(egui::vec2(0.0, (visible.top() - start.top()).max(0.0))); - let (corner, width, room) = pane.and_then(|pane| beside(pane, level, size, screen)).unwrap_or_else(|| { + let placed = pane.and_then(|pane| beside(pane, level, size, screen)); + let shortened = short && placed.is_none(); + let whole = !shortened || self.expanded.as_ref() == Some(&k); + let (corner, width, room) = placed.unwrap_or_else(|| { let (corner, room) = place(anchor, size, screen, row * 3.0, side); (corner, width, room) }); - let (_, drawn) = popup(ui, id, corner, room, |ui| draw(ui, width)); + let mut pressed = false; + let footer = shortened.then_some(|ui: &mut Ui| { + let label = if whole { tl!("Less") } else { tl!("More") }; + pressed = ui.button(label).on_hover_text(tl!("Ctrl+Shift+Space")).clicked(); + }); + let (rect, drawn) = footed(ui, id, corner, room, |ui| draw(ui, width, whole), footer); + match at.filter(|_| shortened) { + Some(at) => { + let on = ui.input(|i| i.pointer.interact_pos().is_some_and(|p| rect.contains(p))); + self.press.give_back(ui, on, out.response.response.id); + self.popup = Some((rect, at)); + } + None => { + self.popup = None; + self.press = Press::default(); + } + } + // Placed by a guess or by other help's size: over the line, its bottom edge would sit // off the line until something repaints, so place it again by what it holds now. if drawn != size { @@ -317,6 +429,10 @@ impl Tip { } self.shown = Some(k); self.size = Some(drawn); + if pressed { + self.toggle(); + ui.ctx().request_repaint(); + } } } @@ -369,12 +485,12 @@ pub(crate) struct List { scroll: Scroll, /// Whether the button pressed on the list is still down: egui takes the focus from the box /// when it comes up (a click elsewhere), and it goes back to the box then. - pressed: bool, + pressed: Press, } impl Default for List { fn default() -> Self { - Self { open: None, dismissed: None, drawn: None, pointer_leads: false, scroll: Scroll::default(), pressed: false } + Self { open: None, dismissed: None, drawn: None, pointer_leads: false, scroll: Scroll::default(), pressed: Press::default() } } } @@ -490,7 +606,7 @@ impl List { if !ui.input(|i| i.focused) { self.close(); self.drawn = None; - self.pressed = false; + self.pressed = Press::default(); return None; } // A press on the list: only then does it outlive the box's focus. Pressed this frame @@ -503,12 +619,7 @@ impl List { // clicked was the box's list, so the focus goes back to it, and the list shows again // next frame if there's still something to offer there (more after the item accepted, // or the item that didn't fit). - if on_list && ui.input(|i| i.pointer.any_pressed()) { - self.pressed = true; - } else if self.pressed && ui.input(|i| !i.pointer.any_down()) { - self.pressed = false; - ui.memory_mut(|m| m.request_focus(out.response.response.id)); - } + self.pressed.give_back(ui, on_list, out.response.response.id); let offer = if out.response.response.has_focus() { // A cursor, not a selection: with text selected, Enter and Tab act on it as usual. work(out.cursor_range.filter(|r| r.is_empty()).map(|r| r.primary.index.0)) diff --git a/crates/ui-egui/src/exprcomplete.rs b/crates/ui-egui/src/exprcomplete.rs index edbe2bdef2..b12d65b1ea 100644 --- a/crates/ui-egui/src/exprcomplete.rs +++ b/crates/ui-egui/src/exprcomplete.rs @@ -403,7 +403,7 @@ pub(crate) fn expr_edit_lines( let at = cursor.filter(|_| !state.list.is_open()); // Kept by its `(`, and anchored there; over the line, as under the box are its error and help. let about = call.map(|c| (c.open, c.open)); - state.tip.show(ui, id.with("expr_tip"), &out, visible, at, about, TIP_ROWS, Side::Above, None, |ui, width| { + state.tip.show(ui, id.with("expr_tip"), &out, visible, at, about, TIP_ROWS, Side::Above, None, false, |ui, width, _| { if let Some(call) = &call { draw_call(ui, call, width); } diff --git a/crates/ui-egui/src/scriptcomplete.rs b/crates/ui-egui/src/scriptcomplete.rs index 3b0cfa39b5..133bc1a109 100644 --- a/crates/ui-egui/src/scriptcomplete.rs +++ b/crates/ui-egui/src/scriptcomplete.rs @@ -170,6 +170,10 @@ struct Scan { nested: Option, value: Option<(usize, String, bool)>, values: Vec<(String, String, bool)>, + /// The key of the entry the end is in: at the top level (`entry`), and in a second-level + /// object that is a top-level key's own value (`inner`). + entry: Option, + inner: Option, // Top-level strings and numeric table IDs, in order; command value_of stays string-only. inputs: Vec<(String, serde_json::Value)>, } @@ -196,6 +200,8 @@ fn scan(text: &str) -> Scan { let (mut array, mut nested) = (None::, None::<(Nested, usize)>); let mut values = Vec::new(); let mut inputs = Vec::new(); + // The key being read, with its depth (1 or 2), and the last one read at each. + let (mut keyed, mut last, mut inner) = (None::<(usize, usize)>, None::, None::); for (i, &c) in chars.iter().enumerate() { let was_quoted = q.quoted(); q.read(c); @@ -211,6 +217,7 @@ fn scan(text: &str) -> Scan { } start = None; named = from.take().and_then(|f| chars.get(f..i)).map(|k| k.iter().collect()); + read_key(keyed.take(), chars.get(..i), &mut last, &mut inner); } continue; } @@ -220,6 +227,7 @@ fn scan(text: &str) -> Scan { '"' => { start = (top && entry).then_some(i + 1); from = (depth == 1 && entry).then_some(i + 1); + keyed = (top && entry && depth <= 2).then_some((i + 1, depth)); // A top-level key's value, or one right in its array. value = match (valued.take(), &array) { (Some(key), _) if depth == 1 => Some((i + 1, key, false)), @@ -251,10 +259,19 @@ fn scan(text: &str) -> Scan { } if depth < 2 { array = None; + inner = None; } entry = false; } - ',' => entry = top, + ',' => { + entry = top; + if depth == 1 { + last = None; + } + if depth <= 2 { + inner = None; + } + } ':' => (valued, entry) = (named.take().filter(|_| depth == 1), false), c if c.is_whitespace() => {} _ => { @@ -281,7 +298,21 @@ fn scan(text: &str) -> Scan { } } } - Scan { start, nested: nested.map(|(n, _)| n), value, values, inputs } + read_key(keyed, Some(&chars), &mut last, &mut inner); + Scan { start, nested: nested.map(|(n, _)| n), value, values, entry: last, inner, inputs } +} + +/// Keeps the key read from `keyed` (its start and depth) to the end of `chars`, as the last at its +/// depth. +fn read_key(keyed: Option<(usize, usize)>, chars: Option<&[char]>, last: &mut Option, inner: &mut Option) { + let Some((from, depth)) = keyed else { return }; + let Some(key) = chars.and_then(|c| c.get(from..)) else { return }; + let key = Some(key.iter().collect()); + if depth == 1 { + *last = key; + } else { + *inner = key; + } } /// The line's object from its `{` up to the cursor at char `at` of `script`, read (`scan`), with @@ -391,7 +422,11 @@ fn line_of<'a>(script: &'a str, h: &Hint) -> Option<&'a str> { /// The keys of the parameters `desc` describes, entry by entry, each with its alternatives /// (`"lon" | "x"`), and the entry's text as described. fn entries(desc: &str) -> Vec<(Vec, String)> { - let params = rustgis_engine::param_list(desc).unwrap_or_default(); + with_keys(&rustgis_engine::param_list(desc).unwrap_or_default()) +} + +/// `entries`, of a description already split into its `params`. +fn with_keys(params: &[rustgis_engine::Param]) -> Vec<(Vec, String)> { params .iter() .map(|p| { @@ -1140,7 +1175,7 @@ fn tool_help(t: &rustgis_engine::analysis::ToolSpec) -> Help { keys: signature(t.params.iter().map(|p| (p.name, !p.required))), label: tl!(t.name).to_string(), about: tl!(t.summary).to_string(), - params: t.params.iter().map(param_line).collect(), + params: t.params.iter().map(|p| (vec![p.name.to_string()], param_line(p))).collect(), location: crate::i18n::location(t.toolbox), } } @@ -1156,6 +1191,25 @@ fn help_at(session: &rustgis_engine::Session, script: &str, at: usize, h: &Hint) inner().or_else(|| help(session, &h.id)) } +/// Which of `help`'s parameters the cursor at char `at` of `script` is in, in line `h`'s braces: +/// the entry of the line's object naming the key there, or, with the help of what a `"params"` +/// object runs, of that object. +fn param_here(script: &str, at: usize, h: &Hint, help: &Help) -> Option { + let (from, to) = (byte_at(script, h.brace)?, byte_at(script, at)?); + let mut read = scan(script.get(from..to)?); + // With the cursor in a key, the key whole: read on to its closing quote, when that comes on + // the line before what ends a key left unclosed (another entry's quote isn't its own). + let rest = script.get(to..)?.split('\n').next()?; + if read.start.is_some() + && let Some(end) = rest.find(['"', ',', ':', '}']).filter(|&i| rest.get(i..).is_some_and(|r| r.starts_with('"'))) + { + read = scan(script.get(from..=to + end)?); + } + // As the key's string reads (`"s\u0069ze"` is `size`); an unfinished escape names nothing. + let key = text_of(&(if help.id == h.id { read.entry } else { read.inner })?)?; + help.params.iter().position(|(keys, _)| keys.contains(&key)) +} + /// `script_ids`, kept until the loaded plugins or the session's commands change (the built-in /// commands don't while the app runs; their count tells another session's registry apart). fn script_ids_cached(ui: &Ui, session: &rustgis_engine::Session) -> std::sync::Arc> { @@ -1192,7 +1246,8 @@ pub struct Help { pub keys: String, pub label: String, pub about: String, - pub params: Vec, + /// Each parameter's keys (its alternatives together) and its line. + pub params: Vec<(Vec, String)>, pub location: String, } @@ -1219,7 +1274,7 @@ pub fn help(session: &rustgis_engine::Session, id: &str) -> Option { }; let params = rustgis_engine::param_list(&desc).unwrap_or_default(); let keys = signature(params.iter().map(|p| (p.key, p.optional))); - Some(Help { id: id.to_string(), keys, label, about, params: params.iter().map(|p| p.text.to_string()).collect(), location }) + Some(Help { id: id.to_string(), keys, label, about, params: with_keys(¶ms), location }) } /// The keys after an id in a help's signature, each with `?` when it may be left out @@ -1292,28 +1347,59 @@ fn draw_key_help(ui: &mut Ui, text: &str, about: Option<&str>, width: f32) { }); } -/// Draws `help` beside the list: the signature and parameters coloured as the script is, in its -/// monospace font (smaller for the parameters). -fn draw_help(ui: &mut Ui, help: &Help, width: f32) { +/// A help's `text` coloured as the script is (after command `id`, in its signature), wrapped at +/// `width`. +fn coloured(id: Option<&str>, text: &str, palette: crate::scriptcolor::Palette, font: &egui::FontId, width: f32) -> egui::text::LayoutJob { + let mut job = crate::scriptcolor::help_job(id, text, palette, font); + job.wrap.max_width = width; + job +} + +/// How a command's help is written: the script's colours, its monospace font for the signature, +/// and a smaller one for the parameters. +fn help_style(ui: &Ui) -> (crate::scriptcolor::Palette, egui::FontId, egui::FontId) { let palette = crate::scriptcolor::Palette::of(&crate::theme::Tokens::get(ui.ctx())); let mono = egui::TextStyle::Monospace.resolve(ui.style()); let small = egui::FontId::monospace(mono.size * 0.85); - let coloured = |id: Option<&str>, text: &str, font: &egui::FontId| { - let mut job = crate::scriptcolor::help_job(id, text, palette, font); - job.wrap.max_width = width; - job - }; + (palette, mono, small) +} + +/// The most rows the short form of a help gives the signature, and the parameter's line. +const SHORT_SIGNATURE_ROWS: usize = 2; +const SHORT_PARAM_ROWS: usize = 6; + +/// Draws the short form of `help`: its signature, and the line of parameter `param`. +fn draw_short(ui: &mut Ui, help: &Help, param: Option, width: f32) { + let (palette, mono, small) = help_style(ui); + ui.vertical(|ui| { + ui.set_max_width(width); + // Cut off past a few rows: some commands take over a hundred keys. + let cut = |mut job: egui::text::LayoutJob, rows| { + job.wrap.max_rows = rows; + job + }; + ui.label(cut(coloured(Some(&help.id), &help.keys, palette, &mono, width), SHORT_SIGNATURE_ROWS)); + if let Some((_, text)) = param.and_then(|i| help.params.get(i)) { + ui.label(cut(coloured(None, text, palette, &small, width), SHORT_PARAM_ROWS)); + } + }); +} + +/// Draws `help` beside the list: the signature and parameters coloured as the script is, in its +/// monospace font (smaller for the parameters). +fn draw_help(ui: &mut Ui, help: &Help, width: f32) { + let (palette, mono, small) = help_style(ui); ui.vertical(|ui| { ui.set_max_width(width); - ui.label(coloured(Some(&help.id), &help.keys, &mono)); + ui.label(coloured(Some(&help.id), &help.keys, palette, &mono, width)); ui.label(&help.label); if !help.about.is_empty() { ui.label(egui::RichText::new(&help.about).small()); } if !help.params.is_empty() { ui.add_space(4.0); - for p in &help.params { - ui.label(coloured(None, p, &small)); + for (_, p) in &help.params { + ui.label(coloured(None, p, palette, &small, width)); } } ui.add_space(4.0); @@ -1401,7 +1487,7 @@ struct HintState { /// the command whose braces it's in and where that call's `(` is (a char index of the script). #[derive(Clone)] enum Shown { - Help(Hint, Help), + Help(Hint, Help, Option), Call(Hint, usize, rustgis_engine::data::query::Call), } @@ -1441,6 +1527,11 @@ pub fn close(ui: &Ui, box_id: Id) { /// dropped, not acted on: its word could be elsewhere now. pub fn keys(ui: &Ui, box_id: Id, script: &str) -> Option<(Offer, String)> { let mut state = load(ui, box_id); + // The short help's More and Less, before Ctrl+Space, which would take the key. + if !state.list.is_open() && state.hint.tip.toggle_keys(ui, box_id) { + store(ui, box_id, state); + return None; + } if state.asked.keys(ui, box_id, script) { state.list.reopen(); store(ui, box_id, state); @@ -1558,7 +1649,9 @@ fn rows_key(session: &rustgis_engine::Session, offer: &Offer) -> u64 { pub fn hint(ui: &Ui, box_id: Id, out: &TextEditOutput, visible: egui::Rect, script: &str, session: &rustgis_engine::Session) { let mut state = load(ui, box_id); let focused = out.response.response.has_focus() && ui.input(|i| i.focused); - let at = out.cursor_range.filter(|r| focused && !state.list.is_open() && r.is_empty()).map(|r| r.primary.index.0); + let cursor = out.cursor_range.filter(|r| focused && !state.list.is_open() && r.is_empty()).map(|r| r.primary.index.0); + // While More or Less is pressed, the cursor it was shown for. + let at = state.hint.tip.held(ui).or(cursor); // Its own hash of the script, not the list's: it mustn't depend on how `show` ran this frame. let text = egui::util::hash(script); // The help is translated, a plugin's command comes and goes with its plugin, and an @@ -1574,14 +1667,15 @@ pub fn hint(ui: &Ui, box_id: Id, out: &TextEditOutput, visible: egui::Rect, scri return Some(Shown::Call(h, open, call)); } let help = help_at(session, script, at, &h)?; - Some(Shown::Help(h, help)) + let param = param_here(script, at, &h, &help); + Some(Shown::Help(h, help, param)) }); state.hint.worked = Some(Worked { at, text, with, value: found.clone() }); found } }; let (help, call) = match found { - Some(Shown::Help(h, help)) => (Some((h, help)), None), + Some(Shown::Help(h, help, param)) => (Some((h, help, param)), None), Some(Shown::Call(h, open, call)) => { // In a call its command's help is hidden, not left: what Escape closed of it stays // closed while the cursor is still in that command's braces (`Tip::hide`). @@ -1594,17 +1688,24 @@ pub fn hint(ui: &Ui, box_id: Id, out: &TextEditOutput, visible: egui::Rect, scri // in (what this `ui` is clipped to) with room there, so the script stays in view. let pane = Some(ui.clip_rect()); if call.is_none() { - let rows = help.as_ref().map_or(0, |(_, help)| help.params.len() + 3); - let about = help.as_ref().map(|(h, _)| (h.clone(), h.brace)); - state.hint.tip.show(ui, box_id.with("complete_hint"), out, visible, at, about, rows, Side::Below, pane, |ui, width| { - if let Some((_, help)) = &help { - draw_help(ui, help, width); + let rows = help.as_ref().map_or(0, |(_, help, _)| help.params.len() + 3); + let about = help.as_ref().map(|(h, ..)| (h.clone(), h.brace)); + // With nothing to leave out, there is no short form. + let short = help.as_ref().is_some_and(|(_, help, _)| !help.params.is_empty()); + let id = box_id.with("complete_hint"); + state.hint.tip.show(ui, id, out, visible, at, about, rows, Side::Below, pane, short, |ui, width, whole| { + if let Some((_, help, param)) = &help { + if whole { + draw_help(ui, help, width); + } else { + draw_short(ui, help, *param, width); + } } }); } let about = call.as_ref().map(|(open, _)| (*open, *open)); let rows = crate::exprcomplete::TIP_ROWS; - state.hint.call.show(ui, box_id.with("complete_call"), out, visible, at, about, rows, Side::Below, pane, |ui, width| { + state.hint.call.show(ui, box_id.with("complete_call"), out, visible, at, about, rows, Side::Below, pane, false, |ui, width, _| { if let Some((_, call)) = &call { crate::exprcomplete::draw_call(ui, call, width); } @@ -2365,7 +2466,7 @@ mod tests { let h = super::help(&app.session, "labels.style").unwrap(); assert!(h.keys.starts_with(" {layer?, class?, size?"), "{}", h.keys); assert_eq!(h.label, "Text Symbol"); - assert!(h.params.iter().any(|p| p == r#""size"?: number"#), "{:?}", h.params); + assert!(h.params.iter().any(|(_, p)| p == r#""size"?: number"#), "{:?}", h.params); assert_eq!(h.location, "Labeling › Text Symbol"); // Required keys go bare. assert!(super::help(&app.session, "labels.field").unwrap().keys.contains("field}")); @@ -2930,6 +3031,267 @@ mod tests { assert!(sig.max.x < script.min.x, "beside the pane: {sig:?} {script:?}"); } + /// The parameter line of `key` in command `id`'s description. + fn entry(h: &egui_kittest::Harness<'static, crate::RustGisApp>, id: &str, key: &str) -> String { + let desc = h.state().session.registry.get(id).unwrap().params; + super::entries(desc).into_iter().find(|(keys, _)| keys.iter().any(|k| k == key)).unwrap().1 + } + + fn button(h: &egui_kittest::Harness<'static, crate::RustGisApp>, label: &str) -> bool { + use egui_kittest::kittest::Queryable; + h.query_by_role_and_label(egui::accesskit::Role::Button, label).is_some() + } + + /// Presses and lets go of button `label` over two frames, as a hand does. + fn press(h: &mut egui_kittest::Harness<'static, crate::RustGisApp>, label: &str) { + use egui_kittest::kittest::Queryable; + let pos = h.get_by_role_and_label(egui::accesskit::Role::Button, label).rect().center(); + h.event(egui::Event::PointerMoved(pos)); + h.run(); + for pressed in [true, false] { + h.event(egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed, modifiers: Default::default() }); + h.run(); + } + } + + /// With no room beside the pane, a command's help is short: its signature and More, with the + /// parameter the cursor is in once it's in one (#3535). + #[test] + fn with_no_room_beside_the_help_is_short() { + use egui_kittest::kittest::Queryable; + let mut h = pane(); + let help = super::help(&h.state().session, "map.goToXY").unwrap(); + let sig = format!("{}{}", help.id, help.keys); + let (lat, scale) = (entry(&h, "map.goToXY", "lat"), entry(&h, "map.goToXY", "scale")); + type_in(&mut h, "map.goToXY {"); + let at = h.get_by_label(&sig).rect().left(); + assert!(button(&h, "More")); + assert!(h.query_by_label(&help.label).is_none(), "not the name"); + assert!(h.query_by_label(&lat).is_none() && h.query_by_label(&scale).is_none(), "no parameter before the first key"); + // An alternative key shows its entry. + type_in(&mut h, r#""y": 5"#); + h.get_by_label(&lat); + assert!(h.query_by_label(&scale).is_none(), "only the cursor's"); + type_in(&mut h, ", "); + assert!(h.query_by_label(&lat).is_none(), "past its comma"); + type_in(&mut h, r#""scale": 3"#); + h.get_by_label(&scale); + assert!(h.query_by_label(&lat).is_none()); + assert!((h.get_by_label(&sig).rect().left() - at).abs() < 0.5, "it didn't slide"); + // Back into the first value. + for _ in 0..r#", "scale": 3"#.len() { + h.key_press(egui::Key::ArrowLeft); + h.run(); + } + h.get_by_label(&lat); + assert!(h.query_by_label(&scale).is_none()); + } + + /// A command with a very long signature, or a parameter with a very long line, is cut off in + /// the short help, which stays small; More shows it whole. + #[test] + fn a_long_signature_is_cut_off_in_the_short_help() { + use egui_kittest::kittest::Queryable; + let mut h = pane(); + let help = super::help(&h.state().session, "layout.addElement").unwrap(); + let sig = format!("{}{}", help.id, help.keys); + let kind = entry(&h, "layout.addElement", "kind"); + type_in(&mut h, r#"layout.addElement {"kind": "#); + // In rows of the help's font, whatever its size. + let mono = egui::TextStyle::Monospace.resolve(&h.ctx.global_style()); + let row = h.ctx.fonts_mut(|f| f.row_height(&mono)); + let rows = |n: usize| (n as f32 + 0.5) * row; + let signature = h.get_by_label(&sig).rect().height(); + let line = h.get_by_label(&kind).rect().height(); + assert!(signature < rows(super::SHORT_SIGNATURE_ROWS), "cut off: {signature} in rows of {row}"); + assert!(line < rows(super::SHORT_PARAM_ROWS), "cut off: {line} in rows of {row}"); + press(&mut h, "More"); + assert!(h.get_by_label(&sig).rect().height() > rows(super::SHORT_SIGNATURE_ROWS), "whole"); + } + + /// A button taller than the usual (its padding) has its room under the whole help too: the + /// help stays under the line instead of being pushed up over it. + #[test] + fn a_tall_button_keeps_the_whole_help_under_the_line() { + use egui_kittest::kittest::Queryable; + let mut h = pane(); + h.ctx.all_styles_mut(|s| s.spacing.button_padding.y = 24.0); + let help = super::help(&h.state().session, "layout.addElement").unwrap(); + let sig = format!("{}{}", help.id, help.keys); + type_in(&mut h, "layout.addElement {"); + let short = h.get_by_label(&sig).rect().top(); + press(&mut h, "More"); + let whole = h.get_by_label(&sig).rect().top(); + assert!((whole - short).abs() < 0.5, "still where it was: {whole}, short at {short}"); + } + + /// In a second-level object the line is its top-level key's, not that of a key of the same + /// name; in a `gp.run` line's `"params"`, the tool's parameter. + #[test] + fn the_short_helps_parameter_in_a_second_level_object() { + use egui_kittest::kittest::Queryable; + let mut h = pane(); + let params = entry(&h, "gp.run", "params"); + let tool = entry(&h, "gp.run", "tool"); + type_in(&mut h, r#"gp.run {"params": {"tool": 1"#); + h.get_by_label(¶ms); + assert!(h.query_by_label(&tool).is_none()); + let mut h = pane(); + let buffer = rustgis_engine::analysis::tool("buffer").unwrap(); + let line = super::param_line(buffer.params.iter().find(|p| p.name == "distance").unwrap()); + type_in(&mut h, r#"gp.run {"tool": "buffer", "params": {"distance": 5"#); + h.get_by_label(&line); + assert!(h.query_by_label(¶ms).is_none()); + } + + /// With the cursor inside a key already written, the line is that key's, not one named by what + /// comes before the cursor (`"halo|Color"` isn't `halo`), at the top level and in `"params"`. + #[test] + fn the_short_helps_parameter_is_the_whole_key_under_the_cursor() { + let app = crate::RustGisApp::with_sample(); + for (script, key) in [ + (r##"labels.style {"haloColor": "#ffffff"}"##, "haloColor"), + (r#"map.goToXY {"lat": 5, "lon": 2}"#, "lat"), + (r#"gp.run {"tool": "buffer", "params": {"distance": 5}}"#, "distance"), + ] { + let from = script.find(&format!("\"{key}\"")).unwrap() + 1; + for at in from..=from + key.len() { + let h = super::hint_at(script, at).unwrap(); + let help = super::help_at(&app.session, script, at, &h).unwrap(); + let param = super::param_here(script, at, &h, &help).map(|i| &help.params[i].0); + assert!(param.is_some_and(|keys| keys.iter().any(|k| k == key)), "{key} at {at}: {param:?}"); + } + } + } + + /// A key with no closing quote is read up to the cursor: another entry's quote doesn't close + /// it. + #[test] + fn the_short_helps_parameter_in_an_unclosed_key_before_another() { + let app = crate::RustGisApp::with_sample(); + for script in [r#"map.goToXY {"lat, "scale": 3}"#, r#"map.goToXY {"lat: 5, "scale": 3}"#, r#"map.goToXY {"lat} "x""#] { + let at = script.find("lat").unwrap() + "lat".len(); + let h = super::hint_at(script, at).unwrap(); + let help = super::help_at(&app.session, script, at, &h).unwrap(); + let param = super::param_here(script, at, &h, &help).map(|i| &help.params[i].0); + assert!(param.is_some_and(|keys| keys.iter().any(|k| k == "lat")), "{script}: {param:?}"); + } + } + + /// A key written with a JSON escape names what the escape reads as (`"s\u0069ze"` is `size`). + #[test] + fn the_short_helps_parameter_reads_the_escapes_of_a_key() { + let app = crate::RustGisApp::with_sample(); + let script = r#"labels.style {"s\u0069ze": 12"#; + let at = script.chars().count(); + let h = super::hint_at(script, at).unwrap(); + let help = super::help_at(&app.session, script, at, &h).unwrap(); + let param = super::param_here(script, at, &h, &help).map(|i| &help.params[i].0); + assert!(param.is_some_and(|keys| keys.iter().any(|k| k == "size")), "{param:?}"); + // An escape left unfinished names nothing, and doesn't panic. + let script = r#"labels.style {"s\u00": 12"#; + let h = super::hint_at(script, script.chars().count()).unwrap(); + let help = super::help_at(&app.session, script, script.chars().count(), &h).unwrap(); + assert!(super::param_here(script, script.chars().count(), &h, &help).is_none()); + } + + /// More shows the whole help and Less the short one again, the script keeping the focus; it + /// stays whole in the same braces, and is short again in the next ones. + #[test] + fn more_shows_the_whole_help_and_less_the_short_one() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut h = pane(); + let help = super::help(&h.state().session, "map.goToXY").unwrap(); + let scale = entry(&h, "map.goToXY", "scale"); + type_in(&mut h, "map.goToXY {"); + press(&mut h, "More"); + h.get_by_label(&help.label); + h.get_by_label(&scale); + assert!(h.get_by_role(Role::MultilineTextInput).is_focused(), "the script keeps the focus"); + type_in(&mut h, r#""lat": 5"#); + assert_eq!(h.state().workflow.script, r#"map.goToXY {"lat": 5"#, "and the cursor"); + h.get_by_label(&help.label); + press(&mut h, "Less"); + assert!(h.query_by_label(&help.label).is_none(), "short again"); + assert!(button(&h, "More") && !button(&h, "Less")); + assert!(h.get_by_role(Role::MultilineTextInput).is_focused()); + // A quick click, in one frame. + h.get_by_role_and_label(Role::Button, "More").click(); + h.run(); + h.get_by_label(&help.label); + // Out of the braces, then in the next ones. + h.key_press(egui::Key::End); + h.run(); + type_in(&mut h, "\nmap.goToXY {"); + assert!(button(&h, "More") && h.query_by_label(&help.label).is_none(), "short in the next braces"); + // Escape closes it whole too, and it comes back short. + press(&mut h, "More"); + h.key_press(egui::Key::Escape); + h.run(); + assert!(!button(&h, "Less"), "closed"); + h.key_press(egui::Key::End); + h.run(); + type_in(&mut h, "\nmap.goToXY {"); + assert!(button(&h, "More"), "short"); + } + + /// Ctrl+Shift+Space does what More and Less do, from the keyboard (#3535); Ctrl+Space still + /// asks for the list. + #[test] + fn ctrl_shift_space_shows_the_whole_help_and_the_short_one() { + use egui::accesskit::Role; + use egui_kittest::kittest::Queryable; + let mut h = pane(); + let help = super::help(&h.state().session, "map.goToXY").unwrap(); + type_in(&mut h, "map.goToXY {"); + for whole in [true, false] { + h.key_press_modifiers(egui::Modifiers::CTRL | egui::Modifiers::SHIFT, egui::Key::Space); + h.run(); + assert_eq!(h.query_by_label(&help.label).is_some(), whole); + assert!(button(&h, if whole { "Less" } else { "More" }), "no list in its place"); + assert!(h.get_by_role(Role::MultilineTextInput).is_focused()); + } + assert_eq!(h.state().workflow.script, "map.goToXY {", "nothing typed"); + h.key_press_modifiers(egui::Modifiers::CTRL, egui::Key::Space); + h.run(); + assert!(h.query_by_label(&help.label).is_none() && !button(&h, "Less"), "Ctrl+Space alone leaves it short"); + } + + /// A command with no parameters has nothing to leave out: its help whole, with no button. + #[test] + fn a_help_with_no_parameters_is_whole() { + use egui_kittest::kittest::Queryable; + let mut h = pane(); + let help = super::help(&h.state().session, "map.zoomFull").unwrap(); + assert!(help.params.is_empty()); + type_in(&mut h, "map.zoomFull {"); + h.get_by_label(&help.label); + assert!(!button(&h, "More")); + } + + /// With room beside the pane the help is whole, with no button; a function's signature has + /// none either. + #[test] + fn only_a_help_with_no_room_is_short() { + use egui_kittest::kittest::Queryable; + let mut h = docked(false, "map.goToXY {"); + let help = super::help(&h.state().session, "map.goToXY").unwrap(); + h.get_by_label(&help.label); + assert!(!button(&h, "More") && !button(&h, "Less")); + h.set_size(egui::vec2(500.0, 700.0)); + h.run(); + assert!(button(&h, "More") && h.query_by_label(&help.label).is_none(), "narrowed: short"); + h.set_size(egui::vec2(1200.0, 700.0)); + h.run(); + h.get_by_label(&help.label); + assert!(!button(&h, "More"), "widened: whole, beside"); + let mut h = pane(); + type_in(&mut h, r#"select.byAttributes {"layer": "Countries", "where": "round(pop_est, "#); + h.get_by_role_and_label(egui::accesskit::Role::Label, "round(x[, places])"); + assert!(!button(&h, "More")); + } + /// A command's help closed with Escape stays closed through a call in its expression: the /// signature shows in the call, and out of it the help doesn't come back, as the cursor never /// left the braces. A call in another command's braces is leaving them. diff --git a/docs/user-guide/analysis.md b/docs/user-guide/analysis.md index 41b74ff103..7c5039a8e7 100644 --- a/docs/user-guide/analysis.md +++ b/docs/user-guide/analysis.md @@ -1907,10 +1907,13 @@ Accepting a command on a line of its own adds its braces: with its required keys values, the cursor at the first (`map.goToXY {"lon": , "lat": }`), or empty with the cursor inside when every key may be left out; a command with no parameters gets none, and a line that has parameters keeps them. While you type a command's parameters (the cursor inside its `{…}`), the same -help shows beside the Script pane, level with the line, so the script stays in view (with no room on -either side, by the cursor); Escape closes it. A quote that starts a key in a command's braces opens -the list of its keys not -given yet, beside the highlighted key's description; accepting one closes it with its colon +help shows beside the Script pane, level with the line, so the script stays in view. With no room on +either side it shows by the cursor, short: the signature, cut off past two lines, and the parameter +the cursor is in, with **More** for the whole help and **Less** to go back (Ctrl+Shift+Space does +either; on macOS too it is the Ctrl key); a command with no parameters keeps its whole help, with +no button. Escape closes it. A quote that starts a key in a command's +braces opens the list of its keys not given yet, beside the highlighted key's description; accepting +one closes it with its colon (`"size": `). The same goes in a key's own object, or in each object of its list, for the keys the command's description gives it (`topology.rules {"add": {"rule": …}}`). In a `gp.run` line, a quote after `"tool": ` opens the list of the tools, beside the highlighted tool's help; accepting