From f2ae408a35df054ba702d7a10caff80211389a3f Mon Sep 17 00:00:00 2001 From: Obtrusive8276 Date: Sun, 1 Nov 2026 13:00:24 +0100 Subject: [PATCH] Blocks palette: previews, block libraries and placement Rewrite this PR on a smaller base. The Blocks window becomes a dockable palette with a Current Drawing tab and a Libraries tab, icon and list views, a kept list of block libraries (folders and DWG/DXF files) and one-click placement through the existing interactive INSERT. - Previews are built only for the visible tiles, a few per frame, under a time and point budget, in a bounded least-recently-used cache. - BLOCKLIBRARY, BLOCKLIBIMPORT and BLOCKLIBRARIES are commands; importing a library block brings only the layers, linetypes, styles and blocks it needs. - INSERT: Enter at the insertion point ends the command, as in AutoCAD. - Hostile library files and block data are bounded; nothing panics. - The canvas, ViewCube, command-line and interactive INSERT changes of the earlier version are gone. - Translations in all interface languages. Co-Authored-By: Claude Sonnet 5.5 --- .github/workflows/release.yml | 1 + ATTRIBUTION.md | 34 +- Cargo.lock | 1 - contributors/people.toml | 4 + crates/engine/src/cmd.rs | 1 + crates/engine/src/cmd/blocks.rs | 221 +-- crates/engine/src/cmd/blocks/dyngrip.rs | 2 +- crates/engine/src/cmd/blocks/insert_file.rs | 152 +- crates/engine/src/cmd/blocks/library.rs | 329 ++++ crates/engine/src/cmd/file.rs | 2 +- crates/engine/src/cmd/griphot.rs | 2 +- crates/engine/src/guard.rs | 2 +- crates/engine/src/running.rs | 13 - crates/engine/src/session/interactive.rs | 2 +- crates/engine/tests/blocklibrary.rs | 237 +++ .../tests/it/insert_attribute_prompts.rs | 17 - crates/engine/tests/it/insert_enter.rs | 20 + crates/engine/tests/it/main.rs | 1 + crates/geom/src/curve.rs | 14 - crates/geom/src/spline.rs | 93 +- crates/geom/src/spline/tests.rs | 14 - crates/io/src/pdf.rs | 1 - crates/render/src/draw.rs | 11 +- crates/render/src/fill.rs | 21 +- crates/render/src/hatch.rs | 305 +--- crates/render/src/lib.rs | 41 +- crates/render/src/pipeline.rs | 67 +- crates/render/src/viewports.rs | 17 +- crates/ui-egui/Cargo.toml | 1 - crates/ui-egui/src/blockmgr.rs | 1497 ----------------- crates/ui-egui/src/blockmgr/library_audit.rs | 139 -- crates/ui-egui/src/blockmgr/preview.rs | 563 ------- crates/ui-egui/src/blockmgr/preview/tests.rs | 263 --- crates/ui-egui/src/blocks_palette.rs | 1335 +++++++++++++++ crates/ui-egui/src/canvas.rs | 80 +- crates/ui-egui/src/canvas/list.rs | 1 - crates/ui-egui/src/canvas/tests.rs | 47 - crates/ui-egui/src/canvas/viewport.rs | 1 - crates/ui-egui/src/canvas/widgets.rs | 70 - crates/ui-egui/src/closing.rs | 9 - crates/ui-egui/src/cmdline.rs | 8 - crates/ui-egui/src/dialogs.rs | 63 - crates/ui-egui/src/docking.rs | 15 +- crates/ui-egui/src/i18n/ar.tsv | 35 +- crates/ui-egui/src/i18n/bs.tsv | 26 + crates/ui-egui/src/i18n/cs.tsv | 35 +- crates/ui-egui/src/i18n/de.tsv | 36 +- crates/ui-egui/src/i18n/el.tsv | 35 +- crates/ui-egui/src/i18n/es.tsv | 35 +- crates/ui-egui/src/i18n/fr.tsv | 67 +- crates/ui-egui/src/i18n/hu.tsv | 35 +- crates/ui-egui/src/i18n/it.tsv | 35 +- crates/ui-egui/src/i18n/ko.tsv | 35 +- crates/ui-egui/src/i18n/pt_br.tsv | 35 +- crates/ui-egui/src/i18n/ru.tsv | 36 +- crates/ui-egui/src/i18n/sv.tsv | 35 +- crates/ui-egui/src/i18n/tests.rs | 4 +- crates/ui-egui/src/i18n/tr.tsv | 35 +- crates/ui-egui/src/i18n/uk.tsv | 35 +- crates/ui-egui/src/i18n/vi.tsv | 26 + crates/ui-egui/src/i18n/zh.tsv | 35 +- crates/ui-egui/src/lib.rs | 39 +- crates/ui-egui/src/menus.rs | 26 +- crates/ui-egui/tests/blocks_palette.rs | 374 ++++ crates/ui-egui/tests/blocks_palette_review.rs | 151 -- crates/ui-egui/tests/it/rapid_clicks.rs | 34 - docs/block-preview-validation.md | 107 -- docs/ui-parity.md | 9 +- packaging/linux/flatpak-bundle.sh | 8 + packaging/linux/flatpak-oci.sh | 64 + 70 files changed, 3170 insertions(+), 3974 deletions(-) create mode 100644 crates/engine/src/cmd/blocks/library.rs create mode 100644 crates/engine/tests/blocklibrary.rs create mode 100644 crates/engine/tests/it/insert_enter.rs delete mode 100644 crates/ui-egui/src/blockmgr.rs delete mode 100644 crates/ui-egui/src/blockmgr/library_audit.rs delete mode 100644 crates/ui-egui/src/blockmgr/preview.rs delete mode 100644 crates/ui-egui/src/blockmgr/preview/tests.rs create mode 100644 crates/ui-egui/src/blocks_palette.rs create mode 100644 crates/ui-egui/tests/blocks_palette.rs delete mode 100644 crates/ui-egui/tests/blocks_palette_review.rs delete mode 100644 docs/block-preview-validation.md create mode 100755 packaging/linux/flatpak-oci.sh diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index 368d4f322..dc9c462db 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -62,6 +62,7 @@ jobs: permissions: # The reusable release workflow tags and uploads the draft release. contents: write + packages: write # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 22550ffaf..427aa1672 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -61,20 +61,20 @@ Generated-in-code assets are original and have no file to list: | Asset | Author | Source | Licence | Notes | |---|---|---|---|---| -| `crates/ui-egui/src/i18n/uk.tsv` | @dmatviichuk | Original Ukrainian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/de.tsv` | the CADCraft contributors | Original German translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/es.tsv` | @PedroGuille | Original Spanish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/pt_br.tsv` | @WladmirJunior | Original Brazilian Portuguese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/bs.tsv` | Nine (@nine-codes) with Claude Code (AI-assisted) | Original Bosnian translations of CADCraft English strings, shared with storytold/craft-i18n `locales/bs/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; not yet reviewed by a native speaker | -| `crates/ui-egui/src/i18n/cs.tsv` | @Losminek (AI-assisted) | Original Czech translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/ru.tsv` | @pechnikov2026-star | Original Russian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original French translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/zh.tsv` | @mayloglog | Original Simplified Chinese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker | -| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added | -| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied | -| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker | -| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading pending | -| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending | +| `crates/ui-egui/src/i18n/uk.tsv` | @dmatviichuk | Original Ukrainian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/de.tsv` | the CADCraft contributors | Original German translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/es.tsv` | @PedroGuille | Original Spanish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/pt_br.tsv` | @WladmirJunior | Original Brazilian Portuguese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/bs.tsv` | Nine (@nine-codes) with Claude Code (AI-assisted) | Original Bosnian translations of CADCraft English strings, shared with storytold/craft-i18n `locales/bs/` | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; not yet reviewed by a native speaker; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/cs.tsv` | @Losminek (AI-assisted) | Original Czech translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/ru.tsv` | @pechnikov2026-star | Original Russian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/fr.tsv` | @pechnikov2026-star | Original French translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/zh.tsv` | @mayloglog | Original Simplified Chinese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/sv.tsv` | Erik Holmbom (@holmbom) with Claude Code (AI-assisted) | Original Swedish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology and the running app reviewed by a native speaker; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/it.tsv` | Emanuele Bottelli (AI-assisted) | Original Italian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/ko.tsv` | @huk082 (AI-assisted) | Original Korean translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; no font assets added; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/ar.tsv` | @hasan-sdaif | Original Arabic translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/hu.tsv` | @Skaywalker | Original Hungarian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading pending; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | +| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending; Blocks palette strings added by Claude Code (AI-assisted), not yet reviewed by a native speaker | diff --git a/Cargo.lock b/Cargo.lock index 420b2e459..c45ba071c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -796,7 +796,6 @@ dependencies = [ "cadcraft-engine", "cadcraft-fonts", "cadcraft-geom", - "cadcraft-io", "cadcraft-render", "chrono", "craft-ui", diff --git a/contributors/people.toml b/contributors/people.toml index fc3f7a2a1..626c114e4 100644 --- a/contributors/people.toml +++ b/contributors/people.toml @@ -99,3 +99,7 @@ sync_github_name = true [people.GULERTOLGA] sync_github_name = true + +[people.Obtrusive8276] +display_name = "Nicopicks" +sync_github_name = false diff --git a/crates/engine/src/cmd.rs b/crates/engine/src/cmd.rs index 172e416d1..a95610246 100644 --- a/crates/engine/src/cmd.rs +++ b/crates/engine/src/cmd.rs @@ -31,6 +31,7 @@ mod overkill; mod pline_opts; pub mod plotters; mod props; +pub use blocks::library::read_library_file; pub use draw2::breakline::BreaklineOptions; pub use props::MatchProps; pub(crate) use props::UNIT_RANGES; diff --git a/crates/engine/src/cmd/blocks.rs b/crates/engine/src/cmd/blocks.rs index 30fac466f..91db3b821 100644 --- a/crates/engine/src/cmd/blocks.rs +++ b/crates/engine/src/cmd/blocks.rs @@ -41,6 +41,10 @@ pub fn specs() -> Vec { .alias(&["i", "-insert", "ddinsert"]) .params("{name (\"*NAME\": exploded), file?: DXF/DWG path (defines or redefines block `name`, default the file name, from its model space; base point $INSBASE), at: [x,y], scale?: number | [x, y], rotation? (degrees), basePoint?: [x,y] (block coordinates), attribs?: {TAG: value}, explode?: bool}") .interactive(|_| Ok(Box::new(InsertM::default()))), + CommandSpec::new("blockspalette", "Blocks Palette", run_blockspalette) + .params("{} → {blocks: [{name, description, references}], truncated} (the app opens the Blocks palette instead)") + .enabled(has_doc) + .noundo(), CommandSpec::new("attdef", "Define Attributes...", run_attdef) .menu(&["Draw", "Block", "Define Attributes..."]) .alias(&["att", "-attdef"]) @@ -85,6 +89,7 @@ pub fn specs() -> Vec { .into_iter() .chain(attribs::attdisp_menu_specs()) .chain(xref::specs()) + .chain(library::specs()) .chain(refedit::specs()) .chain(bedit::specs()) .collect() @@ -299,6 +304,35 @@ fn run_block(s: &mut Session, p: &Value) -> Result { Ok(json!({ "block": name, "insert": r.map(|h| h.hex()) })) } +/// BLOCKSPALETTE as a JSON call: the drawing's own blocks (no anonymous, layout or xref blocks) +/// with their descriptions and how many references use each. The app opens the palette instead. +fn run_blockspalette(s: &mut Session, _p: &Value) -> Result { + let d = s.doc()?; + let mut counts: std::collections::HashMap = std::collections::HashMap::new(); + let mut count = |store: &cadcraft_doc::EntityStore| { + for e in store.iter() { + if let EntityKind::Insert(i) = &e.kind { + let n = counts.entry(i.block.to_ascii_lowercase()).or_insert(0); + *n = n.saturating_add(1); + } + } + }; + count(&d.model); + d.layouts.iter().for_each(|l| count(&l.entities)); + d.blocks.values().for_each(|b| count(&b.entities)); + let mut blocks: Vec<&Arc> = + d.blocks.values().filter(|b| !b.anonymous && b.xref_path.is_none() && !b.name.starts_with('*') && !b.name.contains('|')).collect(); + blocks.sort_by_key(|b| b.name.to_ascii_lowercase()); + let list: Vec = blocks + .iter() + .take(library::MAX_LISTED) + .map( + |b| json!({ "name": b.name, "description": b.description, "references": counts.get(&b.name.to_ascii_lowercase()).copied().unwrap_or(0) }), + ) + .collect(); + Ok(json!({ "blocks": list, "truncated": blocks.len() > library::MAX_LISTED })) +} + fn run_insert(s: &mut Session, p: &Value) -> Result { let p = &insert_file::json_params(s, p)?; let name = str_param(p, "name").ok_or_else(|| bad("insert", "`name` is required"))?.to_string(); @@ -519,7 +553,6 @@ impl Interactive for BlockM { _ => self.sel.prompt(), } } - /// Feed user input into the interactive `BLOCK` state machine. fn input(&mut self, s: &mut Session, i: Input) -> Result { match (&self.name, self.base) { (None, _) if self.existing.is_some() => { @@ -579,6 +612,7 @@ impl BlockM { } mod insert_file; +pub(crate) mod library; pub(crate) mod xref; /// Where the command-line INSERT is in its prompt sequence. @@ -626,10 +660,6 @@ struct InsertM { /// Where the block was dropped to pick a Basepoint on it. dropped: Option, rotation: Option, - preset_scale: Option, - /// The Z factor that goes with `preset_scale`, which a repeated placement starts from. - preset_z: Option, - preset_rotation: Option, /// The attributes asked for: tag, prompt, default value, and Verify (asked again). attdefs: Vec<(String, String, String, bool)>, values: serde_json::Map, @@ -637,8 +667,6 @@ struct InsertM { verified: usize, /// `*name`: insert the block's objects (one uniform scale factor, no attribute values). explode: bool, - /// Keep prompting for another insertion point after each placement until cancelled. - repeat: bool, /// The file waiting for the Redefine answer. file: Option, } @@ -672,18 +700,6 @@ impl InsertM { if self.explode { insert_file::explode_insert(s, h)?; } - if self.repeat { - self.at = None; - self.x_scale = None; - self.scale = self.preset_scale; - self.z_scale = self.preset_z; - self.xyz = false; - self.rotation = self.preset_rotation; - self.values.clear(); - self.verified = 0; - self.stage = InsStage::Point; - return Ok(Step::Continue); - } return Ok(Step::Done); } Ok(Step::Continue) @@ -759,9 +775,6 @@ impl InsertM { } } -/// The keywords that switch repeat placement on or off, offered wherever INSERT waits for a number or a point. -const REPEAT: &[&str] = &["REpeat", "NoRepeat"]; - fn nonzero(t: &str) -> Result { number(t).filter(|v| *v != 0.0).ok_or_else(|| EngineError::Other("Requires a non-zero number.".into())) } @@ -782,24 +795,19 @@ impl Interactive for InsertM { let name = self.file.as_ref().map(|f| f.name.clone()).unwrap_or_default(); Prompt::new(format!("Block \"{name}\" already exists. Redefine it?"), super::curves::KW).kw(&["Yes", "No"]).default("N") } - InsStage::Point => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "X", "Y", "Z", "Rotate", "REpeat", "NoRepeat"]), - InsStage::BasePoint => Prompt::new("Specify base point", Accept::POINT).kw(REPEAT), - InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).kw(REPEAT).default("1"), - InsStage::PresetAxis(i) => { - Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::NUMBER).kw(REPEAT).default("1") + InsStage::Point => Prompt::new("Specify insertion point", Accept::POINT).kw(&["Basepoint", "Scale", "X", "Y", "Z", "Rotate"]), + InsStage::BasePoint => Prompt::new("Specify base point", Accept::POINT), + InsStage::PresetScale => Prompt::new("Specify scale factor for XYZ axes", Accept::NUMBER).default("1"), + InsStage::PresetAxis(i) => Prompt::new(format!("Specify {} scale factor", ["X", "Y", "Z"][i.min(2)]), Accept::NUMBER).default("1"), + InsStage::PresetRotation => Prompt::new("Specify rotation angle", Accept::NUMBER).default("0"), + InsStage::XScale if self.xyz => Prompt::new("Specify X scale factor", Accept::POINT_OR_NUMBER).kw(&["Corner"]).default("1").base(at), + InsStage::XScale => { + Prompt::new("Enter X scale factor, specify opposite corner", Accept::POINT_OR_NUMBER).kw(&["Corner", "XYZ"]).default("1").base(at) } - InsStage::PresetRotation => Prompt::new("Specify rotation angle", Accept::NUMBER).kw(REPEAT).default("0"), - InsStage::XScale if self.xyz => { - Prompt::new("Specify X scale factor", Accept::POINT_OR_NUMBER).kw(&["Corner", "REpeat", "NoRepeat"]).default("1").base(at) - } - InsStage::XScale => Prompt::new("Enter X scale factor, specify opposite corner", Accept::POINT_OR_NUMBER) - .kw(&["Corner", "XYZ", "REpeat", "NoRepeat"]) - .default("1") - .base(at), - InsStage::Corner => Prompt::new("Specify opposite corner", Accept::POINT).kw(REPEAT).base(at), - InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).kw(REPEAT).default("use X scale factor"), - InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).kw(REPEAT).default("use X scale factor"), - InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).kw(REPEAT).default("0").base(at), + InsStage::Corner => Prompt::new("Specify opposite corner", Accept::POINT).base(at), + InsStage::YScale => Prompt::new("Enter Y scale factor", Accept::NUMBER).default("use X scale factor"), + InsStage::ZScale => Prompt::new("Specify Z scale factor or", Accept::NUMBER).default("use X scale factor"), + InsStage::Rotation => Prompt::new("Specify rotation angle", Accept::POINT_OR_NUMBER).default("0").base(at), InsStage::Attribs => { let (_, prompt, default, _) = self.attdefs.get(self.values.len()).cloned().unwrap_or_default(); Prompt::new(if prompt.is_empty() { "Enter attribute value".into() } else { prompt }, Accept::TEXT).default(default) @@ -811,18 +819,7 @@ impl Interactive for InsertM { } } } - /// Feed user input into the interactive `INSERT` state machine. fn input(&mut self, s: &mut Session, i: Input) -> Result { - if let Input::Keyword(k) = &i { - if k.eq_ignore_ascii_case("Repeat") { - self.repeat = true; - return Ok(Step::Continue); - } - if k == "NoRepeat" { - self.repeat = false; - return Ok(Step::Continue); - } - } match self.stage { InsStage::Name => { let n = match i { @@ -874,6 +871,8 @@ impl Interactive for InsertM { Input::Keyword(k) if k == "Y" => self.stage = InsStage::PresetAxis(1), Input::Keyword(k) if k == "Z" => self.stage = InsStage::PresetAxis(2), Input::Keyword(k) if k == "Rotate" => self.stage = InsStage::PresetRotation, + // Enter or Space at the insertion point ends the command, as in AutoCAD. + Input::Enter => return Ok(Step::Cancel), _ => {} }, InsStage::BasePoint => { @@ -885,29 +884,12 @@ impl Interactive for InsertM { } } InsStage::PresetScale => { - if let Input::Text(t) = &i - && let Some((x, y)) = t.split_once(',').filter(|_| !self.explode) - { - let sc = Vec2::new(nonzero(x.trim())?, nonzero(y.trim())?); - self.scale = Some(sc); - // Z follows the size of X, and an axis preset after this one starts from X and Y. - self.z_scale = Some(sc.x.abs()); - self.axes = [Some(sc.x), Some(sc.y), Some(sc.x.abs())]; - if self.at.is_some() { - return self.advance(s); - } - self.preset_scale = Some(sc); - self.preset_z = self.z_scale; - self.stage = InsStage::Point; - return Ok(Step::Continue); - } let f = match i { Input::Text(t) => nonzero(&t)?, Input::Enter => 1.0, _ => return Ok(Step::Continue), }; - let sc = Vec2::new(f, f); - self.scale = Some(sc); + self.scale = Some(Vec2::new(f, f)); self.z_scale = Some(f.abs()); // An axis preset after it changes that axis alone (Scale -3 then X 2: 2/-3/3). self.axes = [Some(f), Some(f), Some(f.abs())]; @@ -915,8 +897,6 @@ impl Interactive for InsertM { if self.at.is_some() { return self.advance(s); } - self.preset_scale = Some(sc); - self.preset_z = self.z_scale; self.stage = InsStage::Point; } // One axis preset: the others are 1, and no scale factors are asked after the point. @@ -932,18 +912,14 @@ impl Interactive for InsertM { let [x, y, z] = self.axes.map(|a| a.unwrap_or(1.0)); self.scale = Some(Vec2::new(x, y)); self.z_scale = Some(z.abs()); - self.preset_scale = self.scale; - self.preset_z = self.z_scale; self.stage = InsStage::Point; } InsStage::PresetRotation => { - let rot = match i { + self.rotation = Some(match i { Input::Text(t) => s.angle_settings().direction(&t).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?, Input::Enter => 0.0, _ => return Ok(Step::Continue), - }; - self.rotation = Some(rot); - self.preset_rotation = Some(rot); + }); self.stage = InsStage::Point; } InsStage::XScale => match i { @@ -1063,7 +1039,6 @@ impl Interactive for AttdefM { _ => Prompt::new("Specify start point of text", Accept::POINT), } } - /// Feed user input into the interactive `ATTDEF` state machine. fn input(&mut self, s: &mut Session, i: Input) -> Result { let text = match &i { Input::Text(t) => Some(t.clone()), @@ -1094,95 +1069,3 @@ impl Interactive for AttdefM { mod attribs; mod battman; mod blockreplace; - -#[cfg(test)] -mod tests { - use super::*; - - /// A comma-separated scale preset also sets Z to the size of X, replacing an earlier preset's Z. - #[test] - fn a_comma_scale_preset_replaces_the_previous_z_factor() { - let mut s = Session::new(); - s.execute("line", &serde_json::json!({ "points": [[0, 0], [5, 0]] })).unwrap(); - s.execute("block", &serde_json::json!({ "name": "B1", "base": [0, 0], "keep": "delete", "handles": ["100"] })).unwrap(); - s.start("insert").unwrap(); - s.cmdline("B1").unwrap(); - s.cmdline("Scale").unwrap(); - s.input(Input::Text("2".into())).unwrap(); - s.cmdline("Scale").unwrap(); - s.input(Input::Text("3,4".into())).unwrap(); - s.input(Input::Point(Vec2::new(10.0, 0.0))).unwrap(); - s.input(Input::Text("0".into())).unwrap(); - let last = s.doc().unwrap().model.iter().last().cloned().unwrap(); - let EntityKind::Insert(ins) = &last.kind else { panic!("an insert") }; - assert_eq!((ins.scale.x, ins.scale.y, ins.scale.z), (3.0, 4.0, 3.0)); - } - - /// A repeated INSERT asks the default scale prompts again, not the previous placement's XYZ ones. - #[test] - fn a_repeated_insert_starts_again_without_the_previous_xyz_choice() { - let mut s = Session::new(); - s.execute("line", &serde_json::json!({ "points": [[0, 0], [5, 0]] })).unwrap(); - s.execute("block", &serde_json::json!({ "name": "B1", "base": [0, 0], "keep": "delete", "handles": ["100"] })).unwrap(); - s.start("insert").unwrap(); - s.cmdline("B1").unwrap(); - s.cmdline("Repeat").unwrap(); - s.input(Input::Point(Vec2::new(10.0, 0.0))).unwrap(); - s.cmdline("XYZ").unwrap(); - s.input(Input::Enter).unwrap(); // X - s.input(Input::Enter).unwrap(); // Y - s.input(Input::Text("5".into())).unwrap(); // Z - s.input(Input::Text("0".into())).unwrap(); // Rotation - assert_eq!(s.current_prompt().unwrap().message, "Specify insertion point"); - s.input(Input::Point(Vec2::new(20.0, 0.0))).unwrap(); - let p = s.current_prompt().unwrap(); - assert_eq!(p.message, "Enter X scale factor, specify opposite corner"); - assert!(p.keywords.iter().any(|k| k == "XYZ")); - } - - /// Verify that the interactive `INSERT` prompt advertises `Repeat` and `NoRepeat`, and that - /// `NoRepeat` disarms repeat placement at any stage without answering scale or rotation prompts. - #[test] - fn interactive_insert_accepts_repeat_and_norepeat_across_stages() { - let mut s = Session::new(); - s.execute("line", &serde_json::json!({ "points": [[0, 0], [5, 0]] })).unwrap(); - s.execute("block", &serde_json::json!({ "name": "B1", "base": [0, 0], "keep": "delete", "handles": ["100"] })).unwrap(); - - s.start("insert").unwrap(); - s.input(Input::Text("B1".into())).unwrap(); - let p = s.current_prompt().unwrap(); - assert!(p.keywords.iter().any(|k| k == "REpeat")); - assert!(p.keywords.iter().any(|k| k == "NoRepeat")); - assert_eq!(p.match_keyword("R").as_deref(), Some("Rotate")); - assert_eq!(p.match_keyword("RE").as_deref(), Some("REpeat")); - - // Complete a placement and verify Repeat returns INSERT to the insertion-point prompt. - s.cmdline("Repeat").unwrap(); - s.input(Input::Point(Vec2::new(10.0, 0.0))).unwrap(); - s.input(Input::Enter).unwrap(); // X scale - s.input(Input::Enter).unwrap(); // Y scale - s.input(Input::Text("0".into())).unwrap(); // Rotation - assert_eq!(s.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - assert!(s.current_prompt().unwrap().accept.point); - assert_eq!(s.current_prompt().unwrap().message, "Specify insertion point"); - assert_eq!(s.doc().unwrap().model.len(), 1); - s.cancel(); - - // Start INSERT, enable Repeat, pick insertion point, then disarm Repeat with NoRepeat during Rotation stage. - s.start("insert").unwrap(); - s.cmdline("B1").unwrap(); - s.cmdline("Repeat").unwrap(); - s.input(Input::Point(Vec2::new(10.0, 0.0))).unwrap(); - s.input(Input::Enter).unwrap(); // X scale = 1 - s.input(Input::Enter).unwrap(); // Y scale = 1 -> now at Rotation stage - assert!(s.current_prompt().unwrap().message.contains("rotation")); - // Sending NoRepeat at the Rotation stage must not answer the rotation prompt or place the block yet. - assert!(s.current_prompt().unwrap().keywords.iter().any(|k| k == "NoRepeat")); - s.cmdline("NoRepeat").unwrap(); - assert!(s.running.is_some()); - assert!(s.current_prompt().unwrap().message.contains("rotation")); - // Answering rotation now places the block and finishes INSERT because repeat was disarmed. - s.input(Input::Text("45".into())).unwrap(); - assert!(s.running.is_none()); - } -} diff --git a/crates/engine/src/cmd/blocks/dyngrip.rs b/crates/engine/src/cmd/blocks/dyngrip.rs index e6d0a7596..dbc92b7fb 100644 --- a/crates/engine/src/cmd/blocks/dyngrip.rs +++ b/crates/engine/src/cmd/blocks/dyngrip.rs @@ -191,7 +191,7 @@ impl Session { let machine = crate::guard::Guarded::wrap(Box::new(edit)); let st = self.state()?; let (before, selection_before) = (st.doc.clone(), st.selection.clone()); - self.running = Some(Running::new("grip", machine, before, selection_before)); + self.running = Some(Running { id: "grip".into(), machine, before, selection_before }); self.pending_window = None; self.point_mods.clear(); self.echo("** STRETCH **"); diff --git a/crates/engine/src/cmd/blocks/insert_file.rs b/crates/engine/src/cmd/blocks/insert_file.rs index 4d0af93b3..7305916ae 100644 --- a/crates/engine/src/cmd/blocks/insert_file.rs +++ b/crates/engine/src/cmd/blocks/insert_file.rs @@ -12,9 +12,12 @@ use std::sync::Arc; use cadcraft_doc::{Block, Drawing, Entity, EntityKind, Handle}; use serde_json::{Value, json}; +#[cfg(not(target_arch = "wasm32"))] +use super::super::file::MAX_DRAWING_BYTES; use super::super::file::io; use super::super::modify::explode_kind; -use super::{references_block, valid_block_name}; +use super::purge::{Kind, candidates, override_arrows}; +use super::{referenced_block, references_block, valid_block_name}; use crate::cmd::{bad, str_param}; use crate::{EngineError, Result, Session}; @@ -37,7 +40,7 @@ impl FileRef { /// Read the file and (re)define its block. Returns the block's name. pub fn define(&self, s: &mut Session) -> Result { let src = read_drawing(&self.path)?; - define_from(s, &src, &self.name) + define_from(s, &src, &self.name, false) } } @@ -45,6 +48,11 @@ impl FileRef { /// path (it has a folder separator or a .dwg/.dxf extension) that isn't the name of a block. pub(super) fn file_ref(s: &Session, t: &str) -> Option { let t = t.trim(); + // A block of this drawing is that block, whatever its name looks like: a name read from a file + // must not pass for `name=path` and make INSERT read another file (CWE-74). + if s.doc().is_ok_and(|d| d.block(t).is_some()) { + return None; + } if let Some((name, path)) = t.split_once('=') { let name = name.trim(); let path = if path.trim().is_empty() { name } else { path.trim() }; @@ -52,14 +60,14 @@ pub(super) fn file_ref(s: &Session, t: &str) -> Option { } let lower = t.to_ascii_lowercase(); let pathlike = t.contains(['/', '\\']) || lower.ends_with(".dwg") || lower.ends_with(".dxf"); - if !pathlike || s.doc().is_ok_and(|d| d.block(t).is_some()) { + if !pathlike { return None; } Some(FileRef { name: stem(t), path: t.to_string(), explicit: false }) } /// The file name without folders and extension (either separator, so Windows paths work anywhere). -fn stem(path: &str) -> String { +pub(super) 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(), @@ -68,7 +76,7 @@ fn stem(path: &str) -> String { } /// Read a drawing file through the io hooks; a path without extension tries .dwg, then .dxf. -fn read_drawing(path: &str) -> Result { +pub(super) fn read_drawing(path: &str) -> Result { let hooks = io().ok_or_else(|| bad("insert", "file formats are not available in this build"))?; let has_ext = stem(path) != path.rsplit(['/', '\\']).next().unwrap_or(path); let candidates = if has_ext { vec![path.to_string()] } else { vec![path.to_string(), format!("{path}.dwg"), format!("{path}.dxf")] }; @@ -85,24 +93,32 @@ fn read_drawing(path: &str) -> Result { fn read_file(_path: &str) -> Result> { #[cfg(not(target_arch = "wasm32"))] { - std::fs::read(_path).map_err(|e| bad("insert", format!("{_path}: {e}"))) + crate::capped_read::read_capped(std::path::Path::new(_path), MAX_DRAWING_BYTES).map_err(|e| bad("insert", format!("{_path}: {e}"))) } #[cfg(target_arch = "wasm32")] Err(bad("insert", "paths are not available on the web")) } /// (Re)define block `name` from `src`'s model space with base point `$INSBASE`, adding the -/// layers, linetypes, styles and blocks of `src` this drawing doesn't have. Nothing changes when -/// the definition fails (an invalid name, or a block that would contain itself). -fn define_from(s: &mut Session, src: &Drawing, name: &str) -> Result { +/// layers, linetypes, styles and blocks of `src` this drawing doesn't have. With `only_needed` +/// the layers, linetypes and styles that nothing uses are left out again, as when a block is +/// taken from a library drawing: only what the block needs comes along. Nothing changes when the +/// definition fails (an invalid name, or a block that would contain itself). +pub(super) fn define_from(s: &mut Session, src: &Drawing, name: &str, only_needed: bool) -> Result { if !valid_block_name(name) { return Err(bad("insert", format!("\"{name}\" is not a valid block name"))); } let mut d = s.doc()?.clone(); + let before = TableNames::of(&d); // Redefining keeps the existing definition's name (block names are case-insensitive). let name = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(name)).cloned().unwrap_or_else(|| name.to_string()); merge_tables(&mut d, src); - let renames = block_names(&d, src, &name); + let mut renames = block_names(&d, src, &name); + if only_needed { + // The other blocks of the file are not copied at all. + let need = needed_blocks(src); + renames.retain(|from, _| need.contains(&from.to_ascii_uppercase())); + } for (from, to) in &renames { let Some(b) = src.blocks.get(from) else { continue }; let mut nb = (**b).clone(); @@ -129,10 +145,126 @@ fn define_from(s: &mut Session, src: &Drawing, name: &str) -> Result { b.entities.push(e); } d.blocks.insert(name.clone(), Arc::new(b)); + if only_needed { + drop_unused_new(&mut d, &before, &name); + } *s.doc_mut()? = d; Ok(name) } +/// The tables a drawing merge adds to, in an order where removing the unused entries of one +/// frees the next (blocks free layers, layers free linetypes, dimension styles free text styles). +const MERGED: [Kind; 8] = + [Kind::Blocks, Kind::Dimstyles, Kind::MleaderStyles, Kind::MlineStyles, Kind::TableStyles, Kind::Layers, Kind::Linetypes, Kind::TextStyles]; + +/// The names (lower case) in one of those tables. +fn names_of(d: &Drawing, kind: Kind) -> BTreeSet { + let lower = |it: &mut dyn Iterator| it.map(|n| n.to_ascii_lowercase()).collect::>(); + match kind { + Kind::Blocks => lower(&mut d.blocks.keys()), + Kind::Dimstyles => lower(&mut d.dim_styles.iter().map(|t| &t.name)), + Kind::MleaderStyles => lower(&mut d.mleader_styles.iter().map(|t| &t.name)), + Kind::MlineStyles => lower(&mut d.mline_styles.iter().map(|t| &t.name)), + Kind::TableStyles => lower(&mut d.table_styles.iter().map(|t| &t.name)), + Kind::Layers => lower(&mut d.layers.iter().map(|t| &t.name)), + Kind::Linetypes => lower(&mut d.linetypes.iter().map(|t| &t.name)), + Kind::TextStyles => lower(&mut d.text_styles.iter().map(|t| &t.name)), + _ => BTreeSet::new(), + } +} + +/// The names in the merged tables, by kind. +struct TableNames(Vec<(Kind, BTreeSet)>); + +impl TableNames { + fn of(d: &Drawing) -> Self { + TableNames(MERGED.iter().map(|k| (*k, names_of(d, *k))).collect()) + } +} + +/// Upper-case names of the blocks `roots` and every block they need, through nested references, +/// dimension blocks, multileader block content and dimension arrowheads. +fn reachable(d: &Drawing, roots: Vec) -> BTreeSet { + let mut seen = BTreeSet::new(); + let mut todo = roots; + let mut guard = 0; + while let Some(n) = todo.pop() { + guard += 1; + if guard > 100_000 || !seen.insert(n.to_ascii_uppercase()) { + continue; + } + let Some(b) = d.block(&n) else { continue }; + for e in b.entities.iter() { + todo.extend(referenced_block(e)); + if let EntityKind::Dimension(dm) = &e.kind { + todo.extend(override_arrows(dm)); + } + } + } + seen +} + +/// Upper-case names of the blocks the model space of `src` needs: the ones it refers to, what +/// those need, and the arrowheads of its dimension styles. +fn needed_blocks(src: &Drawing) -> BTreeSet { + let mut roots: Vec = Vec::new(); + for e in src.model.iter() { + roots.extend(referenced_block(e)); + if let EntityKind::Dimension(dm) = &e.kind { + roots.extend(override_arrows(dm)); + } + } + for st in &src.dim_styles { + let arrows = [&st.arrow_block, &st.arrow_block1, &st.arrow_block2, &st.leader_arrow_block]; + roots.extend(arrows.into_iter().map(|n| n.trim().to_string()).filter(|n| !n.is_empty())); + } + reachable(src, roots) +} + +/// Remove the blocks, layers, linetypes and styles that were not in the drawing `before` and that +/// nothing uses (PURGE's scan), in an order where removing one frees the next. `keep` is the +/// block just defined: nothing refers to it yet, so it and the blocks it needs stay. +fn drop_unused_new(d: &mut Drawing, before: &TableNames, keep: &str) { + // Removing a dimension style frees its arrowhead block, which an earlier table already + // scanned: scan again until a pass removes nothing (a chain is never longer than the tables). + for _ in 0..MERGED.len() { + if !drop_unused_pass(d, before, keep) { + break; + } + } +} + +/// One scan of the merged tables; `true` when it removed something. +fn drop_unused_pass(d: &mut Drawing, before: &TableNames, keep: &str) -> bool { + let mut removed = false; + for (kind, old) in &before.0 { + // Nothing was added to this table: nothing to scan for. + if names_of(d, *kind).is_subset(old) { + continue; + } + let keep_blocks = if matches!(kind, Kind::Blocks) { reachable(d, vec![keep.to_string()]) } else { BTreeSet::new() }; + let fresh: BTreeSet = candidates(d, *kind) + .into_iter() + .filter(|n| !old.contains(&n.to_ascii_lowercase()) && !keep_blocks.contains(&n.to_ascii_uppercase())) + .map(|n| n.to_ascii_lowercase()) + .collect(); + let gone = |name: &str| fresh.contains(&name.to_ascii_lowercase()); + removed |= !fresh.is_empty(); + match kind { + Kind::Blocks => d.blocks.retain(|k, _| !gone(k)), + Kind::Dimstyles => d.dim_styles.retain(|t| !gone(&t.name)), + Kind::MleaderStyles => d.mleader_styles.retain(|t| !gone(&t.name)), + Kind::MlineStyles => d.mline_styles.retain(|t| !gone(&t.name)), + Kind::TableStyles => d.table_styles.retain(|t| !gone(&t.name)), + Kind::Layers => d.layers.retain(|t| !gone(&t.name)), + Kind::Linetypes => d.linetypes.retain(|t| !gone(&t.name)), + Kind::TextStyles => d.text_styles.retain(|t| !gone(&t.name)), + _ => {} + } + } + removed +} + /// Add the source's layers, linetypes and styles that this drawing doesn't have (a name that /// exists keeps this drawing's definition). fn merge_tables(d: &mut Drawing, src: &Drawing) { diff --git a/crates/engine/src/cmd/blocks/library.rs b/crates/engine/src/cmd/blocks/library.rs new file mode 100644 index 000000000..31c37b584 --- /dev/null +++ b/crates/engine/src/cmd/blocks/library.rs @@ -0,0 +1,329 @@ +//! Block libraries for the Blocks palette: a folder of drawings or a single drawing file whose +//! blocks can be placed in the current drawing. +//! +//! BLOCKLIBRARY lists what a library holds, BLOCKLIBRARIES keeps the list of libraries the user +//! added (in the settings folder; in memory where there is none), and BLOCKLIBIMPORT defines a +//! library block in the current drawing so that INSERT can place it. Files are read through the +//! host's io hooks like OPEN, so the engine stays I/O-agnostic. + +use std::path::Path; +#[cfg(not(target_arch = "wasm32"))] +use std::path::PathBuf; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex}; +use std::time::SystemTime; + +use cadcraft_doc::Drawing; +use serde_json::{Value, json}; + +use super::insert_file::{define_from, read_drawing, stem}; +use super::valid_block_name; +use crate::cmd::{CommandSpec, bad, has_doc, str_param}; +use crate::{Result, Session}; + +/// Most drawings one folder library lists. +#[cfg(not(target_arch = "wasm32"))] +const MAX_FILES: usize = 2000; +/// Most directory entries looked at in a folder library. +#[cfg(not(target_arch = "wasm32"))] +const MAX_SCANNED: usize = 100_000; +/// Most blocks a palette listing holds: the rest of a hostile file's table is left out. +pub(super) const MAX_LISTED: usize = 10_000; +/// Most libraries the list keeps. +const MAX_LIBRARIES: usize = 64; +/// The longest library path kept. +const MAX_PATH_BYTES: usize = 4096; +/// The file in the settings folder that keeps the library list, and its largest size. +#[cfg(not(target_arch = "wasm32"))] +const LIST_FILE: &str = "block-libraries.json"; +#[cfg(not(target_arch = "wasm32"))] +const MAX_LIST_BYTES: usize = 256 << 10; + +/// How many parsed library drawings stay in memory. +const CACHE_MAX: usize = 4; + +/// A library drawing already read, and the file's size and time then. +struct Cached { + path: String, + stamp: (u64, Option), + drawing: Arc, +} + +static CACHE: Mutex> = Mutex::new(Vec::new()); + +/// The file's size and modification time; `None` where it cannot be told (nothing is kept then). +fn stamp(path: &str) -> Option<(u64, Option)> { + if cfg!(target_arch = "wasm32") { + return None; + } + std::fs::metadata(path).ok().filter(std::fs::Metadata::is_file).map(|m| (m.len(), m.modified().ok())) +} + +/// A library drawing, read once and kept while the file is as it was: placing a block must not +/// parse the whole file again. +fn cached_drawing(path: &str) -> Result> { + let now = stamp(path); + if let Some(now) = now + && let Ok(cache) = CACHE.lock() + && let Some(hit) = cache.iter().find(|c| c.path == path && c.stamp == now) + { + return Ok(hit.drawing.clone()); + } + // The palette reads previews outside a command, so a parser panic stops here too. + let read = std::panic::catch_unwind(|| read_drawing(path)); + let drawing = Arc::new(read.unwrap_or_else(|p| Err(bad("blocklibrary", format!("{path}: {}", crate::guard::message(p.as_ref())))))?); + if let Some(now) = now + && let Ok(mut cache) = CACHE.lock() + { + cache.retain(|c| c.path != path); + cache.push(Cached { path: path.to_string(), stamp: now, drawing: drawing.clone() }); + while cache.len() > CACHE_MAX { + cache.remove(0); + } + } + Ok(drawing) +} + +/// The list where no settings folder keeps it, and the copy read from it. +static MEMORY: Mutex> = Mutex::new(Vec::new()); +/// The last write of the list failed: the copy in memory is newer than the file. +static UNSAVED: AtomicBool = AtomicBool::new(false); + +/// The commands the Blocks palette uses: BLOCKLIBRARY, BLOCKLIBIMPORT and BLOCKLIBRARIES. +pub(super) fn specs() -> Vec { + vec![ + CommandSpec::new("blocklibrary", "Block Library", run_library) + .params("{path: a folder of DWG/DXF files, or one such file} → {kind: \"folder\", path, files: [{name, file}]} | {kind: \"file\", path, blocks: [{name, description}]}") + .noundo(), + CommandSpec::new("blocklibraries", "Block Libraries", run_libraries) + .params("{op?: \"list\" (default)|\"add\"|\"remove\", path? (add, remove)} → {libraries: [path], path? (add: the entry as kept)}") + .noundo(), + CommandSpec::new("blocklibimport", "Import Library Block", run_import) + .params("{path: DWG/DXF file, block?: the block to take from it (default: the whole drawing), name?: the block to define (default: `block`, else the file name)} → {name}") + .enabled(has_doc), + ] +} + +/// A drawing file by its extension. +fn is_drawing(p: &Path) -> bool { + p.extension().and_then(|e| e.to_str()).is_some_and(|e| e.eq_ignore_ascii_case("dwg") || e.eq_ignore_ascii_case("dxf")) +} + +/// The drawings in a folder, by name: `(block name, full path)`, and whether some were left out. +fn folder_files(dir: &Path) -> Result<(Vec<(String, String)>, bool)> { + #[cfg(not(target_arch = "wasm32"))] + { + let rd = std::fs::read_dir(dir).map_err(|e| bad("blocklibrary", format!("{}: {e}", dir.display())))?; + let entries: Vec = rd.filter_map(|e| e.ok()).map(|e| e.path()).take(MAX_SCANNED.saturating_add(1)).collect(); + let mut truncated = entries.len() > MAX_SCANNED; + let mut out: Vec<(String, String)> = entries + .iter() + .take(MAX_SCANNED) + .filter(|p| is_drawing(p) && p.is_file()) + .filter_map(|p| p.to_str().map(|s| (stem(s), s.to_string()))) + .collect(); + out.sort_by_key(|(n, _)| n.to_ascii_lowercase()); + truncated |= out.len() > MAX_FILES; + out.truncate(MAX_FILES); + Ok((out, truncated)) + } + #[cfg(target_arch = "wasm32")] + { + let _ = dir; + Err(bad("blocklibrary", "paths are not available on the web")) + } +} + +/// Whether two library paths name the same place: letter case counts except where the file +/// system ignores it (Windows, and macOS by default). +fn same_path(a: &str, b: &str) -> bool { + if cfg!(any(windows, target_os = "macos")) { a.eq_ignore_ascii_case(b) } else { a == b } +} + +/// Whether `path` is a folder. +fn is_folder(path: &str) -> bool { + !cfg!(target_arch = "wasm32") && Path::new(path).is_dir() +} + +/// The named blocks of a library drawing: no generated or layout blocks, no xrefs. +pub(crate) fn library_blocks(d: &Drawing) -> Vec<&std::sync::Arc> { + let mut v: Vec<_> = + d.blocks.values().filter(|b| !b.anonymous && b.xref_path.is_none() && !b.name.starts_with('*') && !b.name.contains('|')).collect(); + v.sort_by_key(|b| b.name.to_ascii_lowercase()); + v +} + +/// Read a library file (for the palette's previews too), kept until the file changes. +pub fn read_library_file(path: &str) -> Result> { + cached_drawing(path) +} + +/// BLOCKLIBRARY: list a folder's drawings or a drawing's blocks. +fn run_library(_s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path").map(str::trim).filter(|s| !s.is_empty()).ok_or_else(|| bad("blocklibrary", "`path` is required"))?; + if is_folder(path) { + let (files, truncated) = folder_files(Path::new(path))?; + let list: Vec = files.iter().map(|(name, file)| json!({ "name": name, "file": file })).collect(); + return Ok(json!({ "kind": "folder", "path": path, "files": list, "truncated": truncated })); + } + let d = cached_drawing(path)?; + let blocks = library_blocks(&d); + let list: Vec = blocks.iter().take(MAX_LISTED).map(|b| json!({ "name": b.name, "description": b.description })).collect(); + Ok(json!({ "kind": "file", "path": path, "blocks": list, "truncated": blocks.len() > MAX_LISTED })) +} + +/// BLOCKLIBIMPORT: define a library block (or a whole drawing) in the current drawing. +fn run_import(s: &mut Session, p: &Value) -> Result { + let path = str_param(p, "path").map(str::trim).filter(|s| !s.is_empty()).ok_or_else(|| bad("blocklibimport", "`path` is required"))?; + let block = str_param(p, "block").map(str::trim).filter(|s| !s.is_empty()); + // A whole drawing is named after its file; a block of it after itself. + let name = str_param(p, "name") + .map(str::trim) + .filter(|s| !s.is_empty()) + .map(str::to_string) + .unwrap_or_else(|| block.map_or_else(|| stem(path), str::to_string)); + if !valid_block_name(&name) { + return Err(bad("blocklibimport", format!("\"{name}\" is not a valid block name"))); + } + let mut src = (*cached_drawing(path)?).clone(); + if let Some(block) = block { + let b = src.block(block).cloned().ok_or_else(|| bad("blocklibimport", format!("{path} has no block \"{block}\"")))?; + // The block is a drawing of its own: its objects as model space and its base point as + // $INSBASE, with the file's other blocks around it. + src.model = b.entities.clone(); + src.header.set("INSBASE", cadcraft_doc::HVal::Point(b.base)); + } + // Only the layers, linetypes and styles the block needs come along, not the whole file's. + let name = define_from(s, &src, &name, true)?; + Ok(json!({ "name": name })) +} + +/// Where the library list is kept. +#[cfg(not(target_arch = "wasm32"))] +fn list_path() -> Option { + crate::settings_dir::current().map(|d| d.join(LIST_FILE)) +} + +/// A path the list can hold: short enough, with no control characters. +fn acceptable(path: &str) -> bool { + !path.is_empty() && path.len() <= MAX_PATH_BYTES && !path.chars().any(char::is_control) +} + +/// The list in the settings folder. The file is hand-editable, so what it holds is checked here. +/// `Ok(None)`: no settings folder or no file yet. `Err`: a file that is there but unreadable. +#[cfg(not(target_arch = "wasm32"))] +fn read_list() -> std::result::Result>, String> { + let Some(path) = list_path() else { return Ok(None) }; + if !path.exists() { + return Ok(None); + } + let bytes = crate::capped_read::read_capped(&path, MAX_LIST_BYTES).map_err(|e| format!("{}: {e}", path.display()))?; + let list: Vec = serde_json::from_slice(&bytes).map_err(|e| format!("{}: {e}", path.display()))?; + Ok(Some(list.into_iter().filter(|p| acceptable(p)).take(MAX_LIBRARIES).collect())) +} + +/// On the web there is no settings folder: the list lives in memory only. +#[cfg(target_arch = "wasm32")] +fn read_list() -> std::result::Result>, String> { + Ok(None) +} + +/// The list, and why the file could not be read when it exists but is unreadable. Such a file is +/// never written over: `run_libraries` refuses to change the list while it stays unreadable. +fn load_list() -> (Vec, Option) { + let memory = || MEMORY.lock().map(|m| m.clone()).unwrap_or_default(); + if UNSAVED.load(Ordering::Relaxed) { + return (memory(), None); + } + match read_list() { + Ok(Some(list)) => (list, None), + Ok(None) => (memory(), None), + Err(why) => (memory(), Some(why)), + } +} + +/// Write the list to `path`, its folder made if needed. `false` when it could not be written. +#[cfg(not(target_arch = "wasm32"))] +fn write_list(path: &Path, list: &[String]) -> bool { + let Ok(bytes) = serde_json::to_vec_pretty(list) else { return false }; + if let Some(dir) = path.parent() { + let _ = std::fs::create_dir_all(dir); + } + crate::atomic_write::write_atomic(path, &bytes).is_ok() +} + +/// Keep the list in memory and write it to the settings folder. +fn save_list(list: &[String]) { + if let Ok(mut m) = MEMORY.lock() { + *m = list.to_vec(); + } + // A list that cannot be written is still kept for this session. + #[cfg(not(target_arch = "wasm32"))] + if let Some(p) = list_path() { + UNSAVED.store(!write_list(&p, list), Ordering::Relaxed); + } +} + +/// BLOCKLIBRARIES: list, add to or remove from the libraries. +fn run_libraries(_s: &mut Session, p: &Value) -> Result { + let (mut list, unreadable) = load_list(); + let op = str_param(p, "op").unwrap_or("list"); + if let (Some(why), "add" | "remove") = (&unreadable, op) { + return Err(bad("blocklibraries", format!("the library list cannot be read, so it is left as it is ({why})"))); + } + let path = str_param(p, "path").map(str::trim).filter(|s| !s.is_empty()); + match op { + "list" => {} + "add" => { + let path = path.ok_or_else(|| bad("blocklibraries", "`path` is required"))?; + let drawing = is_drawing(Path::new(path)) && Path::new(path).is_file(); + if !acceptable(path) || !(is_folder(path) || drawing) { + return Err(bad("blocklibraries", "a library is a folder or a DWG/DXF file")); + } + let stored = match list.iter().find(|l| same_path(l, path)) { + Some(l) => l.clone(), + None => { + if list.len() >= MAX_LIBRARIES { + return Err(bad("blocklibraries", format!("at most {MAX_LIBRARIES} libraries"))); + } + list.push(path.to_string()); + path.to_string() + } + }; + save_list(&list); + return Ok(json!({ "libraries": list, "path": stored })); + } + "remove" => { + let path = path.ok_or_else(|| bad("blocklibraries", "`path` is required"))?; + list.retain(|l| !same_path(l, path)); + save_list(&list); + } + other => return Err(bad("blocklibraries", format!("unknown op \"{other}\""))), + } + Ok(json!({ "libraries": list })) +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A list that could not be written stays the list of this session, whatever the file says. + #[test] + fn a_failed_write_keeps_the_list_in_memory() { + let dir = std::env::temp_dir().join(format!("cadcraft-library-list-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let blocker = dir.join("a-file"); + std::fs::write(&blocker, b"x").unwrap(); + let list = vec!["C:/kept".to_string()]; + // A folder that is a file: neither the folder nor the list can be made. + assert!(!write_list(&blocker.join("block-libraries.json"), &list)); + assert!(write_list(&dir.join("block-libraries.json"), &list)); + + *MEMORY.lock().unwrap() = list.clone(); + UNSAVED.store(true, Ordering::Relaxed); + assert_eq!(load_list().0, list); + UNSAVED.store(false, Ordering::Relaxed); + MEMORY.lock().unwrap().clear(); + std::fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/crates/engine/src/cmd/file.rs b/crates/engine/src/cmd/file.rs index 1c3fbd5c8..7fe84ca29 100644 --- a/crates/engine/src/cmd/file.rs +++ b/crates/engine/src/cmd/file.rs @@ -24,7 +24,7 @@ pub use template::{qnew_template, set_qnew_template}; /// endless device must be rejected before it exhausts memory (CWE-400), so native opens read /// through [`crate::capped_read`] rather than buffering to EOF. #[cfg(not(target_arch = "wasm32"))] -const MAX_DRAWING_BYTES: usize = 512 << 20; +pub(crate) const MAX_DRAWING_BYTES: usize = 512 << 20; /// Largest `.scr` script accepted from a local path. #[cfg(not(target_arch = "wasm32"))] const MAX_SCRIPT_BYTES: usize = 64 << 20; diff --git a/crates/engine/src/cmd/griphot.rs b/crates/engine/src/cmd/griphot.rs index f2bfb079e..802f65e69 100644 --- a/crates/engine/src/cmd/griphot.rs +++ b/crates/engine/src/cmd/griphot.rs @@ -483,7 +483,7 @@ impl Session { let machine = crate::guard::Guarded::wrap(Box::new(g)); let st = self.state()?; let (before, selection_before) = (st.doc.clone(), st.selection.clone()); - self.running = Some(Running::new("grip", machine, before, selection_before)); + self.running = Some(Running { id: "grip".into(), machine, before, selection_before }); self.pending_window = None; self.point_mods.clear(); self.echo(label); diff --git a/crates/engine/src/guard.rs b/crates/engine/src/guard.rs index 042da4151..799b7046d 100644 --- a/crates/engine/src/guard.rs +++ b/crates/engine/src/guard.rs @@ -196,7 +196,7 @@ pub(crate) mod tests { let machine = Guarded::create("panictest", factory, s)?; let st = s.state()?; let (before, selection_before) = (st.doc.clone(), st.selection.clone()); - s.running = Some(Running::new("panictest", machine, before, selection_before)); + s.running = Some(Running { id: "panictest".into(), machine, before, selection_before }); s.feed(None) } diff --git a/crates/engine/src/running.rs b/crates/engine/src/running.rs index e8bce6f9c..4ff8ce429 100644 --- a/crates/engine/src/running.rs +++ b/crates/engine/src/running.rs @@ -1,5 +1,3 @@ -use std::sync::atomic::{AtomicU64, Ordering}; - use super::{Arc, Drawing, Handle, Interactive, Serialize, Vec2}; /// An interactive command in progress. @@ -8,17 +6,6 @@ pub struct Running { pub machine: Box, pub before: Arc, pub selection_before: Vec, - /// Tells this run apart from any other run of the same command, which has the same `id`. - pub serial: u64, -} - -static NEXT_SERIAL: AtomicU64 = AtomicU64::new(1); - -impl Running { - /// A run of command `id` with a serial number no other run has had. - pub fn new(id: impl Into, machine: Box, before: Arc, selection_before: Vec) -> Self { - Running { id: id.into(), machine, before, selection_before, serial: NEXT_SERIAL.fetch_add(1, Ordering::Relaxed) } - } } /// A pending window/crossing selection started by a click on empty space. diff --git a/crates/engine/src/session/interactive.rs b/crates/engine/src/session/interactive.rs index c807a598b..d90c91683 100644 --- a/crates/engine/src/session/interactive.rs +++ b/crates/engine/src/session/interactive.rs @@ -78,7 +78,7 @@ impl Session { if nested { self.suspended = self.running.take(); } - self.running = Some(Running::new(spec.id, machine, before, selection_before)); + self.running = Some(Running { id: spec.id.to_string(), machine, before, selection_before }); self.pending_window = None; // Some commands complete immediately (e.g. ERASE with a pickfirst selection). self.feed(None)?; diff --git a/crates/engine/tests/blocklibrary.rs b/crates/engine/tests/blocklibrary.rs new file mode 100644 index 000000000..c5b60bfa2 --- /dev/null +++ b/crates/engine/tests/blocklibrary.rs @@ -0,0 +1,237 @@ +//! Block libraries (the Blocks palette): BLOCKLIBRARY lists a folder of drawings or the blocks +//! of one drawing, BLOCKLIBIMPORT defines a library block in the current drawing, and +//! BLOCKLIBRARIES keeps the list of libraries. + +use std::sync::Arc; +use std::sync::atomic::{AtomicUsize, Ordering}; + +use cadcraft_engine::cmd::file::{IoHooks, set_io}; +use cadcraft_engine::doc::geom::Vec3; +use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, Handle, Layer, Line}; +use cadcraft_engine::{Input, Session}; +use serde_json::json; + +/// How many times a library file was parsed. +static READS: AtomicUsize = AtomicUsize::new(0); + +/// Every library file reads as a drawing with blocks "Valve" (a line on layer Pipes, base point +/// (1, 1)) and "Pump" (empty), whatever its bytes. +fn read(_bytes: &[u8], name: &str) -> Result { + READS.fetch_add(1, Ordering::SeqCst); + let mut d = Drawing::new_metric(); + d.layers.push(Layer { name: "Pipes".into(), ..Layer::default() }); + d.layers.push(Layer { name: "Spare".into(), ..Layer::default() }); + let mut valve = Block::new("Valve"); + valve.description = "Gate valve".into(); + valve.base = Vec3::new(1.0, 1.0, 0.0); + let mut line = Entity::new(Handle(0x70), EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(4.0, 0.0, 0.0) })); + line.common.layer = "Pipes".into(); + valve.entities.push(line); + d.blocks.insert("Valve".into(), Arc::new(valve)); + d.blocks.insert("Pump".into(), Arc::new(Block::new("Pump"))); + // "Outer" holds a reference to "Valve" and nothing else. + let mut s = Session::new(); + *s.doc_mut().unwrap() = d; + s.execute("insert", &json!({ "name": "Valve", "at": [2, 2] })).unwrap(); + let handles: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({ "name": "Outer", "base": [0, 0], "handles": handles, "keep": "delete" })).unwrap(); + // A dimension style nothing uses, with an arrowhead block of its own. + if name.contains("arrow") { + let d = s.doc_mut().unwrap(); + d.blocks.insert("TipArrow".into(), Arc::new(Block::new("TipArrow"))); + d.dim_styles.push(cadcraft_engine::doc::DimStyle { name: "Spare".into(), arrow_block: "TipArrow".into(), ..Default::default() }); + } + // A crafted file: "Valve" holds "Outer", which holds "Valve". + if name.contains("cycle") { + let mut back = (**s.doc().unwrap().block("Outer").unwrap().entities.iter().next().unwrap()).clone(); + if let EntityKind::Insert(i) = &mut back.kind { + i.block = "Outer".into(); + } + let d = s.doc_mut().unwrap(); + let mut valve = (**d.block("Valve").unwrap()).clone(); + valve.entities.push(back); + d.blocks.insert("Valve".into(), Arc::new(valve)); + } + Ok(s.doc().unwrap().clone()) +} + +fn folder() -> std::path::PathBuf { + let dir = std::env::temp_dir().join(format!("cadcraft-blocklibrary-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + for f in ["b-pumps.dwg", "A-valves.dxf", "notes.txt"] { + std::fs::write(dir.join(f), b"x").unwrap(); + } + dir +} + +/// Listing a drawing file and importing its blocks. +fn lists_and_imports(s: &mut Session, file: &str) { + // A drawing file lists its blocks. + let r = s.execute("blocklibrary", &json!({ "path": file })).unwrap(); + assert_eq!(r["kind"], "file"); + assert_eq!( + r["blocks"], + json!([{ "name": "Outer", "description": "" }, { "name": "Pump", "description": "" }, { "name": "Valve", "description": "Gate valve" }]) + ); + + // Importing defines the block (and its layer) here, under another name when asked. + let r = s.execute("blocklibimport", &json!({ "path": file, "block": "Valve", "name": "Gate" })).unwrap(); + assert_eq!(r["name"], "Gate"); + let d = s.doc().unwrap(); + let gate = d.block("Gate").unwrap(); + assert_eq!(gate.entities.iter().count(), 1); + assert_eq!(gate.base, Vec3::new(1.0, 1.0, 0.0)); + assert!(d.layers.iter().any(|l| l.name == "Pipes")); + // Only what the block needs comes along: not the file's other layers or blocks. + assert!(!d.layers.iter().any(|l| l.name == "Spare"), "an unused layer of the library stays out"); + assert!(d.block("Pump").is_none(), "an unused block of the library stays out"); + s.execute("insert", &json!({ "name": "Gate", "at": [10, 10] })).unwrap(); + // A block made of another block brings that one too (and its layer), not the unused ones. + s.execute("blocklibimport", &json!({ "path": file, "block": "Outer", "name": "Assembly" })).unwrap(); + let d = s.doc().unwrap(); + assert!(d.block("Assembly").is_some()); + assert!(d.block("Valve").is_some(), "the nested block stays"); + assert!(d.block("Pump").is_none()); + assert!(d.layers.iter().any(|l| l.name == "Pipes")); + // A whole drawing is named after its file and brings its objects (here none: model space is empty). + let r = s.execute("blocklibimport", &json!({ "path": file })).unwrap(); + assert_eq!(r["name"], "A-valves"); + assert!(!s.doc().unwrap().layers.iter().any(|l| l.name == "Spare")); + assert!(s.execute("blocklibimport", &json!({ "path": file, "block": "Nope" })).is_err()); + assert!(s.execute("blocklibimport", &json!({ "path": file, "block": "Valve", "name": "bad/name" })).is_err()); +} + +/// A dimension style nothing uses is left out, and its arrowhead block with it. +fn leaves_out_an_unused_dimension_style(s: &mut Session, dir: &std::path::Path) { + let file = dir.join("arrow-set.dxf").to_string_lossy().to_string(); + std::fs::write(&file, b"x").unwrap(); + s.execute("blocklibimport", &json!({ "path": file, "block": "Valve", "name": "Tap" })).unwrap(); + let d = s.doc().unwrap(); + assert!(d.block("Tap").is_some()); + assert!(!d.dim_styles.iter().any(|t| t.name == "Spare"), "an unused dimension style stays out"); + assert!(d.block("TipArrow").is_none(), "so does its arrowhead block"); +} + +/// Adding and removing libraries. +fn keeps_the_list(s: &mut Session, dir: &std::path::Path, dir_s: &str, file: &str) { + // The list: add (once), refuse what is not a library, remove. + let l = s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).unwrap(); + assert_eq!(l["libraries"], json!([dir_s])); + // The same path again is kept once; letter case only matters on case-sensitive file systems. + let again = s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).unwrap(); + assert_eq!(again["libraries"], json!([dir_s])); + if cfg!(any(windows, target_os = "macos")) { + let upper = s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s.to_uppercase() })).unwrap(); + assert_eq!(upper["libraries"], json!([dir_s]), "the same folder in other letters is the same library"); + assert_eq!(upper["path"], json!(dir_s), "the entry keeps its first spelling"); + } + s.execute("blocklibraries", &json!({ "op": "add", "path": file })).unwrap(); + assert_eq!(s.execute("blocklibraries", &json!({})).unwrap()["libraries"], json!([dir_s, file])); + assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": dir.join("notes.txt").to_string_lossy() })).is_err()); + let l = s.execute("blocklibraries", &json!({ "op": "remove", "path": file })).unwrap(); + assert_eq!(l["libraries"], json!([dir_s])); + s.execute("blocklibraries", &json!({ "op": "remove", "path": dir_s })).unwrap(); +} + +/// Names, paths and files that try to pass for something else. +fn refuses_hostile_input(s: &mut Session, dir: &std::path::Path, dir_s: &str) { + // A block whose name looks like `name=path` is that block: INSERT reads no file for it. + let reads = READS.load(Ordering::SeqCst); + let mut odd = Session::new(); + odd.doc_mut().unwrap().blocks.insert("a=b".into(), Arc::new(Block::new("a=b"))); + odd.start("insert").unwrap(); + odd.input(Input::Text("a=b".into())).unwrap(); + assert!(odd.prompt_text().starts_with("INSERT Specify insertion point"), "{}", odd.prompt_text()); + assert_eq!(READS.load(Ordering::SeqCst), reads, "no file was read"); + odd.input(Input::Cancel).unwrap(); + + // What is not a readable drawing fails with an error. + assert!(s.execute("blocklibimport", &json!({ "path": dir_s })).is_err(), "a folder is not a drawing"); + assert!(s.execute("blocklibrary", &json!({ "path": dir.join("missing.dxf").to_string_lossy() })).is_err()); + + // A library whose blocks hold each other imports without hanging, and the session goes on. + let cycle = dir.join("cycle.dxf").to_string_lossy().to_string(); + std::fs::write(&cycle, b"x").unwrap(); + let _ = s.execute("blocklibimport", &json!({ "path": cycle, "block": "Outer", "name": "Loop" })); + s.execute("line", &json!({ "points": [[0, 0], [1, 1]] })).unwrap(); +} + +/// A file with a huge block table. +fn bounds_a_huge_table() { + // A file with a huge block table lists a bounded part of it, and says so. + let mut many = Session::new(); + let d = many.doc_mut().unwrap(); + for i in 0..10_001 { + let name = format!("B{i}"); + d.blocks.insert(name.clone(), Arc::new(Block::new(&name))); + } + let r = many.execute("blockspalette", &json!({})).unwrap(); + assert_eq!(r["blocks"].as_array().unwrap().len(), 10_000); + assert_eq!(r["truncated"], true); +} + +/// The list file in the settings folder. +fn checks_the_list_file(s: &mut Session, dir: &std::path::Path, dir_s: &str) { + // The list file is checked when it is read: junk, bad entries, too many, too big. + let list = dir.join("block-libraries.json"); + let libraries = |s: &mut Session| s.execute("blocklibraries", &json!({})).unwrap()["libraries"].as_array().unwrap().clone(); + std::fs::write(&list, "not json").unwrap(); + assert!(libraries(s).is_empty()); + // A file that is there but unreadable is never written over: the list stays as the user left it. + assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).is_err()); + assert!(s.execute("blocklibraries", &json!({ "op": "remove", "path": dir_s })).is_err()); + assert_eq!(std::fs::read(&list).unwrap(), b"not json"); + let mut hostile: Vec = (0..100).map(|i| format!("C:/lib{i}")).collect(); + hostile.insert(0, String::new()); + hostile.insert(1, "bad\nname".into()); + hostile.insert(2, "x".repeat(10_000)); + std::fs::write(&list, serde_json::to_vec(&hostile).unwrap()).unwrap(); + let kept = libraries(s); + assert_eq!(kept.len(), 64); + assert_eq!(kept[0], "C:/lib0"); + std::fs::write(&list, vec![b' '; 300 << 10]).unwrap(); + assert!(libraries(s).is_empty()); + // What the list file holds after an addition is the list, whole. + std::fs::remove_file(&list).unwrap(); + s.execute("blocklibraries", &json!({ "op": "add", "path": dir_s })).unwrap(); + assert_eq!(serde_json::from_slice::>(&std::fs::read(&list).unwrap()).unwrap(), vec![dir_s.to_string()]); + // Paths with control characters or of absurd length are refused. + assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": format!("{dir_s}\nx") })).is_err()); + assert!(s.execute("blocklibraries", &json!({ "op": "add", "path": "y".repeat(5000) })).is_err()); +} + +/// One test: the file hooks and the settings folder are global to the process. +#[test] +fn libraries_list_import_and_are_kept() { + set_io(IoHooks { read, write: |_, _| Err("no writer in this test".into()), plot: None }); + // No settings folder: the list lives in memory, and the real one is never written. + cadcraft_engine::settings_dir::set(None); + let dir = folder(); + let dir_s = dir.to_string_lossy().to_string(); + let mut s = Session::new(); + + // A folder lists its drawings by name, case-insensitively sorted; other files are not drawings. + let r = s.execute("blocklibrary", &json!({ "path": dir_s })).unwrap(); + assert_eq!(r["kind"], "folder"); + let names: Vec<&str> = r["files"].as_array().unwrap().iter().map(|f| f["name"].as_str().unwrap()).collect(); + assert_eq!(names, ["A-valves", "b-pumps"]); + + let reads_before = READS.load(Ordering::SeqCst); + let file = dir.join("A-valves.dxf").to_string_lossy().to_string(); + lists_and_imports(&mut s, &file); + // The file was parsed once for all of that, and again only when it changes. + assert_eq!(READS.load(Ordering::SeqCst) - reads_before, 1, "the file is parsed once, not for every block placed"); + std::fs::write(&file, b"changed contents, another size").unwrap(); + s.execute("blocklibrary", &json!({ "path": file })).unwrap(); + assert_eq!(READS.load(Ordering::SeqCst) - reads_before, 2, "a changed file is read again"); + + leaves_out_an_unused_dimension_style(&mut s, &dir); + keeps_the_list(&mut s, &dir, &dir_s, &file); + refuses_hostile_input(&mut s, &dir, &dir_s); + bounds_a_huge_table(); + cadcraft_engine::settings_dir::set(Some(dir.clone())); + checks_the_list_file(&mut s, &dir, &dir_s); + cadcraft_engine::settings_dir::set(None); + + std::fs::remove_dir_all(&dir).unwrap(); +} diff --git a/crates/engine/tests/it/insert_attribute_prompts.rs b/crates/engine/tests/it/insert_attribute_prompts.rs index 38717c3f8..97df80386 100644 --- a/crates/engine/tests/it/insert_attribute_prompts.rs +++ b/crates/engine/tests/it/insert_attribute_prompts.rs @@ -80,20 +80,3 @@ fn a_verify_attribute_is_asked_again_with_the_value_typed() { s.cmdline("(command \"_.-INSERT\" \"K\" '(300.0 0.0) \"\" \"\" 0 \"X\" \"\")").unwrap(); assert_eq!(values(&s), [pair("T1", "X")]); } - -#[test] -fn a_repeated_insert_verifies_every_placement() { - let mut s = with_block(&[("T1", 4, "V1")]); - s.start("insert").unwrap(); - s.cmdline("K").unwrap(); - s.cmdline("Repeat").unwrap(); - for x in [300.0, 400.0] { - s.input(Input::Point(Vec2::new(x, 0.0))).unwrap(); - s.input(Input::Enter).unwrap(); // X scale - s.input(Input::Enter).unwrap(); // Y scale - s.input(Input::Text("0".into())).unwrap(); // rotation - s.cmdline("X").unwrap(); // the attribute value - assert!(s.prompt_text().contains("PT1 "), "{}", s.prompt_text()); - s.cmdline("X").unwrap(); // verified - } -} diff --git a/crates/engine/tests/it/insert_enter.rs b/crates/engine/tests/it/insert_enter.rs new file mode 100644 index 000000000..51b3cef47 --- /dev/null +++ b/crates/engine/tests/it/insert_enter.rs @@ -0,0 +1,20 @@ +//! Enter or Space at INSERT's insertion point prompt ends the command, as in AutoCAD, instead of +//! asking again (the Blocks palette's Repeat Placement stops this way). + +use cadcraft_engine::{Input, Session}; +use serde_json::json; + +#[test] +fn enter_at_the_insertion_point_ends_insert() { + let mut s = Session::new(); + s.execute("line", &json!({"points": [[0, 0], [10, 0]]})).unwrap(); + let hs: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({"name": "A", "base": [0, 0], "handles": hs, "keep": "delete"})).unwrap(); + + s.start("insert").unwrap(); + s.input(Input::Text("A".into())).unwrap(); + assert!(s.prompt_text().starts_with("INSERT Specify insertion point"), "{}", s.prompt_text()); + s.input(Input::Enter).unwrap(); + assert_eq!(s.prompt_text(), "Command:"); + assert_eq!(s.doc().unwrap().model.iter().count(), 0, "nothing is placed"); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 0763ee6eb..793234bda 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -61,6 +61,7 @@ mod helix; mod inquiry_keywords; mod inquiry_z; mod insert_attribute_prompts; +mod insert_enter; mod insert_prompts; mod isometric; mod join_close; diff --git a/crates/geom/src/curve.rs b/crates/geom/src/curve.rs index 2c7ddfb1e..2b799e433 100644 --- a/crates/geom/src/curve.rs +++ b/crates/geom/src/curve.rs @@ -353,14 +353,6 @@ impl Segment { Segment::Arc { arc, .. } => arc.bounds(), } } - /// Point count used by `tessellate`, including both ends, without allocating points. - pub fn tessellation_points(&self, tol: f64) -> usize { - match self { - Segment::Line(_) => 2, - Segment::Arc { arc, .. } => arc_segments(arc.radius, arc.sweep(), tol) + 1, - } - } - /// Points along the segment in its direction, including both ends. pub fn tessellate(&self, tol: f64, out: &mut Vec) { match self { @@ -506,12 +498,6 @@ impl Polyline { } b } - /// Conservative point count for `tessellate`, before allocating sampled vertices. - /// Shared segment endpoints are counted twice. Input must be bounded before this walk. - pub fn tessellation_points(&self, tol: f64) -> Option { - self.segments().iter().try_fold(usize::from(!self.vertices.is_empty()), |n, s| n.checked_add(s.tessellation_points(tol))) - } - pub fn tessellate(&self, tol: f64) -> Vec { let mut out: Vec = Vec::new(); for s in self.segments() { diff --git a/crates/geom/src/spline.rs b/crates/geom/src/spline.rs index 84cb21f13..d954e66b1 100644 --- a/crates/geom/src/spline.rs +++ b/crates/geom/src/spline.rs @@ -122,10 +122,7 @@ impl Spline { /// How many segments a tessellation at `tol` takes: the control-polygon length guides it, /// capped at `MAX_SAMPLES`. - pub fn sample_count(&self, tol: f64) -> usize { - if !self.is_valid() { - return self.control.len().saturating_sub(1); - } + fn sample_count(&self, tol: f64) -> usize { self.segments_for(self.polygon_length() / tol.max(1e-9)) } @@ -163,15 +160,43 @@ impl Spline { /// box, which contains the curve (the box of the finite control points when one is not /// finite: `hull` skips it, but it would poison every sample). pub fn bounds(&self) -> Bounds2 { - let (budget, floor) = match self.bounds_sampling() { - BoundsSampling::Hull => return Bounds2::from_points(self.control.iter().copied()), - BoundsSampling::Grid => return Bounds2::from_points(self.samples(MAX_SAMPLES)), - BoundsSampling::Spans { budget, floor } => (budget, floor), - }; + let hull = Bounds2::from_points(self.control.iter().copied()); + let diag = hull.min.dist(hull.max); + let finite = self.control.iter().all(|c| c.is_finite()) && self.weights.iter().all(|w| w.is_finite()); + // The convex hull property, which makes the control box contain the curve and a + // degree-1 spline its control polygon, needs every weight positive. + let positive = self.weights.iter().all(|w| *w > 0.0); + if !self.is_valid() || !finite { + return hull; + } + // With a zero or negative weight even a degenerate control box is no bound (zero weights + // evaluate to the origin), so only positive weights take these shortcuts. + if positive && (self.degree == 1 || !(diag.is_finite() && diag > 0.0)) { + return hull; + } + let spans = self.knot_spans().count(); + if spans == 0 { + return hull; + } + if spans > MAX_SAMPLES / 2 { + // Too many spans for two samples each: the control box contains the curve when no + // weight is negative (the convex hull property), so it is the safe answer; a grid could + // step over a narrow span. Negative weights void that property, so they keep the grid. + if positive { + return hull; + } + return Bounds2::from_points(self.samples(MAX_SAMPLES)); + } let (lo, hi) = self.domain(); + let floor = 8.min(MAX_SAMPLES / spans); + // The span's share of the domain first: huge knots (1e308, from a hostile edit) would + // overflow `budget * (b - a)` to infinity and the cast to a boundless count. + let segments = |budget: usize, (a, b): (f64, f64)| floor.max((budget as f64 * ((b - a) / (hi - lo))) as usize).min(MAX_SAMPLES); + let n = self.segments_for(self.polygon_length() / (diag * 1e-3)); + let budget = if self.knot_spans().map(|s| segments(n, s)).sum::() <= MAX_SAMPLES { n } else { MAX_SAMPLES - floor * spans }; let mut out = Bounds2::EMPTY; for (a, b) in self.knot_spans() { - let seg = self.span_segments(budget, floor, a, b); + let seg = segments(budget, (a, b)); for i in 0..seg { out.add(self.eval_valid(a + (b - a) * i as f64 / seg as f64, lo, hi)); } @@ -180,48 +205,6 @@ impl Spline { out } - /// Evaluations performed by `bounds`, without evaluating the curve. Callers must first - /// bound the input arrays: planning walks the controls and knots too. - pub fn bounds_sample_count(&self) -> usize { - match self.bounds_sampling() { - BoundsSampling::Hull => 0, - BoundsSampling::Grid => MAX_SAMPLES + 1, - BoundsSampling::Spans { budget, floor } => self.knot_spans().map(|(a, b)| self.span_segments(budget, floor, a, b)).sum::() + 1, - } - } - - /// Segments for the parameter span `a..b`: a share of `budget` proportional to its width, never below `floor` nor above `MAX_SAMPLES`. - fn span_segments(&self, budget: usize, floor: usize, a: f64, b: f64) -> usize { - let (lo, hi) = self.domain(); - floor.max((budget as f64 * ((b - a) / (hi - lo))) as usize).min(MAX_SAMPLES) - } - - /// The sampling plan used to bound the curve, matching the one the renderer draws. - fn bounds_sampling(&self) -> BoundsSampling { - let hull = Bounds2::from_points(self.control.iter().copied()); - let diag = hull.min.dist(hull.max); - let finite = self.control.iter().all(|c| c.is_finite()) && self.weights.iter().all(|w| w.is_finite()); - let positive = self.weights.iter().all(|w| *w > 0.0); - if !self.is_valid() || !finite || (positive && (self.degree == 1 || !(diag.is_finite() && diag > 0.0))) { - return BoundsSampling::Hull; - } - let spans = self.knot_spans().count(); - if spans == 0 { - return BoundsSampling::Hull; - } - if spans > MAX_SAMPLES / 2 { - return if positive { BoundsSampling::Hull } else { BoundsSampling::Grid }; - } - let floor = 8.min(MAX_SAMPLES / spans); - let n = self.segments_for(self.polygon_length() / (diag * 1e-3)); - let budget = if self.knot_spans().map(|(a, b)| self.span_segments(n, floor, a, b)).sum::() <= MAX_SAMPLES { - n - } else { - MAX_SAMPLES - floor * spans - }; - BoundsSampling::Spans { budget, floor } - } - /// The non-empty knot spans the curve is defined over, in parameter order. fn knot_spans(&self) -> impl Iterator + '_ { let knots = self.knots.get(self.degree..=self.control.len()).unwrap_or(&[]); @@ -233,12 +216,6 @@ impl Spline { /// control points took minutes). const MAX_SAMPLES: usize = 4000; -enum BoundsSampling { - Hull, - Grid, - Spans { budget: usize, floor: usize }, -} - pub(crate) fn clamped_uniform_knots(n: usize, degree: usize) -> Vec { let mut k = vec![0.0; degree + 1]; let inner = n.saturating_sub(degree + 1); diff --git a/crates/geom/src/spline/tests.rs b/crates/geom/src/spline/tests.rs index 36ab25800..d953cfabd 100644 --- a/crates/geom/src/spline/tests.rs +++ b/crates/geom/src/spline/tests.rs @@ -303,17 +303,3 @@ fn a_normal_low_degree_spline_is_valid() { assert!(s.is_valid()); assert!(s.tessellate(1e-3).len() > 4); } -#[test] -fn sampling_plans_match_tessellation_and_bound_hostile_degrees() { - use super::*; - for degree in [1, 2, 3, 8, 32] { - let s = Spline::from_control((0..=degree).map(|i| Vec2::new(i as f64, (i % 2) as f64)).collect(), degree); - for tol in [0.001, 0.1, 10.0] { - assert_eq!(s.sample_count(tol) + 1, s.tessellate(tol).len()); - } - assert!(s.bounds_sample_count() <= MAX_SAMPLES + 1); - } - let s = Spline { degree: usize::MAX, ..Default::default() }; - assert_eq!(s.sample_count(0.1), 0); - assert_eq!(s.bounds_sample_count(), 0); -} diff --git a/crates/io/src/pdf.rs b/crates/io/src/pdf.rs index 22870c47b..3f35233a8 100644 --- a/crates/io/src/pdf.rs +++ b/crates/io/src/pdf.rs @@ -521,7 +521,6 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String min_dash: 0.0, text: true, fill: true, - hatch_budget: None, lineweights, view_height: 0.0, plot_style_table, diff --git a/crates/render/src/draw.rs b/crates/render/src/draw.rs index ea76e71ca..7e00b4c8c 100644 --- a/crates/render/src/draw.rs +++ b/crates/render/src/draw.rs @@ -18,7 +18,7 @@ fn entity_layer(ctx: &Ctx, e: &Entity) -> u32 { pub(crate) fn entity(b: &mut Builder, ctx: &Ctx, e: &Entity) { // Hidden by ISOLATEOBJECTS / HIDEOBJECTS (and so in viewports and plots too). A cancelled // build stops here (block contents come through here too). - if b.output_failed || ctx.d.is_hidden_object(e.handle) || b.opts.cancelled() { + if ctx.d.is_hidden_object(e.handle) || b.opts.cancelled() { return; } // The entity's named plot style and transparency (set by `entity_parts`), for everything it @@ -256,9 +256,8 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) { Prim::Point(p) => b.point(ctx, rgb, p), Prim::Infinite { base, dir, ray } => b.infinite(ctx, rgb, base, dir, ray), Prim::Fill(pts) => { - if let Some(tris) = fill::triangulate_evenodd_limited(&[pts], b.opts.hatch_budget.as_deref()) { - b.tris(ctx, rgb, &tris); - } + let tris = fill::triangulate_evenodd(&[pts]); + b.tris(ctx, rgb, &tris); } } } @@ -295,9 +294,7 @@ fn draw_wipeout(b: &mut Builder, ctx: &Ctx, w: &cadcraft_doc::Wipeout, rgb: Ink, // 0 = none, 1 = shown and plotted, 2 = shown but not plotted. if b.opts.fill { let n = b.list.prims.len(); - if let Some(tris) = fill::triangulate_evenodd_limited(std::slice::from_ref(&w.boundary), b.opts.hatch_budget.as_deref()) { - b.tris(ctx, rgb, &tris); - } + b.tris(ctx, rgb, &fill::triangulate_evenodd(std::slice::from_ref(&w.boundary))); if let Some(p) = b.list.prims.get_mut(n) { p.kind = Kind::Mask; } diff --git a/crates/render/src/fill.rs b/crates/render/src/fill.rs index 4dc2aaa8c..ef6f3dff2 100644 --- a/crates/render/src/fill.rs +++ b/crates/render/src/fill.rs @@ -9,21 +9,9 @@ use cadcraft_geom::{Polyline, Vec2}; /// crossing and each part is paired on its own. Robust for any input; output size is /// O(slabs × crossings), capped for hostile inputs. pub fn triangulate_evenodd(loops: &[Vec]) -> Vec { - triangulate_evenodd_limited(loops, None).unwrap_or_default() -} - -/// Budgeted triangulation discards incomplete fills instead of displaying partial geometry. -pub(crate) fn triangulate_evenodd_limited(loops: &[Vec], budget: Option<&crate::hatch::HatchBudget>) -> Option> { - use crate::hatch::charge; - if !charge(budget, loops.len()) { - return None; - } let mut edges: Vec<(Vec2, Vec2)> = Vec::new(); for l in loops { let n = l.len(); - if !charge(budget, n.saturating_mul(16)) { - return None; - } if n < 3 { continue; } @@ -35,7 +23,7 @@ pub(crate) fn triangulate_evenodd_limited(loops: &[Vec], budget: Option<&c } } if edges.is_empty() || edges.len() > 200_000 { - return Some(Vec::new()); + return Vec::new(); } let mut ys: Vec = edges.iter().flat_map(|(a, b)| [a.y, b.y]).collect(); ys.sort_by(f64::total_cmp); @@ -63,9 +51,6 @@ pub(crate) fn triangulate_evenodd_limited(loops: &[Vec], budget: Option<&c pending.clear(); pending.push((y0, y1)); while let Some((ya, yb)) = pending.pop() { - if !charge(budget, active.len().saturating_mul(16).saturating_add(1)) { - return None; - } let ymid = (ya + yb) / 2.0; let mut xs: Vec<(f64, f64, f64)> = active.iter().map(|e| (x_at(e, ymid), x_at(e, ya), x_at(e, yb))).collect(); xs.sort_by(|a, b| a.0.total_cmp(&b.0)); @@ -99,11 +84,11 @@ pub(crate) fn triangulate_evenodd_limited(loops: &[Vec], budget: Option<&c } } if out.len() > 6_000_000 { - return Some(out); + return out; } } } - Some(out) + out } /// How many extra slab boundaries crossings may add over one region. diff --git a/crates/render/src/hatch.rs b/crates/render/src/hatch.rs index 61e81e6ba..1bfeb1b6c 100644 --- a/crates/render/src/hatch.rs +++ b/crates/render/src/hatch.rs @@ -13,86 +13,16 @@ use cadcraft_color::{Color, Rgb}; use cadcraft_doc::library::{PatternLine, pattern_for}; use cadcraft_doc::{Drawing, Entity, Gradient, Hatch}; use cadcraft_geom::{Bounds2, Polyline, Vec2, point_in_polygon}; -use std::sync::atomic::{AtomicBool, AtomicUsize, Ordering}; - -/// Shared hatch work allowance for one thumbnail. Cloned render options share this allowance. -#[derive(Debug)] -pub struct HatchBudget { - remaining: AtomicUsize, - failed: AtomicBool, -} - -impl HatchBudget { - /// A budget allowing `work` units of hatch computation. - pub fn new(work: usize) -> Self { - Self { remaining: AtomicUsize::new(work), failed: AtomicBool::new(false) } - } - - /// Work units still available. - pub fn remaining(&self) -> usize { - self.remaining.load(Ordering::Relaxed) - } - - /// Whether a reservation was refused. Spending the budget exactly is not a failure. - pub fn failed(&self) -> bool { - self.failed.load(Ordering::Relaxed) - } -} - -/// Reserve work before allocation/iteration. Failed reservations exhaust the shared budget. -pub(crate) fn charge(budget: Option<&HatchBudget>, amount: usize) -> bool { - let Some(budget) = budget else { return true }; - let mut current = budget.remaining.load(Ordering::Relaxed); - loop { - let Some(next) = current.checked_sub(amount) else { - budget.failed.store(true, Ordering::Relaxed); - budget.remaining.store(0, Ordering::Relaxed); - return false; - }; - match budget.remaining.compare_exchange_weak(current, next, Ordering::Relaxed, Ordering::Relaxed) { - Ok(_) => return true, - Err(actual) => current = actual, - } - } -} - -/// Emergency contours remain bounded even when the caller supplies untrusted geometry directly. -fn contours(b: &mut Builder, ctx: &Ctx, h: &Hatch, rgb: Ink, lw: f32, tol: f64) { - let mut left = 65_536usize; - if h.loops.len() > 8192 { - return; - } - for boundary in &h.loops { - if boundary.vertices.len() > 8192 || b.opts.cancelled() { - return; - } - let poly = Polyline { vertices: boundary.vertices.clone(), closed: true }; - let cost = poly.tessellation_points(tol); - let Some(next) = cost.and_then(|cost| left.checked_sub(cost)) else { return }; - left = next; - let points = poly.tessellate(tol); - b.polyline(ctx, rgb, lw, &points); - } -} +use std::sync::atomic::{AtomicBool, Ordering}; +/// Draw a hatch entity: `rgb` is its resolved colour, `tol` the chord tolerance. /// Whether a build's cancel flag has been set. fn is_set(cancel: Option<&AtomicBool>) -> bool { cancel.is_some_and(|c| c.load(Ordering::Relaxed)) } -/// Draw a hatch entity: `rgb` is its resolved colour, `tol` the chord tolerance. pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, h: &Hatch, rgb: Ink, lw: f32, tol: f64) { - let allowance = b.opts.hatch_budget.clone(); - let budget = allowance.as_deref(); - let Some(loops) = fill_loops_limited(h, tol, budget) else { - contours(b, ctx, h, rgb, lw, tol); - return; - }; - // Pattern definitions are drawing-controlled: charge before `lines_of` clones their dashes. - if !charge(budget, h.pattern_lines.len()) || h.pattern_lines.iter().any(|f| !charge(budget, f.dashes.len().saturating_mul(8))) { - contours(b, ctx, h, rgb, lw, tol); - return; - } + let loops = fill_loops(h, tol); // Gradient and background colours given ByLayer follow the hatch's own layer. let layer = if e.common.layer == "0" { ctx.block_layer.as_deref().unwrap_or("0") } else { e.common.layer.as_str() }; let layer_color = ctx.layer_color(layer).unwrap_or(Color::Index(7)); @@ -103,12 +33,9 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, h: &Hatch, rgb: Ink, let dense = b.opts.fill && reads_solid(ctx.d, h, px); if h.solid || h.pattern.eq_ignore_ascii_case("SOLID") || h.gradient.is_some() || dense { if b.opts.fill { - let Some(tris) = fill::triangulate_evenodd_limited(&loops, budget) else { - contours(b, ctx, h, rgb, lw, tol); - return; - }; + let tris = fill::triangulate_evenodd(&loops); match &h.gradient { - Some(g) => gradient(b, ctx, g, layer_color, &tris, budget), + Some(g) => gradient(b, ctx, g, layer_color, &tris), None => b.tris(ctx, rgb, &tris), } } @@ -117,23 +44,14 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, h: &Hatch, rgb: Ink, if let Some(bg) = h.background && b.opts.fill { - let Some(tris) = fill::triangulate_evenodd_limited(&loops, budget) else { - contours(b, ctx, h, rgb, lw, tol); - return; - }; - b.tris(ctx, ink(bg, layer_color, ctx.block_color), &tris); + b.tris(ctx, ink(bg, layer_color, ctx.block_color), &fill::triangulate_evenodd(&loops)); } // The area being looked at, in the hatch's units. let view = b.opts.view.and_then(|v| { let inv = ctx.xf.inverse()?; Some(Bounds2::from_points(v.corners().iter().map(|p| inv.apply(*p)))) }); - let lines = pattern_lines_limited(ctx.d, h, &loops, px, view.as_ref(), b.opts.cancel.as_deref(), budget); - if budget.is_some_and(|b| b.failed()) { - contours(b, ctx, h, rgb, lw, tol); - return; - } - for seg in lines { + for seg in pattern_lines_until(ctx.d, h, &loops, px, view.as_ref(), b.opts.cancel.as_deref()) { if seg.len() == 1 { if let Some(p) = seg.first() { b.point(ctx, rgb, *p); @@ -149,41 +67,27 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, h: &Hatch, rgb: Ink, const MAX_ISLAND_WORK: usize = 20_000_000; /// True when two polygons have the same vertices (ignoring cyclic shift and winding order). -fn same_polygon(a: &[Vec2], b: &[Vec2], budget: Option<&HatchBudget>) -> Option { +fn same_polygon(a: &[Vec2], b: &[Vec2]) -> bool { if a.len() != b.len() { - return Some(false); + return false; } let n = a.len(); if n == 0 { - return Some(true); + return true; } - for k in 0..n { - for reverse in [false, true] { - let Some((left, right)) = b.get(..k).zip(b.get(k..)) else { return Some(false) }; - let forward = right.iter().chain(left.iter()); - let backward = b.get(..=k)?.iter().rev().chain(b.get(k + 1..)?.iter().rev()); - let mut matches = true; - let iter: &mut dyn Iterator = if reverse { &mut backward.clone() } else { &mut forward.clone() }; - for (p, q) in a.iter().zip(iter) { - if !charge(budget, 1) { - return None; - } - if !p.near(*q, 1e-4) { - matches = false; - break; - } - } - if matches { - return Some(true); - } - } - } - Some(false) + let near = |p1: Vec2, p2: Vec2| p1.near(p2, 1e-4); + (0..n).any(|k| (0..n).all(|i| near(a[i], b[(i + k) % n]))) || (0..n).any(|k| (0..n).all(|i| near(a[i], b[(k + n - (i % n)) % n]))) } -/// Remove degenerate and duplicate loops, limiting both pair checks and vertex comparisons. -fn dedup_polygons(loops: &mut Vec>, budget: Option<&HatchBudget>) -> Option<()> { - let mut remaining = MAX_DEDUP_COMPARISONS; +/// Remove degenerate and duplicate boundary loops within a shared comparison budget. +/// Retain remaining loops without further comparisons once the budget is exhausted. +fn dedup_polygons(loops: &mut Vec>) { + // `same_polygon` is O(n²) in a polygon's vertex count (every cyclic alignment, both windings), + // and each loop is compared against every unique one kept so far, so adversarial boundary + // geometry could force quadratic-on-quadratic work. Charge every vertex comparison against a + // shared budget; once it is spent, stop deduplicating and keep the remaining loops as-is + // (CWE-407). + let mut budget: u64 = MAX_DEDUP_COMPARISONS; let mut unique: Vec> = Vec::with_capacity(loops.len()); for l in loops.drain(..) { if l.len() < 3 { @@ -191,21 +95,20 @@ fn dedup_polygons(loops: &mut Vec>, budget: Option<&HatchBudget>) -> O } let mut dup = false; for u in &unique { - if !charge(budget, 1) { - return None; - } if u.len() != l.len() { continue; } + // Each `same_polygon` call costs about 2·len² comparisons; stop if that would overrun. let cost = 2u64.saturating_mul((u.len() as u64).saturating_mul(l.len() as u64)); - match remaining.checked_sub(cost) { - Some(left) => remaining = left, + match budget.checked_sub(cost) { + Some(left) => budget = left, None => { - remaining = 0; + // Out of budget: keep `l` without further comparison. + budget = 0; break; } } - if same_polygon(u, &l, budget)? { + if same_polygon(u, &l) { dup = true; break; } @@ -215,7 +118,6 @@ fn dedup_polygons(loops: &mut Vec>, budget: Option<&HatchBudget>) -> O } } *loops = unique; - Some(()) } /// Vertex comparisons `dedup_polygons` may perform before it stops deduplicating. @@ -226,45 +128,22 @@ const MAX_DEDUP_COMPARISONS: u64 = 50_000_000; /// within islands alternate), 1 outer keeps the outermost loops and their first islands, 2 /// ignore keeps only the outermost loops. Nesting depth = how many other loops enclose a loop. pub fn fill_loops(h: &Hatch, tol: f64) -> Vec> { - fill_loops_limited(h, tol, None).unwrap_or_default() -} - -/// Fill loops for `h`, or `None` when `budget` runs out first. -fn fill_loops_limited(h: &Hatch, tol: f64, budget: Option<&HatchBudget>) -> Option>> { - if !charge(budget, h.loops.len()) { - return None; - } - if budget.is_some() { - for boundary in &h.loops { - if !charge(budget, boundary.vertices.len()) { - return None; - } - let poly = Polyline { vertices: boundary.vertices.clone(), closed: true }; - if !poly.tessellation_points(tol).is_some_and(|n| charge(budget, n)) { - return None; - } - } - } let mut loops: Vec> = h.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }.tessellate(tol)).collect(); - dedup_polygons(&mut loops, budget)?; + dedup_polygons(&mut loops); let max_depth = match h.style { 1 => 1, 2 => 0, - _ => return Some(loops), + _ => return loops, }; let verts: usize = loops.iter().map(Vec::len).sum(); - let island_work = loops.len().saturating_mul(verts); - if island_work > MAX_ISLAND_WORK { - return Some(loops); - } - if !charge(budget, island_work) { - return None; + if loops.len().saturating_mul(verts) > MAX_ISLAND_WORK { + return loops; } let depth = |i: usize, l: &[Vec2]| { let Some(p) = probe(l) else { return 0 }; loops.iter().enumerate().filter(|(j, o)| *j != i && point_in_polygon(o, p)).count() }; - Some(loops.iter().enumerate().filter(|(i, l)| depth(*i, l) <= max_depth).map(|(_, l)| l.clone()).collect()) + loops.iter().enumerate().filter(|(i, l)| depth(*i, l) <= max_depth).map(|(_, l)| l.clone()).collect() } /// A point of a loop to test its nesting with: the middle of its first non-degenerate edge @@ -287,22 +166,16 @@ const MAX_GRADIENT_TRIS: usize = 200_000; /// A two-colour gradient over the fill triangles `tris`: a base fill in the middle colour (it /// hides seams between steps), then the triangles split into small pieces, each drawn in the /// colour step of the gradient value at its centroid. -fn gradient(b: &mut Builder, ctx: &Ctx, g: &Gradient, layer: Color, tris: &[Vec2], budget: Option<&HatchBudget>) { +fn gradient(b: &mut Builder, ctx: &Ctx, g: &Gradient, layer: Color, tris: &[Vec2]) { let c1 = ink(g.color1, layer, ctx.block_color); let c2 = ink(g.color2, layer, ctx.block_color); b.tris(ctx, mix(c1, c2, 0.5), tris); let Some(field) = Field::new(g, tris) else { return }; let mut steps: Vec> = vec![Vec::new(); GRADIENT_LEVELS]; let max2 = field.cell * field.cell; - if !charge(budget, tris.len()) { - return; - } let mut stack: Vec<[Vec2; 3]> = tris.as_chunks::<3>().0.to_vec(); let mut drawn = 0usize; while let Some([a, bb, c]) = stack.pop() { - if !charge(budget, 12) { - break; - } // Split the longest edge while the budget allows. let edges = [(a, bb, c), (bb, c, a), (c, a, bb)]; let (p, q, r) = edges.into_iter().max_by(|x, y| (x.0 - x.1).len2().total_cmp(&(y.0 - y.1).len2())).unwrap_or((a, bb, c)); @@ -507,19 +380,6 @@ pub(crate) fn pattern_lines_until( px: f64, view: Option<&Bounds2>, cancel: Option<&AtomicBool>, -) -> Vec> { - pattern_lines_limited(d, h, loops, px, view, cancel, None) -} - -/// Pattern lines for `h` clipped to `loops`, or `None` when the work budget runs out or `cancel` fires. -fn pattern_lines_limited( - d: &Drawing, - h: &Hatch, - loops: &[Vec], - px: f64, - view: Option<&Bounds2>, - cancel: Option<&AtomicBool>, - budget: Option<&HatchBudget>, ) -> Vec> { let lines = lines_of(d, h); let scale = scale_of(h); @@ -530,9 +390,6 @@ fn pattern_lines_limited( // their cost (CWE-400). let mut work: u64 = MAX_HATCH_WORK; for fam in &lines { - if !charge(budget, fam.dashes.len().saturating_add(1)) { - break; - } // A family with dashes but no positive (ink) element can never draw: skip it so its gaps // are not swept at all. if !fam.dashes.is_empty() && !fam.dashes.iter().any(|d| *d >= 0.0) { @@ -546,8 +403,7 @@ fn pattern_lines_limited( continue; } let dashes: Vec = fam.dashes.iter().map(|d| d * scale).collect(); - let mut sink = Sink { out: &mut out, work: &mut work, budget }; - Family { origin, ang, delta, spacing, dashes: &dashes }.sweep(loops, px, view, cancel, &mut sink); + Family { origin, ang, delta, spacing, dashes: &dashes }.sweep(loops, px, view, cancel, &mut out, &mut work); if out.len() >= MAX_RUNS || work == 0 || is_set(cancel) { break; } @@ -600,14 +456,6 @@ struct Family<'a> { dashes: &'a [f64], } -/// Where a family sweep writes its runs, and the limits it spends while doing so: the per-build -/// dash-work count and the optional shared thumbnail budget. -struct Sink<'s> { - out: &'s mut Vec>, - work: &'s mut u64, - budget: Option<&'s HatchBudget>, -} - impl Family<'_> { /// Into the frame where the family's lines are horizontal. fn to_local(&self, p: Vec2) -> Vec2 { @@ -638,12 +486,7 @@ impl Family<'_> { } /// Intersect a pattern family with boundary loops, respecting view, output, cancellation, and shared dash-work limits. - fn sweep(&self, loops: &[Vec], px: f64, view: Option<&Bounds2>, cancel: Option<&AtomicBool>, sink: &mut Sink<'_>) { - let budget = sink.budget; - let points = loops.iter().fold(0usize, |n, l| n.saturating_add(l.len())); - if !charge(budget, points.saturating_add(loops.len())) { - return; - } + fn sweep(&self, loops: &[Vec], px: f64, view: Option<&Bounds2>, cancel: Option<&AtomicBool>, out: &mut Vec>, work: &mut u64) { let local: Vec> = loops.iter().map(|l| l.iter().map(|p| self.to_local(*p)).collect()).collect(); let bb = Bounds2::from_points(local.iter().flatten().copied()); if bb.is_empty() { @@ -663,10 +506,7 @@ impl Family<'_> { let draws = self.dashes.iter().any(|d| *d >= 0.0); let solid_line = self.dashes.is_empty() || pat_len < 1e-12 || (px > 0.0 && pat_len < 2.0 * px && draws); for k in k0..=k1 { - if !charge(budget, points.saturating_mul(16).saturating_add(1)) { - return; - } - if sink.out.len() >= MAX_RUNS || *sink.work == 0 || is_set(cancel) { + if out.len() >= MAX_RUNS || *work == 0 || is_set(cancel) { return; } let y = k as f64 * self.spacing; @@ -682,27 +522,24 @@ impl Family<'_> { continue; } if solid_line { - sink.out.push(vec![self.to_world(Vec2::new(x0, y)), self.to_world(Vec2::new(x1, y))]); + out.push(vec![self.to_world(Vec2::new(x0, y)), self.to_world(Vec2::new(x1, y))]); } else { - self.dash((x0, x1), y, offset, pat_len, sink); + self.dash((x0, x1), y, offset, pat_len, out, work); } } } } /// The dashes and dots of the span `x0..x1` of the line at `y`, phase anchored at x = `offset`. - fn dash(&self, (x0, x1): (f64, f64), y: f64, offset: f64, pat_len: f64, sink: &mut Sink<'_>) { + fn dash(&self, (x0, x1): (f64, f64), y: f64, offset: f64, pat_len: f64, out: &mut Vec>, work: &mut u64) { let start_rep = ((x0 - offset) / pat_len).floor(); let mut x = offset + start_rep * pat_len; let mut guard = 0; 'outer: while x < x1 { for d in self.dashes { - if !charge(sink.budget, 4) { - return; - } guard += 1; - *sink.work = sink.work.saturating_sub(1); - if guard > 100_000 || sink.out.len() >= MAX_RUNS || *sink.work == 0 { + *work = work.saturating_sub(1); + if guard > 100_000 || out.len() >= MAX_RUNS || *work == 0 { break 'outer; } let len = d.abs(); @@ -710,10 +547,10 @@ impl Family<'_> { let a = x.max(x0); let b = (x + len).min(x1); if b > a { - sink.out.push(vec![self.to_world(Vec2::new(a, y)), self.to_world(Vec2::new(b, y))]); + out.push(vec![self.to_world(Vec2::new(a, y)), self.to_world(Vec2::new(b, y))]); } } else if *d == 0.0 && x >= x0 && x <= x1 { - sink.out.push(vec![self.to_world(Vec2::new(x, y))]); + out.push(vec![self.to_world(Vec2::new(x, y))]); } x += len; if x >= x1 { @@ -746,60 +583,6 @@ mod tests { use cadcraft_doc::{Hatch, HatchLoop}; use cadcraft_geom::PolyVertex; - #[test] - fn thumbnail_budget_preserves_a_multi_island_fill() { - let polygon = |cx: f64, cy: f64, radius: f64| HatchLoop { - vertices: (0..24) - .map(|i| { - let angle = f64::from(i) * std::f64::consts::TAU / 24.0; - PolyVertex::new(Vec2::new(cx + radius * angle.cos(), cy + radius * angle.sin())) - }) - .collect(), - outer: false, - sources: vec![], - }; - let mut boundaries = vec![polygon(0.0, 0.0, 100.0)]; - boundaries.extend((0..20).map(|i| polygon(f64::from(i % 5) * 12.0 - 24.0, f64::from(i / 5) * 12.0 - 18.0, 3.0))); - let hatch = Hatch { - origin: Vec2::ZERO, - pattern: "SOLID".into(), - solid: true, - loops: boundaries, - scale: 1.0, - angle: 0.0, - associative: false, - style: 0, - elevation: 0.0, - gradient: None, - background: None, - pattern_lines: vec![], - }; - let budget = HatchBudget::new(250_000); - let loops = fill_loops_limited(&hatch, 0.01, Some(&budget)).expect("ordinary islands fit the thumbnail budget"); - assert_eq!(loops.len(), 21); - let tris = fill::triangulate_evenodd_limited(&loops, Some(&budget)).expect("fill fits the thumbnail budget"); - assert!(!tris.is_empty()); - assert!(budget.remaining() > 0); - } - - #[test] - fn spending_the_budget_exactly_is_not_a_failure() { - let budget = HatchBudget::new(10); - assert!(charge(Some(&budget), 10)); - assert_eq!(budget.remaining(), 0); - assert!(!budget.failed()); - assert!(!charge(Some(&budget), 1)); - assert!(budget.failed()); - } - - #[test] - fn dedup_stops_when_the_shared_budget_is_exhausted() { - let mut loops = vec![vec![Vec2::ZERO; 100], vec![Vec2::new(1.0, 1.0); 100]]; - let budget = HatchBudget::new(10); - assert!(dedup_polygons(&mut loops, Some(&budget)).is_none()); - assert_eq!(budget.remaining(), 0); - } - #[test] fn fill_loops_deduplicates_coincident_loops() { let loop1 = HatchLoop { @@ -846,7 +629,7 @@ mod dedup_budget_tests { let b = vec![Vec2::ZERO; 5_001]; let tri = vec![Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(0.0, 1.0)]; let mut loops = vec![a, b, tri.clone(), tri]; - assert!(dedup_polygons(&mut loops, None).is_some()); + dedup_polygons(&mut loops); assert_eq!(loops.len(), 3); } } diff --git a/crates/render/src/lib.rs b/crates/render/src/lib.rs index 16671aa91..6fa236e4c 100644 --- a/crates/render/src/lib.rs +++ b/crates/render/src/lib.rs @@ -32,7 +32,7 @@ use pen::Pen; pub use dim::{ArrowGeom, Arrowhead, DimGeometry, DimText, LineRole, arrowhead, dimension_geometry, dimension_geometry_with, format_linear_value}; pub use fill::triangulate_evenodd; -pub use hatch::{HatchBudget, fill_loops as hatch_fill_loops, pattern_swatch}; +pub use hatch::{fill_loops as hatch_fill_loops, pattern_swatch}; pub use paper::{PAPER_SIZES, PaperSize, Sheet, paper_size, sheet}; pub use tolerance::{gdt_points, tolerance_in}; @@ -113,8 +113,6 @@ impl Ctx<'_> { } struct Builder<'a> { - output_left: Option<(usize, usize)>, - output_failed: bool, list: DisplayList, opts: &'a Options, /// Plotting: skip layers marked "do not plot". @@ -136,23 +134,6 @@ struct Builder<'a> { pub const MAX_BLOCK_EXPANSION: usize = 2_000_000; impl Builder<'_> { - /// Reserve retained primitives and vertices before growing display-list buffers. Temporary - /// geometry still requires the caller's input/work preflight (this is not a time limit). - fn reserve_output(&mut self, points: usize) -> bool { - if self.output_failed { - return false; - } - if let Some((prims, verts)) = self.output_left { - if let (Some(prims), Some(verts)) = (prims.checked_sub(1), verts.checked_sub(points)) { - self.output_left = Some((prims, verts)); - } else { - self.output_failed = true; - return false; - } - } - true - } - /// `color` and `lw` as the plot style table prints them. fn styled(&self, color: Ink, lw: f32) -> (Ink, f32) { match self.styles { @@ -188,9 +169,6 @@ impl Builder<'_> { self.push_polyline(ctx, color, 0.0, pts); } fn push_polyline(&mut self, ctx: &Ctx, color: Ink, lw: f32, pts: &[Vec2]) { - if !self.reserve_output(pts.len()) { - return; - } let start = self.list.verts.len() as u32; for p in pts { let q = ctx.xf.apply(*p); @@ -215,9 +193,6 @@ impl Builder<'_> { if tris.len() < 3 { return; } - if !self.reserve_output(tris.len()) { - return; - } self.note_pen(color); let (color, _) = self.styled(color, 0.0); let start = self.list.tris.len() as u32; @@ -240,9 +215,6 @@ impl Builder<'_> { /// Shaped text: strokes as polylines; TrueType glyphs filled (TEXTFILL) or outlined. fn shaped(&mut self, ctx: &Ctx, color: Ink, lw: f32, sh: &cadcraft_fonts::Shaped) { for s in &sh.strokes { - if self.output_failed { - return; - } self.polyline(ctx, color, lw, s); } if sh.glyphs.is_empty() { @@ -253,9 +225,6 @@ impl Builder<'_> { let mut text = sh.text.iter().peekable(); let pixel = if self.plotting { 0.0 } else { self.opts.min_dash * 0.5 }; for (i, g) in sh.glyphs.iter().enumerate() { - if self.output_failed { - return; - } if fill { while text.next_if(|t| t.outline < i).is_some() {} let glyph = text.next_if(|t| t.outline == i); @@ -287,9 +256,6 @@ impl Builder<'_> { } } fn point(&mut self, ctx: &Ctx, color: Ink, p: Vec2) { - if !self.reserve_output(1) { - return; - } let (color, _) = self.styled(color, 0.0); let q = ctx.xf.apply(p); self.list.bounds.add(q); @@ -307,9 +273,6 @@ impl Builder<'_> { }); } fn infinite(&mut self, ctx: &Ctx, color: Ink, base: Vec2, dir: Vec2, ray: bool) { - if !self.reserve_output(2) { - return; - } let (color, _) = self.styled(color, 0.0); let start = self.list.verts.len() as u32; self.list.verts.push(ctx.xf.apply(base)); @@ -349,7 +312,7 @@ mod viewports; pub use dim_draw::{dim_text, dimension_in}; pub use display::{DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha}; -pub use pipeline::{Options, build, build_entities, build_entities_limited, build_plot}; +pub use pipeline::{Options, build, build_entities, build_plot}; use props::{default_lineweight, resolve_common}; use text_entity::text_style; pub use text_entity::{layout_mtext_entity, place_text_entity, text_align}; diff --git a/crates/render/src/pipeline.rs b/crates/render/src/pipeline.rs index f839674d8..8cbcb95b9 100644 --- a/crates/render/src/pipeline.rs +++ b/crates/render/src/pipeline.rs @@ -2,7 +2,6 @@ use super::display::append; use super::display::{DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT}; use super::draw::entity; -use super::hatch::HatchBudget; use super::viewports::{MAX_VIEWPORTS, viewport}; use super::{Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Handle, Lineweight, Mat3, Space, Vec2, paper, pen, plotstyle, point}; @@ -18,9 +17,6 @@ pub struct Options { pub text: bool, /// Highlighted (selected) handles are not special here; the canvas overlays them. pub fill: bool, - /// Optional work budget shared by all hatches of a thumbnail, including nested blocks. - /// Exhausted hatches fall back to bounded contours; normal drawing/export uses `None`. - pub hatch_budget: Option>, pub lineweights: bool, /// Height of the visible area in world units of the space being built. Relative point /// sizes (`PDSIZE` <= 0) are a percentage of it; 0 = the height of the space's extents. @@ -57,7 +53,6 @@ impl Default for Options { min_dash: 0.0, text: true, fill: true, - hatch_budget: None, lineweights: false, view_height: 0.0, plot_style_table: None, @@ -101,17 +96,7 @@ pub(crate) fn top_ctx<'a>(d: &'a Drawing, xf: Mat3, top: Handle, frozen: &'a [St fn build_space(d: &Drawing, space: &Space, opts: &Options, plotting: bool) -> DisplayList { let opts = &with_point_view(d, space, opts); let styler = style_table(d, space, opts, plotting).map(|t| plotstyle::Styler::new(d, t)); - let mut b = Builder { - output_left: None, - output_failed: false, - list: DisplayList::default(), - opts, - plotting, - styles: styler.as_ref(), - named: None, - shared_budget: None, - transparency: 0, - }; + let mut b = Builder { list: DisplayList::default(), opts, plotting, styles: styler.as_ref(), named: None, shared_budget: None, transparency: 0 }; if let Space::Paper(name) = space { b.list.sheet = paper::sheet(d, name); } @@ -162,17 +147,8 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor let parts: Vec = ents .par_chunks(PARALLEL_CHUNK) .map(|chunk| { - let mut part = Builder { - output_left: None, - output_failed: false, - list: DisplayList::default(), - opts, - plotting, - styles: None, - named: None, - shared_budget: Some(&budget), - transparency: 0, - }; + let mut part = + Builder { list: DisplayList::default(), opts, plotting, styles: None, named: None, shared_budget: Some(&budget), transparency: 0 }; for e in chunk { entity(&mut part, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e); } @@ -215,29 +191,6 @@ pub(crate) fn with_point_view(d: &Drawing, space: &Space, opts: &Options) -> Opt /// Build the display list for a set of loose entities (previews, rubber bands). pub fn build_entities<'a, I: IntoIterator>(d: &Drawing, ents: I, opts: &Options) -> DisplayList { - build_entities_with_limit(d, ents, opts, None).0 -} - -/// Bounded retained output for preflighted thumbnail entities. A refused list is discarded whole. -/// The caller must bound input and temporary geometry before invoking the renderer. -pub fn build_entities_limited<'a, I: IntoIterator>( - d: &Drawing, - ents: I, - opts: &Options, - max_primitives: usize, - max_vertices: usize, -) -> Option { - let (list, failed) = build_entities_with_limit(d, ents, opts, Some((max_primitives, max_vertices))); - (!failed).then_some(list) -} - -/// Builds the render list for `entities`, or `None` when the hatch work budget is exhausted. -fn build_entities_with_limit<'a, I: IntoIterator>( - d: &Drawing, - ents: I, - opts: &Options, - limit: Option<(usize, usize)>, -) -> (DisplayList, bool) { let ents: Vec<&Entity> = ents.into_iter().collect(); // Only previews holding points need the model extents for relative point sizes. let with_view; @@ -247,21 +200,11 @@ fn build_entities_with_limit<'a, I: IntoIterator>( } else { opts }; - let mut b = Builder { - output_left: limit, - output_failed: false, - list: DisplayList::default(), - opts, - plotting: false, - styles: None, - named: None, - shared_budget: None, - transparency: 0, - }; + let mut b = Builder { list: DisplayList::default(), opts, plotting: false, styles: None, named: None, shared_budget: None, transparency: 0 }; for e in ents { entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e); } - (b.list, b.output_failed) + b.list } /// After a viewport is appended to a plot: the layers its contents carry in their handles diff --git a/crates/render/src/viewports.rs b/crates/render/src/viewports.rs index 758d66b20..6f1e57517 100644 --- a/crates/render/src/viewports.rs +++ b/crates/render/src/viewports.rs @@ -67,17 +67,8 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds } let opts = &with_point_view(d, space, opts); let styler = style_table(d, space, opts, false).map(|t| plotstyle::Styler::new(d, t)); - let mut b = Builder { - output_left: None, - output_failed: false, - list: DisplayList::default(), - opts, - plotting: false, - styles: styler.as_ref(), - named: None, - shared_budget: None, - transparency: 0, - }; + let mut b = + Builder { list: DisplayList::default(), opts, plotting: false, styles: styler.as_ref(), named: None, shared_budget: None, transparency: 0 }; contents(&mut b, d, vp, area, &Clip::Rect(area), paper::unit_mm_of(d, handle)); b.list } @@ -121,8 +112,6 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou // documented limit (CWE-400). Both the serial sub-builder and the parallel chunks share it. let budget = std::sync::atomic::AtomicUsize::new(b.list.expanded); let mut sub = Builder { - output_left: None, - output_failed: false, list: DisplayList::default(), opts: b.opts, plotting: b.plotting, @@ -146,8 +135,6 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou .par_chunks(PARALLEL_CHUNK) .map(|chunk| { let mut part = Builder { - output_left: None, - output_failed: false, list: DisplayList::default(), opts, plotting: false, diff --git a/crates/ui-egui/Cargo.toml b/crates/ui-egui/Cargo.toml index 59356b7a4..d21c2d8ca 100644 --- a/crates/ui-egui/Cargo.toml +++ b/crates/ui-egui/Cargo.toml @@ -32,7 +32,6 @@ web-time = { workspace = true } craft-update = { workspace = true } [dev-dependencies] -cadcraft-io = { workspace = true } # Tests build the dock area as the desktop app does (headless contexts keep floats in-window). craft-ui = { workspace = true, features = ["native-windows"] } # The workspace `egui` dependency enables `default_fonts` and `monochrome_emoji_fonts` in diff --git a/crates/ui-egui/src/blockmgr.rs b/crates/ui-egui/src/blockmgr.rs deleted file mode 100644 index ef74e621b..000000000 --- a/crates/ui-egui/src/blockmgr.rs +++ /dev/null @@ -1,1497 +0,0 @@ -//! The Block Manager / Blocks palette: displays the drawing's blocks as a list, medium icons or -//! large icons (with a slider and view-mode menu), reuses previews in a bounded LRU cache, -//! lets the user grab a block by clicking or dragging it -//! onto the drawing to place with a single click, and keeps all block editing actions. - -use std::collections::{HashMap, HashSet}; -use std::sync::Arc; - -use cadcraft_doc::{Drawing, EntityKind}; -use cadcraft_geom::{Bounds2, Vec2}; -use egui::{Rect, Sense, Stroke, pos2, vec2}; -use serde_json::json; - -use crate::CadApp; -use crate::theme::Tokens; - -/// How the Blocks palette displays the drawing's blocks. -#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] -pub enum ViewMode { - List, - #[default] - MediumIcons, - LargeIcons, -} - -impl ViewMode { - /// Convert a slider index (`0..=2`) to its corresponding [`ViewMode`]. - pub fn from_index(idx: u8) -> Self { - match idx { - 0 => Self::List, - 2 => Self::LargeIcons, - _ => Self::MediumIcons, - } - } - - /// Numeric slider index (`0` = List, `1` = Medium Icons, `2` = Large Icons). - pub fn index(self) -> u8 { - match self { - Self::List => 0, - Self::MediumIcons => 1, - Self::LargeIcons => 2, - } - } - - /// Human-readable English label for UI translation lookup. - pub fn label(self) -> &'static str { - match self { - Self::List => "List", - Self::MediumIcons => "Medium Icons", - Self::LargeIcons => "Large Icons", - } - } -} - -/// The palette's own state between frames. -#[derive(Clone)] -pub struct State { - pub selected: Option, - pub filter: String, - pub view_mode: ViewMode, - /// Specify scale on screen during insertion instead of using `(scale_x, scale_y)`. - pub prompt_scale: bool, - pub scale_x: f64, - pub scale_y: f64, - /// Specify rotation angle on screen during insertion instead of using `rotation`. - pub prompt_rotation: bool, - pub rotation: f64, - /// Keep placing copies of the grabbed block after each click on the drawing. - pub repeat: bool, - /// Insert the block exploded (`*name`). - pub explode: bool, - /// Put a block in hand ready to drop on the canvas as soon as it is clicked or dragged. - pub grab_on_click: bool, - /// Whether the insertion options section is expanded. - pub show_options: bool, - /// Whether the currently running `INSERT` was started by this palette with repeat placement enabled. - pub repeating: bool, - /// Whether the active insertion was grabbed from this palette. - pub grabbed: bool, - /// The run of `INSERT` this palette started, which no other `INSERT` (typed, or from a menu) can be mistaken for. - pub owner: Option, - /// The new name while renaming the selected block. - pub rename: Option, - /// The last message (a refused delete or rename). - pub note: Option, -} - -impl Default for State { - /// Construct the default palette state (`MediumIcons`, uniform scale `1.0`, `grab_on_click` enabled). - fn default() -> Self { - Self { - selected: None, - filter: String::new(), - view_mode: ViewMode::MediumIcons, - prompt_scale: false, - scale_x: 1.0, - scale_y: 1.0, - prompt_rotation: false, - rotation: 0.0, - repeat: false, - explode: false, - grab_on_click: true, - show_options: true, - repeating: false, - grabbed: false, - owner: None, - rename: None, - note: None, - } - } -} - -/// A block's preview, built once while the block is visible on screen. -#[derive(Clone)] -struct Preview { - list: Arc, - bounds: Bounds2, -} - -/// Bounded LRU of complete results (including refusals) for `(drawing_uid, revision)`. -/// Off-screen entries are preferred eviction candidates; visibility never bypasses the caps. -#[derive(Clone, Default)] -pub struct PreviewCache { - key: (u64, u64), - entries: HashMap, - clock: u64, - names: Option>>, - references: Option<(String, usize)>, -} - -#[derive(Clone)] -struct CacheEntry { - result: PreviewResult, - used: u64, - bytes: usize, -} -const MAX_CACHE_BYTES: usize = 64 * 1024 * 1024; -const MAX_CACHE_RESULTS: usize = 512; -// Leave room for hash-table growth when the 513th result triggers eviction. -const MAX_ENTRY_BYTES: usize = MAX_CACHE_BYTES - 2 * (MAX_CACHE_RESULTS + 1) * (std::mem::size_of::<(String, CacheEntry)>() + 16); - -/// Count capacities, not lengths. Thumbnail lists never own plotted glyph/font data. -fn retained_bytes(result: &PreviewResult) -> Option { - let mut bytes = std::mem::size_of::(); - if let PreviewResult::Ready(p) = result { - let list = &p.list; - if !list.texts.is_empty() { - return None; - } - bytes = bytes.checked_add(std::mem::size_of::() + 2 * std::mem::size_of::())?; - for (capacity, size) in [ - (list.prims.capacity(), std::mem::size_of::()), - (list.verts.capacity(), std::mem::size_of::()), - (list.tris.capacity(), std::mem::size_of::()), - (list.prim_layers.capacity(), std::mem::size_of::()), - (list.texts.capacity(), std::mem::size_of::()), - (list.pens.capacity(), std::mem::size_of::()), - ] { - bytes = bytes.checked_add(capacity.checked_mul(size)?)?; - } - } - Some(bytes) -} - -/// At most three synchronous builds start per frame. An individual build can still stall a frame. -const MAX_BUILDS_PER_FRAME: usize = 3; - -impl PreviewCache { - /// Ensure the cache matches `(uid, revision)`, clearing stale entries if the drawing changed. - pub fn sync_revision(&mut self, uid: u64, revision: u64) { - if self.key != (uid, revision) { - self.key = (uid, revision); - self.entries.clear(); - self.names = None; - self.references = None; - } - } - - /// Touch a result without rebuilding it, even when it has no geometry. - fn touch(&mut self, name: &str) { - self.clock = match self.clock.checked_add(1) { - Some(v) => v, - None => { - for entry in self.entries.values_mut() { - entry.used = 0; - } - 1 - } - }; - if let Some(entry) = self.entries.get_mut(name) { - entry.used = self.clock; - } - } - - /// Caches `result` under `name` (an oversized one becomes a small refusal), then evicts beyond the limits. - fn insert(&mut self, name: String, mut result: PreviewResult, visible: &HashSet) { - let mut bytes = retained_bytes(&result).and_then(|v| v.checked_add(name.capacity())); - // Cache a small refusal instead of rebuilding a result that can never fit. - if bytes.is_none_or(|v| v > MAX_ENTRY_BYTES) { - result = PreviewResult::Unavailable(PreviewFailure::Output); - bytes = std::mem::size_of::().checked_add(name.capacity()); - } - self.entries.insert(name.clone(), CacheEntry { result, used: 0, bytes: bytes.unwrap_or(MAX_CACHE_BYTES) }); - self.touch(&name); - self.evict(visible); - } - - /// Conservative retained allocation estimate, including hash capacity and owned key buffers. - fn estimated_bytes(&self) -> Option { - let slots = std::mem::size_of::<(String, CacheEntry)>().checked_add(16)?; - self.entries.values().try_fold(self.entries.capacity().checked_mul(slots)?, |sum, e| sum.checked_add(e.bytes)) - } - - /// Drops least-recently-used entries until the count and byte limits hold, sparing `visible` names while possible. - fn evict(&mut self, visible: &HashSet) { - while self.entries.len() > MAX_CACHE_RESULTS || self.estimated_bytes().is_none_or(|v| v > MAX_CACHE_BYTES) { - let victim = self.entries.iter().min_by_key(|(name, e)| (visible.contains(*name), e.used)).map(|(name, _)| name.clone()); - let Some(victim) = victim else { break }; - self.entries.remove(&victim); - } - } - - /// Number of block previews currently held in memory. - pub fn len(&self) -> usize { - self.entries.len() - } - - /// Whether no block previews are currently cached. - pub fn is_empty(&self) -> bool { - self.entries.is_empty() - } -} - -/// Egui temporary data id storing the [`State`] of the Blocks palette. -fn state_id() -> egui::Id { - egui::Id::unique("cc_block_manager") -} - -/// Egui temporary data id storing the [`PreviewCache`] of visible blocks. -fn cache_id() -> egui::Id { - egui::Id::unique("cc_block_manager_previews") -} - -/// How many block previews are currently loaded in memory for `ctx`. -pub fn cached_preview_count(ctx: &egui::Context) -> usize { - ctx.data(|d| d.get_temp::(cache_id())).map_or(0, |c| c.len()) -} - -/// The named blocks a user works with: not the generated (`*D12`) ones nor layout blocks. -pub fn names(d: &Drawing) -> Vec { - let mut v: Vec = d.blocks.keys().filter(|k| !k.starts_with('*')).cloned().collect(); - v.sort_by_cached_key(|n| n.to_lowercase()); - v -} - -/// How many block references to `name` the drawing holds (model, layouts and other blocks). -pub fn reference_count(d: &Drawing, name: &str) -> usize { - std::iter::once(&d.model) - .chain(d.layouts.iter().map(|l| &l.entities)) - .chain(d.blocks.values().map(|b| &b.entities)) - .flat_map(|s| s.iter()) - .filter(|e| matches!(&e.kind, EntityKind::Insert(i) if i.block.eq_ignore_ascii_case(name))) - .count() -} - -mod preview; -use preview::{PreviewFailure, PreviewResult, build}; - -/// Draw a display list fitted into `r` on a framed square of the canvas colour. -pub fn paint_list(p: &egui::Painter, r: Rect, list: &cadcraft_render::DisplayList, bounds: &Bounds2) { - let t = Tokens::get(); - p.rect_filled(r, 3.0, t.canvas); - let pad = (r.width().min(r.height()) * 0.1).clamp(2.0, 8.0); - let inner = r.shrink(pad); - if !bounds.is_empty() && inner.width() > 1.0 && inner.height() > 1.0 { - let (w, h) = (bounds.width().max(1e-12), bounds.height().max(1e-12)); - let k = (f64::from(inner.width()) / w).min(f64::from(inner.height()) / h); - let c = bounds.center(); - let mid = inner.center(); - let at = |v: &Vec2| pos2(mid.x + ((v.x - c.x) * k) as f32, mid.y - ((v.y - c.y) * k) as f32); - let bg = cadcraft_color::Rgb(t.canvas.r(), t.canvas.g(), t.canvas.b()); - let clip = p.with_clip_rect(r.shrink(1.0)); - for prim in &list.prims { - let rgb = prim.display_rgb(bg); - let col = egui::Color32::from_rgb(rgb.0, rgb.1, rgb.2); - let pts = list.points(prim); - match prim.kind { - cadcraft_render::Kind::Polyline if pts.len() >= 2 => { - clip.add(egui::Shape::line(pts.iter().map(at).collect(), Stroke::new(1.0, col))); - } - cadcraft_render::Kind::Tris | cadcraft_render::Kind::Mask => { - let fill = if prim.kind == cadcraft_render::Kind::Mask { t.canvas } else { col }; - let mut mesh = egui::Mesh::default(); - for tri in pts.as_chunks::<3>().0 { - let base = u32::try_from(mesh.vertices.len()).unwrap_or(u32::MAX); - for v in tri { - mesh.colored_vertex(at(v), fill); - } - mesh.add_triangle(base, base + 1, base + 2); - } - clip.add(egui::Shape::mesh(mesh)); - } - cadcraft_render::Kind::Point => { - if let Some(v) = pts.first() { - clip.circle_filled(at(v), 1.2, col); - } - } - _ => {} - } - } - } - p.rect_stroke(r, 3.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); -} - -/// Paint a mini glyph for the view-mode button (`List`, `MediumIcons`, `LargeIcons`). -fn paint_view_mode_icon(p: &egui::Painter, r: Rect, mode: ViewMode, col: egui::Color32) { - let inner = r.shrink(3.0); - let stroke = Stroke::new(1.2, col); - match mode { - ViewMode::LargeIcons => { - p.rect_stroke(inner, 1.5, stroke, egui::StrokeKind::Inside); - p.rect_filled(inner.shrink(2.5), 1.0, col.gamma_multiply(0.35)); - } - ViewMode::MediumIcons => { - let gap = 2.0; - let w = (inner.width() - gap) * 0.5; - let h = (inner.height() - gap) * 0.5; - for row in 0..2 { - for col_i in 0..2 { - let min = pos2(inner.left() + col_i as f32 * (w + gap), inner.top() + row as f32 * (h + gap)); - p.rect_stroke(Rect::from_min_size(min, vec2(w, h)), 1.0, stroke, egui::StrokeKind::Inside); - } - } - } - ViewMode::List => { - for i in 0..3 { - let y = inner.top() + (i as f32 + 0.5) * (inner.height() / 3.0); - p.rect_filled(Rect::from_center_size(pos2(inner.left() + 1.5, y), vec2(2.5, 2.5)), 0.5, col); - p.line_segment([pos2(inner.left() + 5.0, y), pos2(inner.right(), y)], stroke); - } - } - } -} - -/// Truncate `text` with `…` so it fits within `max_w` pixels in `font`. -fn truncate_text(p: &egui::Painter, text: &str, font: &egui::FontId, col: egui::Color32, max_w: f32) -> String { - let g = p.layout_no_wrap(text.to_string(), font.clone(), col); - if g.size().x <= max_w { - return text.to_string(); - } - let mut out = String::new(); - for ch in text.chars() { - let cand = format!("{out}{ch}…"); - if p.layout_no_wrap(cand, font.clone(), col).size().x > max_w { - break; - } - out.push(ch); - } - format!("{out}…") -} - -/// Start `INSERT` with `name` in hand and the palette's scale/rotation options preset, so the -/// block follows the crosshairs on the canvas and a single click places it. -pub fn grab_block(app: &mut CadApp, name: &str, st: &State) { - let chosen = if st.explode { format!("*{name}") } else { name.to_string() }; - crate::dialogs::insert_block(app, &chosen); - if app.session.running.as_ref().is_none_or(|r| r.id != "insert") { - return; - } - if app.session.current_prompt().is_none_or(|p| !p.accept.point) { - return; - } - if !st.prompt_scale { - let sx = if st.scale_x.is_finite() && st.scale_x != 0.0 { st.scale_x } else { 1.0 }; - let sy = if st.scale_y.is_finite() && st.scale_y != 0.0 { st.scale_y } else { sx }; - let scale_text = if (sx - sy).abs() < 1e-12 || st.explode { format!("{sx}") } else { format!("{sx},{sy}") }; - let _ = app.session.input(cadcraft_engine::Input::Keyword("Scale".into())); - let _ = app.session.input(cadcraft_engine::Input::Text(scale_text)); - } - if !st.prompt_rotation { - let rot = if st.rotation.is_finite() { st.rotation } else { 0.0 }; - let _ = app.session.input(cadcraft_engine::Input::Keyword("Rotate".into())); - let _ = app.session.input(cadcraft_engine::Input::Text(format!("<<{rot}"))); - } - if st.repeat { - let _ = app.session.input(cadcraft_engine::Input::Keyword("Repeat".into())); - } -} - -/// What a control in the palette asked for, executed once the UI frame is drawn. -enum Act { - /// Grab a block in hand (from clicking or dragging a tile, or the Insert button). - Grab(String), - Edit(String), - Create, - StartRename(String), - Rename(String, String), - Delete(String), - Write(String), - /// Pin the window as a panel on the right; float the panel as a window. - ToPanel, - ToWindow, -} - -/// The data the Block Manager shows this frame. -struct View { - all: Arc>, - selected: Option, - info: Option<(usize, usize, cadcraft_geom::Vec3, bool, String, Option)>, - can_write: bool, -} - -/// Gather the block list, selected block metadata and write capability for this frame. -fn view(app: &CadApp, st: &mut State, cache: &mut PreviewCache) -> Option { - let sess = app.session.state().ok()?; - let d = &sess.doc; - cache.sync_revision(sess.uid, sess.revision); - let all = Arc::clone(cache.names.get_or_insert_with(|| Arc::new(names(d)))); - if st.selected.as_ref().is_some_and(|s| !d.blocks.contains_key(s)) { - st.selected = None; - st.rename = None; - } - if st.selected.is_none() { - st.selected = all.first().cloned(); - } - let selected = st.selected.clone(); - let info = selected.as_deref().and_then(|n| { - let b = d.block(n)?; - if cache.references.as_ref().is_none_or(|(name, _)| name != n) { - cache.references = Some((n.to_string(), reference_count(d, n))); - } - let refs = cache.references.as_ref().map_or(0, |(_, count)| *count); - Some((b.entities.len(), refs, b.base, b.annotative, b.description.clone(), b.xref_path.clone())) - }); - Some(View { all, selected, info, can_write: app.services.pick_save.is_some() }) -} - -/// One frame's visible set and allowance for starting synchronous builds. The elapsed-time -/// check defers the next build; it cannot interrupt a build already in progress. -struct FrameBuilds { - visible: HashSet, - builds_left: usize, - started: web_time::Instant, -} - -/// Render a single block tile/row according to `st.view_mode`, updating `frame` and `cache` -/// only when the tile is actually visible inside the scroll viewport. -fn draw_block_item( - ui: &mut egui::Ui, - d: &Drawing, - name: &str, - selected: bool, - mode: ViewMode, - tile_size: egui::Vec2, - (cache, frame): (&mut PreviewCache, &mut FrameBuilds), -) -> egui::Response { - let t = Tokens::get(); - let (rect, resp) = ui.allocate_exact_size(tile_size, Sense::click_and_drag()); - if !ui.is_rect_visible(rect) { - return resp; - } - frame.visible.insert(name.to_string()); - if !cache.entries.contains_key(name) { - if frame.builds_left > 0 && frame.started.elapsed().as_millis() < 30 { - frame.builds_left -= 1; - cache.insert(name.to_string(), build(d, name), &frame.visible); - } else { - ui.ctx().request_repaint(); - } - } - cache.touch(name); - let p = ui.painter(); - let result = cache.entries.get(name).map(|e| &e.result); - let status = preview_status(result, d.block(name).is_some_and(|b| b.entities.is_empty())); - if selected { - p.rect_filled(rect, 3.0, t.accent.gamma_multiply(0.28)); - p.rect_stroke(rect, 3.0, Stroke::new(1.0, t.accent), egui::StrokeKind::Inside); - } else if resp.hovered() { - p.rect_filled(rect, 3.0, t.control_hover); - } - match mode { - ViewMode::List => { - let thumb = Rect::from_min_size(pos2(rect.left() + 4.0, rect.top() + 3.0), vec2(26.0, (rect.height() - 6.0).max(16.0))); - paint_preview(p, thumb, result, &status, true); - let text_x = thumb.right() + 6.0; - let max_w = (rect.right() - text_x - 4.0).max(20.0); - let label = truncate_text(p, name, &crate::theme::body(), t.text, max_w); - p.text(pos2(text_x, rect.top() + 2.0), egui::Align2::LEFT_TOP, label, crate::theme::body(), t.text); - if let Some(status) = &status { - p.text(pos2(text_x, rect.bottom() - 2.0), egui::Align2::LEFT_BOTTOM, status, crate::theme::small(), t.text_dim); - } - } - ViewMode::MediumIcons | ViewMode::LargeIcons => { - let label_h = 18.0; - let pad = 4.0; - let thumb = Rect::from_min_max( - pos2(rect.left() + pad, rect.top() + pad), - pos2(rect.right() - pad, (rect.bottom() - label_h).max(rect.top() + 16.0)), - ); - paint_preview(p, thumb, result, &status, false); - let max_w = (rect.width() - 6.0).max(20.0); - let font = crate::theme::small(); - let label = truncate_text(p, name, &font, t.text, max_w); - p.text(pos2(rect.center().x, rect.bottom() - label_h * 0.5), egui::Align2::CENTER_CENTER, label, font, t.text); - } - } - if let Some(PreviewResult::Unavailable(reason)) = result { - resp.on_hover_text(format!("{}\n{}", crate::tl!("Preview unavailable"), reason.message())) - } else if let Some(status) = status { - resp.on_hover_text(status) - } else { - resp - } -} - -/// Short text explaining why a block shows no drawing, or `None` when it has a preview. -fn preview_status(result: Option<&PreviewResult>, empty_definition: bool) -> Option<&'static str> { - match result { - None => Some(crate::tl!("Preview pending")), - Some(PreviewResult::Ready(_)) => None, - Some(PreviewResult::Empty) if empty_definition => Some(crate::tl!("Empty block")), - Some(PreviewResult::Empty) => Some(crate::tl!("No visible content")), - Some(PreviewResult::Unavailable(_)) => Some(crate::tl!("Preview unavailable")), - } -} - -/// Paints the preview, or the `status` text in `rect` when there is none (`compact` shows a one-character marker instead). -fn paint_preview(p: &egui::Painter, rect: Rect, result: Option<&PreviewResult>, status: &Option<&'static str>, compact: bool) { - if let Some(PreviewResult::Ready(pv)) = result { - paint_list(p, rect, &pv.list, &pv.bounds); - return; - } - let t = Tokens::get(); - p.rect_filled(rect, 3.0, t.canvas); - p.rect_stroke(rect, 3.0, Stroke::new(1.0, t.border), egui::StrokeKind::Inside); - if let Some(text) = status { - let text = if compact { if matches!(result, Some(PreviewResult::Unavailable(_))) { "!" } else { "…" } } else { *text }; - let galley = p.layout(text.to_string(), crate::theme::small(), t.text_dim, (rect.width() - 6.0).max(1.0)); - p.with_clip_rect(rect).galley(rect.center() - galley.size() / 2.0, galley, t.text_dim); - } -} - -/// A double-click's second release must not restart placement begun by its first click. -fn should_grab(drag: bool, click: bool, double_click: bool, grab_on_click: bool) -> bool { - drag || if grab_on_click { click && !double_click } else { double_click } -} - -/// The manager's contents: top filter + view-mode slider/menu, scrollable block grid/list with -/// cached previews, insertion options, and block editing controls. -fn body(ui: &mut egui::Ui, d: &Drawing, v: &View, st: &mut State, cache: &mut PreviewCache, as_panel: bool, act: &mut Option) { - let View { all, selected, info, can_write, .. } = v; - let can_write = *can_write; - let t = Tokens::get(); - - // Top bar: Filter + View mode slider & dropdown + Float/Pin toggle. - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = 4.0; - let reserved = if as_panel { 112.0 } else { 220.0 }; - let w = (ui.available_width() - reserved).max(64.0); - ui.add(egui::TextEdit::singleline(&mut st.filter).hint_text(crate::tl!("Filter")).desired_width(w)); - - // Slider ("curseur") for List (0) / Medium Icons (1) / Large Icons (2). - let mut mode_idx = st.view_mode.index(); - let slider_resp = ui - .scope(|ui| { - ui.spacing_mut().slider_width = 44.0; - ui.add(egui::Slider::new(&mut mode_idx, 0..=2).show_value(false)) - }) - .inner - .on_hover_text(format!("{}: {}", crate::tl!("View mode"), crate::i18n::t(ViewMode::from_index(mode_idx).label()))); - if slider_resp.changed() { - st.view_mode = ViewMode::from_index(mode_idx); - } - - // View mode icon dropdown button (like AutoCAD's Blocks palette menu). - let (btn_rect, btn_resp) = ui.allocate_exact_size(vec2(28.0, 20.0), Sense::click()); - if btn_resp.hovered() { - ui.painter().rect_filled(btn_rect, 3.0, t.control_hover); - } else { - ui.painter().rect_filled(btn_rect, 3.0, t.control); - } - let icon_rect = Rect::from_min_size(pos2(btn_rect.left() + 2.0, btn_rect.top() + 2.0), vec2(16.0, 16.0)); - paint_view_mode_icon(ui.painter(), icon_rect, st.view_mode, t.text); - crate::icons::paint( - ui.painter(), - Rect::from_center_size(pos2(btn_rect.right() - 5.0, btn_rect.center().y), vec2(8.0, 8.0)), - crate::icons::Icon::ChevronDown, - false, - ); - let btn_resp = btn_resp.on_hover_text(crate::tl!("View mode")); - egui::Popup::from_toggle_button_response(&btn_resp).close_behavior(egui::PopupCloseBehavior::CloseOnClick).show(|ui| { - for mode in [ViewMode::LargeIcons, ViewMode::MediumIcons, ViewMode::List] { - if ui.selectable_label(st.view_mode == mode, crate::i18n::t(mode.label())).clicked() { - st.view_mode = mode; - } - } - }); - - ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { - let (icon, tip) = if as_panel { - (crate::icons::Icon::Workspace, crate::tl!("Float as a window")) - } else { - (crate::icons::Icon::Properties, crate::tl!("Pin as a panel on the right")) - }; - if crate::icons::button(ui, icon, 20.0, tip, false).clicked() { - *act = Some(if as_panel { Act::ToWindow } else { Act::ToPanel }); - } - if !as_panel && ui.button(crate::tl!("Create...")).on_hover_text(crate::tl!("Make a block from objects (BLOCK)")).clicked() { - *act = Some(Act::Create); - } - }); - }); - - ui.add_space(4.0); - let avail = ui.available_size(); - let bottom_reserve = if st.show_options { 210.0 } else { 115.0 }; - let list_h = (avail.y - bottom_reserve).clamp(140.0, 420.0); - let list_w = avail.x; - - let mut frame = FrameBuilds { visible: HashSet::new(), builds_left: MAX_BUILDS_PER_FRAME, started: web_time::Instant::now() }; - - egui::Frame::NONE.stroke(Stroke::new(1.0, t.border)).inner_margin(4.0).show(ui, |ui| { - egui::ScrollArea::vertical().id_salt("cc_block_list").auto_shrink([false, false]).max_height(list_h).show(ui, |ui| { - let inner_w = (list_w - 14.0).max(80.0); - ui.set_width(inner_w); - let filter = st.filter.trim().to_lowercase(); - let filtered: Vec<&String> = all.iter().filter(|n| filter.is_empty() || n.to_lowercase().contains(&filter)).collect(); - if filtered.is_empty() { - let msg = if all.is_empty() { crate::tl!("No blocks defined in this drawing.") } else { crate::tl!("No blocks match the search.") }; - ui.label(egui::RichText::new(msg).color(t.text_dim)); - return; - } - - let mut interact = |n: &String, r: egui::Response| { - let drag = r.drag_started(); - let click = r.clicked(); - let dbl = r.double_clicked(); - if click || drag || dbl { - st.selected = Some((*n).clone()); - st.rename = None; - st.note = None; - } - if drag { - r.ctx.stop_dragging(); - } - if should_grab(drag, click, dbl, st.grab_on_click) { - *act = Some(Act::Grab((*n).clone())); - } - r.on_hover_text(format!("{n}\n{}", crate::tl!("Click or drag to take in hand, then click on the drawing to place"))); - }; - - match st.view_mode { - ViewMode::List => { - ui.spacing_mut().item_spacing.y = 2.0; - for n in filtered { - let on = selected.as_deref() == Some(n.as_str()); - let r = draw_block_item(ui, d, n, on, ViewMode::List, vec2(inner_w, 28.0), (cache, &mut frame)); - interact(n, r); - } - } - ViewMode::MediumIcons => { - let gap = 6.0; - let cols = ((inner_w + gap) / 76.0).floor().max(1.0) as usize; - let tile_w = ((inner_w - gap * (cols.saturating_sub(1) as f32)) / cols as f32).floor().max(58.0); - let tile_h = 76.0; - for row in filtered.chunks(cols) { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = gap; - for n in row { - let on = selected.as_deref() == Some(n.as_str()); - let r = draw_block_item(ui, d, n, on, ViewMode::MediumIcons, vec2(tile_w, tile_h), (cache, &mut frame)); - interact(n, r); - } - }); - ui.add_space(4.0); - } - } - ViewMode::LargeIcons => { - let gap = 8.0; - let cols = ((inner_w + gap) / 118.0).floor().max(1.0) as usize; - let tile_w = ((inner_w - gap * (cols.saturating_sub(1) as f32)) / cols as f32).floor().max(88.0); - let tile_h = 112.0; - for row in filtered.chunks(cols) { - ui.horizontal(|ui| { - ui.spacing_mut().item_spacing.x = gap; - for n in row { - let on = selected.as_deref() == Some(n.as_str()); - let r = draw_block_item(ui, d, n, on, ViewMode::LargeIcons, vec2(tile_w, tile_h), (cache, &mut frame)); - interact(n, r); - } - }); - ui.add_space(6.0); - } - } - } - }); - }); - - cache.evict(&frame.visible); - - ui.add_space(4.0); - - // Insertion Options section (matching AutoCAD's Options panel at the bottom of the Blocks palette). - let (opt_rect, opt_resp) = ui.allocate_exact_size(vec2(ui.available_width(), 20.0), Sense::click()); - ui.painter().rect_filled(opt_rect, 2.0, t.chrome); - crate::icons::paint( - ui.painter(), - Rect::from_center_size(pos2(opt_rect.left() + 10.0, opt_rect.center().y), vec2(10.0, 10.0)), - if st.show_options { crate::icons::Icon::ChevronDown } else { crate::icons::Icon::ChevronRight }, - false, - ); - ui.painter().text( - pos2(opt_rect.left() + 22.0, opt_rect.center().y), - egui::Align2::LEFT_CENTER, - crate::tl!("Options"), - crate::theme::body(), - t.text, - ); - if opt_resp.clicked() { - st.show_options = !st.show_options; - } - if st.show_options { - ui.add_space(2.0); - ui.horizontal(|ui| { - ui.checkbox(&mut st.prompt_scale, crate::tl!("Scale")).on_hover_text(crate::tl!("Specify scale on screen when placing")); - ui.add_enabled_ui(!st.prompt_scale, |ui| { - let x_label = ui.label("X:"); - ui.add(egui::DragValue::new(&mut st.scale_x).speed(0.05).range(0.0001..=1e6)).labelled_by(x_label.id); - let y_label = ui.label("Y:"); - // An exploded insertion scales both axes by X, so Y would be ignored. - ui.add_enabled_ui(!st.explode, |ui| { - let y = ui.add(egui::DragValue::new(&mut st.scale_y).speed(0.05).range(0.0001..=1e6)).labelled_by(y_label.id); - y.on_disabled_hover_text(crate::tl!("Exploded insertion uses the X scale for both axes")); - }); - }); - }); - ui.horizontal(|ui| { - ui.checkbox(&mut st.prompt_rotation, crate::tl!("Rotation")).on_hover_text(crate::tl!("Specify rotation angle on screen when placing")); - ui.add_enabled_ui(!st.prompt_rotation, |ui| { - let angle_label = ui.label(crate::tl!("Angle")); - ui.add(egui::DragValue::new(&mut st.rotation).speed(1.0).range(-360.0..=360.0)).labelled_by(angle_label.id); - }); - }); - ui.horizontal_wrapped(|ui| { - ui.checkbox(&mut st.repeat, crate::tl!("Repeat placement")); - ui.checkbox(&mut st.explode, crate::tl!("Explode")); - ui.checkbox(&mut st.grab_on_click, crate::tl!("Grab on click")) - .on_hover_text(crate::tl!("Click or drag a block to take it in hand, then click on the drawing to place")); - }); - } - - ui.separator(); - - // Selected block details and editing options. - let Some(name) = selected.clone() else { - if as_panel && ui.button(crate::tl!("Create...")).on_hover_text(crate::tl!("Make a block from objects (BLOCK)")).clicked() { - *act = Some(Act::Create); - } - return; - }; - if let Some(mut new) = st.rename.take() { - let mut keep = true; - ui.horizontal(|ui| { - ui.add(egui::TextEdit::singleline(&mut new).desired_width(150.0)); - if ui.button(crate::tl!("OK")).clicked() && !new.trim().is_empty() { - *act = Some(Act::Rename(name.clone(), new.trim().to_string())); - } - if ui.button(crate::tl!("Cancel")).clicked() { - keep = false; - } - }); - if keep { - st.rename = Some(new); - } - } else { - ui.horizontal_wrapped(|ui| { - ui.label(egui::RichText::new(&name).strong()); - if let Some((objects, refs, base, annotative, _, _)) = info { - let summary = format!("({} {}, {} {})", objects, crate::tl!("Objects"), refs, crate::tl!("References")); - let tip = format!( - "{}: {:.4}, {:.4}\n{}: {}", - crate::tl!("Base point"), - base.x, - base.y, - crate::tl!("Annotative"), - if *annotative { crate::tl!("Yes") } else { crate::tl!("No") } - ); - ui.label(egui::RichText::new(summary).small().color(t.text_dim)).on_hover_text(tip); - } - }); - } - if let Some((_, _, _, _, description, xref)) = info { - if let Some(path) = xref { - ui.label(egui::RichText::new(format!("{}: {path}", crate::tl!("External reference"))).small().color(t.text_dim)); - } - if !description.is_empty() { - ui.label(egui::RichText::new(description).small().color(t.text_dim)); - } - } - ui.add_space(2.0); - ui.horizontal_wrapped(|ui| { - if ui.button(crate::tl!("Insert")).clicked() { - *act = Some(Act::Grab(name.clone())); - } - if ui.button(crate::tl!("Edit Block")).on_hover_text(crate::tl!("Open in the Block Editor")).clicked() { - *act = Some(Act::Edit(name.clone())); - } - if ui.button(crate::tl!("Rename...")).clicked() { - *act = Some(Act::StartRename(name.clone())); - } - if ui.button(crate::tl!("Delete")).on_hover_text(crate::tl!("Delete a block that no object uses")).clicked() { - *act = Some(Act::Delete(name.clone())); - } - if can_write && ui.button(crate::tl!("Save to File...")).on_hover_text(crate::tl!("Write the block as a drawing (WBLOCK)")).clicked() { - *act = Some(Act::Write(name.clone())); - } - if as_panel && ui.button(crate::tl!("Create...")).on_hover_text(crate::tl!("Make a block from objects (BLOCK)")).clicked() { - *act = Some(Act::Create); - } - }); - if let Some(n) = &st.note { - ui.label(egui::RichText::new(n).color(t.text_dim)); - } -} - -/// Cancel an in-progress `INSERT` and stop repeat placement. -fn cancel_pending_insert(app: &mut CadApp, st: &mut State) { - let is_ours = |r: &cadcraft_engine::Running| r.id == "insert" && st.owner == Some(r.serial); - // Only the palette's own INSERT, running or suspended by a transparent command; never another one. - let owned = app.session.running.as_ref().is_some_and(is_ours) || app.session.suspended.as_ref().is_some_and(is_ours); - st.grabbed = false; - st.owner = None; - st.repeating = false; - if owned { - app.session.cancel(); - } -} - -/// An `INSERT` the palette did not start is in progress (running, or suspended by a transparent command). -fn foreign_insert(app: &CadApp, st: &State) -> bool { - let foreign = |r: &cadcraft_engine::Running| r.id == "insert" && st.owner != Some(r.serial); - app.session.running.as_ref().is_some_and(foreign) || app.session.suspended.as_ref().is_some_and(foreign) -} - -/// Refuse a drawing edit while someone else's `INSERT` runs: its undo snapshot would predate the -/// edit, so undoing the insertion would also undo the palette's change. -fn refuse_during_foreign_insert(app: &CadApp, st: &mut State) -> bool { - if !foreign_insert(app, st) { - return false; - } - st.note = Some(crate::tl!("Finish or cancel the running INSERT first").to_string()); - true -} - -/// Do what a button asked; false when the manager window should close (a command takes over). -fn apply(app: &mut CadApp, st: &mut State, act: Option, esc_pressed: bool) -> bool { - let is_ours = |r: &cadcraft_engine::Running| r.id == "insert" && st.owner == Some(r.serial); - let ours = app.session.running.as_ref().is_some_and(is_ours); - // A transparent command in front of it only suspends the palette's INSERT. - let owned = ours || app.session.suspended.as_ref().is_some_and(is_ours); - if !owned { - st.grabbed = false; - st.owner = None; - } - if esc_pressed { - if st.repeating { - st.repeat = false; - } - cancel_pending_insert(app, st); - } - let edits = match &act { - Some(Act::Edit(_) | Act::Create | Act::Delete(_)) => true, - Some(Act::Rename(from, to)) => from != to, - _ => false, - }; - if edits && refuse_during_foreign_insert(app, st) { - return true; - } - match act { - Some(Act::Grab(n)) => { - st.rename = None; - grab_block(app, &n, st); - // Only track repeat-placement when the palette's own INSERT started. - st.owner = app.session.running.as_ref().filter(|r| r.id == "insert").map(|r| r.serial); - st.grabbed = st.owner.is_some(); - st.repeating = st.repeat && st.grabbed; - return true; - } - Some(Act::Edit(n)) => { - cancel_pending_insert(app, st); - if let Err(e) = app.run("bedit", json!({ "name": n })) { - app.session.echo(e); - } - return false; - } - Some(Act::Create) => { - cancel_pending_insert(app, st); - app.start("block"); - return false; - } - Some(Act::StartRename(n)) => { - cancel_pending_insert(app, st); - st.rename = Some(n); - return true; - } - // Confirming the name unchanged is not an edit: keep the placement in progress. - Some(Act::Rename(from, to)) if from == to => st.rename = None, - Some(Act::Rename(from, to)) => { - cancel_pending_insert(app, st); - match app.run("rename", json!({ "table": "block", "from": from, "to": to })) { - Ok(_) => { - st.selected = Some(to); - st.rename = None; - st.note = None; - } - Err(e) => st.note = Some(e), - } - } - Some(Act::Delete(n)) => { - cancel_pending_insert(app, st); - let refs = app.session.doc().map(|d| reference_count(d, &n)).unwrap_or(0); - if refs > 0 { - st.note = Some(format!("{} ({refs})", crate::tl!("The block is in use and can't be deleted"))); - } else { - match app.run("purge", json!({ "type": "blocks", "names": n })) { - Ok(_) => { - st.selected = None; - st.note = None; - } - Err(e) => st.note = Some(e), - } - } - } - Some(Act::Write(n)) => { - cancel_pending_insert(app, st); - if let Some(pick) = app.services.pick_save.as_ref() - && let Some(path) = pick(&format!("{n}.dwg")) - && let Err(e) = app.run("wblock", json!({ "path": path, "name": n })) - { - st.note = Some(e); - } - } - Some(Act::ToPanel) => { - app.ui.blocks_window = false; - let _ = open_panel(app); - return false; - } - Some(Act::ToWindow) => { - app.ui.blocks_window = true; - let _ = crate::docking::command(app, false, &json!({ "operation": "close", "panel": crate::docking::Panel::Blocks.id() })); - app.ui.dialog = Some("blocks".into()); - } - None => { - if st.repeating { - if esc_pressed || !owned { - // Repeat INSERT ended (cancelled with Esc or replaced by another command). - st.repeating = false; - st.repeat = false; - } else if !st.repeat && ours && app.session.input(cadcraft_engine::Input::Keyword("NoRepeat".into())).is_ok() { - // Repeat placement was unchecked in the palette while INSERT was running; - // clear palette tracking only after the engine accepts NoRepeat. - st.repeating = false; - } - } else if st.repeat && st.grabbed && ours && app.session.input(cadcraft_engine::Input::Keyword("Repeat".into())).is_ok() { - // Repeat placement was checked after grabbing the block; arm repeat on the running INSERT. - st.repeating = true; - } - } - } - true -} - -/// Open the Block Manager the way it was last used: a panel pinned on the right (the first -/// time) or a window. -pub fn open(app: &mut CadApp) -> Result { - if app.ui.blocks_window { - app.ui.dialog = Some("blocks".into()); - return Ok(serde_json::Value::Null); - } - open_panel(app) -} - -/// Show the Blocks panel, docked on the right of the drawing. -fn open_panel(app: &mut CadApp) -> Result { - if app.ui.dialog.as_deref() == Some("blocks") { - app.ui.dialog = None; - } - let panel = crate::docking::Panel::Blocks; - 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() }))?; - // The first time: pinned at the right edge, beside the Layers and Properties palettes. - if first && app.ui.docking.layout.contains(&crate::docking::Panel::Properties) { - return crate::docking::command(app, false, &json!({ "operation": "move", "panel": panel.id(), "target": "properties", "zone": "right" })); - } - Ok(r) -} - -/// The Blocks panel. -pub fn panel(app: &mut CadApp, ui: &mut egui::Ui) { - let ctx = ui.ctx().clone(); - let mut st = ctx.data(|d| d.get_temp::(state_id())).unwrap_or_default(); - let mut cache = ctx.data(|d| d.get_temp::(cache_id())).unwrap_or_default(); - let Some(v) = view(app, &mut st, &mut cache) else { return }; - let mut act = None; - if let Ok(doc) = app.session.state().map(|s| Arc::clone(&s.doc)) { - egui::ScrollArea::vertical().id_salt("dock-blocks").auto_shrink([false, false]).show(ui, |ui| { - egui::Frame::NONE.inner_margin(6.0).show(ui, |ui| body(ui, &doc, &v, &mut st, &mut cache, true, &mut act)); - }); - } - // The panel stays open whatever the button did. - let esc = ctx.input(|i| i.key_pressed(egui::Key::Escape)); - apply(app, &mut st, act, esc); - ctx.data_mut(|d| { - d.insert_temp(state_id(), st); - d.insert_temp(cache_id(), cache); - }); -} - -/// The Block Manager as a window. -pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { - let mut st = ctx.data(|d| d.get_temp::(state_id())).unwrap_or_default(); - let mut cache = ctx.data(|d| d.get_temp::(cache_id())).unwrap_or_default(); - let Some(v) = view(app, &mut st, &mut cache) else { return }; - let mut act = None; - if let Ok(doc) = app.session.state().map(|s| Arc::clone(&s.doc)) { - egui::Window::new(crate::tl!("Blocks")) - .id(egui::Id::unique("Blocks")) - .open(open) - .default_size(vec2(640.0, 480.0)) - .min_size(vec2(420.0, 320.0)) - .resizable(true) - .show(ctx, |ui| body(ui, &doc, &v, &mut st, &mut cache, false, &mut act)); - } - let to_panel = matches!(act, Some(Act::ToPanel)); - let esc = ctx.input(|i| i.key_pressed(egui::Key::Escape)); - if !apply(app, &mut st, act, esc) && !to_panel { - *open = false; - } - if to_panel { - *open = false; - } - if !*open { - cache.entries.clear(); - } - ctx.data_mut(|d| { - d.insert_temp(state_id(), st); - d.insert_temp(cache_id(), cache); - }); -} - -#[cfg(test)] -mod tests { - use std::collections::HashSet; - use std::sync::Arc; - - use cadcraft_engine::doc::EntityKind; - use cadcraft_engine::geom::Vec2; - use cadcraft_engine::{Input, Session}; - use serde_json::json; - - use super::{PreviewCache, PreviewResult, State, ViewMode, grab_block}; - - fn ready(d: &cadcraft_doc::Drawing, name: &str) -> (cadcraft_render::DisplayList, cadcraft_geom::Bounds2) { - let PreviewResult::Ready(p) = super::build(d, name) else { - panic!("expected ready {name}"); - }; - ((*p.list).clone(), p.bounds) - } - use crate::{CadApp, Services}; - - /// Programmatic INSERT (including aliases and missing parameters) never opens a palette. - #[test] - fn insert_dispatch_distinguishes_programmatic_and_interactive_calls() { - for id in ["insert", "i", "ddinsert"] { - let mut app = CadApp::new(Session::new(), Services::default()); - app.ui.blocks_window = true; - for params in [serde_json::Value::Null, json!({})] { - assert!(app.run(id, params).is_err()); - assert!(app.ui.dialog.is_none()); - assert!(!app.ui.docking.layout.contains(&crate::docking::Panel::Blocks)); - } - app.start(id); - assert_eq!(app.ui.dialog.as_deref(), Some("blocks")); - app.ui.dialog = None; - assert!(app.cmdline(id).is_none()); - assert_eq!(app.ui.dialog.as_deref(), Some("blocks")); - app.ui.dialog = None; - assert!(app.cmdline(&format!("{id} {{}}")).is_some()); - assert!(app.ui.dialog.is_none()); - // Inline arguments (e.g. `insert Pin 10,20`) must not open the palette and lose arguments. - let _ = app.cmdline(&format!("{id} Pin 10,20")); - assert!(app.ui.dialog.is_none()); - assert!(app.session.running.is_some()); - } - let mut app = CadApp::new(Session::new(), Services::default()); - app.ui.blocks_window = true; - app.run("ui.dialog.blocks", serde_json::Value::Null).unwrap(); - assert_eq!(app.ui.dialog.as_deref(), Some("blocks")); - } - - /// Reuse unchanged data; refresh counts after selection, edits, undo and drawing switches. - #[test] - fn metadata_cache_follows_revision_selection_and_drawing() { - let mut app = CadApp::new(Session::new(), Services::default()); - for name in ["Bolt", "Pin"] { - let c = app.session.execute("circle", &json!({"center": [0, 0], "radius": 2})).unwrap(); - app.session.execute("block", &json!({"name": name, "base": [0, 0], "handles": [c["handle"]], "keep": "delete"})).unwrap(); - } - let mut st = State::default(); - let mut cache = PreviewCache::default(); - let first = super::view(&app, &mut st, &mut cache).unwrap(); - let again = super::view(&app, &mut st, &mut cache).unwrap(); - assert!(Arc::ptr_eq(&first.all, &again.all)); - assert_eq!(first.info.unwrap().1, 0); - app.run("insert", json!({"name": "Bolt", "at": [5, 5]})).unwrap(); - let edited = super::view(&app, &mut st, &mut cache).unwrap(); - assert!(!Arc::ptr_eq(&first.all, &edited.all)); - assert_eq!(edited.info.unwrap().1, 1); - st.selected = Some("Pin".into()); - let other = super::view(&app, &mut st, &mut cache).unwrap(); - assert!(Arc::ptr_eq(&edited.all, &other.all)); - assert_eq!(other.info.unwrap().1, 0); - st.selected = Some("Bolt".into()); - assert_eq!(super::view(&app, &mut st, &mut cache).unwrap().info.unwrap().1, 1); - app.session.undo().unwrap(); - assert_eq!(super::view(&app, &mut st, &mut cache).unwrap().info.unwrap().1, 0); - app.session.new_drawing(true); - let empty = super::view(&app, &mut st, &mut cache).unwrap(); - assert!(empty.all.is_empty()); - assert!(empty.selected.is_none()); - assert!(cache.references.is_none()); - } - - /// Ordinary thumbnails retain fills, motifs and curved boundaries, matching normal rendering. - #[test] - fn ordinary_hatches_keep_fills_and_patterns_in_previews() { - use cadcraft_doc::{Block, Drawing, Entity, Handle, Hatch}; - let mut d = Drawing::default(); - for (name, solid, bulge) in [("Solid", true, 0.0), ("Pattern", false, 0.0), ("Curved", true, 1.0)] { - let mut hatch: Hatch = serde_json::from_value(json!({ - "pattern": if solid { "SOLID" } else { "ANSI31" }, "solid": solid, - "loops": [] - })) - .unwrap(); - let mut vertices: Vec<_> = [Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)] - .into_iter() - .map(cadcraft_geom::PolyVertex::new) - .collect(); - vertices[0].bulge = bulge; - hatch.loops.push(cadcraft_doc::HatchLoop { vertices, outer: true, sources: Vec::new() }); - let mut b = Block::new(name); - b.entities.push(Entity::new(Handle(1), EntityKind::Hatch(hatch))); - d.blocks.insert(name.into(), Arc::new(b)); - let (list, bounds) = ready(&d, name); - assert!(!bounds.is_empty(), "{name}"); - assert!(!list.prims.is_empty(), "{name}"); - if solid { - assert!(!list.tris.is_empty(), "{name}: filled thumbnail, not just an outline"); - } else { - let polylines = list.prims.iter().filter(|p| p.kind == cadcraft_render::Kind::Polyline).count(); - assert!(polylines > 1, "pattern lines are retained"); - } - } - let normal = cadcraft_render::build_entities(&d, d.block("Solid").unwrap().entities.iter().map(|e| &**e), &Default::default()); - assert!(!normal.tris.is_empty(), "normal canvas rendering still fills hatches"); - } - - /// Escape in a filter, dialog or unrelated command must preserve the user's preference. - #[test] - fn unrelated_escape_preserves_repeat_preference() { - let mut app = CadApp::new(Session::new(), Services::default()); - let mut st = State { repeat: true, ..Default::default() }; - super::apply(&mut app, &mut st, None, true); - assert!(st.repeat); - app.session.start("line").unwrap(); - super::apply(&mut app, &mut st, None, true); - assert!(st.repeat); - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("line")); - } - - /// Feed the first and second click releases as egui reports them, plus drag-only gestures. - #[test] - fn double_click_grabs_only_once_in_either_mode() { - for grab_on_click in [false, true] { - let grabs = [(false, true, false), (false, true, true)] - .into_iter() - .filter(|&(drag, click, dbl)| super::should_grab(drag, click, dbl, grab_on_click)) - .count(); - assert_eq!(grabs, 1); - assert!(super::should_grab(true, false, false, grab_on_click)); - assert!(!super::should_grab(false, false, false, grab_on_click)); - } - } - - /// Verify block enumeration, reference counting and preview display-list generation. - #[test] - fn blocks_list_their_references_and_build_a_preview() { - let mut s = Session::new(); - let c = s.execute("circle", &json!({"center": [0, 0], "radius": 2})).unwrap(); - let h = c["handle"].as_str().unwrap().to_string(); - s.execute("block", &json!({"name": "Bolt", "base": [0, 0], "handles": [h], "keep": "delete"})).unwrap(); - s.execute("insert", &json!({"name": "Bolt", "at": [5, 5]})).unwrap(); - s.execute("insert", &json!({"name": "Bolt", "at": [9, 5]})).unwrap(); - let d = s.doc().unwrap(); - assert_eq!(super::names(d), ["Bolt"]); - assert_eq!(super::reference_count(d, "bolt"), 2); - let (list, bounds) = ready(d, "Bolt"); - assert!(!list.prims.is_empty()); - assert!((bounds.width() - 4.0).abs() < 1e-6); - } - - /// Verify view-mode index round-tripping and retention across scrolling. - #[test] - fn offscreen_previews_are_reused_and_view_modes_roundtrip() { - for (idx, mode) in [(0, ViewMode::List), (1, ViewMode::MediumIcons), (2, ViewMode::LargeIcons)] { - assert_eq!(ViewMode::from_index(idx), mode); - assert_eq!(mode.index(), idx); - } - let mut s = Session::new(); - for name in ["B1", "B2", "B3"] { - let c = s.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap(); - let h = c["handle"].as_str().unwrap().to_string(); - s.execute("block", &json!({"name": name, "base": [0, 0], "handles": [h], "keep": "delete"})).unwrap(); - } - let d = s.doc().unwrap(); - let mut cache = PreviewCache::default(); - cache.sync_revision(1, 1); - for name in ["B1", "B2", "B3"] { - let (list, bounds) = ready(d, name); - cache.insert(name.into(), PreviewResult::Ready(super::Preview { list: Arc::new(list), bounds }), &HashSet::new()); - } - assert_eq!(cache.len(), 3); - - // Only B2 remains visible; a return to B1/B3 reuses their cached results. - let visible: HashSet = ["B2".to_string()].into_iter().collect(); - cache.evict(&visible); - assert_eq!(cache.len(), 3); - assert!(cache.entries.contains_key("B2")); - assert!(cache.entries.contains_key("B1")); - assert!(cache.entries.contains_key("B3")); - - // A new drawing revision clears everything. - cache.sync_revision(1, 2); - assert!(cache.is_empty()); - } - - /// Verify that grabbing a block presets scale/rotation and places it on a single canvas click. - #[test] - fn grab_block_puts_it_in_hand_and_places_on_single_click() { - let mut app = CadApp::new(Session::new(), Services::default()); - let c = app.session.execute("circle", &json!({"center": [0, 0], "radius": 2})).unwrap(); - let h = c["handle"].as_str().unwrap().to_string(); - app.session.execute("block", &json!({"name": "Valve", "base": [0, 0], "handles": [h], "keep": "delete"})).unwrap(); - - let header = &mut app.session.doc_mut().unwrap().header; - header.set_i64("AUNITS", 3); - header.set_f64("ANGBASE", 0.5); - header.set_i64("ANGDIR", 1); - let st = State { scale_x: 2.0, scale_y: 1.5, rotation: 90.0, ..Default::default() }; - grab_block(&mut app, "Valve", &st); - - // The block is now in hand at the insertion point prompt, with live preview under the cursor. - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - assert_eq!(app.session.current_prompt().map(|p| p.message), Some("Specify insertion point".to_string())); - let preview = app.session.preview(Vec2::new(10.0, 20.0)); - assert_eq!(preview.len(), 1); - - // A single click on the canvas drops the block immediately without extra scale/rotation prompts. - app.session.input(Input::Point(Vec2::new(10.0, 20.0))).unwrap(); - assert!(app.session.running.is_none()); - - let d = app.session.doc().unwrap(); - let ins: Vec<_> = d - .model - .iter() - .filter_map(|e| match &e.kind { - EntityKind::Insert(i) => Some(i), - _ => None, - }) - .collect(); - assert_eq!(ins.len(), 1); - assert_eq!(ins[0].block, "Valve"); - assert!((ins[0].insert.x - 10.0).abs() < 1e-9 && (ins[0].insert.y - 20.0).abs() < 1e-9); - assert!((ins[0].scale.x - 2.0).abs() < 1e-9 && (ins[0].scale.y - 1.5).abs() < 1e-9); - assert!((ins[0].rotation.to_degrees() - 90.0).abs() < 1e-6); - } - - /// Verify that the scroll viewport only builds and retains previews for visible blocks. - #[test] - fn palette_loads_only_visible_blocks_in_scroll_viewport() { - let mut app = CadApp::new(Session::new(), Services::default()); - for i in 0..40 { - let c = app.session.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap(); - let h = c["handle"].as_str().unwrap().to_string(); - app.session.execute("block", &json!({"name": format!("BLK_{i:02}"), "base": [0, 0], "handles": [h], "keep": "delete"})).unwrap(); - } - let ctx = egui::Context::default(); - let screen = Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(300.0, 420.0))); - for mode in [ViewMode::LargeIcons, ViewMode::MediumIcons, ViewMode::List] { - ctx.data_mut(|d| { - let mut st = d.get_temp::(super::state_id()).unwrap_or_default(); - st.view_mode = mode; - d.insert_temp(super::state_id(), st); - }); - for _ in 0..6 { - let input = egui::RawInput { screen_rect: screen, ..Default::default() }; - let mut out = ctx.run_ui(input, |ui| super::panel(&mut app, ui)); - out.textures_delta.clear(); - } - let count = super::cached_preview_count(&ctx); - assert!(count > 0 && count < 40, "mode {mode:?} should keep only visible blocks in memory, got {count}"); - } - } - - #[test] - fn repeat_preference_only_arms_palette_insertions() { - let mut app = CadApp::new(Session::new(), Services::default()); - let circle = app.session.execute("circle", &json!({"center": [0, 0], "radius": 2})).unwrap(); - app.session.execute("block", &json!({"name": "Pin", "base": [0, 0], "handles": [circle["handle"]], "keep": "delete"})).unwrap(); - let mut st = State { repeat: true, ..Default::default() }; - - // A command-line insertion must finish after one placement despite the palette preference. - app.session.start("insert").unwrap(); - app.session.input(Input::Text("Pin".into())).unwrap(); - super::apply(&mut app, &mut st, None, false); - assert!(!st.repeating); - app.session.input(Input::Point(Vec2::new(10.0, 0.0))).unwrap(); - app.session.input(Input::Enter).unwrap(); // X scale - app.session.input(Input::Enter).unwrap(); // Y scale - app.session.input(Input::Text("0".into())).unwrap(); // Rotation - assert!(app.session.running.is_none()); - super::apply(&mut app, &mut st, None, true); - assert!(st.repeat); - - // Enabling Repeat after grabbing from the palette still arms repeated placement. - st.repeat = false; - super::apply(&mut app, &mut st, Some(super::Act::Grab("Pin".into())), false); - assert!(st.grabbed); - st.repeat = true; - super::apply(&mut app, &mut st, None, false); - app.session.input(Input::Point(Vec2::new(20.0, 0.0))).unwrap(); - assert!(app.session.running.is_some()); - assert!(st.repeating); - super::apply(&mut app, &mut st, None, true); - assert!(!st.grabbed); - assert!(app.session.running.is_none()); - } - - /// Verify repeat-placement re-grabbing, Escape cancellation, and cancellation when another command starts. - #[test] - fn repeat_placement_places_multiple_times_and_escape_cancels_it() { - let mut app = CadApp::new(Session::new(), Services::default()); - let c = app.session.execute("circle", &json!({"center": [0, 0], "radius": 2})).unwrap(); - let h = c["handle"].as_str().unwrap().to_string(); - app.session.execute("block", &json!({"name": "Pin", "base": [0, 0], "handles": [h], "keep": "delete"})).unwrap(); - - let mut st = State { repeat: true, ..Default::default() }; - - // Grab "Pin" with Repeat placement enabled. - super::apply(&mut app, &mut st, Some(super::Act::Grab("Pin".into())), false); - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - assert!(st.repeating); - - // First click places the first reference and keeps INSERT running for the next point. - app.session.input(Input::Point(Vec2::new(10.0, 0.0))).unwrap(); - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - super::apply(&mut app, &mut st, None, false); - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - assert_eq!(super::reference_count(app.session.doc().unwrap(), "Pin"), 1); - - // Second click places the second reference and still keeps INSERT running. - app.session.input(Input::Point(Vec2::new(20.0, 0.0))).unwrap(); - super::apply(&mut app, &mut st, None, false); - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - assert_eq!(super::reference_count(app.session.doc().unwrap(), "Pin"), 2); - - // Pressing Escape cancels the running INSERT and stops repeat placement. - app.session.cancel(); - super::apply(&mut app, &mut st, None, false); - assert!(app.session.running.is_none()); - assert!(!st.repeating); - assert!(!st.repeat); - - // Pressing Escape while INSERT is still running cancels both and unchecks repeat. - st.repeat = true; - super::apply(&mut app, &mut st, Some(super::Act::Grab("Pin".into())), false); - assert!(app.session.running.is_some()); - super::apply(&mut app, &mut st, None, true); - assert!(app.session.running.is_none()); - assert!(!st.repeating); - assert!(!st.repeat); - - // Starting another command (e.g. LINE) replaces INSERT and clears repeating so finishing LINE does not re-grab. - st.repeat = true; - super::apply(&mut app, &mut st, Some(super::Act::Grab("Pin".into())), false); - assert!(st.repeating); - app.session.start("line").unwrap(); - super::apply(&mut app, &mut st, None, false); - assert!(!st.repeating); - assert!(!st.repeat); - - // A transparent command only suspends the palette's INSERT: the palette keeps it. - app.session.cancel(); - st.repeat = true; - super::apply(&mut app, &mut st, Some(super::Act::Grab("Pin".into())), false); - app.session.start("'dist").unwrap(); - assert!(app.session.suspended.is_some()); - super::apply(&mut app, &mut st, None, false); - assert!(st.repeating); - assert!(st.grabbed); - - // An INSERT started by anything else (typed with an apostrophe, say) is not the palette's to repeat. - app.session.cancel(); - st.repeat = true; - super::apply(&mut app, &mut st, Some(super::Act::Grab("Pin".into())), false); - assert!(st.repeating); - app.session.cancel(); - app.session.start("insert").unwrap(); - super::apply(&mut app, &mut st, None, false); - assert!(!st.repeating); - assert!(!st.grabbed); - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - } - - /// Confirming a block name unchanged closes the editor and leaves a placement in progress alone. - #[test] - fn renaming_to_the_same_name_keeps_the_insert_running() { - let mut app = CadApp::new(Session::new(), Services::default()); - let circle = app.session.execute("circle", &json!({"center": [0, 0], "radius": 2})).unwrap(); - app.session.execute("block", &json!({"name": "Pin", "base": [0, 0], "handles": [circle["handle"]], "keep": "delete"})).unwrap(); - let mut st = State::default(); - super::apply(&mut app, &mut st, Some(super::Act::Grab("Pin".into())), false); - assert_eq!(app.session.current_prompt().map(|p| p.message), Some("Specify insertion point".to_string())); - st.rename = Some("Pin".into()); - super::apply(&mut app, &mut st, Some(super::Act::Rename("Pin".into(), "Pin".into())), false); - assert!(st.rename.is_none()); - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - assert_eq!(app.session.current_prompt().map(|p| p.message), Some("Specify insertion point".to_string())); - } - - /// Clicking Insert while the rename editor is open clears rename and starts insertion without cancelling it on the next frame. - #[test] - fn insert_while_renaming_clears_rename_and_keeps_insert() { - let mut app = CadApp::new(Session::new(), Services::default()); - let mut st = State { rename: Some("NewName".into()), ..Default::default() }; - super::apply(&mut app, &mut st, Some(super::Act::Grab("Pin".into())), false); - assert!(st.rename.is_none()); - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - - // On the next frame, INSERT is still running. - super::apply(&mut app, &mut st, None, false); - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - } - - /// Edits that change the drawing are refused while an INSERT the palette did not start is running. - #[test] - fn the_palette_refuses_edits_during_a_foreign_insert() { - let mut app = CadApp::new(Session::new(), Services::default()); - let circle = app.session.execute("circle", &json!({"center": [0, 0], "radius": 2})).unwrap(); - app.session.execute("block", &json!({"name": "Pin", "base": [0, 0], "handles": [circle["handle"]], "keep": "delete"})).unwrap(); - let mut st = State::default(); - app.session.start("insert").unwrap(); - for act in [super::Act::Rename("Pin".into(), "Pin2".into()), super::Act::Delete("Pin".into()), super::Act::Edit("Pin".into()), super::Act::Create] { - assert!(super::apply(&mut app, &mut st, Some(act), false)); - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - assert!(st.note.is_some()); - st.note = None; - } - assert!(app.session.doc().is_ok_and(|d| d.blocks.contains_key("Pin") && !d.blocks.contains_key("Pin2"))); - } - - /// A palette action cancels only the INSERT the palette started, which Esc ends even while a transparent command has it suspended. - #[test] - fn the_palette_cancels_only_its_own_insert() { - let mut app = CadApp::new(Session::new(), Services::default()); - let circle = app.session.execute("circle", &json!({"center": [0, 0], "radius": 2})).unwrap(); - app.session.execute("block", &json!({"name": "Pin", "base": [0, 0], "handles": [circle["handle"]], "keep": "delete"})).unwrap(); - let mut st = State::default(); - - // An INSERT started elsewhere survives a palette action. - app.session.start("insert").unwrap(); - super::cancel_pending_insert(&mut app, &mut st); - assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("insert")); - app.session.cancel(); - - // The palette's own INSERT ends with Esc, with a transparent command in front of it too. - super::apply(&mut app, &mut st, Some(super::Act::Grab("Pin".into())), false); - app.session.start("'dist").unwrap(); - assert!(app.session.suspended.is_some()); - super::apply(&mut app, &mut st, None, true); - assert!(app.session.running.is_none()); - assert!(app.session.suspended.is_none()); - } -} - -#[cfg(test)] -mod library_audit; diff --git a/crates/ui-egui/src/blockmgr/library_audit.rs b/crates/ui-egui/src/blockmgr/library_audit.rs deleted file mode 100644 index 5758e1257..000000000 --- a/crates/ui-egui/src/blockmgr/library_audit.rs +++ /dev/null @@ -1,139 +0,0 @@ -//! Opt-in measurement, never a required local fixture. -use super::*; -#[test] -#[ignore = "set CADCRAFT_LIBRARY and CADCRAFT_AUDIT_DIR for a local release audit"] -fn local_library_audit() { - let path = std::env::var("CADCRAFT_LIBRARY").expect("CADCRAFT_LIBRARY"); - let out = std::path::PathBuf::from(std::env::var("CADCRAFT_AUDIT_DIR").expect("CADCRAFT_AUDIT_DIR")); - std::fs::create_dir_all(&out).unwrap(); - let d = cadcraft_io::read(&std::fs::read(&path).unwrap(), &path).unwrap(); - let mut cache = PreviewCache::default(); - let mut csv = String::from("name;entities;status;build_us;primitives;vertices\n"); - for name in names(&d) { - let start = std::time::Instant::now(); - let result = build(&d, &name); - let elapsed = start.elapsed().as_micros(); - let (list, bounds) = match &result { - PreviewResult::Ready(p) => ((*p.list).clone(), p.bounds), - _ => (cadcraft_render::DisplayList::default(), Bounds2::EMPTY), - }; - let status = if d.block(&name).unwrap().entities.is_empty() { - "empty_definition" - } else { - match &result { - PreviewResult::Ready(_) => "ready", - PreviewResult::Empty => "no_visible_content", - PreviewResult::Unavailable(reason) => reason.message(), - } - }; - csv.push_str(&format!( - "{name};{};{status};{elapsed};{};{}\n", - d.block(&name).unwrap().entities.len(), - list.prims.len(), - list.verts.len() + list.tris.len() - )); - if ["GMAT_PAC_VIESSMANN_PURPLE", "DIV_01_LEGENDE_ACCESSOIRES", "TUY_DEPART_DIRECT_POMPE_DOUBLE_ENERGIE"].contains(&name.as_str()) { - let view = cadcraft_render::raster::View::fit(&bounds, 512, 512, 0.1); - cadcraft_render::raster::render(&list, &view, &Default::default()).unwrap().save_png(out.join(format!("{name}.png"))).unwrap(); - } - cache.insert(name, result, &HashSet::new()); - } - std::fs::write(out.join("library.csv"), csv).unwrap(); - let initial_bytes = cache.estimated_bytes().unwrap(); - // Exercise the real tile path in both scroll directions, twelve visible tiles per frame. - let ctx = egui::Context::default(); - let all = names(&d); - let mut rebuilds = 0; - let mut paint_times = Vec::new(); - for page in all.chunks(12).chain(all.chunks(12).rev()) { - let mut frame = FrameBuilds { visible: HashSet::new(), builds_left: MAX_BUILDS_PER_FRAME, started: web_time::Instant::now() }; - let input = egui::RawInput { screen_rect: Some(Rect::from_min_size(egui::Pos2::ZERO, vec2(800.0, 600.0))), ..Default::default() }; - let start = std::time::Instant::now(); - let mut output = ctx.run_ui(input, |ui| { - for row in page.chunks(4) { - ui.horizontal(|ui| { - for name in row { - draw_block_item(ui, &d, name, false, ViewMode::LargeIcons, vec2(150.0, 112.0), (&mut cache, &mut frame)); - } - }); - } - }); - let _meshes = ctx.tessellate(output.shapes, output.pixels_per_point); - paint_times.push(start.elapsed().as_micros()); - output.textures_delta.clear(); - rebuilds += MAX_BUILDS_PER_FRAME - frame.builds_left; - cache.evict(&frame.visible); - } - paint_times.sort_unstable(); - std::fs::write( - out.join("cache.txt"), - format!( - "initial_results={}\nestimated_bytes={}\nscroll_rebuilds={}\ncached_frame_p50_us={}\ncached_frame_max_us={}\n", - cache.len(), - initial_bytes, - rebuilds, - paint_times[paint_times.len() / 2], - paint_times.last().unwrap() - ), - ) - .unwrap(); - let mut warm = String::from("name;build_us\n"); - for name in &all { - let start = std::time::Instant::now(); - let _result = build(&d, name); - warm.push_str(&format!("{name};{}\n", start.elapsed().as_micros())); - } - std::fs::write(out.join("warm.csv"), warm).unwrap(); - - // Render actual palette widgets, including names, clipping, theme and status text. - let mut session = cadcraft_engine::Session::empty(); - session.open_drawing(d.clone(), "Local audit", None); - let app = CadApp::new(session, crate::Services::default()); - let mut state = State { filter: "PAC".into(), view_mode: ViewMode::LargeIcons, ..Default::default() }; - let v = view(&app, &mut state, &mut cache).unwrap(); - let mut harness = egui_kittest::Harness::builder().with_size(vec2(1000.0, 760.0)).wgpu().build_ui_state( - |ui, data: &mut (State, PreviewCache)| { - crate::theme::apply(ui.ctx(), egui::Theme::Dark, false); - let mut action = None; - body(ui, &d, &v, &mut data.0, &mut data.1, false, &mut action); - }, - (state, cache), - ); - harness.run_steps(8); - harness.render().unwrap().save(out.join("palette.png")).unwrap(); - - let mut status_drawing = Drawing::default(); - let mut status_cache = PreviewCache::default(); - for name in ["Ready", "Empty", "Invisible", "Refused", "Pending"] { - let mut b = cadcraft_doc::Block::new(name); - if name != "Empty" { - let mut e = cadcraft_doc::Entity::new( - cadcraft_doc::Handle(1), - EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(2.0, 1.0, 0.0) }), - ); - e.common.visible = name != "Invisible"; - b.entities.push(e); - } - status_drawing.blocks.insert(name.into(), Arc::new(b)); - if name != "Pending" { - let result = if name == "Refused" { PreviewResult::Unavailable(PreviewFailure::Input) } else { build(&status_drawing, name) }; - status_cache.insert(name.into(), result, &HashSet::new()); - } - } - let mut statuses = egui_kittest::Harness::builder().with_size(vec2(1000.0, 200.0)).wgpu().build_ui_state( - |ui, cache: &mut PreviewCache| { - crate::i18n::with_language("fr", || { - crate::theme::apply(ui.ctx(), egui::Theme::Dark, false); - let mut frame = FrameBuilds { visible: HashSet::new(), builds_left: 0, started: web_time::Instant::now() }; - ui.horizontal(|ui| { - for name in ["Ready", "Empty", "Invisible", "Refused", "Pending"] { - draw_block_item(ui, &status_drawing, name, false, ViewMode::LargeIcons, vec2(180.0, 112.0), (cache, &mut frame)); - } - }); - }) - }, - status_cache, - ); - statuses.run_steps(2); - statuses.render().unwrap().save(out.join("statuses.png")).unwrap(); -} diff --git a/crates/ui-egui/src/blockmgr/preview.rs b/crates/ui-egui/src/blockmgr/preview.rs deleted file mode 100644 index fed347334..000000000 --- a/crates/ui-egui/src/blockmgr/preview.rs +++ /dev/null @@ -1,563 +0,0 @@ -//! Synchronous thumbnail preflight. Input, expansion/evaluation work and retained output have -//! separate units. Bounds sampling is charged before bounds; rendering is planned at thumbnail -//! tolerance before allocating curve buffers. No drawing/block names affect these limits. -use super::{Arc, Bounds2, Drawing, EntityKind, Preview, Vec2}; -use cadcraft_doc::{Entity, Insert}; -use cadcraft_geom::{Polyline, Spline}; - -// Preserve the existing input/expansion caps. Curve work now counts basis-loop steps instead -// of fractions of a hypothetical 4000-point tessellation. Four million steps admit hundreds -// of ordinary cubic curves while bounding high degrees independently of their input length. -const MAX_INPUT: usize = 32_768; -const MAX_WORK: usize = 4_000_000; -const MAX_PRIMITIVES: usize = 32_768; -const MAX_VERTICES: usize = 262_144; -// Largest tile has a 90-pixel-high drawing area; 320 samples across its fitted extent also -// cover larger UI scaling factors without retaining full-canvas curve detail. -const REFERENCE_PIXELS: f64 = 320.0; - -#[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(super) enum PreviewFailure { - Input, - Computation, - Output, - Invalid, - MissingReference, -} -impl PreviewFailure { - /// The text shown in the palette for this refusal. - pub(super) fn message(self) -> &'static str { - match self { - Self::Input => crate::tl!("Excessive preview input"), - Self::Computation => crate::tl!("Excessive preview computation"), - Self::Output => crate::tl!("Excessive preview output"), - Self::Invalid => crate::tl!("Invalid preview data"), - Self::MissingReference => crate::tl!("Missing block reference"), - } - } -} -#[derive(Clone)] -pub(super) enum PreviewResult { - Ready(Preview), - Empty, - Unavailable(PreviewFailure), -} -type Checked = Result; - -#[derive(Clone, Copy, Default, Debug)] -struct Budget { - input_items: usize, - text_bytes: usize, - metadata_bytes: usize, - expanded: usize, - computation_steps: usize, - vertices: usize, -} -/// Adds `b` to `a` with checked arithmetic, failing with `failure` on overflow or past `limit`. -fn add(a: &mut usize, b: usize, limit: usize, failure: PreviewFailure) -> Checked<()> { - *a = a.checked_add(b).filter(|v| *v <= limit).ok_or(failure)?; - Ok(()) -} -impl Budget { - /// Charges `n` input items. - fn items(&mut self, n: usize) -> Checked<()> { - add(&mut self.input_items, n, MAX_INPUT, PreviewFailure::Input) - } - /// Charges `n` bytes of text. - fn text(&mut self, n: usize) -> Checked<()> { - add(&mut self.text_bytes, n, MAX_INPUT, PreviewFailure::Input) - } - /// Charges `n` bytes of metadata (style names, column heights). - fn meta(&mut self, n: usize) -> Checked<()> { - if n > MAX_INPUT { - return Err(PreviewFailure::Input); - } - add(&mut self.metadata_bytes, n, 1024 * 1024, PreviewFailure::Input) - } - /// Charges `n` computation steps. - fn work(&mut self, n: usize) -> Checked<()> { - add(&mut self.computation_steps, n, MAX_WORK, PreviewFailure::Computation) - } - /// Charges `n` output vertices. - fn points(&mut self, n: usize) -> Checked<()> { - add(&mut self.vertices, n, MAX_VERTICES, PreviewFailure::Output) - } - /// Charges `n` expanded primitives. - fn expand(&mut self, n: usize) -> Checked<()> { - add(&mut self.expanded, n, MAX_PRIMITIVES, PreviewFailure::Computation) - } - /// Multiplies what was charged since `before` by `copies`, as if the same content were repeated. - fn copies(&mut self, before: Self, copies: usize) -> Checked<()> { - let extra = copies.checked_sub(1).ok_or(PreviewFailure::Invalid)?; - let delta = |after: usize, prior: usize| after.checked_sub(prior).and_then(|v| v.checked_mul(extra)).ok_or(PreviewFailure::Computation); - self.items(delta(self.input_items, before.input_items)?)?; - self.text(delta(self.text_bytes, before.text_bytes)?)?; - let metadata = delta(self.metadata_bytes, before.metadata_bytes)?; - add(&mut self.metadata_bytes, metadata, 1024 * 1024, PreviewFailure::Input)?; - self.work(delta(self.computation_steps, before.computation_steps)?)?; - self.points(delta(self.vertices, before.vertices)?)?; - self.expand(delta(self.expanded, before.expanded)?) - } -} -/// Fails with `Invalid` unless every value is finite. -fn finite(values: impl IntoIterator) -> Checked<()> { - if values.into_iter().all(f64::is_finite) { Ok(()) } else { Err(PreviewFailure::Invalid) } -} -/// Charges the input size of an MText (contents, style, column metadata). -fn mtext_input(m: &cadcraft_doc::MText, b: &mut Budget) -> Checked<()> { - b.text(m.contents.len())?; - b.meta(m.style.len())?; - if let Some(c) = &m.columns { - b.items(c.heights.len())?; - b.items(usize::from(c.count))?; - finite(c.heights.iter().copied())?; - } - finite([m.insert.x, m.insert.y, m.height, m.width, m.rotation]) -} -/// Charges the input size of an INSERT (attributes and array metadata). -fn insert_input(ins: &Insert, b: &mut Budget) -> Checked<()> { - b.meta(ins.block.len())?; - b.items(ins.attribs.len())?; - finite([ins.insert.x, ins.insert.y, ins.scale.x, ins.scale.y, ins.rotation, ins.col_spacing, ins.row_spacing])?; - for a in &ins.attribs { - b.meta(a.tag.len())?; - b.meta(a.prompt.len())?; - b.text(a.text.value.len())?; - b.meta(a.text.style.len())?; - b.meta(a.props.layer.as_ref().map_or(0, String::len))?; - b.meta(a.props.linetype.as_ref().map_or(0, String::len))?; - if let Some(m) = &a.multiline { - b.meta(m.read_as.len())?; - mtext_input(&m.mtext, b)?; - } - } - Ok(()) -} -/// Charges the cost of a spline, following the geometry sampling plan at tolerance `tol`. -fn spline_cost(s: &Spline, tol: Option, b: &mut Budget) -> Checked<()> { - for n in [s.control.len(), s.fit.len(), s.knots.len(), s.weights.len()] { - b.items(n)?; - } - finite(s.control.iter().chain(&s.fit).flat_map(|v| [v.x, v.y]).chain(s.knots.iter().copied()).chain(s.weights.iter().copied()))?; - if !s.is_valid() { - // The renderer draws an invalid spline as its control polygon (no evaluation). - if tol.is_some() { - b.points(s.control.len())?; - } - return Ok(()); - } - let (lo, hi) = s.domain(); - if hi <= lo || !(hi - lo).is_finite() { - return Err(PreviewFailure::Invalid); - } - let samples = if let Some(tol) = tol { s.sample_count(tol).checked_add(1).ok_or(PreviewFailure::Computation)? } else { s.bounds_sample_count() }; - // Basis recursion is triangular in degree, then degree+1 weighted controls; span search - // on a validated monotone knot vector is logarithmic. Include input scans separately. - let degree = s.degree; - let per_eval = degree - .checked_mul(degree + 1) - .and_then(|v| v.checked_div(2)) - .and_then(|v| v.checked_add(degree + 1)) - .and_then(|v| v.checked_add(usize::BITS as usize - s.control.len().leading_zeros() as usize + 1)) - .ok_or(PreviewFailure::Computation)?; - b.work(samples.checked_mul(per_eval).ok_or(PreviewFailure::Computation)?)?; - b.work(s.knots.len().checked_add(s.control.len()).ok_or(PreviewFailure::Computation)?)?; - if tol.is_some() { - b.points(samples)?; - } - Ok(()) -} -/// Charges the cost of a polyline, counting arc and wide-segment expansion like the renderer. -fn polyline_cost(vertices: &[cadcraft_geom::PolyVertex], closed: bool, wide: bool, tol: Option, b: &mut Budget) -> Checked<()> { - b.items(vertices.len())?; - finite(vertices.iter().flat_map(|v| [v.p.x, v.p.y, v.bulge, v.start_width, v.end_width]))?; - if let Some(tol) = tol { - // Input is bounded before cloning/segment conversion. Segment uses arc_segments, exactly - // as the renderer; count both ends conservatively (the joined line drops duplicates). - let p = Polyline { vertices: vertices.to_vec(), closed }; - for seg in p.segments() { - let points = seg.tessellation_points(tol); - b.work(points.checked_mul(if wide { 2 } else { 1 }).ok_or(PreviewFailure::Computation)?)?; - b.points(points.checked_mul(if wide { 7 } else { 1 }).ok_or(PreviewFailure::Output)?)?; - } - } - Ok(()) -} -/// Charges the input, computation and output cost of one entity before it is built. -fn entity_cost(e: &Entity, tol: Option, b: &mut Budget) -> Checked<()> { - b.expand(1)?; - b.meta(e.common.layer.len())?; - b.meta(e.common.linetype.len())?; - b.meta(e.common.plot_style.len())?; - b.items(e.common.xdata.len())?; - b.items(e.common.anno_scales.len())?; - for scale in &e.common.anno_scales { - b.meta(scale.name.len())?; - } - for t in &e.common.xdata { - b.meta(t.value.len())?; - } - match &e.kind { - EntityKind::Spline(s) => spline_cost(s, tol, b)?, - EntityKind::LwPolyline(p) => { - if p.vertices.len() > MAX_INPUT { - return Err(PreviewFailure::Input); - } - finite([p.const_width, p.elevation])?; - polyline_cost(&p.vertices, p.closed, p.const_width > 0.0 || p.vertices.iter().any(|v| v.start_width > 0.0 || v.end_width > 0.0), tol, b)?; - } - EntityKind::Hatch(h) => { - b.items(h.loops.len())?; - b.items(h.pattern_lines.len())?; - b.meta(h.pattern.len())?; - for l in &h.pattern_lines { - b.items(l.dashes.len())?; - } - for l in &h.loops { - b.items(l.sources.len())?; - polyline_cost(&l.vertices, true, false, tol, b)?; - } - } - EntityKind::Text(t) => { - b.text(t.value.len())?; - b.meta(t.style.len())?; - finite([t.insert.x, t.insert.y, t.height, t.rotation])?; - } - EntityKind::MText(m) => mtext_input(m, b)?, - EntityKind::AttDef(a) => { - b.meta(a.tag.len())?; - b.meta(a.prompt.len())?; - b.text(a.text.value.len())?; - b.meta(a.text.style.len())?; - if let Some(m) = &a.multiline { - b.meta(m.read_as.len())?; - mtext_input(&m.mtext, b)?; - } - } - EntityKind::Insert(i) => insert_input(i, b)?, - EntityKind::Polyline3d(p) => { - b.items(p.points.len())?; - finite(p.points.iter().flat_map(|v| [v.x, v.y, v.z]))?; - if tol.is_some() { - b.points(p.points.len())?; - } - } - EntityKind::Leader(l) => { - b.items(l.vertices.len())?; - b.meta(l.style.len())?; - if tol.is_some() { - b.points(l.vertices.len())?; - } - } - EntityKind::Wipeout(w) => { - b.items(w.boundary.len())?; - // Slab triangulation can revisit every edge per vertex and crossing cut. Preserve - // a conservative pre-allocation bound; these are not tolerance-dependent arcs. - let n = w.boundary.len(); - b.work(n.checked_mul(n).and_then(|v| v.checked_mul(16)).ok_or(PreviewFailure::Computation)?)?; - if tol.is_some() { - b.points(n.checked_mul(n).and_then(|v| v.checked_mul(6)).ok_or(PreviewFailure::Output)?)?; - } - } - EntityKind::MLeader(m) => { - b.items(m.leaders.len())?; - for l in &m.leaders { - b.items(l.len())?; - if m.spline && l.len() > 1 { - // from_fit_points solves a banded fit before its fixed-tolerance tessellation. - // Keep its previous 4000 sample bound until that path exposes a plan. - b.work(l.len().checked_mul(l.len()).and_then(|v| v.checked_add(4_001 * 16)).ok_or(PreviewFailure::Computation)?)?; - if tol.is_some() { - b.points(4_001)?; - } - } else if tol.is_some() { - b.points(l.len().checked_add(1).ok_or(PreviewFailure::Output)?)?; - } - } - if let Some(t) = &m.text { - mtext_input(t, b)?; - } - if let Some(i) = &m.block { - insert_input(i, b)?; - } - } - EntityKind::Table(t) => table_cost(t, tol, b)?, - EntityKind::Dimension(dm) => { - b.text(dm.text.len())?; - b.meta(dm.style.len())?; - b.items(dm.overrides.len())?; - b.items(dm.assoc.len())?; - b.items(dm.marks.breaks.len())?; - for (key, value) in &dm.overrides { - b.text(key.len())?; - json_input(value, b, 0)?; - } - if let Some(inspect) = &dm.marks.inspect { - b.text(inspect.label.len())?; - b.text(inspect.rate.len())?; - } - } - EntityKind::MLine(m) => { - b.items(m.vertices.len())?; - b.items(m.def.elements.len())?; - b.work(m.vertices.len().checked_mul(m.def.elements.len()).and_then(|v| v.checked_mul(4097)).ok_or(PreviewFailure::Computation)?)?; - } - EntityKind::Unknown(u) => { - b.items(u.tags.len())?; - for t in &u.tags { - b.text(t.value.len())?; - } - } - EntityKind::Tolerance(t) => { - b.text(t.text.len())?; - b.meta(t.style.len())?; - } - EntityKind::Region(r) => { - b.items(r.loops.len())?; - for l in &r.loops { - b.items(l.sources.len())?; - polyline_cost(&l.vertices, true, false, tol, b)?; - } - } - EntityKind::Line(l) => finite([l.a.x, l.a.y, l.a.z, l.b.x, l.b.y, l.b.z])?, - EntityKind::Circle(c) => { - finite([c.center.x, c.center.y, c.radius])?; - if let Some(tol) = tol { - let n = cadcraft_geom::arc_segments(c.radius, cadcraft_geom::TAU, tol) + 1; - b.work(n)?; - b.points(n)?; - } - } - EntityKind::Arc(a) => { - finite([a.center.x, a.center.y, a.radius, a.start, a.end])?; - if let Some(tol) = tol { - let n = cadcraft_geom::arc_segments(a.radius, cadcraft_geom::ccw_sweep(a.start, a.end), tol) + 1; - b.work(n)?; - b.points(n)?; - } - } - EntityKind::Ellipse(e) => { - finite([e.center.x, e.center.y, e.major.x, e.major.y, e.ratio, e.start, e.end])?; - if let Some(tol) = tol { - let n = cadcraft_geom::arc_segments(e.major.xy().len(), cadcraft_geom::ccw_sweep(e.start, e.end), tol).max(8) + 1; - b.work(n)?; - b.points(n)?; - } - } - _ => {} - } - Ok(()) -} - -/// Charges the cost of a table: its cells, text and grid lines. -fn table_cost(t: &cadcraft_doc::Table, tol: Option, b: &mut Budget) -> Checked<()> { - b.items(t.row_heights.len())?; - b.items(t.col_widths.len())?; - b.items(t.cells.len())?; - let cells = t.row_heights.len().checked_mul(t.col_widths.len()).ok_or(PreviewFailure::Input)?; - b.items(cells)?; - b.meta(t.style.len())?; - for s in &t.row_styles { - b.text(s.len())?; - } - finite(t.row_heights.iter().chain(&t.col_widths).copied())?; - for row in &t.cells { - b.items(row.len())?; - for c in row { - b.text(c.text.len())?; - b.meta(c.style.len())?; - b.text(c.formula.as_ref().map_or(0, String::len))?; - if let Some((r, col)) = c.merged { - b.work( - (r as usize).min(t.row_heights.len()).checked_mul((col as usize).min(t.col_widths.len())).ok_or(PreviewFailure::Computation)?, - )?; - } - } - } - if let Some(br) = &t.breaks { - b.items(br.heights.len())?; - b.items(br.offsets.len())?; - } - if let Some(link) = &t.data_link { - b.meta(link.path.len())?; - } - // Planning visits each source row and at most three repeated label rows per part. Bound - // that small allocation before calling the document's actual table-breaking rules. - b.work(t.row_heights.len().checked_add(3 * cadcraft_doc::MAX_TABLE_PARTS).ok_or(PreviewFailure::Computation)?)?; - let mut drawn_cells = 0usize; - for part in t.parts() { - for row in part.rows { - drawn_cells = drawn_cells.checked_add(t.col_widths.len()).ok_or(PreviewFailure::Computation)?; - if let Some(row) = t.cells.get(row) { - for cell in row { - b.work(cell.text.len())?; - } - } - } - } - b.work(drawn_cells.checked_mul(8).ok_or(PreviewFailure::Computation)?)?; - if tol.is_some() { - b.points(drawn_cells.checked_mul(14).ok_or(PreviewFailure::Output)?)?; - } - - Ok(()) -} - -/// Charges the size of a JSON value, bounding its nesting at `depth`. -fn json_input(value: &serde_json::Value, b: &mut Budget, depth: usize) -> Checked<()> { - if depth >= cadcraft_doc::MAX_BLOCK_DEPTH { - return Err(PreviewFailure::Input); - } - b.items(1)?; - match value { - serde_json::Value::String(s) => b.text(s.len())?, - serde_json::Value::Array(a) => { - b.items(a.len())?; - for v in a { - json_input(v, b, depth + 1)?; - } - } - serde_json::Value::Object(o) => { - b.items(o.len())?; - for (k, v) in o { - b.text(k.len())?; - json_input(v, b, depth + 1)?; - } - } - _ => {} - } - Ok(()) -} - -// Each pass visits at most MAX_PRIMITIVES entities/copies, even without memoization. Arrays -// measure one child then reserve the remaining copies' costs before any expansion happens. -/// Bounds of block `name` including nested inserts; `stack` detects cycles and limits depth. -fn preview_block_bounds(d: &Drawing, name: &str, stack: &mut Vec, tol: Option, budget: &mut Budget) -> Checked { - if stack.len() >= cadcraft_doc::MAX_BLOCK_DEPTH || stack.iter().any(|n| n.eq_ignore_ascii_case(name)) { - return Err(PreviewFailure::Computation); - } - let block = d.block(name).ok_or(PreviewFailure::MissingReference)?; - budget.meta(name.len())?; - budget.meta(block.description.len())?; - budget.items(block.entities.len())?; - stack.push(name.to_string()); - let mut bounds = Bounds2::EMPTY; - for e in block.entities.iter() { - entity_cost(e, tol, budget)?; - let mut local = match &e.kind { - EntityKind::Insert(i) => insert_bounds(d, i, stack, tol, budget)?, - EntityKind::Dimension(dm) => { - let child = match &dm.block { - Some(n) => preview_block_bounds(d, n, stack, tol, budget)?, - None => Bounds2::EMPTY, - }; - if tol.is_some() { - child - } else { - let mut dm = dm.clone(); - dm.block = None; - child.union(&cadcraft_doc::entity_bounds(d, &Entity { kind: EntityKind::Dimension(dm), ..(**e).clone() }, stack.len())) - } - } - EntityKind::MLeader(ml) => { - let child = match &ml.block { - Some(i) => insert_bounds(d, i, stack, tol, budget)?, - None => Bounds2::EMPTY, - }; - if tol.is_some() { - child - } else { - let mut ml = ml.clone(); - ml.block = None; - child.union(&cadcraft_doc::entity_bounds(d, &Entity { kind: EntityKind::MLeader(ml), ..(**e).clone() }, stack.len())) - } - } - _ if tol.is_some() => Bounds2::EMPTY, - _ => cadcraft_doc::entity_bounds(d, e, stack.len()), - }; - if !local.is_empty() { - finite([local.min.x, local.min.y, local.max.x, local.max.y, local.width(), local.height()])?; - // Match hidden geometry in the renderer; preflight still accounts for its input. - if !e.common.visible || d.is_hidden_object(e.handle) { - local = Bounds2::EMPTY; - } - bounds = bounds.union(&local); - } - } - stack.pop(); - Ok(bounds) -} -/// Bounds of one INSERT, covering every copy of an array. -fn insert_bounds(d: &Drawing, i: &Insert, stack: &mut Vec, tol: Option, b: &mut Budget) -> Checked { - let copies = (i.cols.max(1) as usize).checked_mul(i.rows.max(1) as usize).ok_or(PreviewFailure::Computation)?; - b.expand(copies)?; - let target = d.block(&i.block).ok_or(PreviewFailure::MissingReference)?; - // Rendering searches the definition for each attribute tag before applying its properties. - b.work(i.attribs.len().checked_mul(target.entities.len()).ok_or(PreviewFailure::Computation)?)?; - let base = target.base.xy(); - finite([base.x, base.y])?; - let xf = i.transform(base); - let scale = xf.scale_factor(); - if !scale.is_finite() || scale <= 0.0 { - return Err(PreviewFailure::Invalid); - } - let before = *b; - let inner = preview_block_bounds(d, &i.block, stack, tol.map(|t| t / scale.max(1e-12)), b)?; - b.copies(before, copies)?; - let mut bounds = if inner.is_empty() { inner } else { Bounds2::from_points(inner.corners().map(|p| xf.apply(p))) }; - if !bounds.is_empty() { - // All four array corner offsets, including mixed signs/rotated arrays. - for (c, r) in [(i.cols.saturating_sub(1), 0), (0, i.rows.saturating_sub(1)), (i.cols.saturating_sub(1), i.rows.saturating_sub(1))] { - let offset = Vec2::new(i.col_spacing * f64::from(c), i.row_spacing * f64::from(r)).rotate(i.rotation); - bounds = bounds.union(&Bounds2::from_points(inner.corners().map(|p| xf.apply(p) + offset))); - } - } - if tol.is_none() && !i.attribs.is_empty() { - let mut attrs = i.clone(); - attrs.block.clear(); - let e = Entity::new(cadcraft_doc::Handle(0), EntityKind::Insert(attrs)); - bounds = bounds.union(&cadcraft_doc::entity_bounds(d, &e, stack.len())); - } - Ok(bounds) -} - -/// Builds the preview of block `name`; never panics, refusals are returned as `Unavailable`. -pub(super) fn build(d: &Drawing, name: &str) -> PreviewResult { - match build_checked(d, name) { - Ok(v) => v, - Err(e) => PreviewResult::Unavailable(e), - } -} -/// The fallible body of [`build`]. -fn build_checked(d: &Drawing, name: &str) -> Checked { - let block = d.block(name).ok_or(PreviewFailure::MissingReference)?; - let mut budget = Budget::default(); - let bounds = preview_block_bounds(d, name, &mut Vec::new(), None, &mut budget)?; - if bounds.is_empty() { - return Ok(PreviewResult::Empty); - } - let size = bounds.width().max(bounds.height()).max(1e-9); - let opts = cadcraft_render::Options { - tolerance: size / REFERENCE_PIXELS, - min_dash: size / (REFERENCE_PIXELS / 2.0), - view_height: size, - hatch_budget: Some(Arc::new(cadcraft_render::HatchBudget::new(250_000))), - ..Default::default() - }; - // Keep bounds and render work in one allowance, but do not charge the same input twice. - budget.metadata_bytes = 0; - budget.input_items = 0; - budget.text_bytes = 0; - budget.expanded = 0; - preview_block_bounds(d, name, &mut Vec::new(), Some(opts.tolerance), &mut budget)?; - let list = cadcraft_render::build_entities_limited(d, block.entities.iter().map(|e| &**e), &opts, MAX_PRIMITIVES, MAX_VERTICES) - .ok_or(PreviewFailure::Output)?; - if opts.hatch_budget.as_ref().is_some_and(|b| b.failed()) { - return Err(PreviewFailure::Computation); - } - finite(list.verts.iter().chain(&list.tris).flat_map(|v| [v.x, v.y]))?; - if list.prims.is_empty() { Ok(PreviewResult::Empty) } else { Ok(PreviewResult::Ready(Preview { list: Arc::new(list), bounds })) } -} - -#[cfg(test)] -mod tests; diff --git a/crates/ui-egui/src/blockmgr/preview/tests.rs b/crates/ui-egui/src/blockmgr/preview/tests.rs deleted file mode 100644 index c7e288b6d..000000000 --- a/crates/ui-egui/src/blockmgr/preview/tests.rs +++ /dev/null @@ -1,263 +0,0 @@ -use super::*; -use crate::blockmgr::{ - FrameBuilds, MAX_BUILDS_PER_FRAME, MAX_CACHE_BYTES, MAX_CACHE_RESULTS, PreviewCache, State, ViewMode, draw_block_item, grab_block, - reference_count, retained_bytes, -}; -use crate::{CadApp, Services}; -use cadcraft_doc::{Block, Handle, Table, TableCell}; -use cadcraft_engine::{Input, Session}; -use cadcraft_geom::{PolyVertex, Vec3}; -use egui::vec2; -use serde_json::json; -use std::collections::HashSet; - -fn drawing(kind: EntityKind, count: usize) -> Drawing { - let mut d = Drawing::default(); - let mut block = Block::new("Synthetic"); - for i in 0..count { - block.entities.push(Entity::new(Handle(i as u64 + 1), kind.clone())); - } - d.blocks.insert(block.name.clone(), Arc::new(block)); - d -} -fn simple() -> Spline { - Spline::from_control(vec![Vec2::ZERO, Vec2::new(1.0, 0.0), Vec2::new(1.0, 1.0), Vec2::new(2.0, 1.0)], 3) -} -fn line() -> EntityKind { - EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(2.0, 1.0, 0.0) }) -} -fn insert(name: &str) -> Insert { - serde_json::from_value(json!({"block":name,"insert":[0,0,0],"scale":[1,1,1],"attribs":[]})).unwrap() -} -fn assert_failure(d: &Drawing, reason: PreviewFailure) { - assert!(matches!(build(d, "Synthetic"), PreviewResult::Unavailable(r) if r == reason), "expected {reason:?}"); -} - -#[test] -fn hundreds_of_simple_splines_preview_but_fewer_expensive_splines_are_bounded() { - let d = drawing(EntityKind::Spline(simple()), 500); - assert!(matches!(build(&d, "Synthetic"), PreviewResult::Ready(_))); - let expensive = Spline::from_control((0..65).map(|i| Vec2::new(i as f64, (i % 2) as f64 * 10.0)).collect(), 32); - assert_failure(&drawing(EntityKind::Spline(expensive), 10), PreviewFailure::Computation); -} - -#[test] -fn curves_and_wide_polylines_use_thumbnail_tolerance() { - for (count, width) in [(128, 0.0), (16, 2.0)] { - let p = cadcraft_doc::LwPolyline { - vertices: (0..count).map(|i| PolyVertex { bulge: 1.0, ..PolyVertex::new(Vec2::new(i as f64, 0.0)) }).collect(), - closed: false, - const_width: width, - elevation: 0.0, - plinegen: false, - }; - let d = drawing(EntityKind::LwPolyline(p), 1); - let PreviewResult::Ready(p) = build(&d, "Synthetic") else { - panic!("ordinary curved polyline refused"); - }; - assert!(p.list.verts.len() + p.list.tris.len() < MAX_VERTICES); - if width > 0.0 { - assert!(!p.list.tris.is_empty()); - } - } -} - -#[test] -fn hostile_text_mtext_attributes_tables_and_metadata_fail_before_bounds() { - let text: cadcraft_doc::Text = serde_json::from_value(json!({"insert":[0,0,0],"height":1,"value":"x".repeat(MAX_INPUT+1)})).unwrap(); - assert_failure(&drawing(EntityKind::Text(text.clone()), 1), PreviewFailure::Input); - let mut m: cadcraft_doc::MText = serde_json::from_value(json!({"insert":[0,0,0],"height":1,"contents":text.value})).unwrap(); - assert_failure(&drawing(EntityKind::MText(m.clone()), 1), PreviewFailure::Input); - m.contents.clear(); - m.columns = Some(cadcraft_doc::MTextColumns { heights: vec![1.0; MAX_INPUT + 1], ..Default::default() }); - assert_failure(&drawing(EntityKind::MText(m), 1), PreviewFailure::Input); - let mut ins = insert("Missing"); - ins.attribs.push(serde_json::from_value(json!({"tag":"A","text":text})).unwrap()); - assert_failure(&drawing(EntityKind::Insert(ins), 1), PreviewFailure::Input); - let mut t: Table = - serde_json::from_value(json!({"insert":[0,0,0],"rowHeights":[1],"colWidths":[1],"cells":[[{"text":"x".repeat(MAX_INPUT+1)}]]})).unwrap(); - assert_failure(&drawing(EntityKind::Table(t.clone()), 1), PreviewFailure::Input); - t.cells.clear(); - t.row_heights = vec![1.0; 200]; - t.col_widths = vec![1.0; 200]; - assert_failure(&drawing(EntityKind::Table(t), 1), PreviewFailure::Input); - let mut d = drawing(line(), 1); - let b = Arc::make_mut(d.blocks.get_mut("Synthetic").unwrap()); - let e = b.entities.iter().next().unwrap().handle; - // Common data is cloned by bounds and nested references too. - let mut huge = Entity::new(e, line()); - huge.common.xdata.push(cadcraft_doc::RawTag { code: 1000, value: "x".repeat(MAX_INPUT + 1) }); - b.entities = Default::default(); - b.entities.push(huge); - assert_failure(&d, PreviewFailure::Input); -} - -#[test] -fn normal_table_is_visible_and_merge_work_is_bounded() { - let mut t: Table = serde_json::from_value(json!({"insert":[0,0,0],"rowHeights":[1],"colWidths":[1],"cells":[[{"text":"OK"}]]})).unwrap(); - assert!(matches!(build(&drawing(EntityKind::Table(t.clone()), 1), "Synthetic"), PreviewResult::Ready(_))); - t.row_heights = vec![1.0; 100]; - t.col_widths = vec![1.0; 100]; - t.cells = vec![vec![TableCell { merged: Some((100, 100)), ..Default::default() }; 100]; 100]; - assert_failure(&drawing(EntityKind::Table(t), 1), PreviewFailure::Computation); -} - -#[test] -fn excessive_geometry_hatches_and_mleaders_remain_bounded() { - assert_failure( - &drawing(EntityKind::Polyline3d(cadcraft_doc::Polyline3d { points: vec![Vec3::ZERO; MAX_INPUT + 1], closed: false }), 1), - PreviewFailure::Input, - ); - let h: cadcraft_doc::Hatch = serde_json::from_value(json!({"pattern":"SOLID","solid":true,"loops":[]})).unwrap(); - let mut h = h; - h.loops.push(cadcraft_doc::HatchLoop { vertices: vec![PolyVertex::new(Vec2::ZERO); MAX_INPUT + 1], outer: true, sources: vec![] }); - assert_failure(&drawing(EntityKind::Hatch(h), 1), PreviewFailure::Input); - let m = cadcraft_doc::MLeader { - leaders: vec![vec![Vec3::ZERO; MAX_INPUT + 1]], - landing: Vec3::ZERO, - dogleg: 0.0, - text: None, - style: "STANDARD".into(), - arrow_size: 1.0, - spline: false, - block: None, - }; - assert_failure(&drawing(EntityKind::MLeader(m), 1), PreviewFailure::Input); - assert_failure(&drawing(EntityKind::Wipeout(cadcraft_doc::Wipeout { boundary: vec![Vec2::ZERO; MAX_INPUT + 1] }), 1), PreviewFailure::Input); -} - -#[test] -fn exhausted_fill_work_is_a_refusal_instead_of_a_partial_preview() { - let mut h: cadcraft_doc::Hatch = serde_json::from_value(json!({"pattern":"SOLID","solid":true,"loops":[]})).unwrap(); - let vertices = - (0..400).map(|i| PolyVertex::new(Vec2::new(i as f64, if i % 2 == 0 { i as f64 / 400.0 } else { 1.0 - i as f64 / 400.0 }))).collect(); - h.loops.push(cadcraft_doc::HatchLoop { vertices, outer: true, sources: vec![] }); - assert_failure(&drawing(EntityKind::Hatch(h), 1), PreviewFailure::Computation); -} - -#[test] -fn cycles_deep_references_missing_references_and_arrays_are_explicit() { - assert_failure(&drawing(EntityKind::Insert(insert("Synthetic")), 1), PreviewFailure::Computation); - assert_failure(&drawing(EntityKind::Insert(insert("Missing")), 1), PreviewFailure::MissingReference); - let mut d = drawing(line(), 1); - for i in (0..=cadcraft_doc::MAX_BLOCK_DEPTH).rev() { - let mut b = Block::new(&format!("Depth{i}")); - let next = if i == cadcraft_doc::MAX_BLOCK_DEPTH { "Synthetic".into() } else { format!("Depth{}", i + 1) }; - b.entities.push(Entity::new(Handle(1), EntityKind::Insert(insert(&next)))); - d.blocks.insert(b.name.clone(), Arc::new(b)); - } - assert!(matches!(build(&d, "Depth0"), PreviewResult::Unavailable(PreviewFailure::Computation))); - let mut i = insert("Synthetic"); - i.rows = 200; - i.cols = 200; - let mut b = Block::new("Array"); - b.entities.push(Entity::new(Handle(2), EntityKind::Insert(i))); - d.blocks.insert("Array".into(), Arc::new(b)); - assert!(matches!(build(&d, "Array"), PreviewResult::Unavailable(PreviewFailure::Computation))); -} - -#[test] -fn empty_ready_invalid_and_refused_have_distinct_statuses() { - assert!(matches!(build(&drawing(line(), 0), "Synthetic"), PreviewResult::Empty)); - assert!(matches!(build(&drawing(line(), 1), "Synthetic"), PreviewResult::Ready(_))); - let mut s = simple(); - s.knots[0] = f64::NAN; - assert_failure(&drawing(EntityKind::Spline(s), 1), PreviewFailure::Invalid); - assert_ne!( - super::super::preview_status(Some(&PreviewResult::Empty), true), - super::super::preview_status(Some(&PreviewResult::Unavailable(PreviewFailure::Input)), false) - ); - assert_ne!(super::super::preview_status(None, false), super::super::preview_status(Some(&PreviewResult::Empty), false)); -} - -#[test] -fn renderer_refuses_output_before_retaining_excess_geometry() { - let d = drawing(line(), 2); - let ents = || d.block("Synthetic").unwrap().entities.iter().map(|e| &**e); - assert!(cadcraft_render::build_entities_limited(&d, ents(), &Default::default(), 1, 100).is_none()); - assert!(cadcraft_render::build_entities_limited(&d, ents(), &Default::default(), 100, 3).is_none()); - assert_eq!(cadcraft_render::build_entities_limited(&d, ents(), &Default::default(), 2, 4).unwrap().verts.len(), 4); -} - -#[test] -fn cache_caps_prefer_offscreen_lru_and_count_empty_results() { - let mut cache = PreviewCache::default(); - let visible = HashSet::from(["0".to_string()]); - for i in 0..=MAX_CACHE_RESULTS { - cache.insert(i.to_string(), PreviewResult::Empty, &visible); - } - assert_eq!(cache.len(), MAX_CACHE_RESULTS); - assert!(cache.entries.contains_key("0")); - assert!(!cache.entries.contains_key("1")); - cache.touch("2"); - cache.insert("next".into(), PreviewResult::Unavailable(PreviewFailure::Input), &visible); - assert!(!cache.entries.contains_key("3")); - assert!(cache.entries.contains_key("2")); - for entry in cache.entries.values_mut() { - entry.bytes = MAX_CACHE_BYTES / 3; - } - cache.evict(&visible); - assert!(cache.len() <= 2); - assert!(cache.estimated_bytes().unwrap() <= MAX_CACHE_BYTES); - cache.sync_revision(1, 1); - assert!(cache.is_empty()); - cache.insert("refused".into(), PreviewResult::Unavailable(PreviewFailure::Input), &HashSet::new()); - cache.sync_revision(2, 1); - assert!(cache.is_empty()); -} - -#[test] -fn capacity_is_accounted_even_when_vectors_are_empty() { - let list = cadcraft_render::DisplayList { verts: Vec::with_capacity(10_000), ..Default::default() }; - let result = PreviewResult::Ready(Preview { list: Arc::new(list), bounds: Bounds2::EMPTY }); - assert!(retained_bytes(&result).unwrap() >= 10_000 * std::mem::size_of::()); - let mut cache = PreviewCache::default(); - cache.insert("Huge".into(), result, &HashSet::new()); - cache.entries.get_mut("Huge").unwrap().bytes = usize::MAX; - cache.evict(&HashSet::new()); - assert!(cache.is_empty()); - - // A result which cannot fit is replaced by a lightweight cached refusal. - let list = cadcraft_render::DisplayList { verts: Vec::with_capacity(MAX_CACHE_BYTES / std::mem::size_of::()), ..Default::default() }; - cache.insert("Too large".into(), PreviewResult::Ready(Preview { list: Arc::new(list), bounds: Bounds2::EMPTY }), &HashSet::new()); - assert!(matches!(cache.entries.get("Too large").unwrap().result, PreviewResult::Unavailable(PreviewFailure::Output))); - assert!(cache.estimated_bytes().unwrap() < 4096); -} - -#[test] -fn visibility_cannot_override_cache_limits() { - let visible: HashSet<_> = (0..600).map(|i| i.to_string()).collect(); - let mut cache = PreviewCache::default(); - for name in &visible { - cache.insert(name.clone(), PreviewResult::Empty, &visible); - } - assert_eq!(cache.len(), MAX_CACHE_RESULTS); - assert!(cache.estimated_bytes().unwrap() <= MAX_CACHE_BYTES); -} - -#[test] -fn refused_thumbnail_is_not_rebuilt_each_frame_and_does_not_block_insertion() { - let text: cadcraft_doc::Text = serde_json::from_value(json!({"insert":[0,0,0],"height":1,"value":"x".repeat(MAX_INPUT+1)})).unwrap(); - let d = drawing(EntityKind::Text(text), 1); - assert_failure(&d, PreviewFailure::Input); - let ctx = egui::Context::default(); - let mut warm = ctx.run_ui(Default::default(), |_| {}); - warm.textures_delta.clear(); - let mut cache = PreviewCache::default(); - for pass in 0..4 { - let mut frame = FrameBuilds { visible: HashSet::new(), builds_left: MAX_BUILDS_PER_FRAME, started: web_time::Instant::now() }; - let mut out = ctx.run_ui(Default::default(), |ui| { - frame.started = web_time::Instant::now(); - draw_block_item(ui, &d, "Synthetic", false, ViewMode::LargeIcons, vec2(100.0, 112.0), (&mut cache, &mut frame)); - }); - out.textures_delta.clear(); - assert_eq!(frame.builds_left, if pass == 0 { MAX_BUILDS_PER_FRAME - 1 } else { MAX_BUILDS_PER_FRAME }); - } - let mut s = Session::empty(); - s.open_drawing(d, "Synthetic", None); - let mut app = CadApp::new(s, Services::default()); - grab_block(&mut app, "Synthetic", &State::default()); - assert!(app.session.current_prompt().unwrap().accept.point); - app.session.input(Input::Point(Vec2::new(10.0, 20.0))).unwrap(); - assert_eq!(reference_count(app.session.doc().unwrap(), "Synthetic"), 1); -} diff --git a/crates/ui-egui/src/blocks_palette.rs b/crates/ui-egui/src/blocks_palette.rs new file mode 100644 index 000000000..352df95e1 --- /dev/null +++ b/crates/ui-egui/src/blocks_palette.rs @@ -0,0 +1,1335 @@ +//! The Blocks palette: the drawing's own blocks as a gallery (Current Drawing) and the block +//! libraries the user added (Libraries): folders of drawings and single drawing files, kept in +//! a list that can be added to, refreshed and removed from. A name filter, the gallery's view +//! styles and the insertion options (scale, rotation, explode) apply to both tabs. +//! +//! A thin view over the engine: the lists come from the `blockspalette`, `blocklibraries` and +//! `blocklibrary` commands, a library block is defined here by `blocklibimport`, and a block is +//! placed by starting INSERT and answering its first prompts, so the command line shows what the +//! palette did and the insertion point is picked on the drawing as usual. +//! +//! Block definitions come from files, so they are hostile input: a picture is built only for a +//! tile on screen, a few per frame, under a deadline and a size limit, and a panic or a refused +//! picture never stops the block from being placed. + +use std::collections::HashMap; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::sync::atomic::{AtomicBool, Ordering}; +use std::sync::{Arc, Mutex, PoisonError}; +use std::time::Duration; + +use cadcraft_engine::Input; +use cadcraft_engine::doc::{Block, Drawing, Entity}; +use cadcraft_engine::geom::{Bounds2, Vec2}; +use cadcraft_engine::render::{DisplayList, Kind, Options, build_entities}; +use egui::{Color32, Pos2, RichText, Sense, Stroke, vec2}; +use serde_json::{Value, json}; + +use crate::CadApp; +use crate::docking::Panel; + +/// Points kept per block preview: a block with more geometry shows its first part only. +const PREVIEW_POINTS: usize = 30_000; +/// How finely a preview is drawn: the chord tolerance is the block's size over this. +const PREVIEW_DETAIL: f64 = 300.0; +/// Most objects a block can hold and still get a preview. +const PREVIEW_ENTITIES: usize = 50_000; +/// How long a preview pass may keep the interface waiting before it is given up. +const PREVIEW_DEADLINE: Duration = Duration::from_millis(100); +/// Most previews built in one frame; the others wait for the next frames. +const BUILDS_PER_FRAME: usize = 4; +/// Most points the previews in memory hold together. +const MAX_CACHED_POINTS: usize = 4_000_000; +/// Most previews remembered, refused ones included. +const MAX_CACHED_PICTURES: usize = 50_000; +/// The most characters of a block name and of a description shown. +const MAX_NAME_CHARS: usize = 120; +const MAX_DESCRIPTION_CHARS: usize = 240; + +/// BLOCKSPALETTE typed, Window ▸ Blocks and the toolbar icon open this palette. JSON calls (with parameters) +/// run the engine's command and list the blocks. +pub fn route(app: &mut CadApp, id: &str, params: &Value) -> Option> { + // The toolbar's Blocks icon and Window ▸ Blocks open the palette too, as the other ui.dialog.* + // ids do, whatever the parameters. + if id == "ui.dialog.blocks" { + return Some(open_palette(app)); + } + if !params.is_null() { + return None; + } + match cadcraft_engine::cmd::resolve_alias(id).as_str() { + "blockspalette" => Some(open_palette(app)), + _ => None, + } +} + +/// Show the palette. The first time it docks below the other palettes; after that it comes back +/// where it was. +fn open_palette(app: &mut CadApp) -> Result { + crate::docking::command(app, false, &json!({ "operation": "open", "panel": Panel::Blocks.id() })) +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum Tab { + #[default] + Current, + Libraries, +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)] +enum View { + ExtraLarge, + Large, + #[default] + Medium, + Small, + Details, + List, +} + +impl View { + const ALL: [View; 6] = [View::ExtraLarge, View::Large, View::Medium, View::Small, View::Details, View::List]; + + /// The name shown on the view's button. + fn label(self) -> &'static str { + match self { + View::ExtraLarge => crate::tl!("Extra Large Icons"), + View::Large => crate::tl!("Large Icons"), + View::Medium => crate::tl!("Medium Icons"), + View::Small => crate::tl!("Small Icons"), + View::Details => crate::tl!("Details"), + View::List => crate::tl!("List"), + } + } + + /// The side of a gallery tile, for the icon views. + fn tile(self) -> Option { + match self { + View::ExtraLarge => Some(150.0), + View::Large => Some(104.0), + View::Medium => Some(76.0), + View::Small => Some(52.0), + View::Details | View::List => None, + } + } +} + +/// What the palette remembers between frames and drawings. +#[derive(Clone, Debug)] +struct State { + tab: Tab, + view: View, + filter: String, + selected: Option, + /// The libraries the user added (the engine keeps the list), once read. + libraries: Option>, + /// The library whose contents the gallery shows. + library: Option, + /// The folder or file path being typed to add a library. + new_library: String, + /// Bumped to read the library again. + refresh: u32, + /// Scale and rotation are asked on the drawing (the INSERT prompts) while these are on; + /// off, the values below are used without asking. + scale_on_screen: bool, + scale: [f64; 3], + rotation_on_screen: bool, + rotation: f64, + explode: bool, + /// Place the block again once it is placed, until the command is cancelled. + repeat: bool, + /// The block being placed again, the drawing it goes into, that drawing's handle counter when + /// its INSERT started and whether it is placed exploded: a finished INSERT that took no new + /// handle placed nothing (it was cancelled), and repeating stops. So does switching drawings. + repeating: Option<(Item, u64, u64, bool)>, + /// The pass that last drew the palette: what ran while it was hidden went unwatched. + last_pass: u64, +} + +impl Default for State { + fn default() -> Self { + State { + tab: Tab::default(), + view: View::default(), + filter: String::new(), + selected: None, + libraries: None, + library: None, + new_library: String::new(), + refresh: 0, + scale_on_screen: false, + scale: [1.0; 3], + rotation_on_screen: false, + rotation: 0.0, + explode: false, + repeat: true, + repeating: None, + last_pass: 0, + } + } +} + +/// Where a gallery item comes from. +#[derive(Clone, Debug, PartialEq)] +enum Source { + /// A block of the current drawing. + Current, + /// A block of a library drawing, defined here when placed. + LibraryBlock { path: String }, + /// A drawing of a library folder, placed as a block named after it. + LibraryDrawing { path: String }, +} + +/// A block and the drawing it belongs to, to draw its picture when it is needed. +#[derive(Clone)] +struct Lazy { + doc: Arc, + block: Arc, +} + +impl std::fmt::Debug for Lazy { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "Lazy({})", self.block.name) + } +} + +/// One tile of the gallery. +#[derive(Clone, Debug)] +struct Item { + /// What the item is selected by: unique within the gallery. + id: String, + /// The block name (the file name of a drawing). + label: String, + description: String, + /// What the picture is drawn from once the tile is on screen; `None` has no picture. + picture: Option, + source: Source, +} + +impl PartialEq for Item { + fn eq(&self, other: &Self) -> bool { + self.id == other.id + } +} + +/// A gallery's items, and whether a hostile or huge file left some of them out. +#[derive(Clone, Debug, Default)] +struct Listing { + items: Arc>, + truncated: bool, +} + +/// A block's preview, or the fact that it cannot have one. +#[derive(Clone, Debug)] +enum Picture { + Ready(Arc), + Unavailable, +} + +/// A remembered preview. +#[derive(Debug)] +struct Kept { + picture: Picture, + /// The frame that last showed it. + used: u64, + points: usize, + /// It belongs to the current drawing's tab. + current: bool, +} + +/// The previews in memory, by item and block definition, bounded in points: what no frame shows +/// goes first, so scrolling back rebuilds as little as possible and visible tiles never thrash. +#[derive(Debug, Default)] +struct Pictures { + map: HashMap<(String, usize), Kept>, + points: usize, + tick: u64, +} + +impl Pictures { + /// The preview kept for `key`, marked as shown on this frame. + fn get(&mut self, key: &(String, usize)) -> Option { + let tick = self.tick; + self.map.get_mut(key).map(|k| { + k.used = tick; + k.picture.clone() + }) + } + + /// Keep `picture` under `key`, dropping the oldest unshown ones while over the point budget. + fn insert(&mut self, key: (String, usize), picture: Picture, current: bool) { + if self.map.len() >= MAX_CACHED_PICTURES { + self.map.clear(); + self.points = 0; + } + let points = match &picture { + Picture::Ready(shape) => shape.points(), + Picture::Unavailable => 0, + }; + self.points = self.points.saturating_add(points); + if let Some(old) = self.map.insert(key, Kept { picture, used: self.tick, points, current }) { + self.points = self.points.saturating_sub(old.points); + } + while self.points > MAX_CACHED_POINTS { + let oldest = self.map.iter().filter(|(_, k)| k.used < self.tick && k.points > 0).min_by_key(|(_, k)| k.used).map(|(key, _)| key.clone()); + let Some(kept) = oldest.and_then(|key| self.map.remove(&key)) else { break }; + self.points = self.points.saturating_sub(kept.points); + } + } + + /// Forget the current drawing's previews: a nested block may look different now. + fn drop_current(&mut self) { + self.map.retain(|_, k| !k.current); + self.recount(); + } + + /// Forget the libraries' previews: a library read again has new block definitions, and one may + /// sit where a freed one did, under the same key. + fn drop_libraries(&mut self) { + self.map.retain(|_, k| k.current); + self.recount(); + } + + /// Add up the points the kept previews hold. + fn recount(&mut self) { + self.points = self.map.values().map(|k| k.points).fold(0, usize::saturating_add); + } +} + +/// The previews, shared across frames. +type SharedPictures = Arc>; + +/// The current drawing's blocks. The list is rebuilt when the drawing changes; the pictures are +/// drawn later, for the tiles on screen, and stay while the definitions stay as they were. +fn current_items(app: &mut CadApp, ui: &egui::Ui, pictures: &SharedPictures) -> Listing { + let Ok(key) = app.session.state().map(|st| (st.uid, st.revision)) else { return Listing::default() }; + let id = egui::Id::unique("blocks-current"); + if let Some((k, listing)) = ui.data(|d| d.get_temp::<((u64, u64), Listing)>(id)) + && k == key + { + return listing; + } + let listed = app.run("blockspalette", json!({})).unwrap_or(Value::Null); + let Ok(st) = app.session.state() else { return Listing::default() }; + let defs: Arc> = Arc::new(st.doc.blocks.iter().map(|(k, b)| (k.clone(), Arc::as_ptr(b) as usize)).collect()); + let defs_id = egui::Id::unique("blocks-definitions"); + if let Some((uid, old)) = ui.data(|d| d.get_temp::<(u64, Arc>)>(defs_id)) + && uid == key.0 + && old.iter().any(|(name, at)| defs.get(name) != Some(at)) + { + pictures.lock().unwrap_or_else(PoisonError::into_inner).drop_current(); + } + let items: Vec = listed + .get("blocks") + .and_then(Value::as_array) + .map(|a| { + a.iter() + .filter_map(|b| { + let name = b.get("name")?.as_str()?.to_string(); + Some(Item { + id: name.clone(), + description: b.get("description").and_then(Value::as_str).unwrap_or_default().to_string(), + picture: st.doc.block(&name).map(|block| Lazy { doc: st.doc.clone(), block: block.clone() }), + label: name, + source: Source::Current, + }) + }) + .collect() + }) + .unwrap_or_default(); + let truncated = listed.get("truncated").and_then(Value::as_bool).unwrap_or(false); + let listing = Listing { items: Arc::new(items), truncated }; + ui.data_mut(|d| { + d.insert_temp(defs_id, (key.0, defs)); + d.insert_temp(id, (key, listing.clone())); + }); + listing +} + +/// The contents of a library, or why it cannot be read. +type Loaded = Result; + +/// What a library holds, read once and kept until Refresh (reading a drawing walks its blocks). +fn library_items(app: &mut CadApp, ui: &egui::Ui, path: &str, refresh: u32, pictures: &SharedPictures) -> Loaded { + let id = egui::Id::unique("blocks-library"); + if let Some((p, r, loaded)) = ui.data(|d| d.get_temp::<(String, u32, Loaded)>(id)) + && p == path + && r == refresh + { + return loaded; + } + let loaded = read_library(app, path); + pictures.lock().unwrap_or_else(PoisonError::into_inner).drop_libraries(); + ui.data_mut(|d| d.insert_temp(id, (path.to_string(), refresh, loaded.clone()))); + loaded +} + +/// What a library holds: the blocks of a drawing file, or the drawings of a folder. +fn read_library(app: &mut CadApp, path: &str) -> Loaded { + let listed = app.run("blocklibrary", json!({ "path": path }))?; + let text = |v: &Value, k: &str| v.get(k).and_then(Value::as_str).unwrap_or_default().to_string(); + let truncated = listed.get("truncated").and_then(Value::as_bool).unwrap_or(false); + if listed.get("kind").and_then(Value::as_str) == Some("folder") { + let files = listed.get("files").and_then(Value::as_array).cloned().unwrap_or_default(); + let items = files + .iter() + .map(|f| Item { + id: text(f, "file"), + label: text(f, "name"), + description: text(f, "file"), + picture: None, + source: Source::LibraryDrawing { path: text(f, "file") }, + }) + .collect(); + return Ok(Listing { items: Arc::new(items), truncated }); + } + // A drawing file: its blocks, drawn from the file itself. + let drawing = cadcraft_engine::cmd::read_library_file(path).ok(); + let blocks = listed.get("blocks").and_then(Value::as_array).cloned().unwrap_or_default(); + let items = blocks + .iter() + .map(|b| { + let name = text(b, "name"); + let picture = drawing.as_ref().and_then(|d| d.block(&name).map(|block| Lazy { doc: d.clone(), block: block.clone() })); + Item { + id: format!("{path}|{name}"), + description: text(b, "description"), + picture, + label: name, + source: Source::LibraryBlock { path: path.to_string() }, + } + }) + .collect(); + Ok(Listing { items: Arc::new(items), truncated }) +} + +/// A block's picture: polylines and filled triangles in a unit box (aspect kept, centred, Y up +/// as in the drawing), each with its colour (`None`: the interface's text colour, which stands +/// for white and black, colour 7). +#[derive(Clone, Debug, Default)] +struct Shape { + lines: Vec<(Option, Vec)>, + /// Three points per triangle. + tris: Vec<(Option, Vec)>, +} + +impl Shape { + /// How many points the preview holds. + fn points(&self) -> usize { + self.lines.iter().chain(&self.tris).map(|(_, l)| l.len()).fold(0, usize::saturating_add) + } +} + +/// Cancels a build when `deadline` passes, unless the returned channel is dropped first. +#[cfg(not(target_arch = "wasm32"))] +fn watchdog(cancel: Arc, deadline: Duration) -> Option<(std::sync::mpsc::Sender<()>, std::thread::JoinHandle<()>)> { + use std::sync::mpsc::{RecvTimeoutError, channel}; + let (done, wait) = channel::<()>(); + let timer = std::thread::Builder::new().name("block-preview-deadline".into()).spawn(move || { + if matches!(wait.recv_timeout(deadline), Err(RecvTimeoutError::Timeout)) { + cancel.store(true, Ordering::Relaxed); + } + }); + timer.ok().map(|timer| (done, timer)) +} + +/// Build the display list of `ents`, or `None` when it panics, is cancelled or takes too long +/// (there is no timer on the web, where the block's size and the renderer's own limits apply). +fn build_within(d: &Drawing, ents: &[&Entity], mut opts: Options, cancel: &Arc, deadline: Option) -> Option { + opts.cancel = Some(cancel.clone()); + #[cfg(not(target_arch = "wasm32"))] + let timer = deadline.and_then(|t| watchdog(cancel.clone(), t)); + #[cfg(target_arch = "wasm32")] + let _ = deadline; + let built = catch_unwind(AssertUnwindSafe(|| build_entities(d, ents.iter().copied(), &opts))); + #[cfg(not(target_arch = "wasm32"))] + if let Some((done, timer)) = timer { + drop(done); + let _ = timer.join(); + } + if cancel.load(Ordering::Relaxed) { None } else { built.ok() } +} + +/// The picture of a block, drawn now. +fn picture(lazy: &Lazy) -> Picture { + let cancel = Arc::new(AtomicBool::new(false)); + match outline(&lazy.doc, &lazy.block, &cancel, Some(PREVIEW_DEADLINE)) { + Some(shape) => Picture::Ready(Arc::new(shape)), + None => Picture::Unavailable, + } +} + +/// `text`, cut to `max` characters. +fn clipped(text: &str, max: usize) -> std::borrow::Cow<'_, str> { + match text.char_indices().nth(max) { + Some((end, _)) => format!("{}…", text.get(..end).unwrap_or_default()).into(), + None => text.into(), + } +} + +/// The block as the canvas draws it (nested blocks, splines, text and fills included), each +/// object in its colour. A huge block's picture holds only a first part. `None`: the block is too +/// big, or drawing it was cancelled, took too long or failed. +fn outline(d: &Drawing, b: &Block, cancel: &Arc, deadline: Option) -> Option { + let ents: Vec<&Entity> = b.entities.iter().take(PREVIEW_ENTITIES.saturating_add(1)).map(|e| &**e).collect(); + if ents.len() > PREVIEW_ENTITIES { + return None; + } + if ents.is_empty() { + return Some(Shape::default()); + } + // A coarse pass for the size, then one detailed to match it. + let first = build_within(d, &ents, Options { tolerance: 1.0, lineweights: false, ..Options::default() }, cancel, deadline)?; + let span = first.bounds.width().max(first.bounds.height()); + if !(span.is_finite() && span > 0.0) { + return Some(Shape::default()); + } + let opts = Options { tolerance: span / PREVIEW_DETAIL, min_dash: span / PREVIEW_DETAIL, lineweights: false, ..Options::default() }; + let list = build_within(d, &ents, opts, cancel, deadline)?; + let mut lines: Vec<(Option, Vec)> = Vec::new(); + let mut tris: Vec<(Option, Vec)> = Vec::new(); + let mut budget = PREVIEW_POINTS; + for p in &list.prims { + let color = (!p.aci7).then(|| Color32::from_rgb(p.color.0, p.color.1, p.color.2)); + let (start, len) = (p.start as usize, p.len as usize); + match p.kind { + Kind::Polyline => { + let Some(pts) = list.verts.get(start..start.saturating_add(len)) else { continue }; + if pts.len() > budget { + break; + } + budget -= pts.len(); + lines.push((color, pts.to_vec())); + } + Kind::Tris => { + let Some(pts) = list.tris.get(start..start.saturating_add(len)) else { continue }; + if pts.len() > budget { + break; + } + budget -= pts.len(); + tris.push((color, pts.to_vec())); + } + _ => {} + } + } + let finite = |p: &&Vec2| p.x.is_finite() && p.y.is_finite(); + let bounds = Bounds2::from_points(lines.iter().chain(tris.iter()).flat_map(|(_, l)| l).filter(finite).copied()); + if bounds.is_empty() { + return Some(Shape::default()); + } + let span = bounds.width().max(bounds.height()).max(1e-9); + let c = bounds.center(); + let norm = |p: &Vec2| Pos2::new((0.5 + (p.x - c.x) / span) as f32, (0.5 - (p.y - c.y) / span) as f32); + // A triangle with a corner that is not a number is left out whole. + let whole = |t: &&[Vec2; 3]| t.iter().all(|p| p.x.is_finite() && p.y.is_finite()); + Some(Shape { + lines: lines.iter().map(|(c, l)| (*c, l.iter().filter(finite).map(norm).collect())).collect(), + tris: tris.iter().map(|(c, l)| (*c, l.as_chunks::<3>().0.iter().filter(whole).flatten().map(norm).collect())).collect(), + }) +} + +/// What a frame of the gallery draws its pictures with. +struct Painting<'a> { + pictures: &'a mut Pictures, + builds_left: usize, + /// When the frame stops building previews (the web has no clock to read, so no limit there). + #[cfg(not(target_arch = "wasm32"))] + until: std::time::Instant, +} + +impl<'a> Painting<'a> { + fn new(pictures: &'a mut Pictures) -> Self { + Self { + pictures, + builds_left: BUILDS_PER_FRAME, + #[cfg(not(target_arch = "wasm32"))] + until: std::time::Instant::now() + PREVIEW_DEADLINE, + } + } + + /// Whether the frame has used its time: what is still to build waits for the next frame. + fn out_of_time(&self) -> bool { + #[cfg(not(target_arch = "wasm32"))] + return std::time::Instant::now() >= self.until; + #[cfg(target_arch = "wasm32")] + false + } +} + +/// The tile's picture: remembered, or drawn now if the frame still has room for it. A tile that +/// has to wait asks for another frame. +fn shape_of(ui: &egui::Ui, item: &Item, painting: &mut Painting<'_>) -> Option> { + let lazy = item.picture.as_ref()?; + let key = (item.id.clone(), Arc::as_ptr(&lazy.block) as usize); + let known = match painting.pictures.get(&key) { + Some(known) => known, + None if painting.builds_left > 0 && !painting.out_of_time() => { + painting.builds_left -= 1; + let built = picture(lazy); + // A block that took all its time is enough for one frame. + if matches!(built, Picture::Unavailable) { + painting.builds_left = 0; + } + painting.pictures.insert(key, built.clone(), item.source == Source::Current); + built + } + None => { + ui.ctx().request_repaint(); + return None; + } + }; + match known { + Picture::Ready(shape) => Some(shape), + Picture::Unavailable => None, + } +} + +/// Draw the preview in `rect`, or a placeholder when there is none. +fn paint_preview(ui: &egui::Ui, rect: egui::Rect, shape: Option<&Shape>, color: Color32) { + let side = rect.width().min(rect.height()) * 0.86; + let origin = rect.center() - vec2(side, side) / 2.0; + let painter = ui.painter_at(rect); + let Some(shape) = shape.filter(|s| !s.lines.is_empty() || !s.tris.is_empty()) else { + // No picture (a drawing of a library folder, or a block without one): a page with a + // folded corner. + let w = side * 0.62; + let page = egui::Rect::from_center_size(rect.center(), vec2(w, side)); + let fold = w * 0.3; + let pts = vec![ + page.left_top(), + egui::pos2(page.right() - fold, page.top()), + egui::pos2(page.right(), page.top() + fold), + page.right_bottom(), + page.left_bottom(), + page.left_top(), + ]; + painter.add(egui::Shape::line(pts, Stroke::new(1.0, color))); + return; + }; + for (c, line) in &shape.lines { + let pts: Vec = line.iter().map(|p| origin + vec2(p.x * side, p.y * side)).collect(); + painter.add(egui::Shape::line(pts, Stroke::new(1.0, c.unwrap_or(color)))); + } + for (c, tris) in &shape.tris { + let mut mesh = egui::Mesh::default(); + for p in tris { + mesh.colored_vertex(origin + vec2(p.x * side, p.y * side), c.unwrap_or(color)); + } + let n = u32::try_from(tris.len()).unwrap_or(0) / 3 * 3; + mesh.indices.extend(0..n); + painter.add(egui::Shape::mesh(mesh)); + } +} + +/// What a click in the palette asks for, run once the palette is drawn. +enum Act { + Insert { item: Item, explode: bool }, + AddLibrary(String), + PickLibrary, + RemoveLibrary(String), +} + +/// The palette body. +pub fn section(app: &mut CadApp, ui: &mut egui::Ui) { + let t = crate::theme::Tokens::get(); + let state_id = egui::Id::unique("blocks-state"); + let mut st: State = ui.data(|d| d.get_temp(state_id)).unwrap_or_default(); + let mut act = None; + if st.libraries.is_none() { + st.libraries = Some(libraries(app, json!({}))); + } + + ui.add_space(6.0); + ui.horizontal(|ui| { + ui.add_space(8.0); + for (tab, label) in [(Tab::Current, crate::tl!("Current Drawing")), (Tab::Libraries, crate::tl!("Libraries"))] { + if ui.selectable_label(st.tab == tab, label).clicked() { + st.tab = tab; + } + } + }); + if st.tab == Tab::Libraries { + libraries_bar(ui, &mut st, &mut act); + } + ui.horizontal(|ui| { + ui.add_space(8.0); + let w = (ui.available_width() - 150.0).max(80.0); + ui.add(egui::TextEdit::singleline(&mut st.filter).hint_text(crate::tl!("Filter")).desired_width(w)); + let view_label = ui.label(crate::tl!("View")); + craft_ui::ComboBox::from_id_salt("blocks-view") + .selected_text(st.view.label()) + .show_ui(ui, |ui| { + for v in View::ALL { + ui.selectable_value(&mut st.view, v, v.label()); + } + }) + .response + .labelled_by(view_label.id); + }); + ui.add_space(4.0); + + let pictures: SharedPictures = ui.data_mut(|d| d.get_temp_mut_or_default::(egui::Id::unique("blocks-pictures")).clone()); + let loaded: Loaded = match (st.tab, st.library.clone()) { + (Tab::Current, _) => Ok(current_items(app, ui, &pictures)), + (Tab::Libraries, Some(path)) => library_items(app, ui, &path, st.refresh, &pictures), + (Tab::Libraries, None) => Ok(Listing::default()), + }; + let wanted = st.filter.trim().to_lowercase(); + let items: Vec<&Item> = + loaded.as_ref().map(|l| l.items.iter().filter(|i| wanted.is_empty() || named(&i.label, &wanted)).collect()).unwrap_or_default(); + if let Ok(listing) = &loaded + && listing.truncated + { + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.label(RichText::new(crate::tf!("Only the first {n} are shown.", n = listing.items.len())).color(t.warn)); + }); + } + + let options_h = 150.0; + // The panel scrolls when it is shorter than the gallery and the options together. + let room = ui.available_height(); + let gallery_h = if room.is_finite() { (room - options_h).clamp(150.0, 600.0) } else { 260.0 }; + egui::ScrollArea::vertical().id_salt("blocks-gallery").max_height(gallery_h).auto_shrink([false, false]).show(ui, |ui| { + if items.is_empty() { + ui.horizontal_wrapped(|ui| { + ui.add_space(8.0); + let msg = match (&loaded, st.tab, st.library.is_some(), st.filter.trim().is_empty()) { + (Err(e), ..) => e.clone(), + (_, Tab::Libraries, false, _) => crate::tl!("Add a folder of drawings or a drawing file to use its blocks.").to_string(), + (_, Tab::Libraries, true, true) => crate::tl!("This library has no drawings or blocks.").to_string(), + (_, Tab::Current, _, true) => crate::tl!("This drawing has no blocks.").to_string(), + _ => crate::tl!("No block matches the filter.").to_string(), + }; + ui.label(RichText::new(msg).color(t.text_dim)); + }); + return; + } + let mut kept = pictures.lock().unwrap_or_else(PoisonError::into_inner); + kept.tick = kept.tick.wrapping_add(1); + let mut painting = Painting::new(&mut kept); + let mut selected = st.selected.clone(); + gallery(ui, st.view, &items, &mut act, &mut selected, &mut painting); + st.selected = selected; + }); + + ui.add_space(4.0); + ui.separator(); + let placing = app.session.prompt_text() != "Command:"; + ui.add_enabled_ui(!placing, |ui| options(ui, &mut st)); + + repeat_placement(app, ui, &mut st); + match act { + Some(Act::Insert { item, explode }) => { + st.selected = Some(item.id.clone()); + announce_existing(app, &item); + if insert(app, &item, &st, explode) && st.repeat { + let seed = handseed(app); + st.repeating = drawing_uid(app).map(|uid| (item, uid, seed, explode)); + } + } + Some(Act::PickLibrary) => { + if let Some(path) = app.services.pick_open.as_ref().and_then(|f| f()) { + add_library(app, &mut st, &path); + } + } + Some(Act::AddLibrary(path)) => add_library(app, &mut st, &path), + Some(Act::RemoveLibrary(path)) => { + st.libraries = Some(libraries(app, json!({ "op": "remove", "path": path }))); + if st.library.as_deref() == Some(path.as_str()) { + st.library = st.libraries.as_ref().and_then(|l| l.first().cloned()); + } + } + None => {} + } + ui.data_mut(|d| d.insert_temp(state_id, st)); +} + +/// Place the block again when the INSERT the palette started has finished and placed something; +/// a cancelled one (nothing changed), the Repeat option turned off or another command stops it. +fn repeat_placement(app: &mut CadApp, ui: &egui::Ui, st: &mut State) { + let pass = ui.ctx().cumulative_pass_nr(); + let watched = pass == st.last_pass.wrapping_add(1); + st.last_pass = pass; + let Some((item, uid, before, explode)) = st.repeating.clone() else { return }; + if !st.repeat || !watched || drawing_uid(app) != Some(uid) { + st.repeating = None; + return; + } + let prompt = app.session.prompt_text(); + if prompt != "Command:" { + // Still placing it; any other running command ends the repeating. + if !prompt.starts_with("INSERT") { + st.repeating = None; + } + return; + } + st.repeating = None; + if handseed(app) <= before { + // Nothing was placed: INSERT was cancelled. + return; + } + if insert(app, &item, st, explode) { + st.repeating = Some((item, uid, handseed(app), explode)); + ui.ctx().request_repaint(); + } +} + +/// Which drawing is active: a repeat placement belongs to the one it started in. +fn drawing_uid(app: &CadApp) -> Option { + app.session.state().ok().map(|st| st.uid) +} + +/// The drawing's handle counter: placing a block (exploded or not) takes new handles, and +/// cancelling takes none. +fn handseed(app: &CadApp) -> u64 { + app.session.doc().map_or(0, |d| d.handseed) +} + +/// The library list after `params` (`{}` just reads it). An engine error goes to the status line. +fn libraries(app: &mut CadApp, params: Value) -> Vec { + match app.run("blocklibraries", params) { + Ok(v) => v + .get("libraries") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|p| p.as_str().map(str::to_string)).collect()) + .unwrap_or_default(), + Err(e) => { + app.set_status(e); + Vec::new() + } + } +} + +/// Add a library to the list and show it. +fn add_library(app: &mut CadApp, st: &mut State, path: &str) { + match app.run("blocklibraries", json!({ "op": "add", "path": path })) { + Ok(v) => { + let list: Vec = v + .get("libraries") + .and_then(Value::as_array) + .map(|a| a.iter().filter_map(|p| p.as_str().map(str::to_string)).collect()) + .unwrap_or_default(); + st.library = v.get("path").and_then(Value::as_str).map(str::to_string).or_else(|| list.last().cloned()); + st.libraries = Some(list); + st.new_library.clear(); + st.selected = None; + st.refresh = st.refresh.wrapping_add(1); + } + Err(e) => app.set_status(e), + } +} + +/// The last part of a path: what a library is called in the list. +fn short(path: &str) -> &str { + path.trim_end_matches(['/', '\\']).rsplit(['/', '\\']).next().unwrap_or(path) +} + +/// The library list with what manages it: add (picked or typed), refresh, remove. +fn libraries_bar(ui: &mut egui::Ui, st: &mut State, act: &mut Option) { + let t = crate::theme::Tokens::get(); + ui.horizontal(|ui| { + ui.add_space(8.0); + if ui.button(crate::tl!("Open Library...")).on_hover_text(crate::tl!("Add a drawing file as a block library")).clicked() { + *act = Some(Act::PickLibrary); + } + if ui + .add_enabled(st.library.is_some(), egui::Button::new(crate::tl!("Refresh"))) + .on_hover_text(crate::tl!("Read the library again")) + .clicked() + { + st.refresh = st.refresh.wrapping_add(1); + } + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + let label = ui.label(crate::tl!("Folder or file")); + let w = (ui.available_width() - 70.0).max(60.0); + let edit = ui.add(egui::TextEdit::singleline(&mut st.new_library).desired_width(w)).labelled_by(label.id); + let typed = !st.new_library.trim().is_empty(); + let add = ui.add_enabled(typed, egui::Button::new(crate::tl!("Add"))).clicked() + || (typed && edit.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter))); + if add { + *act = Some(Act::AddLibrary(st.new_library.trim().to_string())); + } + }); + let libs = st.libraries.clone().unwrap_or_default(); + if libs.is_empty() { + return; + } + egui::ScrollArea::vertical().id_salt("blocks-libraries").max_height(88.0).auto_shrink([false, true]).show(ui, |ui| { + for path in &libs { + ui.horizontal(|ui| { + ui.add_space(8.0); + let on = st.library.as_deref() == Some(path.as_str()); + let w = (ui.available_width() - 34.0).max(40.0); + let row = ui.add_sized([w, 20.0], egui::Button::selectable(on, short(path)).frame_when_inactive(false).truncate()); + if row.on_hover_text(path).clicked() && !on { + st.library = Some(path.clone()); + st.selected = None; + } + let remove = ui.small_button("×").on_hover_text(crate::tl!("Remove from the list")); + remove.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, format!("{} {}", crate::tl!("Remove"), short(path)))); + if remove.clicked() { + *act = Some(Act::RemoveLibrary(path.clone())); + } + }); + } + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + if let Some(p) = &st.library { + ui.add(egui::Label::new(RichText::new(p).color(t.text_dim).small()).truncate()); + } + }); +} + +/// The tiles of the icon views; a click or a drag sets `act`. +fn gallery(ui: &mut egui::Ui, view: View, items: &[&Item], act: &mut Option, selected: &mut Option, painting: &mut Painting<'_>) { + let t = crate::theme::Tokens::get(); + let on_menu = |ui: &mut egui::Ui, item: &Item, act: &mut Option| { + if ui.button(crate::tl!("Insert")).clicked() { + *act = Some(Act::Insert { item: item.clone(), explode: false }); + ui.close(); + } + if ui.button(crate::tl!("Insert and Explode")).clicked() { + *act = Some(Act::Insert { item: item.clone(), explode: true }); + ui.close(); + } + }; + let react = |resp: &egui::Response, item: &Item, act: &mut Option, selected: &mut Option| { + // A click selects the block and starts placing it. + if resp.clicked() { + *selected = Some(item.id.clone()); + *act = Some(Act::Insert { item: item.clone(), explode: false }); + } + }; + match view.tile() { + Some(side) => { + ui.horizontal_wrapped(|ui| { + ui.add_space(8.0); + ui.spacing_mut().item_spacing = vec2(6.0, 6.0); + for &item in items { + let (rect, resp) = ui.allocate_exact_size(vec2(side, side + 32.0), Sense::click()); + let name = clipped(&item.label, MAX_NAME_CHARS); + // Only the tiles on screen are drawn, and only they build a picture. + if ui.is_rect_visible(rect) { + let on = selected.as_deref() == Some(item.id.as_str()); + if on || resp.hovered() { + ui.painter().rect_filled(rect, 3.0, if on { t.selection } else { t.hover }); + } + let art = egui::Rect::from_min_size(rect.min, vec2(side, side)); + paint_preview(ui, art, shape_of(ui, item, painting).as_deref(), t.text); + // The name under the icon: up to two lines, cut with an ellipsis, centred in the tile. + let mut job = egui::text::LayoutJob::simple(name.to_string(), egui::FontId::proportional(11.0), t.text, side - 4.0); + job.wrap.max_rows = 2; + job.wrap.break_anywhere = true; + job.halign = egui::Align::Center; + let galley = ui.painter().layout_job(job); + let at = egui::pos2(rect.center().x - galley.rect.center().x, rect.min.y + side + 2.0); + ui.painter().galley(at, galley, t.text); + } + let tip = if item.description.is_empty() { + name.to_string() + } else { + format!("{name}\n{}", clipped(&item.description, MAX_DESCRIPTION_CHARS)) + }; + let resp = resp.on_hover_text(tip); + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name.to_string())); + react(&resp, item, act, selected); + resp.context_menu(|ui| on_menu(ui, item, act)); + } + }); + } + None => { + let details = view == View::Details; + for &item in items { + let h = if details { 30.0 } else { 20.0 }; + let (rect, resp) = ui.allocate_exact_size(vec2(ui.available_width(), h), Sense::click()); + let name = clipped(&item.label, MAX_NAME_CHARS); + if ui.is_rect_visible(rect) { + let on = selected.as_deref() == Some(item.id.as_str()); + if on || resp.hovered() { + ui.painter().rect_filled(rect, 2.0, if on { t.selection } else { t.hover }); + } + let mut x = rect.min.x + 8.0; + if details { + let art = egui::Rect::from_min_size(egui::pos2(x, rect.min.y), vec2(h, h)); + paint_preview(ui, art, shape_of(ui, item, painting).as_deref(), t.text); + x += h + 8.0; + } + let font = egui::FontId::proportional(12.0); + ui.painter().text(egui::pos2(x, rect.center().y), egui::Align2::LEFT_CENTER, &name, font.clone(), t.text); + if details { + let x2 = rect.min.x + (rect.width() * 0.45).max(120.0); + let description = clipped(&item.description, MAX_DESCRIPTION_CHARS); + ui.painter().text(egui::pos2(x2, rect.center().y), egui::Align2::LEFT_CENTER, &description, font, t.text_dim); + } + } + resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Button, true, name.to_string())); + react(&resp, item, act, selected); + resp.context_menu(|ui| on_menu(ui, item, act)); + } + } + } +} + +/// The insertion options: what INSERT asks on the drawing, or the values used instead. +fn options(ui: &mut egui::Ui, st: &mut State) { + ui.add_space(4.0); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.label(RichText::new(crate::tl!("Options")).strong()); + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.checkbox(&mut st.scale_on_screen, crate::tl!("Scale")); + ui.add_enabled_ui(!st.scale_on_screen, |ui| { + for (axis, v) in ["X", "Y", "Z"].iter().zip(st.scale.iter_mut()) { + let label = ui.label(*axis); + ui.add(egui::DragValue::new(v).speed(0.1)).labelled_by(label.id); + } + }); + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.checkbox(&mut st.rotation_on_screen, crate::tl!("Rotation")); + ui.add_enabled_ui(!st.rotation_on_screen, |ui| { + let label = ui.label(crate::tl!("Angle")); + ui.add(egui::DragValue::new(&mut st.rotation).speed(1.0).suffix("°")).labelled_by(label.id); + }); + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.checkbox(&mut st.explode, crate::tl!("Explode")); + ui.checkbox(&mut st.repeat, crate::tl!("Repeat Placement")); + }); + ui.horizontal(|ui| { + ui.add_space(8.0); + ui.label(RichText::new(crate::tl!("Click a block, then pick its insertion point.")).color(crate::theme::Tokens::get().text_dim)); + }); +} + +/// A usable scale factor: finite and not zero. +fn factor(v: f64) -> f64 { + if v.is_finite() && v != 0.0 { v } else { 1.0 } +} + +/// Say so when a click on a library tile places the drawing's own block of that name: the tile +/// shows the library's version. Only a click calls this, not each placement of a repeat. +fn announce_existing(app: &mut CadApp, item: &Item) { + let here = app.session.doc().ok().is_some_and(|d| d.block(&item.label).is_some()); + if here && !matches!(item.source, Source::Current) { + app.set_status(crate::tl!("This block is already in the drawing, so its definition is used.").to_string()); + } +} + +/// Start INSERT for the item and answer the prompts the options settle, leaving the insertion +/// point to the drawing. A library block or drawing is defined in this drawing first, unless a +/// block of that name is already here (it is never replaced). `true` when INSERT started. +fn insert(app: &mut CadApp, item: &Item, st: &State, explode: bool) -> bool { + let here = app.session.doc().ok().is_some_and(|d| d.block(&item.label).is_some()); + let name = match &item.source { + // The block (or the whole drawing) comes with only the layers, linetypes and styles it needs. + Source::LibraryBlock { path } | Source::LibraryDrawing { path } if !here => { + let mut params = json!({ "path": path, "name": item.label }); + if matches!(item.source, Source::LibraryBlock { .. }) { + params["block"] = json!(item.label); + } + match app.run("blocklibimport", params) { + Ok(v) => v.get("name").and_then(Value::as_str).unwrap_or(&item.label).to_string(), + Err(e) => { + app.set_status(e); + return false; + } + } + } + _ => item.label.clone(), + }; + if let Err(e) = app.session.start("insert") { + app.set_status(e.to_string()); + return false; + } + let star = explode || st.explode; + if let Err(e) = app.session.input(Input::Text(if star { format!("*{name}") } else { name })) { + app.set_status(e.to_string()); + return false; + } + // INSERT must have taken the name: the answers below would be read as block names otherwise. + if !app.session.current_prompt().is_some_and(|p| p.accept.point) { + let _ = app.session.input(Input::Cancel); + return false; + } + let mut feed = Vec::new(); + if !st.scale_on_screen { + let [x, y, z] = st.scale.map(factor); + if x == y && y == z { + feed.extend([Input::Keyword("Scale".into()), Input::Text(x.to_string())]); + } else { + for (k, v) in [("X", x), ("Y", y), ("Z", z)] { + feed.extend([Input::Keyword(k.into()), Input::Text(v.to_string())]); + } + } + } + if !st.rotation_on_screen { + let r = if st.rotation.is_finite() { st.rotation } else { 0.0 }; + // The palette shows absolute degrees: `<<` reads them whatever AUNITS, ANGBASE and ANGDIR say. + feed.extend([Input::Keyword("Rotate".into()), Input::Text(format!("<<{r}"))]); + } + for i in feed { + if let Err(e) = app.session.input(i) { + app.set_status(e.to_string()); + return false; + } + } + true +} + +/// Whether `label` matches the filter `wanted` (already lowercase), whatever the script. +fn named(label: &str, wanted: &str) -> bool { + wanted.is_empty() || label.to_lowercase().contains(wanted) +} + +#[cfg(test)] +mod tests { + #[test] + fn the_filter_ignores_case_in_every_script() { + assert!(super::named("ÉCROU M8", &"écrou".to_lowercase())); + assert!(super::named("TÜR", "tür")); + assert!(super::named("Valve", "")); + assert!(!super::named("Valve", "pump")); + } + + use cadcraft_engine::Session; + use serde_json::json; + + use std::sync::Arc; + use std::sync::atomic::AtomicBool; + + use cadcraft_engine::doc::geom::Vec3; + use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, Handle, Line}; + use egui::Pos2; + + use super::{Item, Lazy, PREVIEW_ENTITIES, Picture, Pictures, Shape, Source, State, clipped, insert, outline, picture}; + use crate::{CadApp, Services}; + + /// The block's picture, with no cancelling and no deadline. + fn shape(d: &Drawing, b: &Block) -> Shape { + outline(d, b, &Arc::new(AtomicBool::new(false)), None).unwrap() + } + + fn line(h: u64, a: Vec3, b: Vec3) -> Entity { + Entity::new(Handle(h), EntityKind::Line(Line { a, b })) + } + + /// Make block `name` from everything in model space now (the objects are removed). + fn make_block(s: &mut Session, name: &str) { + let handles: Vec = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + s.execute("block", &json!({ "name": name, "base": [0, 0], "handles": handles, "keep": "delete" })).unwrap(); + } + + /// A block made only of references to another block, and one with a circle, spline-free + /// geometry and text, all have a picture, as the canvas would draw them. + #[test] + fn nested_blocks_and_text_have_a_preview() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "INNER"); + s.execute("insert", &json!({ "name": "INNER", "at": [1, 1] })).unwrap(); + s.execute("insert", &json!({ "name": "INNER", "at": [1, 3], "rotation": 90 })).unwrap(); + make_block(&mut s, "OUTER"); + let d = s.doc().unwrap(); + let outer = shape(d, d.block("OUTER").unwrap()); + assert_eq!(outer.lines.len(), 2, "both nested references are drawn"); + let inner = shape(d, d.block("INNER").unwrap()); + assert_eq!(inner.lines.len(), 1); + // Everything lies in the unit box. + assert!(outer.lines.iter().flat_map(|(_, l)| l).all(|p| (0.0..=1.0).contains(&p.x) && (0.0..=1.0).contains(&p.y))); + } + + /// A line in a colour keeps it; one in the default colour takes the interface's. + #[test] + fn previews_keep_the_colours_of_their_objects() { + let mut s = Session::new(); + s.execute("color", &json!({ "color": "red" })).unwrap(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "RED"); + s.execute("color", &json!({ "color": "ByLayer" })).unwrap(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "PLAIN"); + let d = s.doc().unwrap(); + let red = shape(d, d.block("RED").unwrap()); + assert_eq!(red.lines.first().map(|(c, _)| *c), Some(Some(egui::Color32::from_rgb(255, 0, 0)))); + let plain = shape(d, d.block("PLAIN").unwrap()); + assert_eq!(plain.lines.first().map(|(c, _)| *c), Some(None), "colour 7 follows the theme"); + } + + fn item(name: &str) -> Item { + Item { id: name.into(), label: name.into(), description: String::new(), picture: None, source: Source::Current } + } + + /// The rotation shown in degrees is that rotation, in a drawing that measures angles otherwise. + #[test] + fn the_rotation_option_is_absolute_degrees() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "B"); + let header = &mut s.doc_mut().unwrap().header; + header.set_i64("AUNITS", 2); + header.set_i64("ANGDIR", 1); + header.set_f64("ANGBASE", 1.0); + let mut app = CadApp::new(s, Services::default()); + let st = State { rotation_on_screen: false, rotation: 90.0, ..State::default() }; + assert!(insert(&mut app, &item("B"), &st, false)); + app.session.input(cadcraft_engine::Input::Point(cadcraft_engine::geom::Vec2::new(1.0, 1.0))).unwrap(); + assert_eq!(app.session.prompt_text(), "Command:", "the options answered every prompt"); + let d = app.session.doc().unwrap(); + let rotation = d.model.iter().find_map(|e| if let EntityKind::Insert(i) = &e.kind { Some(i.rotation) } else { None }); + let rotation = rotation.expect("an insert"); + assert!((rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "{rotation}"); + } + + /// A name INSERT refuses ends the placement: the scale and rotation answers are not read as + /// block names, so block "1" is not placed. + #[test] + fn a_refused_name_places_nothing() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "1"); + let mut app = CadApp::new(s, Services::default()); + let st = State { scale_on_screen: false, ..State::default() }; + assert!(!insert(&mut app, &item("gone"), &st, false)); + assert_eq!(app.session.prompt_text(), "Command:"); + assert_eq!(app.session.doc().unwrap().model.iter().count(), 0); + } + + /// A cancelled build leaves no partial picture. + #[test] + fn a_cancelled_build_has_no_picture() { + let mut d = Drawing::new_metric(); + let mut b = Block::new("B"); + b.entities.push(line(0x70, Vec3::new(0.0, 0.0, 0.0), Vec3::new(4.0, 0.0, 0.0))); + d.blocks.insert("B".into(), Arc::new(b)); + let block = d.block("B").unwrap(); + assert!(outline(&d, block, &Arc::new(AtomicBool::new(true)), None).is_none()); + } + + /// A block over the size limit gets no picture, and asks nothing of the renderer. + #[test] + fn a_huge_block_has_no_picture() { + let mut b = Block::new("HUGE"); + for i in 0..=PREVIEW_ENTITIES { + b.entities.push(line(0x100 + i as u64, Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 0.0, 0.0))); + } + let lazy = Lazy { doc: Arc::new(Drawing::new_metric()), block: Arc::new(b) }; + assert!(matches!(picture(&lazy), Picture::Unavailable)); + } + + /// Coordinates that are not numbers never reach the picture. + #[test] + fn hostile_coordinates_stay_out_of_the_picture() { + let d = Drawing::new_metric(); + let mut b = Block::new("NAN"); + b.entities.push(line(0x70, Vec3::new(f64::NAN, 0.0, 0.0), Vec3::new(f64::INFINITY, 1.0, 0.0))); + b.entities.push(line(0x71, Vec3::new(0.0, 0.0, 0.0), Vec3::new(f64::MAX, f64::MIN, 0.0))); + b.entities.push(line(0x72, Vec3::new(0.0, 0.0, 0.0), Vec3::new(2.0, 2.0, 0.0))); + let cancel = Arc::new(AtomicBool::new(false)); + if let Some(s) = outline(&d, &b, &cancel, None) { + assert!(s.lines.iter().chain(&s.tris).flat_map(|(_, l)| l).all(|p| p.x.is_finite() && p.y.is_finite())); + } + } + + /// Blocks that hold each other end, whatever the file claims. + #[test] + fn blocks_that_hold_each_other_are_drawn_without_hanging() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "A"); + s.execute("insert", &json!({ "name": "A", "at": [1, 1] })).unwrap(); + make_block(&mut s, "B"); + // Point A at B, as a crafted file can: A -> B -> A. + let reference = (**s.doc().unwrap().block("B").unwrap().entities.iter().next().unwrap()).clone(); + let mut back = reference; + if let EntityKind::Insert(i) = &mut back.kind { + i.block = "B".into(); + } + let d = s.doc_mut().unwrap(); + let mut a = (**d.block("A").unwrap()).clone(); + a.entities.push(back); + d.blocks.insert("A".into(), Arc::new(a)); + let d = s.doc().unwrap(); + let _ = shape(d, d.block("A").unwrap()); + } + + /// What no frame shows goes first; what the current frame shows stays, whatever the total. + #[test] + fn the_cache_is_bounded_and_keeps_what_is_on_screen() { + let big = |n: usize| Picture::Ready(Arc::new(Shape { lines: vec![(None, vec![Pos2::ZERO; n])], tris: Vec::new() })); + let mut p = Pictures { tick: 1, ..Pictures::default() }; + p.insert(("old".into(), 1), big(3_000_000), false); + p.tick = 2; + p.insert(("new".into(), 2), big(3_000_000), false); + assert!(p.get(&("old".into(), 1)).is_none(), "the oldest went"); + assert!(p.get(&("new".into(), 2)).is_some()); + assert_eq!(p.points, 3_000_000); + // Two on the same frame: both are on screen, so neither goes. + p.insert(("also".into(), 3), big(3_000_000), false); + assert_eq!(p.points, 6_000_000); + assert!(p.get(&("new".into(), 2)).is_some() && p.get(&("also".into(), 3)).is_some()); + // The current drawing's previews can go together. + p.insert(("cur".into(), 4), Picture::Unavailable, true); + p.drop_current(); + assert!(p.get(&("cur".into(), 4)).is_none()); + assert_eq!(p.points, 6_000_000); + // A library read again takes its previews with it, and leaves the current drawing's. + p.insert(("cur".into(), 4), Picture::Unavailable, true); + p.drop_libraries(); + assert!(p.get(&("new".into(), 2)).is_none() && p.get(&("also".into(), 3)).is_none()); + assert!(p.get(&("cur".into(), 4)).is_some()); + assert_eq!(p.points, 0); + } + + #[test] + fn a_thousand_full_size_previews_stay_within_the_bounds() { + let full = |n: usize| Picture::Ready(Arc::new(Shape { lines: vec![(None, vec![Pos2::ZERO; n])], tris: Vec::new() })); + let mut p = Pictures::default(); + for i in 0..1000 { + p.tick = i as u64 + 1; + p.insert((format!("Part{i}"), i), full(super::PREVIEW_POINTS), i % 2 == 0); + assert!(p.points <= super::MAX_CACHED_POINTS.max(super::PREVIEW_POINTS), "{}", p.points); + assert!(p.map.len() <= super::MAX_CACHED_PICTURES); + } + // The kept points are the recorded ones, and the newest picture is always there. + assert_eq!(p.points, p.map.values().map(|k| k.points).sum::()); + assert!(p.get(&("Part999".to_string(), 999)).is_some()); + // The most the points can weigh: four million of two f32 each, 32 MiB (the limit here is 64). + assert!(super::MAX_CACHED_POINTS * std::mem::size_of::() <= 64 << 20); + } + + #[cfg(not(target_arch = "wasm32"))] + #[test] + fn a_frame_stops_building_previews_when_its_time_is_used() { + let mut p = Pictures::default(); + let mut painting = super::Painting::new(&mut p); + assert!(!painting.out_of_time()); + painting.until = std::time::Instant::now(); + assert!(painting.out_of_time()); + } + + #[test] + fn long_text_is_cut_to_whole_characters() { + assert_eq!(clipped("court", 10), "court"); + assert_eq!(clipped("éééééé", 3), "ééé…"); + } + + #[test] + fn an_empty_block_has_no_preview() { + let mut s = Session::new(); + s.execute("line", &json!({ "points": [[0, 0], [4, 0]] })).unwrap(); + make_block(&mut s, "ONE"); + let d = s.doc().unwrap(); + let mut empty = (**d.block("ONE").unwrap()).clone(); + empty.entities = Default::default(); + assert!(shape(d, &empty).lines.is_empty()); + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index 8ef3537ea..39040c366 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -38,7 +38,7 @@ use pick::{edit_text_at, hatch_at, wheel_zoom_points}; #[cfg(test)] use viewport::viewport_highlight_tolerance; use viewport::{VpContent, VpHighlight, draw_vp_content, ensure_vp_content}; -use widgets::{draw_tiles, draw_ucs_icon, draw_viewcube, over_command_line, over_navigation_control, tile_rects, tile_xf, viewcube_shown, viewport_label}; +use widgets::{draw_tiles, draw_ucs_icon, draw_viewcube, tile_rects, tile_xf, viewport_label}; /// World ↔ screen transform for the canvas rect. #[derive(Clone, Copy, Debug)] @@ -165,12 +165,6 @@ pub struct CanvasState { hover_cycle: Option<(Pos2, Vec, usize)>, /// What the cycling list and the Shift+Space highlight were made for (see [`CycleKey`]). cycle_key: Option, - /// The current primary-button gesture started on a canvas-painted menu. - menu_press: bool, - /// For each primary release in the current frame, in order: whether its press was on a canvas-painted menu. - release_menu: Vec, - /// A primary press came after the frame's last release, so that release is not where the cursor is now. - press_after_release: bool, } /// The command, prompt, drawing (and its revision) and view that the objects under the cursor @@ -465,6 +459,7 @@ fn paint_pointer_overlay( paper_rect: Option, surround: Color32, selecting: bool, + sheet: Option, ) { let app = &mut *frame.app; let ui = &mut *frame.ui; @@ -491,7 +486,7 @@ fn paint_pointer_overlay( draw_ucs_icon(painter, rect); crate::viewcube::ucs_icon(app, ui, rect); } - if viewcube_shown(app) { + if app.ui.show_viewcube && sheet.is_none() { draw_viewcube(app, ui, rect); } viewport_label(painter, rect); @@ -685,7 +680,6 @@ struct PromptClickContext<'a> { inside: bool, middle_down: bool, primary_clicked: bool, - on_menu: bool, response: &'a egui::Response, } @@ -695,7 +689,7 @@ fn collect_prompt_clicks(app: &mut CadApp, ui: &egui::Ui, context: PromptClickCo let point_prompt = app.session.current_prompt().is_some_and(|p| cadcraft_engine::pointmod::accepts(&p)) && app.session.pending_window.is_none() && !app.session.realtime_zoom_active(); - let mut pressed_primary = context.primary_clicked || (point_prompt && context.response.drag_stopped_by(egui::PointerButton::Primary)); + let pressed_primary = context.primary_clicked || (point_prompt && context.response.drag_stopped_by(egui::PointerButton::Primary)); if point_prompt && context.inside && pressed_primary && !context.middle_down && app.cmd.options.is_none() && app.cmd.buffer.is_empty() { let releases: Vec = ui.input(|i| { i.events @@ -706,23 +700,9 @@ fn collect_prompt_clicks(app: &mut CadApp, ui: &egui::Ui, context: PromptClickCo }) .collect() }); - // The last one is placed below, at the cursor, like any click, unless the cursor has since moved onto a menu - // (which then vetoes the click below) or another press has begun: it is placed here, where it was released. - let last = releases.len().saturating_sub(1); - for (n, pos) in releases.iter().enumerate() { - if n < last || context.on_menu || app.canvas.press_after_release { - if n == last { - pressed_primary = false; - } - if app.canvas.release_menu.get(n).copied().unwrap_or(false) - || !context.rect.contains(*pos) - || over_canvas_menu(app, *pos) - || over_navigation_control(app, context.rect, *pos) - || (app.ui.show_command_line && over_command_line(app, *pos)) - || ui.ctx().layer_id_at(*pos) != Some(ui.layer_id()) - { - continue; - } + // The last one is placed below, at the cursor, like any click. + if let Some((_, earlier)) = releases.split_last() { + for pos in earlier.iter().filter(|p| context.rect.contains(**p)) { let w = effective_point(app, context.xf.to_world(*pos), &context.xf, ui.ctx()); let result = match app.canvas.snap { Some(hit) => app.session.input_snapped(hit), @@ -738,29 +718,6 @@ fn collect_prompt_clicks(app: &mut CadApp, ui: &egui::Ui, context: PromptClickCo pressed_primary } -/// For each primary-button release in `events`, whether the press it ends, or the release itself, was on a menu -/// (`is_menu` at that position), and whether the gesture still open at the end of the frame started on one. `carried` is -/// that last value from the previous frame; the third value is whether a press follows the last release, which owns a release whose press came in an earlier frame. -fn release_owners(events: &[egui::Event], carried: bool, is_menu: impl Fn(Pos2) -> bool) -> (Vec, bool, bool) { - let mut current = carried; - let mut owners = Vec::new(); - let mut press_after_release = false; - for e in events { - match e { - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: true, .. } => { - current = is_menu(*pos); - press_after_release = !owners.is_empty(); - } - egui::Event::PointerButton { pos, button: egui::PointerButton::Primary, pressed: false, .. } => { - owners.push(current || is_menu(*pos)); - press_after_release = false; - } - _ => {} - } - } - (owners, current, press_after_release) -} - /// Draw the drawing area and handle its input (zoom and pan, picking, the crosshair) for this /// frame. /// @@ -804,16 +761,6 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { let navigation = Navigation { rect, tiles: &tiles, response: &resp, xf, pointer }; let Some((inside, on_menu)) = navigate_canvas(app, ui, &navigation) else { return }; let PointerInput { hover_pos, mods, middle_down, pressed_primary, pressed_secondary, dbl_primary, .. } = pointer; - // A menu may close on press; each release belongs to the press before it, wherever the cursor is by - // the end of the frame (`hover_pos` may already be after a move, and a frame can hold several gestures). - if ui.ctx().current_pass_index() == 0 { - let (owners, menu_press, press_after_release) = - ui.input(|i| release_owners(&i.events, app.canvas.menu_press, |at| over_canvas_menu(app, at) || over_navigation_control(app, rect, at) || over_command_line(app, at))); - app.canvas.release_menu = owners; - app.canvas.press_after_release = press_after_release; - app.canvas.menu_press = menu_press; - } - let menu_click = on_menu || app.canvas.release_menu.last().copied().unwrap_or(app.canvas.menu_press); // Re-read the view after navigation. let view = app.session.state().map(|s| s.view()).unwrap_or(view); let scale = f64::from(rect.height()) / view.height.max(1e-12); @@ -846,11 +793,8 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { return; }; - let pressed_primary = collect_prompt_clicks( - app, - ui, - PromptClickContext { rect, xf, inside, middle_down, primary_clicked: pressed_primary, on_menu, response: &resp }, - ); + let pressed_primary = + collect_prompt_clicks(app, ui, PromptClickContext { rect, xf, inside, middle_down, primary_clicked: pressed_primary, response: &resp }); let (raw_world, dyn_frame) = update_canvas_cursor(app, ui, &xf, inside, hover_pos); @@ -887,14 +831,11 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui) { app.canvas.cycle_key = Some(key); } let cycled = pressed_primary && !middle_down && cycle_click(app, &xf, hover_pos, raw_world.filter(|_| inside), mods.shift); - // A menu can disappear when a command starts or its prompt changes in this frame. - // Its previously painted rows still own the click; never pass it through as a point. + // Clicks. if inside - && !menu_click && pressed_primary && !middle_down && !cycled - && !hover_pos.is_some_and(|at| over_command_line(app, at)) && let Some(p) = app.canvas.cursor { if app.session.prompting() { @@ -1197,6 +1138,7 @@ fn paint_canvas(frame: CanvasPaint<'_>) { paper_rect, surround, selecting, + sheet, ); } diff --git a/crates/ui-egui/src/canvas/list.rs b/crates/ui-egui/src/canvas/list.rs index e3afeb232..2d548264e 100644 --- a/crates/ui-egui/src/canvas/list.rs +++ b/crates/ui-egui/src/canvas/list.rs @@ -129,7 +129,6 @@ pub(super) fn ensure_list(app: &mut CadApp, xf: &Xf, views: &[(Bounds2, f64)], c min_dash: 2f64.powi(lod_band) * 2.0, text: true, fill: true, - hatch_budget: None, lineweights: lwdisplay, view_height: st.paper_view().height, plot_style_table: None, diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 431021a10..c4e0c96ce 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -230,50 +230,3 @@ fn dynamic_input_distance_follows_the_drawing_units() { let text = painted_text(&mut app, &ctx, at); assert!(text.contains(&format!(" {} <", arch(c.len()))), "no {} in:\n{text}", arch(c.len())); } - -fn primary(x: f32, pressed: bool) -> egui::Event { - egui::Event::PointerButton { pos: egui::pos2(x, 0.0), button: egui::PointerButton::Primary, pressed, modifiers: Default::default() } -} - -#[test] -fn each_release_belongs_to_its_own_press() { - // A menu sits at x >= 100. - let menu = |p: egui::Pos2| p.x >= 100.0; - // A canvas click completes, then a menu press follows in the same frame: only the open gesture is the menu's. - let (owners, open, _) = super::release_owners(&[primary(10.0, true), primary(10.0, false), primary(120.0, true)], false, menu); - assert_eq!((owners, open), (vec![false], true)); - // The mirror image: a menu click completes, then a canvas press follows. - let (owners, open, _) = super::release_owners(&[primary(120.0, true), primary(120.0, false), primary(10.0, true)], false, menu); - assert_eq!((owners, open), (vec![true], false)); - // Two canvas clicks in one frame. - let (owners, open, _) = - super::release_owners(&[primary(10.0, true), primary(10.0, false), primary(20.0, true), primary(20.0, false)], false, menu); - assert_eq!((owners, open), (vec![false, false], false)); - // A release whose press came in an earlier frame belongs to the carried gesture. - let (owners, open, _) = super::release_owners(&[primary(10.0, false)], true, menu); - assert_eq!((owners, open), (vec![true], true)); - // A canvas press released over a menu is the menu's. - let (owners, open, _) = super::release_owners(&[primary(10.0, true), primary(120.0, false)], false, menu); - assert_eq!((owners, open), (vec![true], false)); - // A press after the last release means that release is not the latest gesture. - let (_, _, later) = super::release_owners(&[primary(10.0, true), primary(10.0, false), primary(20.0, true)], false, menu); - assert!(later); - let (_, _, later) = super::release_owners(&[primary(10.0, true), primary(10.0, false)], false, menu); - assert!(!later); -} - -#[test] -fn a_keyword_past_the_bar_still_belongs_to_the_command_line() { - let mut app = crate::CadApp::new(cadcraft_engine::Session::new(), crate::Services::default()); - let bar = egui::Rect::from_min_size(egui::pos2(100.0, 500.0), egui::vec2(200.0, 24.0)); - // A long prompt: the last keyword sits right of the bar. - let keyword = egui::Rect::from_min_size(egui::pos2(320.0, 503.0), egui::vec2(40.0, 18.0)); - app.ui.show_command_line = true; - app.cmd.click_rect = Some(bar.union(keyword)); - assert!(super::widgets::over_command_line(&app, keyword.center())); - assert!(super::widgets::over_command_line(&app, bar.center())); - assert!(!super::widgets::over_command_line(&app, egui::pos2(380.0, 300.0))); - // A hidden command line leaves the canvas bare. - app.ui.show_command_line = false; - assert!(!super::widgets::over_command_line(&app, keyword.center())); -} diff --git a/crates/ui-egui/src/canvas/viewport.rs b/crates/ui-egui/src/canvas/viewport.rs index de6e86239..c79354b6c 100644 --- a/crates/ui-egui/src/canvas/viewport.rs +++ b/crates/ui-egui/src/canvas/viewport.rs @@ -129,7 +129,6 @@ pub(super) fn ensure_vp_content(app: &mut CadApp, xf_paper: &Xf, ctx: &egui::Con min_dash: 2f64.powi(band) * 2.0, text: true, fill: true, - hatch_budget: None, lineweights: lwdisplay, view_height: st.paper_view().height, plot_style_table: None, diff --git a/crates/ui-egui/src/canvas/widgets.rs b/crates/ui-egui/src/canvas/widgets.rs index 0892bf712..d10e40af3 100644 --- a/crates/ui-egui/src/canvas/widgets.rs +++ b/crates/ui-egui/src/canvas/widgets.rs @@ -84,73 +84,3 @@ pub(super) fn draw_viewcube(app: &mut CadApp, ui: &mut egui::Ui, rect: Rect) { let x = left + label.size().x + gap; p.line(vec![pos2(x, mid - 1.5), pos2(x + chevron / 2.0, mid + 1.5), pos2(x + chevron, mid - 1.5)], Stroke::new(1.2, ink)); } - -/// Whether this frame paints the ViewCube: never on a paper sheet. It follows the current space, not -/// the display list, which is rebuilt after the frame's clicks are handled and is stale (or cleared) -/// right after a layout switch. -pub(super) fn viewcube_shown(app: &CadApp) -> bool { - app.ui.show_viewcube && !matches!(app.session.layout_space(), cadcraft_doc::Space::Paper(_)) -} - -/// The command-line bar or one of its inline keywords, as painted last frame. -pub(super) fn over_command_line(app: &CadApp, p: Pos2) -> bool { - app.ui.show_command_line && app.cmd.click_rect.is_some_and(|r| r.contains(p)) -} - -/// Earlier releases in a batched frame cannot use `Response::hovered()` (it describes -/// only the final pointer position). Reuse the exact navigation widget hit rectangles. -pub(super) fn over_navigation_control(app: &CadApp, rect: Rect, p: Pos2) -> bool { - if app.ui.show_ucs_icon && crate::viewcube::ucs_arms(rect).iter().any(|r| r.contains(p)) { - return true; - } - if viewcube_shown(app) { - let layout = crate::viewcube::Layout::new(rect); - return layout.bounds.contains(p) || layout.pill.contains(p); - } - false -} - -#[cfg(test)] -mod tests { - use super::*; - use crate::Services; - use cadcraft_engine::Session; - - #[test] - fn navigation_control_hit_test_matches_displayed_viewcube() { - use cadcraft_geom::{Bounds2, Vec2}; - use cadcraft_render::DisplayList; - use egui::{Pos2, Rect, vec2}; - - let mut app = CadApp::new(Session::new(), Services::default()); - let rect = Rect::from_min_size(Pos2::ZERO, vec2(1000.0, 1000.0)); - let layout = crate::viewcube::Layout::new(rect); - let p = layout.center; - - // Model space: the ViewCube is displayed and hit-tested, with or without a display list. - app.canvas.list = None; - assert!(super::over_navigation_control(&app, rect, p)); - app.canvas.list = Some(DisplayList::default()); - assert!(super::over_navigation_control(&app, rect, p)); - - // Right after a switch to a layout the display list is still the model one (or cleared): the - // ViewCube is already gone, so a click there belongs to the drawing. - app.session.execute("layout.set", &serde_json::json!({"name": "Layout1"})).unwrap(); - assert!(matches!(app.session.layout_space(), cadcraft_doc::Space::Paper(_))); - assert!(!super::over_navigation_control(&app, rect, p)); - app.canvas.list = None; - assert!(!super::over_navigation_control(&app, rect, p)); - - // Back in the model the list may still hold the sheet, yet the ViewCube is displayed again. - app.session.execute("layout.set", &serde_json::json!({"name": "Model"})).unwrap(); - app.canvas.list = Some(DisplayList { - sheet: Some(cadcraft_render::paper::Sheet { - size: Vec2::new(100.0, 100.0), - printable: Bounds2::new(Vec2::ZERO, Vec2::new(100.0, 100.0)), - unit_mm: 1.0, - }), - ..Default::default() - }); - assert!(super::over_navigation_control(&app, rect, p)); - } -} diff --git a/crates/ui-egui/src/closing.rs b/crates/ui-egui/src/closing.rs index 93a1ef966..04d526fa2 100644 --- a/crates/ui-egui/src/closing.rs +++ b/crates/ui-egui/src/closing.rs @@ -343,15 +343,6 @@ mod tests { assert!(app.session.docs[0].is_dirty()); } - #[test] - fn close_all_typed_with_an_argument_still_asks_before_discarding() { - let mut app = app_with(&["A", "B"]); - dirty(&mut app, 1); - app.cmdline("CLOSEALL Y"); - assert_eq!(app.close_prompt(), Some("B")); - assert_eq!(titles(&app), ["B"]); - } - #[test] fn quitting_asks_about_each_dirty_drawing_then_quits() { let mut app = app_with(&["A", "B", "C"]); diff --git a/crates/ui-egui/src/cmdline.rs b/crates/ui-egui/src/cmdline.rs index a32cabd83..40397df99 100644 --- a/crates/ui-egui/src/cmdline.rs +++ b/crates/ui-egui/src/cmdline.rs @@ -38,9 +38,6 @@ pub struct CmdLine { /// The command line's editing rectangle and caret (screen) from the last frame, for the IME's /// composition window (see `enable_ime`). pub ime_rect: Option<(Rect, Rect)>, - /// The bar and every inline keyword hit rectangle from the last frame; a click there is the - /// command line's, never a point on the canvas (a long prompt pushes keywords past the bar). - pub click_rect: Option, /// The command line's IME context generation: a new one each time it starts collecting text, /// as egui asks of an IME owner that (re)gains focus. ime_generation: u64, @@ -480,7 +477,6 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { // Prompt glyph. p.text(pos2(bar.left() + 8.0, bar.center().y), egui::Align2::LEFT_CENTER, ">_", crate::theme::mono(), t.text_dim); let mut x = bar.left() + 30.0; - let mut click_rect = bar; let prompt = app.session.current_prompt(); let font = crate::theme::body(); match &prompt { @@ -506,7 +502,6 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { for (i, k) in kws.iter().enumerate() { let g = p.layout_no_wrap(k.clone(), font.clone(), t.cmd_keyword); let r = Rect::from_min_size(pos2(x, bar.top() + 3.0), vec2(g.size().x, h - 6.0)); - click_rect = click_rect.union(r); let resp = ui.interact(r, ui.scope_id().with(("kw", i)), Sense::click()); if resp.hovered() { p.rect_filled(r, 2.0, t.cmd_keyword_hover); @@ -576,9 +571,6 @@ pub fn show(app: &mut CadApp, ui: &mut egui::Ui, canvas: Rect) { // Where the IME's composition window follows: the whole command line and the caret in it. let caret = Rect::from_min_size(pos2(caret_x + 1.0, bar.top() + 5.0), vec2(1.0, h - 10.0)); app.cmd.ime_rect = Some((bar, caret)); - // The history lines or window, the resize grip and the AutoComplete rows are the command line's too. - let z = zones(app, canvas, bar); - app.cmd.click_rect = Some([Some(z.all), z.lines, z.window].into_iter().flatten().fold(click_rect, Rect::union)); // History chevron. crate::icons::paint( &p, diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 37860dfc2..4af579878 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -8,7 +8,6 @@ use serde_json::json; use crate::CadApp; use crate::theme::Tokens; -/// Render the currently active modal or floating dialog (`app.ui.dialog`). pub fn show(app: &mut CadApp, ctx: &egui::Context) { crate::mtext_editor::show(app, ctx); crate::quick::quick_properties(app, ctx); @@ -27,7 +26,6 @@ pub fn show(app: &mut CadApp, ctx: &egui::Context) { "about" => about(ctx, &mut open), "preview" => crate::exchange::dialog(app, ctx, &mut open), "commands" => commands(app, ctx, &mut open), - "blocks" => crate::blockmgr::dialog(app, ctx, &mut open), "bedit" => crate::bedit::dialog(app, ctx, &mut open), "authoring" => crate::bedit::authoring_dialog(app, ctx, &mut open), "stylesmanager" => crate::plotstyles::dialog(app, ctx, &mut open), @@ -397,21 +395,6 @@ fn commands(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { } } -/// Start INSERT with `name` already given at its block name prompt, so the next prompt asks for -/// the insertion point. -pub(crate) fn insert_block(app: &mut CadApp, name: &str) { - // The engine's INSERT itself (the UI's INSERT opens the Block Manager). - if let Err(e) = app.session.start("insert") { - app.session.echo(e.to_string()); - } - if app.session.running.as_ref().is_none_or(|r| r.id != "insert") { - return; - } - if let Err(e) = app.session.input(cadcraft_engine::Input::Text(name.to_string())) { - app.session.echo(e.to_string()); - } -} - /// Interface Language combo; selecting a language runs `ui.language` with its code. fn language(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { egui::Window::new(crate::tl!("Interface Language")).id(egui::Id::unique("interface_language")).open(open).resizable(false).show(ctx, |ui| { @@ -428,13 +411,6 @@ fn language(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) { #[cfg(test)] mod tests { - use cadcraft_engine::doc::EntityKind; - use cadcraft_engine::geom::Vec2; - use cadcraft_engine::{Input, Session}; - use serde_json::json; - - use crate::{CadApp, Services}; - #[test] fn fractional_length_precisions_list_binary_fractions() { let labels = ["1\"", "1/2\"", "1/4\"", "1/8\"", "1/16\"", "1/32\"", "1/64\"", "1/128\"", "1/256\""]; @@ -443,43 +419,4 @@ mod tests { assert_eq!(super::length_precisions(5), want); assert_eq!(super::length_precisions(2).len(), 9); } - - #[test] - fn picking_a_block_starts_insert_with_its_name() { - let mut app = CadApp::new(Session::new(), Services::default()); - let c = app.session.execute("circle", &json!({"center": [0, 0], "radius": 1})).unwrap(); - let h = c["handle"].as_str().unwrap().to_string(); - app.session.execute("block", &json!({"name": "Door 2", "base": [0, 0], "handles": [h], "keep": "delete"})).unwrap(); - // A command already running is replaced, as when a command is typed. - app.start("line"); - - super::insert_block(&mut app, "Door 2"); - assert!(app.session.running.as_ref().is_some_and(|r| r.id == "insert")); - assert_eq!(app.session.current_prompt().map(|p| p.message), Some("Specify insertion point".to_string())); - - app.session.input(Input::Point(Vec2::new(5.0, 6.0))).unwrap(); - // X scale, Y scale and rotation take their defaults. - for _ in 0..3 { - app.session.input(Input::Enter).unwrap(); - } - assert!(app.session.running.is_none()); - let d = app.session.doc().unwrap(); - let mut ins = Vec::new(); - for e in d.model.iter() { - if let EntityKind::Insert(i) = &e.kind { - ins.push(i.clone()); - } - } - assert_eq!(ins.len(), 1); - assert_eq!(ins[0].block, "Door 2"); - assert!((ins[0].insert.x - 5.0).abs() < 1e-9 && (ins[0].insert.y - 6.0).abs() < 1e-9); - } - - #[test] - fn picking_a_missing_block_keeps_asking_for_a_name() { - let mut app = CadApp::new(Session::new(), Services::default()); - super::insert_block(&mut app, "Nope"); - assert!(app.session.running.as_ref().is_some_and(|r| r.id == "insert")); - assert_eq!(app.session.current_prompt().map(|p| p.message), Some("Enter block name".to_string())); - } } diff --git a/crates/ui-egui/src/docking.rs b/crates/ui-egui/src/docking.rs index 82b98952a..cabcb5ec3 100644 --- a/crates/ui-egui/src/docking.rs +++ b/crates/ui-egui/src/docking.rs @@ -19,13 +19,11 @@ pub enum Panel { Properties, #[serde(rename = "externalReferences")] ExternalRefs, - /// The Block Manager as a panel. Blocks, } impl Panel { pub const ALL: &[Self] = &[Self::Canvas, Self::ToolSets, Self::Layers, Self::Properties, Self::ExternalRefs]; - /// Stable JSON identifier for this dock panel. pub fn id(self) -> &'static str { match self { Self::Canvas => "canvas", @@ -37,7 +35,6 @@ impl Panel { Self::Blocks => "blocks", } } - /// Human-readable panel title. fn label(self) -> &'static str { match self { Self::Canvas => "Drawing", @@ -155,7 +152,8 @@ fn home_anchor(layout: &Layout, 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::Blocks => &[(Panel::ExternalRefs, true), (Panel::Properties, true), (Panel::Layers, true)], + Panel::QuickCalc => &[(Panel::ExternalRefs, true), (Panel::Properties, true), (Panel::Layers, true)], + Panel::Blocks => &[(Panel::QuickCalc, true), (Panel::ExternalRefs, true), (Panel::Properties, true), (Panel::Layers, true)], }; if let Some(found) = neighbours.iter().copied().find(|(neighbour, _)| docked(layout, *neighbour)) { return Some(found); @@ -407,7 +405,6 @@ impl DockContent for Panels<'_> { } Panel::ToolSets => crate::palettes::toolsets(app, ui), Panel::QuickCalc => crate::palettes::quickcalc::show(app, ui), - Panel::Blocks => crate::blockmgr::panel(app, ui), Panel::Layers => { egui::ScrollArea::vertical() .id_salt("dock-layers") @@ -422,6 +419,12 @@ impl DockContent for Panels<'_> { Panel::ExternalRefs => { egui::ScrollArea::both().id_salt("dock-xrefs").auto_shrink([false, false]).show(ui, |ui| crate::xrefs::section(app, ui)); } + Panel::Blocks => { + egui::ScrollArea::vertical() + .id_salt("dock-blocks") + .auto_shrink([false, false]) + .show(ui, |ui| crate::blocks_palette::section(app, ui)); + } } } fn logical_label(&self, panel: &Panel) -> String { @@ -448,9 +451,9 @@ fn panel_limits(panel: &Panel) -> PanelLimits { let (min, max_width) = match panel { Panel::Canvas => (egui::vec2(300.0, 180.0), 1_000_000.0), Panel::QuickCalc => (egui::vec2(240.0, 160.0), 600.0), - Panel::Blocks => (egui::vec2(240.0, 200.0), 600.0), Panel::ToolSets => (egui::vec2(220.0, 150.0), 480.0), Panel::Layers | Panel::Properties | Panel::ExternalRefs => (egui::vec2(220.0, 100.0), 720.0), + Panel::Blocks => (egui::vec2(240.0, 260.0), 720.0), }; PanelLimits { min, max: egui::vec2(max_width, 1_000_000.0) } } diff --git a/crates/ui-egui/src/i18n/ar.tsv b/crates/ui-egui/src/i18n/ar.tsv index 37927afc8..343055be2 100644 --- a/crates/ui-egui/src/i18n/ar.tsv +++ b/crates/ui-egui/src/i18n/ar.tsv @@ -1242,12 +1242,29 @@ menu View عرض Check for Updates… التحقق من وجود تحديثات… CADCraft is up to date. CADCraft محدّث. Could not check for updates. تعذّر التحقق من وجود تحديثات. - Preview pending المعاينة قيد الانتظار - Preview unavailable المعاينة غير متاحة - No visible content لا يوجد محتوى مرئي - Empty block كتلة فارغة - Excessive preview input بيانات إدخال المعاينة كبيرة جدًا - Excessive preview computation حساب المعاينة مفرط - Excessive preview output مخرجات المعاينة كبيرة جدًا - Invalid preview data بيانات معاينة غير صالحة - Missing block reference مرجع الكتلة مفقود + Add a drawing file as a block library إضافة ملف رسم كمكتبة كتل + Add a folder of drawings or a drawing file to use its blocks. أضف مجلدًا يحتوي على رسومات أو ملف رسم لاستخدام كتله. + Block Libraries مكتبات الكتل + Block Library مكتبة الكتل + Blocks Palette لوحة الكتل + Click a block, then pick its insertion point. انقر على كتلة ثم حدّد نقطة إدراجها. + Current Drawing الرسم الحالي + Details التفاصيل + Extra Large Icons أيقونات كبيرة جدًا + Folder or file مجلد أو ملف + Import Library Block استيراد كتلة من المكتبة + Insert and Explode إدراج وتفجير + Large Icons أيقونات كبيرة + Libraries المكتبات + Medium Icons أيقونات متوسطة + No block matches the filter. لا توجد كتلة تطابق عامل التصفية. + This block is already in the drawing, so its definition is used. هذه الكتلة موجودة بالفعل في الرسم، لذلك يتم استخدام تعريفها. + Open Library... فتح مكتبة... + Read the library again إعادة قراءة المكتبة + Refresh تحديث + Remove from the list إزالة من القائمة + Repeat Placement تكرار الوضع + Small Icons أيقونات صغيرة + This drawing has no blocks. لا يحتوي هذا الرسم على كتل. + This library has no drawings or blocks. لا تحتوي هذه المكتبة على رسومات أو كتل. + Only the first {n} are shown. يتم عرض أول {n} فقط. diff --git a/crates/ui-egui/src/i18n/bs.tsv b/crates/ui-egui/src/i18n/bs.tsv index 14565ce2f..7be4c6db2 100644 --- a/crates/ui-egui/src/i18n/bs.tsv +++ b/crates/ui-egui/src/i18n/bs.tsv @@ -1447,3 +1447,29 @@ menu Modify Izmijeni Save changes to block "{name}"? Sačuvati promjene u bloku „{name}”? Layouts Rasporedi Associate Poveži + Add a drawing file as a block library Dodaj datoteku crteža kao biblioteku blokova + Add a folder of drawings or a drawing file to use its blocks. Dodajte mapu s crtežima ili datoteku crteža da biste koristili njene blokove. + Block Libraries Biblioteke blokova + Block Library Biblioteka blokova + Blocks Palette Paleta blokova + Click a block, then pick its insertion point. Kliknite na blok, zatim odredite njegovu tačku umetanja. + Current Drawing Trenutni crtež + Details Detalji + Extra Large Icons Veoma velike ikone + Folder or file Mapa ili datoteka + Import Library Block Uvezi blok iz biblioteke + Insert and Explode Umetni i rastavi + Large Icons Velike ikone + Libraries Biblioteke + Medium Icons Srednje ikone + No block matches the filter. Nijedan blok ne odgovara filteru. + This block is already in the drawing, so its definition is used. Ovaj blok već postoji u crtežu, pa se koristi njegova definicija. + Open Library... Otvori biblioteku... + Read the library again Ponovo učitaj biblioteku + Refresh Osvježi + Remove from the list Ukloni s liste + Repeat Placement Ponovi postavljanje + Small Icons Male ikone + This drawing has no blocks. Ovaj crtež nema blokova. + This library has no drawings or blocks. Ova biblioteka nema crteža ni blokova. + Only the first {n} are shown. Prikazano je samo prvih {n}. diff --git a/crates/ui-egui/src/i18n/cs.tsv b/crates/ui-egui/src/i18n/cs.tsv index 0b39d8440..e764b759a 100644 --- a/crates/ui-egui/src/i18n/cs.tsv +++ b/crates/ui-egui/src/i18n/cs.tsv @@ -1227,12 +1227,29 @@ menu Modify Modifikace Check for Updates… Zkontrolovat aktualizace… CADCraft is up to date. CADCraft je aktuální. Could not check for updates. Aktualizace se nepodařilo zkontrolovat. - Preview pending Náhled čeká na zpracování - Preview unavailable Náhled není k dispozici - No visible content Žádný viditelný obsah - Empty block Prázdný blok - Excessive preview input Příliš mnoho vstupních dat náhledu - Excessive preview computation Příliš náročný výpočet náhledu - Excessive preview output Příliš velký výstup náhledu - Invalid preview data Neplatná data náhledu - Missing block reference Chybí odkaz na blok + Add a drawing file as a block library Přidat výkresový soubor jako knihovnu bloků + Add a folder of drawings or a drawing file to use its blocks. Přidejte složku s výkresy nebo výkresový soubor, abyste mohli používat jeho bloky. + Block Libraries Knihovny bloků + Block Library Knihovna bloků + Blocks Palette Paleta bloků + Click a block, then pick its insertion point. Klikněte na blok a poté určete jeho vkládací bod. + Current Drawing Aktuální výkres + Details Podrobnosti + Extra Large Icons Extra velké ikony + Folder or file Složka nebo soubor + Import Library Block Importovat blok z knihovny + Insert and Explode Vložit a rozložit + Large Icons Velké ikony + Libraries Knihovny + Medium Icons Střední ikony + No block matches the filter. Filtru neodpovídá žádný blok. + This block is already in the drawing, so its definition is used. Tento blok už v kresbě je, proto se použije jeho definice. + Open Library... Otevřít knihovnu... + Read the library again Načíst knihovnu znovu + Refresh Obnovit + Remove from the list Odebrat ze seznamu + Repeat Placement Opakovat umístění + Small Icons Malé ikony + This drawing has no blocks. Tento výkres neobsahuje žádné bloky. + This library has no drawings or blocks. Tato knihovna neobsahuje žádné výkresy ani bloky. + Only the first {n} are shown. Zobrazuje se pouze prvních {n}. diff --git a/crates/ui-egui/src/i18n/de.tsv b/crates/ui-egui/src/i18n/de.tsv index 31154936f..ee543d647 100644 --- a/crates/ui-egui/src/i18n/de.tsv +++ b/crates/ui-egui/src/i18n/de.tsv @@ -1044,12 +1044,30 @@ Check for Updates… Nach Updates suchen… CADCraft is up to date. CADCraft ist auf dem neuesten Stand. Could not check for updates. Die Suche nach Updates ist fehlgeschlagen. - Preview pending Vorschau ausstehend - Preview unavailable Vorschau nicht verfügbar - No visible content Kein sichtbarer Inhalt - Empty block Leerer Block - Excessive preview input Zu viele Eingabedaten für die Vorschau - Excessive preview computation Zu hoher Rechenaufwand für die Vorschau - Excessive preview output Vorschau-Ausgabe zu groß - Invalid preview data Ungültige Vorschaudaten - Missing block reference Blockverweis fehlt + Add a drawing file as a block library Zeichnungsdatei als Blockbibliothek hinzufügen + Add a folder of drawings or a drawing file to use its blocks. Fügen Sie einen Ordner mit Zeichnungen oder eine Zeichnungsdatei hinzu, um deren Blöcke zu verwenden. + Block Libraries Blockbibliotheken + Block Library Blockbibliothek + Blocks Palette Blockpalette + Click a block, then pick its insertion point. Klicken Sie auf einen Block und geben Sie dann den Einfügepunkt an. + Current Drawing Aktuelle Zeichnung + Details Details + Extra Large Icons Extragroße Symbole + Folder or file Ordner oder Datei + Import Library Block Bibliotheksblock importieren + Insert and Explode Einfügen und auflösen + Large Icons Große Symbole + Libraries Bibliotheken + Medium Icons Mittelgroße Symbole + No block matches the filter. Kein Block entspricht dem Filter. + This block is already in the drawing, so its definition is used. Dieser Block ist bereits in der Zeichnung, daher wird seine Definition verwendet. + Open Library... Bibliothek öffnen... + Read the library again Bibliothek erneut lesen + Refresh Aktualisieren + Remove from the list Aus der Liste entfernen + Repeat Placement Platzierung wiederholen + Small Icons Kleine Symbole + This drawing has no blocks. Diese Zeichnung enthält keine Blöcke. + This library has no drawings or blocks. Diese Bibliothek enthält keine Zeichnungen oder Blöcke. + Options Optionen + Only the first {n} are shown. Nur die ersten {n} werden angezeigt. diff --git a/crates/ui-egui/src/i18n/el.tsv b/crates/ui-egui/src/i18n/el.tsv index 24b64d1ad..713a21064 100644 --- a/crates/ui-egui/src/i18n/el.tsv +++ b/crates/ui-egui/src/i18n/el.tsv @@ -1338,12 +1338,29 @@ menu View Προβολή Check for Updates… Έλεγχος για ενημερώσεις… CADCraft is up to date. Το CADCraft είναι ενημερωμένο. Could not check for updates. Δεν ήταν δυνατός ο έλεγχος για ενημερώσεις. - Preview pending Η προεπισκόπηση εκκρεμεί - Preview unavailable Η προεπισκόπηση δεν είναι διαθέσιμη - No visible content Κανένα ορατό περιεχόμενο - Empty block Κενό μπλοκ - Excessive preview input Υπερβολικά δεδομένα εισόδου προεπισκόπησης - Excessive preview computation Υπερβολικός υπολογισμός προεπισκόπησης - Excessive preview output Υπερβολικά μεγάλη έξοδος προεπισκόπησης - Invalid preview data Μη έγκυρα δεδομένα προεπισκόπησης - Missing block reference Λείπει η αναφορά μπλοκ + Add a drawing file as a block library Προσθήκη αρχείου σχεδίου ως βιβλιοθήκης μπλοκ + Add a folder of drawings or a drawing file to use its blocks. Προσθέστε έναν φάκελο με σχέδια ή ένα αρχείο σχεδίου για να χρησιμοποιήσετε τα μπλοκ του. + Block Libraries Βιβλιοθήκες μπλοκ + Block Library Βιβλιοθήκη μπλοκ + Blocks Palette Παλέτα μπλοκ + Click a block, then pick its insertion point. Κάντε κλικ σε ένα μπλοκ και μετά ορίστε το σημείο εισαγωγής του. + Current Drawing Τρέχον σχέδιο + Details Λεπτομέρειες + Extra Large Icons Πολύ μεγάλα εικονίδια + Folder or file Φάκελος ή αρχείο + Import Library Block Εισαγωγή μπλοκ βιβλιοθήκης + Insert and Explode Εισαγωγή και διάσπαση + Large Icons Μεγάλα εικονίδια + Libraries Βιβλιοθήκες + Medium Icons Μεσαία εικονίδια + No block matches the filter. Κανένα μπλοκ δεν ταιριάζει με το φίλτρο. + This block is already in the drawing, so its definition is used. Αυτό το μπλοκ υπάρχει ήδη στο σχέδιο, οπότε χρησιμοποιείται ο ορισμός του. + Open Library... Άνοιγμα βιβλιοθήκης... + Read the library again Επανάγνωση της βιβλιοθήκης + Refresh Ανανέωση + Remove from the list Αφαίρεση από τη λίστα + Repeat Placement Επανάληψη τοποθέτησης + Small Icons Μικρά εικονίδια + This drawing has no blocks. Αυτό το σχέδιο δεν έχει μπλοκ. + This library has no drawings or blocks. Αυτή η βιβλιοθήκη δεν έχει σχέδια ή μπλοκ. + Only the first {n} are shown. Εμφανίζονται μόνο τα πρώτα {n}. diff --git a/crates/ui-egui/src/i18n/es.tsv b/crates/ui-egui/src/i18n/es.tsv index 6351f966c..4e71e21a2 100644 --- a/crates/ui-egui/src/i18n/es.tsv +++ b/crates/ui-egui/src/i18n/es.tsv @@ -1258,12 +1258,29 @@ Check for Updates… Buscar actualizaciones… CADCraft is up to date. CADCraft está actualizado. Could not check for updates. No se pudo buscar actualizaciones. - Preview pending Vista previa pendiente - Preview unavailable Vista previa no disponible - No visible content Sin contenido visible - Empty block Bloque vacío - Excessive preview input Demasiados datos de entrada para la vista previa - Excessive preview computation Cálculo excesivo para la vista previa - Excessive preview output Salida de la vista previa demasiado grande - Invalid preview data Datos de vista previa no válidos - Missing block reference Falta la referencia de bloque + Add a drawing file as a block library Añadir un archivo de dibujo como biblioteca de bloques + Add a folder of drawings or a drawing file to use its blocks. Añada una carpeta de dibujos o un archivo de dibujo para usar sus bloques. + Block Libraries Bibliotecas de bloques + Block Library Biblioteca de bloques + Blocks Palette Paleta de bloques + Click a block, then pick its insertion point. Haga clic en un bloque y luego indique su punto de inserción. + Current Drawing Dibujo actual + Details Detalles + Extra Large Icons Iconos extragrandes + Folder or file Carpeta o archivo + Import Library Block Importar bloque de biblioteca + Insert and Explode Insertar y descomponer + Large Icons Iconos grandes + Libraries Bibliotecas + Medium Icons Iconos medianos + No block matches the filter. Ningún bloque coincide con el filtro. + This block is already in the drawing, so its definition is used. Este bloque ya está en el dibujo, así que se usa su definición. + Open Library... Abrir biblioteca... + Read the library again Volver a leer la biblioteca + Refresh Actualizar + Remove from the list Quitar de la lista + Repeat Placement Repetir colocación + Small Icons Iconos pequeños + This drawing has no blocks. Este dibujo no tiene bloques. + This library has no drawings or blocks. Esta biblioteca no tiene dibujos ni bloques. + Only the first {n} are shown. Solo se muestran los primeros {n}. diff --git a/crates/ui-egui/src/i18n/fr.tsv b/crates/ui-egui/src/i18n/fr.tsv index 82f30ce61..e2a47a748 100644 --- a/crates/ui-egui/src/i18n/fr.tsv +++ b/crates/ui-egui/src/i18n/fr.tsv @@ -1014,46 +1014,33 @@ Not a number or distance: {text} Ni un nombre ni une distance : {text} Query Texts Interroger les textes Analyze Shapes Analyser les formes - View mode Mode d'affichage - Medium Icons Icône moyenne - Large Icons Grande icône - Repeat placement Répéter le placement - Grab on click Prendre en main au clic - Specify scale on screen when placing Spécifier l'échelle à l'écran lors de la pose - Specify rotation angle on screen when placing Spécifier l'angle de rotation à l'écran lors de la pose - Click or drag to take in hand, then click on the drawing to place Cliquer ou faire glisser pour prendre en main, puis cliquer sur le dessin pour déposer - Click or drag a block to take it in hand, then click on the drawing to place Cliquer ou faire glisser un bloc pour le prendre en main, puis cliquer sur le dessin pour le déposer - No blocks match the search. Aucun bloc ne correspond à la recherche. - Block Manager Gestionnaire de blocs - Search: Rechercher : - Making a preview... Création de l'aperçu... - Edit Block Modifier le bloc - Open in the Block Editor Ouvrir dans l'éditeur de blocs - The block is in use and can't be deleted Ce bloc est utilisé et ne peut pas être supprimé - Finish or cancel the running INSERT first Termine ou annule d'abord la commande INSERT en cours - Exploded insertion uses the X scale for both axes L'insertion éclatée utilise l'échelle X pour les deux axes - Delete a block that no object uses Supprimer un bloc qu'aucun objet n'utilise - Save to File... Enregistrer dans un fichier... - Write the block as a drawing (WBLOCK) Enregistrer le bloc sous forme de dessin (WBLOCK) - Create... Créer... - Make a block from objects (BLOCK) Créer un bloc à partir d'objets (BLOCK) - Objects Objets - References Références - Base point Point de base - Annotative Annotatif - External reference Référence externe - Options Options - Float as a window Détacher en fenêtre - Pin as a panel on the right Épingler en panneau à droite Check for Updates… Rechercher des mises à jour… CADCraft is up to date. CADCraft est à jour. Could not check for updates. Impossible de rechercher les mises à jour. - Preview pending Aperçu en attente - Preview unavailable Aperçu indisponible - No visible content Aucun contenu visible - Empty block Bloc vide - Excessive preview input Données d’entrée trop volumineuses - Excessive preview computation Coût de calcul excessif - Excessive preview output Sortie de l’aperçu trop volumineuse - Invalid preview data Données invalides pour l’aperçu - Missing block reference Référence de bloc manquante + Add a drawing file as a block library Ajouter un fichier de dessin comme bibliothèque de blocs + Add a folder of drawings or a drawing file to use its blocks. Ajoutez un dossier de dessins ou un fichier de dessin pour utiliser ses blocs. + Block Libraries Bibliothèques de blocs + Block Library Bibliothèque de blocs + Blocks Palette Palette des blocs + Click a block, then pick its insertion point. Cliquez sur un bloc, puis indiquez son point d'insertion. + Current Drawing Dessin courant + Details Détails + Extra Large Icons Très grandes icônes + Folder or file Dossier ou fichier + Import Library Block Importer un bloc de bibliothèque + Insert and Explode Insérer et décomposer + Large Icons Grandes icônes + Libraries Bibliothèques + Medium Icons Icônes moyennes + No block matches the filter. Aucun bloc ne correspond au filtre. + This block is already in the drawing, so its definition is used. Ce bloc est déjà dans le dessin ; sa définition est utilisée. + Open Library... Ouvrir une bibliothèque... + Read the library again Relire la bibliothèque + Refresh Actualiser + Remove from the list Retirer de la liste + Repeat Placement Répéter le placement + Small Icons Petites icônes + This drawing has no blocks. Ce dessin ne contient aucun bloc. + This library has no drawings or blocks. Cette bibliothèque ne contient ni dessin ni bloc. + Options Options + Only the first {n} are shown. Seuls les {n} premiers sont affichés. diff --git a/crates/ui-egui/src/i18n/hu.tsv b/crates/ui-egui/src/i18n/hu.tsv index 62cd6f92f..1d0c05e0a 100644 --- a/crates/ui-egui/src/i18n/hu.tsv +++ b/crates/ui-egui/src/i18n/hu.tsv @@ -1349,12 +1349,29 @@ menu View Nézet Check for Updates… Frissítések keresése… CADCraft is up to date. A CADCraft naprakész. Could not check for updates. A frissítések keresése nem sikerült. - Preview pending Előnézet függőben - Preview unavailable Az előnézet nem érhető el - No visible content Nincs látható tartalom - Empty block Üres blokk - Excessive preview input Túl sok bemeneti adat az előnézethez - Excessive preview computation Túl nagy számítási igény az előnézethez - Excessive preview output Túl nagy előnézeti kimenet - Invalid preview data Érvénytelen előnézeti adatok - Missing block reference Hiányzó blokkhivatkozás + Add a drawing file as a block library Rajzfájl hozzáadása blokkkönyvtárként + Add a folder of drawings or a drawing file to use its blocks. Adj hozzá egy rajzokat tartalmazó mappát vagy egy rajzfájlt, hogy használhasd a blokkjait. + Block Libraries Blokkkönyvtárak + Block Library Blokkkönyvtár + Blocks Palette Blokkpaletta + Click a block, then pick its insertion point. Kattints egy blokkra, majd add meg a beszúrási pontját. + Current Drawing Aktuális rajz + Details Részletek + Extra Large Icons Extra nagy ikonok + Folder or file Mappa vagy fájl + Import Library Block Könyvtárblokk importálása + Insert and Explode Beszúrás és szétbontás + Large Icons Nagy ikonok + Libraries Könyvtárak + Medium Icons Közepes ikonok + No block matches the filter. Egy blokk sem felel meg a szűrőnek. + This block is already in the drawing, so its definition is used. Ez a blokk már szerepel a rajzban, ezért a meglévő definícióját használjuk. + Open Library... Könyvtár megnyitása... + Read the library again Könyvtár újraolvasása + Refresh Frissítés + Remove from the list Eltávolítás a listáról + Repeat Placement Elhelyezés ismétlése + Small Icons Kis ikonok + This drawing has no blocks. Ez a rajz nem tartalmaz blokkokat. + This library has no drawings or blocks. Ez a könyvtár nem tartalmaz rajzokat vagy blokkokat. + Only the first {n} are shown. Csak az első {n} látható. diff --git a/crates/ui-egui/src/i18n/it.tsv b/crates/ui-egui/src/i18n/it.tsv index bc4b8ddea..a4858ffa2 100644 --- a/crates/ui-egui/src/i18n/it.tsv +++ b/crates/ui-egui/src/i18n/it.tsv @@ -1367,12 +1367,29 @@ menu Modify Edita Check for Updates… Verifica aggiornamenti… CADCraft is up to date. CADCraft è aggiornato. Could not check for updates. Impossibile verificare gli aggiornamenti. - Preview pending Anteprima in attesa - Preview unavailable Anteprima non disponibile - No visible content Nessun contenuto visibile - Empty block Blocco vuoto - Excessive preview input Dati di input dell'anteprima eccessivi - Excessive preview computation Calcolo dell'anteprima eccessivo - Excessive preview output Output dell'anteprima eccessivo - Invalid preview data Dati di anteprima non validi - Missing block reference Riferimento al blocco mancante + Add a drawing file as a block library Aggiungi un file di disegno come libreria di blocchi + Add a folder of drawings or a drawing file to use its blocks. Aggiungi una cartella di disegni o un file di disegno per usarne i blocchi. + Block Libraries Librerie di blocchi + Block Library Libreria di blocchi + Blocks Palette Tavolozza blocchi + Click a block, then pick its insertion point. Fai clic su un blocco, quindi indica il punto di inserimento. + Current Drawing Disegno corrente + Details Dettagli + Extra Large Icons Icone molto grandi + Folder or file Cartella o file + Import Library Block Importa blocco da libreria + Insert and Explode Inserisci ed esplodi + Large Icons Icone grandi + Libraries Librerie + Medium Icons Icone medie + No block matches the filter. Nessun blocco corrisponde al filtro. + This block is already in the drawing, so its definition is used. Questo blocco è già nel disegno, quindi viene usata la sua definizione. + Open Library... Apri libreria... + Read the library again Rileggi la libreria + Refresh Aggiorna + Remove from the list Rimuovi dall'elenco + Repeat Placement Ripeti posizionamento + Small Icons Icone piccole + This drawing has no blocks. Questo disegno non contiene blocchi. + This library has no drawings or blocks. Questa libreria non contiene disegni o blocchi. + Only the first {n} are shown. Vengono mostrati solo i primi {n}. diff --git a/crates/ui-egui/src/i18n/ko.tsv b/crates/ui-egui/src/i18n/ko.tsv index db50f24c6..6736c99fd 100644 --- a/crates/ui-egui/src/i18n/ko.tsv +++ b/crates/ui-egui/src/i18n/ko.tsv @@ -1247,12 +1247,29 @@ menu Modify 수정 Check for Updates… 업데이트 확인… CADCraft is up to date. CADCraft가 최신 버전입니다. Could not check for updates. 업데이트를 확인하지 못했습니다. - Preview pending 미리 보기 대기 중 - Preview unavailable 미리 보기를 사용할 수 없음 - No visible content 표시할 내용 없음 - Empty block 빈 블록 - Excessive preview input 미리 보기 입력 데이터가 너무 많음 - Excessive preview computation 미리 보기 계산량이 너무 많음 - Excessive preview output 미리 보기 출력이 너무 큼 - Invalid preview data 잘못된 미리 보기 데이터 - Missing block reference 블록 참조 없음 + Add a drawing file as a block library 도면 파일을 블록 라이브러리로 추가 + Add a folder of drawings or a drawing file to use its blocks. 블록을 사용하려면 도면이 들어 있는 폴더나 도면 파일을 추가하세요. + Block Libraries 블록 라이브러리 + Block Library 블록 라이브러리 + Blocks Palette 블록 팔레트 + Click a block, then pick its insertion point. 블록을 클릭한 다음 삽입점을 지정하세요. + Current Drawing 현재 도면 + Details 자세히 + Extra Large Icons 매우 큰 아이콘 + Folder or file 폴더 또는 파일 + Import Library Block 라이브러리 블록 가져오기 + Insert and Explode 삽입 후 분해 + Large Icons 큰 아이콘 + Libraries 라이브러리 + Medium Icons 보통 아이콘 + No block matches the filter. 필터와 일치하는 블록이 없습니다. + This block is already in the drawing, so its definition is used. 이 블록은 이미 도면에 있으므로 기존 정의를 사용합니다. + Open Library... 라이브러리 열기... + Read the library again 라이브러리 다시 읽기 + Refresh 새로 고침 + Remove from the list 목록에서 제거 + Repeat Placement 배치 반복 + Small Icons 작은 아이콘 + This drawing has no blocks. 이 도면에는 블록이 없습니다. + This library has no drawings or blocks. 이 라이브러리에는 도면이나 블록이 없습니다. + Only the first {n} are shown. 처음 {n}개만 표시됩니다. diff --git a/crates/ui-egui/src/i18n/pt_br.tsv b/crates/ui-egui/src/i18n/pt_br.tsv index d46b3f947..90a209e58 100644 --- a/crates/ui-egui/src/i18n/pt_br.tsv +++ b/crates/ui-egui/src/i18n/pt_br.tsv @@ -1256,12 +1256,29 @@ Check for Updates… Verificar atualizações… CADCraft is up to date. O CADCraft está atualizado. Could not check for updates. Não foi possível verificar atualizações. - Preview pending Pré-visualização pendente - Preview unavailable Pré-visualização indisponível - No visible content Nenhum conteúdo visível - Empty block Bloco vazio - Excessive preview input Dados de entrada da pré-visualização excessivos - Excessive preview computation Cálculo da pré-visualização excessivo - Excessive preview output Saída da pré-visualização excessiva - Invalid preview data Dados de pré-visualização inválidos - Missing block reference Referência de bloco ausente + Add a drawing file as a block library Adicionar um arquivo de desenho como biblioteca de blocos + Add a folder of drawings or a drawing file to use its blocks. Adicione uma pasta de desenhos ou um arquivo de desenho para usar seus blocos. + Block Libraries Bibliotecas de blocos + Block Library Biblioteca de blocos + Blocks Palette Paleta de blocos + Click a block, then pick its insertion point. Clique em um bloco e depois indique o ponto de inserção. + Current Drawing Desenho atual + Details Detalhes + Extra Large Icons Ícones extragrandes + Folder or file Pasta ou arquivo + Import Library Block Importar bloco da biblioteca + Insert and Explode Inserir e explodir + Large Icons Ícones grandes + Libraries Bibliotecas + Medium Icons Ícones médios + No block matches the filter. Nenhum bloco corresponde ao filtro. + This block is already in the drawing, so its definition is used. Este bloco já está no desenho, então sua definição é usada. + Open Library... Abrir biblioteca... + Read the library again Ler a biblioteca novamente + Refresh Atualizar + Remove from the list Remover da lista + Repeat Placement Repetir posicionamento + Small Icons Ícones pequenos + This drawing has no blocks. Este desenho não tem blocos. + This library has no drawings or blocks. Esta biblioteca não tem desenhos nem blocos. + Only the first {n} are shown. Apenas os primeiros {n} são exibidos. diff --git a/crates/ui-egui/src/i18n/ru.tsv b/crates/ui-egui/src/i18n/ru.tsv index f9dfaa65e..9f0d5d4a0 100644 --- a/crates/ui-egui/src/i18n/ru.tsv +++ b/crates/ui-egui/src/i18n/ru.tsv @@ -1018,12 +1018,30 @@ Check for Updates… Проверить обновления… CADCraft is up to date. У вас последняя версия CADCraft. Could not check for updates. Не удалось проверить обновления. - Preview pending Предпросмотр ожидается - Preview unavailable Предпросмотр недоступен - No visible content Нет видимого содержимого - Empty block Пустой блок - Excessive preview input Слишком много входных данных для предпросмотра - Excessive preview computation Слишком большой объём вычислений для предпросмотра - Excessive preview output Слишком большой результат предпросмотра - Invalid preview data Недопустимые данные предпросмотра - Missing block reference Отсутствует ссылка на блок + Add a drawing file as a block library Добавить файл чертежа как библиотеку блоков + Add a folder of drawings or a drawing file to use its blocks. Добавьте папку с чертежами или файл чертежа, чтобы использовать его блоки. + Block Libraries Библиотеки блоков + Block Library Библиотека блоков + Blocks Palette Палитра блоков + Click a block, then pick its insertion point. Щелкните блок, затем укажите точку вставки. + Current Drawing Текущий чертеж + Details Подробно + Extra Large Icons Огромные значки + Folder or file Папка или файл + Import Library Block Импортировать блок из библиотеки + Insert and Explode Вставить и расчленить + Large Icons Крупные значки + Libraries Библиотеки + Medium Icons Обычные значки + No block matches the filter. Нет блоков, соответствующих фильтру. + This block is already in the drawing, so its definition is used. Этот блок уже есть в чертеже, поэтому используется его определение. + Open Library... Открыть библиотеку... + Read the library again Прочитать библиотеку заново + Refresh Обновить + Remove from the list Убрать из списка + Repeat Placement Повторять размещение + Small Icons Мелкие значки + This drawing has no blocks. В этом чертеже нет блоков. + This library has no drawings or blocks. В этой библиотеке нет чертежей и блоков. + Options Параметры + Only the first {n} are shown. Показаны только первые {n}. diff --git a/crates/ui-egui/src/i18n/sv.tsv b/crates/ui-egui/src/i18n/sv.tsv index ef8e5c67e..f34e47c40 100644 --- a/crates/ui-egui/src/i18n/sv.tsv +++ b/crates/ui-egui/src/i18n/sv.tsv @@ -1451,12 +1451,29 @@ menu Modify Ändra Check for Updates… Sök efter uppdateringar… CADCraft is up to date. CADCraft är uppdaterat. Could not check for updates. Det gick inte att söka efter uppdateringar. - Preview pending Förhandsvisning väntar - Preview unavailable Förhandsvisning är inte tillgänglig - No visible content Inget synligt innehåll - Empty block Tomt block - Excessive preview input För mycket indata för förhandsvisningen - Excessive preview computation För omfattande beräkning för förhandsvisningen - Excessive preview output För stor utdata från förhandsvisningen - Invalid preview data Ogiltiga förhandsvisningsdata - Missing block reference Blockreferens saknas + Add a drawing file as a block library Lägg till en ritningsfil som blockbibliotek + Add a folder of drawings or a drawing file to use its blocks. Lägg till en mapp med ritningar eller en ritningsfil för att använda dess block. + Block Libraries Blockbibliotek + Block Library Blockbibliotek + Blocks Palette Blockpalett + Click a block, then pick its insertion point. Klicka på ett block och ange sedan dess infogningspunkt. + Current Drawing Aktuell ritning + Details Detaljer + Extra Large Icons Extra stora ikoner + Folder or file Mapp eller fil + Import Library Block Importera biblioteksblock + Insert and Explode Infoga och lös upp + Large Icons Stora ikoner + Libraries Bibliotek + Medium Icons Medelstora ikoner + No block matches the filter. Inget block matchar filtret. + This block is already in the drawing, so its definition is used. Det här blocket finns redan i ritningen, så dess definition används. + Open Library... Öppna bibliotek... + Read the library again Läs in biblioteket igen + Refresh Uppdatera + Remove from the list Ta bort från listan + Repeat Placement Upprepa placering + Small Icons Små ikoner + This drawing has no blocks. Den här ritningen har inga block. + This library has no drawings or blocks. Det här biblioteket har inga ritningar eller block. + Only the first {n} are shown. Endast de första {n} visas. diff --git a/crates/ui-egui/src/i18n/tests.rs b/crates/ui-egui/src/i18n/tests.rs index d1e86ed2c..7a31dc122 100644 --- a/crates/ui-egui/src/i18n/tests.rs +++ b/crates/ui-egui/src/i18n/tests.rs @@ -81,11 +81,11 @@ fn missing_commands_menus_tools_and_snap_labels(language: &str) -> Vec { sources.into_iter().filter(|s| !s.is_empty() && !catalog.contains_key(&("", *s))).map(str::to_string).collect() } -/// Collect UI string literals marked with `tl!` or `tf!` that are not yet present in `language`. fn missing_marked_ui_literals(language: &str) -> BTreeSet { let catalog = catalog(language).unwrap(); let modules = [ "xrefs", + "blocks_palette", "canvas", "chrome", "cmdline", @@ -96,7 +96,6 @@ fn missing_marked_ui_literals(language: &str) -> BTreeSet { "mtext_editor", "layers", "bedit", - "blockmgr", "palettes", "parametric", "quick", @@ -414,7 +413,6 @@ fn dialogs_render_in_every_language_and_keep_their_source_ids() { ("dsettings", "Drafting Settings"), ("about", "About CADCraft"), ("commands", "Command Reference"), - ("blocks", "Blocks"), ("layers", "Layer Properties Manager"), ("qselect", "Quick Select"), ("parameters", "Parameters Manager"), diff --git a/crates/ui-egui/src/i18n/tr.tsv b/crates/ui-egui/src/i18n/tr.tsv index 85a54808a..89a3a544e 100644 --- a/crates/ui-egui/src/i18n/tr.tsv +++ b/crates/ui-egui/src/i18n/tr.tsv @@ -1352,12 +1352,29 @@ menu View Görünüm Check for Updates… Güncellemeleri denetle… CADCraft is up to date. CADCraft güncel. Could not check for updates. Güncellemeler denetlenemedi. - Preview pending Önizleme bekleniyor - Preview unavailable Önizleme kullanılamıyor - No visible content Görünür içerik yok - Empty block Boş blok - Excessive preview input Önizleme için çok fazla girdi verisi - Excessive preview computation Önizleme için aşırı hesaplama - Excessive preview output Önizleme çıktısı çok büyük - Invalid preview data Geçersiz önizleme verisi - Missing block reference Blok başvurusu eksik + Add a drawing file as a block library Çizim dosyasını blok kitaplığı olarak ekle + Add a folder of drawings or a drawing file to use its blocks. Bloklarını kullanmak için çizim içeren bir klasör veya bir çizim dosyası ekleyin. + Block Libraries Blok Kitaplıkları + Block Library Blok Kitaplığı + Blocks Palette Blok Paleti + Click a block, then pick its insertion point. Bir bloğa tıklayın, ardından yerleştirme noktasını belirtin. + Current Drawing Geçerli Çizim + Details Ayrıntılar + Extra Large Icons Çok Büyük Simgeler + Folder or file Klasör veya dosya + Import Library Block Kitaplık Bloğunu İçe Aktar + Insert and Explode Ekle ve Patlat + Large Icons Büyük Simgeler + Libraries Kitaplıklar + Medium Icons Orta Boy Simgeler + No block matches the filter. Filtreyle eşleşen blok yok. + This block is already in the drawing, so its definition is used. Bu blok çizimde zaten var, bu yüzden mevcut tanımı kullanılır. + Open Library... Kitaplık Aç... + Read the library again Kitaplığı yeniden oku + Refresh Yenile + Remove from the list Listeden kaldır + Repeat Placement Yerleştirmeyi Tekrarla + Small Icons Küçük Simgeler + This drawing has no blocks. Bu çizimde blok yok. + This library has no drawings or blocks. Bu kitaplıkta çizim veya blok yok. + Only the first {n} are shown. Yalnızca ilk {n} gösteriliyor. diff --git a/crates/ui-egui/src/i18n/uk.tsv b/crates/ui-egui/src/i18n/uk.tsv index 1bec51ce9..0cafc3b71 100644 --- a/crates/ui-egui/src/i18n/uk.tsv +++ b/crates/ui-egui/src/i18n/uk.tsv @@ -1375,13 +1375,30 @@ Check for Updates… Перевірити оновлення… CADCraft is up to date. Встановлено найновішу версію CADCraft. Could not check for updates. Не вдалося перевірити оновлення. - Preview pending Попередній перегляд очікується - Preview unavailable Попередній перегляд недоступний - No visible content Немає видимого вмісту - Empty block Порожній блок - Excessive preview input Забагато вхідних даних для попереднього перегляду - Excessive preview computation Надто великий обсяг обчислень для попереднього перегляду - Excessive preview output Надто великий результат попереднього перегляду - Invalid preview data Недійсні дані попереднього перегляду - Missing block reference Відсутнє посилання на блок Save changes to block "{name}"? Зберегти зміни в блоці «{name}»? + Add a drawing file as a block library Додати файл креслення як бібліотеку блоків + Add a folder of drawings or a drawing file to use its blocks. Додайте теку з кресленнями або файл креслення, щоб використовувати його блоки. + Block Libraries Бібліотеки блоків + Block Library Бібліотека блоків + Blocks Palette Палітра блоків + Click a block, then pick its insertion point. Клацніть блок, потім укажіть точку вставлення. + Current Drawing Поточне креслення + Details Докладно + Extra Large Icons Дуже великі піктограми + Folder or file Тека або файл + Import Library Block Імпортувати блок із бібліотеки + Insert and Explode Вставити й розчленувати + Large Icons Великі піктограми + Libraries Бібліотеки + Medium Icons Середні піктограми + No block matches the filter. Жоден блок не відповідає фільтру. + This block is already in the drawing, so its definition is used. Цей блок уже є в кресленні, тому використовується його визначення. + Open Library... Відкрити бібліотеку... + Read the library again Прочитати бібліотеку знову + Refresh Оновити + Remove from the list Прибрати зі списку + Repeat Placement Повторювати розміщення + Small Icons Малі піктограми + This drawing has no blocks. У цьому кресленні немає блоків. + This library has no drawings or blocks. У цій бібліотеці немає креслень і блоків. + Only the first {n} are shown. Показано лише перші {n}. diff --git a/crates/ui-egui/src/i18n/vi.tsv b/crates/ui-egui/src/i18n/vi.tsv index 9b1493031..e420a4802 100644 --- a/crates/ui-egui/src/i18n/vi.tsv +++ b/crates/ui-egui/src/i18n/vi.tsv @@ -1451,3 +1451,29 @@ menu Modify Hiệu chỉnh Change Properties Đổi thuộc tính Font Phông chữ Save Layout as Template Lưu layout thành mẫu + Add a drawing file as a block library Thêm tệp bản vẽ làm thư viện block + Add a folder of drawings or a drawing file to use its blocks. Thêm thư mục chứa bản vẽ hoặc tệp bản vẽ để dùng các block của nó. + Block Libraries Thư viện block + Block Library Thư viện block + Blocks Palette Bảng block + Click a block, then pick its insertion point. Nhấp vào một block, rồi chỉ định điểm chèn của nó. + Current Drawing Bản vẽ hiện hành + Details Chi tiết + Extra Large Icons Biểu tượng cực lớn + Folder or file Thư mục hoặc tệp + Import Library Block Nhập block từ thư viện + Insert and Explode Chèn và phân rã + Large Icons Biểu tượng lớn + Libraries Thư viện + Medium Icons Biểu tượng cỡ vừa + No block matches the filter. Không có block nào khớp với bộ lọc. + This block is already in the drawing, so its definition is used. Khối này đã có trong bản vẽ nên định nghĩa của nó được dùng. + Open Library... Mở thư viện... + Read the library again Đọc lại thư viện + Refresh Làm mới + Remove from the list Xóa khỏi danh sách + Repeat Placement Lặp lại việc đặt + Small Icons Biểu tượng nhỏ + This drawing has no blocks. Bản vẽ này không có block. + This library has no drawings or blocks. Thư viện này không có bản vẽ hay block. + Only the first {n} are shown. Chỉ hiển thị {n} mục đầu tiên. diff --git a/crates/ui-egui/src/i18n/zh.tsv b/crates/ui-egui/src/i18n/zh.tsv index fa768e82c..d4af1b313 100644 --- a/crates/ui-egui/src/i18n/zh.tsv +++ b/crates/ui-egui/src/i18n/zh.tsv @@ -1349,12 +1349,29 @@ Check for Updates… 检查更新… CADCraft is up to date. CADCraft 已是最新版本。 Could not check for updates. 无法检查更新。 - Preview pending 预览待处理 - Preview unavailable 预览不可用 - No visible content 没有可见内容 - Empty block 空块 - Excessive preview input 预览输入数据过多 - Excessive preview computation 预览计算量过大 - Excessive preview output 预览输出过大 - Invalid preview data 预览数据无效 - Missing block reference 缺少块引用 + Add a drawing file as a block library 将图形文件添加为块库 + Add a folder of drawings or a drawing file to use its blocks. 添加包含图形的文件夹或图形文件,以使用其中的块。 + Block Libraries 块库 + Block Library 块库 + Blocks Palette 块选项板 + Click a block, then pick its insertion point. 单击块,然后指定其插入点。 + Current Drawing 当前图形 + Details 详细信息 + Extra Large Icons 超大图标 + Folder or file 文件夹或文件 + Import Library Block 导入库中的块 + Insert and Explode 插入并分解 + Large Icons 大图标 + Libraries 库 + Medium Icons 中等图标 + No block matches the filter. 没有与筛选器匹配的块。 + This block is already in the drawing, so its definition is used. 此块已在图形中,因此使用其现有定义。 + Open Library... 打开库... + Read the library again 重新读取库 + Refresh 刷新 + Remove from the list 从列表中移除 + Repeat Placement 重复放置 + Small Icons 小图标 + This drawing has no blocks. 此图形中没有块。 + This library has no drawings or blocks. 此库中没有图形或块。 + Only the first {n} are shown. 仅显示前 {n} 个。 diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index 1ae1a91c3..175e080e5 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -21,7 +21,6 @@ pub mod aliasdlg; pub mod animation; pub mod autosave; pub mod bedit; -pub mod blockmgr; pub mod canvas; pub mod capture; pub mod chrome; @@ -41,6 +40,8 @@ pub mod switch; // The External References palette. pub mod xrefs; +pub mod blocks_palette; + pub mod dyngrips; pub mod dyninput; pub mod gpu; @@ -114,8 +115,6 @@ pub struct UiState { pub in_window_menu: bool, pub start_tab: bool, pub dialog: Option, - /// Show the Block Manager as a floating window instead of a right-hand panel. - pub blocks_window: bool, pub history_lines: usize, /// Interface theme: "system" (follow the OS light/dark appearance), "light" or "dark". pub theme: theme::ThemePref, @@ -180,7 +179,6 @@ impl SaveFormat { } impl Default for UiState { - /// Construct the default interface state for a new CADCraft session. fn default() -> Self { UiState { docking: docking::default_workspace(), @@ -203,7 +201,6 @@ impl Default for UiState { in_window_menu: !cfg!(target_os = "macos"), start_tab: false, dialog: None, - blocks_window: false, history_lines: 3, theme: theme::ThemePref::default(), animations: animation::AnimationPref::default(), @@ -397,7 +394,7 @@ impl CadApp { /// Run a command programmatically (or a UI command). pub fn run(&mut self, id: &str, params: Value) -> Result { - if let Some(r) = menus::run_ui_command(self, id, ¶ms, false) { + if let Some(r) = menus::run_ui_command(self, id, ¶ms) { return r; } let r = self.session.execute(id, ¶ms).map_err(|e| e.to_string()); @@ -416,7 +413,7 @@ impl CadApp { /// Start a command as if typed (interactive when it has prompts). pub fn start(&mut self, name: &str) { - if menus::run_ui_command(self, name, &Value::Null, true).is_some() { + if menus::run_ui_command(self, name, &Value::Null).is_some() { return; } if let Err(e) = self.session.start(name) { @@ -436,11 +433,9 @@ impl CadApp { pub fn cmdline_or(&mut self, text: &str, fallback: Option<&str>) -> Option { if !self.session.prompting() { let first = text.split_whitespace().next().unwrap_or(""); - let rest = text.trim_start().get(first.len()..).unwrap_or("").trim(); - // UI-intercepted commands run in the UI (INSERT opens the palette, CLOSEALL asks before discarding), - // except `{json}` calls and INSERT with inline arguments, which the engine command line takes. - let inline = rest.starts_with('{') || (!rest.is_empty() && matches!(first.to_ascii_lowercase().as_str(), "insert" | "i" | "ddinsert")); - if !first.is_empty() && !inline && menus::run_ui_command(self, &first.to_ascii_lowercase(), &Value::Null, true).is_some() { + // `cmd {json}` is a programmatic call: the engine runs it with those parameters. + let json_form = text.trim_start().get(first.len()..).is_some_and(|rest| rest.trim_start().starts_with('{')); + if !first.is_empty() && !json_form && menus::run_ui_command(self, &first.to_ascii_lowercase(), &Value::Null).is_some() { return None; } } @@ -482,9 +477,6 @@ impl CadApp { if let Some(dir) = &self.ui.last_lisp_dir { prefs["lispDir"] = json!(dir); } - if self.ui.blocks_window { - prefs["blocksWindow"] = json!(true); - } prefs.to_string() } @@ -515,9 +507,6 @@ impl CadApp { if let Some(dir) = v.get("lispDir").and_then(Value::as_str).filter(|d| !d.is_empty()) { self.ui.last_lisp_dir = Some(dir.to_string()); } - if let Some(w) = v.get("blocksWindow").and_then(Value::as_bool) { - self.ui.blocks_window = w; - } } /// Make the system cursor the interface default (`on`) and turn it on; saved preferences and @@ -1161,20 +1150,6 @@ mod tests { assert_eq!(ctx.options(|o| o.theme_preference), egui::ThemePreference::System); } - #[test] - fn the_blocks_window_choice_persists() { - let mut a = app(); - a.ui.blocks_window = true; - let mut b = app(); - b.load_prefs(&a.prefs_json()); - assert!(b.ui.blocks_window); - a.ui.blocks_window = false; - b.load_prefs(r#"{"blocksWindow": false}"#); - assert!(!b.ui.blocks_window); - b.load_prefs(r#"{"blocksWindow": "yes"}"#); - assert!(!b.ui.blocks_window, "malformed values are ignored"); - } - #[test] fn default_save_format_persists_and_names_new_drawings() { let mut a = app(); diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index f4989283b..89752dbd6 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -80,20 +80,21 @@ pub fn is_ui_command(id: &str) -> bool { UI_COMMANDS.iter().any(|c| c.0 == id) } -/// Run a UI command. `interactive` permits typed/menu INSERT to open the palette; -/// programmatic INSERT is left to the engine. `None` if `id` is not handled here. -pub fn run_ui_command(app: &mut CadApp, id: &str, params: &Value, interactive: bool) -> Option> { - crate::i18n::with_language(app.language(), || run_ui_command_inner(app, id, params, interactive)) +/// Run a UI-only command. `None` if `id` isn't one. +pub fn run_ui_command(app: &mut CadApp, id: &str, params: &Value) -> Option> { + crate::i18n::with_language(app.language(), || run_ui_command_inner(app, id, params)) } -/// Routes `id` to the UI-only subsystems; `None` when none of them handles it. -fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value, interactive: bool) -> Option> { +fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value) -> Option> { if let Some(result) = crate::spacemouse::route(app, id, params) { return Some(result); } if let Some(r) = crate::xrefs::route(app, id, params) { return Some(r); } + if let Some(r) = crate::blocks_palette::route(app, id, params) { + return Some(r); + } if let Some(r) = crate::bedit::route(app, id, params) { return Some(r); } @@ -110,11 +111,6 @@ fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value, interactive: if id == "ui.toggle.quickcalc" { return Some(crate::palettes::quickcalc::toggle(app)); } - // The Blocks button and INSERT typed or from a menu open the Block Manager (as AutoCAD's - // INSERT opens its Blocks palette); -INSERT and programmatic calls run the engine command. - if id == "ui.dialog.blocks" || (interactive && matches!(id, "insert" | "i" | "ddinsert") && params.is_null()) { - return Some(crate::blockmgr::open(app)); - } // Explicit opens remain idempotent; typed QUICKCALC with JSON parameters uses the engine's CAL alias. if id == "ui.panel.quickcalc" || (matches!(id, "quickcalc" | "qc") && params.is_null()) { return Some(crate::palettes::quickcalc::open(app)); @@ -309,14 +305,13 @@ fn should_pick_file_path(id: &str, params: &Value) -> bool { /// they report the loss in their result instead. fn user_qsave(app: &mut CadApp) -> Option> { if app.session.state().is_ok_and(|s| s.path.is_none()) { - return run_ui_command(app, "ui.saveas", &Value::Null, true); + return run_ui_command(app, "ui.saveas", &Value::Null); } app.hold_lossy_save().then_some(Ok(Value::Null)) } -/// Runs the UI-only command `id`, or returns `None` so the engine handles it. -fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value, interactive: bool) -> Option> { - if let Some(result) = route_ui_subsystems(app, id, params, interactive) { +fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option> { + if let Some(result) = route_ui_subsystems(app, id, params) { return Some(result); } // When a file command should ask for a file. The `ui.*` commands are the pickers; the engine's @@ -457,7 +452,6 @@ fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value, interactive: } "ui.dialog.language" | "ui.dialog.layers" - | "ui.dialog.blocks" | "ui.dialog.dsettings" | "ui.dialog.about" | "ui.dialog.commands" diff --git a/crates/ui-egui/tests/blocks_palette.rs b/crates/ui-egui/tests/blocks_palette.rs new file mode 100644 index 000000000..6dae47392 --- /dev/null +++ b/crates/ui-egui/tests/blocks_palette.rs @@ -0,0 +1,374 @@ +//! The Blocks palette: BLOCKSPALETTE opens it, it lists the drawing's blocks, a click +//! starts INSERT for the block, and the options settle the scale and rotation prompts. + +use cadcraft_engine::Session; +use cadcraft_ui_egui::{CadApp, Services, docking::Panel}; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +/// Make block `name` from everything in model space now (the objects are removed). +fn make_block(app: &mut CadApp, name: &str, description: &str) { + let handles: Vec = app.session.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect(); + app.run("block", json!({ "name": name, "base": [0, 0], "handles": handles, "keep": "delete", "description": description })).unwrap(); +} + +/// Blocks "Bolt" (a circle) and "Door" (a line, described "Hinged door"). +fn drawing() -> CadApp { + let mut app = CadApp::new(Session::default(), Services::default()); + app.run("circle", json!({ "center": [0, 0], "radius": 1 })).unwrap(); + make_block(&mut app, "Bolt", ""); + app.run("line", json!({ "points": [[0, 0], [2, 0]] })).unwrap(); + make_block(&mut app, "Door", "Hinged door"); + app +} + +fn harness(app: CadApp) -> Harness<'static, CadApp> { + let mut h = Harness::builder().with_size(vec2(1400.0, 900.0)).with_step_dt(1.0 / 60.0).build_ui_state( + |ui, app: &mut CadApp| { + app.logic(&ui.ctx().clone()); + app.ui(ui); + }, + app, + ); + h.run_steps(4); + h +} + +#[test] +fn blockspalette_opens_the_palette_and_lists_the_blocks() { + let mut app = drawing(); + assert!(app.cmdline("BLOCKSPALETTE").is_none()); + assert!(app.ui.docking.layout.contains(&Panel::Blocks)); + app.ui.in_window_menu = false; + let h = harness(app); + h.get_by_label("Door"); + h.get_by_label("Bolt"); +} + +#[test] +fn json_blockspalette_lists_and_never_opens_the_palette() { + let mut app = drawing(); + app.run("insert", json!({ "name": "Door", "at": [5, 5] })).unwrap(); + let r = app.run("blockspalette", json!({})).unwrap(); + assert_eq!( + r["blocks"], + json!([ + { "name": "Bolt", "description": "", "references": 0 }, + { "name": "Door", "description": "Hinged door", "references": 1 }, + ]) + ); + assert!(!app.ui.docking.layout.contains(&Panel::Blocks)); +} + +#[test] +fn a_click_starts_insert_for_the_block() { + let mut app = drawing(); + // Alone in the dock the palette has the whole column. + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + h.get_by_label("Door").click(); + h.run_steps(3); + let prompt = h.state().session.prompt_text(); + assert!(prompt.starts_with("INSERT Specify insertion point"), "{prompt}"); +} + +#[test] +fn options_are_off_while_placing_and_the_block_is_placed_again_until_cancelled() { + use cadcraft_engine::Input; + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + let inserts = |h: &Harness<'static, CadApp>| { + h.state().session.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::Insert(_))).count() + }; + assert!(!h.get_by_label("Repeat Placement").accesskit_node().is_disabled()); + h.get_by_label("Door").click(); + h.run_steps(3); + // Placing: the options are off. + assert!(h.get_by_label("Repeat Placement").accesskit_node().is_disabled()); + // The first block is placed and the same block is attached again (Repeat Placement is on). + h.state_mut().session.input(Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + h.run_steps(3); + assert_eq!(inserts(&h), 1); + assert!(h.state().session.prompt_text().starts_with("INSERT Specify insertion point"), "{}", h.state().session.prompt_text()); + h.state_mut().session.input(Input::Point(cadcraft_engine::geom::Vec2::new(9.0, 5.0))).unwrap(); + h.run_steps(3); + assert_eq!(inserts(&h), 2); + // Cancelling ends it: nothing is placed again and the options are back. + h.state_mut().session.input(Input::Cancel).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); + assert_eq!(inserts(&h), 2); + assert!(!h.get_by_label("Repeat Placement").accesskit_node().is_disabled()); +} + +#[test] +fn insert_started_by_the_palette_flow_waits_for_the_point() { + use cadcraft_engine::Input; + let mut app = drawing(); + app.session.start("insert").unwrap(); + app.session.input(Input::Text("Door".into())).unwrap(); + app.session.input(Input::Keyword("Scale".into())).unwrap(); + app.session.input(Input::Text("2".into())).unwrap(); + app.session.input(Input::Keyword("Rotate".into())).unwrap(); + app.session.input(Input::Text("90".into())).unwrap(); + assert!(app.session.prompt_text().starts_with("INSERT Specify insertion point"), "{}", app.session.prompt_text()); + app.session.input(Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + let ins = app.session.doc().unwrap().model.iter().find_map(|e| match &e.kind { + cadcraft_engine::doc::EntityKind::Insert(i) => Some(i.clone()), + _ => None, + }); + let ins = ins.expect("the block was inserted"); + assert_eq!(ins.block, "Door"); + assert!((ins.scale.x - 2.0).abs() < 1e-9); + assert!((ins.rotation - std::f64::consts::FRAC_PI_2).abs() < 1e-9); +} + +#[test] +fn the_palette_closes_and_reopens_where_it_was() { + let mut app = drawing(); + app.cmdline("BLOCKSPALETTE"); + assert!(app.ui.docking.layout.contains(&Panel::Blocks)); + app.run("ui.dock", json!({ "operation": "close", "panel": "blocks" })).unwrap(); + assert!(!app.ui.docking.layout.contains(&Panel::Blocks)); + app.cmdline("BLOCKSPALETTE"); + assert!(app.ui.docking.layout.contains(&Panel::Blocks)); +} + +/// Every library file reads as a drawing with a block "Valve" (a line), whatever its bytes. +fn read_library(_bytes: &[u8], _name: &str) -> Result { + use cadcraft_engine::doc::geom::Vec3; + use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, Handle, Line}; + let mut d = Drawing::new_metric(); + let mut valve = Block::new("Valve"); + valve.entities.push(Entity::new(Handle(0x70), EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(4.0, 0.0, 0.0) }))); + d.blocks.insert("Valve".into(), std::sync::Arc::new(valve)); + Ok(d) +} + +#[test] +fn a_library_is_added_listed_placed_and_removed() { + use cadcraft_engine::cmd::file::{IoHooks, set_io}; + set_io(IoHooks { read: read_library, write: |_, _| Err("no writer in this test".into()), plot: None }); + // No settings folder: the real library list is never written. + cadcraft_engine::settings_dir::set(None); + let dir = std::env::temp_dir().join(format!("cadcraft-blocks-palette-{}", std::process::id())); + std::fs::create_dir_all(&dir).unwrap(); + let file = dir.join("valves.dxf"); + std::fs::write(&file, b"x").unwrap(); + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.run("blocklibraries", json!({ "op": "add", "path": file.to_string_lossy() })).unwrap(); + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + + // The Libraries tab lists the library; choosing it shows its blocks. + h.get_by_label("Libraries").click(); + h.run_steps(3); + h.get_by_label("valves.dxf").click(); + h.run_steps(3); + h.get_by_label("Valve"); + assert!(h.state().session.doc().unwrap().block("Valve").is_none()); + + // Placing it defines the block here and waits for the insertion point. + h.get_by_label("Valve").click(); + h.run_steps(3); + assert!(h.state().session.doc().unwrap().block("Valve").is_some(), "{}", h.state().session.prompt_text()); + let prompt = h.state().session.prompt_text(); + assert!(prompt.starts_with("INSERT"), "{prompt}"); + h.state_mut().session.input(cadcraft_engine::Input::Cancel).unwrap(); + assert!(!h.state().status.as_ref().is_some_and(|(m, _)| m.contains("already in the drawing"))); + + // Placing it again uses the definition now in the drawing, and says so. + h.get_by_label("Valve").click(); + h.run_steps(3); + assert!(h.state().status.as_ref().is_some_and(|(m, _)| m.contains("already in the drawing")), "{:?}", h.state().status); + // A repeat placement of that block does not say it again. + h.state_mut().status = None; + h.state_mut().session.input(cadcraft_engine::Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + h.run_steps(3); + assert!(h.state().status.is_none(), "{:?}", h.state().status); + h.state_mut().session.input(cadcraft_engine::Input::Cancel).unwrap(); + + // Removing the library empties the list again. + h.get_by_label("Remove valves.dxf").click(); + h.run_steps(3); + let r = h.state_mut().run("blocklibraries", json!({})).unwrap(); + assert_eq!(r["libraries"], json!([])); + std::fs::remove_dir_all(&dir).unwrap(); +} + +#[test] +fn the_toolbar_icon_and_the_window_menu_open_the_palette_not_a_dialog() { + let mut app = drawing(); + app.run("ui.dialog.blocks", serde_json::Value::Null).unwrap(); + assert!(app.ui.docking.layout.contains(&Panel::Blocks)); + assert!(app.ui.dialog.is_none(), "the old Blocks window is gone"); + // Like the other ui.dialog.* ids, it opens whatever the parameters are. + let mut app = drawing(); + app.run("ui.dialog.blocks", json!({})).unwrap(); + assert!(app.ui.docking.layout.contains(&Panel::Blocks)); +} + +#[test] +fn repeat_placement_goes_on_when_the_block_is_placed_exploded() { + use cadcraft_engine::Input; + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + let count = |h: &Harness<'static, CadApp>, refs: bool| { + h.state().session.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::Insert(_)) == refs).count() + }; + h.get(egui_kittest::kittest::by().role(egui::accesskit::Role::CheckBox).label("Explode")).click(); + h.run_steps(2); + h.get_by_label("Door").click(); + h.run_steps(3); + // An exploded block leaves no reference, only its objects, and the next one is attached. + h.state_mut().session.input(Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + h.run_steps(3); + assert_eq!((count(&h, true), count(&h, false)), (0, 1)); + assert!(h.state().session.prompt_text().starts_with("INSERT Specify insertion point"), "{}", h.state().session.prompt_text()); + h.state_mut().session.input(Input::Point(cadcraft_engine::geom::Vec2::new(9.0, 5.0))).unwrap(); + h.run_steps(3); + assert_eq!((count(&h, true), count(&h, false)), (0, 2)); + // Cancelling still ends it. + h.state_mut().session.input(Input::Cancel).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); + assert_eq!(count(&h, false), 2); +} + +#[test] +fn a_hidden_palette_does_not_start_placing_again_when_it_comes_back() { + use cadcraft_engine::Input; + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + h.get_by_label("Door").click(); + h.run_steps(3); + // The palette goes away while the block is being placed, and other commands run. + h.state_mut().run("ui.dock", json!({ "operation": "close", "panel": "blocks" })).unwrap(); + h.run_steps(3); + h.state_mut().session.input(Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + h.state_mut().run("line", json!({ "points": [[0, 0], [2, 0]] })).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); + h.state_mut().run("blockspalette", serde_json::Value::Null).unwrap(); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:", "nothing is attached to the cursor"); +} + +#[test] +fn repeat_placement_does_not_carry_over_to_another_drawing() { + let mut app = drawing(); + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + let mut h = harness(app); + h.get_by_label("Door").click(); + h.run_steps(3); + // The user moves to a new drawing, whose handle counter is well past the first one's. + h.state_mut().session.new_drawing(true); + h.state_mut().session.running = None; + for _ in 0..20 { + h.state_mut().run("line", json!({ "points": [[0, 0], [2, 0]] })).unwrap(); + } + make_block(h.state_mut(), "Door", ""); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:", "nothing is attached in the other drawing"); +} + +/// How many INSERT references model space holds. +fn references(app: &CadApp) -> usize { + app.session.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_engine::doc::EntityKind::Insert(_))).count() +} + +fn open_palette(mut app: CadApp) -> Harness<'static, CadApp> { + for panel in ["layers", "properties"] { + app.run("ui.dock", json!({ "operation": "close", "panel": panel })).unwrap(); + } + app.cmdline("BLOCKSPALETTE"); + app.ui.in_window_menu = false; + harness(app) +} + +#[test] +fn escape_in_the_middle_of_a_drop_places_nothing_and_frees_the_options() { + let mut h = open_palette(drawing()); + h.get_by_label("Door").click(); + h.run_steps(3); + assert!(h.state().session.prompt_text().starts_with("INSERT")); + h.key_press(egui::Key::Escape); + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); + assert_eq!(references(h.state()), 0); + assert!(!h.get_by_label("Repeat Placement").accesskit_node().is_disabled()); + // And nothing is attached again afterwards. + h.run_steps(3); + assert_eq!(h.state().session.prompt_text(), "Command:"); +} + +#[test] +fn a_placed_block_is_one_undo_step() { + let mut h = open_palette(drawing()); + // Repeat off, so one click places one block. + h.get_by_label("Repeat Placement").click(); + h.run_steps(2); + h.get_by_label("Door").click(); + h.run_steps(3); + h.state_mut().session.input(cadcraft_engine::Input::Point(cadcraft_engine::geom::Vec2::new(5.0, 5.0))).unwrap(); + h.run_steps(3); + assert_eq!(references(h.state()), 1); + h.state_mut().run("undo", serde_json::Value::Null).unwrap(); + assert_eq!(references(h.state()), 0, "one undo takes the placed block away"); + assert!(h.state().session.doc().unwrap().block("Door").is_some(), "the block itself is still defined"); +} + +#[test] +fn a_tile_is_reachable_and_placed_from_the_keyboard() { + let mut h = open_palette(drawing()); + h.get_by_label("Door").focus(); + h.run_steps(2); + h.key_press(egui::Key::Enter); + h.run_steps(3); + assert!(h.state().session.prompt_text().starts_with("INSERT"), "{}", h.state().session.prompt_text()); +} + +#[test] +fn a_drawing_of_a_thousand_blocks_stays_responsive_and_bounded() { + let mut app = CadApp::new(Session::default(), Services::default()); + for i in 0..1000 { + app.run("circle", json!({ "center": [i, 0], "radius": 1 })).unwrap(); + make_block(&mut app, &format!("Part{i:04}"), ""); + } + let mut h = open_palette(app); + let started = std::time::Instant::now(); + h.run_steps(60); + // Only the visible tiles are drawn, a few per frame: 60 frames are nowhere near 1000 builds. + assert!(started.elapsed() < std::time::Duration::from_secs(30), "{:?}", started.elapsed()); + h.get_by_label("Part0000"); + assert!(h.state().session.prompt_text() == "Command:"); +} diff --git a/crates/ui-egui/tests/blocks_palette_review.rs b/crates/ui-egui/tests/blocks_palette_review.rs deleted file mode 100644 index 6655630b1..000000000 --- a/crates/ui-egui/tests/blocks_palette_review.rs +++ /dev/null @@ -1,151 +0,0 @@ -//! Regression for a selection menu click arriving as INSERT starts (#2122). -use cadcraft_engine::Session; -use cadcraft_geom::Vec2; -use cadcraft_ui_egui::{CadApp, Services}; -use egui::{Event, Modifiers, PointerButton, Pos2, vec2}; -use egui_kittest::Harness; -use serde_json::json; - -fn release(h: &mut Harness<'_, CadApp>, pos: Pos2) { - h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }); - h.event(Event::PointerButton { pos, button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }); -} - -/// The Blocks palette participates in the column-based DockContent renderer. -#[test] -fn docked_blocks_render_previews_and_reopen() { - use cadcraft_ui_egui::{blockmgr, docking::Panel}; - let mut session = Session::new(); - let circle = session.execute("circle", &json!({"center": [0, 0], "radius": 2})).unwrap(); - session.execute("block", &json!({"name": "Pin", "base": [0, 0], "handles": [circle["handle"]], "keep": "delete"})).unwrap(); - let mut app = CadApp::new(session, Services::default()); - app.ui.start_tab = false; - blockmgr::open(&mut app).unwrap(); - let shots = std::env::var_os("CADCRAFT_BLOCK_SHOTS").map(std::path::PathBuf::from); - let builder = Harness::builder().with_size(vec2(1600.0, 1000.0)); - let builder = if shots.is_some() { builder.wgpu() } else { builder }; - let mut h = builder.build_ui_state( - |ui, app: &mut CadApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); - h.run_steps(5); - assert!(h.state().ui.docking.layout.contains(&Panel::Blocks)); - assert!(h.state().ui.docking.layout.floating.is_empty()); - assert_eq!(blockmgr::cached_preview_count(&h.ctx), 1); - h.state_mut().run("ui.dock", json!({"operation": "close", "panel": "blocks"})).unwrap(); - h.run_steps(3); - assert!(!h.state().ui.docking.layout.contains(&Panel::Blocks)); - blockmgr::open(h.state_mut()).unwrap(); - h.run_steps(5); - assert!(h.state().ui.docking.layout.contains(&Panel::Blocks)); - assert_eq!(blockmgr::cached_preview_count(&h.ctx), 1); - if let Some(dir) = shots { - std::fs::create_dir_all(&dir).unwrap(); - h.render().unwrap().save(dir.join("docked-blocks-merge.png")).unwrap(); - } -} - -#[test] -fn selection_menu_click_cannot_place_a_block_when_insert_starts() { - let mut session = Session::new(); - let c = session.execute("circle", &json!({"center": [0, 0], "radius": 2})).unwrap(); - session.execute("block", &json!({"name": "Pin", "base": [0, 0], "handles": [c["handle"]], "keep": "delete"})).unwrap(); - for end in [10, 20] { - session.execute("line", &json!({"points": [[0, 0], [end, 0]]})).unwrap(); - } - session.execute("setvar", &json!({"name": "SELECTIONCYCLING", "value": 2})).unwrap(); - session.set_selection(Vec::new()); - let mut app = CadApp::new(session, Services::default()); - app.canvas.zoom_pending = true; - let shots = std::env::var_os("CADCRAFT_BLOCK_SHOTS").map(std::path::PathBuf::from); - let builder = Harness::builder().with_size(vec2(1600.0, 1000.0)); - let builder = if shots.is_some() { builder.wgpu() } else { builder }; - let mut h = builder.build_ui_state( - |ui, app: &mut CadApp| { - app.logic(ui.ctx()); - app.ui(ui); - }, - app, - ); - h.run_steps(3); - let at = h.state().canvas.xf.unwrap().to_screen(Vec2::new(5.0, 0.0)); - h.event(Event::PointerMoved(at)); - h.run_steps(1); - release(&mut h, at); - h.run_steps(2); - let rows = h.state().canvas.cycle_rows(); - assert_eq!(rows.len(), 2); - let row = rows[0].0.center(); - h.event(Event::PointerMoved(row)); - h.run_steps(2); - // Start placement between frames, while the old selection list is still on screen. - let st = cadcraft_ui_egui::blockmgr::State { repeat: true, ..Default::default() }; - cadcraft_ui_egui::blockmgr::grab_block(h.state_mut(), "Pin", &st); - release(&mut h, row); - h.run_steps(2); - assert_eq!(cadcraft_ui_egui::blockmgr::reference_count(h.state().session.doc().unwrap(), "Pin"), 0); - assert!(h.state().session.current_prompt().unwrap().accept.point); - // A subsequent click on bare canvas still places the block. - let clear = h.state().canvas.xf.unwrap().to_screen(Vec2::new(7.0, 3.0)); - h.event(Event::PointerMoved(clear)); - h.run_steps(1); - release(&mut h, clear); - h.run_steps(2); - assert_eq!(cadcraft_ui_egui::blockmgr::reference_count(h.state().session.doc().unwrap(), "Pin"), 1); - h.state_mut().session.cancel(); - h.state_mut().start("insert"); - h.run_steps(3); - if let Some(dir) = shots { - std::fs::create_dir_all(&dir).unwrap(); - h.render().unwrap().save(dir.join("blocks-palette.png")).unwrap(); - } -} - -/// Hatched blocks remain visible in the palette instead of empty placeholders. -#[test] -fn hatched_blocks_have_visible_palette_previews() { - use cadcraft_engine::doc::{Block, Drawing, Entity, EntityKind, Handle, Hatch, HatchLoop}; - use std::sync::Arc; - let mut drawing = Drawing::default(); - for (index, (name, solid, curved)) in - [("Solid hatch", true, false), ("Pattern hatch", false, false), ("Curved hatch", true, true)].into_iter().enumerate() - { - let mut hatch: Hatch = - serde_json::from_value(json!({"pattern": if solid { "SOLID" } else { "ANSI31" }, "solid": solid, "loops": []})).unwrap(); - let mut vertices: Vec<_> = [Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0), Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)] - .into_iter() - .map(cadcraft_geom::PolyVertex::new) - .collect(); - if curved { - vertices[0].bulge = 1.0; - } - hatch.loops.push(HatchLoop { vertices, outer: true, sources: Vec::new() }); - let mut block = Block::new(name); - block.entities.push(Entity::new(Handle(index as u64 + 1), EntityKind::Hatch(hatch))); - drawing.blocks.insert(name.into(), Arc::new(block)); - } - let mut session = Session::empty(); - session.open_drawing(drawing, "Hatch previews", None); - let mut app = CadApp::new(session, Services::default()); - app.ui.blocks_window = true; - app.start("insert"); - let shots = std::env::var_os("CADCRAFT_BLOCK_SHOTS").map(std::path::PathBuf::from); - let builder = Harness::builder().with_size(vec2(1000.0, 760.0)); - let builder = if shots.is_some() { builder.wgpu() } else { builder }; - let mut h = builder.build_ui_state( - |ui, app: &mut CadApp| { - cadcraft_ui_egui::theme::apply(ui.ctx(), egui::Theme::Dark, false); - cadcraft_ui_egui::dialogs::show(app, ui.ctx()); - }, - app, - ); - h.run_steps(5); - assert_eq!(cadcraft_ui_egui::blockmgr::cached_preview_count(&h.ctx), 3); - if let Some(dir) = shots { - std::fs::create_dir_all(&dir).unwrap(); - h.render().unwrap().save(dir.join("hatched-block-previews.png")).unwrap(); - } -} diff --git a/crates/ui-egui/tests/it/rapid_clicks.rs b/crates/ui-egui/tests/it/rapid_clicks.rs index e7593c449..1a750630d 100644 --- a/crates/ui-egui/tests/it/rapid_clicks.rs +++ b/crates/ui-egui/tests/it/rapid_clicks.rs @@ -96,37 +96,3 @@ fn a_click_made_while_the_mouse_moves_still_places_the_point() { assert_eq!(got.len(), 1, "{got:?}"); assert!(got[0].1.near(h.state().canvas.xf.unwrap().to_world(up), 1e-4), "{got:?}"); } - -/// Earlier pointer releases must respect controls on the same egui layer as the canvas. -#[test] -fn batched_clicks_skip_visible_navigation_controls() { - for show_controls in [true, false] { - for target in 0..4 { - let mut h = harness(); - h.state_mut().ui.show_viewcube = show_controls; - h.state_mut().ui.show_ucs_icon = show_controls; - h.run_steps(2); - start_line_at(&mut h, Vec2::new(10.0, 10.0)); - let rect = h.state().canvas.rect.unwrap(); - let cube = cadcraft_ui_egui::viewcube::Layout::new(rect); - let [x, y] = cadcraft_ui_egui::viewcube::ucs_arms(rect); - let control = match target { - 0 => cube.face.center(), - 1 => cube.pill.center(), - 2 => x.center(), - _ => y.center(), - }; - let bare = screen(&h, Vec2::new(40.0, 40.0)); - for pos in [control, bare] { - for pressed in [true, false] { - h.input_mut().events.push(Event::PointerMoved(pos)); - h.input_mut().events.push(Event::PointerButton { pos, button: PointerButton::Primary, pressed, modifiers: Modifiers::NONE }); - } - } - h.run_steps(2); - let got = lines(&h); - assert_eq!(got.len(), if show_controls { 1 } else { 2 }, "visible={show_controls}, target={target}: {got:?}"); - assert!(got.last().unwrap().1.near(Vec2::new(40.0, 40.0), 1e-4)); - } - } -} diff --git a/docs/block-preview-validation.md b/docs/block-preview-validation.md deleted file mode 100644 index 2a1f7768b..000000000 --- a/docs/block-preview-validation.md +++ /dev/null @@ -1,107 +0,0 @@ -# Block preview validation - -Validated locally on Windows, 2026-10-28. The baseline was `39f576a9`. -No library drawing, extracted geometry or screenshots are committed. Automated regression tests -use synthetic drawings. The opt-in release audit reads `CADCRAFT_LIBRARY` and writes diagnostics -to `CADCRAFT_AUDIT_DIR`; it is ignored in the normal test suite. - -## Behaviour and limits - -- Preview results distinguish ready geometry, no visible content and refusal. Only a definition - with zero entities is labelled **Empty block**. Refusals have translated hover explanations; - pending results are labelled separately. Palette insertion continues through the existing - INSERT command regardless of thumbnail success. -- Input is bounded separately in collection elements, text bytes and metadata bytes. Curve work - counts planned evaluations, spline basis iterations and input scans; expansion counts entities - and array copies. Output has independent primitive and vertex limits, reserved before growing - display-list buffers. Text shaping retains its existing bounded input and font-renderer limits. -- Splines share the geometry crate's tessellation and bounds-sampling plans. Bounds are charged - before sampling; render planning uses a 320-pixel reference extent, covering the largest tile. - Bulged polylines and hatch contours use the renderer's segment-count rules. Wide polylines - reserve triangles as well as their centre line. -- Hatches and polygon fills retain a shared work allowance before expensive fill operations. - A thumbnail whose allowance is exhausted is refused whole, including when the renderer could - return emergency contours. Normal canvas rendering keeps its existing behaviour. -- The LRU holds at most 512 results and an estimated 64 MiB, including refusals and empty results. - Estimates include collection capacities, owned keys and conservative index overhead. Drawing - UID or revision changes invalidate everything. Visibility influences eviction priority but - never overrides the caps. Results too large to fit become small cached refusals. -- At most three synchronous constructions start per frame. A 30 ms elapsed-time check defers - subsequent constructions; it cannot interrupt one already running. - -## Library audit - -The local DWG contains 364 named imported block definitions: - -| Result | Before | After | -|---|---:|---:| -| Ready preview | 358 | 360 | -| No visible content in a nonempty definition | 0 | 0 | -| Refused preview | 2 (visually ambiguous) | 0 | -| Imported definition with no entities | 4 | 4 | - -The four zero-entity definitions are `BALLON`, `CHAUDIERE MURALE`, `MITIGEUR BY-PASS` and -`Système de remplissage`. In particular, `MITIGEUR BY-PASS` has no imported geometry to preview; -this patch does not repair the DWG import or make claims about the original application's block. - -All named blocks were enumerated in the per-block CSV. Visually checked at 512 pixels and in -actual palette widgets: `GMAT_PAC_VIESSMANN_PURPLE`, `DIV_01_LEGENDE_ACCESSOIRES` and -`TUY_DEPART_DIRECT_POMPE_DOUBLE_ENERGIE`. The first now draws its equipment and connections; -the legend retains its symbols and labels, and the pump assembly retains its geometry and colours. -A separate French screenshot checks ready, empty, invisible, refused and pending tiles. - -## Release measurements - -Single release runs on the same local Windows machine (not latency guarantees): - -| Measurement | Before | After | -|---|---:|---:| -| Sum of all 364 first constructions | 163.434 ms | 146.399 ms | -| Median construction | 47.5 µs | 41 µs | -| Worst first construction (`04 ARRIVEE GAZ POSTE`, font initialisation) | 87.751 ms | 79.855 ms | -| `GMAT_PAC_VIESSMANN_PURPLE` | refused in 1.630 ms | ready in 2.599 ms | -| `DIV_01_LEGENDE_ACCESSOIRES` | 1.781 ms | 1.306 ms | -| `TUY_DEPART_DIRECT_POMPE_DOUBLE_ENERGIE` | 0.240 ms | 0.279 ms | -| Return-scroll reconstructions, pages of twelve blocks | 360 | 0 | - -With font caches already warm, all 364 constructions totalled 53.400 ms; the worst was -`GMAT_10_GROUPE_DOSAGE_EF`, 6.283 ms. The new cache retained all 364 results in an estimated -10,886,253 bytes (10.38 MiB). A cached twelve-thumbnail frame, including CPU tessellation, -took 1.012 ms at the median and 4.609 ms at worst. The old-policy reproduction started 364 -builds on the outward pass and 360 on return (127.762 ms total construction time with warm -font caches, under the renderer-linking qualification below). - -The baseline scroll-policy reproduction uses the budget/bounds/build functions from `39f576a9` -and the old `retain_visible` policy, linked against the local release geometry/render libraries. -Its construction counts are independent of that renderer difference; its elapsed time is not -presented as a strict renderer before/after benchmark. New-cache timings exercise actual palette -tiles, including egui CPU tessellation, with twelve visible thumbnails per frame; they exclude -GPU presentation and the rest of the application. - -Local diagnostic artifacts are under `target/preview-audit-before/` and -`target/preview-audit-after/`: per-block `library.csv`, the new-cache `cache.txt`, warmed-build -`warm.csv`, the palette image, French status image and the three detailed example images. -Reproduce the audit with: - -```text -cargo test --release -p cadcraft-ui-egui --lib local_library_audit -- --ignored --nocapture -``` - -Set the two environment variables first; no machine-specific path is required by automated tests. - -## Validation and remaining limits - -- 25 targeted block-palette tests passed; the added geometry sampling-plan regression also passed. -- `cargo xtask ci` passed all seven steps: fmt, clippy with warnings denied, workspace tests, - i18n checks, asset attribution, dependency layers and wasm. Tests needing sockets and atomic - temporary-file writes were run in the ordinary Windows session because the sandbox denied them. -- Two authenticated local CodeRabbit reviews completed. Their minor findings (timing-sensitive - test setup and a split Markdown revision table) were corrected. -- The local release audit and actual palette/status screenshots were inspected. All 364 results - fit the bounded cache and an outward/return tile traversal performed zero reconstructions. - -The first font-using block can still visibly pause a synchronous frame while fonts initialise. -No new block-name exception or arbitrary timeout hides that cost. There is no background worker -or persistent cache. The 64 MiB estimate covers this thumbnail cache, not font caches, temporary -rendering allocations, egui meshes, GPU memory or total application memory. Per-run timings are -measurements on this machine, not latency guarantees. Imported empty definitions remain empty. diff --git a/docs/ui-parity.md b/docs/ui-parity.md index d51f843e4..3522b5091 100644 --- a/docs/ui-parity.md +++ b/docs/ui-parity.md @@ -1,6 +1,6 @@ # UI parity -> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-28 · **Change:** minor (bounded reusable block previews with explicit refusal reasons) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) +> **Last reviewed:** 2026-10-10 · **Last updated:** 2026-10-27 · **Change:** minor (WIPEOUT closure-aware grips) · **Target:** Autodesk AutoCAD 2027 for Mac (26.0) How CADCraft's interaction compares with AutoCAD's: point entry, object snaps, tracking, dynamic input, grips, selection, the command line, chrome and navigation. A drafter's speed in AutoCAD @@ -161,7 +161,7 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | Tool Sets palette (Drafting, Modeling, … with flyouts) | yes | yes for 2D groups | | Properties Inspector, Quick Properties | yes | yes (every control acts or is visibly unavailable, #182); block references show read-only Position X/Y/Z from their stored insertion point; coordinate editing is still missing | | Layer Properties Manager (filters, states, VP overrides) | yes | yes | -| Blocks palette, Content | yes | Docked/floating Blocks palette with list and icon views, click/drag insertion and repeat placement (#2122). Escape outside placement preserves the repeat preference; double-click starts insertion once. Clicks on disappearing canvas menus do not place blocks; batched clicks also exclude visible ViewCube/WCS and UCS icon targets. Programmatic INSERT stays in the engine; block names and reference counts are cached by drawing/revision/selection. Hatch thumbnails retain fills and patterns within a shared work allowance; exhaustion reports an unavailable thumbnail rather than accepting partial contours. Thumbnail preflight separates input, curve/expansion work and retained output; spline and polyline estimates follow geometry sampling at thumbnail tolerance. A 64 MiB / 512-result LRU retains off-screen previews and refusals. Pending, empty, invisible and unavailable states are distinct, with a translated refusal reason on hover. Insertion is independent of preview success. Builds remain synchronous: the elapsed-time check only defers the next build. See [validation](block-preview-validation.md). | +| Blocks palette, Content | yes | Blocks window (click to insert, #28) | | Status bar toggles | ~25 | most toggles; Annotation Visibility and Workspace do nothing | | ViewCube | interactive 3D | clickable for 2D (Top/Home → extents); dragging does nothing (#7) | | Navigation bar, SteeringWheels | yes | no | @@ -206,10 +206,6 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. |---|---|---| | 2026-10-27 | minor | WIPEOUT grips treat implicit and explicit closure alike; moving the first vertex carries the closing marker, and moving endpoints together keeps both corners editable. Open/closed polyline flags and coincident polyline vertices remain independent (#2256) | | 2026-10-26 | minor | Browser host stores bounded, validated panel layout separately from drawing state; malformed or unsupported records retain defaults. Native workspace storage is unchanged. | -| 2026-10-25 | minor | Restore hatched-block thumbnails using bounded contours; retain full hatch fills/patterns in normal canvas and exports (#2122) | -| 2026-10-25 | minor | Batched canvas clicks respect visible ViewCube/WCS and UCS icon targets, including earlier releases in one frame; hidden controls do not reserve drawing space (#2122) | -| 2026-10-25 | minor | Blocks palette: separate interactive INSERT from JSON dispatch, consume clicks on disappearing canvas menus, cache names/reference counts, and reject automatic hatch previews before expensive processing (#2122) | -| 2026-10-25 | minor | Blocks palette: preserve repeat preference on unrelated Escape, avoid double-click restart, and preflight polyline vertex/tessellation costs before preview bounds and rendering (#2122) | | 2026-10-22 | minor | Polyline segment midpoint grips use rectangles, distinct from square vertex grips, with matching hover and pick bounds (#1950) | | 2026-10-13 | minor | Filled-region highlight boundaries are traversed in deterministic coordinate order, fixing dash-phase jumps on CPU hover/selection redraws and GPU highlight rebuilds; CPU dash-position, pixel and GPU mesh regressions | | 2026-10-14 | minor | Selection cycling (#1143): the list and badge of SELECTIONCYCLING, Shift+Space through overlapping objects (#1145) | @@ -226,4 +222,3 @@ down-arrow options menu (DYNPROMPT), and DYNDIM. | 2026-10-11 | minor | Object snap tracking, Extension, Parallel, Apparent Intersection, additional polar angles (#379): tracking 30% → 70%, object snaps 40% → 45%; total 43% → 48% | | 2026-10-10 | minor | Dynamic input 15% → 45% (pointer boxes, #60); press-drag windows (#63); total 40% → 43% | | 2026-10-10 | major | First UI-parity audit: point entry, snaps, tracking, dynamic input, grips, selection, command line, chrome, navigation, keys | -| 2026-10-28 | minor | Blocks palette: tolerance-based preflight, explicit failures, renderer output reservations and bounded LRU; 364 local library blocks audited, with visual checks and release measurements in [block-preview-validation.md](block-preview-validation.md) | diff --git a/packaging/linux/flatpak-bundle.sh b/packaging/linux/flatpak-bundle.sh index 5154fe076..5c84b8470 100755 --- a/packaging/linux/flatpak-bundle.sh +++ b/packaging/linux/flatpak-bundle.sh @@ -20,10 +20,12 @@ APP_ID=ai.storyteller.cadcraft FLATHUB=https://dl.flathub.org/repo/flathub.flatpakrepo TEST=1 +OCI=0 TARBALL="" while [[ $# -gt 0 ]]; do case "$1" in --no-test) TEST=0; shift ;; + --oci) OCI=1; shift ;; -h | --help) sed -n '2,14p' "$0"; exit 0 ;; -*) echo "unknown argument: $1" >&2; exit 2 ;; *) TARBALL="$1"; shift ;; @@ -61,6 +63,12 @@ OUT="$DIST/$BASENAME.flatpak" # --runtime-repo lets `flatpak install` fetch the freedesktop runtime from Flathub if missing. flatpak build-bundle --runtime-repo="$FLATHUB" "$WORK/repo" "$OUT" "$APP_ID" stable echo "wrote $OUT" +if [[ "$OCI" = 1 ]]; then + OUT_OCI="$DIST/$BASENAME-oci" + rm -rf "$OUT_OCI" + flatpak build-bundle --oci "$WORK/repo" "$OUT_OCI" "$APP_ID" stable + echo "wrote OCI layout to $OUT_OCI" +fi if [[ "$TEST" = 1 ]]; then flatpak install --user -y --noninteractive --reinstall "$OUT" diff --git a/packaging/linux/flatpak-oci.sh b/packaging/linux/flatpak-oci.sh new file mode 100755 index 000000000..d2d2e0f25 --- /dev/null +++ b/packaging/linux/flatpak-oci.sh @@ -0,0 +1,64 @@ +#!/usr/bin/env bash +# Build cadcraft as an OCI container layout and push it to GitHub Container Registry (GHCR) +# for consumption by Flatpak OCI clients (flatpak-oci-specs). +# +# Usage: +# packaging/linux/flatpak-oci.sh [--push] [TARBALL] +# +# Environment variables: +# REGISTRY Target registry image (default: ghcr.io/storytold/cadcraft) +# TAG Target image tag (default: $VERSION-$ARCH, also tags stable-$ARCH) +# GITHUB_TOKEN Token for GHCR authentication when --push is used +set -euo pipefail +# shellcheck source=../env.sh +. "$(dirname "${BASH_SOURCE[0]}")/../env.sh" +HERE="$ROOT/packaging/linux" + +PUSH=0 +TARBALL="" +while [[ $# -gt 0 ]]; do + case "$1" in + --push) PUSH=1; shift ;; + -h | --help) sed -n '2,12p' "$0"; exit 0 ;; + -*) echo "unknown argument: $1" >&2; exit 2 ;; + *) TARBALL="$1"; shift ;; + esac +done + +ARCH="$(uname -m)" +case "$ARCH" in + x86_64) ;; + aarch64 | arm64) ARCH=aarch64 ;; + *) echo "unsupported architecture $ARCH" >&2; exit 2 ;; +esac + +BASENAME="cadcraft-$VERSION-linux-$ARCH" +OUT_OCI="$DIST/$BASENAME-oci" + +echo "==> Building Flatpak OCI layout for $BASENAME" +"$HERE/flatpak-bundle.sh" --oci --no-test "${TARBALL:-}" + +[[ -d "$OUT_OCI" ]] || { echo "error: $OUT_OCI layout not generated" >&2; exit 1; } + +REGISTRY="${REGISTRY:-ghcr.io/storytold/cadcraft}" +TAG="${TAG:-$VERSION-$ARCH}" + +echo "==> OCI layout ready at $OUT_OCI (Target: $REGISTRY:$TAG)" + +if [[ "$PUSH" = 1 ]]; then + command -v skopeo >/dev/null || { echo "error: skopeo is required to push OCI images (apt install skopeo)" >&2; exit 1; } + + AUTH_ARGS=() + if [[ -n "${GITHUB_TOKEN:-}" ]]; then + AUTH_ARGS=(--dest-creds "${GITHUB_ACTOR:-storytold}:$GITHUB_TOKEN") + fi + + echo "==> Pushing to $REGISTRY:$TAG" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:$TAG" + + # Also update architecture-specific stable tag + echo "==> Pushing to $REGISTRY:stable-$ARCH" + skopeo copy --format oci "${AUTH_ARGS[@]}" "oci:$OUT_OCI" "docker://$REGISTRY:stable-$ARCH" + + echo "==> Push complete" +fi