diff --git a/Cargo.lock b/Cargo.lock index e5f4efb6..67af9182 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1322,6 +1322,7 @@ dependencies = [ "draftcraft-geom", "draftcraft-io", "draftcraft-render", + "encoding_rs", "libc", "log", "rstar", diff --git a/apps/draftcraft/src/main.rs b/apps/draftcraft/src/main.rs index 9078da43..31b0fe52 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); 8] { +fn filters_for_save(name: &str) -> [(&'static str, &'static str); 9] { let mut filters = [ ("Drawing (DXF)", "dxf"), ("Drawing (DWG)", "dwg"), @@ -210,6 +210,8 @@ fn filters_for_save(name: &str) -> [(&'static str, &'static str); 8] { ("PDF", "pdf"), ("Sheet Set (DCSS)", "dcss"), ("ZIP archive", "zip"), + // ATTOUT's attribute values. + ("Text, tab-delimited (TXT)", "txt"), ]; 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("plan.pdf"), "pdf"); assert_eq!(first("office.dwt"), "dwt"); assert_eq!(first("Project.dcss"), "dcss"); + assert_eq!(first("Floorplan.txt"), "txt"); 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 c0720d2a..6745a61f 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -15,6 +15,8 @@ draftcraft-doc = { workspace = true } draftcraft-dxf = { workspace = true } draftcraft-constraints = { workspace = true } draftcraft-fonts = { workspace = true } +# ATTIN reads files saved as UTF-16 or Windows-1252 text. +encoding_rs = { workspace = true } draftcraft-render = { workspace = true } craft-docpath = { workspace = true } serde = { workspace = true } diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index aec1ab63..2e963080 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -21,6 +21,7 @@ use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, St mod attdef; mod attedit; +mod attio; mod burst; mod description; mod dyngrip; @@ -89,6 +90,8 @@ pub fn specs() -> Vec { blockreplace::blockreplace_spec(), extract::dataextraction_spec(), extract::eattext_spec(), + attio::attout_spec(), + attio::attin_spec(), description::description_spec(), ] .into_iter() diff --git a/crates/engine/src/cmd/blocks/attedit.rs b/crates/engine/src/cmd/blocks/attedit.rs index f76e87bb..3545876f 100644 --- a/crates/engine/src/cmd/blocks/attedit.rs +++ b/crates/engine/src/cmd/blocks/attedit.rs @@ -140,7 +140,7 @@ fn edit(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&str) -> Option /// Refresh the derived baseline after a value change, even one within the writer's /// imported-font tolerance. Equal XY points request recomputation on export; retain /// both elevations and the independent endpoints used by Aligned/Fit text. -fn set_value(text: &mut Text, value: String) { +pub(super) fn set_value(text: &mut Text, value: String) { if text.value == value { return; } diff --git a/crates/engine/src/cmd/blocks/attio.rs b/crates/engine/src/cmd/blocks/attio.rs new file mode 100644 index 00000000..ef11ae30 --- /dev/null +++ b/crates/engine/src/cmd/blocks/attio.rs @@ -0,0 +1,656 @@ +//! ATTOUT / ATTIN (the Express Tools' Export and Import Attribute Information): the attribute +//! values of block references written to a tab-delimited text file, one row per reference, to be +//! edited in a spreadsheet and read back. +//! +//! The file: a header row `HANDLE`, `BLOCKNAME`, then one column per attribute tag (the tags of +//! every reference written, in the order first met); then one row per block reference: its handle +//! with a leading apostrophe (so a spreadsheet keeps it as text), its block name and its values. +//! A cell is empty when that reference has no such tag. A block with the same tag twice names the +//! second column `TAG(2)`. A value holding a tab, a quote or a line break is quoted, a quote inside +//! it doubled. ATTOUT writes UTF-8 with a byte order mark and CRLF line ends; ATTIN also reads +//! UTF-16 (a spreadsheet's "Unicode text") and Windows-1252 text, LF or CR line ends. +//! +//! ATTIN reads every row, then changes the references it names by handle, all in one undo step. +//! Rows whose handle is missing or isn't a block reference are skipped; tags a file doesn't have, +//! and cells holding `<>`, are left alone; references on locked layers are left alone. + +use draftcraft_doc::{Drawing, EntityKind, Handle, Insert}; +use serde_json::{Value, json}; + +use super::attedit::set_value; +use crate::cmd::curves::is_locked; +use crate::cmd::machines::{SelOutcome, SelectPhase}; +use crate::cmd::{CommandSpec, bad, str_param, targets}; +use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; + +/// Largest file ATTIN reads, and ATTOUT writes (bytes). +const MAX_BYTES: usize = 32 * 1024 * 1024; +/// Most rows in a file (the header included). +const MAX_ROWS: usize = 200_000; +/// Most columns in a row (HANDLE and BLOCKNAME included). +const MAX_COLS: usize = 2_000; +/// Longest cell (bytes). +const MAX_CELL: usize = 65_536; + +/// A cell meaning "this reference has no such attribute": left alone by ATTIN. +const NO_ATTRIBUTE: &str = "<>"; + +pub(super) fn attout_spec() -> CommandSpec { + CommandSpec::new("attout", "Export Attribute Information...", run_attout) + .menu(&["Tools", "Express Tools", "Export Attribute Information..."]) + .params( + "{path?: file to write (tab-delimited .txt; omitted: the text comes back as `text`), handles?: block references (default: the selection, else every block reference with attributes in the current space)} → {references, tags, file?, text?}", + ) + .noundo() + .interactive(|_| Ok(Box::new(AttoutM::default()))) +} + +pub(super) fn attin_spec() -> CommandSpec { + CommandSpec::new("attin", "Import Attribute Information...", run_attin) + .menu(&["Tools", "Express Tools", "Import Attribute Information..."]) + .params( + "{path: file written by ATTOUT (or `text`: its contents), handles?: only these block references may change} → {references, values, skipped, locked, unknownTags, message}", + ) + .interactive(|_| Ok(Box::new(AttinM))) +} + +// ---------------- the file ---------------- + +/// The column key of each editable attribute of `ins`, by attribute index: its tag in capitals, +/// `TAG(n)` for the n-th attribute with the same tag. Attributes with no tag have none. +fn keys(ins: &Insert) -> Vec<(usize, String)> { + let mut seen: Vec<(String, usize)> = Vec::new(); + let mut out = Vec::new(); + for (k, a) in ins.attribs.iter().enumerate() { + let tag = a.tag.trim().to_uppercase(); + if a.constant || tag.is_empty() { + continue; + } + let n = match seen.iter_mut().find(|(t, _)| *t == tag) { + Some((_, n)) => { + *n = n.saturating_add(1); + *n + } + None => { + seen.push((tag.clone(), 1)); + 1 + } + }; + out.push((k, if n == 1 { tag } else { format!("{tag}({n})") })); + } + out +} + +/// `text` as a cell: quoted when it holds a tab, a quote or a line break. +fn cell(text: &str) -> String { + if text.contains(['\t', '"', '\n', '\r']) { format!("\"{}\"", text.replace('"', "\"\"")) } else { text.to_string() } +} + +/// A block reference's name as written: its block's. +fn block_name(d: &Drawing, ins: &Insert) -> String { + d.block(&ins.block).map(|b| b.name.clone()).unwrap_or_else(|| ins.block.clone()) +} + +/// The block references with editable attributes among `hs` (each once, in order). +fn references(d: &Drawing, hs: &[Handle]) -> Vec { + let mut out: Vec = Vec::new(); + for h in hs { + if out.contains(h) { + continue; + } + if let Some(EntityKind::Insert(ins)) = d.entity(*h).map(|e| &e.kind) + && !keys(ins).is_empty() + { + out.push(*h); + } + } + out +} + +/// The file for block references `hs`: its text and the tag columns. +fn attout_text(d: &Drawing, hs: &[Handle]) -> Result<(String, Vec)> { + let mut tags: Vec = Vec::new(); + let mut rows: Vec<(Handle, String, Vec<(String, String)>)> = Vec::new(); + for h in hs { + let Some(EntityKind::Insert(ins)) = d.entity(*h).map(|e| &e.kind) else { continue }; + let values: Vec<(String, String)> = + keys(ins).into_iter().filter_map(|(k, key)| ins.attribs.get(k).map(|a| (key, a.text.value.clone()))).collect(); + for (key, _) in &values { + if !tags.contains(key) { + tags.push(key.clone()); + } + } + rows.push((*h, block_name(d, ins), values)); + } + if rows.len() >= MAX_ROWS || tags.len().saturating_add(2) > MAX_COLS { + return Err(EngineError::Other(format!( + "ATTOUT: too much for one file ({} block references, {} tags; at most {} and {}).", + rows.len(), + tags.len(), + MAX_ROWS - 1, + MAX_COLS - 2 + ))); + } + // A byte order mark, so a spreadsheet reads the file as UTF-8. + let mut out = String::from("\u{feff}"); + let header: Vec = ["HANDLE", "BLOCKNAME"].iter().map(|t| t.to_string()).chain(tags.iter().map(|t| cell(t))).collect(); + out.push_str(&header.join("\t")); + out.push_str("\r\n"); + for (h, name, values) in &rows { + let mut line = vec![format!("'{}", h.hex()), cell(name)]; + line.extend(tags.iter().map(|t| values.iter().find(|(k, _)| k == t).map(|(_, v)| cell(v)).unwrap_or_default())); + out.push_str(&line.join("\t")); + out.push_str("\r\n"); + if out.len() > MAX_BYTES { + return Err(EngineError::Other(format!("ATTOUT: the file would be larger than {} MB.", MAX_BYTES / (1024 * 1024)))); + } + } + Ok((out, tags)) +} + +/// The text of a file: UTF-8 (with or without a byte order mark), UTF-16 with a byte order mark, +/// or else Windows-1252, as a spreadsheet saves "text" on Windows. +fn decode(bytes: &[u8]) -> String { + let text = if let Some(rest) = bytes.strip_prefix(b"\xEF\xBB\xBF") { + String::from_utf8_lossy(rest).into_owned() + } else if let Some(rest) = bytes.strip_prefix(b"\xFF\xFE") { + encoding_rs::UTF_16LE.decode_without_bom_handling(rest).0.into_owned() + } else if let Some(rest) = bytes.strip_prefix(b"\xFE\xFF") { + encoding_rs::UTF_16BE.decode_without_bom_handling(rest).0.into_owned() + } else { + match std::str::from_utf8(bytes) { + Ok(t) => t.to_string(), + Err(_) => encoding_rs::WINDOWS_1252.decode_without_bom_handling(bytes).0.into_owned(), + } + }; + match text.strip_prefix('\u{feff}') { + Some(t) => t.to_string(), + None => text, + } +} + +fn too_big(what: String) -> EngineError { + EngineError::Other(format!("ATTIN: {what}")) +} + +/// The rows of tab-delimited `text`. A cell starting with a quote runs to the closing quote (tabs +/// and line breaks inside it are part of the value, `""` is one quote); CRLF, LF and CR end rows. +/// Blank lines are dropped. +fn parse(text: &str) -> Result>> { + if text.len() > MAX_BYTES { + return Err(too_big(format!("the file is larger than {} MB", MAX_BYTES / (1024 * 1024)))); + } + let mut rows: Vec> = Vec::new(); + let mut row: Vec = Vec::new(); + let mut cur = String::new(); + let mut chars = text.chars().peekable(); + let mut line = 1usize; + // At the start of a cell (a quote there opens a quoted value). + let mut fresh = true; + let push_cell = |row: &mut Vec, cur: &mut String, line: usize| -> Result<()> { + if row.len() >= MAX_COLS { + return Err(too_big(format!("line {line} has more than {MAX_COLS} columns"))); + } + row.push(std::mem::take(cur)); + Ok(()) + }; + let push_row = |rows: &mut Vec>, row: &mut Vec| -> Result<()> { + let r = std::mem::take(row); + if r.len() == 1 && r.first().is_some_and(|c| c.trim().is_empty()) { + return Ok(()); // a blank line + } + if rows.len() >= MAX_ROWS { + return Err(too_big(format!("the file has more than {MAX_ROWS} rows"))); + } + rows.push(r); + Ok(()) + }; + while let Some(c) = chars.next() { + match c { + '"' if fresh => { + let start = line; + loop { + match chars.next() { + Some('"') if chars.peek() == Some(&'"') => { + chars.next(); + cur.push('"'); + } + Some('"') => break, + Some(ch) => { + if ch == '\n' { + line = line.saturating_add(1); + } + cur.push(ch); + } + None => return Err(EngineError::Other(format!("ATTIN: line {start}: a quoted value is never closed"))), + } + if cur.len() > MAX_CELL { + return Err(too_big(format!("line {start}: a value is longer than {MAX_CELL} bytes"))); + } + } + fresh = false; + } + '\t' => { + push_cell(&mut row, &mut cur, line)?; + fresh = true; + } + '\r' | '\n' => { + if c == '\r' && chars.peek() == Some(&'\n') { + chars.next(); + } + push_cell(&mut row, &mut cur, line)?; + push_row(&mut rows, &mut row)?; + line = line.saturating_add(1); + fresh = true; + } + _ => { + cur.push(c); + fresh = false; + if cur.len() > MAX_CELL { + return Err(too_big(format!("line {line}: a value is longer than {MAX_CELL} bytes"))); + } + } + } + } + if !fresh || !cur.is_empty() || !row.is_empty() { + push_cell(&mut row, &mut cur, line)?; + push_row(&mut rows, &mut row)?; + } + Ok(rows) +} + +/// A value as an attribute holds it: no control characters but tabs, and line breaks only in a +/// multiline attribute (a space in a single-line one). +fn clean(value: &str, multiline: bool) -> String { + let value = value.replace("\r\n", "\n"); + value + .chars() + .filter_map(|c| match c { + '\n' | '\r' if multiline => Some('\n'), + '\n' | '\r' => Some(' '), + '\t' => Some('\t'), + c if c.is_control() => None, + c => Some(c), + }) + .collect() +} + +/// A handle cell: hex digits, perhaps after an apostrophe. +fn handle_cell(text: &str) -> Option { + let t = text.trim(); + Handle::parse_hex(t.strip_prefix('\'').unwrap_or(t).trim()) +} + +/// What ATTIN did. +#[derive(Debug, Default)] +struct Imported { + references: usize, + values: usize, + skipped: usize, + locked: usize, + unknown_tags: Vec, +} + +impl Imported { + fn message(&self) -> String { + let plural = |n: usize, one: &str, many: &str| format!("{n} {}", if n == 1 { one } else { many }); + let mut m = format!( + "{} updated ({}).", + plural(self.references, "block reference", "block references"), + plural(self.values, "attribute value", "attribute values") + ); + if self.skipped > 0 { + m.push_str(&format!(" {} skipped: no block reference with that handle.", plural(self.skipped, "row", "rows"))); + } + if self.locked > 0 { + m.push_str(&format!(" {} on locked layers left alone.", plural(self.locked, "block reference", "block references"))); + } + m + } +} + +/// Apply rows read from a file (the header first). `only`: just these references may change. +fn import(s: &mut Session, rows: &[Vec], only: Option<&[Handle]>) -> Result { + let Some((header, body)) = rows.split_first() else { return Err(EngineError::Other("ATTIN: the file is empty.".into())) }; + let names: Vec = header.iter().map(|h| h.trim().to_uppercase()).collect(); + let handle_col = names + .iter() + .position(|n| n == "HANDLE") + .ok_or_else(|| EngineError::Other("ATTIN: the file has no HANDLE column; write it with ATTOUT.".into()))?; + // The tag columns: everything but HANDLE and BLOCKNAME, each name once. + let mut tag_cols: Vec<(usize, &str)> = Vec::new(); + for (c, n) in names.iter().enumerate() { + if c != handle_col && n != "BLOCKNAME" && !n.is_empty() && !tag_cols.iter().any(|(_, t)| *t == n.as_str()) { + tag_cols.push((c, n.as_str())); + } + } + let mut used = vec![false; tag_cols.len()]; + let mut out = Imported::default(); + // Work out every change first, then make them. + let mut changes: Vec<(Handle, Vec<(usize, String)>)> = Vec::new(); + { + let d = s.doc()?; + for row in body { + let Some(h) = row.get(handle_col).and_then(|c| handle_cell(c)) else { + out.skipped = out.skipped.saturating_add(1); + continue; + }; + let Some(EntityKind::Insert(ins)) = d.entity(h).map(|e| &e.kind) else { + out.skipped = out.skipped.saturating_add(1); + continue; + }; + if only.is_some_and(|o| !o.contains(&h)) { + out.skipped = out.skipped.saturating_add(1); + continue; + } + let keys = keys(ins); + let mut edits: Vec<(usize, String)> = Vec::new(); + for (n, (c, tag)) in tag_cols.iter().enumerate() { + let Some(raw) = row.get(*c) else { continue }; + let Some((k, _)) = keys.iter().find(|(_, key)| key == tag) else { continue }; + if let Some(u) = used.get_mut(n) { + *u = true; + } + if raw.trim() == NO_ATTRIBUTE { + continue; + } + let Some(a) = ins.attribs.get(*k) else { continue }; + let value = clean(raw, a.multiline.is_some()); + if value != a.text.value { + edits.push((*k, value)); + } + } + if !edits.is_empty() { + changes.push((h, edits)); + } + } + } + out.unknown_tags = tag_cols.iter().zip(&used).filter(|(_, u)| !**u).map(|((_, t), _)| t.to_string()).collect(); + // A reference named twice: its last row wins. + let mut merged: Vec<(Handle, Vec<(usize, String)>)> = Vec::new(); + for (h, edits) in changes { + match merged.iter_mut().find(|(m, _)| *m == h) { + Some((_, m)) => { + for (k, v) in edits { + match m.iter_mut().find(|(mk, _)| *mk == k) { + Some(e) => e.1 = v, + None => m.push((k, v)), + } + } + } + None => merged.push((h, edits)), + } + } + for (h, edits) in merged { + if is_locked(s, h) || attribute_on_locked_layer(s, h, &edits) { + out.locked = out.locked.saturating_add(1); + continue; + } + let mut n = 0usize; + s.doc_mut()?.modify_entity(h, |e| { + if let EntityKind::Insert(ins) = &mut e.kind { + for (k, v) in &edits { + if let Some(a) = ins.attribs.get_mut(*k) + && a.text.value != *v + { + set_value(&mut a.text, v.clone()); + n = n.saturating_add(1); + } + } + } + })?; + if n > 0 { + out.references = out.references.saturating_add(1); + out.values = out.values.saturating_add(n); + } + } + Ok(out) +} + +/// Whether one of the attributes `edits` would change is on a locked layer of its own. +fn attribute_on_locked_layer(s: &Session, h: Handle, edits: &[(usize, String)]) -> bool { + let Ok(d) = s.doc() else { return false }; + let Some(EntityKind::Insert(ins)) = d.entity(h).map(|e| &e.kind) else { return false }; + edits.iter().any(|(k, _)| ins.attribs.get(*k).and_then(|a| a.props.layer.as_deref()).and_then(|l| d.layer(l)).is_some_and(|l| l.locked)) +} + +// ---------------- files ---------------- + +fn write_file(path: &str, text: &str) -> Result<()> { + #[cfg(not(target_arch = "wasm32"))] + { + crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), text.as_bytes()) + .map_err(|e| bad("attout", format!("{path}: {e}"))) + } + #[cfg(target_arch = "wasm32")] + { + crate::cmd::exchange::deliver_file("attout", path, text.as_bytes(), crate::cmd::file::deliver()) + } +} + +fn read_file(path: &str) -> Result> { + #[cfg(not(target_arch = "wasm32"))] + { + crate::capped_read::read_capped(std::path::Path::new(path), MAX_BYTES).map_err(|e| bad("attin", format!("{path}: {e}"))) + } + #[cfg(target_arch = "wasm32")] + { + Err(bad("attin", format!("{path}: files can't be read in the browser; pass the file's contents as `text`"))) + } +} + +/// 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) +} + +/// The default file: the drawing's name with a .txt extension. +fn default_file(s: &Session) -> String { + let Ok(st) = s.state() else { return "attributes.txt".into() }; + let base = st.path.clone().unwrap_or_else(|| st.title.clone()); + std::path::Path::new(&base).with_extension("txt").to_string_lossy().into_owned() +} + +// ---------------- the commands ---------------- + +/// The block references ATTOUT writes: `handles`, else the selection, else every one with +/// attributes in the current space. +fn attout_targets(s: &Session, p: &Value) -> Result> { + let mut hs = targets(s, p)?; + if hs.is_empty() && p.get("handles").is_none() && p.get("handle").is_none() { + let d = s.doc()?; + hs = d.space(&s.space()).map(|st| st.iter().map(|e| e.handle).collect()).unwrap_or_default(); + } + Ok(references(s.doc()?, &hs)) +} + +fn attout(s: &mut Session, hs: &[Handle], path: Option<&str>) -> Result { + if hs.is_empty() { + return Err(EngineError::Other("ATTOUT: no block references with attributes.".into())); + } + let (text, tags) = attout_text(s.doc()?, hs)?; + let mut r = json!({ "references": hs.len(), "tags": tags }); + match path { + Some(path) => { + write_file(path, &text)?; + r["file"] = json!(path); + r["message"] = json!(format!("{} block reference{} written to {path}.", hs.len(), if hs.len() == 1 { "" } else { "s" })); + } + None => r["text"] = json!(text.strip_prefix('\u{feff}').unwrap_or(&text)), + } + Ok(r) +} + +fn run_attout(s: &mut Session, p: &Value) -> Result { + let hs = attout_targets(s, p)?; + let path = str_param(p, "path").map(unquoted).filter(|f| !f.is_empty()); + attout(s, &hs, path) +} + +fn run_attin(s: &mut Session, p: &Value) -> Result { + let text = match (str_param(p, "text"), str_param(p, "path").map(unquoted).filter(|f| !f.is_empty())) { + (Some(t), _) => t.strip_prefix('\u{feff}').unwrap_or(t).to_string(), + (None, Some(path)) => decode(&read_file(path)?), + (None, None) => return Err(bad("attin", "`path` (a file written by ATTOUT) or `text` is required")), + }; + let only = if p.get("handles").is_some() || p.get("handle").is_some() { Some(targets(s, p)?) } else { None }; + let rows = parse(&text)?; + let r = import(s, &rows, only.as_deref())?; + Ok(json!({ + "references": r.references, + "values": r.values, + "skipped": r.skipped, + "locked": r.locked, + "unknownTags": r.unknown_tags, + "message": r.message(), + })) +} + +/// ATTOUT at the command line: the file name, then the block references. +#[derive(Default)] +struct AttoutM { + file: Option, + sel: SelectPhase, +} + +impl AttoutM { + fn finish(&self, s: &mut Session, picked: &[Handle]) -> Result { + let hs = references(s.doc()?, picked); + let file = self.file.clone().unwrap_or_else(|| default_file(s)); + let r = attout(s, &hs, Some(&file))?; + if let Some(m) = r.get("message").and_then(Value::as_str) { + s.echo(m.to_string()); + } + s.set_selection(Vec::new()); + Ok(Step::Done) + } +} + +impl Interactive for AttoutM { + fn name(&self) -> &'static str { + "ATTOUT" + } + fn begin(&mut self, s: &mut Session) -> Result { + self.sel = SelectPhase::begin(s); + Ok(Step::Continue) + } + fn prompt(&self, s: &Session) -> Prompt { + match self.file { + None => Prompt::new("Enter output file name", Accept::TEXT).default(default_file(s)), + Some(_) => self.sel.prompt(), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if self.file.is_none() { + let f = match &i { + Input::Text(t) if !unquoted(t).is_empty() => unquoted(t).to_string(), + Input::Text(_) | Input::Enter => default_file(s), + _ => return Ok(Step::Continue), + }; + self.file = Some(f); + if self.sel.done { + let hs = self.sel.picked.clone(); + return self.finish(s, &hs); + } + return Ok(Step::Continue); + } + match self.sel.feed(s, &i)? { + SelOutcome::More => Ok(Step::Continue), + SelOutcome::Empty => Ok(Step::Done), + SelOutcome::Done(hs) => self.finish(s, &hs), + } + } +} + +/// ATTIN at the command line: the file name. +#[derive(Default)] +struct AttinM; + +impl Interactive for AttinM { + fn name(&self) -> &'static str { + "ATTIN" + } + fn prompt(&self, s: &Session) -> Prompt { + Prompt::new("Enter input file name", Accept::TEXT).default(default_file(s)) + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + let f = match &i { + Input::Text(t) if !unquoted(t).is_empty() => unquoted(t).to_string(), + Input::Text(_) | Input::Enter => default_file(s), + _ => return Ok(Step::Continue), + }; + // The whole file is applied in this one step: one undo step. + let r = run_attin(s, &json!({ "path": f }))?; + if let Some(m) = r.get("message").and_then(Value::as_str) { + s.echo(m.to_string()); + } + Ok(Step::Done) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn cells_round_trip_through_the_parser() { + let values = ["plain", "a\tb", "say \"hi\"", "two\nlines", "", "\"", "crlf\r\nend", "<>"]; + let line: Vec = values.iter().map(|v| cell(v)).collect(); + let text = format!("HANDLE\tBLOCKNAME\r\n{}\r\n", line.join("\t")); + let rows = parse(&text).unwrap(); + assert_eq!(rows.len(), 2); + assert_eq!(rows[1], values.iter().map(|v| v.to_string()).collect::>()); + } + + #[test] + fn line_ends_blank_lines_and_a_missing_last_line_end() { + let rows = parse("A\tB\rC\tD\n\n\r\nE\tF").unwrap(); + assert_eq!(rows, vec![vec!["A", "B"], vec!["C", "D"], vec!["E", "F"]]); + // An empty cell at the end of a line is kept. + assert_eq!(parse("A\t\n").unwrap(), vec![vec!["A".to_string(), String::new()]]); + assert!(parse("").unwrap().is_empty()); + } + + #[test] + fn hostile_text_is_refused_not_panicked_on() { + assert!(parse("A\t\"never closed\n").is_err()); + assert!(parse(&"\t".repeat(MAX_COLS + 1)).is_err()); + assert!(parse(&"x\n".repeat(MAX_ROWS + 1)).is_err()); + assert!(parse(&"x".repeat(MAX_CELL + 1)).is_err()); + assert!(parse(&format!("\"{}\"", "x".repeat(MAX_CELL + 1))).is_err()); + // A quote inside an unquoted value is just a character. + assert_eq!(parse("a\"b\tc").unwrap(), vec![vec!["a\"b", "c"]]); + // Text after a closing quote stays with the value. + assert_eq!(parse("\"a\"b").unwrap(), vec![vec!["ab"]]); + } + + #[test] + fn files_decode_from_utf8_utf16_and_windows_1252() { + assert_eq!(decode(b"\xEF\xBB\xBFHANDLE"), "HANDLE"); + assert_eq!(decode("caffè".as_bytes()), "caffè"); + // "è" saved as Windows-1252 text. + assert_eq!(decode(b"caff\xE8"), "caffè"); + let mut le = vec![0xFF, 0xFE]; + le.extend("Hè\t1".encode_utf16().flat_map(u16::to_le_bytes)); + assert_eq!(decode(&le), "Hè\t1"); + let mut be = vec![0xFE, 0xFF]; + be.extend("Hè".encode_utf16().flat_map(u16::to_be_bytes)); + assert_eq!(decode(&be), "Hè"); + // An odd byte out and invalid UTF-8 after a mark don't panic. + let _ = decode(b"\xFF\xFE\x41"); + let _ = decode(b"\xEF\xBB\xBF\xC3"); + } + + #[test] + fn handles_values_and_messages() { + assert_eq!(handle_cell("'1A2"), Some(Handle(0x1A2))); + assert_eq!(handle_cell(" 1a2 "), Some(Handle(0x1A2))); + assert_eq!(handle_cell("'"), None); + assert_eq!(handle_cell("nope"), None); + assert_eq!(clean("a\r\nb\u{0}c\td", false), "a bc\td"); + assert_eq!(clean("a\r\nb", true), "a\nb"); + let m = Imported { references: 1, values: 2, skipped: 3, locked: 1, unknown_tags: vec![] }.message(); + assert!(m.contains("1 block reference updated (2 attribute values)") && m.contains("3 rows skipped") && m.contains("locked"), "{m}"); + } +} diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index 1eb1a3bc..a48d5d60 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -100,6 +100,7 @@ pub(super) fn deliver_file(cmd: &str, path: &str, bytes: &[u8], hook: Option "image/svg+xml", "png" => "image/png", "pdf" => "application/pdf", + "txt" => "text/plain; charset=utf-8", _ => "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/tests/it/attout_attin.rs b/crates/engine/tests/it/attout_attin.rs new file mode 100644 index 00000000..3403ec03 --- /dev/null +++ b/crates/engine/tests/it/attout_attin.rs @@ -0,0 +1,249 @@ +//! ATTOUT / ATTIN: attribute values out to a tab-delimited file and back in by handle. + +use std::path::PathBuf; + +use draftcraft_doc::{EntityKind, Handle}; +use draftcraft_engine::{Input, Session}; +use serde_json::{Value, json}; + +/// Blocks DOOR (tags NUMBER, TYPE) and WINDOW (tags NUMBER, WIDTH), two doors, a window, a line. +fn drawing() -> (Session, [String; 4]) { + let mut s = Session::new(); + block(&mut s, "DOOR", &["NUMBER", "TYPE"]); + block(&mut s, "WINDOW", &["Number", "WIDTH"]); + let d1 = insert(&mut s, "DOOR", 0.0, json!({"NUMBER": "D1", "TYPE": "Single"})); + let d2 = insert(&mut s, "DOOR", 10.0, json!({"NUMBER": "D2", "TYPE": "Double"})); + let w1 = insert(&mut s, "WINDOW", 20.0, json!({"NUMBER": "W1", "WIDTH": "900"})); + let r = s.execute("line", &json!({"points": [[0, -5], [10, -5]]})).unwrap(); + let line = r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string(); + (s, [d1, d2, w1, line]) +} + +fn block(s: &mut Session, name: &str, tags: &[&str]) { + for (i, t) in tags.iter().enumerate() { + s.execute("attdef", &json!({"tag": t, "default": "", "at": [0, i as f64], "height": 0.5})).unwrap(); + } + s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap(); + let hs: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({"name": name, "base": [0, 0], "handles": hs, "keep": "delete"})).unwrap(); +} + +fn insert(s: &mut Session, name: &str, x: f64, attribs: Value) -> String { + s.execute("insert", &json!({"name": name, "at": [x, 5], "attribs": attribs})).unwrap()["handle"].as_str().unwrap().to_string() +} + +/// The attribute values of block reference `h`, by tag. +fn values(s: &Session, h: &str) -> Vec<(String, String)> { + let d = s.doc().unwrap(); + let EntityKind::Insert(i) = &d.entity(Handle::parse_hex(h).unwrap()).unwrap().kind else { panic!("not a block reference") }; + i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect() +} + +fn value(s: &Session, h: &str, tag: &str) -> String { + values(s, h).into_iter().find(|(t, _)| t.eq_ignore_ascii_case(tag)).unwrap().1 +} + +fn scratch(name: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("draftcraft-attio-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + dir.join(name) +} + +fn attin_text(s: &mut Session, text: &str) -> Value { + s.execute("attin", &json!({ "text": text })).unwrap() +} + +#[test] +fn attout_writes_handles_names_and_the_union_of_tags() { + let (mut s, [d1, d2, w1, line]) = drawing(); + let path = scratch("out.txt"); + let r = s.execute("attout", &json!({"path": path.to_string_lossy(), "handles": [d1, w1, line, d2]})).unwrap(); + assert_eq!(r["references"], 3, "{r}"); + assert_eq!(r["tags"], json!(["NUMBER", "TYPE", "WIDTH"])); + let bytes = std::fs::read(&path).unwrap(); + assert!(bytes.starts_with(b"\xEF\xBB\xBF"), "UTF-8 with a byte order mark"); + let text = String::from_utf8(bytes[3..].to_vec()).unwrap(); + let expected = + format!("HANDLE\tBLOCKNAME\tNUMBER\tTYPE\tWIDTH\r\n'{d1}\tDOOR\tD1\tSingle\t\r\n'{w1}\tWINDOW\tW1\t\t900\r\n'{d2}\tDOOR\tD2\tDouble\t\r\n"); + assert_eq!(text, expected); + // Without a path the text comes back; without handles, every reference in the space. + let r = s.execute("attout", &json!({})).unwrap(); + assert_eq!(r["references"], 3); + assert!(r["text"].as_str().unwrap().contains(&format!("'{w1}\tWINDOW"))); + // Nothing with attributes is an error, not an empty file. + assert!(s.execute("attout", &json!({"handles": [line]})).is_err()); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn round_trip_attout_edit_attin_and_undo_in_one_step() { + let (mut s, [d1, d2, w1, _]) = drawing(); + let path = scratch("roundtrip.txt"); + let ps = path.to_string_lossy().to_string(); + s.execute("attout", &json!({"path": ps})).unwrap(); + let before: Vec<_> = [&d1, &d2, &w1].iter().map(|h| values(&s, h)).collect(); + + // Unchanged, it changes nothing. + let r = s.execute("attin", &json!({"path": ps})).unwrap(); + assert_eq!((r["references"].as_u64(), r["values"].as_u64(), r["skipped"].as_u64()), (Some(0), Some(0), Some(0)), "{r}"); + + // Edited as a spreadsheet would: CRLF kept, a value with a tab and quotes quoted. + let text = String::from_utf8(std::fs::read(&path).unwrap()).unwrap(); + let edited = text + .replace("\tSingle\t", "\t\"Fire \"\"rated\"\"\tA\"\t") + .replace("\t900\r\n", "\t1200\r\n") + .replace(&format!("'{d2}\tDOOR\tD2"), &format!("'{d2}\tDOOR\tD2-bis")); + std::fs::write(&path, edited).unwrap(); + let r = s.execute("attin", &json!({"path": ps})).unwrap(); + assert_eq!(r["references"], 3, "{r}"); + assert_eq!(r["values"], 3); + assert_eq!(r["skipped"], 0); + assert!(r["message"].as_str().unwrap().contains("3 block references updated (3 attribute values)"), "{r}"); + assert_eq!(value(&s, &d1, "TYPE"), "Fire \"rated\"\tA"); + assert_eq!(value(&s, &d2, "NUMBER"), "D2-bis"); + assert_eq!(value(&s, &w1, "WIDTH"), "1200"); + // Its own output reads back the same. + let again = s.execute("attout", &json!({})).unwrap()["text"].as_str().unwrap().to_string(); + let r = attin_text(&mut s, &again); + assert_eq!(r["values"], 0, "{r}"); + + // One undo step takes the whole import back; redo brings it again. + s.undo().unwrap(); + let after: Vec<_> = [&d1, &d2, &w1].iter().map(|h| values(&s, h)).collect(); + assert_eq!(after, before); + s.redo().unwrap(); + assert_eq!(value(&s, &w1, "WIDTH"), "1200"); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn unknown_handles_and_other_objects_are_skipped() { + let (mut s, [d1, _, _, line]) = drawing(); + let text = format!("HANDLE\tBLOCKNAME\tNUMBER\n'FFFFF\tDOOR\tX\n\tDOOR\tY\n'{line}\tLINE\tZ\nnot-a-handle\tDOOR\tQ\n'{d1}\tDOOR\tD1-new\n"); + let r = attin_text(&mut s, &text); + assert_eq!(r["skipped"], 4, "{r}"); + assert_eq!(r["references"], 1); + assert_eq!(value(&s, &d1, "NUMBER"), "D1-new"); + // Rows outside `handles` are skipped too. + let (mut s, [d1, d2, _, _]) = drawing(); + let text = format!("HANDLE\tNUMBER\n'{d1}\tA\n'{d2}\tB\n"); + let r = s.execute("attin", &json!({"text": text, "handles": [d2]})).unwrap(); + assert_eq!((r["references"].as_u64(), r["skipped"].as_u64()), (Some(1), Some(1)), "{r}"); + assert_eq!(value(&s, &d1, "NUMBER"), "D1"); + assert_eq!(value(&s, &d2, "NUMBER"), "B"); +} + +#[test] +fn tags_missing_from_the_file_or_the_block_are_left_alone() { + let (mut s, [d1, d2, w1, _]) = drawing(); + // No TYPE column; a COLOR column no block has; `<>` and a short row leave values alone; tags + // match in any case; the columns may come in any order. + let text = format!("number\tHandle\tCOLOR\tWIDTH\nN1\t'{d1}\tred\t<>\n<>\t{w1}\tblue\t600\nN2\t'{d2}\n"); + let r = attin_text(&mut s, &text); + assert_eq!(r["unknownTags"], json!(["COLOR"]), "{r}"); + assert_eq!(value(&s, &d1, "NUMBER"), "N1"); + assert_eq!(value(&s, &d1, "TYPE"), "Single"); + assert_eq!(value(&s, &w1, "NUMBER"), "W1"); + assert_eq!(value(&s, &w1, "WIDTH"), "600"); + assert_eq!(value(&s, &d2, "NUMBER"), "N2"); + assert_eq!(value(&s, &d2, "TYPE"), "Double"); + // An empty cell clears a value the block has. + attin_text(&mut s, &format!("HANDLE\tTYPE\n'{d1}\t\n")); + assert_eq!(value(&s, &d1, "TYPE"), ""); +} + +#[test] +fn references_on_locked_layers_are_left_alone_and_reported() { + let (mut s, [d1, d2, _, _]) = drawing(); + s.execute("layer.new", &json!({"name": "Locked"})).unwrap(); + s.execute("layer.set", &json!({"name": "Locked", "locked": true})).unwrap(); + s.doc_mut().unwrap().modify_entity(Handle::parse_hex(&d1).unwrap(), |e| e.common.layer = "Locked".into()).unwrap(); + let r = attin_text(&mut s, &format!("HANDLE\tNUMBER\n'{d1}\tX\n'{d2}\tY\n")); + assert_eq!((r["references"].as_u64(), r["locked"].as_u64()), (Some(1), Some(1)), "{r}"); + assert!(r["message"].as_str().unwrap().contains("locked"), "{r}"); + assert_eq!(value(&s, &d1, "NUMBER"), "D1"); + assert_eq!(value(&s, &d2, "NUMBER"), "Y"); +} + +#[test] +fn hostile_files_are_refused_or_skipped_without_panicking() { + let (mut s, [d1, ..]) = drawing(); + let snapshot = values(&s, &d1); + for bad in [ + String::new(), + "\u{feff}".to_string(), + "no handle column\n'1\tx\n".to_string(), + format!("HANDLE\tNUMBER\n'{d1}\t\"never closed\n"), + format!("HANDLE\tNUMBER\n'{d1}\t{}\n", "x".repeat(70_000)), + format!("HANDLE{}\n", "\tT".repeat(5_000)), + ] { + assert!(s.execute("attin", &json!({"text": bad})).is_err(), "{:.80}", bad); + assert_eq!(values(&s, &d1), snapshot); + } + // Garbage that parses is skipped row by row. + for junk in ["HANDLE\n\0\0\0\n", "HANDLE\tNUMBER\n'-1\tx\n'18446744073709551616\ty\n", "\t\t\t\nHANDLE\n", "HANDLE\tHANDLE\tNUMBER\n"] { + let _ = s.execute("attin", &json!({"text": junk})); + } + // Control characters are dropped and line breaks become spaces in a single-line attribute. + attin_text(&mut s, &format!("HANDLE\tNUMBER\n'{d1}\t\"a\r\nb\u{1}c\"\n")); + assert_eq!(value(&s, &d1, "NUMBER"), "a bc"); + // Bytes that aren't UTF-8 read as Windows-1252; UTF-16 with a byte order mark reads too. + let path = scratch("cp1252.txt"); + let ps = path.to_string_lossy().to_string(); + let mut bytes = format!("HANDLE\tNUMBER\r\n'{d1}\tcaff").into_bytes(); + bytes.extend([0xE8, b'\r', b'\n']); + std::fs::write(&path, &bytes).unwrap(); + s.execute("attin", &json!({"path": ps})).unwrap(); + assert_eq!(value(&s, &d1, "NUMBER"), "caffè"); + let mut utf16 = vec![0xFF, 0xFE]; + utf16.extend(format!("HANDLE\tNUMBER\r\n'{d1}\tüber\r\n").encode_utf16().flat_map(u16::to_le_bytes)); + std::fs::write(&path, &utf16).unwrap(); + s.execute("attin", &json!({"path": ps})).unwrap(); + assert_eq!(value(&s, &d1, "NUMBER"), "über"); + // A file too large is refused before it is read in full; a folder or a missing file is an error. + std::fs::write(&path, vec![b'x'; 32 * 1024 * 1024 + 1]).unwrap(); + assert!(s.execute("attin", &json!({"path": ps})).is_err()); + assert!(s.execute("attin", &json!({"path": std::env::temp_dir().to_string_lossy()})).is_err()); + assert!(s.execute("attin", &json!({"path": scratch("missing.txt").to_string_lossy()})).is_err()); + assert!(s.execute("attin", &json!({})).is_err()); + let _ = std::fs::remove_file(&path); +} + +#[test] +fn the_command_line_forms_ask_for_the_file_then_the_objects() { + let (mut s, [d1, d2, w1, _]) = drawing(); + let path = scratch("typed.txt"); + let ps = path.to_string_lossy().to_string(); + s.start("attout").unwrap(); + assert!(s.prompt_text().contains("output file name"), "{}", s.prompt_text()); + s.input(Input::Text(format!("\"{ps}\""))).unwrap(); + assert!(s.prompt_text().contains("Select objects"), "{}", s.prompt_text()); + s.input(Input::Pick(vec![Handle::parse_hex(&d1).unwrap(), Handle::parse_hex(&w1).unwrap()])).unwrap(); + s.input(Input::Enter).unwrap(); + assert!(s.running.is_none()); + let text = std::fs::read_to_string(&path).unwrap(); + assert_eq!(text.lines().count(), 3, "{text}"); + assert!(!text.contains(&format!("'{d2}"))); + + // A pickfirst selection is used straight after the file name. + std::fs::write(&path, text.replace("\tD1\t", "\tD1-typed\t")).unwrap(); + s.set_selection(vec![Handle::parse_hex(&d2).unwrap()]); + s.start("attout").unwrap(); + s.input(Input::Text(scratch("pickfirst.txt").to_string_lossy().to_string())).unwrap(); + assert!(s.running.is_none()); + assert_eq!(std::fs::read_to_string(scratch("pickfirst.txt")).unwrap().lines().count(), 2); + + // ATTIN asks for the file and applies it as one undo step. + s.start("attin").unwrap(); + assert!(s.prompt_text().contains("input file name"), "{}", s.prompt_text()); + s.input(Input::Text(ps.clone())).unwrap(); + assert!(s.running.is_none()); + assert_eq!(value(&s, &d1, "NUMBER"), "D1-typed"); + s.undo().unwrap(); + assert_eq!(value(&s, &d1, "NUMBER"), "D1"); + // A script reaches the same prompts. + s.script(&format!("attin\n{ps}\n")).unwrap(); + assert_eq!(value(&s, &d1, "NUMBER"), "D1-typed"); + let _ = std::fs::remove_file(&path); + let _ = std::fs::remove_file(scratch("pickfirst.txt")); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 1c11467e..20030920 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -8,6 +8,7 @@ mod assoc_array; mod attdef_command; mod attdisp_attsync; mod attedit_prompts; +mod attout_attin; mod attrib_modes; mod attrib_props; mod attribute_tools; diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index ef11f602..292ef5df 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1652,3 +1652,8 @@ menu Workspaces Aree di lavoro Engineering Ingegneristiche Fractional Frazionarie Scientific Scientifiche + Export Attribute Information... Esporta informazioni attributi... + Import Attribute Information... Importa informazioni attributi... + Export Attributes Esporta attributi + Import Attributes Importa attributi + Text, tab-delimited (TXT) Testo delimitato da tabulazioni (TXT) diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index f1883ea3..aeb5681d 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1626,3 +1626,10 @@ menu Palettes 选项板 menu Customize 自定义 menu Workspaces 工作空间 menu CAD Standards CAD 标准 + Export Attribute Information... 导出属性信息... + Import Attribute Information... 导入属性信息... + Export Attributes 导出属性 + Import Attributes 导入属性 + Text, tab-delimited (TXT) 制表符分隔的文本 (TXT) + Enter output file name 输入要写入的文件名 + Enter input file name 输入要读取的文件名 diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index eb9da7af..74624bf7 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -92,6 +92,8 @@ pub enum Icon { Insert, BlockEdit, AttDef, + AttOut, + AttIn, LayerProps, LayerOff, LayerIso, @@ -832,6 +834,24 @@ fn paint_dimensions(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, _dim: boo fn paint_block_tools(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, _dim: bool) { use Icon::*; match icon { + // ATTOUT / ATTIN: a block and a sheet of rows and columns, an arrow from the block to + // the sheet (export) or from the sheet to the block (import). + AttOut | AttIn => { + pen.poly(&[(6.0, 1.5), (11.0, 4.0), (6.0, 6.5), (1.0, 4.0)], true, b); + pen.poly(&[(1.0, 4.0), (1.0, 8.5), (6.0, 11.0), (11.0, 8.5), (11.0, 4.0)], false, b); + pen.rect(13.0, 8.0, 10.0, 14.0, b); + pen.l(13.0, 12.5, 23.0, 12.5); + pen.l(13.0, 17.0, 23.0, 17.0); + pen.l(17.0, 8.0, 17.0, 22.0); + let thick = Stroke::new(pen.w * 1.8, a); + if icon == AttOut { + pen.p.line(vec![pen.at(5.0, 13.0), pen.at(5.0, 19.0), pen.at(8.5, 19.0)], thick); + pen.big_arrow(12.5, 19.0, 1.0, 0.0, 4.5, 3.0, a); + } else { + pen.p.line(vec![pen.at(12.0, 19.0), pen.at(5.0, 19.0), pen.at(5.0, 16.5)], thick); + pen.big_arrow(5.0, 12.0, 0.0, -1.0, 4.5, 3.0, a); + } + } LayerOff | LayerIso | LayerFreeze | LayerLock | LayerMatch | MakeCurrent | LayerPrev => { pen.poly(&[(2.0, 9.0), (10.0, 5.0), (18.0, 9.0), (10.0, 13.0)], true, b); pen.poly(&[(2.0, 13.0), (10.0, 17.0), (18.0, 13.0)], false, b); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 558f0dad..1c79b1e9 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -130,6 +130,9 @@ fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value) -> Option Option> { app.hold_lossy_save().then_some(Ok(Value::Null)) } +/// ATTOUT and ATTIN from the ribbon, a menu or typed: the file dialog, then the engine's prompts +/// (ATTOUT then asks for the block references). `None` with FILEDIA off or no file dialog here: +/// the engine's command asks for the file name instead. JSON calls carry `path` and never get here. +fn attribute_file(app: &mut CadApp, id: &str, params: &Value) -> Option> { + if !matches!(id, "attout" | "attin") || !params.is_null() || app.session.state().is_err() || !app.session.settings.filedia { + return None; + } + let path = if id == "attout" { + let pick = app.services.pick_save.as_ref()?; + let title = app.session.state().map(|s| s.title.clone()).unwrap_or_default(); + let stem = std::path::Path::new(&title).file_stem().map(|s| s.to_string_lossy().to_string()).filter(|s| !s.is_empty()); + pick(&format!("{}.txt", stem.unwrap_or_else(|| "Drawing".into()))) + } else { + if app.services.no_file_system { + let hint = "ATTIN: there is no file system here; run it with the file's contents, e.g. attin {\"text\": \"HANDLE\\tTAG\\n'1A2\\tvalue\"}"; + app.session.echo(hint.to_string()); + app.set_status(hint); + return Some(Ok(Value::Null)); + } + let pick = app.services.pick_file.as_ref()?; + pick("Text, tab-delimited (TXT)", &["txt"]) + }; + let Some(path) = path else { return Some(Ok(Value::Null)) }; + if let Err(e) = app.session.start(id) { + app.session.echo(e.to_string()); + return Some(Err(e.to_string())); + } + if let Err(e) = app.session.input(draftcraft_engine::Input::Text(path)) { + app.session.echo(e.to_string()); + return Some(Err(e.to_string())); + } + Some(Ok(Value::Null)) +} + fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option> { if let Some(result) = route_ui_subsystems(app, id, params) { return Some(result); @@ -1047,6 +1084,41 @@ mod tests { assert!(app.ui.dialog.is_none()); } + /// ATTOUT from the ribbon asks where to save, then for the block references; ATTIN asks for + /// the file and applies it. JSON calls never open a dialog. + #[test] + fn attout_and_attin_ask_for_the_file() { + let path = std::env::temp_dir().join(format!("draftcraft-attout-ui-{}.txt", std::process::id())); + let ps = path.to_string_lossy().to_string(); + let (mut app, asked) = app_with_picker(Some(ps.clone())); + let s = &mut app.session; + s.execute("attdef", &json!({"tag": "NUMBER", "default": "", "at": [0, 0], "height": 1})).unwrap(); + let hs: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({"name": "TAG", "base": [0, 0], "handles": hs, "keep": "delete"})).unwrap(); + let h = + s.execute("insert", &json!({"name": "TAG", "at": [5, 5], "attribs": {"NUMBER": "1"}})).unwrap()["handle"].as_str().unwrap().to_string(); + let handle = draftcraft_engine::doc::Handle::parse_hex(&h).unwrap(); + + app.start("attout"); + assert_eq!(*asked.borrow(), vec!["Drawing1.txt".to_string()]); + assert!(app.session.prompt_text().contains("Select objects"), "{}", app.session.prompt_text()); + app.session.input(draftcraft_engine::Input::Pick(vec![handle])).unwrap(); + app.session.input(draftcraft_engine::Input::Enter).unwrap(); + let text = std::fs::read_to_string(&path).unwrap(); + assert!(text.contains(&format!("'{h}\tTAG\t1")), "{text}"); + + // ATTIN's picker is the file picker; without one, the engine asks on the command line. + std::fs::write(&path, text.replace("\tTAG\t1", "\tTAG\t2")).unwrap(); + app.cmdline("attin"); + assert!(app.session.prompt_text().contains("input file name"), "{}", app.session.prompt_text()); + app.cmdline(&ps); + assert!(app.session.running.is_none()); + let r = app.run("attout", json!({})).unwrap(); + assert!(r["text"].as_str().unwrap().contains(&format!("'{h}\tTAG\t2")), "{r}"); + assert_eq!(asked.borrow().len(), 1, "JSON calls open no dialog"); + let _ = std::fs::remove_file(&path); + } + #[test] fn cancelled_export_writes_nothing() { let (mut app, asked) = app_with_picker(None); diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 91d4951a..3c4aae02 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -121,8 +121,14 @@ const LEADER_MORE: &[Tool] = &[ (Icon::MLeader, "mleadercollect", "Collect"), ]; const INSERT_MORE: &[Tool] = &[(Icon::Insert, "insert", "Insert"), (Icon::Blocks, "ui.dialog.blocks", "Blocks Palette")]; -const ATT_MORE: &[Tool] = - &[(Icon::AttDef, "attedit", "Single"), (Icon::List, "battman", "Block Attribute Manager"), (Icon::Redo, "attsync", "Synchronize")]; +const ATT_MORE: &[Tool] = &[ + (Icon::AttDef, "attedit", "Single"), + (Icon::List, "battman", "Block Attribute Manager"), + (Icon::Redo, "attsync", "Synchronize"), + SEP, + (Icon::AttOut, "attout", "Export Attributes"), + (Icon::AttIn, "attin", "Import Attributes"), +]; const MEASURE_MORE: &[Tool] = &[ (Icon::Distance, "dist", "Distance"), (Icon::DimRadius, "radius.measure", "Radius"), @@ -646,11 +652,14 @@ pub(crate) const TABS: &[RibbonTab] = &[ panels: &[ RibbonPanel { title: "Blocks", - cols: &[Small(&[ - b(Icon::Explode, "burst", "Explode Attributes"), - b(Icon::Blocks, "blockreplace", "Replace Block"), - b(Icon::Text, "attdisp", "Attribute Display"), - ])], + cols: &[ + Small(&[ + b(Icon::Explode, "burst", "Explode Attributes"), + b(Icon::Blocks, "blockreplace", "Replace Block"), + b(Icon::Text, "attdisp", "Attribute Display"), + ]), + Small(&[b(Icon::AttOut, "attout", "Export Attributes"), b(Icon::AttIn, "attin", "Import Attributes")]), + ], }, RibbonPanel { title: "Text",