diff --git a/Cargo.lock b/Cargo.lock index b22601e6..6272ba25 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -156,6 +156,21 @@ dependencies = [ "zerocopy", ] +[[package]] +name = "alloc-no-stdlib" +version = "2.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc7bb162ec39d46ab1ca8c77bf72e890535becd1751bb45f64c597edb4c8c6b3" + +[[package]] +name = "alloc-stdlib" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e76a019e91224d279006ff972f1e984179a6e9feb050adba6ce8274aef23195" +dependencies = [ + "alloc-no-stdlib", +] + [[package]] name = "allocator-api2" version = "0.2.21" @@ -568,6 +583,27 @@ dependencies = [ "piper", ] +[[package]] +name = "brotli" +version = "8.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5cc91aac060a7a1e25823bdccbfb6af1875b88f17c6daac97894eed8207166b3" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", + "brotli-decompressor", +] + +[[package]] +name = "brotli-decompressor" +version = "5.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a32acac15fe1967bc3986b2a6347dffc965602354ea6f450ad07e8bfd253583" +dependencies = [ + "alloc-no-stdlib", + "alloc-stdlib", +] + [[package]] name = "bumpalo" version = "3.20.3" @@ -954,6 +990,9 @@ name = "craft-pdf" version = "0.1.0" source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ + "bytemuck", + "hayro", + "hayro-interpret", "hayro-syntax", "krilla", "thiserror 2.0.21", @@ -1289,6 +1328,7 @@ dependencies = [ "serde", "serde_json", "thiserror 2.0.21", + "zip", ] [[package]] @@ -1324,6 +1364,7 @@ dependencies = [ "draftcraft-geom", "draftcraft-render", "image", + "kurbo", "miniz_oxide 0.9.1", "quick-xml 0.42.0", "serde", @@ -1682,7 +1723,7 @@ dependencies = [ "unicode-general-category", "unicode-properties", "unicode-segmentation", - "vello_cpu", + "vello_cpu 0.2.0", ] [[package]] @@ -2035,6 +2076,23 @@ dependencies = [ "xml-rs", ] +[[package]] +name = "glifo" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d99fc21d493812643aae86d53b7bbd02f376434a90317e8a790bc209fdd6605e" +dependencies = [ + "bytemuck", + "foldhash 0.2.0", + "hashbrown 0.17.1", + "log", + "peniko", + "png", + "skrifa 0.42.1", + "smallvec", + "vello_common 0.0.9", +] + [[package]] name = "glifo" version = "0.3.0" @@ -2048,7 +2106,7 @@ dependencies = [ "peniko", "skrifa 0.44.0", "smallvec", - "vello_common", + "vello_common 0.2.0", ] [[package]] @@ -2226,17 +2284,59 @@ dependencies = [ "foldhash 0.2.0", ] +[[package]] +name = "hayro" +version = "0.7.1" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +dependencies = [ + "bytemuck", + "hayro-interpret", + "image", + "kurbo", + "log", + "pic-scale", + "vello_cpu 0.0.8", +] + [[package]] name = "hayro-ccitt" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9f4d0e94ddd48749f06bbe4e5389fb9799a0c45bcaf00495042076ef05e3241a" +[[package]] +name = "hayro-cmap" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +dependencies = [ + "brotli", + "hayro-postscript", +] + +[[package]] +name = "hayro-interpret" +version = "0.7.0" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" +dependencies = [ + "bitflags 2.13.2", + "hayro-cmap", + "hayro-syntax", + "kurbo", + "moxcms", + "phf 0.13.1", + "rustc-hash 2.1.3", + "siphasher", + "skrifa 0.47.0", + "smallvec", + "yoke", +] + [[package]] name = "hayro-jbig2" version = "0.3.0" source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ + "fearless_simd", "hayro-ccitt", ] @@ -2245,14 +2345,25 @@ name = "hayro-jpeg2000" version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c75ab947623ef4ccaa7acf0579edf7cbb5a73838e3839a7be73335e522f433a1" +dependencies = [ + "fearless_simd", +] + +[[package]] +name = "hayro-postscript" +version = "0.1.0" +source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" [[package]] name = "hayro-syntax" version = "0.7.2" source = "git+https://github.com/storytold/craft-libs?rev=92d392cff132eaf53e13afff77f38b5c11b73aa0#92d392cff132eaf53e13afff77f38b5c11b73aa0" dependencies = [ + "flate2", + "hayro-ccitt", "hayro-jbig2", "hayro-jpeg2000", + "memchr", "rustc-hash 2.1.3", "smallvec", "stringprep", @@ -3601,17 +3712,37 @@ dependencies = [ "phf_shared 0.11.3", ] +[[package]] +name = "phf" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf" +dependencies = [ + "phf_macros 0.13.1", + "phf_shared 0.13.1", +] + [[package]] name = "phf" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" dependencies = [ - "phf_macros", + "phf_macros 0.14.0", "phf_shared 0.14.0", "serde", ] +[[package]] +name = "phf_generator" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737" +dependencies = [ + "fastrand", + "phf_shared 0.13.1", +] + [[package]] name = "phf_generator" version = "0.14.0" @@ -3622,13 +3753,26 @@ dependencies = [ "phf_shared 0.14.0", ] +[[package]] +name = "phf_macros" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef" +dependencies = [ + "phf_generator 0.13.1", + "phf_shared 0.13.1", + "proc-macro2", + "quote", + "syn 2.0.119", +] + [[package]] name = "phf_macros" version = "0.14.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" dependencies = [ - "phf_generator", + "phf_generator 0.14.0", "phf_shared 0.14.0", "proc-macro2", "quote", @@ -3644,6 +3788,15 @@ dependencies = [ "siphasher", ] +[[package]] +name = "phf_shared" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266" +dependencies = [ + "siphasher", +] + [[package]] name = "phf_shared" version = "0.14.0" @@ -3653,6 +3806,16 @@ dependencies = [ "siphasher", ] +[[package]] +name = "pic-scale" +version = "0.7.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb0ff645d35accaec252de081d55984a0d6c952cb1e5dc2b9afa7c78f07288" +dependencies = [ + "num-traits", + "pxfm", +] + [[package]] name = "pin-project" version = "1.1.13" @@ -3951,6 +4114,17 @@ dependencies = [ "once_cell", ] +[[package]] +name = "read-fonts" +version = "0.44.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5a0cf4bb6cbce4c29756270d189a5e400ac05e91192161d83a0bcb6e68492e8" +dependencies = [ + "bytemuck", + "font-types 0.12.7", + "once_cell", +] + [[package]] name = "read-fonts" version = "0.45.1" @@ -4415,6 +4589,16 @@ dependencies = [ "read-fonts 0.41.0", ] +[[package]] +name = "skrifa" +version = "0.47.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "526e654b303ff4ad73a5a40b25de2b3ce3d039c5e3b6da5f89ae6e57004cb40f" +dependencies = [ + "bytemuck", + "read-fonts 0.44.0", +] + [[package]] name = "skrifa" version = "0.48.0" @@ -5055,6 +5239,40 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "vello_common" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3361bff7f7d82c0c496b92048db83846691f0e844cc28dee92b1c824291b55ee" +dependencies = [ + "bytemuck", + "fearless_simd", + "guillotiere", + "hashbrown 0.17.1", + "log", + "peniko", + "png", + "smallvec", + "thiserror 2.0.21", +] + +[[package]] +name = "vello_common" +version = "0.0.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19d672facaa2d697285a786cd9d44d614cd2ce54cdc022504bf339f8fff3b750" +dependencies = [ + "bytemuck", + "fearless_simd", + "guillotiere", + "hashbrown 0.17.1", + "log", + "peniko", + "png", + "smallvec", + "thiserror 2.0.21", +] + [[package]] name = "vello_common" version = "0.2.0" @@ -5070,6 +5288,19 @@ dependencies = [ "thiserror 2.0.21", ] +[[package]] +name = "vello_cpu" +version = "0.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d8ded630e8316bb94a55881256506d1f3b9947b5f66db8a7d32ca7ba02decd0" +dependencies = [ + "bytemuck", + "glifo 0.1.1", + "hashbrown 0.17.1", + "png", + "vello_common 0.0.8", +] + [[package]] name = "vello_cpu" version = "0.2.0" @@ -5077,9 +5308,9 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ace506ca414548966fcf3c283be94eb1cad8254de488791ee698bf438b0890a9" dependencies = [ "bytemuck", - "glifo", + "glifo 0.3.0", "hashbrown 0.17.1", - "vello_common", + "vello_common 0.2.0", ] [[package]] diff --git a/Cargo.toml b/Cargo.toml index 599f056c..794fbd47 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -106,6 +106,10 @@ debug = 0 krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +hayro = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } +hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0" } # Keep the complete egui family and native event bridge on reviewed fork commits. ecolor = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" } diff --git a/apps/draftcraft-cli/src/lib.rs b/apps/draftcraft-cli/src/lib.rs index 474f3f15..d2b28bd6 100644 --- a/apps/draftcraft-cli/src/lib.rs +++ b/apps/draftcraft-cli/src/lib.rs @@ -46,6 +46,11 @@ fn install_io() { plot: Some(|d, space, opts| draftcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), }); draftcraft_engine::cmd::file::set_image_decoder(|b| draftcraft_io::raster::decode(b).map_err(|e| e.to_string())); + draftcraft_engine::cmd::file::set_pdf_hooks(draftcraft_engine::cmd::file::PdfHooks { + pages: |b| draftcraft_io::pdf_read::pages(b).map_err(|e| e.to_string()), + rasterize: |b, page, dpi| draftcraft_io::pdf_read::rasterize(b, page, dpi).map_err(|e| e.to_string()), + import: draftcraft_io::pdf_read::import_flat, + }); draftcraft_engine::cmd::file::set_write_as(|d, name, o| { draftcraft_io::write_with(d, name, &draftcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); diff --git a/apps/draftcraft-cli/tests/it/undrawn_entities.rs b/apps/draftcraft-cli/tests/it/undrawn_entities.rs index dfef67d7..44fcdcd1 100644 --- a/apps/draftcraft-cli/tests/it/undrawn_entities.rs +++ b/apps/draftcraft-cli/tests/it/undrawn_entities.rs @@ -7,12 +7,13 @@ fn cli(args: &[&str]) -> Output { Command::new(env!("CARGO_BIN_EXE_draftcraft-cli")).args(args).output().unwrap() } -/// A line, two foreign REGIONs and a PDF underlay: the last three are kept as unknown entities. +/// A line, two foreign REGIONs and a DWF underlay: the last three are kept as unknown entities +/// (PDF underlays are drawn; DWF ones are not available yet). const PROXIES: &str = "0\nSECTION\n2\nENTITIES\n\ 0\nLINE\n8\n0\n10\n0\n20\n0\n11\n5\n21\n5\n\ 0\nREGION\n8\n0\n70\n1\n1\nabc\n\ 0\nREGION\n8\n0\n70\n1\n1\ndef\n\ -0\nPDFUNDERLAY\n8\n0\n10\n0\n20\n0\n41\n1\n42\n1\n43\n1\n\ +0\nDWFUNDERLAY\n8\n0\n10\n0\n20\n0\n41\n1\n42\n1\n43\n1\n\ 0\nENDSEC\n0\nEOF\n"; #[test] @@ -34,7 +35,7 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() { let err = String::from_utf8_lossy(&out.stderr); let warnings: Vec<&str> = err.lines().filter(|l| l.contains("not drawn")).collect(); assert_eq!(warnings.len(), 1, "{ext}: {err}"); - assert_eq!(warnings[0], format!("{input}: 3 entities not drawn (PDFUNDERLAY: 1, REGION: 2)"), "{ext}"); + assert_eq!(warnings[0], format!("{input}: 3 entities not drawn (DWFUNDERLAY: 1, REGION: 2)"), "{ext}"); } // A DXF copy keeps them, so there is nothing to warn about. diff --git a/apps/draftcraft-web/src/main.rs b/apps/draftcraft-web/src/main.rs index a40795be..62b4ec32 100644 --- a/apps/draftcraft-web/src/main.rs +++ b/apps/draftcraft-web/src/main.rs @@ -118,6 +118,11 @@ mod web { plot: Some(|d, space, opts| draftcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), }); draftcraft_engine::cmd::file::set_image_decoder(|b| draftcraft_io::raster::decode(b).map_err(|e| e.to_string())); + draftcraft_engine::cmd::file::set_pdf_hooks(draftcraft_engine::cmd::file::PdfHooks { + pages: |b| draftcraft_io::pdf_read::pages(b).map_err(|e| e.to_string()), + rasterize: |b, page, dpi| draftcraft_io::pdf_read::rasterize(b, page, dpi).map_err(|e| e.to_string()), + import: draftcraft_io::pdf_read::import_flat, + }); draftcraft_engine::cmd::file::set_write_as(|d, name, o| { draftcraft_io::write_with(d, name, &draftcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); diff --git a/apps/draftcraft/src/main.rs b/apps/draftcraft/src/main.rs index 224387fd..9078da43 100644 --- a/apps/draftcraft/src/main.rs +++ b/apps/draftcraft/src/main.rs @@ -147,6 +147,11 @@ pub fn install_io() { plot: Some(|d, space, opts| draftcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())), }); draftcraft_engine::cmd::file::set_image_decoder(|b| draftcraft_io::raster::decode(b).map_err(|e| e.to_string())); + draftcraft_engine::cmd::file::set_pdf_hooks(draftcraft_engine::cmd::file::PdfHooks { + pages: |b| draftcraft_io::pdf_read::pages(b).map_err(|e| e.to_string()), + rasterize: |b, page, dpi| draftcraft_io::pdf_read::rasterize(b, page, dpi).map_err(|e| e.to_string()), + import: draftcraft_io::pdf_read::import_flat, + }); draftcraft_engine::cmd::file::set_write_as(|d, name, o| { draftcraft_io::write_with(d, name, &draftcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string()) }); @@ -180,6 +185,13 @@ fn services() -> Services { let dialog = if dir.is_empty() { dialog } else { dialog.set_directory(dir) }; dialog.pick_file().map(|p| p.to_string_lossy().to_string()) })), + pick_file: Some(Box::new(|label: &str, exts: &[&str]| { + rfd::FileDialog::new() + .add_filter(i18n::t(label), exts) + .add_filter(i18n::t("All files"), &["*"]) + .pick_file() + .map(|p| p.to_string_lossy().to_string()) + })), no_file_system: false, } } @@ -188,9 +200,17 @@ fn services() -> Services { /// filter's extension, and macOS accepts only listed extensions, replacing any other with the /// first one. DWG must be listed for a `.dwg` name to survive, and a drawing opened from DWG /// then defaults to DWG; other names keep DXF first. -fn filters_for_save(name: &str) -> [(&'static str, &'static str); 6] { - let mut filters = - [("Drawing (DXF)", "dxf"), ("Drawing (DWG)", "dwg"), ("Drawing Template (DWT)", "dwt"), ("SVG", "svg"), ("PNG", "png"), ("PDF", "pdf")]; +fn filters_for_save(name: &str) -> [(&'static str, &'static str); 8] { + let mut filters = [ + ("Drawing (DXF)", "dxf"), + ("Drawing (DWG)", "dwg"), + ("Drawing Template (DWT)", "dwt"), + ("SVG", "svg"), + ("PNG", "png"), + ("PDF", "pdf"), + ("Sheet Set (DCSS)", "dcss"), + ("ZIP archive", "zip"), + ]; let lower = name.to_ascii_lowercase(); filters.sort_by_key(|(_, ext)| !lower.ends_with(&format!(".{ext}"))); filters @@ -503,6 +523,7 @@ mod tests { assert_eq!(first("Drawing1"), "dxf"); assert_eq!(first("plan.pdf"), "pdf"); assert_eq!(first("office.dwt"), "dwt"); + assert_eq!(first("Project.dcss"), "dcss"); for name in ["a.dwg", "b.dxf", "c"] { let exts: Vec<_> = filters_for_save(name).iter().map(|(_, e)| *e).collect(); assert!(exts.contains(&"dwg") && exts.contains(&"dxf"), "{name}"); diff --git a/crates/doc/src/dynblock.rs b/crates/doc/src/dynblock.rs index 3860b9f9..5cdb3695 100644 --- a/crates/doc/src/dynblock.rs +++ b/crates/doc/src/dynblock.rs @@ -20,6 +20,7 @@ use crate::foreign::ForeignObject; use crate::{Drawing, Handle, RawTag}; mod apply; +pub mod author; mod grips; mod reference; pub use apply::{drag_grip, set_property}; diff --git a/crates/doc/src/dynblock/author.rs b/crates/doc/src/dynblock/author.rs new file mode 100644 index 00000000..69321258 --- /dev/null +++ b/crates/doc/src/dynblock/author.rs @@ -0,0 +1,401 @@ +//! Making a block dynamic: adding parameters and actions to a block (BPARAMETER and BACTION in +//! the Block Editor). +//! +//! They are written as the same objects [`dynamic_block`](super::dynamic_block) reads: the block +//! record's extension dictionary gets an `ACAD_ENHANCEDBLOCK` evaluation graph, and each parameter, +//! its grips and each action become members of it, with the groups the reader and +//! [`set_property`](super::set_property) use. So a reference to the block gets its grips and custom +//! properties in DraftCraft at once, and the objects are kept and written with the drawing. +//! +//! What can be made so far: a linear (distance) parameter and a point parameter, and stretch and +//! move actions on them. + +use std::sync::Arc; + +use draftcraft_geom::{Vec2, Vec3}; + +use super::{ParameterKind, ValueSet, dynamic_block}; +use crate::foreign::ForeignObject; +use crate::{Drawing, Handle, RawTag}; + +/// Most objects one action may act on. +pub const MAX_SELECTION: usize = 10_000; +/// Longest name, label or description kept. +const MAX_TEXT: usize = 255; + +fn tag(code: i32, value: impl Into) -> RawTag { + RawTag { code, value: value.into() } +} + +fn text(s: &str) -> String { + s.chars().filter(|c| !c.is_control()).take(MAX_TEXT).collect() +} + +fn real(v: f64) -> String { + if v.is_finite() { format!("{v}") } else { "0".into() } +} + +fn point(tags: &mut Vec, x: i32, p: Vec3) { + tags.extend([tag(x, real(p.x)), tag(x + 10, real(p.y)), tag(x + 20, real(p.z))]); +} + +/// The definition of a new parameter. +#[derive(Clone, Debug, PartialEq)] +pub enum NewParameter { + /// A distance between two points (block coordinates); `values` limits it. + Linear { base: Vec2, end: Vec2, label: String, description: String, values: ValueSet, from_midpoint: bool }, + /// A position (block coordinates). + Point { at: Vec2, label: String, description: String }, +} + +/// The definition of a new action on parameter `parameter` (its graph id). +#[derive(Clone, Debug, PartialEq)] +pub enum NewAction { + /// Moves the points of `objects` inside `frame` (two corners or a polygon, block coordinates) + /// by the change of the parameter's end point. + Stretch { parameter: i32, frame: Vec, objects: Vec }, + /// Moves `objects` by the change of the parameter's end point (a point parameter's position). + Move { parameter: i32, objects: Vec }, +} + +/// What was added: the member's graph id, object handle and name. +#[derive(Clone, Debug, PartialEq)] +pub struct Added { + pub node: i32, + pub handle: Handle, + pub name: String, +} + +/// The record key of block `name` in the kept foreign data. +fn record_key(name: &str) -> (String, String) { + ("BLOCK_RECORD".to_string(), name.trim().to_ascii_uppercase()) +} + +fn find(d: &Drawing, h: Handle) -> Option<&ForeignObject> { + d.foreign.objects.iter().find(|o| o.handle == h) +} + +fn find_mut(d: &mut Drawing, h: Handle) -> Option<&mut ForeignObject> { + Arc::make_mut(&mut d.foreign).objects.iter_mut().find(|o| o.handle == h) +} + +/// The entry `key` of dictionary object `dict`. +fn entry(o: &ForeignObject, key: &str) -> Option { + let mut it = o.tags.iter(); + while let Some(t) = it.next() { + if t.code == 3 && t.value.eq_ignore_ascii_case(key) { + return it.next().filter(|t| matches!(t.code, 350 | 360)).and_then(|t| Handle::parse_hex(&t.value)); + } + } + None +} + +/// The handle the kept data knows block record `key` by: the file's, or for a block made here a +/// new one, which the writer turns into the written record's handle like a file's. +fn record_handle(d: &mut Drawing, key: &(String, String)) -> Handle { + if let Some(h) = d.foreign.targets.iter().find(|(_, k)| *k == key).map(|(h, _)| *h) { + return h; + } + let h = d.new_handle(); + Arc::make_mut(&mut d.foreign).targets.insert(h, key.clone()); + h +} + +/// Block `name`'s evaluation graph, made (with the extension dictionary that holds it) when the +/// block has none. +fn graph(d: &mut Drawing, name: &str) -> Result { + if d.block(name).is_none() { + return Err(format!("Block \"{name}\" not found.")); + } + let key = record_key(name); + let xdict = match d.foreign.records.get(&key).and_then(|x| x.xdict).filter(|h| find(d, *h).is_some()) { + Some(h) => h, + None => { + let owner = record_handle(d, &key); + let h = d.new_handle(); + Arc::make_mut(&mut d.foreign).objects.push(ForeignObject { + handle: h, + kind: "DICTIONARY".into(), + tags: vec![tag(5, h.hex()), tag(330, owner.hex()), tag(100, "AcDbDictionary"), tag(280, "1"), tag(281, "1")], + }); + Arc::make_mut(&mut d.foreign).records.entry(key).or_default().xdict = Some(h); + h + } + }; + let existing = find(d, xdict) + .and_then(|o| entry(o, "ACAD_ENHANCEDBLOCK")) + .filter(|g| find(d, *g).is_some_and(|o| o.kind.eq_ignore_ascii_case("ACAD_EVALUATION_GRAPH"))); + if let Some(g) = existing { + return Ok(g); + } + let g = d.new_handle(); + Arc::make_mut(&mut d.foreign).objects.push(ForeignObject { + handle: g, + kind: "ACAD_EVALUATION_GRAPH".into(), + tags: vec![tag(5, g.hex()), tag(330, xdict.hex()), tag(100, "AcDbEvalGraph"), tag(96, "0"), tag(97, "0")], + }); + if let Some(dict) = find_mut(d, xdict) { + dict.tags.push(tag(3, "ACAD_ENHANCEDBLOCK")); + dict.tags.push(tag(360, g.hex())); + } + Ok(g) +} + +/// The next free graph id: one more than any the block's graph uses. +fn next_node(d: &Drawing, name: &str) -> i32 { + let Some(m) = dynamic_block(d, name) else { return 0 }; + let used = m.parameters.iter().map(|p| p.node).chain(m.actions.iter().map(|a| a.node)).chain(m.grip_objects.iter().map(|g| g.0)); + let grips = m.parameters.iter().flat_map(|p| p.grips.iter().copied()); + used.chain(grips).max().map_or(0, |n| n.saturating_add(1)) +} + +/// A name not used by another member of the block's graph: `base` followed by a number. +fn unique_name(d: &Drawing, name: &str, base: &str) -> String { + let m = dynamic_block(d, name).unwrap_or_default(); + let taken = |s: &str| { + m.parameters.iter().any(|p| p.element.eq_ignore_ascii_case(s) || p.kind.label().is_some_and(|l| l.eq_ignore_ascii_case(s))) + || m.actions.iter().any(|a| a.name.eq_ignore_ascii_case(s)) + }; + (1..10_000).map(|i| format!("{base}{i}")).find(|s| !taken(s)).unwrap_or_else(|| format!("{base}{}", m.parameters.len() + m.actions.len() + 1)) +} + +/// Add member `tags` (kind `kind`) to graph `g`. +fn add_member(d: &mut Drawing, g: Handle, kind: &str, mut tags: Vec) -> Handle { + let h = d.new_handle(); + tags.insert(0, tag(330, g.hex())); + tags.insert(0, tag(5, h.hex())); + Arc::make_mut(&mut d.foreign).objects.push(ForeignObject { handle: h, kind: kind.into(), tags }); + if let Some(o) = find_mut(d, g) { + o.tags.push(tag(360, h.hex())); + } + h +} + +fn head(node: i32, element: &str) -> Vec { + vec![tag(100, "AcDbEvalExpr"), tag(90, node.to_string()), tag(100, "AcDbBlockElement"), tag(300, element)] +} + +/// Add parameter `p` to block `name`. Its label defaults to "Distance1", "Position1"… +pub fn add_parameter(d: &mut Drawing, name: &str, p: &NewParameter) -> Result { + let finite = |v: Vec2| v.x.is_finite() && v.y.is_finite(); + match p { + NewParameter::Linear { base, end, .. } if !finite(*base) || !finite(*end) => return Err("Invalid point.".into()), + NewParameter::Linear { base, end, .. } if (*end - *base).len() < 1e-9 => return Err("The two points must differ.".into()), + NewParameter::Point { at, .. } if !finite(*at) => return Err("Invalid point.".into()), + _ => {} + } + let g = graph(d, name)?; + let node = next_node(d, name); + let (grip1, grip2) = (node.saturating_add(1), node.saturating_add(2)); + let (kind, element, label, tags, grips): (&str, &str, String, Vec, Vec<(i32, &str)>) = match p { + NewParameter::Linear { base, end, label, description, values, from_midpoint } => { + let label = if label.trim().is_empty() { unique_name(d, name, "Distance") } else { text(label) }; + let mut t = head(node, "Linear"); + t.extend([tag(100, "AcDbBlockParameter"), tag(280, "1"), tag(281, "0"), tag(100, "AcDbBlock2PtParameter")]); + point(&mut t, 1010, base.to3(0.0)); + point(&mut t, 1011, end.to3(0.0)); + t.extend([tag(170, "2"), tag(91, grip1.to_string()), tag(91, grip2.to_string()), tag(177, if *from_midpoint { "1" } else { "0" })]); + t.extend([tag(100, "AcDbBlockLinearParameter"), tag(305, label.clone()), tag(306, text(description)), tag(307, "")]); + t.extend([ + tag(96, values.flags.to_string()), + tag(141, real(values.minimum)), + tag(142, real(values.maximum)), + tag(143, real(values.increment)), + ]); + let list: Vec = values.list.iter().copied().filter(|v| v.is_finite()).take(MAX_SELECTION).collect(); + t.push(tag(175, list.len().to_string())); + t.extend(list.iter().map(|v| tag(144, real(*v)))); + ("BLOCKLINEARPARAMETER", "Linear", label, t, vec![(grip1, "Grip"), (grip2, "Grip")]) + } + NewParameter::Point { at, label, description } => { + let label = if label.trim().is_empty() { unique_name(d, name, "Position") } else { text(label) }; + let mut t = head(node, "Point"); + t.extend([tag(100, "AcDbBlockParameter"), tag(280, "1"), tag(281, "0"), tag(100, "AcDbBlock1PtParameter")]); + point(&mut t, 1010, at.to3(0.0)); + t.push(tag(93, grip1.to_string())); + t.extend([tag(100, "AcDbBlockPointParameter"), tag(303, label.clone()), tag(304, text(description))]); + ("BLOCKPOINTPARAMETER", "Point", label, t, vec![(grip1, "Grip")]) + } + }; + let label_taken = + dynamic_block(d, name).is_some_and(|m| m.parameters.iter().any(|q| q.kind.label().is_some_and(|l| l.eq_ignore_ascii_case(&label)))); + if label_taken { + return Err(format!("The block already has a parameter named \"{label}\".")); + } + let _ = element; + let handle = add_member(d, g, kind, tags); + let grip_kind = if kind == "BLOCKLINEARPARAMETER" { "BLOCKLINEARGRIP" } else { "BLOCKXYGRIP" }; + for (id, el) in grips { + let mut t = head(id, el); + t.extend([tag(100, "AcDbBlockGrip"), tag(91, node.to_string())]); + add_member(d, g, grip_kind, t); + } + Ok(Added { node, handle, name: label }) +} + +/// Add action `a` to block `name`. Its objects must be the block's. +pub fn add_action(d: &mut Drawing, name: &str, a: &NewAction) -> Result { + let m = dynamic_block(d, name).ok_or("Add a parameter first: an action follows a parameter.")?; + let (param, objects) = match a { + NewAction::Stretch { parameter, objects, .. } | NewAction::Move { parameter, objects } => (*parameter, objects), + }; + let p = m.parameters.iter().find(|p| p.node == param).ok_or("No such parameter.")?; + let block = d.block(name).ok_or_else(|| format!("Block \"{name}\" not found."))?; + let mut seen = std::collections::HashSet::new(); + // In the Block Editor the block's objects are the editor drawing's model space. + let objects: Vec = objects + .iter() + .copied() + .filter(|h| (block.entities.get(*h).is_some() || d.model.get(*h).is_some()) && seen.insert(*h)) + .take(MAX_SELECTION) + .collect(); + if objects.is_empty() { + return Err("Select the block's objects the action changes.".into()); + } + let (at, connections): (Vec3, [&str; 2]) = match &p.kind { + ParameterKind::Linear { end, .. } => (*end, ["EndXDelta", "EndYDelta"]), + ParameterKind::Point { at, .. } => (*at, ["XDelta", "YDelta"]), + _ => return Err("Actions can be added to linear and point parameters.".into()), + }; + let (kind, base_name) = match a { + NewAction::Stretch { .. } => ("BLOCKSTRETCHACTION", "Stretch"), + NewAction::Move { .. } => ("BLOCKMOVEACTION", "Move"), + }; + let action_name = unique_name(d, name, base_name); + let g = graph(d, name)?; + let node = next_node(d, name); + let mut t = head(node, &action_name); + t.extend([tag(100, "AcDbBlockAction"), tag(70, "0"), tag(71, objects.len().to_string())]); + t.extend(objects.iter().map(|h| tag(330, h.hex()))); + point(&mut t, 1010, at); + match a { + NewAction::Stretch { frame, .. } => { + let frame: Vec = frame.iter().copied().filter(|q| q.x.is_finite() && q.y.is_finite()).take(4096).collect(); + if frame.len() < 2 { + return Err("A stretch action needs a frame: two corners or a polygon.".into()); + } + t.extend([ + tag(100, "AcDbBlockStretchAction"), + tag(92, param.to_string()), + tag(301, connections[0]), + tag(93, param.to_string()), + tag(302, connections[1]), + ]); + t.push(tag(72, frame.len().to_string())); + for q in &frame { + t.extend([tag(1011, real(q.x)), tag(1021, real(q.y))]); + } + t.extend([tag(73, "0"), tag(75, "0"), tag(140, "1"), tag(141, "0")]); + } + NewAction::Move { .. } => { + t.extend([ + tag(100, "AcDbBlockMoveAction"), + tag(92, param.to_string()), + tag(301, connections[0]), + tag(93, param.to_string()), + tag(302, connections[1]), + ]); + t.extend([tag(140, "1"), tag(141, "0")]); + } + } + let handle = add_member(d, g, kind, t); + Ok(Added { node, handle, name: action_name }) +} + +/// Remove parameter or action `node` from block `name` (with a parameter's grips and the actions +/// that follow it). +pub fn remove(d: &mut Drawing, name: &str, node: i32) -> Result, String> { + let m = dynamic_block(d, name).ok_or("The block has no parameters or actions.")?; + let mut gone: Vec<(Handle, String)> = Vec::new(); + if let Some(p) = m.parameters.iter().find(|p| p.node == node) { + gone.push((p.handle, p.kind.label().unwrap_or(&p.element).to_string())); + gone.extend(m.grip_objects.iter().filter(|(id, _)| p.grips.contains(id)).map(|(_, h)| (*h, String::new()))); + gone.extend(m.actions.iter().filter(|a| a.connections.iter().any(|(n, _)| *n == node)).map(|a| (a.handle, a.name.clone()))); + } else if let Some(a) = m.actions.iter().find(|a| a.node == node) { + gone.push((a.handle, a.name.clone())); + } else { + return Err("No such parameter or action.".into()); + } + let hs: std::collections::HashSet = gone.iter().map(|g| g.0).collect(); + Arc::make_mut(&mut d.foreign).objects.retain(|o| !hs.contains(&o.handle)); + let hexes: std::collections::HashSet = hs.iter().map(|h| h.hex()).collect(); + for o in Arc::make_mut(&mut d.foreign).objects.iter_mut().filter(|o| o.kind.eq_ignore_ascii_case("ACAD_EVALUATION_GRAPH")) { + o.tags.retain(|t| !(t.code == 360 && Handle::parse_hex(&t.value).is_some_and(|h| hexes.contains(&h.hex())))); + } + Ok(gone.into_iter().map(|g| g.1).filter(|n| !n.is_empty()).collect()) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{Block, EntityKind, Insert}; + + /// A drawing with block "B" (a 10 × 5 rectangle's four lines) and a reference to it. + fn drawing() -> (Drawing, Vec, Handle) { + let mut d = Drawing::new_metric(); + let mut b = Block::new("B"); + let pts = [Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 5.0), Vec2::new(0.0, 5.0)]; + let mut hs = Vec::new(); + for i in 0..4 { + let h = d.new_handle(); + let (a, c) = (pts[i], pts[(i + 1) % 4]); + let line = crate::Line { a: a.to3(0.0), b: c.to3(0.0) }; + b.entities.push(crate::Entity::new(h, EntityKind::Line(line))); + hs.push(h); + } + d.blocks.insert("B".into(), Arc::new(b)); + let ins = d.new_handle(); + d.model.push(crate::Entity::new(ins, EntityKind::Insert(Insert { block: "B".into(), ..Insert::default() }))); + (d, hs, ins) + } + + #[test] + fn a_linear_parameter_with_a_stretch_makes_a_working_dynamic_block() { + let (mut d, hs, ins) = drawing(); + let p = NewParameter::Linear { + base: Vec2::new(0.0, 0.0), + end: Vec2::new(10.0, 0.0), + label: String::new(), + description: "Width".into(), + values: ValueSet::default(), + from_midpoint: false, + }; + let added = add_parameter(&mut d, "B", &p).unwrap(); + assert_eq!(added.name, "Distance1"); + let frame = vec![Vec2::new(8.0, -1.0), Vec2::new(12.0, 6.0)]; + let act = add_action(&mut d, "B", &NewAction::Stretch { parameter: added.node, frame, objects: hs.clone() }).unwrap(); + assert_eq!(act.name, "Stretch1"); + let m = dynamic_block(&d, "B").expect("the block is dynamic"); + assert_eq!((m.parameters.len(), m.actions.len()), (1, 1)); + assert_eq!(m.parameters[0].grips.len(), 2); + assert_eq!(m.actions[0].selection, hs); + // The reference has a Distance1 property and grips; setting it stretches the right side. + let (_, props) = super::super::custom_properties(&d, ins).expect("custom properties"); + assert!(props.iter().any(|p| p.name == "Distance1"), "{props:?}"); + assert!(!super::super::grips(&d, ins).is_empty()); + super::super::set_property(&mut d, ins, "Distance1", "16").unwrap(); + let EntityKind::Insert(i) = &d.entity(ins).unwrap().kind else { panic!("insert") }; + let shown = d.block(&i.block).unwrap(); + let xs: Vec = + shown.entities.iter().filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.a.x.max(l.b.x)) } else { None }).collect(); + assert!(xs.iter().any(|x| (x - 16.0).abs() < 1e-9), "{xs:?}"); + } + + #[test] + fn a_point_parameter_with_a_move_and_removing_them() { + let (mut d, hs, _) = drawing(); + let p = + add_parameter(&mut d, "B", &NewParameter::Point { at: Vec2::new(5.0, 5.0), label: "Top".into(), description: String::new() }).unwrap(); + let mv = add_action(&mut d, "B", &NewAction::Move { parameter: p.node, objects: vec![hs[2]] }).unwrap(); + assert_eq!(mv.name, "Move1"); + // Same label twice, no objects, unknown parameter. + assert!(add_parameter(&mut d, "B", &NewParameter::Point { at: Vec2::ZERO, label: "top".into(), description: String::new() }).is_err()); + assert!(add_action(&mut d, "B", &NewAction::Move { parameter: p.node, objects: vec![Handle(0xFFFFF)] }).is_err()); + assert!(add_action(&mut d, "B", &NewAction::Move { parameter: 999, objects: hs.clone() }).is_err()); + let gone = remove(&mut d, "B", p.node).unwrap(); + assert_eq!(gone, ["Top", "Move1"]); + let m = dynamic_block(&d, "B").unwrap(); + assert!(m.parameters.is_empty() && m.actions.is_empty() && m.grip_objects.is_empty()); + assert!(add_parameter(&mut d, "NOPE", &NewParameter::Point { at: Vec2::ZERO, label: String::new(), description: String::new() }).is_err()); + } +} diff --git a/crates/doc/src/entity.rs b/crates/doc/src/entity.rs index 6f239b06..25feacc0 100644 --- a/crates/doc/src/entity.rs +++ b/crates/doc/src/entity.rs @@ -51,7 +51,7 @@ pub use common::{Common, Handle, Lineweight, RawTag, Transparency}; pub use curves::{Arc, Circle, Ellipse, Face3d, Line, LwPolyline, Point, PolyfaceMesh, Polyline3d, RayLine, Solid}; pub use dim::{AssocSnap, DimAssoc, DimBreak, DimKind, DimMarks, Dimension, Inspection, JoggedRadius, Leader, MLeader}; pub use fill::{Gradient, Hatch, HatchLoop}; -pub use layout::{Image, Table, TableCell, Viewport}; +pub use layout::{Image, POINTS_PER_INCH, Table, TableCell, Underlay, UnderlayKind, Viewport}; pub use text::{HAlign, MText, MTextColumnType, MTextColumns, Text, VAlign}; pub use wipeout::Wipeout; #[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] @@ -144,6 +144,7 @@ impl EntityKind { EntityKind::PolyfaceMesh(_) => "Polyface Mesh", EntityKind::Region(_) => "Region", EntityKind::Viewport(_) => "Viewport", + EntityKind::Image(i) if i.underlay.is_some() => "PDF Underlay", EntityKind::Image(_) => "Raster Image", EntityKind::Wipeout(_) => "Wipeout", EntityKind::Table(_) => "Table", @@ -180,6 +181,7 @@ impl EntityKind { EntityKind::PolyfaceMesh(_) => "POLYLINE", EntityKind::Region(_) => "REGION", EntityKind::Viewport(_) => "VIEWPORT", + EntityKind::Image(i) if i.underlay.is_some() => "PDFUNDERLAY", EntityKind::Image(_) => "IMAGE", EntityKind::Wipeout(_) => "WIPEOUT", EntityKind::Table(_) => "ACAD_TABLE", diff --git a/crates/doc/src/entity/layout.rs b/crates/doc/src/entity/layout.rs index 5b3e0c6b..668987d1 100644 --- a/crates/doc/src/entity/layout.rs +++ b/crates/doc/src/entity/layout.rs @@ -119,6 +119,83 @@ pub struct Image { pub pixel_size: Vec2, #[serde(default)] pub resolution_units: u8, + /// Set when this is an underlay (a page of a PDF file, PDFUNDERLAY) instead of a raster image. + /// An underlay's "pixels" are the page's PDF points (1/72 inch): `size` is the page in points + /// and `u`/`v` one point in drawing units, so the page draws at any resolution it is rendered at. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub underlay: Option, +} + +/// The file type of an underlay. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub enum UnderlayKind { + #[default] + Pdf, +} + +impl UnderlayKind { + /// The DXF type of the reference entity and of its definition object. + pub fn dxf_names(self) -> (&'static str, &'static str) { + match self { + UnderlayKind::Pdf => ("PDFUNDERLAY", "PDFDEFINITION"), + } + } +} + +/// What makes an [`Image`] an underlay: the file type and the page shown. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Underlay { + pub kind: UnderlayKind, + /// The page: its number, counted from 1, as text (the definition's group 2). + pub page: String, + /// Shown in one colour (the reference's flag 4). + #[serde(default)] + pub monochrome: bool, + /// Colours adjusted for the background (the reference's flag 8). + #[serde(default)] + pub adjust_for_background: bool, + /// The clip boundary as the file has it (inches from the insertion point, y up, before scale + /// and rotation), written back as read. [`Image::clip`] shows it once the page size is known. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub clip: Vec, +} + +impl Underlay { + /// The contrast and fade (percent) a new underlay starts with. + pub const DEFAULT_CONTRAST: u8 = 20; + pub const DEFAULT_FADE: u8 = 25; + + /// The page index counted from 0, when the page names a number. + pub fn page_index(&self) -> Option { + self.page.trim().parse::().ok().and_then(|n| n.checked_sub(1)) + } +} + +/// PDF points per inch: an underlay's page is measured in points, its reference scale in drawing +/// units per inch. +pub const POINTS_PER_INCH: f64 = 72.0; + +impl Image { + /// An underlay's clip boundary ([`Underlay::clip`]) as image pixel coordinates (points from + /// the top-left pixel centre, y down), once the page size is known; empty otherwise. + pub fn underlay_display_clip(&self) -> Vec { + let Some(u) = &self.underlay else { return Vec::new() }; + if u.clip.len() < 2 || self.size.y <= 0.0 { + return Vec::new(); + } + u.clip.iter().map(|q| Vec2::new(q.x * POINTS_PER_INCH - 0.5, self.size.y - q.y * POINTS_PER_INCH - 0.5)).collect() + } + + /// The key of this image's pixels in [`crate::Drawing::rasters`]: the file, and for an + /// underlay the page too. + pub fn raster_key(&self) -> String { + match &self.underlay { + Some(u) => format!("{}#page={}", self.path, u.page.trim()), + None => self.path.clone(), + } + } } fn image_display() -> u16 { @@ -150,6 +227,7 @@ impl Default for Image { fade: 0, pixel_size: image_pixel(), resolution_units: 0, + underlay: None, } } } diff --git a/crates/doc/src/lib.rs b/crates/doc/src/lib.rs index 5cc559be..dd8580a0 100644 --- a/crates/doc/src/lib.rs +++ b/crates/doc/src/lib.rs @@ -35,7 +35,7 @@ pub use gdt::*; pub use header::{HVal, Header}; pub use plotstyle::*; pub use plotter::*; -pub use raster::{Raster, Rasters}; +pub use raster::{ImportedShape, Raster, Rasters, ShapeClass}; pub use refedit::{RefEdit, WorkItem}; pub use store::EntityStore; pub use tables::*; diff --git a/crates/doc/src/raster.rs b/crates/doc/src/raster.rs index 1eb72199..d2c39332 100644 --- a/crates/doc/src/raster.rs +++ b/crates/doc/src/raster.rs @@ -91,3 +91,26 @@ impl std::fmt::Debug for Rasters { write!(f, "Rasters({})", self.0.len()) } } + +/// An object an importer (PDFIMPORT) read from another file format, before it is placed: its +/// geometry in the source's own units, and what it looked like there. +#[derive(Clone, Debug, PartialEq)] +pub struct ImportedShape { + pub kind: crate::EntityKind, + /// Its colour in the source; `None` when it had none of its own (a pattern, a shading). + pub color: Option, + /// Its stroke width in the source's units (0 for fills and text). + pub width: f64, + pub class: ShapeClass, +} + +/// What an [`ImportedShape`] was in the source. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ShapeClass { + /// A stroked line or curve. + Vector, + /// A filled area. + Fill, + /// Text. + Text, +} diff --git a/crates/engine/Cargo.toml b/crates/engine/Cargo.toml index 579c5b23..c0720d2a 100644 --- a/crates/engine/Cargo.toml +++ b/crates/engine/Cargo.toml @@ -27,6 +27,10 @@ rstar = { version = "0.13", default-features = false } [target.'cfg(unix)'.dependencies] libc = "0.2" +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +# ETRANSMIT's .zip packages; the same version and features the UI's updater uses. +zip = { version = "9", default-features = false, features = ["deflate"] } + [dev-dependencies] # Real DXF files for the external reference tests (io is a lower layer). draftcraft-io = { workspace = true } diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 01808c1f..6a7e16b9 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -14,11 +14,13 @@ mod draworder; mod edit; mod exchange; pub mod file; +mod geo; mod gripcmds; mod griphot; pub(crate) mod groups; pub(crate) mod hatch; mod image; +mod imageops; mod inquiry; mod layer; mod layout; @@ -27,6 +29,8 @@ mod merge; mod mleader_content; mod mleader_edit; mod modify; +mod pointcloud; +pub mod underlay; pub(crate) use modify::Erased; mod modify2; mod mtext_opts; @@ -41,6 +45,7 @@ pub(crate) use props::{current_color_value, set_current_color_value}; mod qselect; mod selecttools; mod settings; +pub mod sheetset; mod spline_opts; mod table; mod tolerance; @@ -202,6 +207,12 @@ pub fn command_specs() -> &'static [CommandSpec] { v.extend(layout::specs()); v.extend(exchange::specs()); v.extend(image::specs()); + v.extend(underlay::specs()); + v.extend(imageops::specs()); + v.extend(sheetset::specs()); + v.extend(file::transmit::specs()); + v.extend(geo::specs()); + v.extend(pointcloud::specs()); v.extend(props::specs()); v.extend(inquiry::specs()); v.extend(settings::specs()); diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 644e0f95..aec1ab63 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -1,7 +1,9 @@ //! Blocks: BLOCK, INSERT, ATTDEF, ATTEDIT (programmatic), WBLOCK, BASE, PURGE, block listing, the //! Block Editor. +mod bauthor; pub(crate) mod bedit; +pub mod designcenter; pub(in crate::cmd) mod purge; use std::sync::Arc; @@ -95,6 +97,8 @@ pub fn specs() -> Vec { .chain(refedit::specs()) .chain(xclip::specs()) .chain(bedit::specs()) + .chain(bauthor::specs()) + .chain([designcenter::spec()]) .collect() } @@ -600,7 +604,7 @@ impl BlockM { } } -mod insert_file; +pub(crate) mod insert_file; pub(crate) mod xref; /// Where the command-line INSERT is in its prompt sequence. diff --git a/crates/engine/src/cmd/blocks/bauthor.rs b/crates/engine/src/cmd/blocks/bauthor.rs new file mode 100644 index 00000000..1a12630e --- /dev/null +++ b/crates/engine/src/cmd/blocks/bauthor.rs @@ -0,0 +1,482 @@ +//! BPARAMETER and BACTION: make the block open in the Block Editor dynamic. A parameter is a +//! property a reference to the block can change (a distance, a position); an action says what a +//! change does to the block's objects (stretch them, move them). BSAVE saves them with the block; +//! its references then get grips and custom properties that drive the actions. The objects are +//! made by [`draftcraft_doc::dynblock::author`]. +//! +//! Points are given in the Block Editor's coordinates, where the block's base point is the origin. + +use draftcraft_doc::dynblock::author::{self, NewAction, NewParameter}; +use draftcraft_doc::dynblock::{ParameterKind, ValueSet, dynamic_block}; +use draftcraft_doc::{Drawing, Handle}; +use draftcraft_geom::Vec2; +use serde_json::{Value, json}; + +use crate::blockedit::CURRENT_DRAWING; +use crate::cmd::machines::{SelOutcome, SelectPhase, number}; +use crate::cmd::{CommandSpec, bad, bool_or, point_value, str_param, targets}; +use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; + +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("bparameter", "Parameter", run_bparameter) + .alias(&["bparam"]) + .params( + "{type?: linear|point (none: list the block's parameters and actions), base?: [x,y], end?: [x,y] (linear), at?: [x,y] \ + (point), label? (default Distance1, Position1…), description?, min?, max?, increment?, list?: [numbers] (a linear \ + parameter's allowed values), fromMidpoint?: bool, remove?: label or graph id (removes a parameter with its actions, or an \ + action)} → {block, node, handle, label} (list: {block, parameters: [{node, label, type}], actions: [{node, name, type, \ + parameter}]})", + ) + .enabled(editing_a_block) + .interactive(|_| Ok(Box::new(ParamM::default()))), + CommandSpec::new("baction", "Action", run_baction) + .alias(&["bac"]) + .params( + "{type: stretch|move, parameter: label or graph id, handles? (the block's objects it changes; default the selection), \ + frame?: [[x,y],[x,y]] or polygon (stretch: the points inside it move)} → {block, node, handle, name}", + ) + .enabled(editing_a_block) + .interactive(|_| Ok(Box::new(ActionM::default()))), + ] +} + +/// The Block Editor is open on a block (parameters belong to a block, not to the drawing itself). +fn editing_a_block(s: &Session) -> std::result::Result<(), String> { + match s.state() { + Ok(st) => match st.block_editor() { + Some(n) if n.eq_ignore_ascii_case(CURRENT_DRAWING) => { + Err("Parameters and actions belong to a block: open one in the Block Editor.".into()) + } + Some(_) => Ok(()), + None => Err("The Block Editor is not open.".into()), + }, + Err(e) => Err(e.to_string()), + } +} + +/// The block being edited and its base point (the editor's origin). +fn block(s: &Session, id: &str) -> Result<(String, Vec2)> { + editing_a_block(s).map_err(|e| bad(id, e))?; + let st = s.state()?; + let name = st.block_editor().unwrap_or_default().to_string(); + let base = st.doc.block(&name).map(|b| b.base.xy()).unwrap_or_default(); + Ok((name, base)) +} + +/// A block the Block Editor started and never saved has no definition yet: give the editor's +/// drawing an empty one to hang the parameters on (BSAVE fills it). +fn ensure_block(s: &mut Session, name: &str) -> Result<()> { + if s.doc()?.block(name).is_none() { + let d = s.doc_mut()?; + d.blocks.insert(name.to_string(), std::sync::Arc::new(draftcraft_doc::Block::new(name))); + } + Ok(()) +} + +fn type_name(k: &ParameterKind) -> &'static str { + match k { + ParameterKind::Linear { .. } => "linear", + ParameterKind::Polar { .. } => "polar", + ParameterKind::Xy { .. } => "xy", + ParameterKind::Rotation { .. } => "rotation", + ParameterKind::Alignment { .. } => "alignment", + ParameterKind::Flip { .. } => "flip", + ParameterKind::Point { .. } => "point", + ParameterKind::Visibility { .. } => "visibility", + ParameterKind::Lookup { .. } => "lookup", + ParameterKind::BasePoint { .. } => "basepoint", + ParameterKind::Other { .. } => "other", + } +} + +/// The parameter a JSON value names: its label (any case) or its graph id. +fn parameter_node(d: &Drawing, name: &str, v: &Value) -> Option { + let m = dynamic_block(d, name)?; + if let Some(n) = v.as_i64().and_then(|n| i32::try_from(n).ok()) { + return m + .parameters + .iter() + .chain([]) + .find(|p| p.node == n) + .map(|p| p.node) + .or_else(|| m.actions.iter().find(|a| a.node == n).map(|a| a.node)); + } + let t = v.as_str()?.trim(); + m.parameters + .iter() + .find(|p| p.kind.label().is_some_and(|l| l.eq_ignore_ascii_case(t))) + .map(|p| p.node) + .or_else(|| m.actions.iter().find(|a| a.name.eq_ignore_ascii_case(t)).map(|a| a.node)) +} + +fn list(d: &Drawing, name: &str) -> Value { + let m = dynamic_block(d, name).unwrap_or_default(); + let label = |n: i32| m.parameters.iter().find(|p| p.node == n).and_then(|p| p.kind.label()).unwrap_or_default().to_string(); + json!({ + "block": name, + "parameters": m.parameters.iter().map(|p| json!({ "node": p.node, "label": p.kind.label().unwrap_or(&p.element), "type": type_name(&p.kind) })).collect::>(), + "actions": m.actions.iter().map(|a| json!({ + "node": a.node, + "name": a.name, + "type": format!("{:?}", a.kind).split([' ', '{']).next().unwrap_or("").to_ascii_lowercase(), + "parameter": a.connections.first().map(|(n, _)| label(*n)), + })).collect::>(), + }) +} + +fn num(p: &Value, key: &str) -> Option { + p.get(key).and_then(Value::as_f64).filter(|v| v.is_finite()) +} + +fn run_bparameter(s: &mut Session, p: &Value) -> Result { + const ID: &str = "bparameter"; + let (name, base) = block(s, ID)?; + if let Some(r) = p.get("remove") { + let node = parameter_node(s.doc()?, &name, r).ok_or_else(|| bad(ID, "no such parameter or action"))?; + let gone = author::remove(s.doc_mut()?, &name, node).map_err(|e| bad(ID, e))?; + return Ok(json!({ "block": name, "removed": gone })); + } + let Some(kind) = str_param(p, "type").map(str::to_ascii_lowercase) else { return Ok(list(s.doc()?, &name)) }; + let pt = |key: &str| -> Result { + p.get(key).and_then(point_value).map(|q| q + base).ok_or_else(|| bad(ID, format!("`{key}` must be a point [x, y]"))) + }; + let label = str_param(p, "label").unwrap_or_default().to_string(); + let description = str_param(p, "description").unwrap_or_default().to_string(); + let new = match kind.as_str() { + "linear" | "l" => { + let mut values = ValueSet::default(); + if let Some(v) = num(p, "min") { + values.flags |= 1; + values.minimum = v; + } + if let Some(v) = num(p, "max") { + values.flags |= 2; + values.maximum = v; + } + if let Some(v) = num(p, "increment").filter(|v| *v > 0.0) { + values.flags |= 4; + values.increment = v; + } + if let Some(l) = p.get("list").and_then(Value::as_array) { + values.list = l.iter().filter_map(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0).take(author::MAX_SELECTION).collect(); + if !values.list.is_empty() { + values.flags |= 8; + } + } + if values.has_minimum() && values.has_maximum() && values.minimum > values.maximum { + return Err(bad(ID, "`min` is more than `max`")); + } + NewParameter::Linear { base: pt("base")?, end: pt("end")?, label, description, values, from_midpoint: bool_or(p, "fromMidpoint", false) } + } + "point" | "p" => NewParameter::Point { at: pt("at")?, label, description }, + other => return Err(bad(ID, format!("\"{other}\" parameters can't be made yet (linear or point)"))), + }; + ensure_block(s, &name)?; + let added = author::add_parameter(s.doc_mut()?, &name, &new).map_err(|e| bad(ID, e))?; + Ok(json!({ "block": name, "node": added.node, "handle": added.handle.hex(), "label": added.name })) +} + +fn run_baction(s: &mut Session, p: &Value) -> Result { + const ID: &str = "baction"; + let (name, base) = block(s, ID)?; + let kind = str_param(p, "type").map(str::to_ascii_lowercase).ok_or_else(|| bad(ID, "`type` is required: stretch or move"))?; + let param = p.get("parameter").ok_or_else(|| bad(ID, "`parameter` is required: a parameter's label"))?; + let node = parameter_node(s.doc()?, &name, param).ok_or_else(|| bad(ID, "no such parameter in this block"))?; + let objects: Vec = targets(s, p)?; + let new = match kind.as_str() { + "stretch" | "s" => { + let frame: Vec = + p.get("frame").and_then(Value::as_array).map(|a| a.iter().filter_map(point_value).map(|q| q + base).collect()).unwrap_or_default(); + if frame.len() < 2 { + return Err(bad(ID, "a stretch action needs `frame`: two corners or a polygon")); + } + NewAction::Stretch { parameter: node, frame, objects } + } + "move" | "m" => NewAction::Move { parameter: node, objects }, + other => return Err(bad(ID, format!("\"{other}\" actions can't be made yet (stretch or move)"))), + }; + let added = author::add_action(s.doc_mut()?, &name, &new).map_err(|e| bad(ID, e))?; + Ok(json!({ "block": name, "node": added.node, "handle": added.handle.hex(), "name": added.name })) +} + +fn kw(i: &Input) -> Option { + match i { + Input::Keyword(k) | Input::Text(k) => Some(k.trim().to_ascii_lowercase()), + _ => None, + } +} + +/// Run `f` and report an error at the command line instead of stopping with it. +fn finish(s: &mut Session, r: Result) -> Result { + match r { + Ok(v) => { + if let Some(l) = v.get("label").or_else(|| v.get("name")).and_then(Value::as_str) { + s.echo(format!("{l} added.")); + } + } + Err(e) => s.echo(e.to_string()), + } + Ok(Step::Done) +} + +// ---------------- BPARAMETER prompts ---------------- + +#[derive(Default)] +struct ParamM { + kind: Option<&'static str>, + pts: Vec, +} + +impl Interactive for ParamM { + fn name(&self) -> &'static str { + "BPARAMETER" + } + fn begin(&mut self, _s: &mut Session) -> Result { + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + match (self.kind, self.pts.len()) { + (None, _) => Prompt::new("Enter parameter type", Accept::TEXT).kw(&["Linear", "Point"]).default("Linear"), + (Some("linear"), 0) => Prompt::new("Specify start point", Accept::POINT), + (Some("linear"), _) => Prompt::new("Specify endpoint", Accept::POINT).base_opt(self.pts.first().copied()), + (Some(_), _) => Prompt::new("Specify parameter location", Accept::POINT), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + let Some(kind) = self.kind else { + let k = if matches!(i, Input::Enter) { Some("linear".to_string()) } else { kw(&i) }; + self.kind = match k.as_deref() { + Some(k) if k.starts_with('l') => Some("linear"), + Some(k) if k.starts_with('p') => Some("point"), + _ => { + s.echo("Invalid option keyword."); + None + } + }; + return Ok(Step::Continue); + }; + let Input::Point(q) = i else { return Ok(Step::Continue) }; + self.pts.push(q); + match (kind, self.pts.as_slice()) { + ("linear", [a, b]) => { + let r = run_bparameter(s, &json!({ "type": "linear", "base": [a.x, a.y], "end": [b.x, b.y] })); + finish(s, r) + } + ("point", [a]) => { + let r = run_bparameter(s, &json!({ "type": "point", "at": [a.x, a.y] })); + finish(s, r) + } + _ => Ok(Step::Continue), + } + } +} + +// ---------------- BACTION prompts ---------------- + +#[derive(Default, Clone, Copy, PartialEq, Eq)] +enum ActStage { + #[default] + Kind, + Parameter, + Corner1, + Corner2, + Select, +} + +#[derive(Default)] +struct ActionM { + stage: ActStage, + kind: &'static str, + parameter: String, + frame: Vec, + sel: SelectPhase, +} + +impl ActionM { + fn run(&self, s: &mut Session, hs: &[Handle]) -> Result { + let mut p = json!({ "type": self.kind, "parameter": self.parameter, "handles": hs.iter().map(|h| h.hex()).collect::>() }); + if self.kind == "stretch" { + p["frame"] = json!(self.frame.iter().map(|q| [q.x, q.y]).collect::>()); + } + let r = run_baction(s, &p); + s.set_selection(Vec::new()); + finish(s, r) + } +} + +impl Interactive for ActionM { + fn name(&self) -> &'static str { + "BACTION" + } + fn begin(&mut self, s: &mut Session) -> Result { + let (name, _) = block(s, "baction")?; + if dynamic_block(s.doc()?, &name).is_none_or(|m| m.parameters.is_empty()) { + s.echo("Add a parameter first (BPARAMETER): an action follows a parameter."); + return Ok(Step::Done); + } + Ok(Step::Continue) + } + fn prompt(&self, s: &Session) -> Prompt { + match self.stage { + ActStage::Kind => Prompt::new("Enter action type", Accept::TEXT).kw(&["Stretch", "Move"]).default("Stretch"), + ActStage::Parameter => { + let first = s + .state() + .ok() + .and_then(|st| dynamic_block(&st.doc, st.block_editor()?)) + .and_then(|m| m.parameters.iter().find_map(|p| p.kind.label().map(str::to_string))) + .unwrap_or_default(); + Prompt::new("Enter the parameter the action follows", Accept::TEXT).default(&first) + } + ActStage::Corner1 => Prompt::new("Specify first corner of stretch frame", Accept::POINT), + ActStage::Corner2 => { + let p = Prompt::new("Specify opposite corner", Accept::POINT); + match self.frame.first() { + Some(a) => p.corner(*a), + None => p, + } + } + ActStage::Select => self.sel.prompt(), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + match self.stage { + ActStage::Kind => { + let k = if matches!(i, Input::Enter) { Some("stretch".to_string()) } else { kw(&i) }; + match k.as_deref() { + Some(k) if k.starts_with('s') => self.kind = "stretch", + Some(k) if k.starts_with('m') => self.kind = "move", + _ => { + s.echo("Invalid option keyword."); + return Ok(Step::Continue); + } + } + self.stage = ActStage::Parameter; + Ok(Step::Continue) + } + ActStage::Parameter => { + let typed = match &i { + Input::Enter => self.prompt(s).default.unwrap_or_default().to_ascii_lowercase(), + other => kw(other).unwrap_or_default(), + }; + let (name, _) = block(s, "baction")?; + let found = parameter_node(s.doc()?, &name, &json!(typed)) + .or_else(|| number(&typed).and_then(|n| parameter_node(s.doc().ok()?, &name, &json!(n as i64)))); + if found.is_none() { + s.echo(format!("No parameter \"{typed}\" in this block.")); + return Ok(Step::Continue); + } + self.parameter = typed; + self.stage = if self.kind == "stretch" { ActStage::Corner1 } else { ActStage::Select }; + if self.stage == ActStage::Select { + self.sel = SelectPhase::default(); + } + Ok(Step::Continue) + } + ActStage::Corner1 => { + if let Input::Point(q) = i { + self.frame = vec![q]; + self.stage = ActStage::Corner2; + } + Ok(Step::Continue) + } + ActStage::Corner2 => { + if let Input::Point(q) = i { + self.frame.push(q); + self.sel = SelectPhase::default(); + self.stage = ActStage::Select; + } + Ok(Step::Continue) + } + ActStage::Select => match self.sel.feed(s, &i)? { + SelOutcome::More => Ok(Step::Continue), + SelOutcome::Empty => Ok(Step::Done), + SelOutcome::Done(hs) => self.run(s, &hs), + }, + } + } +} + +#[cfg(test)] +mod tests { + use draftcraft_doc::EntityKind; + use serde_json::json; + + use crate::Session; + + /// A 10 × 5 rectangle of lines made into block "PANEL", with a reference, open in the Block + /// Editor. + fn session() -> (Session, Vec) { + let mut s = Session::new(); + let mut hs = Vec::new(); + for (a, b) in [([0, 0], [10, 0]), ([10, 0], [10, 5]), ([10, 5], [0, 5]), ([0, 5], [0, 0])] { + let r = s.execute("line", &json!({ "points": [a, b] })).unwrap(); + hs.push(r["handles"][0].as_str().or_else(|| r["handle"].as_str()).unwrap().to_string()); + } + s.execute("block", &json!({ "name": "PANEL", "base": [0, 0], "handles": hs, "retain": false })).unwrap(); + s.execute("insert", &json!({ "name": "PANEL", "at": [100, 0] })).unwrap(); + s.execute("bedit", &json!({ "name": "PANEL" })).unwrap(); + let hs = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + (s, hs) + } + + #[test] + fn a_stretchable_block_made_in_the_block_editor() { + let (mut s, hs) = session(); + let p = s.execute("bparameter", &json!({ "type": "linear", "base": [0, 0], "end": [10, 0], "label": "Width", "min": 5, "max": 30 })).unwrap(); + assert_eq!(p["label"], "Width"); + let a = s.execute("baction", &json!({ "type": "stretch", "parameter": "width", "frame": [[8, -1], [12, 6]], "handles": hs })).unwrap(); + assert_eq!(a["name"], "Stretch1"); + let l = s.execute("bparameter", &json!({})).unwrap(); + assert_eq!(l["parameters"][0]["label"], "Width"); + assert_eq!(l["actions"][0]["parameter"], "Width"); + s.execute("bclose", &json!({ "save": true })).unwrap(); + // The reference now stretches with its Width property. + let ins = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Insert(_))).unwrap().handle; + let d = s.doc_mut().unwrap(); + draftcraft_doc::dynblock::set_property(d, ins, "Width", "20").unwrap(); + assert!(draftcraft_doc::dynblock::set_property(d, ins, "Width", "50").is_ok(), "clamped to the maximum"); + let EntityKind::Insert(i) = &d.entity(ins).unwrap().kind else { panic!("insert") }; + let xs: Vec = d + .block(&i.block) + .unwrap() + .entities + .iter() + .filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.a.x.max(l.b.x)) } else { None }) + .collect(); + assert!(xs.iter().any(|x| (x - 30.0).abs() < 1e-9), "{xs:?}"); + } + + #[test] + fn refused_outside_a_block_and_with_bad_input() { + let mut s = Session::new(); + assert!(s.execute("bparameter", &json!({ "type": "point", "at": [0, 0] })).is_err(), "no Block Editor"); + let (mut s, hs) = session(); + assert!(s.execute("bparameter", &json!({ "type": "rotation", "base": [0, 0], "end": [1, 0] })).is_err()); + assert!(s.execute("bparameter", &json!({ "type": "linear", "base": [0, 0], "end": [0, 0] })).is_err()); + assert!(s.execute("bparameter", &json!({ "type": "linear", "base": [0, 0], "end": [1, 0], "min": 9, "max": 2 })).is_err()); + assert!(s.execute("baction", &json!({ "type": "move", "parameter": "nope", "handles": hs })).is_err()); + s.execute("bparameter", &json!({ "type": "point", "at": [5, 5] })).unwrap(); + assert!(s.execute("baction", &json!({ "type": "stretch", "parameter": "Position1", "handles": hs })).is_err(), "no frame"); + let r = s.execute("bparameter", &json!({ "remove": "Position1" })).unwrap(); + assert_eq!(r["removed"], json!(["Position1"])); + } + + #[test] + fn bparameter_and_baction_at_the_command_line() { + let (mut s, _) = session(); + s.cmdline("bparameter l 0,0 10,0").unwrap(); + assert!(s.running.is_none()); + s.cmdline("baction s Distance1 8,-1 12,6 all").unwrap(); + s.input(crate::Input::Enter).unwrap(); + let l = s.execute("bparameter", &json!({})).unwrap(); + assert_eq!(l["actions"].as_array().map(Vec::len), Some(1), "{l}"); + } +} diff --git a/crates/engine/src/cmd/blocks/designcenter.rs b/crates/engine/src/cmd/blocks/designcenter.rs new file mode 100644 index 00000000..aa8900a2 --- /dev/null +++ b/crates/engine/src/cmd/blocks/designcenter.rs @@ -0,0 +1,260 @@ +//! ADCENTER (DesignCenter): look inside another drawing file and bring its blocks, layers, +//! linetypes and styles into this one. +//! +//! Called with only a path it lists what the file holds; with `kind` and `names` it copies those +//! definitions. A name this drawing already has keeps this drawing's definition, as when AutoCAD's +//! DesignCenter adds content. A copied block brings the blocks it references (to +//! [`MAX_BLOCK_DEPTH`] levels) and the layers and linetypes its objects use. The file is read +//! through the host's io hooks, like INSERT of a file. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +use draftcraft_doc::{Drawing, EntityKind, MAX_BLOCK_DEPTH}; +use serde_json::{Value, json}; + +use super::insert_file::{adopt, read_drawing}; +use crate::cmd::merge::merge_named; +use crate::cmd::{CommandSpec, bad, str_param}; +use crate::{Result, Session}; + +/// Most names one listing reports per kind, and one call copies. +const MAX_NAMES: usize = 10_000; + +/// The kinds of content DesignCenter shows for a drawing, as `kind` names them. +pub const KINDS: &[&str] = &["blocks", "layers", "linetypes", "textStyles", "dimStyles", "tableStyles", "mleaderStyles", "mlineStyles"]; + +pub(super) fn spec() -> CommandSpec { + CommandSpec::new("adcenter", "DesignCenter", run_adcenter).menu(&["Tools", "Palettes", "DesignCenter"]).alias(&["adc", "dc", "dcenter"]).params( + "{path: DXF/DWG file, kind?: blocks|layers|linetypes|textStyles|dimStyles|tableStyles|mleaderStyles|mlineStyles, \ + names?: [names] (copy these into the drawing; names it has keep its definitions)} → listing {path, blocks: [{name, \ + description, objects}], layers: [names], linetypes, textStyles, dimStyles, tableStyles, mleaderStyles, mlineStyles} | \ + copy {kind, added: [names], kept: [names]}", + ) +} + +fn run_adcenter(s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path").filter(|x| !x.trim().is_empty()).ok_or_else(|| bad("adcenter", "`path` names the drawing file to look in"))?; + let src = read_drawing(path)?; + let Some(kind) = str_param(p, "kind") else { + let mut out = listing(&src); + out["path"] = json!(path); + return Ok(out); + }; + let kind = KINDS + .iter() + .find(|k| k.eq_ignore_ascii_case(kind)) + .copied() + .ok_or_else(|| bad("adcenter", format!("unknown kind \"{kind}\" ({})", KINDS.join(", "))))?; + let names: Vec = match p.get("names") { + Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).take(MAX_NAMES).map(str::to_string).collect(), + Some(Value::String(one)) => vec![one.clone()], + _ => return Err(bad("adcenter", "`names` lists what to copy")), + }; + if names.is_empty() { + return Err(bad("adcenter", "`names` lists what to copy")); + } + let mut d = s.doc()?.clone(); + let (added, kept) = copy(&mut d, &src, kind, &names)?; + if !added.is_empty() { + *s.doc_mut()? = d; + } + let message = match (added.len(), kept.len()) { + (0, _) => format!("Nothing added: the drawing already has {}.", kept.join(", ")), + (n, 0) => format!("Added {n} item(s): {}.", added.join(", ")), + (n, _) => format!("Added {n} item(s): {}; kept the drawing's {}.", added.join(", "), kept.join(", ")), + }; + Ok(json!({ "kind": kind, "added": added, "kept": kept, "message": message })) +} + +/// What a drawing holds, by kind. Generated (`*…`) blocks, layout blocks and xrefs aren't listed. +fn listing(src: &Drawing) -> Value { + let blocks: Vec = src + .blocks + .values() + .filter(|b| !b.anonymous && !b.name.starts_with('*') && b.xref_path.is_none()) + .take(MAX_NAMES) + .map(|b| json!({ "name": b.name, "description": b.description, "objects": b.entities.len() })) + .collect(); + fn names(v: &[T], name: fn(&T) -> &str) -> Vec<&str> { + v.iter().take(MAX_NAMES).map(name).collect() + } + json!({ + "blocks": blocks, + "layers": names(&src.layers, |l| &l.name), + "linetypes": names(&src.linetypes, |l| &l.name), + "textStyles": names(&src.text_styles, |t| &t.name), + "dimStyles": names(&src.dim_styles, |t| &t.name), + "tableStyles": names(&src.table_styles, |t| &t.name), + "mleaderStyles": names(&src.mleader_styles, |t| &t.name), + "mlineStyles": names(&src.mline_styles, |t| &t.name), + }) +} + +/// Copy the named definitions of `kind` from `src` into `d`. Returns (added, kept) names; a name +/// `src` lacks is an error and nothing is copied. +fn copy(d: &mut Drawing, src: &Drawing, kind: &str, names: &[String]) -> Result<(Vec, Vec)> { + if kind == "blocks" { + return copy_blocks(d, src, names); + } + fn pick(ours: &mut Vec, theirs: &[T], names: &[String], name: fn(&T) -> &str) -> Result<(Vec, Vec)> { + let mut chosen = Vec::new(); + for n in names { + let t = theirs.iter().find(|t| name(t).eq_ignore_ascii_case(n)).ok_or_else(|| bad("adcenter", format!("the file has no \"{n}\"")))?; + chosen.push(t.clone()); + } + let (mut added, mut kept) = (Vec::new(), Vec::new()); + for t in &chosen { + if merge_named(ours, std::slice::from_ref(t), name) > 0 { added.push(name(t).to_string()) } else { kept.push(name(t).to_string()) } + } + Ok((added, kept)) + } + match kind { + "layers" => { + let r = pick(&mut d.layers, &src.layers, names, |l| &l.name)?; + // A copied layer brings its linetype. + let lts: Vec = r.0.iter().filter_map(|n| src.layers.iter().find(|l| &l.name == n)).map(|l| l.linetype.clone()).collect(); + add_linetypes(d, src, lts); + Ok(r) + } + "linetypes" => pick(&mut d.linetypes, &src.linetypes, names, |l| &l.name), + "textStyles" => pick(&mut d.text_styles, &src.text_styles, names, |t| &t.name), + "dimStyles" => pick(&mut d.dim_styles, &src.dim_styles, names, |t| &t.name), + "tableStyles" => pick(&mut d.table_styles, &src.table_styles, names, |t| &t.name), + "mleaderStyles" => pick(&mut d.mleader_styles, &src.mleader_styles, names, |t| &t.name), + "mlineStyles" => pick(&mut d.mline_styles, &src.mline_styles, names, |t| &t.name), + _ => Err(bad("adcenter", format!("unknown kind \"{kind}\""))), + } +} + +/// Add the linetypes of `src` named in `names` that `d` lacks. +fn add_linetypes(d: &mut Drawing, src: &Drawing, names: impl IntoIterator) { + let wanted: BTreeSet = names.into_iter().map(|n| n.to_ascii_uppercase()).collect(); + let theirs: Vec<_> = src.linetypes.iter().filter(|l| wanted.contains(&l.name.to_ascii_uppercase())).cloned().collect(); + merge_named(&mut d.linetypes, &theirs, |l| &l.name); +} + +/// Copy the named blocks, the blocks they reference and the layers and linetypes their objects +/// use. A block this drawing already has keeps its definition. +fn copy_blocks(d: &mut Drawing, src: &Drawing, names: &[String]) -> Result<(Vec, Vec)> { + let mut roots = Vec::new(); + for n in names { + let key = src.blocks.keys().find(|k| k.eq_ignore_ascii_case(n)).ok_or_else(|| bad("adcenter", format!("the file has no block \"{n}\"")))?; + roots.push(key.clone()); + } + // The blocks to bring: the named ones and what they reference, breadth first, to a bounded depth. + let mut needed: BTreeSet = BTreeSet::new(); + let mut level: Vec = roots.clone(); + for _ in 0..=MAX_BLOCK_DEPTH { + let mut next = Vec::new(); + for name in level { + if !needed.insert(name.clone()) { + continue; + } + let Some(b) = src.blocks.get(&name) else { continue }; + for e in b.entities.iter() { + let refd = match &e.kind { + EntityKind::Insert(i) => Some(&i.block), + EntityKind::Dimension(dm) => dm.block.as_ref(), + _ => None, + }; + if let Some(r) = refd.and_then(|r| src.blocks.keys().find(|k| k.eq_ignore_ascii_case(r))) { + next.push(r.clone()); + } + } + } + if next.is_empty() { + break; + } + level = next; + } + let renames: BTreeMap = + crate::cmd::merge::block_renames(d, src, None).into_iter().filter(|(from, _)| needed.contains(from)).collect(); + let (mut layers, mut linetypes) = (BTreeSet::new(), BTreeSet::new()); + for (from, to) in &renames { + let Some(b) = src.blocks.get(from) else { continue }; + let mut nb = (**b).clone(); + nb.name = to.clone(); + nb.entities = Default::default(); + for e in b.entities.iter() { + layers.insert(e.common.layer.to_ascii_uppercase()); + linetypes.insert(e.common.linetype.clone()); + nb.entities.push(adopt(d, src, e, &renames)); + } + d.blocks.insert(to.clone(), Arc::new(nb)); + } + let new_layers: Vec<_> = src.layers.iter().filter(|l| layers.contains(&l.name.to_ascii_uppercase())).cloned().collect(); + linetypes.extend(new_layers.iter().map(|l| l.linetype.clone())); + merge_named(&mut d.layers, &new_layers, |l| &l.name); + add_linetypes(d, src, linetypes); + let (mut added, mut kept) = (Vec::new(), Vec::new()); + for r in roots { + if renames.contains_key(&r) { added.push(r) } else { kept.push(r) } + } + Ok((added, kept)) +} + +#[cfg(test)] +mod tests { + use super::*; + use draftcraft_doc::{Block, Circle, Entity, Handle, Insert, Layer}; + use draftcraft_geom::Vec3; + + fn source() -> Drawing { + let mut d = Drawing::new_metric(); + let mut parts = Layer::new("PARTS"); + parts.linetype = "DASHED".into(); + d.layers.push(parts); + d.linetypes.push(draftcraft_doc::Linetype::simple("DASHED", "", &[0.5, -0.25])); + let mut nut = Block::new("NUT"); + let mut c = Entity::new(Handle(0x50), EntityKind::Circle(Circle { center: Vec3::ZERO, radius: 1.0 })); + c.common.layer = "PARTS".into(); + nut.entities.push(c); + d.blocks.insert("NUT".into(), Arc::new(nut)); + let mut bolt = Block::new("BOLT"); + let ins = Insert { + block: "NUT".into(), + insert: Vec3::ZERO, + scale: Vec3::new(1.0, 1.0, 1.0), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + }; + bolt.entities.push(Entity::new(Handle(0x51), EntityKind::Insert(ins))); + d.blocks.insert("BOLT".into(), Arc::new(bolt)); + d + } + + #[test] + fn a_block_brings_what_it_references() { + let src = source(); + let mut d = Drawing::new_metric(); + let (added, kept) = copy(&mut d, &src, "blocks", &["bolt".into()]).unwrap(); + assert_eq!((added, kept), (vec!["BOLT".to_string()], vec![])); + assert!(d.block("NUT").is_some(), "the nested block comes along"); + assert!(d.layers.iter().any(|l| l.name == "PARTS"), "the layer its objects use"); + assert!(d.linetypes.iter().any(|l| l.name == "DASHED"), "and that layer's linetype"); + // A second copy keeps the drawing's definitions. + let (added, kept) = copy(&mut d, &src, "blocks", &["BOLT".into()]).unwrap(); + assert!(added.is_empty()); + assert_eq!(kept, vec!["BOLT".to_string()]); + } + + #[test] + fn listing_and_missing_names() { + let src = source(); + let l = listing(&src); + let blocks: Vec<&str> = l["blocks"].as_array().unwrap().iter().filter_map(|b| b["name"].as_str()).collect(); + assert!(blocks.contains(&"BOLT") && blocks.contains(&"NUT")); + assert!(l["layers"].as_array().unwrap().iter().any(|n| n == "PARTS")); + let mut d = Drawing::new_metric(); + assert!(copy(&mut d, &src, "layers", &["NOPE".into()]).is_err()); + let (added, _) = copy(&mut d, &src, "layers", &["parts".into()]).unwrap(); + assert_eq!(added, vec!["PARTS".to_string()]); + assert!(d.linetypes.iter().any(|l| l.name == "DASHED")); + } +} diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index bcc5ef26..753fbc8e 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -68,7 +68,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(crate) 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")] }; @@ -135,7 +135,7 @@ fn define_from(s: &mut Session, src: &Drawing, name: &str) -> Result { /// 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) { +pub(super) fn merge_tables(d: &mut Drawing, src: &Drawing) { use crate::cmd::merge::merge_named as merge; merge(&mut d.layers, &src.layers, |l| &l.name); merge(&mut d.linetypes, &src.linetypes, |l| &l.name); @@ -148,7 +148,7 @@ fn merge_tables(d: &mut Drawing, src: &Drawing) { /// 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 { +pub(super) fn adopt(d: &mut Drawing, src: &Drawing, e: &Entity, renames: &BTreeMap) -> Entity { let mut e = e.clone(); let old = e.handle; e.handle = d.new_handle(); diff --git a/crates/engine/src/cmd/exchange.rs b/crates/engine/src/cmd/exchange.rs index b1e2aa5c..1eb1a3bc 100644 --- a/crates/engine/src/cmd/exchange.rs +++ b/crates/engine/src/cmd/exchange.rs @@ -57,9 +57,10 @@ pub fn specs() -> Vec { .noundo(), CommandSpec::new("attach", "Attach", |s, p| match str_param(p, "path").map(extension) { Some(e) if super::image::is_image_ext(&e) => super::image::run_imageattach(s, p), - _ => Err(EngineError::Other("ATTACH is not available yet for this file: only raster images (PNG, JPEG, BMP, TIFF; see IMAGEATTACH) can be attached, PDF/DWF/DGN underlays can't be shown yet".into())), + Some(e) if super::underlay::is_pdf_ext(&e) => super::underlay::run_pdfattach(s, p), + _ => Err(EngineError::Other("ATTACH is not available yet for this file: raster images (PNG, JPEG, BMP, TIFF; see IMAGEATTACH) and PDF files (see PDFATTACH) can be attached, DWF/DGN underlays can't be shown yet".into())), }) - .params("{path: image file, …} as IMAGEATTACH; other file types are not available yet"), + .params("{path: image or PDF file, …} as IMAGEATTACH or PDFATTACH; other file types are not available yet"), CommandSpec::new("share", "Share", |_, _| { Err(EngineError::Other("SHARE is not available yet: there is no online service to share through; EXPORT or PUBLISH the drawing and send the file".into())) }) diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index f546640c..07369951 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -69,6 +69,7 @@ pub fn entity_codec() -> Option<&'static EntityCodec> { /// COMPARE (drawing comparison). pub mod compare; +pub(crate) mod transmit; /// Decode a raster image file (PNG, JPEG, BMP, TIFF) to pixels: installed by the app with the /// image reader, a lower layer. @@ -83,6 +84,27 @@ pub fn image_decoder() -> Option { IMAGE.get().copied() } +/// The PDF reader (PDF underlays and PDFIMPORT): installed by the app with the reader, a lower +/// layer. +pub struct PdfHooks { + /// Each page's width and height in points. + pub pages: fn(&[u8]) -> std::result::Result, String>, + /// Page (from 0) as pixels on white paper at up to this many dots per inch. + pub rasterize: fn(&[u8], usize, f64) -> std::result::Result, + /// Page (from 0) as objects in points (lower-left corner at the origin, y up), reading + /// vectors, fills, text; plus how many images were left out and whether content was cut. + pub import: fn(&[u8], usize, bool, bool, bool) -> std::result::Result<(Vec, usize, bool), String>, +} + +static PDF: OnceLock = OnceLock::new(); + +pub fn set_pdf_hooks(h: PdfHooks) { + let _ = PDF.set(h); +} +pub fn pdf_hooks() -> Option<&'static PdfHooks> { + PDF.get() +} + /// Hand finished file bytes to the user where there is no file system (the browser: a download). /// Arguments: file name, MIME type, bytes. `Ok` only once the delivery was actually started. pub type DeliverHook = fn(&str, &str, &[u8]) -> std::result::Result<(), String>; @@ -325,6 +347,7 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result { let i = add_read(s, drawing, binary_dxf, &name, path); super::blocks::xref::after_open(s, i); super::image::after_open(s, i); + super::underlay::after_open(s, i); Ok(opened(s, i, true)) } @@ -384,6 +407,8 @@ fn run_open(s: &mut Session, p: &Value) -> Result { let i = open_bytes(s, &bytes, path, Some(path.to_string()))?; super::blocks::xref::after_open(s, i); super::image::after_open(s, i); + super::underlay::after_open(s, i); + super::underlay::after_open(s, i); return Ok(opened(s, i, true)); } #[cfg(target_arch = "wasm32")] @@ -395,6 +420,7 @@ fn run_open(s: &mut Session, p: &Value) -> Result { let i = open_bytes(s, &bytes, name, None)?; super::blocks::xref::after_open(s, i); super::image::after_open(s, i); + super::underlay::after_open(s, i); Ok(opened(s, i, false)) } diff --git a/crates/engine/src/cmd/file/transmit.rs b/crates/engine/src/cmd/file/transmit.rs new file mode 100644 index 00000000..9ed7e931 --- /dev/null +++ b/crates/engine/src/cmd/file/transmit.rs @@ -0,0 +1,261 @@ +//! ETRANSMIT: package the drawing with the files it needs (raster images, PDF underlays, +//! external references, and font files kept beside the drawing) into a folder or a .zip file, +//! with a transmittal report. Every file goes into one folder and the packaged drawing names its +//! references by file name, so the package opens anywhere. +//! +//! The referenced paths come from the drawing, which is input: they are resolved against the +//! drawing's folder, counted and size-capped, and a file that can't be read is reported missing +//! instead of failing the package. + +use std::collections::{BTreeMap, BTreeSet}; +use std::sync::Arc; + +use draftcraft_doc::{Drawing, EntityKind}; +use serde_json::{Value, json}; + +use super::io; +use crate::cmd::{CommandSpec, bad, str_param}; +use crate::{Result, Session}; + +/// Most referenced files packaged. +const MAX_FILES: usize = 10_000; +/// Largest referenced file packaged, and largest package. +const MAX_FILE_BYTES: u64 = 1 << 30; +const MAX_TOTAL_BYTES: u64 = 4 << 30; + +pub fn specs() -> Vec { + vec![ + CommandSpec::new("etransmit", "eTransmit...", run_etransmit) + .menu(&["File", "eTransmit..."]) + .params( + "{path: folder, or NAME.zip, to write the package to, report?: bool (default true: a transmittal report)} → {path, \ + drawing, files: [{name, source}], missing: [paths], bytes}", + ) + .noundo(), + ] +} + +/// A file the package carries: its name in the package and the bytes. +struct Packed { + name: String, + source: String, + bytes: Vec, +} + +/// A free name in the package for `wanted`: `plan (2).png` when `plan.png` is taken. +fn unique(taken: &mut BTreeSet, wanted: &str) -> String { + let (stem, ext) = match wanted.rsplit_once('.') { + Some((s, e)) if !s.is_empty() => (s.to_string(), format!(".{e}")), + _ => (wanted.to_string(), String::new()), + }; + let mut name = wanted.to_string(); + let mut i = 2; + while taken.contains(&name.to_lowercase()) && i < 100_000 { + name = format!("{stem} ({i}){ext}"); + i += 1; + } + taken.insert(name.to_lowercase()); + name +} + +fn file_name(path: &str) -> &str { + path.rsplit(['/', '\\']).next().unwrap_or(path) +} + +/// Read a referenced file: as given, else against the drawing's folder, else by its name in the +/// drawing's folder. +fn read_reference(dir: Option<&std::path::Path>, path: &str) -> Option<(String, Vec)> { + #[cfg(not(target_arch = "wasm32"))] + { + let mut candidates = vec![std::path::PathBuf::from(path)]; + if let Some(dir) = dir { + candidates.push(dir.join(path)); + candidates.push(dir.join(file_name(path))); + } + for c in candidates { + if let Ok(meta) = std::fs::metadata(&c) + && meta.is_file() + && meta.len() <= MAX_FILE_BYTES + && let Ok(bytes) = std::fs::read(&c) + { + return Some((c.to_string_lossy().into_owned(), bytes)); + } + } + None + } + #[cfg(target_arch = "wasm32")] + { + let _ = (dir, path); + None + } +} + +/// The drawing's references: images and underlays by path, xrefs by path, and fonts by name. +fn references(d: &Drawing) -> (BTreeSet, BTreeSet, BTreeSet) { + let mut images = BTreeSet::new(); + let stores = std::iter::once(&d.model) + .chain(d.layouts.iter().map(|l| &l.entities)) + .chain(d.blocks.values().filter(|b| b.xref_path.is_none()).map(|b| &b.entities)); + for store in stores { + for e in store.iter() { + if let EntityKind::Image(i) = &e.kind + && !i.path.trim().is_empty() + { + images.insert(i.path.clone()); + } + if images.len() > MAX_FILES { + break; + } + } + } + let xrefs = d.blocks.values().filter_map(|b| b.xref_path.clone()).filter(|p| !p.trim().is_empty()).take(MAX_FILES).collect(); + let fonts = d + .text_styles + .iter() + .flat_map(|t| [t.font.clone(), t.big_font.clone()]) + .filter(|f| { + let l = f.to_ascii_lowercase(); + l.ends_with(".shx") || l.ends_with(".ttf") || l.ends_with(".otf") + }) + .take(MAX_FILES) + .collect(); + (images, xrefs, fonts) +} + +fn run_etransmit(s: &mut Session, p: &Value) -> Result { + let out = str_param(p, "path") + .filter(|x| !x.trim().is_empty()) + .ok_or_else(|| bad("etransmit", "`path` is the folder or .zip file to write"))? + .trim() + .to_string(); + let hooks = io().ok_or_else(|| bad("etransmit", "file formats are not available in this build"))?; + let state = s.state()?; + let src_path = state.path.clone(); + let dir = src_path.as_deref().and_then(|p| std::path::Path::new(p).parent()).map(std::path::Path::to_path_buf); + let mut d: Drawing = (**state.drawing()).clone(); + let drawing_name = match src_path.as_deref().map(file_name) { + Some(n) if n.to_ascii_lowercase().ends_with(".dwg") || n.to_ascii_lowercase().ends_with(".dxf") => n.to_string(), + Some(n) => format!("{}.dxf", n.rsplit_once('.').map(|(s, _)| s).unwrap_or(n)), + None => "Drawing.dxf".into(), + }; + let (images, xrefs, fonts) = references(&d); + let mut taken: BTreeSet = [drawing_name.to_lowercase()].into(); + let mut packed: Vec = Vec::new(); + let mut missing = Vec::new(); + let mut renames: BTreeMap = BTreeMap::new(); + let mut total: u64 = 0; + for path in images.iter().chain(&xrefs).chain(&fonts) { + if renames.contains_key(path) { + continue; + } + match read_reference(dir.as_deref(), path) { + Some((source, bytes)) => { + total = total.saturating_add(bytes.len() as u64); + if total > MAX_TOTAL_BYTES { + return Err(bad("etransmit", "the package would be larger than 4 GB")); + } + let name = unique(&mut taken, file_name(path)); + renames.insert(path.clone(), name.clone()); + packed.push(Packed { name, source, bytes }); + } + None => missing.push(path.clone()), + } + } + // The packaged drawing names its images and xrefs by their file names in the package. + let rename_store = |store: &mut draftcraft_doc::EntityStore| { + let hs: Vec<_> = + store.iter().filter(|e| matches!(&e.kind, EntityKind::Image(i) if renames.contains_key(&i.path))).map(|e| e.handle).collect(); + for h in hs { + store.modify(h, |e| { + if let EntityKind::Image(i) = &mut e.kind + && let Some(n) = renames.get(&i.path) + { + i.path = n.clone(); + } + }); + } + }; + rename_store(&mut d.model); + for l in &mut d.layouts { + rename_store(&mut l.entities); + } + for b in d.blocks.values_mut() { + if let Some(n) = b.xref_path.as_ref().and_then(|x| renames.get(x)).cloned() { + Arc::make_mut(b).xref_path = Some(n); + } else if b.xref_path.is_none() && b.entities.iter().any(|e| matches!(&e.kind, EntityKind::Image(i) if renames.contains_key(&i.path))) { + rename_store(&mut Arc::make_mut(b).entities); + } + } + let drawing = (hooks.write)(&d, &drawing_name).map_err(|e| bad("etransmit", e))?; + let mut files = vec![Packed { name: drawing_name.clone(), source: src_path.clone().unwrap_or_default(), bytes: drawing }]; + files.append(&mut packed); + if p.get("report").and_then(Value::as_bool).unwrap_or(true) { + let stem = drawing_name.rsplit_once('.').map(|(s, _)| s).unwrap_or(&drawing_name).to_string(); + let mut text = format!("Transmittal report for {drawing_name}\nMade by DraftCraft eTransmit.\n\nFiles in this package:\n"); + for f in &files { + text.push_str(&format!(" {}{}\n", f.name, if f.source.is_empty() { String::new() } else { format!(" (from {})", f.source) })); + } + if !missing.is_empty() { + text.push_str("\nReferenced files that were not found (not included):\n"); + for m in &missing { + text.push_str(&format!(" {m}\n")); + } + } + let name = unique(&mut taken, &format!("{stem} - Transmittal.txt")); + files.push(Packed { name, source: String::new(), bytes: text.into_bytes() }); + } + let bytes: u64 = files.iter().map(|f| f.bytes.len() as u64).sum(); + write_package(&out, &files)?; + let list: Vec = files.iter().map(|f| json!({ "name": f.name, "source": f.source })).collect(); + let message = if missing.is_empty() { + format!("Packaged {} file(s) to {out}.", files.len()) + } else { + format!("Packaged {} file(s) to {out}; {} referenced file(s) not found: {}.", files.len(), missing.len(), missing.join(", ")) + }; + Ok(json!({ "path": out, "drawing": drawing_name, "files": list, "missing": missing, "bytes": bytes, "message": message })) +} + +#[cfg(not(target_arch = "wasm32"))] +fn write_package(out: &str, files: &[Packed]) -> Result<()> { + use std::io::Write; + let path = std::path::Path::new(out); + if out.to_ascii_lowercase().ends_with(".zip") { + let mut buf = std::io::Cursor::new(Vec::new()); + { + let mut zip = zip::ZipWriter::new(&mut buf); + let opts = zip::write::SimpleFileOptions::default().compression_method(zip::CompressionMethod::Deflated).large_file(true); + for f in files { + zip.start_file(f.name.as_str(), opts).map_err(|e| bad("etransmit", e.to_string()))?; + zip.write_all(&f.bytes).map_err(|e| bad("etransmit", e.to_string()))?; + } + zip.finish().map_err(|e| bad("etransmit", e.to_string()))?; + } + crate::atomic_write::write_atomic_making_folders(path, buf.get_ref()).map_err(|e| bad("etransmit", format!("{out}: {e}"))) + } else { + std::fs::create_dir_all(path).map_err(|e| bad("etransmit", format!("{out}: {e}")))?; + for f in files { + crate::atomic_write::write_atomic(&path.join(&f.name), &f.bytes).map_err(|e| bad("etransmit", format!("{}: {e}", f.name)))?; + } + Ok(()) + } +} + +#[cfg(target_arch = "wasm32")] +fn write_package(_out: &str, _files: &[Packed]) -> Result<()> { + Err(bad("etransmit", "eTransmit is not available on the web")) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn package_names_never_collide() { + let mut taken = BTreeSet::new(); + assert_eq!(unique(&mut taken, "plan.png"), "plan.png"); + assert_eq!(unique(&mut taken, "PLAN.png"), "PLAN (2).png"); + assert_eq!(unique(&mut taken, "plan.png"), "plan (3).png"); + assert_eq!(unique(&mut taken, "README"), "README"); + assert_eq!(unique(&mut taken, "readme"), "readme (2)"); + } +} diff --git a/crates/engine/src/cmd/geo.rs b/crates/engine/src/cmd/geo.rs new file mode 100644 index 00000000..71d7d7f2 --- /dev/null +++ b/crates/engine/src/cmd/geo.rs @@ -0,0 +1,179 @@ +//! GEOGRAPHICLOCATION and GEOREMOVE: where on Earth the drawing is. The drawing's origin is at +//! the given latitude and longitude, and the north direction is the angle from the drawing's +//! Y axis to north. They are kept in the published DXF header variables `$LATITUDE`, +//! `$LONGITUDE` and `$NORTHDIRECTION`. +//! +//! With a location set, a drawing point converts to latitude and longitude (`point`) and back +//! (`latitude`/`longitude` with `toPoint`), on a local plane tangent to the WGS 84 ellipsoid at +//! the location: accurate to centimetres within a few kilometres, which is what a site drawing +//! spans. + +use draftcraft_doc::HVal; +use serde_json::{Value, json}; + +use crate::cmd::{CommandSpec, bad, point_value}; +use crate::{Result, Session}; + +/// WGS 84 semi-major axis (metres) and first eccentricity squared. +const WGS84_A: f64 = 6_378_137.0; +const WGS84_E2: f64 = 0.006_694_379_990_14; + +pub fn specs() -> Vec { + vec![ + CommandSpec::new("geographiclocation", "Geographic Location...", run_geo).menu(&["Tools", "Geographic Location..."]).alias(&["geo"]).params( + "{latitude?: -90..90, longitude?: -180..180 (degrees, WGS 84; sets the location of the drawing's origin), north?: \ + degrees (the angle from the drawing's Y axis to north, counter-clockwise), point?: [x,y] (convert this drawing point to \ + latitude/longitude), toPoint?: bool (with latitude/longitude: convert them to a drawing point instead of setting the \ + location)} → {latitude, longitude, north, units} | {point, latitude, longitude}", + ), + CommandSpec::new("georemove", "Remove Location", run_georemove).menu(&["Tools", "Remove Location"]).params("{}"), + ] +} + +/// Metres per drawing unit for INSUNITS (unitless drawings count as metres). +fn metres_per_unit(insunits: i64) -> f64 { + match insunits { + 1 => 0.0254, + 2 => 0.3048, + 3 => 1609.344, + 4 => 0.001, + 5 => 0.01, + 7 => 1000.0, + 8 => 2.54e-8, + 9 => 2.54e-5, + 10 => 0.9144, + 14 => 0.1, + 21 => 1200.0 / 3937.0, + _ => 1.0, + } +} + +/// The location: (latitude, longitude, north in radians), if one is set. +fn location(s: &Session) -> Result> { + let h = &s.doc()?.header; + let (lat, lon) = (h.get("LATITUDE").and_then(HVal::as_f64), h.get("LONGITUDE").and_then(HVal::as_f64)); + let north = h.get("NORTHDIRECTION").and_then(HVal::as_f64).filter(|n| n.is_finite()).unwrap_or(0.0); + Ok(match (lat, lon) { + (Some(lat), Some(lon)) if lat.is_finite() && lon.is_finite() => Some((lat, lon, north)), + _ => None, + }) +} + +/// Radii of curvature at `lat` (degrees): (meridian, prime vertical), metres. +fn radii(lat: f64) -> (f64, f64) { + let s = lat.to_radians().sin(); + let w = (1.0 - WGS84_E2 * s * s).sqrt(); + (WGS84_A * (1.0 - WGS84_E2) / (w * w * w), WGS84_A / w) +} + +/// A drawing point's latitude and longitude. +fn to_geo(loc: (f64, f64, f64), unit_m: f64, x: f64, y: f64) -> (f64, f64) { + let (lat0, lon0, north) = loc; + // East/north metres: the drawing turned so that north is up. + let (sn, cn) = north.sin_cos(); + let (e, n) = ((x * cn + y * sn) * unit_m, (-x * sn + y * cn) * unit_m); + let (m, pv) = radii(lat0); + let lat = lat0 + (n / m).to_degrees(); + let lon = lon0 + (e / (pv * lat0.to_radians().cos().max(1e-9))).to_degrees(); + (lat, lon) +} + +/// A latitude and longitude's drawing point. +fn to_point(loc: (f64, f64, f64), unit_m: f64, lat: f64, lon: f64) -> (f64, f64) { + let (lat0, lon0, north) = loc; + let (m, pv) = radii(lat0); + let n = (lat - lat0).to_radians() * m; + let e = (lon - lon0).to_radians() * pv * lat0.to_radians().cos(); + let (sn, cn) = north.sin_cos(); + ((e * cn - n * sn) / unit_m, (e * sn + n * cn) / unit_m) +} + +fn degrees(p: &Value, k: &str, limit: f64) -> Result> { + match p.get(k) { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_f64() + .filter(|x| x.is_finite() && x.abs() <= limit) + .map(Some) + .ok_or_else(|| bad("geographiclocation", format!("`{k}` must be a number of degrees within ±{limit}"))), + } +} + +fn run_geo(s: &mut Session, p: &Value) -> Result { + let unit_m = metres_per_unit(s.doc()?.header.i64("INSUNITS", 0)); + let (lat, lon) = (degrees(p, "latitude", 90.0)?, degrees(p, "longitude", 180.0)?); + let north = degrees(p, "north", 360.0)?; + if let Some(pt) = p.get("point") { + let pt = point_value(pt).ok_or_else(|| bad("geographiclocation", "`point` must be [x, y]"))?; + let loc = location(s)?.ok_or_else(|| bad("geographiclocation", "the drawing has no geographic location"))?; + let (la, lo) = to_geo(loc, unit_m, pt.x, pt.y); + return Ok(json!({ "point": [pt.x, pt.y], "latitude": la, "longitude": lo })); + } + if p.get("toPoint").and_then(Value::as_bool).unwrap_or(false) { + let loc = location(s)?.ok_or_else(|| bad("geographiclocation", "the drawing has no geographic location"))?; + let (la, lo) = lat.zip(lon).ok_or_else(|| bad("geographiclocation", "`latitude` and `longitude` are the place to convert"))?; + let (x, y) = to_point(loc, unit_m, la, lo); + return Ok(json!({ "point": [x, y], "latitude": la, "longitude": lo })); + } + if lat.is_some() != lon.is_some() { + return Err(bad("geographiclocation", "give both `latitude` and `longitude`")); + } + if lat.is_some() || north.is_some() { + let has = location(s)?.is_some(); + if lat.is_none() && !has { + return Err(bad("geographiclocation", "set `latitude` and `longitude` first")); + } + let h = &mut s.doc_mut()?.header; + if let (Some(la), Some(lo)) = (lat, lon) { + h.set("LATITUDE", HVal::Real(la)); + h.set("LONGITUDE", HVal::Real(lo)); + } + if let Some(n) = north { + h.set("NORTHDIRECTION", HVal::Real(n.to_radians())); + } + } + match location(s)? { + Some((la, lo, n)) => { + let message = format!("Location: latitude {la:.6}, longitude {lo:.6}, north {:.2}°.", n.to_degrees()); + Ok(json!({ "latitude": la, "longitude": lo, "north": n.to_degrees(), "unitMetres": unit_m, "message": message })) + } + None => Ok(json!({ "latitude": null, "longitude": null, "message": "The drawing has no geographic location." })), + } +} + +fn run_georemove(s: &mut Session, _p: &Value) -> Result { + if location(s)?.is_none() { + return Err(bad("georemove", "the drawing has no geographic location")); + } + let h = &mut s.doc_mut()?.header; + for k in ["LATITUDE", "LONGITUDE", "NORTHDIRECTION"] { + h.vars.remove(k); + } + Ok(json!({ "message": "Geographic location removed." })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn a_location_converts_both_ways() { + let mut s = Session::new(); + assert!(s.execute("geographiclocation", &json!({"point": [0, 0]})).is_err(), "no location yet"); + s.doc_mut().unwrap().header.set_i64("INSUNITS", 6); + s.execute("geographiclocation", &json!({"latitude": 45.4642, "longitude": 9.19, "north": 30})).unwrap(); + let r = s.execute("geographiclocation", &json!({"point": [100, 250]})).unwrap(); + let (la, lo) = (r["latitude"].as_f64().unwrap(), r["longitude"].as_f64().unwrap()); + let back = s.execute("geographiclocation", &json!({"latitude": la, "longitude": lo, "toPoint": true})).unwrap(); + let (x, y) = (back["point"][0].as_f64().unwrap(), back["point"][1].as_f64().unwrap()); + assert!((x - 100.0).abs() < 1e-6 && (y - 250.0).abs() < 1e-6, "{back}"); + // One kilometre north on an unrotated drawing is about 0.009° of latitude. + s.execute("geographiclocation", &json!({"north": 0})).unwrap(); + let r = s.execute("geographiclocation", &json!({"point": [0, 1000]})).unwrap(); + assert!((r["latitude"].as_f64().unwrap() - 45.4642 - 0.009).abs() < 0.0005, "{r}"); + assert!(s.execute("geographiclocation", &json!({"latitude": 91, "longitude": 0})).is_err()); + assert!(s.execute("geographiclocation", &json!({"latitude": 10})).is_err()); + s.execute("georemove", &json!({})).unwrap(); + assert!(s.execute("georemove", &json!({})).is_err()); + } +} diff --git a/crates/engine/src/cmd/image.rs b/crates/engine/src/cmd/image.rs index 2c76be02..1447b40d 100644 --- a/crates/engine/src/cmd/image.rs +++ b/crates/engine/src/cmd/image.rs @@ -29,12 +29,15 @@ const MAX_PATH: usize = 4096; pub fn specs() -> Vec { vec![ - CommandSpec::new("imageattach", "Raster Image Reference...", run_imageattach).alias(&["iat"]).params( - "{path: PNG/JPEG/BMP/TIFF file (saved as given; a relative path is relative to this drawing's folder), data?: base64 file contents \ + CommandSpec::new("imageattach", "Raster Image Reference...", run_imageattach) + .alias(&["iat"]) + .menu(&["Insert", "Raster Image Reference..."]) + .params( + "{path: PNG/JPEG/BMP/TIFF file (saved as given; a relative path is relative to this drawing's folder), data?: base64 file contents \ (instead of reading `path`), at?: [x,y] lower-left corner (default 0,0), scale?: number (default 1: the image is one drawing unit \ wide), width?: width in drawing units (instead of `scale`), rotation? (degrees), name? (default: the file name)} → {name, handle, \ path, pixels: [w, h], size: [w, h]}", - ), + ), CommandSpec::new("image", "Raster Images", run_image) .alias(&["im"]) .params("{} → {images: [{name, path, foundAt, status: Loaded|Not Found|Not loaded, references, pixels?: [w, h]}]}") @@ -53,7 +56,8 @@ fn images(d: &Drawing) -> impl Iterator { let layouts = d.layouts.iter().map(|l| &l.entities); let blocks = d.blocks.values().map(|b| &b.entities); model.chain(layouts).chain(blocks).flat_map(|store| store.iter()).filter_map(|e| match &e.kind { - EntityKind::Image(i) => Some(i), + // Underlays are PDF pages (`super::underlay`). + EntityKind::Image(i) if i.underlay.is_none() => Some(i), _ => None, }) } @@ -71,7 +75,7 @@ fn paths(d: &Drawing) -> Vec { } /// The contents of the image file saved as `path` in a drawing at `host`. -fn read_file(path: &str, host: Option<&str>) -> std::result::Result, String> { +pub(crate) fn read_file(path: &str, host: Option<&str>) -> std::result::Result, String> { #[cfg(not(target_arch = "wasm32"))] { let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?; diff --git a/crates/engine/src/cmd/imageops.rs b/crates/engine/src/cmd/imageops.rs new file mode 100644 index 00000000..b0306e96 --- /dev/null +++ b/crates/engine/src/cmd/imageops.rs @@ -0,0 +1,650 @@ +//! IMAGECLIP, PDFCLIP, IMAGEADJUST and PDFADJUST: clip raster images and PDF underlays to a +//! rectangle or polygon and change how they show (brightness, contrast, fade, monochrome). The +//! Image and PDF Underlay contextual ribbon tabs reach them. +//! +//! A boundary is given in drawing coordinates and kept on the image in its own pixel coordinates +//! ([`Image::clip`]), so it moves, scales and rotates with the image. An underlay also keeps it as +//! the file does (inches from its insertion point, [`draftcraft_doc::Underlay::clip`]). + +use draftcraft_doc::{EntityKind, Handle, Image, MAX_CLIP_VERTICES, POINTS_PER_INCH}; +use draftcraft_geom::Vec2; +use serde_json::{Value, json}; + +use super::machines::{SelOutcome, SelectPhase}; +use super::{CommandSpec, bad, bool_or, has_doc, point_value, str_param, targets}; +use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step}; + +/// Which objects a command works on. +#[derive(Clone, Copy, PartialEq, Eq)] +enum Kind { + Image, + Underlay, +} + +impl Kind { + fn id(self, clip: bool) -> &'static str { + match (self, clip) { + (Kind::Image, true) => "imageclip", + (Kind::Underlay, true) => "pdfclip", + (Kind::Image, false) => "imageadjust", + (Kind::Underlay, false) => "pdfadjust", + } + } + fn wants(self, i: &Image) -> bool { + (self == Kind::Underlay) == i.underlay.is_some() + } + fn nothing(self) -> &'static str { + match self { + Kind::Image => "select raster images", + Kind::Underlay => "select PDF underlays", + } + } +} + +pub(super) fn specs() -> Vec { + const CLIP: &str = "{handles? | handle? (default the selection), option?: new|on|off|delete (default new with a boundary, else \ + query), rectangle?: [[x,y],[x,y]] | points?: [[x,y],…] (3 to 4096, drawing coordinates)} → {handles, option} \ + (query: {clips: [{handle, boundary, enabled}]})"; + vec![ + CommandSpec::new("imageclip", "Image Clip", |s, p| run_clip(s, p, Kind::Image)) + .alias(&["icl"]) + .menu(&["Modify", "Clip", "Image"]) + .params(CLIP) + .enabled(has_doc) + .interactive(|_| Ok(Box::new(ClipM::new(Kind::Image)))), + CommandSpec::new("pdfclip", "PDF Clip", |s, p| run_clip(s, p, Kind::Underlay)) + .menu(&["Modify", "Clip", "PDF Underlay"]) + .params(CLIP) + .enabled(has_doc) + .interactive(|_| Ok(Box::new(ClipM::new(Kind::Underlay)))), + CommandSpec::new("imageadjust", "Image Adjust", |s, p| run_adjust(s, p, Kind::Image)) + .alias(&["iad"]) + .menu(&["Modify", "Object", "Image", "Adjust..."]) + .params("{handles? (default the selection), brightness?: 0-100, contrast?: 0-100, fade?: 0-100} → {handles, brightness, contrast, fade}") + .enabled(has_doc) + .interactive(|_| Ok(Box::new(AdjustM::new(Kind::Image)))), + CommandSpec::new("pdfadjust", "PDF Adjust", |s, p| run_adjust(s, p, Kind::Underlay)) + .params("{handles? (default the selection), contrast?: 0-100, fade?: 0-80, monochrome?: bool, adjustColors?: bool (for the background)} → {handles, contrast, fade, monochrome, adjustColors}") + .enabled(has_doc) + .interactive(|_| Ok(Box::new(AdjustM::new(Kind::Underlay)))), + ] +} + +/// The images (or underlays) among `hs`, once each. +fn pick(s: &Session, hs: &[Handle], kind: Kind) -> Vec { + let Ok(d) = s.doc() else { return Vec::new() }; + let mut seen = std::collections::HashSet::new(); + hs.iter() + .copied() + .filter(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Image(i)) if kind.wants(i))) + .filter(|h| seen.insert(*h)) + .collect() +} + +fn hexes(hs: &[Handle]) -> Vec { + hs.iter().map(|h| h.hex()).collect() +} + +/// A drawing point as image pixel coordinates (from the top-left pixel centre, y down), with +/// the same point in the image's own frame (a: along U, b: along V, in pixels from the corner). +fn to_pixels(i: &Image, q: Vec2) -> Option<(Vec2, Vec2)> { + let (u, v) = (i.u.xy(), i.v.xy()); + let det = u.x * v.y - u.y * v.x; + if !det.is_finite() || det.abs() < 1e-300 { + return None; + } + let r = q - i.insert.xy(); + let a = (r.x * v.y - r.y * v.x) / det; + let b = (u.x * r.y - u.y * r.x) / det; + (a.is_finite() && b.is_finite()).then(|| (Vec2::new(a - 0.5, i.size.y - b - 0.5), Vec2::new(a, b))) +} + +/// An image's boundary outline in drawing coordinates. +fn outline(i: &Image) -> Vec { + let pts: Vec = match i.clip.as_slice() { + [a, b] => vec![*a, Vec2::new(b.x, a.y), *b, Vec2::new(a.x, b.y)], + p => p.to_vec(), + }; + pts.iter().map(|p| i.insert.xy() + i.u.xy() * (p.x + 0.5) + i.v.xy() * (i.size.y - p.y - 0.5)).collect() +} + +fn boundary(p: &Value, id: &str) -> Result<(Vec, bool)> { + if let Some(r) = p.get("rectangle") { + let pts: Vec = r.as_array().map(|a| a.iter().filter_map(point_value).collect()).unwrap_or_default(); + let [a, b] = pts.as_slice() else { return Err(bad(id, "`rectangle` needs two finite corners [[x,y],[x,y]]")) }; + if (a.x - b.x).abs() <= 1e-12 || (a.y - b.y).abs() <= 1e-12 { + return Err(bad(id, "the clipping rectangle must have a width and a height")); + } + return Ok((vec![*a, *b], true)); + } + let pts = p.get("points").and_then(Value::as_array).ok_or_else(|| bad(id, "a boundary is required: `rectangle` or `points`"))?; + if !(3..=MAX_CLIP_VERTICES).contains(&pts.len()) { + return Err(bad(id, format!("a polygonal boundary needs 3 to {MAX_CLIP_VERTICES} points"))); + } + let pts: Vec = + pts.iter().map(|v| point_value(v).ok_or_else(|| bad(id, "every boundary point must be a finite [x, y]"))).collect::>()?; + Ok((pts, false)) +} + +fn run_clip(s: &mut Session, p: &Value, kind: Kind) -> Result { + let id = kind.id(true); + let hs = pick(s, &targets(s, p)?, kind); + if hs.is_empty() { + return Err(bad(id, kind.nothing())); + } + let has_boundary = p.get("rectangle").is_some() || p.get("points").is_some(); + let option = str_param(p, "option").map(str::to_ascii_lowercase).unwrap_or_else(|| if has_boundary { "new".into() } else { "query".into() }); + match option.as_str() { + "new" | "n" => { + let (world, rect) = boundary(p, id)?; + let mut changes = Vec::with_capacity(hs.len()); + { + let d = s.doc()?; + for h in &hs { + let Some(EntityKind::Image(i)) = d.entity(*h).map(|e| &e.kind) else { continue }; + // A rectangle stays two corners only while the image is square to the axes. + let square = i.u.y.abs() < 1e-12 && i.v.x.abs() < 1e-12; + let pts: Vec = match (rect, world.as_slice()) { + (true, [a, b]) if !square => vec![*a, Vec2::new(b.x, a.y), *b, Vec2::new(a.x, b.y)], + _ => world.clone(), + }; + let mapped: Vec<(Vec2, Vec2)> = pts + .iter() + .map(|q| to_pixels(i, *q)) + .collect::>() + .ok_or_else(|| bad(id, "an image with a zero size can't be clipped"))?; + changes.push((*h, mapped)); + } + } + for (h, mapped) in changes { + s.doc_mut()? + .modify_entity(h, |e| { + if let EntityKind::Image(i) = &mut e.kind { + i.clip = mapped.iter().map(|m| m.0).collect(); + i.clipping = true; + i.display |= 4; + if let Some(u) = &mut i.underlay { + u.clip = mapped.iter().map(|m| m.1 * (1.0 / POINTS_PER_INCH)).collect(); + } + } + }) + .map_err(|e| bad(id, e.to_string()))?; + } + } + "on" | "off" => { + let on = option == "on"; + let d = s.doc()?; + if !hs.iter().all(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Image(i)) if i.clip.len() >= 2)) { + return Err(bad(id, "no clipping boundary on the selected objects")); + } + for h in &hs { + s.doc_mut()? + .modify_entity(*h, |e| { + if let EntityKind::Image(i) = &mut e.kind { + i.clipping = on; + i.display = if on { i.display | 4 } else { i.display & !4 }; + } + }) + .map_err(|e| bad(id, e.to_string()))?; + } + } + "delete" | "d" => { + for h in &hs { + s.doc_mut()? + .modify_entity(*h, |e| { + if let EntityKind::Image(i) = &mut e.kind { + i.clip.clear(); + i.clipping = false; + i.display &= !4; + if let Some(u) = &mut i.underlay { + u.clip.clear(); + } + } + }) + .map_err(|e| bad(id, e.to_string()))?; + } + } + "query" | "?" => { + let d = s.doc()?; + let clips: Vec = hs + .iter() + .filter_map(|h| match &d.entity(*h)?.kind { + EntityKind::Image(i) => Some(json!({ + "handle": h.hex(), + "boundary": (i.clip.len() >= 2).then(|| outline(i).iter().map(|p| [p.x, p.y]).collect::>()), + "enabled": i.clipping && i.clip.len() >= 2, + })), + _ => None, + }) + .collect(); + return Ok(json!({ "clips": clips })); + } + o => return Err(bad(id, format!("unknown option \"{o}\" (new, on, off, delete or query)"))), + } + Ok(json!({ "handles": hexes(&hs), "option": option })) +} + +/// A percentage parameter: `None` when absent, an error outside 0..=`max`. +fn pct(p: &Value, key: &str, max: u8, id: &str) -> Result> { + match p.get(key) { + None | Some(Value::Null) => Ok(None), + Some(v) => v + .as_f64() + .or_else(|| v.as_str().and_then(|t| t.trim().parse().ok())) + .filter(|x| x.is_finite() && (0.0..=f64::from(max)).contains(x)) + .map(|x| Some(x.round() as u8)) + .ok_or_else(|| bad(id, format!("`{key}` must be a number from 0 to {max}"))), + } +} + +fn run_adjust(s: &mut Session, p: &Value, kind: Kind) -> Result { + let id = kind.id(false); + let hs = pick(s, &targets(s, p)?, kind); + if hs.is_empty() { + return Err(bad(id, kind.nothing())); + } + let brightness = if kind == Kind::Image { pct(p, "brightness", 100, id)? } else { None }; + let contrast = pct(p, "contrast", 100, id)?; + let fade = pct(p, "fade", if kind == Kind::Image { 100 } else { 80 }, id)?; + let mono = p.get("monochrome").map(|_| bool_or(p, "monochrome", false)); + let adjust = p.get("adjustColors").map(|_| bool_or(p, "adjustColors", false)); + let changes = brightness.is_some() || contrast.is_some() || fade.is_some() || (kind == Kind::Underlay && (mono.is_some() || adjust.is_some())); + if changes { + for h in &hs { + s.doc_mut()? + .modify_entity(*h, |e| { + if let EntityKind::Image(i) = &mut e.kind { + if let Some(v) = brightness { + i.brightness = v; + } + if let Some(v) = contrast { + i.contrast = v; + } + if let Some(v) = fade { + i.fade = v; + } + if let Some(u) = &mut i.underlay { + if let Some(m) = mono { + u.monochrome = m; + } + if let Some(a) = adjust { + u.adjust_for_background = a; + } + } + } + }) + .map_err(|e| bad(id, e.to_string()))?; + } + } + // The first object's values: what the command shows (and every object has after a change). + let d = s.doc()?; + let Some(EntityKind::Image(i)) = hs.first().and_then(|h| d.entity(*h)).map(|e| &e.kind) else { return Err(bad(id, kind.nothing())) }; + let mut out = json!({ "handles": hexes(&hs), "contrast": i.contrast, "fade": i.fade }); + match &i.underlay { + Some(u) => { + out["monochrome"] = json!(u.monochrome); + out["adjustColors"] = json!(u.adjust_for_background); + } + None => out["brightness"] = json!(i.brightness), + } + Ok(out) +} + +fn kw(i: &Input) -> Option { + match i { + Input::Keyword(k) | Input::Text(k) => Some(k.trim().to_ascii_lowercase()), + _ => None, + } +} + +// ---------------- IMAGECLIP / PDFCLIP prompts ---------------- + +#[derive(Default, Clone, Copy, PartialEq, Eq)] +enum ClipStage { + #[default] + Select, + Option, + Boundary, + Corner2, + Polygon, +} + +struct ClipM { + kind: Kind, + stage: ClipStage, + sel: SelectPhase, + hs: Vec, + pts: Vec, +} + +impl ClipM { + fn new(kind: Kind) -> Self { + ClipM { kind, stage: ClipStage::Select, sel: SelectPhase::default(), hs: Vec::new(), pts: Vec::new() } + } + fn selected(&mut self, s: &mut Session, hs: &[Handle]) -> Step { + self.hs = pick(s, hs, self.kind); + if self.hs.is_empty() { + s.echo(match self.kind { + Kind::Image => "No raster images selected.", + Kind::Underlay => "No PDF underlays selected.", + }); + return Step::Done; + } + self.stage = ClipStage::Option; + Step::Continue + } + fn apply(&mut self, s: &mut Session, mut p: Value) -> Result { + p["handles"] = json!(hexes(&self.hs)); + if let Err(e) = run_clip(s, &p, self.kind) { + s.echo(e.to_string()); + } + s.set_selection(Vec::new()); + Ok(Step::Done) + } +} + +impl Interactive for ClipM { + fn name(&self) -> &'static str { + match self.kind { + Kind::Image => "IMAGECLIP", + Kind::Underlay => "PDFCLIP", + } + } + fn begin(&mut self, s: &mut Session) -> Result { + self.sel = SelectPhase::begin(s); + self.sel.single = true; + if self.sel.done { + let hs = self.sel.picked.clone(); + return Ok(self.selected(s, &hs)); + } + Ok(Step::Continue) + } + fn prompt(&self, _s: &Session) -> Prompt { + match self.stage { + ClipStage::Select => match self.kind { + Kind::Image => Prompt::new("Select image to clip", Accept::SELECT), + Kind::Underlay => Prompt::new("Select PDF to clip", Accept::SELECT), + }, + ClipStage::Option => Prompt::new("Enter image clipping option", Accept::TEXT).kw(&["ON", "OFF", "Delete", "New boundary"]).default("New"), + ClipStage::Boundary => { + Prompt::new("Specify first corner point or", Accept::POINT).kw(&["Polygonal", "Rectangular"]).default("Rectangular") + } + ClipStage::Corner2 => { + let p = Prompt::new("Specify opposite corner point", Accept::POINT); + match self.pts.first() { + Some(a) => p.corner(*a), + None => p, + } + } + ClipStage::Polygon => { + let msg = if self.pts.is_empty() { "Specify first point" } else { "Specify next point" }; + let p = Prompt::new(msg, Accept::POINT).base_opt(self.pts.last().copied()); + if self.pts.is_empty() { p } else { p.kw(&["Undo"]) } + } + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + match self.stage { + ClipStage::Select => match self.sel.feed(s, &i)? { + SelOutcome::More => Ok(Step::Continue), + SelOutcome::Empty => Ok(Step::Done), + SelOutcome::Done(hs) => Ok(self.selected(s, &hs)), + }, + ClipStage::Option => { + let k = if matches!(i, Input::Enter) { Some("new".to_string()) } else { kw(&i) }; + match k.as_deref() { + Some("on") => self.apply(s, json!({ "option": "on" })), + Some("off") => self.apply(s, json!({ "option": "off" })), + Some(k) if k.starts_with('d') => self.apply(s, json!({ "option": "delete" })), + Some(k) if k.starts_with('n') => { + self.stage = ClipStage::Boundary; + Ok(Step::Continue) + } + _ => { + s.echo("Invalid option keyword."); + Ok(Step::Continue) + } + } + } + ClipStage::Boundary => match (&i, kw(&i).as_deref()) { + (Input::Point(p), _) => { + self.pts = vec![*p]; + self.stage = ClipStage::Corner2; + Ok(Step::Continue) + } + (_, Some(k)) if k.starts_with('p') => { + self.pts.clear(); + self.stage = ClipStage::Polygon; + Ok(Step::Continue) + } + _ => Ok(Step::Continue), + }, + ClipStage::Corner2 => match (i, self.pts.first().copied()) { + (Input::Point(b), Some(a)) => self.apply(s, json!({ "option": "new", "rectangle": [[a.x, a.y], [b.x, b.y]] })), + _ => Ok(Step::Continue), + }, + ClipStage::Polygon => match i { + Input::Point(p) if self.pts.len() < MAX_CLIP_VERTICES => { + self.pts.push(p); + Ok(Step::Continue) + } + Input::Point(_) => { + s.echo(format!("A boundary has at most {MAX_CLIP_VERTICES} points.")); + Ok(Step::Continue) + } + Input::Keyword(_) | Input::Text(_) => { + self.pts.pop(); + Ok(Step::Continue) + } + Input::Enter if self.pts.len() >= 3 => { + let pts: Vec<[f64; 2]> = self.pts.iter().map(|p| [p.x, p.y]).collect(); + self.apply(s, json!({ "option": "new", "points": pts })) + } + Input::Enter => { + s.echo("A polygonal boundary needs at least 3 points."); + Ok(Step::Continue) + } + _ => Ok(Step::Continue), + }, + } + } +} + +// ---------------- IMAGEADJUST / PDFADJUST prompts ---------------- + +struct AdjustM { + kind: Kind, + sel: SelectPhase, + hs: Vec, + /// The setting being asked for, once chosen. + setting: Option<&'static str>, +} + +impl AdjustM { + fn new(kind: Kind) -> Self { + AdjustM { kind, sel: SelectPhase::default(), hs: Vec::new(), setting: None } + } + fn settings(&self) -> &'static [&'static str] { + match self.kind { + Kind::Image => &["Brightness", "Contrast", "Fade"], + Kind::Underlay => &["Contrast", "Fade", "Monochrome"], + } + } +} + +impl Interactive for AdjustM { + fn name(&self) -> &'static str { + match self.kind { + Kind::Image => "IMAGEADJUST", + Kind::Underlay => "PDFADJUST", + } + } + fn begin(&mut self, s: &mut Session) -> Result { + self.sel = SelectPhase::begin(s); + if self.sel.done { + self.hs = pick(s, &self.sel.picked.clone(), self.kind); + if self.hs.is_empty() { + s.echo(self.kind.nothing()); + return Ok(Step::Done); + } + } + Ok(Step::Continue) + } + fn prompt(&self, s: &Session) -> Prompt { + if self.hs.is_empty() { + return self.sel.prompt(); + } + let current = |key: &str| -> String { + let v = run_adjust_query(s, &self.hs, self.kind); + v.get(key).map(|x| x.to_string()).unwrap_or_default() + }; + match self.setting { + None => Prompt::new("Enter adjustment option", Accept::TEXT).kw(self.settings()), + Some("monochrome") => { + Prompt::new("Monochrome?", Accept::TEXT).kw(&["Yes", "No"]).default(if current("monochrome") == "true" { "Yes" } else { "No" }) + } + Some(k) => Prompt::new(format!("Enter {k} value (0-100)"), Accept::NUMBER).default(current(k)), + } + } + fn input(&mut self, s: &mut Session, i: Input) -> Result { + if matches!(i, Input::Cancel) { + return Ok(Step::Cancel); + } + if self.hs.is_empty() { + return match self.sel.feed(s, &i)? { + SelOutcome::More => Ok(Step::Continue), + SelOutcome::Empty => Ok(Step::Done), + SelOutcome::Done(hs) => { + self.hs = pick(s, &hs, self.kind); + if self.hs.is_empty() { + s.echo(self.kind.nothing()); + return Ok(Step::Done); + } + Ok(Step::Continue) + } + }; + } + let Some(setting) = self.setting else { + let k = kw(&i).unwrap_or_default(); + let chosen = ["brightness", "contrast", "fade", "monochrome"].into_iter().find(|n| !k.is_empty() && n.starts_with(&k)); + match chosen.filter(|n| self.settings().iter().any(|o| o.eq_ignore_ascii_case(n))) { + Some(n) => self.setting = Some(n), + None if matches!(i, Input::Enter) => return Ok(Step::Done), + None => s.echo("Invalid option keyword."), + } + return Ok(Step::Continue); + }; + let value = match (&i, setting) { + (Input::Enter, _) => return Ok(Step::Done), + (_, "monochrome") => json!(kw(&i).is_some_and(|k| k.starts_with('y'))), + (_, _) => match kw(&i).and_then(|t| t.parse::().ok()) { + Some(v) => json!(v), + None => { + s.echo("Requires a number from 0 to 100."); + return Ok(Step::Continue); + } + }, + }; + let mut p = json!({ "handles": hexes(&self.hs) }); + p[setting] = value; + if let Err(e) = run_adjust(s, &p, self.kind) { + s.echo(e.to_string()); + return Ok(Step::Continue); + } + Ok(Step::Done) + } +} + +/// The adjustment values of the first of `hs`, without changing anything. +fn run_adjust_query(s: &Session, hs: &[Handle], kind: Kind) -> Value { + let Ok(d) = s.doc() else { return Value::Null }; + let Some(EntityKind::Image(i)) = hs.first().and_then(|h| d.entity(*h)).map(|e| &e.kind) else { return Value::Null }; + match (&i.underlay, kind) { + (Some(u), _) => json!({ "contrast": i.contrast, "fade": i.fade, "monochrome": u.monochrome }), + (None, _) => json!({ "brightness": i.brightness, "contrast": i.contrast, "fade": i.fade }), + } +} + +#[cfg(test)] +mod tests { + use super::*; + + fn session_with_image(underlay: bool) -> (Session, Handle) { + let mut s = Session::new(); + let img = Image { + insert: draftcraft_geom::Vec3::new(10.0, 20.0, 0.0), + size: Vec2::new(100.0, 50.0), + path: "a.png".into(), + underlay: underlay.then(|| draftcraft_doc::Underlay { page: "1".into(), ..Default::default() }), + ..Image::default() + }; + let h = s.add_entity(EntityKind::Image(img)).unwrap(); + (s, h) + } + + fn image(s: &Session, h: Handle) -> Image { + match &s.doc().unwrap().entity(h).unwrap().kind { + EntityKind::Image(i) => i.clone(), + _ => panic!("not an image"), + } + } + + #[test] + fn a_rectangle_clips_in_pixels_and_turns_off_and_goes() { + let (mut s, h) = session_with_image(false); + let r = s.execute("imageclip", &json!({ "handle": h.hex(), "rectangle": [[20, 30], [40, 60]] })).unwrap(); + assert_eq!(r["option"], "new"); + let i = image(&s, h); + // (20, 30) is 10 right and 10 up from the corner: pixel (9.5, 39.5). + assert_eq!(i.clip, vec![Vec2::new(9.5, 39.5), Vec2::new(29.5, 9.5)]); + assert!(i.clipping && i.display & 4 != 0); + let q = s.execute("imageclip", &json!({ "handle": h.hex() })).unwrap(); + assert_eq!(q["clips"][0]["boundary"][0], json!([20.0, 30.0])); + s.execute("imageclip", &json!({ "handle": h.hex(), "option": "off" })).unwrap(); + assert!(!image(&s, h).clipping); + s.execute("imageclip", &json!({ "handle": h.hex(), "option": "delete" })).unwrap(); + assert!(image(&s, h).clip.is_empty()); + // An image isn't an underlay, and a bad boundary changes nothing. + assert!(s.execute("pdfclip", &json!({ "handle": h.hex(), "rectangle": [[0, 0], [1, 1]] })).is_err()); + assert!(s.execute("imageclip", &json!({ "handle": h.hex(), "rectangle": [[0, 0], [0, 1]] })).is_err()); + assert!(s.execute("imageclip", &json!({ "handle": h.hex(), "points": [[0, 0], [1, 1]] })).is_err()); + } + + #[test] + fn an_underlay_clip_is_also_kept_in_inches() { + let (mut s, h) = session_with_image(true); + s.execute("pdfclip", &json!({ "handle": h.hex(), "points": [[10, 20], [82, 20], [82, 56]] })).unwrap(); + let i = image(&s, h); + let u = i.underlay.unwrap(); + assert_eq!(u.clip, vec![Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0), Vec2::new(1.0, 0.5)]); + assert_eq!(i.clip.len(), 3); + } + + #[test] + fn adjust_sets_and_reports_the_values() { + let (mut s, h) = session_with_image(false); + let r = s.execute("imageadjust", &json!({ "handle": h.hex(), "brightness": 70, "fade": 10 })).unwrap(); + assert_eq!((r["brightness"].as_u64(), r["contrast"].as_u64(), r["fade"].as_u64()), (Some(70), Some(50), Some(10))); + assert!(s.execute("imageadjust", &json!({ "handle": h.hex(), "contrast": 101 })).is_err()); + assert!(s.execute("imageadjust", &json!({ "handle": h.hex(), "contrast": "lots" })).is_err()); + let (mut s, h) = session_with_image(true); + let r = s.execute("pdfadjust", &json!({ "handle": h.hex(), "monochrome": true, "fade": 40 })).unwrap(); + assert_eq!((r["monochrome"].as_bool(), r["fade"].as_u64()), (Some(true), Some(40))); + assert!(s.execute("pdfadjust", &json!({ "handle": h.hex(), "fade": 90 })).is_err(), "an underlay fades up to 80"); + } + + #[test] + fn imageclip_prompts_for_a_rectangle() { + let (mut s, h) = session_with_image(false); + s.set_selection(vec![h]); + s.start("imageclip").unwrap(); + s.input(Input::Enter).unwrap(); + s.input(Input::Point(Vec2::new(20.0, 30.0))).unwrap(); + s.input(Input::Point(Vec2::new(40.0, 60.0))).unwrap(); + assert!(s.running.is_none()); + assert_eq!(image(&s, h).clip.len(), 2); + } +} diff --git a/crates/engine/src/cmd/layer.rs b/crates/engine/src/cmd/layer.rs index d0811489..264aafa3 100644 --- a/crates/engine/src/cmd/layer.rs +++ b/crates/engine/src/cmd/layer.rs @@ -12,7 +12,7 @@ use super::{CommandSpec, bad, bool_or, ok, str_param, targets}; use crate::{Result, Session}; pub fn specs() -> Vec { - vec![ + let mut v = vec![ CommandSpec::new("layer", "Layers", run_list) .menu(&["Format", "Layers"]) .alias(&["la", "layers", "-layer"]) @@ -68,7 +68,9 @@ pub fn specs() -> Vec { .menu(&["Format", "Layer Tools", "Layer Delete"]) .params("{names: [...]} (deletes the layers and every object on them)") .interactive(|_| Ok(Box::new(merge::LayerRemove::delete()))), - ] + ]; + v.extend(tools::specs()); + v } fn layer_json(l: &Layer, current: bool) -> Value { @@ -466,6 +468,8 @@ fn run_state_rename(s: &mut Session, p: &Value) -> Result { // LAYMRG and LAYDEL. mod merge; +// LAYTRANS and LAYWALK. +mod tools; #[cfg(test)] mod tests { diff --git a/crates/engine/src/cmd/layer/merge.rs b/crates/engine/src/cmd/layer/merge.rs index 8a2038af..d616416a 100644 --- a/crates/engine/src/cmd/layer/merge.rs +++ b/crates/engine/src/cmd/layer/merge.rs @@ -13,11 +13,11 @@ use super::super::{bad, find_command, str_param}; use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step}; /// Layers whose names carry `|` belong to an attached xref and are managed by it. -fn xref_layer(name: &str) -> bool { +pub(super) fn xref_layer(name: &str) -> bool { name.contains('|') } -fn protected(name: &str) -> bool { +pub(super) fn protected(name: &str) -> bool { name == "0" || name.eq_ignore_ascii_case("Defpoints") } @@ -71,7 +71,7 @@ fn resolve_sources(d: &Drawing, cmd: &str, names: &[String], delete: bool) -> Re /// Every entity store whose objects belong to this drawing: model space, layouts and the block /// definitions (an attached xref's blocks are left alone; they come from its file). /// `f` gets each store with objects on the `set` layers and returns how many it changed. -fn for_each_store(d: &mut Drawing, set: &HashSet, mut f: impl FnMut(&mut EntityStore) -> usize) -> usize { +pub(super) fn for_each_store(d: &mut Drawing, set: &HashSet, mut f: impl FnMut(&mut EntityStore) -> usize) -> usize { let mut n = f(&mut d.model); for layout in &mut d.layouts { n += f(&mut layout.entities); @@ -85,7 +85,7 @@ fn for_each_store(d: &mut Drawing, set: &HashSet, mut f: impl FnMut(&mut n } -fn on_layers<'a>(store: &'a EntityStore, set: &'a HashSet) -> impl Iterator + 'a { +pub(super) fn on_layers<'a>(store: &'a EntityStore, set: &'a HashSet) -> impl Iterator + 'a { store.iter().filter(|e| set.contains(&e.common.layer.to_ascii_lowercase())).map(|e| e.handle) } diff --git a/crates/engine/src/cmd/layer/tools.rs b/crates/engine/src/cmd/layer/tools.rs new file mode 100644 index 00000000..936d5e44 --- /dev/null +++ b/crates/engine/src/cmd/layer/tools.rs @@ -0,0 +1,244 @@ +//! LAYTRANS (Layer Translator) and LAYWALK (Layer Walk). +//! +//! LAYTRANS maps layers to other names, the way a drawing is brought to an office's layer +//! standard: every object on a mapped layer moves to its new layer (made from a standards drawing +//! when one is given, else from the old layer's properties), and old layers left empty are purged. +//! +//! LAYWALK shows only the chosen layers, to see what is on them; ending the walk restores which +//! layers were on, unless asked to keep the walk's state. + +use std::collections::{BTreeMap, HashSet}; + +use draftcraft_color::Color; +use serde_json::{Value, json}; + +use super::merge::{for_each_store, forget_in_viewports, on_layers, protected, xref_layer}; +use crate::cmd::blocks::insert_file::read_drawing; +use crate::cmd::{CommandSpec, bad, str_param}; +use crate::{Result, Session}; + +/// Most layer mappings one LAYTRANS call applies. +const MAX_MAPPINGS: usize = 10_000; + +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("laytrans", "Layer Translator", run_laytrans).menu(&["Tools", "CAD Standards", "Layer Translator..."]).params( + "{map: {FROM: TO, …} (layer names; FROM may use * and ? wildcards), standards?: DXF/DWG file whose layer definitions \ + the TO layers take, forceByLayer?: bool (objects moved get ByLayer colour and linetype), purge?: bool (default true: \ + delete FROM layers left empty)} → {translated: [{from, to, moved}], created: [names], purged: [names]}", + ), + CommandSpec::new("laywalk", "Layer Walk", run_laywalk) + .menu(&["Format", "Layer Tools", "Layer Walk..."]) + .params( + "{layers?: [names] (show only these; * and ? wildcards), operation?: \"end\" (stop walking), restore?: bool (with end, \ + default true: turn the layers back on or off as they were)} → {walking: bool, shown: [names]}", + ) + .noundo(), + ] +} + +/// `*` and `?` wildcard match, without letter case. +fn wild(pattern: &str, name: &str) -> bool { + let (p, n): (Vec, Vec) = (pattern.to_lowercase().chars().collect(), name.to_lowercase().chars().collect()); + // Iterative match with backtracking to the last `*` (linear in practice; no recursion). + let (mut pi, mut ni, mut star, mut mark) = (0usize, 0usize, None, 0usize); + while ni < n.len() { + match p.get(pi) { + Some('*') => { + star = Some(pi); + mark = ni; + pi += 1; + } + Some(c) if *c == '?' || Some(c) == n.get(ni) => { + pi += 1; + ni += 1; + } + _ => match star { + Some(sp) => { + pi = sp + 1; + mark += 1; + ni = mark; + } + None => return false, + }, + } + } + p.get(pi..).is_some_and(|rest| rest.iter().all(|c| *c == '*')) +} + +fn run_laytrans(s: &mut Session, p: &Value) -> Result { + let map = p.get("map").and_then(Value::as_object).ok_or_else(|| bad("laytrans", "`map` gives each layer's new name: {\"OLD\": \"NEW\"}"))?; + if map.len() > MAX_MAPPINGS { + return Err(bad("laytrans", format!("at most {MAX_MAPPINGS} mappings"))); + } + let standards = match str_param(p, "standards").filter(|x| !x.trim().is_empty()) { + Some(path) => Some(read_drawing(path).map_err(|e| bad("laytrans", e.to_string()))?), + None => None, + }; + let force = p.get("forceByLayer").and_then(Value::as_bool).unwrap_or(false); + let purge = p.get("purge").and_then(Value::as_bool).unwrap_or(true); + let mut d = s.doc()?.clone(); + // Each existing layer's new name: the first mapping whose FROM matches it. + let mut plan: BTreeMap = BTreeMap::new(); + for (from, to) in map { + let to = + to.as_str().map(str::trim).filter(|t| !t.is_empty()).ok_or_else(|| bad("laytrans", format!("`{from}` needs a layer name to map to")))?; + if xref_layer(to) { + return Err(bad("laytrans", format!("cannot translate to xref-dependent layer \"{to}\""))); + } + let mut any = false; + for l in &d.layers { + if wild(from, &l.name) && !xref_layer(&l.name) && !l.name.eq_ignore_ascii_case(to) { + plan.entry(l.name.clone()).or_insert_with(|| to.to_string()); + any = true; + } + } + if !any && !from.contains(['*', '?']) && d.layer(from).is_none() { + return Err(bad("laytrans", format!("no layer `{from}`"))); + } + } + let mut created = Vec::new(); + let mut translated = Vec::new(); + for (from, to) in &plan { + if d.layer(to).is_none() { + let layer = match standards.as_ref().and_then(|st| st.layer(to)) { + Some(l) => l.clone(), + None => { + let mut l = d.layer(from).cloned().unwrap_or_else(|| draftcraft_doc::Layer::new(to)); + l.name = to.clone(); + l + } + }; + if let Some(lt) = standards.as_ref().and_then(|st| st.linetypes.iter().find(|x| x.name.eq_ignore_ascii_case(&layer.linetype))) + && !d.linetypes.iter().any(|x| x.name.eq_ignore_ascii_case(<.name)) + { + d.linetypes.push(lt.clone()); + } + created.push(layer.name.clone()); + d.layers.push(layer); + } + let target = d.layer(to).map(|l| l.name.clone()).unwrap_or_else(|| to.clone()); + let set: HashSet = [from.to_ascii_lowercase()].into(); + let moved = for_each_store(&mut d, &set, |store| { + let hs: Vec<_> = on_layers(store, &set).collect(); + for h in &hs { + store.modify(*h, |e| { + e.common.layer = target.clone(); + if force { + e.common.color = Color::ByLayer; + e.common.linetype = "ByLayer".into(); + } + }); + } + hs.len() + }); + translated.push(json!({ "from": from, "to": target, "moved": moved })); + } + let mut purged = Vec::new(); + if purge { + let current = d.header.str("CLAYER", "0").to_ascii_lowercase(); + let gone: HashSet = + plan.keys().filter(|n| !protected(n) && n.to_ascii_lowercase() != current).map(|n| n.to_ascii_lowercase()).collect(); + forget_in_viewports(&mut d, &gone); + d.layers.retain(|l| { + let drop = gone.contains(&l.name.to_ascii_lowercase()); + if drop { + purged.push(l.name.clone()); + } + !drop + }); + } + let n = translated.len(); + *s.doc_mut()? = d; + let message = format!("Translated {n} layer(s); created {}, purged {}.", created.len(), purged.len()); + Ok(json!({ "translated": translated, "created": created, "purged": purged, "message": message })) +} + +fn run_laywalk(s: &mut Session, p: &Value) -> Result { + if str_param(p, "operation").is_some_and(|o| o.eq_ignore_ascii_case("end")) { + let restore = p.get("restore").and_then(Value::as_bool).unwrap_or(true); + let saved = s.laywalk.take(); + if restore && let Some(saved) = saved { + let d = s.doc_mut()?; + for (name, on) in saved { + if let Some(l) = d.layer_mut(&name) { + l.on = on; + } + } + } + return Ok(json!({ "walking": false, "shown": [], "message": "Layer walk ended." })); + } + let patterns: Vec = match p.get("layers") { + Some(Value::String(one)) => vec![one.clone()], + Some(Value::Array(a)) => a.iter().filter_map(Value::as_str).take(MAX_MAPPINGS).map(str::to_string).collect(), + _ => Vec::new(), + }; + if s.laywalk.is_none() { + let saved = s.doc()?.layers.iter().map(|l| (l.name.clone(), l.on)).collect(); + s.laywalk = Some(saved); + } + let d = s.doc_mut()?; + let mut shown = Vec::new(); + for l in &mut d.layers { + // No layers chosen: everything shows, as when the walk starts. + l.on = patterns.is_empty() || patterns.iter().any(|pat| wild(pat, &l.name)); + if l.on { + shown.push(l.name.clone()); + } + } + let message = format!("Layer walk: {} layer(s) shown.", shown.len()); + Ok(json!({ "walking": true, "shown": shown, "message": message })) +} + +#[cfg(test)] +mod tests { + use super::*; + use draftcraft_doc::{Entity, EntityKind, Handle, Layer, Line}; + use draftcraft_geom::Vec3; + + fn session() -> Session { + let mut s = Session::new(); + let d = s.doc_mut().unwrap(); + for n in ["WALLS-OLD", "DOORS-OLD", "TEXT"] { + d.layers.push(Layer::new(n)); + } + let mut e = Entity::new(Handle(0x900), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })); + e.common.layer = "WALLS-OLD".into(); + d.model.push(e); + s + } + + #[test] + fn wildcards() { + assert!(wild("*-old", "WALLS-OLD")); + assert!(wild("W?LLS*", "walls-old")); + assert!(!wild("*-new", "WALLS-OLD")); + assert!(wild("*", "")); + assert!(!wild("a", "")); + } + + #[test] + fn layers_are_translated_and_purged() { + let mut s = session(); + let r = s.execute("laytrans", &json!({"map": {"WALLS-OLD": "A-WALL", "DOORS-*": "A-DOOR"}, "forceByLayer": true})).unwrap(); + assert_eq!(r["created"], json!(["A-DOOR", "A-WALL"])); + let d = s.doc().unwrap(); + assert!(d.layer("WALLS-OLD").is_none() && d.layer("DOORS-OLD").is_none(), "{r}"); + assert!(d.model.iter().all(|e| e.common.layer == "A-WALL")); + assert!(s.execute("laytrans", &json!({"map": {"NOPE": "X"}})).is_err()); + assert!(s.execute("laytrans", &json!({"map": {"TEXT": "x|y"}})).is_err(), "xref layers are not targets"); + } + + #[test] + fn a_walk_shows_only_its_layers_then_restores() { + let mut s = session(); + s.doc_mut().unwrap().layer_mut("TEXT").unwrap().on = false; + let r = s.execute("laywalk", &json!({"layers": ["*-OLD"]})).unwrap(); + assert_eq!(r["shown"], json!(["WALLS-OLD", "DOORS-OLD"])); + assert!(!s.doc().unwrap().layer("0").unwrap().on); + s.execute("laywalk", &json!({"layers": "TEXT"})).unwrap(); + s.execute("laywalk", &json!({"operation": "end"})).unwrap(); + let d = s.doc().unwrap(); + assert!(d.layer("0").unwrap().on && !d.layer("TEXT").unwrap().on, "the layers are as they were before the walk"); + } +} diff --git a/crates/engine/src/cmd/pointcloud.rs b/crates/engine/src/cmd/pointcloud.rs new file mode 100644 index 00000000..9f396260 --- /dev/null +++ b/crates/engine/src/cmd/pointcloud.rs @@ -0,0 +1,346 @@ +//! POINTCLOUDATTACH: bring a point cloud into the drawing as points. DraftCraft reads XYZ text +//! files (`x y z [r g b]` per line, spaces, commas, semicolons or tabs between the values; also +//! .pts and .csv) and LAS files (ASPRS LAS 1.0–1.4, point formats 0–10, from the published +//! specification); AutoCAD's own .rcp/.rcs are not published and stay "not available yet". +//! +//! The points go into a block named after the file and one reference to it is inserted, so the +//! cloud moves, hides (by its layer) and erases as one object. A cloud larger than `maxPoints` is +//! thinned evenly. The file is hostile input: its size, the point count and every number are +//! checked, and points with non-finite coordinates are skipped. + +use std::sync::Arc; + +use draftcraft_color::{Color, Rgb}; +use draftcraft_doc::{Block, Entity, EntityKind, Insert, Point}; +use draftcraft_geom::{Vec2, Vec3}; +use serde_json::{Value, json}; + +use super::file::base64_decode; +use crate::cmd::{CommandSpec, bad, point_value, str_param}; +use crate::{Result, Session}; + +/// Largest point cloud file read. +const MAX_FILE_BYTES: u64 = 512 << 20; +/// Default and largest number of points kept. +const DEFAULT_POINTS: usize = 100_000; +const MAX_POINTS: usize = 1_000_000; +/// Most text lines looked at in an XYZ file. +const MAX_LINES: usize = 50_000_000; + +const ID: &str = "pointcloudattach"; + +pub fn specs() -> Vec { + vec![CommandSpec::new(ID, "Point Cloud...", run_attach).menu(&["Insert", "Point Cloud..."]).alias(&["pcattach", "pointcloud"]).params( + "{path: .xyz/.pts/.csv/.txt or .las file, data?: base64 file contents, at?: [x,y] (default 0,0), scale?: number (default 1), \ + maxPoints?: 1..1000000 (default 100000; larger clouds are thinned evenly), name?: block name (default the file name)} → \ + {handle, block, points, total, colored}", + )] +} + +/// A point of the cloud and its colour, if the file has one. +type CloudPoint = (Vec3, Option); + +/// A text file's points: up to `keep`, every `stride`-th of the valid lines. Returns the points +/// and how many valid lines there were. +fn parse_xyz(text: &str, keep: usize) -> (Vec, usize) { + let lines = || { + text.lines().take(MAX_LINES).filter_map(|l| { + let nums: Vec = l + .split(|c: char| c.is_whitespace() || matches!(c, ',' | ';')) + .filter(|t| !t.is_empty()) + .map_while(|t| t.parse::().ok()) + .collect(); + let (x, y, z) = (*nums.first()?, *nums.get(1)?, nums.get(2).copied().unwrap_or(0.0)); + if !(x.is_finite() && y.is_finite() && z.is_finite()) { + return None; + } + // Colour: the last three numbers when there are at least six (x y z [intensity] r g b). + let rgb = (nums.len() >= 6) + .then(|| nums.get(nums.len() - 3..)) + .flatten() + .filter(|c| c.iter().all(|v| (0.0..=255.0).contains(v))) + .map(|c| Rgb(c[0] as u8, c[1] as u8, c[2] as u8)); + Some((Vec3::new(x, y, z), rgb)) + }) + }; + let total = lines().count(); + let stride = total.div_ceil(keep.max(1)).max(1); + (lines().step_by(stride).take(keep).collect(), total) +} + +fn u16_at(b: &[u8], at: usize) -> Option { + Some(u16::from_le_bytes(b.get(at..at.checked_add(2)?)?.try_into().ok()?)) +} +fn u32_at(b: &[u8], at: usize) -> Option { + Some(u32::from_le_bytes(b.get(at..at.checked_add(4)?)?.try_into().ok()?)) +} +fn i32_at(b: &[u8], at: usize) -> Option { + Some(i32::from_le_bytes(b.get(at..at.checked_add(4)?)?.try_into().ok()?)) +} +fn u64_at(b: &[u8], at: usize) -> Option { + Some(u64::from_le_bytes(b.get(at..at.checked_add(8)?)?.try_into().ok()?)) +} +fn f64_at(b: &[u8], at: usize) -> Option { + Some(f64::from_le_bytes(b.get(at..at.checked_add(8)?)?.try_into().ok()?)) +} + +/// A LAS file's points (public ASPRS LAS specification): up to `keep`, evenly thinned. +fn parse_las(b: &[u8], keep: usize) -> std::result::Result<(Vec, usize), String> { + if b.get(0..4) != Some(b"LASF") { + return Err("not a LAS file".into()); + } + let bad = || "a damaged LAS header".to_string(); + let minor = *b.get(25).ok_or_else(bad)?; + let offset = usize::try_from(u32_at(b, 96).ok_or_else(bad)?).map_err(|_| bad())?; + // Bits 6 and 7 of the format byte mark compressed (LAZ) data, which isn't read. + let format_byte = *b.get(104).ok_or_else(bad)?; + if format_byte & 0xC0 != 0 { + return Err("compressed LAS (LAZ) files are not available yet".into()); + } + let format = format_byte & 0x3F; + let record = usize::from(u16_at(b, 105).ok_or_else(bad)?); + let legacy = u64::from(u32_at(b, 107).ok_or_else(bad)?); + let count = if legacy == 0 && minor >= 4 { u64_at(b, 247).ok_or_else(bad)? } else { legacy }; + let scale = [f64_at(b, 131), f64_at(b, 139), f64_at(b, 147)]; + let origin = [f64_at(b, 155), f64_at(b, 163), f64_at(b, 171)]; + let (Some(sx), Some(sy), Some(sz)) = (scale[0], scale[1], scale[2]) else { return Err(bad()) }; + let (Some(ox), Some(oy), Some(oz)) = (origin[0], origin[1], origin[2]) else { return Err(bad()) }; + if ![sx, sy, sz, ox, oy, oz].iter().all(|v| v.is_finite()) { + return Err(bad()); + } + // Where each point format keeps red, green and blue. + let rgb_at = match format { + 2 => Some(20), + 3 | 5 => Some(28), + 7 | 8 | 10 => Some(30), + 0 | 1 | 4 | 6 | 9 => None, + _ => return Err(format!("LAS point format {format} is not available yet")), + }; + let min_record = rgb_at.map_or(12, |at| at + 6); + if record < min_record { + return Err(bad()); + } + // Only the records the file really holds. + let fits = b.len().saturating_sub(offset) / record; + let total = usize::try_from(count).unwrap_or(usize::MAX).min(fits); + let stride = total.div_ceil(keep.max(1)).max(1); + // 16-bit colours are scaled to 8 bits; files with 8-bit values in 16-bit fields are detected. + let mut out = Vec::with_capacity(total.min(keep)); + let mut wide = false; + for i in (0..total).step_by(stride).take(keep) { + let Some(at) = i.checked_mul(record).and_then(|r| r.checked_add(offset)) else { break }; + let (Some(x), Some(y), Some(z)) = (i32_at(b, at), i32_at(b, at + 4), i32_at(b, at + 8)) else { break }; + let p = Vec3::new(f64::from(x) * sx + ox, f64::from(y) * sy + oy, f64::from(z) * sz + oz); + if !(p.x.is_finite() && p.y.is_finite() && p.z.is_finite()) { + continue; + } + let rgb = rgb_at.and_then(|c| Some([u16_at(b, at + c)?, u16_at(b, at + c + 2)?, u16_at(b, at + c + 4)?])); + wide |= rgb.is_some_and(|c| c.iter().any(|v| *v > 255)); + out.push((p, rgb.map(|c| Rgb(c[0] as u8, c[1] as u8, c[2] as u8)), rgb)); + } + let points = out + .into_iter() + .map(|(p, low, full)| { + let c = if wide { full.map(|c| Rgb((c[0] >> 8) as u8, (c[1] >> 8) as u8, (c[2] >> 8) as u8)) } else { low }; + (p, c) + }) + .collect(); + Ok((points, total)) +} + +fn read(path: &str, host: Option<&str>) -> std::result::Result, String> { + #[cfg(not(target_arch = "wasm32"))] + { + let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?; + let limit = usize::try_from(MAX_FILE_BYTES).unwrap_or(usize::MAX); + crate::capped_read::read_capped(&file, limit).map_err(|e| { + if e.kind() == std::io::ErrorKind::InvalidData { format!("the file is larger than {} MB", MAX_FILE_BYTES >> 20) } else { e.to_string() } + }) + } + #[cfg(target_arch = "wasm32")] + { + let _ = (path, host); + Err("files are not available on the web: pass the file as `data`".into()) + } +} + +fn run_attach(s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path").filter(|x| !x.trim().is_empty()).ok_or_else(|| bad(ID, "`path` names the point cloud file"))?.trim().to_string(); + let lower = path.to_ascii_lowercase(); + if lower.ends_with(".rcp") || lower.ends_with(".rcs") { + return Err(bad(ID, "ReCap point clouds (.rcp, .rcs) are not available yet: export the scan as LAS or XYZ")); + } + let keep = match p.get("maxPoints") { + None => DEFAULT_POINTS, + Some(v) => v + .as_u64() + .and_then(|n| usize::try_from(n).ok()) + .filter(|n| (1..=MAX_POINTS).contains(n)) + .ok_or_else(|| bad(ID, format!("`maxPoints` must be 1 to {MAX_POINTS}")))?, + }; + let at = match p.get("at") { + Some(v) => point_value(v).ok_or_else(|| bad(ID, "`at` must be [x, y]"))?, + None => Vec2::ZERO, + }; + let scale = match p.get("scale") { + Some(v) => v.as_f64().filter(|x| x.is_finite() && *x > 0.0).ok_or_else(|| bad(ID, "`scale` must be greater than zero"))?, + None => 1.0, + }; + let bytes = match p.get("data") { + Some(d) => { + base64_decode(d.as_str().ok_or_else(|| bad(ID, "`data` must be base64 text"))?).ok_or_else(|| bad(ID, "`data` is not valid base64"))? + } + None => { + let host = s.state()?.path.clone(); + read(&path, host.as_deref()).map_err(|e| bad(ID, format!("{path}: {e}")))? + } + }; + if bytes.len() as u64 > MAX_FILE_BYTES { + return Err(bad(ID, format!("the file is larger than {} MB", MAX_FILE_BYTES >> 20))); + } + let (points, total) = if bytes.starts_with(b"LASF") || lower.ends_with(".las") { + parse_las(&bytes, keep).map_err(|e| bad(ID, format!("{path}: {e}")))? + } else { + parse_xyz(&String::from_utf8_lossy(&bytes), keep) + }; + if points.is_empty() { + return Err(bad(ID, format!("{path}: no points found"))); + } + let stem = path.rsplit(['/', '\\']).next().unwrap_or(&path); + let stem = stem.rsplit_once('.').map(|(s, _)| s).filter(|s| !s.is_empty()).unwrap_or(stem); + let wanted = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| format!("PointCloud_{stem}")); + let wanted: String = wanted.chars().map(|c| if c.is_alphanumeric() || matches!(c, '_' | '-' | ' ' | '$') { c } else { '_' }).take(200).collect(); + let colored = points.iter().any(|(_, c)| c.is_some()); + let d = s.doc_mut()?; + // A taken name gets a number. + let mut name = wanted.clone(); + let mut i = 2; + while d.block(&name).is_some() && i < 100_000 { + name = format!("{wanted}_{i}"); + i += 1; + } + let mut block = Block::new(&name); + block.description = format!("Point cloud from {path}"); + let layer = d.header.str("CLAYER", "0"); + for (pt, rgb) in &points { + let mut e = Entity::new(d.new_handle(), EntityKind::Point(Point { p: *pt, angle: 0.0 })); + e.common.layer = "0".into(); + if let Some(c) = rgb { + e.common.color = Color::True(*c); + } + block.entities.push(e); + } + d.blocks.insert(name.clone(), Arc::new(block)); + let ins = Insert { + block: name.clone(), + insert: at.to3(0.0), + scale: Vec3::new(scale, scale, scale), + rotation: 0.0, + attribs: Vec::new(), + cols: 1, + rows: 1, + col_spacing: 0.0, + row_spacing: 0.0, + clip: None, + }; + let h = d.new_handle(); + let mut e = Entity::new(h, EntityKind::Insert(ins)); + e.common.layer = layer; + let space = s.space(); + if let Some(store) = s.doc_mut()?.space_mut(&space) { + store.push(e); + } + let kept = points.len(); + let message = if kept < total { + format!("Point cloud \"{name}\": {kept} of {total} points (thinned).") + } else { + format!("Point cloud \"{name}\": {kept} points.") + }; + Ok(json!({ "handle": h.hex(), "block": name, "points": kept, "total": total, "colored": colored, "message": message })) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::cmd::file::base64_encode; + + fn las(points: &[(i32, i32, i32, [u16; 3])]) -> Vec { + let mut b = vec![0u8; 227]; + b[0..4].copy_from_slice(b"LASF"); + b[24] = 1; + b[25] = 2; + b[94..96].copy_from_slice(&227u16.to_le_bytes()); + b[96..100].copy_from_slice(&227u32.to_le_bytes()); + b[104] = 2; + b[105..107].copy_from_slice(&26u16.to_le_bytes()); + b[107..111].copy_from_slice(&(points.len() as u32).to_le_bytes()); + for (i, s) in [0.01f64, 0.01, 0.01].iter().enumerate() { + b[131 + i * 8..139 + i * 8].copy_from_slice(&s.to_le_bytes()); + } + b[155..163].copy_from_slice(&1000.0f64.to_le_bytes()); + for (x, y, z, c) in points { + let mut r = vec![0u8; 26]; + r[0..4].copy_from_slice(&x.to_le_bytes()); + r[4..8].copy_from_slice(&y.to_le_bytes()); + r[8..12].copy_from_slice(&z.to_le_bytes()); + for (k, v) in c.iter().enumerate() { + r[20 + k * 2..22 + k * 2].copy_from_slice(&v.to_le_bytes()); + } + b.extend(r); + } + b + } + + #[test] + fn xyz_points_are_read_and_thinned() { + let text = "# header\n0 0 0 255 0 0\n1,2,3\nbad line\n2;4;6;10;0;255;0\nnan 1 2\n"; + let (pts, total) = parse_xyz(text, 10); + assert_eq!(total, 3); + assert_eq!(pts[0].1, Some(Rgb(255, 0, 0))); + assert_eq!(pts[1], (Vec3::new(1.0, 2.0, 3.0), None)); + assert_eq!(pts[2].1, Some(Rgb(0, 255, 0))); + let many: String = (0..1000).map(|i| format!("{i} 0 0\n")).collect(); + let (pts, total) = parse_xyz(&many, 100); + assert_eq!((pts.len(), total), (100, 1000)); + } + + #[test] + fn las_points_and_colours() { + let b = las(&[(100, 200, 300, [65535, 0, 0]), (0, 0, 0, [0, 65535, 0])]); + let (pts, total) = parse_las(&b, 10).unwrap(); + assert_eq!(total, 2); + assert_eq!(pts[0].0, Vec3::new(1001.0, 2.0, 3.0)); + assert_eq!(pts[0].1, Some(Rgb(255, 0, 0))); + // A record count larger than the file holds reads only what is there. + let mut lying = b.clone(); + lying[107..111].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(parse_las(&lying, 10).unwrap().1, 2); + // Damaged and unsupported files are refused. + assert!(parse_las(b"LASF", 10).is_err()); + let mut laz = b.clone(); + laz[104] |= 0x80; + assert!(parse_las(&laz, 10).is_err()); + let mut tiny = b; + tiny[105..107].copy_from_slice(&4u16.to_le_bytes()); + assert!(parse_las(&tiny, 10).is_err()); + } + + #[test] + fn a_cloud_is_one_block_reference() { + let mut s = Session::new(); + let data = base64_encode(b"0 0 0\n10 0 0\n10 10 5\n"); + let r = s.execute(ID, &json!({"path": "scan.xyz", "data": data, "at": [5, 5]})).unwrap(); + assert_eq!(r["points"], 3); + assert_eq!(r["block"], "PointCloud_scan"); + let r2 = s.execute(ID, &json!({"path": "scan.xyz", "data": data})).unwrap(); + assert_eq!(r2["block"], "PointCloud_scan_2"); + assert_eq!(s.doc().unwrap().model.len(), 2); + for bad in [ + json!({"path": "a.rcp"}), + json!({"path": "a.xyz", "data": base64_encode(b"no points")}), + json!({"path": "a.xyz", "data": data, "maxPoints": 0}), + ] { + assert!(s.execute(ID, &bad).is_err(), "{bad}"); + } + } +} diff --git a/crates/engine/src/cmd/sheetset.rs b/crates/engine/src/cmd/sheetset.rs new file mode 100644 index 00000000..689d0a57 --- /dev/null +++ b/crates/engine/src/cmd/sheetset.rs @@ -0,0 +1,363 @@ +//! SHEETSET (Sheet Set Manager): an ordered list of sheets, each a layout of a drawing file, +//! kept in a sheet set file of DraftCraft's own (`.dcss`, JSON; AutoCAD's `.dst` format is not +//! published). Sheets can be added, renumbered, retitled, reordered and removed, and the whole +//! set published to PDF, one file per sheet. +//! +//! The sheet set file is input like any other file: its size, its number of sheets and every +//! field are checked. A drawing inside the sheet set file's folder is stored by its relative path, +//! so the project folder can move. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::cmd::blocks::insert_file::read_drawing; +use crate::cmd::file::io; +use crate::cmd::{CommandSpec, bad, str_param}; +use crate::{Result, Session}; + +/// Most sheets in a set. +pub const MAX_SHEETS: usize = 1_000; +/// Largest sheet set file read. +const MAX_FILE_BYTES: u64 = 4 * 1024 * 1024; +/// Longest name, title, number or description kept. +const MAX_TEXT: usize = 1_000; +/// The `format` value of a sheet set file. +const FORMAT: &str = "draftcraft-sheetset"; + +/// A sheet set as saved. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SheetSet { + #[serde(default)] + pub format: String, + #[serde(default)] + pub version: u32, + #[serde(default)] + pub name: String, + #[serde(default)] + pub description: String, + #[serde(default)] + pub sheets: Vec, +} + +/// One sheet: a layout of a drawing file. +#[derive(Clone, Debug, Default, PartialEq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct Sheet { + #[serde(default)] + pub number: String, + #[serde(default)] + pub title: String, + /// The drawing, relative to the sheet set file's folder when it is inside it. + pub file: String, + pub layout: String, +} + +pub fn specs() -> Vec { + vec![ + CommandSpec::new("sheetset", "Sheet Set Manager", run_sheetset) + .menu(&["Tools", "Palettes", "Sheet Set Manager"]) + .alias(&["ssm", "opensheetset", "newsheetset"]) + .params( + "{operation: new|list|add|update|move|remove|publish, path: sheet set file (.dcss), name?, description? (new), file?: \ + drawing (add; its layouts, or `layout`), layout?, number?, title? (add, update), index?: 0-based sheet (update, move, \ + remove), to?: new index (move), output?: folder for publish (else base64 `data` per sheet), overwrite?: bool (new)} → \ + {path, name, description, sheets: [{index, number, title, file, layout}]} (publish: {sheets: [{index, layout, path? | \ + data}]})", + ) + .noundo(), + ] +} + +fn run_sheetset(s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path").filter(|x| !x.trim().is_empty()).ok_or_else(|| bad("sheetset", "`path` names the sheet set file (.dcss)"))?; + let op = str_param(p, "operation").unwrap_or("list").to_ascii_lowercase(); + let text = |k: &str| str_param(p, k).map(|v| clip(v.trim())); + let index = |set: &SheetSet| -> Result { + let i = p.get("index").and_then(Value::as_u64).ok_or_else(|| bad("sheetset", "`index` is the sheet's position, from 0"))?; + usize::try_from(i).ok().filter(|i| *i < set.sheets.len()).ok_or_else(|| bad("sheetset", format!("there is no sheet {i}"))) + }; + match op.as_str() { + "new" => { + if exists(path) && !p.get("overwrite").and_then(Value::as_bool).unwrap_or(false) { + return Err(bad("sheetset", format!("{path} already exists (pass overwrite: true to replace it)"))); + } + let name = text("name").filter(|n| !n.is_empty()).unwrap_or_else(|| stem(path)); + let set = SheetSet { format: FORMAT.into(), version: 1, name, description: text("description").unwrap_or_default(), sheets: Vec::new() }; + save(path, &set)?; + Ok(describe(path, &set, format!("Created sheet set \"{}\".", set.name))) + } + "list" | "open" => { + let set = load(path)?; + let n = set.sheets.len(); + Ok(describe(path, &set, format!("Sheet set \"{}\": {n} sheet(s).", set.name))) + } + "add" => { + let mut set = load(path)?; + let file = text("file").filter(|f| !f.is_empty()).ok_or_else(|| bad("sheetset", "`file` names the drawing whose layout is the sheet"))?; + let resolved = resolve(path, &file); + let layouts: Vec = match text("layout").filter(|l| !l.is_empty()) { + Some(l) => vec![l], + None => { + let d = read_drawing(&resolved).map_err(|e| bad("sheetset", e.to_string()))?; + let mut ls: Vec<_> = d.layouts.iter().collect(); + ls.sort_by_key(|l| l.tab_order); + ls.iter().map(|l| l.name.clone()).collect() + } + }; + if layouts.is_empty() { + return Err(bad("sheetset", format!("{file} has no layouts"))); + } + if set.sheets.len().saturating_add(layouts.len()) > MAX_SHEETS { + return Err(bad("sheetset", format!("a sheet set holds at most {MAX_SHEETS} sheets"))); + } + let stored = relative(path, &resolved); + let one = layouts.len() == 1; + for layout in layouts { + let number = if one { text("number") } else { None }.unwrap_or_else(|| (set.sheets.len() + 1).to_string()); + let title = if one { text("title") } else { None }.unwrap_or_else(|| format!("{} - {layout}", stem(&stored))); + set.sheets.push(Sheet { number, title, file: stored.clone(), layout }); + } + save(path, &set)?; + Ok(describe(path, &set, format!("Sheet set \"{}\": {} sheet(s).", set.name, set.sheets.len()))) + } + "update" => { + let mut set = load(path)?; + let i = index(&set)?; + if let Some(sh) = set.sheets.get_mut(i) { + if let Some(n) = text("number") { + sh.number = n; + } + if let Some(t) = text("title") { + sh.title = t; + } + if let Some(l) = text("layout").filter(|l| !l.is_empty()) { + sh.layout = l; + } + } + save(path, &set)?; + Ok(describe(path, &set, format!("Sheet {i} updated."))) + } + "move" => { + let mut set = load(path)?; + let i = index(&set)?; + let to = p + .get("to") + .and_then(Value::as_u64) + .and_then(|t| usize::try_from(t).ok()) + .ok_or_else(|| bad("sheetset", "`to` is the new position"))?; + let to = to.min(set.sheets.len().saturating_sub(1)); + let sh = set.sheets.remove(i); + set.sheets.insert(to, sh); + save(path, &set)?; + Ok(describe(path, &set, format!("Sheet moved to {to}."))) + } + "remove" => { + let mut set = load(path)?; + let i = index(&set)?; + let gone = set.sheets.remove(i); + save(path, &set)?; + Ok(describe(path, &set, format!("Removed sheet {} {}.", gone.number, gone.title))) + } + "publish" => publish(s, path, text("output").filter(|o| !o.is_empty())), + other => Err(bad("sheetset", format!("unknown operation \"{other}\" (new, list, add, update, move, remove, publish)"))), + } +} + +/// Plot every sheet to a PDF of its own: `/ .pdf`, or base64 data. +fn publish(_s: &mut Session, path: &str, output: Option<String>) -> Result<Value> { + if io().and_then(|h| h.plot).is_none() { + return Err(bad("sheetset", "plotting is not available in this build")); + } + let set = load(path)?; + if set.sheets.is_empty() { + return Err(bad("sheetset", "the sheet set has no sheets")); + } + let mut out = Vec::new(); + let mut cache: Option<(String, draftcraft_doc::Drawing)> = None; + for (i, sh) in set.sheets.iter().enumerate() { + let file = resolve(path, &sh.file); + let d = match cache.take() { + Some((f, d)) if f == file => d, + _ => read_drawing(&file).map_err(|e| bad("sheetset", format!("sheet {i}: {e}")))?, + }; + let mut sheet = Session::new(); + *sheet.doc_mut()? = d.clone(); + cache = Some((file, d)); + let mut q = json!({ "layout": sh.layout }); + if let Some(dir) = &output { + let name = file_part(&format!("{} {}", sh.number, sh.title)); + q["path"] = json!(std::path::Path::new(dir).join(format!("{}.pdf", name.trim())).to_string_lossy()); + } + let mut r = sheet.execute("plot", &q).map_err(|e| bad("sheetset", format!("sheet {i} ({}): {e}", sh.layout)))?; + if let Some(o) = r.as_object_mut() { + o.insert("index".into(), json!(i)); + o.insert("layout".into(), json!(sh.layout)); + } + out.push(r); + } + let message = format!("Published {} sheet(s) of \"{}\".", out.len(), set.name); + Ok(json!({ "sheets": out, "message": message })) +} + +fn describe(path: &str, set: &SheetSet, message: String) -> Value { + let sheets: Vec<Value> = set + .sheets + .iter() + .enumerate() + .map(|(i, sh)| json!({ "index": i, "number": sh.number, "title": sh.title, "file": sh.file, "layout": sh.layout })) + .collect(); + json!({ "path": path, "name": set.name, "description": set.description, "sheets": sheets, "message": message }) +} + +fn clip(s: &str) -> String { + s.chars().filter(|c| !c.is_control()).take(MAX_TEXT).collect() +} + +/// A text made safe for a file name. +fn file_part(name: &str) -> String { + name.chars().map(|c| if c.is_alphanumeric() || matches!(c, ' ' | '-' | '_' | '.') { c } else { '_' }).collect() +} + +fn stem(path: &str) -> String { + let file = path.rsplit(['/', '\\']).next().unwrap_or(path); + file.rsplit_once('.').map(|(s, _)| s).filter(|s| !s.is_empty()).unwrap_or(file).to_string() +} + +/// A sheet's drawing path as stored, against the sheet set file's folder. +fn resolve(set_path: &str, file: &str) -> String { + let f = std::path::Path::new(file); + if f.is_absolute() { + return file.to_string(); + } + match std::path::Path::new(set_path).parent() { + Some(dir) if !dir.as_os_str().is_empty() => dir.join(f).to_string_lossy().into_owned(), + _ => file.to_string(), + } +} + +/// A drawing inside the sheet set file's folder is stored by its relative path. +fn relative(set_path: &str, file: &str) -> String { + let dir = std::path::Path::new(set_path).parent().filter(|d| !d.as_os_str().is_empty()); + match dir.and_then(|d| std::path::Path::new(file).strip_prefix(d).ok()) { + Some(rel) if !rel.as_os_str().is_empty() => rel.to_string_lossy().into_owned(), + _ => file.to_string(), + } +} + +/// Check a sheet set read from a file: its format, and its size. +fn checked(mut set: SheetSet) -> Result<SheetSet> { + if set.format != FORMAT { + return Err(bad("sheetset", "not a DraftCraft sheet set file")); + } + if set.sheets.len() > MAX_SHEETS { + return Err(bad("sheetset", format!("a sheet set holds at most {MAX_SHEETS} sheets"))); + } + set.name = clip(&set.name); + set.description = clip(&set.description); + for sh in &mut set.sheets { + sh.number = clip(&sh.number); + sh.title = clip(&sh.title); + sh.file = clip(&sh.file); + sh.layout = clip(&sh.layout); + } + Ok(set) +} + +/// Parse a sheet set file's text. +pub fn parse(text: &str) -> Result<SheetSet> { + let set: SheetSet = serde_json::from_str(text).map_err(|e| bad("sheetset", format!("not a sheet set file: {e}")))?; + checked(set) +} + +#[cfg(not(target_arch = "wasm32"))] +fn exists(path: &str) -> bool { + std::path::Path::new(path).exists() +} + +#[cfg(target_arch = "wasm32")] +fn exists(_path: &str) -> bool { + false +} + +#[cfg(not(target_arch = "wasm32"))] +fn load(path: &str) -> Result<SheetSet> { + use std::io::Read; + let f = std::fs::File::open(path).map_err(|e| bad("sheetset", format!("{path}: {e}")))?; + let mut text = String::new(); + f.take(MAX_FILE_BYTES + 1).read_to_string(&mut text).map_err(|e| bad("sheetset", format!("{path}: {e}")))?; + if text.len() as u64 > MAX_FILE_BYTES { + return Err(bad("sheetset", format!("{path} is too large for a sheet set file"))); + } + parse(&text) +} + +#[cfg(target_arch = "wasm32")] +fn load(_path: &str) -> Result<SheetSet> { + Err(bad("sheetset", "sheet sets are not available on the web")) +} + +#[cfg(not(target_arch = "wasm32"))] +fn save(path: &str, set: &SheetSet) -> Result<()> { + let text = serde_json::to_string_pretty(set).map_err(|e| bad("sheetset", e.to_string()))?; + if let Some(dir) = std::path::Path::new(path).parent().filter(|d| !d.as_os_str().is_empty()) { + std::fs::create_dir_all(dir).map_err(|e| bad("sheetset", format!("{path}: {e}")))?; + } + std::fs::write(path, text).map_err(|e| bad("sheetset", format!("{path}: {e}"))) +} + +#[cfg(target_arch = "wasm32")] +fn save(_path: &str, _set: &SheetSet) -> Result<()> { + Err(bad("sheetset", "sheet sets are not available on the web")) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn dir() -> std::path::PathBuf { + let d = std::env::temp_dir().join(format!("dc-sheetset-{}-{:?}", std::process::id(), std::thread::current().id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + #[test] + fn a_sheet_set_is_built_and_edited() { + let d = dir(); + let path = d.join("Project.dcss").to_string_lossy().into_owned(); + let drawing = d.join("plans").join("A-101.dwg").to_string_lossy().into_owned(); + let mut s = Session::new(); + let r = s.execute("sheetset", &json!({"operation": "new", "path": path})).unwrap(); + assert_eq!(r["name"], "Project"); + assert!(s.execute("sheetset", &json!({"operation": "new", "path": path})).is_err(), "no silent overwrite"); + let r = s + .execute( + "sheetset", + &json!({"operation": "add", "path": path, "file": drawing, "layout": "Plan", "number": "A-101", "title": "Ground floor"}), + ) + .unwrap(); + assert_eq!(r["sheets"][0]["file"], format!("plans{}A-101.dwg", std::path::MAIN_SEPARATOR), "stored relative to the set"); + s.execute("sheetset", &json!({"operation": "add", "path": path, "file": drawing, "layout": "Roof"})).unwrap(); + s.execute("sheetset", &json!({"operation": "move", "path": path, "index": 1, "to": 0})).unwrap(); + let r = s.execute("sheetset", &json!({"operation": "update", "path": path, "index": 0, "title": "Roof plan"})).unwrap(); + assert_eq!(r["sheets"][0]["title"], "Roof plan"); + assert_eq!(r["sheets"][1]["number"], "A-101"); + let r = s.execute("sheetset", &json!({"operation": "remove", "path": path, "index": 0})).unwrap(); + assert_eq!(r["sheets"].as_array().unwrap().len(), 1); + assert!(s.execute("sheetset", &json!({"operation": "remove", "path": path, "index": 9})).is_err()); + let _ = std::fs::remove_dir_all(&d); + } + + #[test] + fn hostile_sheet_set_files_are_refused() { + assert!(parse("[]").is_err()); + assert!(parse(r#"{"format":"other","sheets":[]}"#).is_err()); + let many: Vec<Value> = (0..MAX_SHEETS + 1).map(|_| json!({"file": "a.dwg", "layout": "L"})).collect(); + assert!(parse(&json!({"format": FORMAT, "sheets": many}).to_string()).is_err()); + let long = "x".repeat(10 * MAX_TEXT); + let set = parse(&json!({"format": FORMAT, "name": long, "sheets": [{"file": "a\u{7}.dwg", "layout": "L"}]}).to_string()).unwrap(); + assert_eq!(set.name.chars().count(), MAX_TEXT); + assert_eq!(set.sheets[0].file, "a.dwg"); + } +} diff --git a/crates/engine/src/cmd/underlay.rs b/crates/engine/src/cmd/underlay.rs new file mode 100644 index 00000000..693528fb --- /dev/null +++ b/crates/engine/src/cmd/underlay.rs @@ -0,0 +1,432 @@ +//! PDF underlays (PDFATTACH, ATTACH of a PDF) and PDFIMPORT. +//! +//! An underlay is an [`Image`] whose [`Image::underlay`] names the PDF page it shows: the page is +//! measured in points (1/72 inch) and placed at a scale in drawing units per inch, so at scale 1 +//! an inch drawing shows the page at its true size (a millimetre drawing starts at 25.4). Its +//! pixels are the page rendered when the drawing opens or the PDF is attached, kept with the open +//! drawing ([`Drawing::rasters`]) and never in the file. A page that can't be read stays a frame. +//! +//! PDFIMPORT turns a PDF page (a file, or the page an underlay shows, in the underlay's place) +//! into DraftCraft objects: stroked paths become polylines and splines, filled areas solid +//! hatches and text single-line text, on the layers `PDF_Geometry`, `PDF_Solid Fills` and +//! `PDF_Text`, with the PDF's colours and line widths. +//! +//! The PDF reader is a lower layer (`draftcraft_io::pdf_read`); the app installs it with +//! [`super::file::set_pdf_hooks`]. + +use std::sync::Arc; + +use draftcraft_color::{Color, Rgb}; +use draftcraft_doc::{Common, Drawing, EntityKind, Handle, Image, ImportedShape, Lineweight, POINTS_PER_INCH, ShapeClass, Space, Underlay}; +use draftcraft_geom::{Mat3, Vec2}; +use serde_json::{Value, json}; + +use super::file::{base64_decode, pdf_hooks}; +use super::{CommandSpec, bad, bool_or, f64_or, point_param, str_param}; +use crate::{Result, Session}; + +/// Longest PDF path taken from a caller. +const MAX_PATH: usize = 4096; +/// The resolution underlays are rendered at (dots per inch of the page), at most. +pub const UNDERLAY_DPI: f64 = 150.0; +/// Most underlay pages rendered per drawing. +const MAX_PAGES_LOADED: usize = 200; + +pub fn specs() -> Vec<CommandSpec> { + vec![ + CommandSpec::new("pdfattach", "PDF Underlay...", run_pdfattach).alias(&["pdfat"]).menu(&["Insert", "PDF Underlay..."]).params( + "{path: PDF file (saved as given; a relative path is relative to this drawing's folder), data?: base64 file contents (instead of \ + reading `path`), page?: number from 1 (default 1), at?: [x,y] lower-left corner (default 0,0), scale?: drawing units per inch \ + (default: the drawing's insertion units, 25.4 for millimetres), rotation? (degrees), name?} → {name, handle, path, page, pages, \ + size: [w, h] in drawing units}", + ), + CommandSpec::new("pdfimport", "PDF Import", run_pdfimport).menu(&["Insert", "PDF Import"]).params( + "{handle?: hex of a PDF underlay (imports the page it shows, where it is; `keep?: false` also removes the underlay), \ + path?: PDF file, data?: base64 contents, page?: from 1 (default 1), at?: [x,y] (default 0,0), scale?: drawing units per inch \ + (default as PDFATTACH), rotation?, vectors?: true, fills?: true, text?: true, lineweights?: true (PDF line widths as \ + lineweights)} → {handles: [hex], counts: {vectors, fills, text}, notes: [..]}", + ), + CommandSpec::new("ulayers", "Underlay Layers", run_ulayers) + .params("{} → {underlays: [{handle, name, path, page, status: Loaded|Not Found|Not loaded}]}") + .noundo(), + ] +} + +/// Whether `ext` (lower case, no dot) is a PDF. +pub(crate) fn is_pdf_ext(ext: &str) -> bool { + ext == "pdf" +} + +/// Drawing units per inch for the drawing's insertion units (INSUNITS); without units, by +/// MEASUREMENT (25.4 for a metric drawing). +pub fn units_per_inch(d: &Drawing) -> f64 { + match d.header.i64("INSUNITS", 0) { + 1 => 1.0, + 2 => 1.0 / 12.0, + 3 => 1.0 / 63_360.0, + 4 => 25.4, + 5 => 2.54, + 6 => 0.0254, + 7 => 0.0000254, + 8 => 1_000_000.0, + 9 => 1000.0, + 10 => 1.0 / 36.0, + 14 => 254.0, + _ if d.header.i64("MEASUREMENT", 0) == 1 => 25.4, + _ => 1.0, + } +} + +/// Every underlay of `d` (model space, layouts, blocks) with its handle. +fn underlays(d: &Drawing) -> impl Iterator<Item = (Handle, &Image)> { + let stores = std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)).chain(d.blocks.values().map(|b| &b.entities)); + stores.flat_map(|s| s.iter()).filter_map(|e| match &e.kind { + EntityKind::Image(i) if i.underlay.is_some() => Some((e.handle, i)), + _ => None, + }) +} + +/// The file bytes: `data` when the caller hands them over, else the file at `path`. +fn file_bytes(s: &Session, cmd: &str, p: &Value, path: &str) -> Result<Vec<u8>> { + if let Some(data) = p.get("data") { + let text = data.as_str().ok_or_else(|| bad(cmd, "`data` must be base64 text"))?; + return base64_decode(text).ok_or_else(|| bad(cmd, "`data` is not valid base64")); + } + let host = s.state()?.path.clone(); + super::image::read_file(path, host.as_deref()).map_err(|e| bad(cmd, format!("{path}: {e}"))) +} + +fn path_param(cmd: &str, p: &Value) -> Result<String> { + let path = str_param(p, "path").map(str::trim).filter(|x| !x.is_empty()).ok_or_else(|| bad(cmd, "`path` is required"))?; + if path.len() > MAX_PATH { + return Err(bad(cmd, "`path` is too long")); + } + Ok(path.to_string()) +} + +fn page_param(cmd: &str, p: &Value) -> Result<usize> { + match p.get("page") { + None | Some(Value::Null) => Ok(0), + Some(v) => { + let n = + v.as_u64().or_else(|| v.as_str().and_then(|t| t.trim().parse().ok())).ok_or_else(|| bad(cmd, "`page` must be a number from 1"))?; + usize::try_from(n).ok().and_then(|n| n.checked_sub(1)).ok_or_else(|| bad(cmd, "`page` must be a number from 1")) + } + } +} + +/// Where and how large a page goes: lower-left corner, rotation (radians), drawing units per inch. +fn placement(s: &Session, cmd: &str, p: &Value) -> Result<(Vec2, f64, f64)> { + let at = point_param(p, "at").unwrap_or(Vec2::ZERO); + if !(at.x.is_finite() && at.y.is_finite()) { + return Err(bad(cmd, "`at` must be a point")); + } + let scale = f64_or(p, "scale", units_per_inch(s.doc()?)); + if !(scale.is_finite() && scale > 0.0) { + return Err(bad(cmd, "`scale` must be greater than zero")); + } + Ok((at, f64_or(p, "rotation", 0.0).to_radians(), scale)) +} + +/// The definition name for a new underlay: the file name without folders and extension. +fn stem(path: &str) -> String { + let file = path.rsplit(['/', '\\']).next().unwrap_or(path); + match file.rsplit_once('.') { + Some((stem, _)) if !stem.is_empty() => stem.to_string(), + _ => file.to_string(), + } +} + +const ATTACH: &str = "pdfattach"; + +pub(crate) fn run_pdfattach(s: &mut Session, p: &Value) -> Result<Value> { + let hooks = pdf_hooks().ok_or_else(|| bad(ATTACH, "PDF files can't be read in this build"))?; + let path = path_param(ATTACH, p)?; + let index = page_param(ATTACH, p)?; + let (at, rotation, scale) = placement(s, ATTACH, p)?; + let bytes = file_bytes(s, ATTACH, p, &path)?; + let pages = (hooks.pages)(&bytes).map_err(|e| bad(ATTACH, format!("{path}: {e}")))?; + let &(w, h) = pages.get(index).ok_or_else(|| bad(ATTACH, format!("{path} has {} page(s)", pages.len())))?; + let point = scale / POINTS_PER_INCH; + let u = Vec2::from_angle(rotation) * point; + if !(point.is_normal() && (point * w.max(h)).is_finite()) { + return Err(bad(ATTACH, "the page would be too small or too large to draw")); + } + let raster = (hooks.rasterize)(&bytes, index, UNDERLAY_DPI).map_err(|e| bad(ATTACH, format!("{path}: {e}")))?; + let name = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| stem(&path)); + let image = Image { + insert: at.to3(0.0), + u: u.to3(0.0), + v: u.perp().to3(0.0), + size: Vec2::new(w, h), + path: path.clone(), + name: name.clone(), + contrast: Underlay::DEFAULT_CONTRAST, + fade: Underlay::DEFAULT_FADE, + underlay: Some(Underlay { page: (index + 1).to_string(), adjust_for_background: true, ..Underlay::default() }), + ..Image::default() + }; + let key = image.raster_key(); + s.doc_mut()?.rasters.insert(&key, Arc::new(raster)); + let handle = s.add_entity(EntityKind::Image(image))?; + Ok(json!({ + "name": name, "handle": handle.hex(), "path": path, "page": index + 1, "pages": pages.len(), + "size": [w * point, h * point], + })) +} + +/// Load the pages the underlays of drawing `i` show, just opened, and give each underlay its +/// page size (the file doesn't record it). Pages that can't be read are reported and their +/// underlays stay frames; opening never fails over an underlay. +pub(crate) fn after_open(s: &mut Session, i: usize) { + let Some(hooks) = pdf_hooks() else { return }; + let Some(st) = s.docs.get(i) else { return }; + let host = st.path.clone(); + // (file, page index, raster key) of each page shown, once. + let mut wanted: Vec<(String, usize, String)> = Vec::new(); + for (_, img) in underlays(&st.doc) { + let Some(page) = img.underlay.as_ref().and_then(Underlay::page_index) else { continue }; + let key = img.raster_key(); + if !wanted.iter().any(|(_, _, k)| *k == key) { + wanted.push((img.path.clone(), page, key)); + } + } + if wanted.is_empty() { + return; + } + let mut notes = Vec::new(); + if wanted.len() > MAX_PAGES_LOADED { + wanted.truncate(MAX_PAGES_LOADED); + notes.push(format!("PDF underlays: only the first {MAX_PAGES_LOADED} pages are shown")); + } + let mut rasters = st.doc.rasters.clone(); + let mut sizes: Vec<(String, (f64, f64))> = Vec::new(); + let mut files: Vec<(String, Option<Vec<(f64, f64)>>)> = Vec::new(); + for (path, page, key) in &wanted { + let bytes = match super::image::read_file(path, host.as_deref()) { + Ok(b) => b, + Err(e) => { + notes.push(format!("PDF underlay {path}: {e}")); + continue; + } + }; + if !files.iter().any(|(p, _)| p == path) { + files.push((path.clone(), (hooks.pages)(&bytes).ok())); + } + if let Some(size) = files.iter().find(|(p, _)| p == path).and_then(|(_, pages)| pages.as_ref()?.get(*page).copied()) { + sizes.push((key.clone(), size)); + } + if rasters.get(key).is_none() { + match (hooks.rasterize)(&bytes, *page, UNDERLAY_DPI) { + Ok(r) => rasters.insert(key, Arc::new(r)), + Err(e) => notes.push(format!("PDF underlay {path}, page {}: {e}", page + 1)), + } + } + } + let Some(st) = s.docs.get_mut(i) else { return }; + // Loading pages is not a change to the drawing (see `image::after_open`). + let unchanged = Arc::ptr_eq(&st.doc, &st.saved); + let d = Arc::make_mut(&mut st.doc); + d.rasters = rasters; + apply_sizes(d, &sizes); + if unchanged { + st.saved = st.doc.clone(); + } + for n in notes { + s.echo(n); + } +} + +/// Give underlays the page sizes of `sizes` (by raster key), and their display clip. +fn apply_sizes(d: &mut Drawing, sizes: &[(String, (f64, f64))]) { + let fix = |store: &mut draftcraft_doc::EntityStore| { + let hs: Vec<Handle> = store + .iter() + .filter(|e| matches!(&e.kind, EntityKind::Image(i) if i.underlay.is_some() && sizes.iter().any(|(k, _)| *k == i.raster_key()))) + .map(|e| e.handle) + .collect(); + for h in hs { + store.modify(h, |e| { + if let EntityKind::Image(i) = &mut e.kind + && let Some((_, (w, h))) = sizes.iter().find(|(k, _)| *k == i.raster_key()) + { + i.size = Vec2::new(*w, *h); + i.clip = i.underlay_display_clip(); + } + }); + } + }; + fix(&mut d.model); + for l in &mut d.layouts { + fix(&mut l.entities); + } + for b in d.blocks.values_mut() { + if underlays_in(&b.entities) { + fix(&mut Arc::make_mut(b).entities); + } + } +} + +fn underlays_in(store: &draftcraft_doc::EntityStore) -> bool { + store.iter().any(|e| matches!(&e.kind, EntityKind::Image(i) if i.underlay.is_some())) +} + +fn run_ulayers(s: &mut Session, _p: &Value) -> Result<Value> { + let host = s.state()?.path.clone(); + let d = s.doc()?; + let rows: Vec<Value> = underlays(d) + .map(|(h, i)| { + let loaded = d.rasters.get(&i.raster_key()).is_some(); + let found = super::blocks::xref::find_file(&i.path, host.as_deref()).is_some(); + let status = if loaded { + "Loaded" + } else if found { + "Not loaded" + } else { + "Not Found" + }; + json!({ "handle": h.hex(), "name": i.name, "path": i.path, "page": i.underlay.as_ref().map(|u| u.page.clone()), "status": status }) + }) + .collect(); + Ok(json!({ "underlays": rows })) +} + +const IMPORT: &str = "pdfimport"; + +/// The transform taking a page point (x, y) to `origin + x·u + y·v`. +fn frame(u: Vec2, v: Vec2, origin: Vec2) -> Mat3 { + Mat3 { a: u.x, b: u.y, c: v.x, d: v.y, e: origin.x, f: origin.y } +} + +/// The standard lineweights in hundredths of a millimetre. +const LINEWEIGHTS: [u16; 24] = [0, 5, 9, 13, 15, 18, 20, 25, 30, 35, 40, 50, 53, 60, 70, 80, 90, 100, 106, 120, 140, 158, 200, 211]; + +/// The standard lineweight nearest a width in points; `None` for a hairline (width 0). +fn lineweight(points: f64) -> Option<Lineweight> { + if !(points.is_finite() && points > 0.0) { + return None; + } + let mm100 = points / POINTS_PER_INCH * 2540.0; + LINEWEIGHTS.iter().copied().min_by(|a, b| (f64::from(*a) - mm100).abs().total_cmp(&(f64::from(*b) - mm100).abs())).map(Lineweight::Mm100) +} + +/// A PDF colour as a drawing colour: black and white follow the background (colour 7), others +/// stay true colours. +fn color(c: Option<Rgb>) -> Color { + match c { + None => Color::ByLayer, + Some(Rgb(0, 0, 0)) => Color::Index(7), + Some(rgb) => Color::True(rgb), + } +} + +fn layer_of(class: ShapeClass) -> &'static str { + match class { + ShapeClass::Vector => "PDF_Geometry", + ShapeClass::Fill => "PDF_Solid Fills", + ShapeClass::Text => "PDF_Text", + } +} + +fn run_pdfimport(s: &mut Session, p: &Value) -> Result<Value> { + let hooks = pdf_hooks().ok_or_else(|| bad(IMPORT, "PDF files can't be read in this build"))?; + let opts = (bool_or(p, "vectors", true), bool_or(p, "fills", true), bool_or(p, "text", true)); + // The page and where it goes: from an underlay, or from the parameters. + let (bytes, page, place, from) = match str_param(p, "handle") { + Some(hex) => { + let h = Handle::parse_hex(hex.trim()).ok_or_else(|| bad(IMPORT, "`handle` must be a hex handle"))?; + let d = s.doc()?; + let space = s.space(); + let store = d.space(&space).ok_or_else(|| bad(IMPORT, "no current space"))?; + let img = match store.get(h).map(|e| &e.kind) { + Some(EntityKind::Image(i)) if i.underlay.is_some() => i.clone(), + _ => return Err(bad(IMPORT, format!("{hex} is not a PDF underlay in the current space"))), + }; + let page = img.underlay.as_ref().and_then(Underlay::page_index).unwrap_or(0); + // A point of the page to the drawing: the underlay's own placement. + let m = frame(img.u.xy(), img.v.xy(), img.insert.xy()); + let bytes = file_bytes(s, IMPORT, &json!({}), &img.path)?; + (bytes, page, m, Some(h)) + } + None => { + let path = if p.get("data").is_some() { str_param(p, "path").unwrap_or("data.pdf").to_string() } else { path_param(IMPORT, p)? }; + let page = page_param(IMPORT, p)?; + let (at, rotation, scale) = placement(s, IMPORT, p)?; + let point = scale / POINTS_PER_INCH; + let u = Vec2::from_angle(rotation) * point; + let m = frame(u, u.perp(), at); + (file_bytes(s, IMPORT, p, &path)?, page, m, None) + } + }; + let (shapes, images, truncated) = (hooks.import)(&bytes, page, opts.0, opts.1, opts.2).map_err(|e| bad(IMPORT, e))?; + let lineweights = bool_or(p, "lineweights", true); + let base = s.current_common(); + let space: Space = s.space(); + let mut handles = Vec::new(); + let (mut vectors, mut fills, mut texts) = (0usize, 0usize, 0usize); + for ImportedShape { mut kind, color: c, width, class } in shapes { + kind.transform(&place); + let common = Common { + layer: layer_of(class).to_string(), + color: color(c), + lineweight: if lineweights && class == ShapeClass::Vector { + lineweight(width).unwrap_or(Lineweight::ByLayer) + } else { + Lineweight::ByLayer + }, + ..base.clone() + }; + match class { + ShapeClass::Vector => vectors += 1, + ShapeClass::Fill => fills += 1, + ShapeClass::Text => texts += 1, + } + handles.push(s.doc_mut()?.add(&space, common, kind)?.hex()); + } + let mut notes = Vec::new(); + if images > 0 { + notes.push(format!("{images} raster image(s) of the page were not imported")); + } + if truncated { + notes.push("the page has more content than PDFIMPORT reads; the rest was left out".to_string()); + } + if let Some(h) = from + && !bool_or(p, "keep", true) + { + s.doc_mut()?.space_mut(&space).map(|st| st.remove(h)); + } + for n in ¬es { + s.echo(format!("PDFIMPORT: {n}")); + } + Ok(json!({ "handles": handles, "counts": { "vectors": vectors, "fills": fills, "text": texts }, "notes": notes })) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn lineweights_round_to_the_standard_ones() { + assert_eq!(lineweight(0.0), None); + // 1 point is 0.3528 mm. + assert_eq!(lineweight(1.0), Some(Lineweight::Mm100(35))); + assert_eq!(lineweight(100.0), Some(Lineweight::Mm100(211))); + } + + #[test] + fn units_per_inch_follow_insunits() { + let mut d = Drawing::new_metric(); + assert_eq!(units_per_inch(&d), 25.4); + d.header.set_i64("INSUNITS", 1); + assert_eq!(units_per_inch(&d), 1.0); + d.header.set_i64("INSUNITS", 6); + assert!((units_per_inch(&d) - 0.0254).abs() < 1e-12); + } + + #[test] + fn black_follows_the_background() { + assert_eq!(color(Some(Rgb(0, 0, 0))), Color::Index(7)); + assert_eq!(color(Some(Rgb(1, 2, 3))), Color::True(Rgb(1, 2, 3))); + assert_eq!(color(None), Color::ByLayer); + } +} diff --git a/crates/engine/src/lib.rs b/crates/engine/src/lib.rs index 4f881d59..15c737fa 100644 --- a/crates/engine/src/lib.rs +++ b/crates/engine/src/lib.rs @@ -122,6 +122,8 @@ pub struct Session { picked_viewport: Option<snap::ViewportPoint>, /// The last drawing comparison (COMPARE), drawn over the drawing it was made for. pub compare: Option<cmd::file::compare::Comparison>, + /// LAYWALK: which layers were on before the walk began, restored when it ends. + pub laywalk: Option<Vec<(String, bool)>>, /// Object snap tracking: acquired points and the path under the cursor (from the UI's /// [`Session::snap_cursor`] calls; direct distance entry follows the path). pub tracking: snap::tracking::Tracker, @@ -191,6 +193,7 @@ impl Session { ctrl_down: false, picked_viewport: None, compare: None, + laywalk: None, tracking: snap::tracking::Tracker::default(), viewport_px: (1200.0, 800.0), clipboard: Vec::new(), diff --git a/crates/engine/tests/dynblock_authoring.rs b/crates/engine/tests/dynblock_authoring.rs new file mode 100644 index 00000000..bbe60189 --- /dev/null +++ b/crates/engine/tests/dynblock_authoring.rs @@ -0,0 +1,62 @@ +//! A block made dynamic in the Block Editor (BPARAMETER, BACTION) keeps its parameters and +//! actions through a DXF save, and its references stretch after reopening. +//! +//! A DWG save doesn't keep them yet: the DWG writer (acadrust) writes another program's objects +//! only from their original DWG data, which objects made here don't have. + +use draftcraft_engine::Session; +use draftcraft_engine::cmd::file::{IoHooks, set_io}; +use draftcraft_engine::doc::EntityKind; +use serde_json::json; + +fn hooks() { + set_io(IoHooks { + read: |b, name| draftcraft_io::read(b, name).map_err(|e| e.to_string()), + write: |d, name| draftcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: None, + }); +} + +#[test] +fn an_authored_dynamic_block_survives_save_and_reopen() { + hooks(); + let dir = std::env::temp_dir().join(format!("draftcraft-dynauthor-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + for ext in ["dxf"] { + let mut s = Session::new(); + let mut hs = Vec::new(); + for (a, b) in [([0, 0], [10, 0]), ([10, 0], [10, 5]), ([10, 5], [0, 5]), ([0, 5], [0, 0])] { + let r = s.execute("line", &json!({ "points": [a, b] })).unwrap(); + hs.push(r["handles"][0].as_str().or_else(|| r["handle"].as_str()).unwrap().to_string()); + } + s.execute("block", &json!({ "name": "PANEL", "base": [0, 0], "handles": hs, "retain": false })).unwrap(); + s.execute("insert", &json!({ "name": "PANEL", "at": [100, 0] })).unwrap(); + s.execute("bedit", &json!({ "name": "PANEL" })).unwrap(); + let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("bparameter", &json!({ "type": "linear", "base": [0, 0], "end": [10, 0], "label": "Width" })).unwrap(); + s.execute("baction", &json!({ "type": "stretch", "parameter": "Width", "frame": [[8, -1], [12, 6]], "handles": hs })).unwrap(); + s.execute("bclose", &json!({ "save": true })).unwrap(); + let path = dir.join(format!("panel.{ext}")); + s.execute("saveas", &json!({ "path": path.to_string_lossy() })).unwrap(); + + let mut s = Session::new(); + s.execute("open", &json!({ "path": path.to_string_lossy() })).unwrap(); + let m = draftcraft_engine::doc::dynblock::dynamic_block(s.doc().unwrap(), "PANEL").unwrap_or_else(|| panic!("{ext}: not dynamic")); + assert_eq!((m.parameters.len(), m.actions.len()), (1, 1), "{ext}"); + assert_eq!(m.actions[0].selection.len(), 4, "{ext}: the action keeps its objects"); + let ins = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Insert(_))).unwrap().handle; + let d = s.doc_mut().unwrap(); + draftcraft_engine::doc::dynblock::set_property(d, ins, "Width", "25").unwrap(); + let EntityKind::Insert(i) = &d.entity(ins).unwrap().kind else { panic!("insert") }; + let xs: Vec<f64> = d + .block(&i.block) + .unwrap() + .entities + .iter() + .filter_map(|e| if let EntityKind::Line(l) = &e.kind { Some(l.a.x.max(l.b.x)) } else { None }) + .collect(); + assert!(xs.iter().any(|x| (x - 25.0).abs() < 1e-9), "{ext}: {xs:?}"); + } + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/engine/tests/image_attach.rs b/crates/engine/tests/image_attach.rs index 6da6fb47..1bb58114 100644 --- a/crates/engine/tests/image_attach.rs +++ b/crates/engine/tests/image_attach.rs @@ -139,7 +139,7 @@ fn bad_input_is_refused_and_changes_nothing() { assert!(s.execute("imageattach", &p).is_err(), "{p}"); } assert!(images(&s).is_empty()); - assert!(s.execute("attach", &json!({ "path": "plan.pdf" })).unwrap_err().to_string().contains("not available yet")); + assert!(s.execute("attach", &json!({ "path": "plan.dwf" })).unwrap_err().to_string().contains("not available yet")); assert_eq!(listed(&mut s), json!([])); } diff --git a/crates/engine/tests/pdf_underlay.rs b/crates/engine/tests/pdf_underlay.rs new file mode 100644 index 00000000..30a68af7 --- /dev/null +++ b/crates/engine/tests/pdf_underlay.rs @@ -0,0 +1,191 @@ +//! PDF underlays and PDFIMPORT: attaching a page (from a file and from handed-over bytes), the +//! DXF it saves as (PDFUNDERLAY, PDFDEFINITION, ACAD_PDFDEFINITIONS), the page found and drawn +//! again when the drawing is reopened, and a page imported as objects. + +use std::path::{Path, PathBuf}; + +use draftcraft_engine::Session; +use draftcraft_engine::cmd::file::{IoHooks, PdfHooks, base64_encode, set_io, set_pdf_hooks}; +use draftcraft_engine::doc::{EntityKind, Image}; +use serde_json::json; + +fn hooks() { + set_io(IoHooks { + read: |b, name| draftcraft_io::read(b, name).map_err(|e| e.to_string()), + write: |d, name| draftcraft_io::write(d, name).map_err(|e| e.to_string()), + plot: None, + }); + set_pdf_hooks(PdfHooks { + pages: |b| draftcraft_io::pdf_read::pages(b).map_err(|e| e.to_string()), + rasterize: |b, page, dpi| draftcraft_io::pdf_read::rasterize(b, page, dpi).map_err(|e| e.to_string()), + import: draftcraft_io::pdf_read::import_flat, + }); +} + +fn folder(tag: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("draftcraft-pdf-{}-{tag}", std::process::id())); + let _ = std::fs::remove_dir_all(&dir); + std::fs::create_dir_all(&dir).unwrap(); + dir +} + +/// A two-page PDF (US Letter, then A4 landscape) with a blue line, a red square and a text. +fn pdf() -> Vec<u8> { + let content = b"q 2 w 0 0 1 RG 72 72 m 144 72 l S 1 0 0 rg 200 200 50 50 re f Q BT /F1 12 Tf 72 300 Td (Plan) Tj ET"; + let mut objs: Vec<Vec<u8>> = vec![ + b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(), + b"<< /Type /Pages /Kids [3 0 R 6 0 R] /Count 2 >>".to_vec(), + b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".to_vec(), + ]; + let mut stream = format!("<< /Length {} >>\nstream\n", content.len()).into_bytes(); + stream.extend_from_slice(content); + stream.extend_from_slice(b"\nendstream"); + objs.push(stream); + objs.push(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec()); + objs.push(b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 842 595] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".to_vec()); + let mut out = b"%PDF-1.4\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for off in offsets { + out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out +} + +fn underlays(s: &Session) -> Vec<Image> { + s.doc() + .unwrap() + .model + .iter() + .filter_map(|e| if let EntityKind::Image(i) = &e.kind { i.underlay.as_ref().map(|_| i.clone()) } else { None }) + .collect() +} + +fn open(s: &mut Session, path: &Path) { + s.execute("open", &json!({ "path": path.to_string_lossy() })).unwrap(); +} + +#[test] +fn attach_places_the_page_at_its_true_size() { + hooks(); + let mut s = Session::new(); + // A new session's drawing is in inches: a US Letter page is 8.5 × 11. + let r = s.execute("pdfattach", &json!({ "path": "plans/site.pdf", "data": base64_encode(&pdf()), "at": [10, 20] })).unwrap(); + assert_eq!((r["name"].as_str(), r["page"].as_u64(), r["pages"].as_u64()), (Some("site"), Some(1), Some(2))); + let size: Vec<f64> = r["size"].as_array().unwrap().iter().map(|v| v.as_f64().unwrap()).collect(); + assert!((size[0] - 8.5).abs() < 1e-9 && (size[1] - 11.0).abs() < 1e-9, "{size:?}"); + let u = underlays(&s).pop().unwrap(); + assert_eq!((u.insert.x, u.insert.y, u.size.x, u.size.y), (10.0, 20.0, 612.0, 792.0)); + assert_eq!(u.underlay.as_ref().unwrap().page, "1"); + assert!(s.doc().unwrap().rasters.get(&u.raster_key()).is_some()); + assert_eq!(s.doc().unwrap().model.iter().next().unwrap().kind.type_name(), "PDF Underlay"); + + // The second page, by ATTACH, at an explicit scale and rotation. + s.execute("attach", &json!({ "path": "plans/site.pdf", "data": base64_encode(&pdf()), "page": 2, "scale": 1, "rotation": 90 })).unwrap(); + let u = underlays(&s).pop().unwrap(); + assert_eq!((u.size.x, u.size.y), (842.0, 595.0)); + assert!(u.u.x.abs() < 1e-12 && (u.u.y - 1.0 / 72.0).abs() < 1e-12, "{u:?}"); + // It draws with its pixels. + let list = + draftcraft_engine::render::build(s.doc().unwrap(), &draftcraft_engine::doc::Space::Model, &draftcraft_engine::render::Options::default()); + assert_eq!(list.images.len(), 2); + + for bad in [json!({ "path": "x.pdf", "data": base64_encode(b"not a pdf") }), json!({ "path": "x.pdf", "data": base64_encode(&pdf()), "page": 3 })] + { + assert!(s.execute("pdfattach", &bad).is_err(), "{bad}"); + } + assert!(s.execute("pdfattach", &json!({ "path": "x.pdf", "data": base64_encode(&pdf()), "page": 0 })).is_err()); +} + +#[test] +fn an_underlay_survives_save_and_reopen_and_finds_its_page() { + hooks(); + let dir = folder("reopen"); + std::fs::write(dir.join("site.pdf"), pdf()).unwrap(); + let dwg = dir.join("plan.dxf"); + let mut s = Session::new(); + s.execute("saveas", &json!({ "path": dwg.to_string_lossy() })).unwrap(); + s.execute("pdfattach", &json!({ "path": "site.pdf", "page": 2, "at": [5, 6], "scale": 2, "rotation": 30 })).unwrap(); + s.execute("qsave", &json!({})).unwrap(); + let text = std::fs::read_to_string(&dwg).unwrap(); + for needed in ["PDFUNDERLAY", "PDFDEFINITION", "ACAD_PDFDEFINITIONS", "AcDbUnderlayReference", "AcDbUnderlayDefinition", "AcDbPdfReference"] { + assert!(text.contains(needed), "{needed} missing"); + } + assert!(!text.contains("\nIMAGEDEF\r\n") && !text.contains("\nIMAGEDEF\n"), "an underlay is not an image"); + + let mut s = Session::new(); + open(&mut s, &dwg); + let u = underlays(&s).pop().unwrap(); + assert_eq!((u.path.as_str(), u.underlay.as_ref().unwrap().page.as_str()), ("site.pdf", "2")); + assert_eq!((u.size.x, u.size.y), (842.0, 595.0), "the page size comes from the PDF"); + assert!((u.insert.x - 5.0).abs() < 1e-9 && (u.insert.y - 6.0).abs() < 1e-9); + let a = 30f64.to_radians(); + assert!((u.u.x - a.cos() * 2.0 / 72.0).abs() < 1e-9 && (u.u.y - a.sin() * 2.0 / 72.0).abs() < 1e-9, "{u:?}"); + assert!(s.doc().unwrap().rasters.get(&u.raster_key()).is_some(), "the page is drawn again"); + assert!(!s.state().unwrap().is_dirty(), "loading the page is not a change"); + let listed = s.execute("ulayers", &json!({})).unwrap(); + assert_eq!(listed["underlays"][0]["status"], "Loaded"); + + // Without its PDF, the underlay stays in the drawing (and in the file when saved again). + std::fs::remove_file(dir.join("site.pdf")).unwrap(); + let mut s = Session::new(); + open(&mut s, &dwg); + assert_eq!(underlays(&s).len(), 1); + assert_eq!(s.execute("ulayers", &json!({})).unwrap()["underlays"][0]["status"], "Not Found"); + let again = dir.join("again.dxf"); + s.execute("saveas", &json!({ "path": again.to_string_lossy() })).unwrap(); + assert!(std::fs::read_to_string(&again).unwrap().contains("PDFUNDERLAY")); + let _ = std::fs::remove_dir_all(&dir); +} + +#[test] +fn pdfimport_turns_a_page_into_objects() { + hooks(); + let mut s = Session::new(); + s.execute("pdfattach", &json!({ "path": "site.pdf", "data": base64_encode(&pdf()), "at": [100, 0], "scale": 72 })).unwrap(); + // The underlay's page from its file: the test hands the bytes over instead. + let r = s.execute("pdfimport", &json!({ "path": "site.pdf", "data": base64_encode(&pdf()), "at": [100, 0], "scale": 72 })).unwrap(); + assert_eq!(r["counts"], json!({ "vectors": 1, "fills": 1, "text": 1 })); + let d = s.doc().unwrap(); + let mut layers: Vec<String> = d.model.iter().filter(|e| !matches!(e.kind, EntityKind::Image(_))).map(|e| e.common.layer.clone()).collect(); + layers.sort(); + assert_eq!(layers, ["PDF_Geometry", "PDF_Solid Fills", "PDF_Text"]); + // At 72 units per inch one point is one unit: the line runs from (172, 72) to (244, 72). + let line = d.model.iter().find_map(|e| if let EntityKind::LwPolyline(p) = &e.kind { Some(p.clone()) } else { None }).unwrap(); + let pts: Vec<(f64, f64)> = line.vertices.iter().map(|v| (v.p.x, v.p.y)).collect(); + assert_eq!(pts, [(172.0, 72.0), (244.0, 72.0)]); + let text = d.model.iter().find_map(|e| if let EntityKind::Text(t) = &e.kind { Some(t.clone()) } else { None }).unwrap(); + assert_eq!(text.value, "Plan"); + assert!((text.insert.x - 172.0).abs() < 1e-6 && (text.insert.y - 300.0).abs() < 1e-6); + // Undo takes the whole import back in one step. + s.execute("undo", &json!({})).unwrap(); + assert_eq!(s.doc().unwrap().model.len(), 1); + assert!(s.execute("pdfimport", &json!({ "handle": "FFFFF" })).is_err()); +} + +#[test] +fn an_underlay_survives_a_dwg_round_trip() { + hooks(); + let dir = folder("dwg"); + std::fs::write(dir.join("site.pdf"), pdf()).unwrap(); + let dwg = dir.join("plan.dwg"); + let mut s = Session::new(); + s.execute("saveas", &json!({ "path": dwg.to_string_lossy() })).unwrap(); + s.execute("pdfattach", &json!({ "path": "site.pdf", "page": 2, "at": [5, 6], "scale": 2 })).unwrap(); + s.execute("qsave", &json!({})).unwrap(); + let mut s = Session::new(); + open(&mut s, &dwg); + let u = underlays(&s).pop().expect("the underlay is in the DWG"); + assert_eq!((u.path.as_str(), u.underlay.as_ref().unwrap().page.as_str()), ("site.pdf", "2")); + assert_eq!((u.size.x, u.size.y), (842.0, 595.0)); + assert!((u.insert.x - 5.0).abs() < 1e-9 && (u.u.x - 2.0 / 72.0).abs() < 1e-9, "{u:?}"); + let _ = std::fs::remove_dir_all(&dir); +} diff --git a/crates/io/Cargo.toml b/crates/io/Cargo.toml index deb7b606..62360e01 100644 --- a/crates/io/Cargo.toml +++ b/crates/io/Cargo.toml @@ -20,7 +20,9 @@ thiserror = { workspace = true } serde_json = { workspace = true } serde = { workspace = true } miniz_oxide = "0.9" -craft-pdf = { workspace = true, features = ["write"] } +craft-pdf = { workspace = true, features = ["write", "raster"] } +# PDF paths as the PDF reader hands them over (PDFIMPORT); the version craft-pdf's reader uses. +kurbo = "0.13" quick-xml = { workspace = true } image = { workspace = true } diff --git a/crates/io/src/dxf_image.rs b/crates/io/src/dxf_image.rs index 26c52033..5756b3fe 100644 --- a/crates/io/src/dxf_image.rs +++ b/crates/io/src/dxf_image.rs @@ -233,7 +233,8 @@ pub(crate) fn plan<'a>(entities: impl Iterator<Item = &'a draftcraft_doc::Entity let mut next_suffix: HashMap<String, usize> = HashMap::new(); for e in entities { let EntityKind::Image(i) = &e.kind else { continue }; - if p.by_entity.contains_key(&e.handle) { + // Underlays have definitions of their own (`dxf_underlay`). + if i.underlay.is_some() || p.by_entity.contains_key(&e.handle) { continue; } let k = (i.path.clone(), i.name.clone()); diff --git a/crates/io/src/dxf_raw.rs b/crates/io/src/dxf_raw.rs index bffa0cdd..6cce287c 100644 --- a/crates/io/src/dxf_raw.rs +++ b/crates/io/src/dxf_raw.rs @@ -34,6 +34,7 @@ const MODELLED_KEYS: &[&str] = &[ "ACAD_TABLESTYLE", "ACAD_IMAGE_DICT", "ACAD_IMAGE_VARS", + "ACAD_PDFDEFINITIONS", ]; /// Extension dictionary entries not kept raw: dimension associativity (DraftCraft reads and diff --git a/crates/io/src/dxf_read.rs b/crates/io/src/dxf_read.rs index aaa695e3..a45c1390 100644 --- a/crates/io/src/dxf_read.rs +++ b/crates/io/src/dxf_read.rs @@ -130,6 +130,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize) -> Result<Drawing> { apply_sortents(&mut d, &objs.sortents, &rx.brs, &paper_block_for, &first_layout); objs.apply(&mut d, &rx); crate::dxf_image::resolve(&secs, &mut d); + crate::dxf_underlay::resolve(&secs, &mut d); crate::dxf_mline::resolve(&secs, &mut d); // Keep handles unique against the header's seed. let seed = d.header.str("HANDSEED", ""); diff --git a/crates/io/src/dxf_read/entities.rs b/crates/io/src/dxf_read/entities.rs index d45121b8..c0c2e079 100644 --- a/crates/io/src/dxf_read/entities.rs +++ b/crates/io/src/dxf_read/entities.rs @@ -274,6 +274,8 @@ pub(super) fn entity_with_table_budget(kind: &str, tags: &[Tag], table_cells_lef } // The file path comes from the IMAGEDEF object (`dxf_image::resolve`). "IMAGE" => EntityKind::Image(crate::dxf_image::read_entity(tags)), + // The file and page come from the PDFDEFINITION object (`dxf_underlay::resolve`). + "PDFUNDERLAY" => EntityKind::Image(crate::dxf_underlay::read_entity(tags)), "TOLERANCE" => { let dir = t.p(11); let dir = if dir.xy().is_finite() && dir.xy().len() > 1e-12 { dir } else { Vec3::new(1.0, 0.0, 0.0) }; diff --git a/crates/io/src/dxf_underlay.rs b/crates/io/src/dxf_underlay.rs new file mode 100644 index 00000000..f4fb455e --- /dev/null +++ b/crates/io/src/dxf_underlay.rs @@ -0,0 +1,334 @@ +//! PDF underlays in DXF (DXF Reference: UNDERLAY entity, UNDERLAYDEFINITION object). A +//! PDFUNDERLAY entity holds the placement, clip boundary and display settings; it points (group +//! 340) to a PDFDEFINITION object holding the file and the page, which the `ACAD_PDFDEFINITIONS` +//! dictionary names. +//! +//! DraftCraft keeps an underlay as an [`Image`] whose [`Image::underlay`] is set: one "pixel" is +//! one PDF point (1/72 inch), so the reference's scale (drawing units per inch, groups 41/42) is +//! 72 times a point's length. The page size isn't in the file; it is filled in when the PDF is +//! read (`draftcraft_engine::cmd::underlay`). The clip boundary (groups 11/21) is in the +//! underlay's own units (inches from the insertion point, before scale and rotation) and is +//! written back as read. + +use std::collections::{HashMap, HashSet}; +use std::sync::Arc; + +use draftcraft_doc::{Drawing, EntityKind, EntityStore, Handle, Image, POINTS_PER_INCH, Underlay, UnderlayKind}; +use draftcraft_dxf::{Section, Tag}; +use draftcraft_geom::{Vec2, Vec3}; + +/// Most clip boundary vertices kept per underlay (hostile files). +const MAX_CLIP: usize = 100_000; +/// The named object dictionary key of the PDF definitions. +pub(crate) const DICT_KEY: &str = "ACAD_PDFDEFINITIONS"; + +/// Reference flags (group 280). +const FLAG_CLIP: i64 = 1; +const FLAG_ON: i64 = 2; +const FLAG_MONO: i64 = 4; +const FLAG_ADJUST: i64 = 8; + +fn key(s: &str) -> String { + s.trim().to_ascii_uppercase() +} + +/// Whether `kind` (a record's DXF type) is an underlay reference DraftCraft models. +pub(crate) fn is_reference(kind: &str) -> bool { + kind.eq_ignore_ascii_case("PDFUNDERLAY") +} + +/// The PDFUNDERLAY entity's own groups (after the `AcDbUnderlayReference` marker when present). +/// The file and page come from its definition ([`resolve`]); the page size from the PDF. +pub(crate) fn read_entity(tags: &[Tag]) -> Image { + let start = tags.iter().position(|t| t.code == 100 && t.str() == "AcDbUnderlayReference").unwrap_or(0); + let tags = tags.get(start..).unwrap_or(&[]); + let f = |c: i32| tags.iter().find(|t| t.code == c).map(Tag::f64).filter(|v| v.is_finite()); + let i = |c: i32| tags.iter().find(|t| t.code == c).map(Tag::i64); + let pct = |c: i32, d: u8| i(c).and_then(|v| u8::try_from(v.clamp(0, 100)).ok()).unwrap_or(d); + let insert = Vec3::new(f(10).unwrap_or(0.0), f(20).unwrap_or(0.0), f(30).unwrap_or(0.0)); + let nonzero = |v: Option<f64>| v.filter(|s| *s != 0.0).unwrap_or(1.0); + let (sx, sy) = (nonzero(f(41)), nonzero(f(42))); + let rot = f(50).unwrap_or(0.0).to_radians(); + let dir = Vec2::from_angle(rot); + let flags = i(280).unwrap_or(FLAG_ON); + let xs = tags.iter().filter(|t| t.code == 11).map(Tag::f64); + let ys = tags.iter().filter(|t| t.code == 21).map(Tag::f64); + let clip: Vec<Vec2> = xs.zip(ys).take(MAX_CLIP).map(|(x, y)| Vec2::new(x, y)).filter(|q| q.x.is_finite() && q.y.is_finite()).collect(); + Image { + insert, + u: (dir * (sx / POINTS_PER_INCH)).to3(0.0), + v: (dir.perp() * (sy / POINTS_PER_INCH)).to3(0.0), + // Unknown until the PDF is read. + size: Vec2::ZERO, + clipping: flags & FLAG_CLIP != 0, + display: if flags & FLAG_ON != 0 { 7 } else { 6 }, + contrast: pct(281, Underlay::DEFAULT_CONTRAST), + fade: pct(282, 0), + underlay: Some(Underlay { + kind: UnderlayKind::Pdf, + page: String::new(), + monochrome: flags & FLAG_MONO != 0, + adjust_for_background: flags & FLAG_ADJUST != 0, + clip, + }), + ..Image::default() + } +} + +/// Call `f` with each record (`0 TYPE` and the groups after it) of a section, without copying. +fn each_record<'a>(tags: &'a [Tag], mut f: impl FnMut(&str, &'a [Tag])) { + let mut open: Option<(String, usize)> = None; + for (i, t) in tags.iter().enumerate() { + if t.code == 0 { + if let Some((k, s)) = open.take() { + f(&k, tags.get(s..i).unwrap_or(&[])); + } + open = Some((t.str(), i + 1)); + } + } + if let Some((k, s)) = open { + f(&k, tags.get(s..).unwrap_or(&[])); + } +} + +/// A PDFDEFINITION object's data. +#[derive(Default)] +struct Def { + name: String, + path: String, + page: String, +} + +fn is_underlay(e: &draftcraft_doc::Entity) -> bool { + matches!(&e.kind, EntityKind::Image(i) if i.underlay.is_some()) +} + +fn has_underlays(store: &EntityStore) -> bool { + store.iter().any(|e| is_underlay(e)) +} + +/// Fill in each underlay's file, page and name from the definition it points to. +pub(crate) fn resolve(secs: &[Section], d: &mut Drawing) { + if !has_underlays(&d.model) && !d.layouts.iter().any(|l| has_underlays(&l.entities)) && !d.blocks.values().any(|b| has_underlays(&b.entities)) { + return; + } + // Reference handle → definition handle. + let mut refs: HashMap<Handle, String> = HashMap::new(); + for s in secs.iter().filter(|s| s.name == "ENTITIES" || s.name == "BLOCKS") { + each_record(&s.tags, |kind, tags| { + if !is_reference(kind) { + return; + } + let h = tags.iter().find(|t| t.code == 5).and_then(|t| Handle::parse_hex(&t.str())); + let def = tags.iter().find(|t| t.code == 340).map(|t| key(&t.str())); + if let (Some(h), Some(def)) = (h, def) { + refs.insert(h, def); + } + }); + } + let mut defs: HashMap<String, Def> = HashMap::new(); + let mut names: HashMap<String, String> = HashMap::new(); + for s in secs.iter().filter(|s| s.name == "OBJECTS") { + each_record(&s.tags, |kind, tags| match kind { + "PDFDEFINITION" => { + let Some(h) = tags.iter().find(|t| t.code == 5).map(|t| key(&t.str())) else { return }; + let start = tags.iter().position(|t| t.code == 100 && t.str() == "AcDbUnderlayDefinition").unwrap_or(0); + let body = tags.get(start..).unwrap_or(&[]); + let s = |c: i32| body.iter().find(|t| t.code == c).map(Tag::str).unwrap_or_default(); + defs.insert(h, Def { path: s(1), page: s(2), ..Def::default() }); + } + "DICTIONARY" => { + let mut name: Option<String> = None; + for t in tags { + match t.code { + 3 => name = Some(t.str()), + 350 | 360 => { + if let Some(n) = name.take() { + names.insert(key(&t.str()), n); + } + } + _ => {} + } + } + } + _ => {} + }); + } + for (h, def) in &mut defs { + if let Some(n) = names.get(h) { + def.name = n.clone(); + } + } + let by_ref: HashMap<Handle, &Def> = refs.iter().filter_map(|(r, dh)| Some((*r, defs.get(dh)?))).collect(); + if by_ref.is_empty() { + return; + } + // A shared budget on the strings copied into references (see `dxf_image::resolve`). + let mut budget: usize = 64 << 20; + fill(&mut d.model, &by_ref, &mut budget); + for l in &mut d.layouts { + fill(&mut l.entities, &by_ref, &mut budget); + } + for b in d.blocks.values_mut() { + if b.entities.iter().any(|e| is_underlay(e) && by_ref.contains_key(&e.handle)) { + fill(&mut Arc::make_mut(b).entities, &by_ref, &mut budget); + } + } +} + +fn fill(store: &mut EntityStore, by_ref: &HashMap<Handle, &Def>, budget: &mut usize) { + let hs: Vec<Handle> = store.iter().filter(|e| is_underlay(e) && by_ref.contains_key(&e.handle)).map(|e| e.handle).collect(); + for h in hs { + let Some(def) = by_ref.get(&h) else { continue }; + let cost = def.path.len() + def.name.len() + def.page.len(); + let Some(left) = budget.checked_sub(cost) else { return }; + *budget = left; + store.modify(h, |e| { + if let EntityKind::Image(i) = &mut e.kind + && let Some(u) = &mut i.underlay + { + i.path = def.path.clone(); + i.name = def.name.clone(); + u.page = def.page.clone(); + } + }); + } +} + +/// One PDFDEFINITION to write, shared by the references to the same file, page and name. +struct PlannedDef { + handle: String, + name: String, + path: String, + page: String, +} + +/// The objects behind a drawing's underlays, with handles allocated before anything is written. +#[derive(Default)] +pub(crate) struct Plan { + /// Reference entity → its definition's handle. + pub by_entity: HashMap<Handle, String>, + defs: Vec<PlannedDef>, + /// The `ACAD_PDFDEFINITIONS` dictionary. + pub dict: String, +} + +impl Plan { + pub fn is_empty(&self) -> bool { + self.defs.is_empty() + } +} + +/// The definition's name: the underlay's own, else the file name without extension, with the +/// page after it when it isn't the first ("plan - 2"). +fn def_name(i: &Image, page: &str) -> String { + let n = i.name.trim(); + if !n.is_empty() { + return n.to_string(); + } + let file = i.path.rsplit(['/', '\\']).next().unwrap_or(""); + let stem = file.rsplit_once('.').map(|(s, _)| s).unwrap_or(file).trim(); + let stem = if stem.is_empty() { "PDF" } else { stem }; + match page.trim() { + "" | "1" => stem.to_string(), + p => format!("{stem} - {p}"), + } +} + +/// Allocate the definition and dictionary handles for every underlay. +pub(crate) fn plan<'a>(entities: impl Iterator<Item = &'a draftcraft_doc::Entity>, mut next: impl FnMut() -> String) -> Plan { + let mut p = Plan::default(); + let mut index: HashMap<(String, String, String), usize> = HashMap::new(); + let mut used: HashSet<String> = HashSet::new(); + for e in entities { + let EntityKind::Image(i) = &e.kind else { continue }; + let Some(u) = &i.underlay else { continue }; + if p.by_entity.contains_key(&e.handle) { + continue; + } + let k = (i.path.clone(), u.page.clone(), i.name.clone()); + let at = match index.get(&k) { + Some(&at) => at, + None => { + let base = def_name(i, &u.page); + let mut name = base.clone(); + let mut n = 2usize; + while !used.insert(key(&name)) { + name = format!("{base}_{n}"); + n = n.saturating_add(1); + } + p.defs.push(PlannedDef { handle: next(), name, path: i.path.clone(), page: u.page.clone() }); + let at = p.defs.len().saturating_sub(1); + index.insert(k, at); + at + } + }; + if let Some(def) = p.defs.get(at) { + p.by_entity.insert(e.handle, def.handle.clone()); + } + } + if !p.defs.is_empty() { + p.dict = next(); + } + p +} + +/// The reference's scale (drawing units per inch along its x and y) and rotation (degrees). +pub fn scale_and_rotation(i: &Image) -> (f64, f64, f64) { + let u = i.u.xy(); + let v = i.v.xy(); + let sx = u.len() * POINTS_PER_INCH; + // A mirrored underlay has its y axis clockwise from its x axis. + let mirrored = u.x * v.y - u.y * v.x < 0.0; + let sy = v.len() * POINTS_PER_INCH * if mirrored { -1.0 } else { 1.0 }; + let rot = u.y.atan2(u.x).to_degrees(); + let rot = if rot < 0.0 { rot + 360.0 } else { rot }; + (sx, sy, rot) +} + +/// The PDFUNDERLAY entity's groups after its common entity groups. +pub(crate) fn entity_tags(i: &Image, def: &str) -> Vec<Tag> { + let Some(u) = &i.underlay else { return Vec::new() }; + let (sx, sy, rot) = scale_and_rotation(i); + let finite = |v: f64, d: f64| if v.is_finite() && v != 0.0 { v } else { d }; + let mut t = vec![Tag::s(340, def), Tag::f(10, i.insert.x), Tag::f(20, i.insert.y), Tag::f(30, i.insert.z)]; + t.extend([Tag::f(41, finite(sx, 1.0)), Tag::f(42, finite(sy, 1.0)), Tag::f(43, 1.0), Tag::f(50, finite(rot, 0.0))]); + t.extend([Tag::f(210, 0.0), Tag::f(220, 0.0), Tag::f(230, 1.0)]); + let mut flags = 0; + if i.clipping { + flags |= FLAG_CLIP; + } + if i.display & 1 != 0 { + flags |= FLAG_ON; + } + if u.monochrome { + flags |= FLAG_MONO; + } + if u.adjust_for_background { + flags |= FLAG_ADJUST; + } + t.extend([Tag::i(280, flags), Tag::i(281, i64::from(i.contrast.min(100))), Tag::i(282, i64::from(i.fade.min(80)))]); + for q in &u.clip { + t.extend([Tag::f(11, q.x), Tag::f(21, q.y)]); + } + t +} + +/// The definitions dictionary and the PDFDEFINITION objects; `root` is the named object +/// dictionary, which lists `ACAD_PDFDEFINITIONS`. +pub(crate) fn objects(p: &Plan, root: &str) -> Vec<Tag> { + let mut t = Vec::new(); + if p.is_empty() { + return t; + } + t.extend([Tag::s(0, "DICTIONARY"), Tag::s(5, &p.dict), Tag::s(330, root), Tag::s(100, "AcDbDictionary"), Tag::i(281, 1)]); + for d in &p.defs { + t.extend([Tag::s(3, &d.name), Tag::s(350, &d.handle)]); + } + for d in &p.defs { + t.extend([Tag::s(0, "PDFDEFINITION"), Tag::s(5, &d.handle), Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, &p.dict), Tag::s(102, "}")]); + t.extend([Tag::s(330, &p.dict), Tag::s(100, "AcDbUnderlayDefinition"), Tag::s(1, &d.path)]); + t.push(Tag::s(2, if d.page.trim().is_empty() { "1" } else { d.page.trim() })); + } + t +} diff --git a/crates/io/src/dxf_write/ctx.rs b/crates/io/src/dxf_write/ctx.rs index 25194bb4..c0874ae1 100644 --- a/crates/io/src/dxf_write/ctx.rs +++ b/crates/io/src/dxf_write/ctx.rs @@ -50,6 +50,8 @@ pub(super) struct Ctx { pub(super) block_records: HashMap<String, String>, /// Raster images' IMAGEDEF, IMAGEDEF_REACTOR and dictionary handles. pub(super) images: crate::dxf_image::Plan, + /// Underlays' definitions and their dictionary. + pub(super) underlays: crate::dxf_underlay::Plan, /// The version the file ends up in (the DWG version for a DWG save): it decides which /// entity types exist (MULTILEADER from 2007). pub(super) target: Version, diff --git a/crates/io/src/dxf_write/entity.rs b/crates/io/src/dxf_write/entity.rs index 94a7bb93..14079fcd 100644 --- a/crates/io/src/dxf_write/entity.rs +++ b/crates/io/src/dxf_write/entity.rs @@ -570,6 +570,14 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap w.p(10, *v); } } + EntityKind::Image(i) if i.underlay.is_some() => { + // Every underlay has its definition (planned in `write`); the fallback never happens. + let Some(def) = cx.underlays.by_entity.get(&e.handle) else { return }; + let (kind, _) = i.underlay.as_ref().map(|u| u.kind.dxf_names()).unwrap_or(("PDFUNDERLAY", "")); + w.s(0, kind); + common(w, e, owner, paper, "AcDbUnderlayReference"); + w.t.extend(crate::dxf_underlay::entity_tags(i, def)); + } EntityKind::Image(i) => { // Every image has its IMAGEDEF (planned in `write`); the fallback never happens. let Some((def, reactor)) = cx.images.by_entity.get(&e.handle) else { return }; diff --git a/crates/io/src/dxf_write/header.rs b/crates/io/src/dxf_write/header.rs index 26c6f170..1e9b5474 100644 --- a/crates/io/src/dxf_write/header.rs +++ b/crates/io/src/dxf_write/header.rs @@ -46,6 +46,10 @@ const HEADER_VARS: &[(&str, i32)] = &[ ("INSUNITS", 70), ("MEASUREMENT", 70), ("PSLTSCALE", 70), + // The geographic location (GEOGRAPHICLOCATION): degrees, and the north direction in radians. + ("LATITUDE", 40), + ("LONGITUDE", 40), + ("NORTHDIRECTION", 40), ]; /// The current dimension style's variables as header variables (`$DIMTXT`, `$DIMDEC`…), after diff --git a/crates/io/src/dxf_write/sections.rs b/crates/io/src/dxf_write/sections.rs index d4835498..479d403e 100644 --- a/crates/io/src/dxf_write/sections.rs +++ b/crates/io/src/dxf_write/sections.rs @@ -339,6 +339,10 @@ fn write_classes(w: &mut W, cx: &Ctx, every: &[&Entity]) { if every.iter().any(|e| matches!(e.kind, EntityKind::Wipeout(_))) { classes.push(("WIPEOUT", "AcDbWipeout", 127, true)); } + if !cx.underlays.is_empty() { + classes.push(("PDFUNDERLAY", "AcDbPdfReference", 4095, true)); + classes.push(("PDFDEFINITION", "AcDbPdfDefinition", 1153, false)); + } if !cx.images.is_empty() { classes.push(("IMAGE", "AcDbRasterImage", 127, true)); classes.push(("IMAGEDEF", "AcDbRasterImageDef", 0, false)); @@ -583,6 +587,10 @@ fn write_root_group_objects( w.s(3, "ACAD_IMAGE_VARS"); w.s(350, cx.images.vars.clone()); } + if !cx.underlays.is_empty() { + w.s(3, crate::dxf_underlay::DICT_KEY); + w.s(350, cx.underlays.dict.clone()); + } w.s(3, "ACAD_LAYOUT"); w.s(350, layout_dict.clone()); w.s(3, "ACAD_MLEADERSTYLE"); @@ -752,6 +760,7 @@ fn write_objects(w: &mut W, plan: ObjectWritePlan<'_>) { write_layout_objects(w, &plan); // Raster image definitions. w.t.extend(crate::dxf_image::objects(&plan.cx.images, plan.root_dict)); + w.t.extend(crate::dxf_underlay::objects(&plan.cx.underlays, plan.root_dict)); w.s(0, "ENDSEC"); } @@ -955,6 +964,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34 let mut table_defs = table_block_definitions(d, &every, &mut w, &mut cx); // Image definitions (IMAGEDEF objects) of raster images anywhere in the drawing. cx.images = crate::dxf_image::plan(every.iter().copied(), || w.h()); + cx.underlays = crate::dxf_underlay::plan(every.iter().copied(), || w.h()); cx.mlines = crate::dxf_mline::plan(d, every.iter().copied(), || w.h()); plan_dimension_associations(d, &all_spaces, &mut w, &mut cx); let default_table_style = [TableStyle::default()]; diff --git a/crates/io/src/lib.rs b/crates/io/src/lib.rs index b928c810..075a4687 100644 --- a/crates/io/src/lib.rs +++ b/crates/io/src/lib.rs @@ -12,10 +12,12 @@ mod dxf_image; mod dxf_mleader; mod dxf_read; mod dxf_table; +mod dxf_underlay; mod dxf_write; mod dxf_xref; mod legacy_names; pub mod pdf; +pub mod pdf_read; pub mod plotter; /// Raster image files (PNG, JPEG, BMP, TIFF) decoded to pixels. pub mod raster; diff --git a/crates/io/src/pdf_read.rs b/crates/io/src/pdf_read.rs new file mode 100644 index 00000000..590d86cd --- /dev/null +++ b/crates/io/src/pdf_read.rs @@ -0,0 +1,576 @@ +//! Reading PDF files (PDF underlays and PDFIMPORT), with craft-pdf's reader (hayro; pure Rust). +//! +//! - [`pages`]: each page's size in points (1/72 inch), as the page is shown (after its rotation). +//! - [`rasterize`]: one page as pixels, on white paper, for an underlay to show. +//! - [`import`]: one page's vector content as DraftCraft objects in points, the page's lower-left +//! corner at the origin and y up: stroked paths as polylines and splines (each cubic Bézier +//! exactly), filled areas as solid hatches, and text as single-line text. Images, shadings and +//! clipping are not imported. +//! +//! PDF files are hostile input: the input size, page count, objects and points are capped, and +//! the reader runs inside `catch_unwind` (craft-pdf's guards), so a damaged file is an error. + +use craft_pdf::interpret::font::Glyph; +use craft_pdf::interpret::{ + BlendMode, ClipPath, Context, Device, GlyphDrawMode, Image as PdfImage, InterpreterCache, InterpreterSettings, Paint, PathDrawMode, SoftMask, + TransformExt, +}; +use craft_pdf::syntax::page::Page; +use draftcraft_color::Rgb; +use draftcraft_doc::{EntityKind, Hatch, HatchLoop, ImportedShape, LwPolyline, Raster, ShapeClass, Text}; +use draftcraft_geom::{PolyVertex, Spline, Vec2}; +use kurbo::{Affine, BezPath, PathEl, Point, Rect, Shape}; + +use crate::{IoError, Result}; + +/// Largest PDF file read (bytes). +pub const MAX_PDF_BYTES: usize = 256 << 20; +/// Most pages listed. +pub const MAX_PAGES: usize = 10_000; +/// Most objects imported from one page. +pub const MAX_SHAPES: usize = 500_000; +/// Most points kept across one page's import (polyline vertices and spline control points). +const MAX_POINTS: usize = 8_000_000; +/// Longest text run kept (characters). +const MAX_TEXT: usize = 2000; +/// The longest side of a rendered page, in pixels. +pub const MAX_RASTER_SIDE: u32 = 6000; +/// The most pixels of a rendered page. +pub const MAX_RASTER_PIXELS: u64 = 24_000_000; + +fn bad(e: impl std::fmt::Display) -> IoError { + IoError::Format(format!("PDF: {e}")) +} + +fn open(bytes: &[u8]) -> Result<craft_pdf::syntax::Pdf> { + if bytes.len() > MAX_PDF_BYTES { + return Err(bad(format!("the file is larger than {} MB", MAX_PDF_BYTES >> 20))); + } + if !bytes.starts_with(b"%PDF") && !bytes.get(..1024).unwrap_or(bytes).windows(4).any(|w| w == b"%PDF") { + return Err(bad("not a PDF file")); + } + std::panic::catch_unwind(|| craft_pdf::open_slice(bytes, None)).map_err(|_| bad("the file can't be read"))?.map_err(|e| bad(format!("{e:?}"))) +} + +/// Each page's width and height in points, as shown (a rotated page is turned). +pub fn pages(bytes: &[u8]) -> Result<Vec<(f64, f64)>> { + let pdf = open(bytes)?; + let pages = pdf.pages(); + let out: Vec<(f64, f64)> = pages.iter().take(MAX_PAGES).map(|p| p.render_dimensions()).map(|(w, h)| (f64::from(w), f64::from(h))).collect(); + if out.is_empty() { + return Err(bad("the file has no pages")); + } + Ok(out) +} + +fn page<'a>(pdf: &'a craft_pdf::syntax::Pdf, index: usize) -> Result<&'a Page<'a>> { + pdf.pages().get(index).ok_or_else(|| bad(format!("there is no page {}", index.saturating_add(1)))) +} + +/// The scale (pixels per point) that renders a `w` × `h` point page within the raster limits, +/// at most `wanted`. +fn raster_scale(w: f64, h: f64, wanted: f64) -> f64 { + let side = f64::from(MAX_RASTER_SIDE) / w.max(h).max(1.0); + let area = (MAX_RASTER_PIXELS as f64 / (w * h).max(1.0)).sqrt(); + wanted.min(side).min(area).max(0.01) +} + +/// Page `index` (from 0) as pixels on white paper, at up to `dpi` dots per inch (less for a page +/// too large for [`MAX_RASTER_SIDE`] and [`MAX_RASTER_PIXELS`]). +pub fn rasterize(bytes: &[u8], index: usize, dpi: f64) -> Result<Raster> { + let pdf = open(bytes)?; + let page = page(&pdf, index)?; + let (w, h) = page.render_dimensions(); + let s = raster_scale(f64::from(w), f64::from(h), (dpi / 72.0).clamp(0.05, 8.0)) as f32; + let cache = craft_pdf::raster::RenderCache::new(); + let options = craft_pdf::raster::Options { scale: [s, s], background: [255, 255, 255, 255], ..Default::default() }; + let r = craft_pdf::raster::render(page, &cache, &InterpreterSettings::default(), &options).map_err(bad)?; + // Premultiplied on opaque white paper: every pixel is opaque, so the bytes are straight RGBA. + Raster::new(r.width, r.height, r.bytes().to_vec()).ok_or_else(|| bad("the page could not be drawn")) +} + +/// What [`import`] reads. +#[derive(Clone, Copy, Debug)] +pub struct ImportOptions { + pub vectors: bool, + pub fills: bool, + pub text: bool, +} + +impl Default for ImportOptions { + fn default() -> Self { + ImportOptions { vectors: true, fills: true, text: true } + } +} + +/// What was left out of an import, for the result's notes. +#[derive(Clone, Debug, Default, PartialEq, Eq)] +pub struct ImportNotes { + pub images: usize, + pub truncated: bool, +} + +/// Page `index` (from 0) as DraftCraft objects in points, the page's lower-left corner at the +/// origin, y up. +pub fn import(bytes: &[u8], index: usize, opts: ImportOptions) -> Result<(Vec<ImportedShape>, ImportNotes)> { + let pdf = open(bytes)?; + let page = page(&pdf, index)?; + let (w, h) = page.render_dimensions(); + let cache = InterpreterCache::new(); + let mut ctx = Context::new( + page.initial_transform(false).to_kurbo(), + Rect::new(0.0, 0.0, f64::from(w), f64::from(h)), + &cache, + page.xref(), + InterpreterSettings::default(), + ); + let mut dev = Collector { opts, page: (f64::from(w), f64::from(h)), ..Collector::default() }; + craft_pdf::interpret_page(page, &mut ctx, &mut dev).map_err(bad)?; + dev.flush_text(); + let notes = ImportNotes { images: dev.images, truncated: dev.truncated }; + Ok((dev.shapes, notes)) +} + +/// [`import`] with plain arguments and a text error, the form the engine's hook takes: the +/// shapes, how many images were left out and whether the page had more than was read. +pub fn import_flat( + bytes: &[u8], + index: usize, + vectors: bool, + fills: bool, + text: bool, +) -> std::result::Result<(Vec<ImportedShape>, usize, bool), String> { + import(bytes, index, ImportOptions { vectors, fills, text }).map(|(s, n)| (s, n.images, n.truncated)).map_err(|e| e.to_string()) +} + +/// A text run being collected: glyphs on one baseline. +struct Run { + text: String, + origin: Vec2, + /// Unit vector along the baseline. + dir: Vec2, + /// The font size (em) in points. + em: f64, + /// Where the last glyph's ink ends, along the baseline from `origin`. + end: f64, + color: Option<Rgb>, +} + +#[derive(Default)] +struct Collector { + opts: ImportOptions, + page: (f64, f64), + shapes: Vec<ImportedShape>, + points: usize, + images: usize, + truncated: bool, + run: Option<Run>, +} + +fn v(p: Point) -> Vec2 { + Vec2::new(p.x, p.y) +} + +fn rgb(paint: &Paint<'_>) -> Option<Rgb> { + match paint { + Paint::Color(c) => { + let [r, g, b, _] = c.to_rgba().to_rgba8(); + Some(Rgb(r, g, b)) + } + Paint::Pattern(_) => None, + } +} + +/// A cubic Bézier chain (start point, then three points per curve) as one exact spline: +/// knots of multiplicity three at each joint. +fn bezier_chain(control: Vec<Vec2>) -> Spline { + let curves = control.len().saturating_sub(1) / 3; + let mut knots = vec![0.0; 4]; + for i in 1..curves { + knots.extend([i as f64; 3]); + } + knots.extend([curves as f64; 4]); + let mut s = Spline::from_control(control, 3); + s.knots = knots; + s +} + +/// The subpaths of a path in page points: each a list of pieces, a run of straight segments (a +/// polyline) or a run of cubic curves (a spline), and whether it is closed. +fn subpaths(path: &BezPath, m: Affine) -> Vec<(Vec<Piece>, bool)> { + let mut out = Vec::new(); + let mut pieces: Vec<Piece> = Vec::new(); + let mut start = Point::ZERO; + let mut cur = Point::ZERO; + let mut closed = false; + let finish = |pieces: &mut Vec<Piece>, closed: bool, out: &mut Vec<(Vec<Piece>, bool)>| { + if !pieces.is_empty() { + out.push((std::mem::take(pieces), closed)); + } + }; + for el in path.elements() { + match *el { + PathEl::MoveTo(p) => { + finish(&mut pieces, closed, &mut out); + closed = false; + start = m * p; + cur = start; + } + PathEl::LineTo(p) => { + let p = m * p; + match pieces.last_mut() { + Some(Piece::Lines(pts)) => pts.push(v(p)), + _ => pieces.push(Piece::Lines(vec![v(cur), v(p)])), + } + cur = p; + } + PathEl::QuadTo(q, p) => { + let (q, p) = (m * q, m * p); + let c1 = cur + (q - cur) * (2.0 / 3.0); + let c2 = p + (q - p) * (2.0 / 3.0); + push_cubic(&mut pieces, cur, c1, c2, p); + cur = p; + } + PathEl::CurveTo(c1, c2, p) => { + let (c1, c2, p) = (m * c1, m * c2, m * p); + push_cubic(&mut pieces, cur, c1, c2, p); + cur = p; + } + PathEl::ClosePath => { + if cur.distance(start) > 1e-9 { + match pieces.last_mut() { + Some(Piece::Lines(pts)) => pts.push(v(start)), + _ => pieces.push(Piece::Lines(vec![v(cur), v(start)])), + } + } + cur = start; + closed = true; + finish(&mut pieces, closed, &mut out); + closed = false; + } + } + } + finish(&mut pieces, closed, &mut out); + out +} + +fn push_cubic(pieces: &mut Vec<Piece>, from: Point, c1: Point, c2: Point, to: Point) { + match pieces.last_mut() { + Some(Piece::Curves(pts)) => pts.extend([v(c1), v(c2), v(to)]), + _ => pieces.push(Piece::Curves(vec![v(from), v(c1), v(c2), v(to)])), + } +} + +enum Piece { + Lines(Vec<Vec2>), + Curves(Vec<Vec2>), +} + +impl Piece { + fn len(&self) -> usize { + match self { + Piece::Lines(p) | Piece::Curves(p) => p.len(), + } + } +} + +/// The length of the vector (1, 0) under `m`, for widths and sizes. +fn mean_scale(m: Affine) -> f64 { + let c = m.as_coeffs(); + ((c[0] * c[3] - c[1] * c[2]).abs()).sqrt() +} + +impl Collector { + fn room(&mut self, points: usize) -> bool { + if self.shapes.len() >= MAX_SHAPES || self.points.saturating_add(points) > MAX_POINTS { + self.truncated = true; + return false; + } + self.points += points; + true + } + + fn push(&mut self, kind: EntityKind, color: Option<Rgb>, width: f64, class: ShapeClass) { + self.shapes.push(ImportedShape { kind, color, width, class }); + } + + fn stroke(&mut self, path: &BezPath, m: Affine, color: Option<Rgb>, width: f64) { + for (pieces, closed) in subpaths(path, m) { + let whole = pieces.len() == 1; + for piece in pieces { + if !self.room(piece.len()) { + return; + } + let kind = match piece { + Piece::Lines(pts) => { + let mut pts = pts; + let closed = closed && whole && pts.len() > 2; + if closed && pts.first().zip(pts.last()).is_some_and(|(a, b)| a.dist(*b) < 1e-9) { + pts.pop(); + } + if pts.len() < 2 { + continue; + } + let vertices = pts.into_iter().map(PolyVertex::new).collect(); + EntityKind::LwPolyline(LwPolyline { vertices, closed, const_width: 0.0, elevation: 0.0, plinegen: false }) + } + Piece::Curves(pts) => EntityKind::Spline(bezier_chain(pts)), + }; + self.push(kind, color, width, ShapeClass::Vector); + } + } + } + + fn fill(&mut self, path: &BezPath, m: Affine, color: Option<Rgb>) { + // Curves flattened to within a hundredth of a point. + let mut loops = Vec::new(); + let mut pts: Vec<Vec2> = Vec::new(); + let flat = |pts: &mut Vec<Vec2>, loops: &mut Vec<HatchLoop>| { + if pts.len() >= 3 { + loops.push(HatchLoop { vertices: pts.drain(..).map(PolyVertex::new).collect(), outer: loops.is_empty(), sources: Vec::new() }); + } + pts.clear(); + }; + let path = m * path.clone(); + let mut count = 0usize; + kurbo::flatten(path.elements().iter().copied(), 0.01, |el| { + count += 1; + if count > MAX_POINTS { + return; + } + match el { + PathEl::MoveTo(p) => { + flat(&mut pts, &mut loops); + pts.push(v(p)); + } + PathEl::LineTo(p) => pts.push(v(p)), + PathEl::ClosePath => flat(&mut pts, &mut loops), + _ => {} + } + }); + flat(&mut pts, &mut loops); + let points: usize = loops.iter().map(|l| l.vertices.len()).sum(); + if loops.is_empty() || !self.room(points) { + return; + } + // The page's own white background is paper, not drawing. + let bbox = path.bounding_box(); + let (pw, ph) = self.page; + if color == Some(Rgb(255, 255, 255)) && bbox.width() >= pw * 0.95 && bbox.height() >= ph * 0.95 { + return; + } + let hatch = Hatch { + pattern: "SOLID".into(), + solid: true, + loops, + scale: 1.0, + angle: 0.0, + associative: false, + style: 0, + elevation: 0.0, + gradient: None, + origin: Vec2::ZERO, + background: None, + pattern_lines: Vec::new(), + }; + self.push(EntityKind::Hatch(hatch), color, 0.0, ShapeClass::Fill); + } + + fn flush_text(&mut self) { + let Some(run) = self.run.take() else { return }; + let value = run.text.trim_end().to_string(); + if value.is_empty() || !self.room(1) { + return; + } + let text = Text { + insert: run.origin.to3(0.0), + align_pt: None, + // Capital letters are about 0.7 em high. + height: run.em * 0.7, + value, + rotation: run.dir.y.atan2(run.dir.x), + width_factor: 1.0, + oblique: 0.0, + style: "Standard".into(), + halign: Default::default(), + valign: Default::default(), + }; + self.push(EntityKind::Text(text), run.color, 0.0, ShapeClass::Text); + } + + fn glyph(&mut self, glyph: &Glyph<'_>, m: Affine, color: Option<Rgb>) { + let Some(ch) = glyph.as_unicode() else { return }; + let ch = match ch { + craft_pdf::interpret::hayro_cmap::BfString::Char(c) => c.to_string(), + craft_pdf::interpret::hayro_cmap::BfString::String(s) => s, + }; + if ch.chars().any(char::is_control) { + return; + } + let origin = v(m * Point::ZERO); + let o = m * Point::ZERO; + let up = m * Point::new(0.0, 1000.0) - o; + let along = m * Point::new(1000.0, 0.0) - o; + let em = up.hypot(); + if !(em.is_finite() && em > 1e-6 && origin.x.is_finite() && origin.y.is_finite()) { + return; + } + let dir = Vec2::new(along.x, along.y); + let dir = if dir.len() > 1e-9 { dir * (1.0 / dir.len()) } else { Vec2::new(1.0, 0.0) }; + // Where the glyph's ink ends (its outline's right side), along the baseline. + let ink = match glyph { + Glyph::Outline(g) => { + let b = (m * g.outline()).bounding_box(); + let corners = [Vec2::new(b.x0, b.y0), Vec2::new(b.x1, b.y0), Vec2::new(b.x0, b.y1), Vec2::new(b.x1, b.y1)]; + corners.iter().map(|c| (*c - origin).dot(dir)).fold(f64::NEG_INFINITY, f64::max) + } + Glyph::Type3(_) => em * 0.5, + }; + let ink = if ink.is_finite() && ink > 0.0 { ink } else { em * 0.5 }; + if let Some(run) = &mut self.run { + let rel = origin - run.origin; + let along = rel.dot(run.dir); + let across = rel.dot(run.dir.perp()).abs(); + let same = (em - run.em).abs() <= run.em * 0.15 && run.dir.dot(dir) > 0.999 && run.color == color; + let gap = along - run.end; + if same && across <= run.em * 0.2 && gap > -run.em * 0.5 && gap < run.em * 1.5 && run.text.chars().count() < MAX_TEXT { + if gap > run.em * 0.2 && !run.text.ends_with(' ') && ch != " " { + run.text.push(' '); + } + run.text.push_str(&ch); + run.end = run.end.max(along + ink); + return; + } + } + self.flush_text(); + if ch.trim().is_empty() { + return; + } + self.run = Some(Run { text: ch, origin, dir, em, end: ink, color }); + } +} + +impl<'a> Device<'a> for Collector { + fn set_soft_mask(&mut self, _mask: Option<SoftMask<'a>>) {} + fn set_blend_mode(&mut self, _blend_mode: BlendMode) {} + + fn draw_path(&mut self, path: &BezPath, transform: Affine, paint: &Paint<'a>, draw_mode: &PathDrawMode) { + match draw_mode { + PathDrawMode::Stroke(props) if self.opts.vectors => { + self.flush_text(); + let width = f64::from(props.line_width) * mean_scale(transform); + self.stroke(path, transform, rgb(paint), if width.is_finite() { width } else { 0.0 }); + } + PathDrawMode::Fill(_) if self.opts.fills => { + self.flush_text(); + self.fill(path, transform, rgb(paint)); + } + _ => {} + } + } + + fn push_clip_path(&mut self, _clip_path: &ClipPath) {} + fn push_transparency_group(&mut self, _opacity: f32, _mask: Option<SoftMask<'a>>, _blend_mode: BlendMode) {} + + fn draw_glyph(&mut self, glyph: &Glyph<'a>, transform: Affine, glyph_transform: Affine, paint: &Paint<'a>, draw_mode: &GlyphDrawMode) { + if !self.opts.text || matches!(draw_mode, GlyphDrawMode::Clip | GlyphDrawMode::Invisible) { + return; + } + self.glyph(glyph, transform * glyph_transform, rgb(paint)); + } + + fn draw_image(&mut self, _image: PdfImage<'a, '_>, _transform: Affine) { + self.images = self.images.saturating_add(1); + } + + fn pop_clip_path(&mut self) {} + fn pop_transparency_group(&mut self) {} +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A one-page PDF with a stroked line, a stroked curve, a red filled square and a text. + fn sample_pdf() -> Vec<u8> { + let content = b"q 2 w 0 0 1 RG 72 72 m 144 72 l S 72 144 m 100 200 150 200 180 144 c S 1 0 0 rg 200 200 50 50 re f Q \ +BT /F1 12 Tf 72 300 Td (Hi there) Tj ET"; + let mut objs: Vec<Vec<u8>> = Vec::new(); + objs.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec()); + objs.push(b"<< /Type /Pages /Kids [3 0 R] /Count 1 >>".to_vec()); + objs.push(b"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 612 792] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>".to_vec()); + let mut stream = format!("<< /Length {} >>\nstream\n", content.len()).into_bytes(); + stream.extend_from_slice(content); + stream.extend_from_slice(b"\nendstream"); + objs.push(stream); + objs.push(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>".to_vec()); + let mut out = b"%PDF-1.4\n".to_vec(); + let mut offsets = Vec::new(); + for (i, o) in objs.iter().enumerate() { + offsets.push(out.len()); + out.extend_from_slice(format!("{} 0 obj\n", i + 1).as_bytes()); + out.extend_from_slice(o); + out.extend_from_slice(b"\nendobj\n"); + } + let xref = out.len(); + out.extend_from_slice(format!("xref\n0 {}\n0000000000 65535 f \n", objs.len() + 1).as_bytes()); + for off in offsets { + out.extend_from_slice(format!("{off:010} 00000 n \n").as_bytes()); + } + out.extend_from_slice(format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objs.len() + 1).as_bytes()); + out + } + + #[test] + fn pages_lists_the_page_size() { + assert_eq!(pages(&sample_pdf()).unwrap(), vec![(612.0, 792.0)]); + } + + #[test] + fn rasterize_draws_on_white_paper() { + let r = rasterize(&sample_pdf(), 0, 36.0).unwrap(); + assert_eq!((r.width(), r.height()), (306, 396)); + assert!(r.opaque()); + // The red square (200..250 points from the left, 200..250 from the bottom). + assert_eq!(r.pixel(112, 396 - 112), Some([255, 0, 0, 255])); + assert_eq!(r.pixel(5, 5), Some([255, 255, 255, 255])); + assert!(rasterize(&sample_pdf(), 1, 72.0).is_err()); + } + + #[test] + fn import_reads_lines_curves_fills_and_text() { + let (shapes, notes) = import(&sample_pdf(), 0, ImportOptions::default()).unwrap(); + assert_eq!(notes, ImportNotes::default()); + let line = shapes.iter().find(|s| matches!(s.kind, EntityKind::LwPolyline(_))).unwrap(); + let EntityKind::LwPolyline(p) = &line.kind else { panic!("a polyline") }; + assert_eq!(p.vertices.iter().map(|v| v.p).collect::<Vec<_>>(), vec![Vec2::new(72.0, 72.0), Vec2::new(144.0, 72.0)]); + assert_eq!(line.color, Some(Rgb(0, 0, 255))); + assert!((line.width - 2.0).abs() < 1e-9); + let curve = shapes.iter().find_map(|s| if let EntityKind::Spline(s) = &s.kind { Some(s) } else { None }).unwrap(); + assert_eq!(curve.control.len(), 4); + assert_eq!(curve.knots, vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0]); + let fill = shapes.iter().find(|s| s.class == ShapeClass::Fill).unwrap(); + assert_eq!(fill.color, Some(Rgb(255, 0, 0))); + let text = shapes.iter().find_map(|s| if let EntityKind::Text(t) = &s.kind { Some(t) } else { None }).unwrap(); + assert_eq!(text.value, "Hi there"); + assert!((text.insert.x - 72.0).abs() < 1e-6 && (text.insert.y - 300.0).abs() < 1e-6, "{:?}", text.insert); + let only_text = import(&sample_pdf(), 0, ImportOptions { vectors: false, fills: false, text: true }).unwrap().0; + assert_eq!(only_text.len(), 1); + } + + #[test] + fn hostile_input_is_an_error() { + assert!(pages(b"not a pdf").is_err()); + assert!(pages(b"%PDF-1.4\n garbage").is_err()); + let mut cut = sample_pdf(); + cut.truncate(cut.len() / 2); + let _ = pages(&cut); + let _ = import(&cut, 0, ImportOptions::default()); + } + + #[test] + fn bezier_chains_have_a_joint_knot_per_curve() { + let s = bezier_chain((0..7).map(|i| Vec2::new(f64::from(i), 0.0)).collect()); + assert_eq!(s.knots, vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 2.0, 2.0, 2.0, 2.0]); + } +} diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index b0638e23..2170668d 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -288,7 +288,7 @@ fn draw_image(b: &mut Builder, ctx: &Ctx, i: &draftcraft_doc::Image, rgb: Ink, l let v = i.v.xy() * i.size.y; // Display flag 1: show the image. Without pixels (file not found, not loaded yet, hidden) // the rectangle is crossed out. - let raster = if i.display & 1 != 0 { ctx.d.rasters.get(&i.path) } else { None }; + let raster = if i.display & 1 != 0 { ctx.d.rasters.get(&i.raster_key()) } else { None }; if let Some(r) = raster { b.image(ctx, rgb, i, r); } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 6aa66f0b..8f23f556 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -31,6 +31,7 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "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), + "cui" => crate::workspaces::dialog(app, ctx, &mut open), o if o == "options" || o.starts_with("options:") => crate::options::dialog(app, ctx, o, &mut open), other => crate::managers::dialog(app, ctx, other, &mut open), } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index bbc2d914..ac69340b 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -19,6 +19,9 @@ pub enum Panel { Properties, #[serde(rename = "externalReferences")] ExternalRefs, + DesignCenter, + ToolPalettes, + SheetSet, } impl Panel { @@ -31,6 +34,9 @@ impl Panel { Self::Layers => "layers", Self::Properties => "properties", Self::ExternalRefs => "externalReferences", + Self::DesignCenter => "designCenter", + Self::ToolPalettes => "toolPalettes", + Self::SheetSet => "sheetSet", } } fn label(self) -> &'static str { @@ -41,6 +47,9 @@ impl Panel { Self::Layers => "Layers", Self::Properties => "Properties", Self::ExternalRefs => "External References", + Self::DesignCenter => "DesignCenter", + Self::ToolPalettes => "Tool Palettes", + Self::SheetSet => "Sheet Set Manager", } } /// The icon a palette shows in a column collapsed to icons. @@ -53,10 +62,13 @@ impl Panel { Self::Layers => Some(Icon::Layers), Self::Properties => Some(Icon::Properties), Self::ExternalRefs => Some(Icon::Attach), + Self::DesignCenter => Some(Icon::DesignCenter), + Self::ToolPalettes => Some(Icon::ToolPalette), + Self::SheetSet => Some(Icon::SheetSet), } } /// Palettes outside the default arrangement, opened on request (QUICKCALC). - pub const ON_DEMAND: &[Self] = &[Self::QuickCalc]; + pub const ON_DEMAND: &[Self] = &[Self::QuickCalc, Self::DesignCenter, Self::ToolPalettes, Self::SheetSet]; } /// The drawing view never moves, floats, closes or takes tabs; palettes dock beside it. @@ -148,7 +160,9 @@ fn home_anchor(layout: &Layout<Panel>, panel: Panel) -> Option<(Panel, bool)> { Panel::Layers => &[(Panel::Properties, false), (Panel::ExternalRefs, false)], 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::QuickCalc | Panel::DesignCenter | Panel::ToolPalettes | Panel::SheetSet => { + &[(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 +428,9 @@ impl DockContent<Panel> for Panels<'_> { Panel::ExternalRefs => { egui::ScrollArea::both().id_salt("dock-xrefs").auto_shrink([false, false]).show(ui, |ui| crate::xrefs::section(app, ui)); } + Panel::DesignCenter => crate::palettes::designcenter::show(app, ui), + Panel::ToolPalettes => crate::palettes::toolpalettes::show(app, ui), + Panel::SheetSet => crate::palettes::sheetset::show(app, ui), } } fn logical_label(&self, panel: &Panel) -> String { @@ -442,6 +459,31 @@ 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::DesignCenter | Panel::ToolPalettes | Panel::SheetSet => (egui::vec2(220.0, 160.0), 900.0), }; PanelLimits { min, max: egui::vec2(max_width, 1_000_000.0) } } + +/// Open an on-demand palette (QuickCalc, DesignCenter, Tool Palettes, Sheet Set Manager). The +/// first time it floats by the right edge of the drawing, `width` wide; afterwards it returns +/// where it was closed. +pub(crate) fn open_on_demand(app: &mut crate::CadApp, panel: Panel, width: f32) -> Result<Value, String> { + let first = !app.ui.docking.layout.contains(&panel) && !app.ui.docking.hidden.iter().any(|(p, _)| *p == panel); + let r = command(app, false, &json!({ "operation": "open", "panel": panel.id() }))?; + if !first { + return Ok(r); + } + let area = app.canvas.rect.unwrap_or(egui::Rect::from_min_size(egui::pos2(220.0, 80.0), egui::vec2(1000.0, 800.0))); + let h = (area.height() - 40.0).clamp(200.0, 560.0); + let rect = [area.right() - width - 16.0, area.top() + 24.0, width, h]; + command(app, false, &json!({ "operation": "float", "panel": panel.id(), "rect": rect })) +} + +/// Close an open palette, or open it. +pub(crate) fn toggle_on_demand(app: &mut crate::CadApp, panel: Panel, width: f32) -> Result<Value, String> { + if app.ui.docking.layout.contains(&panel) { + command(app, false, &json!({ "operation": "close", "panel": panel.id() })) + } else { + open_on_demand(app, panel, width) + } +} diff --git a/crates/ui-egui/src/exchange.rs b/crates/ui-egui/src/exchange.rs index e3dc2984..f51811a2 100644 --- a/crates/ui-egui/src/exchange.rs +++ b/crates/ui-egui/src/exchange.rs @@ -1,4 +1,4 @@ -//! EXPORT, IMPORT, PUBLISH and PREVIEW from a menu, the tool bar or the command line: the first +//! EXPORT, IMPORT, PUBLISH, ETRANSMIT, POINTCLOUDATTACH and PREVIEW from a menu, the tool bar or the command line: the first //! three ask for a file, PREVIEW shows the plot in a window. Calls with parameters (scripts, the //! control channel, MCP) never get here and never open a dialog: they run the engine commands. @@ -23,6 +23,38 @@ pub fn route(app: &mut CadApp, id: &str) -> Result<Value, String> { app.ui.dialog = Some("preview".into()); Ok(Value::Null) } + "attach" | "imageattach" | "iat" | "pdfattach" | "pdfat" | "pdfimport" => { + let (label, exts, cmd): (&str, &[&str], &str) = match id { + "imageattach" | "iat" => ("Images (PNG, JPEG, BMP, TIFF)", &["png", "jpg", "jpeg", "bmp", "tif", "tiff"], "imageattach"), + "pdfattach" | "pdfat" => ("PDF files", &["pdf"], "pdfattach"), + "pdfimport" => ("PDF files", &["pdf"], "pdfimport"), + _ => ("Images and PDF files", &["pdf", "png", "jpg", "jpeg", "bmp", "tif", "tiff"], "attach"), + }; + if cmd == "pdfimport" + && let Some(h) = selected_underlay(app) + { + return app.run("pdfimport", json!({ "handle": h })); + } + let Some(pick) = app.services.pick_file.as_ref() else { return no_picker(app, &cmd.to_ascii_uppercase(), r#"{"path": "plan.pdf"}"#) }; + match pick(label, exts) { + Some(path) => app.run(cmd, json!({ "path": path })), + None => Ok(Value::Null), + } + } + "pointcloudattach" | "pcattach" | "pointcloud" => { + let Some(pick) = app.services.pick_file.as_ref() else { return no_picker(app, "POINTCLOUDATTACH", r#"{"path": "scan.las"}"#) }; + match pick("Point clouds (XYZ, LAS)", &["xyz", "pts", "csv", "txt", "las"]) { + Some(path) => app.run("pointcloudattach", json!({ "path": path })), + None => Ok(Value::Null), + } + } + "etransmit" => { + let Some(pick) = app.services.pick_save.as_ref() else { return no_picker(app, "ETRANSMIT", r#"{"path": "package.zip"}"#) }; + match pick(&format!("{stem}.zip")) { + Some(path) => app.run("etransmit", json!({ "path": path })), + None => Ok(Value::Null), + } + } "import" | "imp" => { let Some(pick) = app.services.pick_open.as_ref() else { return no_picker(app, "IMPORT", r#"import {"path": "parts.dxf"}"#) }; match pick() { @@ -47,6 +79,17 @@ pub fn route(app: &mut CadApp, id: &str) -> Result<Value, String> { } } +/// The one PDF underlay selected, if that is the selection: PDFIMPORT from the ribbon imports it. +fn selected_underlay(app: &CadApp) -> Option<String> { + let st = app.session.state().ok()?; + let [h] = st.selection.as_slice() else { return None }; + let store = st.doc.space(&app.session.space())?; + match &store.get(*h)?.kind { + draftcraft_engine::doc::EntityKind::Image(i) if i.underlay.is_some() => Some(h.hex()), + _ => None, + } +} + fn no_picker(app: &mut CadApp, name: &str, example: &str) -> Result<Value, String> { let msg = format!("{name}: there is no file dialog here; run it with parameters, e.g. {example}"); app.session.echo(msg.clone()); @@ -181,6 +224,33 @@ mod tests { (CadApp::new(Session::new(), services), asked) } + #[test] + fn attach_and_pdf_commands_pick_a_file_of_their_kind() { + let asked = Rc::new(RefCell::new(Vec::new())); + let a = asked.clone(); + let services = Services { + pick_file: Some(Box::new(move |label: &str, exts: &[&str]| { + a.borrow_mut().push(format!("{label}: {}", exts.join(" "))); + None + })), + ..Services::default() + }; + let mut app = CadApp::new(Session::new(), services); + app.start("pdfattach"); + app.cmdline("PDFIMPORT"); + app.start("imageattach"); + app.start("attach"); + let asked = asked.borrow(); + assert_eq!(asked.len(), 4, "{asked:?}"); + assert_eq!((asked[0].as_str(), asked[1].as_str()), ("PDF files: pdf", "PDF files: pdf")); + assert!(asked[2].starts_with("Images (") && !asked[2].contains("pdf"), "{}", asked[2]); + assert!(asked[3].contains("pdf") && asked[3].contains("png"), "{}", asked[3]); + // A cancelled pick changes nothing, and a JSON call never asks. + assert!(app.session.doc().is_ok_and(|d| d.model.is_empty())); + assert!(app.run("pdfattach", json!({ "path": "missing.pdf" })).is_err()); + assert_eq!(asked.len(), 4); + } + #[test] fn typed_and_menu_commands_ask_json_calls_never_do() { let (mut app, asked) = app(); diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index fdb23471..7565dedc 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1519,3 +1519,125 @@ menu Modify Edita Ribbon Barra multifunzione {panel} panel Pannello {panel} Exit DraftCraft Esci da DraftCraft +# PDF underlays and PDFIMPORT + PDF Underlay... Sottoposto PDF... + PDF Import Importa PDF + PDF Underlay Sottoposto PDF + Underlay Layers Layer dei sottoposti + PDF files File PDF + Images (PNG, JPEG, BMP, TIFF) Immagini (PNG, JPEG, BMP, TIFF) + Images and PDF files Immagini e file PDF + Raster Image Reference... Riferimento immagine raster... +# Contextual ribbon tabs and slide-out panels + Hatch Editor Editor tratteggio + Formatting Formattazione + Paragraph Paragrafo + Open/Save Apri/Salva + Adjust Regola + Clipping Ritaglio + Close Text Editor Chiudi editor di testo + Edit Block Modifica blocco + Create Clipping Boundary Crea contorno di ritaglio + Image Clip Ritaglio immagine + PDF Clip Ritaglio PDF + Image Adjust Regola immagine + PDF Adjust Regola PDF + Adjust... Regola... + Multiple Points Punti multipli + Break at Point Spezza in un punto + Edit Polyline Modifica polilinea + Edit Spline Modifica spline + Multileader Style Stile multidirettrice + Authoring Creazione + Parameter Parametro + Action Azione + DesignCenter DesignCenter + Tool Palettes Tavolozze strumenti + Sheet Set Manager Gestione gruppo di fogli + Type the drawing's path, then press Enter. Digita il percorso del disegno, poi premi Invio. + Drawing file File di disegno + Folder Cartella + Linetypes Tipi di linea + Text Styles Stili di testo + Dimension Styles Stili di quota + Table Styles Stili di tabella + Multileader Styles Stili di multidirettrice + Multiline Styles Stili di multilinea + Add to Drawing Aggiungi al disegno + Create Tool Palette Crea tavolozza strumenti + Nothing of this kind in the file. Nessun elemento di questo tipo nel file. + Open a drawing to see its blocks, layers and styles. Apri un disegno per vederne blocchi, layer e stili. + Delete Palette Elimina tavolozza + New Palette Nuova tavolozza + No tool palettes. Nessuna tavolozza strumenti. + This palette is empty: add a command below, or make a palette from DesignCenter. Questa tavolozza è vuota: aggiungi un comando qui sotto, oppure crea una tavolozza da DesignCenter. + Delete Tool Elimina strumento + Add Command Aggiungi comando + New Sheet Set... Nuovo gruppo di fogli... + Open Sheet Set... Apri gruppo di fogli... + Sheet sets (DCSS) Gruppi di fogli (DCSS) + Sheet set file File del gruppo di fogli + Make or open a sheet set to list its sheets. Crea o apri un gruppo di fogli per elencarne i fogli. + Add Drawing... Aggiungi disegno... + Publish to PDF... Pubblica in PDF... + No sheets yet: add a drawing's layouts. Ancora nessun foglio: aggiungi i layout di un disegno. + Number Numero + Title Titolo + Move Up Sposta su + Move Down Sposta giù + Sheet Set (DCSS) Gruppo di fogli (DCSS) + Close Tool Palettes Chiudi tavolozze strumenti + Close DesignCenter Chiudi DesignCenter + Close Sheet Set Manager Chiudi gestione gruppo di fogli + Manage Tool Palettes Gestisci tavolozze strumenti +menu Palettes Tavolozze + Changes apply at once; Save Current As keeps them in a workspace. Le modifiche si applicano subito; Salva corrente con nome le conserva in un'area di lavoro. + Click layers to show only them; Ctrl or Shift adds to the choice. Fai clic sui layer per mostrare solo quelli; Ctrl o Maiusc li aggiungono alla scelta. + Current Workspace Area di lavoro corrente + Customize Interface Personalizza interfaccia + Customize User Interface Personalizza interfaccia utente + Customize... Personalizza... + Edit Aliases... Modifica alias... + Force object color and linetype to ByLayer Imposta colore e tipo di linea degli oggetti DaLayer + Geographic Location Posizione geografica + Geographic Location... Posizione geografica... + Latitude Latitudine + Longitude Longitudine + North direction Direzione del nord + Layer Translation Mappings Corrispondenze di conversione layer + Layer Translator Convertitore layer + Layer Translator... Convertitore layer... + Layer Walk Esplora layer + Layer Walk... Esplora layer... + Location Posizione + Set Location Imposta posizione + Remove Location Rimuovi posizione + The drawing's origin is at this place (WGS 84 degrees). L'origine del disegno si trova in questo luogo (gradi WGS 84). + Map Associa + New layer name Nome nuovo layer + No mappings yet: pick layers on the left, a name on the right, then Map. Nessuna corrispondenza: scegli i layer a sinistra, un nome a destra, poi Associa. + Translate Converti + Translate From Converti da + Translate To Converti in + Restore on exit Ripristina all'uscita + Point Cloud Nuvola di punti + Point Cloud... Nuvola di punti... + Point clouds (XYZ, LAS) Nuvole di punti (XYZ, LAS) + ZIP archive Archivio ZIP + eTransmit eTransmit + eTransmit... eTransmit... + Quick Access Toolbar Barra di accesso rapido + Rename Rinomina + Reset to Standard Ripristina standard + Ribbon Tabs Schede della barra multifunzione + Save Current As Salva corrente con nome + Save Current As... Salva corrente con nome... + Save Workspace Salva area di lavoro + User Interface Interfaccia utente + Workspace Settings Impostazioni area di lavoro + Workspace Settings... Impostazioni area di lavoro... + Workspace name Nome area di lavoro + Workspace: Area di lavoro: + Workspaces Aree di lavoro + Interface... Interfaccia... +menu Workspaces Aree di lavoro diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index f1555f47..42302818 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -101,7 +101,6 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet<String> { "canvas", "chrome", "cmdline", - "credits", "dialogs", "hatchdlg", "aliasdlg", diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index 04d6c7aa..fbc82c6d 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1508,3 +1508,117 @@ menu View 视图 Xref 外部参照 Xref Clip Frame 外部参照剪裁边框 Ribbon 功能区 + PDF Underlay... PDF 参考底图... + PDF Import PDF 输入 + PDF Underlay PDF 参考底图 + Underlay Layers 参考底图图层 + Adjust... 调整... + Close Text Editor 关闭文字编辑器 + Image Adjust 图像调整 + Image Clip 图像剪裁 + PDF Adjust PDF 调整 + PDF Clip PDF 剪裁 + Image 图像 + Action 动作 + Parameter 参数 + DesignCenter 设计中心 + Tool Palettes 工具选项板 + Sheet Set Manager 图纸集管理器 + Type the drawing's path, then press Enter. 输入图形的路径,然后按 Enter。 + Drawing file 图形文件 + Folder 文件夹 + Linetypes 线型 + Text Styles 文字样式 + Dimension Styles 标注样式 + Table Styles 表格样式 + Multileader Styles 多重引线样式 + Multiline Styles 多线样式 + Add to Drawing 添加到图形 + Create Tool Palette 创建工具选项板 + Nothing of this kind in the file. 文件中没有此类内容。 + Open a drawing to see its blocks, layers and styles. 打开图形以查看其块、图层和样式。 + Annotate 注释 + Delete Palette 删除选项板 + New Palette 新建选项板 + No tool palettes. 没有工具选项板。 + This palette is empty: add a command below, or make a palette from DesignCenter. 此选项板为空:在下方添加命令,或从设计中心创建选项板。 + Delete Tool 删除工具 + Add Command 添加命令 + New Sheet Set... 新建图纸集... + Open Sheet Set... 打开图纸集... + Sheet sets (DCSS) 图纸集 (DCSS) + Sheet set file 图纸集文件 + Make or open a sheet set to list its sheets. 新建或打开图纸集以列出其图纸。 + Add Drawing... 添加图形... + Publish to PDF... 发布为 PDF... + No sheets yet: add a drawing's layouts. 尚无图纸:请添加图形的布局。 + Number 编号 + Title 标题 + Move Up 上移 + Move Down 下移 + Sheet Set (DCSS) 图纸集 (DCSS) + Close Tool Palettes 关闭工具选项板 + Close DesignCenter 关闭设计中心 + Close Sheet Set Manager 关闭图纸集管理器 + Manage Tool Palettes 管理工具选项板 + Palettes 选项板 +menu Palettes 选项板 + 2D Drafting 二维草图与注释 + 2D Wireframe 二维线框 + Top 俯视 + CAD Standards CAD 标准 + Commands 命令 + Edit Aliases 编辑别名 + Edit Aliases... 编辑别名... + Changes apply at once; Save Current As keeps them in a workspace. 更改立即生效;“将当前另存为”会把它们保存在工作空间中。 + Click layers to show only them; Ctrl or Shift adds to the choice. 单击图层只显示这些图层;按住 Ctrl 或 Shift 可加入选择。 + Current Workspace 当前工作空间 + Customize Interface 自定义界面 + Customize User Interface 自定义用户界面 + Customize... 自定义... + Force object color and linetype to ByLayer 强制对象颜色和线型为随层 + Geographic Location 地理位置 + Geographic Location... 地理位置... + Latitude 纬度 + Longitude 经度 + North direction 北向 + Layer Translation Mappings 图层转换映射 + Layer Translator 图层转换器 + Layer Translator... 图层转换器... + Layer Walk 图层漫游 + Layer Walk... 图层漫游... + Location 位置 + Set Location 设置位置 + Remove Location 删除位置 + The drawing's origin is at this place (WGS 84 degrees). 图形原点位于此处(WGS 84 度)。 + Map 映射 + New layer name 新图层名 + No mappings yet: pick layers on the left, a name on the right, then Map. 尚无映射:在左侧选择图层,在右侧选择名称,然后单击“映射”。 + Translate 转换 + Translate From 转换自 + Translate To 转换为 + Restore on exit 退出时恢复 + Point Cloud 点云 + Point Cloud... 点云... + Point clouds (XYZ, LAS) 点云 (XYZ, LAS) + ZIP archive ZIP 压缩文件 + eTransmit 电子传递 + eTransmit... 电子传递... + Quick Access Toolbar 快速访问工具栏 + Rename 重命名 + Reset to Standard 重置为标准 + Ribbon Tabs 功能区选项卡 + Save Current As 将当前另存为 + Save Current As... 将当前另存为... + Save Workspace 保存工作空间 + User Interface 用户界面 + Workspace 工作空间 + Workspace Settings 工作空间设置 + Workspace Settings... 工作空间设置... + Workspace name 工作空间名称 + Workspace: 工作空间: + Workspaces 工作空间 + Interface... 界面... +menu Customize 自定义 +menu Workspaces 工作空间 +menu CAD Standards CAD 标准 diff --git a/crates/ui-egui/src/icons.rs b/crates/ui-egui/src/icons.rs index 041bbf32..eb9da7af 100644 --- a/crates/ui-egui/src/icons.rs +++ b/crates/ui-egui/src/icons.rs @@ -23,6 +23,7 @@ pub enum Icon { Import, Export, Attach, + Pdf, Share, ZoomWindow, Pan, @@ -159,6 +160,29 @@ pub enum Icon { ZoomFit, TextStyle, DimStyle, + Bold, + Italic, + Underline, + Overline, + AlignLeft, + AlignCenter, + AlignRight, + AlignJustify, + Bullets, + Numbering, + Symbol, + Adjust, + ClipFrame, + CloseTab, + DesignCenter, + ToolPalette, + SheetSet, + Transmit, + LayerWalk, + LayerTranslate, + GeoLocation, + PointCloud, + Customize, } struct Pen<'a> { @@ -258,6 +282,7 @@ pub fn paint(p: &Painter, rect: Rect, icon: Icon, dim: bool) { paint_display_toggles(&pen, icon, b, a, dim); paint_navigation_controls(&pen, icon, b, a, dim); paint_constraints(&pen, icon, b, a, dim); + paint_context_tools(&pen, icon, b, a); } fn paint_file_view(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, dim: bool) { @@ -341,6 +366,13 @@ fn paint_file_view(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32, dim: bool) pen.big_arrow(24.0, 13.0, 1.0, 0.0, 7.0, 5.0, a); } } + Pdf => { + // A page with a folded corner and a band across it lettered PDF (our own drawing). + pen.poly(&[(5.0, 2.0), (14.0, 2.0), (19.0, 7.0), (19.0, 22.0), (5.0, 22.0)], true, b); + pen.poly(&[(14.0, 2.0), (14.0, 7.0), (19.0, 7.0)], false, b); + pen.rect(2.0, 11.0, 17.0, 7.0, a); + pen.text(10.5, 14.5, "PDF", 6.5, a); + } Attach => { pen.rect(4.0, 5.0, 16.0, 14.0, b); pen.poly(&[(6.0, 17.0), (10.0, 11.0), (13.0, 15.0), (15.0, 13.0), (18.0, 17.0)], false, a); @@ -1211,3 +1243,136 @@ pub fn describe_control(ui: &egui::Ui, response: &egui::Response, label: &str, s } crate::control::record_widget(ui, response, label, if tab { "tab" } else { "button" }, selected); } + +/// The contextual ribbon tabs' tools: text formatting, image adjustment and clipping, and the +/// green tick that closes a contextual tab (our own drawings). +fn paint_context_tools(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32) { + use Icon::*; + let lines = |xs: [(f32, f32); 4]| { + for (i, (x0, x1)) in xs.iter().enumerate() { + let y = 5.0 + i as f32 * 4.6; + pen.l(*x0, y, *x1, y); + } + }; + match icon { + Bold => pen.text(12.0, 12.0, "B", 19.0, b), + Italic => { + pen.p.line_segment([pen.at(14.0, 4.0), pen.at(10.0, 20.0)], Stroke::new(pen.w * 2.2, b)); + pen.l(11.0, 4.0, 18.0, 4.0); + pen.l(7.0, 20.0, 14.0, 20.0); + } + Underline | Overline => { + pen.text(12.0, 11.5, "U", 16.0, b); + let y = if icon == Underline { 21.0 } else { 3.0 }; + pen.p.line_segment([pen.at(6.0, y), pen.at(18.0, y)], Stroke::new(pen.w * 1.6, a)); + } + AlignLeft => lines([(4.0, 20.0), (4.0, 14.0), (4.0, 20.0), (4.0, 12.0)]), + AlignCenter => lines([(4.0, 20.0), (7.0, 17.0), (4.0, 20.0), (8.0, 16.0)]), + AlignRight => lines([(4.0, 20.0), (10.0, 20.0), (4.0, 20.0), (12.0, 20.0)]), + AlignJustify => lines([(4.0, 20.0), (4.0, 20.0), (4.0, 20.0), (4.0, 20.0)]), + Bullets | Numbering => { + for i in 0..3 { + let y = 6.0 + i as f32 * 6.0; + if icon == Bullets { + pen.fill_c(5.5, y, 1.6, a); + } else { + pen.text(5.5, y, &(i + 1).to_string(), 7.0, a); + } + pen.l(10.0, y, 20.0, y); + } + } + Symbol => pen.text(12.0, 12.5, "@", 18.0, b), + Adjust => { + // Three sliders. + for (i, k) in [7.0, 15.0, 10.0].iter().enumerate() { + let y = 6.0 + i as f32 * 6.0; + pen.l(3.0, y, 21.0, y); + pen.fill_rect(k - 1.5, y - 2.5, 3.0, 5.0, a); + } + } + ClipFrame => { + pen.rect(3.0, 6.0, 14.0, 12.0, b); + pen.poly(&[(9.0, 3.0), (21.0, 3.0), (21.0, 13.0), (9.0, 13.0)], true, a); + } + CloseTab => { + let green = Color32::from_rgb(0x3c, 0xa0, 0x50); + pen.p.line_segment([pen.at(4.0, 13.0), pen.at(9.5, 18.5)], Stroke::new(pen.w * 2.6, green)); + pen.p.line_segment([pen.at(9.5, 18.5), pen.at(20.0, 5.5)], Stroke::new(pen.w * 2.6, green)); + } + _ => paint_manager_tools(pen, icon, b, a), + } +} + +/// The palettes and managers: DesignCenter, Tool Palettes, Sheet Set Manager, eTransmit, layer +/// walk and translate, geographic location, point clouds and customisation (our own +/// drawings). +fn paint_manager_tools(pen: &Pen<'_>, icon: Icon, b: Color32, a: Color32) { + use Icon::*; + match icon { + DesignCenter => { + // A folder tree beside a block. + pen.rect(3.0, 4.0, 7.0, 16.0, b); + pen.l(5.0, 8.0, 8.0, 8.0); + pen.l(5.0, 12.0, 8.0, 12.0); + pen.l(5.0, 16.0, 8.0, 16.0); + pen.rect(12.0, 7.0, 9.0, 9.0, a); + pen.l(12.0, 7.0, 21.0, 16.0); + } + ToolPalette => { + // A tall palette with three tools. + pen.rect(5.0, 3.0, 14.0, 18.0, b); + for i in 0..3 { + let y = 7.0 + i as f32 * 5.0; + pen.fill_rect(8.0, y - 1.5, 3.0, 3.0, a); + pen.l(13.0, y, 17.0, y); + } + } + SheetSet => { + // Three stacked sheets. + pen.rect(9.0, 3.0, 11.0, 14.0, b); + pen.rect(6.5, 5.5, 11.0, 14.0, b); + pen.rect(4.0, 8.0, 11.0, 13.0, a); + } + Transmit => { + // A package with an arrow out of it. + pen.rect(3.0, 10.0, 12.0, 10.0, b); + pen.l(3.0, 14.0, 15.0, 14.0); + pen.l(12.0, 8.0, 20.0, 3.0); + pen.poly(&[(15.0, 3.0), (20.0, 3.0), (20.0, 8.0)], false, a); + } + LayerWalk | LayerTranslate => { + // Two layer sheets, and an eye or an arrow between them. + pen.poly(&[(3.0, 8.0), (12.0, 4.0), (21.0, 8.0), (12.0, 12.0)], true, b); + pen.poly(&[(3.0, 15.0), (12.0, 11.0), (21.0, 15.0), (12.0, 19.0)], true, b); + if icon == LayerWalk { + pen.c(12.0, 20.0, 2.5, a); + pen.fill_c(12.0, 20.0, 1.0, a); + } else { + pen.l(17.0, 18.0, 22.0, 22.0); + pen.poly(&[(19.0, 22.0), (22.0, 22.0), (22.0, 19.0)], false, a); + } + } + GeoLocation => { + // A map pin over a globe line. + pen.c(12.0, 9.0, 5.0, a); + pen.fill_c(12.0, 9.0, 1.6, a); + pen.poly(&[(8.0, 12.0), (12.0, 20.0), (16.0, 12.0)], false, a); + pen.l(3.0, 20.0, 21.0, 20.0); + } + PointCloud => { + for (x, y) in + [(5.0, 8.0), (9.0, 5.0), (13.0, 9.0), (18.0, 6.0), (7.0, 14.0), (12.0, 15.0), (17.0, 13.0), (10.0, 19.0), (15.0, 19.0), (20.0, 17.0)] + { + pen.fill_c(x, y, 1.3, if (x as i32 + y as i32) % 3 == 0 { a } else { b }); + } + } + Customize => { + // A wrench over a small window. + pen.rect(3.0, 4.0, 12.0, 10.0, b); + pen.l(3.0, 7.0, 15.0, 7.0); + pen.p.line_segment([pen.at(11.0, 20.0), pen.at(18.0, 13.0)], Stroke::new(pen.w * 2.4, a)); + pen.c(19.0, 12.0, 2.6, a); + } + _ => {} + } +} diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 7331d036..95c28780 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -72,6 +72,7 @@ pub mod viewcube; pub mod vpscale; #[cfg(not(target_arch = "wasm32"))] pub mod window_frame; +pub mod workspaces; pub mod exchange; @@ -141,6 +142,14 @@ pub struct UiState { pub recent_files: Vec<String>, /// The folder the last APPLOAD file came from: the next pick starts there. pub last_lisp_dir: Option<String>, + /// The Quick Access Toolbar's commands (CUI); `None`: the standard ones. + pub qat: Option<Vec<String>>, + /// Ribbon tabs the user hid (CUI). + pub hidden_tabs: Vec<String>, + /// Saved workspaces (WORKSPACE); the built-in "2D Drafting" isn't among them. + pub workspaces: Vec<workspaces::SavedWorkspace>, + /// The current workspace's name; empty: the built-in one. + pub current_workspace: String, } /// A DXF/DWG file version (2000 … 2018). @@ -223,6 +232,10 @@ impl Default for UiState { save_version: SaveVersion::default().year().to_string(), recent_files: Vec::new(), last_lisp_dir: None, + qat: None, + hidden_tabs: Vec::new(), + workspaces: Vec::new(), + current_workspace: String::new(), } } } @@ -236,6 +249,9 @@ pub struct Services { /// `None` where there is no native file dialog: the desktop without one asks for the name, /// and the web (no file system) says to drop the file (`no_file_system`). pub pick_lisp: Option<Box<dyn Fn(&str) -> Option<String>>>, + /// Pick a file to read of the given kind: a filter label and its extensions (ATTACH, + /// PDFATTACH, PDFIMPORT, IMAGEATTACH). `None` where there is no native file dialog. + pub pick_file: Option<Box<dyn Fn(&str, &[&str]) -> Option<String>>>, /// The host has no file system to read a path from (the browser): a dropped file's contents /// are what it loads, and APPLOAD says so instead of asking for a name it cannot read. pub no_file_system: bool, @@ -258,6 +274,8 @@ pub struct CadApp { pub spacemouse: spacemouse::State, /// Calculator data shared by its floating and docked views; durable fields live in prefs. pub(crate) quickcalc: palettes::quickcalc::State, + /// DesignCenter, Tool Palettes and the Sheet Set Manager; the tool palettes live in prefs. + pub(crate) side_palettes: palettes::SidePalettes, pub cmd: cmdline::CmdLine, pub status: Option<(String, f64)>, /// Drawings being read on worker threads ([`opening`]). @@ -334,6 +352,8 @@ pub struct CadApp { pub hatch_dlg: Option<hatchdlg::HatchDlgState>, /// The Edit Block Definition dialog ([`bedit`]). pub bedit: bedit::State, + /// The contextual ribbon tab shown and the tab before it ([`ribbon::context`]). + pub(crate) ribbon_context: ribbon::context::State, /// The startup update check and its prompt (desktop; [`updates_ui`]). #[cfg(not(target_arch = "wasm32"))] pub updates_rt: updates_ui::Runtime, @@ -353,6 +373,7 @@ impl CadApp { canvas: canvas::CanvasState::default(), spacemouse: spacemouse::State::default(), quickcalc: palettes::quickcalc::State::default(), + side_palettes: palettes::SidePalettes::default(), cmd: cmdline::CmdLine::default(), status: None, opening: opening::Opening::default(), @@ -393,6 +414,7 @@ impl CadApp { alias_dlg: None, hatch_dlg: None, bedit: bedit::State::default(), + ribbon_context: ribbon::context::State::default(), #[cfg(not(target_arch = "wasm32"))] updates_rt: updates_ui::Runtime::default(), } @@ -495,6 +517,7 @@ impl CadApp { "saveFormat": self.ui.save_format.as_str(), "saveVersion": self.ui.save_version, "quickcalc": self.quickcalc.prefs(), + "toolPalettes": self.side_palettes.tool_palettes.prefs(), }); if self.spacemouse.settings != spacemouse::Settings::default() { prefs["spacemouse"] = json!(self.spacemouse.settings); @@ -514,6 +537,9 @@ impl CadApp { if let Some(calculator) = v.get("quickcalc") { self.quickcalc.load_prefs(calculator); } + if let Some(tp) = v.get("toolPalettes") { + self.side_palettes.tool_palettes.load_prefs(tp); + } if let Some(prefs) = v.get("spacemouse") { let _ = self.spacemouse.load_settings(prefs); } diff --git a/crates/ui-egui/src/managers.rs b/crates/ui-egui/src/managers.rs index 61225c28..119d98d3 100644 --- a/crates/ui-egui/src/managers.rs +++ b/crates/ui-egui/src/managers.rs @@ -17,6 +17,8 @@ use crate::theme::Tokens; /// The Block Attribute Manager (BATTMAN). mod battman; +/// Layer Translator, Layer Walk and Geographic Location. +mod layertools; /// Named Viewports (View > Viewports > Named Viewports...). mod named_vports; @@ -36,6 +38,9 @@ pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, "pagesetup" => "pagesetup", "constraintsettings" | "csettings" => "csettings", "vports.named" => "namedvports", + "laytrans" => "laytrans", + "laywalk" => "laywalk", + "geographiclocation" | "geo" => "geo", "plot" | "print" => { PLOT_GEN.fetch_add(1, Ordering::Relaxed); "plot" @@ -58,6 +63,9 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool "pagesetup" => page_setup(app, ctx, open), "csettings" => constraint_settings(app, ctx, open), "namedvports" => named_vports::dialog(app, ctx, open), + "laytrans" => layertools::laytrans(app, ctx, open), + "laywalk" => layertools::laywalk(app, ctx, open), + "geo" => layertools::geo(app, ctx, open), "plot" => plot(app, ctx, open), _ => { *open = false; diff --git a/crates/ui-egui/src/managers/layertools.rs b/crates/ui-egui/src/managers/layertools.rs new file mode 100644 index 00000000..6355d401 --- /dev/null +++ b/crates/ui-egui/src/managers/layertools.rs @@ -0,0 +1,265 @@ +//! Layer Translator (LAYTRANS), Layer Walk (LAYWALK) and Geographic Location +//! (GEOGRAPHICLOCATION) dialogs. They read the drawing and change it only through those +//! commands, so every change is scriptable. + +use std::collections::BTreeSet; + +use egui::{RichText, vec2}; +use serde_json::{Value, json}; + +use super::Action; +use crate::CadApp; +use crate::theme::Tokens; + +fn temp<T: Clone + Send + Sync + 'static>(ctx: &egui::Context, id: &str) -> Option<T> { + ctx.data_mut(|d| d.get_temp::<T>(egui::Id::unique(id))) +} + +fn set_temp<T: Clone + Send + Sync + 'static>(ctx: &egui::Context, id: &str, v: T) { + ctx.data_mut(|d| d.insert_temp(egui::Id::unique(id), v)); +} + +fn layer_names(app: &CadApp) -> Vec<String> { + app.session.doc().map(|d| d.layers.iter().map(|l| l.name.clone()).collect()).unwrap_or_default() +} + +// ---------- Layer Translator ---------- + +/// The translator's state while the dialog is open. +#[derive(Clone, Default)] +struct Trans { + from: BTreeSet<String>, + to: String, + standards: String, + /// The standards drawing's layers. + targets: Vec<String>, + map: Vec<(String, String)>, + force: bool, + error: Option<String>, +} + +pub(super) fn laytrans(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { + const KEY: &str = "laytrans-state"; + let t = Tokens::get(); + let mut st: Trans = temp(ctx, KEY).unwrap_or_default(); + let names = layer_names(app); + let mut action = None; + let mut load: Option<String> = None; + let mut close = false; + egui::Window::new(crate::tl!("Layer Translator")).open(open).collapsible(false).resizable(true).default_width(520.0).show(ctx, |ui| { + ui.columns(2, |cols| { + cols[0].strong(crate::tl!("Translate From")); + egui::ScrollArea::vertical().id_salt("laytrans-from").max_height(220.0).show(&mut cols[0], |ui| { + for n in &names { + let on = st.from.contains(n); + if ui.selectable_label(on, n).clicked() { + if on { + st.from.remove(n); + } else { + st.from.insert(n.clone()); + } + } + } + }); + cols[1].strong(crate::tl!("Translate To")); + cols[1].horizontal(|ui| { + if ui.button(crate::tl!("Load...")).clicked() { + load = app.services.pick_file.as_ref().and_then(|pick| pick("Drawings (DWG, DXF)", &["dwg", "dxf"])); + } + ui.label(RichText::new(st.standards.rsplit(['/', '\\']).next().unwrap_or_default()).color(t.text_dim)); + }); + egui::ScrollArea::vertical().id_salt("laytrans-to").max_height(170.0).show(&mut cols[1], |ui| { + for n in &st.targets { + if ui.selectable_label(*n == st.to, n).clicked() { + st.to = n.clone(); + } + } + }); + cols[1].add(egui::TextEdit::singleline(&mut st.to).hint_text(crate::tl!("New layer name"))); + }); + ui.horizontal(|ui| { + let can = !st.from.is_empty() && !st.to.trim().is_empty(); + if ui.add_enabled(can, egui::Button::new(crate::tl!("Map"))).clicked() { + let to = st.to.trim().to_string(); + for f in std::mem::take(&mut st.from) { + st.map.retain(|(a, _)| *a != f); + st.map.push((f, to.clone())); + } + } + ui.checkbox(&mut st.force, crate::tl!("Force object color and linetype to ByLayer")); + }); + ui.separator(); + ui.strong(crate::tl!("Layer Translation Mappings")); + let mut remove = None; + egui::ScrollArea::vertical().id_salt("laytrans-map").max_height(140.0).show(ui, |ui| { + if st.map.is_empty() { + ui.label(RichText::new(crate::tl!("No mappings yet: pick layers on the left, a name on the right, then Map.")).color(t.text_dim)); + } + for (i, (f, to)) in st.map.iter().enumerate() { + ui.horizontal(|ui| { + ui.label(format!("{f} → {to}")); + if ui.small_button("×").on_hover_text(crate::tl!("Remove")).clicked() { + remove = Some(i); + } + }); + } + }); + if let Some(i) = remove { + st.map.remove(i); + } + if let Some(e) = &st.error { + ui.colored_label(t.warn, e); + } + ui.horizontal(|ui| { + if ui.add_enabled(!st.map.is_empty(), egui::Button::new(crate::tl!("Translate"))).clicked() { + let map: serde_json::Map<String, Value> = st.map.iter().map(|(f, to)| (f.clone(), json!(to))).collect(); + let mut p = json!({ "map": map, "forceByLayer": st.force }); + if !st.standards.is_empty() { + p["standards"] = json!(st.standards); + } + action = Some(("laytrans", p)); + close = true; + } + if ui.button(crate::tl!("Cancel")).clicked() { + close = true; + } + }); + }); + if let Some(path) = load { + match app.run("adcenter", json!({ "path": path })) { + Ok(v) => { + st.targets = v["layers"].as_array().map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default(); + st.standards = path; + st.error = None; + } + Err(e) => st.error = Some(e), + } + } + if close { + *open = false; + } + if *open { + set_temp(ctx, KEY, st); + } else { + ctx.data_mut(|d| d.remove::<Trans>(egui::Id::unique(KEY))); + } + action +} + +// ---------- Layer Walk ---------- + +#[derive(Clone)] +struct Walk { + shown: BTreeSet<String>, + restore: bool, +} + +pub(super) fn laywalk(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { + const KEY: &str = "laywalk-state"; + let names = layer_names(app); + let mut st: Walk = temp(ctx, KEY).unwrap_or_else(|| Walk { shown: BTreeSet::new(), restore: true }); + let mut action = None; + let mut close = false; + let t = Tokens::get(); + egui::Window::new(crate::tl!("Layer Walk")).open(open).collapsible(false).resizable(true).default_width(260.0).show(ctx, |ui| { + ui.label(RichText::new(crate::tl!("Click layers to show only them; Ctrl or Shift adds to the choice.")).color(t.text_dim)); + egui::ScrollArea::vertical().id_salt("laywalk-list").max_height(320.0).show(ui, |ui| { + for n in &names { + let on = st.shown.contains(n); + if ui.selectable_label(on, n).clicked() { + let multi = ui.input(|i| i.modifiers.command || i.modifiers.shift); + if !multi { + st.shown.clear(); + } + if on && multi { + st.shown.remove(n); + } else { + st.shown.insert(n.clone()); + } + action = Some(("laywalk", json!({ "layers": st.shown.iter().collect::<Vec<_>>() }))); + } + } + }); + ui.add_space(vec2(0.0, 4.0).y); + ui.checkbox(&mut st.restore, crate::tl!("Restore on exit")); + if ui.button(crate::tl!("Close")).clicked() { + close = true; + } + }); + if close { + *open = false; + } + if *open { + set_temp(ctx, KEY, st); + } else { + ctx.data_mut(|d| d.remove::<Walk>(egui::Id::unique(KEY))); + // Closing ends the walk; it ran only if a layer was picked. + if app.session.laywalk.is_some() { + return Some(("laywalk", json!({ "operation": "end", "restore": st.restore }))); + } + } + action +} + +// ---------- Geographic Location ---------- + +#[derive(Clone)] +struct Geo { + latitude: String, + longitude: String, + north: String, +} + +pub(super) fn geo(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) -> Action { + const KEY: &str = "geo-state"; + let has = app.session.doc().is_ok_and(|d| d.header.get("LATITUDE").is_some() && d.header.get("LONGITUDE").is_some()); + let mut st: Geo = temp(ctx, KEY).unwrap_or_else(|| { + let h = app.session.doc().map(|d| d.header.clone()).unwrap_or_default(); + let f = |k: &str| h.get(k).and_then(draftcraft_engine::doc::HVal::as_f64).map(|v| format!("{v:.6}")).unwrap_or_default(); + let north = h + .get("NORTHDIRECTION") + .and_then(draftcraft_engine::doc::HVal::as_f64) + .map(|v| format!("{:.2}", v.to_degrees())) + .unwrap_or_else(|| "0".into()); + Geo { latitude: f("LATITUDE"), longitude: f("LONGITUDE"), north } + }); + let t = Tokens::get(); + let mut action = None; + let mut close = false; + egui::Window::new(crate::tl!("Geographic Location")).open(open).collapsible(false).resizable(false).show(ctx, |ui| { + ui.label(RichText::new(crate::tl!("The drawing's origin is at this place (WGS 84 degrees).")).color(t.text_dim)); + egui::Grid::new("geo-grid").num_columns(2).spacing(vec2(8.0, 6.0)).show(ui, |ui| { + for (label, value) in [("Latitude", &mut st.latitude), ("Longitude", &mut st.longitude), ("North direction", &mut st.north)] { + let l = ui.label(crate::i18n::t(label)); + ui.add(egui::TextEdit::singleline(value).desired_width(140.0)).labelled_by(l.id); + ui.end_row(); + } + }); + ui.horizontal(|ui| { + let num = |s: &str| s.trim().replace(',', ".").parse::<f64>().ok().filter(|v| v.is_finite()); + let parsed = (num(&st.latitude), num(&st.longitude), num(&st.north)); + if ui.add_enabled(parsed.0.is_some() && parsed.1.is_some(), egui::Button::new(crate::tl!("OK"))).clicked() + && let (Some(la), Some(lo)) = (parsed.0, parsed.1) + { + action = Some(("geographiclocation", json!({ "latitude": la, "longitude": lo, "north": parsed.2.unwrap_or(0.0) }))); + close = true; + } + if ui.add_enabled(has, egui::Button::new(crate::tl!("Remove Location"))).clicked() { + action = Some(("georemove", json!({}))); + close = true; + } + if ui.button(crate::tl!("Cancel")).clicked() { + close = true; + } + }); + }); + if close { + *open = false; + } + if *open { + set_temp(ctx, KEY, st); + } else { + ctx.data_mut(|d| d.remove::<Geo>(egui::Id::unique(KEY))); + } + action +} diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index ca46aa53..558f0dad 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -32,6 +32,11 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("ui.panel.layers", "Layers Palette", &["Window", "Layers Palette"], None), ("ui.toggle.quickcalc", "QuickCalc", &["Window", "QuickCalc"], Some("Cmd+8")), ("ui.panel.quickcalc", "QuickCalc", &[], None), + ("toolpalettes", "Tool Palettes", &["Tools", "Palettes", "Tool Palettes"], None), + ("toolpalettesclose", "Close Tool Palettes", &[], None), + ("adcclose", "Close DesignCenter", &[], None), + ("sheetsethide", "Close Sheet Set Manager", &[], None), + ("ui.toolpalettes", "Manage Tool Palettes", &[], None), ("ui.toggle.systemcursor", "Show System Cursor", &["View", "Accessibility", "Show System Cursor"], None), ("ui.animations.system", "Use System Setting", &["View", "Accessibility", "Animation Effects", "Use System Setting"], None), ("ui.animations.on", "On", &["View", "Accessibility", "Animation Effects", "On"], None), @@ -78,7 +83,32 @@ pub const UI_COMMANDS: &[(&str, &str, &[&str], Option<&str>)] = &[ ("ui.dialog.find", "Find and Replace", &[], Some("Cmd+F")), ("ui.language", "Language", &[], None), ("ui.noop", "", &[], None), + // The contextual ribbon tabs' buttons (crate::ribbon::context). + ("ui.context.close", "Close", &[], None), + ("ui.mtext.bold", "Bold", &[], None), + ("ui.mtext.italic", "Italic", &[], None), + ("ui.mtext.underline", "Underline", &[], None), + ("ui.mtext.overline", "Overline", &[], None), + ("ui.mtext.left", "Left", &[], None), + ("ui.mtext.center", "Center", &[], None), + ("ui.mtext.right", "Right", &[], None), + ("ui.mtext.justify", "Justify", &[], None), + ("ui.mtext.bullets", "Bulleted list", &[], None), + ("ui.mtext.numbers", "Numbered list", &[], None), + ("ui.mtext.degree", "Degree", &[], None), + ("ui.mtext.plusminus", "Plus/minus", &[], None), + ("ui.mtext.diameter", "Diameter", &[], None), + ("ui.mtext.tab", "Insert tab", &[], None), + ("ui.mtext.ok", "Close Text Editor", &[], None), + ("ui.mtext.cancel", "Cancel", &[], None), ("ui.quit", "Quit DraftCraft", &[], Some("Cmd+Q")), + ("cui", "Customize User Interface", &["Tools", "Customize", "Interface..."], None), + ("workspace", "Workspaces", &["Tools", "Workspaces", "Workspace Settings..."], None), + ("-workspace", "Workspaces", &[], None), + ("wscurrent", "Current Workspace", &[], None), + ("wssave", "Save Workspace", &["Tools", "Workspaces", "Save Current As..."], None), + ("wssettings", "Workspace Settings", &[], None), + ("ui.cui", "Customize Interface", &[], None), ]; pub fn is_ui_command(id: &str) -> bool { @@ -100,9 +130,18 @@ fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value) -> Option<Res if let Some(r) = crate::bedit::route(app, id, params) { return Some(r); } + if let Some(r) = crate::ribbon::context::route(app, id, params) { + return Some(r); + } + if let Some(r) = crate::palettes::route(app, id, params) { + return Some(r); + } if let Some(r) = crate::managers::route(app, id, params) { return Some(r); } + if let Some(r) = crate::workspaces::route(app, id, params) { + return Some(r); + } if matches!(id, "ui.dock" | "ui.dock.reset") { return Some(crate::docking::command(app, id == "ui.dock.reset", params)); } @@ -419,7 +458,10 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Re app.ui.start_tab = false; Ok(Value::Null) } - "export" | "exp" | "import" | "imp" | "publish" | "preview" | "pre" if params.is_null() && app.session.state().is_ok() => { + "export" | "exp" | "import" | "imp" | "publish" | "preview" | "pre" | "attach" | "imageattach" | "iat" | "pdfattach" | "pdfat" + | "pdfimport" | "etransmit" | "pointcloudattach" | "pcattach" | "pointcloud" + if params.is_null() && app.session.state().is_ok() => + { return Some(crate::exchange::route(app, id)); } "ui.hidepalettes" => { diff --git a/crates/ui-egui/src/mtext_editor.rs b/crates/ui-egui/src/mtext_editor.rs index 176e4f1c..81ff9c59 100644 --- a/crates/ui-egui/src/mtext_editor.rs +++ b/crates/ui-egui/src/mtext_editor.rs @@ -91,12 +91,67 @@ fn color32(c: MTextColor) -> Color32 { Color32::from_rgb(rgb.0, rgb.1, rgb.2) } +/// The Text Editor ribbon tab's buttons (`ui.mtext.<action>`), applied on the editor's next frame. +pub(crate) const ACTIONS: &[&str] = &[ + "bold", + "italic", + "underline", + "overline", + "left", + "center", + "right", + "justify", + "bullets", + "numbers", + "degree", + "plusminus", + "diameter", + "tab", + "ok", + "cancel", +]; + +/// Whether the editor is open: MTEXT is collecting its text. +pub(crate) fn is_open(app: &CadApp) -> bool { + app.session.editing_mtext().is_some() && app.session.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point) +} + +/// Apply a Text Editor ribbon button to the editor's selection (or the next typed text). +/// `Some` when it ends the editor. +fn ribbon_action(st: &mut State, action: &str, base_h: f64) -> Option<Done> { + let range = st.sel.0.min(st.sel.1)..st.sel.0.max(st.sel.1); + let align = |st: &mut State, al: ParaAlign| { + let on = st.fmt.para(st.fmt.paragraph_of(range.start)).align == al; + st.fmt.edit_paras(range.clone(), |p| p.align = if on { ParaAlign::Default } else { al }); + }; + match action { + "bold" => toggle(st, Flag::Bold), + "italic" => toggle(st, Flag::Italic), + "underline" => toggle(st, Flag::Underline), + "overline" => toggle(st, Flag::Overline), + "left" => align(st, ParaAlign::Left), + "center" => align(st, ParaAlign::Center), + "right" => align(st, ParaAlign::Right), + "justify" => align(st, ParaAlign::Justify), + "bullets" => st.fmt.make_list(range.clone(), ListStyle::Bullet, 3.0 * base_h), + "numbers" => st.fmt.make_list(range.clone(), ListStyle::Number, 3.0 * base_h), + "degree" => insert(st, "°"), + "plusminus" => insert(st, "±"), + "diameter" => insert(st, "⌀"), + "tab" => insert(st, "\t"), + "ok" => return Some(Done::Ok), + "cancel" => return Some(Done::Cancel), + _ => {} + } + None +} + /// Show the editor while MTEXT collects its text; clears its state when it isn't running. pub fn show(app: &mut CadApp, ctx: &egui::Context) { let mtext = app.session.editing_mtext(); - let asking = app.session.current_prompt().is_some_and(|p| p.accept.text && !p.accept.point); - let (Some(mt), true) = (mtext, asking) else { + let (Some(mt), true) = (mtext, is_open(app)) else { ctx.data_mut(|d| d.remove::<State>(state_id())); + app.ribbon_context.text_action = None; return; }; let t = Tokens::get(); @@ -124,6 +179,12 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { let pos = pos2(at.x.clamp(rect.left(), max_x), at.y.clamp(rect.top() + st.top, (rect.bottom() - 120.0).max(rect.top() + st.top))); let mut done = Done::No; + if let Some(action) = app.ribbon_context.text_action.take() { + if let Some(d) = ribbon_action(&mut st, action, base_h) { + done = d; + } + ctx.memory_mut(|m| m.request_focus(edit_id())); + } let top_start = pos.y - st.top; egui::Area::new(egui::Id::unique("mtext_editor_area")).order(egui::Order::Foreground).fixed_pos(pos2(pos.x, top_start)).show(ctx, |ui| { egui::Frame::NONE.fill(t.panel).stroke(Stroke::new(1.0, t.accent)).inner_margin(egui::Margin::same(0)).show(ui, |ui| { @@ -146,7 +207,9 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { }); }); }); - if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { + if done != Done::No { + // A ribbon button ended the editor. + } else if ctx.input(|i| i.key_pressed(egui::Key::Escape)) { done = Done::Cancel; } else if ctx.input(|i| i.modifiers.command && i.key_pressed(egui::Key::Enter)) { done = Done::Ok; diff --git a/crates/ui-egui/src/palettes.rs b/crates/ui-egui/src/palettes.rs index b084b19a..ee566961 100644 --- a/crates/ui-egui/src/palettes.rs +++ b/crates/ui-egui/src/palettes.rs @@ -9,12 +9,44 @@ use crate::CadApp; use crate::icons::{self, Icon}; use crate::theme::Tokens; +/// DesignCenter (ADCENTER). +pub mod designcenter; #[cfg(test)] mod layer_menu_tests; /// The hatch pattern picker. pub mod patterns; /// The QuickCalc palette. pub mod quickcalc; +/// The Sheet Set Manager (SHEETSET). +pub mod sheetset; +/// The Tool Palettes window (TOOLPALETTES). +pub mod toolpalettes; + +/// The DesignCenter, Tool Palettes and Sheet Set Manager palettes' state. +#[derive(Default)] +pub struct SidePalettes { + pub design_center: designcenter::State, + pub tool_palettes: toolpalettes::State, + pub sheet_set: sheetset::State, +} + +/// Open or close DesignCenter, Tool Palettes and the Sheet Set Manager: typed or chosen without +/// parameters (ADCENTER, TOOLPALETTES, SHEETSET and their CLOSE/HIDE commands); `ui.toolpalettes` +/// manages the tool palettes. +pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> { + use crate::docking::{Panel, command}; + let close = |app: &mut CadApp, panel: Panel| command(app, false, &json!({ "operation": "close", "panel": panel.id() })); + match id { + "ui.toolpalettes" => Some(app.side_palettes.tool_palettes.command(params)), + "toolpalettes" | "tp" if params.is_null() => Some(toolpalettes::open(app)), + "toolpalettesclose" => Some(close(app, Panel::ToolPalettes)), + "adcenter" | "adc" | "dc" | "dcenter" if params.is_null() => Some(designcenter::open(app)), + "adcclose" => Some(close(app, Panel::DesignCenter)), + "sheetset" | "ssm" | "opensheetset" | "newsheetset" if params.is_null() => Some(sheetset::open(app)), + "sheetsethide" => Some(close(app, Panel::SheetSet)), + _ => None, + } +} type Tool = (Icon, &'static str, &'static str); diff --git a/crates/ui-egui/src/palettes/designcenter.rs b/crates/ui-egui/src/palettes/designcenter.rs new file mode 100644 index 00000000..9037deaa --- /dev/null +++ b/crates/ui-egui/src/palettes/designcenter.rs @@ -0,0 +1,262 @@ +//! The DesignCenter palette (ADCENTER): pick a drawing file, look at its blocks, layers, +//! linetypes and styles, and add the chosen ones to the current drawing, insert a block, or make +//! a tool palette of the file's blocks. Everything goes through the engine's ADCENTER command. + +use std::collections::BTreeSet; + +use egui::vec2; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// The content kinds with their labels, in ADCENTER's `kind` names. +pub(crate) const KINDS: &[(&str, &str)] = &[ + ("blocks", "Blocks"), + ("layers", "Layers"), + ("linetypes", "Linetypes"), + ("textStyles", "Text Styles"), + ("dimStyles", "Dimension Styles"), + ("tableStyles", "Table Styles"), + ("mleaderStyles", "Multileader Styles"), + ("mlineStyles", "Multiline Styles"), +]; + +/// Most drawings the folder list shows. +const MAX_FOLDER: usize = 500; + +/// What the palette is looking at. +#[derive(Default)] +pub struct State { + /// The drawing file typed or picked. + pub(crate) path: String, + /// ADCENTER's listing of the loaded file. + pub(crate) listing: Option<Value>, + pub(crate) kind: usize, + pub(crate) selected: BTreeSet<String>, + /// The drawings in the loaded file's folder. + folder: Vec<String>, + error: Option<String>, +} + +impl State { + /// List `path` with ADCENTER; on success it becomes the file shown. + pub(crate) fn load(&mut self, app: &mut CadApp, path: &str) { + match app.run("adcenter", json!({ "path": path })) { + Ok(v) => { + self.path = path.to_string(); + self.listing = Some(v); + self.selected.clear(); + self.error = None; + self.folder = folder_drawings(path); + } + Err(e) => self.error = Some(e), + } + } + + fn kind_id(&self) -> &'static str { + KINDS.get(self.kind).map(|k| k.0).unwrap_or("blocks") + } + + /// The names of the current kind in the listing. + fn names(&self) -> Vec<(String, Option<u64>)> { + let Some(l) = &self.listing else { return Vec::new() }; + let Some(items) = l.get(self.kind_id()).and_then(Value::as_array) else { return Vec::new() }; + items + .iter() + .filter_map(|v| match v { + Value::String(s) => Some((s.clone(), None)), + Value::Object(o) => o.get("name").and_then(Value::as_str).map(|n| (n.to_string(), o.get("objects").and_then(Value::as_u64))), + _ => None, + }) + .collect() + } + + /// Copy the selected names into the drawing. Returns whether the command ran. + fn add(&mut self, app: &mut CadApp, names: Vec<String>) -> bool { + let r = app.run("adcenter", json!({ "path": self.path, "kind": self.kind_id(), "names": names })); + match r { + Ok(v) => { + if let Some(m) = v.get("message").and_then(Value::as_str) { + app.set_status(m.to_string()); + } + self.error = None; + true + } + Err(e) => { + self.error = Some(e); + false + } + } + } +} + +/// The DWG and DXF files beside `path`, by name (desktop only). +fn folder_drawings(path: &str) -> Vec<String> { + #[cfg(not(target_arch = "wasm32"))] + { + let Some(dir) = std::path::Path::new(path).parent() else { return Vec::new() }; + let Ok(rd) = std::fs::read_dir(dir) else { return Vec::new() }; + let mut out: Vec<String> = rd + .flatten() + .take(20 * MAX_FOLDER) + .filter_map(|e| { + let p = e.path(); + let ext = p.extension()?.to_string_lossy().to_ascii_lowercase(); + matches!(ext.as_str(), "dwg" | "dxf").then(|| p.to_string_lossy().into_owned()) + }) + .take(MAX_FOLDER) + .collect(); + out.sort(); + out + } + #[cfg(target_arch = "wasm32")] + { + let _ = path; + Vec::new() + } +} + +fn file_name(path: &str) -> &str { + path.rsplit(['/', '\\']).next().unwrap_or(path) +} + +/// Open the palette (ADCENTER typed or chosen without parameters). +pub(crate) fn open(app: &mut CadApp) -> Result<Value, String> { + crate::docking::open_on_demand(app, crate::docking::Panel::DesignCenter, 340.0) +} + +/// The palette's body. +pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + let mut st = std::mem::take(&mut app.side_palettes.design_center); + let mut load: Option<String> = None; + let mut insert: Option<String> = None; + let mut add = false; + let mut make_palette = false; + ui.add_space(6.0); + ui.spacing_mut().item_spacing = vec2(4.0, 4.0); + ui.horizontal(|ui| { + ui.add_space(6.0); + if ui.button(crate::tl!("Open...")).clicked() { + match app.services.pick_file.as_ref() { + Some(pick) => load = pick("Drawings (DWG, DXF)", &["dwg", "dxf"]), + None => st.error = Some(crate::i18n::t("Type the drawing's path, then press Enter.").to_string()), + } + } + let field = egui::TextEdit::singleline(&mut st.path).hint_text(crate::tl!("Drawing file")).desired_width(ui.available_width() - 8.0); + let r = ui.add(field); + if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) && !st.path.trim().is_empty() { + load = Some(st.path.trim().to_string()); + } + }); + if let Some(e) = &st.error { + ui.horizontal(|ui| { + ui.add_space(6.0); + ui.colored_label(t.warn, e); + }); + } + if st.folder.len() > 1 { + egui::CollapsingHeader::new(crate::tl!("Folder")).id_salt("adc-folder").show(ui, |ui| { + egui::ScrollArea::vertical().id_salt("adc-folder-list").max_height(120.0).show(ui, |ui| { + for f in &st.folder { + if ui.selectable_label(*f == st.path, file_name(f)).clicked() { + load = Some(f.clone()); + } + } + }); + }); + } + if st.listing.is_some() { + ui.horizontal(|ui| { + ui.add_space(6.0); + let current = KINDS.get(st.kind).map(|k| k.1).unwrap_or("Blocks"); + craft_ui::ComboBox::from_id_salt("adc-kind").selected_text(crate::i18n::t(current)).show_ui(ui, |ui| { + for (i, (_, label)) in KINDS.iter().enumerate() { + if ui.selectable_value(&mut st.kind, i, crate::i18n::t(label)).changed() { + st.selected.clear(); + } + } + }); + ui.label(egui::RichText::new(file_name(&st.path)).color(t.text_dim)); + }); + let names = st.names(); + let blocks = st.kind_id() == "blocks"; + ui.horizontal(|ui| { + ui.add_space(6.0); + let some = !st.selected.is_empty(); + if ui.add_enabled(some, egui::Button::new(crate::tl!("Add to Drawing"))).clicked() { + add = true; + } + if blocks { + if ui.add_enabled(st.selected.len() == 1, egui::Button::new(crate::tl!("Insert"))).clicked() { + insert = st.selected.iter().next().cloned(); + } + if ui.add_enabled(!names.is_empty(), egui::Button::new(crate::tl!("Create Tool Palette"))).clicked() { + make_palette = true; + } + } + }); + ui.separator(); + egui::ScrollArea::vertical().id_salt("adc-items").auto_shrink([false, false]).show(ui, |ui| { + if names.is_empty() { + ui.label(egui::RichText::new(crate::tl!("Nothing of this kind in the file.")).color(t.text_dim)); + } + for (name, objects) in &names { + let on = st.selected.contains(name); + let text = match objects { + Some(n) => format!("{name} ({n})"), + None => name.clone(), + }; + let r = ui.selectable_label(on, text); + if r.clicked() { + let multi = ui.input(|i| i.modifiers.command || i.modifiers.shift); + if !multi { + st.selected.clear(); + } + if on && multi { + st.selected.remove(name); + } else { + st.selected.insert(name.clone()); + } + } + if blocks && r.double_clicked() { + insert = Some(name.clone()); + } + } + }); + } else { + ui.horizontal(|ui| { + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::tl!("Open a drawing to see its blocks, layers and styles.")).color(t.text_dim)); + }); + } + if let Some(p) = load { + st.load(app, &p); + } + if add { + let names: Vec<String> = st.selected.iter().cloned().collect(); + st.add(app, names); + } + if let Some(name) = insert + && st.add(app, vec![name.clone()]) + { + // -INSERT asks for the insertion point at the command line. + app.cmdline("-insert"); + if let Err(e) = app.session.input(draftcraft_engine::Input::Text(name)) { + st.error = Some(e.to_string()); + } + } + if make_palette { + let blocks: Vec<String> = st.names().into_iter().map(|(n, _)| n).collect(); + let name = file_name(&st.path).rsplit_once('.').map(|(s, _)| s.to_string()).unwrap_or_else(|| file_name(&st.path).to_string()); + let r = app.run("ui.toolpalettes", json!({ "operation": "newPalette", "palette": name, "blocks": blocks, "file": st.path })); + match r { + Ok(_) => { + let _ = super::toolpalettes::open(app); + } + Err(e) => st.error = Some(e), + } + } + app.side_palettes.design_center = st; +} diff --git a/crates/ui-egui/src/palettes/quickcalc.rs b/crates/ui-egui/src/palettes/quickcalc.rs index 62971808..0cdbfd72 100644 --- a/crates/ui-egui/src/palettes/quickcalc.rs +++ b/crates/ui-egui/src/palettes/quickcalc.rs @@ -251,27 +251,13 @@ impl State { /// Close only QuickCalc when present; otherwise restore it through the normal open path. /// Hiding the panel leaves its expression, history and variables intact. pub(crate) fn toggle(app: &mut CadApp) -> Result<Value, String> { - let panel = crate::docking::Panel::QuickCalc; - if app.ui.docking.layout.contains(&panel) { - crate::docking::command(app, false, &json!({ "operation": "close", "panel": panel.id() })) - } else { - open(app) - } + crate::docking::toggle_on_demand(app, crate::docking::Panel::QuickCalc, 300.0) } /// Open the palette. The first time it floats by the right edge of the drawing; afterwards it /// returns where it was closed. pub fn open(app: &mut CadApp) -> Result<Value, String> { - let panel = crate::docking::Panel::QuickCalc; - let first = !app.ui.docking.layout.contains(&panel) && !app.ui.docking.hidden.iter().any(|(p, _)| *p == panel); - let r = crate::docking::command(app, false, &json!({ "operation": "open", "panel": panel.id() }))?; - if !first { - return Ok(r); - } - let area = app.canvas.rect.unwrap_or(egui::Rect::from_min_size(egui::pos2(220.0, 80.0), vec2(1000.0, 800.0))); - let (w, h) = (300.0, (area.height() - 40.0).clamp(200.0, 560.0)); - let rect = [area.right() - w - 16.0, area.top() + 24.0, w, h]; - crate::docking::command(app, false, &json!({ "operation": "float", "panel": panel.id(), "rect": rect })) + crate::docking::open_on_demand(app, crate::docking::Panel::QuickCalc, 300.0) } /// The unit-conversion value row. The visible "Value" label names the numeric field (its diff --git a/crates/ui-egui/src/palettes/sheetset.rs b/crates/ui-egui/src/palettes/sheetset.rs new file mode 100644 index 00000000..e1098059 --- /dev/null +++ b/crates/ui-egui/src/palettes/sheetset.rs @@ -0,0 +1,211 @@ +//! The Sheet Set Manager palette (SHEETSET): make or open a sheet set file, add drawings' layouts +//! as sheets, renumber, retitle, reorder and remove them, open a sheet's drawing, and publish the +//! set to PDF. Everything goes through the engine's SHEETSET command. + +use egui::vec2; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// The sheet set the palette shows. +#[derive(Default)] +pub struct State { + /// The sheet set file. + pub(crate) path: String, + /// SHEETSET's description of it. + pub(crate) set: Option<Value>, + selected: Option<usize>, + /// The selected sheet's number and title being edited. + number: String, + title: String, + error: Option<String>, +} + +impl State { + fn run(&mut self, app: &mut CadApp, params: Value) -> bool { + match app.run("sheetset", params) { + Ok(v) => { + if let Some(m) = v.get("message").and_then(Value::as_str) { + app.set_status(m.to_string()); + } + if v.get("name").is_some() { + if let Some(p) = v.get("path").and_then(Value::as_str) { + self.path = p.to_string(); + } + self.set = Some(v); + } + self.error = None; + true + } + Err(e) => { + self.error = Some(e); + false + } + } + } + + fn sheets(&self) -> Vec<Value> { + self.set.as_ref().and_then(|s| s.get("sheets")).and_then(Value::as_array).cloned().unwrap_or_default() + } + + fn select(&mut self, i: Option<usize>) { + self.selected = i; + let sheet = i.and_then(|i| self.sheets().get(i).cloned()); + let field = |k: &str| sheet.as_ref().and_then(|s| s.get(k)).and_then(Value::as_str).unwrap_or_default().to_string(); + self.number = field("number"); + self.title = field("title"); + } +} + +/// Open the palette (SHEETSET typed or chosen without parameters). +pub(crate) fn open(app: &mut CadApp) -> Result<Value, String> { + crate::docking::open_on_demand(app, crate::docking::Panel::SheetSet, 320.0) +} + +/// A sheet's drawing, against the sheet set file's folder. +fn sheet_file(set_path: &str, file: &str) -> String { + let f = std::path::Path::new(file); + if f.is_absolute() { + return file.to_string(); + } + match std::path::Path::new(set_path).parent() { + Some(dir) if !dir.as_os_str().is_empty() => dir.join(f).to_string_lossy().into_owned(), + _ => file.to_string(), + } +} + +/// The palette's body. +pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + let mut st = std::mem::take(&mut app.side_palettes.sheet_set); + let mut todo: Option<Value> = None; + let mut open_sheet: Option<(String, String)> = None; + ui.add_space(6.0); + ui.spacing_mut().item_spacing = vec2(4.0, 4.0); + ui.horizontal(|ui| { + ui.add_space(6.0); + if ui.button(crate::tl!("New Sheet Set...")).clicked() + && let Some(p) = app.services.pick_save.as_ref().and_then(|pick| pick("Sheet Set.dcss")) + { + todo = Some(json!({ "operation": "new", "path": p, "overwrite": true })); + } + if ui.button(crate::tl!("Open Sheet Set...")).clicked() + && let Some(p) = app.services.pick_file.as_ref().and_then(|pick| pick("Sheet sets (DCSS)", &["dcss"])) + { + todo = Some(json!({ "operation": "list", "path": p })); + } + }); + if app.services.pick_file.is_none() { + ui.horizontal(|ui| { + ui.add_space(6.0); + let r = + ui.add(egui::TextEdit::singleline(&mut st.path).hint_text(crate::tl!("Sheet set file")).desired_width(ui.available_width() - 8.0)); + if r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)) && !st.path.trim().is_empty() { + todo = Some(json!({ "operation": "list", "path": st.path.trim() })); + } + }); + } + if let Some(e) = &st.error { + ui.horizontal(|ui| { + ui.add_space(6.0); + ui.colored_label(t.warn, e); + }); + } + let Some(set) = st.set.clone() else { + ui.horizontal(|ui| { + ui.add_space(6.0); + ui.label(egui::RichText::new(crate::tl!("Make or open a sheet set to list its sheets.")).color(t.text_dim)); + }); + app.side_palettes.sheet_set = st; + if let Some(p) = todo { + let mut st = std::mem::take(&mut app.side_palettes.sheet_set); + st.run(app, p); + app.side_palettes.sheet_set = st; + } + return; + }; + let path = st.path.clone(); + ui.horizontal(|ui| { + ui.add_space(6.0); + ui.strong(set.get("name").and_then(Value::as_str).unwrap_or_default()); + }); + ui.horizontal(|ui| { + ui.add_space(6.0); + if ui.button(crate::tl!("Add Drawing...")).clicked() + && let Some(f) = app.services.pick_file.as_ref().and_then(|pick| pick("Drawings (DWG, DXF)", &["dwg", "dxf"])) + { + todo = Some(json!({ "operation": "add", "path": path, "file": f })); + } + if ui.button(crate::tl!("Publish to PDF...")).clicked() + && let Some(p) = app.services.pick_save.as_ref().and_then(|pick| pick("Sheets.pdf")) + { + let dir = std::path::Path::new(&p).parent().map(|d| d.to_string_lossy().into_owned()).unwrap_or_default(); + todo = Some(json!({ "operation": "publish", "path": path, "output": dir })); + } + }); + ui.separator(); + let sheets = st.sheets(); + let mut select: Option<Option<usize>> = None; + egui::ScrollArea::vertical().id_salt("sheetset-sheets").max_height((ui.available_height() - 90.0).max(80.0)).show(ui, |ui| { + if sheets.is_empty() { + ui.label(egui::RichText::new(crate::tl!("No sheets yet: add a drawing's layouts.")).color(t.text_dim)); + } + for (i, sh) in sheets.iter().enumerate() { + let f = |k: &str| sh.get(k).and_then(Value::as_str).unwrap_or_default(); + let r = ui.selectable_label(st.selected == Some(i), format!("{} {}", f("number"), f("title"))).on_hover_text(format!( + "{} · {}", + f("file"), + f("layout") + )); + if r.clicked() { + select = Some(Some(i)); + } + if r.double_clicked() { + open_sheet = Some((sheet_file(&path, f("file")), f("layout").to_string())); + } + } + }); + if let Some(s) = select { + st.select(s); + } + if let Some(i) = st.selected.filter(|i| *i < sheets.len()) { + ui.separator(); + ui.horizontal(|ui| { + ui.add_space(6.0); + ui.add(egui::TextEdit::singleline(&mut st.number).hint_text(crate::tl!("Number")).desired_width(60.0)); + ui.add(egui::TextEdit::singleline(&mut st.title).hint_text(crate::tl!("Title")).desired_width(ui.available_width() - 8.0)); + }); + ui.horizontal_wrapped(|ui| { + ui.add_space(6.0); + if ui.button(crate::tl!("Apply")).clicked() { + todo = Some(json!({ "operation": "update", "path": path, "index": i, "number": st.number, "title": st.title })); + } + if ui.add_enabled(i > 0, egui::Button::new("▲")).on_hover_text(crate::tl!("Move Up")).clicked() { + todo = Some(json!({ "operation": "move", "path": path, "index": i, "to": i - 1 })); + st.selected = Some(i - 1); + } + if ui.add_enabled(i + 1 < sheets.len(), egui::Button::new("▼")).on_hover_text(crate::tl!("Move Down")).clicked() { + todo = Some(json!({ "operation": "move", "path": path, "index": i, "to": i + 1 })); + st.selected = Some(i + 1); + } + if ui.button(crate::tl!("Open")).clicked() + && let Some(sh) = sheets.get(i) + { + let f = |k: &str| sh.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + open_sheet = Some((sheet_file(&path, &f("file")), f("layout"))); + } + if ui.button(crate::tl!("Remove")).clicked() { + todo = Some(json!({ "operation": "remove", "path": path, "index": i })); + st.selected = None; + } + }); + } + if let Some(p) = todo { + st.run(app, p); + } + app.side_palettes.sheet_set = st; + if let Some((file, _layout)) = open_sheet { + app.open_path(std::path::Path::new(&file)); + } +} diff --git a/crates/ui-egui/src/palettes/toolpalettes.rs b/crates/ui-egui/src/palettes/toolpalettes.rs new file mode 100644 index 00000000..2c9cc4a1 --- /dev/null +++ b/crates/ui-egui/src/palettes/toolpalettes.rs @@ -0,0 +1,351 @@ +//! The Tool Palettes window (TOOLPALETTES): named palettes of tools, each a command to start or a +//! block to insert (from this drawing or from a drawing file). The palettes are kept with the +//! preferences. `ui.toolpalettes` manages them programmatically; DesignCenter's Create Tool +//! Palette makes one of a file's blocks. + +use egui::vec2; +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::icons::{self, Icon}; +use crate::theme::Tokens; + +/// Most palettes, and most tools on one palette. +const MAX_PALETTES: usize = 100; +const MAX_TOOLS: usize = 500; +/// Longest palette name or tool label kept. +const MAX_LABEL: usize = 200; + +/// One tool on a palette. +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +#[serde(tag = "type", rename_all = "camelCase")] +pub enum PaletteTool { + /// Start a command, as the ribbon does. + Command { command: String, label: String }, + /// Insert a block; one from a drawing file is added to the drawing first (ADCENTER). + Block { + name: String, + #[serde(default)] + file: Option<String>, + }, +} + +impl PaletteTool { + fn label(&self) -> String { + match self { + Self::Command { label, .. } => crate::i18n::t(label).to_string(), + Self::Block { name, .. } => name.clone(), + } + } + fn icon(&self) -> Icon { + match self { + Self::Command { command, .. } => crate::ribbon::icon_for(command).unwrap_or(Icon::Menu), + Self::Block { .. } => Icon::Blocks, + } + } +} + +#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)] +pub struct Palette { + pub name: String, + pub tools: Vec<PaletteTool>, +} + +/// The palettes and which one shows. +#[derive(Clone, Debug, PartialEq)] +pub struct State { + pub palettes: Vec<Palette>, + pub active: usize, + /// The command typed in the Add Command field. + adding: String, +} + +fn cmd(command: &str, label: &str) -> PaletteTool { + PaletteTool::Command { command: command.into(), label: label.into() } +} + +impl Default for State { + /// Draw, Modify and Annotate palettes of common commands. + fn default() -> Self { + let palettes = vec![ + Palette { + name: "Draw".into(), + tools: vec![ + cmd("line", "Line"), + cmd("pline", "Polyline"), + cmd("circle", "Circle"), + cmd("arc", "Arc"), + cmd("rectang", "Rectangle"), + cmd("hatch", "Hatch"), + ], + }, + Palette { + name: "Modify".into(), + tools: vec![ + cmd("move", "Move"), + cmd("copy", "Copy"), + cmd("rotate", "Rotate"), + cmd("scale", "Scale"), + cmd("trim", "Trim"), + cmd("offset", "Offset"), + ], + }, + Palette { + name: "Annotate".into(), + tools: vec![cmd("dimlinear", "Linear"), cmd("mtext", "Multiline Text"), cmd("mleader", "Multileader"), cmd("table", "Table")], + }, + ]; + State { palettes, active: 0, adding: String::new() } + } +} + +fn clip(s: &str) -> String { + s.chars().filter(|c| !c.is_control()).take(MAX_LABEL).collect() +} + +impl State { + /// The palettes for the preferences file. + pub(crate) fn prefs(&self) -> Value { + json!({ "palettes": self.palettes, "active": self.active }) + } + + /// Restore saved palettes; malformed ones keep the current palettes. + pub(crate) fn load_prefs(&mut self, v: &Value) { + let Some(p) = v.get("palettes").and_then(|p| serde_json::from_value::<Vec<Palette>>(p.clone()).ok()) else { return }; + let mut palettes: Vec<Palette> = p.into_iter().take(MAX_PALETTES).collect(); + for pal in &mut palettes { + pal.name = clip(&pal.name); + pal.tools.truncate(MAX_TOOLS); + } + self.palettes = palettes; + self.active = + v.get("active").and_then(Value::as_u64).and_then(|a| usize::try_from(a).ok()).unwrap_or(0).min(self.palettes.len().saturating_sub(1)); + } + + fn find(&self, name: &str) -> Option<usize> { + self.palettes.iter().position(|p| p.name.eq_ignore_ascii_case(name)) + } + + /// `ui.toolpalettes`: `{operation: list|newPalette|deletePalette|rename|add|remove|activate, palette, to?, command?, label?, block?, + /// blocks?, file?, index?}`. + pub(crate) fn command(&mut self, p: &Value) -> Result<Value, String> { + let s = |k: &str| p.get(k).and_then(Value::as_str).map(clip); + let op = s("operation").unwrap_or_else(|| "list".into()); + let palette = |st: &Self| -> Result<usize, String> { + match s("palette") { + Some(n) => st.find(&n).ok_or_else(|| format!("no tool palette \"{n}\"")), + None => (st.active < st.palettes.len()).then_some(st.active).ok_or_else(|| "there are no tool palettes".to_string()), + } + }; + match op.as_str() { + "list" => {} + "newPalette" => { + let name = s("palette").filter(|n| !n.trim().is_empty()).ok_or("`palette` names the new palette")?; + if self.palettes.len() >= MAX_PALETTES { + return Err(format!("at most {MAX_PALETTES} tool palettes")); + } + // A taken name gets a number. + let mut unique = name.clone(); + let mut i = 2; + while self.find(&unique).is_some() && i < 10_000 { + unique = format!("{name} ({i})"); + i += 1; + } + let file = s("file").filter(|f| !f.is_empty()); + let tools: Vec<PaletteTool> = p + .get("blocks") + .and_then(Value::as_array) + .map(|a| { + a.iter().filter_map(Value::as_str).take(MAX_TOOLS).map(|n| PaletteTool::Block { name: clip(n), file: file.clone() }).collect() + }) + .unwrap_or_default(); + self.palettes.push(Palette { name: unique, tools }); + self.active = self.palettes.len() - 1; + } + "deletePalette" => { + let i = palette(self)?; + self.palettes.remove(i); + self.active = self.active.min(self.palettes.len().saturating_sub(1)); + } + "rename" => { + let i = palette(self)?; + let to = s("to").filter(|n| !n.trim().is_empty()).ok_or("`to` is the new name")?; + if self.find(&to).is_some_and(|j| j != i) { + return Err(format!("a tool palette is already named \"{to}\"")); + } + if let Some(pal) = self.palettes.get_mut(i) { + pal.name = to; + } + } + "activate" => self.active = palette(self)?, + "add" => { + let i = palette(self)?; + let tool = match (s("command"), s("block")) { + (Some(c), _) => { + let c = c.trim().to_ascii_lowercase(); + let label = match draftcraft_engine::find_command(&c) { + Some(spec) => spec.label.to_string(), + None if crate::menus::is_ui_command(&c) => c.clone(), + None => return Err(format!("unknown command \"{c}\"")), + }; + PaletteTool::Command { label: s("label").unwrap_or(label), command: c } + } + (None, Some(b)) => PaletteTool::Block { name: b, file: s("file").filter(|f| !f.is_empty()) }, + (None, None) => return Err("`command` or `block` is the tool to add".into()), + }; + let pal = self.palettes.get_mut(i).ok_or("no such palette")?; + if pal.tools.len() >= MAX_TOOLS { + return Err(format!("at most {MAX_TOOLS} tools on a palette")); + } + pal.tools.push(tool); + } + "remove" => { + let i = palette(self)?; + let pal = self.palettes.get_mut(i).ok_or("no such palette")?; + let at = p + .get("index") + .and_then(Value::as_u64) + .and_then(|x| usize::try_from(x).ok()) + .filter(|x| *x < pal.tools.len()) + .ok_or("`index` is the tool's position, from 0")?; + pal.tools.remove(at); + } + other => return Err(format!("unknown operation \"{other}\" (list, newPalette, deletePalette, rename, activate, add, remove)")), + } + Ok(json!({ "palettes": self.palettes, "active": self.active })) + } +} + +/// Open the palette window (TOOLPALETTES). +pub(crate) fn open(app: &mut CadApp) -> Result<Value, String> { + crate::docking::open_on_demand(app, crate::docking::Panel::ToolPalettes, 240.0) +} + +/// Run a tool: start its command, or insert its block (copied from its file first). +fn use_tool(app: &mut CadApp, tool: &PaletteTool) { + match tool { + PaletteTool::Command { command, .. } => app.start(command), + PaletteTool::Block { name, file } => { + if let Some(f) = file + && app.session.doc().is_ok_and(|d| d.block(name).is_none()) + && let Err(e) = app.run("adcenter", json!({ "path": f, "kind": "blocks", "names": [name] })) + { + app.set_status(e); + return; + } + app.cmdline("-insert"); + if let Err(e) = app.session.input(draftcraft_engine::Input::Text(name.clone())) { + app.set_status(e.to_string()); + } + } + } +} + +/// The window's body: the palette tabs down the side, the active palette's tools. +pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { + let t = Tokens::get(); + let mut st = std::mem::replace(&mut app.side_palettes.tool_palettes, State { palettes: Vec::new(), active: 0, adding: String::new() }); + let mut run: Option<PaletteTool> = None; + let mut action: Option<Value> = None; + ui.add_space(4.0); + ui.spacing_mut().item_spacing = vec2(4.0, 4.0); + // The palette tabs. + ui.horizontal_wrapped(|ui| { + ui.add_space(4.0); + for (i, pal) in st.palettes.iter().enumerate() { + let r = ui.selectable_label(i == st.active, crate::i18n::t(&pal.name)); + if r.clicked() { + st.active = i; + } + r.context_menu(|ui| { + if ui.button(crate::tl!("Delete Palette")).clicked() { + action = Some(json!({ "operation": "deletePalette", "palette": pal.name })); + ui.close(); + } + }); + } + if icons::button(ui, Icon::Plus, 20.0, crate::tl!("New Palette"), false).clicked() { + action = Some(json!({ "operation": "newPalette", "palette": crate::i18n::t("New Palette") })); + } + }); + ui.separator(); + let active = st.active; + egui::ScrollArea::vertical().id_salt("tool-palette").auto_shrink([false, false]).show(ui, |ui| { + let Some(pal) = st.palettes.get(active) else { + ui.label(egui::RichText::new(crate::tl!("No tool palettes.")).color(t.text_dim)); + return; + }; + if pal.tools.is_empty() { + ui.label( + egui::RichText::new(crate::tl!("This palette is empty: add a command below, or make a palette from DesignCenter.")).color(t.text_dim), + ); + } + for (i, tool) in pal.tools.iter().enumerate() { + let r = ui + .horizontal(|ui| { + ui.add_space(4.0); + let (rect, _) = ui.allocate_exact_size(vec2(22.0, 22.0), egui::Sense::hover()); + icons::paint(ui.painter(), rect, tool.icon(), false); + ui.add(egui::Button::new(tool.label()).frame(false)) + }) + .inner; + if r.clicked() { + run = Some(tool.clone()); + } + r.context_menu(|ui| { + if ui.button(crate::tl!("Delete Tool")).clicked() { + action = Some(json!({ "operation": "remove", "palette": pal.name, "index": i })); + ui.close(); + } + }); + } + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.add_space(4.0); + let field = egui::TextEdit::singleline(&mut st.adding).hint_text(crate::tl!("Command")).desired_width(110.0); + let r = ui.add(field); + let enter = r.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter)); + if (ui.button(crate::tl!("Add Command")).clicked() || enter) && !st.adding.trim().is_empty() { + action = Some(json!({ "operation": "add", "palette": pal.name, "command": st.adding.trim() })); + } + }); + }); + if let Some(a) = action { + match st.command(&a) { + Ok(_) => st.adding.clear(), + Err(e) => app.set_status(e), + } + } + app.side_palettes.tool_palettes = st; + if let Some(tool) = run { + use_tool(app, &tool); + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn palettes_are_managed_and_kept() { + let mut st = State::default(); + st.command(&json!({"operation": "newPalette", "palette": "Parts", "blocks": ["BOLT", "NUT"], "file": "/p/parts.dwg"})).unwrap(); + assert_eq!(st.palettes[st.active].name, "Parts"); + assert_eq!(st.palettes[st.active].tools.len(), 2); + st.command(&json!({"operation": "newPalette", "palette": "parts"})).unwrap(); + assert_eq!(st.palettes[st.active].name, "parts (2)", "a taken name gets a number"); + st.command(&json!({"operation": "add", "command": "LINE"})).unwrap(); + assert!(st.command(&json!({"operation": "add", "command": "nosuchcommand"})).is_err()); + st.command(&json!({"operation": "rename", "to": "Mine"})).unwrap(); + st.command(&json!({"operation": "remove", "palette": "Mine", "index": 0})).unwrap(); + assert!(st.command(&json!({"operation": "remove", "palette": "Mine", "index": 0})).is_err()); + let mut back = State::default(); + back.load_prefs(&st.prefs()); + assert_eq!(back.palettes, st.palettes); + assert_eq!(back.active, st.active); + // Malformed preferences keep what there is. + back.load_prefs(&json!({"palettes": 5})); + assert_eq!(back.palettes, st.palettes); + } +} diff --git a/crates/ui-egui/src/ribbon.rs b/crates/ui-egui/src/ribbon.rs index 1dc4a44e..aeef02e1 100644 --- a/crates/ui-egui/src/ribbon.rs +++ b/crates/ui-egui/src/ribbon.rs @@ -9,6 +9,8 @@ use serde_json::json; use crate::CadApp; use crate::icons::{self, Icon}; + +pub(crate) mod context; use crate::theme::Tokens; /// A menu entry: icon, command id, label. @@ -136,6 +138,88 @@ const PASTE_MORE: &[Tool] = &[ const COPYCLIP_MORE: &[Tool] = &[(Icon::Copy, "copyclip", "Copy Clip"), (Icon::Copy, "copybase", "Copy with Base Point")]; /// The ribbon tabs and panels, in the order the Windows "2D Drafting" workspace shows them. +/// Slide-out panels: the tools a panel keeps below its title (tab, panel, tools). Its title +/// opens them; a collapsed panel lists them after its own. +const SLIDE_OUTS: &[(&str, &str, &[Tool])] = &[ + ( + "Home", + "Draw", + &[ + (Icon::XLine, "xline", "Construction Line"), + (Icon::Ray, "ray", "Ray"), + (Icon::Point, "point", "Multiple Points"), + (Icon::Point, "divide", "Divide"), + (Icon::Point, "measure", "Measure"), + SEP, + (Icon::Donut, "donut", "Donut"), + (Icon::RevCloud, "revcloud", "Revision Cloud"), + (Icon::Region, "region", "Region"), + (Icon::Wipeout, "wipeout", "Wipeout"), + (Icon::Boundary, "boundary", "Boundary"), + ], + ), + ( + "Home", + "Modify", + &[ + (Icon::Break, "break", "Break"), + (Icon::Break, "breakatpoint", "Break at Point"), + (Icon::Join, "join", "Join"), + (Icon::Lengthen, "lengthen", "Lengthen"), + (Icon::Chamfer, "chamfer", "Chamfer"), + (Icon::Spline, "blend", "Blend Curves"), + SEP, + (Icon::Polyline, "pedit", "Edit Polyline"), + (Icon::Spline, "splinedit", "Edit Spline"), + (Icon::Move, "align", "Align"), + (Icon::Redo, "reverse", "Reverse"), + (Icon::Erase, "overkill", "Delete Duplicate Objects"), + (Icon::MoveTop, "draworder", "Draw Order"), + ], + ), + ( + "Home", + "Annotation", + &[ + (Icon::TextStyle, "style", "Text Style"), + (Icon::DimStyle, "dimstyle", "Dimension Style"), + (Icon::MLeader, "mleaderstyle", "Multileader Style"), + (Icon::TextStyle, "tablestyle", "Table Style"), + ], + ), + ( + "Home", + "Layers", + &[ + (Icon::MakeCurrent, "laycur", "Change to Current Layer"), + (Icon::LayerMatch, "laymrg", "Merge"), + (Icon::Erase, "laydel", "Delete"), + (Icon::LayerPrev, "layerp", "Previous"), + (Icon::LayerWalk, "laywalk", "Layer Walk"), + ], + ), + ( + "Home", + "Block", + &[ + (Icon::List, "battman", "Block Attribute Manager"), + (Icon::Redo, "attsync", "Synchronize"), + (Icon::BlockCreate, "wblock", "Write Block"), + (Icon::Insert, "blockreplace", "Replace Block"), + ], + ), + ( + "Home", + "Utilities", + &[(Icon::Distance, "dist", "Distance"), (Icon::Point, "id", "ID Point"), (Icon::Area, "area", "Area"), (Icon::List, "list", "List")], + ), +]; + +/// The slide-out tools of `tab`'s panel `title`, if it has any. +fn slide_out(tab: &str, title: &str) -> &'static [Tool] { + SLIDE_OUTS.iter().find(|(t, p, _)| *t == tab && *p == title).map_or(&[], |s| s.2) +} + pub(crate) const TABS: &[RibbonTab] = &[ RibbonTab { name: "Home", @@ -284,7 +368,20 @@ pub(crate) const TABS: &[RibbonTab] = &[ ]), ], }, - RibbonPanel { title: "Import", cols: &[Large(b(Icon::Import, "import", "Import")), Large(b(Icon::Hatch, "imageattach", "Image"))] }, + RibbonPanel { + title: "Import", + cols: &[ + Large(b(Icon::Import, "import", "Import")), + Large(b(Icon::Pdf, "pdfimport", "PDF Import")), + Small(&[ + b(Icon::Hatch, "imageattach", "Image"), + b(Icon::Pdf, "pdfattach", "PDF Underlay"), + b(Icon::List, "ulayers", "Underlay Layers"), + ]), + ], + }, + RibbonPanel { title: "Point Cloud", cols: &[Large(b(Icon::PointCloud, "pointcloudattach", "Attach"))] }, + RibbonPanel { title: "Location", cols: &[Large(b(Icon::GeoLocation, "geographiclocation", "Set Location"))] }, RibbonPanel { title: "Data", cols: &[ @@ -441,13 +538,15 @@ pub(crate) const TABS: &[RibbonTab] = &[ RibbonPanel { title: "Palettes", cols: &[ + Large(b(Icon::ToolPalette, "toolpalettes", "Tool Palettes")), Large(b(Icon::Properties, "ui.panel.properties", "Properties")), Large(b(Icon::Layers, "ui.panel.layers", "Layers")), Small(&[ + b(Icon::SheetSet, "sheetset", "Sheet Set Manager"), + b(Icon::DesignCenter, "adcenter", "DesignCenter"), b(Icon::Table, "ui.toggle.quickcalc", "QuickCalc"), - b(Icon::Attach, "xref", "External References"), - b(Icon::Blocks, "ui.dialog.blocks", "Blocks"), ]), + Small(&[b(Icon::Attach, "xref", "External References"), b(Icon::Blocks, "ui.dialog.blocks", "Blocks")]), ], }, RibbonPanel { @@ -470,8 +569,13 @@ pub(crate) const TABS: &[RibbonTab] = &[ RibbonPanel { title: "Customization", cols: &[ + Large(b(Icon::Customize, "cui", "User Interface")), Large(b(Icon::Gear, "options", "Options")), - Small(&[b(Icon::Text, "aliasedit", "Edit Aliases"), b(Icon::Menu, "ui.dialog.commands", "Commands")]), + Small(&[ + b(Icon::Text, "aliasedit", "Edit Aliases"), + b(Icon::Menu, "ui.dialog.commands", "Commands"), + b(Icon::Workspace, "workspace", "Workspaces"), + ]), ], }, RibbonPanel { title: "Applications", cols: &[Large(b(Icon::Open, "appload", "Load Application"))] }, @@ -479,6 +583,7 @@ pub(crate) const TABS: &[RibbonTab] = &[ title: "CAD Standards", cols: &[ Large(b(Icon::Erase, "purge", "Purge")), + Large(b(Icon::LayerTranslate, "laytrans", "Layer Translator")), Small(&[b(Icon::Search, "audit", "Audit"), b(Icon::Join, "overkill", "Overkill"), b(Icon::Redo, "recover", "Recover")]), ], }, @@ -595,6 +700,7 @@ const APP_MENU: &[(Icon, &str, &str)] = &[ (Icon::Import, "import", "Import"), (Icon::Export, "export", "Export"), (Icon::Publish, "publish", "Publish"), + (Icon::Transmit, "etransmit", "eTransmit"), (Icon::Plot, "plot", "Print"), (Icon::Search, "audit", "Drawing Utilities"), (Icon::Close, "close", "Close"), @@ -701,6 +807,11 @@ fn first_icon(panel: &RibbonPanel) -> Icon { } /// Every command a panel reaches, for its collapsed button and its title menu. +/// The icon the ribbon shows for `cmd`, if it has a button there. +pub(crate) fn icon_for(cmd: &str) -> Option<Icon> { + TABS.iter().flat_map(|t| t.panels.iter()).flat_map(all_tools).find(|(_, c, _)| c.eq_ignore_ascii_case(cmd)).map(|(icon, _, _)| icon) +} + fn all_tools(panel: &RibbonPanel) -> Vec<Tool> { let mut out: Vec<Tool> = Vec::new(); let mut push = |b: &Btn| { @@ -926,6 +1037,7 @@ pub fn title_and_ribbon(app: &mut CadApp, ui: &mut egui::Ui) { let t = Tokens::get(); let ribbon_h = if app.ui.show_toolbar { TAB_ROW + if app.ui.ribbon_minimized { 0.0 } else { BODY + PANEL_TITLE + 4.0 } } else { 0.0 }; let mut out = Out::default(); + context::update(app); egui::Panel::top("cc_title_ribbon").exact_size(APP_BAR + ribbon_h).frame(egui::Frame::NONE.fill(bar_color(&t))).show(ui, |ui| { let r = ui.max_rect(); app_bar(app, ui, Rect::from_min_size(r.min, vec2(r.width(), APP_BAR)), &mut out); @@ -988,7 +1100,7 @@ fn app_bar(app: &mut CadApp, ui: &mut egui::Ui, bar: Rect, out: &mut Out) { aresp.on_hover_text(crate::tl!("Application Menu")); x = ab.right() + 10.0; // Quick Access Toolbar. - for (icon, cmd, label) in QAT { + for (icon, cmd, label) in &qat_tools(app) { if !known(cmd) { continue; } @@ -1011,17 +1123,40 @@ fn app_bar(app: &mut CadApp, ui: &mut egui::Ui, bar: Rect, out: &mut Out) { let wresp = ui.interact(ws, ui.scope_id().with("workspace"), Sense::click()); p.rect_filled(ws, 2.0, if wresp.hovered() { t.control } else { t.chrome_dark }); p.rect_stroke(ws, 2.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - p.with_clip_rect(ws.shrink(2.0)).text(pos2(ws.left() + 7.0, cy), Align2::LEFT_CENTER, crate::tl!("2D Drafting"), label_font(), t.text); + let current = crate::workspaces::current(app); + let shown = if current == crate::workspaces::BUILT_IN { crate::i18n::t(crate::workspaces::BUILT_IN).to_string() } else { current.clone() }; + p.with_clip_rect(ws.shrink(2.0)).text(pos2(ws.left() + 7.0, cy), Align2::LEFT_CENTER, shown, label_font(), t.text); arrow(&p, pos2(ws.right() - 9.0, cy), t.text); icons::describe_control(ui, &wresp, "Workspace", None, false); + let names = crate::workspaces::names(app); + let mut switch_to: Option<String> = None; egui::Popup::menu(&wresp).show(|ui| { - let _ = ui.selectable_label(true, crate::tl!("2D Drafting")); + for n in &names { + let label = if n == crate::workspaces::BUILT_IN { crate::i18n::t(n).to_string() } else { n.clone() }; + if ui.selectable_label(*n == current, label).clicked() && *n != current { + switch_to = Some(n.clone()); + ui.close(); + } + } ui.separator(); + if ui.button(crate::tl!("Save Current As...")).clicked() { + out.command = Some("cui"); + ui.close(); + } + if ui.button(crate::tl!("Customize...")).clicked() { + out.command = Some("cui"); + ui.close(); + } if ui.button(crate::tl!("Reset Palettes")).clicked() { out.command = Some("ui.dock.reset"); ui.close(); } }); + if let Some(n) = switch_to + && let Err(e) = crate::workspaces::set_current(app, &n) + { + app.set_status(e); + } let qat_end = ws.right() + 14.0; // Search box on the right: typed text runs as a command, like the command line. let search_w = 220.0; @@ -1098,25 +1233,80 @@ fn fit_panels(p: &egui::Painter, tab: &RibbonTab, available: f32) -> (Vec<bool>, (compacts, widths, small, collapsed) } +/// The tabs the ribbon shows now: the standard ones, then the contextual tab the app's state +/// calls for ([`context`]). +fn shown_tabs(app: &CadApp) -> Vec<&'static RibbonTab> { + TABS.iter().filter(|tab| !app.ui.hidden_tabs.iter().any(|h| h == tab.name)).chain(context::current(app)).collect() +} + +/// The standard ribbon tabs' names (CUI shows or hides them). +pub(crate) fn tab_names() -> Vec<&'static str> { + TABS.iter().map(|tab| tab.name).collect() +} + +/// The Quick Access Toolbar's tools: the customized ones (CUI), else the standard ones. +fn qat_tools(app: &CadApp) -> Vec<Tool> { + match &app.ui.qat { + None => QAT.to_vec(), + Some(ids) => ids.iter().filter_map(|id| qat_tool(id)).take(crate::workspaces::MAX_QAT).collect(), + } +} + +/// The Quick Access Toolbar's command ids. +pub(crate) fn qat_ids(app: &CadApp) -> Vec<String> { + qat_tools(app).iter().map(|t| t.1.to_string()).collect() +} + +/// A command as a Quick Access Toolbar tool: its ribbon icon, else a generic one. +fn qat_tool(id: &str) -> Option<Tool> { + let id = id.trim(); + if let Some(t) = QAT.iter().chain(APP_MENU).find(|t| t.1.eq_ignore_ascii_case(id)) { + return Some(*t); + } + if let Some(t) = TABS.iter().flat_map(|t| t.panels.iter()).flat_map(all_tools).find(|t| t.1.eq_ignore_ascii_case(id)) { + return Some(t); + } + if let Some(c) = draftcraft_engine::find_command(id) { + return Some((Icon::Customize, c.id, c.label)); + } + crate::menus::UI_COMMANDS.iter().find(|c| c.0.eq_ignore_ascii_case(id)).map(|c| (Icon::Customize, c.0, c.1)) +} + /// The ribbon tab names and the minimize switch after them. -fn ribbon_tabs(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, active: usize) { +fn ribbon_tabs(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, tabs: &[&'static RibbonTab], active: usize) { let t = Tokens::get(); let p = ui.painter().clone(); let tabs_top = area.top(); // Tabs. let mut tx = area.left() + 6.0; - for (i, tab) in TABS.iter().enumerate() { + for (i, tab) in tabs.iter().enumerate() { let name = crate::i18n::t(tab.name); let w = text_w(&p, name) + 22.0; let tr = Rect::from_min_size(pos2(tx, tabs_top + 2.0), vec2(w, TAB_ROW - 2.0)); let resp = ui.interact(tr, ui.scope_id().with(("ribbon_tab", i)), Sense::click()); let selected = i == active; + let contextual = context::is_contextual(tab.name); + if contextual { + // A contextual tab stands out in the accent colour, as on Windows. + p.rect_filled(tr, egui::CornerRadius { nw: 2, ne: 2, sw: 0, se: 0 }, t.accent.gamma_multiply(0.22)); + p.hline(tr.x_range(), tr.top() + 1.0, Stroke::new(2.0, t.accent)); + } if selected && !app.ui.ribbon_minimized { p.rect_filled(tr, egui::CornerRadius { nw: 2, ne: 2, sw: 0, se: 0 }, t.chrome); + if contextual { + p.hline(tr.x_range(), tr.top() + 1.0, Stroke::new(2.0, t.accent)); + } } else if selected || resp.hovered() { p.rect_filled(tr, 2.0, t.control_hover.gamma_multiply(0.45)); } - p.text(tr.center(), Align2::CENTER_CENTER, name, FontId::proportional(12.5), if selected || resp.hovered() { t.text } else { t.text_dim }); + let color = if contextual { + t.accent + } else if selected || resp.hovered() { + t.text + } else { + t.text_dim + }; + p.text(tr.center(), Align2::CENTER_CENTER, name, FontId::proportional(12.5), color); icons::describe_control(ui, &resp, tab.name, Some(selected), true); if resp.clicked() { if app.ui.ribbon_minimized { @@ -1162,16 +1352,17 @@ fn ribbon(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, out: &mut Out) { let p = ui.painter().clone(); let tabs_top = area.top(); let body_top = tabs_top + TAB_ROW; - let active = TABS.iter().position(|tab| tab.name == app.ui.ribbon_tab).unwrap_or(0); + let tabs = shown_tabs(app); + let active = tabs.iter().position(|tab| tab.name == app.ui.ribbon_tab).unwrap_or(0); if !app.ui.ribbon_minimized { p.rect_filled(Rect::from_min_max(pos2(area.left(), body_top), area.max), 0.0, t.chrome); p.hline(area.x_range(), area.bottom() - 0.5, Stroke::new(1.0, t.border)); } - ribbon_tabs(app, ui, area, active); + ribbon_tabs(app, ui, area, &tabs, active); if app.ui.ribbon_minimized { return; } - let Some(tab) = TABS.get(active) else { return }; + let Some(tab) = tabs.get(active).copied() else { return }; let (compacts, widths, small, collapsed) = fit_panels(&p, tab, area.width() - 8.0); let body = Rect::from_min_max(pos2(area.left(), body_top + 2.0), pos2(area.right(), area.bottom() - 2.0)); @@ -1199,8 +1390,14 @@ fn ribbon(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, out: &mut Out) { clip.text(pos2(br.center().x, br.top() + 50.0), Align2::CENTER_TOP, crate::i18n::t(panel.title), label_font(), t.text); arrow(&clip, pos2(br.center().x, br.top() + 72.0), t.text); icons::describe_control(ui, &resp, &panel_name(panel.title), None, false); + let mut tools = all_tools(panel); + let more = slide_out(tab.name, panel.title); + if !more.is_empty() { + tools.push(SEP); + tools.extend_from_slice(more); + } egui::Popup::menu(&resp).show(|ui| { - if let Some(c) = tool_menu(ui, &all_tools(panel)) { + if let Some(c) = tool_menu(ui, &tools) { out.command = Some(c); } }); @@ -1217,8 +1414,11 @@ fn ribbon(app: &mut CadApp, ui: &mut egui::Ui, area: Rect, out: &mut Out) { clip.text(pos2(title_r.center().x - 6.0, title_r.center().y), Align2::CENTER_CENTER, title, label_font(), t.text_dim); arrow(&clip, pos2(title_r.center().x - 6.0 + tw / 2.0 + 9.0, title_r.center().y), t.text_dim); icons::describe_control(ui, &tresp, &panel_name(panel.title), None, false); + // The title opens the panel's slide-out, or for a panel without one, its commands. + let more = slide_out(tab.name, panel.title); egui::Popup::menu(&tresp).show(|ui| { - if let Some(c) = tool_menu(ui, &all_tools(panel)) { + let tools = if more.is_empty() { all_tools(panel) } else { more.to_vec() }; + if let Some(c) = tool_menu(ui, &tools) { out.command = Some(c); } }); @@ -1567,7 +1767,7 @@ mod tests { #[test] fn every_ribbon_command_exists() { let mut missing = Vec::new(); - for tab in TABS { + for tab in TABS.iter().chain(context::CONTEXT_TABS) { for panel in tab.panels { for (_, cmd, _) in all_tools(panel) { if !known(cmd) { @@ -1576,6 +1776,14 @@ mod tests { } } } + for (tab, panel, tools) in SLIDE_OUTS { + assert!(TABS.iter().any(|t| t.name == *tab && t.panels.iter().any(|p| p.title == *panel)), "no panel {tab}/{panel}"); + for (_, cmd, _) in tools.iter().filter(|t| t.1 != SEP.1) { + if !known(cmd) { + missing.push(format!("{tab}/{panel} slide-out: {cmd}")); + } + } + } for (_, cmd, _) in QAT.iter().chain(APP_MENU) { if !known(cmd) { missing.push(format!("QAT/app menu: {cmd}")); diff --git a/crates/ui-egui/src/ribbon/context.rs b/crates/ui-egui/src/ribbon/context.rs new file mode 100644 index 00000000..8dab5422 --- /dev/null +++ b/crates/ui-egui/src/ribbon/context.rs @@ -0,0 +1,309 @@ +//! Contextual ribbon tabs: a tab of its own appears after the others, in the accent colour, while +//! its context holds, and is selected when the context begins, as on Windows: Text Editor while +//! MTEXT's editor is open, Block Editor in the Block Editor, and Hatch Editor, Array, Image or +//! PDF Underlay while the selection is only hatches, one associative array, raster images or PDF +//! underlays. When the context ends the ribbon goes back to the tab it was on. +//! +//! The Text Editor tab's buttons are UI commands (`ui.mtext.*`) the editor applies to its +//! selection on the next frame ([`crate::mtext_editor`]); the other tabs start ordinary commands. + +use draftcraft_engine::doc::EntityKind; +use serde_json::Value; + +use super::Col::{Large, Small}; +use super::{RibbonPanel, RibbonTab, b}; +use crate::CadApp; +use crate::icons::Icon; + +pub(crate) const TEXT_EDITOR: &str = "Text Editor"; +pub(crate) const BLOCK_EDITOR: &str = "Block Editor"; +pub(crate) const HATCH_EDITOR: &str = "Hatch Editor"; +pub(crate) const ARRAY: &str = "Array"; +pub(crate) const IMAGE: &str = "Image"; +pub(crate) const PDF_UNDERLAY: &str = "PDF Underlay"; + +/// Close button of the tabs that a selection opens: it clears the selection. +const CLOSE_SELECTION: super::Btn = b(Icon::CloseTab, "ui.context.close", "Close"); + +pub(crate) const CONTEXT_TABS: &[RibbonTab] = &[ + RibbonTab { + name: TEXT_EDITOR, + panels: &[ + RibbonPanel { + title: "Formatting", + cols: &[ + Small(&[b(Icon::Bold, "ui.mtext.bold", "Bold"), b(Icon::Italic, "ui.mtext.italic", "Italic")]), + Small(&[b(Icon::Underline, "ui.mtext.underline", "Underline"), b(Icon::Overline, "ui.mtext.overline", "Overline")]), + ], + }, + RibbonPanel { + title: "Paragraph", + cols: &[ + Small(&[ + b(Icon::AlignLeft, "ui.mtext.left", "Left"), + b(Icon::AlignCenter, "ui.mtext.center", "Center"), + b(Icon::AlignRight, "ui.mtext.right", "Right"), + ]), + Small(&[ + b(Icon::AlignJustify, "ui.mtext.justify", "Justify"), + b(Icon::Bullets, "ui.mtext.bullets", "Bulleted list"), + b(Icon::Numbering, "ui.mtext.numbers", "Numbered list"), + ]), + ], + }, + RibbonPanel { + title: "Insert", + cols: &[ + Small(&[ + b(Icon::Symbol, "ui.mtext.degree", "Degree"), + b(Icon::Symbol, "ui.mtext.plusminus", "Plus/minus"), + b(Icon::DimDiameter, "ui.mtext.diameter", "Diameter"), + ]), + Small(&[b(Icon::AlignJustify, "ui.mtext.tab", "Insert tab")]), + ], + }, + RibbonPanel { title: "Close", cols: &[Large(b(Icon::CloseTab, "ui.mtext.ok", "Close Text Editor"))] }, + ], + }, + RibbonTab { + name: BLOCK_EDITOR, + panels: &[ + RibbonPanel { + title: "Open/Save", + cols: &[ + Large(b(Icon::BlockEdit, "bedit", "Edit Block")), + Small(&[b(Icon::Save, "bsave", "Save Block"), b(Icon::SaveAs, "bsaveas", "Save Block As")]), + ], + }, + RibbonPanel { + title: "Authoring", + cols: &[Large(b(Icon::Parameters, "bparameter", "Parameter")), Large(b(Icon::Stretch, "baction", "Action"))], + }, + RibbonPanel { + title: "Geometry", + cols: &[Small(&[b(Icon::AttDef, "attdef", "Define Attributes"), b(Icon::Constraint, "autoconstrain", "Auto Constrain")])], + }, + RibbonPanel { title: "Close", cols: &[Large(b(Icon::CloseTab, "bclose", "Close Block Editor"))] }, + ], + }, + RibbonTab { + name: HATCH_EDITOR, + panels: &[ + RibbonPanel { title: "Pattern", cols: &[Large(b(Icon::Hatch, "hatchedit", "Hatch Edit"))] }, + RibbonPanel { + title: "Properties", + cols: &[Small(&[b(Icon::Properties, "properties", "Properties"), b(Icon::MatchProp, "matchprop", "Match Properties")])], + }, + RibbonPanel { + title: "Options", + cols: &[Small(&[b(Icon::MoveBottom, "hatchtoback", "Send Hatches to Back"), b(Icon::Boundary, "boundary", "Boundary")])], + }, + RibbonPanel { title: "Close", cols: &[Large(CLOSE_SELECTION)] }, + ], + }, + RibbonTab { + name: ARRAY, + panels: &[ + RibbonPanel { + title: "Options", + cols: &[Large(b(Icon::ArrayRect, "arrayedit", "Edit Array")), Small(&[b(Icon::Explode, "explode", "Explode")])], + }, + RibbonPanel { title: "Properties", cols: &[Small(&[b(Icon::Properties, "properties", "Properties")])] }, + RibbonPanel { title: "Close", cols: &[Large(CLOSE_SELECTION)] }, + ], + }, + RibbonTab { + name: IMAGE, + panels: &[ + RibbonPanel { title: "Adjust", cols: &[Large(b(Icon::Adjust, "imageadjust", "Adjust"))] }, + RibbonPanel { title: "Clipping", cols: &[Large(b(Icon::ClipFrame, "imageclip", "Create Clipping Boundary"))] }, + RibbonPanel { + title: "Options", + cols: &[Small(&[b(Icon::List, "image", "External References"), b(Icon::MoveBottom, "draworder", "Draw Order")])], + }, + RibbonPanel { title: "Close", cols: &[Large(CLOSE_SELECTION)] }, + ], + }, + RibbonTab { + name: PDF_UNDERLAY, + panels: &[ + RibbonPanel { title: "Adjust", cols: &[Large(b(Icon::Adjust, "pdfadjust", "Adjust"))] }, + RibbonPanel { title: "Clipping", cols: &[Large(b(Icon::ClipFrame, "pdfclip", "Create Clipping Boundary"))] }, + RibbonPanel { + title: "Options", + cols: &[Large(b(Icon::Pdf, "pdfimport", "PDF Import")), Small(&[b(Icon::List, "ulayers", "Underlay Layers")])], + }, + RibbonPanel { title: "Close", cols: &[Large(CLOSE_SELECTION)] }, + ], + }, +]; + +/// Which contextual tab is up and the tab the ribbon was on before it. +#[derive(Default)] +pub struct State { + shown: Option<&'static str>, + before: Option<String>, + /// A Text Editor tab button for the MTEXT editor to apply on its next frame. + pub(crate) text_action: Option<&'static str>, +} + +fn tab(name: &str) -> Option<&'static RibbonTab> { + CONTEXT_TABS.iter().find(|t| t.name == name) +} + +pub(crate) fn is_contextual(name: &str) -> bool { + tab(name).is_some() +} + +/// The contextual tab the app's state calls for now. +pub(crate) fn current(app: &CadApp) -> Option<&'static RibbonTab> { + if crate::mtext_editor::is_open(app) { + return tab(TEXT_EDITOR); + } + let st = app.session.state().ok()?; + if st.block_editor().is_some() { + return tab(BLOCK_EDITOR); + } + let d = &st.doc; + let kinds: Vec<&'static str> = st + .selection + .iter() + .take(10_000) + .map(|h| match d.entity(*h) { + Some(e) if d.array_params(e).is_some() => ARRAY, + Some(e) => match &e.kind { + EntityKind::Hatch(_) => HATCH_EDITOR, + EntityKind::Image(i) if i.underlay.is_some() => PDF_UNDERLAY, + EntityKind::Image(_) => IMAGE, + _ => "", + }, + None => "", + }) + .collect(); + let first = *kinds.first()?; + // One array at a time (its tab edits one); the other kinds may be many of the same. + let same = kinds.iter().all(|k| *k == first) && (first != ARRAY || kinds.len() == 1); + if first.is_empty() || !same { + return None; + } + tab(first) +} + +/// Bring the ribbon to the contextual tab when a context begins and back when it ends. +pub(crate) fn update(app: &mut CadApp) { + let now = current(app).map(|t| t.name); + if now == app.ribbon_context.shown { + return; + } + match now { + Some(name) => { + if app.ribbon_context.shown.is_none() || !is_contextual(&app.ui.ribbon_tab) { + app.ribbon_context.before = Some(app.ui.ribbon_tab.clone()); + } + app.ui.ribbon_tab = name.to_string(); + } + None => { + if let Some(before) = app.ribbon_context.before.take() + && is_contextual(&app.ui.ribbon_tab) + { + app.ui.ribbon_tab = before; + } + } + } + app.ribbon_context.shown = now; +} + +/// The Text Editor buttons and the Close button of the selection tabs. +pub(crate) fn route(app: &mut CadApp, id: &str, _params: &Value) -> Option<Result<Value, String>> { + if id == "ui.context.close" { + app.session.set_selection(Vec::new()); + return Some(Ok(Value::Null)); + } + let action = id.strip_prefix("ui.mtext.")?; + let known = crate::mtext_editor::ACTIONS.iter().find(|a| **a == action)?; + if !crate::mtext_editor::is_open(app) { + return Some(Err("The text editor is not open.".into())); + } + app.ribbon_context.text_action = Some(known); + Some(Ok(Value::Null)) +} + +#[cfg(test)] +mod tests { + use draftcraft_engine::Session; + use draftcraft_engine::doc::{EntityKind, Image, Underlay}; + use egui::{Rect, pos2, vec2}; + use serde_json::json; + + use super::*; + use crate::Services; + + fn image(app: &mut CadApp, underlay: bool) -> draftcraft_engine::doc::Handle { + let i = Image { underlay: underlay.then(|| Underlay { page: "1".into(), ..Default::default() }), ..Image::default() }; + app.session.add_entity(EntityKind::Image(i)).unwrap() + } + + #[test] + fn a_selection_brings_its_tab_and_clearing_it_goes_back() { + let mut app = CadApp::new(Session::new(), Services::default()); + app.ui.ribbon_tab = "Insert".into(); + let (img, pdf) = (image(&mut app, false), image(&mut app, true)); + update(&mut app); + assert_eq!(app.ui.ribbon_tab, "Insert"); + app.session.set_selection(vec![img]); + update(&mut app); + assert_eq!(app.ui.ribbon_tab, IMAGE); + // From one contextual tab to another, the tab to go back to stays the first one. + app.session.set_selection(vec![pdf]); + update(&mut app); + assert_eq!(app.ui.ribbon_tab, PDF_UNDERLAY); + // A mixed selection has no contextual tab. + app.session.set_selection(vec![img, pdf]); + update(&mut app); + assert_eq!(app.ui.ribbon_tab, "Insert"); + app.session.set_selection(vec![pdf]); + update(&mut app); + app.start("ui.context.close"); + assert!(app.session.selection().is_empty()); + update(&mut app); + assert_eq!(app.ui.ribbon_tab, "Insert"); + // A tab the user picked meanwhile is kept when the context ends. + app.session.set_selection(vec![img]); + update(&mut app); + app.ui.ribbon_tab = "View".into(); + app.session.set_selection(Vec::new()); + update(&mut app); + assert_eq!(app.ui.ribbon_tab, "View"); + } + + #[test] + fn the_text_editor_tab_formats_the_editor_text() { + let ctx = egui::Context::default(); + let mut app = CadApp::new(Session::new(), Services::default()); + let frame = |app: &mut CadApp| { + let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(pos2(0.0, 0.0), vec2(1200.0, 800.0))), ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| crate::mtext_editor::show(app, ui.ctx())); + out.textures_delta.clear(); + }; + assert!(app.run("ui.mtext.bold", json!(null)).is_err(), "no editor open"); + app.start("mtext"); + app.session.input(draftcraft_engine::Input::Point(draftcraft_geom::Vec2::new(1.0, 1.0))).unwrap(); + app.session.input(draftcraft_engine::Input::Point(draftcraft_geom::Vec2::new(6.0, 0.0))).unwrap(); + frame(&mut app); + update(&mut app); + assert_eq!(app.ui.ribbon_tab, TEXT_EDITOR); + // Bold, then the degree sign typed in bold, then Close Text Editor. + app.start("ui.mtext.bold"); + frame(&mut app); + app.start("ui.mtext.degree"); + frame(&mut app); + app.start("ui.mtext.ok"); + frame(&mut app); + let d = app.session.doc().unwrap(); + let text = d.model.iter().find_map(|e| if let EntityKind::MText(m) = &e.kind { Some(m.contents.clone()) } else { None }); + let text = text.expect("the MTEXT was made"); + assert!(text.contains("|b1") && text.contains("°"), "{text}"); + update(&mut app); + assert_ne!(app.ui.ribbon_tab, TEXT_EDITOR); + } +} diff --git a/crates/ui-egui/src/workspaces.rs b/crates/ui-egui/src/workspaces.rs new file mode 100644 index 00000000..e4b14539 --- /dev/null +++ b/crates/ui-egui/src/workspaces.rs @@ -0,0 +1,387 @@ +//! Workspaces (WORKSPACE, WSCURRENT, WSSAVE) and interface customization (CUI). +//! +//! A workspace is a named arrangement of the interface: the palettes and where they dock, which +//! bars show (ribbon, file tabs, status bar, command line), the Quick Access Toolbar's commands +//! and which ribbon tabs show. "2D Drafting" is the built-in one, DraftCraft's default layout; +//! the others are saved with the preferences. The Customize User Interface dialog (CUI) edits the +//! Quick Access Toolbar and the ribbon tabs and manages the workspaces. +//! +//! The JSON forms never open a dialog: `workspace {operation, name, to}`, `wscurrent {name}`, +//! `wssave {name}`, `ui.cui {qat, hiddenTabs}`. + +use serde::{Deserialize, Serialize}; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::theme::Tokens; + +/// The built-in workspace: DraftCraft's default layout, which can't be renamed or deleted. +pub const BUILT_IN: &str = "2D Drafting"; +/// Most saved workspaces, and most Quick Access Toolbar commands. +const MAX_WORKSPACES: usize = 50; +pub(crate) const MAX_QAT: usize = 40; +/// Longest workspace name kept. +const MAX_NAME: usize = 100; + +/// A saved workspace. +#[derive(Clone, Debug, Serialize, Deserialize)] +#[serde(default, rename_all = "camelCase")] +pub struct SavedWorkspace { + pub name: String, + pub docking: crate::docking::Workspace, + pub show_toolbar: bool, + pub ribbon_minimized: bool, + pub show_file_tabs: bool, + pub show_status_bar: bool, + pub show_command_line: bool, + pub show_toolsets: bool, + pub show_palettes: bool, + /// The Quick Access Toolbar's commands; `None`: the standard ones. + pub qat: Option<Vec<String>>, + pub hidden_tabs: Vec<String>, +} + +impl Default for SavedWorkspace { + fn default() -> Self { + let ui = crate::UiState::default(); + SavedWorkspace::capture(BUILT_IN, &ui) + } +} + +impl SavedWorkspace { + fn capture(name: &str, ui: &crate::UiState) -> Self { + SavedWorkspace { + name: name.to_string(), + docking: ui.docking.clone(), + show_toolbar: ui.show_toolbar, + ribbon_minimized: ui.ribbon_minimized, + show_file_tabs: ui.show_file_tabs, + show_status_bar: ui.show_status_bar, + show_command_line: ui.show_command_line, + show_toolsets: ui.show_toolsets, + show_palettes: ui.show_palettes, + qat: ui.qat.clone(), + hidden_tabs: ui.hidden_tabs.clone(), + } + } + + fn apply(&self, ui: &mut crate::UiState) { + // A saved layout that no longer validates gives way to the default one. + ui.docking = if crate::docking::validate(&self.docking).is_ok() { self.docking.clone() } else { crate::docking::default_workspace() }; + ui.show_toolbar = self.show_toolbar; + ui.ribbon_minimized = self.ribbon_minimized; + ui.show_file_tabs = self.show_file_tabs; + ui.show_status_bar = self.show_status_bar; + ui.show_command_line = self.show_command_line; + ui.show_toolsets = self.show_toolsets; + ui.show_palettes = self.show_palettes; + ui.qat = self.qat.clone(); + ui.hidden_tabs = self.hidden_tabs.clone(); + } +} + +fn clip(s: &str) -> String { + s.chars().filter(|c| !c.is_control()).take(MAX_NAME).collect::<String>().trim().to_string() +} + +/// The workspaces' names, the built-in one first. +pub fn names(app: &CadApp) -> Vec<String> { + std::iter::once(BUILT_IN.to_string()).chain(app.ui.workspaces.iter().map(|w| w.name.clone())).collect() +} + +/// The current workspace's name. +pub fn current(app: &CadApp) -> String { + if app.ui.current_workspace.is_empty() { BUILT_IN.to_string() } else { app.ui.current_workspace.clone() } +} + +fn find(app: &CadApp, name: &str) -> Option<usize> { + app.ui.workspaces.iter().position(|w| w.name.eq_ignore_ascii_case(name)) +} + +fn listing(app: &CadApp) -> Value { + json!({ "workspaces": names(app), "current": current(app) }) +} + +/// Make `name` current: lay the interface out as it was saved. +pub fn set_current(app: &mut CadApp, name: &str) -> Result<Value, String> { + if name.eq_ignore_ascii_case(BUILT_IN) { + SavedWorkspace::default().apply(&mut app.ui); + app.ui.current_workspace = BUILT_IN.into(); + } else { + let i = find(app, name).ok_or_else(|| format!("no workspace \"{name}\""))?; + let w = app.ui.workspaces.get(i).cloned().ok_or("no such workspace")?; + w.apply(&mut app.ui); + app.ui.current_workspace = w.name; + } + app.set_status(format!("{} {}", crate::i18n::t("Workspace:"), current(app))); + Ok(listing(app)) +} + +/// Save the interface as it is now as workspace `name` (replacing one of that name) and make it +/// current. +pub fn save_as(app: &mut CadApp, name: &str) -> Result<Value, String> { + let name = clip(name); + if name.is_empty() { + return Err("a workspace needs a name".into()); + } + if name.eq_ignore_ascii_case(BUILT_IN) { + return Err(format!("\"{BUILT_IN}\" is the built-in workspace: save under another name")); + } + let w = SavedWorkspace::capture(&name, &app.ui); + match find(app, &name) { + Some(i) => { + if let Some(slot) = app.ui.workspaces.get_mut(i) { + *slot = w; + } + } + None if app.ui.workspaces.len() >= MAX_WORKSPACES => return Err(format!("at most {MAX_WORKSPACES} workspaces")), + None => app.ui.workspaces.push(w), + } + app.ui.current_workspace = name; + Ok(listing(app)) +} + +/// `workspace {operation: list|setCurrent|saveAs|rename|delete, name, to}` and its relatives. +pub fn command(app: &mut CadApp, id: &str, p: &Value) -> Result<Value, String> { + let s = |k: &str| p.get(k).and_then(Value::as_str).map(clip); + let op = match id { + "wscurrent" => { + if s("name").is_none() { + return Ok(listing(app)); + } + "setcurrent".to_string() + } + "wssave" => "saveas".to_string(), + _ => s("operation").unwrap_or_else(|| "list".into()).to_ascii_lowercase(), + }; + let name = || s("name").filter(|n| !n.is_empty()).ok_or_else(|| "`name` is the workspace".to_string()); + match op.as_str() { + "list" => Ok(listing(app)), + "setcurrent" | "set" => set_current(app, &name()?), + "saveas" | "save" => save_as(app, &name()?), + "rename" => { + let from = name()?; + let to = s("to").filter(|n| !n.is_empty()).ok_or("`to` is the new name")?; + if from.eq_ignore_ascii_case(BUILT_IN) || to.eq_ignore_ascii_case(BUILT_IN) { + return Err(format!("\"{BUILT_IN}\" is the built-in workspace")); + } + if find(app, &to).is_some_and(|j| Some(j) != find(app, &from)) { + return Err(format!("a workspace is already named \"{to}\"")); + } + let i = find(app, &from).ok_or_else(|| format!("no workspace \"{from}\""))?; + if let Some(w) = app.ui.workspaces.get_mut(i) { + w.name = to.clone(); + } + if app.ui.current_workspace.eq_ignore_ascii_case(&from) { + app.ui.current_workspace = to; + } + Ok(listing(app)) + } + "delete" => { + let n = name()?; + if n.eq_ignore_ascii_case(BUILT_IN) { + return Err(format!("\"{BUILT_IN}\" is the built-in workspace")); + } + if n.eq_ignore_ascii_case(¤t(app)) { + return Err("the current workspace can't be deleted: make another current first".into()); + } + let i = find(app, &n).ok_or_else(|| format!("no workspace \"{n}\""))?; + app.ui.workspaces.remove(i); + Ok(listing(app)) + } + other => Err(format!("unknown operation \"{other}\" (list, setCurrent, saveAs, rename, delete)")), + } +} + +/// `ui.cui {qat?: [command ids] | null (the standard ones), hiddenTabs?: [tab names]}` → the +/// customization. +pub fn cui_command(app: &mut CadApp, p: &Value) -> Result<Value, String> { + if let Some(q) = p.get("qat") { + app.ui.qat = match q { + Value::Null => None, + Value::Array(a) => { + let mut ids = Vec::new(); + for v in a.iter().take(MAX_QAT) { + let id = v.as_str().map(|x| x.trim().to_ascii_lowercase()).ok_or("`qat` lists command ids")?; + if draftcraft_engine::find_command(&id).is_none() && !crate::menus::is_ui_command(&id) { + return Err(format!("unknown command \"{id}\"")); + } + ids.push(id); + } + Some(ids) + } + _ => return Err("`qat` lists command ids".into()), + }; + } + if let Some(h) = p.get("hiddenTabs") { + let a = h.as_array().ok_or("`hiddenTabs` lists ribbon tab names")?; + let tabs = crate::ribbon::tab_names(); + let mut hidden = Vec::new(); + for v in a { + let n = v.as_str().ok_or("`hiddenTabs` lists ribbon tab names")?; + let tab = tabs.iter().find(|t| t.eq_ignore_ascii_case(n)).ok_or_else(|| format!("no ribbon tab \"{n}\""))?; + hidden.push(tab.to_string()); + } + if hidden.len() >= tabs.len() { + return Err("at least one ribbon tab must show".into()); + } + app.ui.hidden_tabs = hidden; + } + Ok(json!({ "qat": crate::ribbon::qat_ids(app), "hiddenTabs": app.ui.hidden_tabs, "custom": app.ui.qat.is_some() })) +} + +/// Route WORKSPACE, WSCURRENT, WSSAVE, WSSETTINGS, CUI and `ui.cui`: typed or chosen without +/// parameters, they open the Customize User Interface dialog (WSSAVE asks for a name there). +pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> { + match id { + "ui.cui" => Some(cui_command(app, params)), + "cui" | "workspace" | "-workspace" | "wssave" | "wssettings" if params.is_null() => { + app.ui.dialog = Some("cui".into()); + Some(Ok(Value::Null)) + } + "wscurrent" if params.is_null() => { + let r = listing(app); + app.session.echo(format!("WSCURRENT = \"{}\"", current(app))); + Some(Ok(r)) + } + "workspace" | "-workspace" | "wscurrent" | "wssave" => Some(command(app, id.trim_start_matches('-'), params)), + _ => None, + } +} + +/// The dialog's state while it is open. +#[derive(Clone, Default)] +struct Cui { + selected: Option<String>, + new_name: String, + add_command: String, + error: Option<String>, +} + +/// The Customize User Interface dialog: workspaces, the Quick Access Toolbar and the ribbon tabs. +pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { + let key = egui::Id::unique("cui-state"); + let mut st: Cui = ctx.data_mut(|d| d.get_temp(key)).unwrap_or_default(); + let t = Tokens::get(); + let mut todo: Vec<(&str, Value)> = Vec::new(); + egui::Window::new(crate::tl!("Customize User Interface")).open(open).collapsible(false).resizable(true).default_width(560.0).show(ctx, |ui| { + ui.columns(3, |cols| { + // Workspaces. + cols[0].strong(crate::tl!("Workspaces")); + let cur = current(app); + for n in names(app) { + let label = if n == cur { format!("{n} ✓") } else { n.clone() }; + if cols[0].selectable_label(st.selected.as_deref() == Some(&n), label).clicked() { + st.selected = Some(n.clone()); + } + } + cols[0].add_space(4.0); + let sel = st.selected.clone(); + cols[0].horizontal_wrapped(|ui| { + if ui.add_enabled(sel.is_some(), egui::Button::new(crate::tl!("Set Current"))).clicked() + && let Some(n) = &sel + { + todo.push(("workspace", json!({ "operation": "setCurrent", "name": n }))); + } + let deletable = sel.as_deref().is_some_and(|n| n != BUILT_IN && n != cur); + if ui.add_enabled(deletable, egui::Button::new(crate::tl!("Delete"))).clicked() + && let Some(n) = &sel + { + todo.push(("workspace", json!({ "operation": "delete", "name": n }))); + st.selected = None; + } + }); + cols[0].add(egui::TextEdit::singleline(&mut st.new_name).hint_text(crate::tl!("Workspace name"))); + cols[0].horizontal_wrapped(|ui| { + let named = !st.new_name.trim().is_empty(); + if ui.add_enabled(named, egui::Button::new(crate::tl!("Save Current As"))).clicked() { + todo.push(("workspace", json!({ "operation": "saveAs", "name": st.new_name.trim() }))); + } + let renamable = named && sel.as_deref().is_some_and(|n| n != BUILT_IN); + if ui.add_enabled(renamable, egui::Button::new(crate::tl!("Rename"))).clicked() + && let Some(n) = &sel + { + todo.push(("workspace", json!({ "operation": "rename", "name": n, "to": st.new_name.trim() }))); + st.selected = Some(st.new_name.trim().to_string()); + } + }); + + // Quick Access Toolbar. + cols[1].strong(crate::tl!("Quick Access Toolbar")); + let qat = crate::ribbon::qat_ids(app); + let mut changed: Option<Vec<String>> = None; + for (i, id) in qat.iter().enumerate() { + cols[1].horizontal(|ui| { + let label = draftcraft_engine::find_command(id).map(|c| crate::i18n::t(c.label).to_string()).unwrap_or_else(|| id.clone()); + ui.label(label); + if ui.small_button("▲").on_hover_text(crate::tl!("Move Up")).clicked() && i > 0 { + let mut q = qat.clone(); + q.swap(i, i - 1); + changed = Some(q); + } + if ui.small_button("×").on_hover_text(crate::tl!("Remove")).clicked() { + let mut q = qat.clone(); + q.remove(i); + changed = Some(q); + } + }); + } + cols[1].horizontal(|ui| { + ui.add(egui::TextEdit::singleline(&mut st.add_command).hint_text(crate::tl!("Command")).desired_width(90.0)); + if ui.button(crate::tl!("Add")).clicked() && !st.add_command.trim().is_empty() { + let mut q = qat.clone(); + q.push(st.add_command.trim().to_ascii_lowercase()); + changed = Some(q); + } + }); + if cols[1].button(crate::tl!("Reset to Standard")).clicked() { + todo.push(("ui.cui", json!({ "qat": null }))); + } + if let Some(q) = changed { + todo.push(("ui.cui", json!({ "qat": q }))); + } + + // Ribbon tabs. + cols[2].strong(crate::tl!("Ribbon Tabs")); + let hidden = app.ui.hidden_tabs.clone(); + for tab in crate::ribbon::tab_names() { + let mut shown = !hidden.iter().any(|h| h == tab); + if cols[2].checkbox(&mut shown, crate::i18n::t(tab)).changed() { + let mut h: Vec<String> = hidden.iter().filter(|x| *x != tab).cloned().collect(); + if !shown { + h.push(tab.to_string()); + } + todo.push(("ui.cui", json!({ "hiddenTabs": h }))); + } + } + cols[2].add_space(6.0); + if cols[2].button(crate::tl!("Edit Aliases...")).clicked() { + todo.push(("aliasedit", Value::Null)); + } + }); + if let Some(e) = &st.error { + ui.colored_label(t.warn, e); + } + ui.label(egui::RichText::new(crate::tl!("Changes apply at once; Save Current As keeps them in a workspace.")).color(t.text_dim)); + }); + for (cmd, p) in todo { + let r = if p.is_null() { + app.start(cmd); + Ok(Value::Null) + } else { + app.run(cmd, p) + }; + st.error = r.err(); + if cmd == "workspace" && st.error.is_none() { + st.new_name.clear(); + } + if cmd == "ui.cui" && st.error.is_none() { + st.add_command.clear(); + } + } + if *open { + ctx.data_mut(|d| d.insert_temp(key, st)); + } else { + ctx.data_mut(|d| d.remove::<Cui>(key)); + } +} diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 6cc883a6..03d01e1a 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -38,4 +38,5 @@ mod toolsets_gear; mod toolsets_parametric; mod viewport_double_click_selection; mod workspace_focus; +mod workspaces_cui; mod zoomed_far_in; diff --git a/crates/ui-egui/tests/it/workspaces_cui.rs b/crates/ui-egui/tests/it/workspaces_cui.rs new file mode 100644 index 00000000..4f7ca844 --- /dev/null +++ b/crates/ui-egui/tests/it/workspaces_cui.rs @@ -0,0 +1,87 @@ +//! Workspaces (WORKSPACE, WSCURRENT, WSSAVE) and interface customization (CUI): a saved +//! workspace brings its layout back, the built-in one can't be changed, and the Quick Access +//! Toolbar and ribbon tabs follow the customization. + +use draftcraft_engine::Session; +use draftcraft_ui_egui::{CadApp, Services}; +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::Queryable; +use serde_json::json; + +fn app() -> CadApp { + let mut app = CadApp::new(Session::default(), Services::default()); + app.run("new", json!({})).unwrap(); + app.ui.start_tab = false; + app +} + +#[test] +fn a_saved_workspace_restores_its_layout() { + let mut app = app(); + app.ui.show_status_bar = false; + app.ui.ribbon_minimized = true; + let r = app.run("workspace", json!({"operation": "saveAs", "name": "Minimal"})).unwrap(); + assert_eq!(r["current"], "Minimal"); + assert_eq!(r["workspaces"], json!(["2D Drafting", "Minimal"])); + // The built-in workspace is the default layout. + app.run("wscurrent", json!({"name": "2D Drafting"})).unwrap(); + assert!(app.ui.show_status_bar && !app.ui.ribbon_minimized); + // The saved one brings its layout back. + app.run("wscurrent", json!({"name": "minimal"})).unwrap(); + assert!(!app.ui.show_status_bar && app.ui.ribbon_minimized); + assert_eq!(app.run("wscurrent", json!({})).unwrap()["current"], "Minimal"); +} + +#[test] +fn the_built_in_workspace_and_the_current_one_are_protected() { + let mut app = app(); + assert!(app.run("workspace", json!({"operation": "saveAs", "name": "2D Drafting"})).is_err()); + assert!(app.run("workspace", json!({"operation": "delete", "name": "2D Drafting"})).is_err()); + app.run("wssave", json!({"name": "Mine"})).unwrap(); + assert!(app.run("workspace", json!({"operation": "delete", "name": "Mine"})).is_err(), "Mine is current"); + app.run("workspace", json!({"operation": "rename", "name": "Mine", "to": "Ours"})).unwrap(); + assert_eq!(app.ui.current_workspace, "Ours"); + app.run("wscurrent", json!({"name": "2D Drafting"})).unwrap(); + let r = app.run("workspace", json!({"operation": "delete", "name": "Ours"})).unwrap(); + assert_eq!(r["workspaces"], json!(["2D Drafting"])); + assert!(app.run("wscurrent", json!({"name": "Nowhere"})).is_err()); + assert!(app.run("workspace", json!({"operation": "explode"})).is_err()); +} + +#[test] +fn cui_customizes_the_quick_access_toolbar_and_the_tabs() { + let mut app = app(); + let r = app.run("ui.cui", json!({"qat": ["new", "LINE", "circle"], "hiddenTabs": ["view", "Output"]})).unwrap(); + assert_eq!(r["qat"], json!(["new", "line", "circle"])); + assert_eq!(app.ui.hidden_tabs, vec!["View".to_string(), "Output".to_string()]); + assert!(app.run("ui.cui", json!({"qat": ["nosuchcommand"]})).is_err()); + assert!(app.run("ui.cui", json!({"hiddenTabs": ["Nowhere"]})).is_err()); + + let mut h = Harness::builder().with_size(vec2(1400.0, 800.0)).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + assert!(h.query_by_role_and_label(Role::Tab, "Output").is_none(), "Output is hidden"); + assert!(h.query_by_role_and_label(Role::Tab, "Insert").is_some()); + // The standard toolbar comes back. + h.state_mut().run("ui.cui", json!({"qat": null, "hiddenTabs": []})).unwrap(); + h.run_steps(3); + assert!(h.query_by_role_and_label(Role::Tab, "Output").is_some()); + assert_eq!(h.state().ui.qat, None); +} + +#[test] +fn typed_cui_opens_the_dialog_and_never_from_json() { + let mut app = app(); + app.cmdline("cui"); + assert_eq!(app.ui.dialog.as_deref(), Some("cui")); + app.ui.dialog = None; + app.run("workspace", json!({"operation": "list"})).unwrap(); + assert_eq!(app.ui.dialog, None); +}