Compare commits

..
29 Commits
Author SHA1 Message Date
Tanish Manku d1cb40332b Stack u2: #3077: collapse the nested if (clippy) 2026-11-19 15:42:50 -07:00
Tanish Mankuandgraficaeusebio-cloud b7d5ed3401 Stack u2: #1279: test that Options reset also brings back the status bar and command line
Carried over from #1283's test, which also covered the status bar.

Co-authored-by: graficaeusebio-cloud <224763601+graficaeusebio-cloud@users.noreply.github.com>
2026-11-19 15:19:53 -07:00
Tanish Manku 6b767073d8 Stack u2: #1279: Options reset keeps the user's shortcuts and remembered folders
The reset now rebuilds the whole interface state so hidden bars come back (#1240), but that
also dropped the user's keyboard shortcuts and the APPLOAD and .pgp folders, which the old
reset and Window > Reset Palettes keep.
2026-11-19 15:18:53 -07:00
Tanish Manku 7bcfe25938 Stack u2: #1452: a Chinese label for MENUBAR's Menu Bar
main requires a Chinese label for every command (chinese_menus_and_commands_are_fully_translated);
the new MENUBAR command's label had none.
2026-11-19 15:18:13 -07:00
Tanish Manku 3886fb952d Merge #3077 2026-11-19 15:17:16 -07:00
Tanish Manku 6c9eedd7e1 Merge #2443 2026-11-19 15:17:16 -07:00
Tanish Manku 6411c1a4ab Merge #1867 2026-11-19 15:17:15 -07:00
Tanish Manku 6f203fb64b Merge #1452 2026-11-19 15:17:15 -07:00
Tanish Manku a2d209e10b Merge #1279 2026-11-19 15:17:15 -07:00
midasmatterhorn cd226cdf0f ui: keep the in-window menu where the host has no native one 2026-11-14 17:18:20 +03:00
assamaralandClaude Opus 5.5 8d2c9d1a26 fix(app): a saved main window below the minimum size opens at the default size
On Windows app.ron can hold a 64x64 window (e.g. saved while minimized).
eframe restores it as is, so the next launch shows an unusable tiny window.
Such an entry is now dropped from app.ron before launch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-11 15:19:42 -03:00
Nicholas Gower 0156fd9b9f docking: follow the shared surface's stock tab menu and non-exhaustive node
The dock area's tab menu item is "Close Panel" in the pinned craft-ui, and
Node is non-exhaustive, so the accordion scan needs a catch-all arm.
2026-11-02 08:26:29 -08:00
Nicholas Gower df2a5131af i18n: the panel close button's accessible name translates as a whole
The header close button built its name by joining an English "Close" to
the translated panel label, so Spanish screen readers heard "Close Capas".
A single translatable "Close {panel}" template now carries both parts, and
the tooltip's "Close panel" joins the catalogs too. Spanish gets both
rows, Ukrainian (the reference catalog) is required to have them, and
docking.rs joins the scanned sources so future marked strings stay covered.

Regression test: a Spanish harness finds "Cerrar Capas" and "Cerrar
Propiedades" by accessible name, proves "Close Capas" is gone, and closes
Layers through the localized button.
2026-11-02 08:24:52 -08:00
Nicholas Gower 5644c6c946 docs: document the functions touched by #1838 2026-11-02 08:24:04 -08:00
Nicholas Gower 0fa45daf25 UI: a visible close button on every panel header (fixes #1838)
Every dockable panel header now carries an X beside its title, so closing
a palette no longer has to be discovered in the tab context menu. The
button queues the same Close action as that menu item.

Tab and floating group headers use the docking surface's header callback;
accordion title bars place the same button left of the stock collapse
control. The accessible name includes the panel ("Close Layers"), the
tooltip says "Close panel", and the drawing canvas stays unclosable.

Regression test: crates/ui-egui/tests/docking_workflows.rs. It opens the
External References tab and checks its button does not cover the title,
closes the default Layers accordion entry, closes a floating Properties
group, and still closes Layers through the context menu.
2026-11-02 08:23:33 -08:00
austin62jake a92fb047d8 Merge remote-tracking branch 'upstream/main' into fix/refmanager-menu-closes 2026-11-01 07:07:28 -06:00
midasmatterhorn 33dc795c5f ui: the options reset brings a hidden menu bar and tool bar back 2026-11-01 05:26:41 +03:00
Aldo Zarate 4255108429 Merge remote-tracking branch 'upstream/main' into feat/menubar-toolbar-cmds
# Conflicts:
#	crates/ui-egui/src/lib.rs
2026-10-31 14:08:28 -06:00
Aldo Zarate 0b585fa8cb Merge remote-tracking branch 'upstream/main' into feat/menubar-toolbar-cmds
# Conflicts:
#	crates/engine/src/lib.rs
2026-10-30 13:52:46 -06:00
austin62jakeandClaude Opus 5.5 21d9627840 fix(ui): Window > Reference Manager closes the open palette
Once the External References palette was open, Window > Reference
Manager only opened it again, so there was no obvious way to close it
(the tab's right-click Close Panel works but is easy to miss). The menu
item now closes the palette when it is open, as Window > QuickCalc does
for QuickCalc (#2001). Typed XREF still only opens it, as in AutoCAD,
and XREF with JSON parameters still only lists the references.

Fixes #2273.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 22:33:23 -05:00
Aldo ZarateandClaude Opus 5.5 1c611d610d Control API: the bars are synced after every request
A command a control request runs (MENUBAR, TOOLBAR, also through cmdline.key) may ask for a bar;
control::handle now applies that before the next request, so a later query or ui.set sees the
bars as they are.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:29:46 -06:00
Aldo Zarate 076b7761a3 Merge remote-tracking branch 'upstream/main' into feat/menubar-toolbar-cmds 2026-10-28 10:26:55 -06:00
Aldo ZarateandClaude Opus 5.5 71a0ef2260 MENUBAR started from the interface offers the bar as shown now
CadApp::start syncs the bars before starting the command, as run and cmdline do, so MENUBAR's
default is the menu bar as the interface shows it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 10:12:50 -06:00
Aldo ZarateandClaude Opus 5.5 4fadc54dbe MENUBAR/TOOLBAR: control-API calls see the bars as shown now
CadApp::run now syncs the bars before and after the engine runs, as the command line does,
so a bar query right after a ui.set reports the interface's current bars and a MENUBAR or
TOOLBAR request is applied at once.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:46:12 -06:00
Aldo ZarateandClaude Opus 5.5 9c2ebc0e12 MENUBAR/TOOLBAR: request each bar on its own
The request was both bars as one snapshot, so a tool bar change made between MENUBAR and the
UI applying it was undone. Each command now asks only for its own bar, and the UI applies only
the bars asked for.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 09:25:10 -06:00
Aldo ZarateandClaude Opus 5.5 98240d82d0 MENUBAR/TOOLBAR: explicit imports for the wildcard-imports lint
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-28 08:03:36 -06:00
Aldo Zarate 1e1cf10a1c Merge remote-tracking branch 'upstream/main' into feat/menubar-toolbar-cmds 2026-10-28 08:02:57 -06:00
Aldo Zarate af460caac6 Merge remote-tracking branch 'upstream/main' into feat/menubar-toolbar-cmds 2026-10-26 19:34:20 -06:00
Aldo ZarateandClaude Opus 5.5 ad072e6cb0 MENUBAR and TOOLBAR at the command line bring hidden bars back (#1341)
On Windows and Linux the in-window menu bar is the only menu, so once it
was hidden there was no way back from the keyboard: MENUBAR and TOOLBAR,
which AutoCAD users type for this, were unknown commands.

MENUBAR asks "Enter new value for MENUBAR <1>:" (1 shows, 0 hides), and
TOOLBAR (alias -TOOLBAR) asks for Show or Hide, Show by default. The JSON
forms report or set the bars. The engine records the change and the UI
applies it, reporting what it shows every frame.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-15 10:54:43 -06:00
32 changed files with 957 additions and 208 deletions
Generated
+3 -4
View File
@@ -717,7 +717,6 @@ version = "0.21.0"
dependencies = [
"cadcraft-color",
"cadcraft-geom",
"craft-dxf",
"serde",
"serde_json",
"thiserror 2.0.21",
@@ -1184,7 +1183,7 @@ source = "git+https://github.com/storytold/craft-libs?rev=0325b2d73676d736e94097
[[package]]
name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
[[package]]
name = "craft-docpath"
@@ -1203,9 +1202,9 @@ dependencies = [
[[package]]
name = "craft-dxf"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a#219c1d0b14177af6f291395d6587f61a5e09043a"
source = "git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9#9ed120e6b1bd5116a4649c578d1272d60cf932b9"
dependencies = [
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=219c1d0b14177af6f291395d6587f61a5e09043a)",
"craft-codepage 0.1.0 (git+https://github.com/storytold/craft-libs?rev=9ed120e6b1bd5116a4649c578d1272d60cf932b9)",
"encoding_rs",
"kurbo",
"log",
+1 -1
View File
@@ -14,7 +14,7 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "219c1d0b14177af6f291395d6587f61a5e09043a" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "9ed120e6b1bd5116a4649c578d1272d60cf932b9" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "7bb6c90076a0177d01cc4c482e7fd8dc9f31a8bf" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "2f2d1d84e3a36b3f93e81507aeff3f0da97a7162" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "ae5020c1ed922cf7976a3a5545f05b07f466be12" }
+45 -4
View File
@@ -233,11 +233,38 @@ fn saved_window(app_ron: &str) -> bool {
ron::from_str::<std::collections::HashMap<String, String>>(app_ron).is_ok_and(|kv| kv.contains_key(WINDOW_KEY))
}
/// The window state from the last session is saved and will be restored (#2595).
/// The window state from the last session is saved and will be restored (#2595). A saved size
/// below the minimum (seen on Windows: 64×64 points, which eframe restores un-maximized and
/// unusable) is dropped first, so the window opens at its default size.
fn restores_window() -> bool {
eframe::storage_dir(APP_ID).and_then(|dir| std::fs::read_to_string(dir.join("app.ron")).ok()).is_some_and(|ron| saved_window(&ron))
let Some(path) = eframe::storage_dir(APP_ID).map(|dir| dir.join("app.ron")) else { return false };
let Ok(mut ron) = std::fs::read_to_string(&path) else { return false };
if let Some(fixed) = without_tiny_window(&ron)
&& std::fs::write(&path, &fixed).is_ok()
{
ron = fixed;
}
saved_window(&ron)
}
/// `app_ron` without its window entry when that entry's inner size is below `MIN_INNER_SIZE`;
/// `None` when there is nothing to drop (no entry, a usable size, or an unreadable file).
fn without_tiny_window(app_ron: &str) -> Option<String> {
let mut kv = ron::from_str::<std::collections::BTreeMap<String, String>>(app_ron).ok()?;
let w = kv.get(WINDOW_KEY)?;
let size = &w[w.find("inner_size_points:")?..];
let num = |k: &str| size[size.find(k)? + k.len()..].split([',', ')']).next()?.trim().parse::<f32>().ok();
let (x, y) = (num("x:")?, num("y:")?);
if x >= MIN_INNER_SIZE[0] && y >= MIN_INNER_SIZE[1] {
return None;
}
kv.remove(WINDOW_KEY);
ron::ser::to_string_pretty(&kv, ron::ser::PrettyConfig::default()).ok()
}
/// The smallest main window, in points.
const MIN_INNER_SIZE: [f32; 2] = [900.0, 560.0];
/// The main window: its size, title bar, placement and rendering needs. `restoring`: a window state
/// saved by the last session is restored instead of opening centred.
fn window_options(restoring: bool) -> eframe::NativeOptions {
@@ -245,7 +272,7 @@ fn window_options(restoring: bool) -> eframe::NativeOptions {
viewport: egui::ViewportBuilder::default()
.with_title("CADCraft")
.with_inner_size([1600.0, 1000.0])
.with_min_inner_size([900.0, 560.0])
.with_min_inner_size(MIN_INNER_SIZE)
.with_drag_and_drop(true)
.with_fullsize_content_view(true)
.with_titlebar_shown(false)
@@ -403,6 +430,9 @@ fn main() -> eframe::Result {
app.ui = ui;
}
app.set_system_cursor_default(vars.system_cursor == Switch::On);
// macOS: CADCRAFT_NO_NATIVE_MENU=1 keeps the menus inside the window.
#[cfg(target_os = "macos")]
app.set_native_menus(vars.no_native_menu != Switch::On);
if let Some(error) = &workspace_error {
eprintln!("CADCraft workspace: {error}");
app.set_status(error);
@@ -481,7 +511,7 @@ fn main() -> eframe::Result {
#[cfg(test)]
mod tests {
use super::{filters_for_save, follow_desktop, saved_window, window_options};
use super::{filters_for_save, follow_desktop, saved_window, window_options, without_tiny_window};
#[test]
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
@@ -525,6 +555,17 @@ mod tests {
assert!(!saved_window("not ron at all"));
}
/// A saved 64×64 window (below the minimum) is dropped; a usable one is kept.
#[test]
fn a_tiny_saved_window_is_dropped() {
let tiny = r#"{"window": "(normal_geometry:(outer_position_pixels:Some((x:0.0,y:0.0)),scale_factor:1.25,inner_size_points:(x:64.0,y:64.0)),fullscreen:false,maximized:true)", "cadcraft.prefs": "{}"}"#;
let fixed = without_tiny_window(tiny).expect("dropped");
assert!(!saved_window(&fixed) && fixed.contains("cadcraft.prefs"));
let ok = tiny.replace("x:64.0,y:64.0)),", "x:1600.0,y:1000.0)),");
assert_eq!(without_tiny_window(&ok), None);
assert_eq!(without_tiny_window("not ron"), None);
}
/// View ▸ Theme ▸ System on Linux: winit reports no theme, so the desktop's answer stands in;
/// without one (or where winit answers and the desktop doesn't) the input is left alone.
#[test]
-1
View File
@@ -11,7 +11,6 @@ workspace = true
[dependencies]
cadcraft-geom = { workspace = true }
cadcraft-color = { workspace = true }
craft-dxf = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+314 -46
View File
@@ -1,14 +1,32 @@
//! Readers for the user's own linetype (`.lin`) and hatch pattern (`.pat`) files.
//!
//! Grammar and hostile-input capping live in [`craft_dxf::lin_pat`]; this module maps the
//! parsed definitions into CADCraft's [`Linetype`] and [`UserPattern`] document types.
use cadcraft_geom::Vec2;
pub use craft_dxf::lin_pat::{MAX_DEFINITIONS, MAX_LINE_CHARS, MAX_LINETYPE_ELEMENTS, MAX_PATTERN_DASHES, MAX_PATTERN_FAMILIES, MAX_VALUE, Parsed};
//! Both follow the publicly documented text formats: a header line `*NAME[,description]`, then
//! the definition (`A,dash,gap,…` for a linetype, `angle, x, y, dx, dy[, dash, …]` lines for
//! a pattern), with `;` starting a comment line. CADCraft ships no such file; these read the
//! files users bring. Everything here treats the text as hostile: lines, definitions, dashes,
//! families and warnings are capped, numbers must be finite and reasonable, and nothing panics.
//! Problems become warnings and the definitions that can be read are kept.
use super::PatternLine;
use crate::{DashElement, Linetype};
/// Longest line read; longer lines are skipped with a warning.
pub const MAX_LINE_CHARS: usize = 4096;
/// Most definitions (linetypes or patterns) read from one file.
pub const MAX_DEFINITIONS: usize = 4096;
/// Most elements in one linetype.
pub const MAX_LINETYPE_ELEMENTS: usize = 256;
/// Most line families in one hatch pattern (what the renderer draws, too).
pub const MAX_PATTERN_FAMILIES: usize = 1024;
/// Most dashes in one pattern line family (as for a pattern definition read from DXF).
pub const MAX_PATTERN_DASHES: usize = 256;
/// Largest magnitude accepted for a length, offset or scale.
pub const MAX_VALUE: f64 = 1.0e6;
/// Longest name or description kept.
const MAX_NAME_CHARS: usize = 255;
/// Most warnings collected; the rest are counted in a last line.
const MAX_WARNINGS: usize = 100;
/// A hatch pattern read from a user's `.pat` file.
#[derive(Clone, Debug, PartialEq, serde::Serialize, serde::Deserialize)]
pub struct UserPattern {
@@ -17,57 +35,307 @@ pub struct UserPattern {
pub lines: Vec<PatternLine>,
}
/// What a file held: the definitions that could be read, and why anything else was skipped.
#[derive(Clone, Debug, PartialEq)]
pub struct Parsed<T> {
pub items: Vec<T>,
pub warnings: Vec<String>,
}
impl<T> Default for Parsed<T> {
fn default() -> Self {
Parsed { items: Vec::new(), warnings: Vec::new() }
}
}
impl<T> Parsed<T> {
fn warn(&mut self, line: usize, msg: impl Into<String>) {
match self.warnings.len() {
n if n < MAX_WARNINGS => self.warnings.push(format!("line {line}: {}", msg.into())),
MAX_WARNINGS => self.warnings.push("more problems not listed".into()),
_ => {}
}
}
}
/// A header line `*NAME[,description]`: the name and description, or why it can't be used.
fn header(rest: &str) -> std::result::Result<(String, String), String> {
let (name, desc) = rest.split_once(',').unwrap_or((rest, ""));
let name = name.trim();
if name.is_empty() {
return Err("a definition without a name".into());
}
if name.chars().count() > MAX_NAME_CHARS || name.chars().any(char::is_control) {
return Err("a definition name that is too long or has control characters".into());
}
let desc: String = desc.trim().chars().filter(|c| !c.is_control()).take(MAX_NAME_CHARS).collect();
Ok((name.to_string(), desc))
}
/// A finite number within ±[`MAX_VALUE`].
fn number(t: &str) -> Option<f64> {
t.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= MAX_VALUE)
}
/// The file's text lines with 1-based numbers, without a leading byte-order mark.
fn lines(text: &str) -> impl Iterator<Item = (usize, &str)> {
text.trim_start_matches('\u{feff}').lines().enumerate().map(|(i, l)| (i.saturating_add(1), l.trim()))
}
// ---------- LIN ----------
/// Read the linetypes of a `.lin` file. Simple linetypes and complex ones with embedded text
/// (`["TEXT",STYLE,S=…,R=…,A=…,U=…,X=…,Y=…]`) are read; shape elements (`[SHAPE,file.shx,…]`)
/// need SHX shape fonts, so they are left out with a warning and the dashes around them kept.
/// Lengths are in drawing units as written: a user's file is never rescaled.
pub fn parse_lin(text: &str) -> Parsed<Linetype> {
let parsed = craft_dxf::lin_pat::parse_lin(text);
Parsed {
items: parsed
.items
.into_iter()
.map(|d| Linetype {
name: d.name,
description: d.description,
pattern: d
.pattern
.into_iter()
.map(|e| DashElement {
length: e.length,
text: e.text,
shape: None,
style: e.style,
scale: e.scale,
rotation: e.rotation,
offset: Vec2::new(e.offset[0], e.offset[1]),
absolute: e.absolute,
})
.collect(),
})
.collect(),
warnings: parsed.warnings,
let mut out = Parsed::default();
// The definition being read: name, description, header line.
let mut pending: Option<(String, String, usize)> = None;
for (no, line) in lines(text) {
if line.is_empty() || line.starts_with(';') {
continue;
}
if line.chars().count() > MAX_LINE_CHARS {
out.warn(no, "line too long; skipped");
continue;
}
if let Some(rest) = line.strip_prefix('*') {
if let Some((name, _, at)) = pending.take() {
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
}
match header(rest) {
Ok((name, desc)) => pending = Some((name, desc, no)),
Err(e) => out.warn(no, format!("{e}; skipped")),
}
continue;
}
let Some((name, description, _)) = pending.take() else {
out.warn(no, "pattern line without a *NAME line before it; skipped");
continue;
};
if out.items.len() >= MAX_DEFINITIONS {
out.warn(no, format!("more than {MAX_DEFINITIONS} linetypes; the rest are skipped"));
break;
}
if out.items.iter().any(|l: &Linetype| l.name.eq_ignore_ascii_case(&name)) {
out.warn(no, format!("linetype {name} is defined twice; the first definition is kept"));
continue;
}
match lin_pattern(line, no, &name, &mut out) {
Ok(pattern) => out.items.push(Linetype { name, description, pattern }),
Err(e) => out.warn(no, format!("linetype {name}: {e}; skipped")),
}
}
if let Some((name, _, at)) = pending {
out.warn(at, format!("linetype {name} has no pattern line; skipped"));
}
out
}
/// Split a pattern line at commas outside `[…]` and `"…"`.
fn lin_fields(line: &str) -> std::result::Result<Vec<&str>, String> {
let mut out = Vec::new();
let (mut depth, mut quoted, mut start) = (0usize, false, 0usize);
for (i, c) in line.char_indices() {
match c {
'"' => quoted = !quoted,
'[' if !quoted => depth = depth.saturating_add(1),
']' if !quoted => depth = depth.checked_sub(1).ok_or("a ] without its [")?,
',' if !quoted && depth == 0 => {
out.push(line.get(start..i).unwrap_or("").trim());
start = i.saturating_add(1);
}
_ => {}
}
if out.len() > MAX_LINETYPE_ELEMENTS.saturating_mul(2) {
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
}
}
if quoted || depth != 0 {
return Err("an unclosed [ or \"".into());
}
out.push(line.get(start..).unwrap_or("").trim());
Ok(out)
}
/// The elements of a pattern line `A,dash,gap,[…],…`.
fn lin_pattern(line: &str, no: usize, name: &str, out: &mut Parsed<Linetype>) -> std::result::Result<Vec<DashElement>, String> {
let mut fields = lin_fields(line)?;
// The alignment field ("A") comes first; a line of plain numbers is read as well.
if fields.first().is_some_and(|f| f.eq_ignore_ascii_case("a")) {
fields.remove(0);
} else if fields.first().is_some_and(|f| number(f).is_none() && !f.starts_with('[')) {
return Err(format!("unknown alignment `{}` (expected A)", fields.first().copied().unwrap_or("")));
}
let mut pattern: Vec<DashElement> = Vec::new();
for f in fields.into_iter().filter(|f| !f.is_empty()) {
if pattern.len() >= MAX_LINETYPE_ELEMENTS {
return Err(format!("more than {MAX_LINETYPE_ELEMENTS} elements"));
}
let Some(inner) = f.strip_prefix('[') else {
let len = number(f).ok_or_else(|| format!("`{f}` is not a dash length"))?;
pattern.push(DashElement::dash(len));
continue;
};
let inner = inner.strip_suffix(']').ok_or_else(|| format!("`{f}` is not a complete [ ] element"))?;
match lin_text(inner)? {
Some(text) => {
// The text sits at the end of the element before it (a zero-length one if none).
if pattern.last().is_none_or(|e| e.text.is_some()) {
pattern.push(DashElement::dash(0.0));
}
if let Some(last) = pattern.last_mut() {
*last = DashElement { length: last.length, ..text };
}
}
None => {
let shape = inner.split(',').next().unwrap_or("").trim();
out.warn(no, format!("linetype {name}: shape {shape} needs an SHX shape file, which CADCraft can't read; left out"));
}
}
}
if pattern.is_empty() {
return Err("no dashes".into());
}
if pattern.iter().all(|e| e.length == 0.0) && pattern.iter().all(|e| e.text.is_none()) {
return Err("every element has zero length".into());
}
Ok(pattern)
}
/// A `"TEXT",STYLE,key=value…` element (the inside of `[…]`), or `None` for a shape element.
fn lin_text(inner: &str) -> std::result::Result<Option<DashElement>, String> {
let inner = inner.trim();
let Some(after) = inner.strip_prefix('"') else { return Ok(None) };
let (text, rest) = after.split_once('"').ok_or("unclosed text quote")?;
if text.chars().count() > MAX_NAME_CHARS || text.chars().any(char::is_control) {
return Err("embedded text that is too long or has control characters".into());
}
let mut parts = rest.split(',').map(str::trim);
if !parts.next().unwrap_or("").is_empty() {
return Err("text element: expected a comma after the text".into());
}
let style = parts.next().unwrap_or("").trim();
if style.is_empty() || style.contains('=') {
return Err("text element: the text style is missing".into());
}
let mut e = DashElement { text: Some(text.to_string()), style: Some(style.to_string()), ..DashElement::dash(0.0) };
for kv in parts.filter(|p| !p.is_empty()) {
let (k, v) = kv.split_once('=').ok_or_else(|| format!("text element: `{kv}` is not key=value"))?;
match k.trim().to_ascii_uppercase().as_str() {
"S" => e.scale = number(v).filter(|s| *s > 0.0).ok_or_else(|| format!("text element: bad scale `{v}`"))?,
"X" => e.offset.x = number(v).ok_or_else(|| format!("text element: bad X offset `{v}`"))?,
"Y" => e.offset.y = number(v).ok_or_else(|| format!("text element: bad Y offset `{v}`"))?,
// Upright text keeps a rotation relative to the line, like R.
k @ ("R" | "A" | "U") => {
e.rotation = angle(v).ok_or_else(|| format!("text element: bad rotation `{v}`"))?;
e.absolute = k == "A";
}
other => return Err(format!("text element: unknown option `{other}`")),
}
}
Ok(Some(e))
}
/// An angle in degrees, or with a `d` (degrees), `r` (radians) or `g` (grads) suffix; radians out.
fn angle(t: &str) -> Option<f64> {
let t = t.trim().to_ascii_lowercase();
let (num, unit) = match t.char_indices().last() {
Some((i, c @ ('d' | 'r' | 'g'))) => (t.get(..i)?, c),
_ => (t.as_str(), 'd'),
};
let v = num.trim().parse::<f64>().ok().filter(|v| v.is_finite() && v.abs() <= 1.0e5)?;
Some(match unit {
'r' => v,
'g' => v * std::f64::consts::PI / 200.0,
_ => v.to_radians(),
})
}
// ---------- PAT ----------
/// Read the hatch patterns of a `.pat` file. Values are used as written (an inch file for inch
/// drawings, a millimetre file for metric ones).
pub fn parse_pat(text: &str) -> Parsed<UserPattern> {
let parsed = craft_dxf::lin_pat::parse_pat(text);
Parsed {
items: parsed
.items
.into_iter()
.map(|p| UserPattern {
name: p.name,
description: p.description,
lines: p
.lines
.into_iter()
.map(|l| PatternLine { angle: l.angle, origin: (l.origin[0], l.origin[1]), delta: (l.delta[0], l.delta[1]), dashes: l.dashes })
.collect(),
})
.collect(),
warnings: parsed.warnings,
let mut out: Parsed<UserPattern> = Parsed::default();
// The pattern being read, its header line, and whether it already failed.
let mut cur: Option<(UserPattern, usize, bool)> = None;
let finish = |cur: Option<(UserPattern, usize, bool)>, out: &mut Parsed<UserPattern>| {
let Some((p, at, failed)) = cur else { return };
if failed {
return;
}
if p.lines.is_empty() {
out.warn(at, format!("pattern {} has no line families; skipped", p.name));
} else if out.items.len() >= MAX_DEFINITIONS {
out.warn(at, format!("more than {MAX_DEFINITIONS} patterns; {} skipped", p.name));
} else if out.items.iter().any(|q| q.name.eq_ignore_ascii_case(&p.name)) {
out.warn(at, format!("pattern {} is defined twice; the first definition is kept", p.name));
} else {
out.items.push(p);
}
};
for (no, line) in lines(text) {
// A comment runs to the end of the line.
let line = line.split(';').next().unwrap_or("").trim();
if line.is_empty() {
continue;
}
if line.chars().count() > MAX_LINE_CHARS {
out.warn(no, "line too long; skipped");
continue;
}
if let Some(rest) = line.strip_prefix('*') {
finish(cur.take(), &mut out);
match header(rest) {
Ok((name, description)) => cur = Some((UserPattern { name: name.to_ascii_uppercase(), description, lines: Vec::new() }, no, false)),
Err(e) => out.warn(no, format!("{e}; skipped")),
}
continue;
}
let Some((p, _, failed)) = cur.as_mut() else {
out.warn(no, "line family without a *NAME line before it; skipped");
continue;
};
if *failed {
continue;
}
if p.lines.len() >= MAX_PATTERN_FAMILIES {
out.warn(no, format!("pattern {}: more than {MAX_PATTERN_FAMILIES} line families; skipped", p.name));
*failed = true;
continue;
}
match pat_family(line) {
Ok(l) => p.lines.push(l),
Err(e) => {
out.warn(no, format!("pattern {}: {e}; skipped", p.name));
*failed = true;
}
}
}
finish(cur, &mut out);
out
}
/// One line family: `angle, x-origin, y-origin, delta-x, delta-y[, dash-1, dash-2, …]`.
fn pat_family(line: &str) -> std::result::Result<PatternLine, String> {
let mut v = Vec::new();
for f in line.split(',') {
if v.len() >= MAX_PATTERN_DASHES.saturating_add(5) {
return Err(format!("more than {MAX_PATTERN_DASHES} dashes in a line family"));
}
let f = f.trim();
if f.is_empty() && v.len() >= 5 {
continue;
}
v.push(number(f).ok_or_else(|| format!("`{f}` is not a number"))?);
}
let (Some(&angle), Some(&x), Some(&y), Some(&dx), Some(&dy)) = (v.first(), v.get(1), v.get(2), v.get(3), v.get(4)) else {
return Err("a line family needs angle, x, y, delta-x and delta-y".into());
};
if dy.abs() < 1e-9 {
return Err("a line family with zero spacing (delta-y)".into());
}
Ok(PatternLine { angle, origin: (x, y), delta: (dx, dy), dashes: v.get(5..).unwrap_or(&[]).to_vec() })
}
+2
View File
@@ -22,6 +22,7 @@ pub(crate) mod groups;
pub(crate) mod hatch;
mod image;
mod inquiry;
pub mod interface;
mod layer;
mod layout;
mod lisp;
@@ -212,6 +213,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(inquiry::specs());
v.extend(settings::specs());
v.extend(options::specs());
v.extend(interface::specs());
v.extend(utility::specs());
v.extend(table::specs());
v.extend(tolerance::specs());
+2 -7
View File
@@ -56,7 +56,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("usage", "Analyze Usage", usage::run).params(usage::PARAMS).noundo(),
CommandSpec::new("loops", "Implied Loops", loops::run).params(loops::PARAMS).noundo(),
CommandSpec::new("texts", "Query Texts", run_texts)
.params("{contains?: text (any case; `query` is the same filter), layer?, window?: [[x,y],[x,y]] (by insertion point), limit? (default 200), offset?} → {count (all matches), returned, offset, texts: [{handle, type, layer, text, at, height, rotation (degrees), style, tag? (attributes)}]}: the readable text of TEXT, MTEXT (formatting removed), block attributes and multileaders")
.params("{contains?: text (any case), layer?, window?: [[x,y],[x,y]] (by insertion point), limit? (default 200), offset?} → {count (all matches), returned, offset, texts: [{handle, type, layer, text, at, height, rotation (degrees), style, tag? (attributes)}]}: the readable text of TEXT, MTEXT (formatting removed), block attributes and multileaders")
.noundo(),
CommandSpec::new("countlist", "Count List", count::run_countlist)
.params("{space?: all (default)|current|model|<layout>, nested?: bool} → per-block counts, as COUNT")
@@ -664,12 +664,7 @@ fn run_texts(s: &mut Session, p: &Value) -> Result<Value> {
v.as_u64().map(|n| usize::try_from(n).unwrap_or(usize::MAX)).ok_or_else(|| bad(CMD, format!("`{k}` must be a whole number, 0 or more")))
})
};
// `query` is what agents tend to call the filter; without this alias it was silently ignored
// and every text came back (#3011).
let contains = match text("contains")? {
Some(c) => Some(c),
None => text("query")?,
};
let contains = text("contains")?;
let layer = text("layer")?;
let window = given("window")
.map(|w| {
+134
View File
@@ -0,0 +1,134 @@
//! MENUBAR and TOOLBAR: show or hide the window's menu bar and tool bar from the command line, as
//! in AutoCAD. With the menu bar hidden on Windows and Linux (where it is the only menu), typing
//! these is the way back.
//!
//! The UI owns the bars: it reports what it shows in [`Session::bars_shown`] and applies
//! [`Session::bars_request`], which these commands set.
use serde_json::{Value, json};
use super::{CommandSpec, always, bad};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
/// The interface bars MENUBAR and TOOLBAR control.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct InterfaceBars {
pub menubar: bool,
pub toolbar: bool,
}
impl Default for InterfaceBars {
fn default() -> Self {
InterfaceBars { menubar: true, toolbar: true }
}
}
/// A change MENUBAR or TOOLBAR asked for: only the bars a command set, so the UI leaves the other
/// as it is (it may have been changed since).
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct BarsRequest {
pub menubar: Option<bool>,
pub toolbar: Option<bool>,
}
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("menubar", "Menu Bar", run_menubar)
.params("{value?: 0|1} (1 shows the in-window menu bar, 0 hides it; without it, reports it)")
.enabled(always)
.noundo()
.interactive(|s| Ok(Box::new(MenubarM { current: s.bars_shown.menubar }))),
CommandSpec::new("toolbar", "Tool Bar", run_toolbar)
.alias(&["-toolbar"])
.params("{show?: bool} (without it, reports it)")
.enabled(always)
.noundo()
.interactive(|_| Ok(Box::new(ToolbarM))),
]
}
fn set_menubar(s: &mut Session, on: bool) {
s.bars_shown.menubar = on;
s.bars_request.menubar = Some(on);
}
fn set_toolbar(s: &mut Session, show: bool) {
s.bars_shown.toolbar = show;
s.bars_request.toolbar = Some(show);
}
fn run_menubar(s: &mut Session, p: &Value) -> Result<Value> {
let v = match p.get("value") {
None | Some(Value::Null) => return Ok(json!({ "value": u8::from(s.bars_shown.menubar) })),
Some(v) => v
.as_u64()
.or_else(|| v.as_str().and_then(|t| t.trim().parse().ok()))
.filter(|v| *v <= 1)
.ok_or_else(|| bad("menubar", "`value` must be 0 or 1"))?,
};
set_menubar(s, v == 1);
Ok(json!({ "value": v }))
}
fn run_toolbar(s: &mut Session, p: &Value) -> Result<Value> {
let Some(show) = p.get("show").filter(|v| !v.is_null()) else { return Ok(json!({ "show": s.bars_shown.toolbar })) };
let show = show.as_bool().ok_or_else(|| bad("toolbar", "`show` must be true or false"))?;
set_toolbar(s, show);
Ok(json!({ "show": show }))
}
/// Typed MENUBAR: "Enter new value for MENUBAR <1>:".
struct MenubarM {
current: bool,
}
impl Interactive for MenubarM {
fn name(&self) -> &'static str {
"MENUBAR"
}
fn prompt(&self, _s: &Session) -> Prompt {
Prompt::new("Enter new value for MENUBAR", Accept::NUMBER).default(u8::from(self.current).to_string())
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match i {
Input::Enter => Ok(Step::Done),
Input::Text(t) => match run_menubar(s, &json!({ "value": t })) {
Ok(_) => Ok(Step::Done),
Err(_) => {
s.echo("Requires 0 or 1.");
Ok(Step::Continue)
}
},
_ => Ok(Step::Continue),
}
}
}
/// Typed TOOLBAR: "Enter tool bar option [Show/Hide] <Show>:" (CADCraft has one tool bar).
struct ToolbarM;
impl Interactive for ToolbarM {
fn name(&self) -> &'static str {
"TOOLBAR"
}
fn prompt(&self, _s: &Session) -> Prompt {
Prompt::new("Enter tool bar option", Accept::TEXT).kw(&["Show", "Hide"]).default("Show")
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let word = match &i {
Input::Enter => "show".to_string(),
Input::Keyword(k) | Input::Text(k) => k.trim().to_ascii_lowercase(),
_ => return Ok(Step::Continue),
};
let show = if !word.is_empty() && "show".starts_with(&word) {
true
} else if !word.is_empty() && "hide".starts_with(&word) {
false
} else {
s.echo("Invalid option keyword.");
return Ok(Step::Continue);
};
run_toolbar(s, &json!({ "show": show }))?;
Ok(Step::Done)
}
}
+2 -23
View File
@@ -264,23 +264,16 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, format!("`{name}` has no style `{rm}`")));
}
}
let mut changed: Option<String> = None;
if let Some(v) = p.get("style") {
let sname = v.get("name").and_then(Value::as_str).map(str::trim).filter(|n| !n.is_empty());
let sname = sname.ok_or_else(|| bad(cmd, "`style.name` is required"))?;
// The name as it is stored (at most 255 characters, as `sanitized` cuts it, and
// without a space the cut leaves at the end, which `sanitized` trims), so a long
// name finds the style it was stored as and the reply finds the edited style.
let cut: String = sname.chars().take(255).collect();
let sname = cut.trim_end();
changed = Some(sname.to_string());
let idx = match t.styles.iter().position(|x| x.name.eq_ignore_ascii_case(sname)) {
Some(i) => i,
None if t.kind == PlotStyleKind::Named => {
if t.styles.len() >= cadcraft_doc::MAX_NAMED_STYLES {
return Err(bad(cmd, "the table has too many styles"));
}
t.styles.push(PlotStyle::object(sname));
t.styles.push(PlotStyle::object(&sname.chars().take(255).collect::<String>()));
t.styles.len() - 1
}
None => return Err(bad(cmd, format!("`{name}` has no style `{sname}` (colour-dependent styles are Color_1 to Color_255)"))),
@@ -290,21 +283,7 @@ fn run_stylesmanager(s: &mut Session, p: &Value) -> Result<Value> {
}
}
let t = t.sanitized();
// Only what changed, not the table (a colour-dependent one has 255 styles): the table's
// name, the description if given, the edited style and the removed style's name.
let mut out = json!({ "name": t.name });
if let Some(o) = out.as_object_mut() {
if str_param(p, "description").is_some() {
o.insert("description".into(), json!(t.description));
}
let edited = changed.and_then(|n| t.styles.iter().find(|x| x.name.eq_ignore_ascii_case(&n)));
if let Some(e) = edited.and_then(|x| serde_json::to_value(x).ok()) {
o.insert("style".into(), e);
}
if let Some(r) = str_param(p, "removeStyle") {
o.insert("removedStyle".into(), json!(r.trim()));
}
}
let out = serde_json::to_value(&t).unwrap_or(Value::Null);
store(s.doc_mut()?, t);
Ok(out)
}
+6
View File
@@ -156,6 +156,10 @@ pub struct Session {
lisp_last: Option<std::result::Result<lisp::value::Value, String>>,
/// What the last HATCHPICK kept (the Hatch and Gradient dialog's picks).
pub hatch_picks: Option<cmd::hatch::HatchPicks>,
/// The window's menu bar and tool bar as the UI shows them (it reports them every frame).
pub bars_shown: cmd::interface::InterfaceBars,
/// The bars MENUBAR or TOOLBAR asked to change, for the UI to apply.
pub bars_request: cmd::interface::BarsRequest,
/// The object named with a point for the input a prompt picking one object is taking
/// ([`Session::input_object`]): a pick at exactly that point picks that object
/// ([`Session::pick_object`]).
@@ -215,6 +219,8 @@ impl Session {
lisp: lisp::LispState::default(),
lisp_last: None,
hatch_picks: None,
bars_shown: Default::default(),
bars_request: Default::default(),
pick_hint: None,
}
}
-9
View File
@@ -213,19 +213,10 @@ pub fn getvar(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
let name = string(&a[0])?;
Ok(Flow::Value(match crate::sysvars::get(ctx.s, &name) {
Some(serde_json::Value::Number(n)) if in_radians(&name) => Value::Real(n.as_f64().unwrap_or(0.0).to_radians()),
Some(serde_json::Value::Object(o)) if o.contains_key("x") => point_list(&o, &name),
v => v.map(|v| from_json(&v)).unwrap_or_default(),
}))
}
/// Header point variables are stored as `{x, y, z}`; AutoLISP gives a point list. LIMMIN, LIMMAX,
/// SNAPBASE and HPORIGIN are 2D points, so they lose z; the rest (INSBASE, UCSORG, ...) keep all three.
fn point_list(o: &serde_json::Map<String, serde_json::Value>, name: &str) -> Value {
let coord = |k: &str| Value::Real(o.get(k).and_then(serde_json::Value::as_f64).unwrap_or(0.0));
let planar = ["LIMMIN", "LIMMAX", "SNAPBASE", "HPORIGIN"].iter().any(|v| v.eq_ignore_ascii_case(name.trim()));
if planar { Value::list(vec![coord("x"), coord("y")]) } else { Value::list(vec![coord("x"), coord("y"), coord("z")]) }
}
/// Set a system variable after bounded JSON conversion, reporting invalid or oversized values as LISP errors.
pub fn setvar(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 2, 2)?;
-11
View File
@@ -649,17 +649,6 @@ fn getvar_drawing_and_session_variables() {
assert_eq!(ok(&mut s, "(getvar \"DWGTITLED\")"), "1");
}
/// LIMMIN, LIMMAX, SNAPBASE and HPORIGIN read as 2D point lists and INSBASE as a 3D one, not as JSON text (#2988).
#[test]
fn getvar_point_variables_are_point_lists() {
let mut s = session();
assert_eq!(ok(&mut s, "(getvar \"LIMMIN\")"), "(0.0 0.0)");
assert_eq!(ok(&mut s, "(getvar \"LIMMAX\")"), "(12.0 9.0)");
assert_eq!(ok(&mut s, "(getvar \"SNAPBASE\")"), "(0.0 0.0)");
assert_eq!(ok(&mut s, "(getvar \"INSBASE\")"), "(0.0 0.0 0.0)");
assert_eq!(ok(&mut s, "(setvar \"HPORIGIN\" '(3.0 4.0)) (getvar \"HPORIGIN\")"), "(3.0 4.0)");
}
/// CECOLOR is a string in AutoCAD, whatever it was set from (#1999).
#[test]
fn getvar_cecolor_is_a_string() {
+1 -69
View File
@@ -62,10 +62,7 @@ fn stylesmanager_creates_edits_saves_and_loads_tables() {
&json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5", "color": "#00ff00", "screening": 40, "lineweight": 0.35, "linetype": "HIDDEN", "end": "round"}}),
)
.unwrap();
// `set` replies with the table's name and the edited style, not the table.
assert_eq!(r["name"], "office.stb");
let pen = r["style"].clone();
assert_eq!(pen["name"], "Pen 5");
let pen = r["styles"].as_array().unwrap().iter().find(|v| v["name"] == "Pen 5").unwrap().clone();
assert_eq!(
(pen["color"].as_str(), pen["screening"].as_u64(), pen["lineweight"].as_u64(), pen["end"].as_str()),
(Some("#00ff00"), Some(40), Some(35), Some("round"))
@@ -134,68 +131,3 @@ fn plot_style_save_is_atomic_and_keeps_permissions() {
assert_eq!(std::fs::metadata(&path).unwrap().permissions().mode() & 0o777, 0o600);
let _ = std::fs::remove_dir_all(&dir);
}
/// #3011: `set` on a colour-dependent table (255 styles) replies with what changed, not the table.
#[test]
fn stylesmanager_set_replies_with_the_change_not_the_whole_table() {
let mut s = Session::new();
let set = json!({"action": "set", "name": "monochrome.ctb", "style": {"name": "Color_13", "lineweight": 0.3}});
let r = s.execute("stylesmanager", &set).unwrap();
assert_eq!(r["name"], "monochrome.ctb", "{r}");
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some("Color_13"), Some(30)), "{r}");
// Only the change: no table summary, no other style.
let keys: Vec<&str> = r.as_object().unwrap().keys().map(String::as_str).collect();
assert_eq!(keys, ["name", "style"], "{r}");
assert!(r.to_string().len() < 1000, "the reply is short, not the 255-style table: {} bytes", r.to_string().len());
// The edit is in the drawing.
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "monochrome.ctb"})).unwrap();
let c13 = got["styles"].as_array().unwrap().iter().find(|v| v["name"] == "Color_13").unwrap();
assert_eq!(c13["lineweight"], 30);
// Removing a style of a named table names what went.
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "style": {"name": "Pen 5"}})).unwrap();
let r =
s.execute("stylesmanager", &json!({"action": "set", "name": "office.stb", "removeStyle": "Pen 5", "description": "Office pens"})).unwrap();
assert_eq!((r["removedStyle"].as_str(), r["description"].as_str()), (Some("Pen 5"), Some("Office pens")), "{r}");
assert!(r.get("style").is_none() && r.get("styles").is_none(), "{r}");
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
assert_eq!(got["styles"].as_array().map(Vec::len), Some(1), "{got}");
}
/// A style name over 255 characters is stored cut to 255: the reply names the stored style, and
/// setting the same long name again edits that style instead of adding one.
#[test]
fn stylesmanager_set_with_a_long_style_name_replies_with_the_stored_style() {
let mut s = Session::new();
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
let long = "P".repeat(300);
let stored = "P".repeat(255);
let set = |lw: f64| json!({"action": "set", "name": "office.stb", "style": {"name": long, "lineweight": lw}});
let r = s.execute("stylesmanager", &set(0.3)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(30)), "{r}");
let r = s.execute("stylesmanager", &set(0.5)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(50)), "{r}");
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
let styles = got["styles"].as_array().unwrap();
assert_eq!(styles.len(), 2, "Normal and the one long-named style: {got}");
assert_eq!(styles[1]["lineweight"], 50, "{got}");
}
/// A long name whose 255th character is a space is stored without it (`sanitized` trims the cut
/// name), so the reply still has the style and setting the same name again edits it.
#[test]
fn stylesmanager_set_with_a_long_name_cut_at_a_space_edits_one_style() {
let mut s = Session::new();
s.execute("stylesmanager", &json!({"action": "new", "name": "office", "kind": "named"})).unwrap();
let long = format!("{} tail", "P".repeat(254));
let stored = "P".repeat(254);
let set = |lw: f64| json!({"action": "set", "name": "office.stb", "style": {"name": long, "lineweight": lw}});
let r = s.execute("stylesmanager", &set(0.3)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(30)), "{r}");
let r = s.execute("stylesmanager", &set(0.5)).unwrap();
assert_eq!((r["style"]["name"].as_str(), r["style"]["lineweight"].as_u64()), (Some(stored.as_str()), Some(50)), "{r}");
let got = s.execute("stylesmanager", &json!({"action": "get", "name": "office.stb"})).unwrap();
let styles = got["styles"].as_array().unwrap();
assert_eq!(styles.len(), 2, "Normal and the one long-named style: {got}");
assert_eq!(styles[1]["lineweight"], 50, "{got}");
}
-16
View File
@@ -226,22 +226,6 @@ fn find_text_reads_texts_and_render_shows_one_area() {
assert_eq!((w, h), (1600, 800));
}
/// Guards #3011: `find_text` filters by `query` as it does by `contains`, instead of ignoring it
/// and returning every text.
#[test]
fn find_text_filters_by_query() {
let mut s = Server::new(Box::new(Headless::default()));
call(&mut s, 1, "initialize", json!({"protocolVersion": "2025-06-18"}));
tool(&mut s, "execute", json!({"command": "text", "params": {"at": [1, 1], "height": 0.15, "text": "RECAMARA 1"}}));
tool(&mut s, "execute", json!({"command": "text", "params": {"at": [50, 1], "height": 0.15, "text": "COCINA"}}));
assert_eq!(tool(&mut s, "find_text", json!({}))["count"], 2);
let r = tool(&mut s, "find_text", json!({"query": "cocina"}));
assert_eq!((r["count"].as_u64(), r["texts"][0]["text"].as_str()), (Some(1), Some("COCINA")), "{r}");
assert_eq!(tool(&mut s, "find_text", json!({"query": "nada"}))["count"], 0);
// `contains` still works and wins when both are given.
assert_eq!(tool(&mut s, "find_text", json!({"contains": "recamara", "query": "cocina"}))["texts"][0]["text"], "RECAMARA 1");
}
/// Guards a lazy Remote bridge: it serves tools without the app, reports how to start it
/// (`--control`), and reaches the app once that app starts listening on the port.
#[test]
+2 -2
View File
@@ -28,8 +28,8 @@ pub fn tool_definitions(has_ui: bool) -> Value {
"background": {"type": "string", "description": "\"dark\" (default without plot_style), \"white\" (default with one), \"paper\" or \"#rrggbb\""},
"plot_style": {"type": "string", "description": "a plot style table: monochrome.ctb, grayscale.ctb, default.ctb, default.stb, monochrome.stb, or one the drawing holds; \"none\" or \"\" for the objects' own properties"},
"path": {"type": "string"}}}}),
json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case; `query` is the same filter), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.",
"inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "query": {"type": "string"}, "layer": {"type": "string"},
json!({"name": "find_text", "description": "Read the drawing's texts: TEXT, MTEXT (formatting removed), block attributes and multileaders, each with its text, insertion point `at`, height, rotation, style, layer and handle. Filter by `contains` (any case), `layer` and/or `window` [[x0,y0],[x1,y1]] around the insertion points; page with offset and limit (default 200). Use it to find room names, sheet titles and notes without reading all the geometry.",
"inputSchema": {"type": "object", "properties": {"contains": {"type": "string"}, "layer": {"type": "string"},
"window": {"type": "array", "items": {"type": "array", "items": {"type": "number"}, "minItems": 2, "maxItems": 2}, "minItems": 2, "maxItems": 2},
"limit": {"type": "integer", "minimum": 0}, "offset": {"type": "integer", "minimum": 0}}}}),
json!({"name": "new_drawing", "description": "Create a new drawing (imperial by default, or metric).",
+8
View File
@@ -308,6 +308,14 @@ fn key_from(name: &str) -> Option<egui::Key> {
}
pub fn handle(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
let out = handle_request(app, ctx, req);
// A command the request ran may have asked for a bar (MENUBAR, TOOLBAR): apply it before
// the next request, so a later query or `ui.set` sees the bars as they are now.
app.sync_bars();
out
}
fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -> Outcome {
let p = &req.params;
let s = |k: &str| p.get(k).and_then(Value::as_str);
let f = |k: &str| p.get(k).and_then(Value::as_f64);
+94 -1
View File
@@ -316,6 +316,10 @@ pub fn command(app: &mut crate::CadApp, reset: bool, params: &Value) -> Result<V
}
/// Validate and repair the stored workspace, sync it with the app, and render the dock panels; a failed restore falls back to the default layout with a status message.
/// Draw the docked workspace: restore or fall back from the persisted layout, render every
/// panel body plus the header close buttons, and apply the resulting actions through
/// [`command`]. Bodies may dispatch commands, so the canonical workspace is published before
/// rendering while the layout snapshot stays immutable.
pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) {
let t = crate::theme::Tokens::get();
let mut workspace = app.ui.docking.clone();
@@ -348,7 +352,33 @@ pub fn show(app: &mut crate::CadApp, ui: &mut egui::Ui) {
if let Some(panel) = app.raise_panel.take() {
area = area.raise_panel(panel);
}
let mut output = area.show_content(ui, &workspace.layout, &style, &mut Panels { app });
let (mut output, header_close) = {
let mut panels = Panels { app, close: None };
let output = area.show_content(ui, &workspace.layout, &style, &mut panels);
(output, panels.close)
};
// Accordion title bars are rendered by the shared surface without a header callback, so
// place the same close button over their title bar, left of the stock collapse control.
let mut close = header_close;
for panel in stack_panels(&workspace.layout) {
if !permissions(&panel).closable {
continue;
}
let Some(title) = ui.ctx().read_response(egui::Id::unique("cadcraft-docking").with(("tab", panel))) else { continue };
if !title.rect.is_positive() {
continue;
}
let rect = egui::Rect::from_center_size(
egui::pos2(title.rect.right() - 18.0 - CLOSE_BUTTON * 0.5 - 4.0, title.rect.center().y),
egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON),
);
if close_button(ui, panel, rect) {
close = Some(panel);
}
}
if let Some(panel) = close {
output.actions.push(Action::Close { panel });
}
// Keys typed in a floating panel's own OS window run the main window's shortcuts and
// command line; files dropped on one open like files dropped on the main window.
app.forward_native_input(ui.ctx(), std::mem::take(&mut output.forwarded_events), output.forwarded_modifiers);
@@ -393,9 +423,55 @@ pub fn native_input_blocked(app: &crate::CadApp, ctx: &egui::Context) -> bool {
/// The panels' contents, names, size limits and icons for the dock area.
pub struct Panels<'a> {
pub app: &'a mut crate::CadApp,
/// The panel whose header close button was clicked this frame.
pub close: Option<Panel>,
}
/// Size of a panel header's close button, in points.
const CLOSE_BUTTON: f32 = 16.0;
/// The accessible name of a header's close button. One translated template carries both the
/// verb and the panel name, so a catalog translates the whole name instead of leaving an
/// English verb in front of a translated panel label.
fn close_label(panel: Panel) -> String {
crate::tf!("Close {panel}", panel = crate::i18n::t(panel.label()))
}
/// A visible close button for a panel header. It runs the same action as the tab context
/// menu's "Close panel"; the accessible name includes the panel so the headers stay distinct.
fn close_button(ui: &mut egui::Ui, panel: Panel, rect: egui::Rect) -> bool {
let t = crate::theme::Tokens::get();
let response = ui.interact(rect, egui::Id::unique("cadcraft-docking").with(("close", panel.id())), egui::Sense::click());
let label = close_label(panel);
crate::icons::describe_control(ui, &response, &label, None, false);
if response.hovered() {
ui.painter().rect_filled(rect.expand(2.0), 2.0, t.control_hover.gamma_multiply(0.6));
}
crate::icons::paint(ui.painter(), rect, crate::icons::Icon::Close, false);
response.on_hover_text(crate::tl!("Close panel")).clicked()
}
/// Panels whose title bar is an accordion entry rather than a tab group header.
fn stack_panels(layout: &Layout<Panel>) -> Vec<Panel> {
let mut panels = Vec::new();
let mut nodes: Vec<&Node<Panel>> = layout.root.iter().collect();
while let Some(node) = nodes.pop() {
match node {
Node::Split { first, second, .. } => {
nodes.push(first);
nodes.push(second);
}
Node::Stack { entries } => panels.extend(entries.iter().map(|entry| entry.panel)),
// Tab groups draw their own header; nothing else stacks an accordion entry.
_ => {}
}
}
panels
}
impl DockContent<Panel> for Panels<'_> {
/// Render `panel`'s existing view; Layers, Properties and External References scroll
/// independently, and the drawing canvas paints its own background before the view.
fn body(&mut self, ui: &mut egui::Ui, panel: &Panel) {
let app = &mut *self.app;
match panel {
@@ -445,6 +521,23 @@ impl DockContent<Panel> for Panels<'_> {
crate::icons::paint(painter, rect, icon, false);
true
}
/// Reserve header space for the close button only when `active` may be closed, so the
/// drawing view's title gets no empty gap.
fn group_header_width(&self, _panels: &[Panel], active: &Panel, _floating: bool, _strip_width: f32) -> f32 {
if permissions(active).closable { CLOSE_BUTTON + 8.0 } else { 0.0 }
}
/// Draw the close button at the right edge of a tab-group header and remember the panel
/// to close once the docking surface has returned, so layout changes stay outside rendering.
fn group_header(&mut self, ui: &mut egui::Ui, _panels: &[Panel], active: &Panel, _floating: bool) {
let header = ui.max_rect();
let rect = egui::Rect::from_center_size(
egui::pos2(header.right() - CLOSE_BUTTON * 0.5 - 4.0, header.center().y),
egui::vec2(CLOSE_BUTTON, CLOSE_BUTTON),
);
if close_button(ui, *active, rect) {
self.close = Some(*active);
}
}
}
fn panel_limits(panel: &Panel) -> PanelLimits {
+3
View File
@@ -139,11 +139,13 @@
Clip Viewport Delimitar ventana gráfica
Clipboard Portapapeles
Close Cerrar
Close {panel} Cerrar {panel}
Close All Cerrar todo
Close All Other Drawings Cerrar todos los demás dibujos
Close Array Editing Cerrar la edición de matriz
Close Comparison Cerrar comparación
Export Comparison Exportar comparación
Close panel Cerrar panel
Closed Cerrada
Coincident Coincidente
Collapse Palettes Contraer paletas
@@ -542,6 +544,7 @@
Measure Medir
Measure Distance Medir distancia
Measure Geometry Medir geometría
Menu Bar Barra de menús
Merge Cells Combinar celdas
Merged PRs PR integradas
Mid Between 2 Points Punto medio entre 2 puntos
1 # CADCraft Spanish interface catalog — original translations.
139
140
141
142
143
144
145
146
147
148
149
150
151
544
545
546
547
548
549
550
+1
View File
@@ -146,6 +146,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet<String> {
"chrome",
"cmdline",
"credits",
"docking",
"dialogs",
"hatchdlg",
"aliasdlg",
+3
View File
@@ -143,11 +143,13 @@
Xref Clip Frame Рамка обрізки зовнішнього посилання
Clipboard Буфер обміну
Close Закрити
Close {panel} Закрити {panel}
Close All Закрити всі
Close All Other Drawings Закрити всі інші креслення
Closed Замкнений
Close Comparison Закрити порівняння
Export Comparison Експортувати порівняння
Close panel Закрити панель
Coincident Збіг
Collapse Palettes Згорнути палітри
Collapse Tool Sets Згорнути набори інструментів
@@ -534,6 +536,7 @@
Measure Розмітити
Measure Distance Виміряти відстань
Measure Geometry Виміряти геометрію
Menu Bar Рядок меню
Merge Cells Об'єднати комірки
Merged PRs Об'єднані PR
Mid Between 2 Points Середина між 2 точками
1 # CADCraft Ukrainian interface catalog — original translations by @dmatviichuk.
143
144
145
146
147
148
149
150
151
152
153
154
155
536
537
538
539
540
541
542
+1
View File
@@ -928,6 +928,7 @@
Time 时间
To get started, create or open a drawing. 若要开始,请创建或打开一个图形。
Tool Bar 工具栏
Menu Bar 菜单栏
Tool Sets 工具集
Tools 工具
Torus 圆环体
1 # CADCraft Simplified Chinese interface catalog — original translations.
928
929
930
931
932
933
934
+85 -1
View File
@@ -283,6 +283,9 @@ pub struct CadApp {
pub system_animations: Option<bool>,
/// What `ui.system_cursor` goes back to when the interface is reset ([`Self::set_system_cursor_default`]).
pub system_cursor_default: bool,
/// Whether the host has a native menu bar: off where the menus stay in the window
/// ([`Self::set_native_menus`]).
pub native_menus: bool,
pub session: Session,
pub ui: UiState,
/// The interface's own preferences from the Options dialog ([`options`]).
@@ -381,6 +384,7 @@ impl CadApp {
system_languages: Vec::new(),
system_animations: None,
system_cursor_default: false,
native_menus: cfg!(target_os = "macos"),
session,
ui: UiState::default(),
options: options::UiOptions::default(),
@@ -588,7 +592,11 @@ impl CadApp {
if let Some(r) = menus::run_ui_command(self, id, &params) {
return r;
}
// The bars as the interface shows them now (a `ui.set` may have just changed one), and any
// MENUBAR or TOOLBAR request applied at once.
self.sync_bars();
let r = self.session.execute(id, &params).map_err(|e| e.to_string());
self.sync_bars();
if let Ok(v) = &r
&& let Some(m) = v.get("message").and_then(Value::as_str)
{
@@ -607,6 +615,7 @@ impl CadApp {
if menus::run_ui_command(self, name, &Value::Null).is_some() {
return;
}
self.sync_bars();
if let Err(e) = self.session.start(name) {
self.session.echo(e.to_string());
}
@@ -622,6 +631,7 @@ 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<String> {
self.sync_bars();
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.
@@ -636,7 +646,9 @@ impl CadApp {
return None;
}
}
let e = match (self.session.cmdline(text), fallback) {
let r = self.session.cmdline(text);
self.sync_bars();
let e = match (r, fallback) {
(Ok(()), _) => return None,
(Err(cadcraft_engine::EngineError::UnknownCommand(_)), Some(f)) => return self.cmdline(f),
(Err(e), _) => e.to_string(),
@@ -645,6 +657,18 @@ impl CadApp {
Some(e)
}
/// Apply a menu bar / tool bar change MENUBAR or TOOLBAR asked for, and report the bars shown.
fn sync_bars(&mut self) {
let b = std::mem::take(&mut self.session.bars_request);
if let Some(on) = b.menubar {
self.ui.in_window_menu = on;
}
if let Some(show) = b.toolbar {
self.ui.show_toolbar = show;
}
self.session.bars_shown = cadcraft_engine::cmd::interface::InterfaceBars { menubar: self.ui.in_window_menu, toolbar: self.ui.show_toolbar };
}
/// The theme the interface shows now (the choice resolved against the OS appearance).
pub fn shown_theme(&self) -> egui::Theme {
self.shown_theme.unwrap_or_else(|| self.ui.theme.resolve(None))
@@ -731,6 +755,15 @@ impl CadApp {
}
}
/// Tell the interface whether the host has a native menu bar. Where it has none, the
/// in-window menu is the only menu, so it is shown and a reset keeps it.
pub fn set_native_menus(&mut self, on: bool) {
self.native_menus = on;
if !on {
self.ui.in_window_menu = true;
}
}
pub fn set_status(&mut self, s: impl Into<String>) {
self.status = Some((s.into(), now_ms()));
}
@@ -1087,6 +1120,7 @@ impl CadApp {
/// Draw one UI pass: title/toolbar, optional menu/status bar/file tabs, the standalone tool-set strip when a drawing is shown but Tool Sets is not docked, docking or the start page, and the floating overlays; record `frame_ms`. Runs on every pass, including one egui later discards.
fn draw(&mut self, ui: &mut egui::Ui) {
let t0 = now_ms();
self.sync_bars();
control::begin_frame(ui.ctx());
let t = theme::Tokens::get();
chrome::title_and_toolbar(self, ui);
@@ -1408,4 +1442,54 @@ mod tests {
let ui: UiState = serde_json::from_value(json!({ "saveFormat": "dwg" })).unwrap_or_default();
assert_eq!(ui.save_format, SaveFormat::Dwg);
}
#[test]
fn options_reset_brings_the_interface_back() {
// Hiding the interface (View/Window toggles) can leave no way back — on Windows the
// in-window menu bar is the only menu there is. Options > Reset must restore it (#1240).
let mut a = app();
a.run("ui.toggle.toolbar", json!({ "on": false })).unwrap();
a.run("ui.toggle.menubar", json!({ "on": cfg!(target_os = "macos") })).unwrap();
a.start("ui.hidepalettes");
assert!(!a.ui.show_toolbar && !a.ui.show_palettes && !a.ui.show_toolsets);
assert_eq!(a.ui.in_window_menu, cfg!(target_os = "macos"), "the test did not hide the menu bar");
a.run("options", json!({ "reset": true })).unwrap();
assert!(a.ui.show_toolbar, "the tool bar is still hidden");
assert!(a.ui.show_palettes, "the palettes are still hidden");
assert!(a.ui.show_toolsets);
assert_eq!(a.ui.in_window_menu, !cfg!(target_os = "macos"), "the menu bar did not come back");
}
#[test]
fn options_reset_keeps_the_menu_where_the_host_has_no_native_one() {
// With CADCRAFT_NO_NATIVE_MENU=1 the menus stay in the window: the host reports no native
// menu bar, so the in-window one is the only menu and the reset must leave it (#1240).
let mut a = app();
a.set_native_menus(false);
assert!(a.ui.in_window_menu, "the host's setting did not show the in-window menu");
a.run("ui.toggle.menubar", json!({ "on": false })).unwrap();
a.run("options", json!({ "reset": true })).unwrap();
assert!(a.ui.in_window_menu, "the only menu bar did not come back");
// Beside a native menu bar, the reset returns to the platform default.
a.set_native_menus(true);
a.run("ui.toggle.menubar", json!({ "on": true })).unwrap();
a.run("options", json!({ "reset": true })).unwrap();
assert!(!a.ui.in_window_menu, "the in-window menu is not the default beside a native one");
}
#[test]
fn options_reset_keeps_the_users_shortcuts_and_folders() {
// The reset brings hidden bars back (#1240); it must not also lose the user's own
// keyboard shortcuts or the folders the file pickers remember.
let mut a = app();
a.ui.shortcuts.insert("line".into(), "Ctrl+Shift+L".into());
a.ui.last_lisp_dir = Some("lisp-folder".into());
a.ui.last_pgp_dir = Some("pgp-folder".into());
a.run("ui.toggle.toolbar", json!({ "on": false })).unwrap();
a.run("options", json!({ "reset": true })).unwrap();
assert!(a.ui.show_toolbar, "the tool bar is still hidden");
assert_eq!(a.ui.shortcuts.get("line").map(String::as_str), Some("Ctrl+Shift+L"), "the reset lost a user shortcut");
assert_eq!(a.ui.last_lisp_dir.as_deref(), Some("lisp-folder"));
assert_eq!(a.ui.last_pgp_dir.as_deref(), Some("pgp-folder"));
}
}
+9 -2
View File
@@ -797,13 +797,20 @@ fn switch_on_hover(ctx: &egui::Context, titles: &[egui::Response]) {
}
}
/// Activate a menu command. QuickCalc toggles transparently; other items clear pending
/// command-line text and start their command interactively.
/// Activate a menu command. QuickCalc toggles transparently, and Reference Manager closes its
/// palette when it is open (typed XREF only opens it); other items clear pending command-line
/// text and start their command interactively.
pub fn activate(app: &mut CadApp, id: &str) {
if id == "ui.toggle.quickcalc" {
run_transparent(app, id);
return;
}
if id == "xref" && app.ui.docking.layout.contains(&crate::docking::Panel::ExternalRefs) {
if let Err(e) = crate::xrefs::close_palette(app) {
app.set_status(e);
}
return;
}
app.cmd.buffer.clear();
app.start(id);
}
+23 -6
View File
@@ -434,13 +434,30 @@ fn apply_right_click(o: &mut UiOptions, c: &UiChanges) {
/// The interface preferences back to their defaults (the interface language stays).
fn reset_ui(app: &mut CadApp) {
let d = crate::UiState::default();
app.ui.theme = d.theme;
app.ui.animations = d.animations;
app.ui.save_format = d.save_format;
app.ui.save_version = d.save_version;
// Everything interface, back to its defaults: a hidden menu bar, tool bar, palettes or
// panels and a rearranged panel layout come back — once the menu bar is hidden there may be
// no other way to reach the toggles (#1240). The interface language stays; the open dialog,
// the start tab, the recent files and the remembered folders are state, not preferences, and
// stay too. The user's keyboard shortcuts are their own customisation, which Window > Reset
// Palettes keeps as well: a reset meant to bring a bar back must not lose them.
let (language, dialog, start_tab) = (app.ui.interface_language, app.ui.dialog.take(), app.ui.start_tab);
let recent_files = std::mem::take(&mut app.ui.recent_files);
let shortcuts = std::mem::take(&mut app.ui.shortcuts);
let (last_lisp_dir, last_pgp_dir) = (app.ui.last_lisp_dir.take(), app.ui.last_pgp_dir.take());
app.ui = crate::UiState {
interface_language: language,
dialog,
start_tab,
recent_files,
shortcuts,
last_lisp_dir,
last_pgp_dir,
..Default::default()
};
// Where the host has no native menu bar the in-window one is the only menu: the reset must
// leave it in place (#1240).
app.ui.in_window_menu = !app.native_menus;
app.ui.system_cursor = app.system_cursor_default;
app.ui.history_lines = d.history_lines;
app.options = UiOptions::default();
}
+6
View File
@@ -42,6 +42,12 @@ fn open_palette(app: &mut CadApp) -> Result<Value, String> {
crate::docking::command(app, false, &json!({ "operation": "open", "panel": Panel::ExternalRefs.id() }))
}
/// Close the palette: Window ▸ Reference Manager while it is open, as Window ▸ QuickCalc closes
/// QuickCalc (#2273).
pub(crate) fn close_palette(app: &mut CadApp) -> Result<Value, String> {
crate::docking::command(app, false, &json!({ "operation": "close", "panel": Panel::ExternalRefs.id() }))
}
/// A picked file inside the host drawing's folder is attached by its relative path, so the
/// project folder can move.
fn relative_to_host(app: &CadApp, picked: &str) -> String {
+60 -1
View File
@@ -123,7 +123,7 @@ fn palette_icons_are_painted_in_code_and_shown_in_an_iconic_column() {
let ctx = egui::Context::default();
let mut paint = |panel: Panel| {
let mut painted = false;
let mut content = Panels { app: &mut app };
let mut content = Panels { app: &mut app, close: None };
let mut output = ctx.run_ui(egui::RawInput::default(), |ui| {
let painter = ui.ctx().layer_painter(egui::LayerId::background());
let rect = egui::Rect::from_min_size(egui::Pos2::ZERO, vec2(20.0, 20.0));
@@ -593,3 +593,62 @@ fn group_drag_bar_moves_the_whole_group_into_the_other_dock() {
assert_eq!(frames(layout), [[Panel::Canvas]]);
assert_eq!(h.state().session.doc().unwrap(), &document);
}
/// Guard that every closable panel header offers a visible close button: a docked tab group,
/// the default accordion stack, and a floating group. Each click must remove the panel, the
/// button must not cover the title, and the tab context menu must still close the same panel.
#[test]
fn every_panel_header_has_a_close_button_that_closes_like_the_context_menu() {
let mut h = harness(None, 1280.0, 1.0);
assert!(h.query_by_label("Close Tool Sets").is_some(), "docked tab headers show a close button");
assert!(h.query_by_label("Close Drawing").is_none(), "the drawing view is not a closable panel");
// External References opens as a tabbed pane; its button sits beside the title, not over it.
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"externalReferences"})).unwrap();
h.run_steps(4);
assert!(h.state().ui.docking.layout.contains(&Panel::ExternalRefs));
let close = h.get_by_label("Close External References").rect();
let title = h.get_by_role_and_label(egui::accesskit::Role::Tab, "External References").rect();
assert!(!close.intersects(title), "the close button does not cover the panel title");
h.get_by_label("Close External References").click();
h.run_steps(4);
assert!(!h.state().ui.docking.layout.contains(&Panel::ExternalRefs));
// Accordion headers (the default Layers/Properties stack) get one too.
assert!(h.state().ui.docking.layout.contains(&Panel::Layers));
h.get_by_label("Close Layers").click();
h.run_steps(4);
assert!(!h.state().ui.docking.layout.contains(&Panel::Layers));
// The context menu still closes the same panel after it is reopened.
h.state_mut().run("ui.dock", json!({"operation":"open","panel":"layers"})).unwrap();
h.run_steps(4);
assert!(h.state().ui.docking.layout.contains(&Panel::Layers));
h.get_by_role_and_label(egui::accesskit::Role::Tab, "Layers").click_button(PointerButton::Secondary);
h.run_steps(3);
// The docking surface's stock tab menu item ("Close Panel"), not our tooltip.
h.get_by_label("Close Panel").click();
h.run_steps(4);
assert!(!h.state().ui.docking.layout.contains(&Panel::Layers));
// Floating panels get the same button in their group header.
h.state_mut().run("ui.dock", json!({"operation":"float","panel":"properties","rect":[400,250,300,350]})).unwrap();
h.run_steps(4);
h.get_by_label("Close Properties").click();
h.run_steps(4);
assert!(!h.state().ui.docking.layout.contains(&Panel::Properties));
}
/// The accessible name is one translated string, not an English verb glued to a translated
/// panel label: Spanish readers must hear "Cerrar Capas", never "Close Capas".
#[test]
fn spanish_close_button_accessible_name_is_localized_as_a_whole() {
let mut h = harness(None, 1280.0, 1.0);
h.state_mut().run("ui.language", json!({"lang": "es"})).unwrap();
h.run_steps(4);
assert!(h.query_by_label("Cerrar Capas").is_some(), "the accordion close button is named in Spanish");
assert!(h.query_by_label("Cerrar Propiedades").is_some(), "every panel's close button follows the language");
assert!(h.query_by_label("Close Capas").is_none(), "no English verb survives the translation");
h.get_by_label("Cerrar Capas").click();
h.run_steps(4);
assert!(!h.state().ui.docking.layout.contains(&Panel::Layers), "the localized name still closes its panel");
}
+19
View File
@@ -252,3 +252,22 @@ fn selection_highlight_settings_set_save_and_show_in_the_selection_tab() {
assert!(text.contains(label), "{label} missing from:\n{text}");
}
}
#[test]
fn reset_brings_back_hidden_menu_bar_toolbar_and_status_bar() {
// #1240: with the in-window menu bar, the toolbar and the status bar hidden, OPTIONS ▸ Reset
// to Defaults (typed, or from the right-click menu) is the way back.
let mut a = app();
let d = cadcraft_ui_egui::UiState::default();
a.ui.in_window_menu = !d.in_window_menu;
a.ui.show_toolbar = false;
a.ui.show_status_bar = false;
a.ui.show_command_line = false;
a.ui.show_palettes = false;
a.run("options", json!({"reset": true})).unwrap();
assert_eq!(a.ui.in_window_menu, d.in_window_menu);
assert_eq!(a.ui.show_toolbar, d.show_toolbar);
assert_eq!(a.ui.show_status_bar, d.show_status_bar);
assert_eq!(a.ui.show_command_line, d.show_command_line);
assert_eq!(a.ui.show_palettes, d.show_palettes);
}
+107
View File
@@ -0,0 +1,107 @@
//! MENUBAR and TOOLBAR at the command line bring a hidden menu bar and tool bar back (#1341):
//! on Windows and Linux the in-window menu bar is the only menu, so with it hidden typing these
//! is the way back, as in AutoCAD.
use cadcraft_engine::Session;
use cadcraft_ui_egui::{CadApp, Services};
use serde_json::json;
fn app() -> CadApp {
CadApp::new(Session::new(), Services::default())
}
#[test]
fn typed_menubar_shows_and_hides_the_menu_bar() {
let mut app = app();
app.ui.in_window_menu = false;
app.cmdline("MENUBAR");
assert_eq!(app.session.prompt_text(), "MENUBAR Enter new value for MENUBAR <0>:");
app.cmdline("1");
assert!(app.session.running.is_none());
assert!(app.ui.in_window_menu);
// 0 hides it again; anything else is refused and asked again.
app.cmdline("MENUBAR");
app.cmdline("2");
assert!(app.session.running.is_some(), "still asking");
app.cmdline("0");
assert!(!app.ui.in_window_menu);
}
#[test]
fn typed_toolbar_shows_the_tool_bar_by_default() {
let mut app = app();
app.ui.show_toolbar = false;
app.cmdline("TOOLBAR");
assert_eq!(app.session.prompt_text(), "TOOLBAR Enter tool bar option or [Show/Hide] <Show>:");
app.cmdline("");
assert!(app.ui.show_toolbar);
app.cmdline("TOOLBAR");
app.cmdline("H");
assert!(!app.ui.show_toolbar);
}
#[test]
fn the_json_forms_report_and_set_the_bars() {
let mut app = app();
app.ui.in_window_menu = true;
app.ui.show_toolbar = false;
app.cmdline("MENUBAR");
app.cmdline("");
assert_eq!(app.session.execute("menubar", &json!({})).unwrap(), json!({ "value": 1 }));
assert_eq!(app.session.execute("toolbar", &json!({})).unwrap(), json!({ "show": false }));
app.session.execute("toolbar", &json!({ "show": true })).unwrap();
app.cmdline("MENUBAR");
app.cmdline("");
assert!(app.ui.show_toolbar && app.ui.in_window_menu);
assert!(app.session.execute("menubar", &json!({ "value": 3 })).is_err());
}
/// MENUBAR changes only the menu bar: a tool bar change made before the request is applied
/// stays (a control-API `ui.set` can come between them).
#[test]
fn menubar_leaves_a_later_tool_bar_change() {
let mut app = app();
app.ui.in_window_menu = true;
app.ui.show_toolbar = true;
app.session.execute("menubar", &json!({ "value": 0 })).unwrap();
app.ui.show_toolbar = false;
app.cmdline("'REDRAW");
assert!(!app.ui.in_window_menu, "MENUBAR applied");
assert!(!app.ui.show_toolbar, "the tool bar keeps its later change");
}
/// A bar query through `CadApp::run` reports the bars as the interface shows them now, even when
/// a UI change came just before it with no frame drawn in between.
#[test]
fn a_bar_query_sees_a_ui_change_just_made() {
let mut app = app();
app.ui.show_toolbar = true;
assert_eq!(app.run("toolbar", json!({})).unwrap(), json!({ "show": true }));
app.ui.show_toolbar = false;
assert_eq!(app.run("toolbar", json!({})).unwrap(), json!({ "show": false }));
app.run("toolbar", json!({ "show": true })).unwrap();
assert!(app.ui.show_toolbar, "the request is applied at once");
}
#[test]
fn menubar_started_from_the_ui_offers_the_bar_as_shown_now() {
let mut app = app();
app.ui.in_window_menu = true;
app.cmdline("");
app.ui.in_window_menu = false;
app.start("menubar");
let prompt = app.session.prompt_text();
assert!(prompt.contains("<0>"), "{prompt}");
}
#[test]
fn enter_through_the_control_api_applies_the_bar_before_the_next_request() {
let mut app = app();
let ctx = egui::Context::default();
app.ui.show_toolbar = false;
app.start("toolbar");
let (req, _pending) = cadcraft_ui_egui::control::ControlRequest::new("cmdline.key", serde_json::json!({ "key": "enter" }));
cadcraft_ui_egui::control::handle(&mut app, &ctx, &req);
assert!(app.session.running.is_none());
assert!(app.ui.show_toolbar, "TOOLBAR's default Show is applied before the next request");
}
+18 -1
View File
@@ -5,7 +5,7 @@ use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io};
use cadcraft_engine::doc::geom::Vec3;
use cadcraft_engine::doc::{Drawing, Entity, EntityKind, Handle, Layer, Line, XrefStatus};
use cadcraft_ui_egui::{CadApp, Services, docking::Panel};
use cadcraft_ui_egui::{CadApp, Services, docking::Panel, menus};
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::Queryable;
@@ -71,6 +71,23 @@ fn xref_opens_the_palette_and_its_buttons_manage_the_xref() {
h.get_by_label("site");
}
/// Window ▸ Reference Manager closes the palette when it is open, like Window ▸ QuickCalc; typed,
/// XREF only ever opens it (#2273).
#[test]
fn the_window_menu_item_closes_an_open_palette() {
let mut app = CadApp::new(Session::default(), Services::default());
let open = |app: &CadApp| app.ui.docking.layout.contains(&Panel::ExternalRefs);
menus::activate(&mut app, "xref");
assert!(open(&app), "the menu item opens the palette");
menus::activate(&mut app, "xref");
assert!(!open(&app), "the menu item closes the open palette");
menus::activate(&mut app, "xref");
assert!(open(&app), "and opens it again");
assert!(app.cmdline("XREF").is_none());
assert!(app.cmdline("XR").is_none());
assert!(open(&app), "typed XREF keeps it open");
}
#[test]
fn json_xref_lists_and_never_opens_the_palette() {
let mut app = CadApp::new(Session::default(), Services::default());
+6
View File
@@ -144,6 +144,12 @@ The shortcut also works with text-field focus. Toggling preserves the running dr
and pending command-line input. The expression, history and calculator variables survive
closing/reopening within the same session; they are not saved across application restarts.
The External References palette (`externalReferences`) is not part of the default arrangement
either. Typed `XREF`/`XR` opens and activates it. **Window > Reference Manager** (also
`ui.menu.invoke` with `xref`) opens it too, but closes it when it is present, as Window >
QuickCalc does; closing leaves the running command and command-line input alone. `xref` with
JSON parameters lists the references and never opens or closes the palette.
Invoke these UI commands through `engine.execute`, for example `{"command":"ui.dock","params":{"operation":"float","panel":"layers","rect":[100,100,320,440]}}`.
Advanced `ui.dock` operations use the same validated transaction as pointer gestures:
+1 -1
View File
@@ -48,7 +48,7 @@ Example client configuration (Claude Code / Claude Desktop):
| `execute {"command": "loops", "params": {tolerance?, maxPairs?, limit?, offset?}}` | Implied closed loops from loose LINE and ARC chains: each closed loop with its member handles, perimeter, area and winding, exact with arcs; each open chain with the endpoint gap, its location (`at`, `ends`) and length; and branch junctions (three or more ends meeting), reported but not resolved. `tolerance` defaults to 1e-9 × the extents diagonal; the quadratic endpoint pairing stops at `maxPairs` (default 1,000,000) and reports `capped` with `pairTestsNeeded` instead of guessing from a partial pairing. |
| `query_entities {type?, layer?, selected?, window?, crossing?, limit?, offset?}` | Filtered entities with handles and geometry. `selected: true` restricts results to the current selection in the active space; an empty selection returns no entities. Omitted/false queries all entities in that space. Filters combine before paging. `window` `[[x0,y0],[x1,y1]]` finds objects whose geometry is inside it or crosses it (`crossing: false`: entirely inside). `count` is every match, `returned` the page (`offset`, `limit`, default 500). |
| `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`; `"none"` (or `""`) draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. |
| `find_text {contains?, query?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (`contains`, or `query` as an alias; any case), layer and a window around the insertion points. Read-only (the `texts` command). |
| `find_text {contains?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (any case), layer and a window around the insertion points. Read-only (the `texts` command). |
| `new_drawing {metric?}`, `open {path}`, `save {path?}`, `cancel` | Files and Escape. `save` to a `.svg`, `.png` or `.pdf` path exports: the drawing keeps its name and unsaved changes. |
| `screenshot`, `ui_inspect`, `ui_click {x, y}` | Only when connected to the app. |
+1 -2
View File
@@ -81,8 +81,7 @@ prints as `Normal`. A colour-dependent table ignores the property.
style and the named styles.
- `layer.set {name, plotStyle}` sets a layer's plot style.
- `stylesmanager {action, …}` manages the tables: `list`, `get`, `new` (`kind`, `from`), `set`
(`style: {name, …fields}`, `removeStyle`, `description`; it replies with the table's name and
only what changed), `delete`, `load` (`path` or `text`)
(`style: {name, …fields}`, `removeStyle`, `description`), `delete`, `load` (`path` or `text`)
and `save` (`path`, or returns `text`). Typed or chosen from **File ▸ Plot Styles...**, it
opens the Plot Style Manager dialog.