diff --git a/contributors/people.toml b/contributors/people.toml index cde01f9329..e5aad34867 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -106,6 +106,10 @@ sync_github_name = true [people.GULERTOLGA] sync_github_name = true +[people.Obtrusive8276] +display_name = "Nicopicks" +sync_github_name = false + [people.Tyler-Chiriboga] real_name = "Tyler Chiriboga" sync_github_name = true diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index f16a16fe7c..cb9d7cadce 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -34,6 +34,7 @@ mod overkill; mod pline_opts; pub mod plotters; mod props; +pub use blocks::library::{clear_library_cache, list_library, read_library_file}; pub use draw2::breakline::BreaklineOptions; pub use props::MatchProps; pub(crate) use props::UNIT_RANGES; diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index efea47962a..91295de66b 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -44,6 +44,10 @@ pub fn specs() -> Vec { .alias(&["i", "-insert", "ddinsert"]) .params("{name (\"*NAME\": exploded), file?: DXF/DWG path (defines or redefines block `name`, default the file name, from its model space; base point $INSBASE), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y] (block coordinates), attribs?: {TAG: value}, explode?: bool}") .interactive(|_| Ok(Box::new(InsertM::default()))), + CommandSpec::new("blockspalette", "Blocks Palette", run_blockspalette) + .params("{references?: bool (default true; counting reads every object)} → {blocks: [{name, description, references?}], truncated} (the app opens the Blocks palette instead)") + .enabled(has_doc) + .noundo(), CommandSpec::new("minsert", "Multiple Insert", run_minsert) .params("{name, file?: DXF/DWG path (as INSERT), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y], attribs?: {TAG: value}, rows?: 1..32767 (default 1), columns?: 1..32767 (default 1), rowSpacing?, columnSpacing? (along the reference's own axes, not scaled with it)}") .interactive(|_| Ok(Box::new(InsertM { minsert: true, ..InsertM::default() }))), @@ -92,6 +96,7 @@ pub fn specs() -> Vec { .into_iter() .chain(attribs::attdisp_menu_specs()) .chain(xref::specs()) + .chain(library::specs()) .chain(refedit::specs()) .chain(xclip::specs()) .chain(bedit::specs()) @@ -113,6 +118,15 @@ fn referenced_block(e: &Entity) -> Option { } } +/// The attributes an object carries: a block reference's, or those of a multileader's block content. +pub(crate) fn object_attribs(e: &Entity) -> &[Attrib] { + match &e.kind { + EntityKind::Insert(i) => &i.attribs, + EntityKind::MLeader(m) => m.block.as_ref().map_or(&[][..], |b| b.attribs.as_slice()), + _ => &[], + } +} + /// Whether any of `ents` refers to block `name`, directly or through nested block references, /// dimension blocks and multileader block content. pub(crate) fn references_block(d: &cadcraft_doc::Drawing, ents: &[Entity], name: &str) -> bool { @@ -346,6 +360,40 @@ fn run_block(s: &mut Session, p: &Value) -> Result { Ok(json!({ "block": name, "insert": r.map(|h| h.hex()) })) } +/// BLOCKSPALETTE as a JSON call: the drawing's own blocks (no anonymous, layout or xref blocks) +/// with their descriptions and how many objects draw each (block references, dimensions and +/// multileader block content). The app opens the palette instead. +fn run_blockspalette(s: &mut Session, p: &Value) -> Result { + let d = s.doc()?; + let counting = bool_or(p, "references", true); + let mut counts: std::collections::HashMap = std::collections::HashMap::new(); + if counting { + let mut count = |store: &cadcraft_doc::EntityStore| { + for e in store.iter() { + if let Some(block) = referenced_block(e) { + let n = counts.entry(block.to_ascii_lowercase()).or_insert(0); + *n = n.saturating_add(1); + } + } + }; + count(&d.model); + d.layouts.iter().for_each(|l| count(&l.entities)); + d.blocks.values().for_each(|b| count(&b.entities)); + } + let (blocks, truncated) = library::library_blocks(d); + let list: Vec = blocks + .iter() + .map(|b| { + let mut block = json!({ "name": b.name, "description": b.description }); + if counting { + block["references"] = json!(counts.get(&b.name.to_ascii_lowercase()).copied().unwrap_or(0)); + } + block + }) + .collect(); + Ok(json!({ "blocks": list, "truncated": truncated })) +} + fn run_insert(s: &mut Session, p: &Value) -> Result { insert_json(s, p, "insert", Grid::ONE) } @@ -601,6 +649,7 @@ impl BlockM { } mod insert_file; +pub(crate) mod library; pub(crate) mod xref; /// Where the command-line INSERT is in its prompt sequence. @@ -705,6 +754,9 @@ impl InsertM { if self.explode { insert_file::explode_insert(s, h)?; } + // Written here, not when the name is given: a cancelled INSERT leaves the drawing as + // it was, so it takes no undo step that would undo nothing visible. + s.doc_mut()?.header.set_str("INSNAME", &n); return Ok(Step::Done); } Ok(Step::Continue) @@ -760,13 +812,14 @@ impl InsertM { }) .collect() }; - s.doc_mut()?.header.set_str("INSNAME", &b.name); self.name = Some(b.name.clone()); self.stage = InsStage::Point; Ok(()) } - /// Define the block from a file, then choose it; a file that can't be read is reported. + /// Define the block from a file, then choose it; a file that can't be read is reported. The + /// definition comes before the insertion point and stays when INSERT is then cancelled, as in + /// AutoCAD 2027. fn choose_file(&mut self, s: &mut Session, f: &insert_file::FileRef) -> Result<()> { match f.define(s) { Ok(name) => self.choose(s, &name), diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index e39dc06bb9..4872bb0a4f 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -6,7 +6,7 @@ //! (names this drawing already has keep this drawing's definitions). The file is read through the //! host's io hooks like OPEN, so the engine stays I/O-agnostic. -use std::collections::BTreeMap; +use std::collections::{BTreeMap, BTreeSet}; use std::sync::Arc; use cadcraft_doc::{Block, Drawing, Entity, EntityKind, Handle}; @@ -14,7 +14,8 @@ use serde_json::{Value, json}; use super::super::file::io; use super::super::modify::explode_kind; -use super::{references_block, valid_block_name}; +use super::purge::{Kind, candidates, is_arrow_override, override_arrows, override_name, scan_reads_everything}; +use super::{referenced_block, references_block, valid_block_name}; use crate::cmd::{bad, str_param}; use crate::{EngineError, Result, Session}; @@ -37,7 +38,7 @@ impl FileRef { /// Read the file and (re)define its block. Returns the block's name. pub fn define(&self, s: &mut Session) -> Result { let src = read_drawing(&self.path)?; - define_from(s, &src, &self.name) + define_from(s, &src, &self.name, false) } } @@ -45,6 +46,11 @@ impl FileRef { /// path (it has a folder separator or a .dwg/.dxf extension) that isn't the name of a block. pub(super) fn file_ref(s: &Session, t: &str) -> Option { let t = t.trim(); + // A block of this drawing is that block, whatever its name looks like: a name read from a file + // must not pass for `name=path` and make INSERT read another file (CWE-74). + if s.doc().is_ok_and(|d| d.block(t).is_some()) { + return None; + } if let Some((name, path)) = t.split_once('=') { let name = name.trim(); let path = if path.trim().is_empty() { name } else { path.trim() }; @@ -52,7 +58,7 @@ pub(super) fn file_ref(s: &Session, t: &str) -> Option { } let lower = t.to_ascii_lowercase(); let pathlike = t.contains(['/', '\\']) || lower.ends_with(".dwg") || lower.ends_with(".dxf"); - if !pathlike || s.doc().is_ok_and(|d| d.block(t).is_some()) { + if !pathlike { return None; } Some(FileRef { name: stem(t), path: t.to_string(), explicit: false }) @@ -68,7 +74,7 @@ pub(super) fn stem(path: &str) -> String { } /// Read a drawing file through the io hooks; a path without extension tries .dwg, then .dxf. -fn read_drawing(path: &str) -> Result { +pub(super) fn read_drawing(path: &str) -> Result { let hooks = io().ok_or_else(|| bad("insert", "file formats are not available in this build"))?; let has_ext = stem(path) != path.rsplit(['/', '\\']).next().unwrap_or(path); let candidates = if has_ext { vec![path.to_string()] } else { vec![path.to_string(), format!("{path}.dwg"), format!("{path}.dxf")] }; @@ -93,18 +99,29 @@ fn read_file(_path: &str) -> Result> { } /// (Re)define block `name` from `src`'s model space with base point `$INSBASE`, adding the -/// layers, linetypes, styles and blocks of `src` this drawing doesn't have. Nothing changes when -/// the definition fails (an invalid name, or a block that would contain itself). -fn define_from(s: &mut Session, src: &Drawing, name: &str) -> Result { +/// layers, linetypes, styles and blocks of `src` this drawing doesn't have. With `only_needed` +/// the layers, linetypes and styles that nothing uses are left out again, as when a block is +/// taken from a library drawing: only what the block needs comes along. Nothing changes when the +/// definition fails (an invalid name, or a block that would contain itself). +pub(super) fn define_from(s: &mut Session, src: &Drawing, name: &str, only_needed: bool) -> Result { if !valid_block_name(name) { return Err(bad("insert", format!("\"{name}\" is not a valid block name"))); } let mut d = s.doc()?.clone(); + let before = TableNames::of(&d); // Redefining keeps the existing definition's name (block names are case-insensitive). let name = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(name)).cloned().unwrap_or_else(|| name.to_string()); + let own_dim_styles = names_of(&d, Kind::Dimstyles); merge_tables(&mut d, src); - let renames = crate::cmd::merge::block_renames(&d, src, Some(&name)); - for (from, to) in &renames { + let mut renames = crate::cmd::merge::block_renames(&d, src, Some(&name)); + if only_needed { + // The other blocks of the file are not copied at all. + let need = needed_blocks(src); + renames.retain(|from, _| need.contains(&from.to_ascii_uppercase())); + } + let renames = Renames::new(renames); + rename_style_arrows(&mut d, &own_dim_styles, &renames); + for (from, to) in &renames.exact { let Some(b) = src.blocks.get(from) else { continue }; let mut nb = (**b).clone(); nb.name = to.clone(); @@ -130,10 +147,129 @@ fn define_from(s: &mut Session, src: &Drawing, name: &str) -> Result { b.entities.push(e); } d.blocks.insert(name.clone(), Arc::new(b)); + if only_needed { + drop_unused_new(&mut d, &before, &name); + } *s.doc_mut()? = d; Ok(name) } +/// The tables a drawing merge adds to, in an order where removing the unused entries of one +/// frees the next (blocks free layers, layers free linetypes, dimension styles free text styles). +const MERGED: [Kind; 8] = + [Kind::Blocks, Kind::Dimstyles, Kind::MleaderStyles, Kind::MlineStyles, Kind::TableStyles, Kind::Layers, Kind::Linetypes, Kind::TextStyles]; + +/// The names (lower case) in one of those tables. +fn names_of(d: &Drawing, kind: Kind) -> BTreeSet { + let lower = |it: &mut dyn Iterator| it.map(|n| n.to_ascii_lowercase()).collect::>(); + match kind { + Kind::Blocks => lower(&mut d.blocks.keys()), + Kind::Dimstyles => lower(&mut d.dim_styles.iter().map(|t| &t.name)), + Kind::MleaderStyles => lower(&mut d.mleader_styles.iter().map(|t| &t.name)), + Kind::MlineStyles => lower(&mut d.mline_styles.iter().map(|t| &t.name)), + Kind::TableStyles => lower(&mut d.table_styles.iter().map(|t| &t.name)), + Kind::Layers => lower(&mut d.layers.iter().map(|t| &t.name)), + Kind::Linetypes => lower(&mut d.linetypes.iter().map(|t| &t.name)), + Kind::TextStyles => lower(&mut d.text_styles.iter().map(|t| &t.name)), + _ => BTreeSet::new(), + } +} + +/// The names in the merged tables, by kind. +struct TableNames(Vec<(Kind, BTreeSet)>); + +impl TableNames { + fn of(d: &Drawing) -> Self { + TableNames(MERGED.iter().map(|k| (*k, names_of(d, *k))).collect()) + } +} + +/// Upper-case names of the blocks `roots` and every block they need, through nested references, +/// dimension blocks, multileader block content and dimension arrowheads. +fn reachable(d: &Drawing, roots: Vec) -> BTreeSet { + let mut seen = BTreeSet::new(); + let mut todo = roots; + // Each block is walked once, so this ends, cycles included. + while let Some(n) = todo.pop() { + if !seen.insert(n.to_ascii_uppercase()) { + continue; + } + let Some(b) = d.block(&n) else { continue }; + for e in b.entities.iter() { + todo.extend(referenced_block(e)); + if let EntityKind::Dimension(dm) = &e.kind { + todo.extend(override_arrows(dm)); + } + } + } + seen +} + +/// Upper-case names of the blocks the model space of `src` needs: the ones it refers to, what +/// those need, and the arrowheads of its dimension styles. +fn needed_blocks(src: &Drawing) -> BTreeSet { + let mut roots: Vec = Vec::new(); + for e in src.model.iter() { + roots.extend(referenced_block(e)); + if let EntityKind::Dimension(dm) = &e.kind { + roots.extend(override_arrows(dm)); + } + } + for st in &src.dim_styles { + let arrows = [&st.arrow_block, &st.arrow_block1, &st.arrow_block2, &st.leader_arrow_block]; + roots.extend(arrows.into_iter().map(|n| n.trim().to_string()).filter(|n| !n.is_empty())); + } + reachable(src, roots) +} + +/// Remove the blocks, layers, linetypes and styles that were not in the drawing `before` and that +/// nothing uses (PURGE's scan), in an order where removing one frees the next. `keep` is the +/// block just defined: nothing refers to it yet, so it and the blocks it needs stay. Nothing goes +/// from a drawing too big for that scan: an unused entry stays, but a used one would be lost. +fn drop_unused_new(d: &mut Drawing, before: &TableNames, keep: &str) { + if !scan_reads_everything(d) { + return; + } + // Removing a dimension style frees its arrowhead block, which an earlier table already + // scanned: scan again until a pass removes nothing (a chain is never longer than the tables). + for _ in 0..MERGED.len() { + if !drop_unused_pass(d, before, keep) { + break; + } + } +} + +/// One scan of the merged tables; `true` when it removed something. +fn drop_unused_pass(d: &mut Drawing, before: &TableNames, keep: &str) -> bool { + let mut removed = false; + for (kind, old) in &before.0 { + // Nothing was added to this table: nothing to scan for. + if names_of(d, *kind).is_subset(old) { + continue; + } + let keep_blocks = if matches!(kind, Kind::Blocks) { reachable(d, vec![keep.to_string()]) } else { BTreeSet::new() }; + let fresh: BTreeSet = candidates(d, *kind) + .into_iter() + .filter(|n| !old.contains(&n.to_ascii_lowercase()) && !keep_blocks.contains(&n.to_ascii_uppercase())) + .map(|n| n.to_ascii_lowercase()) + .collect(); + let gone = |name: &str| fresh.contains(&name.to_ascii_lowercase()); + removed |= !fresh.is_empty(); + match kind { + Kind::Blocks => d.blocks.retain(|k, _| !gone(k)), + Kind::Dimstyles => d.dim_styles.retain(|t| !gone(&t.name)), + Kind::MleaderStyles => d.mleader_styles.retain(|t| !gone(&t.name)), + Kind::MlineStyles => d.mline_styles.retain(|t| !gone(&t.name)), + Kind::TableStyles => d.table_styles.retain(|t| !gone(&t.name)), + Kind::Layers => d.layers.retain(|t| !gone(&t.name)), + Kind::Linetypes => d.linetypes.retain(|t| !gone(&t.name)), + Kind::TextStyles => d.text_styles.retain(|t| !gone(&t.name)), + _ => {} + } + } + removed +} + /// Add the source's layers, linetypes and styles that this drawing doesn't have (a name that /// exists keeps this drawing's definition). fn merge_tables(d: &mut Drawing, src: &Drawing) { @@ -147,9 +283,42 @@ fn merge_tables(d: &mut Drawing, src: &Drawing) { merge(&mut d.mline_styles, &src.mline_styles, |t| &t.name); } +/// The names the copied source blocks take, found as `Drawing::block` finds a block: a reference +/// may spell a name differently from its definition. +struct Renames { + exact: BTreeMap, + upper: BTreeMap, +} + +impl Renames { + fn new(exact: BTreeMap) -> Self { + let mut upper = BTreeMap::new(); + for (from, to) in &exact { + upper.entry(from.to_ascii_uppercase()).or_insert_with(|| to.clone()); + } + Renames { exact, upper } + } + + fn get(&self, name: &str) -> Option<&String> { + self.exact.get(name).or_else(|| self.upper.get(&name.to_ascii_uppercase())) + } +} + +/// Point the dimension styles the source brought at their renamed arrowhead blocks. The styles +/// this drawing already had (`own`) name this drawing's blocks. +fn rename_style_arrows(d: &mut Drawing, own: &BTreeSet, renames: &Renames) { + for st in d.dim_styles.iter_mut().filter(|t| !own.contains(&t.name.to_ascii_lowercase())) { + for arrow in [&mut st.arrow_block, &mut st.arrow_block1, &mut st.arrow_block2, &mut st.leader_arrow_block] { + if let Some(n) = renames.get(arrow.trim()) { + arrow.clone_from(n); + } + } + } +} + /// A copy of a source entity for this drawing: a fresh handle, block references renamed, and /// links to other source objects (associative dimension points) dropped. -fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &BTreeMap) -> Entity { +fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &Renames) -> Entity { let mut e = e.clone(); let old = e.handle; e.handle = d.new_handle(); @@ -174,6 +343,23 @@ fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &BTreeMap { + if let Some(b) = &mut m.block + && let Some(n) = renames.get(&b.block) + { + b.block = n.clone(); + } } _ => {} } @@ -234,6 +420,78 @@ mod tests { assert!(file_ref(&s, "BOLT").is_none()); } + /// A block holding very many references still reaches every block it needs. + #[test] + fn a_block_of_many_references_keeps_all_it_needs() { + let reference = |handle: u64, block: &str| { + let insert: cadcraft_doc::Insert = serde_json::from_value(json!({ "block": block, "insert": [0, 0, 0] })).unwrap(); + Entity::new(Handle(handle), EntityKind::Insert(insert)) + }; + let mut big = Block::new("Big"); + big.entities.push(reference(0x100, "Deep")); + for i in 0..100_001 { + big.entities.push(reference(0x200 + i, "Leaf")); + } + let mut d = Drawing::default(); + d.blocks.insert("Big".into(), Arc::new(big)); + d.blocks.insert("Deep".into(), Arc::new(Block::new("Deep"))); + d.blocks.insert("Leaf".into(), Arc::new(Block::new("Leaf"))); + assert!(reachable(&d, vec!["Big".into()]).contains("DEEP")); + } + + /// A drawing with very many references does not lose the arrowhead of a merged dimension + /// style: the arrowheads are the last thing PURGE's walk looks at. + #[test] + fn many_references_keep_a_merged_arrowhead() { + let mut d = Drawing::new_metric(); + d.blocks.insert("Leaf".into(), Arc::new(Block::new("Leaf"))); + for i in 0..100_001 { + let insert: cadcraft_doc::Insert = serde_json::from_value(json!({ "block": "Leaf", "insert": [0, 0, 0] })).unwrap(); + d.model.push(Entity::new(Handle(0x200 + i), EntityKind::Insert(insert))); + } + let before = TableNames::of(&d); + d.blocks.insert("Tip".into(), Arc::new(Block::new("Tip"))); + d.dim_styles.push(cadcraft_doc::DimStyle { name: "Late".into(), arrow_block: "Tip".into(), ..Default::default() }); + d.header.set_str("DIMSTYLE", "Late"); + d.blocks.insert("Merged".into(), Arc::new(Block::new("Merged"))); + drop_unused_new(&mut d, &before, "Merged"); + assert!(d.block("Tip").is_some()); + } + + /// Past the purge scan's limit nothing is called unused: a merged block's dimension style and + /// layer stay even when the scan never reaches its objects. + #[test] + fn a_drawing_too_big_for_the_scan_keeps_what_was_merged() { + let mut s = Session::new(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap(); + let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone(); + dim.common.layer = "Late".into(); + if let EntityKind::Dimension(dm) = &mut dim.kind { + dm.style = "Late".into(); + } + // One definition under many names: millions of objects for the scan, thousands in memory. + let mut filler = Block::new("Filler"); + for i in 0..10_000 { + filler.entities.push(Entity::new(Handle(0x1000 + i), dim.kind.clone())); + } + let filler = Arc::new(filler); + let mut d = Drawing::new_metric(); + for i in 0..501 { + d.blocks.insert(format!("F{i:03}"), filler.clone()); + } + let before = TableNames::of(&d); + assert!(!scan_reads_everything(&d)); + d.layers.push(cadcraft_doc::Layer { name: "Late".into(), ..Default::default() }); + d.dim_styles.push(cadcraft_doc::DimStyle { name: "Late".into(), ..Default::default() }); + // Sorted after every filler, so past the limit. + let mut merged = Block::new("Z"); + merged.entities.push(dim); + d.blocks.insert("Z".into(), Arc::new(merged)); + drop_unused_new(&mut d, &before, "Z"); + assert!(d.layers.iter().any(|l| l.name == "Late")); + assert!(d.dim_styles.iter().any(|t| t.name == "Late")); + } + #[test] fn inserted_file_brings_its_mline_styles() { let mut src = Drawing::default(); @@ -246,4 +504,211 @@ mod tests { merge_tables(&mut d, &src); assert_eq!(d.mline_styles.len(), before); } + + /// A block reference, for the fixtures below. + fn reference(handle: u64, block: &str) -> Entity { + let insert: cadcraft_doc::Insert = serde_json::from_value(json!({ "block": block, "insert": [0, 0, 0] })).unwrap(); + Entity::new(Handle(handle), EntityKind::Insert(insert)) + } + + /// An anonymous block `*U1` that its description tells apart. + fn anonymous(description: &str) -> Arc { + let mut b = Block::new("*U1"); + b.description = description.into(); + Arc::new(b) + } + + /// Takes `model`, whose `*U1` is the file's, into a drawing with a `*U1` of its own, and says + /// which of the two the one object of block "Part" refers to. + fn colliding_block_after_import(model: Entity) -> String { + let mut src = Drawing::new_metric(); + src.blocks.insert("*U1".into(), anonymous("from the file")); + src.model.push(model); + let mut s = Session::new(); + s.doc_mut().unwrap().blocks.insert("*U1".into(), anonymous("from the drawing")); + define_from(&mut s, &src, "Part", true).unwrap(); + let d = s.doc().unwrap(); + let part = d.block("Part").unwrap(); + let to = part.entities.iter().next().and_then(|e| referenced_block(e)).unwrap(); + d.block(&to).unwrap().description.clone() + } + + /// Block names are case-insensitive, so `*u1` is the file's `*U1` and takes its new name. + #[test] + fn a_renamed_block_is_found_whatever_the_case_of_the_reference() { + assert_eq!(colliding_block_after_import(reference(0x500, "*u1")), "from the file"); + } + + /// The block content of a multileader takes the new name like any other reference. + #[test] + fn a_multileader_follows_its_renamed_block() { + let EntityKind::Insert(content) = reference(0x500, "*U1").kind else { return }; + let mut m: cadcraft_doc::MLeader = + serde_json::from_value(json!({ "leaders": [], "landing": [0, 0, 0], "dogleg": 0.0, "text": null })).unwrap(); + m.block = Some(content); + assert_eq!(colliding_block_after_import(Entity::new(Handle(0x501), EntityKind::MLeader(m))), "from the file"); + } + + /// An arrowhead override given as a number names its block: the block comes along, and the + /// override is left as given when the block keeps its name. + #[test] + fn a_numeric_arrowhead_override_brings_its_block() { + let mut s = Session::new(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap(); + let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone(); + if let EntityKind::Dimension(dm) = &mut dim.kind { + dm.overrides.insert("DIMBLK1".into(), json!(45)); + } + let mut src = Drawing::new_metric(); + src.blocks.insert("45".into(), Arc::new(Block::new("45"))); + src.model.push(dim); + let mut t = Session::new(); + define_from(&mut t, &src, "Part", true).unwrap(); + let d = t.doc().unwrap(); + assert!(d.block("45").is_some()); + let e = d.block("Part").unwrap().entities.iter().next().unwrap().clone(); + let EntityKind::Dimension(dm) = &e.kind else { panic!("not a dimension") }; + assert_eq!(dm.overrides["DIMBLK1"], json!(45)); + } + + /// Arrowheads are references too: a dimension style that came along and a dimension's override + /// follow the renamed block, and a style this drawing already had keeps its own. + #[test] + fn arrowheads_follow_a_renamed_block() { + let mut s = Session::new(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap(); + let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone(); + if let EntityKind::Dimension(dm) = &mut dim.kind { + dm.style = "Came".into(); + dm.overrides.insert("DIMBLK1".into(), json!("*U1")); + } + let style = |name: &str| cadcraft_doc::DimStyle { name: name.into(), arrow_block: "*U1".into(), ..Default::default() }; + let mut src = Drawing::new_metric(); + src.blocks.insert("*U1".into(), anonymous("from the file")); + src.dim_styles.extend([style("Came"), style("Own")]); + src.model.push(dim); + let mut t = Session::new(); + let d = t.doc_mut().unwrap(); + d.blocks.insert("*U1".into(), anonymous("from the drawing")); + d.dim_styles.push(style("Own")); + define_from(&mut t, &src, "Part", true).unwrap(); + + let d = t.doc().unwrap(); + let of = |name: &str| d.block(name).unwrap().description.clone(); + let arrow = |name: &str| d.dim_styles.iter().find(|st| st.name == name).unwrap().arrow_block.clone(); + assert_eq!(of(&arrow("Came")), "from the file"); + assert_eq!(of(&arrow("Own")), "from the drawing"); + let e = d.block("Part").unwrap().entities.iter().next().unwrap().clone(); + let EntityKind::Dimension(dm) = &e.kind else { return }; + assert_eq!(of(dm.overrides["DIMBLK1"].as_str().unwrap()), "from the file"); + } + + /// What the objects of an imported block name comes along, directly or through another table: + /// a leader's dimension style, a dimension's text style override, the text style in a linetype, + /// an attribute's layer and multiline text style, here on a block reference and on a + /// multileader's block content. What nothing names stays out. + #[test] + fn an_import_keeps_every_style_and_layer_its_objects_name() { + let mut s = Session::new(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap(); + let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone(); + if let EntityKind::Dimension(dm) = &mut dim.kind { + dm.overrides.insert("DIMTXSTY".into(), json!("InOverride")); + } + let attrib = |style: &str, layer: &str| { + let mut a: cadcraft_doc::Attrib = serde_json::from_value(json!({ + "tag": "A", + "text": { "insert": [0, 0, 0], "height": 1.0, "value": "1" }, + "multiline": { "mtext": { "insert": [0, 0, 0], "height": 1.0, "contents": "1", "style": style }, "readAs": "1" }, + })) + .unwrap(); + a.props.layer = Some(layer.into()); + a + }; + let mut placed = reference(0x500, "Inner"); + if let EntityKind::Insert(i) = &mut placed.kind { + i.attribs.push(attrib("InAttribute", "OnAttribute")); + } + let EntityKind::Insert(mut content) = reference(0x501, "Inner").kind else { return }; + content.attribs.push(attrib("InContent", "OnContent")); + let mut multileader: cadcraft_doc::MLeader = + serde_json::from_value(json!({ "leaders": [], "landing": [0, 0, 0], "dogleg": 0.0, "text": null })).unwrap(); + multileader.block = Some(content); + let leader: cadcraft_doc::Leader = serde_json::from_value(json!({ "vertices": [], "style": "ForLeader" })).unwrap(); + let line = cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(1.0, 0.0, 0.0) }; + let mut line = Entity::new(Handle(0x502), EntityKind::Line(line)); + line.common.linetype = "WithText".into(); + + let mut src = Drawing::new_metric(); + src.blocks.insert("Inner".into(), Arc::new(Block::new("Inner"))); + for name in ["InOverride", "InAttribute", "InContent", "InLinetype", "Spare"] { + let mut t = src.text_styles[0].clone(); + t.name = name.into(); + src.text_styles.push(t); + } + for name in ["OnAttribute", "OnContent", "Unused"] { + src.layers.push(cadcraft_doc::Layer { name: name.into(), ..Default::default() }); + } + let dash = cadcraft_doc::DashElement { style: Some("InLinetype".into()), ..cadcraft_doc::DashElement::dash(1.0) }; + src.linetypes.push(cadcraft_doc::Linetype { name: "WithText".into(), description: String::new(), pattern: vec![dash] }); + src.dim_styles.push(cadcraft_doc::DimStyle { name: "ForLeader".into(), ..Default::default() }); + src.model.push(dim); + src.model.push(placed); + src.model.push(Entity::new(Handle(0x503), EntityKind::MLeader(multileader))); + src.model.push(Entity::new(Handle(0x504), EntityKind::Leader(leader))); + src.model.push(line); + let mut t = Session::new(); + define_from(&mut t, &src, "Part", true).unwrap(); + + let d = t.doc().unwrap(); + let styles: Vec<&str> = d.text_styles.iter().map(|t| t.name.as_str()).collect(); + for name in ["InOverride", "InAttribute", "InContent", "InLinetype"] { + assert!(styles.contains(&name), "{name}: {styles:?}"); + } + assert!(!styles.contains(&"Spare"), "{styles:?}"); + let layers: Vec<&str> = d.layers.iter().map(|l| l.name.as_str()).collect(); + assert!(layers.contains(&"OnAttribute") && layers.contains(&"OnContent"), "{layers:?}"); + assert!(!layers.contains(&"Unused"), "{layers:?}"); + assert!(d.dim_styles.iter().any(|st| st.name == "ForLeader")); + } + + /// The text style of a table style's cell style is in use. + #[test] + fn a_table_style_keeps_its_cell_styles_text_style() { + let mut d = Drawing::new_metric(); + let mut t = d.text_styles[0].clone(); + t.name = "InCell".into(); + d.text_styles.push(t); + let mut cell = cadcraft_doc::TableStyle::default().cell_style("Data"); + cell.text_style = "InCell".into(); + d.table_styles[0].cell_styles.push(cell); + assert!(!candidates(&d, Kind::TextStyles).iter().any(|n| n == "InCell")); + } + + /// A linetype of the file stays when a dimension style that came along names it, and stays out + /// when only a style that did not come along does. + #[test] + fn a_linetype_follows_the_dimension_style_that_names_it() { + let mut s = Session::new(); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap(); + let mut dim = (**s.doc().unwrap().model.iter().next().unwrap()).clone(); + if let EntityKind::Dimension(dm) = &mut dim.kind { + dm.style = "Used".into(); + } + let mut src = Drawing::new_metric(); + for name in ["Kept", "Left"] { + let mut lt = src.linetypes[0].clone(); + lt.name = name.into(); + src.linetypes.push(lt); + } + src.dim_styles.push(cadcraft_doc::DimStyle { name: "Used".into(), dim_linetype: "Kept".into(), ..Default::default() }); + src.dim_styles.push(cadcraft_doc::DimStyle { name: "Spare".into(), ext_linetype1: "Left".into(), ..Default::default() }); + src.model.push(dim); + let mut t = Session::new(); + define_from(&mut t, &src, "Part", true).unwrap(); + let d = t.doc().unwrap(); + assert!(d.linetypes.iter().any(|l| l.name == "Kept")); + assert!(!d.dim_styles.iter().any(|st| st.name == "Spare")); + assert!(!d.linetypes.iter().any(|l| l.name == "Left")); + } } diff --git a/crates/engine/src/cmd/blocks/library.rs b/crates/engine/src/cmd/blocks/library.rs new file mode 100644 index 0000000000..b7d7ba0017 --- /dev/null +++ b/crates/engine/src/cmd/blocks/library.rs @@ -0,0 +1,378 @@ +//! Block libraries for the Blocks palette: a folder of drawings or a single drawing file whose +//! blocks can be placed in the current drawing. +//! +//! BLOCKLIBRARY lists what a library holds, BLOCKLIBRARIES keeps the list of libraries the user +//! added (in the settings folder; in memory where there is none), and BLOCKLIBIMPORT defines a +//! library block in the current drawing so that INSERT can place it. Files are read through the +//! host's io hooks like OPEN, so the engine stays I/O-agnostic. + +use std::path::Path; +#[cfg(not(target_arch = "wasm32"))] +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::SystemTime; + +use cadcraft_doc::Drawing; +use serde_json::{Value, json}; + +use super::insert_file::{define_from, read_drawing, stem}; +use super::valid_block_name; +use crate::cmd::{CommandSpec, always, bad, has_doc, str_param}; +use crate::{Result, Session}; + +/// Most drawings one folder library lists. +#[cfg(not(target_arch = "wasm32"))] +const MAX_FILES: usize = 2000; +/// Most directory entries looked at in a folder library. +#[cfg(not(target_arch = "wasm32"))] +const MAX_SCANNED: usize = 100_000; +/// Most blocks a palette listing holds: the rest of a hostile file's table is left out. +const MAX_LISTED: usize = 10_000; +/// Most libraries the list keeps. +const MAX_LIBRARIES: usize = 64; +/// The longest library path kept. +const MAX_PATH_BYTES: usize = 4096; +/// The file in the settings folder that keeps the library list, and its largest size. +#[cfg(not(target_arch = "wasm32"))] +const LIST_FILE: &str = "block-libraries.json"; +#[cfg(not(target_arch = "wasm32"))] +const MAX_LIST_BYTES: usize = 256 << 10; + +/// How many parsed library drawings stay in memory. +const CACHE_MAX: usize = 4; + +/// A library drawing already read, and the file's size and time then. +struct Cached { + path: String, + stamp: (u64, Option), + drawing: Arc, +} + +static CACHE: Mutex> = Mutex::new(Vec::new()); + +/// Forget the library drawings read so far: the next read parses each file again, even one whose +/// size and time did not change (Refresh in the palette). +pub fn clear_library_cache() { + if let Ok(mut cache) = CACHE.lock() { + cache.clear(); + } +} + +/// The file's size and modification time; `None` where it cannot be told (nothing is kept then). +fn stamp(path: &str) -> Option<(u64, Option)> { + if cfg!(target_arch = "wasm32") { + return None; + } + std::fs::metadata(path).ok().filter(std::fs::Metadata::is_file).map(|m| (m.len(), m.modified().ok())) +} + +/// A library drawing, read once and kept while the file is as it was: placing a block must not +/// parse the whole file again. +fn cached_drawing(path: &str) -> Result> { + // The reader sniffs the bytes, so a DXF named `part.bin` would load: the contract is DWG/DXF by name. + if !is_drawing(Path::new(path)) { + return Err(bad("blocklibrary", format!("{path}: expected a DWG or DXF file"))); + } + let now = stamp(path); + if let Some(now) = now + && let Ok(cache) = CACHE.lock() + && let Some(hit) = cache.iter().find(|c| c.path == path && c.stamp == now) + { + return Ok(hit.drawing.clone()); + } + // The palette reads previews outside a command, so a parser panic stops here too. + let read = std::panic::catch_unwind(|| read_drawing(path)); + let drawing = Arc::new(read.unwrap_or_else(|p| Err(bad("blocklibrary", format!("{path}: {}", crate::guard::message(p.as_ref())))))?); + if let Some(now) = now + && let Ok(mut cache) = CACHE.lock() + { + cache.retain(|c| c.path != path); + cache.push(Cached { path: path.to_string(), stamp: now, drawing: drawing.clone() }); + while cache.len() > CACHE_MAX { + cache.remove(0); + } + } + Ok(drawing) +} + +/// The list where no settings folder keeps it, and the copy read from it. +static MEMORY: Mutex> = Mutex::new(Vec::new()); +/// The last write of the list failed: the copy in memory is newer than the file. +static UNSAVED: AtomicBool = AtomicBool::new(false); + +/// The commands the Blocks palette uses: BLOCKLIBRARY, BLOCKLIBIMPORT and BLOCKLIBRARIES. +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("blocklibrary", "Block Library", run_library) + .params("{path: a folder of DWG/DXF files, or one such file} → {kind: \"folder\", path, files: [{name, file}], truncated} | {kind: \"file\", path, blocks: [{name, description}], truncated}") + .enabled(always) + .noundo(), + CommandSpec::new("blocklibraries", "Block Libraries", run_libraries) + .params("{op?: \"list\" (default)|\"add\"|\"remove\", path? (add, remove)} → {libraries: [path], path? (add: the entry as kept)}") + .enabled(always) + .noundo(), + CommandSpec::new("blocklibimport", "Import Library Block", run_import) + .params("{path: DWG/DXF file, block?: the block to take from it (default: the whole drawing), name?: the block to define (default: `block`, else the file name; never one the drawing already has)} → {name}") + .enabled(has_doc), + ] +} + +/// A drawing file by its extension. +fn is_drawing(p: &Path) -> bool { + p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("dwg") || e.eq_ignore_ascii_case("dxf")) +} + +/// The drawings in a folder, by name: `(block name, full path)`, and whether some were left out. +fn folder_files(dir: &Path) -> Result<(Vec<(String, String)>, bool)> { + #[cfg(not(target_arch = "wasm32"))] + { + let rd = std::fs::read_dir(dir).map_err(|e| bad("blocklibrary", format!("{}: {e}", dir.display())))?; + let entries: Vec = rd.filter_map(|e| e.ok()).map(|e| e.path()).take(MAX_SCANNED.saturating_add(1)).collect(); + let mut truncated = entries.len() > MAX_SCANNED; + let mut out: Vec<(String, String)> = entries + .iter() + .take(MAX_SCANNED) + .filter(|p| is_drawing(p) && p.is_file()) + .filter_map(|p| p.to_str().map(|s| (stem(s), s.to_string()))) + .collect(); + out.sort_by_key(|(n, _)| n.to_ascii_lowercase()); + truncated |= out.len() > MAX_FILES; + out.truncate(MAX_FILES); + Ok((out, truncated)) + } + #[cfg(target_arch = "wasm32")] + { + let _ = dir; + Err(bad("blocklibrary", "paths are not available on the web")) + } +} + +/// Whether two library paths name the same place: letter case counts except where the file +/// system ignores it (Windows, and macOS by default). +fn same_path(a: &str, b: &str) -> bool { + if cfg!(any(windows, target_os = "macos")) { a.eq_ignore_ascii_case(b) } else { a == b } +} + +/// Whether `path` is a folder. +fn is_folder(path: &str) -> bool { + !cfg!(target_arch = "wasm32") && Path::new(path).is_dir() +} + +/// The first `MAX_LISTED` named blocks of a library drawing by name (no generated or layout +/// blocks, no xrefs), and whether there were more. The names are made lower case once, and only +/// the blocks that are kept are sorted. +pub(crate) fn library_blocks(d: &Drawing) -> (Vec<&std::sync::Arc>, bool) { + let mut keyed: Vec<(String, &std::sync::Arc)> = d + .blocks + .values() + .filter(|b| !b.anonymous && b.xref_path.is_none() && !b.name.starts_with('*') && !b.name.contains('|')) + .map(|b| (b.name.to_ascii_lowercase(), b)) + .collect(); + let truncated = keyed.len() > MAX_LISTED; + if truncated { + keyed.select_nth_unstable_by(MAX_LISTED, |a, b| a.0.cmp(&b.0)); + keyed.truncate(MAX_LISTED); + } + keyed.sort_by(|a, b| a.0.cmp(&b.0)); + (keyed.into_iter().map(|(_, b)| b).collect(), truncated) +} + +/// Read a library file (for the palette's previews too), kept until the file changes. +pub fn read_library_file(path: &str) -> Result> { + cached_drawing(path) +} + +/// What BLOCKLIBRARY answers for `path`. It needs no session, so the palette reads big drawings +/// and slow folders on a worker thread. +pub fn list_library(path: &str) -> Result { + if is_folder(path) { + let (files, truncated) = folder_files(Path::new(path))?; + let list: Vec = files.iter().map(|(name, file)| json!({ "name": name, "file": file })).collect(); + return Ok(json!({ "kind": "folder", "path": path, "files": list, "truncated": truncated })); + } + let d = cached_drawing(path)?; + let (blocks, truncated) = library_blocks(&d); + let list: Vec = blocks.iter().map(|b| json!({ "name": b.name, "description": b.description })).collect(); + Ok(json!({ "kind": "file", "path": path, "blocks": list, "truncated": truncated })) +} + +/// BLOCKLIBRARY: list a folder's drawings or a drawing's blocks. +fn run_library(_s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path").map(str::trim).filter(|s| !s.is_empty()).ok_or_else(|| bad("blocklibrary", "`path` is required"))?; + list_library(path) +} + +/// BLOCKLIBIMPORT: define a library block (or a whole drawing) in the current drawing, under a +/// name it does not have yet. +fn run_import(s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path").map(str::trim).filter(|s| !s.is_empty()).ok_or_else(|| bad("blocklibimport", "`path` is required"))?; + let block = str_param(p, "block").map(str::trim).filter(|s| !s.is_empty()); + // A whole drawing is named after its file; a block of it after itself. + let name = str_param(p, "name") + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| block.map_or_else(|| stem(path), str::to_string)); + if !valid_block_name(&name) { + return Err(bad("blocklibimport", format!("\"{name}\" is not a valid block name"))); + } + // A block the drawing already has is never replaced, as in the palette: its references + // would change with it. + if s.doc()?.block(&name).is_some() { + return Err(bad("blocklibimport", format!("block \"{name}\" is already in the drawing"))); + } + let mut src = (*cached_drawing(path)?).clone(); + let mut picked = None; + if let Some(block) = block { + let b = src.block(block).cloned().ok_or_else(|| bad("blocklibimport", format!("{path} has no block \"{block}\"")))?; + // The block is a drawing of its own: its objects as model space and its base point as + // $INSBASE, with the file's other blocks around it. + src.model = b.entities.clone(); + src.header.set("INSBASE", cadcraft_doc::HVal::Point(b.base)); + picked = Some(b); + } + // Only the layers, linetypes and styles the block needs come along, not the whole file's. + let name = define_from(s, &src, &name, true)?; + // The definition is a new one: what the block says about itself still comes along. + if let Some(from) = picked + && let Some(b) = s.doc_mut()?.blocks.get_mut(&name) + { + let b = Arc::make_mut(b); + b.annotative = from.annotative; + b.description.clone_from(&from.description); + b.units = from.units; + b.explodable = from.explodable; + } + Ok(json!({ "name": name })) +} + +/// Where the library list is kept. +#[cfg(not(target_arch = "wasm32"))] +fn list_path() -> Option { + crate::settings_dir::current().map(|d| d.join(LIST_FILE)) +} + +/// A path the list can hold: short enough, with no control characters. +fn acceptable(path: &str) -> bool { + !path.is_empty() && path.len() <= MAX_PATH_BYTES && !path.chars().any(char::is_control) +} + +/// The list in the settings folder. The file is hand-editable, so what it holds is checked here. +/// `Ok(None)`: no settings folder or no file yet. `Err`: a file that is there but unreadable. +#[cfg(not(target_arch = "wasm32"))] +fn read_list() -> std::result::Result>, String> { + let Some(path) = list_path() else { return Ok(None) }; + if !path.exists() { + return Ok(None); + } + let bytes = crate::capped_read::read_capped(&path, MAX_LIST_BYTES).map_err(|e| format!("{}: {e}", path.display()))?; + let list: Vec = serde_json::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display()))?; + Ok(Some(list.into_iter().filter(|p| acceptable(p)).take(MAX_LIBRARIES).collect())) +} + +/// On the web there is no settings folder: the list lives in memory only. +#[cfg(target_arch = "wasm32")] +fn read_list() -> std::result::Result>, String> { + Ok(None) +} + +/// The list, and why the file could not be read when it exists but is unreadable. Such a file is +/// never written over: `run_libraries` refuses to change the list while it stays unreadable. +fn load_list() -> (Vec, Option) { + let memory = || MEMORY.lock().map(|m| m.clone()).unwrap_or_default(); + if UNSAVED.load(Ordering::Relaxed) { + return (memory(), None); + } + match read_list() { + Ok(Some(list)) => (list, None), + Ok(None) => (memory(), None), + Err(why) => (memory(), Some(why)), + } +} + +/// Write the list to `path`, its folder made if needed. `false` when it could not be written. +#[cfg(not(target_arch = "wasm32"))] +fn write_list(path: &Path, list: &[String]) -> bool { + let Ok(bytes) = serde_json::to_vec_pretty(list) else { return false }; + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + crate::atomic_write::write_atomic(path, &bytes).is_ok() +} + +/// Keep the list in memory and write it to the settings folder. +fn save_list(list: &[String]) { + if let Ok(mut m) = MEMORY.lock() { + *m = list.to_vec(); + } + // A list that cannot be written is still kept for this session. + #[cfg(not(target_arch = "wasm32"))] + if let Some(p) = list_path() { + UNSAVED.store(!write_list(&p, list), Ordering::Relaxed); + } +} + +/// BLOCKLIBRARIES: list, add to or remove from the libraries. +fn run_libraries(_s: &mut Session, p: &Value) -> Result { + let (mut list, unreadable) = load_list(); + let op = str_param(p, "op").unwrap_or("list"); + if let (Some(why), "add" | "remove") = (&unreadable, op) { + return Err(bad("blocklibraries", format!("the library list cannot be read, so it is left as it is ({why})"))); + } + let path = str_param(p, "path").map(str::trim).filter(|s| !s.is_empty()); + match op { + "list" => {} + "add" => { + let path = path.ok_or_else(|| bad("blocklibraries", "`path` is required"))?; + let drawing = is_drawing(Path::new(path)) && Path::new(path).is_file(); + if !acceptable(path) || !(is_folder(path) || drawing) { + return Err(bad("blocklibraries", "a library is a folder or a DWG/DXF file")); + } + let stored = match list.iter().find(|l| same_path(l, path)) { + Some(l) => l.clone(), + None => { + if list.len() >= MAX_LIBRARIES { + return Err(bad("blocklibraries", format!("at most {MAX_LIBRARIES} libraries"))); + } + list.push(path.to_string()); + path.to_string() + } + }; + save_list(&list); + return Ok(json!({ "libraries": list, "path": stored })); + } + "remove" => { + let path = path.ok_or_else(|| bad("blocklibraries", "`path` is required"))?; + list.retain(|l| !same_path(l, path)); + save_list(&list); + } + other => return Err(bad("blocklibraries", format!("unknown op \"{other}\""))), + } + Ok(json!({ "libraries": list })) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A list that could not be written stays the list of this session, whatever the file says. + #[test] + fn a_failed_write_keeps_the_list_in_memory() { + let dir = std::env::temp_dir().join(format!("cadcraft-library-list-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let blocker = dir.join("a-file"); + std::fs::write(&blocker, b"x").unwrap(); + let list = vec!["C:/kept".to_string()]; + // A folder that is a file: neither the folder nor the list can be made. + assert!(!write_list(&blocker.join("block-libraries.json"), &list)); + assert!(write_list(&dir.join("block-libraries.json"), &list)); + + *MEMORY.lock().unwrap() = list.clone(); + UNSAVED.store(true, Ordering::Relaxed); + assert_eq!(load_list().0, list); + UNSAVED.store(false, Ordering::Relaxed); + MEMORY.lock().unwrap().clear(); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/engine/src/cmd/blocks/purge.rs b/crates/engine/src/cmd/blocks/purge.rs index b91507b152..4ef6946c7c 100644 --- a/crates/engine/src/cmd/blocks/purge.rs +++ b/crates/engine/src/cmd/blocks/purge.rs @@ -114,17 +114,40 @@ fn json_key(kind: Kind) -> &'static str { } } +/// Most objects PURGE's scan reads, as the scan of used layers does. +const MAX_SCAN: usize = 5_000_000; + +fn all_entities(d: &Drawing) -> impl Iterator> { + d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())) +} + fn entities(d: &Drawing) -> impl Iterator> { - d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter())).take(5_000_000) + all_entities(d).take(MAX_SCAN) +} + +/// Whether the scan reads the whole drawing: past its limit, what is in use can look unused. +pub(in crate::cmd) fn scan_reads_everything(d: &Drawing) -> bool { + all_entities(d).nth(MAX_SCAN).is_none() +} + +/// Whether a dimension override sets an arrowhead block. +pub(in crate::cmd) fn is_arrow_override(key: &str) -> bool { + cadcraft_doc::DimStyle::field_name(key).is_some_and(|f| f.starts_with("arrowBlock") || f == "leaderArrowBlock") +} + +/// The name a dimension override gives a style, linetype or arrowhead block. A number names one +/// too: DIMOVERRIDE keeps it as given, and the dimension is drawn with it as text. +pub(in crate::cmd) fn override_name(v: &Value) -> Option { + match v { + Value::String(n) => Some(n.trim().to_string()), + Value::Number(n) => Some(n.to_string()), + _ => None, + } } /// The arrowhead block names a dimension's overrides set. pub(in crate::cmd) fn override_arrows(dm: &cadcraft_doc::Dimension) -> impl Iterator + '_ { - dm.overrides - .iter() - .filter(|(k, _)| cadcraft_doc::DimStyle::field_name(k).is_some_and(|f| f.starts_with("arrowBlock") || f == "leaderArrowBlock")) - .filter_map(|(_, v)| v.as_str().map(|n| n.trim().to_string())) - .filter(|n| !n.is_empty()) + dm.overrides.iter().filter(|(k, _)| is_arrow_override(k)).filter_map(|(_, v)| override_name(v)).filter(|n| !n.is_empty()) } /// Upper-case names of blocks reachable from model space, the layouts and dimensions, and the @@ -151,10 +174,9 @@ pub(in crate::cmd) fn used_blocks(d: &Drawing) -> HashSet { _ => {} } } - let mut guard = 0; + // Each block is walked once, so this ends, cycles included. while let Some(n) = frontier.pop() { - guard += 1; - if guard > 100_000 || !used.insert(n.to_ascii_uppercase()) { + if !used.insert(n.to_ascii_uppercase()) { continue; } if let Some(b) = d.block(&n) { @@ -178,6 +200,33 @@ fn is(name: &str, list: &[&str]) -> bool { list.iter().any(|n| n.eq_ignore_ascii_case(name)) } +/// The linetypes an object names besides its own: its attributes' overrides, its dimension +/// overrides, and the copy of its style a multiline keeps. +fn linetypes_inside(e: &cadcraft_doc::Entity) -> Vec { + let mut out: Vec = super::object_attribs(e).iter().filter_map(|a| a.props.linetype.clone()).collect(); + match &e.kind { + EntityKind::Dimension(dm) => out.extend( + dm.overrides + .iter() + .filter(|(k, _)| cadcraft_doc::DimStyle::field_name(k).is_some_and(|f| matches!(f, "dimLinetype" | "extLinetype1" | "extLinetype2"))) + .filter_map(|(_, v)| override_name(v)), + ), + EntityKind::MLine(m) => out.extend(m.def.elements.iter().map(|e| e.linetype.clone())), + _ => {} + } + out +} + +/// The linetypes named by objects, layers, dimension styles and multiline styles. +fn linetypes_in_use(d: &Drawing) -> impl Iterator + '_ { + let objects = entities(d).map(|e| e.common.linetype.clone()); + let inside = entities(d).flat_map(|e| linetypes_inside(e)); + let layers = d.layers.iter().map(|l| l.linetype.clone()); + let dims = d.dim_styles.iter().flat_map(|t| [t.dim_linetype.clone(), t.ext_linetype1.clone(), t.ext_linetype2.clone()]); + let mlines = d.mline_styles.iter().flat_map(|t| t.elements.iter().map(|e| e.linetype.clone())); + objects.chain(inside).chain(layers).chain(dims).chain(mlines) +} + /// Names of the unused objects of a named kind, in table order. This is PURGE's scan; `USAGE` /// reads it too, without purging anything. pub(in crate::cmd) fn candidates(d: &Drawing, kind: Kind) -> Vec { @@ -197,21 +246,7 @@ pub(in crate::cmd) fn candidates(d: &Drawing, kind: Kind) -> Vec { .collect() } Kind::Linetypes => { - // Objects and layers use linetypes, and so do dimension styles and a dimension's own - // overrides (DIMLTYPE, DIMLTEX1, DIMLTEX2), and multiline styles' elements. - let styles = d.dim_styles.iter().flat_map(|s| [s.dim_linetype.clone(), s.ext_linetype1.clone(), s.ext_linetype2.clone()]); - let overrides = entities(d).filter_map(|e| if let EntityKind::Dimension(dm) = &e.kind { Some(dm) } else { None }).flat_map(|dm| { - ["dimLinetype", "extLinetype1", "extLinetype2"].into_iter().filter_map(|k| dm.overrides.get(k)?.as_str().map(str::to_string)) - }); - let mlines = d.mline_styles.iter().flat_map(|s| s.elements.iter().map(|el| el.linetype.clone())); - let used = lower( - &mut entities(d) - .map(|e| e.common.linetype.clone()) - .chain(d.layers.iter().map(|l| l.linetype.clone())) - .chain(styles) - .chain(overrides) - .chain(mlines), - ); + let used = lower(&mut linetypes_in_use(d)); let cur = d.header.str("CELTYPE", "ByLayer"); d.linetypes .iter() diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index 41c58febe9..f97c25bcb8 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -106,6 +106,10 @@ pub fn used_layers(d: &cadcraft_doc::Drawing) -> std::collections::HashSet Vec { let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities)); for st in stores { for e in st.iter() { + out.extend(super::blocks::object_attribs(e).iter().flat_map(attrib_text_styles)); match &e.kind { EntityKind::Text(t) => out.push(t.style.clone()), EntityKind::MText(t) => out.push(t.style.clone()), - EntityKind::AttDef(a) => out.push(a.text.style.clone()), - EntityKind::Insert(i) => out.extend(i.attribs.iter().map(|a| a.text.style.clone())), + EntityKind::AttDef(a) => out.extend(attrib_text_styles(a)), EntityKind::MLeader(m) => out.extend(m.text.iter().map(|t| t.style.clone())), + EntityKind::Dimension(dm) => out.extend( + dm.overrides + .iter() + .filter(|(k, _)| cadcraft_doc::DimStyle::field_name(k) == Some("textStyle")) + .filter_map(|(_, v)| super::blocks::purge::override_name(v)), + ), _ => {} } } @@ -867,6 +873,11 @@ pub(super) fn text_styles_in_use(d: &cadcraft_doc::Drawing) -> Vec { out } +/// The text styles of an attribute or attribute definition, its multiline text included. +fn attrib_text_styles(a: &cadcraft_doc::Attrib) -> impl Iterator + '_ { + std::iter::once(a.text.style.clone()).chain(a.multiline.iter().map(|m| m.mtext.style.clone())) +} + fn run_style_rename(s: &mut Session, p: &Value) -> Result { let from = str_param(p, "from").ok_or_else(|| bad("style.rename", "`from` is required"))?.to_string(); let to = str_param(p, "to").map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| bad("style.rename", "`to` is required"))?.to_string(); diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 3e79cfcb83..ec8b54a591 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -85,6 +85,11 @@ pub struct Session { pub doc_epoch: u64, pub settings: Settings, pub running: Option, + /// How many commands were started, nested transparent ones left out. + pub commands_started: u64, + /// The last command that ended by itself, not cancelled: its number in `commands_started`, and + /// whether it took new handles (it added to the drawing, and nothing took that back). + pub last_finished: Option<(u64, bool)>, /// A script is running ([`Session::script`]); a SCRIPT command inside it is refused. in_script: bool, /// The command suspended while a transparent command (`'ZOOM`, `'PAN`…) prompts inside it; @@ -176,6 +181,8 @@ impl Session { doc_epoch: 0, settings: Settings::default(), running: None, + commands_started: 0, + last_finished: None, in_script: false, suspended: None, log: Vec::new(), diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index 2655903e88..e5f21452f8 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -63,6 +63,7 @@ impl Session { let Some(spec) = find_command(&id) else { // A command defined in LISP: (defun c:NAME …). if !transparent && let Some(f) = self.lisp_command(&lower) { + self.commands_started = self.commands_started.wrapping_add(1); if self.running.is_some() { self.cancel(); } @@ -96,8 +97,11 @@ impl Session { self.echo(format!("Command: {}", spec.id.to_ascii_uppercase())); return self.input(Input::Keyword("Undo".into())); } - if !nested && self.running.is_some() { - self.cancel(); + if !nested { + self.commands_started = self.commands_started.wrapping_add(1); + if self.running.is_some() { + self.cancel(); + } } (spec.enabled)(self).map_err(|m| EngineError::Disabled(spec.id.into(), m))?; if let Some(why) = cmd::blocks::bedit::refused_in_editor(self, spec.id) { @@ -378,7 +382,14 @@ impl Session { Ok(()) } Ok(Step::Done) => { + let seed = run.before.handseed; self.finish(run, false); + let added = self.doc().is_ok_and(|d| d.handseed != seed); + // A transparent command ending inside another (`'ZOOM` in an INSERT) is not that + // command ending: it shares its number. + if self.suspended.is_none() { + self.last_finished = Some((self.commands_started, added)); + } self.resume_suspended(); Ok(()) } diff --git a/crates/engine/tests/blocklibrary.rs b/crates/engine/tests/blocklibrary.rs new file mode 100644 index 0000000000..7f09f2cb1a --- /dev/null +++ b/crates/engine/tests/blocklibrary.rs @@ -0,0 +1,308 @@ +//! Block libraries (the Blocks palette): BLOCKLIBRARY lists a folder of drawings or the blocks +//! of one drawing, BLOCKLIBIMPORT defines a library block in the current drawing, and +//! BLOCKLIBRARIES keeps the list of libraries. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::geom::Vec3; +use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, Handle, Layer, Line}; +use cadcraft_engine::{Input, Session}; +use serde_json::json; + +/// How many times a library file was parsed. +static READS: AtomicUsize = AtomicUsize::new(0); + +/// Every library file reads as a drawing with blocks "Valve" (a line on layer Pipes, base point +/// (1, 1)) and "Pump" (empty), whatever its bytes. +fn read(_bytes: &[u8], name: &str) -> Result { + READS.fetch_add(1, Ordering::SeqCst); + let mut d = Drawing::new_metric(); + d.layers.push(Layer { name: "Pipes".into(), ..Layer::default() }); + d.layers.push(Layer { name: "Spare".into(), ..Layer::default() }); + let mut valve = Block::new("Valve"); + valve.description = "Gate valve".into(); + valve.annotative = true; + valve.units = 6; + valve.explodable = false; + valve.base = Vec3::new(1.0, 1.0, 0.0); + let mut line = Entity::new(Handle(0x70), EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(4.0, 0.0, 0.0) })); + line.common.layer = "Pipes".into(); + valve.entities.push(line); + d.blocks.insert("Valve".into(), Arc::new(valve)); + d.blocks.insert("Pump".into(), Arc::new(Block::new("Pump"))); + // "Outer" holds a reference to "Valve" and nothing else. + let mut s = Session::new(); + *s.doc_mut().unwrap() = d; + s.execute("insert", &json!({ "name": "Valve", "at": [2, 2] })).unwrap(); + let handles: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({ "name": "Outer", "base": [0, 0], "handles": handles, "keep": "delete" })).unwrap(); + // A dimension style nothing uses, with an arrowhead block of its own. + if name.contains("arrow") { + let d = s.doc_mut().unwrap(); + d.blocks.insert("TipArrow".into(), Arc::new(Block::new("TipArrow"))); + d.dim_styles.push(cadcraft_engine::doc::DimStyle { name: "Spare".into(), arrow_block: "TipArrow".into(), ..Default::default() }); + } + // A crafted file: "Valve" holds "Outer", which holds "Valve". + if name.contains("cycle") { + let mut back = (**s.doc().unwrap().block("Outer").unwrap().entities.iter().next().unwrap()).clone(); + if let EntityKind::Insert(i) = &mut back.kind { + i.block = "Outer".into(); + } + let d = s.doc_mut().unwrap(); + let mut valve = (**d.block("Valve").unwrap()).clone(); + valve.entities.push(back); + d.blocks.insert("Valve".into(), Arc::new(valve)); + } + Ok(s.doc().unwrap().clone()) +} + +/// A new folder with two drawings and a file that is not one. +fn folder() -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("cadcraft-blocklibrary-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for f in ["b-pumps.dwg", "A-valves.dxf", "notes.txt"] { + std::fs::write(dir.join(f), b"x").unwrap(); + } + dir +} + +/// Listing a drawing file and importing its blocks. +fn lists_and_imports(s: &mut Session, file: &str) { + // A drawing file lists its blocks. + let r = s.execute("blocklibrary", &json!({ "path": file })).unwrap(); + assert_eq!(r["kind"], "file"); + assert_eq!( + r["blocks"], + json!([{ "name": "Outer", "description": "" }, { "name": "Pump", "description": "" }, { "name": "Valve", "description": "Gate valve" }]) + ); + + // Importing defines the block (and its layer) here, under another name when asked. + let r = s.execute("blocklibimport", &json!({ "path": file, "block": "Valve", "name": "Gate" })).unwrap(); + assert_eq!(r["name"], "Gate"); + let d = s.doc().unwrap(); + let gate = d.block("Gate").unwrap(); + assert_eq!(gate.entities.iter().count(), 1); + assert_eq!(gate.base, Vec3::new(1.0, 1.0, 0.0)); + assert_eq!((gate.description.as_str(), gate.annotative, gate.units, gate.explodable), ("Gate valve", true, 6, false)); + assert!(d.layers.iter().any(|l| l.name == "Pipes")); + // Only what the block needs comes along: not the file's other layers or blocks. + assert!(!d.layers.iter().any(|l| l.name == "Spare"), "an unused layer of the library stays out"); + assert!(d.block("Pump").is_none(), "an unused block of the library stays out"); + s.execute("insert", &json!({ "name": "Gate", "at": [10, 10] })).unwrap(); + // A block already here is never replaced, whatever the letter case. + assert!(s.execute("blocklibimport", &json!({ "path": file, "block": "Pump", "name": "gate" })).is_err()); + assert_eq!(s.doc().unwrap().block("Gate").unwrap().entities.iter().count(), 1); + assert!(s.doc().unwrap().block("Pump").is_none()); + // A block made of another block brings that one too (and its layer), not the unused ones. + s.execute("blocklibimport", &json!({ "path": file, "block": "Outer", "name": "Assembly" })).unwrap(); + let d = s.doc().unwrap(); + assert!(d.block("Assembly").is_some()); + assert!(d.block("Valve").is_some(), "the nested block stays"); + assert!(d.block("Pump").is_none()); + assert!(d.layers.iter().any(|l| l.name == "Pipes")); + // A whole drawing is named after its file and brings its objects (here none: model space is empty). + let r = s.execute("blocklibimport", &json!({ "path": file })).unwrap(); + assert_eq!(r["name"], "A-valves"); + assert!(!s.doc().unwrap().layers.iter().any(|l| l.name == "Spare")); + assert!(s.execute("blocklibimport", &json!({ "path": file, "block": "Nope" })).is_err()); + assert!(s.execute("blocklibimport", &json!({ "path": file, "block": "Valve", "name": "bad/name" })).is_err()); +} + +/// A dimension style nothing uses is left out, and its arrowhead block with it. +fn leaves_out_an_unused_dimension_style(s: &mut Session, dir: &std::path::Path) { + let file = dir.join("arrow-set.dxf").to_string_lossy().to_string(); + std::fs::write(&file, b"x").unwrap(); + s.execute("blocklibimport", &json!({ "path": file, "block": "Valve", "name": "Tap" })).unwrap(); + let d = s.doc().unwrap(); + assert!(d.block("Tap").is_some()); + assert!(!d.dim_styles.iter().any(|t| t.name == "Spare"), "an unused dimension style stays out"); + assert!(d.block("TipArrow").is_none(), "so does its arrowhead block"); +} + +/// Adding and removing libraries. +fn keeps_the_list(s: &mut Session, dir: &std::path::Path, dir_s: &str, file: &str) { + // The list: add (once), refuse what is not a library, remove. + let l = s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).unwrap(); + assert_eq!(l["libraries"], json!([dir_s])); + // The same path again is kept once; letter case only matters on case-sensitive file systems. + let again = s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).unwrap(); + assert_eq!(again["libraries"], json!([dir_s])); + if cfg!(any(windows, target_os = "macos")) { + let upper = s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s.to_uppercase() })).unwrap(); + assert_eq!(upper["libraries"], json!([dir_s]), "the same folder in other letters is the same library"); + assert_eq!(upper["path"], json!(dir_s), "the entry keeps its first spelling"); + } + s.execute("blocklibraries", &json!({ "op": "add", "path": file })).unwrap(); + assert_eq!(s.execute("blocklibraries", &json!({})).unwrap()["libraries"], json!([dir_s, file])); + assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": dir.join("notes.txt").to_string_lossy() })).is_err()); + let l = s.execute("blocklibraries", &json!({ "op": "remove", "path": file })).unwrap(); + assert_eq!(l["libraries"], json!([dir_s])); + s.execute("blocklibraries", &json!({ "op": "remove", "path": dir_s })).unwrap(); +} + +/// Names, paths and files that try to pass for something else. +fn refuses_hostile_input(s: &mut Session, dir: &std::path::Path, dir_s: &str) { + // A block whose name looks like `name=path` is that block: INSERT reads no file for it. + let reads = READS.load(Ordering::SeqCst); + let mut odd = Session::new(); + odd.doc_mut().unwrap().blocks.insert("a=b".into(), Arc::new(Block::new("a=b"))); + odd.start("insert").unwrap(); + odd.input(Input::Text("a=b".into())).unwrap(); + assert!(odd.prompt_text().starts_with("INSERT Specify insertion point"), "{}", odd.prompt_text()); + assert_eq!(READS.load(Ordering::SeqCst), reads, "no file was read"); + odd.input(Input::Cancel).unwrap(); + + // What is not a readable drawing fails with an error. + assert!(s.execute("blocklibimport", &json!({ "path": dir_s })).is_err(), "a folder is not a drawing"); + assert!(s.execute("blocklibrary", &json!({ "path": dir.join("missing.dxf").to_string_lossy() })).is_err()); + + // A file is a library by its name, not by its bytes: `part.bin` is refused before it is read. + let bin = dir.join("part.bin").to_string_lossy().to_string(); + std::fs::write(&bin, b"x").unwrap(); + let reads = READS.load(Ordering::SeqCst); + assert!(s.execute("blocklibrary", &json!({ "path": bin })).is_err()); + assert!(s.execute("blocklibimport", &json!({ "path": bin, "block": "Valve", "name": "FromBin" })).is_err()); + assert!(cadcraft_engine::cmd::read_library_file(&bin).is_err()); + assert_eq!(READS.load(Ordering::SeqCst), reads, "the file was not parsed"); + assert!(s.doc().unwrap().block("FromBin").is_none()); + + // A library whose blocks hold each other imports without hanging, and the session goes on. + let cycle = dir.join("cycle.dxf").to_string_lossy().to_string(); + std::fs::write(&cycle, b"x").unwrap(); + let _ = s.execute("blocklibimport", &json!({ "path": cycle, "block": "Outer", "name": "Loop" })); + s.execute("line", &json!({ "points": [[0, 0], [1, 1]] })).unwrap(); +} + +/// The Blocks palette can open on the Start tab: listing a library and the kept list need no +/// drawing; importing one does. +#[test] +fn the_library_commands_that_read_no_drawing_run_without_one() { + let mut s = Session::empty(); + let dir = std::env::temp_dir().join(format!("cadcraft-blocklibrary-nodoc-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + std::fs::write(dir.join("pumps.dwg"), b"x").unwrap(); + let r = s.execute("blocklibrary", &json!({ "path": dir.to_string_lossy() })).unwrap(); + assert_eq!(r["files"].as_array().map(Vec::len), Some(1)); + s.execute("blocklibraries", &json!({})).unwrap(); + let err = s.execute("blocklibimport", &json!({ "path": dir.join("pumps.dwg").to_string_lossy() })).unwrap_err(); + assert!(err.to_string().contains("no drawing"), "{err}"); + let _ = std::fs::remove_dir_all(&dir); +} + +/// A file with a huge block table. +fn bounds_a_huge_table() { + // A file with a huge block table lists a bounded part of it, and says so. + let mut many = Session::new(); + let d = many.doc_mut().unwrap(); + for i in 0..10_001 { + let name = format!("B{i}"); + d.blocks.insert(name.clone(), Arc::new(Block::new(&name))); + } + let r = many.execute("blockspalette", &json!({})).unwrap(); + let names: Vec<&str> = r["blocks"].as_array().unwrap().iter().map(|b| b["name"].as_str().unwrap()).collect(); + assert_eq!(names.len(), 10_000); + assert_eq!(r["truncated"], true); + // The first ones by name, sorted: B9999 comes last of all, so it is the one left out. + assert_eq!(names.first(), Some(&"B0")); + assert!(!names.contains(&"B9999")); + assert!(names.windows(2).all(|w| w[0].to_ascii_lowercase() <= w[1].to_ascii_lowercase())); +} + +/// BLOCKSPALETTE counts every object that draws a block: references and multileader block content. +fn counts_what_draws_each_block() { + let mut s = Session::new(); + s.doc_mut().unwrap().blocks.insert("Tag".into(), Arc::new(Block::new("Tag"))); + s.execute("insert", &json!({ "name": "Tag", "at": [0, 0] })).unwrap(); + s.execute("mleader", &json!({ "points": [[0, 0], [10, 5]], "block": "tag" })).unwrap(); + let r = s.execute("blockspalette", &json!({})).unwrap(); + assert_eq!(r["blocks"], json!([{ "name": "Tag", "description": "", "references": 2 }])); +} + +/// The list file in the settings folder. +fn checks_the_list_file(s: &mut Session, dir: &std::path::Path, dir_s: &str) { + // The list file is checked when it is read: junk, bad entries, too many, too big. + let list = dir.join("block-libraries.json"); + let libraries = |s: &mut Session| s.execute("blocklibraries", &json!({})).unwrap()["libraries"].as_array().unwrap().clone(); + std::fs::write(&list, "not json").unwrap(); + assert!(libraries(s).is_empty()); + // A file that is there but unreadable is never written over: the list stays as the user left it. + assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).is_err()); + assert!(s.execute("blocklibraries", &json!({ "op": "remove", "path": dir_s })).is_err()); + assert_eq!(std::fs::read(&list).unwrap(), b"not json"); + let mut hostile: Vec = (0..100).map(|i| format!("C:/lib{i}")).collect(); + hostile.insert(0, String::new()); + hostile.insert(1, "bad\nname".into()); + hostile.insert(2, "x".repeat(10_000)); + std::fs::write(&list, serde_json::to_vec(&hostile).unwrap()).unwrap(); + let kept = libraries(s); + assert_eq!(kept.len(), 64); + assert_eq!(kept[0], "C:/lib0"); + std::fs::write(&list, vec![b' '; 300 << 10]).unwrap(); + assert!(libraries(s).is_empty()); + // What the list file holds after an addition is the list, whole. + std::fs::remove_file(&list).unwrap(); + s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).unwrap(); + assert_eq!(serde_json::from_slice::>(&std::fs::read(&list).unwrap()).unwrap(), vec![dir_s.to_string()]); + // Paths with control characters or of absurd length are refused. + assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": format!("{dir_s}\nx") })).is_err()); + assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": "y".repeat(5000) })).is_err()); +} + +/// A file named at INSERT's prompt defines its block before the insertion point is asked for, and +/// Escape there keeps the definition and places nothing, as in AutoCAD 2027. +fn a_cancelled_insert_keeps_the_definition_from_a_file(s: &mut Session, file: &str) { + let placed = s.doc().unwrap().model.iter().count(); + s.start("insert").unwrap(); + s.input(Input::Text(format!("FromFile={file}"))).unwrap(); + assert!(s.prompt_text().starts_with("INSERT Specify insertion point"), "{}", s.prompt_text()); + assert!(s.doc().unwrap().block("FromFile").is_some()); + s.input(Input::Cancel).unwrap(); + assert!(s.doc().unwrap().block("FromFile").is_some()); + assert_eq!(s.doc().unwrap().model.iter().count(), placed); +} + +/// One test: the file hooks and the settings folder are global to the process. +#[test] +fn libraries_list_import_and_are_kept() { + set_io(IoHooks { read, write: |_, _| Err("no writer in this test".into()), plot: None }); + // No settings folder: the list lives in memory, and the real one is never written. + cadcraft_engine::settings_dir::set(None); + let dir = folder(); + let dir_s = dir.to_string_lossy().to_string(); + let mut s = Session::new(); + + // A folder lists its drawings by name, case-insensitively sorted; other files are not drawings. + let r = s.execute("blocklibrary", &json!({ "path": dir_s })).unwrap(); + assert_eq!(r["kind"], "folder"); + let names: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["A-valves", "b-pumps"]); + + let reads_before = READS.load(Ordering::SeqCst); + let file = dir.join("A-valves.dxf").to_string_lossy().to_string(); + lists_and_imports(&mut s, &file); + // The file was parsed once for all of that, and again only when it changes. + assert_eq!(READS.load(Ordering::SeqCst) - reads_before, 1, "the file is parsed once, not for every block placed"); + std::fs::write(&file, b"changed contents, another size").unwrap(); + s.execute("blocklibrary", &json!({ "path": file })).unwrap(); + assert_eq!(READS.load(Ordering::SeqCst) - reads_before, 2, "a changed file is read again"); + // Refresh in the palette reads it again even when its size and time look the same. + cadcraft_engine::cmd::clear_library_cache(); + let listed = s.execute("blocklibrary", &json!({ "path": file })).unwrap(); + assert_eq!(READS.load(Ordering::SeqCst) - reads_before, 3, "a cleared file is read again"); + // The palette's worker thread gets the same answer without a session. + assert_eq!(cadcraft_engine::cmd::list_library(&file).unwrap(), listed); + + leaves_out_an_unused_dimension_style(&mut s, &dir); + a_cancelled_insert_keeps_the_definition_from_a_file(&mut s, &file); + keeps_the_list(&mut s, &dir, &dir_s, &file); + refuses_hostile_input(&mut s, &dir, &dir_s); + bounds_a_huge_table(); + counts_what_draws_each_block(); + cadcraft_engine::settings_dir::set(Some(dir.clone())); + checks_the_list_file(&mut s, &dir, &dir_s); + cadcraft_engine::settings_dir::set(None); + + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/engine/tests/it/insert_enter.rs b/crates/engine/tests/it/insert_enter.rs new file mode 100644 index 0000000000..49bb66d692 --- /dev/null +++ b/crates/engine/tests/it/insert_enter.rs @@ -0,0 +1,78 @@ +//! Enter or Space at INSERT's insertion point prompt asks again, as in AutoCAD 2027; Escape ends +//! the command (the Blocks palette's Repeat Placement stops this way). + +use cadcraft_engine::geom::Vec2; +use cadcraft_engine::{Input, Session}; +use serde_json::json; + +#[test] +fn enter_at_the_insertion_point_asks_again() { + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let hs: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({"name": "A", "base": [0, 0], "handles": hs, "keep": "delete"})).unwrap(); + + s.start("insert").unwrap(); + s.input(Input::Text("A".into())).unwrap(); + assert!(s.prompt_text().starts_with("INSERT Specify insertion point"), "{}", s.prompt_text()); + s.input(Input::Enter).unwrap(); + assert!(s.prompt_text().starts_with("INSERT Specify insertion point"), "{}", s.prompt_text()); + s.input(Input::Cancel).unwrap(); + assert_eq!(s.prompt_text(), "Command:"); + assert_eq!(s.doc().unwrap().model.iter().count(), 0, "nothing is placed"); + assert_eq!(s.last_finished, None, "ending it this way is cancelling it"); +} + +/// A cancelled INSERT leaves the drawing as it was: it takes no undo step, or the next undo would +/// seem to do nothing (Repeat Placement always ends this way). A placed block keeps its name. +#[test] +fn a_cancelled_insert_takes_no_undo_step() { + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let hs: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({"name": "A", "base": [0, 0], "handles": hs, "keep": "delete"})).unwrap(); + let steps = s.state().unwrap().undo.len(); + + s.start("insert").unwrap(); + s.input(Input::Text("A".into())).unwrap(); + s.input(Input::Cancel).unwrap(); + assert_eq!(s.state().unwrap().undo.len(), steps); + assert_eq!(s.doc().unwrap().header.str("INSNAME", ""), ""); + + s.start("insert").unwrap(); + s.input(Input::Text("A".into())).unwrap(); + s.input(Input::Keyword("Scale".into())).unwrap(); + s.input(Input::Text("1".into())).unwrap(); + s.input(Input::Keyword("Rotate".into())).unwrap(); + s.input(Input::Text("0".into())).unwrap(); + s.input(Input::Point(Vec2::new(1.0, 1.0))).unwrap(); + assert_eq!(s.state().unwrap().undo.len(), steps + 1); + assert_eq!(s.doc().unwrap().header.str("INSNAME", ""), "A"); +} + +/// How the last command ended: by itself, with what it added; a cancelled one changes nothing. +#[test] +fn the_last_finished_command_says_whether_it_added_objects() { + let mut s = Session::new(); + s.start("line").unwrap(); + s.input(Input::Point(Vec2::new(0.0, 0.0))).unwrap(); + s.input(Input::Point(Vec2::new(1.0, 1.0))).unwrap(); + s.input(Input::Enter).unwrap(); + let line = (s.commands_started, true); + assert_eq!(s.last_finished, Some(line)); + s.start("circle").unwrap(); + s.input(Input::Cancel).unwrap(); + assert_eq!(s.last_finished, Some(line)); +} + +/// A transparent command runs inside the current one: it does not count as a new command. +#[test] +fn only_a_command_of_its_own_counts_as_started() { + let mut s = Session::new(); + s.start("line").unwrap(); + let started = s.commands_started; + s.start("'zoom").unwrap(); + assert_eq!(s.commands_started, started); + s.start("circle").unwrap(); + assert_eq!(s.commands_started, started + 1); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 44ce588818..4942bcb2b7 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -68,6 +68,7 @@ mod inquiry_keywords; mod inquiry_variables; mod inquiry_z; mod insert_attribute_prompts; +mod insert_enter; mod insert_prompts; mod isometric; mod join_close; diff --git a/crates/engine/tests/it/purge_mlinestyles.rs b/crates/engine/tests/it/purge_mlinestyles.rs index a0f955c96f..d355f2ef4f 100644 --- a/crates/engine/tests/it/purge_mlinestyles.rs +++ b/crates/engine/tests/it/purge_mlinestyles.rs @@ -4,7 +4,7 @@ use std::sync::Arc; use cadcraft_engine::Session; -use cadcraft_engine::doc::{Block, Common, Entity, EntityKind, Handle, Insert, MLine, MLineJust, MLineStyle, Space}; +use cadcraft_engine::doc::{Attrib, Block, Common, Entity, EntityKind, Handle, Insert, MLine, MLineElement, MLineJust, MLineStyle, Space}; use cadcraft_engine::geom::{Vec2, Vec3}; use serde_json::json; @@ -75,3 +75,67 @@ fn purge_mlinestyles_at_the_command_line() { assert!(s.running.is_none(), "{}", s.prompt_text()); assert_eq!(styles(&s), ["STANDARD", "Model", "InBlock", "Gone", "Current"]); } + +/// A linetype is in use when only a dimension style, a dimension override, a multiline style, a +/// multiline's copy of its style or an attribute override names it. +#[test] +fn linetypes_named_by_styles_and_attributes_are_kept() { + let mut s = session(); + let d = s.doc_mut().unwrap(); + for name in ["InDimStyle", "InOverride", "InMline", "InMlineCopy", "InAttribute", "Unused"] { + let mut lt = d.linetypes[0].clone(); + lt.name = name.into(); + d.linetypes.push(lt); + } + d.dim_styles[0].ext_linetype2 = "InDimStyle".into(); + let element = MLineElement { linetype: "InMline".into(), ..MLineElement::default() }; + d.mline_styles.iter_mut().for_each(|t| t.elements.push(element.clone())); + let at = serde_json::to_value(Vec3::ZERO).unwrap(); + let mut attrib: Attrib = serde_json::from_value(json!({ "tag": "A", "text": { "insert": at, "height": 1.0, "value": "1" } })).unwrap(); + attrib.props.linetype = Some("InAttribute".into()); + let Some(EntityKind::Insert(mut ins)) = d.model.iter().find_map(|e| matches!(e.kind, EntityKind::Insert(_)).then(|| e.kind.clone())) else { + return; + }; + ins.attribs.push(attrib); + d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap(); + let copy = MLineElement { linetype: "InMlineCopy".into(), ..MLineElement::default() }; + let drawn = MLineStyle { name: "Model".into(), elements: vec![copy], ..MLineStyle::default() }; + d.add(&Space::Model, Common::default(), mline(&drawn)).unwrap(); + let dim = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap(); + let handle = dim["handle"].clone(); + s.execute("dimoverride", &json!({ "handles": [handle], "DIMLTYPE": "InOverride" })).unwrap(); + s.execute("purge", &json!({ "type": "linetypes" })).unwrap(); + let names: Vec = s.doc().unwrap().linetypes.iter().map(|l| l.name.clone()).collect(); + for kept in ["InDimStyle", "InOverride", "InMline", "InMlineCopy", "InAttribute"] { + assert!(names.iter().any(|n| n == kept), "{kept}: {names:?}"); + } + assert!(!names.iter().any(|n| n == "Unused"), "{names:?}"); +} + +/// A dimension override given as a number names a text style, linetype or arrowhead block all +/// the same (DIMOVERRIDE keeps the number, the dimension is drawn with it as text): PURGE keeps +/// them. +#[test] +fn numbers_in_dimension_overrides_name_what_they_use() { + let mut s = session(); + let d = s.doc_mut().unwrap(); + for name in ["123", "Spare"] { + let mut t = d.text_styles[0].clone(); + t.name = name.into(); + d.text_styles.push(t); + } + for name in ["7", "Spare"] { + let mut lt = d.linetypes[0].clone(); + lt.name = name.into(); + d.linetypes.push(lt); + } + d.blocks.insert("45".into(), Arc::new(Block::new("45"))); + let h = s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap()["handle"].clone(); + s.execute("dimoverride", &json!({ "handles": [h], "DIMTXSTY": 123, "DIMLTYPE": 7, "DIMBLK1": 45 })).unwrap(); + let r = s.execute("purge", &json!({ "type": "all" })).unwrap(); + let d = s.doc().unwrap(); + assert!(d.text_style("123").is_some(), "{r}"); + assert!(d.linetypes.iter().any(|l| l.name == "7"), "{r}"); + assert!(d.block("45").is_some(), "{r}"); + assert_eq!((r["purged"]["textstyles"].clone(), r["purged"]["linetypes"].clone()), (json!(["Spare"]), json!(["Spare"])), "{r}"); +} diff --git a/crates/ui-egui/src/blocks_palette.rs b/crates/ui-egui/src/blocks_palette.rs new file mode 100644 index 0000000000..3cb43a61c2 --- /dev/null +++ b/crates/ui-egui/src/blocks_palette.rs @@ -0,0 +1,1735 @@ +//! The Blocks palette: the drawing's own blocks as a gallery (Current Drawing) and the block +//! libraries the user added (Libraries): folders of drawings and single drawing files, kept in +//! a list that can be added to, refreshed and removed from. A name filter, the gallery's view +//! styles and the insertion options (scale, rotation, explode) apply to both tabs. +//! +//! A thin view over the engine: the lists come from the `blockspalette`, `blocklibraries` and +//! `blocklibrary` commands, a library block is defined here by `blocklibimport`, and a block is +//! placed by starting INSERT and answering its first prompts, so the command line shows what the +//! palette did and the insertion point is picked on the drawing as usual. +//! +//! Block definitions come from files, so they are hostile input: a picture is built only for a +//! tile on screen, a few per frame, under a deadline and a size limit, and a panic or a refused +//! picture never stops the block from being placed. + +use std::collections::HashMap; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use cadcraft_engine::Input; +use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, HatchLoop, Insert, MAX_BLOCK_DEPTH}; +use cadcraft_engine::geom::{Bounds2, Vec2}; +use cadcraft_engine::render::{DisplayList, Kind, Options, build_entities}; +use egui::{Color32, Pos2, RichText, Sense, Stroke, vec2}; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::docking::Panel; + +/// Points kept per block preview: a block with more geometry shows its first part only. +const PREVIEW_POINTS: usize = 30_000; +/// How finely a preview is drawn: the chord tolerance is the block's size over this. +const PREVIEW_DETAIL: f64 = 300.0; +/// Most objects a block can hold and still get a preview. +const PREVIEW_ENTITIES: usize = 50_000; +/// Most work (vertices, control points and repeated references, counted before drawing) a +/// preview may ask for: a single object can hold millions of vertices. +const PREVIEW_WORK: usize = 500_000; +/// What a character costs in that count: a glyph takes several times the work of a vertex. +const TEXT_WORK: usize = 4; +/// The shortest dash pattern the pass that finds the size draws: none, they do not change it. +const NO_DASHES: f64 = 1e30; +/// How long a preview pass may keep the interface waiting before it is given up. +const PREVIEW_DEADLINE: Duration = Duration::from_millis(100); +/// Most previews built in one frame; the others wait for the next frames. +const BUILDS_PER_FRAME: usize = 4; +/// Most points the previews in memory hold together. +const MAX_CACHED_POINTS: usize = 4_000_000; +/// Most previews remembered, refused ones included. +const MAX_CACHED_PICTURES: usize = 50_000; +/// The most characters of a block name and of a description shown. +const MAX_NAME_CHARS: usize = 120; +const MAX_DESCRIPTION_CHARS: usize = 240; + +/// BLOCKSPALETTE typed, Window ▸ Blocks and the toolbar icon open this palette. JSON calls (with parameters) +/// run the engine's command and list the blocks. +pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option> { + // The toolbar's Blocks icon and Window ▸ Blocks open the palette too, as the other ui.dialog.* + // ids do, whatever the parameters. + if id == "ui.dialog.blocks" { + return Some(open_palette(app)); + } + if !params.is_null() { + return None; + } + match cadcraft_engine::cmd::resolve_alias(id).as_str() { + "blockspalette" => Some(open_palette(app)), + _ => None, + } +} + +/// Show the palette. The first time it docks below the other palettes; after that it comes back +/// where it was. +fn open_palette(app: &mut CadApp) -> Result { + crate::docking::command(app, false, &json!({ "operation": "open", "panel": Panel::Blocks.id() })) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Tab { + #[default] + Current, + Libraries, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum View { + ExtraLarge, + Large, + #[default] + Medium, + Small, + Details, + List, +} + +impl View { + const ALL: [View; 6] = [View::ExtraLarge, View::Large, View::Medium, View::Small, View::Details, View::List]; + + /// The name shown on the view's button. + fn label(self) -> &'static str { + match self { + View::ExtraLarge => crate::tl!("Extra Large Icons"), + View::Large => crate::tl!("Large Icons"), + View::Medium => crate::tl!("Medium Icons"), + View::Small => crate::tl!("Small Icons"), + View::Details => crate::tl!("Details"), + View::List => crate::tl!("List"), + } + } + + /// The side of a gallery tile, for the icon views. + fn tile(self) -> Option { + match self { + View::ExtraLarge => Some(150.0), + View::Large => Some(104.0), + View::Medium => Some(76.0), + View::Small => Some(52.0), + View::Details | View::List => None, + } + } +} + +/// What the palette remembers between frames and drawings. +#[derive(Clone, Debug)] +struct State { + tab: Tab, + view: View, + filter: String, + selected: Option, + /// The libraries the user added (the engine keeps the list), once read. + libraries: Option>, + /// The library whose contents the gallery shows. + library: Option, + /// The folder or file path being typed to add a library. + new_library: String, + /// Bumped to read the library again. + refresh: u32, + /// The library is being read: Refresh waits for it, so clicks do not pile up reads. + reading: bool, + /// Scale and rotation are asked on the drawing (the INSERT prompts) while these are on; + /// off, the values below are used without asking. + scale_on_screen: bool, + scale: [f64; 3], + rotation_on_screen: bool, + rotation: f64, + explode: bool, + /// Place the block again once it is placed, until the command is cancelled. + repeat: bool, + /// The block being placed again, while its INSERT runs. + repeating: Option, + /// The pass that last drew the palette: what ran while it was hidden went unwatched. + last_pass: u64, +} + +/// A placement the palette started and repeats, until its INSERT ends without placing anything, +/// another command starts or the drawing changes. +#[derive(Clone, Debug)] +struct Repeating { + item: Item, + /// The drawing it goes into. + uid: u64, + /// The INSERT's number in the session's count of commands. + started: u64, + explode: bool, +} + +impl Repeating { + /// The placement of `item`, whose INSERT has just started; `None` with no drawing. + fn started_now(app: &CadApp, item: Item, explode: bool) -> Option { + let uid = drawing_uid(app)?; + Some(Repeating { item, uid, started: app.session.commands_started, explode }) + } +} + +impl Default for State { + fn default() -> Self { + State { + tab: Tab::default(), + view: View::default(), + filter: String::new(), + selected: None, + libraries: None, + library: None, + new_library: String::new(), + refresh: 0, + reading: false, + scale_on_screen: false, + scale: [1.0; 3], + rotation_on_screen: false, + rotation: 0.0, + explode: false, + repeat: true, + repeating: None, + last_pass: 0, + } + } +} + +/// Where a gallery item comes from. +#[derive(Clone, Debug, PartialEq)] +enum Source { + /// A block of the current drawing. + Current, + /// A block of a library drawing, defined here when placed. + LibraryBlock { path: String }, + /// A drawing of a library folder, placed as a block named after it. + LibraryDrawing { path: String }, +} + +/// A block and the drawing it belongs to, to draw its picture when it is needed. +#[derive(Clone)] +struct Lazy { + doc: Arc, + block: Arc, +} + +impl std::fmt::Debug for Lazy { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Lazy({})", self.block.name) + } +} + +/// One tile of the gallery. +#[derive(Clone, Debug)] +struct Item { + /// What the item is selected by: unique within the gallery. + id: String, + /// The block name (the file name of a drawing). + label: String, + description: String, + /// What the picture is drawn from once the tile is on screen; `None` has no picture. + picture: Option, + source: Source, +} + +impl PartialEq for Item { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } +} + +/// A gallery's items, and whether a hostile or huge file left some of them out. +#[derive(Clone, Debug, Default)] +struct Listing { + items: Arc>, + truncated: bool, +} + +/// A block's preview, or the fact that it cannot have one. +#[derive(Clone, Debug)] +enum Picture { + Ready(Arc), + Unavailable, +} + +/// A remembered preview. +#[derive(Debug)] +struct Kept { + picture: Picture, + /// The frame that last showed it. + used: u64, + points: usize, + /// It belongs to the current drawing's tab. + current: bool, +} + +/// The previews in memory, by item and block definition, bounded in points: what no frame shows +/// goes first, so scrolling back rebuilds as little as possible and visible tiles never thrash. +#[derive(Debug, Default)] +struct Pictures { + map: HashMap<(String, usize), Kept>, + points: usize, + tick: u64, +} + +impl Pictures { + /// The preview kept for `key`, marked as shown on this frame. + fn get(&mut self, key: &(String, usize)) -> Option { + let tick = self.tick; + self.map.get_mut(key).map(|k| { + k.used = tick; + k.picture.clone() + }) + } + + /// Keep `picture` under `key`, dropping the oldest unshown ones while over the point budget. + fn insert(&mut self, key: (String, usize), picture: Picture, current: bool) { + if self.map.len() >= MAX_CACHED_PICTURES { + self.map.clear(); + self.points = 0; + } + let points = match &picture { + Picture::Ready(shape) => shape.points(), + Picture::Unavailable => 0, + }; + self.points = self.points.saturating_add(points); + if let Some(old) = self.map.insert(key, Kept { picture, used: self.tick, points, current }) { + self.points = self.points.saturating_sub(old.points); + } + while self.points > MAX_CACHED_POINTS { + let oldest = self.map.iter().filter(|(_, k)| k.used < self.tick && k.points > 0).min_by_key(|(_, k)| k.used).map(|(key, _)| key.clone()); + let Some(kept) = oldest.and_then(|key| self.map.remove(&key)) else { break }; + self.points = self.points.saturating_sub(kept.points); + } + } + + /// Forget the current drawing's previews: a nested block may look different now. + fn drop_current(&mut self) { + self.map.retain(|_, k| !k.current); + self.recount(); + } + + /// Forget the libraries' previews: a library read again has new block definitions, and one may + /// sit where a freed one did, under the same key. + fn drop_libraries(&mut self) { + self.map.retain(|_, k| k.current); + self.recount(); + } + + /// Add up the points the kept previews hold. + fn recount(&mut self) { + self.points = self.map.values().map(|k| k.points).fold(0, usize::saturating_add); + } +} + +/// The previews, shared across frames. +type SharedPictures = Arc>; + +/// The current drawing's blocks. The list is rebuilt when the drawing changes; the pictures are +/// drawn later, for the tiles on screen, and stay while the definitions stay as they were. +fn current_items(app: &mut CadApp, ui: &egui::Ui, pictures: &SharedPictures) -> Listing { + let Ok(key) = app.session.state().map(|st| (st.uid, st.revision)) else { return Listing::default() }; + let id = egui::Id::unique("blocks-current"); + if let Some((k, listing)) = ui.data(|d| d.get_temp::<((u64, u64), Listing)>(id)) + && k == key + { + return listing; + } + // The palette shows no reference counts, and counting reads every object after each edit. + let listed = app.run("blockspalette", json!({ "references": false })).unwrap_or(Value::Null); + let Ok(st) = app.session.state() else { return Listing::default() }; + let defs: Arc> = Arc::new(st.doc.blocks.iter().map(|(k, b)| (k.clone(), Arc::as_ptr(b) as usize)).collect()); + let defs_id = egui::Id::unique("blocks-definitions"); + if let Some((uid, old)) = ui.data(|d| d.get_temp::<(u64, Arc>)>(defs_id)) + && uid == key.0 + && old.iter().any(|(name, at)| defs.get(name) != Some(at)) + { + pictures.lock().unwrap_or_else(PoisonError::into_inner).drop_current(); + } + let items: Vec = listed + .get("blocks") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(|b| { + let name = b.get("name")?.as_str()?.to_string(); + Some(Item { + id: name.clone(), + description: b.get("description").and_then(Value::as_str).unwrap_or_default().to_string(), + picture: st.doc.block(&name).map(|block| Lazy { doc: st.doc.clone(), block: block.clone() }), + label: name, + source: Source::Current, + }) + }) + .collect() + }) + .unwrap_or_default(); + let truncated = listed.get("truncated").and_then(Value::as_bool).unwrap_or(false); + let listing = Listing { items: Arc::new(items), truncated }; + ui.data_mut(|d| { + d.insert_temp(defs_id, (key.0, defs)); + d.insert_temp(id, (key, listing.clone())); + }); + listing +} + +/// The contents of a library, or why it cannot be read. +type Loaded = Result; + +/// Where a library's contents arrive: empty until they are read. +type Slot = Arc>>; + +/// The library the palette shows. +#[derive(Clone)] +struct Library { + path: String, + refresh: u32, + slot: Slot, +} + +/// How many libraries may be read at once: a quick switch between big libraries must not pile up +/// threads reading them. A read beyond that waits, and the palette says it is reading. +const MAX_READS: usize = 4; + +/// The reads running, counted so that no more than `max` run at once. +struct Reads { + running: AtomicUsize, + max: usize, +} + +static READS: Reads = Reads { running: AtomicUsize::new(0), max: MAX_READS }; + +/// One place among the running reads, given back when it is dropped. +struct Read<'a>(&'a Reads); + +impl Reads { + /// A place for a new read, or `None` while `max` are running. + fn take(&self) -> Option> { + let mut n = self.running.load(Ordering::Acquire); + while n < self.max { + match self.running.compare_exchange_weak(n, n + 1, Ordering::AcqRel, Ordering::Acquire) { + Ok(_) => return Some(Read(self)), + Err(now) => n = now, + } + } + None + } +} + +impl Drop for Read<'_> { + fn drop(&mut self) { + self.0.running.fetch_sub(1, Ordering::AcqRel); + } +} + +/// What a library holds, read once and kept until Refresh, or `None` while it is being read (or +/// waits for a place among the running reads). +fn library_items(ui: &egui::Ui, path: &str, refresh: u32, pictures: &SharedPictures) -> Option { + let id = egui::Id::unique("blocks-library"); + let known = ui.data(|d| d.get_temp::(id)).filter(|l| l.path == path && l.refresh == refresh); + let library = match known { + Some(library) => library, + None => { + let Some(place) = READS.take() else { + ui.ctx().request_repaint_after(Duration::from_millis(100)); + return None; + }; + pictures.lock().unwrap_or_else(PoisonError::into_inner).drop_libraries(); + let library = Library { path: path.to_string(), refresh, slot: read_in_background(ui.ctx(), path, place) }; + ui.data_mut(|d| d.insert_temp(id, library.clone())); + library + } + }; + library.slot.lock().unwrap_or_else(PoisonError::into_inner).clone() +} + +/// Read a library on a worker thread: a big drawing or a slow network folder must not stop the +/// interface. The web has no threads and reads it now, as OPEN does. +fn read_in_background(ctx: &egui::Context, path: &str, place: Read<'static>) -> Slot { + #[cfg(not(target_arch = "wasm32"))] + { + let slot = Slot::default(); + let (out, ctx, owned) = (slot.clone(), ctx.clone(), path.to_string()); + let worker = std::thread::Builder::new().name("block-library".into()).spawn(move || { + let _place = place; + let loaded = catch_unwind(|| read_library(&owned)).unwrap_or_else(|_| Err(format!("{owned}: the file could not be read"))); + *out.lock().unwrap_or_else(PoisonError::into_inner) = Some(loaded); + ctx.request_repaint(); + }); + // No thread to read on: read it here. + if worker.is_err() { + *slot.lock().unwrap_or_else(PoisonError::into_inner) = Some(read_library(path)); + } + slot + } + #[cfg(target_arch = "wasm32")] + { + let _ = (ctx, place); + Arc::new(Mutex::new(Some(read_library(path)))) + } +} + +/// What a library holds: the blocks of a drawing file, or the drawings of a folder. +fn read_library(path: &str) -> Loaded { + let listed = cadcraft_engine::cmd::list_library(path).map_err(|e| e.to_string())?; + let text = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + let truncated = listed.get("truncated").and_then(Value::as_bool).unwrap_or(false); + if listed.get("kind").and_then(Value::as_str) == Some("folder") { + let files = listed.get("files").and_then(Value::as_array).cloned().unwrap_or_default(); + let items = files + .iter() + .map(|f| Item { + id: text(f, "file"), + label: text(f, "name"), + description: text(f, "file"), + picture: None, + source: Source::LibraryDrawing { path: text(f, "file") }, + }) + .collect(); + return Ok(Listing { items: Arc::new(items), truncated }); + } + // A drawing file: its blocks, drawn from the file itself. + let drawing = cadcraft_engine::cmd::read_library_file(path).ok(); + let blocks = listed.get("blocks").and_then(Value::as_array).cloned().unwrap_or_default(); + let items = blocks + .iter() + .map(|b| { + let name = text(b, "name"); + let picture = drawing.as_ref().and_then(|d| d.block(&name).map(|block| Lazy { doc: d.clone(), block: block.clone() })); + Item { + id: format!("{path}|{name}"), + description: text(b, "description"), + picture, + label: name, + source: Source::LibraryBlock { path: path.to_string() }, + } + }) + .collect(); + Ok(Listing { items: Arc::new(items), truncated }) +} + +/// A block's picture: polylines and filled triangles in a unit box (aspect kept, centred, Y up +/// as in the drawing), each with its colour (`None`: the interface's text colour, which stands +/// for white and black, colour 7). +#[derive(Clone, Debug, Default)] +struct Shape { + lines: Vec<(Option, Vec)>, + /// Three points per triangle. + tris: Vec<(Option, Vec)>, +} + +impl Shape { + /// How many points the preview holds. + fn points(&self) -> usize { + self.lines.iter().chain(&self.tris).map(|(_, l)| l.len()).fold(0, usize::saturating_add) + } +} + +/// Cancels a build when `deadline` passes, unless the returned channel is dropped first. +#[cfg(not(target_arch = "wasm32"))] +fn watchdog(cancel: Arc, deadline: Duration) -> Option<(std::sync::mpsc::Sender<()>, std::thread::JoinHandle<()>)> { + use std::sync::mpsc::{RecvTimeoutError, channel}; + let (done, wait) = channel::<()>(); + let timer = std::thread::Builder::new().name("block-preview-deadline".into()).spawn(move || { + if matches!(wait.recv_timeout(deadline), Err(RecvTimeoutError::Timeout)) { + cancel.store(true, Ordering::Relaxed); + } + }); + timer.ok().map(|timer| (done, timer)) +} + +/// Build the display list of `ents`, or `None` when it panics, is cancelled or takes too long +/// (there is no timer on the web, where the block's size and the renderer's own limits apply). +fn build_within(d: &Drawing, ents: &[&Entity], mut opts: Options, cancel: &Arc, deadline: Option) -> Option { + opts.cancel = Some(cancel.clone()); + #[cfg(not(target_arch = "wasm32"))] + let timer = deadline.and_then(|t| watchdog(cancel.clone(), t)); + #[cfg(target_arch = "wasm32")] + let _ = deadline; + let built = catch_unwind(AssertUnwindSafe(|| build_entities(d, ents.iter().copied(), &opts))); + #[cfg(not(target_arch = "wasm32"))] + if let Some((done, timer)) = timer { + drop(done); + let _ = timer.join(); + } + if cancel.load(Ordering::Relaxed) { None } else { built.ok() } +} + +/// What is left of `deadline` after `spent` (still `None` where there is no deadline). +fn left(deadline: Option, spent: Duration) -> Option { + deadline.map(|d| d.saturating_sub(spent)) +} + +/// The picture of a block, drawn now. +fn picture(lazy: &Lazy) -> Picture { + let cancel = Arc::new(AtomicBool::new(false)); + match outline(&lazy.doc, &lazy.block, &cancel, Some(PREVIEW_DEADLINE)) { + Some(shape) => Picture::Ready(Arc::new(shape)), + None => Picture::Unavailable, + } +} + +/// `text`, cut to `max` characters. +fn clipped(text: &str, max: usize) -> std::borrow::Cow<'_, str> { + match text.char_indices().nth(max) { + Some((end, _)) => format!("{}…", text.get(..end).unwrap_or_default()).into(), + None => text.into(), + } +} + +/// Take `n` from the work left, one at least (looking at an empty object is work too); `None` +/// when there is not that much. +fn spend(left: &mut usize, n: usize) -> Option<()> { + *left = left.checked_sub(n.max(1))?; + Some(()) +} + +/// The sum of what `sizes` yields. +fn total(sizes: impl Iterator) -> usize { + sizes.fold(0, usize::saturating_add) +} + +/// What drawing `text` costs. +fn text_work(text: &str) -> usize { + text.len().saturating_mul(TEXT_WORK) +} + +/// The vertices of filled loops. +fn loop_vertices(loops: &[HatchLoop]) -> usize { + total(loops.iter().map(|l| l.vertices.len())) +} + +/// What the block `name` costs, drawn `times` times: what it costs once, multiplied. +fn block_work(d: &Drawing, name: &str, times: usize, depth: usize, left: &mut usize) -> Option<()> { + let Some(inner) = d.block(name) else { return Some(()) }; + if depth >= MAX_BLOCK_DEPTH { + return None; + } + let mut once = *left; + for e in inner.entities.iter() { + work_of(d, e, depth + 1, &mut once)?; + } + spend(left, left.saturating_sub(once).saturating_mul(times)) +} + +/// What a block reference costs: its attributes, and its block once for each cell of its array. +fn reference_work(d: &Drawing, i: &Insert, depth: usize, left: &mut usize) -> Option<()> { + spend(left, total(i.attribs.iter().map(|a| text_work(&a.text.value))))?; + let cells = (i.rows.max(1) as usize).saturating_mul(i.cols.max(1) as usize); + block_work(d, &i.block, cells, depth, left) +} + +/// What drawing `e` costs, counted before it is drawn: its vertices, control points and +/// characters, and the blocks it draws. `None` when the cost is not worth knowing (it is too big). +fn work_of(d: &Drawing, e: &Entity, depth: usize, left: &mut usize) -> Option<()> { + match &e.kind { + EntityKind::LwPolyline(p) => spend(left, p.vertices.len()), + EntityKind::Polyline3d(p) => spend(left, p.points.len()), + EntityKind::Spline(sp) => spend(left, sp.control.len().saturating_add(sp.fit.len())), + EntityKind::MLine(m) => spend(left, m.vertices.len().saturating_mul(m.def.elements.len().max(1))), + EntityKind::Leader(l) => spend(left, l.vertices.len()), + EntityKind::Wipeout(w) => spend(left, w.boundary.len()), + EntityKind::Region(r) => spend(left, loop_vertices(&r.loops)), + EntityKind::Hatch(h) => spend(left, loop_vertices(&h.loops).saturating_add(h.pattern_lines.len())), + EntityKind::Text(t) => spend(left, text_work(&t.value)), + EntityKind::MText(t) => spend(left, text_work(&t.contents)), + EntityKind::AttDef(a) => spend(left, text_work(&a.tag)), + EntityKind::Table(t) => spend(left, total(t.cells.iter().flatten().map(|c| text_work(&c.text).saturating_add(1)))), + EntityKind::Insert(i) => reference_work(d, i, depth, left), + EntityKind::Dimension(dm) => { + spend(left, 1)?; + dm.block.as_ref().map_or(Some(()), |name| block_work(d, name, 1, depth, left)) + } + EntityKind::MLeader(m) => { + spend(left, total(m.leaders.iter().map(Vec::len)).saturating_add(m.text.as_ref().map_or(0, |t| text_work(&t.contents))))?; + m.block.as_ref().map_or(Some(()), |i| reference_work(d, i, depth, left)) + } + _ => spend(left, 1), + } +} + +/// Whether the objects can be drawn within the preview's work limit, counted before any drawing. +fn affordable(d: &Drawing, ents: &[&Entity]) -> bool { + let mut left = PREVIEW_WORK; + ents.iter().all(|e| work_of(d, e, 0, &mut left).is_some()) +} + +/// The block as the canvas draws it (nested blocks, splines, text and fills included), each +/// object in its colour. A huge block's picture holds only a first part. `None`: the block is too +/// big, or drawing it was cancelled, took too long or failed. +fn outline(d: &Drawing, b: &Block, cancel: &Arc, deadline: Option) -> Option { + let ents: Vec<&Entity> = b.entities.iter().take(PREVIEW_ENTITIES.saturating_add(1)).map(|e| &**e).collect(); + if ents.len() > PREVIEW_ENTITIES { + return None; + } + if ents.is_empty() { + return Some(Shape::default()); + } + if !affordable(d, &ents) { + return None; + } + // A coarse pass for the size, then one detailed to match it. The view height is given, so a + // point is sized by the block and the drawing is not scanned for its extents. + let coarse = Options { tolerance: 1.0, min_dash: NO_DASHES, lineweights: false, view_height: 1.0, ..Options::default() }; + #[cfg(not(target_arch = "wasm32"))] + let started = std::time::Instant::now(); + let first = build_within(d, &ents, coarse, cancel, deadline)?; + // The two passes share one deadline: a preview takes `PREVIEW_DEADLINE` at most, not twice that. + #[cfg(not(target_arch = "wasm32"))] + let deadline = left(deadline, started.elapsed()); + let span = first.bounds.width().max(first.bounds.height()); + if !(span.is_finite() && span > 0.0) { + return Some(Shape::default()); + } + let opts = + Options { tolerance: span / PREVIEW_DETAIL, min_dash: span / PREVIEW_DETAIL, lineweights: false, view_height: span, ..Options::default() }; + let list = build_within(d, &ents, opts, cancel, deadline)?; + let mut lines: Vec<(Option, Vec)> = Vec::new(); + let mut tris: Vec<(Option, Vec)> = Vec::new(); + let mut budget = PREVIEW_POINTS; + for p in &list.prims { + let color = (!p.aci7).then(|| Color32::from_rgb(p.color.0, p.color.1, p.color.2)); + let (start, len) = (p.start as usize, p.len as usize); + match p.kind { + Kind::Polyline => { + let Some(pts) = list.verts.get(start..start.saturating_add(len)) else { continue }; + if pts.len() > budget { + break; + } + budget -= pts.len(); + lines.push((color, pts.to_vec())); + } + Kind::Tris => { + let Some(pts) = list.tris.get(start..start.saturating_add(len)) else { continue }; + if pts.len() > budget { + break; + } + budget -= pts.len(); + tris.push((color, pts.to_vec())); + } + _ => {} + } + } + let finite = |p: &&Vec2| p.x.is_finite() && p.y.is_finite(); + let bounds = Bounds2::from_points(lines.iter().chain(tris.iter()).flat_map(|(_, l)| l).filter(finite).copied()); + if bounds.is_empty() { + return Some(Shape::default()); + } + let span = bounds.width().max(bounds.height()).max(1e-9); + let c = bounds.center(); + let norm = |p: &Vec2| Pos2::new((0.5 + (p.x - c.x) / span) as f32, (0.5 - (p.y - c.y) / span) as f32); + // A triangle with a corner that is not a number is left out whole. + let whole = |t: &&[Vec2; 3]| t.iter().all(|p| p.x.is_finite() && p.y.is_finite()); + Some(Shape { + lines: lines.iter().map(|(c, l)| (*c, l.iter().filter(finite).map(norm).collect())).collect(), + tris: tris.iter().map(|(c, l)| (*c, l.as_chunks::<3>().0.iter().filter(whole).flatten().map(norm).collect())).collect(), + }) +} + +/// What a frame of the gallery draws its pictures with. +struct Painting<'a> { + pictures: &'a mut Pictures, + builds_left: usize, + /// When the frame stops building previews (the web has no clock to read, so no limit there). + #[cfg(not(target_arch = "wasm32"))] + until: std::time::Instant, +} + +impl<'a> Painting<'a> { + /// A frame's painting, with its whole allowance of previews and time. + fn new(pictures: &'a mut Pictures) -> Self { + Self { + pictures, + builds_left: BUILDS_PER_FRAME, + #[cfg(not(target_arch = "wasm32"))] + until: std::time::Instant::now() + PREVIEW_DEADLINE, + } + } + + /// Whether the frame has used its time: what is still to build waits for the next frame. + fn out_of_time(&self) -> bool { + #[cfg(not(target_arch = "wasm32"))] + return std::time::Instant::now() >= self.until; + #[cfg(target_arch = "wasm32")] + false + } +} + +/// The tile's picture: remembered, or drawn now if the frame still has room for it. A tile that +/// has to wait asks for another frame. +fn shape_of(ui: &egui::Ui, item: &Item, painting: &mut Painting<'_>) -> Option> { + let lazy = item.picture.as_ref()?; + let key = (item.id.clone(), Arc::as_ptr(&lazy.block) as usize); + let known = match painting.pictures.get(&key) { + Some(known) => known, + None if painting.builds_left > 0 && !painting.out_of_time() => { + painting.builds_left -= 1; + let built = picture(lazy); + // A block that took all its time is enough for one frame. + if matches!(built, Picture::Unavailable) { + painting.builds_left = 0; + } + painting.pictures.insert(key, built.clone(), item.source == Source::Current); + built + } + None => { + ui.ctx().request_repaint(); + return None; + } + }; + match known { + Picture::Ready(shape) => Some(shape), + Picture::Unavailable => None, + } +} + +/// Draw the preview in `rect`, or a placeholder when there is none. +fn paint_preview(ui: &egui::Ui, rect: egui::Rect, shape: Option<&Shape>, color: Color32) { + let side = rect.width().min(rect.height()) * 0.86; + let origin = rect.center() - vec2(side, side) / 2.0; + let painter = ui.painter_at(rect); + let Some(shape) = shape.filter(|s| !s.lines.is_empty() || !s.tris.is_empty()) else { + // No picture (a drawing of a library folder, or a block without one): a page with a + // folded corner. + let w = side * 0.62; + let page = egui::Rect::from_center_size(rect.center(), vec2(w, side)); + let fold = w * 0.3; + let pts = vec![ + page.left_top(), + egui::pos2(page.right() - fold, page.top()), + egui::pos2(page.right(), page.top() + fold), + page.right_bottom(), + page.left_bottom(), + page.left_top(), + ]; + painter.add(egui::Shape::line(pts, Stroke::new(1.0, color))); + return; + }; + for (c, line) in &shape.lines { + let pts: Vec = line.iter().map(|p| origin + vec2(p.x * side, p.y * side)).collect(); + painter.add(egui::Shape::line(pts, Stroke::new(1.0, c.unwrap_or(color)))); + } + for (c, tris) in &shape.tris { + let mut mesh = egui::Mesh::default(); + for p in tris { + mesh.colored_vertex(origin + vec2(p.x * side, p.y * side), c.unwrap_or(color)); + } + let n = u32::try_from(tris.len()).unwrap_or(0) / 3 * 3; + mesh.indices.extend(0..n); + painter.add(egui::Shape::mesh(mesh)); + } +} + +/// What a click in the palette asks for, run once the palette is drawn. +enum Act { + Insert { item: Item, explode: bool }, + AddLibrary(String), + PickLibrary, + RemoveLibrary(String), +} + +/// The palette body. +pub fn section(app: &mut CadApp, ui: &mut egui::Ui) { + let t = crate::theme::Tokens::get(); + let state_id = egui::Id::unique("blocks-state"); + let mut st: State = ui.data(|d| d.get_temp(state_id)).unwrap_or_default(); + let mut act = None; + if st.libraries.is_none() { + st.libraries = Some(libraries(app, json!({}))); + } + + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.add_space(8.0); + for (tab, label) in [(Tab::Current, crate::tl!("Current Drawing")), (Tab::Libraries, crate::tl!("Libraries"))] { + if ui.selectable_label(st.tab == tab, label).clicked() { + st.tab = tab; + } + } + }); + if st.tab == Tab::Libraries { + libraries_bar(ui, &mut st, &mut act); + } + ui.horizontal(|ui| { + ui.add_space(8.0); + let w = (ui.available_width() - 150.0).max(80.0); + ui.add(egui::TextEdit::singleline(&mut st.filter).hint_text(crate::tl!("Filter")).desired_width(w)); + let view_label = ui.label(crate::tl!("View")); + craft_ui::ComboBox::from_id_salt("blocks-view") + .selected_text(st.view.label()) + .show_ui(ui, |ui| { + for v in View::ALL { + ui.selectable_value(&mut st.view, v, v.label()); + } + }) + .response + .labelled_by(view_label.id); + }); + ui.add_space(4.0); + + let pictures: SharedPictures = ui.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::unique("blocks-pictures")).clone()); + let mut reading = false; + let loaded: Loaded = match (st.tab, st.library.clone()) { + (Tab::Current, _) => Ok(current_items(app, ui, &pictures)), + (Tab::Libraries, Some(path)) => match library_items(ui, &path, st.refresh, &pictures) { + Some(loaded) => loaded, + None => { + reading = true; + Ok(Listing::default()) + } + }, + (Tab::Libraries, None) => Ok(Listing::default()), + }; + st.reading = reading; + let wanted = st.filter.trim().to_lowercase(); + let items: Vec<&Item> = + loaded.as_ref().map(|l| l.items.iter().filter(|i| wanted.is_empty() || named(&i.label, &wanted)).collect()).unwrap_or_default(); + if let Ok(listing) = &loaded + && listing.truncated + { + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.label(RichText::new(crate::tf!("Only the first {n} are shown.", n = listing.items.len())).color(t.warn)); + }); + } + + let options_h = 150.0; + // The panel scrolls when it is shorter than the gallery and the options together. + let room = ui.available_height(); + let gallery_h = if room.is_finite() { (room - options_h).clamp(150.0, 600.0) } else { 260.0 }; + egui::ScrollArea::vertical().id_salt("blocks-gallery").max_height(gallery_h).auto_shrink([false, false]).show(ui, |ui| { + if items.is_empty() { + ui.horizontal_wrapped(|ui| { + ui.add_space(8.0); + let msg = match (&loaded, st.tab, st.library.is_some(), st.filter.trim().is_empty()) { + _ if reading => crate::tl!("Reading the library...").to_string(), + (Err(e), ..) => e.clone(), + (_, Tab::Libraries, false, _) => crate::tl!("Add a folder of drawings or a drawing file to use its blocks.").to_string(), + (_, Tab::Libraries, true, true) => crate::tl!("This library has no drawings or blocks.").to_string(), + (_, Tab::Current, _, true) => crate::tl!("This drawing has no blocks.").to_string(), + _ => crate::tl!("No block matches the filter.").to_string(), + }; + ui.label(RichText::new(msg).color(t.text_dim)); + }); + return; + } + let mut kept = pictures.lock().unwrap_or_else(PoisonError::into_inner); + kept.tick = kept.tick.wrapping_add(1); + let mut painting = Painting::new(&mut kept); + let mut selected = st.selected.clone(); + gallery(ui, st.view, &items, &mut act, &mut selected, &mut painting); + st.selected = selected; + }); + + ui.add_space(4.0); + ui.separator(); + let placing = app.session.prompt_text() != "Command:"; + ui.add_enabled_ui(!placing, |ui| options(ui, &mut st)); + + repeat_placement(app, ui, &mut st); + match act { + Some(Act::Insert { item, explode }) => { + st.selected = Some(item.id.clone()); + announce_existing(app, &item); + if insert(app, &item, &st, explode) && st.repeat { + st.repeating = Repeating::started_now(app, item, explode); + } + } + Some(Act::PickLibrary) => { + if let Some(path) = app.services.pick_open.as_ref().and_then(|f| f()) { + add_library(app, &mut st, &path); + } + } + Some(Act::AddLibrary(path)) => add_library(app, &mut st, &path), + Some(Act::RemoveLibrary(path)) => { + st.libraries = Some(libraries(app, json!({ "op": "remove", "path": path }))); + if st.library.as_deref() == Some(path.as_str()) { + st.library = st.libraries.as_ref().and_then(|l| l.first().cloned()); + } + } + None => {} + } + ui.data_mut(|d| d.insert_temp(state_id, st)); +} + +/// Place the block again when the INSERT the palette started has finished and placed something; +/// a cancelled one (nothing changed), the Repeat option turned off or another command stops it. +fn repeat_placement(app: &mut CadApp, ui: &egui::Ui, st: &mut State) { + let pass = ui.ctx().cumulative_pass_nr(); + let watched = pass == st.last_pass.wrapping_add(1); + st.last_pass = pass; + let Some(placing) = st.repeating.clone() else { return }; + if !st.repeat || !watched || drawing_uid(app) != Some(placing.uid) { + st.repeating = None; + return; + } + let prompt = app.session.prompt_text(); + if prompt != "Command:" { + // Still placing it. A command started since ends the repeating; a transparent 'ZOOM or 'PAN + // inside the INSERT (prompt `>>ZOOM`) does not count as one. + if app.session.commands_started != placing.started { + st.repeating = None; + } + return; + } + st.repeating = None; + // Only this INSERT placing something repeats it: it may have been cancelled, and a command + // started since means the user moved on, even one that ended before this frame (queued control + // requests do that). A JSON command does not count: it never stops a running command, so it + // leaves the repeat alone whichever side of this frame it lands. + let session = &app.session; + if session.commands_started != placing.started || session.last_finished != Some((placing.started, true)) { + return; + } + if insert(app, &placing.item, st, placing.explode) { + st.repeating = Repeating::started_now(app, placing.item, placing.explode); + ui.ctx().request_repaint(); + } +} + +/// Which drawing is active: a repeat placement belongs to the one it started in. +fn drawing_uid(app: &CadApp) -> Option { + app.session.state().ok().map(|st| st.uid) +} + +/// The library list after `params` (`{}` just reads it). An engine error goes to the status line. +fn libraries(app: &mut CadApp, params: Value) -> Vec { + match app.run("blocklibraries", params) { + Ok(v) => v + .get("libraries") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|p| p.as_str().map(str::to_string)).collect()) + .unwrap_or_default(), + Err(e) => { + app.set_status(e); + Vec::new() + } + } +} + +/// Add a library to the list and show it. +fn add_library(app: &mut CadApp, st: &mut State, path: &str) { + match app.run("blocklibraries", json!({ "op": "add", "path": path })) { + Ok(v) => { + let list: Vec = v + .get("libraries") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|p| p.as_str().map(str::to_string)).collect()) + .unwrap_or_default(); + st.library = v.get("path").and_then(Value::as_str).map(str::to_string).or_else(|| list.last().cloned()); + st.libraries = Some(list); + st.new_library.clear(); + st.selected = None; + st.refresh = st.refresh.wrapping_add(1); + } + Err(e) => app.set_status(e), + } +} + +/// The last part of a path: what a library is called in the list. +fn short(path: &str) -> &str { + path.trim_end_matches(['/', '\\']).rsplit(['/', '\\']).next().unwrap_or(path) +} + +/// The library list with what manages it: add (picked or typed), refresh, remove. +fn libraries_bar(ui: &mut egui::Ui, st: &mut State, act: &mut Option) { + let t = crate::theme::Tokens::get(); + ui.horizontal(|ui| { + ui.add_space(8.0); + if ui.button(crate::tl!("Open Library...")).on_hover_text(crate::tl!("Add a drawing file as a block library")).clicked() { + *act = Some(Act::PickLibrary); + } + if ui + .add_enabled(st.library.is_some() && !st.reading, egui::Button::new(crate::tl!("Refresh"))) + .on_hover_text(crate::tl!("Read the library again")) + .clicked() + { + // The files are parsed again, even one whose size and time look the same. + cadcraft_engine::cmd::clear_library_cache(); + st.refresh = st.refresh.wrapping_add(1); + } + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + let label = ui.label(crate::tl!("Folder or file")); + let w = (ui.available_width() - 70.0).max(60.0); + let edit = ui.add(egui::TextEdit::singleline(&mut st.new_library).desired_width(w)).labelled_by(label.id); + let typed = !st.new_library.trim().is_empty(); + let add = ui.add_enabled(typed, egui::Button::new(crate::tl!("Add"))).clicked() + || (typed && edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))); + if add { + *act = Some(Act::AddLibrary(st.new_library.trim().to_string())); + } + }); + let libs = st.libraries.clone().unwrap_or_default(); + if libs.is_empty() { + return; + } + egui::ScrollArea::vertical().id_salt("blocks-libraries").max_height(88.0).auto_shrink([false, true]).show(ui, |ui| { + for path in &libs { + ui.horizontal(|ui| { + ui.add_space(8.0); + let on = st.library.as_deref() == Some(path.as_str()); + let w = (ui.available_width() - 34.0).max(40.0); + let row = ui.add_sized([w, 20.0], egui::Button::selectable(on, short(path)).frame_when_inactive(false).truncate()); + if row.on_hover_text(path).clicked() && !on { + st.library = Some(path.clone()); + st.selected = None; + } + let remove = ui.small_button("×").on_hover_text(crate::tl!("Remove from the list")); + remove.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{} {}", crate::tl!("Remove"), short(path)))); + if remove.clicked() { + *act = Some(Act::RemoveLibrary(path.clone())); + } + }); + } + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + if let Some(p) = &st.library { + ui.add(egui::Label::new(RichText::new(p).color(t.text_dim).small()).truncate()); + } + }); +} + +/// The tiles or rows of the gallery; a click sets `act`. +fn gallery(ui: &mut egui::Ui, view: View, items: &[&Item], act: &mut Option, selected: &mut Option, painting: &mut Painting<'_>) { + let t = crate::theme::Tokens::get(); + let on_menu = |ui: &mut egui::Ui, item: &Item, act: &mut Option| { + if ui.button(crate::tl!("Insert")).clicked() { + *act = Some(Act::Insert { item: item.clone(), explode: false }); + ui.close(); + } + if ui.button(crate::tl!("Insert and Explode")).clicked() { + *act = Some(Act::Insert { item: item.clone(), explode: true }); + ui.close(); + } + }; + let react = |resp: &egui::Response, item: &Item, act: &mut Option, selected: &mut Option| { + // A click selects the block and starts placing it. + if resp.clicked() { + *selected = Some(item.id.clone()); + *act = Some(Act::Insert { item: item.clone(), explode: false }); + } + }; + match view.tile() { + Some(side) => { + ui.horizontal_wrapped(|ui| { + ui.add_space(8.0); + ui.spacing_mut().item_spacing = vec2(6.0, 6.0); + for &item in items { + let (rect, resp) = ui.allocate_exact_size(vec2(side, side + 32.0), Sense::click()); + let name = clipped(&item.label, MAX_NAME_CHARS); + // Only the tiles on screen are drawn, and only they build a picture. + if ui.is_rect_visible(rect) { + let on = selected.as_deref() == Some(item.id.as_str()); + if on || resp.hovered() { + ui.painter().rect_filled(rect, 3.0, if on { t.selection } else { t.hover }); + } + let art = egui::Rect::from_min_size(rect.min, vec2(side, side)); + paint_preview(ui, art, shape_of(ui, item, painting).as_deref(), t.text); + // The name under the icon: up to two lines, cut with an ellipsis, centred in the tile. + let mut job = egui::text::LayoutJob::simple(name.to_string(), egui::FontId::proportional(11.0), t.text, side - 4.0); + job.wrap.max_rows = 2; + job.wrap.break_anywhere = true; + job.halign = egui::Align::Center; + let galley = ui.painter().layout_job(job); + let at = egui::pos2(rect.center().x - galley.rect.center().x, rect.min.y + side + 2.0); + ui.painter().galley(at, galley, t.text); + } + let tip = if item.description.is_empty() { + name.to_string() + } else { + format!("{name}\n{}", clipped(&item.description, MAX_DESCRIPTION_CHARS)) + }; + let resp = resp.on_hover_text(tip); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name.to_string())); + react(&resp, item, act, selected); + resp.context_menu(|ui| on_menu(ui, item, act)); + } + }); + } + None => { + let details = view == View::Details; + for &item in items { + let h = if details { 30.0 } else { 20.0 }; + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click()); + let name = clipped(&item.label, MAX_NAME_CHARS); + if ui.is_rect_visible(rect) { + let on = selected.as_deref() == Some(item.id.as_str()); + if on || resp.hovered() { + ui.painter().rect_filled(rect, 2.0, if on { t.selection } else { t.hover }); + } + let mut x = rect.min.x + 8.0; + if details { + let art = egui::Rect::from_min_size(egui::pos2(x, rect.min.y), vec2(h, h)); + paint_preview(ui, art, shape_of(ui, item, painting).as_deref(), t.text); + x += h + 8.0; + } + let font = egui::FontId::proportional(12.0); + ui.painter().text(egui::pos2(x, rect.center().y), egui::Align2::LEFT_CENTER, &name, font.clone(), t.text); + if details { + let x2 = rect.min.x + (rect.width() * 0.45).max(120.0); + let description = clipped(&item.description, MAX_DESCRIPTION_CHARS); + ui.painter().text(egui::pos2(x2, rect.center().y), egui::Align2::LEFT_CENTER, &description, font, t.text_dim); + } + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name.to_string())); + react(&resp, item, act, selected); + resp.context_menu(|ui| on_menu(ui, item, act)); + } + } + } +} + +/// The insertion options: what INSERT asks on the drawing, or the values used instead. +fn options(ui: &mut egui::Ui, st: &mut State) { + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.label(RichText::new(crate::tl!("Options")).strong()); + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.checkbox(&mut st.scale_on_screen, crate::tl!("Scale")); + ui.add_enabled_ui(!st.scale_on_screen, |ui| { + for (axis, v) in ["X", "Y", "Z"].iter().zip(st.scale.iter_mut()) { + let label = ui.label(*axis); + ui.add(egui::DragValue::new(v).speed(0.1)).labelled_by(label.id); + } + }); + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.checkbox(&mut st.rotation_on_screen, crate::tl!("Rotation")); + ui.add_enabled_ui(!st.rotation_on_screen, |ui| { + let label = ui.label(crate::tl!("Angle")); + ui.add(egui::DragValue::new(&mut st.rotation).speed(1.0).suffix("°")).labelled_by(label.id); + }); + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.checkbox(&mut st.explode, crate::tl!("Explode")); + ui.checkbox(&mut st.repeat, crate::tl!("Repeat Placement")); + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.label(RichText::new(crate::tl!("Click a block, then pick its insertion point.")).color(crate::theme::Tokens::get().text_dim)); + }); +} + +/// A usable scale factor: finite and not zero. +fn factor(v: f64) -> f64 { + if v.is_finite() && v != 0.0 { v } else { 1.0 } +} + +/// Say so when a click on a library tile places the drawing's own block of that name: the tile +/// shows the library's version. Only a click calls this, not each placement of a repeat. +fn announce_existing(app: &mut CadApp, item: &Item) { + let here = app.session.doc().ok().is_some_and(|d| d.block(&item.label).is_some()); + if here && !matches!(item.source, Source::Current) { + app.set_status(crate::tl!("This block is already in the drawing, so its definition is used.").to_string()); + } +} + +/// Start INSERT for the item and answer the prompts the options settle, leaving the insertion +/// point to the drawing. A library block or drawing is defined in this drawing first, unless a +/// block of that name is already here (it is never replaced). `true` when INSERT started. +fn insert(app: &mut CadApp, item: &Item, st: &State, explode: bool) -> bool { + let here = app.session.doc().ok().is_some_and(|d| d.block(&item.label).is_some()); + let name = match &item.source { + // The block (or the whole drawing) comes with only the layers, linetypes and styles it needs. + Source::LibraryBlock { path } | Source::LibraryDrawing { path } if !here => { + // A running command ends first: it would take the import into its own undo step. + if app.session.current_prompt().is_some() { + app.session.cancel(); + } + let mut params = json!({ "path": path, "name": item.label }); + if matches!(item.source, Source::LibraryBlock { .. }) { + params["block"] = json!(item.label); + } + match app.run("blocklibimport", params) { + Ok(v) => v.get("name").and_then(Value::as_str).unwrap_or(&item.label).to_string(), + Err(e) => { + app.set_status(e); + return false; + } + } + } + _ => item.label.clone(), + }; + if let Err(e) = app.session.start("insert") { + app.set_status(e.to_string()); + return false; + } + let star = explode || st.explode; + if let Err(e) = app.session.input(Input::Text(if star { format!("*{name}") } else { name })) { + app.set_status(e.to_string()); + return false; + } + // INSERT must have taken the name: the answers below would be read as block names otherwise. + if !app.session.current_prompt().is_some_and(|p| p.accept.point) { + let _ = app.session.input(Input::Cancel); + return false; + } + let mut feed = Vec::new(); + if !st.scale_on_screen { + let [x, y, z] = st.scale.map(factor); + if x == y && y == z { + feed.extend([Input::Keyword("Scale".into()), Input::Text(x.to_string())]); + } else { + for (k, v) in [("X", x), ("Y", y), ("Z", z)] { + feed.extend([Input::Keyword(k.into()), Input::Text(v.to_string())]); + } + } + } + if !st.rotation_on_screen { + let r = if st.rotation.is_finite() { st.rotation } else { 0.0 }; + // The palette shows absolute degrees: `<<` reads them whatever AUNITS, ANGBASE and ANGDIR say. + feed.extend([Input::Keyword("Rotate".into()), Input::Text(format!("<<{r}"))]); + } + for i in feed { + if let Err(e) = app.session.input(i) { + app.set_status(e.to_string()); + return false; + } + } + // The canvas reads this: a right-click at the insertion point cancels this placement. + app.canvas.palette_insert = Some(app.session.commands_started); + true +} + +/// Whether `label` matches the filter `wanted` (already lowercase), whatever the script. +fn named(label: &str, wanted: &str) -> bool { + wanted.is_empty() || label.to_lowercase().contains(wanted) +} + +#[cfg(test)] +mod tests { + #[test] + fn the_two_passes_of_a_preview_share_its_deadline() { + use std::time::Duration; + let ms = Duration::from_millis; + assert_eq!(super::left(Some(ms(100)), ms(30)), Some(ms(70))); + assert_eq!(super::left(Some(ms(100)), ms(150)), Some(Duration::ZERO), "nothing is left, never a negative time"); + assert_eq!(super::left(None, ms(30)), None, "no deadline stays none"); + } + + #[test] + fn the_filter_ignores_case_in_every_script() { + assert!(super::named("ÉCROU M8", &"écrou".to_lowercase())); + assert!(super::named("TÜR", "tür")); + assert!(super::named("Valve", "")); + assert!(!super::named("Valve", "pump")); + } + + use cadcraft_engine::Session; + use serde_json::json; + + use std::sync::Arc; + use std::sync::atomic::AtomicBool; + + use cadcraft_engine::doc::geom::Vec3; + use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, Handle, Line}; + use egui::Pos2; + + use super::{Item, Lazy, PREVIEW_ENTITIES, PREVIEW_WORK, Picture, Pictures, Shape, Source, State, affordable, clipped, insert, outline, picture}; + use crate::{CadApp, Services}; + + /// The block's picture, with no cancelling and no deadline. + fn shape(d: &Drawing, b: &Block) -> Shape { + outline(d, b, &Arc::new(AtomicBool::new(false)), None).unwrap() + } + + fn line(h: u64, a: Vec3, b: Vec3) -> Entity { + Entity::new(Handle(h), EntityKind::Line(Line { a, b })) + } + + /// Make block `name` from everything in model space now (the objects are removed). + fn make_block(s: &mut Session, name: &str) { + let handles: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({ "name": name, "base": [0, 0], "handles": handles, "keep": "delete" })).unwrap(); + } + + /// A block made only of references to another block, and one with a circle, spline-free + /// geometry and text, all have a picture, as the canvas would draw them. + #[test] + fn nested_blocks_and_text_have_a_preview() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "INNER"); + s.execute("insert", &json!({ "name": "INNER", "at": [1, 1] })).unwrap(); + s.execute("insert", &json!({ "name": "INNER", "at": [1, 3], "rotation": 90 })).unwrap(); + make_block(&mut s, "OUTER"); + let d = s.doc().unwrap(); + let outer = shape(d, d.block("OUTER").unwrap()); + assert_eq!(outer.lines.len(), 2, "both nested references are drawn"); + let inner = shape(d, d.block("INNER").unwrap()); + assert_eq!(inner.lines.len(), 1); + // Everything lies in the unit box. + assert!(outer.lines.iter().flat_map(|(_, l)| l).all(|p| (0.0..=1.0).contains(&p.x) && (0.0..=1.0).contains(&p.y))); + } + + /// A line in a colour keeps it; one in the default colour takes the interface's. + #[test] + fn previews_keep_the_colours_of_their_objects() { + let mut s = Session::new(); + s.execute("color", &json!({ "color": "red" })).unwrap(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "RED"); + s.execute("color", &json!({ "color": "ByLayer" })).unwrap(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "PLAIN"); + let d = s.doc().unwrap(); + let red = shape(d, d.block("RED").unwrap()); + assert_eq!(red.lines.first().map(|(c, _)| *c), Some(Some(egui::Color32::from_rgb(255, 0, 0)))); + let plain = shape(d, d.block("PLAIN").unwrap()); + assert_eq!(plain.lines.first().map(|(c, _)| *c), Some(None), "colour 7 follows the theme"); + } + + /// No more than `max` library reads run at once; a place comes back when its read ends. + #[test] + fn library_reads_are_limited_and_given_back() { + let reads = super::Reads { running: std::sync::atomic::AtomicUsize::new(0), max: 2 }; + let first = reads.take().expect("a first place"); + let second = reads.take().expect("a second place"); + assert!(reads.take().is_none(), "a third read waits"); + drop(first); + let third = reads.take().expect("a place came back"); + assert!(reads.take().is_none()); + drop((second, third)); + assert!(reads.take().is_some()); + } + + /// A quick right-click cancels the placement the palette started, at its insertion point only: a + /// typed INSERT keeps AutoCAD's Enter, and so does the palette's own scale prompt. + #[test] + fn right_click_cancels_a_palette_placement_at_its_insertion_point() { + use crate::canvas::right_click_cancels_placing; + let mut app = CadApp::new(Session::new(), Services::default()); + app.session.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut app.session, "BOLT"); + let st = State { scale_on_screen: true, ..State::default() }; + assert!(insert(&mut app, &item("BOLT"), &st, false)); + assert!(right_click_cancels_placing(&app)); + app.session.input(cadcraft_engine::Input::Keyword("Scale".into())).unwrap(); + let asked = app.session.current_prompt().map(|p| p.message).unwrap_or_default(); + assert_ne!(asked, "Specify insertion point", "the scale prompt is on screen: {asked}"); + assert!(!right_click_cancels_placing(&app), "the scale prompt keeps Enter"); + app.session.cancel(); + + assert!(insert(&mut app, &item("BOLT"), &State::default(), false)); + assert_eq!(app.session.current_prompt().map(|p| p.message), Some("Specify insertion point".into())); + assert!(right_click_cancels_placing(&app)); + app.session.cancel(); + assert!(!right_click_cancels_placing(&app), "nothing runs"); + + app.session.start("insert").unwrap(); + app.session.input(cadcraft_engine::Input::Text("BOLT".into())).unwrap(); + assert!(!right_click_cancels_placing(&app), "a typed INSERT is not the palette's"); + } + + fn item(name: &str) -> Item { + Item { id: name.into(), label: name.into(), description: String::new(), picture: None, source: Source::Current } + } + + /// The rotation shown in degrees is that rotation, in a drawing that measures angles otherwise. + #[test] + fn the_rotation_option_is_absolute_degrees() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "B"); + let header = &mut s.doc_mut().unwrap().header; + header.set_i64("AUNITS", 2); + header.set_i64("ANGDIR", 1); + header.set_f64("ANGBASE", 1.0); + let mut app = CadApp::new(s, Services::default()); + let st = State { rotation_on_screen: false, rotation: 90.0, ..State::default() }; + assert!(insert(&mut app, &item("B"), &st, false)); + app.session.input(cadcraft_engine::Input::Point(cadcraft_engine::geom::Vec2::new(1.0, 1.0))).unwrap(); + assert_eq!(app.session.prompt_text(), "Command:", "the options answered every prompt"); + let d = app.session.doc().unwrap(); + let rotation = d.model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i.rotation) } else { None }); + let rotation = rotation.expect("an insert"); + assert!((rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{rotation}"); + } + + /// The scale set in the palette is the one the placed block gets, the same on every axis or not. + #[test] + fn the_scale_options_reach_the_placed_block() { + for scale in [[2.0; 3], [2.0, 3.0, 4.0]] { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "B"); + let mut app = CadApp::new(s, Services::default()); + let st = State { scale_on_screen: false, scale, ..State::default() }; + assert!(insert(&mut app, &item("B"), &st, false)); + app.session.input(cadcraft_engine::Input::Point(cadcraft_engine::geom::Vec2::new(1.0, 1.0))).unwrap(); + assert_eq!(app.session.prompt_text(), "Command:", "the options answered every prompt"); + let d = app.session.doc().unwrap(); + let placed = d.model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i.scale) } else { None }); + let placed = placed.expect("an insert"); + assert_eq!([placed.x, placed.y, placed.z], scale); + } + } + + /// A name INSERT refuses ends the placement: the scale and rotation answers are not read as + /// block names, so block "1" is not placed. + #[test] + fn a_refused_name_places_nothing() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "1"); + let mut app = CadApp::new(s, Services::default()); + let st = State { scale_on_screen: false, ..State::default() }; + assert!(!insert(&mut app, &item("gone"), &st, false)); + assert_eq!(app.session.prompt_text(), "Command:"); + assert_eq!(app.session.doc().unwrap().model.iter().count(), 0); + } + + /// A cancelled build leaves no partial picture. + #[test] + fn a_cancelled_build_has_no_picture() { + let mut d = Drawing::new_metric(); + let mut b = Block::new("B"); + b.entities.push(line(0x70, Vec3::new(0.0, 0.0, 0.0), Vec3::new(4.0, 0.0, 0.0))); + d.blocks.insert("B".into(), Arc::new(b)); + let block = d.block("B").unwrap(); + assert!(outline(&d, block, &Arc::new(AtomicBool::new(true)), None).is_none()); + } + + /// A block over the size limit gets no picture, and asks nothing of the renderer. + #[test] + fn a_huge_block_has_no_picture() { + let mut b = Block::new("HUGE"); + for i in 0..=PREVIEW_ENTITIES { + b.entities.push(line(0x100 + i as u64, Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0))); + } + let lazy = Lazy { doc: Arc::new(Drawing::new_metric()), block: Arc::new(b) }; + assert!(matches!(picture(&lazy), Picture::Unavailable)); + } + + /// One object with a million vertices, or a reference repeated a million times, is refused + /// before anything is drawn; ordinary ones are drawn. + #[test] + fn work_is_counted_before_drawing() { + use cadcraft_engine::doc::LwPolyline; + use cadcraft_engine::geom::{PolyVertex, Vec2}; + let poly = |n: usize| { + let vertices = (0..n).map(|i| PolyVertex { p: Vec2::new(i as f64, (i % 7) as f64), ..PolyVertex::default() }).collect(); + Entity::new( + Handle(0x200), + EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false }), + ) + }; + let d = Drawing::new_metric(); + let mut big = Block::new("BIG"); + big.entities.push(poly(PREVIEW_WORK + 1)); + let cancel = Arc::new(AtomicBool::new(false)); + assert!(outline(&d, &big, &cancel, None).is_none(), "a million vertices are not drawn"); + let mut small = Block::new("SMALL"); + small.entities.push(poly(1_000)); + assert!(outline(&d, &small, &cancel, None).is_some_and(|s| !s.lines.is_empty())); + + // A reference repeated across a huge array costs what one cell costs, times the cells. + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "CELL"); + s.execute("insert", &json!({ "name": "CELL", "at": [0, 0] })).unwrap(); + let mut array = (**s.doc().unwrap().model.iter().next().unwrap()).clone(); + if let EntityKind::Insert(i) = &mut array.kind { + i.rows = 5_000; + i.cols = 5_000; + } + let mut holder = Block::new("GRID"); + holder.entities.push(array); + assert!(outline(s.doc().unwrap(), &holder, &cancel, None).is_none(), "25 million cells are not drawn"); + } + + /// Lists of every kind, long texts and the blocks a dimension or a multileader draws count. + #[test] + fn work_covers_every_list_and_the_blocks_objects_draw() { + use cadcraft_engine::doc::{HatchLoop, LwPolyline, MLine, MLineJust, MLineStyle, Region, Wipeout}; + use cadcraft_engine::geom::{PolyVertex, Vec2}; + /// Whether an object of this kind is refused before anything is drawn. + fn too_much(d: &Drawing, kind: EntityKind) -> bool { + !affordable(d, &[&Entity::new(Handle(0x200), kind)]) + } + let points: Vec = (0..=PREVIEW_WORK).map(|i| Vec2::new(i as f64, (i % 7) as f64)).collect(); + let vertices: Vec = points.iter().map(|p| PolyVertex { p: *p, ..PolyVertex::default() }).collect(); + let d = Drawing::new_metric(); + assert!(too_much(&d, EntityKind::Wipeout(Wipeout { boundary: points.clone() }))); + assert!(too_much(&d, EntityKind::MLine(MLine::new(&MLineStyle::default(), &points, false, MLineJust::default(), 1.0)))); + let region = Region { loops: vec![HatchLoop { vertices: vertices.clone(), outer: true, sources: Vec::new() }] }; + assert!(too_much(&d, EntityKind::Region(region))); + // An object with nothing in it still takes a visit, for each cell of an array. + let mut empty = Block::new("EMPTY"); + let nothing = LwPolyline { vertices: Vec::new(), closed: false, const_width: 0.0, elevation: 0.0, plinegen: false }; + empty.entities.push(Entity::new(Handle(0x202), EntityKind::LwPolyline(nothing))); + let mut grid = Drawing::new_metric(); + grid.blocks.insert("EMPTY".into(), Arc::new(empty)); + let cells = (PREVIEW_WORK as f64).sqrt() as u32 + 1; + let array = json!({ "block": "EMPTY", "insert": [0, 0, 0], "rows": cells, "cols": cells }); + assert!(too_much(&grid, EntityKind::Insert(serde_json::from_value(array).unwrap()))); + + let mut s = Session::new(); + let mut heavy = Block::new("HEAVY"); + let poly = LwPolyline { vertices, closed: false, const_width: 0.0, elevation: 0.0, plinegen: false }; + heavy.entities.push(Entity::new(Handle(0x201), EntityKind::LwPolyline(poly))); + s.doc_mut().unwrap().blocks.insert("HEAVY".into(), Arc::new(heavy)); + s.execute("dimlinear", &json!({ "p1": [0, 0], "p2": [4, 0], "at": [2, 2] })).unwrap(); + s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap(); + s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "block": "HEAVY" })).unwrap(); + let d = s.doc().unwrap(); + let of = |pick: fn(&EntityKind) -> bool| d.model.iter().find(|e| pick(&e.kind)).map(|e| e.kind.clone()).unwrap(); + // The drawn block of the dimension, the block of the multileader and a very long text. + let mut dim = of(|k| matches!(k, EntityKind::Dimension(_))); + assert!(!too_much(d, dim.clone())); + if let EntityKind::Dimension(dm) = &mut dim { + dm.block = Some("HEAVY".into()); + } + assert!(too_much(d, dim)); + assert!(too_much(d, of(|k| matches!(k, EntityKind::MLeader(m) if m.block.is_some())))); + let mut with_text = of(|k| matches!(k, EntityKind::MLeader(m) if m.text.is_some())); + if let EntityKind::MLeader(m) = &mut with_text + && let Some(text) = &mut m.text + { + text.contents = "x".repeat(PREVIEW_WORK); + assert!(too_much(d, EntityKind::MText(text.clone()))); + } + assert!(too_much(d, with_text)); + } + + /// A block of points is sized by itself, not by a drawing a thousand times bigger: each X + /// stays a small part of the picture. + #[test] + fn a_point_preview_does_not_follow_the_drawing_extents() { + use cadcraft_engine::doc::{Common, Point, Space}; + let mut d = Drawing::new_metric(); + d.header.set_i64("PDMODE", 3); + let far = Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(1e6, 1e6, 0.0) }; + d.add(&Space::Model, Common::default(), EntityKind::Line(far)).unwrap(); + let mut b = Block::new("DOTS"); + for i in 0..4 { + b.entities.push(Entity::new(Handle(0x300 + i), EntityKind::Point(Point { p: Vec3::new(i as f64, 0.0, 0.0), angle: 0.0 }))); + } + let shape = outline(&d, &b, &Arc::new(AtomicBool::new(false)), None).unwrap(); + assert!(!shape.lines.is_empty()); + for (_, line) in &shape.lines { + let (min, max) = line.iter().fold((f32::MAX, f32::MIN), |(lo, hi), p| (lo.min(p.x), hi.max(p.x))); + assert!(max - min < 0.25, "a point takes {} of the picture", max - min); + } + } + + /// Coordinates that are not numbers never reach the picture. + #[test] + fn hostile_coordinates_stay_out_of_the_picture() { + let d = Drawing::new_metric(); + let mut b = Block::new("NAN"); + b.entities.push(line(0x70, Vec3::new(f64::NAN, 0.0, 0.0), Vec3::new(f64::INFINITY, 1.0, 0.0))); + b.entities.push(line(0x71, Vec3::new(0.0, 0.0, 0.0), Vec3::new(f64::MAX, f64::MIN, 0.0))); + b.entities.push(line(0x72, Vec3::new(0.0, 0.0, 0.0), Vec3::new(2.0, 2.0, 0.0))); + let cancel = Arc::new(AtomicBool::new(false)); + if let Some(s) = outline(&d, &b, &cancel, None) { + assert!(s.lines.iter().chain(&s.tris).flat_map(|(_, l)| l).all(|p| p.x.is_finite() && p.y.is_finite())); + } + } + + /// Blocks that hold each other end, whatever the file claims. + #[test] + fn blocks_that_hold_each_other_are_drawn_without_hanging() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "A"); + s.execute("insert", &json!({ "name": "A", "at": [1, 1] })).unwrap(); + make_block(&mut s, "B"); + // Point A at B, as a crafted file can: A -> B -> A. + let reference = (**s.doc().unwrap().block("B").unwrap().entities.iter().next().unwrap()).clone(); + let mut back = reference; + if let EntityKind::Insert(i) = &mut back.kind { + i.block = "B".into(); + } + let d = s.doc_mut().unwrap(); + let mut a = (**d.block("A").unwrap()).clone(); + a.entities.push(back); + d.blocks.insert("A".into(), Arc::new(a)); + let d = s.doc().unwrap(); + // The loop is found while the work is counted: no picture, and nothing drawn. + assert!(outline(d, d.block("A").unwrap(), &Arc::new(AtomicBool::new(false)), None).is_none()); + } + + /// What no frame shows goes first; what the current frame shows stays, whatever the total. + #[test] + fn the_cache_is_bounded_and_keeps_what_is_on_screen() { + let big = |n: usize| Picture::Ready(Arc::new(Shape { lines: vec![(None, vec![Pos2::ZERO; n])], tris: Vec::new() })); + let mut p = Pictures { tick: 1, ..Pictures::default() }; + p.insert(("old".into(), 1), big(3_000_000), false); + p.tick = 2; + p.insert(("new".into(), 2), big(3_000_000), false); + assert!(p.get(&("old".into(), 1)).is_none(), "the oldest went"); + assert!(p.get(&("new".into(), 2)).is_some()); + assert_eq!(p.points, 3_000_000); + // Two on the same frame: both are on screen, so neither goes. + p.insert(("also".into(), 3), big(3_000_000), false); + assert_eq!(p.points, 6_000_000); + assert!(p.get(&("new".into(), 2)).is_some() && p.get(&("also".into(), 3)).is_some()); + // The current drawing's previews can go together. + p.insert(("cur".into(), 4), Picture::Unavailable, true); + p.drop_current(); + assert!(p.get(&("cur".into(), 4)).is_none()); + assert_eq!(p.points, 6_000_000); + // A library read again takes its previews with it, and leaves the current drawing's. + p.insert(("cur".into(), 4), Picture::Unavailable, true); + p.drop_libraries(); + assert!(p.get(&("new".into(), 2)).is_none() && p.get(&("also".into(), 3)).is_none()); + assert!(p.get(&("cur".into(), 4)).is_some()); + assert_eq!(p.points, 0); + } + + /// However many full-size previews come in, the cache stays within its bounds. + #[test] + fn a_thousand_full_size_previews_stay_within_the_bounds() { + let full = |n: usize| Picture::Ready(Arc::new(Shape { lines: vec![(None, vec![Pos2::ZERO; n])], tris: Vec::new() })); + let mut p = Pictures::default(); + for i in 0..1000 { + p.tick = i as u64 + 1; + p.insert((format!("Part{i}"), i), full(super::PREVIEW_POINTS), i % 2 == 0); + assert!(p.points <= super::MAX_CACHED_POINTS.max(super::PREVIEW_POINTS), "{}", p.points); + assert!(p.map.len() <= super::MAX_CACHED_PICTURES); + } + // The kept points are the recorded ones, and the newest picture is always there. + assert_eq!(p.points, p.map.values().map(|k| k.points).sum::()); + assert!(p.get(&("Part999".to_string(), 999)).is_some()); + // The most the points can weigh: four million of two f32 each, 32 MiB (the limit here is 64). + assert!(super::MAX_CACHED_POINTS * std::mem::size_of::() <= 64 << 20); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_frame_stops_building_previews_when_its_time_is_used() { + let mut p = Pictures::default(); + let mut painting = super::Painting::new(&mut p); + assert!(!painting.out_of_time()); + painting.until = std::time::Instant::now(); + assert!(painting.out_of_time()); + } + + #[test] + fn long_text_is_cut_to_whole_characters() { + assert_eq!(clipped("court", 10), "court"); + assert_eq!(clipped("éééééé", 3), "ééé…"); + } + + #[test] + fn an_empty_block_has_no_preview() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "ONE"); + let d = s.doc().unwrap(); + let mut empty = (**d.block("ONE").unwrap()).clone(); + empty.entities = Default::default(); + assert!(shape(d, &empty).lines.is_empty()); + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 4d0cace94e..f3e113916a 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -186,6 +186,10 @@ pub struct CanvasState { /// The right-click that opened the shortcut menu held Shift or Ctrl: it is the object snap /// menu ([`crate::context_menu`]). pub snap_menu: bool, + /// The number (in the session's count of commands) of the INSERT the Blocks palette started + /// and is placing: a quick right-click at its insertion point cancels it + /// ([`right_click_cancels_placing`]). + pub palette_insert: Option, /// Tab was pressed over a snap marker: show the next candidate ([`SnapCycle`]). pub snap_tab: bool, pub snap_cycle: Option, @@ -783,6 +787,15 @@ fn collect_prompt_clicks(app: &mut CadApp, ui: &egui::Ui, context: PromptClickCo pressed_primary } +/// Whether a quick right-click cancels the running command instead of acting as Enter: it asks for +/// the insertion point of an INSERT the Blocks palette started. AutoCAD's Enter asks the point again, +/// and Escape (or this) is how a placement ends, so the palette's own placements get a way out +/// with the mouse. +pub(crate) fn right_click_cancels_placing(app: &CadApp) -> bool { + app.canvas.palette_insert == Some(app.session.commands_started) + && app.session.current_prompt().is_some_and(|p| p.message == "Specify insertion point") +} + /// Draw the drawing area and handle its input (zoom and pan, picking, the crosshair) for this /// frame. /// @@ -969,7 +982,11 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.canvas.snap_menu = mods.shift || mods.ctrl; } if crate::context_menu::in_command(app, ui, inside, pressed_secondary) { - let _ = app.session.input(Input::Enter); + if right_click_cancels_placing(app) { + crate::cmdline::escape(app); + } else { + let _ = app.session.input(Input::Enter); + } } // Right-click on a grip with options (polyline vertex, line end…) opens the grip menu. if inside && pressed_secondary && idle && !app.canvas.snap_menu { diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index ef6c457d1d..f926ae31c4 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -372,11 +372,7 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) { egui::Event::Ime(_) => {} egui::Event::Key { key, pressed: true, repeat, modifiers, .. } => match key { Key::Enter => submit(app), - Key::Escape => { - app.cmd.buffer.clear(); - app.cmd.preedit.clear(); - app.session.cancel(); - } + Key::Escape => escape(app), Key::Backspace => { let press = KeyPress { repeat, plain: !(modifiers.alt || modifiers.ctrl || modifiers.command) }; let erase = backspace_erases( @@ -425,6 +421,14 @@ pub fn keyboard(app: &mut CadApp, ctx: &egui::Context) { } } +/// What Escape does, and the right-click or menu "Cancel" that stand for it: what was typed so far +/// goes, and so does the running command. +pub fn escape(app: &mut CadApp) { + app.cmd.buffer.clear(); + app.cmd.preedit.clear(); + app.session.cancel(); +} + pub fn submit(app: &mut CadApp) { app.cmd.preedit.clear(); // Grip dimensional input: the typed lengths and angles place the grip. diff --git a/crates/ui-egui/src/context_menu.rs b/crates/ui-egui/src/context_menu.rs index d9af319c28..060346efe7 100644 --- a/crates/ui-egui/src/context_menu.rs +++ b/crates/ui-egui/src/context_menu.rs @@ -225,9 +225,7 @@ pub fn choose(app: &mut CadApp, id: &str) { app.cmd.buffer.clear(); app.cmdline(""); } else if id == CANCEL { - // Escape. - app.cmd.buffer.clear(); - app.session.cancel(); + crate::cmdline::escape(app); } else if let Some(text) = id.strip_prefix(TYPE) { app.cmd.buffer.clear(); app.cmdline(text); diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index fcd8713a3d..a4df24cf1a 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -28,7 +28,6 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "about" => about(ctx, &mut open), "preview" => crate::exchange::dialog(app, ctx, &mut open), "commands" => commands(app, ctx, &mut open), - "blocks" => blocks(app, ctx, &mut open), "bedit" => crate::bedit::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), "stylesmanager" => crate::plotstyles::dialog(app, ctx, &mut open), @@ -399,38 +398,6 @@ fn commands(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } } -/// Blocks window listing named (non-anonymous) blocks; clicking one starts INSERT with that block name already supplied. -fn blocks(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { - let mut pick = None; - egui::Window::new(crate::tl!("Blocks")).id(egui::Id::unique("Blocks")).open(open).default_size(vec2(320.0, 360.0)).show(ctx, |ui| { - let Ok(d) = app.session.doc() else { return }; - let names: Vec<&String> = d.blocks.keys().filter(|k| !k.starts_with('*')).collect(); - if names.is_empty() { - ui.label(crate::tl!("No blocks defined in this drawing.")); - } - for n in names { - if ui.button(n).on_hover_text(crate::tl!("Insert this block")).clicked() { - pick = Some(n.clone()); - } - } - }); - if let Some(n) = pick { - insert_block(app, &n); - } -} - -/// Start INSERT with `name` already given at its block name prompt, so the next prompt asks for -/// the insertion point. -fn insert_block(app: &mut CadApp, name: &str) { - app.start("insert"); - if app.session.running.as_ref().is_none_or(|r| r.id != "insert") { - return; - } - if let Err(e) = app.session.input(cadcraft_engine::Input::Text(name.to_string())) { - app.session.echo(e.to_string()); - } -} - /// Interface Language combo; selecting a language runs `ui.language` with its code. fn language(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { egui::Window::new(crate::tl!("Interface Language")).id(egui::Id::unique("interface_language")).open(open).resizable(false).show(ctx, |ui| { @@ -447,13 +414,6 @@ fn language(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { #[cfg(test)] mod tests { - use cadcraft_engine::doc::EntityKind; - use cadcraft_engine::geom::Vec2; - use cadcraft_engine::{Input, Session}; - use serde_json::json; - - use crate::{CadApp, Services}; - #[test] fn fractional_length_precisions_list_binary_fractions() { let labels = ["1\"", "1/2\"", "1/4\"", "1/8\"", "1/16\"", "1/32\"", "1/64\"", "1/128\"", "1/256\""]; @@ -462,43 +422,4 @@ mod tests { assert_eq!(super::length_precisions(5), want); assert_eq!(super::length_precisions(2).len(), 9); } - - #[test] - fn picking_a_block_starts_insert_with_its_name() { - let mut app = CadApp::new(Session::new(), Services::default()); - let c = app.session.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap(); - let h = c["handle"].as_str().unwrap().to_string(); - app.session.execute("block", &json!({"name": "Door 2", "base": [0, 0], "handles": [h], "keep": "delete"})).unwrap(); - // A command already running is replaced, as when a command is typed. - app.start("line"); - - super::insert_block(&mut app, "Door 2"); - assert!(app.session.running.as_ref().is_some_and(|r| r.id == "insert")); - assert_eq!(app.session.current_prompt().map(|p| p.message), Some("Specify insertion point".to_string())); - - app.session.input(Input::Point(Vec2::new(5.0, 6.0))).unwrap(); - // X scale, Y scale and rotation take their defaults. - for _ in 0..3 { - app.session.input(Input::Enter).unwrap(); - } - assert!(app.session.running.is_none()); - let d = app.session.doc().unwrap(); - let mut ins = Vec::new(); - for e in d.model.iter() { - if let EntityKind::Insert(i) = &e.kind { - ins.push(i.clone()); - } - } - assert_eq!(ins.len(), 1); - assert_eq!(ins[0].block, "Door 2"); - assert!((ins[0].insert.x - 5.0).abs() < 1e-9 && (ins[0].insert.y - 6.0).abs() < 1e-9); - } - - #[test] - fn picking_a_missing_block_keeps_asking_for_a_name() { - let mut app = CadApp::new(Session::new(), Services::default()); - super::insert_block(&mut app, "Nope"); - assert!(app.session.running.as_ref().is_some_and(|r| r.id == "insert")); - assert_eq!(app.session.current_prompt().map(|p| p.message), Some("Enter block name".to_string())); - } } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 50fb52a254..cabcb5ec30 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -19,6 +19,7 @@ pub enum Panel { Properties, #[serde(rename = "externalReferences")] ExternalRefs, + Blocks, } impl Panel { @@ -31,6 +32,7 @@ impl Panel { Self::Layers => "layers", Self::Properties => "properties", Self::ExternalRefs => "externalReferences", + Self::Blocks => "blocks", } } fn label(self) -> &'static str { @@ -41,6 +43,7 @@ impl Panel { Self::Layers => "Layers", Self::Properties => "Properties", Self::ExternalRefs => "External References", + Self::Blocks => "Blocks", } } /// The icon a palette shows in a column collapsed to icons. @@ -53,10 +56,11 @@ impl Panel { Self::Layers => Some(Icon::Layers), Self::Properties => Some(Icon::Properties), Self::ExternalRefs => Some(Icon::Attach), + Self::Blocks => Some(Icon::Blocks), } } /// Palettes outside the default arrangement, opened on request (QUICKCALC). - pub const ON_DEMAND: &[Self] = &[Self::QuickCalc]; + pub const ON_DEMAND: &[Self] = &[Self::QuickCalc, Self::Blocks]; } /// The drawing view never moves, floats, closes or takes tabs; palettes dock beside it. @@ -149,6 +153,7 @@ fn home_anchor(layout: &Layout, panel: Panel) -> Option<(Panel, bool)> { Panel::Properties => &[(Panel::Layers, true), (Panel::ExternalRefs, false)], Panel::ExternalRefs => &[(Panel::Properties, true), (Panel::Layers, true)], Panel::QuickCalc => &[(Panel::ExternalRefs, true), (Panel::Properties, true), (Panel::Layers, true)], + Panel::Blocks => &[(Panel::QuickCalc, true), (Panel::ExternalRefs, true), (Panel::Properties, true), (Panel::Layers, true)], }; if let Some(found) = neighbours.iter().copied().find(|(neighbour, _)| docked(layout, *neighbour)) { return Some(found); @@ -414,6 +419,12 @@ impl DockContent for Panels<'_> { Panel::ExternalRefs => { egui::ScrollArea::both().id_salt("dock-xrefs").auto_shrink([false, false]).show(ui, |ui| crate::xrefs::section(app, ui)); } + Panel::Blocks => { + egui::ScrollArea::vertical() + .id_salt("dock-blocks") + .auto_shrink([false, false]) + .show(ui, |ui| crate::blocks_palette::section(app, ui)); + } } } fn logical_label(&self, panel: &Panel) -> String { @@ -442,6 +453,7 @@ fn panel_limits(panel: &Panel) -> PanelLimits { Panel::QuickCalc => (egui::vec2(240.0, 160.0), 600.0), Panel::ToolSets => (egui::vec2(220.0, 150.0), 480.0), Panel::Layers | Panel::Properties | Panel::ExternalRefs => (egui::vec2(220.0, 100.0), 720.0), + Panel::Blocks => (egui::vec2(240.0, 260.0), 720.0), }; PanelLimits { min, max: egui::vec2(max_width, 1_000_000.0) } } diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 9d5c15837d..7e2ec0b050 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -1368,6 +1368,33 @@ menu View عرض overrides built-in يتجاوز المدمج {alias} is already defined; select it and use Edit. {alias} معرَّف مسبقاً؛ حدده واستخدم «تحرير». {command} is an unknown command. {command} أمر غير معروف. + Add a drawing file as a block library إضافة ملف رسم كمكتبة كتل + Add a folder of drawings or a drawing file to use its blocks. أضف مجلدًا يحتوي على رسومات أو ملف رسم لاستخدام كتله. + Block Libraries مكتبات الكتل + Block Library مكتبة الكتل + Blocks Palette لوحة الكتل + Click a block, then pick its insertion point. انقر على كتلة ثم حدّد نقطة إدراجها. + Current Drawing الرسم الحالي + Details التفاصيل + Extra Large Icons أيقونات كبيرة جدًا + Folder or file مجلد أو ملف + Import Library Block استيراد كتلة من المكتبة + Insert and Explode إدراج وتفجير + Large Icons أيقونات كبيرة + Libraries المكتبات + Medium Icons أيقونات متوسطة + No block matches the filter. لا توجد كتلة تطابق عامل التصفية. + This block is already in the drawing, so its definition is used. هذه الكتلة موجودة بالفعل في الرسم، لذلك يتم استخدام تعريفها. + Open Library... فتح مكتبة... + Read the library again إعادة قراءة المكتبة + Reading the library... جارٍ قراءة المكتبة... + Refresh تحديث + Remove from the list إزالة من القائمة + Repeat Placement تكرار الوضع + Small Icons أيقونات صغيرة + This drawing has no blocks. لا يحتوي هذا الرسم على كتل. + This library has no drawings or blocks. لا تحتوي هذه المكتبة على رسومات أو كتل. + Only the first {n} are shown. يتم عرض أول {n} فقط. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 2e63cdd21a..5c82b977a8 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1444,6 +1444,33 @@ menu Modify Izmijeni Save changes to block "{name}"? Sačuvati promjene u bloku „{name}”? Layouts Rasporedi Associate Poveži + Add a drawing file as a block library Dodaj datoteku crteža kao biblioteku blokova + Add a folder of drawings or a drawing file to use its blocks. Dodajte mapu s crtežima ili datoteku crteža da biste koristili njene blokove. + Block Libraries Biblioteke blokova + Block Library Biblioteka blokova + Blocks Palette Paleta blokova + Click a block, then pick its insertion point. Kliknite na blok, zatim odredite njegovu tačku umetanja. + Current Drawing Trenutni crtež + Details Detalji + Extra Large Icons Veoma velike ikone + Folder or file Mapa ili datoteka + Import Library Block Uvezi blok iz biblioteke + Insert and Explode Umetni i rastavi + Large Icons Velike ikone + Libraries Biblioteke + Medium Icons Srednje ikone + No block matches the filter. Nijedan blok ne odgovara filteru. + This block is already in the drawing, so its definition is used. Ovaj blok već postoji u crtežu, pa se koristi njegova definicija. + Open Library... Otvori biblioteku... + Read the library again Ponovo učitaj biblioteku + Reading the library... Čitanje biblioteke... + Refresh Osvježi + Remove from the list Ukloni s liste + Repeat Placement Ponovi postavljanje + Small Icons Male ikone + This drawing has no blocks. Ovaj crtež nema blokova. + This library has no drawings or blocks. Ova biblioteka nema crteža ni blokova. + Only the first {n} are shown. Prikazano je samo prvih {n}. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 7b474f6c97..7feb001dec 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1224,6 +1224,33 @@ menu Modify Modifikace Check for Updates… Zkontrolovat aktualizace… CADCraft is up to date. CADCraft je aktuální. Could not check for updates. Aktualizace se nepodařilo zkontrolovat. + Add a drawing file as a block library Přidat výkresový soubor jako knihovnu bloků + Add a folder of drawings or a drawing file to use its blocks. Přidejte složku s výkresy nebo výkresový soubor, abyste mohli používat jeho bloky. + Block Libraries Knihovny bloků + Block Library Knihovna bloků + Blocks Palette Paleta bloků + Click a block, then pick its insertion point. Klikněte na blok a poté určete jeho vkládací bod. + Current Drawing Aktuální výkres + Details Podrobnosti + Extra Large Icons Extra velké ikony + Folder or file Složka nebo soubor + Import Library Block Importovat blok z knihovny + Insert and Explode Vložit a rozložit + Large Icons Velké ikony + Libraries Knihovny + Medium Icons Střední ikony + No block matches the filter. Filtru neodpovídá žádný blok. + This block is already in the drawing, so its definition is used. Tento blok už v kresbě je, proto se použije jeho definice. + Open Library... Otevřít knihovnu... + Read the library again Načíst knihovnu znovu + Reading the library... Načítání knihovny... + Refresh Obnovit + Remove from the list Odebrat ze seznamu + Repeat Placement Opakovat umístění + Small Icons Malé ikony + This drawing has no blocks. Tento výkres neobsahuje žádné bloky. + This library has no drawings or blocks. Tato knihovna neobsahuje žádné výkresy ani bloky. + Only the first {n} are shown. Zobrazuje se pouze prvních {n}. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index c0d2345616..179779f32b 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1041,6 +1041,34 @@ Check for Updates… Nach Updates suchen… CADCraft is up to date. CADCraft ist auf dem neuesten Stand. Could not check for updates. Die Suche nach Updates ist fehlgeschlagen. + Add a drawing file as a block library Zeichnungsdatei als Blockbibliothek hinzufügen + Add a folder of drawings or a drawing file to use its blocks. Fügen Sie einen Ordner mit Zeichnungen oder eine Zeichnungsdatei hinzu, um deren Blöcke zu verwenden. + Block Libraries Blockbibliotheken + Block Library Blockbibliothek + Blocks Palette Blockpalette + Click a block, then pick its insertion point. Klicken Sie auf einen Block und geben Sie dann den Einfügepunkt an. + Current Drawing Aktuelle Zeichnung + Details Details + Extra Large Icons Extragroße Symbole + Folder or file Ordner oder Datei + Import Library Block Bibliotheksblock importieren + Insert and Explode Einfügen und auflösen + Large Icons Große Symbole + Libraries Bibliotheken + Medium Icons Mittelgroße Symbole + No block matches the filter. Kein Block entspricht dem Filter. + This block is already in the drawing, so its definition is used. Dieser Block ist bereits in der Zeichnung, daher wird seine Definition verwendet. + Open Library... Bibliothek öffnen... + Read the library again Bibliothek erneut lesen + Reading the library... Bibliothek wird gelesen... + Refresh Aktualisieren + Remove from the list Aus der Liste entfernen + Repeat Placement Platzierung wiederholen + Small Icons Kleine Symbole + This drawing has no blocks. Diese Zeichnung enthält keine Blöcke. + This library has no drawings or blocks. Diese Bibliothek enthält keine Zeichnungen oder Blöcke. + Options Optionen + Only the first {n} are shown. Nur die ersten {n} werden angezeigt. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 94b29c1e6c..333f39870e 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1381,6 +1381,33 @@ menu View Προβολή Check for Updates… Έλεγχος για ενημερώσεις… CADCraft is up to date. Το CADCraft είναι ενημερωμένο. Could not check for updates. Δεν ήταν δυνατός ο έλεγχος για ενημερώσεις. + Add a drawing file as a block library Προσθήκη αρχείου σχεδίου ως βιβλιοθήκης μπλοκ + Add a folder of drawings or a drawing file to use its blocks. Προσθέστε έναν φάκελο με σχέδια ή ένα αρχείο σχεδίου για να χρησιμοποιήσετε τα μπλοκ του. + Block Libraries Βιβλιοθήκες μπλοκ + Block Library Βιβλιοθήκη μπλοκ + Blocks Palette Παλέτα μπλοκ + Click a block, then pick its insertion point. Κάντε κλικ σε ένα μπλοκ και μετά ορίστε το σημείο εισαγωγής του. + Current Drawing Τρέχον σχέδιο + Details Λεπτομέρειες + Extra Large Icons Πολύ μεγάλα εικονίδια + Folder or file Φάκελος ή αρχείο + Import Library Block Εισαγωγή μπλοκ βιβλιοθήκης + Insert and Explode Εισαγωγή και διάσπαση + Large Icons Μεγάλα εικονίδια + Libraries Βιβλιοθήκες + Medium Icons Μεσαία εικονίδια + No block matches the filter. Κανένα μπλοκ δεν ταιριάζει με το φίλτρο. + This block is already in the drawing, so its definition is used. Αυτό το μπλοκ υπάρχει ήδη στο σχέδιο, οπότε χρησιμοποιείται ο ορισμός του. + Open Library... Άνοιγμα βιβλιοθήκης... + Read the library again Επανάγνωση της βιβλιοθήκης + Reading the library... Ανάγνωση της βιβλιοθήκης... + Refresh Ανανέωση + Remove from the list Αφαίρεση από τη λίστα + Repeat Placement Επανάληψη τοποθέτησης + Small Icons Μικρά εικονίδια + This drawing has no blocks. Αυτό το σχέδιο δεν έχει μπλοκ. + This library has no drawings or blocks. Αυτή η βιβλιοθήκη δεν έχει σχέδια ή μπλοκ. + Only the first {n} are shown. Εμφανίζονται μόνο τα πρώτα {n}. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 7928cd66fb..693d757381 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1255,6 +1255,33 @@ Check for Updates… Buscar actualizaciones… CADCraft is up to date. CADCraft está actualizado. Could not check for updates. No se pudo buscar actualizaciones. + Add a drawing file as a block library Añadir un archivo de dibujo como biblioteca de bloques + Add a folder of drawings or a drawing file to use its blocks. Añada una carpeta de dibujos o un archivo de dibujo para usar sus bloques. + Block Libraries Bibliotecas de bloques + Block Library Biblioteca de bloques + Blocks Palette Paleta de bloques + Click a block, then pick its insertion point. Haga clic en un bloque y luego indique su punto de inserción. + Current Drawing Dibujo actual + Details Detalles + Extra Large Icons Iconos extragrandes + Folder or file Carpeta o archivo + Import Library Block Importar bloque de biblioteca + Insert and Explode Insertar y descomponer + Large Icons Iconos grandes + Libraries Bibliotecas + Medium Icons Iconos medianos + No block matches the filter. Ningún bloque coincide con el filtro. + This block is already in the drawing, so its definition is used. Este bloque ya está en el dibujo, así que se usa su definición. + Open Library... Abrir biblioteca... + Read the library again Volver a leer la biblioteca + Reading the library... Leyendo la biblioteca... + Refresh Actualizar + Remove from the list Quitar de la lista + Repeat Placement Repetir colocación + Small Icons Iconos pequeños + This drawing has no blocks. Este dibujo no tiene bloques. + This library has no drawings or blocks. Esta biblioteca no tiene dibujos ni bloques. + Only the first {n} are shown. Solo se muestran los primeros {n}. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 99297e1cad..f07a53f369 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1014,6 +1014,34 @@ Check for Updates… Rechercher des mises à jour… CADCraft is up to date. CADCraft est à jour. Could not check for updates. Impossible de rechercher les mises à jour. + Add a drawing file as a block library Ajouter un fichier de dessin comme bibliothèque de blocs + Add a folder of drawings or a drawing file to use its blocks. Ajoutez un dossier de dessins ou un fichier de dessin pour utiliser ses blocs. + Block Libraries Bibliothèques de blocs + Block Library Bibliothèque de blocs + Blocks Palette Palette des blocs + Click a block, then pick its insertion point. Cliquez sur un bloc, puis indiquez son point d'insertion. + Current Drawing Dessin courant + Details Détails + Extra Large Icons Très grandes icônes + Folder or file Dossier ou fichier + Import Library Block Importer un bloc de bibliothèque + Insert and Explode Insérer et décomposer + Large Icons Grandes icônes + Libraries Bibliothèques + Medium Icons Icônes moyennes + No block matches the filter. Aucun bloc ne correspond au filtre. + This block is already in the drawing, so its definition is used. Ce bloc est déjà dans le dessin ; sa définition est utilisée. + Open Library... Ouvrir une bibliothèque... + Read the library again Relire la bibliothèque + Reading the library... Lecture de la bibliothèque... + Refresh Actualiser + Remove from the list Retirer de la liste + Repeat Placement Répéter le placement + Small Icons Petites icônes + This drawing has no blocks. Ce dessin ne contient aucun bloc. + This library has no drawings or blocks. Cette bibliothèque ne contient ni dessin ni bloc. + Options Options + Only the first {n} are shown. Seuls les {n} premiers sont affichés. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 569b38a6e8..39e1382558 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1346,6 +1346,33 @@ menu View Nézet Check for Updates… Frissítések keresése… CADCraft is up to date. A CADCraft naprakész. Could not check for updates. A frissítések keresése nem sikerült. + Add a drawing file as a block library Rajzfájl hozzáadása blokkkönyvtárként + Add a folder of drawings or a drawing file to use its blocks. Adj hozzá egy rajzokat tartalmazó mappát vagy egy rajzfájlt, hogy használhasd a blokkjait. + Block Libraries Blokkkönyvtárak + Block Library Blokkkönyvtár + Blocks Palette Blokkpaletta + Click a block, then pick its insertion point. Kattints egy blokkra, majd add meg a beszúrási pontját. + Current Drawing Aktuális rajz + Details Részletek + Extra Large Icons Extra nagy ikonok + Folder or file Mappa vagy fájl + Import Library Block Könyvtárblokk importálása + Insert and Explode Beszúrás és szétbontás + Large Icons Nagy ikonok + Libraries Könyvtárak + Medium Icons Közepes ikonok + No block matches the filter. Egy blokk sem felel meg a szűrőnek. + This block is already in the drawing, so its definition is used. Ez a blokk már szerepel a rajzban, ezért a meglévő definícióját használjuk. + Open Library... Könyvtár megnyitása... + Read the library again Könyvtár újraolvasása + Reading the library... Könyvtár olvasása... + Refresh Frissítés + Remove from the list Eltávolítás a listáról + Repeat Placement Elhelyezés ismétlése + Small Icons Kis ikonok + This drawing has no blocks. Ez a rajz nem tartalmaz blokkokat. + This library has no drawings or blocks. Ez a könyvtár nem tartalmaz rajzokat vagy blokkokat. + Only the first {n} are shown. Csak az első {n} látható. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index 9a1ea85d22..4d79c9b92a 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1366,6 +1366,33 @@ menu Modify Edita Check for Updates… Verifica aggiornamenti… CADCraft is up to date. CADCraft è aggiornato. Could not check for updates. Impossibile verificare gli aggiornamenti. + Add a drawing file as a block library Aggiungi un file di disegno come libreria di blocchi + Add a folder of drawings or a drawing file to use its blocks. Aggiungi una cartella di disegni o un file di disegno per usarne i blocchi. + Block Libraries Librerie di blocchi + Block Library Libreria di blocchi + Blocks Palette Tavolozza blocchi + Click a block, then pick its insertion point. Fai clic su un blocco, quindi indica il punto di inserimento. + Current Drawing Disegno corrente + Details Dettagli + Extra Large Icons Icone molto grandi + Folder or file Cartella o file + Import Library Block Importa blocco da libreria + Insert and Explode Inserisci ed esplodi + Large Icons Icone grandi + Libraries Librerie + Medium Icons Icone medie + No block matches the filter. Nessun blocco corrisponde al filtro. + This block is already in the drawing, so its definition is used. Questo blocco è già nel disegno, quindi viene usata la sua definizione. + Open Library... Apri libreria... + Read the library again Rileggi la libreria + Reading the library... Lettura della libreria... + Refresh Aggiorna + Remove from the list Rimuovi dall'elenco + Repeat Placement Ripeti posizionamento + Small Icons Icone piccole + This drawing has no blocks. Questo disegno non contiene blocchi. + This library has no drawings or blocks. Questa libreria non contiene disegni o blocchi. + Only the first {n} are shown. Vengono mostrati solo i primi {n}. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/ka.tsv b/crates/ui-egui/src/i18n/ka.tsv index e29940844f..6adf8f444f 100644 --- a/crates/ui-egui/src/i18n/ka.tsv +++ b/crates/ui-egui/src/i18n/ka.tsv @@ -1472,6 +1472,33 @@ menu View ხედი Text to find მოსაძებნი ტექსტი Whole words მთლიანი სიტყვები Nothing found ვერაფერი მოიძებნა + Add a drawing file as a block library ნახაზის ფაილის დამატება ბლოკების ბიბლიოთეკად + Add a folder of drawings or a drawing file to use its blocks. დაამატეთ ნახაზების საქაღალდე ან ნახაზის ფაილი მისი ბლოკების გამოსაყენებლად. + Block Libraries ბლოკების ბიბლიოთეკები + Block Library ბლოკების ბიბლიოთეკა + Blocks Palette ბლოკების პალიტრა + Click a block, then pick its insertion point. დაწკაპეთ ბლოკზე, შემდეგ მიუთითეთ მისი ჩასმის წერტილი. + Current Drawing მიმდინარე ნახაზი + Details დეტალები + Extra Large Icons ძალიან დიდი ხატულები + Folder or file საქაღალდე ან ფაილი + Import Library Block ბიბლიოთეკის ბლოკის იმპორტი + Insert and Explode ჩასმა და დაშლა + Large Icons დიდი ხატულები + Libraries ბიბლიოთეკები + Medium Icons საშუალო ხატულები + No block matches the filter. ფილტრს არც ერთი ბლოკი არ შეესაბამება. + This block is already in the drawing, so its definition is used. ეს ბლოკი ნახაზში უკვე არის, ამიტომ გამოიყენება მისი განსაზღვრება. + Open Library... ბიბლიოთეკის გახსნა... + Read the library again ბიბლიოთეკის თავიდან წაკითხვა + Reading the library... ბიბლიოთეკა იკითხება... + Refresh განახლება + Remove from the list სიიდან მოცილება + Repeat Placement განთავსების გამეორება + Small Icons პატარა ხატულები + This drawing has no blocks. ამ ნახაზში ბლოკები არ არის. + This library has no drawings or blocks. ამ ბიბლიოთეკაში ნახაზები ან ბლოკები არ არის. + Only the first {n} are shown. ნაჩვენებია მხოლოდ პირველი {n}. # ArtCraft feature naming Additional Tools დამატებითი ხელსაწყოები diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index d785f5ab38..ce50ed655f 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1244,6 +1244,33 @@ menu Modify 수정 Check for Updates… 업데이트 확인… CADCraft is up to date. CADCraft가 최신 버전입니다. Could not check for updates. 업데이트를 확인하지 못했습니다. + Add a drawing file as a block library 도면 파일을 블록 라이브러리로 추가 + Add a folder of drawings or a drawing file to use its blocks. 블록을 사용하려면 도면이 들어 있는 폴더나 도면 파일을 추가하세요. + Block Libraries 블록 라이브러리 + Block Library 블록 라이브러리 + Blocks Palette 블록 팔레트 + Click a block, then pick its insertion point. 블록을 클릭한 다음 삽입점을 지정하세요. + Current Drawing 현재 도면 + Details 자세히 + Extra Large Icons 매우 큰 아이콘 + Folder or file 폴더 또는 파일 + Import Library Block 라이브러리 블록 가져오기 + Insert and Explode 삽입 후 분해 + Large Icons 큰 아이콘 + Libraries 라이브러리 + Medium Icons 보통 아이콘 + No block matches the filter. 필터와 일치하는 블록이 없습니다. + This block is already in the drawing, so its definition is used. 이 블록은 이미 도면에 있으므로 기존 정의를 사용합니다. + Open Library... 라이브러리 열기... + Read the library again 라이브러리 다시 읽기 + Reading the library... 라이브러리를 읽는 중... + Refresh 새로 고침 + Remove from the list 목록에서 제거 + Repeat Placement 배치 반복 + Small Icons 작은 아이콘 + This drawing has no blocks. 이 도면에는 블록이 없습니다. + This library has no drawings or blocks. 이 라이브러리에는 도면이나 블록이 없습니다. + Only the first {n} are shown. 처음 {n}개만 표시됩니다. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/pt_br.tsv b/crates/ui-egui/src/i18n/pt_br.tsv index 0ac44abbde..593424edef 100644 --- a/crates/ui-egui/src/i18n/pt_br.tsv +++ b/crates/ui-egui/src/i18n/pt_br.tsv @@ -1253,6 +1253,33 @@ Check for Updates… Verificar atualizações… CADCraft is up to date. O CADCraft está atualizado. Could not check for updates. Não foi possível verificar atualizações. + Add a drawing file as a block library Adicionar um arquivo de desenho como biblioteca de blocos + Add a folder of drawings or a drawing file to use its blocks. Adicione uma pasta de desenhos ou um arquivo de desenho para usar seus blocos. + Block Libraries Bibliotecas de blocos + Block Library Biblioteca de blocos + Blocks Palette Paleta de blocos + Click a block, then pick its insertion point. Clique em um bloco e depois indique o ponto de inserção. + Current Drawing Desenho atual + Details Detalhes + Extra Large Icons Ícones extragrandes + Folder or file Pasta ou arquivo + Import Library Block Importar bloco da biblioteca + Insert and Explode Inserir e explodir + Large Icons Ícones grandes + Libraries Bibliotecas + Medium Icons Ícones médios + No block matches the filter. Nenhum bloco corresponde ao filtro. + This block is already in the drawing, so its definition is used. Este bloco já está no desenho, então sua definição é usada. + Open Library... Abrir biblioteca... + Read the library again Ler a biblioteca novamente + Reading the library... Lendo a biblioteca... + Refresh Atualizar + Remove from the list Remover da lista + Repeat Placement Repetir posicionamento + Small Icons Ícones pequenos + This drawing has no blocks. Este desenho não tem blocos. + This library has no drawings or blocks. Esta biblioteca não tem desenhos nem blocos. + Only the first {n} are shown. Apenas os primeiros {n} são exibidos. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index d0600b589d..79c085ee9b 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1015,6 +1015,34 @@ Check for Updates… Проверить обновления… CADCraft is up to date. У вас последняя версия CADCraft. Could not check for updates. Не удалось проверить обновления. + Add a drawing file as a block library Добавить файл чертежа как библиотеку блоков + Add a folder of drawings or a drawing file to use its blocks. Добавьте папку с чертежами или файл чертежа, чтобы использовать его блоки. + Block Libraries Библиотеки блоков + Block Library Библиотека блоков + Blocks Palette Палитра блоков + Click a block, then pick its insertion point. Щелкните блок, затем укажите точку вставки. + Current Drawing Текущий чертеж + Details Подробно + Extra Large Icons Огромные значки + Folder or file Папка или файл + Import Library Block Импортировать блок из библиотеки + Insert and Explode Вставить и расчленить + Large Icons Крупные значки + Libraries Библиотеки + Medium Icons Обычные значки + No block matches the filter. Нет блоков, соответствующих фильтру. + This block is already in the drawing, so its definition is used. Этот блок уже есть в чертеже, поэтому используется его определение. + Open Library... Открыть библиотеку... + Read the library again Прочитать библиотеку заново + Reading the library... Чтение библиотеки... + Refresh Обновить + Remove from the list Убрать из списка + Repeat Placement Повторять размещение + Small Icons Мелкие значки + This drawing has no blocks. В этом чертеже нет блоков. + This library has no drawings or blocks. В этой библиотеке нет чертежей и блоков. + Options Параметры + Only the first {n} are shown. Показаны только первые {n}. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index ebe376b225..54ff113c55 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1448,6 +1448,33 @@ menu Modify Ändra Check for Updates… Sök efter uppdateringar… CADCraft is up to date. CADCraft är uppdaterat. Could not check for updates. Det gick inte att söka efter uppdateringar. + Add a drawing file as a block library Lägg till en ritningsfil som blockbibliotek + Add a folder of drawings or a drawing file to use its blocks. Lägg till en mapp med ritningar eller en ritningsfil för att använda dess block. + Block Libraries Blockbibliotek + Block Library Blockbibliotek + Blocks Palette Blockpalett + Click a block, then pick its insertion point. Klicka på ett block och ange sedan dess infogningspunkt. + Current Drawing Aktuell ritning + Details Detaljer + Extra Large Icons Extra stora ikoner + Folder or file Mapp eller fil + Import Library Block Importera biblioteksblock + Insert and Explode Infoga och lös upp + Large Icons Stora ikoner + Libraries Bibliotek + Medium Icons Medelstora ikoner + No block matches the filter. Inget block matchar filtret. + This block is already in the drawing, so its definition is used. Det här blocket finns redan i ritningen, så dess definition används. + Open Library... Öppna bibliotek... + Read the library again Läs in biblioteket igen + Reading the library... Läser biblioteket... + Refresh Uppdatera + Remove from the list Ta bort från listan + Repeat Placement Upprepa placering + Small Icons Små ikoner + This drawing has no blocks. Den här ritningen har inga block. + This library has no drawings or blocks. Det här biblioteket har inga ritningar eller block. + Only the first {n} are shown. Endast de första {n} visas. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index a3b1977400..970f5eb624 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -98,6 +98,7 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet { let catalog = catalog(language).unwrap(); let modules = [ "xrefs", + "blocks_palette", "canvas", "chrome", "cmdline", @@ -481,7 +482,6 @@ fn dialogs_render_in_every_language_and_keep_their_source_ids() { ("dsettings", "Drafting Settings"), ("about", "About CADCraft"), ("commands", "Command Reference"), - ("blocks", "Blocks"), ("layers", "Layer Properties Manager"), ("qselect", "Quick Select"), ("parameters", "Parameters Manager"), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index e0ca60c143..fd51400afa 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1349,6 +1349,33 @@ menu View Görünüm Check for Updates… Güncellemeleri denetle… CADCraft is up to date. CADCraft güncel. Could not check for updates. Güncellemeler denetlenemedi. + Add a drawing file as a block library Çizim dosyasını blok kitaplığı olarak ekle + Add a folder of drawings or a drawing file to use its blocks. Bloklarını kullanmak için çizim içeren bir klasör veya bir çizim dosyası ekleyin. + Block Libraries Blok Kitaplıkları + Block Library Blok Kitaplığı + Blocks Palette Blok Paleti + Click a block, then pick its insertion point. Bir bloğa tıklayın, ardından yerleştirme noktasını belirtin. + Current Drawing Geçerli Çizim + Details Ayrıntılar + Extra Large Icons Çok Büyük Simgeler + Folder or file Klasör veya dosya + Import Library Block Kitaplık Bloğunu İçe Aktar + Insert and Explode Ekle ve Patlat + Large Icons Büyük Simgeler + Libraries Kitaplıklar + Medium Icons Orta Boy Simgeler + No block matches the filter. Filtreyle eşleşen blok yok. + This block is already in the drawing, so its definition is used. Bu blok çizimde zaten var, bu yüzden mevcut tanımı kullanılır. + Open Library... Kitaplık Aç... + Read the library again Kitaplığı yeniden oku + Reading the library... Kitaplık okunuyor... + Refresh Yenile + Remove from the list Listeden kaldır + Repeat Placement Yerleştirmeyi Tekrarla + Small Icons Küçük Simgeler + This drawing has no blocks. Bu çizimde blok yok. + This library has no drawings or blocks. Bu kitaplıkta çizim veya blok yok. + Only the first {n} are shown. Yalnızca ilk {n} gösteriliyor. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index c0d15062ad..89f8ba865e 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1383,6 +1383,33 @@ CADCraft is up to date. Встановлено найновішу версію CADCraft. Could not check for updates. Не вдалося перевірити оновлення. Save changes to block "{name}"? Зберегти зміни в блоці «{name}»? + Add a drawing file as a block library Додати файл креслення як бібліотеку блоків + Add a folder of drawings or a drawing file to use its blocks. Додайте теку з кресленнями або файл креслення, щоб використовувати його блоки. + Block Libraries Бібліотеки блоків + Block Library Бібліотека блоків + Blocks Palette Палітра блоків + Click a block, then pick its insertion point. Клацніть блок, потім укажіть точку вставлення. + Current Drawing Поточне креслення + Details Докладно + Extra Large Icons Дуже великі піктограми + Folder or file Тека або файл + Import Library Block Імпортувати блок із бібліотеки + Insert and Explode Вставити й розчленувати + Large Icons Великі піктограми + Libraries Бібліотеки + Medium Icons Середні піктограми + No block matches the filter. Жоден блок не відповідає фільтру. + This block is already in the drawing, so its definition is used. Цей блок уже є в кресленні, тому використовується його визначення. + Open Library... Відкрити бібліотеку... + Read the library again Прочитати бібліотеку знову + Reading the library... Читання бібліотеки... + Refresh Оновити + Remove from the list Прибрати зі списку + Repeat Placement Повторювати розміщення + Small Icons Малі піктограми + This drawing has no blocks. У цьому кресленні немає блоків. + This library has no drawings or blocks. У цій бібліотеці немає креслень і блоків. + Only the first {n} are shown. Показано лише перші {n}. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 86131685ed..afe0c670f9 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1449,6 +1449,33 @@ menu Modify Hiệu chỉnh Change Properties Đổi thuộc tính Font Phông chữ Save Layout as Template Lưu layout thành mẫu + Add a drawing file as a block library Thêm tệp bản vẽ làm thư viện block + Add a folder of drawings or a drawing file to use its blocks. Thêm thư mục chứa bản vẽ hoặc tệp bản vẽ để dùng các block của nó. + Block Libraries Thư viện block + Block Library Thư viện block + Blocks Palette Bảng block + Click a block, then pick its insertion point. Nhấp vào một block, rồi chỉ định điểm chèn của nó. + Current Drawing Bản vẽ hiện hành + Details Chi tiết + Extra Large Icons Biểu tượng cực lớn + Folder or file Thư mục hoặc tệp + Import Library Block Nhập block từ thư viện + Insert and Explode Chèn và phân rã + Large Icons Biểu tượng lớn + Libraries Thư viện + Medium Icons Biểu tượng cỡ vừa + No block matches the filter. Không có block nào khớp với bộ lọc. + This block is already in the drawing, so its definition is used. Khối này đã có trong bản vẽ nên định nghĩa của nó được dùng. + Open Library... Mở thư viện... + Read the library again Đọc lại thư viện + Reading the library... Đang đọc thư viện... + Refresh Làm mới + Remove from the list Xóa khỏi danh sách + Repeat Placement Lặp lại việc đặt + Small Icons Biểu tượng nhỏ + This drawing has no blocks. Bản vẽ này không có block. + This library has no drawings or blocks. Thư viện này không có bản vẽ hay block. + Only the first {n} are shown. Chỉ hiển thị {n} mục đầu tiên. Find All Find All Find what: Find what: Match case Match case diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 0e6409b522..f1c43421b0 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1351,6 +1351,34 @@ Check for Updates… 检查更新… CADCraft is up to date. CADCraft 已是最新版本。 Could not check for updates. 无法检查更新。 + Add a drawing file as a block library 将图形文件添加为块库 + Add a folder of drawings or a drawing file to use its blocks. 添加包含图形的文件夹或图形文件,以使用其中的块。 + Block Libraries 块库 + Block Library 块库 + Blocks Palette 块选项板 + Click a block, then pick its insertion point. 单击块,然后指定其插入点。 + Current Drawing 当前图形 + Details 详细信息 + Extra Large Icons 超大图标 + Folder or file 文件夹或文件 + Import Library Block 导入库中的块 + Insert and Explode 插入并分解 + Large Icons 大图标 + Libraries 库 + Medium Icons 中等图标 + No block matches the filter. 没有与筛选器匹配的块。 + This block is already in the drawing, so its definition is used. 此块已在图形中,因此使用其现有定义。 + Open Library... 打开库... + Read the library again 重新读取库 + Reading the library... 正在读取库... + Refresh 刷新 + Remove from the list 从列表中移除 + Repeat Placement 重复放置 + Small Icons 小图标 + This drawing has no blocks. 此图形中没有块。 + This library has no drawings or blocks. 此库中没有图形或块。 + Only the first {n} are shown. 仅显示前 {n} 个。 + # Menu and command labels the October 2026 update missed (#1129). Align Multileaders 对齐多重引线 Analyze Usage 分析使用情况 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 890732449f..454544ab27 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -45,6 +45,8 @@ pub mod textdlg; // The External References palette. pub mod xrefs; +pub mod blocks_palette; + pub mod dyngrips; pub mod dyninput; pub mod gpu; diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index e0b3c50dfc..5ef80d8a7a 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -156,6 +156,9 @@ fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value) -> Option Option = app.session.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + app.run("block", json!({ "name": name, "base": [0, 0], "handles": handles, "keep": "delete", "description": description })).unwrap(); +} + +/// Blocks "Bolt" (a circle) and "Door" (a line, described "Hinged door"). +fn drawing() -> CadApp { + let mut app = CadApp::new(Session::default(), Services::default()); + app.run("circle", json!({ "center": [0, 0], "radius": 1 })).unwrap(); + make_block(&mut app, "Bolt", ""); + app.run("line", json!({ "points": [[0, 0], [2, 0]] })).unwrap(); + make_block(&mut app, "Door", "Hinged door"); + app +} + +fn harness(app: CadApp) -> Harness<'static, CadApp> { + let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h +} + +#[test] +fn blockspalette_opens_the_palette_and_lists_the_blocks() { + let mut app = drawing(); + assert!(app.cmdline("BLOCKSPALETTE").is_none()); + assert!(app.ui.docking.layout.contains(&Panel::Blocks)); + app.ui.in_window_menu = false; + let h = harness(app); + h.get_by_label("Door"); + h.get_by_label("Bolt"); +} + +#[test] +fn json_blockspalette_lists_and_never_opens_the_palette() { + let mut app = drawing(); + app.run("insert", json!({ "name": "Door", "at": [5, 5] })).unwrap(); + let r = app.run("blockspalette", json!({})).unwrap(); + assert_eq!( + r["blocks"], + json!([ + { "name": "Bolt", "description": "", "references": 0 }, + { "name": "Door", "description": "Hinged door", "references": 1 }, + ]) + ); + // The palette itself asks for no counts, which would read every object. + let r = app.run("blockspalette", json!({ "references": false })).unwrap(); + assert_eq!(r["blocks"][1], json!({ "name": "Door", "description": "Hinged door" })); + assert!(!app.ui.docking.layout.contains(&Panel::Blocks)); +} + +/// A click on a tile starts INSERT and answers the prompts the options settle. +#[test] +fn a_click_starts_insert_for_the_block() { + let mut app = drawing(); + // Alone in the dock the palette has the whole column. + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + h.get_by_label("Door").click(); + h.run_steps(3); + let prompt = h.state().session.prompt_text(); + assert!(prompt.starts_with("INSERT Specify insertion point"), "{prompt}"); +} + +/// The options wait while a block is being placed, and Repeat Placement goes on until Escape. +#[test] +fn options_are_off_while_placing_and_the_block_is_placed_again_until_cancelled() { + use cadcraft_engine::Input; + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + let inserts = |h: &Harness<'static, CadApp>| { + h.state().session.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::Insert(_))).count() + }; + assert!(!h.get_by_label("Repeat Placement").accesskit_node().is_disabled()); + h.get_by_label("Door").click(); + h.run_steps(3); + // Placing: the options are off. + assert!(h.get_by_label("Repeat Placement").accesskit_node().is_disabled()); + // The first block is placed and the same block is attached again (Repeat Placement is on). + h.state_mut().session.input(Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + h.run_steps(3); + assert_eq!(inserts(&h), 1); + assert!(h.state().session.prompt_text().starts_with("INSERT Specify insertion point"), "{}", h.state().session.prompt_text()); + h.state_mut().session.input(Input::Point(cadcraft_engine::geom::Vec2::new(9.0, 5.0))).unwrap(); + h.run_steps(3); + assert_eq!(inserts(&h), 2); + // Cancelling ends it: nothing is placed again and the options are back. + h.state_mut().session.input(Input::Cancel).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); + assert_eq!(inserts(&h), 2); + assert!(!h.get_by_label("Repeat Placement").accesskit_node().is_disabled()); +} + +/// Commands that run from start to end between two frames (queued control requests do) add to +/// the drawing too, but that is no placement of the block: nothing starts placing it again. +#[test] +fn another_command_between_two_frames_ends_the_repeat() { + use cadcraft_engine::Input; + use cadcraft_engine::geom::Vec2; + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + h.get_by_label("Door").click(); + h.run_steps(3); + assert!(h.state().session.prompt_text().starts_with("INSERT"), "{}", h.state().session.prompt_text()); + + let session = &mut h.state_mut().session; + session.start("line").unwrap(); + session.input(Input::Point(Vec2::new(0.0, 0.0))).unwrap(); + session.input(Input::Point(Vec2::new(1.0, 1.0))).unwrap(); + session.input(Input::Enter).unwrap(); + assert_eq!(session.prompt_text(), "Command:"); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); + + // INSERT cancelled, then a JSON command that goes through no prompt. + h.get_by_label("Door").click(); + h.run_steps(3); + assert!(h.state().session.prompt_text().starts_with("INSERT"), "{}", h.state().session.prompt_text()); + h.state_mut().session.input(Input::Cancel).unwrap(); + h.state_mut().run("line", json!({ "points": [[2, 2], [3, 3]] })).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); + + // The block placed, then a command of its own that asks nothing: the user has moved on. + h.get_by_label("Door").click(); + h.run_steps(3); + let session = &mut h.state_mut().session; + session.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap(); + session.start("regen").unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); + + // A JSON command never stops a running one, so it does not end the repeat here either. + h.get_by_label("Door").click(); + h.run_steps(3); + h.state_mut().session.input(Input::Point(Vec2::new(6.0, 6.0))).unwrap(); + h.state_mut().run("line", json!({ "points": [[4, 4], [5, 5]] })).unwrap(); + h.run_steps(3); + assert!(h.state().session.prompt_text().starts_with("INSERT"), "{}", h.state().session.prompt_text()); + h.state_mut().session.input(Input::Cancel).unwrap(); +} + +/// A transparent command run inside the placing INSERT (`'ZOOM`) is not another command: the +/// INSERT resumes and the block goes on being placed again. +#[test] +fn a_transparent_command_while_placing_keeps_the_repeat() { + use cadcraft_engine::Input; + use cadcraft_engine::geom::Vec2; + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + h.get_by_label("Door").click(); + h.run_steps(3); + h.state_mut().session.start("'zoom").unwrap(); + assert!(h.state().session.prompt_text().starts_with(">>ZOOM"), "{}", h.state().session.prompt_text()); + h.run_steps(3); + h.state_mut().session.input(Input::Cancel).unwrap(); + h.run_steps(3); + assert!(h.state().session.prompt_text().starts_with("INSERT Specify insertion point"), "{}", h.state().session.prompt_text()); + h.state_mut().session.input(Input::Point(Vec2::new(5.0, 5.0))).unwrap(); + h.run_steps(3); + assert!(h.state().session.prompt_text().starts_with("INSERT Specify insertion point"), "the repeat went on: {}", h.state().session.prompt_text()); + h.state_mut().session.input(Input::Cancel).unwrap(); +} + +/// A transparent command that ends inside the placing INSERT (an object added meanwhile by a JSON +/// command) is not the INSERT ending: cancelling the INSERT then places nothing again. +#[test] +fn a_transparent_command_ending_inside_the_insert_does_not_count_as_a_placement() { + use cadcraft_engine::Input; + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + h.get_by_label("Door").click(); + h.run_steps(3); + h.state_mut().session.start("'zoom").unwrap(); + h.state_mut().run("line", json!({ "points": [[4, 4], [5, 5]] })).unwrap(); + h.state_mut().session.input(Input::Keyword("Extents".into())).unwrap(); + assert!(h.state().session.prompt_text().starts_with("INSERT Specify insertion point"), "{}", h.state().session.prompt_text()); + h.run_steps(3); + h.state_mut().session.input(Input::Cancel).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:", "the cancelled INSERT is not placed again"); +} + +/// INSERT started as the palette starts it stops at the insertion point. +#[test] +fn insert_started_by_the_palette_flow_waits_for_the_point() { + use cadcraft_engine::Input; + let mut app = drawing(); + app.session.start("insert").unwrap(); + app.session.input(Input::Text("Door".into())).unwrap(); + app.session.input(Input::Keyword("Scale".into())).unwrap(); + app.session.input(Input::Text("2".into())).unwrap(); + app.session.input(Input::Keyword("Rotate".into())).unwrap(); + app.session.input(Input::Text("90".into())).unwrap(); + assert!(app.session.prompt_text().starts_with("INSERT Specify insertion point"), "{}", app.session.prompt_text()); + app.session.input(Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + let ins = app.session.doc().unwrap().model.iter().find_map(|e| match &e.kind { + cadcraft_engine::doc::EntityKind::Insert(i) => Some(i.clone()), + _ => None, + }); + let ins = ins.expect("the block was inserted"); + assert_eq!(ins.block, "Door"); + assert!((ins.scale.x - 2.0).abs() < 1e-9); + assert!((ins.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-9); +} + +#[test] +fn the_palette_closes_and_reopens_where_it_was() { + let mut app = drawing(); + app.cmdline("BLOCKSPALETTE"); + assert!(app.ui.docking.layout.contains(&Panel::Blocks)); + app.run("ui.dock", json!({ "operation": "close", "panel": "blocks" })).unwrap(); + assert!(!app.ui.docking.layout.contains(&Panel::Blocks)); + app.cmdline("BLOCKSPALETTE"); + assert!(app.ui.docking.layout.contains(&Panel::Blocks)); +} + +/// How many times a library file was parsed. +static READS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0); + +/// Every library file reads as a drawing with a block "Valve" (a line), whatever its bytes, and +/// takes long enough to see the palette go on drawing meanwhile. +fn read_library(_bytes: &[u8], _name: &str) -> Result { + use cadcraft_engine::doc::geom::Vec3; + use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, Handle, Line}; + READS.fetch_add(1, std::sync::atomic::Ordering::SeqCst); + std::thread::sleep(std::time::Duration::from_millis(300)); + let mut d = Drawing::new_metric(); + let mut valve = Block::new("Valve"); + valve.entities.push(Entity::new(Handle(0x70), EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(4.0, 0.0, 0.0) }))); + d.blocks.insert("Valve".into(), std::sync::Arc::new(valve)); + Ok(d) +} + +/// Draw frames until `label` shows: a library is read on a worker thread. +fn wait_for(h: &mut Harness<'static, CadApp>, label: &str) { + for _ in 0..1000 { + if h.query_by_label(label).is_some() { + return; + } + std::thread::sleep(std::time::Duration::from_millis(10)); + h.run_steps(1); + } + panic!("{label} never showed"); +} + +/// The whole life of a library: added, read in the background, refreshed, placed from, removed. +#[test] +fn a_library_is_added_listed_placed_and_removed() { + use cadcraft_engine::cmd::file::{IoHooks, set_io}; + set_io(IoHooks { read: read_library, write: |_, _| Err("no writer in this test".into()), plot: None }); + // No settings folder: the real library list is never written. + cadcraft_engine::settings_dir::set(None); + let dir = std::env::temp_dir().join(format!("cadcraft-blocks-palette-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("valves.dxf"); + std::fs::write(&file, b"x").unwrap(); + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.run("blocklibraries", json!({ "op": "add", "path": file.to_string_lossy() })).unwrap(); + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + + // The Libraries tab lists the library; choosing it shows its blocks. + h.get_by_label("Libraries").click(); + h.run_steps(3); + h.get_by_label("valves.dxf").click(); + h.run_steps(2); + // The palette goes on drawing while the file is read, and says so. + h.get_by_label("Reading the library..."); + assert!(h.get_by_label("Refresh").accesskit_node().is_disabled()); + wait_for(&mut h, "Valve"); + assert!(h.state().session.doc().unwrap().block("Valve").is_none()); + + // Refresh parses the file again, even though its size and time have not changed. + let reads = READS.load(std::sync::atomic::Ordering::SeqCst); + h.get_by_label("Refresh").click(); + h.run_steps(2); + wait_for(&mut h, "Valve"); + assert_eq!(READS.load(std::sync::atomic::Ordering::SeqCst), reads + 1); + + // Placing it defines the block here and waits for the insertion point. + h.get_by_label("Valve").click(); + h.run_steps(3); + assert!(h.state().session.doc().unwrap().block("Valve").is_some(), "{}", h.state().session.prompt_text()); + let prompt = h.state().session.prompt_text(); + assert!(prompt.starts_with("INSERT"), "{prompt}"); + h.state_mut().session.input(cadcraft_engine::Input::Cancel).unwrap(); + assert!(!h.state().status.as_ref().is_some_and(|(m, _)| m.contains("already in the drawing"))); + + // Placing it again uses the definition now in the drawing, and says so. + h.get_by_label("Valve").click(); + h.run_steps(3); + assert!(h.state().status.as_ref().is_some_and(|(m, _)| m.contains("already in the drawing")), "{:?}", h.state().status); + // A repeat placement of that block does not say it again. + h.state_mut().status = None; + h.state_mut().session.input(cadcraft_engine::Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + h.run_steps(3); + assert!(h.state().status.is_none(), "{:?}", h.state().status); + h.state_mut().session.input(cadcraft_engine::Input::Cancel).unwrap(); + h.run_steps(3); + + // One undo takes the placed block away, a second the definition the palette imported. + assert_eq!(references(h.state()), 1); + h.state_mut().run("undo", serde_json::Value::Null).unwrap(); + assert_eq!(references(h.state()), 0); + assert!(h.state().session.doc().unwrap().block("Valve").is_some()); + h.state_mut().run("undo", serde_json::Value::Null).unwrap(); + assert!(h.state().session.doc().unwrap().block("Valve").is_none()); + + // A command still running ends before the import, so the only undo step is the import's. + let steps = h.state().session.state().unwrap().undo.len(); + h.state_mut().session.start("circle").unwrap(); + h.get_by_label("Valve").click(); + h.run_steps(3); + assert!(h.state().session.prompt_text().starts_with("INSERT"), "{}", h.state().session.prompt_text()); + assert_eq!(h.state().session.state().unwrap().undo.len(), steps + 1); + h.state_mut().session.input(cadcraft_engine::Input::Cancel).unwrap(); + h.run_steps(3); + h.state_mut().run("undo", serde_json::Value::Null).unwrap(); + assert!(h.state().session.doc().unwrap().block("Valve").is_none()); + + // Removing the library empties the list again. + h.get_by_label("Remove valves.dxf").click(); + h.run_steps(3); + let r = h.state_mut().run("blocklibraries", json!({})).unwrap(); + assert_eq!(r["libraries"], json!([])); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn the_toolbar_icon_and_the_window_menu_open_the_palette_not_a_dialog() { + let mut app = drawing(); + app.run("ui.dialog.blocks", serde_json::Value::Null).unwrap(); + assert!(app.ui.docking.layout.contains(&Panel::Blocks)); + assert!(app.ui.dialog.is_none(), "the old Blocks window is gone"); + // Like the other ui.dialog.* ids, it opens whatever the parameters are. + let mut app = drawing(); + app.run("ui.dialog.blocks", json!({})).unwrap(); + assert!(app.ui.docking.layout.contains(&Panel::Blocks)); +} + +/// An exploded block leaves no reference, and it repeats all the same. +#[test] +fn repeat_placement_goes_on_when_the_block_is_placed_exploded() { + use cadcraft_engine::Input; + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + let count = |h: &Harness<'static, CadApp>, refs: bool| { + h.state().session.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::Insert(_)) == refs).count() + }; + h.get(egui_kittest::kittest::by().role(egui::accesskit::Role::CheckBox).label("Explode")).click(); + h.run_steps(2); + h.get_by_label("Door").click(); + h.run_steps(3); + // An exploded block leaves no reference, only its objects, and the next one is attached. + h.state_mut().session.input(Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + h.run_steps(3); + assert_eq!((count(&h, true), count(&h, false)), (0, 1)); + assert!(h.state().session.prompt_text().starts_with("INSERT Specify insertion point"), "{}", h.state().session.prompt_text()); + h.state_mut().session.input(Input::Point(cadcraft_engine::geom::Vec2::new(9.0, 5.0))).unwrap(); + h.run_steps(3); + assert_eq!((count(&h, true), count(&h, false)), (0, 2)); + // Cancelling still ends it. + h.state_mut().session.input(Input::Cancel).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); + assert_eq!(count(&h, false), 2); +} + +/// What ran while the palette was hidden went unwatched: nothing repeats when it comes back. +#[test] +fn a_hidden_palette_does_not_start_placing_again_when_it_comes_back() { + use cadcraft_engine::Input; + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + h.get_by_label("Door").click(); + h.run_steps(3); + // The palette goes away while the block is being placed, and other commands run. + h.state_mut().run("ui.dock", json!({ "operation": "close", "panel": "blocks" })).unwrap(); + h.run_steps(3); + h.state_mut().session.input(Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + h.state_mut().run("line", json!({ "points": [[0, 0], [2, 0]] })).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); + h.state_mut().run("blockspalette", serde_json::Value::Null).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:", "nothing is attached to the cursor"); +} + +/// Switching drawings ends the repeat. +#[test] +fn repeat_placement_does_not_carry_over_to_another_drawing() { + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + h.get_by_label("Door").click(); + h.run_steps(3); + // The user moves to a new drawing, whose handle counter is well past the first one's. + h.state_mut().session.new_drawing(true); + h.state_mut().session.running = None; + for _ in 0..20 { + h.state_mut().run("line", json!({ "points": [[0, 0], [2, 0]] })).unwrap(); + } + make_block(h.state_mut(), "Door", ""); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:", "nothing is attached in the other drawing"); +} + +/// How many INSERT references model space holds. +fn references(app: &CadApp) -> usize { + app.session.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::Insert(_))).count() +} + +/// `app` with the palette open and the panels above it closed, so its gallery has room. +fn open_palette(mut app: CadApp) -> Harness<'static, CadApp> { + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + harness(app) +} + +#[test] +fn escape_while_placing_places_nothing_and_frees_the_options() { + let mut h = open_palette(drawing()); + h.get_by_label("Door").click(); + h.run_steps(3); + assert!(h.state().session.prompt_text().starts_with("INSERT")); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); + assert_eq!(references(h.state()), 0); + assert!(!h.get_by_label("Repeat Placement").accesskit_node().is_disabled()); + // And nothing is attached again afterwards. + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); +} + +#[test] +fn a_placed_block_is_one_undo_step() { + let mut h = open_palette(drawing()); + // Repeat off, so one click places one block. + h.get_by_label("Repeat Placement").click(); + h.run_steps(2); + h.get_by_label("Door").click(); + h.run_steps(3); + h.state_mut().session.input(cadcraft_engine::Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + h.run_steps(3); + assert_eq!(references(h.state()), 1); + h.state_mut().run("undo", serde_json::Value::Null).unwrap(); + assert_eq!(references(h.state()), 0, "one undo takes the placed block away"); + assert!(h.state().session.doc().unwrap().block("Door").is_some(), "the block itself is still defined"); +} + +#[test] +fn a_tile_is_reachable_and_placed_from_the_keyboard() { + let mut h = open_palette(drawing()); + h.get_by_label("Door").focus(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(h.state().session.prompt_text().starts_with("INSERT"), "{}", h.state().session.prompt_text()); +} + +/// A big gallery builds only the visible tiles, a few per frame, so it opens quickly. +#[test] +fn a_drawing_of_a_thousand_blocks_stays_responsive_and_bounded() { + let mut app = CadApp::new(Session::default(), Services::default()); + for i in 0..1000 { + app.run("circle", json!({ "center": [i, 0], "radius": 1 })).unwrap(); + make_block(&mut app, &format!("Part{i:04}"), ""); + } + let mut h = open_palette(app); + let started = std::time::Instant::now(); + h.run_steps(60); + // Only the visible tiles are drawn, a few per frame: 60 frames are nowhere near 1000 builds. + assert!(started.elapsed() < std::time::Duration::from_secs(30), "{:?}", started.elapsed()); + h.get_by_label("Part0000"); + assert!(h.state().session.prompt_text() == "Command:"); +} diff --git a/crates/ui-egui/tests/it/context_menu.rs b/crates/ui-egui/tests/it/context_menu.rs index 7dda86f29b..220e1ae14d 100644 --- a/crates/ui-egui/tests/it/context_menu.rs +++ b/crates/ui-egui/tests/it/context_menu.rs @@ -202,3 +202,38 @@ fn shift_right_click_opens_the_snap_menu() { } assert!(app.session.prompt_text().contains("Specify next point"), "no Enter: {}", app.session.prompt_text()); } + +/// A quick right-click on the canvas at the insertion point of an INSERT the Blocks palette started +/// cancels it; the same click during a typed INSERT is Enter, which asks the point again. +#[test] +fn quick_right_click_cancels_a_palette_placement_only() { + let mut app = CadApp::new(Session::new(), Services::default()); + let ctx = egui::Context::default(); + app.logic(&ctx); + painted(&mut app, &ctx, Vec::new(), egui::Modifiers::NONE); + app.session.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + let handles: Vec = app.session.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + app.session.execute("block", &json!({ "name": "BOLT", "base": [0, 0], "handles": handles, "keep": "delete" })).unwrap(); + let at = egui::pos2(800.0, 500.0); + let click = |pressed| egui::Event::PointerButton { pos: at, button: egui::PointerButton::Secondary, pressed, modifiers: egui::Modifiers::NONE }; + let right_click = |app: &mut CadApp| { + painted(app, &ctx, vec![egui::Event::PointerMoved(at)], egui::Modifiers::NONE); + painted(app, &ctx, vec![click(true), click(false)], egui::Modifiers::NONE); + painted(app, &ctx, Vec::new(), egui::Modifiers::NONE); + }; + + app.cmdline("INSERT"); + app.cmdline("BOLT"); + assert!(app.session.prompt_text().contains("Specify insertion point"), "{}", app.session.prompt_text()); + right_click(&mut app); + assert!(app.session.prompt_text().contains("Specify insertion point"), "a typed INSERT asks again: {}", app.session.prompt_text()); + app.session.cancel(); + + app.cmdline("INSERT"); + app.cmdline("BOLT"); + app.canvas.palette_insert = Some(app.session.commands_started); + app.cmd.buffer = "12,".into(); + right_click(&mut app); + assert!(!app.session.prompting(), "the palette's placement ends: {}", app.session.prompt_text()); + assert!(app.cmd.buffer.is_empty(), "the half-typed point goes too: {}", app.cmd.buffer); +}