diff --git a/CHANGELOG.md b/CHANGELOG.md index 67e68cbc..5773cde6 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -11,6 +11,9 @@ How to write it (see AGENTS.md): ## Unreleased +### New +- The command line's AutoComplete learns which commands you use: the ones you run most, and most recently, move up the list, so typing LI soon offers LINE first if you draw lines more than you list. The arrow keys move through the suggestions, and Reset Suggestion Order in the command line's right-click menu forgets what was learned. + ### Improved - The Workspace button on the status bar opens a menu of the workspaces, as on Windows, with the current one checked. - The workspace menus show 3D Modeling greyed out, with a note that 3D solids are not available in this build yet. diff --git a/crates/ui-egui/src/cmd_usage.rs b/crates/ui-egui/src/cmd_usage.rs new file mode 100644 index 00000000..39dd1bc0 --- /dev/null +++ b/crates/ui-egui/src/cmd_usage.rs @@ -0,0 +1,284 @@ +//! Adaptive AutoComplete: the command line learns which commands its user runs and lists the +//! ones used most, and most recently, first (as AutoCAD's adaptive suggestions and the fish +//! shell do), without any alias editing. +//! +//! Each command run from the command line adds one to its score. Scores fade with use, not with +//! time: every later command run counts one tick of a clock, and a score halves every +//! [`HALF_LIFE`] ticks. So a command used often lately ranks above one used often long ago, a +//! weekend away changes nothing, and the result depends only on what was run, in what order +//! (deterministic, and the same on the web). +//! +//! The counts are kept with the interface preferences ([`crate::CadApp::prefs_json`]); what is +//! loaded back is treated as hostile: malformed entries are dropped and everything is capped. + +use std::collections::BTreeMap; + +use serde_json::{Map, Value, json}; + +/// A score halves after this many later command runs. +pub const HALF_LIFE: f64 = 300.0; +/// The most commands remembered; the lowest scores go first. +pub const MAX_ENTRIES: usize = 200; +/// The highest score kept. Steady use of one command alone tends to about `HALF_LIFE / ln 2` +/// (≈ 433), so this only bounds what a stored file claims. +pub const MAX_SCORE: f64 = 1000.0; +/// What an exactly typed alias is worth in the ranking, in uses: another command matching the +/// same letters lists above it (and Enter runs it) once its score is higher than this. +pub const EXACT_ALIAS_BONUS: f64 = 3.0; +/// The clock is rebased before it reaches this, so ages always stay exact in an `f64`. +const MAX_CLOCK: u64 = 1 << 40; +/// The longest command id kept (the longest real id is far shorter). +const MAX_ID_LEN: usize = 64; +/// The most entries read from stored preferences before the rest are ignored. +const MAX_LOADED: usize = MAX_ENTRIES * 4; + +#[derive(Clone, Copy, Debug, PartialEq)] +struct Entry { + /// The score as of `at`. + score: f64, + /// The clock when the command was last run. + at: u64, +} + +/// What the command line has learned about its user's commands. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct Usage { + /// Command runs recorded so far (since the last rebase). + clock: u64, + /// Command id (lower case) → its score. + entries: BTreeMap, +} + +/// `score` after `age` later command runs: halved every [`HALF_LIFE`] runs. +pub fn decayed(score: f64, age: u64) -> f64 { + if !score.is_finite() || score <= 0.0 { + return 0.0; + } + score * 0.5f64.powf(age as f64 / HALF_LIFE) +} + +/// The order of items with these `weights`: highest first; equal weights keep their order. +pub fn rank(weights: &[f64]) -> Vec { + let mut order: Vec = (0..weights.len()).collect(); + let w = |i: usize| weights.get(i).copied().filter(|w| !w.is_nan()).unwrap_or(0.0); + order.sort_by(|&a, &b| w(b).total_cmp(&w(a))); + order +} + +/// Whether `id` looks like a command id worth keeping. +fn valid_id(id: &str) -> bool { + !id.is_empty() && id.len() <= MAX_ID_LEN && id.bytes().all(|b| b.is_ascii_alphanumeric() || b"._-+".contains(&b)) +} + +impl Usage { + /// Nothing learned yet. + pub fn is_empty(&self) -> bool { + self.entries.is_empty() + } + + /// How many commands are remembered. + pub fn len(&self) -> usize { + self.entries.len() + } + + /// Forget everything learned. + pub fn clear(&mut self) { + *self = Self::default(); + } + + /// `id`'s score now (0 for a command never run). + pub fn score(&self, id: &str) -> f64 { + let id = id.to_ascii_lowercase(); + self.entries.get(&id).map_or(0.0, |e| decayed(e.score, self.clock.saturating_sub(e.at))) + } + + /// The command `id` was run from the command line. + pub fn record(&mut self, id: &str) { + let id = id.to_ascii_lowercase(); + if !valid_id(&id) { + return; + } + if self.clock >= MAX_CLOCK { + self.rebase(); + } + let now = self.clock; + let before = self.score(&id); + self.entries.insert(id, Entry { score: (before + 1.0).min(MAX_SCORE), at: now }); + self.clock = now.saturating_add(1); + self.prune(); + } + + /// Bring every score to now and restart the clock at zero. + fn rebase(&mut self) { + let clock = self.clock; + for e in self.entries.values_mut() { + e.score = decayed(e.score, clock.saturating_sub(e.at)); + e.at = 0; + } + self.clock = 0; + } + + /// Drop the lowest scores until at most [`MAX_ENTRIES`] remain. + fn prune(&mut self) { + while self.entries.len() > MAX_ENTRIES { + let lowest = self + .entries + .iter() + .map(|(id, e)| (id, decayed(e.score, self.clock.saturating_sub(e.at)))) + .min_by(|a, b| a.1.total_cmp(&b.1)) + .map(|(id, _)| id.clone()); + match lowest { + Some(id) => self.entries.remove(&id), + None => break, + }; + } + } + + /// The learned scores as JSON for the preferences: `{"clock": n, "commands": {"line": [score, at]}}`. + pub fn to_json(&self) -> Value { + let commands: Map = self.entries.iter().map(|(id, e)| (id.clone(), json!([e.score, e.at]))).collect(); + json!({ "clock": self.clock, "commands": commands }) + } + + /// Read what [`Self::to_json`] wrote. Hostile input is expected: a malformed whole gives + /// nothing learned, a malformed entry is skipped, and the sizes are capped. + pub fn from_json(v: &Value) -> Self { + let mut out = Self::default(); + let Some(clock) = v.get("clock").and_then(Value::as_u64).filter(|c| *c <= MAX_CLOCK) else { return out }; + let Some(commands) = v.get("commands").and_then(Value::as_object) else { return out }; + out.clock = clock; + for (id, e) in commands.iter().take(MAX_LOADED) { + let id = id.to_ascii_lowercase(); + let score = e.get(0).and_then(Value::as_f64).filter(|s| s.is_finite() && *s > 0.0 && *s <= MAX_SCORE); + let at = e.get(1).and_then(Value::as_u64).filter(|at| *at <= clock); + if let (true, Some(score), Some(at)) = (valid_id(&id), score, at) { + out.entries.insert(id, Entry { score, at }); + } + } + out.prune(); + out + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_score_halves_every_half_life_and_never_goes_negative() { + assert_eq!(decayed(4.0, 0), 4.0); + assert!((decayed(4.0, HALF_LIFE as u64) - 2.0).abs() < 1e-9); + assert!((decayed(4.0, 2 * HALF_LIFE as u64) - 1.0).abs() < 1e-9); + assert_eq!(decayed(-1.0, 3), 0.0); + assert_eq!(decayed(f64::NAN, 3), 0.0); + assert_eq!(decayed(f64::INFINITY, 3), 0.0); + assert!(decayed(MAX_SCORE, u64::MAX) >= 0.0); + } + + #[test] + fn ranking_is_by_weight_and_ties_keep_their_order() { + assert_eq!(rank(&[0.0, 0.0, 0.0]), vec![0, 1, 2]); + assert_eq!(rank(&[1.0, 3.0, 1.0, 2.0]), vec![1, 3, 0, 2]); + assert_eq!(rank(&[f64::NAN, 1.0]), vec![1, 0]); + assert_eq!(rank(&[f64::INFINITY, 5.0]), vec![0, 1]); + assert!(rank(&[]).is_empty()); + } + + #[test] + fn recent_use_outranks_old_use() { + let mut u = Usage::default(); + for _ in 0..5 { + u.record("list"); + } + for _ in 0..5 { + u.record("line"); + } + // Same count, but LINE is more recent. + assert!(u.score("line") > u.score("list")); + assert!(u.score("LINE") > 4.9, "ids are case-insensitive"); + // Many other commands later, LIST's five old uses have faded below one fresh use. + for _ in 0..(3 * HALF_LIFE as usize) { + u.record("pan"); + } + u.record("erase"); + assert!(u.score("list") < u.score("erase"), "{} < {}", u.score("list"), u.score("erase")); + assert_eq!(u.score("never"), 0.0); + } + + #[test] + fn sizes_and_scores_are_capped() { + let mut u = Usage::default(); + for i in 0..(MAX_ENTRIES + 50) { + u.record(&format!("cmd{i}")); + } + assert_eq!(u.len(), MAX_ENTRIES); + // The oldest were the ones dropped. + assert_eq!(u.score("cmd0"), 0.0); + assert!(u.score(&format!("cmd{}", MAX_ENTRIES + 49)) > 0.0); + let mut one = Usage::default(); + for _ in 0..5000 { + one.record("line"); + } + assert!(one.score("line") <= MAX_SCORE); + // Ids that are no command id are not kept. + let mut bad = Usage::default(); + bad.record(""); + bad.record(&"x".repeat(MAX_ID_LEN + 1)); + bad.record("line; rm"); + assert!(bad.is_empty()); + } + + #[test] + fn the_clock_is_rebased_without_changing_scores() { + let mut u = Usage { clock: MAX_CLOCK, entries: BTreeMap::new() }; + u.entries.insert("line".into(), Entry { score: 8.0, at: MAX_CLOCK - HALF_LIFE as u64 }); + let before = u.score("line"); + u.record("list"); + assert!(u.clock < 10); + assert!((u.score("line") - before).abs() < 0.1, "{} vs {before}", u.score("line")); + } + + #[test] + fn learned_scores_survive_a_round_trip() { + let mut u = Usage::default(); + for id in ["line", "line", "circle", "list"] { + u.record(id); + } + let back = Usage::from_json(&u.to_json()); + assert_eq!(back, u); + let mut cleared = back; + cleared.clear(); + assert!(cleared.is_empty()); + } + + #[test] + fn corrupt_stored_values_are_ignored() { + let good = |v: Value| Usage::from_json(&v); + // Not the expected shape at all. + for v in [json!(null), json!("line"), json!([1, 2]), json!({"clock": -1, "commands": {}}), json!({"clock": 3})] { + assert!(good(v).is_empty()); + } + assert!(good(json!({"clock": u64::MAX, "commands": {"line": [1.0, 0]}})).is_empty()); + // Malformed entries are dropped, good ones kept. + let u = good(json!({ + "clock": 10, + "commands": { + "line": [4.0, 9], + "list": ["many", 1], + "copy": [1e300, 1], + "move": [-2.0, 1], + "pan": [1.0, 11], + "erase": [1.0], + "trim": {"score": 1}, + "bad id!": [1.0, 1], + "": [1.0, 1] + } + })); + assert_eq!(u.len(), 1); + assert!(u.score("line") > 3.9); + // A stored file listing far too many commands keeps only the best. + let many: Map = (0..5000).map(|i| (format!("c{i:05}"), json!([1.0 + f64::from(i) / 10000.0, 0]))).collect(); + let u = good(json!({"clock": 1, "commands": many})); + assert_eq!(u.len(), MAX_ENTRIES); + } +} diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index 5b6ffb6c..f8eb9aa0 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -49,6 +49,12 @@ pub struct CmdLine { active_at: f64, /// How much of the inline history shows (1 = all, 0 = faded away): it fades when idle. lines_alpha: f32, + /// What the command line learned about the commands run from it: AutoComplete lists the + /// ones used most, and most recently, first ([`crate::cmd_usage`]). + pub usage: crate::cmd_usage::Usage, + /// The AutoComplete row the arrows moved to (0 = the first) and the text it was chosen for: + /// typing anything else goes back to the first row. + highlight: (usize, String), } /// The most history lines the command line shows above its bar. @@ -112,8 +118,8 @@ fn tab(app: &mut CadApp) { { // Both values typed: Tab locks the second one as well. app.cmd.locked_second = Some(app.cmd.buffer.clone()); - } else if let Some(s) = suggestions(&app.cmd.buffer).first() { - app.cmd.buffer = s.id.clone(); + } else if let Some(s) = highlighted(app) { + app.cmd.buffer = s.id; } } @@ -128,24 +134,47 @@ pub struct Suggestion { pub label: &'static str, } -/// Matching command names/aliases for AutoComplete. -fn suggestions(prefix: &str) -> Vec { +/// The most AutoComplete suggestions listed. +const MAX_SUGGESTIONS: usize = 8; + +/// Matching command names/aliases for AutoComplete, the commands used most (`usage`) first. +/// +/// Without anything learned the order is: the exact alias or command name, then commands whose +/// name starts with `prefix` (shortest first), then commands with an alias starting with it. Learned +/// scores then move commands up; an exactly typed command name always stays first, and an exactly +/// typed alias counts as [`crate::cmd_usage::EXACT_ALIAS_BONUS`] uses, so a few stray uses of +/// another command do not take its place. +pub fn suggestions(prefix: &str, usage: &crate::cmd_usage::Usage) -> Vec { + let found = matches(prefix); + let p = prefix.to_ascii_lowercase(); + let weights: Vec = found + .iter() + .enumerate() + .map(|(i, (s, exact))| match (i, exact) { + (0, true) if s.id.eq_ignore_ascii_case(&p) => f64::INFINITY, + (0, true) => usage.score(&s.id) + crate::cmd_usage::EXACT_ALIAS_BONUS, + _ => usage.score(&s.id), + }) + .collect(); + let mut found: Vec> = found.into_iter().map(|(s, _)| Some(s)).collect(); + crate::cmd_usage::rank(&weights).into_iter().filter_map(|i| found.get_mut(i).and_then(Option::take)).take(MAX_SUGGESTIONS).collect() +} + +/// Every command matching `prefix`, in the unlearned order; `true` marks the exact match. +fn matches(prefix: &str) -> Vec<(Suggestion, bool)> { if prefix.is_empty() || prefix.contains(' ') { return Vec::new(); } let p = prefix.to_ascii_lowercase(); - let mut out: Vec = Vec::new(); + let mut out: Vec<(Suggestion, bool)> = Vec::new(); let mut seen_ids: HashSet<&'static str> = HashSet::new(); // 1. Exact match: alias resolution or exact command name match. - let resolved = draftcraft_engine::cmd::resolve_alias(&p); - if let Some(spec) = draftcraft_engine::cmd::find_command(&resolved) - && !spec.id.contains('.') - { + if let Some(spec) = exact_command(&p) { let display = if spec.id == p { spec.id.to_ascii_uppercase() } else { format!("{} ({})", p.to_ascii_uppercase(), spec.id.to_ascii_uppercase()) }; - out.push(Suggestion { id: spec.id.to_ascii_uppercase(), display, label: spec.label }); + out.push((Suggestion { id: spec.id.to_ascii_uppercase(), display, label: spec.label }, true)); seen_ids.insert(spec.id); } @@ -154,7 +183,7 @@ fn suggestions(prefix: &str) -> Vec { draftcraft_engine::command_specs().iter().filter(|c| !c.id.contains('.') && !seen_ids.contains(c.id) && c.id.starts_with(&p)).collect(); id_matches.sort_by_key(|c| (c.id.len(), c.id)); for c in id_matches { - out.push(Suggestion { id: c.id.to_ascii_uppercase(), display: c.id.to_ascii_uppercase(), label: c.label }); + out.push((Suggestion { id: c.id.to_ascii_uppercase(), display: c.id.to_ascii_uppercase(), label: c.label }, false)); seen_ids.insert(c.id); } @@ -172,18 +201,64 @@ fn suggestions(prefix: &str) -> Vec { alias_matches.sort_by_key(|(alias, c)| (alias.len(), *alias, c.id)); for (alias, c) in alias_matches { if seen_ids.insert(c.id) { - out.push(Suggestion { - id: c.id.to_ascii_uppercase(), - display: format!("{} ({})", alias.to_ascii_uppercase(), c.id.to_ascii_uppercase()), - label: c.label, - }); + out.push(( + Suggestion { + id: c.id.to_ascii_uppercase(), + display: format!("{} ({})", alias.to_ascii_uppercase(), c.id.to_ascii_uppercase()), + label: c.label, + }, + false, + )); } } - - out.truncate(8); out } +/// The command a typed word names exactly, as an alias or by its name. +fn exact_command(word: &str) -> Option<&'static draftcraft_engine::CommandSpec> { + let p = word.to_ascii_lowercase(); + let resolved = draftcraft_engine::cmd::resolve_alias(&p); + draftcraft_engine::cmd::find_command(&resolved).filter(|spec| !spec.id.contains('.')) +} + +/// The AutoComplete list for what is typed now (none while a command prompts). +fn current_suggestions(app: &CadApp) -> Vec { + if app.session.prompting() { Vec::new() } else { suggestions(&app.cmd.buffer, &app.cmd.usage) } +} + +/// Which AutoComplete row is highlighted: the one the arrows moved to for this text, else the first. +fn highlight_index(app: &CadApp, len: usize) -> usize { + let (i, text) = &app.cmd.highlight; + if *text == app.cmd.buffer && *i < len { *i } else { 0 } +} + +/// The highlighted AutoComplete suggestion: what Tab completes and Enter runs. +fn highlighted(app: &CadApp) -> Option { + let mut sug = suggestions(&app.cmd.buffer, &app.cmd.usage); + let i = highlight_index(app, sug.len()); + (i < sug.len()).then(|| sug.swap_remove(i)) +} + +/// Move the AutoComplete highlight by `step` rows. `false` when there is no list to move in, or +/// Up is pressed on the first row (the arrows then browse the command history as before). +fn suggestion_key(app: &mut CadApp, step: isize) -> bool { + if app.cmd.history_pos.is_some() { + return false; + } + let n = current_suggestions(app).len(); + if n == 0 { + return false; + } + let i = highlight_index(app, n); + let next = match i.checked_add_signed(step) { + Some(next) if next < n => next, + Some(_) => n - 1, + None => return false, + }; + app.cmd.highlight = (next, app.cmd.buffer.clone()); + true +} + impl CmdLine { /// Track the selection: a new selection starts with nothing typed since. pub fn watch_selection(&mut self, sel: &[draftcraft_doc::Handle]) { @@ -389,6 +464,8 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) { app.cmd.buffer.pop(); } } + Key::ArrowUp if !modifiers.any() && suggestion_key(app, -1) => {} + Key::ArrowDown if !modifiers.any() && suggestion_key(app, 1) => {} Key::ArrowUp if !modifiers.any() && !app.cmd.history.is_empty() => { let n = app.cmd.history.len(); let pos = app.cmd.history_pos.map(|p| p.saturating_sub(1)).unwrap_or(n - 1); @@ -453,9 +530,36 @@ pub fn submit(app: &mut CadApp) { } return; } - // A partly typed command name runs the highlighted (first) AutoComplete suggestion. - let completion = if app.session.prompting() { None } else { suggestions(text.trim()).into_iter().next() }; - app.cmdline_or(&text, completion.map(|s| s.id.to_ascii_lowercase()).as_deref()); + if app.session.prompting() { + app.cmdline(&text); + return; + } + // The highlighted AutoComplete suggestion: the first one, or the one the arrows moved to. + let word = text.trim(); + let mut sug = suggestions(word, &app.cmd.usage); + // (The buffer is taken by now: the highlight is checked against the text it held.) + let chosen = match &app.cmd.highlight { + (i, was) if *was == text && *i < sug.len() => *i, + _ => 0, + }; + let top = (chosen < sug.len()).then(|| sug.swap_remove(chosen)); + app.cmd.highlight = (0, String::new()); + let typed = exact_command(text.split_whitespace().next().unwrap_or("")); + // A suggestion the arrows moved to, or one the learned ranking put above the alias typed + // exactly, is what Enter runs; a partly typed command name runs the highlighted suggestion. + let picked = top.as_ref().filter(|s| chosen > 0 || typed.is_some_and(|c| !c.id.eq_ignore_ascii_case(&s.id))).map(|s| s.id.to_ascii_lowercase()); + let fallback = top.map(|s| s.id.to_ascii_lowercase()); + let ran = match picked { + Some(id) => app.cmdline(&id).is_none().then_some(id), + None => match app.cmdline_or_ran(&text, fallback.as_deref()) { + Ok(true) => fallback, + Ok(false) => typed.map(|c| c.id.to_string()), + Err(_) => None, + }, + }; + if let Some(id) = ran { + app.cmd.usage.record(&id); + } } fn visible_lines(app: &CadApp, canvas: Rect, bar: Rect) -> usize { @@ -641,7 +745,8 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { ); // AutoComplete list. if !app.session.prompting() { - let sug = suggestions(&app.cmd.buffer); + let sug = current_suggestions(app); + let lit = highlight_index(app, sug.len()); if !sug.is_empty() { let rh = 20.0; let lr = Rect::from_min_size( @@ -653,7 +758,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { for (i, s) in sug.iter().enumerate() { let r = Rect::from_min_size(pos2(lr.left(), lr.top() + rh * i as f32), vec2(lr.width(), rh)); let resp = ui.interact(r, ui.scope_id().with(("sug", i)), Sense::click()); - if resp.hovered() || i == 0 { + if resp.hovered() || i == lit { p.rect_filled(r.shrink(1.0), 2.0, if resp.hovered() { t.cmd_keyword_hover } else { t.list_row }); } p.text(Pos2::new(r.left() + 8.0, r.center().y), egui::Align2::LEFT_CENTER, &s.display, crate::theme::body(), t.text); @@ -666,7 +771,9 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { ); if resp.clicked() { app.cmd.buffer.clear(); - app.start(&s.id.to_ascii_lowercase()); + let id = s.id.to_ascii_lowercase(); + app.start(&id); + app.cmd.usage.record(&id); } } } @@ -703,7 +810,7 @@ fn zones(app: &CadApp, canvas: Rect, bar: Rect) -> Zones { let grip = Rect::from_min_max(pos2(bar.left(), top - 3.0), pos2(bar.right(), top + 3.0)); let mut all = bar.union(grip); if !app.session.prompting() { - let k = suggestions(&app.cmd.buffer).len(); + let k = current_suggestions(app).len(); if k > 0 { all = all.union(Rect::from_min_size(pos2(bar.left(), bar.top() - 6.0 - 20.0 * k as f32 - above), vec2(bar.width(), 1.0))); } @@ -1030,7 +1137,7 @@ mod autocomplete_tests { #[test] fn exact_alias_is_first_suggestion_with_alias_display() { - let rec = suggestions("rec"); + let rec = suggestions("rec", &Default::default()); assert!(!rec.is_empty()); assert_eq!(rec[0].id, "RECTANG"); assert_eq!(rec[0].display, "REC (RECTANG)"); @@ -1040,26 +1147,26 @@ mod autocomplete_tests { assert_eq!(rec[1].id, "RECOVER"); assert_eq!(rec[1].display, "RECOVER"); - let l = suggestions("l"); + let l = suggestions("l", &Default::default()); assert_eq!(l[0].id, "LINE"); assert_eq!(l[0].display, "L (LINE)"); - let c = suggestions("c"); + let c = suggestions("c", &Default::default()); assert_eq!(c[0].id, "CIRCLE"); assert_eq!(c[0].display, "C (CIRCLE)"); - let co = suggestions("co"); + let co = suggestions("co", &Default::default()); assert_eq!(co[0].id, "COPY"); assert_eq!(co[0].display, "CO (COPY)"); } #[test] fn prefix_without_alias_shows_command_id() { - let rect = suggestions("rect"); + let rect = suggestions("rect", &Default::default()); assert_eq!(rect[0].id, "RECTANG"); assert_eq!(rect[0].display, "RECTANG"); - let line = suggestions("line"); + let line = suggestions("line", &Default::default()); assert_eq!(line[0].id, "LINE"); assert_eq!(line[0].display, "LINE"); } @@ -1106,4 +1213,133 @@ mod autocomplete_tests { assert!(app.session.running.is_none()); assert!(app.session.log.iter().any(|l| l.contains("unknown command")), "{:?}", app.session.log); } + + fn ids(s: &[Suggestion]) -> Vec<&str> { + s.iter().map(|s| s.id.as_str()).collect() + } + + fn running(app: &CadApp) -> Option<&str> { + app.session.running.as_ref().map(|r| r.id.as_str()) + } + + /// Type `text` and press Down `downs` times, then Enter; cancel what started. + fn pick(app: &mut CadApp, text: &str, downs: usize) -> Option { + app.cmd.buffer = text.to_string(); + for _ in 0..downs { + assert!(suggestion_key(app, 1), "Down moves in the list"); + } + submit(app); + let ran = running(app).map(str::to_string); + app.session.cancel(); + ran + } + + #[test] + fn li_lists_line_above_list_once_line_is_used_more() { + let mut app = app(); + let fresh = suggestions("li", &app.cmd.usage); + assert_eq!(fresh[0].id, "LIST", "LI is LIST's alias: {:?}", ids(&fresh)); + let line = fresh.iter().position(|s| s.id == "LINE").unwrap_or(usize::MAX); + assert!(line > 0 && line < fresh.len(), "{:?}", ids(&fresh)); + // Typing LI, Down to LINE and Enter: the arrows choose what Enter runs. + assert_eq!(pick(&mut app, "li", line).as_deref(), Some("line")); + // A few uses do not yet move LINE above the alias typed exactly... + assert_eq!(suggestions("li", &app.cmd.usage)[0].id, "LIST"); + // (LINE has moved up: right under LIST.) + assert_eq!(suggestions("li", &app.cmd.usage)[1].id, "LINE"); + for _ in 0..3 { + assert_eq!(pick(&mut app, "li", 1).as_deref(), Some("line")); + } + // ...but used more often than that, LINE lists first and Enter on LI runs it. + let learned = suggestions("li", &app.cmd.usage); + assert_eq!(ids(&learned)[..2], ["LINE", "LIST"], "{:?}", ids(&learned)); + assert_eq!(pick(&mut app, "li", 0).as_deref(), Some("line")); + // LIST is still a Down away, and choosing it counts for it. + assert_eq!(pick(&mut app, "li", 1).as_deref(), Some("list")); + // A command name typed in full always runs that command. + assert_eq!(suggestions("list", &app.cmd.usage)[0].id, "LIST"); + } + + #[test] + fn uses_typed_in_any_form_count_and_fade() { + let mut app = app(); + // L is LINE's alias: running LINE through it counts for LINE. + for _ in 0..5 { + assert_eq!(pick(&mut app, "l", 0).as_deref(), Some("line")); + } + assert!(app.cmd.usage.score("line") > 4.9); + assert_eq!(suggestions("li", &app.cmd.usage)[0].id, "LINE"); + // Commands typed with their options count too, under their own name. + app.cmd.buffer = "circle 0,0 5".into(); + submit(&mut app); + assert!(app.cmd.usage.score("circle") > 0.9); + // Much later, LINE's old uses have faded and LIST is back on top for LI. + for _ in 0..(3 * crate::cmd_usage::HALF_LIFE as usize) { + app.cmd.usage.record("pan"); + } + assert_eq!(suggestions("li", &app.cmd.usage)[0].id, "LIST"); + } + + #[test] + fn learning_moves_a_command_into_the_shortened_list() { + let mut usage = crate::cmd_usage::Usage::default(); + let all = matches("d"); + assert!(all.len() > MAX_SUGGESTIONS, "D matches many commands"); + let Some((last, _)) = all.last() else { return }; + assert!(!ids(&suggestions("d", &usage)).contains(&last.id.as_str())); + usage.record(&last.id); + let learned = suggestions("d", &usage); + assert_eq!(learned.len(), MAX_SUGGESTIONS); + // Right after the alias typed exactly, if D is one; else first. + let at = usize::from(all.first().is_some_and(|(_, exact)| *exact)); + assert_eq!(learned.get(at).map(|s| s.id.as_str()), Some(last.id.as_str()), "{:?}", ids(&learned)); + } + + #[test] + fn arrows_move_the_highlight_and_typing_resets_it() { + let mut app = app(); + app.cmd.buffer = "re".into(); + let n = current_suggestions(&app).len(); + assert!(n > 2); + assert!(!suggestion_key(&mut app, -1), "Up on the first row is left to the history"); + assert!(suggestion_key(&mut app, 1)); + assert!(suggestion_key(&mut app, 1)); + assert_eq!(highlight_index(&app, n), 2); + assert!(suggestion_key(&mut app, -1)); + assert_eq!(highlight_index(&app, n), 1); + for _ in 0..20 { + suggestion_key(&mut app, 1); + } + assert_eq!(highlight_index(&app, n), n - 1, "Down stops on the last row"); + let second = current_suggestions(&app).get(n - 1).map(|s| s.id.clone()); + tab(&mut app); + assert_eq!(Some(app.cmd.buffer.clone()), second, "Tab completes the highlighted row"); + app.cmd.buffer = "rec".into(); + assert_eq!(highlight_index(&app, current_suggestions(&app).len()), 0, "new text starts at the first row"); + } + + #[test] + fn learned_order_is_kept_with_the_preferences_and_can_be_reset() { + let mut app = app(); + for _ in 0..6 { + pick(&mut app, "line", 0); + } + let prefs = app.prefs_json(); + let mut restarted = CadApp::new(draftcraft_engine::Session::empty(), crate::Services::default()); + restarted.load_prefs(&prefs); + assert_eq!(restarted.cmd.usage, app.cmd.usage); + assert_eq!(suggestions("li", &restarted.cmd.usage)[0].id, "LINE"); + // A corrupt stored value is ignored. + let mut corrupt = CadApp::new(draftcraft_engine::Session::empty(), crate::Services::default()); + corrupt.load_prefs(r#"{"cmdlineUsage": {"clock": "soon", "commands": {"line": [1e308, 1]}}}"#); + assert!(corrupt.cmd.usage.is_empty()); + corrupt.load_prefs(r#"{"cmdlineUsage": {"clock": 4, "commands": {"line": "often", "list": [2.0, 3]}}}"#); + assert_eq!(corrupt.cmd.usage.len(), 1); + assert_eq!(suggestions("li", &corrupt.cmd.usage)[0].id, "LIST"); + // Reset: back to the unlearned order, and nothing is stored. + let r = crate::menus::run_ui_command(&mut restarted, "ui.cmdline.resetsuggestions", &serde_json::Value::Null); + assert_eq!(r, Some(Ok(serde_json::json!({ "forgotten": 1 })))); + assert_eq!(suggestions("li", &restarted.cmd.usage)[0].id, "LIST"); + assert!(!restarted.prefs_json().contains("cmdlineUsage")); + } } diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 6b4f5371..26eb9018 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -142,6 +142,7 @@ Circumference المحيط Clear مسح Clear Command History مسح سجل الأوامر + Reset Suggestion Order إعادة تعيين ترتيب الاقتراحات Clear History مسح السجل Clip مقطع Clip Viewport قص إطار العرض diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 373cf525..1d10a89d 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -156,6 +156,7 @@ Command Aliases Pseudonimi naredbi Command History Historija naredbi Clear Command History Očisti historiju naredbi + Reset Suggestion Order Poništi redoslijed prijedloga Command Line Komandna linija Command Line History Lines Redovi historije komandne linije Command Reference Referenca naredbi diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index cd7aa964..0efef291 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -154,6 +154,7 @@ Command Aliases Aliasy příkazů Command History Historie příkazů Clear Command History Vymazat historii příkazů + Reset Suggestion Order Obnovit pořadí návrhů Command Line Příkazový řádek Command Line History Lines Počet řádků historie příkazového řádku Command Reference Přehled příkazů diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 6e5841f7..8dbe1dd7 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -153,6 +153,7 @@ Circumference Περιφέρεια Clear Εκκαθάριση Clear Command History Εκκαθάριση ιστορικού εντολών + Reset Suggestion Order Επαναφορά σειράς προτάσεων Clear History Εκκαθάριση ιστορικού Clear Recent Files Εκκαθάριση πρόσφατων αρχείων Click the ruler to add a tab stop, right-click to remove one Κάντε κλικ στον χάρακα για προσθήκη στηλοθέτη ή δεξί κλικ για αφαίρεση diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 549dfd42..0c0faab9 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -134,6 +134,7 @@ Circumference Circunferencia Clear Limpiar Clear Command History Borrar el historial de comandos + Reset Suggestion Order Restablecer el orden de las sugerencias Clear History Borrar historial Clip Delimitar Clip Viewport Delimitar ventana gráfica diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index df4af803..c73c5c8a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -166,6 +166,7 @@ Circumference Kerület Clear Kiürítés Clear Command History Parancselőzmények törlése + Reset Suggestion Order Javaslatok sorrendjének visszaállítása Clear History Előzmények törlése Clear Recent Files Legutóbbi fájlok listájának törlése Click the ruler to add a tab stop, right-click to remove one Kattintással tabulátorpozíciót adhatsz a vonalzóhoz, jobb kattintással eltávolíthatod diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index f269e0f6..b285426a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -166,6 +166,7 @@ menu Modify Edita Command Aliases Alias dei comandi Command History Cronologia comandi Clear Command History Cancella cronologia comandi + Reset Suggestion Order Ripristina ordine dei suggerimenti Command Line Riga di comando Command Line History Lines Righe della cronologia della riga di comando Command Reference Riferimento comandi diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index 77d78287..21d2fe3b 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -155,6 +155,7 @@ Command Aliases 명령 별칭 Command History 명령 기록 Clear Command History 명령 기록 지우기 + Reset Suggestion Order 제안 순서 재설정 Command Line 명령행 Command Line History Lines 명령행 기록 줄 수 Command Reference 명령 참조 diff --git a/crates/ui-egui/src/i18n/pt_br.tsv b/crates/ui-egui/src/i18n/pt_br.tsv index ac52b9c2..f2d2eebb 100644 --- a/crates/ui-egui/src/i18n/pt_br.tsv +++ b/crates/ui-egui/src/i18n/pt_br.tsv @@ -131,6 +131,7 @@ Circumference Circunferência Clear Limpar Clear Command History Limpar histórico de comandos + Reset Suggestion Order Redefinir ordem das sugestões Clear History Limpar histórico Clip Recortar Clip Viewport Recortar viewport diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index af9aeb35..79b109a0 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -135,6 +135,7 @@ Circumference Omkrets Clear Rensa Clear Command History Rensa kommandohistoriken + Reset Suggestion Order Återställ förslagsordningen Clear History Rensa historiken Clip Beskär Clip Viewport Beskär vyfönster diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 3bca4bad..d8847a6a 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -167,6 +167,7 @@ Circumference Çevre Clear Temizle Clear Command History Komut Geçmişini Temizle + Reset Suggestion Order Öneri Sırasını Sıfırla Clear History Geçmişi Temizle Clear Recent Files Son Dosyaları Temizle Click the ruler to add a tab stop, right-click to remove one Sekme durağı eklemek için cetvele tıklayın, kaldırmak için sağ tıklayın diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 0f6e16f5..506f8afb 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -160,6 +160,7 @@ Command Aliases Псевдоніми команд Command History Історія команд Clear Command History Очистити історію команд + Reset Suggestion Order Скинути порядок підказок Command Line Командний рядок Command Line History Lines Рядки історії командного рядка Command Reference Довідник команд diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 4e5f5d52..2b7728c2 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -155,6 +155,7 @@ Command Aliases Bí danh lệnh Command History Lịch sử lệnh Clear Command History Xóa lịch sử lệnh + Reset Suggestion Order Đặt lại thứ tự gợi ý Command Line Dòng lệnh Command Line History Lines Số dòng lịch sử dòng lệnh Command Reference Tham chiếu lệnh diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 55e078c9..72726db6 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1181,6 +1181,7 @@ Export Comparison 导出比较 Plotter Manager 打印机管理 Clear Command History 清除命令历史记录 + Reset Suggestion Order 重置建议顺序 Degrees of freedom: {n} 自由度: {n} Open 打开 Arrow size 箭头大小 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 94ae3f86..173ade0f 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -28,6 +28,7 @@ pub mod capture; pub mod chrome; pub mod clipboard; pub mod closing; +pub mod cmd_usage; pub mod cmdline; pub mod context_menu; pub mod control; @@ -488,21 +489,32 @@ impl CadApp { /// command or system variable) runs `fallback` instead: Enter on a partly typed name accepts /// the highlighted AutoComplete suggestion. pub fn cmdline_or(&mut self, text: &str, fallback: Option<&str>) -> Option { + self.cmdline_or_ran(text, fallback).err() + } + + /// [`Self::cmdline_or`], telling what ran: `Ok(true)` when `text` was unknown and `fallback` + /// ran instead, `Ok(false)` when `text` ran, `Err` when it failed (the error is echoed). + pub fn cmdline_or_ran(&mut self, text: &str, fallback: Option<&str>) -> Result { if !self.session.prompting() { let first = text.split_whitespace().next().unwrap_or(""); // `cmd {json}` is a programmatic call: the engine runs it with those parameters. let json_form = text.trim_start().get(first.len()..).is_some_and(|rest| rest.trim_start().starts_with('{')); if !first.is_empty() && !json_form && menus::run_ui_command(self, &first.to_ascii_lowercase(), &Value::Null).is_some() { - return None; + return Ok(false); } } let e = match (self.session.cmdline(text), fallback) { - (Ok(()), _) => return None, - (Err(draftcraft_engine::EngineError::UnknownCommand(_)), Some(f)) => return self.cmdline(f), + (Ok(()), _) => return Ok(false), + (Err(draftcraft_engine::EngineError::UnknownCommand(_)), Some(f)) => { + return match self.cmdline(f) { + None => Ok(true), + Some(e) => Err(e), + }; + } (Err(e), _) => e.to_string(), }; self.session.echo(e.clone()); - Some(e) + Err(e) } /// The theme the interface shows now (the choice resolved against the OS appearance). @@ -536,6 +548,9 @@ impl CadApp { if let Some(dir) = &self.ui.last_lisp_dir { prefs["lispDir"] = json!(dir); } + if !self.cmd.usage.is_empty() { + prefs["cmdlineUsage"] = self.cmd.usage.to_json(); + } prefs.to_string() } @@ -572,6 +587,9 @@ impl CadApp { if let Some(dir) = v.get("lispDir").and_then(Value::as_str).filter(|d| !d.is_empty()) { self.ui.last_lisp_dir = Some(dir.to_string()); } + if let Some(usage) = v.get("cmdlineUsage") { + self.cmd.usage = cmd_usage::Usage::from_json(usage); + } } /// Make the system cursor the interface default (`on`) and turn it on; saved preferences and diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index a11c74a1..1717e520 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -80,6 +80,7 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("ui.toggle.history", "Command History", &["Window", "Command History"], Some("F2")), ("ui.cmdline.lines", "Command Line History Lines", &[], None), ("ui.cmdline.clear", "Clear Command History", &[], None), + ("ui.cmdline.resetsuggestions", "Reset Suggestion Order", &[], None), ("ui.dialog.language", "Interface Language", &["Edit", "Interface Language"], None), ("ui.dialog.find", "Find and Replace", &[], Some("Cmd+F")), ("ui.language", "Language", &[], None), @@ -538,6 +539,12 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option { + let forgotten = app.cmd.usage.len(); + app.cmd.usage.clear(); + Ok(json!({ "forgotten": forgotten })) + } "ui.dialog.language" | "ui.dialog.layers" | "ui.dialog.blocks" diff --git a/crates/ui-egui/src/shortcut_menus.rs b/crates/ui-egui/src/shortcut_menus.rs index 91846d9c..2ba2fe4d 100644 --- a/crates/ui-egui/src/shortcut_menus.rs +++ b/crates/ui-egui/src/shortcut_menus.rs @@ -43,7 +43,7 @@ fn push(groups: &mut Vec>, group: Vec) { } /// The command line's menu: Recent Commands, Dynamic Input, the history window and its height, -/// Copy History and Clear. +/// Copy History and Clear, and Reset Suggestion Order. pub fn command_line_entries(app: &CadApp) -> Vec> { let mut groups = Vec::new(); let recent: Vec = app @@ -64,6 +64,12 @@ pub fn command_line_entries(app: &CadApp) -> Vec> { let mut edit = vec![action("Copy History", "cmdline:copy".into(), !app.session.log.is_empty())]; edit.extend(item(app, "ui.cmdline.clear", None)); groups.push(edit); + // AutoComplete's learned order (the commands used most listed first) can be forgotten. + let reset = item(app, "ui.cmdline.resetsuggestions", None).map(|e| match e { + Entry::Item { label, id, shortcut, .. } => Entry::Item { label, id, shortcut, enabled: !app.cmd.usage.is_empty() }, + other => other, + }); + push(&mut groups, reset.into_iter().collect()); groups }