diff --git a/CHANGELOG.md b/CHANGELOG.md index f5c5d01b..17211bc9 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -12,6 +12,7 @@ How to write it (see AGENTS.md): ## Unreleased ### New +- Your settings in one file: Export Settings and Import Settings (Manage › Customization, or CONFIGEXPORT and CONFIGIMPORT) save the theme, Options, units, grid and snap, lineweights, plot style and command aliases to a TOML file and read it back on any computer. - 3DMOVE, 3DROTATE, ROTATE3D, 3DSCALE, MIRROR3D, 3DALIGN and 3DARRAY move, turn, scale, mirror, align and array objects in space, under Modify ▸ 3D Operations, with AutoCAD's prompts and aliases (3M, 3R, 3AL, 3A). - LINE takes points in space: type x,y,z or @dx,dy,dz and the line keeps its height. - The command line's AutoComplete learns which commands you use: the ones you run most, and most recently, move up the list, so typing LI soon offers LINE first if you draw lines more than you list. The arrow keys move through the suggestions, and Reset Suggestion Order in the command line's right-click menu forgets what was learned. diff --git a/Cargo.lock b/Cargo.lock index bdac7ee7..1bb675f0 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1392,6 +1392,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "toml", "zip", ] diff --git a/Cargo.toml b/Cargo.toml index 0319a7b4..24ac84da 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -67,6 +67,8 @@ unicode-bidi = "0.3.18" icu_segmenter = { version = "~2.3", default-features = false, features = ["compiled_data", "lstm"] } image = { version = "0.25", default-features = false, features = ["png", "jpeg", "bmp", "tiff"] } encoding_rs = "0.8.35" +# The portable settings file (CONFIGEXPORT, CONFIGIMPORT): TOML, keys kept in the order written. +toml = { version = "1.1", default-features = false, features = ["std", "serde", "parse", "display", "preserve_order"] } # XML for the SVG reader (streaming parser, no entity expansion beyond the five predefined ones) quick-xml = "0.42" diff --git a/apps/draftcraft/src/main.rs b/apps/draftcraft/src/main.rs index bff0e49d..b811ffd1 100644 --- a/apps/draftcraft/src/main.rs +++ b/apps/draftcraft/src/main.rs @@ -200,7 +200,7 @@ fn services() -> Services { /// filter's extension, and macOS accepts only listed extensions, replacing any other with the /// first one. DWG must be listed for a `.dwg` name to survive, and a drawing opened from DWG /// then defaults to DWG; other names keep DXF first. -fn filters_for_save(name: &str) -> [(&'static str, &'static str); 9] { +fn filters_for_save(name: &str) -> [(&'static str, &'static str); 10] { let mut filters = [ ("Drawing (DXF)", "dxf"), ("Drawing (DWG)", "dwg"), @@ -212,6 +212,8 @@ fn filters_for_save(name: &str) -> [(&'static str, &'static str); 9] { ("ZIP archive", "zip"), // ATTOUT's attribute values. ("Text, tab-delimited (TXT)", "txt"), + // CONFIGEXPORT's settings file. + ("DraftCraft settings (TOML)", "toml"), ]; let lower = name.to_ascii_lowercase(); filters.sort_by_key(|(_, ext)| !lower.ends_with(&format!(".{ext}"))); @@ -524,6 +526,7 @@ mod tests { assert_eq!(first("office.dwt"), "dwt"); assert_eq!(first("Project.dcss"), "dcss"); assert_eq!(first("Floorplan.txt"), "txt"); + assert_eq!(first("draftcraft-settings.toml"), "toml"); for name in ["a.dwg", "b.dxf", "c"] { let exts: Vec<_> = filters_for_save(name).iter().map(|(_, e)| *e).collect(); assert!(exts.contains(&"dwg") && exts.contains(&"dxf"), "{name}"); diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index a8549f85..e5607ff5 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -21,6 +21,8 @@ draftcraft-render = { workspace = true } craft-docpath = { workspace = true } serde = { workspace = true } serde_json = { workspace = true } +# The portable settings file (CONFIGEXPORT, CONFIGIMPORT). +toml = { workspace = true } thiserror = { workspace = true } log = { workspace = true } # 3D solids (feature `solids`, docs/solids.md): the kernel facade, the only way to the kernel. diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 553415c4..9fcb6e36 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -7,6 +7,7 @@ mod array; mod audit; pub(crate) mod blocks; pub mod clipboard; +pub mod config; pub mod constraints; mod draw; mod draw2; @@ -221,6 +222,7 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(inquiry::specs()); v.extend(settings::specs()); v.extend(options::specs()); + v.extend(config::specs()); v.extend(utility::specs()); v.extend(table::specs()); v.extend(tolerance::specs()); diff --git a/crates/engine/src/cmd/config.rs b/crates/engine/src/cmd/config.rs new file mode 100644 index 00000000..40193a51 --- /dev/null +++ b/crates/engine/src/cmd/config.rs @@ -0,0 +1,645 @@ +//! CONFIGEXPORT and CONFIGIMPORT: the portable settings file (`docs/config-file.md`). +//! +//! One flat TOML file carries the settings a user sets up once and wants on every computer, or +//! wants to hand to a colleague: the Options profile (object snaps, grid and snap spacing, +//! selection, MEASUREINIT…), the drawing settings (units, linetype scale, current lineweight, +//! annotation scale…), the plot settings of the layouts (plot style table, lineweights) and the +//! user's command aliases. The desktop and web app add the interface's own preferences (theme, +//! colours, language) under `[interface]`; the engine alone hands that section back unapplied. +//! +//! AutoCAD keeps these in a user profile in the Windows registry (exported from Options ▸ +//! Profiles as an `.arg` file) plus a `.pgp` alias file and a template; there is no command +//! that writes them all to one text file, so the names follow AutoCAD's `noun + IMPORT/EXPORT` +//! commands (PDFIMPORT, ATTEXT/ATTOUT…). +//! +//! The file is untrusted input: it is read only up to [`MAX_CONFIG_BYTES`], parsed by the +//! `toml` crate (which limits nesting), and every entry goes through the same checks as SETVAR, +//! OPTIONS, PAGESETUP and ALIASEDIT. Import applies what it can and lists every unknown or +//! invalid entry instead of stopping; a file that is not TOML at all is refused as a whole. + +use serde_json::{Map, Value, json}; + +use super::{CommandSpec, always, bad}; +use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; + +/// The largest settings file read (a real one is a few kilobytes). +pub const MAX_CONFIG_BYTES: usize = 256 * 1024; +/// The most entries read from one file, all sections together. +const MAX_ENTRIES: usize = 20_000; +/// The most problems listed. +const MAX_ISSUES: usize = 100; +/// The file format version this build writes and reads. +pub const VERSION: i64 = 1; +/// The name the command line and the file dialogs suggest. +pub const DEFAULT_FILE: &str = "draftcraft-settings.toml"; + +/// The drawing settings the `[drawing]` section carries, in the order the file lists them. +pub const DRAWING_VARS: &[&str] = &[ + "MEASUREMENT", + "INSUNITS", + "LUNITS", + "LUPREC", + "AUNITS", + "AUPREC", + "ANGBASE", + "LTSCALE", + "CELWEIGHT", + "LWDEFAULT", + "DIMSCALE", + "TEXTSIZE", + "CANNOSCALE", +]; + +/// The page setup entries of the `[plot]` section (PAGESETUP's names). +pub const PLOT_KEYS: &[&str] = &["plotStyleTable", "displayPlotStyles", "plotTransparency", "lineweights"]; + +/// The order `[interface]` lists the app's preferences in (the OPTIONS JSON form's names). +const INTERFACE_ORDER: &[&str] = &[ + "theme", + "animations", + "interfaceLanguage", + "interfaceScale", + "modelBackground", + "paperBackground", + "selectionColor", + "snapMarkerSize", + "systemCursor", + "historyLines", + "timeSensitiveRightClick", + "saveFormat", + "saveVersion", + "SAVETIME", + "ISAVEBAK", +]; + +/// The sections a file may have. +const SECTIONS: &[&str] = &["interface", "profile", "drawing", "plot", "aliases"]; + +/// The section only the app applies (the interface's own preferences). +pub const INTERFACE: &str = "interface"; + +pub fn specs() -> Vec { + vec![ + CommandSpec::new("configexport", "Export Settings...", run_configexport) + .menu(&["Tools", "Export Settings..."]) + .params("{file?: path of the .toml file to write (omitted: the text comes back as `text`), interface?: {name: value} the app adds} → {text, settings, file?}") + .enabled(always) + .noundo() + .interactive(|_| Ok(Box::new(FileM { export: true }))), + CommandSpec::new("configimport", "Import Settings...", run_configimport) + .menu(&["Tools", "Import Settings..."]) + .params("{file?: path of a .toml settings file | text?: its contents | settings?: the same as JSON {profile?, drawing?, plot?, aliases?}, quiet?: no command-line report} → {applied: [section.name], issues: [text], interface?: the section only the app applies}") + .enabled(always) + .interactive(|_| Ok(Box::new(FileM { export: false }))), + ] +} + +// ---------- the file ---------- + +/// A TOML value as JSON (the parser already limits how deep it nests). +fn json_of(v: &toml::Value) -> Value { + match v { + toml::Value::String(s) => Value::String(s.clone()), + toml::Value::Integer(i) => json!(i), + toml::Value::Float(f) => serde_json::Number::from_f64(*f).map_or(Value::Null, Value::Number), + toml::Value::Boolean(b) => Value::Bool(*b), + toml::Value::Datetime(d) => Value::String(d.to_string()), + toml::Value::Array(a) => Value::Array(a.iter().map(json_of).collect()), + toml::Value::Table(t) => Value::Object(t.iter().map(|(k, v)| (k.clone(), json_of(v))).collect()), + } +} + +/// A JSON value as TOML; `None` for null (TOML has none: a missing entry keeps the setting). +fn toml_of(v: &Value) -> Option { + Some(match v { + Value::Null => return None, + Value::Bool(b) => toml::Value::Boolean(*b), + Value::Number(n) => match n.as_i64() { + Some(i) => toml::Value::Integer(i), + None => toml::Value::Float(n.as_f64().filter(|f| f.is_finite())?), + }, + Value::String(s) => toml::Value::String(s.clone()), + Value::Array(a) => toml::Value::Array(a.iter().filter_map(toml_of).collect()), + Value::Object(m) => toml::Value::Table(m.iter().filter_map(|(k, v)| Some((k.clone(), toml_of(v)?))).collect()), + }) +} + +/// Parse a settings file's text into its sections, as JSON. Refused when it is too large or not +/// TOML; what is inside is checked when it is applied. +pub fn parse(text: &str) -> std::result::Result, String> { + if text.len() > MAX_CONFIG_BYTES { + return Err(format!("the settings file is larger than {} KB", MAX_CONFIG_BYTES / 1024)); + } + let table: toml::Table = text.trim_start_matches('\u{feff}').parse().map_err(|e: toml::de::Error| { + let msg: String = e.message().chars().take(300).collect(); + match e.span().map(|r| line_of(text, r.start)) { + Some(line) => format!("not a settings file (line {line}: {msg})"), + None => format!("not a settings file ({msg})"), + } + })?; + match json_of(&toml::Value::Table(table)) { + Value::Object(m) => Ok(m), + _ => Err("not a settings file".into()), + } +} + +/// The 1-based line of byte offset `at`. +fn line_of(text: &str, at: usize) -> usize { + text.as_bytes().iter().take(at).filter(|b| **b == b'\n').count().saturating_add(1) +} + +/// The file's text for `settings` (sections as built by [`snapshot`], the app's `interface` included). +pub fn render(settings: &Map) -> String { + let mut out = String::from( + "# DraftCraft settings (docs/config-file.md).\n# Import it with CONFIGIMPORT (Manage ▸ Customization ▸ Import Settings); entries left out keep their current value.\n\n", + ); + out.push_str(&format!("version = {VERSION}\n")); + let notes = [ + (INTERFACE, "The interface: theme, colours, language, size (the Options dialog)."), + ("profile", "Drafting settings kept with the user profile (OPTIONS, SETVAR): snaps, grid, selection, MEASUREINIT."), + ("drawing", "Applied to the current drawing: units, linetype scale, current lineweight, annotation scale."), + ("plot", "Applied to every layout of the current drawing (PAGESETUP)."), + ("aliases", "Command aliases: alias = \"command\" (ALIASEDIT)."), + ]; + for (name, note) in notes { + let Some(Value::Object(section)) = settings.get(name) else { continue }; + if section.is_empty() { + continue; + } + // The order the Options dialog and the docs use; anything else after, as it came. + let order: &[&str] = match name { + INTERFACE => INTERFACE_ORDER, + "profile" => super::options::PROFILE_VARS, + "drawing" => DRAWING_VARS, + "plot" => PLOT_KEYS, + _ => &[], + }; + let mut ordered: Vec<(String, Value)> = order.iter().filter_map(|k| Some(((*k).to_string(), section.get(*k)?.clone()))).collect(); + ordered.extend(section.iter().filter(|(k, _)| !order.contains(&k.as_str())).map(|(k, v)| (k.clone(), v.clone()))); + let mut body = toml::Table::new(); + for (k, v) in &ordered { + if let Some(t) = toml_of(v) { + body.insert(k.clone(), t); + } + } + let mut one = toml::Table::new(); + let body = toml::Value::Table(body); + one.insert(name.to_string(), body); + out.push_str(&format!("\n# {note}\n{one}")); + } + out +} + +// ---------- export ---------- + +/// The settings as the file holds them, by section (the app adds `interface`). +pub fn snapshot(s: &Session) -> Map { + let mut m = Map::new(); + if let Value::Object(profile) = super::options::profile(s) { + m.insert("profile".into(), Value::Object(profile)); + } + if let Ok(d) = s.doc() { + let mut drawing = Map::new(); + let units = crate::units::DrawingUnits::of(d); + let h = &d.header; + for name in DRAWING_VARS { + let v = match *name { + "MEASUREMENT" => json!(h.i64("MEASUREMENT", 0)), + "INSUNITS" => json!(h.i64("INSUNITS", 0)), + "LUNITS" => json!(units.lunits), + "LUPREC" => json!(units.luprec), + "AUNITS" => json!(units.aunits), + "AUPREC" => json!(units.auprec), + "LTSCALE" => json!(h.f64("LTSCALE", 1.0)), + "CELWEIGHT" => json!(h.i64("CELWEIGHT", -1)), + "TEXTSIZE" => json!(h.f64("TEXTSIZE", 0.2)), + "CANNOSCALE" => json!(d.current_anno_scale().name), + other => match crate::sysvars::get(s, other) { + Some(v) => v, + None => continue, + }, + }; + drawing.insert((*name).to_string(), v); + } + m.insert("drawing".into(), Value::Object(drawing)); + // The current layout's page setup, else the first layout's. + let current = s.space().layout().map(str::to_string); + let mut layouts: Vec<_> = d.layouts.iter().collect(); + layouts.sort_by_key(|l| l.tab_order); + let page = current.and_then(|n| d.layout(&n)).or_else(|| layouts.first().copied()).map(|l| &l.page); + if let Some(p) = page { + m.insert( + "plot".into(), + json!({ + "plotStyleTable": if draftcraft_doc::no_plot_style_table(&p.plot_style_table) { "None" } else { p.plot_style_table.as_str() }, + "displayPlotStyles": p.show_plot_styles, + "plotTransparency": p.plot_transparency, + "lineweights": p.lineweights, + }), + ); + } + } + let aliases: Map = super::file::user_aliases().into_iter().map(|(a, id)| (a.to_ascii_uppercase(), Value::String(id))).collect(); + if !aliases.is_empty() { + m.insert("aliases".into(), Value::Object(aliases)); + } + m +} + +/// The `[interface]` section the engine can't make or apply itself, handed over by the app when +/// the commands ask for the file name at the command line (no file dialog, or FILEDIA off). +#[derive(Clone, Debug, Default)] +pub struct HostInterface { + /// The app's interface settings, set before the command starts: CONFIGEXPORT writes them. + pub current: Option>, + /// The `[interface]` section CONFIGIMPORT read, for the app to apply. + pub imported: Option, +} + +/// CONFIGEXPORT `{file?, interface?}`. +fn run_configexport(s: &mut Session, p: &Value) -> Result { + let cmd = "configexport"; + let mut settings = snapshot(s); + match p.get(INTERFACE) { + None | Some(Value::Null) => { + if let Some(ui) = s.config_interface.current.clone() { + settings.insert(INTERFACE.into(), Value::Object(ui)); + } + } + Some(Value::Object(ui)) => { + settings.insert(INTERFACE.into(), Value::Object(ui.clone())); + } + Some(_) => return Err(bad(cmd, "`interface` must be an object")), + } + let text = render(&settings); + let mut out = json!({ "text": text, "settings": settings }); + match p.get("file") { + None | Some(Value::Null) => {} + Some(Value::String(path)) => { + write_file(cmd, path.trim(), &text)?; + s.echo(format!("Settings exported to {}.", path.trim())); + out["file"] = json!(path.trim()); + } + Some(_) => return Err(bad(cmd, "`file` must be a file path")), + } + Ok(out) +} + +fn write_file(cmd: &str, path: &str, text: &str) -> Result<()> { + if path.is_empty() { + return Err(bad(cmd, "`file` is empty")); + } + #[cfg(not(target_arch = "wasm32"))] + { + crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), text.as_bytes()).map_err(|e| bad(cmd, format!("{path}: {e}"))) + } + #[cfg(target_arch = "wasm32")] + { + super::exchange::deliver_file(cmd, path, text.as_bytes(), super::file::deliver()) + } +} + +fn read_file(cmd: &str, path: &str) -> Result { + #[cfg(not(target_arch = "wasm32"))] + { + let bytes = crate::capped_read::read_capped(std::path::Path::new(path), MAX_CONFIG_BYTES).map_err(|e| bad(cmd, format!("{path}: {e}")))?; + String::from_utf8(bytes).map_err(|_| bad(cmd, format!("{path}: not UTF-8 text"))) + } + #[cfg(target_arch = "wasm32")] + { + Err(bad(cmd, format!("{path}: files can't be read in the browser; pass the file's contents as `text`"))) + } +} + +// ---------- import ---------- + +/// The sections CONFIGIMPORT's parameters name: `settings` (JSON), `text` or `file` (TOML). +pub fn load_params(cmd: &str, p: &Value) -> Result> { + if let Some(v) = p.get("settings").filter(|v| !v.is_null()) { + return match v { + Value::Object(m) => Ok(m.clone()), + _ => Err(bad(cmd, "`settings` must be an object of sections")), + }; + } + let text = match (p.get("text"), p.get("file")) { + (Some(Value::String(t)), _) => t.clone(), + (Some(v), _) if !v.is_null() => return Err(bad(cmd, "`text` must be the file's contents")), + (_, Some(Value::String(path))) => read_file(cmd, path.trim())?, + (_, Some(v)) if !v.is_null() => return Err(bad(cmd, "`file` must be a file path")), + _ => return Err(bad(cmd, "pass `file` (a .toml settings file), `text` or `settings`")), + }; + parse(&text).map_err(|e| bad(cmd, e)) +} + +/// What an import did: the entries applied (`section.name`) and the problems. +#[derive(Default, Debug)] +pub struct Report { + pub applied: Vec, + pub issues: Vec, + /// Problems not listed once [`MAX_ISSUES`] were. + pub more: usize, +} + +impl Report { + pub fn issue(&mut self, msg: impl Into) { + if self.issues.len() < MAX_ISSUES { + self.issues.push(msg.into()); + } else { + self.more = self.more.saturating_add(1); + } + } + /// The one-line summary the command line shows. + pub fn summary(&self) -> String { + let skipped = self.issues.len().saturating_add(self.more); + match skipped { + 0 => format!("{} setting(s) imported.", self.applied.len()), + n => format!("{} setting(s) imported, {n} skipped.", self.applied.len()), + } + } + pub fn to_json(&self) -> Value { + let mut issues = self.issues.clone(); + if self.more > 0 { + issues.push(format!("… and {} more", self.more)); + } + json!({ "applied": self.applied, "issues": issues, "message": self.summary() }) + } +} + +/// Apply the sections the engine owns; the `interface` section is left to the caller. +pub fn apply(s: &mut Session, settings: &Map, r: &mut Report) { + let mut budget = MAX_ENTRIES; + match settings.get("version") { + None => {} + Some(v) => match v.as_i64() { + Some(VERSION) => {} + Some(n) if n > VERSION => r.issue(format!("version: the file is from a newer DraftCraft (version {n}); what this one knows is imported")), + _ => r.issue("version: must be 1"), + }, + } + for name in settings.keys().filter(|k| *k != "version" && !SECTIONS.contains(&k.as_str())) { + r.issue(format!("[{}]: unknown section; skipped", clip(name))); + } + // Always in the same order, whatever order the file has. + for name in SECTIONS.iter().filter(|n| **n != INTERFACE) { + let Some(section) = settings.get(*name) else { continue }; + let Value::Object(entries) = section else { + r.issue(format!("{name}: must be a section ([{name}])")); + continue; + }; + let take = entries.len().min(budget); + if take < entries.len() { + r.issue(format!("[{name}]: more than {MAX_ENTRIES} entries in the file; the rest are skipped")); + } + budget -= take; + let entries = entries.iter().take(take); + match *name { + "profile" => apply_profile(s, entries, r), + "drawing" => apply_drawing(s, entries, r), + "plot" => apply_plot(s, entries, r), + "aliases" => apply_aliases(entries, r), + _ => {} + } + } +} + +/// A file's name or key cut short for a message. +fn clip(k: &str) -> String { + let mut t: String = k.chars().filter(|c| !c.is_control()).take(64).collect(); + if k.chars().count() > 64 { + t.push('…'); + } + t +} + +fn apply_profile<'a>(s: &mut Session, entries: impl Iterator, r: &mut Report) { + for (k, v) in entries { + let name = k.trim().to_ascii_uppercase(); + if !super::options::is_profile_var(&name) { + r.issue(format!("profile.{}: unknown setting; skipped", clip(k))); + continue; + } + let before = s.settings.clone(); + match crate::sysvars::set(s, &name, v) { + Ok(()) => r.applied.push(format!("profile.{name}")), + Err(_) => { + s.settings = before; + r.issue(format!("profile.{name}: invalid value {}; skipped", clip(&v.to_string()))); + } + } + } +} + +/// A finite real number greater than zero (and not absurdly large). +fn positive(v: &Value) -> Option { + v.as_f64().filter(|f| f.is_finite() && *f > 0.0 && *f < 1e12) +} + +fn apply_drawing<'a>(s: &mut Session, entries: impl Iterator, r: &mut Report) { + let entries: Vec<_> = entries.collect(); + if s.doc().is_err() { + if !entries.is_empty() { + r.issue("[drawing]: no drawing is open; skipped"); + } + return; + } + let mut changed = false; + for (k, v) in entries { + let name = k.trim().to_ascii_uppercase(); + if !DRAWING_VARS.contains(&name.as_str()) { + r.issue(format!("drawing.{}: unknown setting; skipped", clip(k))); + continue; + } + match set_drawing_var(s, &name, v) { + Ok(()) => { + r.applied.push(format!("drawing.{name}")); + changed = true; + } + Err(e) => r.issue(format!("drawing.{name}: {e}; skipped")), + } + } + if changed { + s.touch(); + } +} + +/// Set one `[drawing]` variable, checked as SETVAR and UNITS check it. +fn set_drawing_var(s: &mut Session, name: &str, v: &Value) -> std::result::Result<(), String> { + let invalid = || format!("invalid value {}", clip(&v.to_string())); + let int = |lo: i64, hi: i64| v.as_i64().filter(|i| (lo..=hi).contains(i)); + let d = s.doc_mut().map_err(|e| e.to_string())?; + match name { + "MEASUREMENT" => d.header.set_i64(name, int(0, 1).ok_or_else(invalid)?), + "LUNITS" | "LUPREC" | "AUNITS" | "AUPREC" | "INSUNITS" => { + let (_, lo, hi) = super::UNIT_RANGES.iter().find(|(k, ..)| k.eq_ignore_ascii_case(name)).copied().ok_or_else(invalid)?; + let i = int(lo, hi).ok_or_else(invalid)?; + // Dimension styles that showed the drawing's units follow them, as with UNITS. + let before = crate::units::DrawingUnits::of(d); + d.header.set_i64(name, i); + crate::units::dim_styles_follow_units(d, before); + } + "LTSCALE" | "TEXTSIZE" => d.header.set_f64(name, positive(v).ok_or_else(invalid)?), + "CELWEIGHT" => { + let i = v.as_i64().filter(|i| (-3..=-1).contains(i) || crate::sysvars::LINEWEIGHTS.contains(i)).ok_or_else(invalid)?; + d.header.set_i64(name, i); + } + // ANGBASE, LWDEFAULT, DIMSCALE and CANNOSCALE: SETVAR's own checks. + _ => crate::sysvars::set(s, name, v).map_err(|_| invalid())?, + } + Ok(()) +} + +fn apply_plot<'a>(s: &mut Session, entries: impl Iterator, r: &mut Report) { + let entries: Vec<_> = entries.collect(); + let Ok(d) = s.doc() else { + if !entries.is_empty() { + r.issue("[plot]: no drawing is open; skipped"); + } + return; + }; + // Checked once, then set on every layout. + let mut table: Option = None; + let mut flags: Vec<(&str, bool)> = Vec::new(); + for (k, v) in entries { + let Some(key) = PLOT_KEYS.iter().find(|p| p.eq_ignore_ascii_case(k.trim())).copied() else { + r.issue(format!("plot.{}: unknown setting; skipped", clip(k))); + continue; + }; + if key == "plotStyleTable" { + let name = v.as_str().map(str::trim).filter(|t| t.chars().count() <= 260 && !t.chars().any(char::is_control)); + match name { + Some(n) if draftcraft_doc::no_plot_style_table(n) => table = Some(String::new()), + Some(n) if draftcraft_doc::plot_style_table(d, n).is_some() => table = Some(n.to_string()), + Some(n) => r.issue(format!("plot.plotStyleTable: this drawing has no plot style table `{}`; skipped", clip(n))), + None => r.issue("plot.plotStyleTable: must be a table name such as \"monochrome.ctb\" or \"None\"; skipped"), + } + } else { + match v.as_bool() { + Some(b) => flags.push((key, b)), + None => r.issue(format!("plot.{key}: must be true or false; skipped")), + } + } + } + if table.is_none() && flags.is_empty() { + return; + } + let Ok(d) = s.doc_mut() else { return }; + for l in &mut d.layouts { + if let Some(t) = &table { + l.page.plot_style_table.clone_from(t); + } + for (key, b) in &flags { + match *key { + "displayPlotStyles" => l.page.show_plot_styles = *b, + "plotTransparency" => l.page.plot_transparency = *b, + "lineweights" => l.page.lineweights = *b, + _ => {} + } + } + } + if table.is_some() { + r.applied.push("plot.plotStyleTable".into()); + } + r.applied.extend(flags.iter().map(|(k, _)| format!("plot.{k}"))); + s.touch(); +} + +fn apply_aliases<'a>(entries: impl Iterator, r: &mut Report) { + for (alias, target) in entries { + let Some(t) = target.as_str() else { + r.issue(format!("aliases.{}: the command must be a name in quotes; skipped", clip(alias))); + continue; + }; + match super::file::add_user_alias(alias, t) { + Ok(_) => r.applied.push(format!("aliases.{}", clip(alias).to_ascii_uppercase())), + Err(e) => r.issue(format!("aliases.{}: {e}; skipped", clip(alias))), + } + } +} + +/// CONFIGIMPORT `{file? | text? | settings?}`. +fn run_configimport(s: &mut Session, p: &Value) -> Result { + let settings = load_params("configimport", p)?; + let mut r = Report::default(); + apply(s, &settings, &mut r); + let mut out = r.to_json(); + if let Some(ui) = settings.get(INTERFACE) { + // Only the app applies it; it comes back for the app (or the caller) to use. + out[INTERFACE] = ui.clone(); + } + if !super::bool_or(p, "quiet", false) { + s.echo(format!("CONFIGIMPORT: {}", r.summary())); + for i in &r.issues { + s.echo(format!(" {i}")); + } + } + Ok(out) +} + +// ---------- at the command line ---------- + +/// CONFIGEXPORT and CONFIGIMPORT typed where there is no file dialog: the file name. +struct FileM { + export: bool, +} + +/// A typed file name without the quotes around it. +fn unquoted(t: &str) -> &str { + let t = t.trim(); + t.strip_prefix('"').and_then(|u| u.strip_suffix('"')).unwrap_or(t) +} + +impl Interactive for FileM { + fn name(&self) -> &'static str { + if self.export { "CONFIGEXPORT" } else { "CONFIGIMPORT" } + } + fn prompt(&self, _s: &Session) -> Prompt { + let q = if self.export { "Enter settings file name to write" } else { "Enter settings file name to read" }; + Prompt::new(q, Accept::TEXT).default(DEFAULT_FILE) + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let file = match &i { + Input::Text(t) if !unquoted(t).is_empty() => unquoted(t).to_string(), + Input::Text(_) | Input::Enter => DEFAULT_FILE.to_string(), + _ => return Ok(Step::Continue), + }; + let p = json!({ "file": file }); + if self.export { + run_configexport(s, &p)?; + } else { + let r = run_configimport(s, &p)?; + // The app applies it when the command ends ([`HostInterface::imported`]). + s.config_interface.imported = r.get(INTERFACE).cloned(); + } + Ok(Step::Done) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn toml_and_json_carry_the_same_values() { + let m = parse("version = 1\n[profile]\nPICKBOX = 5\nSNAPUNIT = [0.5, 2.0]\n[aliases]\nZZ = \"line\"\n").unwrap(); + assert_eq!(m["profile"]["PICKBOX"], json!(5)); + assert_eq!(m["profile"]["SNAPUNIT"], json!([0.5, 2.0])); + let again = parse(&render(&m)).unwrap(); + assert_eq!(again["profile"], m["profile"]); + assert_eq!(again["aliases"], m["aliases"]); + // Null has no TOML form: it is left out (a missing entry keeps the setting). + assert_eq!(toml_of(&json!({"a": null, "b": 1})), toml_of(&json!({"b": 1}))); + } + + #[test] + fn what_is_not_toml_is_refused_with_its_line() { + let e = parse("[profile]\nPICKBOX = = 5\n").unwrap_err(); + assert!(e.contains("line 2"), "{e}"); + assert!(parse("\u{0}\u{1}\u{2}garbage").is_err()); + assert!(parse(&"x".repeat(MAX_CONFIG_BYTES + 1)).is_err()); + // Nesting deeper than the parser allows is an error, not a stack overflow. + let deep = format!("a = {}1{}", "[".repeat(100_000), "]".repeat(100_000)); + assert!(parse(&deep).is_err()); + let deep_tables = format!("a = {}1{}", "{b = ".repeat(50_000), "}".repeat(50_000)); + assert!(parse(&deep_tables).is_err()); + } +} diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index e679d0b0..006db5d2 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -109,6 +109,7 @@ pub(super) fn deliver_file(cmd: &str, path: &str, bytes: &[u8], hook: Option "image/png", "pdf" => "application/pdf", "txt" => "text/plain; charset=utf-8", + "toml" => "application/toml", _ => "application/octet-stream", }; let deliver = hook.ok_or_else(|| bad(cmd, "files can't be written in this build; omit `path` to get the file as base64 `data`"))?; diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 677ce13a..b21ca845 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -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_ALIASES, alias_name, command_id}; -pub(crate) use pgp::{specs as alias_specs, user_alias}; +pub(crate) use pgp::{add_user_alias, specs as alias_specs, user_alias, user_aliases}; 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 diff --git a/crates/engine/src/cmd/file/pgp.rs b/crates/engine/src/cmd/file/pgp.rs index 6083828e..18287cd2 100644 --- a/crates/engine/src/cmd/file/pgp.rs +++ b/crates/engine/src/cmd/file/pgp.rs @@ -43,6 +43,24 @@ pub(crate) fn user_alias(name: &str) -> Option { store().map.get(name).cloned() } +/// The user aliases now (lower-case alias → command id), for CONFIGEXPORT. +pub(crate) fn user_aliases() -> BTreeMap { + store().map.clone() +} + +/// Add or replace one user alias (CONFIGIMPORT): `alias` must be one ALIASEDIT takes and +/// `target` name a command. Returns the command id. +pub(crate) fn add_user_alias(alias: &str, target: &str) -> std::result::Result { + let name = alias_name(alias)?; + let id = command_id(target).ok_or_else(|| format!("unknown command {}", target.trim()))?; + let mut st = store(); + if !st.map.contains_key(&name) && st.map.len() >= MAX_ALIASES { + return Err(format!("more than {MAX_ALIASES} aliases")); + } + st.map.insert(name, id.clone()); + Ok(id) +} + /// The command id `target` names (`*LINE`, `_.line`, `-LAYER`…), if there is such a command. pub fn command_id(target: &str) -> Option { let t = target.trim().trim_start_matches('*').trim().trim_start_matches(['_', '.']).to_ascii_lowercase(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 7f57c1be..06a2f3e1 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -163,6 +163,8 @@ pub struct Session { /// ([`Session::input_object`]): a pick at exactly that point picks that object /// ([`Session::pick_object`]). pick_hint: Option<(Handle, Vec2)>, + /// The app's side of the settings file (CONFIGEXPORT, CONFIGIMPORT at the command line). + pub config_interface: cmd::config::HostInterface, } impl Default for Session { @@ -220,6 +222,7 @@ impl Session { lisp_last: None, hatch_picks: None, pick_hint: None, + config_interface: cmd::config::HostInterface::default(), } } diff --git a/crates/engine/src/sysvars.rs b/crates/engine/src/sysvars.rs index eab25262..b1669098 100644 --- a/crates/engine/src/sysvars.rs +++ b/crates/engine/src/sysvars.rs @@ -6,6 +6,8 @@ use crate::{EngineError, Result, Session}; mod table; +pub(crate) use table::LINEWEIGHTS; + const SESSION_VARS: &[&str] = &[ "AUDITCTL", "ATTREQ", diff --git a/crates/engine/src/sysvars/table.rs b/crates/engine/src/sysvars/table.rs index f0a132a9..db0a07e1 100644 --- a/crates/engine/src/sysvars/table.rs +++ b/crates/engine/src/sysvars/table.rs @@ -79,7 +79,7 @@ const HEADER: &[(&str, Kind, Def)] = &[ ]; /// The standard lineweights in hundredths of a millimetre. -const LINEWEIGHTS: [i64; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, 60, 70, 80, 90, 100, 106, 120, 140, 158, 200, 211]; +pub(crate) const LINEWEIGHTS: [i64; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, 60, 70, 80, 90, 100, 106, 120, 140, 158, 200, 211]; /// On/off session settings: name, read, write. type Toggle = (&'static str, fn(&Settings) -> bool, fn(&mut Settings, bool)); diff --git a/crates/engine/tests/config_file.rs b/crates/engine/tests/config_file.rs new file mode 100644 index 00000000..844e217a --- /dev/null +++ b/crates/engine/tests/config_file.rs @@ -0,0 +1,252 @@ +//! The portable settings file: CONFIGEXPORT writes the profile, drawing, plot and alias settings +//! to one TOML file and CONFIGIMPORT reads them back, applying what it can and listing the rest. +//! User aliases are process-wide, so the tests that touch them run one at a time. + +use std::sync::Mutex; + +use draftcraft_engine::Session; +use draftcraft_engine::cmd::config; +use draftcraft_engine::cmd::resolve_alias; +use serde_json::{Value, json}; + +#[path = "support/temp_dir.rs"] +mod temp_dir; + +use temp_dir::TempDir; + +static ONE_AT_A_TIME: Mutex<()> = Mutex::new(()); + +fn snapshot(s: &Session) -> Value { + Value::Object(config::snapshot(s)) +} + +fn issues(r: &Value) -> Vec { + r["issues"].as_array().map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default() +} + +/// A session whose settings are all away from the defaults. +fn customised() -> Session { + let mut s = Session::new(); + s.execute("options", &json!({ "PICKBOX": 7, "OSMODE": 15, "GRIDUNIT": [10.0, 10.0], "SNAPUNIT": [5.0, 5.0], "LWDISPLAY": 1, "MEASUREINIT": 1 })) + .unwrap(); + for (name, v) in [ + ("LUNITS", json!(4)), + ("LUPREC", json!(2)), + ("AUNITS", json!(1)), + ("INSUNITS", json!(4)), + ("LTSCALE", json!(25.0)), + ("LWDEFAULT", json!(35)), + ("DIMSCALE", json!(50.0)), + ("TEXTSIZE", json!(2.5)), + ] { + s.execute("setvar", &json!({ "name": name, "value": v })).unwrap(); + } + s.execute("lweight", &json!({ "lineweight": 0.5 })).unwrap(); + s.execute("aliasedit", &json!({ "set": { "zzcfgx": "circle" } })).unwrap(); + s +} + +#[test] +fn export_then_import_gives_the_same_settings() { + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut a = customised(); + let dir = TempDir::new("config"); + let file = dir.path_str("mine.toml"); + let r = a.execute("configexport", &json!({ "file": file })).unwrap(); + let text = std::fs::read_to_string(&file).unwrap(); + assert_eq!(r["text"].as_str(), Some(text.as_str())); + assert!(text.contains("[profile]") && text.contains("PICKBOX = 7") && text.contains("[drawing]") && text.contains("LUNITS = 4"), "{text}"); + assert!(text.contains("[aliases]") && text.contains("ZZCFGX = \"circle\""), "{text}"); + + // Forget the alias, then read the file into a session with every default. + a.execute("aliasedit", &json!({ "remove": ["zzcfgx"] })).unwrap(); + assert_eq!(resolve_alias("zzcfgx"), "zzcfgx"); + let mut b = Session::new(); + assert_ne!(snapshot(&b)["profile"], snapshot(&a)["profile"]); + let r = b.execute("configimport", &json!({ "file": file })).unwrap(); + assert_eq!(issues(&r), Vec::::new()); + assert_eq!(resolve_alias("zzcfgx"), "circle"); + assert_eq!(snapshot(&b), snapshot(&a)); + assert_eq!(b.settings.pickbox, 7.0); + // The drawing change is one undo step. + b.execute("u", &json!({})).unwrap(); + assert_eq!(snapshot(&b)["drawing"]["LUNITS"], json!(2)); + a.execute("aliasedit", &json!({ "remove": ["zzcfgx"] })).unwrap(); +} + +#[test] +fn the_plot_settings_go_to_every_layout() { + let mut s = Session::new(); + let r = s + .execute("configimport", &json!({ "text": "[plot]\nplotStyleTable = \"monochrome.ctb\"\nlineweights = false\ndisplayPlotStyles = true\n" })) + .unwrap(); + assert_eq!(issues(&r), Vec::::new()); + let d = s.doc().unwrap(); + assert!(!d.layouts.is_empty()); + for l in &d.layouts { + assert_eq!(l.page.plot_style_table, "monochrome.ctb"); + assert!(!l.page.lineweights && l.page.show_plot_styles); + } + assert_eq!(snapshot(&s)["plot"]["plotStyleTable"], json!("monochrome.ctb")); +} + +#[test] +fn unknown_and_invalid_entries_are_reported_and_the_rest_applied() { + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = Session::new(); + let before = snapshot(&s); + let text = r#" +version = 7 +[profile] +PICKBOX = 9 +OSMODE = "lots" +NOSUCHVAR = 1 +SNAPUNIT = [-1, 0] +[drawing] +LUNITS = 99 +LTSCALE = nan +CELWEIGHT = 17 +INSUNITS = 6 +TEXTSIZE = -2 +CANNOSCALE = "no such scale" +[plot] +plotStyleTable = "nowhere.ctb" +lineweights = "yes" +[aliases] +zzcfgok = "line" +"two words" = "line" +zzcfgbad = "nosuchcommand" +zzcfgnum = 5 +LINE = "circle" +[macros] +a = 1 +"#; + let r = s.execute("configimport", &json!({ "text": text })).unwrap(); + let applied: Vec<&str> = r["applied"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(applied, ["profile.PICKBOX", "drawing.INSUNITS", "aliases.ZZCFGOK"]); + let issues = issues(&r); + for needle in [ + "version", + "profile.OSMODE", + "profile.NOSUCHVAR", + "profile.SNAPUNIT", + "drawing.LUNITS", + "drawing.LTSCALE", + "drawing.CELWEIGHT", + "drawing.TEXTSIZE", + "drawing.CANNOSCALE", + "plot.plotStyleTable", + "plot.lineweights", + "aliases.two words", + "aliases.zzcfgbad", + "aliases.zzcfgnum", + "aliases.LINE", + "[macros]", + ] { + assert!(issues.iter().any(|i| i.starts_with(needle)), "no issue for {needle}: {issues:#?}"); + } + assert_eq!(issues.len(), 16, "{issues:#?}"); + let after = snapshot(&s); + assert_eq!(after["profile"]["PICKBOX"], json!(9.0)); + assert_eq!(after["profile"]["OSMODE"], before["profile"]["OSMODE"]); + assert_eq!(after["profile"]["SNAPUNIT"], before["profile"]["SNAPUNIT"]); + assert_eq!(after["drawing"]["LUNITS"], before["drawing"]["LUNITS"]); + assert_eq!(after["drawing"]["LTSCALE"], before["drawing"]["LTSCALE"]); + assert_eq!(after["drawing"]["INSUNITS"], json!(6)); + assert_eq!(resolve_alias("zzcfgok"), "line"); + assert_eq!(resolve_alias("line"), "line"); + s.execute("aliasedit", &json!({ "remove": ["zzcfgok"] })).unwrap(); +} + +#[test] +fn a_hostile_file_is_refused_cleanly() { + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let mut s = Session::new(); + let before = snapshot(&s); + let dir = TempDir::new("config-hostile"); + let deep = format!("[profile]\nPICKBOX = {}1{}\n", "[".repeat(100_000), "]".repeat(100_000)); + let cases: Vec<(&str, Value)> = vec![ + ("not toml", json!({ "text": "PICKBOX: 5\n" })), + ("too deep", json!({ "text": deep })), + ("too large", json!({ "text": format!("# {}\n", "x".repeat(config::MAX_CONFIG_BYTES)) })), + ("binary", json!({ "file": dir.file("bin.toml", [0u8, 159, 146, 150, 255, 0, 1]) })), + ("too large file", json!({ "file": dir.file("big.toml", vec![b'#'; config::MAX_CONFIG_BYTES + 1]) })), + ("missing file", json!({ "file": dir.path_str("nope.toml") })), + ("a folder", json!({ "file": dir.path_str("") })), + ("nothing", json!({})), + ("wrong types", json!({ "text": 5 })), + ("settings not an object", json!({ "settings": [1, 2] })), + ]; + for (what, p) in cases { + assert!(s.execute("configimport", &p).is_err(), "{what} was accepted"); + } + // Sections of the wrong shape, absurd numbers and many keys: skipped, never applied. + let mut many = String::from("[profile]\n"); + for i in 0..25_000 { + many.push_str(&format!("a{i}=1\n")); + } + assert!(many.len() < config::MAX_CONFIG_BYTES); + for text in ["profile = 5\ndrawing = [1]\naliases = \"x\"", many.as_str()] { + let r = s.execute("configimport", &json!({ "text": text })).unwrap(); + assert!(!issues(&r).is_empty()); + } + s.execute("configimport", &json!({ "text": "[profile]\nPICKBOX = 1e308\nMAXARRAY = -9223372036854775808\n" })).unwrap(); + let mut after = snapshot(&s); + // PICKBOX = 1e308 is clamped by SETVAR as when typed; everything else is as it was. + after["profile"]["PICKBOX"] = before["profile"]["PICKBOX"].clone(); + after["profile"]["MAXARRAY"] = before["profile"]["MAXARRAY"].clone(); + assert_eq!(after, before); +} + +#[test] +fn without_a_drawing_the_drawing_sections_are_skipped() { + let mut s = Session::new(); + s.execute("closeall", &json!({})).unwrap(); + assert!(s.docs.is_empty()); + let r = s.execute("configexport", &json!({})).unwrap(); + assert!(r["settings"].get("drawing").is_none()); + let r = s.execute("configimport", &json!({ "text": "[profile]\nPICKBOX = 4\n[drawing]\nLUNITS = 2\n[plot]\nlineweights = true\n" })).unwrap(); + assert_eq!(issues(&r).len(), 2, "{r}"); + assert_eq!(s.settings.pickbox, 4.0); +} + +#[test] +fn the_interface_section_comes_back_for_the_app() { + let mut s = Session::new(); + let r = s.execute("configimport", &json!({ "text": "[interface]\ntheme = \"dark\"\n" })).unwrap(); + assert_eq!(r["interface"], json!({ "theme": "dark" })); + assert_eq!(issues(&r), Vec::::new()); + let r = s.execute("configexport", &json!({ "interface": { "theme": "dark", "modelBackground": null } })).unwrap(); + let text = r["text"].as_str().unwrap(); + assert!(text.contains("[interface]\ntheme = \"dark\"\n"), "{text}"); + assert!(!text.contains("modelBackground")); + assert!(s.execute("configexport", &json!({ "interface": "dark" })).is_err()); +} + +#[test] +fn typed_at_the_command_line_it_asks_for_the_file_name() { + let mut s = Session::new(); + let dir = TempDir::new("config-typed"); + let file = dir.path_str("typed.toml"); + s.cmdline("CONFIGEXPORT").unwrap(); + s.cmdline(&format!("\"{file}\"")).unwrap(); + assert!(s.running.is_none()); + assert!(std::fs::read_to_string(&file).unwrap().contains("[profile]")); + s.cmdline("CONFIGIMPORT").unwrap(); + s.cmdline(&file).unwrap(); + assert!(s.running.is_none()); +} + +#[test] +fn the_example_in_the_docs_imports_cleanly() { + let _one = ONE_AT_A_TIME.lock().unwrap_or_else(|e| e.into_inner()); + let doc = include_str!("../../../docs/config-file.md"); + let example = doc.split("```toml\n").nth(1).and_then(|rest| rest.split("```").next()).unwrap(); + let mut s = Session::new(); + let r = s.execute("configimport", &json!({ "text": example })).unwrap(); + assert_eq!(issues(&r), Vec::::new()); + assert_eq!(r["interface"]["theme"], json!("dark")); + assert_eq!(snapshot(&s)["drawing"]["CANNOSCALE"], json!("1:50")); + assert_eq!(resolve_alias("rr"), "rectang"); + s.execute("aliasedit", &json!({ "remove": ["c", "rr"] })).unwrap(); +} diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 030d4aad..566ae69b 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1707,6 +1707,12 @@ menu Workspaces Aree di lavoro Visualize Visualizza Primitive Primitive Views Viste +# Portable settings file (CONFIGIMPORT, CONFIGEXPORT). + Import Settings Importa impostazioni + Export Settings Esporta impostazioni + Import Settings... Importa impostazioni... + Export Settings... Esporta impostazioni... + DraftCraft settings (TOML) Impostazioni DraftCraft (TOML) # 3D modify (3DMOVE, 3DROTATE, 3DSCALE, MIRROR3D, 3DALIGN, 3DARRAY). 3D Move Spostamento 3D 3D Rotate Rotazione 3D diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index d7579b72..a9d84416 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1680,6 +1680,12 @@ menu CAD Standards CAD 标准 Visualize 可视化 Primitive 图元 Views 视图 +# Portable settings file (CONFIGIMPORT, CONFIGEXPORT). + Import Settings 导入设置 + Export Settings 导出设置 + Import Settings... 导入设置... + Export Settings... 导出设置... + DraftCraft settings (TOML) DraftCraft 设置 (TOML) # 3D modify (3DMOVE, 3DROTATE, 3DSCALE, MIRROR3D, 3DALIGN, 3DARRAY). 3D Move 三维移动 3D Rotate 三维旋转 diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 2bf24c01..da238a09 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -185,6 +185,9 @@ pub enum Icon { GeoLocation, PointCloud, Customize, + /// CONFIGIMPORT and CONFIGEXPORT: the portable settings file. + SettingsImport, + SettingsExport, // 3D solids (docs/solids.md). Box3d, Wedge, @@ -1657,6 +1660,23 @@ fn paint_manager_tools(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32) { pen.p.line_segment([pen.at(11.0, 20.0), pen.at(18.0, 13.0)], Stroke::new(pen.w * 2.4, a)); pen.c(19.0, 12.0, 2.6, a); } + SettingsImport | SettingsExport => { + // A sheet of settings (three sliders), with an arrow into it (import) or out of it + // (export). + pen.rect(3.0, 3.0, 13.0, 18.0, b); + for (y, knob) in [(7.0, 6.5), (11.0, 12.0), (15.0, 8.5)] { + pen.l(5.5, y, 13.5, y); + pen.fill_c(knob, y, 1.5, b); + } + let thick = Stroke::new(pen.w * 2.0, a); + if icon == SettingsImport { + pen.p.line_segment([pen.at(23.0, 19.0), pen.at(16.0, 19.0)], thick); + pen.big_arrow(10.0, 19.0, -1.0, 0.0, 6.0, 4.0, a); + } else { + pen.p.line_segment([pen.at(10.0, 19.0), pen.at(17.0, 19.0)], thick); + pen.big_arrow(23.0, 19.0, 1.0, 0.0, 6.0, 4.0, a); + } + } _ => {} } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 173ade0f..156bc338 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -754,6 +754,7 @@ impl CadApp { self.gpu_fault_tick(ctx); managers::plot_window_resume(self, ctx); hatchdlg::resume(self); + options::config_imported(self); // What follows is frame work, once per layout frame or hidden tick. if ctx.current_pass_index() != 0 { return; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 1717e520..431a3973 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -167,6 +167,9 @@ fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value) -> Option Result { if reset { reset_ui(app); } + apply_ui(app, ui); + Ok(report(app)) +} + +/// Make the interface preference changes `ui` holds (already checked by [`parse_ui`]). +fn apply_ui(app: &mut CadApp, ui: UiChanges) { if let Some(t) = ui.theme { app.ui.theme = t; } @@ -310,7 +316,146 @@ fn run_json(app: &mut CadApp, params: &Value) -> Result { if let Some(b) = ui.time_sensitive_right_click { app.options.time_sensitive_right_click = b; } - Ok(report(app)) +} + +// ---------- the portable settings file ---------- + +/// The colour preferences, whose default (`null` in the JSON form) the settings file writes as +/// `"default"` (TOML has no null). +const COLOR_KEYS: [&str; 3] = ["modelBackground", "paperBackground", "selectionColor"]; + +/// The most `[interface]` entries one import reads. +const MAX_INTERFACE_ENTRIES: usize = 256; + +/// The interface preferences as the settings file's `[interface]` section: the OPTIONS JSON +/// form's, without SAVEFILEPATH (a folder on this computer only). +pub fn config_interface(app: &CadApp) -> Map { + let mut m = ui_json(app); + m.remove("SAVEFILEPATH"); + for k in COLOR_KEYS { + if m.get(k).is_some_and(Value::is_null) { + m.insert(k.into(), json!("default")); + } + } + m +} + +/// Apply a settings file's `[interface]` section: each entry the OPTIONS JSON form takes is +/// applied, every other one is reported in `r`. +pub fn apply_config_interface(app: &mut CadApp, section: &Value, r: &mut draftcraft_engine::cmd::config::Report) { + let Some(m) = section.as_object() else { + r.issue("interface: must be a section ([interface]); skipped"); + return; + }; + let mut c = UiChanges::default(); + for (k, v) in m.iter().take(MAX_INTERFACE_ENTRIES) { + let key: String = k.chars().filter(|c| !c.is_control()).take(64).collect(); + // A folder on one computer: a file from somewhere else never moves the autosaves. + if k.eq_ignore_ascii_case("SAVEFILEPATH") { + r.issue(format!("interface.{key}: a folder on one computer is not read from a settings file; skipped")); + continue; + } + let default_color = COLOR_KEYS.contains(&k.as_str()) && v.as_str().is_some_and(|t| t.trim().eq_ignore_ascii_case("default")); + let v = if default_color { Value::Null } else { v.clone() }; + match parse_ui(k, &v, &mut c) { + Ok(true) => r.applied.push(format!("interface.{key}")), + Ok(false) => r.issue(format!("interface.{key}: unknown setting; skipped")), + Err(e) => r.issue(format!("interface.{key}: {e}; skipped")), + } + } + if m.len() > MAX_INTERFACE_ENTRIES { + r.issue(format!("[interface]: more than {MAX_INTERFACE_ENTRIES} entries; the rest are skipped")); + } + apply_ui(app, c); +} + +/// CONFIGEXPORT and CONFIGIMPORT in the app: from the ribbon, a menu or typed (no parameters) +/// the file dialog asks for the file, and the `[interface]` section is written and applied here. +/// JSON calls never open a dialog. `None` where the engine's command should run as it is: +/// with FILEDIA off or no file dialog, it asks for the file name at the command line. +pub fn config_route(app: &mut CadApp, id: &str, params: &Value) -> Option> { + use draftcraft_engine::cmd::config; + if !matches!(id, "configexport" | "configimport") { + return None; + } + let dialog = params.is_null() && app.session.settings.filedia; + // Asked at the command line instead (FILEDIA off, no dialog): the engine writes the + // interface settings handed to it now, and leaves what it read for [`config_imported`]. + app.session.config_interface.current = Some(config_interface(app)); + if id == "configexport" { + let mut p = if params.is_null() { + if app.services.no_file_system { + // The browser downloads the file. + json!({ "file": config::DEFAULT_FILE }) + } else { + let pick = app.services.pick_save.as_ref().filter(|_| dialog)?; + let Some(path) = pick(config::DEFAULT_FILE) else { return Some(Ok(Value::Null)) }; + json!({ "file": path }) + } + } else { + params.clone() + }; + if let Some(o) = p.as_object_mut() { + o.insert(config::INTERFACE.into(), Value::Object(config_interface(app))); + } + return Some(app.session.execute("configexport", &p).map_err(|e| e.to_string())); + } + let p = if params.is_null() { + if app.services.no_file_system { + let hint = "CONFIGIMPORT: there is no file system here; run it with the file's contents, e.g. configimport {\"text\": \"[profile]\\nPICKBOX = 5\"}"; + app.session.echo(hint.to_string()); + app.set_status(hint); + return Some(Ok(Value::Null)); + } + let pick = app.services.pick_file.as_ref().filter(|_| dialog)?; + let Some(path) = pick("DraftCraft settings (TOML)", &["toml"]) else { return Some(Ok(Value::Null)) }; + json!({ "file": path }) + } else { + params.clone() + }; + Some(config_import(app, &p)) +} + +/// Apply the `[interface]` section CONFIGIMPORT read at the command line (once per frame). +pub fn config_imported(app: &mut CadApp) { + let Some(section) = app.session.config_interface.imported.take() else { return }; + let mut r = draftcraft_engine::cmd::config::Report::default(); + apply_config_interface(app, §ion, &mut r); + if !r.applied.is_empty() || !r.issues.is_empty() { + app.session.echo(format!("CONFIGIMPORT: {} interface setting(s) imported.", r.applied.len())); + for i in &r.issues { + app.session.echo(format!(" {i}")); + } + } +} + +/// Read a settings file, apply its `[interface]` section here and the rest through the engine's +/// CONFIGIMPORT (one undo step for the drawing), and report both together. +fn config_import(app: &mut CadApp, p: &Value) -> Result { + use draftcraft_engine::cmd::config; + let mut settings = config::load_params("configimport", p).map_err(|e| e.to_string())?; + let interface = settings.remove(config::INTERFACE); + let mut r = config::Report::default(); + if let Some(section) = &interface { + apply_config_interface(app, section, &mut r); + } + let engine = app.session.execute("configimport", &json!({ "settings": settings, "quiet": true })).map_err(|e| e.to_string())?; + let strings = |k: &str| { + engine + .get(k) + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect::>()) + .unwrap_or_default() + }; + r.applied.extend(strings("applied")); + for issue in strings("issues") { + r.issue(issue); + } + app.session.echo(format!("CONFIGIMPORT: {}", r.summary())); + for i in &r.issues { + app.session.echo(format!(" {i}")); + } + Ok(r.to_json()) } /// The interface preferences back to their defaults (the interface language stays). @@ -401,4 +546,38 @@ mod tests { assert_eq!(parse_hex(bad), None, "{bad}"); } } + + fn app() -> CadApp { + CadApp::new(draftcraft_engine::Session::new(), crate::Services::default()) + } + + /// The settings file carries the interface preferences too: export from one app, import into + /// another, and both have the same; the colour defaults travel as "default". + #[test] + fn the_settings_file_carries_the_interface_both_ways() { + let mut a = app(); + a.run("options", serde_json::json!({ "theme": "light", "modelBackground": "#102030", "interfaceScale": 1.25, "PICKBOX": 6 })).unwrap(); + let r = a.run("configexport", serde_json::json!({})).unwrap(); + let text = r["text"].as_str().unwrap_or_default().to_string(); + assert!(text.contains("theme = \"light\"") && text.contains("paperBackground = \"default\""), "{text}"); + assert!(!text.contains("SAVEFILEPATH"), "a folder on this computer only"); + let mut b = app(); + let r = b.run("configimport", serde_json::json!({ "text": text })).unwrap(); + assert_eq!(r["issues"], serde_json::json!([]), "{r}"); + assert_eq!(config_interface(&b), config_interface(&a)); + assert_eq!(b.ui.theme, ThemePref::Light); + assert_eq!(b.options.model_background, Some(Color32::from_rgb(0x10, 0x20, 0x30))); + assert_eq!(b.session.settings.pickbox, 6.0); + // Bad interface entries are listed and change nothing. + let r = b + .run( + "configimport", + serde_json::json!({ "text": "[interface]\ntheme = \"sepia\"\ninterfaceScale = 99\nnope = 1\nSAVEFILEPATH = \"/tmp\"\nmodelBackground = \"default\"\n" }), + ) + .unwrap(); + assert_eq!(r["applied"], serde_json::json!(["interface.modelBackground"])); + assert_eq!(r["issues"].as_array().map(Vec::len), Some(4), "{r}"); + assert_eq!(b.ui.theme, ThemePref::Light); + assert_eq!(b.options.model_background, None); + } } diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 306f46fe..0bfd04f7 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -784,6 +784,7 @@ const TABS: &[RibbonTab] = &[ b(Icon::Menu, "ui.dialog.commands", "Commands"), b(Icon::Workspace, "workspace", "Workspaces"), ]), + Small(&[b(Icon::SettingsImport, "configimport", "Import Settings"), b(Icon::SettingsExport, "configexport", "Export Settings")]), ], }, RibbonPanel { title: "Applications", cols: &[Large(b(Icon::Open, "appload", "Load Application"))] }, diff --git a/docs/config-file.md b/docs/config-file.md new file mode 100644 index 00000000..312d821b --- /dev/null +++ b/docs/config-file.md @@ -0,0 +1,95 @@ +# The settings file + +One text file holds the settings you set up once and want everywhere: on another computer, after a +reinstall, or for everyone in an office. It is plain [TOML](https://toml.io), so you can read it, +edit it, keep it in version control and send it to a colleague. + +| Command | Ribbon | What it does | +|---|---|---| +| CONFIGEXPORT | Manage › Customization › Export Settings | Writes your settings to a `.toml` file. | +| CONFIGIMPORT | Manage › Customization › Import Settings | Reads a `.toml` file and applies what it holds. | + +Both are also in Tools › Export Settings… and Tools › Import Settings…. From the ribbon, a menu or +typed, they open a file dialog; with FILEDIA set to 0 (or where there is no file dialog) they ask +for the file name at the command line instead. In the browser, CONFIGEXPORT downloads the file. + +AutoCAD keeps these settings in several places (the user profile in the registry, a `.pgp` alias +file, a template) and has no single command that writes them all to one file, so DraftCraft's names +follow its `noun + IMPORT/EXPORT` commands such as PDFIMPORT. + +## What is in it + +| Section | Holds | Applies to | +|---|---|---| +| `[interface]` | The app's own preferences: theme, colours, interface language and size, autosave | the app | +| `[profile]` | The Options profile: object snaps, polar tracking, grid and snap spacing, selection, grips, MEASUREINIT | the app, kept across restarts | +| `[drawing]` | MEASUREMENT, INSUNITS, LUNITS, LUPREC, AUNITS, AUPREC, ANGBASE, LTSCALE, CELWEIGHT, LWDEFAULT, DIMSCALE, TEXTSIZE, CANNOSCALE | the current drawing (one undo step) | +| `[plot]` | `plotStyleTable`, `displayPlotStyles`, `plotTransparency`, `lineweights` | every layout of the current drawing | +| `[aliases]` | Command aliases, `ALIAS = "command"` | this session, as ALIASEDIT's | + +The names and values are the ones SETVAR, OPTIONS, PAGESETUP and ALIASEDIT take: a value the +file holds is checked exactly as if it were typed there. MEASUREINIT in `[profile]` makes new +drawings metric or imperial; the `[drawing]` section changes the drawing open now. To start every +new drawing with the same drawing settings, save a drawing as a template and set QNEWTEMPLATE. + +## Importing + +Every section and every entry is optional: what the file leaves out keeps its current value, so a +file can hold just the few settings you care about. Import applies every entry it can and lists +the rest at the command line with the reason (an unknown name, a value out of range, a plot style +table the drawing doesn't have). A file that is not TOML, is not UTF-8 text or is larger than +256 KB is refused as a whole and nothing changes. + +## Example + +```toml +version = 1 + +[interface] +theme = "dark" +modelBackground = "#1e2229" # or "default" +interfaceScale = 1.0 + +[profile] +OSMODE = 4135 # endpoint, midpoint, center, intersection, extension +GRIDUNIT = [10.0, 10.0] +SNAPUNIT = [5.0, 5.0] +PICKBOX = 5 +MEASUREINIT = 1 # new drawings are metric + +[drawing] +MEASUREMENT = 1 +INSUNITS = 4 # millimetres +LUNITS = 2 # decimal +LUPREC = 2 +LTSCALE = 10.0 +CELWEIGHT = -1 # ByLayer +LWDEFAULT = 25 # 0.25 mm +DIMSCALE = 1.0 +TEXTSIZE = 2.5 +CANNOSCALE = "1:50" + +[plot] +plotStyleTable = "monochrome.ctb" +lineweights = true + +[aliases] +C = "circle" +RR = "rectang" +``` + +## From scripts, agents and the CLI + +The JSON forms never open a dialog: + +```text +configexport {"file": "/path/settings.toml"} → {text, settings, file} +configexport {} → {text, settings} +configimport {"file": "/path/settings.toml"} → {applied, issues, message} +configimport {"text": "[profile]\nPICKBOX = 5\n"} +configimport {"settings": {"profile": {"PICKBOX": 5}}} +``` + +`applied` lists the entries applied as `section.NAME`, `issues` the ones skipped and why. Without +the app (the CLI, the MCP server on its own) the `[interface]` section is not applied; CONFIGIMPORT +returns it as `interface` instead. diff --git a/docs/customization.md b/docs/customization.md index ce6fe753..ea368c9a 100644 --- a/docs/customization.md +++ b/docs/customization.md @@ -9,6 +9,7 @@ and what is not there yet. | Startup LISP (`acad.lsp`, `acaddoc.lsp`) | Loaded from the support folder at startup and for each drawing. | [autolisp.md](autolisp.md#at-startup) | | Scripts (`.scr`) | SCRIPT (Tools > Run Script...), `draftcraft-cli run --script-file`, and script text over MCP and the control channel. | below | | Command aliases (`.pgp`) | ALIASEDIT `{file}` loads an alias file for the session; REINIT reads it again. | below | +| A profile (`.arg`) or a setup you repeat by hand | One TOML settings file: CONFIGEXPORT writes the interface, Options, drawing, plot and alias settings, CONFIGIMPORT reads them back. | [config-file.md](config-file.md) | | Compiled plug-ins (C++, .NET) | Not supported. A plug-in API, for plug-ins written in Rust and compiled to WebAssembly, may come later. | — | | Programs that drive the CAD program from outside | The JSON control channel, the MCP server and `draftcraft-cli`. Any language that can open a TCP socket or start a process can use them. | below |