mirror of
https://github.com/storytold/cadcraft.git
synced 2026-11-22 05:51:34 -06:00
* Blocks palette: list/medium/large icon modes, visible-only preview cache, grab-and-drop placement * Address CodeRabbit review: repeat-placement tracking, Arc<Drawing> clone, contains_pointer, docstrings * Keep repeat INSERT inside engine state machine and leave canvas hover check intact * Handle Repeat/NoRepeat across all INSERT stages and bound preview work budget * Fix Blocks palette review findings and preflight polyline previews * Fix Blocks palette review findings and menu click ownership * Restore bounded hatch thumbnails and exclude navigation clicks * Support faithful hatch previews with shared work budget and bounded contour fallback * Allow checking Repeat placement while block insertion is already in progress * Address PR 2122 review feedback on hatch budget, ViewCube hit-testing and preview test * Charge leader and wipeout expansion and bound MLeader array inserts in preview preflight * Charge MLeader paths in preview preflight and match ViewCube hit-testing to displayed sheet * Allow block insertion while rename editor is open and clarify hatch preview docs * Limit palette repeat placement to palette-started insertions * Account hatch preview comparisons as work occurs * Bound attribute thumbnail work and preserve palette rotation * Charge spline sampling work to the block preview budget * Charge splines at 1/32 of their sampling cap so ordinary blocks still preview * Charge text lengths in block preview budget and preserve inline INSERT arguments * Bound MText column metadata in block previews * Allow detailed block palette previews * Explain refused block previews and keep them cached while scrolling Previews now return Ready, Empty or Unavailable(reason) instead of an ambiguous empty display list, so a refused thumbnail is no longer shown like an empty block. Preflight separates input, computation and retained output, and reuses the geometry/render sampling rules at a thumbnail tolerance instead of a 4,000-sample worst case. A 64 MiB / 512-result LRU replaces retain_visible. Insertion never depends on preview success. Also: invalid-but-finite splines draw as their control polygon, and the insertion-point prompt advertises REpeat so R keeps meaning Rotate. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Remove changes unrelated to the Blocks palette Drop the contributor entry and the two xtask test adjustments so the PR only contains palette, preview and insertion changes. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Document the functions touched by the Blocks palette preview work Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Keep placement on unchanged rename and tighten palette click ownership Confirming a block name unchanged no longer cancels the INSERT in progress. Command-line releases are not placed as points when two arrive in one frame, and menu ownership of a press is taken from the press position of the last press in the frame. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Translate palette refusal messages and track canvas click ownership per release Mark the five preview refusal texts for translation and add the palette status texts to the other catalogs. Give each primary release in a frame the owner of its own press, and place a release at its own position when the cursor has moved onto a menu or a new press has begun. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Treat navigation controls as release owners in batched canvas clicks Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Track INSERT ownership and refuse palette edits during a foreign INSERT The palette now cancels only the INSERT it started (identified by a per-run serial), advertises REpeat/NoRepeat at every numeric and point prompt, and refuses Edit, Create, Rename and Delete while an INSERT it did not start is running, so undoing that insertion cannot also undo a palette edit. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Keep clicks on command-line keywords from placing canvas points The command line now records one rectangle covering the bar and every inline keyword, and the canvas treats a press, release or ordinary click there as the command line's, so a keyword pushed past the bar by a long prompt cannot also send a point. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Decide whether the ViewCube is shown from the current space, not the display list The display list is rebuilt after a frame's clicks are handled, so right after a layout switch it was stale or cleared. A click where the ViewCube had just disappeared was dropped, and a click on one that had just appeared reached the drawing as a point. Painting and hit-testing now share viewcube_shown, which follows the layout space. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Treat only a refused charge as hatch budget exhaustion Spending the hatch budget exactly left zero remaining, which hatch::draw and the preview builder read as exhaustion, so a valid preview could lose its hatches or be refused. HatchBudget now records a refused reservation separately and both checks use it. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Keep CLOSEALL's confirmation, widen the command-line click area, persist the Blocks window choice Only {json} calls and INSERT with inline arguments bypass the UI router, so CLOSEALL Y still asks before discarding drawings. The command line's click rectangle now includes the history lines or window, the resize grip and the AutoComplete rows. The floating-window preference of the Blocks palette is saved and restored with the other preferences. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Update Z and axis presets with a comma scale; grey the palette's Y scale when exploding A comma-separated scale preset now sets Z to the size of X and the axis presets to X, Y and that Z, so an earlier Scale cannot leave a stale Z. The Blocks palette disables its Y scale while Explode is on, with a tooltip saying the exploded insertion scales both axes by X. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Fix doc comments on the BLOCK and ATTDEF input methods and the INSERT tests BlockM::input and AttdefM::input named the INSERT state machine; the NoRepeat description sat on the comma-scale test instead of the repeat test, and the two newer INSERT tests had none of their own. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Reset the Verify counter between repeated INSERT placements Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * 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> * Blocks palette: read libraries off the UI thread, bound preview work CodeRabbit's reviews off2ae408and62bff60: - A library is listed on a worker thread (the web reads it at once), with a "Reading the library..." message in every catalog. Refresh waits for the read, and now parses the file again even when its size and time look the same. `list_library` is what BLOCKLIBRARY answers, without a session. - A preview's work is counted before anything is drawn: vertices, text, and the blocks references, dimensions and multileaders draw. An object with nothing in it still costs one visit. The pass that finds the size draws no dashes, and a block of points no longer scans the drawing's extents. - A block listing keeps the first blocks by name without sorting the whole table, for BLOCKSPALETTE too. - Merging a drawing removes nothing from a drawing too big for the purge scan: past its limit, a layer or style in use can look unused. Also fixed: a block with more than 100,000 references could lose the blocks it needs on import, because the walk counted repeated names. The same count in `used_blocks`, which PURGE shares, could drop the arrowhead of a merged dimension style, so that limit goes too: each block is walked once, so the walk ends, cycles included. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Blocks palette: repeat a placement only after its own INSERT placed The palette took any new handle as proof that its INSERT had placed the block. Queued control requests can cancel that INSERT and run another command to its end between two frames, and that command's handles then started a placement nobody asked for. The session now says how the last command ended: `commands_started` numbers the commands, nested transparent ones left out, and `last_finished` holds the number of the last one that ended by itself and whether it added to the drawing. The palette repeats only when that is its own INSERT, which also removes its handle counter. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Blocks palette: a command started after a placement ends the repeat A command with no prompt, such as REGEN, started right after INSERT placed the block left `last_finished` on that INSERT, so the palette started placing again after the user had moved on. The palette now also requires that no command has started since. A JSON command still does not end the repeat, on purpose: it never stops a running command, so one that lands a frame later finds the next INSERT running and leaves it alone. Ending the repeat only when it lands before the frame would make the result depend on timing. A test pins this. Also adds the doc comments CodeRabbit's coverage check asks for, on this PR's own functions and tests. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * INSERT: a cancelled placement takes no undo step INSERT wrote INSNAME when the name was given, so cancelling it left a changed drawing and an undo step that undid nothing visible. Repeat Placement, on by default, always ends with a cancelled INSERT, so the first undo after placing a block from the palette appeared to do nothing. INSNAME is now written when the block is placed. A cancelled INSERT no longer offers its name as the next default. Tests go through the palette where they only imitated it: the scale set in the palette, and the two undo steps of a block from a library. The palette places with two clicks, so the wording about a drag is gone. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Block import: keep what a block names and says about itself BLOCKLIBIMPORT defined a new block from the chosen one's objects and base point, so its description, annotative flag, units and explodable flag were lost. They now come along. The import's clean-up uses PURGE's scan, which only read the linetypes of objects and layers. A linetype named only by a dimension style, a dimension override, a multiline style, a multiline's copy of its style or an attribute override looked unused, so the import dropped it and PURGE removed it while the style still named it. The scan reads them all now. A reference to a renamed anonymous block kept the drawing's block of that name when it spelled the name in another case, or when it was a multileader's block content. Both now take the new name, found as Drawing::block finds a block. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * INSERT: Enter asks again at the insertion point, arrowheads follow renames This PR made Enter and Space at the insertion point end INSERT, "as in AutoCAD". AutoCAD 2027 does not: from -INSERT, from its palette and during repeated placement it answers that a point or option is needed and asks again. Only Escape ends it, so that change is gone. A file named at the block name prompt defines its block before the insertion point is asked for, and Escape keeps that definition, which is what AutoCAD 2027 does too. A test pins it. An anonymous arrowhead block renamed by a merge kept its old name in the dimension styles that came along and in dimension overrides, so they pointed at this drawing's block. Both follow the rename now; a style this drawing already had keeps its own. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Block import and palette: keep every named style and layer, skip unused counts Selective import uses PURGE's scans, which missed dimension styles named by leaders, text styles named by linetype pattern elements, table cell styles, dimension DIMTXSTY overrides and multiline or multileader-content attributes, plus layers and linetypes named by attributes on multileader block content. They all count as in use now. The palette asks BLOCKSPALETTE for no reference counts so it does not read every object after each edit, and cancels any running command before importing a library block so the import keeps its own undo step. * Blocks palette: a quick right-click at the insertion point cancels the placement A placement started from the palette had no way out with the mouse: Enter at the insertion point asks again, as AutoCAD 2027 does, and a quick right-click is Enter. At that prompt only, for an INSERT the palette started, a quick right-click now ends the command like Escape, which also ends Repeat Placement. A typed INSERT and the scale and rotation prompts keep Enter, and holding the button still opens the command menu. Escape, the menu's Cancel and this right-click share one function that also clears the half-typed text and the IME preedit; the menu's Cancel left the preedit behind. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Blocks palette: a transparent command no longer stops Repeat Placement A 'ZOOM or 'PAN run while the palette's INSERT asks for the insertion point shows the prompt `>>ZOOM`, which the palette took for another command and so stopped repeating the placement. A transparent command inside the INSERT does not start a command; it is now the count of commands started that tells whether the user moved on. A test pins it. The blocklibrary params string names the `truncated` field both results return. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Blocks palette: a transparent command ending inside INSERT is not its end; bound library reads A transparent command that finishes inside a running one ('ZOOM in an INSERT) recorded its end under the outer command's number. With an object added meanwhile, cancelling the resumed INSERT looked like a placement and the palette started another. Only a top-level command records its end now. Switching quickly between big libraries started a reading thread for each. At most four libraries are read at once; a further one waits, and the palette says it is reading until a place comes back. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Blocks palette: BLOCKLIBIMPORT never replaces a block; BLOCKSPALETTE counts every object that draws one BLOCKLIBIMPORT refuses a name the drawing already has (any letter case), the rule the palette already follows, so a direct JSON call can no longer change existing references. BLOCKSPALETTE counts block references, dimensions and multileader block content through `referenced_block`. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Blocks palette: a library file must be named .dwg or .dxf cached_drawing read any regular path, and the reader sniffs the bytes, so a DXF named part.bin was listed by BLOCKLIBRARY, imported by BLOCKLIBIMPORT and loaded by the palette. It now refuses other names before the cache lookup, so the three callers share the check. Regression test with a part.bin. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Blocks palette: library listing needs no drawing; a preview's two passes share one deadline BLOCKLIBRARY and BLOCKLIBRARIES ignore the session but had the has_doc guard, so the palette opened on the Start tab got "no drawing open", kept an empty library list and never reloaded it. They are now always enabled; BLOCKLIBIMPORT still needs a drawing. outline() gave each of its two build passes the full PREVIEW_DEADLINE, so one preview could take twice the limit. The detailed pass now gets what the coarse pass left. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com> * Blocks palette: a dimension override given as a number names its style, linetype or arrowhead DIMOVERRIDE keeps a number as given (DIMTXSTY 123) and the dimension is drawn with it as text, but the in-use scans only read strings, so PURGE, style deletion and import cleanup could drop a style, linetype or arrowhead block still in use. `purge::override_name` reads either, for text styles, linetypes, arrowheads (main's `override_arrows` had the same defect) and the arrowhead rename at import, which now rewrites an override only when its block is really renamed. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * Blocks palette: put show()'s doc comment back on show() right_click_cancels_placing had been inserted between show()'s doc comment (the cursor-visibility contract, #1701) and show() itself, so the contract documented the wrong function. Moved, no code change. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> * i18n(ka): add the 27 Blocks palette strings Georgian rows for the strings this PR adds to the other catalogs (cargo test -p cadcraft-ui-egui translation_gaps -- --ignored --nocapture lists none of them any more). --------- Co-authored-by: Claude Sonnet 5.5 <noreply@anthropic.com>
571 lines
26 KiB
Rust
571 lines
26 KiB
Rust
//! Layers: LAYER (programmatic sub-ids, -LAYER prompts), layer tools (LAYMCUR, LAYISO, LAYOFF, LAYFRZ…).
|
|
|
|
mod prompts;
|
|
|
|
use cadcraft_color::Color;
|
|
use cadcraft_doc::{Layer, Lineweight};
|
|
use serde_json::{Value, json};
|
|
|
|
use super::machines::SelectRun;
|
|
use super::{CommandSpec, bad, bool_or, ok, str_param, targets};
|
|
|
|
use crate::{Result, Session};
|
|
|
|
pub fn specs() -> Vec<CommandSpec> {
|
|
vec![
|
|
CommandSpec::new("layer", "Layers", run_list)
|
|
.menu(&["Format", "Layers"])
|
|
.alias(&["la", "layers", "-layer"])
|
|
.params("{} → layers, states (typed -LAYER: option prompts)")
|
|
.interactive(|_| Ok(Box::new(prompts::LayerM::default()))),
|
|
CommandSpec::new("layer.new", "New Layer", run_new).params("{name, color?, linetype?, lineweight? (mm), current?: bool}"),
|
|
CommandSpec::new("layer.set", "Set Layer Properties", run_set)
|
|
.params("{name, on?, frozen?, locked?, plot?, color?, linetype?, lineweight?, transparency?, description?, newVpFreeze?, plotStyle? (named plot style), newName?}"),
|
|
CommandSpec::new("layer.current", "Make Current", run_current)
|
|
.menu(&["Format", "Layer Tools", "Make Current"])
|
|
.alias(&["clayer"])
|
|
.params("{name}"),
|
|
CommandSpec::new("layer.delete", "Delete Layer", run_delete).params("{name}"),
|
|
CommandSpec::new("laymcur", "Make Object's Layer Current", run_laymcur).params("{handles?}"),
|
|
CommandSpec::new("laymch", "Layer Match", run_laymch).menu(&["Format", "Layer Tools", "Layer Match"]).params("{handles?, layer}"),
|
|
CommandSpec::new("laycur", "Change to Current Layer", run_laycur)
|
|
.menu(&["Format", "Layer Tools", "Change to Current Layer"])
|
|
.params("{handles?}")
|
|
.interactive(|_| Ok(Box::new(SelectRun::new("laycur", "LAYCUR")))),
|
|
CommandSpec::new("layiso", "Isolate Layer", run_layiso).menu(&["Format", "Layer Tools", "Isolate Layer"]).params("{handles?}"),
|
|
CommandSpec::new("layuniso", "Unisolate Layer", run_layuniso).menu(&["Format", "Layer Tools", "Unisolate Layer"]),
|
|
CommandSpec::new("layfrz", "Freeze Layer", |s, p| set_obj_layers(s, p, |l| l.frozen = true))
|
|
.menu(&["Format", "Layer Tools", "Freeze Layer"])
|
|
.params("{handles?}")
|
|
.interactive(|_| Ok(Box::new(SelectRun::single("layfrz", "LAYFRZ", "Select an object on the layer to be frozen")))),
|
|
CommandSpec::new("layoff", "Layer Off", |s, p| set_obj_layers(s, p, |l| l.on = false))
|
|
.menu(&["Format", "Layer Tools", "Layer Off"])
|
|
.params("{handles?}")
|
|
// Layer Off stays active until Enter or Esc, as in AutoCAD (#1418): one object per
|
|
// pick and the prompt comes straight back.
|
|
.interactive(|_| Ok(Box::new(SelectRun::repeat("layoff", "LAYOFF", "Select an object on the layer to be turned off")))),
|
|
CommandSpec::new("laylck", "Lock Layer", |s, p| set_obj_layers(s, p, |l| l.locked = true))
|
|
.menu(&["Format", "Layer Tools", "Lock Layer"])
|
|
.params("{handles?}")
|
|
.interactive(|_| Ok(Box::new(SelectRun::single("laylck", "LAYLCK", "Select an object on the layer to be locked")))),
|
|
CommandSpec::new("layulk", "Unlock Layer", |s, p| set_obj_layers(s, p, |l| l.locked = false))
|
|
.menu(&["Format", "Layer Tools", "Unlock Layer"])
|
|
.params("{handles?}")
|
|
.interactive(|_| Ok(Box::new(SelectRun::single("layulk", "LAYULK", "Select an object on the layer to be unlocked")))),
|
|
CommandSpec::new("layon", "Turn All Layers On", |s, _| all_layers(s, |l| l.on = true)),
|
|
CommandSpec::new("laythw", "Thaw All Layers", |s, _| all_layers(s, |l| l.frozen = false)),
|
|
CommandSpec::new("layerp", "Previous Layer", run_layerp).menu(&["Format", "Layer Tools", "Previous Layer"]),
|
|
CommandSpec::new("layerstate.save", "Save Layer State", run_state_save).menu(&["Format", "Layer States Manager..."]).params("{name}"),
|
|
CommandSpec::new("layerstate.restore", "Restore Layer State", run_state_restore).params("{name}"),
|
|
CommandSpec::new("layerstate.list", "List Layer States", run_state_list).params("{} → states").noundo(),
|
|
CommandSpec::new("layerstate.delete", "Delete Layer State", run_state_delete).params("{name}"),
|
|
CommandSpec::new("layerstate.rename", "Rename Layer State", run_state_rename).params("{from, to}"),
|
|
CommandSpec::new("laymrg", "Layer Merge", merge::run_laymrg)
|
|
.menu(&["Format", "Layer Tools", "Layer Merge"])
|
|
.params("{from: [names], to} (the from layers' objects move to `to`, then the from layers are deleted)")
|
|
.interactive(|_| Ok(Box::new(merge::LayerRemove::merge()))),
|
|
CommandSpec::new("laydel", "Layer Delete", merge::run_laydel)
|
|
.menu(&["Format", "Layer Tools", "Layer Delete"])
|
|
.params("{names: [...]} (deletes the layers and every object on them)")
|
|
.interactive(|_| Ok(Box::new(merge::LayerRemove::delete()))),
|
|
]
|
|
}
|
|
|
|
fn layer_json(l: &Layer, current: bool) -> Value {
|
|
json!({
|
|
"name": l.name, "on": l.on, "frozen": l.frozen, "locked": l.locked, "plot": l.plot,
|
|
"color": l.color.name(), "colorRgb": l.color.resolve(Color::Index(7), Color::Index(7)).hex(),
|
|
"linetype": l.linetype, "lineweight": l.lineweight.name(), "transparency": l.transparency,
|
|
"description": l.description, "current": current, "newVpFreeze": l.vp_freeze_new, "plotStyle": l.plot_style,
|
|
})
|
|
}
|
|
|
|
fn run_list(s: &mut Session, _p: &Value) -> Result<Value> {
|
|
let d = s.doc()?;
|
|
let cur = d.header.str("CLAYER", "0");
|
|
let used = used_layers(d);
|
|
let layers: Vec<Value> = d
|
|
.layers
|
|
.iter()
|
|
.map(|l| {
|
|
let mut v = layer_json(l, l.name.eq_ignore_ascii_case(&cur));
|
|
if let Some(o) = v.as_object_mut() {
|
|
o.insert("used".into(), json!(used.contains(&l.name.to_ascii_lowercase())));
|
|
}
|
|
v
|
|
})
|
|
.collect();
|
|
Ok(json!({ "layers": layers, "states": d.layer_states.iter().map(|st| st.name.clone()).collect::<Vec<_>>() }))
|
|
}
|
|
|
|
/// Lower-case names of layers that have objects on them (model, layouts and block definitions).
|
|
pub fn used_layers(d: &cadcraft_doc::Drawing) -> std::collections::HashSet<String> {
|
|
let mut set = std::collections::HashSet::new();
|
|
let ents = d.model.iter().chain(d.layouts.iter().flat_map(|l| l.entities.iter())).chain(d.blocks.values().flat_map(|b| b.entities.iter()));
|
|
for e in ents.take(5_000_000) {
|
|
if !set.contains(&e.common.layer.to_ascii_lowercase()) {
|
|
set.insert(e.common.layer.to_ascii_lowercase());
|
|
}
|
|
// An attribute can sit on a layer of its own.
|
|
for layer in super::blocks::object_attribs(e).iter().filter_map(|a| a.props.layer.as_ref()) {
|
|
set.insert(layer.to_ascii_lowercase());
|
|
}
|
|
}
|
|
set
|
|
}
|
|
|
|
pub(super) fn parse_lw(v: &Value) -> Option<Lineweight> {
|
|
if let Some(f) = v.as_f64() {
|
|
return Some(Lineweight::Mm100((f * 100.0).round().clamp(0.0, 211.0) as u16));
|
|
}
|
|
match v.as_str()?.to_ascii_lowercase().as_str() {
|
|
"bylayer" => Some(Lineweight::ByLayer),
|
|
"byblock" => Some(Lineweight::ByBlock),
|
|
"default" => Some(Lineweight::Default),
|
|
s => s.trim_end_matches("mm").trim().parse::<f64>().ok().map(|f| Lineweight::Mm100((f * 100.0).round().clamp(0.0, 211.0) as u16)),
|
|
}
|
|
}
|
|
|
|
fn apply(l: &mut Layer, p: &Value) -> Result<()> {
|
|
if let Some(v) = p.get("on").and_then(Value::as_bool) {
|
|
l.on = v;
|
|
}
|
|
if let Some(v) = p.get("frozen").and_then(Value::as_bool) {
|
|
l.frozen = v;
|
|
}
|
|
if let Some(v) = p.get("locked").and_then(Value::as_bool) {
|
|
l.locked = v;
|
|
}
|
|
if let Some(v) = p.get("plot").and_then(Value::as_bool) {
|
|
l.plot = v;
|
|
}
|
|
if let Some(v) = str_param(p, "plotStyle").map(str::trim) {
|
|
if v.is_empty() || v.eq_ignore_ascii_case("bylayer") || v.eq_ignore_ascii_case("byblock") {
|
|
return Err(bad("layer", "a layer's plot style is a style name (such as Normal)"));
|
|
}
|
|
l.plot_style = v.chars().take(255).collect();
|
|
}
|
|
if let Some(c) = p.get("color") {
|
|
let c = c
|
|
.as_str()
|
|
.and_then(Color::parse)
|
|
.or_else(|| c.as_u64().and_then(|i| u8::try_from(i).ok()).filter(|i| *i > 0).map(Color::Index))
|
|
.ok_or_else(|| bad("layer", "bad colour"))?;
|
|
if matches!(c, Color::ByLayer | Color::ByBlock) {
|
|
return Err(bad("layer", "a layer colour must be an index or true colour"));
|
|
}
|
|
l.color = c;
|
|
}
|
|
if let Some(lt) = str_param(p, "linetype") {
|
|
l.linetype = lt.to_string();
|
|
}
|
|
if let Some(lw) = p.get("lineweight") {
|
|
l.lineweight = parse_lw(lw).ok_or_else(|| bad("layer", "bad lineweight"))?;
|
|
}
|
|
if let Some(t) = p.get("transparency").and_then(Value::as_u64) {
|
|
l.transparency = t.min(90) as u8;
|
|
}
|
|
if let Some(v) = p.get("newVpFreeze").and_then(Value::as_bool) {
|
|
l.vp_freeze_new = v;
|
|
}
|
|
if let Some(d) = str_param(p, "description") {
|
|
l.description = d.to_string();
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// The loaded linetype named by `linetype`, if given: a layer cannot use ByLayer, ByBlock or a
|
|
/// linetype the drawing does not have.
|
|
fn loaded_linetype(d: &cadcraft_doc::Drawing, cmd: &str, p: &Value) -> Result<Option<String>> {
|
|
let Some(lt) = str_param(p, "linetype") else { return Ok(None) };
|
|
if lt.eq_ignore_ascii_case("ByLayer") || lt.eq_ignore_ascii_case("ByBlock") {
|
|
return Err(bad(cmd, "a layer linetype cannot be ByLayer or ByBlock"));
|
|
}
|
|
let t = d.linetype(lt).ok_or_else(|| bad(cmd, format!("linetype `{lt}` is not loaded (load it with LINETYPE)")))?;
|
|
Ok(Some(t.name.clone()))
|
|
}
|
|
|
|
fn valid_name(n: &str) -> bool {
|
|
!n.trim().is_empty() && n.len() <= 255 && !n.chars().any(|c| c.is_control() || "<>/\\\":;?*|,=`".contains(c))
|
|
}
|
|
|
|
fn run_new(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let name = str_param(p, "name").ok_or_else(|| bad("layer.new", "`name` is required"))?.to_string();
|
|
if !valid_name(&name) {
|
|
return Err(bad("layer.new", "invalid layer name"));
|
|
}
|
|
let d = s.doc_mut()?;
|
|
if d.layer(&name).is_some() {
|
|
return Err(bad("layer.new", format!("layer `{name}` already exists")));
|
|
}
|
|
let lt = loaded_linetype(d, "layer.new", p)?;
|
|
let mut l = Layer::new(&name);
|
|
apply(&mut l, p)?;
|
|
if let Some(lt) = lt {
|
|
l.linetype = lt;
|
|
}
|
|
d.layers.push(l);
|
|
if bool_or(p, "current", false) {
|
|
d.header.set_str("CLAYER", &name);
|
|
}
|
|
ok()
|
|
}
|
|
|
|
fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let name = str_param(p, "name").ok_or_else(|| bad("layer.set", "`name` is required"))?.to_string();
|
|
let new_name = str_param(p, "newName").map(str::to_string);
|
|
// Validate on a copy before borrowing the drawing mutably, so a rejected call
|
|
// leaves the layer untouched and records no undo step.
|
|
let d = s.doc()?;
|
|
let cur = d.header.str("CLAYER", "0");
|
|
let mut updated = d.layer(&name).cloned().ok_or_else(|| bad("layer.set", format!("no layer `{name}`")))?;
|
|
let old = updated.name.clone();
|
|
let lt = loaded_linetype(d, "layer.set", p)?;
|
|
apply(&mut updated, p)?;
|
|
if let Some(lt) = lt {
|
|
updated.linetype = lt;
|
|
}
|
|
if p.get("frozen").and_then(Value::as_bool) == Some(true) && old.eq_ignore_ascii_case(&cur) {
|
|
return Err(bad("layer.set", "cannot freeze the current layer"));
|
|
}
|
|
if let Some(nn) = &new_name {
|
|
if old == "0" || old.eq_ignore_ascii_case("Defpoints") {
|
|
return Err(bad("layer.set", "cannot rename layer 0 or Defpoints"));
|
|
}
|
|
if !valid_name(nn) {
|
|
return Err(bad("layer.set", "invalid layer name"));
|
|
}
|
|
if !nn.eq_ignore_ascii_case(&old) && d.layer(nn).is_some() {
|
|
return Err(bad("layer.set", format!("layer `{nn}` already exists")));
|
|
}
|
|
}
|
|
let d = s.doc_mut()?;
|
|
let l = d.layer_mut(&old).ok_or_else(|| bad("layer.set", format!("no layer `{name}`")))?;
|
|
*l = updated;
|
|
if let Some(nn) = new_name {
|
|
l.name = nn.clone();
|
|
// Re-point entities in model space, every layout and every block definition.
|
|
repoint(&mut d.model, &old, &nn);
|
|
for layout in &mut d.layouts {
|
|
repoint(&mut layout.entities, &old, &nn);
|
|
}
|
|
for block in d.blocks.values_mut() {
|
|
if block.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&old)) {
|
|
repoint(&mut std::sync::Arc::make_mut(block).entities, &old, &nn);
|
|
}
|
|
}
|
|
merge::rename_in_viewports(d, &old, &nn);
|
|
if cur.eq_ignore_ascii_case(&old) {
|
|
d.header.set_str("CLAYER", &nn);
|
|
}
|
|
}
|
|
ok()
|
|
}
|
|
|
|
fn repoint(store: &mut cadcraft_doc::EntityStore, old: &str, new: &str) {
|
|
let hs: Vec<_> = store.iter().filter(|e| e.common.layer.eq_ignore_ascii_case(old)).map(|e| e.handle).collect();
|
|
for h in hs {
|
|
store.modify(h, |e| e.common.layer = new.to_string());
|
|
}
|
|
}
|
|
|
|
fn run_current(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let name = str_param(p, "name").ok_or_else(|| bad("layer.current", "`name` is required"))?.to_string();
|
|
let d = s.doc_mut()?;
|
|
let l = d.layer_mut(&name).ok_or_else(|| bad("layer.current", format!("no layer `{name}`")))?;
|
|
l.frozen = false;
|
|
let n = l.name.clone();
|
|
prev_push(d);
|
|
d.header.set_str("CLAYER", &n);
|
|
ok()
|
|
}
|
|
|
|
fn prev_push(d: &mut cadcraft_doc::Drawing) {
|
|
let snap = serde_json::to_string(&d.layers).unwrap_or_default();
|
|
d.header.set_str("CADCRAFT_LAYERP", &snap);
|
|
}
|
|
|
|
fn run_layerp(s: &mut Session, _p: &Value) -> Result<Value> {
|
|
let d = s.doc_mut()?;
|
|
let snap = d.header.str("CADCRAFT_LAYERP", "");
|
|
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layerp", "No previous layer state."))?;
|
|
d.layers = layers;
|
|
Ok(json!({"message": "Restored previous layer states."}))
|
|
}
|
|
|
|
fn run_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let name = str_param(p, "name").ok_or_else(|| bad("layer.delete", "`name` is required"))?.to_string();
|
|
let d = s.doc_mut()?;
|
|
if name == "0" || name.eq_ignore_ascii_case("Defpoints") || d.header.str("CLAYER", "0").eq_ignore_ascii_case(&name) {
|
|
return Err(bad("layer.delete", "cannot delete layer 0, Defpoints or the current layer"));
|
|
}
|
|
let used = d.model.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name))
|
|
|| d.layouts.iter().any(|l| l.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name)))
|
|
|| d.blocks.values().any(|b| b.entities.iter().any(|e| e.common.layer.eq_ignore_ascii_case(&name)));
|
|
if used {
|
|
return Err(bad("layer.delete", "layer has objects on it"));
|
|
}
|
|
d.layers.retain(|l| !l.name.eq_ignore_ascii_case(&name));
|
|
merge::forget_in_viewports(d, &std::collections::HashSet::from([name.to_ascii_lowercase()]));
|
|
ok()
|
|
}
|
|
|
|
fn obj_layers(s: &Session, p: &Value) -> Result<Vec<String>> {
|
|
let hs = targets(s, p)?;
|
|
let d = s.doc()?;
|
|
let mut v: Vec<String> = hs.iter().filter_map(|h| d.entity(*h).map(|e| e.common.layer.clone())).collect();
|
|
v.sort();
|
|
v.dedup();
|
|
Ok(v)
|
|
}
|
|
|
|
fn run_laymcur(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let ls = obj_layers(s, p)?;
|
|
let l = ls.first().cloned().ok_or_else(|| bad("laymcur", "select an object"))?;
|
|
s.doc_mut()?.header.set_str("CLAYER", &l);
|
|
Ok(json!({ "message": format!("{l} is now the current layer.") }))
|
|
}
|
|
|
|
fn run_laymch(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let hs = targets(s, p)?;
|
|
let layer = str_param(p, "layer").ok_or_else(|| bad("laymch", "`layer` is required"))?.to_string();
|
|
let d = s.doc_mut()?;
|
|
d.ensure_layer(&layer);
|
|
for h in &hs {
|
|
d.modify_entity(*h, |e| e.common.layer = layer.clone())?;
|
|
}
|
|
Ok(json!({ "changed": hs.len() }))
|
|
}
|
|
|
|
fn run_laycur(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let hs = targets(s, p)?;
|
|
let d = s.doc_mut()?;
|
|
let cur = d.header.str("CLAYER", "0");
|
|
for h in &hs {
|
|
d.modify_entity(*h, |e| e.common.layer = cur.clone())?;
|
|
}
|
|
Ok(json!({ "changed": hs.len() }))
|
|
}
|
|
|
|
fn run_layiso(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let keep = obj_layers(s, p)?;
|
|
if keep.is_empty() {
|
|
return Err(bad("layiso", "select objects on the layers to isolate"));
|
|
}
|
|
let d = s.doc_mut()?;
|
|
prev_push(d);
|
|
d.header.set_str("CADCRAFT_LAYISO", &serde_json::to_string(&d.layers).unwrap_or_default());
|
|
for l in &mut d.layers {
|
|
if !keep.iter().any(|k| k.eq_ignore_ascii_case(&l.name)) {
|
|
l.on = false;
|
|
}
|
|
}
|
|
if let Some(k) = keep.first() {
|
|
d.header.set_str("CLAYER", k);
|
|
}
|
|
Ok(json!({ "message": format!("Layer(s) {} have been isolated.", keep.join(", ")) }))
|
|
}
|
|
|
|
fn run_layuniso(s: &mut Session, _p: &Value) -> Result<Value> {
|
|
let d = s.doc_mut()?;
|
|
let snap = d.header.str("CADCRAFT_LAYISO", "");
|
|
let layers: Vec<Layer> = serde_json::from_str(&snap).map_err(|_| bad("layuniso", "No isolated layers."))?;
|
|
d.layers = layers;
|
|
ok()
|
|
}
|
|
|
|
fn set_obj_layers(s: &mut Session, p: &Value, f: fn(&mut Layer)) -> Result<Value> {
|
|
let ls = obj_layers(s, p)?;
|
|
let d = s.doc_mut()?;
|
|
let cur = d.header.str("CLAYER", "0");
|
|
prev_push(d);
|
|
for n in &ls {
|
|
if let Some(l) = d.layer_mut(n) {
|
|
let was_frozen = l.frozen;
|
|
f(l);
|
|
if l.frozen && !was_frozen && l.name.eq_ignore_ascii_case(&cur) {
|
|
l.frozen = false;
|
|
}
|
|
}
|
|
}
|
|
s.set_selection(Vec::new());
|
|
Ok(json!({ "layers": ls }))
|
|
}
|
|
|
|
fn all_layers(s: &mut Session, f: fn(&mut Layer)) -> Result<Value> {
|
|
let d = s.doc_mut()?;
|
|
prev_push(d);
|
|
d.layers.iter_mut().for_each(f);
|
|
ok()
|
|
}
|
|
|
|
fn run_state_save(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.save", "`name` is required"))?.to_string();
|
|
let d = s.doc_mut()?;
|
|
let layers = d.layers.clone();
|
|
d.layer_states.retain(|st| st.name != name);
|
|
d.layer_states.push(cadcraft_doc::LayerState { name, layers });
|
|
ok()
|
|
}
|
|
|
|
fn run_state_restore(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.restore", "`name` is required"))?;
|
|
let d = s.doc_mut()?;
|
|
let st = d.layer_states.iter().find(|st| st.name == name).cloned().ok_or_else(|| bad("layerstate.restore", "no such layer state"))?;
|
|
restore_layers(d, st.layers);
|
|
ok()
|
|
}
|
|
|
|
/// Put the saved layers back over the drawing's layers of the same name (without regard to case);
|
|
/// saved layers the drawing no longer has are skipped. Both lists can come from a file, so the
|
|
/// drawing's layers are looked up in an index rather than scanned per saved layer.
|
|
pub(crate) fn restore_layers(d: &mut cadcraft_doc::Drawing, saved: Vec<Layer>) {
|
|
let mut index: std::collections::HashMap<String, usize> = std::collections::HashMap::with_capacity(d.layers.len());
|
|
for (i, l) in d.layers.iter().enumerate() {
|
|
// The first of names that differ only in case, as `Drawing::layer_mut` finds it.
|
|
index.entry(l.name.to_ascii_lowercase()).or_insert(i);
|
|
}
|
|
for layer in saved {
|
|
if let Some(l) = index.get(&layer.name.to_ascii_lowercase()).and_then(|&i| d.layers.get_mut(i)) {
|
|
*l = layer;
|
|
}
|
|
}
|
|
}
|
|
|
|
fn run_state_list(s: &mut Session, _p: &Value) -> Result<Value> {
|
|
let d = s.doc()?;
|
|
let states: Vec<Value> = d.layer_states.iter().map(|st| json!({ "name": st.name, "layers": st.layers.len() })).collect();
|
|
let msg = if states.is_empty() {
|
|
"No saved layer states.".to_string()
|
|
} else {
|
|
d.layer_states.iter().map(|st| st.name.clone()).collect::<Vec<_>>().join(", ")
|
|
};
|
|
Ok(json!({ "states": states, "message": msg }))
|
|
}
|
|
|
|
fn run_state_delete(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.delete", "`name` is required"))?;
|
|
let d = s.doc_mut()?;
|
|
if !d.layer_states.iter().any(|st| st.name == name) {
|
|
return Err(bad("layerstate.delete", "no such layer state"));
|
|
}
|
|
d.layer_states.retain(|st| st.name != name);
|
|
ok()
|
|
}
|
|
|
|
fn run_state_rename(s: &mut Session, p: &Value) -> Result<Value> {
|
|
let from = str_param(p, "from").ok_or_else(|| bad("layerstate.rename", "`from` is required"))?;
|
|
let to = str_param(p, "to").map(str::trim).ok_or_else(|| bad("layerstate.rename", "`to` is required"))?.to_string();
|
|
if !valid_name(&to) {
|
|
return Err(bad("layerstate.rename", "invalid name"));
|
|
}
|
|
let d = s.doc_mut()?;
|
|
if d.layer_states.iter().any(|st| st.name == to) {
|
|
return Err(bad("layerstate.rename", format!("layer state `{to}` already exists")));
|
|
}
|
|
let st = d.layer_states.iter_mut().find(|st| st.name == from).ok_or_else(|| bad("layerstate.rename", "no such layer state"))?;
|
|
st.name = to;
|
|
ok()
|
|
}
|
|
|
|
// LAYMRG and LAYDEL.
|
|
mod merge;
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use serde_json::json;
|
|
|
|
use crate::Session;
|
|
|
|
/// Restoring many saved layers, most of them missing, takes one pass and matches without case.
|
|
#[test]
|
|
fn restore_layers_matches_by_name_in_linear_time() {
|
|
let mut d = cadcraft_doc::Drawing::new_imperial();
|
|
d.layers = (0..20_000).map(|i| cadcraft_doc::Layer::new(&format!("L{i}"))).collect();
|
|
let mut saved: Vec<cadcraft_doc::Layer> = (0..20_000).map(|i| cadcraft_doc::Layer::new(&format!("missing{i}"))).collect();
|
|
let mut back = cadcraft_doc::Layer::new("l7");
|
|
back.frozen = true;
|
|
saved.push(back);
|
|
let started = std::time::Instant::now();
|
|
super::restore_layers(&mut d, saved);
|
|
assert!(started.elapsed() < std::time::Duration::from_secs(2));
|
|
assert!(d.layer("L7").is_some_and(|l| l.frozen));
|
|
assert_eq!(d.layers.len(), 20_000);
|
|
}
|
|
|
|
#[test]
|
|
fn layer_states_save_list_restore_delete() {
|
|
let mut s = Session::new();
|
|
s.execute("layer.new", &json!({ "name": "A", "color": 1 })).unwrap();
|
|
s.execute("layerstate.save", &json!({ "name": "base" })).unwrap();
|
|
s.execute("layer.set", &json!({ "name": "A", "on": false, "color": 3 })).unwrap();
|
|
let l = s.execute("layerstate.list", &json!({})).unwrap();
|
|
assert_eq!(l["states"][0]["name"], "base");
|
|
s.execute("layerstate.restore", &json!({ "name": "base" })).unwrap();
|
|
let a = s.doc().unwrap().layer("A").unwrap().clone();
|
|
assert!(a.on);
|
|
assert_eq!(a.color, cadcraft_color::Color::Index(1));
|
|
s.execute("layerstate.rename", &json!({ "from": "base", "to": "start" })).unwrap();
|
|
assert!(s.execute("layerstate.delete", &json!({ "name": "base" })).is_err());
|
|
s.execute("layerstate.delete", &json!({ "name": "start" })).unwrap();
|
|
assert!(s.execute("layerstate.list", &json!({})).unwrap()["states"].as_array().unwrap().is_empty());
|
|
// `used` flags in the layer list.
|
|
s.execute("line", &json!({ "points": [[0, 0], [1, 1]] })).unwrap();
|
|
let v = s.execute("layer", &json!({})).unwrap();
|
|
let used: Vec<bool> = v["layers"].as_array().unwrap().iter().map(|l| l["used"].as_bool().unwrap()).collect();
|
|
assert!(used.contains(&true) && used.contains(&false));
|
|
}
|
|
|
|
#[test]
|
|
fn rejected_layer_set_changes_nothing() {
|
|
let mut s = Session::new();
|
|
// Layer 0 is current; freezing it is rejected and must not apply the colour either.
|
|
let before = s.doc().unwrap().layer("0").unwrap().clone();
|
|
let undo = s.state().unwrap().undo.len();
|
|
assert!(s.execute("layer.set", &json!({ "name": "0", "frozen": true, "color": 3 })).is_err());
|
|
assert_eq!(s.doc().unwrap().layer("0").unwrap(), &before);
|
|
assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step for a rejected call");
|
|
// Same for a rejected rename.
|
|
assert!(s.execute("layer.set", &json!({ "name": "0", "newName": "X", "color": 3 })).is_err());
|
|
assert_eq!(s.doc().unwrap().layer("0").unwrap(), &before);
|
|
assert_eq!(s.state().unwrap().undo.len(), undo, "no undo step for a rejected call");
|
|
// A valid colour-only edit of the current layer still applies.
|
|
s.execute("layer.set", &json!({ "name": "0", "color": 3 })).unwrap();
|
|
assert_ne!(s.doc().unwrap().layer("0").unwrap(), &before);
|
|
}
|
|
|
|
#[test]
|
|
fn delete_and_purge_keep_layers_used_by_block_definitions() {
|
|
let mut s = Session::new();
|
|
s.execute("layer.new", &json!({ "name": "A", "color": 1 })).unwrap();
|
|
s.execute("layer.current", &json!({ "name": "A" })).unwrap();
|
|
let l = s.execute("line", &json!({ "points": [[0, 0], [1, 1]] })).unwrap()["handles"][0].as_str().unwrap().to_string();
|
|
s.execute("block", &json!({ "name": "B", "base": [0, 0], "handles": [l], "keep": "delete" })).unwrap();
|
|
s.execute("layer.current", &json!({ "name": "0" })).unwrap();
|
|
s.execute("insert", &json!({ "name": "B", "at": [5, 5] })).unwrap();
|
|
assert!(s.execute("layer.delete", &json!({ "name": "A" })).is_err());
|
|
s.execute("purge", &json!({})).unwrap();
|
|
assert!(s.doc().unwrap().layer("A").is_some());
|
|
}
|
|
|
|
#[test]
|
|
fn rename_repoints_paper_space_and_block_entities() {
|
|
let mut s = Session::new();
|
|
s.execute("layer.new", &json!({ "name": "A", "color": "red", "current": true })).unwrap();
|
|
s.execute("line", &json!({ "points": [[0, 0], [1, 1]] })).unwrap();
|
|
s.execute("selectall", &json!({})).unwrap();
|
|
s.execute("block", &json!({ "name": "Part", "base": [0, 0], "keep": "delete" })).unwrap();
|
|
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
|
|
s.execute("line", &json!({ "points": [[0, 0], [1, 1]] })).unwrap();
|
|
s.execute("layer.set", &json!({ "name": "A", "newName": "B" })).unwrap();
|
|
let d = s.doc().unwrap();
|
|
let on_layer = |name: &str| {
|
|
let paper = d.layouts.iter().flat_map(|l| l.entities.iter());
|
|
let blocks = d.blocks.values().flat_map(|b| b.entities.iter());
|
|
paper.chain(blocks).filter(|e| e.common.layer == name).count()
|
|
};
|
|
assert_eq!(on_layer("A"), 0);
|
|
assert_eq!(on_layer("B"), 2);
|
|
}
|
|
}
|