mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-19 20:30:42 -06:00
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 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5.5
parent
8089c79375
commit
f2ae408a35
@@ -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:
|
||||
|
||||
+17
-17
@@ -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 |
|
||||
|
||||
Generated
-1
@@ -796,7 +796,6 @@ dependencies = [
|
||||
"cadcraft-engine",
|
||||
"cadcraft-fonts",
|
||||
"cadcraft-geom",
|
||||
"cadcraft-io",
|
||||
"cadcraft-render",
|
||||
"chrono",
|
||||
"craft-ui",
|
||||
|
||||
@@ -99,3 +99,7 @@ sync_github_name = true
|
||||
|
||||
[people.GULERTOLGA]
|
||||
sync_github_name = true
|
||||
|
||||
[people.Obtrusive8276]
|
||||
display_name = "Nicopicks"
|
||||
sync_github_name = false
|
||||
|
||||
@@ -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;
|
||||
|
||||
+52
-169
@@ -41,6 +41,10 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
.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<CommandSpec> {
|
||||
.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<Value> {
|
||||
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<Value> {
|
||||
let d = s.doc()?;
|
||||
let mut counts: std::collections::HashMap<String, usize> = 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<Block>> =
|
||||
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<Value> = 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<Value> {
|
||||
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<Step> {
|
||||
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<Vec2>,
|
||||
rotation: Option<f64>,
|
||||
preset_scale: Option<Vec2>,
|
||||
/// The Z factor that goes with `preset_scale`, which a repeated placement starts from.
|
||||
preset_z: Option<f64>,
|
||||
preset_rotation: Option<f64>,
|
||||
/// The attributes asked for: tag, prompt, default value, and Verify (asked again).
|
||||
attdefs: Vec<(String, String, String, bool)>,
|
||||
values: serde_json::Map<String, Value>,
|
||||
@@ -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<insert_file::FileRef>,
|
||||
}
|
||||
@@ -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<f64> {
|
||||
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<Step> {
|
||||
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<Step> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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 **");
|
||||
|
||||
@@ -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<String> {
|
||||
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<FileRef> {
|
||||
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<FileRef> {
|
||||
}
|
||||
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<Drawing> {
|
||||
pub(super) fn read_drawing(path: &str) -> Result<Drawing> {
|
||||
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<Drawing> {
|
||||
fn read_file(_path: &str) -> Result<Vec<u8>> {
|
||||
#[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<String> {
|
||||
/// 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<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
let lower = |it: &mut dyn Iterator<Item = &String>| it.map(|n| n.to_ascii_lowercase()).collect::<BTreeSet<String>>();
|
||||
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<String>)>);
|
||||
|
||||
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<String>) -> BTreeSet<String> {
|
||||
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<String> {
|
||||
let mut roots: Vec<String> = 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<String> = 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) {
|
||||
|
||||
@@ -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<SystemTime>),
|
||||
drawing: Arc<Drawing>,
|
||||
}
|
||||
|
||||
static CACHE: Mutex<Vec<Cached>> = 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<SystemTime>)> {
|
||||
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<Arc<Drawing>> {
|
||||
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<Vec<String>> = 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<CommandSpec> {
|
||||
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<PathBuf> = 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<cadcraft_doc::Block>> {
|
||||
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<Arc<Drawing>> {
|
||||
cached_drawing(path)
|
||||
}
|
||||
|
||||
/// BLOCKLIBRARY: list a folder's drawings or a drawing's blocks.
|
||||
fn run_library(_s: &mut Session, p: &Value) -> Result<Value> {
|
||||
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<Value> = 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<Value> = 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<Value> {
|
||||
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<PathBuf> {
|
||||
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<Option<Vec<String>>, 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<String> = 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<Option<Vec<String>>, 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<String>, Option<String>) {
|
||||
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<Value> {
|
||||
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();
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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)
|
||||
}
|
||||
|
||||
|
||||
@@ -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<dyn Interactive>,
|
||||
pub before: Arc<Drawing>,
|
||||
pub selection_before: Vec<Handle>,
|
||||
/// 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<String>, machine: Box<dyn Interactive>, before: Arc<Drawing>, selection_before: Vec<Handle>) -> 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.
|
||||
|
||||
@@ -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)?;
|
||||
|
||||
@@ -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<Drawing, String> {
|
||||
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<String> = 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<String> = (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::<Vec<String>>(&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();
|
||||
}
|
||||
@@ -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 <X>"), "{}", s.prompt_text());
|
||||
s.cmdline("X").unwrap(); // verified
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<String> = 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");
|
||||
}
|
||||
@@ -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;
|
||||
|
||||
@@ -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<Vec2>) {
|
||||
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<usize> {
|
||||
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<Vec2> {
|
||||
let mut out: Vec<Vec2> = Vec::new();
|
||||
for s in self.segments() {
|
||||
|
||||
+35
-58
@@ -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::<usize>() <= 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::<usize>() + 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::<usize>() <= 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<Item = (f64, f64)> + '_ {
|
||||
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<f64> {
|
||||
let mut k = vec![0.0; degree + 1];
|
||||
let inner = n.saturating_sub(degree + 1);
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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<Vec2>]) -> Vec<Vec2> {
|
||||
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<Vec2>], budget: Option<&crate::hatch::HatchBudget>) -> Option<Vec<Vec2>> {
|
||||
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<Vec2>], budget: Option<&c
|
||||
}
|
||||
}
|
||||
if edges.is_empty() || edges.len() > 200_000 {
|
||||
return Some(Vec::new());
|
||||
return Vec::new();
|
||||
}
|
||||
let mut ys: Vec<f64> = 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<Vec2>], 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<Vec2>], 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.
|
||||
|
||||
+44
-261
@@ -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<bool> {
|
||||
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<Item = &Vec2> = 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<Vec<Vec2>>, 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<Vec<Vec2>>) {
|
||||
// `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<Vec2>> = Vec::with_capacity(loops.len());
|
||||
for l in loops.drain(..) {
|
||||
if l.len() < 3 {
|
||||
@@ -191,21 +95,20 @@ fn dedup_polygons(loops: &mut Vec<Vec<Vec2>>, 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<Vec<Vec2>>, 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<Vec<Vec2>> {
|
||||
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<Vec<Vec<Vec2>>> {
|
||||
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<Vec<Vec2>> = 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<Vec2>> = 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<Vec<Vec2>> {
|
||||
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<Vec2>],
|
||||
px: f64,
|
||||
view: Option<&Bounds2>,
|
||||
cancel: Option<&AtomicBool>,
|
||||
budget: Option<&HatchBudget>,
|
||||
) -> Vec<Vec<Vec2>> {
|
||||
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<f64> = 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<Vec<Vec2>>,
|
||||
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<Vec2>], 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<Vec2>], px: f64, view: Option<&Bounds2>, cancel: Option<&AtomicBool>, out: &mut Vec<Vec<Vec2>>, work: &mut u64) {
|
||||
let local: Vec<Vec<Vec2>> = 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<Vec<Vec2>>, 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);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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};
|
||||
|
||||
@@ -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<std::sync::Arc<HatchBudget>>,
|
||||
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<DisplayList> = 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<Item = &'a Entity>>(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<Item = &'a Entity>>(
|
||||
d: &Drawing,
|
||||
ents: I,
|
||||
opts: &Options,
|
||||
max_primitives: usize,
|
||||
max_vertices: usize,
|
||||
) -> Option<DisplayList> {
|
||||
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<Item = &'a Entity>>(
|
||||
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<Item = &'a Entity>>(
|
||||
} 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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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();
|
||||
}
|
||||
@@ -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<T> = Result<T, PreviewFailure>;
|
||||
|
||||
#[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<Item = f64>) -> 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<f64>, 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<f64>, 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<f64>, 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<f64>, 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<String>, tol: Option<f64>, budget: &mut Budget) -> Checked<Bounds2> {
|
||||
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<String>, tol: Option<f64>, b: &mut Budget) -> Checked<Bounds2> {
|
||||
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<PreviewResult> {
|
||||
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;
|
||||
@@ -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::<Vec2>());
|
||||
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::<Vec2>()), ..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);
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -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<Handle>, usize)>,
|
||||
/// What the cycling list and the Shift+Space highlight were made for (see [`CycleKey`]).
|
||||
cycle_key: Option<CycleKey>,
|
||||
/// 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<bool>,
|
||||
/// 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<Rect>,
|
||||
surround: Color32,
|
||||
selecting: bool,
|
||||
sheet: Option<cadcraft_render::Sheet>,
|
||||
) {
|
||||
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<egui::Pos2> = 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, 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,
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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"]);
|
||||
|
||||
@@ -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<Rect>,
|
||||
/// 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,
|
||||
|
||||
@@ -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()));
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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: 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<Panel> 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<Panel> for Panels<'_> {
|
||||
Panel::ExternalRefs => {
|
||||
egui::ScrollArea::both().id_salt("dock-xrefs").auto_shrink([false, false]).show(ui, |ui| crate::xrefs::section(app, ui));
|
||||
}
|
||||
Panel::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) }
|
||||
}
|
||||
|
||||
@@ -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} فقط.
|
||||
|
||||
|
@@ -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}.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1447 and column 24.
|
@@ -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}.
|
||||
|
||||
|
@@ -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.
|
||||
|
||||
|
@@ -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}.
|
||||
|
||||
|
@@ -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}.
|
||||
|
||||
|
@@ -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.
|
||||
|
||||
|
@@ -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ó.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 16 and column 72.
|
@@ -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}.
|
||||
|
||||
|
@@ -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}개만 표시됩니다.
|
||||
|
||||
|
@@ -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.
|
||||
|
||||
|
@@ -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}.
|
||||
|
||||
|
@@ -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.
|
||||
|
||||
|
@@ -81,11 +81,11 @@ fn missing_commands_menus_tools_and_snap_labels(language: &str) -> Vec<String> {
|
||||
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<String> {
|
||||
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<String> {
|
||||
"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"),
|
||||
|
||||
@@ -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.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 11 and column 13.
|
@@ -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}.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1378 and column 24.
|
@@ -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.
|
||||
|
||||
|
Can't render this file because it contains an unexpected character in line 1446 and column 24.
|
@@ -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} 个。
|
||||
|
||||
|
@@ -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<String>,
|
||||
/// 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<Value, String> {
|
||||
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<String> {
|
||||
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();
|
||||
|
||||
+10
-16
@@ -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<Result<Value, String>> {
|
||||
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<Result<Value, String>> {
|
||||
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<Result<Value, String>> {
|
||||
fn route_ui_subsystems(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
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<Result<Value, String>> {
|
||||
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<Result<Value, String>> {
|
||||
if let Some(result) = route_ui_subsystems(app, id, params, interactive) {
|
||||
fn run_ui_command_inner(app: &mut CadApp, id: &str, params: &Value) -> Option<Result<Value, String>> {
|
||||
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"
|
||||
|
||||
@@ -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<String> = 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<cadcraft_engine::doc::Drawing, String> {
|
||||
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:");
|
||||
}
|
||||
@@ -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();
|
||||
}
|
||||
}
|
||||
@@ -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));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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.
|
||||
+2
-7
@@ -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) |
|
||||
|
||||
@@ -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"
|
||||
|
||||
Executable
+64
@@ -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
|
||||
Reference in New Issue
Block a user