Greek: commands, aliases and prompt keywords typed with the Greek layout, and 46 missing Greek rows (#2722)

**What**

Typing a command with the Greek keyboard layout active (ΛΙΝΕ for LINE, ΜΙΡΡΟΡ for MIRROR) now works like typing the Latin name, in four places: starting a command, answering a prompt keyword (ΘΝΔΟ = Undo), the selection words at "Select objects" (ΑΛΛ = ALL), and command-line AutoComplete. The layout puts each Greek letter on the key of the Latin letter it sounds like (θ on U, ψ on C, ω on V, Q types `;`, W the final sigma), so `keyboard::latin_keys` maps letter by letter and ignores accents, including a combining tonos or dialytika straight after its letter. It returns `None` for a word with no Greek letter, so Latin input is never touched. ASCII characters in a Greek word are kept, in lower case (the dash of `-ΛΑΥΕΡ`), and a word with any other character is not read as Latin keys.

A command the interface handles itself answers to its Greek-typed name too: ΨΛΟΣΕ asks about unsaved changes as CLOSE does, `;ΣΑΩΕ` opens the Save picker for a drawing without a file, ΛΑΥΕΡ opens the Layers dialog.

What keeps existing behaviour:
- A word that is already a command, alias or LISP function keeps its own meaning, as typed or in another case or accent (a Greek `(defun c:ΛΙΝΕ …)` runs as itself, also when typed λινε).
- A keyword a prompt offers in its own Greek spelling (a LISP program's list) wins over its Latin reading, with Greek case folded.
- A selection word wins over a keyword on the same key, as it does for Latin typing: at COUNT's "Select object to count or [List/Spaces]", Λ is Last, like L.
- A name that exists wins over the keyword or selection word its keys spell: an existing block at BEDIT's "block name or select" and at BLOCKREPLACE's two name prompts (a block called Μ opens at BEDIT, it is not Multiple), and a loaded hatch pattern at HATCH's pattern prompt (a pattern called ΣΟΛΙΔ is that pattern, not Solid). The name is found in any case or accent and the command gets it as stored.
- Only the lookup reads the Greek keys: text that is no selection word reaches the command as typed (a Greek block name at BEDIT's "block name or select"), and an unknown Greek command is reported as typed.

Known and accepted:
- At a prompt that takes a name and offers a keyword, a Greek word whose keys spell the keyword is the keyword while no block has that name (Σ is Select at BLOCKREPLACE), as the Latin `S` is there.
- Two aliases whose Greek names differ only in case or accent can both exist (the alias editor folds ASCII only). Each runs when typed as stored; another spelling of the word runs the first of them in the store's order.
- Object snap overrides and the other point modifiers (END, FROM, M2P, TT, TK, `.X`) are not read from Greek-layout typing. They need the Latin layout, as before.
- Calls by command id are unchanged: a `cmd {json}` line and `execute` (control channel, MCP) do not read a Greek-typed name.
- In a script a line that starts with `;` is still a comment, so a line `;ΣΑΩΕ` there is not QSAVE.

Also adds 46 `el.tsv` rows for strings that were in the source but missing from the catalog when the rows were written (alias editor, save-on-close and units dialogs, a few menu and command labels). On this head the i18n report lists 39 strings that fall back to English for `el` (mostly keyboard shortcuts, right-click customization and alias import); they are not in this PR. Four command labels keep the English name in parentheses, like the rest of the catalog. The `el.tsv` row of `ATTRIBUTION.md` credits these rows (AI-assisted, read by the contributor, a native Greek speaker), and `contributors/people.toml` has the author's entry.

**Tests**
- `keyboard::tests`: the mapping, non-Greek words left alone, combining marks only straight after a Greek letter, one Greek word in any case, accent or final sigma, a character the layout does not type is no spelling of a Greek letter (the micro sign is not μ), 100 000-letter and malformed input do not panic
- `engine/tests/it/greek_keyboard.rs`: ΛΙΝΕ draws a line (lower case and accents too), `;ΣΑΩΕ`, an unknown Greek word is reported as typed, the selection word ΑΛΛ, Λ, λ and ΛΑΣΤ at COUNT's prompt count like L (Last, not the List option), keywords at MIRROR's prompt (Ν is read as No and keeps the sources, Υ erases them), a Greek LISP command runs as itself and in any case or accent, a Greek block name at BEDIT reaches the command as typed, a block called Μ opens at BEDIT (in either case), a block called Σ at BLOCKREPLACE, a loaded pattern called ΣΟΛΙΔ at HATCH's pattern prompt (upper case, lower case, accented)
- `engine/tests/greek_keyboard_aliases.rs` (its own binary, the alias store is process-global): a Greek alias keeps its meaning, as typed and in any case or accent; a word of 1 000 000 Greek letters is looked up among 5 000 Greek aliases within 5 s (170 s before the word was folded once per lookup)
- `prompt::tests`: a Greek keyword is matched as spelled, before its Latin reading
- `ui-egui`: ΨΛΟΣΕ asks before it closes a drawing with unsaved changes, and a LISP `c:ΨΛΟΣΕ` still runs as itself; ΛΑΥΕΡ (also λάυερ) opens the Layers dialog and `;ΣΑΩΕ` the Save picker; AutoComplete reads a Greek prefix as Latin keys, offers the Greek alias that Enter would run, and leaves a Greek word the drawing's LISP defines as typed
- Each fix after review landed with a test that failed before it.

**What ran** on e171e083, `cargo xtask ci` step by step: `cargo fmt --all -- --check` and `cargo clippy --workspace --all-targets -- -D warnings` clean; `cargo test --workspace --lib --bins --tests --no-fail-fast`: 3759 passed, 0 failed, 28 ignored; the doctest step (the workspace has no doctests), the i18n report, `cargo xtask assets`, `cargo xtask layers` and `cargo xtask wasm` passed. The same steps passed on e171e083 merged with main at e1d379ad, a local merge that is not pushed: 3761 passed, 0 failed, 28 ignored.

Main is merged in. The merge commit e3b3a2e0 had kept only this branch's side of `cmd/file.rs` and `cmd/file/pgp.rs`; e8a79d19 restores main's alias-persistence helpers and exports next to `greek_alias`, so those two files are main's again plus this PR's own lines.

**Docs (not edited here, per AGENTS.md)**: `docs/localization.md` "Greek (`el`) interface" and `docs/localization-parity.md` row "Greek | el" (its row count) could mention that commands typed with the Greek layout are accepted.

Nothing here is Autodesk-derived: the mapping is the standard Greek layout, written from the layout itself.

<!-- This is an auto-generated comment: release notes by coderabbit.ai -->

## Summary by CodeRabbit

* **New Features**
  * Greek keyboard-layout input is recognized as Latin keystrokes when entering commands, aliases, autocomplete prefixes, selection keywords, and prompt options.
  * Greek commands and aliases can be matched across case and accent variants. Existing commands, aliases, and matching block names take precedence over Greek-layout interpretations; unrecognized input retains its original text.
  * At prompts that accept either a block name or a selection keyword, Greek input is treated as a name when a matching block exists; otherwise, it can be interpreted as a selection keyword.
  * Greek-layout input can also match loaded or built-in hatch pattern names, which take precedence over prompt keyword interpretation.
  * In BLOCKREPLACE prompts, you can select a block reference to choose a block.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->
This commit is contained in:
Dimitrios Vidalis
2026-11-15 12:12:28 +01:00
committed by GitHub
parent e43c39c55e
commit 7064a685a8
21 changed files with 825 additions and 35 deletions
+1 -1
View File
@@ -77,6 +77,6 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied |
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading pending |
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted); 46 later rows: @V1dalTheAbidal with Claude Code (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; the 46 later rows were read by their contributor, a native Greek speaker; independent native proofreading of the whole file pending |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending |
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
+3
View File
@@ -118,3 +118,6 @@ sync_github_name = true
[people.helenkwok]
real_name = "Helen Kwok"
[people.V1dalTheAbidal]
sync_github_name = true
+4 -2
View File
@@ -184,8 +184,10 @@ impl Interactive for BlockreplaceM {
}
fn prompt(&self, _s: &Session) -> Prompt {
match self.stage {
Stage::Old => Prompt::new("Enter the name of the block to replace", Accept::TEXT).kw(&["?", "Select"]),
Stage::New => Prompt::new(format!("Enter the name of the replacement block for {}", self.old), Accept::TEXT).kw(&["?", "Select"]),
Stage::Old => Prompt::new("Enter the name of the block to replace", Accept::TEXT).kw(&["?", "Select"]).takes_block(),
Stage::New => {
Prompt::new(format!("Enter the name of the replacement block for {}", self.old), Accept::TEXT).kw(&["?", "Select"]).takes_block()
}
Stage::Select => Prompt::new("Select a block reference", Accept::SELECT),
Stage::Purge => Prompt::new(format!("Purge the unreferenced block definition {}?", self.old), KW).kw(&["Yes", "No"]).default("Yes"),
}
+1 -1
View File
@@ -17,7 +17,7 @@ use crate::{Accept, Input, Prompt, Result, Session, Step};
/// The rules the Command Aliases dialog checks before it sends an alias to ALIASEDIT.
pub use pgp::{MAX_ALIAS_PROFILE_BYTES, MAX_ALIASES, alias_name, alias_profile, command_id, restore_aliases};
pub(crate) use pgp::{specs as alias_specs, user_alias};
pub(crate) use pgp::{greek_alias, specs as alias_specs, user_alias};
pub use template::{qnew_template, set_qnew_template};
/// Largest drawing accepted from a local path, matching the per-file xref limit. A path naming an
+6
View File
@@ -59,6 +59,12 @@ pub(crate) fn user_alias(name: &str) -> Option<String> {
store().map.get(name).cloned()
}
/// The user alias that is the Greek word `word` in another case or accent.
pub(crate) fn greek_alias(word: &str) -> Option<String> {
let same = crate::keyboard::same_greek_word_as(word)?;
store().map.keys().find(|alias| same(alias)).cloned()
}
/// The user aliases and the file REINIT reads, as the host's user profile keeps them:
/// `{"aliases": {alias: command}, "file": path or null}`. Not drawing data.
pub fn alias_profile() -> Value {
+14 -1
View File
@@ -533,6 +533,19 @@ fn run_region(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "message": format!("{n} Region(s) created.") }))
}
/// Whether the upper-case `name` is a pattern: a standard one or a loaded one.
fn pattern_exists(name: &str) -> bool {
cadcraft_doc::library::pattern(name).is_some() || patfile::user_pattern(name).is_some()
}
/// The existing pattern `name` means, typed at the pattern prompt: read upper-cased, else a loaded
/// pattern's own name when only its Greek spelling differs in case or accent (σολιδ for ΣΟΛΙΔ).
pub(crate) fn pattern_named(name: &str) -> Option<String> {
let name = name.trim();
let up = name.to_ascii_uppercase();
if pattern_exists(&up) { Some(up) } else { patfile::user_pattern_name(name) }
}
/// The origin sub-prompt's keywords (a point sets a new origin).
const ORIGIN_KW: [&str; 6] = ["Bottom left", "bottom Right", "Top left", "top riGht", "Center", "Use current"];
@@ -597,7 +610,7 @@ impl HatchM {
Some(n) => n,
None => t.trim().to_ascii_uppercase(),
};
if cadcraft_doc::library::pattern(&up).is_some() || patfile::user_pattern(&up).is_some() {
if pattern_exists(&up) {
self.settings.pattern = up.clone();
s.doc_mut()?.header.set_str("HPNAME", &up);
} else {
+7
View File
@@ -28,6 +28,13 @@ pub(crate) fn user_pattern(name: &str) -> Option<UserPattern> {
store().iter().find(|p| p.name.eq_ignore_ascii_case(name)).cloned()
}
/// The name of the user pattern that is the Greek word `name` in another case or accent
/// ([`user_pattern`] folds ASCII only).
pub(crate) fn user_pattern_name(name: &str) -> Option<String> {
let same = crate::keyboard::same_greek_word_as(name)?;
store().iter().find(|p| same(&p.name)).map(|p| p.name.clone())
}
/// The line families a new hatch of pattern `name` carries: a user pattern's, else none (the
/// library's patterns are drawn and saved from the library).
pub(crate) fn lines_for(name: &str) -> Vec<PatternLine> {
+186
View File
@@ -0,0 +1,186 @@
//! Words typed on a Greek keyboard layout.
//!
//! With the Greek layout active, the keys that type LINE produce ΛΙΝΕ. Command names, aliases and
//! prompt keywords are Latin, so a Greek speaker would have to switch layouts for every command.
//! [`latin_keys`] reads a word as the Latin keys that produced it (the layout puts each Greek
//! letter on the key of the Latin letter it sounds like): the command line then accepts ΛΙΝΕ and
//! ΣΤΡΕΤΨΗ as LINE and STRETCH. Accents (the layout's dead key) are ignored.
/// The Latin key a Greek letter is typed on (lower case, accents removed).
fn key_of(c: char) -> Option<char> {
Some(match c {
'α' | 'ά' => 'a',
'β' => 'b',
'γ' => 'g',
'δ' => 'd',
'ε' | 'έ' => 'e',
'ζ' => 'z',
'η' | 'ή' => 'h',
'θ' => 'u',
'ι' | 'ί' | 'ϊ' | 'ΐ' => 'i',
'κ' => 'k',
'λ' => 'l',
'μ' => 'm',
'ν' => 'n',
'ξ' => 'j',
'ο' | 'ό' => 'o',
'π' => 'p',
'ρ' => 'r',
'σ' => 's',
// The W key types the final sigma.
'ς' => 'w',
'τ' => 't',
'υ' | 'ύ' | 'ϋ' | 'ΰ' => 'y',
'φ' => 'f',
'χ' => 'x',
'ψ' => 'c',
'ω' | 'ώ' => 'v',
// The Q key types the semicolon, which Greek text writes as ";" or U+037E.
';' | '\u{37e}' => 'q',
_ => return None,
})
}
/// Whether `c` is a Greek letter (the basic and accented ranges the layout types).
fn is_greek_letter(c: char) -> bool {
matches!(c, '\u{386}'..='\u{3ce}') && c != '\u{387}'
}
/// `word` read as the Latin keys of a Greek-layout keyboard, lower case: `Some` only when the word
/// has a Greek letter and every character is a Greek letter the layout types, the semicolon on
/// the Q key, or ASCII (itself, in lower case). A combining tonos or dialytika, the accent of
/// decomposed text, is ignored like the accent of a precomposed letter, but only straight after
/// the Greek letter it accents and once each: anywhere else the word is not Greek-layout typing.
pub fn latin_keys(word: &str) -> Option<String> {
let mut greek = false;
// What the previous Greek letter already carries (tonos, dialytika); `None` when the previous
// character is not a Greek letter, which leaves a combining mark nothing to accent.
let mut marks: Option<(bool, bool)> = None;
let mut out = String::with_capacity(word.len());
for c in word.chars() {
if matches!(c, '\u{301}' | '\u{308}') {
let (tonos, dialytika) = marks.as_mut()?;
if std::mem::replace(if c == '\u{301}' { tonos } else { dialytika }, true) {
return None;
}
continue;
}
if c.is_ascii() {
// The Q key types the ASCII semicolon in the Greek layout; every other ASCII character is itself.
out.push(if c == ';' { 'q' } else { c.to_ascii_lowercase() });
marks = None;
continue;
}
let lower = c.to_lowercase().next().unwrap_or(c);
out.push(key_of(lower)?);
let letter = is_greek_letter(lower);
greek |= letter;
marks = letter.then_some((false, false));
}
greek.then_some(out)
}
/// `word` with its case, accents and final sigma folded away, when it is Greek-layout typing: every
/// spelling of one Greek word gives the same string. It is the word's keys, with the final sigma
/// read as the letter sigma instead of the W key.
pub fn greek_fold(word: &str) -> Option<String> {
latin_keys(&word.replace('ς', "σ"))
}
/// Whether `a` and `b` are one Greek word, whatever their case, accents or final sigma.
pub fn same_greek_word(a: &str, b: &str) -> bool {
same_greek_word_as(b).is_some_and(|same| same(a))
}
/// A test for "is the Greek word `word`, whatever the case, accents or final sigma", or `None`
/// when `word` is not Greek-layout typing. `word` is folded here, once: looking a typed word up
/// among many names costs its length once, not once for every name.
pub fn same_greek_word_as(word: &str) -> Option<impl Fn(&str) -> bool> {
let fold = greek_fold(word)?;
Some(move |name: &str| greek_fold(name).as_deref() == Some(fold.as_str()))
}
#[cfg(test)]
mod tests {
use super::{latin_keys, same_greek_word};
/// One Greek word compares equal in any case, accent or final sigma; another word, or a Latin
/// one, does not.
#[test]
fn one_greek_word_is_the_same_in_any_case_accent_or_final_sigma() {
for (a, b) in [("ΣΟΛΙΔ", "σολιδ"), ("ΣΟΛΙΔ", "σολίδ"), ("ΛΑΣ", "λας"), ("ΛΑΣ", "λασ"), ("ΛΙ\u{301}ΝΕ", "λινε")]
{
assert!(same_greek_word(a, b), "{a} {b}");
}
for (a, b) in [("ΣΟΛΙΔ", "ΣΟΛΙ"), ("ΣΟΛΙΔ", "solid"), ("solid", "SOLID")] {
assert!(!same_greek_word(a, b), "{a} {b}");
}
}
/// A character the layout does not type is never taken for the Greek letter Unicode upper-cases
/// it to: the micro sign is not μ, the long s and the sharp s are not σ, an alpha with an iota
/// subscript is not αι, the theta symbol is not θ.
#[test]
fn a_character_the_layout_does_not_type_is_no_spelling_of_a_greek_letter() {
let pairs = [("\u{b5}", "μ"), ("Λ\u{17f}", "ΛΣ"), ("Λ\u{df}", "ΛΣΣ"), ("\u{1fb3}", "αι"), ("\u{3d1}", "θ")];
let same: Vec<_> = pairs.iter().filter(|(a, b)| same_greek_word(a, b) || same_greek_word(b, a)).collect();
assert!(same.is_empty(), "{same:?}");
}
/// Greek-layout typing reads as its Latin keys: plain, accented and decomposed letters, the Q
/// and W keys, ASCII prefixes.
#[test]
fn greek_layout_commands_read_as_their_latin_keys() {
assert_eq!(latin_keys("ΛΙΝΕ").as_deref(), Some("line"));
assert_eq!(latin_keys("λινε").as_deref(), Some("line"));
assert_eq!(latin_keys("ΣΤΡΕΤΨΗ").as_deref(), Some("stretch"));
assert_eq!(latin_keys("ΜΙΡΡΟΡ").as_deref(), Some("mirror"));
assert_eq!(latin_keys("ΘΝΔΟ").as_deref(), Some("undo"));
// The Q key types ";", the W key the final sigma.
assert_eq!(latin_keys(";ΣΑΩΕ").as_deref(), Some("qsave"));
assert_eq!(latin_keys("ςΒΛΟΨΚ").as_deref(), Some("wblock"));
// Accented letters (the layout's dead key) read as the plain letter.
assert_eq!(latin_keys("ΛΊΝΕ").as_deref(), Some("line"));
assert_eq!(latin_keys("ΆΡΡΑΥ").as_deref(), Some("array"));
// The same accents written as a combining mark after the letter (decomposed text).
assert_eq!(latin_keys("ΛΙ\u{301}ΝΕ").as_deref(), Some("line"));
assert_eq!(latin_keys("ΛΙΝΕ\u{301}").as_deref(), Some("line"));
assert_eq!(latin_keys("ΛΙ\u{308}ΝΕ").as_deref(), Some("line"));
assert_eq!(latin_keys("ΛΙ\u{308}\u{301}ΝΕ").as_deref(), Some("line"), "dialytika and tonos on one letter");
// Prefixes and digits are kept.
assert_eq!(latin_keys("-ΛΑΥΕΡ").as_deref(), Some("-layer"));
assert_eq!(latin_keys("_ΛΙΝΕ").as_deref(), Some("_line"));
}
/// A word with no Greek letter, or with a character the layout does not type, is not read.
#[test]
fn words_that_are_not_greek_layout_typing_are_left_alone() {
assert_eq!(latin_keys("line"), None, "no Greek letter");
assert_eq!(latin_keys(""), None);
assert_eq!(latin_keys(";"), None, "a semicolon alone is not a word");
assert_eq!(latin_keys("ΛΙΝΕ Ж"), None, "a letter the layout does not type");
assert_eq!(latin_keys("ΛΙΝΕ 日本"), None);
assert_eq!(latin_keys("\u{387}"), None, "the ano teleia is punctuation, not a letter");
}
/// A combining tonos or dialytika counts only straight after a Greek letter, and once each.
#[test]
fn a_combining_mark_must_follow_the_greek_letter_it_accents() {
assert_eq!(latin_keys("\u{301}ΛΙΝΕ"), None, "no letter before the mark");
assert_eq!(latin_keys("\u{308}ΛΙΝΕ"), None);
assert_eq!(latin_keys("ΛΙΝΕ-\u{301}"), None, "after punctuation");
assert_eq!(latin_keys("a\u{301}ΛΙΝΕ"), None, "after a Latin letter");
assert_eq!(latin_keys("Λ\u{301}\u{301}ΙΝΕ"), None, "a second tonos on one letter");
assert_eq!(latin_keys("Λ\u{308}\u{308}ΙΝΕ"), None, "a second dialytika on one letter");
}
/// A 100 000-letter word and odd code points are read or refused; nothing panics.
#[test]
fn hostile_text_never_panics() {
let long = "Ω".repeat(100_000);
assert_eq!(latin_keys(&long).map(|s| s.len()), Some(100_000));
for s in ["\u{0}", "\u{301}", "ΛΙΝΕ\u{301}", "\u{10ffff}", "ς\u{3c2}\u{3a3}"] {
let _ = latin_keys(s);
}
}
}
+1
View File
@@ -22,6 +22,7 @@ mod finite;
pub mod grip_dims;
pub mod grips;
mod guard;
pub mod keyboard;
pub mod lisp;
pub mod mtext_edit;
pub mod pointmod;
+52 -2
View File
@@ -102,6 +102,10 @@ pub struct Prompt {
/// the routine writes, so it cannot be read for the word "Select" (#1598).
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub picks_one: bool,
/// The prompt takes a block's name as well as its keywords: a Greek word that is an existing
/// block's name is that block, not a keyword read from its Latin keys.
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub takes_block: bool,
}
/// Parse `@distance<angle` (relative polar), returning `(distance, angle in radians)`.
@@ -136,6 +140,11 @@ impl Prompt {
self.picker = Some(p);
self
}
/// Takes a block's name besides its keywords (the `takes_block` field).
pub fn takes_block(mut self) -> Self {
self.takes_block = true;
self
}
pub fn kw(mut self, k: &[&str]) -> Self {
self.keywords = k.iter().map(ToString::to_string).collect();
self
@@ -215,6 +224,24 @@ impl Prompt {
return None;
}
let tl = t.to_ascii_lowercase();
// A keyword typed with the Greek keyboard layout active (ΘΝΔΟ for Undo) is its Latin keys, unless
// the prompt offers that spelling itself (a Greek keyword in a LISP program's list): its word
// or a prefix of it as typed (ΘΝ for ΘΝΔΟ, not UN for Undo) is read before the Latin keys.
if let Some(latin) = crate::keyboard::latin_keys(t) {
// Greek letters have case, accents and a final sigma, which the ASCII-only folding above does not see.
let typed = crate::keyboard::greek_fold(t).unwrap_or_else(|| latin.clone());
let greek = || self.keywords.iter().filter_map(|k| crate::keyboard::greek_fold(k).map(|fold| (k, fold)));
return greek()
.find(|(_, k)| *k == typed)
.or_else(|| greek().find(|(_, k)| k.starts_with(&typed)))
.map(|(k, _)| k.clone())
.or_else(|| self.match_latin_keyword(&latin));
}
self.match_latin_keyword(&tl)
}
/// [`Prompt::match_keyword`] for text already read as Latin letters, in lower case.
fn match_latin_keyword(&self, tl: &str) -> Option<String> {
let keys = self.keywords.iter().map(|k| {
let shortcut: String = k.chars().filter(|c| c.is_ascii_uppercase() || c.is_ascii_digit()).collect::<String>().to_ascii_lowercase();
let shortcut =
@@ -227,8 +254,8 @@ impl Prompt {
// CHPROP: "Ambiguous response, please clarify..."), `LTS` is ltScale.
let past_capitals = |k: &str| k.char_indices().rfind(|(_, c)| c.is_ascii_uppercase() || c.is_ascii_digit()).map_or(1, |(i, _)| i + 1);
keys.clone()
.find(|(_, kl, sc)| tl == *kl || tl == *sc)
.or_else(|| keys.clone().find(|(k, kl, _)| tl.len() >= past_capitals(k) && kl.starts_with(&tl)))
.find(|(_, kl, sc)| tl == kl.as_str() || tl == sc.as_str())
.or_else(|| keys.clone().find(|(k, kl, _)| tl.len() >= past_capitals(k) && kl.starts_with(tl)))
.map(|(k, _, _)| k.clone())
}
}
@@ -394,6 +421,29 @@ mod tests {
assert_eq!(parse_point("1,2,3,4", last), None);
}
/// A keyword the prompt offers in Greek is matched as spelled (any case, accent or final sigma,
/// or a prefix) before the Latin reading of the same keys; without one, the keys answer the
/// Latin keyword.
#[test]
fn a_greek_keyword_is_matched_as_spelled_before_its_latin_reading() {
// ΘΝΔΟ is the keys U-N-D-O, so it answers Undo, unless the prompt offers the Greek word itself
// (a LISP program's keyword list).
let both = Prompt::new("", Accept::TEXT).kw(&["Undo", "ΘΝΔΟ"]);
assert_eq!(both.match_keyword("ΘΝΔΟ").as_deref(), Some("ΘΝΔΟ"));
assert_eq!(both.match_keyword("θνδο").as_deref(), Some("ΘΝΔΟ"), "Greek case is folded like Latin case");
assert_eq!(both.match_keyword("Undo").as_deref(), Some("Undo"));
// A prefix of the Greek word as typed (ΘΝ) is that keyword, not the Latin prefix UN of Undo.
assert_eq!(both.match_keyword("ΘΝ").as_deref(), Some("ΘΝΔΟ"));
assert_eq!(both.match_keyword("θν").as_deref(), Some("ΘΝΔΟ"), "in either case");
assert_eq!(both.match_keyword("θνδό").as_deref(), Some("ΘΝΔΟ"), "with an accent");
let sigma = Prompt::new("", Accept::TEXT).kw(&["Last", "ΛΑΣΤ"]);
assert_eq!(sigma.match_keyword("λας").as_deref(), Some("ΛΑΣΤ"), "a final sigma folds too");
let latin = Prompt::new("", Accept::TEXT).kw(&["Undo"]);
assert_eq!(latin.match_keyword("ΘΝ").as_deref(), Some("Undo"));
assert_eq!(latin.match_keyword("ΘΝΔΟ").as_deref(), Some("Undo"));
assert_eq!(latin.match_keyword("Θ").as_deref(), Some("Undo"), "a Greek-layout shortcut still works");
}
#[test]
fn keywords() {
let p = Prompt::new("Specify next point", Accept::POINT).kw(&["Undo", "Close"]);
+20 -3
View File
@@ -116,9 +116,26 @@ impl Session {
};
}
// At "Select objects" prompts the selection modes (Previous, Last, ALL) win over a command
// keyword sharing the letter (HATCH's "picK internal point" against `P`).
let selection_mode = prompt.accept.select
&& matches!(tt.strip_prefix('_').unwrap_or(tt).to_ascii_lowercase().as_str(), "all" | "l" | "last" | "p" | "previous");
// keyword sharing the letter (HATCH's "picK internal point" against `P`). A word typed with
// the Greek keyboard layout active is read by its keys there too: Λ is Last at COUNT's prompt,
// not List.
let selection_mode = prompt.accept.select && {
let word = tt.strip_prefix('_').unwrap_or(tt);
let keys = crate::keyboard::latin_keys(word).unwrap_or_else(|| word.to_ascii_lowercase());
matches!(keys.as_str(), "all" | "l" | "last" | "p" | "previous")
};
// A Greek word that is an existing name at a prompt that takes one is that name, in any case:
// ΣΟΛΙΔ is also the keys of Solid.
let existing = if matches!(prompt.picker, Some(crate::Picker::HatchPattern(_))) {
crate::keyboard::greek_fold(tt).and_then(|_| cmd::hatch::pattern_named(tt))
} else if prompt.takes_block {
self.greek_block_name(tt)
} else {
None
};
if let Some(name) = existing {
return self.input(Input::Text(name));
}
// A leading underscore asks for a keyword by its English name, whatever the interface
// language (`_M`, `_Yes`): scripts and LISP routines write them that way. (Snap
// overrides such as `_cen` were taken above.)
+63 -8
View File
@@ -8,6 +8,39 @@ use super::{
impl Session {
// ---------------- interactive commands ----------------
/// Whether `name`, as typed, is a command, an alias or a LISP command: the lookups
/// [`Session::start`] dispatches by, so only ASCII is lower-cased and a Greek alias stays as stored.
fn names_a_command(&self, name: &str) -> bool {
let lower = name.trim_start_matches(['_', '.', '-']).to_ascii_lowercase();
let dashed = name.trim_start_matches(['_', '.']);
find_command(&cmd::resolve_alias(dashed)).is_some()
|| find_command(&cmd::resolve_alias(&lower)).is_some()
|| self.lisp_command(&lower).is_some()
}
/// The alias or LISP command that is the Greek word `name` in another case or accent (λινε for
/// c:ΛΙΝΕ): those lookups fold ASCII only.
fn greek_command_name(&self, name: &str) -> Option<String> {
let bare = name.trim_start_matches(['_', '.', '-']);
let same = crate::keyboard::same_greek_word_as(bare)?;
let lisp = || self.lisp_commands().into_iter().find(|c| same(c) && self.lisp_command(c).is_some());
cmd::file::greek_alias(bare).or_else(lisp)
}
/// Whether the Greek word `name` is a command of its own, which [`Session::start`] runs instead
/// of the Latin name its keys type.
pub fn greek_word_is_a_command(&self, name: &str) -> bool {
self.names_a_command(name) || self.greek_command_name(name).is_some()
}
/// The existing block that is the Greek word `word`: as spelled, else in another case or accent
/// (μ for Μ).
pub(super) fn greek_block_name(&self, word: &str) -> Option<String> {
let same = crate::keyboard::same_greek_word_as(word)?;
let blocks = &self.doc().ok()?.blocks;
blocks.keys().find(|k| *k == word).or_else(|| blocks.keys().find(|k| same(k))).cloned()
}
/// Start a command by name or alias as if typed at the command line.
pub fn start(&mut self, name: &str) -> Result<()> {
self.last_polar = None;
@@ -17,6 +50,12 @@ impl Session {
Some(n) => (true, n),
None => (false, name),
};
// A name typed with the Greek keyboard layout active (ΛΙΝΕ for LINE) is the Latin name's keys,
// unless it is a command, alias or LISP function of its own, in any case or accent.
let typed = name;
let latin =
crate::keyboard::latin_keys(name).filter(|_| !self.names_a_command(name)).map(|latin| self.greek_command_name(name).unwrap_or(latin));
let name = latin.as_deref().unwrap_or(name);
let lower = name.trim_start_matches(['_', '.', '-']).to_ascii_lowercase();
// A command-line form with an id of its own (-ATTEDIT) is not the command it prefixes.
let dashed = cmd::resolve_alias(&name.trim_start_matches(['_', '.']).to_ascii_lowercase());
@@ -37,7 +76,7 @@ impl Session {
self.start(if transparent { "'setvar" } else { "setvar" })?;
return self.input(Input::Text(var));
}
return Err(EngineError::UnknownCommand(name.to_string()));
return Err(EngineError::UnknownCommand(typed.to_string()));
};
if transparent && spec.transparent && self.running.is_some() {
// Transparent commands (zoom, pan…) run without cancelling the active one.
@@ -175,17 +214,33 @@ impl Session {
Input::Text(t) => Input::Text(t.trim().strip_prefix('_').map(str::to_string).unwrap_or(t)),
other => other,
};
if let Input::Text(t) | Input::Keyword(t) = &input
&& let Some(m) = select::SelectMode::from_keyword(t)
// A selection word typed with the Greek keyboard layout active (ΑΛΛ for ALL) is looked up as its
// Latin keys. Only the lookup is: text that is no selection word (a block name at BEDIT's prompt,
// which also takes a selection) reaches the command as typed. The name of an existing block at
// a prompt that takes a name reaches it as stored, in whatever case it was typed: a block
// called Μ is that block there, not Multiple.
let block = match &input {
Input::Text(t) if prompt.accept.text => self.greek_block_name(t.trim()),
_ => None,
};
let is_block = block.is_some();
let input = block.map_or(input, Input::Text);
let word = match &input {
Input::Text(t) => Some(crate::keyboard::latin_keys(t.trim()).filter(|_| !is_block).unwrap_or_else(|| t.clone())),
Input::Keyword(k) => Some(k.clone()),
_ => None,
};
if let Some(w) = &word
&& let Some(m) = select::SelectMode::from_keyword(w)
{
self.pending_window = None;
self.select_mode = Some(m);
return Ok(None);
}
if let Input::Text(t) | Input::Keyword(t) = &input
&& !prompt.keywords.iter().any(|k| k.eq_ignore_ascii_case(t.trim()))
if let Some(w) = &word
&& !prompt.keywords.iter().any(|k| k.eq_ignore_ascii_case(w.trim()))
{
match t.trim().to_ascii_lowercase().as_str() {
match w.trim().to_ascii_lowercase().as_str() {
"si" | "single" => {
self.select_single = true;
return Ok(None);
@@ -213,8 +268,8 @@ impl Session {
}
}
}
Input::Text(ref t) | Input::Keyword(ref t) => {
let tl = t.trim().to_ascii_lowercase();
Input::Text(_) | Input::Keyword(_) => {
let tl = word.as_deref().unwrap_or_default().trim().to_ascii_lowercase();
let d = self.doc()?;
let store = d.space(&space);
let frozen = self.viewport_frozen();
@@ -0,0 +1,67 @@
//! A word typed with the Greek keyboard layout that is an alias of its own (ALIASEDIT) is that
//! alias, not the Latin name its keys type. The aliases are process-wide, so this file keeps to
//! one test at a time.
use std::sync::Mutex;
use cadcraft_engine::Session;
use cadcraft_engine::doc::EntityKind;
use serde_json::json;
/// The alias store is process-wide: each test holds this while it changes the aliases.
static ONE_AT_A_TIME: Mutex<()> = Mutex::new(());
/// A Greek word the user made an alias runs the alias's command, not the command its keys type.
#[test]
fn a_greek_alias_starts_its_command_not_the_latin_keys_command() {
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut s = Session::new();
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
// ΛΙΝΕ types LINE, but the user made it an alias of CIRCLE: aliases are stored as typed (only
// ASCII is lower-cased), and the alias wins.
s.execute("aliasedit", &json!({ "set": { "ΛΙΝΕ": "circle" } })).unwrap();
let ran = s.script(
"ΛΙΝΕ 0,0 5
",
);
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
ran.unwrap();
let doc = s.doc().unwrap();
let circles = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
let lines = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
assert_eq!((circles, lines), (1, 0), "the alias drew the circle, LINE was not started");
}
/// The alias is found when it is typed in lower case or with an accent too.
#[test]
fn a_greek_alias_starts_its_command_in_any_case_or_accent() {
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut s = Session::new();
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
s.execute("aliasedit", &json!({ "set": { "ΛΙΝΕ": "circle" } })).unwrap();
let ran: Vec<_> = ["λινε", "λίνε"].iter().map(|typed| s.script(&format!("{typed} 0,0 5\n"))).collect();
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
assert!(ran.iter().all(Result::is_ok), "{ran:?}");
let doc = s.doc().unwrap();
let circles = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
let lines = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
assert_eq!((circles, lines), (2, 0), "the alias drew both circles, LINE was not started");
}
/// 5 000 Greek aliases and a pasted word of a million letters that is none of them: looking it up
/// costs the word's length once, not once for every alias.
#[test]
fn a_long_greek_word_is_folded_once_however_many_greek_aliases_there_are() {
let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner());
let mut s = Session::new();
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
let set: serde_json::Map<String, serde_json::Value> = (0..5_000).map(|i| (format!("ΞΞ{i}"), json!("line"))).collect();
s.execute("aliasedit", &json!({ "set": set })).unwrap();
let word = "Ω".repeat(1_000_000);
let t = std::time::Instant::now();
let started = s.start(&word);
let took = t.elapsed();
s.execute("aliasedit", &json!({ "clear": true })).unwrap();
assert!(started.is_err(), "no command has those keys");
assert!(took.as_secs() < 5, "{took:?}");
}
+225
View File
@@ -0,0 +1,225 @@
//! A command or keyword typed with the Greek keyboard layout active (ΛΙΝΕ for LINE, ΘΝΔΟ for
//! Undo) works as its Latin name: the layout types each Greek letter on the Latin key it sounds
//! like.
use cadcraft_engine::Session;
use cadcraft_engine::doc::EntityKind;
use serde_json::json;
/// How many lines the drawing's model space holds.
fn lines(s: &Session) -> usize {
s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count()
}
/// ΛΙΝΕ draws a line like LINE, in lower case and with accents too; `;ΣΑΩΕ` starts QSAVE; a
/// Greek word that is no command's keys is reported as typed.
#[test]
fn greek_layout_commands_start_like_the_latin_ones() {
let mut s = Session::new();
s.script("ΛΙΝΕ 0,0 10,0\n\n").unwrap();
assert_eq!(lines(&s), 1, "{}", s.prompt_text());
// Accents the layout's dead key adds are ignored; lower case works too.
s.script("λίνε 0,5 10,5\n\n").unwrap();
assert_eq!(lines(&s), 2);
// The Q key types a semicolon: QSAVE is ";ΣΑΩΕ", which only starts the command (no file needed
// here: it reports, it never fails as an unknown command).
let err = s.start(";ΣΑΩΕ").map(|_| String::new()).unwrap_or_else(|e| e.to_string());
assert!(!err.contains("unknown command"), "{err}");
// A Greek word that is no command's keys is reported as typed, not as the Latin letters read from it.
let err = s.start("ΧΥΖ").unwrap_err().to_string();
assert!(err.contains("ΧΥΖ") && !err.contains("xyz"), "{err}");
}
/// A LISP command with a Greek name runs as itself, not as the command its keys type.
#[test]
fn a_greek_lisp_command_runs_as_itself_not_as_the_latin_keys_command() {
let mut s = Session::new();
// ΛΙΝΕ types LINE, but the routine defines a command of that Greek name: it is the command typed.
s.cmdline("(defun c:ΛΙΝΕ () (command \"_.CIRCLE\" '(0 0) 5) (princ))").unwrap();
s.cmdline("ΛΙΝΕ").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let doc = s.doc().unwrap();
let circles = doc.model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
assert_eq!((circles, lines(&s)), (1, 0), "the routine drew the circle, LINE was not started");
}
/// ΑΛΛ at "Select objects" selects everything, as ALL does.
#[test]
fn greek_layout_selection_words_select_like_the_latin_ones() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap();
s.execute("circle", &json!({ "center": [20, 0], "radius": 5 })).unwrap();
// ΑΛΛ is the keys A-L-L: ALL at the "Select objects" prompt.
s.script(
"ERASE ΑΛΛ
",
)
.unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!(s.doc().unwrap().model.is_empty(), "ΑΛΛ selected nothing");
}
/// Ν and Υ answer MIRROR's "Erase source objects?" as N and Y do.
#[test]
fn greek_layout_keywords_match_prompt_options() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap();
s.script("ΜΙΡΡΟΡ ALL\n\n0,0 10,0\n").unwrap();
// ... the last prompt asks whether to delete the sources: N (Greek layout: Ν) keeps them. Text
// the prompt does not know keeps them too, so what Ν is read as is checked itself.
let no = s.current_prompt().and_then(|p| p.match_keyword("Ν"));
assert_eq!(no.as_deref(), Some("No"), "{}", s.prompt_text());
s.script("Ν\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let circles = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
assert_eq!(circles, 2, "the circle and its mirror image");
// Υ (the Y key) answers Yes, which erases the source: unmatched Greek text would count as No, so
// only a recognised keyword gives this result.
let mut yes = Session::new();
yes.execute("circle", &json!({ "center": [0, 0], "radius": 5 })).unwrap();
yes.script(
"ΜΙΡΡΟΡ ALL
0,0 10,0
Υ
",
)
.unwrap();
assert!(yes.running.is_none(), "{}", yes.prompt_text());
let circles = yes.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
assert_eq!(circles, 1, "Υ answered Yes and the source was erased");
}
/// A Greek block name typed at BEDIT's "block name or select" opens that block: it is not read
/// as a selection word.
#[test]
fn a_greek_block_name_typed_at_a_name_or_select_prompt_reaches_the_command_as_typed() {
let mut s = Session::new();
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
s.execute("block", &json!({ "name": "ΠΟΡΤΑ", "base": [0, 0], "handles": [l] })).unwrap();
// BEDIT asks for a block name or a selected reference. ΠΟΡΤΑ is also the keys P-O-R-T-A, which a
// selection word would be read from, but no selection word is meant here: the name is typed as it is.
s.start("BEDIT").unwrap();
s.cmdline("ΠΟΡΤΑ").unwrap();
let open = s.state().unwrap().block_editor().map(str::to_string);
assert_eq!(open.as_deref(), Some("ΠΟΡΤΑ"), "{}", s.prompt_text());
}
/// Μ is the M key, Multiple at a selection prompt; once a block has that name, typing it at
/// BEDIT opens the block.
#[test]
fn a_block_named_like_a_greek_selection_word_opens_at_a_name_or_select_prompt() {
// The Greek capital Mu (U+039C) is the M key: Multiple at a selection prompt.
let mu = "\u{39c}";
let mut s = Session::new();
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
// With no block of that name it stays the selection word, which BEDIT's prompt waits through.
s.start("BEDIT").unwrap();
s.cmdline(mu).unwrap();
assert!(s.running.is_some(), "Multiple keeps the prompt: {}", s.prompt_text());
assert!(s.state().unwrap().block_editor().is_none());
s.cancel();
// Once a block has that name, typing it opens that block.
s.execute("block", &json!({ "name": mu, "base": [0, 0], "handles": [l] })).unwrap();
s.start("BEDIT").unwrap();
s.cmdline(mu).unwrap();
let open = s.state().unwrap().block_editor().map(str::to_string);
assert_eq!(open.as_deref(), Some(mu), "{}", s.prompt_text());
}
/// ΣΟΛΙΔ is the keys of Solid at HATCH's pattern prompt; once a loaded pattern has that name,
/// typing it in any case or accent chooses that pattern.
#[test]
fn a_loaded_pattern_named_like_the_greek_keys_of_solid_is_that_pattern_at_the_pattern_prompt() {
// ΣΟΛΙΔ is the keys S-O-L-I-D: Solid at HATCH's pattern prompt, which takes no scale or angle.
let mut s = Session::new();
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap();
s.start("hatch").unwrap();
s.input(cadcraft_engine::Input::Keyword("Pattern".into())).unwrap();
s.cmdline("ΣΟΛΙΔ").unwrap();
assert!(!s.prompt_text().contains("scale"), "Solid: {}", s.prompt_text());
s.cancel();
// A pattern file that defines a pattern of that name: typing the name chooses that pattern, which asks its scale.
s.execute("hatch.patterns", &json!({ "text": "*ΣΟΛΙΔ, test\n0,0,0,0,1\n" })).unwrap();
let asked = ["ΣΟΛΙΔ", "σολιδ", "σολίδ"].map(|typed| {
s.start("hatch").unwrap();
s.input(cadcraft_engine::Input::Keyword("Pattern".into())).unwrap();
s.cmdline(typed).unwrap();
let asked = s.prompt_text();
s.cancel();
asked
});
s.execute("hatch.patterns", &json!({ "clear": true })).unwrap();
assert!(asked.iter().all(|a| a.contains("scale")), "the loaded pattern, in any spelling: {asked:?}");
}
/// A LISP command with a Greek name runs when typed in upper case, lower case or with an accent.
#[test]
fn a_greek_lisp_command_runs_in_any_case_or_accent() {
for typed in ["ΛΙΝΕ", "λινε", "λίνε"] {
let mut s = Session::new();
s.cmdline("(defun c:ΛΙΝΕ () (command \"_.CIRCLE\" '(0 0) 5) (princ))").unwrap();
s.cmdline(typed).unwrap();
let circles = s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Circle(_))).count();
assert_eq!((circles, lines(&s)), (1, 0), "{typed}: {}", s.prompt_text());
}
}
/// A block called Μ opens at BEDIT when its name is typed in either case.
#[test]
fn a_block_opens_in_any_case_or_accent_at_a_prompt_that_also_takes_a_selection() {
for typed in ["\u{39c}", "\u{3bc}"] {
let mut s = Session::new();
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
s.execute("block", &json!({ "name": "\u{39c}", "base": [0, 0], "handles": [l] })).unwrap();
s.start("BEDIT").unwrap();
s.cmdline(typed).unwrap();
let open = s.state().unwrap().block_editor().map(str::to_string);
assert_eq!(open.as_deref(), Some("\u{39c}"), "{typed}: {}", s.prompt_text());
}
}
/// Σ is the S key, Select at BLOCKREPLACE; once a block has that name, typing it in either case
/// names the block.
#[test]
fn a_block_named_like_the_keys_of_select_is_that_block_at_blockreplace() {
let mut s = Session::new();
// Σ is the S key: the Select option of BLOCKREPLACE, while no block has that name.
s.start("BLOCKREPLACE").unwrap();
s.cmdline("Σ").unwrap();
assert!(s.prompt_text().contains("Select a block reference"), "{}", s.prompt_text());
s.cancel();
let l = s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap()["handles"][0].clone();
s.execute("block", &json!({ "name": "Σ", "base": [0, 0], "handles": [l] })).unwrap();
s.execute("insert", &json!({ "name": "Σ", "at": [0, 0] })).unwrap();
for typed in ["Σ", "σ"] {
s.start("BLOCKREPLACE").unwrap();
s.cmdline(typed).unwrap();
let asked = s.prompt_text();
s.cancel();
assert!(asked.contains("replacement block for Σ"), "{typed}: {asked}");
}
}
/// Λ is the L key. At COUNT's "Select object to count or [List/Spaces]" the Latin L is the selection
/// word Last, not the List option: the Greek key is read the same way, and so is the whole word.
#[test]
fn a_greek_selection_word_wins_over_a_keyword_on_the_same_key() {
let answer = |typed: &str| {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 1 })).unwrap();
s.execute("line", &json!({ "points": [[0, 0], [5, 0]] })).unwrap();
s.start("COUNT").unwrap();
let from = s.log.len();
s.cmdline(typed).unwrap();
s.log[from..].join("\n")
};
let last = answer("L");
assert!(last.contains("like the selected one"), "L counts the objects like the last one: {last}");
assert_ne!(last, answer("List"));
for typed in ["Λ", "λ", "ΛΑΣΤ"] {
assert_eq!(answer(typed), last, "{typed}");
}
}
+1
View File
@@ -52,6 +52,7 @@ mod extend_polyline_arc_end;
mod fillet_chamfer;
mod fix_holds_grips;
mod followups_626;
mod greek_keyboard;
mod grip_dim_input;
mod grip_options;
mod grip_selection;
+10 -3
View File
@@ -402,13 +402,21 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
}
}
/// The alias store is process-wide. A test of this crate that changes it holds this guard while
/// it does, so such tests take turns.
#[cfg(test)]
pub(crate) fn lock_alias_store() -> std::sync::MutexGuard<'static, ()> {
static LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
LOCK.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
#[cfg(test)]
mod tests {
use std::cell::RefCell;
use std::path::PathBuf;
use std::rc::Rc;
use std::sync::MutexGuard;
use std::sync::atomic::{AtomicU32, Ordering};
use std::sync::{Mutex, MutexGuard, PoisonError};
use cadcraft_engine::Session;
use serde_json::json;
@@ -419,8 +427,7 @@ mod tests {
/// The alias store is process-wide, so the tests that load files take turns and clear it.
fn alone() -> MutexGuard<'static, ()> {
static LOCK: Mutex<()> = Mutex::new(());
LOCK.lock().unwrap_or_else(PoisonError::into_inner)
super::lock_alias_store()
}
fn temp_dir(name: &str) -> PathBuf {
+21
View File
@@ -489,4 +489,25 @@ mod tests {
assert!(app.closing.is_none());
assert!(app.session.docs.is_empty());
}
/// CLOSE typed with the Greek keyboard layout active (ΨΛΟΣΕ) is the interface's CLOSE, which
/// asks about unsaved changes, not the engine's, which closes at once. A Greek word that is a
/// command of its own stays that command.
#[test]
fn close_typed_with_the_greek_layout_asks_before_it_closes() {
let mut app = app_with(&["A", "B"]);
dirty(&mut app, 1);
app.cmdline("ΨΛΟΣΕ");
assert_eq!(app.close_prompt(), Some("B"));
assert_eq!(titles(&app), ["A", "B"]);
app.answer_close(Choice::Cancel);
assert!(app.closing.is_none());
// The drawing's LISP defines a command of that Greek name: typing it runs that command.
app.cmdline("(defun c:ΨΛΟΣΕ () (princ))");
app.cmdline("ΨΛΟΣΕ");
assert!(app.closing.is_none());
assert_eq!(titles(&app), ["A", "B"]);
assert!(app.session.docs[1].is_dirty());
}
}
+73 -13
View File
@@ -102,7 +102,7 @@ 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() {
} else if let Some(s) = suggestions_in(&app.session, &app.cmd.buffer).first() {
app.cmd.buffer = s.id.clone();
}
}
@@ -118,12 +118,26 @@ pub struct Suggestion {
pub label: &'static str,
}
/// Matching command names/aliases for AutoComplete.
fn suggestions(prefix: &str) -> Vec<Suggestion> {
/// [`suggestions`] for what `session` can run: a Greek word that is a command of its own there (an
/// alias, a command the drawing's LISP defines) stays as typed.
fn suggestions_in(session: &cadcraft_engine::Session, prefix: &str) -> Vec<Suggestion> {
suggestions(prefix, &|word| session.greek_word_is_a_command(word))
}
/// Matching command names/aliases for AutoComplete. `is_own_command` tells whether a Greek-layout
/// word is a command of its own rather than the Latin name its keys type.
fn suggestions(prefix: &str, is_own_command: &dyn Fn(&str) -> bool) -> Vec<Suggestion> {
if prefix.is_empty() || prefix.contains(' ') {
return Vec::new();
}
let p = prefix.to_ascii_lowercase();
// Typed with the Greek keyboard layout (ΛΙΝ), it completes as the Latin name (LINE), unless the word
// as typed already names a command, alias or LISP command: that is what Enter runs.
let typed = prefix.to_ascii_lowercase();
let p = if cadcraft_engine::cmd::find_command(&cadcraft_engine::cmd::resolve_alias(&typed)).is_some() {
typed
} else {
cadcraft_engine::keyboard::latin_keys(prefix).filter(|_| !is_own_command(prefix)).unwrap_or(typed)
};
let mut out: Vec<Suggestion> = Vec::new();
let mut seen_ids: HashSet<&'static str> = HashSet::new();
@@ -444,7 +458,7 @@ 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() };
let completion = if app.session.prompting() { None } else { suggestions_in(&app.session, text.trim()).into_iter().next() };
app.cmdline_or(&text, completion.map(|s| s.id.to_ascii_lowercase()).as_deref());
}
@@ -585,7 +599,7 @@ 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 = suggestions_in(&app.session, &app.cmd.buffer);
if !sug.is_empty() {
let rh = 20.0;
let lr = Rect::from_min_size(
@@ -647,7 +661,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 = suggestions_in(&app.session, &app.cmd.buffer).len();
if k > 0 {
let above = if n == 0 { 0.0 } else { LINE_H * n as f32 + 6.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)));
@@ -757,6 +771,52 @@ mod tests {
frame(app, ctx, vec![Event::PointerButton { pos: at, button: PointerButton::Primary, pressed, modifiers: egui::Modifiers::default() }]);
}
/// A Greek-layout prefix completes like its Latin keys; a prefix in another script is matched
/// as it is.
#[test]
fn autocomplete_reads_a_greek_layout_prefix_as_its_latin_keys() {
// ΛΙΝ is the keys L-I-N on the Greek layout: it completes like the Latin prefix does.
let latin: Vec<String> = suggestions("lin", &|_| false).into_iter().map(|s| s.id).collect();
assert!(latin.iter().any(|id| id == "LINE"), "{latin:?}");
let greek: Vec<String> = suggestions("ΛΙΝ", &|_| false).into_iter().map(|s| s.id).collect();
assert_eq!(greek, latin);
// A prefix that is not Greek-layout typing is matched as it is.
assert!(suggestions("ЖЖЖ", &|_| false).is_empty());
}
/// A Greek word the user made an alias is offered as that alias's command, which is what Enter
/// runs.
#[test]
fn autocomplete_offers_the_greek_alias_the_user_defined_that_enter_would_run() {
// Enter runs a word that is an alias as typed, so AutoComplete must not read it as Latin keys first:
// Ξ is the J key (JOIN's alias), but the user made Ξ an alias of QSAVE. The alias store is
// process-wide and the alias dialog's tests clear it, so this test takes its turn with them.
let _alone = crate::aliasdlg::lock_alias_store();
let mut session = Session::empty();
session.execute("aliasedit", &serde_json::json!({ "set": { "Ξ": "qsave" } })).unwrap();
let first = suggestions("Ξ", &|_| false).into_iter().next().map(|s| s.id);
session.execute("aliasedit", &serde_json::json!({ "remove": ["Ξ"] })).unwrap();
assert_eq!(first.as_deref(), Some("QSAVE"));
}
/// A Greek word the drawing's LISP defines as a command is not completed to the Latin name of
/// its keys.
#[test]
fn autocomplete_leaves_a_greek_word_the_drawings_lisp_defines_as_typed() {
// ΛΙΝΕ is the keys of LINE, but the drawing defines a command of that Greek name: Enter runs that
// command, so Tab must not replace the word with LINE.
let mut session = Session::new();
session.cmdline("(defun c:ΛΙΝΕ () (princ))").unwrap();
for word in ["ΛΙΝΕ", "λινε", "λίνε"] {
assert!(suggestions_in(&session, word).is_empty(), "{word}: {:?}", suggestions_in(&session, word));
}
// Another word of the same keys is still read as Latin: Enter would start LINE for it too.
assert!(suggestions_in(&session, "ΛΙΝ").iter().any(|s| s.id == "LINE"));
// Without the definition ΛΙΝΕ completes as LINE.
let plain = Session::new();
assert!(suggestions_in(&plain, "ΛΙΝΕ").iter().any(|s| s.id == "LINE"));
}
#[test]
fn ime_preedit_is_shown_and_its_commit_is_inserted_once() {
use cadcraft_engine::geom::Vec2;
@@ -890,7 +950,7 @@ mod autocomplete_tests {
#[test]
fn exact_alias_is_first_suggestion_with_alias_display() {
let rec = suggestions("rec");
let rec = suggestions("rec", &|_| false);
assert!(!rec.is_empty());
assert_eq!(rec[0].id, "RECTANG");
assert_eq!(rec[0].display, "REC (RECTANG)");
@@ -900,26 +960,26 @@ mod autocomplete_tests {
assert_eq!(rec[1].id, "RECOVER");
assert_eq!(rec[1].display, "RECOVER");
let l = suggestions("l");
let l = suggestions("l", &|_| false);
assert_eq!(l[0].id, "LINE");
assert_eq!(l[0].display, "L (LINE)");
let c = suggestions("c");
let c = suggestions("c", &|_| false);
assert_eq!(c[0].id, "CIRCLE");
assert_eq!(c[0].display, "C (CIRCLE)");
let co = suggestions("co");
let co = suggestions("co", &|_| false);
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", &|_| false);
assert_eq!(rect[0].id, "RECTANG");
assert_eq!(rect[0].display, "RECTANG");
let line = suggestions("line");
let line = suggestions("line", &|_| false);
assert_eq!(line[0].id, "LINE");
assert_eq!(line[0].display, "LINE");
}
+46
View File
@@ -47,6 +47,9 @@
Add: Pick points Προσθήκη: επιλέξτε σημεία
Add: Select objects Προσθήκη: επιλέξτε αντικείμενα
Additional angles Πρόσθετες γωνίες
Add… Προσθήκη…
Alias Ψευδώνυμο
Alias file: {file} Αρχείο ψευδωνύμων: {file}
Align Στοίχιση
Align Multileaders Στοίχιση πολλαπλών γραμμών υπόδειξης (Multileaders)
Align Text Στοίχιση κειμένου
@@ -57,6 +60,8 @@
All Scales Όλες οι κλίμακες
All Used Layers Όλα τα χρησιμοποιούμενα επίπεδα (Layers)
An array that would create more objects than this is refused. Απορρίπτεται η διάταξη επειδή θα δημιουργούσε περισσότερα αντικείμενα από το επιτρεπτό όριο.
Analyze Shapes Ανάλυση σχημάτων
Analyze Usage Ανάλυση χρήσης
Angle Γωνία
Angular Γωνιακό
Animation Effects Εφέ κίνησης
@@ -89,6 +94,7 @@
Automatic save file location Θέση αρχείων αυτόματης αποθήκευσης
Axis, End Άξονας, τέλος
B B
Backup copy Αντίγραφο ασφαλείας
Base Βάση
Baseline Γραμμή βάσης (Baseline)
Batch Publish Μαζική δημοσίευση
@@ -118,6 +124,7 @@
Box Κουτί (Box)
Break Διακοπή (Break)
Break At Point Διακοπή σε σημείο (Break at Point)
Break-line Symbol Σύμβολο γραμμής διακοπής (Break-line Symbol)
Bring Above Objects Μεταφορά πάνω από τα αντικείμενα
Bring Annotations to Front Μεταφορά σχολιασμών στο προσκήνιο
Bring to Front Μεταφορά στο προσκήνιο
@@ -145,10 +152,13 @@
Center, Start, Length Κέντρο, αρχή, μήκος
Centered Κεντραρισμένο
Chamfer Λοξότμηση (Chamfer)
Change Αλλαγή
Change Properties Αλλαγή ιδιοτήτων (Change Properties)
Change Space Αλλαγή χώρου σχεδίασης
Change to Current Layer Μεταφορά στο τρέχον επίπεδο (Layer)
Changed: {n} Αλλαγές: {n}
Changes apply at once and are kept for next time. Οι αλλαγές εφαρμόζονται αμέσως και διατηρούνται για την επόμενη φορά.
Choose the command the alias starts. Επιλέξτε την εντολή που εκκινεί το ψευδώνυμο.
Circle Κύκλος
Circumference Περιφέρεια
Clear Εκκαθάριση
@@ -166,6 +176,16 @@
Close Array Editing Κλείσιμο επεξεργασίας διάταξης
Close Block Editor Κλείσιμο επεξεργαστή μπλοκ
Close Comparison Κλείσιμο σύγκρισης
Command Εντολή
Convert Text to Mtext Μετατροπή κειμένου σε πολυγραμμικό κείμενο (MText)
Create backup copy with each save Δημιουργία αντιγράφου ασφαλείας σε κάθε αποθήκευση
Customize Προσαρμογή
Define each corner of the selection window with a separate click. Ορίστε κάθε γωνία του παραθύρου επιλογής με ξεχωριστό κλικ.
Discard Απόρριψη
Don't Save Να μην αποθηκευτεί
Edit Command Aliases (PGP)... Επεξεργασία ψευδωνύμων εντολών (PGP)...
Edit… Επεξεργασία…
Explode Attributes to Text Διάσπαση ιδιοτήτων (Attributes) σε κείμενο
Export Comparison Εξαγωγή σύγκρισης
Closed Κλειστό
Coincident Σύμπτωση (Coincident)
@@ -197,6 +217,29 @@
Constraint Bars Γραμμές περιορισμών
Constraint Settings Ρυθμίσεις περιορισμών
Construction Line Βοηθητική ευθεία (Construction Line)
Express Tools Εργαλεία Express (Express Tools)
Font Γραμματοσειρά
Imperial (inches) Αγγλοσαξονικό (ίντσες)
Implied Loops Έμμεσοι βρόχοι
Interface scale Κλίμακα περιβάλλοντος
Island Νησίδα
Metric (millimetres) Μετρικό (χιλιοστά)
More than {n} aliases. Περισσότερα από {n} ψευδώνυμα.
Move/Copy/Rotate Μετακίνηση/Αντιγραφή/Περιστροφή
Multiple Insert Πολλαπλή εισαγωγή (Multiple Insert)
New and the first drawing at startup use these units unless a default template is set (QNEWTEMPLATE). Τα νέα σχέδια και το πρώτο σχέδιο κατά την εκκίνηση χρησιμοποιούν αυτές τις μονάδες, εκτός αν έχει οριστεί προεπιλεγμένο πρότυπο (QNEWTEMPLATE).
No alias file loaded. REINIT replaces these aliases with a file's. Δεν έχει φορτωθεί αρχείο ψευδωνύμων. Η εντολή REINIT αντικαθιστά αυτά τα ψευδώνυμα με αυτά ενός αρχείου.
Save Layout as Template Αποθήκευση διάταξης ως πρότυπο (Save Layout as Template)
Save alias Αποθήκευση ψευδωνύμου
Save changes to block "{name}"? Να αποθηκευτούν οι αλλαγές στο μπλοκ «{name}»;
Save changes to {name}? Να αποθηκευτούν οι αλλαγές στο {name};
Select boundaries to remove Επιλέξτε περιγράμματα για αφαίρεση
Select using two clicks only Επιλογή μόνο με δύο κλικ
Type an alias name. Πληκτρολογήστε ένα όνομα ψευδωνύμου.
Units Μονάδες
Units of new drawings Μονάδες νέων σχεδίων
Your changes will be lost if you don't save them. Οι αλλαγές σας θα χαθούν αν δεν τις αποθηκεύσετε.
built-in ενσωματωμένο
contains authoring elements. Open in Block Editor? περιέχει στοιχεία δημιουργίας. Άνοιγμα στον επεξεργαστή μπλοκ;
Contents Περιεχόμενα
Continue Συνέχεια
@@ -1317,6 +1360,9 @@
Zoom Realtime Μεγέθυνση σε πραγματικό χρόνο
Zoom sensitivity Ευαισθησία μεγέθυνσης
Zoom Window Μεγέθυνση περιοχής παραθύρου
overrides built-in υπερισχύει του ενσωματωμένου
{alias} is already defined; select it and use Edit. Το {alias} είναι ήδη ορισμένο· επιλέξτε το και χρησιμοποιήστε την Επεξεργασία.
{command} is an unknown command. Το {command} δεν είναι γνωστή εντολή.
{contributors} · {commits} {contributors} · {commits}
{kind} (constraint {id}) {kind} (περιορισμός {id})
{kind} constraint {name} = {expression} (double-click to edit) {kind} περιορισμός {name} = {expression} (διπλό κλικ για επεξεργασία)
Can't render this file because it contains an unexpected character in line 234 and column 24.
+7 -1
View File
@@ -624,7 +624,13 @@ impl CadApp {
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() {
// A name typed with the Greek keyboard layout active (ΨΛΟΣΕ for CLOSE) is the Latin name's
// keys, unless it is a command of its own, as it is when the engine starts it: the
// interface's own commands answer to it too (CLOSE asks about unsaved changes).
let name = cadcraft_engine::keyboard::latin_keys(first)
.filter(|_| !self.session.greek_word_is_a_command(first))
.unwrap_or_else(|| first.to_ascii_lowercase());
if !first.is_empty() && !json_form && menus::run_ui_command(self, &name, &Value::Null).is_some() {
return None;
}
}
@@ -67,6 +67,23 @@ fn json_file_commands_never_open_pickers() {
assert_eq!(picks.get(), 5);
}
/// A command typed with the Greek keyboard layout active is the Latin name's keys for the
/// interface's own commands too: ΛΑΥΕΡ opens the Layers dialog and `;ΣΑΩΕ` (the Q key types a
/// semicolon) asks where to save a drawing that has no file, as LAYER and QSAVE do.
#[test]
fn greek_layout_names_open_the_dialogs_and_pickers() {
let (mut app, picks) = app();
app.cmdline("ΛΑΥΕΡ");
assert_eq!(app.ui.dialog.as_deref(), Some("layers"));
app.ui.dialog = None;
app.cmdline("λάυερ");
assert_eq!(app.ui.dialog.as_deref(), Some("layers"), "lower case and an accent");
app.ui.dialog = None;
assert_eq!(picks.get(), 0);
app.cmdline(";ΣΑΩΕ");
assert_eq!(picks.get(), 1, "the Save picker opens");
}
#[test]
fn typed_json_form_runs_the_command() {
let (mut app, _) = app();