Merge #3231: Dynamic Input: Tab cycles back to the first box and keeps the second value (#3201)

This commit is contained in:
Tanish Manku
2026-11-24 19:29:15 -07:00
5 changed files with 477 additions and 21 deletions
+3
View File
@@ -138,3 +138,6 @@ real_name = "Tyrel Haveman"
real_name = "Sladrian Pedroso"
display_name = "Sladrian Pedroso"
sync_github_name = false
[people.iHateStupidPeople]
sync_github_name = true
+9 -5
View File
@@ -953,7 +953,7 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
if let Some(f) = dyn_frame
&& crate::dyninput::parse(&app.cmd.buffer, &f).is_some()
{
app.cmd.buffer.clear();
app.cmd.clear_entry();
}
// Preserve a snap's viewport origin for DIST, and its deferred curve where needed.
let result = match app.canvas.snap {
@@ -1026,10 +1026,11 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) {
fn track_cursor(app: &mut CadApp, raw: Option<Vec2>, xf: &Xf, ctx: &egui::Context, dyn_frame: Option<crate::dyninput::Frame>) {
if let Some(w) = raw {
let mut eff = effective_point(app, w, xf, ctx);
// A locked Dynamic Input value (`40,` or `40<` typed) holds the cursor and overrides snaps.
// A locked Dynamic Input value (`40,` or `40<` typed, or a Tab-locked second value) holds the
// cursor and overrides snaps.
if let Some(f) = dyn_frame
&& let Some(e) = crate::dyninput::parse(&app.cmd.buffer, &f)
&& e.first_locked().is_some()
&& crate::dyninput::holds_cursor(&e, app.cmd.second_locked())
{
eff = crate::dyninput::constrain(&e, &f, eff, app.cmd.second_locked());
app.canvas.snap = None;
@@ -1046,7 +1047,10 @@ fn track_cursor(app: &mut CadApp, raw: Option<Vec2>, xf: &Xf, ctx: &egui::Contex
app.session.cursor = eff;
app.session.cursor_deferred = app.canvas.snap.and_then(|h| h.deferred);
// Typed or menu snap overrides (END, NON…) and Tab cycling; a locked Dynamic Input value wins.
if dyn_frame.and_then(|f| crate::dyninput::parse(&app.cmd.buffer, &f)).is_none_or(|e| e.first_locked().is_none()) {
if dyn_frame
.and_then(|f| crate::dyninput::parse(&app.cmd.buffer, &f))
.is_none_or(|e| !crate::dyninput::holds_cursor(&e, app.cmd.second_locked()))
{
override_cursor(app, w, xf);
}
// Typed grip dimensions win over snap overrides too.
@@ -1094,7 +1098,7 @@ fn press_at(app: &mut CadApp, xf: &Xf, ctx: &egui::Context, pos: Pos2, mods: egu
if let Some(f) = dyn_frame
&& crate::dyninput::parse(&app.cmd.buffer, &f).is_some()
{
app.cmd.buffer.clear();
app.cmd.clear_entry();
}
// Preserve a snap's viewport origin for DIST, and its deferred curve where needed.
let result = match app.canvas.snap {
+7 -5
View File
@@ -38,7 +38,8 @@ pub(super) fn dynamic_input(app: &mut CadApp, p: &egui::Painter, hover: Pos2, fi
&& let Some(c) = app.canvas.cursor
{
let message = if show_prompt { crate::i18n::t(&prompt.message) } else { "" };
let r = dynamic_input_boxes(p, at, message, &f, &e, c, app.cmd.second_locked(), options, length_units(&app.session));
let r =
dynamic_input_boxes(p, at, message, &f, &e, c, (app.cmd.first_active(), app.cmd.second_locked()), options, length_units(&app.session));
options_menu(app, p, r, hover);
return;
}
@@ -166,7 +167,8 @@ fn angle_box(p: &egui::Painter, at: Pos2, message: &str, value: &str, typed: boo
/// The Dynamic Input value boxes: X and Y, or distance and angle. Typed values show in full
/// text colour, a locked value (a separator typed after it) gets a lock, the active box gets the
/// accent outline, and open boxes show the cursor's live value, dimmed. Values measured from the
/// last point are marked with `@`.
/// last point are marked with `@`. `(first_active, second_locked)`: Tab wrapped around to the first
/// box, and Tab locked the second value.
#[allow(clippy::too_many_arguments)]
fn dynamic_input_boxes(
p: &egui::Painter,
@@ -175,7 +177,7 @@ fn dynamic_input_boxes(
f: &crate::dyninput::Frame,
e: &crate::dyninput::Entry<'_>,
cursor: Vec2,
second_locked: bool,
(first_active, second_locked): (bool, bool),
options: bool,
(lu, lp): (i64, i64),
) -> Rect {
@@ -199,14 +201,14 @@ fn dynamic_input_boxes(
if e.first.is_empty() { dist(live_first) } else { e.first.to_owned() },
!e.first.is_empty(),
e.first_locked().is_some(),
!e.split,
!e.split || first_active,
),
(
label_second,
if e.second.is_empty() { live_second } else { e.second.to_owned() },
!e.second.is_empty(),
second_locked,
e.split && !second_locked,
e.split && !first_active,
),
];
+317 -8
View File
@@ -29,6 +29,9 @@ pub struct CmdLine {
pub options: Option<crate::dyninput::OptionsMenu>,
/// The text whose second Dynamic Input value Tab locked; the lock holds while it is unchanged.
locked_second: Option<String>,
/// The text at which Tab wrapped around to the first Dynamic Input box of a split entry
/// (`40<90`); the first box stays active while the command line holds that text.
first_active: Option<String>,
/// Where the options menu's rows were drawn last frame (screen), for clicks on them.
pub option_rows: Vec<(Rect, String)>,
/// Where the Dynamic Input tooltip stays while the options menu is open.
@@ -85,7 +88,8 @@ pub fn capture_tab(ctx: &egui::Context, raw: &mut egui::RawInput) {
}
/// Tab on the command line: cycle the object snaps under the cursor, type the Dynamic Input
/// separator (`,` or `<`) after a value, or complete a command name.
/// separator (`,` or `<`) after a value, cycle between the two Dynamic Input boxes, or complete a
/// command name.
fn tab(app: &mut CadApp) {
// Grip dimensional input: Tab locks the typed value and moves to the next field.
if crate::grip_dyn::tab(app) {
@@ -99,10 +103,19 @@ fn tab(app: &mut CadApp) {
{
app.cmd.buffer.push(sep);
} else if let Some(f) = dyn_frame(app)
&& crate::dyninput::can_lock_second(&app.cmd.buffer, &f)
&& crate::dyninput::is_split(&app.cmd.buffer, &f)
{
// Both values typed: Tab locks the second one as well.
app.cmd.locked_second = Some(app.cmd.buffer.clone());
if app.cmd.first_active() {
// Back in the first box: Tab moves on to the second one again.
app.cmd.first_active = None;
} else {
// Leaving the second box: a typed value locks as well (both values typed), and Tab
// wraps around to the first box so its value can be changed.
if crate::dyninput::can_lock_second(&app.cmd.buffer, &f) {
app.cmd.locked_second = Some(app.cmd.buffer.clone());
}
app.cmd.first_active = Some(app.cmd.buffer.clone());
}
} else if let Some(s) = suggestions_in(&app.session, &app.cmd.buffer).first() {
app.cmd.buffer = s.id.clone();
}
@@ -210,6 +223,63 @@ impl CmdLine {
self.locked_second.as_deref() == Some(self.buffer.as_str())
}
/// Tab wrapped around to the first Dynamic Input box and it is still the active one.
pub fn first_active(&self) -> bool {
self.first_active.as_deref() == Some(self.buffer.as_str())
}
/// Forget the first-box record once the command line no longer holds its text (Escape, history
/// recall, a picked option or a click cleared or replaced it), so typing the same text again later
/// does not reactivate the first box without Tab. `dyn_live` is false while the Dynamic Input
/// boxes are not on screen (F12 turned it off): the record goes too, and Backspace and typing
/// edit the end of the command line again.
fn forget_stale_first(&mut self, dyn_live: bool) {
if !dyn_live || !self.first_active() {
self.first_active = None;
}
}
/// Type `text` at the command line: at the end, or into the first Dynamic Input box when Tab
/// wrapped around to it (the second value, and its lock, are kept). `frame` is the Dynamic
/// Input frame on screen (`dyn_frame`), which decides whether a separator may switch formats.
fn type_text(&mut self, text: &str, frame: Option<crate::dyninput::Frame>) {
if self.first_active()
&& let Some(f) = frame
&& let Some(edit) = crate::dyninput::type_in_first(&self.buffer, text, &f)
{
let keep_lock = self.second_locked() && !edit.done;
self.buffer = edit.text;
self.first_active = (!edit.done).then(|| self.buffer.clone());
self.locked_second = keep_lock.then(|| self.buffer.clone());
return;
}
self.buffer.push_str(text);
}
/// The typed entry is used up or thrown away (a click placed the point, or Escape): the text
/// goes, and so do the first-box record and the second value's lock, so typing the same text
/// again later does not lock anything without Tab.
pub fn clear_entry(&mut self) {
self.buffer.clear();
self.first_active = None;
self.locked_second = None;
}
/// Backspace at the command line: erase the last character, or the first Dynamic Input
/// value's last character while its box is active (the separator and second value stay).
fn backspace(&mut self) {
if self.first_active()
&& let Some(text) = crate::dyninput::backspace_in_first(&self.buffer)
{
let keep_lock = self.second_locked();
self.buffer = text;
self.first_active = Some(self.buffer.clone());
self.locked_second = keep_lock.then(|| self.buffer.clone());
return;
}
self.buffer.pop();
}
/// The options menu row under `at` (screen), if the menu is open.
pub fn option_at(&self, at: Pos2) -> Option<String> {
self.options.as_ref()?;
@@ -318,6 +388,7 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
}
options_still_fit(app);
for ev in events {
app.cmd.forget_stale_first(dyn_frame(app).is_some());
// The options menu takes the arrows, Enter and Escape; typing closes it.
if app.cmd.options.is_some() {
let space = matches!(&ev, egui::Event::Text(t) if t == " ") && !text_prompt;
@@ -357,7 +428,8 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
submit(app);
} else {
app.cmd.preedit.clear();
app.cmd.buffer.push_str(&t);
let f = dyn_frame(app);
app.cmd.type_text(&t, f);
}
}
// IME composition: the pre-edit is shown but stays out of the buffer; the commit is
@@ -367,7 +439,8 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
egui::Event::Ime(egui::ImeEvent::Commit(text)) => {
app.cmd.preedit.clear();
if text != "\n" && text != "\r" {
app.cmd.buffer.push_str(&text);
let f = dyn_frame(app);
app.cmd.type_text(&text, f);
}
}
egui::Event::Ime(_) => {}
@@ -387,7 +460,7 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
if erase {
let _ = app.run("erase.selection", serde_json::json!({}));
} else {
app.cmd.buffer.pop();
app.cmd.backspace();
}
}
Key::ArrowUp if !modifiers.any() && !app.cmd.history.is_empty() => {
@@ -395,6 +468,7 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
let pos = app.cmd.history_pos.map(|p| p.saturating_sub(1)).unwrap_or(n - 1);
app.cmd.history_pos = Some(pos);
app.cmd.buffer = app.cmd.history.get(pos).cloned().unwrap_or_default();
app.cmd.first_active = None;
}
Key::ArrowDown if !modifiers.any() => {
if !options_key(app, 1)
@@ -407,6 +481,7 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
} else {
app.cmd.history_pos = Some(np);
app.cmd.buffer = app.cmd.history.get(np).cloned().unwrap_or_default();
app.cmd.first_active = None;
}
}
}
@@ -420,13 +495,14 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) {
}
app.cmd.note_typing();
}
app.cmd.forget_stale_first(dyn_frame(app).is_some());
}
/// What Escape does, and the right-click or menu "Cancel" that stand for it: what was typed so far
/// goes, and so does the running command.
pub fn escape(app: &mut CadApp) {
app.paste.cancel();
app.cmd.buffer.clear();
app.cmd.clear_entry();
app.cmd.preedit.clear();
app.session.cancel();
}
@@ -449,6 +525,7 @@ pub fn submit(app: &mut CadApp) {
}
let text = std::mem::take(&mut app.cmd.buffer);
app.cmd.locked_second = None;
app.cmd.first_active = None;
app.cmd.history_pos = None;
if !text.trim().is_empty() && !app.session.prompting() {
app.cmd.history.push(text.clone());
@@ -1044,3 +1121,235 @@ mod autocomplete_tests {
assert!(app.session.log.iter().any(|l| l.contains("unknown command")), "{:?}", app.session.log);
}
}
#[cfg(test)]
mod dyn_tab_tests {
use super::*;
use cadcraft_doc::EntityKind;
use cadcraft_geom::Vec2;
/// LINE with Dynamic Input on, at its second point (from the origin).
fn line_from_origin() -> CadApp {
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
app.cmdline("line");
app.cmdline("0,0");
assert!(dyn_frame(&app).is_some_and(|f| f.base.is_some()), "a second point prompt");
app
}
/// Type `text` at the command line with the Dynamic Input frame on screen.
fn type_in(app: &mut CadApp, text: &str) {
let f = dyn_frame(app);
app.cmd.type_text(text, f);
}
fn line_end(app: &CadApp) -> Option<Vec2> {
app.session.doc().ok()?.model.iter().find_map(|e| match &e.kind {
EntityKind::Line(l) => Some(l.b.xy()),
_ => None,
})
}
#[test]
fn tab_wraps_back_to_the_first_box_and_keeps_the_second_value() {
// #3201: `40` Tab `90`, Tab back to the length, change it to 50, Enter.
let mut app = line_from_origin();
type_in(&mut app, "40");
tab(&mut app);
assert_eq!(app.cmd.buffer, "40<");
assert!(!app.cmd.first_active());
type_in(&mut app, "90");
// Tab locks the angle and wraps around to the length box.
tab(&mut app);
assert!(app.cmd.first_active() && app.cmd.second_locked());
// Backspace and typing edit only the length; the angle and its lock stay.
app.cmd.backspace();
app.cmd.backspace();
app.cmd.backspace();
assert_eq!(app.cmd.buffer, "<90");
type_in(&mut app, "50");
assert_eq!(app.cmd.buffer, "50<90");
assert!(app.cmd.first_active() && app.cmd.second_locked());
// Tab moves on to the angle box again, and again wraps around.
tab(&mut app);
assert!(!app.cmd.first_active());
assert_eq!(app.cmd.buffer, "50<90");
tab(&mut app);
assert!(app.cmd.first_active());
submit(&mut app);
let b = line_end(&app);
assert!(b.is_some_and(|b| b.dist(Vec2::new(0.0, 50.0)) < 1e-9), "{b:?}");
assert!(!app.cmd.first_active());
}
fn run_frame(app: &mut CadApp, ctx: &egui::Context, events: Vec<egui::Event>) {
let raw = egui::RawInput {
screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1400.0, 900.0))),
events,
..Default::default()
};
let mut out = ctx.run_ui(raw, |ui| {
app.logic(ui.ctx());
app.ui(ui);
});
out.textures_delta.clear();
}
fn typed(text: &str) -> Vec<egui::Event> {
text.chars().map(|c| egui::Event::Text(c.to_string())).collect()
}
#[test]
fn escape_forgets_the_first_box() {
// Retyping the text the first box was active at must not reactivate it without Tab.
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
run_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(center)]);
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, typed("40\t90\t"));
assert!(app.cmd.first_active(), "{:?}", app.cmd.buffer);
let escape = egui::Key::Escape;
let m = egui::Modifiers::NONE;
run_frame(
&mut app,
&ctx,
vec![
egui::Event::Key { key: escape, physical_key: None, pressed: true, repeat: false, modifiers: m },
egui::Event::Key { key: escape, physical_key: None, pressed: false, repeat: false, modifiers: m },
],
);
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, typed("40<90"));
assert!(!app.cmd.first_active());
run_frame(&mut app, &ctx, typed("1"));
assert_eq!(app.cmd.buffer, "40<901");
}
#[test]
fn dynamic_input_off_edits_the_end_of_the_command_line() {
// F12 with the first box active: Backspace and typing must edit the end again.
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
run_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(center)]);
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, typed("40\t90\t"));
assert!(app.cmd.first_active(), "{:?}", app.cmd.buffer);
app.session.settings.dynmode = false;
let back = egui::Key::Backspace;
let m = egui::Modifiers::NONE;
run_frame(
&mut app,
&ctx,
vec![
egui::Event::Key { key: back, physical_key: None, pressed: true, repeat: false, modifiers: m },
egui::Event::Key { key: back, physical_key: None, pressed: false, repeat: false, modifiers: m },
],
);
assert_eq!(app.cmd.buffer, "40<9");
assert!(!app.cmd.first_active());
run_frame(&mut app, &ctx, typed("5"));
assert_eq!(app.cmd.buffer, "40<95");
}
#[test]
fn the_locked_angle_holds_the_click_once_the_length_is_erased() {
// #3201: `40` Tab `90` Tab, erase the 40: the angle box keeps its lock, so the canvas
// cursor lies along 90 degrees at the pointer's distance, and a click places the line's
// end there.
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, typed("40\t90\t"));
let back = egui::Key::Backspace;
let m = egui::Modifiers::NONE;
let key = |pressed| egui::Event::Key { key: back, physical_key: None, pressed, repeat: false, modifiers: m };
run_frame(&mut app, &ctx, vec![key(true), key(false), key(true), key(false)]);
assert_eq!(app.cmd.buffer, "<90");
assert!(app.cmd.first_active() && app.cmd.second_locked());
let at = center + egui::vec2(37.0, -23.0);
run_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
let c = app.canvas.cursor;
assert!(c.is_some_and(|c| c.x.abs() < 1e-9 && c.y > 0.0), "{c:?}");
let click = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: m };
run_frame(&mut app, &ctx, vec![click(true)]);
run_frame(&mut app, &ctx, vec![click(false)]);
let b = line_end(&app);
assert!(b.zip(c).is_some_and(|(b, c)| b.dist(c) < 1e-9), "{b:?} {c:?}");
}
#[test]
fn tab_from_an_empty_second_box_wraps_without_locking() {
let mut app = line_from_origin();
type_in(&mut app, "40");
tab(&mut app);
tab(&mut app);
assert!(app.cmd.first_active() && !app.cmd.second_locked());
// A separator typed in the first box moves to the second box again.
type_in(&mut app, "5<");
assert_eq!(app.cmd.buffer, "405<");
assert!(!app.cmd.first_active());
type_in(&mut app, "0");
assert_eq!(app.cmd.buffer, "405<0");
}
#[test]
fn escape_and_a_click_drop_the_second_value_lock() {
// #3231 review: after Escape or a click, retyping `40<90` must not be locked without Tab.
for click in [false, true] {
let mut app = line_from_origin();
type_in(&mut app, "40<90");
tab(&mut app);
assert!(app.cmd.second_locked());
if click {
app.cmd.clear_entry();
} else {
escape(&mut app);
app.cmdline("line");
app.cmdline("0,0");
}
type_in(&mut app, "40<90");
assert!(!app.cmd.second_locked(), "click: {click}");
assert!(!app.cmd.first_active(), "click: {click}");
}
}
#[test]
fn a_canvas_click_drops_the_second_value_lock() {
// #3231: the click is taken when the button goes down; using up the typed `40<90` there
// must drop the Tab lock too, or retyping `40<90` comes back locked without Tab.
let mut app = CadApp::new(cadcraft_engine::Session::new(), crate::Services::default());
app.session.settings.dynmode = true;
let ctx = egui::Context::default();
run_frame(&mut app, &ctx, Vec::new());
let center = app.canvas.rect.map_or(egui::pos2(700.0, 450.0), |r| r.center());
app.cmdline("line");
app.cmdline("0,0");
run_frame(&mut app, &ctx, typed("40<90\t"));
assert!(app.cmd.second_locked());
let at = center + egui::vec2(37.0, -23.0);
let m = egui::Modifiers::NONE;
run_frame(&mut app, &ctx, vec![egui::Event::PointerMoved(at)]);
let click = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Primary, pressed, modifiers: m };
run_frame(&mut app, &ctx, vec![click(true)]);
run_frame(&mut app, &ctx, vec![click(false)]);
assert!(app.cmd.buffer.is_empty(), "{:?}", app.cmd.buffer);
assert!(!app.cmd.second_locked());
run_frame(&mut app, &ctx, typed("40<90"));
assert!(!app.cmd.second_locked());
assert!(!app.cmd.first_active());
}
}
+141 -3
View File
@@ -6,7 +6,10 @@
//! - `40,` locks X = 40 and moves to Y; `40<` locks the distance and moves to the angle. A locked
//! value holds the cursor.
//! - Tab types the separator for the format on show, so `40` Tab `90` reads `40<90`; Tab after the
//! second value locks it too (both boxes show a lock and the cursor sits on the point).
//! second value locks it too (both boxes show a lock and the cursor sits on the point) and wraps
//! around to the first box, so the first value can be changed; Tab there moves on to the second
//! box again. Typing and Backspace in the first box edit only the first value
//! ([`type_in_first`], [`backspace_in_first`]); a separator typed there moves to the second box.
//! - Enter sends the entry with `@` in front when it is measured from the last point (relative is
//! the default; DYNPICOORDS = 1 makes it absolute), and fills an empty box from the cursor.
//! - A plain number and Enter stays direct distance entry; `@`/`#` entries, keywords and command
@@ -139,17 +142,96 @@ pub fn tab_separator(text: &str, frame: &Frame) -> Option<char> {
parse(text, frame).filter(|e| !e.split).map(|e| e.format.separator())
}
/// Whether `text` is a pointer-input entry with a separator typed (both boxes are on show).
pub fn is_split(text: &str, frame: &Frame) -> bool {
parse(text, frame).is_some_and(|e| e.split)
}
/// The text of a split entry around its separator: (first value, separator, second value), or
/// `None` when no separator is typed.
fn split_raw(text: &str) -> Option<(&str, char, &str)> {
let at = text.find([',', '<'])?;
let sep = text.get(at..)?.chars().next()?;
Some((text.get(..at)?, sep, text.get(at + sep.len_utf8()..)?))
}
/// The result of typing in the first box once Tab has moved back to it.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct FirstEdit {
/// The new command-line text.
pub text: String,
/// A separator was typed: the first value is done and the second box is active again.
pub done: bool,
}
/// Type `typed` in the first box of the split entry `text`: the characters go before the
/// separator and the second value is kept. A separator (`,` or `<`) ends the first value again,
/// picks the format, and anything typed after it goes to the second box. `None` when `text` has no
/// separator (the first box is the end of the text, so plain typing already edits it). A separator
/// that switches the format is refused when the second value does not read in the new format
/// (`40<N` to `,`: `N` is an angle, not a distance): the entry and the first box stay as they were.
pub fn type_in_first(text: &str, typed: &str, frame: &Frame) -> Option<FirstEdit> {
let (first, sep0, second) = split_raw(text)?;
let mut sep = sep0;
let mut first = first.to_owned();
let mut second = second.to_owned();
let mut done = false;
for c in typed.chars() {
match c {
',' | '<' if !done => {
sep = c;
done = true;
}
_ if done => second.push(c),
_ => first.push(c),
}
}
let edited = format!("{first}{sep}{second}");
if sep != sep0 && parse(&edited, frame).is_none() {
return Some(FirstEdit { text: text.to_owned(), done: false });
}
Some(FirstEdit { text: edited, done })
}
/// Backspace in the first box of the split entry `text`: erase the first value's last character
/// and keep the separator and the second value (an empty first box stays empty). `None` when
/// `text` has no separator.
pub fn backspace_in_first(text: &str) -> Option<String> {
let (first, sep, second) = split_raw(text)?;
let mut first = first.trim_end().to_owned();
first.pop();
Some(format!("{first}{sep}{second}"))
}
/// Whether Tab locks the second value too: both values are typed.
pub fn can_lock_second(text: &str, frame: &Frame) -> bool {
parse(text, frame).is_some_and(|e| e.split && e.first_locked().is_some() && e.second_value().is_some())
}
/// Whether the entry holds the cursor: a first value is locked, or Tab locked the second value
/// (`second_locked`) and it is still typed while the first box is empty (`<90` after the first
/// value was erased).
pub fn holds_cursor(entry: &Entry<'_>, second_locked: bool) -> bool {
entry.first_locked().is_some() || (second_locked && entry.second_value().is_some())
}
/// Hold the cursor to the locked values: the first one once a separator follows it, and both
/// when Tab has locked the second one too (`second_locked`), which pins the cursor to the point.
/// With the first box empty, a locked second value alone holds the cursor: Y stays at the typed
/// value, or the cursor's distance is laid along the typed angle.
pub fn constrain(entry: &Entry<'_>, frame: &Frame, p: Vec2, second_locked: bool) -> Vec2 {
let Some(v) = entry.first_locked() else { return p };
// In UCS coordinates; `p` and the result are world points.
let (o, u) = (frame.origin(), frame.ucs.to_ucs(p));
let Some(v) = entry.first_locked() else {
let held = match (second_locked, entry.second_value()) {
(true, Some(w)) => match entry.format {
Format::Cartesian => Vec2::new(u.x, o.y + w),
Format::Polar => o + Vec2::from_angle(w) * (u - o).len(),
},
_ => return p,
};
return if held.is_finite() { frame.ucs.to_wcs(held) } else { p };
};
if second_locked && let Some(w) = entry.second_value() {
let q = match entry.format {
Format::Cartesian => o + Vec2::new(v, w),
@@ -265,7 +347,7 @@ mod tests {
assert_eq!(tab_separator("40", &polar), Some('<'));
// `40` Tab `90` Enter: 40 units straight up.
assert!(close(sent("40<90", &polar, Vec2::ZERO, base), Vec2::new(10.0, 50.0)));
// Already split: Tab does nothing more.
// Already split: Tab types no second separator.
assert_eq!(tab_separator("40<", &polar), None);
let cart = Frame { cartesian: true, ..polar };
assert_eq!(tab_separator("40", &cart), Some(','));
@@ -311,6 +393,43 @@ mod tests {
assert!(close(sent_in("3,", &f, Vec2::new(80.0, 99.0), base), Vec2::new(80.0, 63.0)));
let e = parse("4<", &f).unwrap();
assert!(close(Some(constrain(&e, &f, Vec2::new(100.0, 90.0), false)), Vec2::new(100.0, 64.0)));
// A Tab-locked angle with the first box empty (#3201) is read from the UCS X axis too: the
// cursor keeps its distance from the base and turns onto the typed angle.
let e = parse("<90", &f).unwrap();
assert!(close(Some(constrain(&e, &f, Vec2::new(100.0, 65.0), true)), Vec2::new(95.0, 60.0)));
}
#[test]
fn typing_in_the_first_box_keeps_the_second_value() {
// #3201: back in the first box of `40<90`, Backspace twice and `50` gives `50<90`.
let t = backspace_in_first("40<90");
assert_eq!(t.as_deref(), Some("4<90"));
let t = backspace_in_first("4<90");
assert_eq!(t.as_deref(), Some("<90"));
// An empty first box stays empty; the separator and the angle are not erased.
assert_eq!(backspace_in_first("<90").as_deref(), Some("<90"));
let f = second_point(Vec2::ZERO);
let e = type_in_first("<90", "50", &f);
assert_eq!(e, Some(FirstEdit { text: "50<90".into(), done: false }));
// A separator ends the first value again; what follows goes to the second box.
let e = type_in_first("50<90", ",3", &f);
assert_eq!(e, Some(FirstEdit { text: "50,903".into(), done: true }));
// Nothing split: plain typing already edits the first box.
assert_eq!(type_in_first("40", "5", &f), None);
assert_eq!(backspace_in_first("40"), None);
assert!(is_split("40<", &second_point(Vec2::ZERO)));
assert!(!is_split("40", &second_point(Vec2::ZERO)));
}
#[test]
fn a_format_switch_that_breaks_the_second_value_is_refused() {
// #3231 review: `40<N` keeps its bearing; `,` would make `40,N`, which reads as nothing.
let f = second_point(Vec2::ZERO);
let e = type_in_first("40<N", ",", &f);
assert_eq!(e, Some(FirstEdit { text: "40<N".into(), done: false }));
// A second value that reads in both formats still switches.
let e = type_in_first("40<90", ",", &f);
assert_eq!(e, Some(FirstEdit { text: "40,90".into(), done: true }));
}
#[test]
@@ -365,6 +484,25 @@ mod tests {
assert_eq!(constrain(&e, &f, Vec2::new(-7.0, 9.0), true), Vec2::new(4.0, 5.0));
}
#[test]
fn a_locked_second_value_holds_the_cursor_with_the_first_box_empty() {
// #3201: `40<90` locked by Tab, then the 40 erased: `<90` still holds the angle.
let base = Vec2::new(1.0, 1.0);
let f = second_point(base);
let e = parse("<90", &f).unwrap();
assert!(holds_cursor(&e, true));
assert!(!holds_cursor(&e, false));
// Pointer at (3,4) from the base: the live distance 5 is laid along 90 degrees.
assert!(close(Some(constrain(&e, &f, Vec2::new(4.0, 5.0), true)), Vec2::new(1.0, 6.0)));
// Not locked: a typed angle alone does not hold the cursor.
assert_eq!(constrain(&e, &f, Vec2::new(4.0, 5.0), false), Vec2::new(4.0, 5.0));
let e = parse(",7", &f).unwrap();
assert_eq!(constrain(&e, &f, Vec2::new(4.0, 5.0), true), Vec2::new(4.0, 8.0));
// Nothing typed in either box holds nothing.
let e = parse("<", &f).unwrap();
assert!(!holds_cursor(&e, true));
}
#[test]
fn options_menu_cycles_the_keywords() {
assert_eq!(OptionsMenu::open(&[]), None);