Compare commits

..
37 Commits
Author SHA1 Message Date
Tanish Manku 129dd86ef2 Stack d2: #2648: an arc's pick off its sweep goes through seg_param
#2648 sent an arc pick outside its sweep to the nearer end with its own copy of the rule that
#2693 put in curves::seg_param. TRIM of an arc now uses seg_param, so the rule is in one place.
No change in behaviour: an_arc_picked_just_off_one_end_loses_the_piece_at_that_end covers it.
2026-11-19 15:17:16 -07:00
Tanish Manku 451caaac32 Stack d2: #2759: EXTEND's params name the open-polyline end rule
#2693 extends the end of an open polyline on the pick's side of its middle parameter, not the
nearer end; the EXTEND params doc from #2759 said only "the nearer end".
2026-11-19 15:15:33 -07:00
Tanish Manku 0cd36ad172 Stack d2: #2759: a pick on a line far from the origin is on it
The JSON TRIM diagnostic told a pick on the line from one off it within an absolute 1e-9. At
survey coordinates rounding alone moves the pick further than that, so a pick on the line was
reported as off it. The tolerance is now rounding of the coordinates, at least 1e-9.
2026-11-19 15:15:20 -07:00
Tanish Manku 63347dbf12 Stack d2: #2759: explain a line TRIM picked on its only cut
#2648 refuses a line trim picked within 5e-7 of its only cut with its own message, and Quick mode
leaves the line in place. The JSON form now explains that refusal as it explains the generic one,
and the Quick-mode test expects the line kept, as #2648 measured in AutoCAD 2024.
2026-11-19 15:15:12 -07:00
Tanish Manku 05cfcaa249 Merge branch 'pr/2759' into stack/d2
# Conflicts:
#	crates/engine/src/cmd/modify.rs
#	crates/engine/src/cmd/modify/trim.rs
#	crates/engine/src/cmd/trimextend.rs
#	crates/engine/tests/it/main.rs
2026-11-19 14:47:50 -07:00
Tanish Manku 6ed36aa844 Merge branch 'pr/3183' into stack/d2 2026-11-19 14:47:09 -07:00
Tanish Manku cd4e04a0d1 Merge branch 'pr/2104' into stack/d2 2026-11-19 14:47:09 -07:00
Tanish Manku 76b13c7ed2 Merge branch 'pr/2693' into stack/d2
# Conflicts:
#	crates/engine/tests/it/main.rs
2026-11-19 14:47:08 -07:00
Tanish Manku 26819d3a68 Merge branch 'pr/2648' into stack/d2 2026-11-19 14:46:59 -07:00
Tanish Manku 777ebededb Merge branch 'pr/2550' into stack/d2 2026-11-19 14:46:59 -07:00
Tanish Manku 41368223db Merge branch 'pr/2548' into stack/d2 2026-11-19 14:46:59 -07:00
jayzed80 8db82ebf7c TRIM/EXTEND: Space enters an option at the mode, projection and edge prompts (#3092) 2026-11-15 09:38:01 +00:00
Zaxaerith 149ba217ef fix(engine): distinguish TRIM pick failures and unblock formatting 2026-11-15 16:23:24 +08:00
Zaxaerith 41c2a99a22 Merge upstream main into the TRIM and EXTEND pick fix
Keep the TRIM handle-return contract and clarify the projected cutting-intersection diagnostic.
2026-11-15 14:13:58 +08:00
Zaxaerith 96a9fa615c fix(engine): clarify JSON TRIM and EXTEND pick diagnostics (#2750) 2026-11-04 12:13:46 +08:00
2ez4gcxandClaude Opus 5.5 cf46d11e27 BREAK and BREAKATPOINT: test the measured ends, closing side and undo
Pins AutoCAD 2024's results (accoreconsole, entget of every object after
the command) for the cases that are easy to get wrong:

- BREAKATPOINT at either end of a line, or at the end vertex of an open
  polyline, leaves the object whole;
- at an open polyline's middle vertex it splits it there, the original
  keeping the first part;
- BREAK of a closed polyline at two points of one side, either way round
  and on the side that closes it too, opens it with its own handle;
- a circle trimmed or broken becomes an arc with its own handle.

Undo after each break restores the object under its handle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 20:37:26 +07:00
2ez4gcxandClaude Opus 5.5 1b7cf50fbe Arc points a hair outside the sweep take the nearer end
EXTEND, TRIM, BREAK, DIVIDE and MEASURE place a point on an arc segment by
its angle from the arc's start. A point the closest-point search accepts
just before the start (within the 1e-12 sweep tolerance) wrapped round to
nearly a full turn and was clamped to the far end:

- EXTEND on a polyline picked there extended the wrong end;
- TRIM put a second cut at the far end of an arc span when a cutting edge
  ran through the vertex where the span starts (63 of 400 angles through
  that vertex on main), and took out the arc alone;
- DIVIDE and MEASURE ran from the wrong end.

`curves::seg_param` now sends an angle outside the sweep to the nearer end.
TRIM's `param_on` is that function, and EXTEND takes its pick parameter from
`curves::vertex_param_of`, the walk DIVIDE uses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:15:56 +07:00
2ez4gcxandClaude Opus 5.5 f6a97d273f EXTEND: a polyline extends the end on the pick's side of its middle
Measured in AutoCAD 2024 (accoreconsole): EXTEND on an open polyline
extends the end on the pick's side of the polyline's middle parameter,
not the end vertex nearer the pick. The pick's parameter is the segment
it is nearest, counted from 0, plus how far along it; from half the
number of segments on, the last end extends. (0,220) (20,220) (20,230)
(15,221) picked at (16,220) is 0.8 of 3, so the first end extends,
though the last vertex is 1.4 from the pick.

A repeated vertex counts as a segment, so the parameter is computed
over the vertex pairs rather than Polyline::segments.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 12:20:28 +07:00
2ez4gcxandClaude Opus 5.5 1415bb7fe1 Merge fix/break-trim-geometry into feat/breakatpoint-command-line
Brings #2548's measured pass-over rule: a cut by another edge at the
pick is passed over; a pick on the polyline's own cut trims nothing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 00:05:33 +07:00
2ez4gcxandClaude Opus 5.5 f370a5580e TRIM: lines, arcs and circles pass over a cut at the pick
Measured in AutoCAD 2024 (accoreconsole). A line, an arc or a circle
picked within 5e-7 of a cut by another edge runs the trim on across
that cut, as a polyline does: a line cut at x = 3 and 7 and picked on
3 loses 0 to 7; a circle cut at 60, 120, 240 and 300 degrees and
picked on 60 loses the arc from 300 round to 120. With no cut left,
nothing is trimmed, and Quick mode leaves the object in place, as it
meets an edge.

An arc picked just off its start is now trimmed at its start: the pick
was taken as being at the arc's end, round the circle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 23:23:59 +07:00
2ez4gcxandClaude Opus 5.5 3a9b653b51 TRIM: a cut by another edge at the pick is passed over
Measured in AutoCAD 2024 (accoreconsole): a pick within 5e-7 of a cut
by another edge doesn't leave the polyline as it is. AutoCAD runs the
piece on across that cut to the next one either side: with lines at
x = 3 and 7, a pick on 3 removes 0 to 7; with lines at 3, 5 and 7, a
pick on 5 removes 3 to 7. A pick that near one of the polyline's own
cuts (a vertex, where it is one of its own edges) still trims nothing.

When every cut is passed over, the refusal doesn't say "intersect", so
Quick mode doesn't erase the polyline as one no edge crosses.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 23:19:42 +07:00
2ez4gcxandClaude Opus 5.5 b1fa96a690 Merge fix/break-trim-geometry into feat/breakatpoint-command-line
Brings #2548's measured TRIM rules: a pick on a cut trims nothing,
vertices in line don't cut, an edge through a closed polyline's start
vertex cuts it, and a closed polyline cut once is refused.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:31:53 +07:00
2ez4gcxandClaude Opus 5.5 061ecd1cd6 TRIM: a pick on a cut trims nothing; vertices in line don't cut
Measured in AutoCAD 2024 (accoreconsole) and followed here:

- A pick within 5e-7 of a cut along the polyline trims nothing, at any
  size; this replaces picking a side by cut index.
- An edge through a closed polyline's start vertex cuts it there.
- A closed polyline cut at one point is refused ("Curve must intersect
  cutting edges at least twice."); Quick mode leaves it in place.
- A vertex between two line segments within 1e-8 of parallel, straight
  on or doubling back, is not a cut.
- Crossing picks stay just inside a segment, off its vertices.

A polyline's own crossings are searched only on the segment picked and
those it runs straight on into, against the segments near them; past
2^24 pairs or 65,536 crossings the trim is refused instead of being made
at some of its cuts.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 22:31:38 +07:00
ZachAR3 7619133bd6 docs: leave geometry-parity.md unchanged in this PR (#1594) 2026-11-02 16:07:30 +01:00
ZachAR3 596b9fe2ca Merge remote-tracking branch 'origin/main' into extend-trim-quick-fence
# Conflicts:
#	crates/engine/src/cmd/trimextend.rs
#	docs/geometry-parity.md
2026-11-02 15:37:54 +01:00
2ez4gcxandClaude Opus 5.5 c039fee2df Merge fix/break-trim-geometry into feat/breakatpoint-command-line
Brings #2548's index-based choice of the piece next to a picked cut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:15:52 +07:00
2ez4gcxandClaude Opus 5.5 9c2b8a2589 TRIM: a pick on a cut takes the piece next to that cut, by index
The split point was moved 2 x 4 ULP off a cut the pick was on. When two
cuts are closer than that (1e9 out, a segment a few ULP long) it moved
past the other cut too, and the long segment before was trimmed instead
of the short one picked. The cut the pick is on (the nearest within
rounding) now bounds the piece directly: with the next cut when the pick
is at its segment's start, with the previous one otherwise.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 18:15:46 +07:00
2ez4gcxandClaude Opus 5.5 189b1810f4 Merge fix/break-trim-geometry into feat/breakatpoint-command-line
Brings #2548's fix keeping a pick inside a segment on its side of a cut.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:22:30 +07:00
2ez4gcxandClaude Opus 5.5 45d84f1090 TRIM: only a pick on a cut picks a side of it
A pick within 1e-9 of the polyline's length from a cut was moved across
it. On a long polyline that window is wide: 10000 long, a pick inside a
segment a millionth long was moved before the cut ahead of it, and
1e9 long, a pick half a unit up the second segment was moved onto the
first, so the wrong segment was trimmed. Only a pick on a cut within
rounding (4 ULP of the length) now picks a side of it; any other pick
splits the cuts where it is.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 15:22:24 +07:00
2ez4gcxandClaude Opus 5.5 0f645f1275 Merge fix/break-trim-geometry into feat/breakatpoint-command-line
Brings #2548's fixes for a pick on a vertex and for closing pieces.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:46:31 +07:00
2ez4gcxandClaude Opus 5.5 e35dfe6533 TRIM: a pick on a vertex keeps the polyline; close only meeting ends
A pick exactly on a cut (a vertex, now that a polyline cuts itself at
each) found no piece on either side, and the whole polyline was erased.
It now takes the piece of the segment it was found on: the one before a
vertex the segment ends at, the one after a vertex it starts at.

A piece was closed when its ends were within 1e-9 of the coordinates'
size: about one unit 1e9 from the origin, so ends 0.58 apart closed. It
is now rounding error only, 64 ULP of the larger coordinate.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 12:46:23 +07:00
2ez4gcxandClaude Opus 5.5 179e946a70 Merge fix/break-trim-geometry into feat/breakatpoint-command-line
Brings #2548's touch points and Quick-mode self-cuts for TRIM of a
polyline into this stacked branch.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:11:49 +07:00
2ez4gcxandClaude Opus 5.5 a70223e25f TRIM: a polyline cuts itself where it touches itself, in Quick mode too
A polyline that is one of the cutting edges was cut at its vertices and
where two of its segments cross, not where a vertex of it (an end
included) touches another of its segments. Trimmed there, a polyline
whose end returns onto its own segment lost the stretch past the touch
too. In Quick mode with every object it didn't cut itself at all.

As AutoCAD 2024 does (Standard mode by accoreconsole; Quick mode in
AutoCAD itself, picking on screen):
- a vertex touching another segment of the same polyline cuts that
  segment, in Standard and in Quick mode;
- a piece whose two ends meet is left closed, without the repeated
  vertex, its arcs kept.

Edges::quick is gone: nothing reads it any more.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-02 11:11:31 +07:00
2ez4gcxandClaude Opus 5.5 032a5dc3c7 feat(modify): BREAKATPOINT at the command line, as AutoCAD does
BREAKATPOINT gets AutoCAD 2024's prompts ("Select object:", then
"Specify break point:") and splits the object there; before, it only
had its JSON form, so typing it, a script or the menu failed. BREAK
and BREAKATPOINT now end the command when the break can't be made
("Arc cannot be full 360 degrees", no full stop, as measured), refuse
an object on a locked layer when it is picked, and leave nothing
selected after Enter.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 18:19:01 +07:00
2ez4gcxandClaude Opus 5.5 4c875d949e fix(modify): BREAK and TRIM on closed and self-cutting polylines, keeping Z
BREAK on a closed polyline removes the stretch between the two points
that doesn't run through the start vertex, whichever point comes first;
at one point (or BREAKATPOINT) it splits the polyline in two, and at the
start vertex leaves it closed. In Standard mode, or when picked as an
edge, a polyline that is one of the cutting edges is also cut at its own
vertices and crossings. Pieces keep a line's Z, an arc's centre Z and a
polyline's elevation, constant width and linetype generation, for TRIM
as for BREAK. All measured in AutoCAD 2024 except Quick mode's implicit
edges, which keep leaving the polyline out.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 17:12:08 +07:00
ZachAR3 683dd0bfec TRIM and EXTEND: test Quick-mode EXTEND through its fence (#1594)
The empty-space fence test now drives EXTEND through the second fence
point and checks the extended lines, not only the prompt.
2026-10-25 02:09:31 +01:00
ZachAR3 61483802a1 TRIM and EXTEND: a pick in empty space starts a fence in Quick mode (fixes #1594)
In Quick mode AutoCAD reads two picks in empty space as a crossing
fence: everything the fence crosses is trimmed or extended, without
choosing the Fence option first. CADCraft opened a crossing window
there. A pick in empty space now starts that two-point fence in Quick
mode; the next point applies it and the command asks for the next
object again. Standard mode keeps the crossing window.
2026-10-25 00:19:11 +02:00
49 changed files with 2280 additions and 2655 deletions
+1 -39
View File
@@ -931,49 +931,11 @@ pub struct Ucs {
pub y_axis: Vec3,
}
/// A saved layer state (LAYERSTATE), as AutoCAD keeps one in the LAYER table's
/// `ACAD_LAYERSTATES` dictionary.
/// A saved layer state (LAYERSTATE).
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default)]
pub struct LayerState {
pub name: String,
pub layers: Vec<Layer>,
/// The properties restoring sets ([`LayerState::ON`] …): AutoCAD's mask (group 91 of the
/// state's XRECORD). Bits CADCraft doesn't use are kept as read.
pub mask: u32,
/// The layer restoring makes current; empty, or a layer the drawing doesn't have, leaves the
/// current layer as it is (AutoCAD 2024, measured).
pub current: String,
/// Group 301 of the state's XRECORD: empty as AutoCAD 2024's -LAYER saves a state; a text a
/// file holds there is kept.
pub description: String,
}
impl Default for LayerState {
fn default() -> Self {
LayerState { name: String::new(), layers: Vec::new(), mask: LayerState::ALL, current: String::new(), description: String::new() }
}
}
impl LayerState {
pub const ON: u32 = 1;
pub const FROZEN: u32 = 2;
pub const LOCKED: u32 = 4;
pub const PLOT: u32 = 8;
pub const VP_FREEZE_NEW: u32 = 16;
pub const COLOR: u32 = 32;
pub const LINETYPE: u32 = 64;
pub const LINEWEIGHT: u32 = 128;
pub const PLOT_STYLE: u32 = 256;
pub const TRANSPARENCY: u32 = 1024;
/// Every property: the mask of AutoCAD 2024's -LAYER stAte Save with its defaults (2047; bit
/// 512, which no property toggles, is always set).
pub const ALL: u32 = 2047;
/// A state of every property of `layers`, with `current` the layer restoring makes current.
pub fn new(name: impl Into<String>, layers: Vec<Layer>, current: impl Into<String>) -> Self {
LayerState { name: name.into(), layers, current: current.into(), ..LayerState::default() }
}
}
/// A named group of entities (GROUP).
+12 -72
View File
@@ -27,10 +27,6 @@ mod edit;
/// Most preview entities drawn while the array is edited.
const PREVIEW_LIMIT: usize = 2000;
/// Most objects whose key points are searched for a Key point base point.
const MAX_KEY_OBJECTS: usize = 10_000;
/// The prompt after the Key point option of a base point.
const KEY_POINT_PROMPT: &str = "Specify key point on source objects to use as base point";
/// Keyword-only prompts: each typed token is matched on its own (no free text).
const KEYWORDS: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
@@ -45,13 +41,13 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("arrayrect", "Rectangular Array", run_arrayrect)
.menu(&["Modify", "Array", "Rectangular Array"])
.params(
"{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
"{handles?, rows, cols, rowSpacing, colSpacing, levels? (1), levelSpacing?, rowElevation?, axisAngle? (degrees), base? ([x, y], default the objects' centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
)
.interactive(|_| Ok(Box::new(RectM::default()))),
CommandSpec::new("arraypolar", "Polar Array", run_arraypolar)
.menu(&["Modify", "Array", "Polar Array"])
.params(
"{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), keyPoint? ([x, y]: the base point is the objects' key point nearest it), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
"{handles?, center, count, angle? (degrees, default 360), rotate?: bool, rows? (1), rowSpacing?, rowElevation?, levels? (1), levelSpacing?, base? ([x, y], default the first object's centre), associative?: bool (default ARRAYASSOCIATIVITY, on)} → {handle (the array, when associative), created (copies)}",
)
.interactive(|_| Ok(Box::new(PolarM::default()))),
CommandSpec::new("-array", "Array", classic::run_classic)
@@ -250,45 +246,6 @@ fn bounds(d: &Drawing, hs: &[Handle]) -> Bounds2 {
hs.iter().filter_map(|h| d.entity(*h).map(|e| cadcraft_doc::entity_bounds(d, e, 0))).fold(Bounds2::EMPTY, |a, b| a.union(&b))
}
/// The key point of `ents`, placed by `m`, nearest `at`: one of their grips (end points,
/// midpoints, centres, vertices, insertion points). `None` when they have none. More than
/// [`MAX_KEY_OBJECTS`] objects are refused: searching only some could miss the nearest one.
pub(crate) fn nearest_key_point<'a>(ents: impl Iterator<Item = &'a Entity>, m: &Mat3, at: Vec2) -> Result<Option<Vec2>> {
if !at.is_finite() {
return Ok(None);
}
let mut best: Option<(Vec2, f64)> = None;
for (n, e) in ents.enumerate() {
if n >= MAX_KEY_OBJECTS {
return Err(other(format!("Too many objects to search for a key point (at most {MAX_KEY_OBJECTS}); specify a point.")));
}
let mut k = e.kind.clone();
k.transform(m);
for g in k.grips().into_iter().filter(|g| g.is_finite()) {
let d = g.dist(at);
if best.is_none_or(|(_, bd)| d < bd) {
best = Some((g, d));
}
}
}
Ok(best.map(|b| b.0))
}
/// `keyPoint` of a JSON form: absent or null is none; anything else must be a point, rather than
/// be taken as none and the base point found another way.
pub(crate) fn key_point_param(cmd: &str, p: &Value) -> Result<Option<Vec2>> {
match p.get("keyPoint") {
None | Some(Value::Null) => Ok(None),
Some(_) => point_param(p, "keyPoint").map(Some).ok_or_else(|| bad(cmd, "`keyPoint` must be a point [x, y]")),
}
}
/// The key point of objects `hs` in the drawing nearest `at`.
pub(crate) fn key_point_of(d: &Drawing, hs: &[Handle], at: Vec2) -> Result<Vec2> {
nearest_key_point(hs.iter().filter_map(|h| d.entity(*h)).map(|e| &**e), &Mat3::IDENTITY, at)?
.ok_or_else(|| other("The objects have no key point; specify a point."))
}
/// The centre of the first object (the point a non-rotated polar copy is moved by).
fn first_center(d: &Drawing, hs: &[Handle]) -> Option<Vec2> {
hs.first().and_then(|h| d.entity(*h)).map(|e| cadcraft_doc::entity_bounds(d, e, 0).center()).filter(|c| c.is_finite())
@@ -429,10 +386,9 @@ fn run_arrayrect(s: &mut Session, p: &Value) -> Result<Value> {
row_elevation: f64_or(p, "rowElevation", 0.0),
});
let rs = f64_or(p, "rowSpacing", 1.0);
let base = match (key_point_param("arrayrect", p)?, point_param(p, "base")) {
(Some(k), _) => key_point_of(s.doc()?, &hs, k)?,
(None, Some(b)) => b,
(None, None) => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(),
let base = match point_param(p, "base") {
Some(b) => b,
None => Some(bounds(s.doc()?, &hs).center()).filter(|c| c.is_finite()).unwrap_or_default(),
};
let p2 = params(kind, levels, f64_or(p, "levelSpacing", rs));
let associative = bool_or(p, "associative", assoc_default(s));
@@ -446,10 +402,7 @@ fn run_arraypolar(s: &mut Session, p: &Value) -> Result<Value> {
let rows = count_or("arraypolar", p, "rows", 1)?;
let levels = count_or("arraypolar", p, "levels", 1)?;
check_size(s, n.saturating_mul(rows).saturating_mul(levels), hs.len())?;
let base = match key_point_param("arraypolar", p)? {
Some(k) => key_point_of(s.doc()?, &hs, k)?,
None => point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c),
};
let base = point_param(p, "base").or_else(|| s.doc().ok().and_then(|d| first_center(d, &hs))).unwrap_or(c);
let row_spacing = f64_or(p, "rowSpacing", 1.0);
let fill = f64_or(p, "angle", 360.0);
if !(fill.abs() >= 1e-9 && fill.abs() <= 360.0 + 1e-9) {
@@ -550,8 +503,6 @@ enum RStage {
Main,
Assoc,
Base,
/// Base point: Key point (a grip of the source objects).
BaseKey,
/// COUnt: columns, then rows.
CountCols,
CountRows,
@@ -712,7 +663,6 @@ impl Interactive for RectM {
.default("eXit"),
Assoc => assoc_prompt(self.assoc),
Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
CountCols | ColsCount => cols(),
CountRows | RowsCount => rows(),
SpaceCols => dist("Specify the distance between columns", self.cs).kw(&["Unit cell"]),
@@ -762,12 +712,10 @@ impl Interactive for RectM {
self.base = self.centroid;
Main
}
(Base, Input::Keyword(_)) => BaseKey,
(BaseKey, Input::Point(p)) => {
self.base = key_point_of(s.doc()?, &self.objs, *p)?;
Main
(Base, Input::Keyword(_)) => {
s.echo("Key points are not available yet; specify a point.");
Base
}
(BaseKey, Input::Enter) => Base,
(CountCols | ColsCount, _) => match count(&i, self.cols, max_count(s, self.rows.saturating_mul(self.levels), n))? {
Some(c) => {
self.cols = c;
@@ -910,9 +858,6 @@ enum PStage {
Main,
Assoc,
Base,
/// Key point of the base point asked from the center prompt, or from the main prompt.
CenterBaseKey,
BaseKey,
Items,
Between,
Fill,
@@ -1089,7 +1034,6 @@ impl Interactive for PolarM {
match self.stage {
Center => Prompt::new("Specify center point of array", Accept::POINT).kw(&["Base point", "Axis of rotation"]),
CenterBase | Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
CenterBaseKey | BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
Main => Prompt::new("Select grip to edit array", Accept::POINT)
.kw(&["ASsociative", "Base point", "Items", "Angle between", "Fill angle", "ROWs", "Levels", "ROTate items", "eXit"])
.default("eXit"),
@@ -1148,14 +1092,10 @@ impl Interactive for PolarM {
self.base = None;
if stage == CenterBase { Center } else { Main }
}
(CenterBase, Input::Keyword(_)) => CenterBaseKey,
(Base, Input::Keyword(_)) => BaseKey,
(CenterBaseKey | BaseKey, Input::Point(p)) => {
self.base = Some(key_point_of(s.doc()?, &self.objs, *p)?);
if stage == CenterBaseKey { Center } else { Main }
(CenterBase | Base, Input::Keyword(_)) => {
s.echo("Key points are not available yet; specify a point.");
stage
}
(CenterBaseKey, Input::Enter) => CenterBase,
(BaseKey, Input::Enter) => Base,
(Items, _) => match count(&i, self.items, max_count(s, self.rows.saturating_mul(self.levels), n))? {
Some(c) => {
self.items = c;
+10 -49
View File
@@ -18,9 +18,7 @@ use super::super::helpers::v3;
use super::super::machines::{SelOutcome, SelectPhase, number};
use super::super::{CommandSpec, bad, bool_or, point_param, targets};
use super::{
KEY_POINT_PROMPT, KEYWORDS, angle, check_size, count, fmt, key_point_of, key_point_param, nearest_key_point, nesting, other, yes, yes_no,
};
use super::{KEYWORDS, angle, check_size, count, fmt, nesting, other, yes, yes_no};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub(super) fn specs() -> Vec<CommandSpec> {
@@ -28,7 +26,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
CommandSpec::new("arrayedit", "Edit Array", run_arrayedit)
.menu(&["Modify", "Object", "Array"])
.params(
"{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, keyPoint? ([x, y]: the new base point is the source objects' key point nearest it, on the item there), replace?.keyPoint? ([x, y]: the replacement objects' key point nearest it is their base point), source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}",
"{handle, cols?, rows?, colSpacing?, rowSpacing?, axisAngle? (degrees), rowElevation?, levels?, levelSpacing?, items?, angle? (fill, degrees), angleBetween?, rotate?: bool, center? ([x, y]), base? ([x, y], the new base point), reset?: bool, replace?: {handles, base? ([x, y], default the objects' centre), items: [[i, j, level]…] | \"source\"}, source?: {item? ([i, j, level], default [0, 0, 0])} (places the source objects for editing; ARRAYCLOSE ends)}",
)
.interactive(|_| Ok(Box::new(EditM::default()))),
CommandSpec::new("arrayclose", "Close Array Editing", run_arrayclose)
@@ -217,16 +215,6 @@ fn item_at(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Option<(u32, u32, u32)
best.map(|b| b.0)
}
/// ARRAYEDIT Key point: the key point of the source objects nearest `at`, with the objects as
/// placed at the item under `at` (within `tol`).
fn source_key_point(d: &Drawing, h: Handle, at: Vec2, tol: f64) -> Result<Vec2> {
let item = item_at(d, h, at, tol).ok_or_else(|| other("No array item there; specify a point on an item of the array."))?;
let (ins, blk, p) = array_of(d, h)?;
let src = d.block(&p.source).ok_or_else(|| other("The array's source block is missing."))?;
let m = ins.transform(blk.base.xy()).then_before(item_place(&p, item)?).then_before(Mat3::translate(-src.base.xy()));
nearest_key_point(src.entities.iter().map(|e| e.as_ref()), &m, at)?.ok_or_else(|| other("The source objects have no key point; specify a point."))
}
/// Move the base point of array `h` to world point `base` without moving the items.
fn rebase(s: &mut Session, h: Handle, base: Vec2) -> Result<()> {
let d = s.doc()?;
@@ -355,9 +343,6 @@ fn close_source(s: &mut Session, save: bool) -> Result<Value> {
// ---------------- JSON ----------------
/// How far outside an item's extents a JSON `keyPoint` may be.
const KEY_POINT_TOLERANCE: f64 = 1e-6;
fn item_param(v: &Value) -> Option<(u32, u32, u32)> {
let a = v.as_array()?;
let n = |k: usize| a.get(k).and_then(Value::as_u64).and_then(|x| u32::try_from(x).ok());
@@ -464,7 +449,9 @@ fn fill_from_between(b: f64, items: u32) -> Result<f64> {
fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
let h = super::super::curves::handle_param(p, "handle").ok_or_else(|| bad("arrayedit", "`handle` (the array) is required"))?;
refuse_while_editing(s)?;
array_of(s.doc()?, h)?;
let (ins, blk, _) = array_of(s.doc()?, h)?;
let w = ins.transform(blk.base.xy());
let to_local = w.inverse().ok_or_else(|| other("The array's scale is zero."))?;
if bool_or(p, "reset", false) {
let (_, _, mut a) = array_of(s.doc()?, h)?;
a.replaced.clear();
@@ -472,10 +459,7 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
}
if let Some(r) = p.get("replace").filter(|v| !v.is_null()) {
let hs = targets(s, r)?;
let base = match key_point_param("arrayedit", r)? {
Some(k) => key_point_of(s.doc()?, &hs, k)?,
None => point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default()),
};
let base = point_param(r, "base").unwrap_or_else(|| s.doc().map(|d| centroid(d, &hs)).unwrap_or_default());
let name = block_from(s, h, &hs, base)?;
let (_, _, mut a) = array_of(s.doc()?, h)?;
match r.get("items") {
@@ -493,13 +477,7 @@ fn run_arrayedit(s: &mut Session, p: &Value) -> Result<Value> {
if let Some(b) = point_param(p, "base") {
rebase(s, h, b)?;
}
if let Some(k) = key_point_param("arrayedit", p)? {
let at = source_key_point(s.doc()?, h, k, KEY_POINT_TOLERANCE)?;
rebase(s, h, at)?;
}
// A new base point moves the array's insertion point: read `center` in its placement after.
let (ins, blk, mut a) = array_of(s.doc()?, h)?;
let to_local = ins.transform(blk.base.xy()).inverse().ok_or_else(|| other("The array's scale is zero."))?;
let (_, _, mut a) = array_of(s.doc()?, h)?;
let before = a.clone();
apply_params(&mut a, p, &to_local)?;
if a != before {
@@ -529,8 +507,6 @@ enum Stage {
Select,
Main,
Base,
/// Base point: Key point (of the source objects).
BaseKey,
ColsCount,
ColsSpace,
ColsTotal,
@@ -548,8 +524,6 @@ enum Stage {
/// REPlace: objects, their base point, then the items to replace.
RepSelect,
RepBase,
/// REPlace base point: Key point (of the replacement objects).
RepKey,
RepItems,
/// Source: the item whose objects are placed for editing.
SourceItem,
@@ -685,7 +659,6 @@ impl Interactive for EditM {
.kw(&["Source", "REPlace", "Base point", "Rows", "Columns", "Levels", "RESet", "eXit"])
.default("eXit"),
Base => Prompt::new("Specify base point", Accept::POINT).kw(&["Key point"]).default("centroid"),
BaseKey => Prompt::new(KEY_POINT_PROMPT, Accept::POINT),
ColsCount => Prompt::new("Enter the number of columns", Accept::NUMBER).default(cols.to_string()),
ColsSpace => dist("Specify the distance between columns", cs).kw(&["Total"]),
ColsTotal => dist("Specify the distance between the first and last column", total(cols, cs)),
@@ -714,7 +687,6 @@ impl Interactive for EditM {
Rotate => Prompt::new("Rotate arrayed items?", KEYWORDS).kw(&["Yes", "No"]).default(yes(polar.as_ref().is_none_or(|k| k.rotate))),
RepSelect => Prompt::new("Select replacement objects", Accept::SELECT),
RepBase => Prompt::new("Select base point of replacement objects", Accept::POINT).kw(&["Key point"]).default("centroid"),
RepKey => Prompt::new("Specify key point on replacement objects to use as base point", Accept::POINT),
RepItems => Prompt::new("Select an item in array to replace", Accept::POINT).kw(&["Source objects"]),
SourceItem => Prompt::new("Select item in array", Accept::POINT),
}
@@ -774,21 +746,10 @@ impl Interactive for EditM {
}
Main
}
(Base, Input::Keyword(_)) => BaseKey,
(RepBase, Input::Keyword(_)) => RepKey,
(BaseKey, Input::Point(p)) => {
let tol = s.pixel_size() * s.settings.pickbox;
let at = source_key_point(s.doc()?, h, *p, tol)?;
rebase(s, h, at)?;
Main
(Base | RepBase, Input::Keyword(_)) => {
s.echo("Key points are not available yet; specify a point.");
stage
}
(BaseKey, Input::Enter) => Base,
(RepKey, Input::Point(p)) => {
let base = key_point_of(s.doc()?, &self.rep_objs, *p)?;
self.rep_block = Some(block_from(s, h, &self.rep_objs.clone(), base)?);
RepItems
}
(RepKey, Input::Enter) => RepBase,
(ColsCount | Items, _) => match count(&i, c64, self.max_for(s, r64.saturating_mul(l64)))? {
Some(n) => {
let n = super::count32(n);
+6 -164
View File
@@ -4,7 +4,6 @@
use cadcraft_doc::color::Color;
use cadcraft_doc::{AttribProps, Common, EntityKind, HAlign, Handle, Text, VAlign};
use cadcraft_geom::Vec3;
use serde_json::{Map, Value, json};
use crate::cmd::curves::KW;
@@ -154,19 +153,6 @@ fn set_value(text: &mut Text, value: String) {
}
}
/// Move `text` so the point it is placed by lands on `to`: the alignment point of justified text,
/// else the insertion point. Both points move by the same offset, so aligned and fit text keep the
/// baseline between them.
fn move_text(text: &mut Text, to: cadcraft_geom::Vec2) {
let anchor = match text.align_pt {
Some(ap) if !matches!((text.halign, text.valign), (HAlign::Left, VAlign::Baseline) | (HAlign::Aligned | HAlign::Fit, _)) => ap,
_ => text.insert,
};
let d = Vec3::new(to.x - anchor.x, to.y - anchor.y, 0.0);
text.insert = text.insert + d;
text.align_pt = text.align_pt.map(|ap| ap + d);
}
/// Change the properties set on attribute `k` of block reference `h`.
fn set_props(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut AttribProps)) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
@@ -179,18 +165,6 @@ fn set_props(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut Attri
Ok(())
}
/// Modify the attribute `k` of block reference `h`.
fn modify_attrib(s: &mut Session, (h, k): (Handle, usize), f: impl FnOnce(&mut cadcraft_doc::Attrib)) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
if let EntityKind::Insert(ins) = &mut e.kind
&& let Some(a) = ins.attribs.get_mut(k)
{
f(a);
}
})?;
Ok(())
}
/// The layer and colour attribute `k` of block reference `h` is drawn with: its own, else its
/// definition's (layer 0 is the reference's layer).
fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)> {
@@ -206,14 +180,6 @@ fn current_props(s: &Session, (h, k): (Handle, usize)) -> Option<(String, Color)
Some((layer, c.color))
}
/// The current text properties of attribute `k` of block reference `h`.
fn current_text(s: &Session, (h, k): (Handle, usize)) -> Option<cadcraft_doc::Text> {
let d = s.doc().ok()?;
let e = d.entity(h)?;
let EntityKind::Insert(ins) = &e.kind else { return None };
ins.attribs.get(k).map(|a| a.text.clone())
}
/// Replace every `find` in `value` with `with`, unless the result would be too long.
fn replaced(value: &str, find: &str, with: &str) -> Option<String> {
if find.is_empty() || !value.contains(find) {
@@ -326,10 +292,6 @@ enum Stage {
Select,
/// One at a time: what to do with the current attribute.
Option,
Position,
Height,
Angle,
Style,
ValueKind,
NewValue,
Layer,
@@ -403,7 +365,6 @@ impl Interactive for DashAtteditM {
}
fn prompt(&self, s: &Session) -> Prompt {
let cur = self.items.get(self.cur).and_then(|it| current_props(s, *it));
let cur_text = self.items.get(self.cur).and_then(|it| current_text(s, *it));
match self.stage {
Stage::OneAtATime => Prompt::new("Edit attributes one at a time?", KW).kw(&["Yes", "No"]).default("Y"),
Stage::VisibleOnly => Prompt::new("Edit only attributes visible on screen?", KW).kw(&["Yes", "No"]).default("Y"),
@@ -411,31 +372,7 @@ impl Interactive for DashAtteditM {
Stage::TagSpec => Prompt::new("Enter attribute tag specification", Accept::TEXT).default("*"),
Stage::ValueSpec => Prompt::new("Enter attribute value specification", Accept::TEXT).default("*"),
Stage::Select => Prompt::new("Select attributes", Accept::SELECT),
Stage::Option => {
Prompt::new("Enter an option", KW).kw(&["Value", "Position", "Height", "Angle", "Style", "Layer", "Color", "Next"]).default("N")
}
Stage::Position => Prompt::new("Enter new text insertion point", Accept::POINT),
Stage::Height => {
let p = Prompt::new("Enter new text height", Accept::POINT_OR_NUMBER);
match cur_text {
Some(t) => p.default(format!("{:.4}", t.height)),
None => p,
}
}
Stage::Angle => {
let p = Prompt::new("Enter new text rotation angle", Accept::POINT_OR_NUMBER);
match cur_text {
Some(t) => p.default(format!("{:.4}", t.rotation.to_degrees())),
None => p,
}
}
Stage::Style => {
let p = Prompt::new("Enter new text style", Accept::TEXT);
match cur_text {
Some(t) => p.default(t.style),
None => p,
}
}
Stage::Option => Prompt::new("Enter an option", KW).kw(&["Value", "Layer", "Color", "Next"]).default("N"),
Stage::ValueKind => Prompt::new("Enter type of value modification", KW).kw(&["Change", "Replace"]).default("R"),
Stage::NewValue => Prompt::new("Enter new attribute value", Accept::TEXT),
Stage::Layer => {
@@ -509,10 +446,6 @@ impl Interactive for DashAtteditM {
}
Stage::Option => match &i {
Input::Keyword(k) if k == "Value" => self.stage = Stage::ValueKind,
Input::Keyword(k) if k == "Position" => self.stage = Stage::Position,
Input::Keyword(k) if k == "Height" => self.stage = Stage::Height,
Input::Keyword(k) if k == "Angle" => self.stage = Stage::Angle,
Input::Keyword(k) if k == "Style" => self.stage = Stage::Style,
Input::Keyword(k) if k == "Layer" => self.stage = Stage::Layer,
Input::Keyword(k) if k == "Color" => self.stage = Stage::Color,
Input::Keyword(_) | Input::Enter => {
@@ -524,105 +457,14 @@ impl Interactive for DashAtteditM {
}
Input::Text(t) => {
let tl = t.trim().to_ascii_lowercase();
let opts = ["Value", "Position", "Height", "Angle", "Style", "Layer", "Color", "Next"];
match opts.iter().find(|k| !tl.is_empty() && k.to_ascii_lowercase().starts_with(&tl)) {
Some(&"Value") => self.stage = Stage::ValueKind,
Some(&"Position") => self.stage = Stage::Position,
Some(&"Height") => self.stage = Stage::Height,
Some(&"Angle") => self.stage = Stage::Angle,
Some(&"Style") => self.stage = Stage::Style,
Some(&"Layer") => self.stage = Stage::Layer,
Some(&"Color") => self.stage = Stage::Color,
Some(&"Next") => {
self.cur += 1;
if self.cur >= self.items.len() {
return Ok(Step::Done);
}
self.show_current(s);
}
_ => return Err(invalid_keyword()),
}
let later = ["Position", "Height", "Angle", "Style"];
return match later.iter().find(|k| !tl.is_empty() && k.to_ascii_lowercase().starts_with(&tl)) {
Some(k) => Err(EngineError::Other(format!("{k} is not available yet."))),
None => Err(invalid_keyword()),
};
}
_ => {}
},
Stage::Position => {
let p = match i {
Input::Point(p) => p,
Input::Enter => {
self.stage = Stage::Option;
return Ok(Step::Continue);
}
_ => return Ok(Step::Continue),
};
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| move_text(&mut a.text, p))?;
}
self.stage = Stage::Option;
}
Stage::Height => {
let h = match &i {
Input::Point(p) => {
let cur_pt = self.items.get(self.cur).and_then(|it| current_text(s, *it)).map(|t| t.insert.xy());
match cur_pt {
Some(base) => base.dist(*p).max(1e-9),
None => p.len().max(1e-9),
}
}
Input::Text(t) if !t.trim().is_empty() => crate::units::parse_distance(t.trim())
.filter(|v| *v > 0.0)
.ok_or_else(|| EngineError::Other("Requires a positive number.".into()))?,
Input::Enter => {
self.stage = Stage::Option;
return Ok(Step::Continue);
}
_ => return Ok(Step::Continue),
};
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| {
a.text.height = h;
})?;
}
self.stage = Stage::Option;
}
Stage::Angle => {
let ang = match &i {
Input::Point(p) => {
let cur_pt = self.items.get(self.cur).and_then(|it| current_text(s, *it)).map(|t| t.insert.xy());
match cur_pt {
Some(base) => base.angle_to(*p),
None => p.y.atan2(p.x),
}
}
Input::Text(t) if !t.trim().is_empty() => {
s.angle_settings().direction(t.trim()).ok_or_else(|| EngineError::Other("Requires an angle.".into()))?
}
Input::Enter => {
self.stage = Stage::Option;
return Ok(Step::Continue);
}
_ => return Ok(Step::Continue),
};
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| {
a.text.rotation = ang;
})?;
}
self.stage = Stage::Option;
}
Stage::Style => {
let Some(t) = text else { return Ok(Step::Continue) };
let t = t.trim();
if !t.is_empty() {
let st =
s.doc()?.text_style(t).map(|st| st.name.clone()).ok_or_else(|| EngineError::Other(format!("Cannot find style \"{t}\".")))?;
if let Some(it) = self.items.get(self.cur).copied() {
modify_attrib(s, it, |a| {
a.text.style = st;
})?;
}
}
self.stage = Stage::Option;
}
Stage::ValueKind => match &i {
Input::Keyword(k) if k == "Change" => self.stage = Stage::Find,
Input::Keyword(_) | Input::Enter => self.stage = Stage::NewValue,
+11 -1
View File
@@ -564,7 +564,17 @@ pub fn seg_param(s: &Segment, p: Vec2) -> f64 {
match s {
Segment::Line(l) => l.param_of(p).clamp(0.0, 1.0),
Segment::Arc { arc, ccw } => {
let t = (cadcraft_geom::norm_angle(arc.center.angle_to(p) - arc.start) / arc.sweep().max(1e-15)).clamp(0.0, 1.0);
// A point just outside the sweep (on the arc within tolerance of an end) goes to the
// nearer end: a hair before the start is the start, not round the circle to the end.
let a = cadcraft_geom::norm_angle(arc.center.angle_to(p) - arc.start);
let sweep = arc.sweep().max(1e-15);
let t = if a <= sweep {
a / sweep
} else if a - sweep < TAU - a {
1.0
} else {
0.0
};
if *ccw { t } else { 1.0 - t }
}
}
+19
View File
@@ -601,6 +601,25 @@ fn measure_spline_by_its_own_parameter() {
assert!(pts.len() == 3 && [7.0, 4.0, 1.0].iter().all(|x| pts.iter().any(|p| near(*p, *x, 0.0))), "{pts:?}");
}
/// A pick a hair outside an arc's sweep beside its start is at its start, for an arc and for a
/// polyline's arc span alike: MEASURE runs from there (round the circle it was the far end).
#[test]
fn measure_from_a_pick_a_hair_before_an_arcs_start() {
let curves = [
("arc", json!({"center": [0, 0], "radius": 1, "start": 0, "end": 180})),
("pline", json!({"vertices": [{"p": [1, 0], "bulge": 1}, [-1, 0]]})),
];
for (cmd, args) in curves {
let mut s = Session::new();
let e = h(&s.execute(cmd, &args).unwrap());
s.execute("measure", &json!({"handle": e, "length": 1, "from": [1, -1e-13]})).unwrap();
let pts: Vec<Vec2> =
s.doc().unwrap().model.iter().filter_map(|e| if let EntityKind::Point(p) = &e.kind { Some(p.p.xy()) } else { None }).collect();
// From (1, 0), a point every radian.
assert!(pts.len() == 3 && [1.0f64, 2.0, 3.0].iter().all(|a| pts.iter().any(|p| near(*p, a.cos(), a.sin()))), "{cmd}: {pts:?}");
}
}
/// MEASURE counts every vertex in a polyline's parameter, coincident ones too (AutoCAD's polyline
/// parameter is the vertex index; the chain drops zero-length spans), and picks an ellipse's end
/// by the ellipse parameter like any other curve: AutoCAD 2024 runs both measured cases below from
+16 -246
View File
@@ -1,7 +1,6 @@
//! Layers: LAYER (programmatic sub-ids, -LAYER prompts), layer tools (LAYMCUR, LAYISO, LAYOFF, LAYFRZ…).
mod prompts;
mod state_prompts;
use cadcraft_color::Color;
use cadcraft_doc::{Layer, Lineweight};
@@ -56,9 +55,7 @@ pub fn specs() -> Vec<CommandSpec> {
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, mask? (properties restoring sets: 1 on, 2 frozen, 4 locked, 8 plot, 16 new viewport freeze, 32 color, 64 linetype, 128 lineweight, 256 plot style, 1024 transparency; default all)}"),
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}"),
@@ -403,108 +400,31 @@ fn all_layers(s: &mut Session, f: fn(&mut Layer)) -> Result<Value> {
}
fn run_state_save(s: &mut Session, p: &Value) -> Result<Value> {
use cadcraft_doc::LayerState as S;
let name = str_param(p, "name").ok_or_else(|| bad("layerstate.save", "`name` is required"))?.to_string();
// As -LAYER stAte Save and layerstate.rename take names: none empty, over 255 characters, with a
// control character or with one AutoCAD 2024 refuses (measured for Save).
if !valid_name(&name) {
return Err(bad("layerstate.save", "invalid name"));
}
// The properties restoring sets; bit 512, which no property toggles, is always set, as AutoCAD
// 2024 saves it (measured: On alone is 513).
let mask = match p.get("mask") {
None | Some(Value::Null) => S::ALL,
Some(v) => {
let m = v.as_u64().filter(|m| m & !u64::from(S::ALL) == 0);
m.and_then(|m| u32::try_from(m).ok()).ok_or_else(|| bad("layerstate.save", "`mask` must be a sum of layer state bits (0 to 2047)"))? | 512
}
};
let d = s.doc_mut()?;
let layers = d.layers.clone();
let current = d.header.str("CLAYER", "0");
// Replace the state Restore and Delete reach (the same spelling, else another case), so a
// drawing keeps one state per name: AutoCAD 2024 finds states without regard to case. Its
// -LAYER stAte Save and layerstate-save refuse `s1` after `S1` (measured), as the command line
// here does; this command replaces, as it does a state of the same spelling. When a file holds
// both `S1` and `s1`, only the one spelled so is replaced.
if let Some(i) = state_index(d, &name) {
d.layer_states.remove(i);
}
d.layer_states.push(S { mask, ..S::new(name, layers, current) });
d.layer_states.retain(|st| st.name != name);
d.layer_states.push(cadcraft_doc::LayerState { name, layers });
ok()
}
/// The saved state called `name`: the one spelled so, else the first whose name differs only in
/// case. AutoCAD 2024 finds layer states without regard to case (measured: Restore, Edit, Name
/// and Delete of `s1` reach `S1`); case is compared as for layers and view snapshots.
pub(super) fn state_index(d: &cadcraft_doc::Drawing, name: &str) -> Option<usize> {
d.layer_states.iter().position(|st| st.name == name).or_else(|| d.layer_states.iter().position(|st| st.name.eq_ignore_ascii_case(name)))
}
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 = state_index(d, name).and_then(|i| d.layer_states.get(i)).cloned().ok_or_else(|| bad("layerstate.restore", "no such layer state"))?;
restore_state(d, &st);
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()
}
/// Restore a saved layer state as AutoCAD 2024 does (measured): first the current layer it
/// names, when the drawing has it and the restore doesn't leave it frozen, then on each drawing
/// layer the state names (without regard to case) the properties its mask covers. The current
/// layer is never frozen; other properties (descriptions, names) stay as they are.
pub(crate) fn restore_state(d: &mut cadcraft_doc::Drawing, st: &cadcraft_doc::LayerState) {
use cadcraft_doc::LayerState as S;
// A frozen layer only thaws with Frozen in the mask and an entry of its own: without one
// AutoCAD 2024 keeps the current layer (measured).
let thaws = |l: &Layer| st.mask & S::FROZEN != 0 && st.layers.iter().any(|saved| saved.name.eq_ignore_ascii_case(&l.name));
if let Some(l) = d.layer(&st.current).filter(|l| !l.frozen || thaws(l)) {
let name = l.name.clone();
d.header.set_str("CLAYER", &name);
}
let current = d.header.str("CLAYER", "0");
let index = layer_index(d);
let has = |bit: u32| st.mask & bit != 0;
for saved in &st.layers {
let Some(l) = index.get(&saved.name.to_ascii_lowercase()).and_then(|&i| d.layers.get_mut(i)) else { continue };
if has(S::ON) {
l.on = saved.on;
}
if has(S::FROZEN) {
l.frozen = saved.frozen && !l.name.eq_ignore_ascii_case(&current);
}
if has(S::LOCKED) {
l.locked = saved.locked;
}
if has(S::PLOT) {
l.plot = saved.plot;
}
if has(S::VP_FREEZE_NEW) {
l.vp_freeze_new = saved.vp_freeze_new;
}
if has(S::COLOR) {
l.color = saved.color;
}
if has(S::LINETYPE) {
l.linetype.clone_from(&saved.linetype);
}
if has(S::LINEWEIGHT) {
l.lineweight = saved.lineweight;
}
if has(S::PLOT_STYLE) {
l.plot_style.clone_from(&saved.plot_style);
}
if has(S::TRANSPARENCY) {
l.transparency = saved.transparency;
}
}
}
/// 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 index = layer_index(d);
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;
@@ -512,16 +432,6 @@ pub(crate) fn restore_layers(d: &mut cadcraft_doc::Drawing, saved: Vec<Layer>) {
}
}
/// The drawing's layers by lower-case name: the first of names that differ only in case, as
/// `Drawing::layer_mut` finds it.
fn layer_index(d: &cadcraft_doc::Drawing) -> std::collections::HashMap<String, usize> {
let mut index = std::collections::HashMap::with_capacity(d.layers.len());
for (i, l) in d.layers.iter().enumerate() {
index.entry(l.name.to_ascii_lowercase()).or_insert(i);
}
index
}
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();
@@ -536,8 +446,10 @@ fn run_state_list(s: &mut Session, _p: &Value) -> Result<Value> {
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()?;
let i = state_index(d, name).ok_or_else(|| bad("layerstate.delete", "no such layer state"))?;
d.layer_states.remove(i);
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()
}
@@ -548,12 +460,10 @@ fn run_state_rename(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("layerstate.rename", "invalid name"));
}
let d = s.doc_mut()?;
// A name in another case counts, the state's own too (AutoCAD 2024 refuses `S1` to `s1`,
// measured).
if d.layer_states.iter().any(|st| st.name.eq_ignore_ascii_case(&to)) {
if d.layer_states.iter().any(|st| st.name == to) {
return Err(bad("layerstate.rename", format!("layer state `{to}` already exists")));
}
let st = state_index(d, from).and_then(|i| d.layer_states.get_mut(i)).ok_or_else(|| bad("layerstate.rename", "no such layer state"))?;
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()
}
@@ -606,146 +516,6 @@ mod tests {
assert!(used.contains(&true) && used.contains(&false));
}
/// Restoring follows AutoCAD 2024 (measured with -LAYER stAte and states written into a DXF):
/// the current layer first, then only the properties the mask covers; the current layer stays
/// thawed; a current layer that is empty or gone leaves the current layer as it is.
#[test]
fn layer_state_restore_follows_the_mask_and_current_layer() {
use cadcraft_color::Color;
use cadcraft_doc::LayerState;
let mut s = Session::new();
s.execute("layer.new", &json!({ "name": "A", "color": 1, "current": true })).unwrap();
s.execute("layer.new", &json!({ "name": "B" })).unwrap();
s.execute("layerstate.save", &json!({ "name": "all" })).unwrap();
let saved = s.doc().unwrap().layer_states[0].clone();
assert_eq!((saved.mask, saved.current.as_str()), (LayerState::ALL, "A"));
// Only On: A's colour stays green, B comes back on (AutoCAD's S7, mask 513).
let d = s.doc_mut().unwrap();
d.layer_states.push(LayerState { name: "on".into(), mask: LayerState::ON | 512, ..saved.clone() });
s.execute("layer.set", &json!({ "name": "A", "color": 3 })).unwrap();
s.execute("layer.set", &json!({ "name": "B", "on": false, "locked": true })).unwrap();
s.execute("layer.current", &json!({ "name": "B" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "on" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
let (a, b) = (d.layer("A").unwrap(), d.layer("B").unwrap());
assert_eq!((a.color, b.on, b.locked), (Color::Index(3), true, true));
// Every property.
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
let d = s.doc().unwrap();
assert_eq!((d.layer("A").unwrap().color, d.layer("B").unwrap().locked), (Color::Index(1), false));
// A state that freezes B with no current layer of its own (or one that is gone), restored
// with B current: B stays current and thawed; A is turned off.
for current in ["", "NOSUCH"] {
let mut frozen = s.doc().unwrap().layers.clone();
for l in &mut frozen {
l.frozen = l.name == "B";
l.on = l.name != "A";
}
s.doc_mut().unwrap().layer_states.push(LayerState::new(format!("f{current}"), frozen.clone(), current));
s.execute("layer.current", &json!({ "name": "B" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": format!("f{current}") })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "B", "{current:?}");
assert!(!d.layer("B").unwrap().frozen && !d.layer("A").unwrap().on, "{current:?}");
// Naming A current, it becomes current and B freezes.
s.doc_mut().unwrap().layer_states.push(LayerState::new("fA", frozen, "A"));
s.execute("layerstate.restore", &json!({ "name": "fA" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
assert!(d.layer("B").unwrap().frozen);
s.doc_mut().unwrap().layer_states.retain(|st| st.name != "fA");
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
}
// A current layer the state's mask leaves frozen doesn't become current (AutoCAD's S9: On
// only, current B; restored with A current and B frozen).
let mut on_only = s.doc().unwrap().layer_states[0].clone();
(on_only.name, on_only.mask, on_only.current) = ("S9".into(), LayerState::ON | 512, "B".into());
s.doc_mut().unwrap().layer_states.push(on_only);
s.execute("layer.current", &json!({ "name": "A" })).unwrap();
s.execute("layer.set", &json!({ "name": "B", "frozen": true })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "S9" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
assert!(d.layer("B").unwrap().frozen);
// With Frozen in the mask B is thawed and made current.
let mut thaw = s.doc().unwrap().layer_states[0].clone();
(thaw.name, thaw.current) = ("thaw".into(), "B".into());
s.doc_mut().unwrap().layer_states.push(thaw);
s.execute("layerstate.restore", &json!({ "name": "thaw" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "B");
assert!(!d.layer("B").unwrap().frozen);
// Frozen in the mask, but no entry for B (a state written elsewhere): nothing would thaw
// B, so A stays current and B frozen (AutoCAD 2024, measured).
let mut no_entry = s.doc().unwrap().layer_states[0].clone();
(no_entry.name, no_entry.current) = ("no entry".into(), "B".into());
no_entry.layers.retain(|l| l.name != "B");
s.doc_mut().unwrap().layer_states.push(no_entry);
s.execute("layer.current", &json!({ "name": "A" })).unwrap();
s.execute("layer.set", &json!({ "name": "B", "frozen": true })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "no entry" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "A");
assert!(d.layer("B").unwrap().frozen);
// An entry spelled in another case is B's (layer names ignore case, as the restore of the
// properties does): B is thawed and made current.
let mut other_case = s.doc().unwrap().layer_states[0].clone();
(other_case.name, other_case.current) = ("other case".into(), "B".into());
for l in other_case.layers.iter_mut().filter(|l| l.name == "B") {
l.name = "b".into();
}
s.doc_mut().unwrap().layer_states.push(other_case);
s.execute("layerstate.restore", &json!({ "name": "other case" })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.header.str("CLAYER", ""), "B");
assert!(!d.layer("B").unwrap().frozen);
// What a state doesn't hold stays: the description.
s.execute("layer.set", &json!({ "name": "A", "description": "kept" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "all" })).unwrap();
assert_eq!(s.doc().unwrap().layer("A").unwrap().description, "kept");
}
/// Plotting, freezing in new viewports, linetype, lineweight, plot style and transparency each
/// come back under their own mask bit only: a state of one bit restores that property and
/// leaves the other five as they are.
#[test]
fn layer_state_restores_each_property_under_its_own_bit_only() {
use cadcraft_doc::{Drawing, LayerState as S, Lineweight};
let mut s = Session::new();
s.execute("layer.new", &json!({ "name": "A" })).unwrap();
s.execute("layerstate.save", &json!({ "name": "all" })).unwrap();
let saved = s.doc().unwrap().layer_states[0].clone();
let props = |d: &Drawing| {
let l = d.layer("A").unwrap();
(l.plot, l.vp_freeze_new, l.linetype.clone(), l.lineweight, l.plot_style.clone(), l.transparency)
};
let change = |d: &mut Drawing| {
let l = d.layer_mut("A").unwrap();
(l.plot, l.vp_freeze_new, l.linetype, l.lineweight, l.plot_style, l.transparency) =
(false, true, "DASHED".into(), Lineweight::from_dxf(50), "Thick".into(), 40);
};
let before = props(s.doc().unwrap());
change(s.doc_mut().unwrap());
let after = props(s.doc().unwrap());
for bit in [S::PLOT, S::VP_FREEZE_NEW, S::LINETYPE, S::LINEWEIGHT, S::PLOT_STYLE, S::TRANSPARENCY] {
let name = format!("b{bit}");
s.doc_mut().unwrap().layer_states.push(S { name: name.clone(), mask: bit | 512, ..saved.clone() });
change(s.doc_mut().unwrap());
s.execute("layerstate.restore", &json!({ "name": name })).unwrap();
let mut want = after.clone();
match bit {
S::PLOT => want.0 = before.0,
S::VP_FREEZE_NEW => want.1 = before.1,
S::LINETYPE => want.2.clone_from(&before.2),
S::LINEWEIGHT => want.3 = before.3,
S::PLOT_STYLE => want.4.clone_from(&before.4),
_ => want.5 = before.5,
}
assert_eq!(props(s.doc().unwrap()), want, "mask {bit}");
}
}
#[test]
fn rejected_layer_set_changes_nothing() {
let mut s = Session::new();
+7 -20
View File
@@ -8,7 +8,6 @@ use serde_json::{Value, json};
use super::super::find_command;
use super::super::qselect::wildcard;
use super::state_prompts;
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
const OPTIONS: &[&str] = &[
@@ -35,9 +34,9 @@ const OPTIONS: &[&str] = &[
];
/// Keyword-only: spaces separate inputs.
pub(super) const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
/// A name or value: Space ends the input, as it does in AutoCAD scripts.
pub(super) const NAME: Accept = Accept { number: true, ..Accept::TEXT };
const NAME: Accept = Accept { number: true, ..Accept::TEXT };
/// A per-layer change applied to a list of layer names.
#[derive(Clone, Debug)]
@@ -112,8 +111,6 @@ enum Stage {
Layers(Change),
/// Turning the current layer off asks first.
ConfirmOff(Vec<String>),
/// stAte and its options.
State(state_prompts::Stage),
}
#[derive(Default)]
@@ -126,19 +123,19 @@ fn current_layer(s: &Session) -> String {
}
/// Run a layer command's body directly: the running command records the single undo step.
pub(super) fn call(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
fn call(s: &mut Session, id: &str, p: &Value) -> Result<Value> {
let spec = find_command(id).ok_or_else(|| EngineError::UnknownCommand(id.into()))?;
(spec.run)(s, p)
}
pub(super) fn message(e: &EngineError) -> String {
fn message(e: &EngineError) -> String {
match e {
EngineError::BadParams { msg, .. } => msg.clone(),
other => other.to_string(),
}
}
pub(super) fn retry(msg: impl Into<String>) -> EngineError {
fn retry(msg: impl Into<String>) -> EngineError {
EngineError::Other(msg.into())
}
@@ -191,9 +188,8 @@ impl LayerM {
"LOck" => Stage::Layers(Change::Lock),
"Unlock" => Stage::Layers(Change::Unlock),
"Description" => Stage::Description,
"stAte" => Stage::State(state_prompts::Stage::Option),
other => {
// MATerial, rEconcile: report and stay at the option prompt.
// MATerial, stAte, rEconcile: report and stay at the option prompt.
s.echo(format!("-LAYER {other} is not available yet."));
Stage::Option
}
@@ -266,7 +262,7 @@ impl LayerM {
Ok(Step::Continue)
};
match stage {
Stage::Option | Stage::State(_) => Ok(Step::Continue),
Stage::Option => Ok(Step::Continue),
Stage::List => {
self.list(s, text.as_deref().unwrap_or("*"));
Ok(Step::Continue)
@@ -438,18 +434,9 @@ impl Interactive for LayerM {
if enter_is_current { p.default(cur) } else { p }
}
Stage::ConfirmOff(_) => Prompt::new(format!("Really want layer \"{cur}\" (the CURRENT layer) off?"), KW).kw(&["Yes", "No"]).default("N"),
Stage::State(st) => st.prompt(),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if let Stage::State(st) = &mut self.stage
&& !matches!(i, Input::Cancel)
{
if !st.input(s, &i)? {
self.stage = Stage::Option;
}
return Ok(Step::Continue);
}
match (&self.stage, &i) {
(_, Input::Cancel) => Ok(Step::Cancel),
(Stage::Option, Input::Enter) => Ok(Step::Done),
@@ -1,256 +0,0 @@
//! -LAYER stAte: save, restore, edit, rename, delete and list the drawing's layer states, with
//! AutoCAD 2024's prompts and messages (measured). Save, Restore, Name and Delete run the
//! `layerstate.*` commands; Edit changes the state's mask in place.
use cadcraft_doc::LayerState as LS;
use serde_json::{Value, json};
use super::prompts::{KW, NAME, call, message, retry};
use super::{state_index, valid_name};
use crate::{Input, Prompt, Result, Session};
/// The options after stAte. Import and EXport (layer state files) are not available yet.
const OPTIONS: &[&str] = &["?", "Save", "Restore", "Edit", "Name", "Delete", "Import", "EXport"];
/// "Enter states to change": each keyword, the name AutoCAD 2024 lists it by and its mask bit, in
/// AutoCAD's order.
const TOGGLES: [(&str, &str, u32); 10] = [
("On", "On", LS::ON),
("Frozen", "Frozen", LS::FROZEN),
("Lock", "Lock", LS::LOCKED),
("Plot", "Plot", LS::PLOT),
("Newvpfreeze", "Newvpfreeze", LS::VP_FREEZE_NEW),
("Color", "Color", LS::COLOR),
("lineType", "lineType", LS::LINETYPE),
("lineWeight", "lineWeight", LS::LINEWEIGHT),
("TRansparency", "Transparency", LS::TRANSPARENCY),
("plotStyle", "plotStyle", LS::PLOT_STYLE),
];
/// The options that ask for a saved state's name.
#[derive(Clone, Copy, Debug)]
pub(super) enum Pick {
Restore,
Edit,
Name,
Delete,
}
impl Pick {
fn verb(self) -> &'static str {
match self {
Pick::Restore => "restore",
Pick::Edit => "edit",
Pick::Name => "rename",
Pick::Delete => "delete",
}
}
}
#[derive(Clone, Debug, Default)]
pub(super) enum Stage {
#[default]
Option,
/// Save: the new state's name.
SaveName,
/// Restore, Edit, Name or Delete: the saved state's name.
Pick(Pick),
/// Name: the new name of the state called so.
RenameTo(String),
/// "Enter states to change" for the state `name`: one Save makes on Enter, or one Edit
/// changes (`edit`).
Toggles { name: String, mask: u32, edit: bool },
}
impl Stage {
pub(super) fn prompt(&self) -> Prompt {
match self {
Stage::Option => Prompt::new("Enter an option", KW).kw(OPTIONS),
Stage::SaveName | Stage::RenameTo(_) => Prompt::new("Enter new layer state name", NAME),
Stage::Pick(p) => Prompt::new(format!("Enter name of layer state to {}", p.verb()), NAME).kw(&["?"]),
Stage::Toggles { .. } => Prompt::new("Enter states to change", KW).kw(&TOGGLES.map(|t| t.0)),
}
}
/// One input. `Ok(false)`: back to -LAYER's options. An invalid input leaves the stage as it
/// is, so the prompt is asked again.
pub(super) fn input(&mut self, s: &mut Session, i: &Input) -> Result<bool> {
let text = match i {
Input::Text(t) | Input::Keyword(t) => Some(t.trim().to_string()).filter(|t| !t.is_empty()),
_ => None,
};
let next = match std::mem::take(self) {
Stage::Option => match i {
Input::Enter => return Ok(false),
Input::Keyword(k) => option(s, k),
_ => return Err(retry("Invalid option keyword.")),
},
Stage::SaveName => match text {
None => Stage::Option,
Some(n) => save_name(s, n),
},
Stage::Pick(p) => match (i, text) {
(Input::Keyword(k), _) if k == "?" => {
list(s);
Stage::Pick(p)
}
(_, None) => Stage::Option,
(_, Some(n)) => pick(s, p, &n),
},
Stage::RenameTo(from) => {
if let Some(to) = text {
rename(s, &from, &to);
}
Stage::Option
}
Stage::Toggles { name, mut mask, edit } => match i {
Input::Keyword(k) => {
if let Some(&(_, _, bit)) = TOGGLES.iter().find(|t| t.0 == k) {
mask ^= bit;
}
show(s, mask);
Stage::Toggles { name, mask, edit }
}
Input::Enter => {
finish(s, &name, mask, edit);
Stage::Option
}
_ => {
*self = Stage::Toggles { name, mask, edit };
return Err(retry("Invalid option keyword."));
}
},
};
*self = next;
Ok(true)
}
}
fn option(s: &mut Session, k: &str) -> Stage {
match k {
"?" => {
list(s);
Stage::Option
}
"Save" => Stage::SaveName,
"Restore" => Stage::Pick(Pick::Restore),
"Edit" => Stage::Pick(Pick::Edit),
"Name" => Stage::Pick(Pick::Name),
"Delete" => Stage::Pick(Pick::Delete),
other => {
s.echo(format!("-LAYER stAte {other} is not available yet."));
Stage::Option
}
}
}
/// Whether a saved state has the name `n` in any case.
fn taken(s: &Session, n: &str) -> bool {
s.doc().is_ok_and(|d| d.layer_states.iter().any(|st| st.name.eq_ignore_ascii_case(n)))
}
/// Save's name: refused (asked again) when it has a character AutoCAD 2024 refuses (the layer
/// name ones, measured one by one), is longer than 255 characters (measured 256), or is a saved
/// state's name in any case (measured `s1` after `S1`).
fn save_name(s: &mut Session, n: String) -> Stage {
if !valid_name(&n) {
s.echo(format!("\"{n}\" is an invalid layer state name."));
return Stage::SaveName;
}
if taken(s, &n) {
s.echo(format!("Layer state \"{n}\" already exists."));
return Stage::SaveName;
}
let mask = s.settings.layer_state_mask;
show(s, mask);
Stage::Toggles { name: n, mask, edit: false }
}
fn pick(s: &mut Session, p: Pick, n: &str) -> Stage {
let found = s.doc().ok().and_then(|d| state_index(d, n).and_then(|i| d.layer_states.get(i)).map(|st| (st.name.clone(), st.mask)));
let Some((name, mask)) = found else {
s.echo("Unknown layer state name.");
return Stage::Pick(p);
};
match p {
Pick::Restore => {
run(s, "layerstate.restore", &json!({ "name": name }));
Stage::Option
}
Pick::Delete => {
run(s, "layerstate.delete", &json!({ "name": name }));
Stage::Option
}
Pick::Edit => {
show(s, mask);
Stage::Toggles { name, mask, edit: true }
}
Pick::Name => Stage::RenameTo(name),
}
}
/// Name's new name. A name some state has in any case, the state's own too, is refused with
/// AutoCAD 2024's two lines (measured `S2` onto `S2`, `S1` onto `s1`). A name with a character
/// AutoCAD refuses leaves the state as it is with no message, as AutoCAD does (measured `a,b`,
/// `a<b`); AutoCAD renames to a name starting with "*" as an anonymous `*A1`, and CADCraft leaves
/// that state as it is too.
fn rename(s: &mut Session, from: &str, to: &str) {
if taken(s, to) {
s.echo("Layer state could not be renamed.");
s.echo(format!("{to} already exists."));
} else if valid_name(to) {
run(s, "layerstate.rename", &json!({ "from": from, "to": to }));
}
}
/// Enter at "Enter states to change": Save makes the state with this mask and keeps the toggles
/// for the next Save; Edit sets the state's mask and keeps the bits no toggle reaches (AutoCAD's
/// 65536 after a restore). Edit leaves the next Save's toggles alone (measured).
fn finish(s: &mut Session, name: &str, mask: u32, edit: bool) {
if !edit {
if run(s, "layerstate.save", &json!({ "name": name, "mask": mask & LS::ALL })) {
s.settings.layer_state_mask = mask & LS::ALL;
}
return;
}
// Only a changed mask touches the drawing.
let Ok(d) = s.doc() else { return };
let Some(i) = state_index(d, name).filter(|&i| d.layer_states.get(i).is_some_and(|st| st.mask != mask)) else { return };
if let Ok(d) = s.doc_mut()
&& let Some(st) = d.layer_states.get_mut(i)
{
st.mask = mask;
}
}
/// Run a `layerstate.*` command, reporting a refusal; `true` when it ran.
fn run(s: &mut Session, id: &str, p: &Value) -> bool {
match call(s, id, p) {
Ok(_) => true,
Err(e) => {
s.echo(message(&e));
false
}
}
}
/// The toggles as AutoCAD 2024 lists them before "Enter states to change".
fn show(s: &mut Session, mask: u32) {
s.echo("States");
for (_, label, bit) in TOGGLES {
s.echo(format!("{label:<20}{}", if mask & bit != 0 { "Yes" } else { "No" }));
}
}
/// `?`: every saved state by name without regard to case, as AutoCAD 2024 lists them (measured:
/// `S2`, `b`, `S1` saved in that order list as `b`, `S1`, `S2`; a name starting with "*", its
/// `*A1`, is listed too).
fn list(s: &mut Session) {
let mut names: Vec<String> = s.doc().map(|d| d.layer_states.iter().map(|st| st.name.clone()).collect()).unwrap_or_default();
names.sort_by_cached_key(|n| n.to_ascii_lowercase());
s.echo("Layer state");
s.echo("-".repeat(29));
for n in names {
s.echo(n);
}
}
+20 -7
View File
@@ -26,7 +26,7 @@ mod stretch;
mod transform;
mod trim;
use break_join::{BreakM, run_break, run_breakat, run_join};
use break_join::{BreakAtPointM, BreakM, run_break, run_breakat, run_join};
use explode::run_explode;
pub(crate) use explode::{explode_kind, explode_with};
use fillet::{FilletM, run_chamfer, run_fillet};
@@ -37,7 +37,7 @@ use select_then::{DisplaceM, Op, SelectThen};
use stretch::{StretchM, run_stretch};
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{Edges, extend, trim};
pub(crate) use trim::{CUT_ONCE, Edges, extend, json_pick_error, trim};
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -85,14 +85,24 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("trim", "Trim", trimextend::run_trim)
.menu(&["Modify", "Trim"])
.alias(&["tr"])
.params(
"{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"} → {handles: the object (kept, reshaped) then the new pieces; none when it was erased} (pick) | {trimmed} (fence, crossing)",
)
.params(concat!(
"{handle, pick: [x,y]} | {fence: [[x,y],...]} | {crossing: [[x,y],[x,y]]}; edges?: [hex] (default: every object; a polyline that is one of them, or every object in Standard mode, also cuts itself at its vertices and crossings), edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\" ",
"→ {handles: the object (kept, reshaped) then the new pieces; none when it was erased} (pick) | {trimmed} (fence, crossing). ",
"For handle+pick: handle is the object to trim; pick selects the portion of that object to remove ",
"(normally a point on it, away from a cutting intersection); edges are the cutting edges. The JSON default is standard mode."
))
.interactive(|_| Ok(Box::new(TrimM::new(false)))),
CommandSpec::new("extend", "Extend", trimextend::run_extend)
.menu(&["Modify", "Extend"])
.alias(&["ex"])
.params("{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\"}")
.params(concat!(
"{handle, pick: [x,y]} | {fence: [[x,y],...]} | {crossing: [[x,y],[x,y]]}; ",
"edges?: [hex], edgeMode?: \"extend\"|\"none\". ",
"For handle+pick: handle is the object to extend; pick points toward the boundary to extend to ",
"(normally a point on that boundary), selecting the nearer end of the object ",
"(of an open polyline, the end on the pick's side of its middle parameter); ",
"edges are the boundary edges, and the nearest forward intersection is used."
))
.interactive(|_| Ok(Box::new(TrimM::new(true)))),
CommandSpec::new("fillet", "Fillet", run_fillet)
.menu(&["Modify", "Fillet"])
@@ -114,7 +124,10 @@ pub fn specs() -> Vec<CommandSpec> {
.alias(&["br"])
.params("{handle, p1, p2} → {handles: the object (kept, reshaped) then the new pieces; none when nothing is left}")
.interactive(|_| Ok(Box::new(BreakM::default()))),
CommandSpec::new("breakatpoint", "Break At Point", run_breakat).menu(&["Modify", "Break At Point"]).params("{handle, at} → {handles: the object (kept, reshaped) then the new piece}"),
CommandSpec::new("breakatpoint", "Break At Point", run_breakat)
.menu(&["Modify", "Break At Point"])
.params("{handle, at} → {handles: the object (kept, reshaped) then the new piece}")
.interactive(|_| Ok(Box::new(BreakAtPointM::default()))),
CommandSpec::new("join", "Join", run_join)
.menu(&["Modify", "Join"])
.alias(&["j"])
+95 -34
View File
@@ -4,16 +4,6 @@ use super::{
Value, Vec2, arc, bad, json, lwpoly, norm_angle, point_param, point_req, targets,
};
/// Gives a rebuilt arc piece its source centre Z, or a rebuilt polyline piece its source elevation.
fn with_z(mut k: EntityKind, z: f64) -> EntityKind {
match &mut k {
EntityKind::Arc(a) => a.center.z = z,
EntityKind::LwPolyline(p) => p.elevation = z,
_ => {}
}
k
}
/// Break `h` between two points (or at one point when p1 == p2).
pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Result<Vec<Handle>> {
if crate::cmd::curves::is_locked(s, h) {
@@ -39,12 +29,12 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re
}
EntityKind::Circle(c) => {
if p1.near(p2, 1e-12) {
return Err(EngineError::Other("Arc cannot be full 360 degrees.".into()));
return Err(EngineError::Other("Arc cannot be full 360 degrees".into()));
}
let a1 = c.center.xy().angle_to(p1);
let a2 = c.center.xy().angle_to(p2);
// AutoCAD removes the CCW portion from the first to the second point.
vec![with_z(arc(&Arc::new(c.center.xy(), c.radius, a2, a1)), c.center.z)]
vec![arc(&Arc::new(c.center.xy(), c.radius, a2, a1))]
}
EntityKind::Arc(a) => {
let ga = Arc::new(a.center.xy(), a.radius, a.start, a.end);
@@ -55,10 +45,10 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re
}
let mut v = Vec::new();
if t1 > 1e-12 {
v.push(with_z(arc(&Arc::new(ga.center, ga.radius, ga.start, ga.start + t1)), a.center.z));
v.push(arc(&Arc::new(ga.center, ga.radius, ga.start, ga.start + t1)));
}
if t2 < ga.sweep() - 1e-12 {
v.push(with_z(arc(&Arc::new(ga.center, ga.radius, ga.start + t2, ga.end)), a.center.z));
v.push(arc(&Arc::new(ga.center, ga.radius, ga.start + t2, ga.end)));
}
v
}
@@ -81,24 +71,32 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re
};
let (mut t1, mut t2) = (lp(p1), lp(p2));
if p.closed {
if (t1 - t2).abs() < 1e-9 {
return Err(EngineError::Other("Cannot break a closed polyline at a single point.".into()));
let (lo, hi) = if t1 <= t2 { (t1, t2) } else { (t2, t1) };
let tol = 1e-9 * (1.0 + total);
if hi - lo < tol {
// One point: the outline opens at its start vertex and splits at the point;
// at the start vertex itself it stays whole and closed.
if lo < tol || lo > total - tol {
return Ok(vec![h]);
}
vec![lwpoly(sub_polyline(&segs, 0.0, lo), false), lwpoly(sub_polyline(&segs, lo, total), false)]
} else {
// The stretch between the points that doesn't run through the start vertex
// goes, whichever point came first; what is left runs from the later point
// round through the start vertex to the earlier one.
let doubled: Vec<Segment> = segs.iter().chain(segs.iter()).copied().collect();
vec![lwpoly(sub_polyline(&doubled, hi, lo + total), false)]
}
// Like a circle: the stretch from the first point to the second, along the
// vertices, goes; what is left runs from the second point round to the first.
let doubled: Vec<Segment> = segs.iter().chain(segs.iter()).copied().collect();
let end = if t1 > t2 { t1 } else { t1 + total };
vec![with_z(lwpoly(sub_polyline(&doubled, t2, end), false), p.elevation)]
} else {
if t1 > t2 {
std::mem::swap(&mut t1, &mut t2);
}
let mut v = Vec::new();
if t1 > 1e-12 {
v.push(with_z(lwpoly(sub_polyline(&segs, 0.0, t1), false), p.elevation));
v.push(lwpoly(sub_polyline(&segs, 0.0, t1), false));
}
if t2 < total - 1e-12 {
v.push(with_z(lwpoly(sub_polyline(&segs, t2, total), false), p.elevation));
v.push(lwpoly(sub_polyline(&segs, t2, total), false));
}
v
}
@@ -215,6 +213,41 @@ pub(super) fn run_join(s: &mut Session, p: &Value) -> Result<Value> {
Ok(json!({ "handle": r.map(|h| h.hex()) }))
}
/// The object picked at `p` for BREAK and BREAKATPOINT ("*Invalid selection*" when there is none).
/// One on a locked layer is refused there, and the command asks for an object again, as AutoCAD
/// 2024 does; the pick doesn't fall through to an object under it.
fn pick_to_break(s: &mut Session, p: Vec2) -> Result<Option<Handle>> {
let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5;
let space = s.space();
match s.pick_object(&space, p, ap)? {
Some(h) if crate::cmd::curves::is_locked(s, h) => {
s.echo("The object is on a locked layer.");
Ok(None)
}
Some(h) => {
s.set_selection(vec![h]);
Ok(Some(h))
}
None => {
s.echo("*Invalid selection*");
Ok(None)
}
}
}
/// Break `h` from `p1` to `p2` and end the command. As in AutoCAD 2024, a break that can't be made
/// (a whole circle at one point: "Arc cannot be full 360 degrees") is reported and ends the
/// command too, leaving the object as it was.
fn break_and_end(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Result<Step> {
match break_entity(s, h, p1, p2) {
Ok(_) => {}
Err(EngineError::Other(m)) => s.echo(m),
Err(e) => return Err(e),
}
s.set_selection(Vec::new());
Ok(Step::Done)
}
#[derive(Default)]
pub(super) struct BreakM {
obj: Option<(Handle, Vec2)>,
@@ -236,14 +269,8 @@ impl Interactive for BreakM {
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match (self.obj, i) {
(None, Input::Point(p)) => {
let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5;
let space = s.space();
match s.pick_object(&space, p, ap)? {
Some(h) => {
self.obj = Some((h, p));
s.set_selection(vec![h]);
}
None => s.echo("*Invalid selection*"),
if let Some(h) = pick_to_break(s, p)? {
self.obj = Some((h, p));
}
Ok(Step::Continue)
}
@@ -256,12 +283,46 @@ impl Interactive for BreakM {
self.first_point = false;
Ok(Step::Continue)
}
(Some((h, p1)), Input::Point(p2)) => {
break_entity(s, h, p1, p2)?;
(Some((h, p1)), Input::Point(p2)) => break_and_end(s, h, p1, p2),
(Some(_), Input::Enter) => {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(_, Input::Enter) => Ok(Step::Done),
(None, Input::Enter) => Ok(Step::Done),
_ => Ok(Step::Continue),
}
}
}
/// BREAKATPOINT at the command line, with AutoCAD 2024's prompts: "Select object:", then "Specify
/// break point:"; the object is split there with no gap (the point projects onto it).
#[derive(Default)]
pub(super) struct BreakAtPointM {
obj: Option<Handle>,
}
impl Interactive for BreakAtPointM {
fn name(&self) -> &'static str {
"BREAKATPOINT"
}
fn prompt(&self, _s: &Session) -> Prompt {
match self.obj {
None => Prompt::new("Select object", Accept::POINT),
Some(_) => Prompt::new("Specify break point", Accept::POINT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match (self.obj, i) {
(None, Input::Point(p)) => {
self.obj = pick_to_break(s, p)?;
Ok(Step::Continue)
}
(Some(h), Input::Point(p)) => break_and_end(s, h, p, p),
(Some(_), Input::Enter) => {
s.set_selection(Vec::new());
Ok(Step::Done)
}
(None, Input::Enter) => Ok(Step::Done),
_ => Ok(Step::Continue),
}
}
+266 -37
View File
@@ -1,3 +1,5 @@
use cadcraft_geom::Bounds2;
use super::{
Arc, EngineError, Entity, EntityKind, Handle, Line, PolyVertex, Polyline, Prim, Result, Segment, Session, TAU, Vec2, angle_in_sweep, arc,
ccw_sweep, intersect_ext, line, lwpoly, norm_angle,
@@ -91,13 +93,62 @@ fn prim_to_segments(p: &Prim) -> Vec<Segment> {
}
}
/// Explain the generic line failures for JSON handle+pick calls, and a line TRIM picked on its
/// only cuts ([`ON_THE_CUT`]). Other curves retain their own diagnostics: their nearest-parameter
/// rules do not prove that a pick is invalid.
pub(crate) fn json_pick_error(s: &Session, h: Handle, pick: Vec2, edges: Edges, extending: bool, error: EngineError) -> EngineError {
let generic = if extending { "Object does not intersect an edge." } else { "Object does not intersect a cutting edge." };
if !matches!(&error, EngineError::Other(message) if message == generic || (!extending && message == ON_THE_CUT)) {
return error;
}
let Ok(d) = s.doc() else { return error };
let Some(e) = d.entity(h) else { return error };
let EntityKind::Line(l) = &e.kind else { return error };
let Ok(cut) = edge_segments(s, edges, h) else { return error };
let ln = Line::new(l.a.xy(), l.b.xy());
let message = if extending {
// The selected end already failed. Check the opposite end with the same ray and
// forward-intersection rules before attributing the failure to the pick's end choice.
let (fixed, end) = if pick.dist(ln.b) < pick.dist(ln.a) { (ln.b, ln.a) } else { (ln.a, ln.b) };
let dir = (end - fixed).normalized();
let ray = Segment::Line(Line::new(end, end + dir * 1e8));
let opposite_hit = cut.iter().flat_map(|c| intersect_ext(&ray, c, false)).any(|x| (x - end).dot(dir) > 1e-9);
if opposite_hit {
"The `pick` point selects an end with no boundary ahead; choose `pick` toward the boundary to extend to."
} else {
"No usable boundary intersection was found for either end of the object to extend."
}
} else {
let pick_param = ln.param_of(pick).clamp(0.0, 1.0);
let has_cut = cut.iter().flat_map(|c| intersect_ext(&Segment::Line(ln), c, false)).any(|x| {
let t = ln.param_of(x);
t > 1e-9 && t < 1.0 - 1e-9
});
if !has_cut {
"No usable cutting-edge intersection in the interior of the object to trim."
} else if pick_param.is_nan() {
return error;
} else if !ln.at(pick_param).near(pick, 1e-9_f64.max(64.0 * f64::EPSILON * (1.0 + pick.len().max(ln.a.len()).max(ln.b.len())))) {
"The `pick` point is off the line and projects onto a cutting intersection; pick away from that intersection."
} else {
"The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection."
}
};
EngineError::Other(message.into())
}
/// Trim `h` at the piece containing `pick`. Returns the handles that replace it.
/// Trim `h` at the piece containing `pick`. Returns what it became: its pieces, `h` first
/// ([`replace_with_pieces`]).
pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Result<Vec<Handle>> {
if crate::cmd::curves::is_locked(s, h) {
return Err(EngineError::Other("The object is on a locked layer.".into()));
}
let e = s.doc()?.entity(h).map(|e| (**e).clone()).ok_or_else(|| EngineError::Other("no such object".into()))?;
let cut = edge_segments(s, edges, h)?;
// A polyline that is one of the edges (picked, or with every object in either mode) cuts
// itself too.
let itself = edges.only.is_none_or(|o| o.contains(&h));
let pieces: Vec<EntityKind> = match &e.kind {
EntityKind::Line(l) => {
let ln = Line::new(l.a.xy(), l.b.xy());
@@ -109,10 +160,12 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
.collect();
ts.sort_by(f64::total_cmp);
let tp = ln.param_of(pick).clamp(0.0, 1.0);
let found = ts.len();
ts.retain(|t| (t - tp).abs() * ln.len() > ON_CUT);
let lo = ts.iter().copied().filter(|t| *t < tp).fold(0.0, f64::max);
let hi = ts.iter().copied().filter(|t| *t > tp).fold(1.0, f64::min);
if lo == 0.0 && hi == 1.0 {
return Err(EngineError::Other("Object does not intersect a cutting edge.".into()));
return Err(EngineError::Other(if ts.len() < found { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into()));
}
let mut v = Vec::new();
if lo > 0.0 {
@@ -131,11 +184,14 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
let mut ts: Vec<f64> =
cut.iter().flat_map(|c| intersect_ext(&seg, c, false)).map(param).filter(|t| *t > 1e-9 && *t < sweep - 1e-9).collect();
ts.sort_by(f64::total_cmp);
let tp = param(pick).min(sweep);
// A pick off the arc is at the end it is nearer, round the circle.
let tp = crate::cmd::curves::seg_param(&seg, pick) * sweep;
let found = ts.len();
ts.retain(|t| (t - tp).abs() * ga.radius > ON_CUT);
let lo = ts.iter().copied().filter(|t| *t < tp).fold(0.0, f64::max);
let hi = ts.iter().copied().filter(|t| *t > tp).fold(sweep, f64::min);
if lo == 0.0 && hi == sweep {
return Err(EngineError::Other("Object does not intersect a cutting edge.".into()));
return Err(EngineError::Other(if ts.len() < found { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into()));
}
let mut v = Vec::new();
if lo > 0.0 {
@@ -151,10 +207,16 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
let mut angs: Vec<f64> = cut.iter().flat_map(|x| intersect_ext(&full, x, false)).map(|p| c.center.xy().angle_to(p)).collect();
angs.sort_by(f64::total_cmp);
angs.dedup_by(|a, b| (*a - *b).abs() < 1e-9);
if angs.len() < 2 {
return Err(EngineError::Other("Circle must intersect cutting edges at two or more points.".into()));
}
let ap = c.center.xy().angle_to(pick);
let found = angs.len();
angs.retain(|a| {
let d = norm_angle(a - ap);
d.min(TAU - d) * c.radius > ON_CUT
});
if angs.len() < 2 {
let why = if found >= 2 { ON_THE_CUT } else { "Circle must intersect cutting edges at two or more points." };
return Err(EngineError::Other(why.into()));
}
// The removed arc runs between the two intersections around the pick.
let n = angs.len();
let mut keep = None;
@@ -167,7 +229,10 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
}
keep.into_iter().collect()
}
EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick)?,
EntityKind::LwPolyline(p) => match trim_polyline(p, &cut, pick, itself)? {
Some(pieces) => pieces,
None => return Ok(vec![h]),
},
k => crate::cmd::modify2::trim_other(k, &cut, pick)?,
};
replace_with_pieces(s, h, pieces)
@@ -181,19 +246,20 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
/// in its middle keeps its handle on the piece from its start point, the piece to its end point is
/// new; a circle broken or trimmed becomes an arc with the circle's handle.)
///
/// Dimensions attached to the object follow [`crate::assoc::follow_pieces`]. Its parametric
/// constraints are removed: its new shape no longer meets them, and solving them again would move
/// the objects they tie it to.
/// Each piece keeps what the object had beyond its outline ([`inherit`]). Dimensions attached to
/// the object follow [`crate::assoc::follow_pieces`]. Its parametric constraints are removed: its
/// new shape no longer meets them, and solving them again would move the objects they tie it to.
pub(super) fn replace_with_pieces(s: &mut Session, h: Handle, pieces: Vec<EntityKind>) -> Result<Vec<Handle>> {
let d = s.doc_mut()?;
let mut pieces = pieces.into_iter();
let Some(first) = pieces.next() else {
if pieces.is_empty() {
d.remove_entity(h);
return Ok(Vec::new());
};
}
let (Some(space), Some(old)) = (d.space_of(h), d.entity(h).cloned()) else {
return Err(EngineError::Other("no such object".into()));
};
let mut pieces = pieces.into_iter().map(|k| inherit(&old.kind, k));
let Some(first) = pieces.next() else { return Ok(Vec::new()) };
d.modify_entity(h, |e| e.kind = first)?;
let mut out = vec![h];
for kind in pieces {
@@ -213,6 +279,31 @@ pub(super) fn replace_with_pieces(s: &mut Session, h: Handle, pieces: Vec<Entity
Ok(out)
}
/// `piece`, cut from `source`, with what it keeps of it as AutoCAD 2024's BREAK and TRIM leave
/// pieces: a line's Z along it, an arc's (or a circle's) centre Z, and a polyline's elevation,
/// constant width and linetype generation.
fn inherit(source: &EntityKind, mut piece: EntityKind) -> EntityKind {
match (source, &mut piece) {
(EntityKind::Line(s), EntityKind::Line(p)) => {
let ln = Line::new(s.a.xy(), s.b.xy());
if ln.len() > 0.0 {
let z = |t: f64| s.a.z + (s.b.z - s.a.z) * t;
p.a.z = z(ln.param_of(p.a.xy()));
p.b.z = z(ln.param_of(p.b.xy()));
}
}
(EntityKind::Arc(s), EntityKind::Arc(p)) => p.center.z = s.center.z,
(EntityKind::Circle(s), EntityKind::Arc(p)) => p.center.z = s.center.z,
(EntityKind::LwPolyline(s), EntityKind::LwPolyline(p)) => {
p.elevation = s.elevation;
p.const_width = s.const_width;
p.plinegen = s.plinegen;
}
_ => {}
}
piece
}
/// Sub-polyline between length parameters `a` and `b` (open polylines).
pub(super) fn sub_polyline(segs: &[Segment], a: f64, b: f64) -> Vec<PolyVertex> {
let mut out: Vec<PolyVertex> = Vec::new();
@@ -245,15 +336,128 @@ pub(super) fn sub_polyline(segs: &[Segment], a: f64, b: f64) -> Vec<PolyVertex>
out
}
fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2) -> Result<Vec<EntityKind>> {
/// Two line segments of a polyline within this sine of parallel run on as one, straight on or
/// doubling back: the vertex between them doesn't cut it, and they don't cut each other. AutoCAD
/// 2024 cuts at a bend of 1e-8 and not at one of 8e-9, whatever the lengths.
const STRAIGHT: f64 = 1e-8;
/// Upper bounds on one trim's search for where a polyline crosses itself (hostile files): the pairs
/// of segments searched (those the piece picked can reach, times those near them) and the
/// crossings found. Past either the trim is refused, rather than made at some of its cuts.
const MAX_SELF_PAIRS: usize = 1 << 24;
const MAX_SELF_CROSSINGS: usize = 1 << 16;
/// How near a cut a pick is on it, along the object. AutoCAD 2024 trims nothing for a pick that
/// near one of a polyline's own cuts, and passes over a cut by another edge, the trim running on
/// across it, on lines, arcs and circles too. On open polylines from 1e-3 to 1e9 long it was within
/// 5e-7, and 5.1e-7 away trimmed at the cut (around a closed rectangle it reached a little further,
/// to 1e-6; on a line, further still, to 5e-4 on one 10 long).
const ON_CUT: f64 = 5e-7;
/// The refusal when every cut was passed over ([`ON_CUT`]): the object meets an edge, at the pick,
/// so Quick mode leaves it in place rather than erasing it as one no edge crosses.
const ON_THE_CUT: &str = "The pick is on the cut: nothing to trim.";
/// AutoCAD 2024's refusal to trim a closed polyline cut at one point only.
pub(crate) const CUT_ONCE: &str = "Curve must intersect cutting edges at least twice.";
/// Whether segments `a` and `b` of a polyline run on as one ([`STRAIGHT`]).
fn runs_on(a: &Segment, b: &Segment) -> bool {
let (Segment::Line(a), Segment::Line(b)) = (a, b) else { return false };
let (u, v) = (a.b - a.a, b.b - b.a);
u.cross(v).abs() < STRAIGHT * u.len() * v.len()
}
/// Where a polyline that is one of the cutting edges cuts itself around segment `k`, the one
/// picked, as lengths along it: at its vertices (every vertex of a closed one, its start included)
/// but those it runs straight on through ([`runs_on`]), and, on `k` and the segments it runs
/// straight on into, where another of its segments crosses them or a vertex of it (an end
/// included) touches them. The piece picked lies within those segments, so crossings elsewhere
/// don't bound it. AutoCAD 2024 trims a polyline that is one of the cutting edges at these.
fn self_cuts(segs: &[Segment], closed: bool, k: usize) -> Result<Vec<f64>> {
let n = segs.len();
let mut starts = Vec::with_capacity(n);
let mut acc = 0.0;
for s in segs {
starts.push(acc);
acc += s.len();
}
let before = |i: usize| {
if i > 0 {
Some(i - 1)
} else if closed {
n.checked_sub(1)
} else {
None
}
};
let after = |i: usize| {
if i + 1 < n {
Some(i + 1)
} else if closed {
Some(0)
} else {
None
}
};
// Whether the polyline runs straight on through the vertex segment `i` starts at.
let straight = |i: usize| matches!((before(i).and_then(|j| segs.get(j)), segs.get(i)), (Some(a), Some(b)) if runs_on(a, b));
let mut ts: Vec<f64> = (usize::from(!closed)..n).filter(|i| !straight(*i)).filter_map(|i| starts.get(i).copied()).collect();
let mut run = vec![k];
let mut i = k;
while let Some(j) = before(i).filter(|_| straight(i) && run.len() < n) {
run.push(j);
i = j;
}
let mut i = k;
while let Some(j) = after(i).filter(|j| straight(*j) && run.len() < n) {
run.push(j);
i = j;
}
let boxes: Vec<_> = segs.iter().map(Segment::bounds).collect();
let reach = run.iter().filter_map(|i| boxes.get(*i)).fold(Bounds2::EMPTY, |r, b| r.union(b));
let near: Vec<usize> = (0..n).filter(|j| boxes.get(*j).is_some_and(|b| b.intersects(&reach))).collect();
if run.len().saturating_mul(near.len()) > MAX_SELF_PAIRS {
return Err(EngineError::Other("Too many segments to trim the polyline where it crosses itself.".into()));
}
// A crossing, or a vertex of another segment touching this one, cuts it; so does a crossing
// where it runs straight on into the next. Two segments meeting at a vertex cut nothing more.
let cuts = |t: f64, i: usize| (t > 1e-9 && t < 1.0 - 1e-9) || (t <= 1e-9 && straight(i)) || (t >= 1.0 - 1e-9 && after(i).is_some_and(straight));
let vertices = ts.len();
for &i in &run {
let (Some(a), Some(box_a), Some(a0)) = (segs.get(i), boxes.get(i), starts.get(i)) else { continue };
for &j in &near {
let (Some(b), Some(box_b)) = (segs.get(j), boxes.get(j)) else { continue };
if j == i || runs_on(a, b) || !box_a.intersects(box_b) {
continue;
}
for x in intersect_ext(a, b, false) {
let t = param_on(a, x);
if cuts(t, i) {
ts.push(a0 + t * a.len());
if ts.len() - vertices > MAX_SELF_CROSSINGS {
return Err(EngineError::Other("Too many crossings to trim the polyline where it crosses itself.".into()));
}
}
}
}
}
Ok(ts)
}
/// Trim a polyline at the piece containing `pick`, between the cuts by `cut` and, when it is one
/// of the cutting edges (`itself`), by its own ([`self_cuts`]). `None`: the pick is on one of its
/// own cuts ([`ON_CUT`]), which trims nothing.
fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2, itself: bool) -> Result<Option<Vec<EntityKind>>> {
let pl = Polyline { vertices: p.vertices.clone(), closed: p.closed };
let segs = pl.segments();
let total: f64 = segs.iter().map(Segment::len).sum();
let mut ts: Vec<f64> = Vec::new();
let mut acc = 0.0;
let mut tp = 0.0;
// The pick's length along the polyline and the segment it is on.
let (mut tp, mut k) = (0.0, 0);
let mut best = f64::INFINITY;
for s in &segs {
for (i, s) in segs.iter().enumerate() {
let len = s.len();
for x in cut.iter().flat_map(|c| intersect_ext(s, c, false)) {
ts.push(acc + param_on(s, x) * len);
@@ -262,13 +466,34 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2) -> R
if c.dist(pick) < best {
best = c.dist(pick);
tp = acc + param_on(s, c) * len;
k = i;
}
acc += len;
}
ts.retain(|t| *t > 1e-9 && *t < total - 1e-9);
let mut own = if itself { self_cuts(&segs, p.closed, k)? } else { Vec::new() };
// An open polyline's ends cut nothing; a closed one's start vertex cuts it like any other (a
// cut there is at 0 or at its length, which the pieces below take as one).
if !p.closed {
ts.retain(|t| *t > 1e-9 && *t < total - 1e-9);
own.retain(|t| *t > 1e-9 && *t < total - 1e-9);
}
// How far apart two lengths along the polyline are, round its start too when it is closed.
let apart = |s: f64, t: f64| if p.closed { (s - t).abs().min(total - (s - t).abs()) } else { (s - t).abs() };
// A pick on one of its own cuts trims nothing; a cut by another edge there is passed over, and
// the piece runs on across it.
if own.iter().any(|t| apart(*t, tp) <= ON_CUT) {
return Ok(None);
}
let found = ts.len();
ts.retain(|t| apart(*t, tp) > ON_CUT);
let passed = ts.len() < found;
ts.extend(own);
ts.sort_by(f64::total_cmp);
if ts.is_empty() {
return Err(EngineError::Other("Object does not intersect a cutting edge.".into()));
return Err(EngineError::Other(if passed { ON_THE_CUT } else { "Object does not intersect a cutting edge." }.into()));
}
if p.closed && ts.first().is_some_and(|f| ts.iter().all(|t| apart(*f, *t) <= ON_CUT)) {
return Err(EngineError::Other(CUT_ONCE.into()));
}
let lo = ts.iter().copied().filter(|t| *t < tp).fold(f64::NEG_INFINITY, f64::max);
let hi = ts.iter().copied().filter(|t| *t > tp).fold(f64::INFINITY, f64::min);
@@ -283,33 +508,31 @@ fn trim_polyline(p: &cadcraft_doc::LwPolyline, cut: &[Segment], pick: Vec2) -> R
if hi.is_finite() { hi } else { ts.first().copied().unwrap_or(total) + total },
);
let doubled: Vec<Segment> = segs.iter().chain(segs.iter()).copied().collect();
let (a, mut b) = if hi > total { (hi - total, lo) } else { (hi, lo + total) };
// A single cut leaves the whole outline, opened there.
if b <= a + 1e-9 {
b += total;
}
let (a, b) = if hi > total { (hi - total, lo) } else { (hi, lo + total) };
out.push(mk(sub_polyline(&doubled, a, b)));
} else {
// A piece whose ends meet (the polyline touched itself there) is closed, without its
// repeated vertex, as AutoCAD leaves it.
let piece = |mut vs: Vec<PolyVertex>| {
// Within rounding of the coordinates, however far from the origin, and no more.
let meets = vs.len() >= 4
&& matches!((vs.first(), vs.last()), (Some(a), Some(b)) if a.p.near(b.p, 64.0 * f64::EPSILON * (1.0 + a.p.len().max(b.p.len()))));
if meets {
vs.pop();
}
lwpoly(vs, meets)
};
if lo.is_finite() {
out.push(mk(sub_polyline(&segs, 0.0, lo)));
out.push(piece(sub_polyline(&segs, 0.0, lo)));
}
if hi.is_finite() {
out.push(mk(sub_polyline(&segs, hi, total)));
out.push(piece(sub_polyline(&segs, hi, total)));
}
}
Ok(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect())
Ok(Some(out.into_iter().filter(|k| matches!(k, EntityKind::LwPolyline(l) if l.vertices.len() >= 2)).collect()))
}
pub(super) fn param_on(s: &Segment, p: Vec2) -> f64 {
match s {
Segment::Line(l) => l.param_of(p).clamp(0.0, 1.0),
Segment::Arc { arc, ccw } => {
let t = norm_angle(arc.center.angle_to(p) - arc.start) / arc.sweep().max(1e-15);
let t = t.clamp(0.0, 1.0);
if *ccw { t } else { 1.0 - t }
}
}
}
pub(super) use crate::cmd::curves::seg_param as param_on;
/// A polyline arc segment on `ga`'s circle that ends at `end` after turning through `sweep`
/// (signed, positive counterclockwise), run on round the circle to the nearest boundary edge: the
@@ -372,7 +595,13 @@ pub(crate) fn extend(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Re
EntityKind::LwPolyline(p) if !p.closed && p.vertices.len() >= 2 => {
let mut vs = p.vertices.clone();
let n = vs.len();
let from_end = vs.last().is_some_and(|l| pick.dist(l.p) < vs.first().map(|f| pick.dist(f.p)).unwrap_or(f64::INFINITY));
// The pick's parameter: the segment it is nearest, plus how far along it. AutoCAD 2024
// extends the end on that side of the polyline's middle parameter, the last from the
// middle on, not the end nearer the pick. A repeated vertex counts as a segment, so
// these come from the vertices, not `Polyline::segments`, which skips it.
let spans: Vec<_> = vs.windows(2).filter_map(|w| Some((w.first()?.p, w.get(1)?.p, w.first()?.bulge))).collect();
let at = crate::cmd::curves::vertex_param_of(&spans, pick);
let from_end = 2.0 * at >= (n - 1) as f64;
let (i_end, i_prev) = if from_end { (n - 1, n - 2) } else { (0, 1) };
let end = vs.get(i_end).map(|v| v.p).unwrap_or_default();
let prev = vs.get(i_prev).map(|v| v.p).unwrap_or_default();
+2 -2
View File
@@ -101,7 +101,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("rename", "Rename...", run_rename)
.menu(&["Format", "Rename..."])
.alias(&["ren", "-rename"])
.params("{table: layer|linetype|style|dimstyle|block|mleaderstyle|tablestyle|view|ucs|vport, from, to}")
.params("{table: layer|linetype|style|dimstyle|block|mleaderstyle|tablestyle|view|ucs, from, to}")
.interactive(|_| Ok(Box::new(rename::RenameM::default()))),
]
}
@@ -995,7 +995,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
"block" => rename::block(s, &from, &to)?,
"mleaderstyle" | "multileaderstyle" => rename::simple(s, "mleaderstyle", &from, &to)?,
"tablestyle" | "view" | "ucs" | "vport" => rename::simple(s, &table, &from, &to)?,
"tablestyle" | "view" | "ucs" => rename::simple(s, &table, &from, &to)?,
"style" | "textstyle" => {
run_style_rename(s, &json!({ "from": from, "to": to }))?;
}
+16 -81
View File
@@ -93,8 +93,6 @@ pub(super) fn simple(s: &mut Session, table: &str, from: &str, to: &str) -> Resu
"tablestyle" => d.table_styles.iter_mut().map(|t| &mut t.name).collect(),
"view" => d.views.iter_mut().map(|t| &mut t.name).collect(),
"ucs" => d.ucss.iter_mut().map(|t| &mut t.name).collect(),
// A saved viewport configuration, every tile of it; never the one shown (`*Active`).
"vport" => d.vports.iter_mut().filter(|v| !v.is_active()).map(|t| &mut t.name).collect(),
_ => return Err(bad("rename", "unsupported table")),
};
if !to.eq_ignore_ascii_case(from) && names.iter().any(|n| n.eq_ignore_ascii_case(&to)) {
@@ -136,47 +134,35 @@ const TYPES: &[(&str, Option<&str>, &str)] = &[
("Plotstyle", None, "plot style"),
("textStyle", Some("style"), "text style"),
("Tablestyle", Some("tablestyle"), "table style"),
("Ucs", Some("ucs"), "ucs"),
("Ucs", Some("ucs"), "UCS"),
("VIew", Some("view"), "view"),
("VPort", Some("vport"), "viewport configuration"),
("VPort", None, "viewport configuration"),
];
/// The noun in "Cannot find …" and "Invalid … name.": AutoCAD 2024 writes "UCS" there, "ucs" in
/// its prompts and in "A ucs named … already exists." (measured).
fn title(noun: &str) -> &str {
if noun == "ucs" { "UCS" } else { noun }
}
/// Keyword-only: spaces separate inputs.
const KW: Accept = Accept { point: false, number: false, text: false, select: false, enter: true };
/// A name: Space ends the input.
const NAME: Accept = Accept { number: true, ..Accept::TEXT };
fn any_named<'a>(mut names: impl Iterator<Item = &'a String>, name: &str) -> Option<String> {
names.find(|n| n.eq_ignore_ascii_case(name)).cloned()
fn any_named<'a>(mut names: impl Iterator<Item = &'a String>, name: &str) -> bool {
names.any(|n| n.eq_ignore_ascii_case(name))
}
/// The name as the drawing spells it of the `table` entry named `name` (without regard to case).
fn stored(d: &Drawing, table: &str, name: &str) -> Option<String> {
fn exists(d: &Drawing, table: &str, name: &str) -> bool {
match table {
"block" => d.block(name).map(|t| t.name.clone()),
"layer" => d.layer(name).map(|t| t.name.clone()),
"linetype" => d.linetype(name).map(|t| t.name.clone()),
"style" => d.text_style(name).map(|t| t.name.clone()),
"dimstyle" => d.dim_style(name).map(|t| t.name.clone()),
"block" => d.block(name).is_some(),
"layer" => d.layer(name).is_some(),
"linetype" => d.linetype(name).is_some(),
"style" => d.text_style(name).is_some(),
"dimstyle" => d.dim_style(name).is_some(),
"mleaderstyle" => any_named(d.mleader_styles.iter().map(|t| &t.name), name),
"tablestyle" => any_named(d.table_styles.iter().map(|t| &t.name), name),
"view" => any_named(d.views.iter().map(|t| &t.name), name),
"ucs" => any_named(d.ucss.iter().map(|t| &t.name), name),
"vport" => any_named(d.vports.iter().filter(|v| !v.is_active()).map(|t| &t.name), name),
_ => Some(name.to_string()),
_ => true,
}
}
fn exists(d: &Drawing, table: &str, name: &str) -> bool {
stored(d, table, name).is_some()
}
#[derive(Default)]
enum Stage {
#[default]
@@ -213,15 +199,6 @@ impl Interactive for RenameM {
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
// No new name is an invalid one (AutoCAD 2024, measured for layers, blocks, views and
// viewport configurations).
if i == Input::Enter
&& let Stage::New(t, _) = &self.stage
&& let Some((_, Some(_), noun)) = TYPES.get(*t)
{
s.echo(format!("Invalid {} name.", title(noun)));
return Ok(Step::Done);
}
if matches!(i, Input::Cancel | Input::Enter) {
return Ok(if i == Input::Cancel { Step::Cancel } else { Step::Done });
}
@@ -240,41 +217,12 @@ impl Interactive for RenameM {
self.stage = Stage::Old(t);
return Ok(Step::Continue);
};
// AutoCAD 2024 ends -RENAME on an old name it won't rename (measured): "Invalid … name."
// for a viewport configuration or block whose name starts with "*" (*Active,
// *Model_Space, an anonymous block's *U0) and for linetypes ByLayer and ByBlock;
// "Cannot rename …" and "*Invalid*" for layer 0 and linetype Continuous.
let invalid = match *table {
Some("vport" | "block") => name.starts_with('*'),
Some("linetype") => name.eq_ignore_ascii_case("bylayer") || name.eq_ignore_ascii_case("byblock"),
_ => false,
};
if invalid {
s.echo(format!("Invalid {} name.", title(noun)));
return Ok(Step::Done);
if let Some(table) = table
&& !exists(s.doc()?, table, &name)
{
self.stage = Stage::Old(t);
return Err(EngineError::Other(format!("No {noun} named \"{name}\".")));
}
let fixed = match *table {
Some("layer") => name == "0",
Some("linetype") => name.eq_ignore_ascii_case("continuous"),
_ => false,
};
if fixed {
s.echo(format!("Cannot rename {} \"{name}\".", title(noun)));
s.echo("*Invalid*");
return Ok(Step::Done);
}
// The old name as the drawing spells it: a new name in another case than that is a
// rename, even when it is the old name as typed (AutoCAD 2024, measured).
let name = match table {
Some(table) => match stored(s.doc()?, table, &name) {
Some(n) => n,
None => {
s.echo(format!("Cannot find {} \"{name}\".", title(noun)));
return Ok(Step::Done);
}
},
None => name,
};
self.stage = Stage::New(t, name);
Ok(Step::Continue)
}
@@ -287,19 +235,6 @@ impl Interactive for RenameM {
s.echo(format!("Renaming a {noun} is not available yet."));
return Ok(Step::Done);
};
// AutoCAD 2024's messages, each ending the command (measured).
if !valid_name(&name) {
s.echo(format!("Invalid {} name.", title(noun)));
return Ok(Step::Done);
}
if !name.eq_ignore_ascii_case(&old) && exists(s.doc()?, table, &name) {
s.echo(format!("A {noun} named \"{name}\" already exists."));
s.echo("*Invalid*");
return Ok(Step::Done);
}
if name == old {
return Ok(Step::Done);
}
match super::run_rename(s, &json!({ "table": table, "from": old, "to": name })) {
Ok(_) => Ok(Step::Done),
Err(e) => {
+45 -11
View File
@@ -8,8 +8,9 @@ use cadcraft_doc::{Drawing, EntityKind, Handle};
use cadcraft_geom::{Bounds2, Line, Vec2, line_line};
use serde_json::{Value, json};
use super::curves::KW;
use super::helpers::{line, lwpoly, rect_vertices};
use super::modify::{Edges, extend, trim};
use super::modify::{CUT_ONCE, Edges, extend, json_pick_error, trim};
use super::{bad, point_param, points_param};
use crate::{Accept, EngineError, Input, Interactive, Prompt, Result, Session, Step};
@@ -31,8 +32,10 @@ fn proj_mode(s: &Session) -> i64 {
}
/// Whether a trim error says the object meets no cutting edge (a Quick-mode trim then erases it).
/// A closed polyline cut at one point meets one, and is left as it is.
fn misses_edges(e: &EngineError) -> bool {
e.to_string().contains("intersect")
let m = e.to_string();
m.contains("intersect") && m != CUT_ONCE
}
/// Trim or extend `h` at `at`. A Quick-mode (`quick`) trim of an object no cutting edge crosses
@@ -103,7 +106,12 @@ fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, qu
for w in pl.windows(2) {
let (Some(p), Some(q)) = (w.first(), w.get(1)) else { continue };
let seg = Line::new(*p, *q);
let cands = [*p, *q, seg.closest(a)].into_iter().chain(sides.iter().filter_map(|sd| line_line(sd, &seg)));
// Kept `tol` inside the segment: a vertex, where two segments meet, is a cut of a
// polyline that is one of its own edges, and a pick on a cut trims nothing.
let e = (tol / seg.len()).min(0.5);
let cands = [seg.at(e), seg.at(1.0 - e), seg.at(seg.param_of(a).clamp(e, 1.0 - e))]
.into_iter()
.chain(sides.iter().filter_map(|sd| line_line(sd, &seg)));
for c in cands.filter(|c| inside(*c)) {
if best.is_none_or(|b| c.dist(a) < b.dist(a)) {
best = Some(c);
@@ -173,7 +181,6 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result<Value> {
let cmd = if extending { "extend" } else { "trim" };
let only: Option<Vec<Handle>> =
p.get("edges").and_then(Value::as_array).map(|a| a.iter().filter_map(|v| v.as_str().and_then(Handle::parse_hex)).collect());
let edges = Edges { only: only.as_deref(), implied: edge_mode_param(cmd, p)? };
let quick = match p.get("mode") {
None | Some(Value::Null) => false,
Some(v) => match v.as_str().map(|m| m.trim().to_ascii_lowercase()).as_deref() {
@@ -182,6 +189,7 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result<Value> {
_ => return Err(bad(cmd, "`mode` must be \"quick\" or \"standard\"")),
},
};
let edges = Edges { only: only.as_deref(), implied: edge_mode_param(cmd, p)? };
let key = if extending { "extended" } else { "trimmed" };
if p.get("fence").is_some_and(|v| !v.is_null()) {
let pts = points_param(p, "fence")
@@ -197,8 +205,19 @@ fn run(s: &mut Session, p: &Value, extending: bool) -> Result<Value> {
return Ok(json!({ key: n }));
}
let h = super::targets(s, p)?.first().copied().ok_or_else(|| bad(cmd, "`handle` is required"))?;
let pick = point_param(p, "pick").ok_or_else(|| bad(cmd, "`pick` ([x, y]) is required"))?;
let r = apply(s, h, pick, extending, edges, quick)?;
let pick = point_param(p, "pick").ok_or_else(|| {
bad(
cmd,
if extending {
"`pick` ([x, y]) is required: point toward the boundary to extend to, selecting the nearer end"
} else {
"`pick` ([x, y]) is required: select the portion of the object to trim away"
},
)
})?;
// Diagnose only an existing single-pick JSON failure. Successful calls, Quick-mode
// erasure, fence/crossing and the interactive command keep their existing behavior.
let r = apply(s, h, pick, extending, edges, quick).map_err(|e| json_pick_error(s, h, pick, edges, extending, e))?;
if extending { Ok(Value::Null) } else { Ok(json!({ "handles": r.iter().map(|h| h.hex()).collect::<Vec<_>>() })) }
}
@@ -220,6 +239,8 @@ enum Stage {
Edges(Vec<Handle>),
/// Fence points so far.
Fence(Vec<Vec2>),
/// Quick mode's two-point fence, started by a pick in empty space: its first point.
QuickFence(Vec2),
/// A crossing window: its first corner once picked.
Crossing(Option<Vec2>),
Mode,
@@ -356,11 +377,12 @@ impl Interactive for TrimM {
None => Prompt::new("Specify first fence point", Accept::POINT),
Some(l) => Prompt::new("Specify next fence point", Accept::POINT).kw(&["Undo"]).base(*l),
},
Stage::QuickFence(a) => Prompt::new("Specify next fence point", Accept::POINT).base(*a),
Stage::Crossing(None) => Prompt::new("Specify first corner", Accept::POINT),
Stage::Crossing(Some(_)) => Prompt::new("Specify opposite corner", Accept::POINT),
Stage::Mode => {
let msg = if self.extend { "Enter an extend mode option" } else { "Enter a trim mode option" };
Prompt::new(msg, Accept::TEXT).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
Prompt::new(msg, KW).kw(&["Quick", "Standard"]).default(if quick_mode(s) { "Quick" } else { "Standard" })
}
Stage::Project => {
let cur = match proj_mode(s) {
@@ -368,9 +390,9 @@ impl Interactive for TrimM {
2 => "View",
_ => "Ucs",
};
Prompt::new("Enter a projection option", Accept::TEXT).kw(&["None", "Ucs", "View"]).default(cur)
Prompt::new("Enter a projection option", KW).kw(&["None", "Ucs", "View"]).default(cur)
}
Stage::Edge => Prompt::new("Enter an implied edge extension mode", Accept::TEXT).kw(&["Extend", "No extend"]).default(if edge_mode(s) {
Stage::Edge => Prompt::new("Enter an implied edge extension mode", KW).kw(&["Extend", "No extend"]).default(if edge_mode(s) {
"Extend"
} else {
"No extend"
@@ -455,6 +477,16 @@ impl Interactive for TrimM {
}
Ok(Step::Continue)
}
Stage::QuickFence(a) => {
self.stage = Stage::Pick;
if let Input::Point(b) = i {
let r = self.step(s, |m, s| fence(s, &[a, b], extending, m.edges(quick, implied), quick).map(|_| ()));
if let Err(e) = r {
s.echo(e.to_string());
}
}
Ok(Step::Continue)
}
Stage::Crossing(first) => {
match (first, i) {
(None, Input::Point(p)) => self.stage = Stage::Crossing(Some(p)),
@@ -475,8 +507,9 @@ impl Interactive for TrimM {
let ap = s.pixel_size() * s.settings.pickbox.max(1.0) * 1.5;
let space = s.space();
let Some(h) = s.pick_object(&space, p, ap)? else {
// A pick in empty space opens a crossing window there.
self.stage = Stage::Crossing(Some(p));
// A pick in empty space starts a two-point fence in Quick mode (as in
// AutoCAD, #1594) and a crossing window in Standard mode.
self.stage = if quick { Stage::QuickFence(p) } else { Stage::Crossing(Some(p)) };
return Ok(Step::Continue);
};
let r = self.step(s, |m, s| apply(s, h, p, extending, m.edges(quick, implied), quick).map(|_| ()));
@@ -525,6 +558,7 @@ impl Interactive for TrimM {
.windows(2)
.filter_map(|w| Some(line(*w.first()?, *w.get(1)?)))
.collect(),
Stage::QuickFence(a) => vec![line(*a, c)],
Stage::Crossing(Some(a)) => vec![lwpoly(rect_vertices(*a, c), true)],
_ => Vec::new(),
}
+1 -1
View File
@@ -138,7 +138,7 @@ fn save(s: &mut Session, name: &str, window: Option<Bounds2>, snapshot: bool) ->
let layer_state = snapshot.then(|| {
let state = snapshot_name(name);
d.layer_states.retain(|l| !l.name.eq_ignore_ascii_case(&state));
d.layer_states.push(LayerState::new(state.clone(), d.layers.clone(), ""));
d.layer_states.push(LayerState { name: state.clone(), layers: d.layers.clone() });
state
});
if let Some(old) = &replaced {
+1 -2
View File
@@ -31,7 +31,7 @@ impl Accept {
/// [Truecolor/COlorbook] <BYLAYER>:". A prompt asking for something else besides its keywords has
/// it: "Enter block name or [?]:", "Specify insertion base point or [Basepoint/…]:". Read from
/// AutoCAD's command line over measured runs, where no prompt was written both ways.
const NO_OR: &[&str] = &[
const NO_OR: [&str; 28] = [
"Bring to front",
"Calculate rectangle dimensions based on",
"Choose mode for selected object conversion",
@@ -50,7 +50,6 @@ const NO_OR: &[&str] = &[
"Enter option",
"Enter polyline linetype generation option",
"Enter property to change",
"Enter states to change",
"Enter the type of array",
"Enter type of unused objects to purge",
"Enter viewport arrangement",
-5
View File
@@ -27,10 +27,6 @@ pub struct Settings {
pub measureinit: bool,
/// -VIEW sEttings > Layer snapshot: named views save the layer settings with them.
pub view_layer_snapshot: bool,
/// -LAYER stAte Save: the properties a new layer state restores (its mask), as the last Save
/// left them. AutoCAD 2024 keeps these toggles in the registry from one Save to the next
/// (measured); Edit doesn't change them.
pub layer_state_mask: u32,
pub dynmode: bool,
/// DYNDIGRIP: which dimensions grip dimensional input shows while a grip is stretched (bits:
/// 1 resulting length, 2 length change, 4 absolute angle, 8 angle change, 16 radius); read
@@ -152,7 +148,6 @@ impl Default for Settings {
zoomfactor: 60,
measureinit: false,
view_layer_snapshot: true,
layer_state_mask: cadcraft_doc::LayerState::ALL,
dynmode: true,
dyndigrip: 31,
dyndivis: 1,
-202
View File
@@ -1,202 +0,0 @@
//! The Key point option of a base point: ARRAYRECT, ARRAYPOLAR and ARRAYEDIT (Base point and
//! REPlace) take the source objects' key point (an end point, midpoint, centre…) nearest the
//! picked point as the base point; the JSON forms take `keyPoint`.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{ArrayKind, ArrayParams, EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use serde_json::json;
fn source_line(s: &mut Session) -> String {
let r = s.execute("line", &json!({"points": [[0, 0], [2, 1]]})).unwrap();
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).unwrap().to_string()
}
fn handle(v: &serde_json::Value) -> Handle {
Handle::parse_hex(v["handle"].as_str().unwrap()).unwrap()
}
/// The array's insertion point (its base point) and parameters.
fn array(s: &Session, h: Handle) -> (Vec2, ArrayParams) {
let d = s.doc().unwrap();
let e = d.entity(h).unwrap();
let EntityKind::Insert(i) = &e.kind else { panic!("not an array") };
(i.insert.xy(), d.array_params(e).unwrap())
}
fn only_array(s: &Session) -> Handle {
let d = s.doc().unwrap();
let arrays: Vec<Handle> = d.model.iter().filter(|e| d.array_params(e).is_some()).map(|e| e.handle).collect();
assert_eq!(arrays.len(), 1);
arrays[0]
}
fn typed(s: &mut Session, inputs: &[&str]) {
for t in inputs {
s.cmdline(t).unwrap();
}
}
#[test]
fn arrayrect_and_arraypolar_take_a_key_point_as_the_base_point() {
let mut s = Session::new();
let l = source_line(&mut s);
let r = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "keyPoint": [1.9, 1.05]})).unwrap();
assert!(array(&s, handle(&r)).0.near(Vec2::new(2.0, 1.0), 1e-9));
let mut s = Session::new();
let l = source_line(&mut s);
let r = s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 4, "keyPoint": [1.1, 0.4]})).unwrap();
assert!(array(&s, handle(&r)).0.near(Vec2::new(1.0, 0.5), 1e-9), "the line's midpoint");
}
#[test]
fn typed_key_points_at_arrayrect_and_arraypolar() {
let mut s = Session::new();
source_line(&mut s);
typed(&mut s, &["arrayrect", "l", "", "b", "k", "1.9,0.95", "x"]);
assert!(array(&s, only_array(&s)).0.near(Vec2::new(2.0, 1.0), 1e-9));
// Enter at the key point prompt goes back to the base point prompt.
let mut s = Session::new();
source_line(&mut s);
typed(&mut s, &["arraypolar", "l", "", "b", "k"]);
assert!(s.current_prompt().unwrap().message.contains("key point"));
typed(&mut s, &[""]);
assert!(s.current_prompt().unwrap().message.contains("base point"));
typed(&mut s, &["k", "0.1,0.1", "-10,0", "x"]);
assert!(array(&s, only_array(&s)).0.near(Vec2::new(0.0, 0.0), 1e-9));
}
#[test]
fn arrayedit_moves_the_base_point_to_a_key_point_of_an_item() {
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
// Near the start of the third item: the base point goes to (10, 0), the items stay.
s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [10.2, 0.05]})).unwrap();
let (at, p) = array(&s, h);
assert!(at.near(Vec2::new(10.0, 0.0), 1e-9), "{at:?}");
assert!(matches!(p.kind, ArrayKind::Rect(r) if r.cols == 3 && r.col_spacing == 5.0));
let items = s.execute("explode", &json!({"handles": [h.hex()]})).unwrap();
assert!(items.to_string().len() > 2);
let d = s.doc().unwrap();
let mut starts: Vec<(i64, i64)> = d
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Line(l) => Some(((l.a.x * 10.0).round() as i64, (l.a.y * 10.0).round() as i64)),
_ => None,
})
.collect();
starts.sort();
assert_eq!(starts, [(0, 0), (50, 0), (100, 0)]);
// Not on an item: refused.
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [3.5, 40]})).is_err());
assert!(array(&s, h).0.near(Vec2::ZERO, 1e-9));
// Typed: Base point, Key point, a point on the second item near its end.
s.set_selection(vec![h]);
typed(&mut s, &["arrayedit", "b", "k", "6.9,0.9", "x"]);
assert!(array(&s, h).0.near(Vec2::new(7.0, 1.0), 1e-9));
}
#[test]
fn replacement_objects_take_a_key_point_as_their_base_point() {
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 3, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
let c = s.execute("circle", &json!({"center": [50, 50], "radius": 1})).unwrap()["handle"].clone();
// The circle's right quadrant is the base point: on item 1 (at x = 5) its centre is at x = 4.
s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [c], "keyPoint": [51.2, 50.1], "items": [[1, 0, 0]]}})).unwrap();
s.execute("explode", &json!({"handles": [h.hex()]})).unwrap();
let d = s.doc().unwrap();
// The replaced item stays a reference to the replacement block.
let centres: Vec<Vec2> = d
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::Insert(i) => d.block(&i.block).map(|b| (i.transform(b.base.xy()), b)),
_ => None,
})
.flat_map(|(m, b)| {
b.entities
.iter()
.filter_map(move |e| match &e.kind {
EntityKind::Circle(c) => Some(m.apply(c.center.xy())),
_ => None,
})
.collect::<Vec<_>>()
})
.collect();
assert!(centres.iter().any(|c| c.near(Vec2::new(4.0, 0.0), 1e-9)), "{centres:?}");
}
#[test]
fn hostile_key_points_never_panic() {
let mut s = Session::new();
let l = source_line(&mut s);
for kp in [json!(["a", 1]), json!([1e308, -1e308]), json!([]), json!("x"), json!(null)] {
let _ = s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "keyPoint": kp}));
let _ = s.execute("arraypolar", &json!({"handles": [l], "center": [5, 5], "count": 3, "keyPoint": kp}));
}
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
for kp in [json!([1e308, 1e308]), json!([-1e308, 0]), json!(["x"]), json!([0.5, 0.25])] {
let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": kp}));
let _ = s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [], "keyPoint": kp, "items": [[0, 0, 0]]}}));
}
// Typed key points far away or on nothing are refused without leaving the command broken.
s.set_selection(vec![h]);
typed(&mut s, &["arrayedit", "b", "k"]);
assert!(s.cmdline("1e300,1e300").is_err() || s.running.is_some());
s.cancel();
}
/// A `keyPoint` that is there but isn't a point is refused, not taken as no key point (which
/// would make the array at another base point).
#[test]
fn a_key_point_that_is_not_a_point_is_refused() {
let mut s = Session::new();
let l = source_line(&mut s);
assert!(s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "keyPoint": ["bad", 1]})).is_err());
assert!(s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 3, "keyPoint": "x"})).is_err());
assert!(s.doc().unwrap().model.iter().all(|e| s.doc().unwrap().array_params(e).is_none()), "no array made");
let h = handle(&s.execute("arrayrect", &json!({"handles": [l], "cols": 2, "rows": 1, "colSpacing": 5, "base": [0, 0]})).unwrap());
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "keyPoint": [1]})).is_err());
let c = s.execute("circle", &json!({"center": [50, 50], "radius": 1})).unwrap()["handle"].clone();
assert!(s.execute("arrayedit", &json!({"handle": h.hex(), "replace": {"handles": [c], "keyPoint": {}, "items": [[1, 0, 0]]}})).is_err());
}
/// More objects than the key point search takes are refused rather than searched in part, which
/// could miss the nearest key point.
#[test]
fn a_key_point_of_too_many_objects_is_refused() {
let mut s = Session::new();
// 10,001 lines; the last one ends nearest the key point.
let pts: Vec<[f64; 2]> = (0..10_002).map(|i| [f64::from(i), 0.0]).collect();
let r = s.execute("line", &json!({ "points": pts })).unwrap();
let hs: Vec<String> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
assert_eq!(hs.len(), 10_001, "{r}");
let e = s.execute("arraypolar", &json!({"handles": hs, "center": [0, -50], "count": 2, "keyPoint": [10_001.2, 0]})).unwrap_err();
assert!(e.to_string().contains("10000"), "{e}");
}
/// ARRAYEDIT with a new base point (`base` or `keyPoint`) and a polar `center` in one call puts the
/// centre where asked: the base point moves the array's insertion point, so the centre is read in
/// the array's placement after that move.
#[test]
fn arrayedit_center_with_a_new_base_point_lands_where_asked() {
for (key, at) in [("base", json!([2, 1])), ("keyPoint", json!([1.95, 0.99]))] {
let mut s = Session::new();
let l = source_line(&mut s);
let h = handle(&s.execute("arraypolar", &json!({"handles": [l], "center": [-10, 0], "count": 4, "base": [0, 0]})).unwrap());
s.execute("arrayedit", &json!({"handle": h.hex(), key: at, "center": [5, 0]})).unwrap();
let (ins, p) = array(&s, h);
let ArrayKind::Polar(k) = p.kind else { panic!("not polar") };
assert!(ins.near(Vec2::new(2.0, 1.0), 1e-9), "{key}: {ins:?}");
// The centre is kept relative to the insertion point.
assert!((ins + k.center).near(Vec2::new(5.0, 0.0), 1e-9), "{key}: centre at {:?}", ins + k.center);
}
}
+4 -43
View File
@@ -83,22 +83,14 @@ fn dash_attedit_one_at_a_time_edits_the_selected_attributes() {
let mut s = with_block();
let h = handle(&insert(&mut s, 100.0, json!({"T": "abc"})));
type_lines(&mut s, &["-attedit", "y", "", "T", "", "105,0", ""]);
assert!(s.prompt_text().contains("[Value/Position/Height/Angle/Style/Layer/Color/Next] <N>"), "{}", s.prompt_text());
// Edit Position, Height, Angle, and Style
type_lines(&mut s, &["p", "10,20", "h", "2.5", "a", "45", "s", "Standard"]);
// Edit Value: change and replace
assert!(s.prompt_text().contains("[Value/Layer/Color/Next] <N>"), "{}", s.prompt_text());
// Unsupported options say so and keep the prompt.
s.cmdline("p").unwrap();
assert!(s.log.iter().any(|l| l.contains("Position is not available yet")), "{:?}", s.log);
type_lines(&mut s, &["v", "c", "b", "B", "v", "r", "replaced value", "n"]);
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(value(&s, h, "T"), "replaced value");
assert_eq!(value(&s, h, "U"), "u");
let EntityKind::Insert(ins) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
let att = ins.attribs.iter().find(|a| a.tag == "T").unwrap();
assert!((att.text.insert.x - 10.0).abs() < 1e-6);
assert!((att.text.insert.y - 20.0).abs() < 1e-6);
assert!((att.text.height - 2.5).abs() < 1e-6);
assert!((att.text.rotation.to_degrees() - 45.0).abs() < 1e-4);
assert_eq!(att.text.style, "Standard");
}
#[test]
@@ -117,34 +109,3 @@ fn attribute_tags_match_in_any_case_and_unknown_tags_are_reported() {
let r = s.execute("attedit", &json!({"handle": h.hex(), "values": {"T": "four"}})).unwrap();
assert_eq!(r, json!({"changed": 1}));
}
/// -ATTEDIT Position moves an aligned or fit attribute without losing its baseline: both of its
/// points move by the same offset (setting both to the picked point would leave no direction or
/// length to fit the text between).
#[test]
fn dash_attedit_position_keeps_an_aligned_attributes_baseline() {
use cadcraft_doc::HAlign;
use cadcraft_geom::Vec3;
for halign in [HAlign::Aligned, HAlign::Fit] {
let mut s = with_block();
let h = handle(&insert(&mut s, 100.0, json!({"T": "abc"})));
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
for a in i.attribs.iter_mut().filter(|a| a.tag == "T") {
a.text.halign = halign;
a.text.insert = Vec3::new(100.0, 1.0, 0.0);
a.text.align_pt = Some(Vec3::new(104.0, 1.0, 0.0));
}
}
})
.unwrap();
type_lines(&mut s, &["-attedit", "y", "", "T", "", "105,0", "", "p", "10,20", "n"]);
assert!(s.running.is_none(), "{}", s.prompt_text());
let EntityKind::Insert(ins) = &s.doc().unwrap().entity(h).unwrap().kind else { panic!("not an insert") };
let t = &ins.attribs.iter().find(|a| a.tag == "T").unwrap().text;
assert!(t.insert.xy().near(cadcraft_geom::Vec2::new(10.0, 20.0), 1e-9), "{halign:?}: {:?}", t.insert);
assert!(t.align_pt.is_some_and(|p| p.xy().near(cadcraft_geom::Vec2::new(14.0, 20.0), 1e-9)), "{halign:?}: {:?}", t.align_pt);
}
}
+1 -1
View File
@@ -38,7 +38,7 @@ fn dash_attedit_sets_layer_and_colour_of_one_attribute() {
for t in ["-attedit", "y", "", "T", "", "105,0", ""] {
s.cmdline(t).unwrap();
}
assert!(s.prompt_text().contains("[Value/Position/Height/Angle/Style/Layer/Color/Next] <N>"), "{}", s.prompt_text());
assert!(s.prompt_text().contains("[Value/Layer/Color/Next] <N>"), "{}", s.prompt_text());
s.cmdline("l").unwrap();
assert!(s.prompt_text().contains("Enter new layer name <0>"), "{}", s.prompt_text());
// An unknown layer is refused and asked again.
@@ -1,5 +1,6 @@
//! BREAK on a closed polyline removes the stretch from the first to the second point along the
//! vertex direction and leaves one open polyline (#1173).
//! BREAK on a closed polyline removes the stretch between the two points that doesn't run
//! through its start vertex, whichever point comes first, and leaves one open polyline from the
//! later point round to the earlier one (#1173; AutoCAD 2024, accoreconsole).
use cadcraft_doc::{EntityKind, LwPolyline};
use cadcraft_engine::Session;
@@ -38,14 +39,15 @@ fn break_opens_a_closed_polyline_at_the_command_line() {
}
#[test]
fn break_json_on_a_closed_polyline_follows_the_order_of_the_points() {
fn break_json_on_a_closed_polyline_ignores_the_order_of_the_points() {
let mut s = Session::new();
let r = closed_rect(&mut s);
// Second point before the first along the vertices: the long way round goes, the short
// stretch between them stays.
// Second point before the first along the vertices: the same stretch goes as with the points
// the other way round (measured with the first point after the second, and both ways on a
// 100 x 10 rectangle broken at (10, 0) and (10, 10), where the long stretch went).
s.execute("break", &json!({ "handle": r["handle"], "p1": [100, 30], "p2": [50, 0] })).unwrap();
let ps = polys(&s);
assert_eq!(ps.len(), 1);
assert!(!ps[0].closed);
assert_eq!(pts(&ps[0]), vec![(50.0, 0.0), (100.0, 0.0), (100.0, 30.0)]);
assert_eq!(pts(&ps[0]), vec![(100.0, 30.0), (100.0, 60.0), (0.0, 60.0), (0.0, 0.0), (50.0, 0.0)]);
}
@@ -0,0 +1,134 @@
//! BREAKATPOINT and BREAK where the result is easy to get wrong, as AutoCAD 2024 runs them
//! (accoreconsole, `entget` of every object after the command, on these drawings):
//!
//! - BREAKATPOINT at either end of a line, or at the end vertex of an open polyline, leaves the
//! object whole;
//! - at an open polyline's middle vertex it splits it there, the original keeping the first part;
//! - BREAK of a closed polyline at two points of one side, either way round and on the side that
//! closes it too, opens it with its own handle;
//! - a circle trimmed or broken becomes an arc with its own handle.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Handle};
use serde_json::{Value, json};
fn handle(v: &Value) -> Handle {
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
}
/// The model space objects in order: handle and kind.
fn objects(s: &Session) -> Vec<(Handle, EntityKind)> {
s.doc().unwrap().model.iter().map(|e| (e.handle, e.kind.clone())).collect()
}
/// A polyline's closed flag and vertices (rounded to 1e-9).
fn pts(k: &EntityKind) -> (bool, Vec<(f64, f64)>) {
let EntityKind::LwPolyline(p) = k else { panic!("not a polyline: {k:?}") };
let r = |v: f64| (v * 1e9).round() / 1e9;
(p.closed, p.vertices.iter().map(|v| (r(v.p.x), r(v.p.y))).collect())
}
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap())
}
fn pline(s: &mut Session, vertices: Value, closed: bool) -> Handle {
handle(&s.execute("pline", &json!({ "vertices": vertices, "closed": closed })).unwrap())
}
fn run(s: &mut Session, script: &str) {
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
}
#[test]
fn breakatpoint_at_an_end_leaves_the_object_whole() {
for at in ["100,0", "0,0"] {
let mut s = Session::new();
let l = line(&mut s, [0.0, 0.0], [100.0, 0.0]);
run(&mut s, &format!("BREAKATPOINT {at} {at}\n"));
let objs = objects(&s);
assert_eq!(objs.len(), 1, "{at}: {objs:?}");
let EntityKind::Line(k) = &objs[0].1 else { panic!("{objs:?}") };
assert!(objs[0].0 == l && (k.a.x, k.a.y, k.b.x, k.b.y) == (0.0, 0.0, 100.0, 0.0), "{at}: {objs:?}");
}
let mut s = Session::new();
let p = pline(&mut s, json!([[0, 0], [50, 0], [50, 30]]), false);
run(&mut s, "BREAKATPOINT 50,30 50,30\n");
let objs = objects(&s);
assert_eq!(objs.len(), 1, "{objs:?}");
assert_eq!((objs[0].0, pts(&objs[0].1)), (p, (false, vec![(0.0, 0.0), (50.0, 0.0), (50.0, 30.0)])));
}
#[test]
fn breakatpoint_at_a_middle_vertex_splits_there_and_the_original_keeps_the_first_part() {
let mut s = Session::new();
let p = pline(&mut s, json!([[0, 0], [50, 0], [50, 30]]), false);
run(&mut s, "BREAKATPOINT 50,0 50,0\n");
let objs = objects(&s);
assert_eq!(objs.len(), 2, "{objs:?}");
let first = objs.iter().find(|o| o.0 == p).expect("the original stays");
let other = objs.iter().find(|o| o.0 != p).unwrap();
assert_eq!(pts(&first.1), (false, vec![(0.0, 0.0), (50.0, 0.0)]));
assert_eq!(pts(&other.1), (false, vec![(50.0, 0.0), (50.0, 30.0)]));
// One undo brings back the polyline as it was, under its handle, and nothing else.
s.undo().unwrap();
let objs = objects(&s);
assert_eq!(objs.len(), 1, "{objs:?}");
assert_eq!((objs[0].0, pts(&objs[0].1)), (p, (false, vec![(0.0, 0.0), (50.0, 0.0), (50.0, 30.0)])));
}
#[test]
fn break_at_two_points_of_one_side_opens_a_closed_polyline_with_its_handle() {
let bottom = vec![(30.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0), (0.0, 0.0), (20.0, 0.0)];
// The side from (0, 10) back to the start vertex closes the rectangle.
let closing = vec![(0.0, 3.0), (0.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0), (0.0, 8.0)];
for (script, want) in [("BREAK 20,0 30,0\n", &bottom), ("BREAK 30,0 20,0\n", &bottom), ("BREAK 0,8 0,3\n", &closing)] {
let mut s = Session::new();
let r = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true);
run(&mut s, script);
let objs = objects(&s);
assert_eq!(objs.len(), 1, "{script}: {objs:?}");
assert_eq!((objs[0].0, pts(&objs[0].1)), (r, (false, want.clone())), "{script}");
// Undo closes it again.
s.undo().unwrap();
let objs = objects(&s);
let rect = vec![(0.0, 0.0), (100.0, 0.0), (100.0, 10.0), (0.0, 10.0)];
assert_eq!(objs.iter().map(|o| (o.0, pts(&o.1))).collect::<Vec<_>>(), vec![(r, (true, rect))], "{script}");
}
}
#[test]
fn a_circle_trimmed_or_broken_becomes_an_arc_with_its_handle() {
// Trimmed between the lines x = -5 and x = 5, picked at its top: the arc from 120 to 60
// degrees, round the bottom.
let mut s = Session::new();
let c = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap());
let l = line(&mut s, [-5.0, -20.0], [-5.0, 20.0]);
let m = line(&mut s, [5.0, -20.0], [5.0, 20.0]);
s.execute("trim", &json!({ "handle": c.hex(), "pick": [0, 10], "edges": [l.hex(), m.hex()] })).unwrap();
// The arc's handle, and whether it is AutoCAD's: radius 10 round (0, 0), from `start` to
// `end` degrees (to 1e-9 radians, 0 and 360 alike).
let arc_is = |s: &Session, start: f64, end: f64| {
let objs = objects(s);
let (h, k) = objs.iter().find(|o| matches!(o.1, EntityKind::Arc(_))).cloned().expect("an arc");
let EntityKind::Arc(a) = k else { panic!("not an arc") };
let same = |got: f64, want: f64| {
let d = (got - want.to_radians()).rem_euclid(std::f64::consts::TAU);
d < 1e-9 || std::f64::consts::TAU - d < 1e-9
};
let ok = (a.radius - 10.0).abs() < 1e-9 && a.center.x.abs() < 1e-9 && a.center.y.abs() < 1e-9 && same(a.start, start) && same(a.end, end);
(h, ok)
};
assert_eq!(arc_is(&s, 120.0, 60.0), (c, true));
// Broken from (10, 0) to (0, 10): the arc from 90 degrees round to 0.
let mut s = Session::new();
let c = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap());
run(&mut s, "BREAK 10,0 0,10\n");
assert_eq!(objects(&s).len(), 1);
assert_eq!(arc_is(&s, 90.0, 0.0), (c, true));
// Undo gives the circle back under its handle.
s.undo().unwrap();
let objs = objects(&s);
assert!(objs.len() == 1 && objs[0].0 == c && matches!(objs[0].1, EntityKind::Circle(_)), "{objs:?}");
}
@@ -0,0 +1,647 @@
//! BREAK on a closed polyline and TRIM of a polyline that is one of its own cutting edges, as
//! AutoCAD 2024 does them (measured with accoreconsole on these drawings):
//!
//! - BREAK between two points of a closed polyline removes the stretch between them that doesn't
//! run through its start vertex, whichever point comes first; BREAK or BREAKATPOINT at one point
//! splits it there into two open polylines, and at its start vertex leaves it closed.
//! - A polyline that is one of the cutting edges (picked, or with every object, in Standard or
//! Quick mode) is also cut at its own vertices, where it crosses itself and where a vertex of it
//! touches another of its segments. A piece whose ends meet there is left closed. A vertex
//! between two line segments in line (within 1e-8, straight on or doubling back) doesn't cut it.
//! - A pick within 5e-7 of one of the polyline's own cuts, whatever its size, trims nothing; a cut
//! by another edge that near the pick is passed over. An edge through a closed polyline's start
//! vertex cuts it there.
//!
//! Quick mode was measured in AutoCAD 2024 itself, picking on screen: its scripted TRIM runs
//! Standard mode only.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Handle};
use serde_json::{Value, json};
type Vertex = (f64, f64, f64);
fn handle(v: &Value) -> Handle {
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
}
fn pline(s: &mut Session, vertices: Value, closed: bool) -> Handle {
handle(&s.execute("pline", &json!({ "vertices": vertices, "closed": closed })).unwrap())
}
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap())
}
/// Every polyline in model space in order: its handle, closed flag and vertices with bulges.
fn polys(s: &Session) -> Vec<(Handle, bool, Vec<Vertex>)> {
s.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::LwPolyline(p) => Some((e.handle, p.closed, p.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect())),
_ => None,
})
.collect()
}
fn same(got: &[Vertex], want: &[Vertex]) -> bool {
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-9 && (g.1 - w.1).abs() < 1e-9 && (g.2 - w.2).abs() < 1e-9)
}
/// The polylines are `want` in order, (`kept`, closed, vertices): `kept` is whether it has the
/// handle `h`.
fn expect(s: &Session, h: Handle, want: &[(bool, bool, &[Vertex])]) {
let got = polys(s);
assert_eq!(got.len(), want.len(), "{got:?}");
for ((gh, gc, gv), (kept, closed, wv)) in got.iter().zip(want) {
assert_eq!((*gh == h, *gc), (*kept, *closed), "{got:?}");
assert!(same(gv, wv), "{gv:?} != {wv:?}");
}
}
fn run(s: &mut Session, script: &str) {
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
}
// ---------------- BREAK on a closed polyline ----------------
#[test]
fn break_removes_the_stretch_between_the_points_that_misses_the_start_vertex() {
// 100 x 10 rectangle broken at (10, 0) and (10, 10): the 190-unit stretch between them goes,
// the 20 units across the start vertex stay, with the points either way round.
for script in ["BREAK 10,0 10,10\n", "BREAK 10,10 10,0\n"] {
let mut s = Session::new();
let r = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true);
run(&mut s, script);
expect(&s, r, &[(true, false, &[(10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]);
}
}
#[test]
fn break_with_the_first_point_after_the_second_keeps_the_run_through_the_start() {
let mut s = Session::new();
let p = pline(&mut s, json!([[0, 0], { "p": [40, 0], "bulge": 0.5 }, [60, 0], [60, 30], [0, 30]]), true);
run(&mut s, "BREAK 60,20 10,0\n");
expect(&s, p, &[(true, false, &[(60.0, 20.0, 0.0), (60.0, 30.0, 0.0), (0.0, 30.0, 0.0), (0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]);
}
const SQUARE: [[f64; 2]; 4] = [[250.0, 0.0], [270.0, 0.0], [270.0, 20.0], [250.0, 20.0]];
#[test]
fn break_at_one_point_splits_a_closed_polyline_in_two() {
let first: &[Vertex] = &[(250.0, 0.0, 0.0), (260.0, 0.0, 0.0)];
let second: &[Vertex] = &[(260.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0), (250.0, 20.0, 0.0), (250.0, 0.0, 0.0)];
let mut s = Session::new();
let p = pline(&mut s, json!(SQUARE), true);
run(&mut s, "BREAK 260,0 260,0\n");
expect(&s, p, &[(true, false, first), (false, false, second)]);
// BREAKATPOINT does the same.
let mut s = Session::new();
let p = pline(&mut s, json!(SQUARE), true);
let r = s.execute("breakatpoint", &json!({ "handle": p.hex(), "at": [260, 0] })).unwrap();
assert_eq!(r["handles"].as_array().unwrap().len(), 2);
expect(&s, p, &[(true, false, first), (false, false, second)]);
}
#[test]
fn break_at_a_vertex_splits_there_and_at_the_start_vertex_changes_nothing() {
let mut s = Session::new();
let p = pline(&mut s, json!(SQUARE), true);
run(&mut s, "BREAK 270,20 270,20\n");
expect(
&s,
p,
&[
(true, false, &[(250.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0)]),
(false, false, &[(270.0, 20.0, 0.0), (250.0, 20.0, 0.0), (250.0, 0.0, 0.0)]),
],
);
let mut s = Session::new();
let p = pline(&mut s, json!(SQUARE), true);
run(&mut s, "BREAK 250,0 250,0\n");
expect(&s, p, &[(true, true, &[(250.0, 0.0, 0.0), (270.0, 0.0, 0.0), (270.0, 20.0, 0.0), (250.0, 20.0, 0.0)])]);
}
// ---------------- TRIM of a polyline that cuts itself ----------------
/// A polyline with an arc, and vertical lines at x = 20 and x = 60 crossing it.
fn arc_polyline(s: &mut Session) -> (Handle, Handle, Handle) {
let p = pline(s, json!([[0, 0], { "p": [40, 0], "bulge": 0.4 }, [70, 0], [90, 30]]), false);
let b = line(s, [20.0, -10.0], [20.0, 40.0]);
let c = line(s, [60.0, -20.0], [60.0, 40.0]);
(p, b, c)
}
/// The piece from the x = 60 cut on the arc to the end, as measured.
const FROM_C: [Vertex; 3] = [(60.0, -5.417486860749438, 0.1330399827453447), (70.0, 0.0, 0.0), (90.0, 30.0, 0.0)];
fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edges: Option<&[Handle]>) {
let mut p = json!({ "handle": h.hex(), "pick": pick });
if let Some(es) = edges {
p["edges"] = json!(es.iter().map(|e| e.hex()).collect::<Vec<_>>());
}
s.execute("trim", &p).unwrap();
}
#[test]
fn with_every_object_cutting_a_polyline_trims_to_its_own_vertex() {
let mut s = Session::new();
let (p, ..) = arc_polyline(&mut s);
trim(&mut s, p, [55.0, -6.0], None);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
}
#[test]
fn edges_that_leave_the_polyline_out_cut_only_where_they_cross_it() {
let mut s = Session::new();
let (p, b, c) = arc_polyline(&mut s);
trim(&mut s, p, [55.0, -6.0], Some(&[b, c]));
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (20.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
}
#[test]
fn a_polyline_that_is_its_only_edge_loses_the_whole_segment_picked() {
let mut s = Session::new();
let (p, ..) = arc_polyline(&mut s);
trim(&mut s, p, [55.0, -6.0], Some(&[p]));
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &[(70.0, 0.0, 0.0), (90.0, 30.0, 0.0)])]);
// The first segment: one piece left, the polyline itself.
let mut s = Session::new();
let (p, ..) = arc_polyline(&mut s);
trim(&mut s, p, [10.0, 0.0], Some(&[p]));
expect(&s, p, &[(true, false, &[(40.0, 0.0, 0.4), (70.0, 0.0, 0.0), (90.0, 30.0, 0.0)])]);
}
#[test]
fn a_closed_polyline_that_is_its_only_edge_opens_without_the_segment_picked() {
let mut s = Session::new();
let p = pline(&mut s, json!([[0, 0], [40, 0], [40, 30], [0, 30]]), true);
trim(&mut s, p, [20.0, 0.0], Some(&[p]));
expect(&s, p, &[(true, false, &[(40.0, 0.0, 0.0), (40.0, 30.0, 0.0), (0.0, 30.0, 0.0), (0.0, 0.0, 0.0)])]);
}
#[test]
fn a_polyline_crossing_itself_is_cut_at_the_crossing() {
let x = json!([[0, 0], [40, 20], [40, 0], [0, 20]]);
let mut s = Session::new();
let p = pline(&mut s, x.clone(), false);
trim(&mut s, p, [10.0, 5.0], Some(&[p]));
expect(&s, p, &[(true, false, &[(20.0, 10.0, 0.0), (40.0, 20.0, 0.0), (40.0, 0.0, 0.0), (0.0, 20.0, 0.0)])]);
// Every object (the polyline alone): cut between the crossing and the next vertex.
let mut s = Session::new();
let p = pline(&mut s, x, false);
trim(&mut s, p, [30.0, 15.0], None);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (20.0, 10.0, 0.0)]), (false, false, &[(40.0, 20.0, 0.0), (40.0, 0.0, 0.0), (0.0, 20.0, 0.0)])]);
}
#[test]
fn a_closed_polyline_at_survey_coordinates_trims_to_its_own_vertex() {
let mut s = Session::new();
let p = pline(
&mut s,
json!([[612345.678, 2398765.432], { "p": [612385.678, 2398765.432], "bulge": 0.4 }, [612415.678, 2398765.432], [612415.678, 2398795.432], [612345.678, 2398795.432]]),
true,
);
let b = line(&mut s, [612365.678, 2398755.432], [612365.678, 2398805.432]);
let c = line(&mut s, [612405.678, 2398745.432], [612405.678, 2398805.432]);
trim(&mut s, p, [612400.678, 2398759.432], Some(&[p, b, c]));
let got = polys(&s);
assert_eq!(got.len(), 1);
let (h, closed, vs) = &got[0];
assert!(*h == p && !closed);
let want: [Vertex; 6] = [
(612405.678, 2398760.014513139, 0.1330399827461127),
(612415.678, 2398765.432, 0.0),
(612415.678, 2398795.432, 0.0),
(612345.678, 2398795.432, 0.0),
(612345.678, 2398765.432, 0.0),
(612385.678, 2398765.432, 0.0),
];
// Survey coordinates: a micrometre on the points, the bulge to 1e-9.
assert_eq!(vs.len(), want.len());
for (g, w) in vs.iter().zip(&want) {
assert!((g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6 && (g.2 - w.2).abs() < 1e-9, "{g:?} != {w:?}");
}
}
#[test]
fn standard_mode_at_the_command_line_with_every_object_cuts_at_the_polyline_vertex() {
let mut s = Session::new();
let (p, ..) = arc_polyline(&mut s);
// Mode Standard, Enter: every object is a cutting edge.
run(&mut s, "TRIM O S\n\n55,-6\n\n");
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
}
#[test]
fn a_polyline_picked_as_an_edge_in_quick_mode_cuts_itself_too() {
// Quick mode with the edges given (its cuTting edges option): picked is picked.
let mut s = Session::new();
let (p, _, c) = arc_polyline(&mut s);
s.execute("trim", &json!({ "handle": p.hex(), "pick": [55, -6], "mode": "quick", "edges": [p.hex(), c.hex()] })).unwrap();
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
}
#[test]
fn quick_mode_with_every_object_cuts_a_polyline_at_its_own_vertex_too() {
// As Standard mode with every object: from the vertex at (40, 0), not from the line at x = 20.
let mut s = Session::new();
let (p, ..) = arc_polyline(&mut s);
s.execute("trim", &json!({ "handle": p.hex(), "pick": [55, -6], "mode": "quick" })).unwrap();
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (40.0, 0.0, 0.0)]), (false, false, &FROM_C)]);
}
/// A rectangle, then an open polyline whose last vertex (6.9, 6.2) touches its second segment
/// inside the rectangle (reversed: whose first vertex does). The polyline's handle.
fn touching(s: &mut Session, reversed: bool) -> Handle {
pline(s, json!([[3.9, 3.8], [8.3, 3.8], [8.3, 6.9], [3.9, 6.9]]), true);
let mut v = vec![[2.3, 3.3], [5.3, 8.0], [8.5, 4.4], [8.8, 7.8], [6.9, 6.2]];
if reversed {
v.reverse();
}
pline(s, json!(v), false)
}
const RECT: [Vertex; 4] = [(3.9, 3.8, 0.0), (8.3, 3.8, 0.0), (8.3, 6.9, 0.0), (3.9, 6.9, 0.0)];
/// Where the second segment crosses the rectangle's top and right sides.
const TOP: Vertex = (6.277777777777777, 6.9, 0.0);
const RIGHT: Vertex = (8.3, 4.625, 0.0);
#[test]
fn a_polyline_is_cut_where_its_end_touches_it() {
let start: [Vertex; 3] = [(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), TOP];
let looped: [Vertex; 3] = [(6.9, 6.2, 0.0), (8.5, 4.4, 0.0), (8.8, 7.8, 0.0)];
// Picked above the touch, in the rectangle: cut from the top side to the touch. What is left
// after it ends where it starts, so it is closed. Quick mode as picked on screen, and Standard
// mode with every object at the command line.
let mut s = Session::new();
let p = touching(&mut s, false);
s.execute("trim", &json!({ "handle": p.hex(), "pick": [6.58, 6.56], "mode": "quick" })).unwrap();
expect(&s, p, &[(false, true, &RECT), (true, false, &start), (false, true, &looped)]);
let mut s = Session::new();
let p = touching(&mut s, false);
run(&mut s, "TRIM O S\n\n6.58,6.56\n\n");
expect(&s, p, &[(false, true, &RECT), (true, false, &start), (false, true, &looped)]);
// Below the touch: cut from the touch to the right side.
let mut s = Session::new();
let p = touching(&mut s, false);
trim(&mut s, p, [7.604, 5.408], None);
let end: [Vertex; 4] = [RIGHT, (8.5, 4.4, 0.0), (8.8, 7.8, 0.0), (6.9, 6.2, 0.0)];
expect(&s, p, &[(false, true, &RECT), (true, false, &[(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), (6.9, 6.2, 0.0)]), (false, false, &end)]);
// The first vertex touching: the closed loop is the piece that keeps the handle.
let mut s = Session::new();
let p = touching(&mut s, true);
trim(&mut s, p, [6.58, 6.56], None);
expect(
&s,
p,
&[
(false, true, &RECT),
(true, true, &[(6.9, 6.2, 0.0), (8.8, 7.8, 0.0), (8.5, 4.4, 0.0)]),
(false, false, &[TOP, (5.3, 8.0, 0.0), (2.3, 3.3, 0.0)]),
],
);
}
#[test]
fn a_closed_piece_keeps_its_arcs() {
let mut s = Session::new();
pline(&mut s, json!([[3.9, 3.8], [8.3, 3.8], [8.3, 6.9], [3.9, 6.9]]), true);
let p = pline(&mut s, json!([[2.3, 3.3], [5.3, 8.0], { "p": [8.5, 4.4], "bulge": 0.3 }, [8.8, 7.8], [6.9, 6.2]]), false);
trim(&mut s, p, [6.58, 6.56], None);
let looped: [Vertex; 3] = [(6.9, 6.2, 0.0), (8.5, 4.4, 0.3), (8.8, 7.8, 0.0)];
expect(&s, p, &[(false, true, &RECT), (true, false, &[(2.3, 3.3, 0.0), (5.3, 8.0, 0.0), TOP]), (false, true, &looped)]);
}
#[test]
fn a_pick_half_a_unit_from_a_vertex_1e9_out_trims_the_segment_it_is_on() {
let mut s = Session::new();
let p = pline(&mut s, json!([[0, 0], [1e9, 0], [1e9, 10]]), false);
trim(&mut s, p, [1e9, 0.5], None);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (1e9, 0.0, 0.0)])]);
}
// ---------------- a pick on a cut ----------------
type Edge = ([f64; 2], [f64; 2]);
/// The polyline `v`, with lines `edges`, trimmed at `pick` with every object as an edge, or only
/// the lines when `only_lines`; the polyline's handle and whether the trim was made.
fn attempt(v: Value, closed: bool, edges: &[Edge], only_lines: bool, pick: [f64; 2]) -> (Session, Handle, bool) {
let mut s = Session::new();
let p = pline(&mut s, v, closed);
let ls: Vec<String> = edges.iter().map(|(a, b)| line(&mut s, *a, *b).hex()).collect();
let mut params = json!({ "handle": p.hex(), "pick": pick });
if only_lines {
params["edges"] = json!(ls);
}
let made = s.execute("trim", &params).is_ok();
(s, p, made)
}
/// [`attempt`] with at most one line, which must trim.
fn trimmed(v: Value, closed: bool, edge: Option<Edge>, only_line: bool, pick: [f64; 2]) -> (Session, Handle) {
let (s, p, made) = attempt(v, closed, edge.as_slice(), only_line, pick);
assert!(made, "{pick:?}");
(s, p)
}
/// A vertical line through x = `x`.
fn at(x: f64) -> Edge {
([x, -5.0], [x, 5.0])
}
#[test]
fn a_pick_on_a_cut_trims_nothing() {
// The vertex (10, 0) is the only cut. A pick whose nearest point is within 5e-7 of it, on it
// or off to the side, leaves the polyline as it was; one 6e-7 from it trims the segment it is
// on.
let v = || json!([[0, 0], [10, 0], [10, 10]]);
let whole: [Vertex; 3] = [(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0)];
for pick in [[10.0, 0.0], [10.0, 4e-7], [10.5, 4e-7], [9.99999999, 0.0]] {
let (s, p) = trimmed(v(), false, None, false, pick);
expect(&s, p, &[(true, false, &whole)]);
}
let (s, p) = trimmed(v(), false, None, false, [10.0, 6e-7]);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]);
let (s, p) = trimmed(v(), false, None, false, [9.9999994, 0.0]);
expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
}
#[test]
fn a_pick_on_a_cut_is_within_the_same_distance_at_any_size() {
// A polyline a thousandth across, and one 1e9 long with a line through its vertex: 1e-7 from
// the vertex is on the cut, 1e-6 off it.
let small = || json!([[0, 0], [0.001, 0], [0.001, 0.001]]);
let (s, p) = trimmed(small(), false, None, false, [0.001, 1e-7]);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (0.001, 0.0, 0.0), (0.001, 0.001, 0.0)])]);
let (s, p) = trimmed(small(), false, None, false, [0.001, 1e-6]);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (0.001, 0.0, 0.0)])]);
let long = || json!([[0, 0], [10, 0], [10, 1e9]]);
let through = Some(([0.0, -10.0], [20.0, 10.0]));
let (s, p) = trimmed(long(), false, through, false, [10.0, 1e-7]);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 1e9, 0.0)])]);
let (s, p) = trimmed(long(), false, through, false, [10.0, 1e-6]);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0)])]);
}
#[test]
fn a_cut_by_another_edge_at_the_pick_is_passed_over() {
// A pick within 5e-7 of a cut by another edge runs the piece on across it, to the next cut
// either side; 6e-7 away the cut holds.
let flat = || json!([[0, 0], [10, 0]]);
let piece = |a: f64, b: f64| [(a, 0.0, 0.0), (b, 0.0, 0.0)];
for pick in [[3.0, 0.0], [3.0000004, 0.0]] {
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(7.0)], true, pick);
expect(&s, p, &[(true, false, &piece(7.0, 10.0))]);
}
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(7.0)], true, [3.0000006, 0.0]);
expect(&s, p, &[(true, false, &piece(0.0, 3.0)), (false, false, &piece(7.0, 10.0))]);
// Lines at 3, 5 and 7: picked on 5, 3 to 7 goes; picked on 7, 5 to the end.
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(5.0), at(7.0)], true, [5.0, 0.0]);
expect(&s, p, &[(true, false, &piece(0.0, 3.0)), (false, false, &piece(7.0, 10.0))]);
let (s, p, _) = attempt(flat(), false, &[at(3.0), at(5.0), at(7.0)], true, [7.0, 0.0]);
expect(&s, p, &[(true, false, &piece(0.0, 5.0))]);
// Every object an edge: on to the polyline's own vertex (10, 0).
let (s, p, _) = attempt(json!([[0, 0], [10, 0], [10, 10]]), false, &[at(5.0)], false, [5.0, 0.0]);
expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
// A closed rectangle cut at x = 30 and 70 top and bottom, picked on the bottom at 30: round
// its start vertex, from 30 on the top to 70 on the bottom.
let tall = |x: f64| ([x, -5.0], [x, 15.0]);
let (s, p, _) = attempt(json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true, &[tall(30.0), tall(70.0)], true, [30.0, 0.0]);
expect(&s, p, &[(true, false, &[(70.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (30.0, 10.0, 0.0)])]);
// One line only, picked on its cut or 4e-7 past it: no cut is left, and nothing is trimmed.
for pick in [[5.0, 0.0], [5.0000004, 0.0]] {
let (s, p, made) = attempt(json!([[0, 0], [10, 0], [10, 10]]), false, &[at(5.0)], true, pick);
assert!(!made);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
}
// In Quick mode too: the polyline meets the line, so it isn't erased as one no edge crosses.
let mut s = Session::new();
let p = pline(&mut s, json!([[0, 0], [10, 0]]), false);
line(&mut s, [5.0, -5.0], [5.0, 5.0]);
assert!(s.execute("trim", &json!({ "handle": p.hex(), "pick": [5, 0], "mode": "quick" })).is_err());
expect(&s, p, &[(true, false, &piece(0.0, 10.0))]);
}
#[test]
fn a_pick_on_a_vertex_an_edge_runs_through_trims_nothing() {
// The line's cut is found on the segments either side of the vertex, a rounding apart. Both
// are passed over, so no cut is left and the polyline stays as it was, not split there.
let cases = [
([[5.5, 1.1], [23.3, 7.7], [30.1, 29.9]], ([23.3, 7.7], [45.7, 2.3])),
([[5.5, 1.1], [23.3, 7.7], [30.1, 29.9]], ([2.0 * 23.3 - 45.7, 2.0 * 7.7 - 2.3], [45.7, 2.3])),
([[1.3, 2.7], [37.9, 11.3], [55.1, 48.7]], ([4.5, 43.5], [71.3, -20.9])),
];
for (v, edge) in cases {
let (s, p, made) = attempt(json!(v), false, &[edge], true, v[1]);
let whole: Vec<Vertex> = v.iter().map(|q| (q[0], q[1], 0.0)).collect();
assert!(!made);
expect(&s, p, &[(true, false, &whole)]);
}
}
#[test]
fn an_edge_through_a_closed_polylines_start_vertex_cuts_it_there() {
// The line cuts the rectangle at (0, 0) and at (10, 10) on its top. The pick takes the piece
// it is on, whichever vertex the rectangle starts at. 4e-7 from (0, 0) that cut is passed
// over, which leaves one, and the trim is refused.
let rect = || json!([[0, 0], [100, 0], [100, 10], [0, 10]]);
let edge = Some(([-5.0, -5.0], [15.0, 15.0]));
let left: [Vertex; 3] = [(10.0, 10.0, 0.0), (0.0, 10.0, 0.0), (0.0, 0.0, 0.0)];
let (s, p) = trimmed(rect(), true, edge, true, [50.0, 0.0]);
expect(&s, p, &[(true, false, &left)]);
let (s, p) = trimmed(json!([[50, 0], [100, 0], [100, 10], [0, 10], [0, 0]]), true, edge, true, [50.0, 10.0]);
expect(&s, p, &[(true, false, &left)]);
let (s, p) = trimmed(rect(), true, edge, true, [0.0, 5.0]);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (10.0, 10.0, 0.0)])]);
let whole: [Vertex; 4] = [(0.0, 0.0, 0.0), (100.0, 0.0, 0.0), (100.0, 10.0, 0.0), (0.0, 10.0, 0.0)];
let (s, p, made) = attempt(rect(), true, edge.as_slice(), true, [0.0, 4e-7]);
assert!(!made);
expect(&s, p, &[(true, true, &whole)]);
// The rectangle alone, picked on its start vertex, and 4e-7 from it on its last segment.
for pick in [[0.0, 0.0], [0.0, 4e-7]] {
let (s, p) = trimmed(rect(), true, None, false, pick);
expect(&s, p, &[(true, true, &whole)]);
}
}
#[test]
fn a_closed_polyline_cut_at_one_point_is_left_as_it_was() {
// A line touching the rectangle only at its start vertex, and one crossing its bottom once and
// ending inside: AutoCAD refuses either trim, and Quick mode doesn't erase the rectangle.
for (a, b, pick) in [([-5.0, 5.0], [5.0, -5.0], [50.0, 0.0]), ([50.0, -5.0], [50.0, 5.0], [20.0, 0.0])] {
for mode in ["standard", "quick"] {
let mut s = Session::new();
let p = pline(&mut s, json!([[0, 0], [100, 0], [100, 10], [0, 10]]), true);
let l = line(&mut s, a, b);
let before = polys(&s);
let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": pick, "edges": [l.hex()], "mode": mode }));
assert!(r.is_err_and(|e| e.to_string() == "Curve must intersect cutting edges at least twice."), "{a:?} {mode}");
assert_eq!(polys(&s), before, "{a:?} {mode}");
}
}
}
// ---------------- where a polyline runs straight on ----------------
#[test]
fn a_vertex_the_polyline_runs_straight_on_through_doesnt_cut_it() {
// (5, 0) lies between two segments in line: the pick takes everything back to the cut before
// it, the start of the polyline or the closed polyline's start vertex.
let v = || json!([[0, 0], [5, 0], [10, 0], [10, 10]]);
let (s, p) = trimmed(v(), false, None, false, [7.0, 0.0]);
expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
let (s, p) = trimmed(v(), true, None, false, [7.0, 0.0]);
expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (0.0, 0.0, 0.0)])]);
// A crossing on the segment in line before the one picked bounds the piece, as does one on the
// segment in line after it, and one right at the vertex in line.
let (s, p) = trimmed(json!([[0, 0], [5, 0], [10, 0], [10, 10], [2, 10], [2, -5]]), false, None, false, [7.0, 0.0]);
expect(
&s,
p,
&[
(true, false, &[(0.0, 0.0, 0.0), (2.0, 0.0, 0.0)]),
(false, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (2.0, 10.0, 0.0), (2.0, -5.0, 0.0)]),
],
);
let (s, p) = trimmed(json!([[0, 0], [5, 0], [10, 0], [10, 10], [8, 10], [8, -5]]), false, None, false, [3.5, 0.0]);
expect(&s, p, &[(true, false, &[(8.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (8.0, 10.0, 0.0), (8.0, -5.0, 0.0)])]);
let at_vertex = || json!([[0, 0], [5, 0], [10, 0], [10, 10], [5, 10], [5, -5]]);
let rest: [Vertex; 4] = [(10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (5.0, 10.0, 0.0), (5.0, -5.0, 0.0)];
let (s, p) = trimmed(at_vertex(), false, None, false, [7.0, 0.0]);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (5.0, 0.0, 0.0)]), (false, false, &rest)]);
let (s, p) = trimmed(at_vertex(), false, None, false, [3.0, 0.0]);
expect(&s, p, &[(true, false, &[(5.0, 0.0, 0.0), (10.0, 0.0, 0.0), (10.0, 10.0, 0.0), (5.0, 10.0, 0.0), (5.0, -5.0, 0.0)])]);
// Straight on, or doubling back over itself: no cut at all.
for (v, pick) in [(json!([[0, 0], [5, 0], [10, 0]]), [7.0, 0.0]), (json!([[0, 0], [10, 0], [5, 0]]), [2.0, 0.0])] {
let mut s = Session::new();
let p = pline(&mut s, v, false);
let before = polys(&s);
assert!(s.execute("trim", &json!({ "handle": p.hex(), "pick": pick })).is_err());
assert_eq!(polys(&s), before);
}
}
#[test]
fn a_bend_of_1e_8_cuts_a_polyline_and_a_smaller_one_doesnt() {
// The bend at (5, 0), as the sine of its angle, whatever the segments' lengths.
for (end, pick, cuts) in [
([10.0, 4e-8], [7.0, 0.0], false),
([10.0, 6e-8], [7.0, 0.0], true),
([5005.0, 1e-6], [700.0, 0.0], false),
([5005.0, 0.01], [700.0, 0.0], true),
] {
let mut s = Session::new();
let p = pline(&mut s, json!([[0, 0], [5, 0], end]), false);
let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": pick }));
assert_eq!((r.is_ok(), polys(&s)[0].2.len()), if cuts { (true, 2) } else { (false, 3) }, "{end:?}");
}
// Two arcs of one circle, or a line and an arc on from it, cut where they meet.
let q = 0.41421356237309503;
let (s, p) = trimmed(json!([{ "p": [0, 0], "bulge": -q }, { "p": [5, 5], "bulge": -q }, [10, 0]]), false, None, false, [8.5355339, 3.5355339]);
expect(&s, p, &[(true, false, &[(0.0, 0.0, -q), (5.0, 5.0, 0.0)])]);
let (s, p) = trimmed(json!([[0, 0], { "p": [5, 0], "bulge": q }, [10, 5]]), false, None, false, [8.5355339, 1.4644661]);
expect(&s, p, &[(true, false, &[(0.0, 0.0, 0.0), (5.0, 0.0, 0.0)])]);
}
#[test]
fn a_polyline_of_thousands_of_segments_is_cut_where_it_crosses_itself() {
// 3,003 segments, the last crossing the first at (50, 0): the pick on the first takes it from
// there to the vertex (100, 0), as with a few segments.
let mut v = vec![json!([0, 0]), json!([100, 0]), json!([100, 20])];
v.extend((1..=3000).map(|i| json!([100.0 - f64::from(i) / 60.0, 20.0 + f64::from(i % 2)])));
v.push(json!([50, -10]));
let (s, p) = trimmed(json!(v), false, None, false, [75.0, 0.0]);
let got = polys(&s);
assert_eq!(got.len(), 2, "{:?}", got.iter().map(|g| g.2.len()).collect::<Vec<_>>());
assert!(got[0].0 == p && same(&got[0].2, &[(0.0, 0.0, 0.0), (50.0, 0.0, 0.0)]), "{:?}", got[0]);
assert_eq!((got[1].2.len(), got[1].2.first().copied()), (3003, Some((100.0, 0.0, 0.0))));
}
#[test]
fn a_polyline_too_long_to_search_for_its_own_crossings_is_left_as_it_was() {
// 4,100 segments in line: the run picked times those near it is past the bound searched. 300
// segments in line over the same stretch, back and forth, crossed by 300 more: 90,000
// crossings, past the bound kept. The trim is refused, and Quick mode doesn't erase the
// polyline as one no edge crosses.
let mut back_and_forth: Vec<[f64; 2]> = (0..=300).map(|i| [if i % 2 == 0 { 0.0 } else { 10.0 }, 0.0]).collect();
back_and_forth.extend((0..300).map(|i| [0.5 + f64::from(i) * 0.03, if i % 2 == 0 { 5.0 } else { -5.0 }]));
for (v, why) in [(json!((0..=4100).map(|i| [i, 0]).collect::<Vec<_>>()), "Too many segments"), (json!(back_and_forth), "Too many crossings")] {
let mut s = Session::new();
let p = pline(&mut s, v, false);
let before = polys(&s);
let r = s.execute("trim", &json!({ "handle": p.hex(), "pick": [0.2, 0], "mode": "quick" }));
assert!(r.is_err_and(|e| e.to_string().contains(why)), "{why}");
assert_eq!(polys(&s), before);
}
}
#[test]
fn a_piece_whose_ends_only_come_near_stays_open_far_from_the_origin() {
// 1e9 out, as survey coordinates in millimetres are: the piece left runs from the line's cut
// to the polyline's end, 0.58 away, and stays open.
let o = 1e9;
let mut s = Session::new();
let p = pline(&mut s, json!([[o + 2.3, 3.3], [o + 5.3, 8.0], [o + 8.5, 4.4], [o + 8.8, 7.8], [o + 7.4, 6.5]]), false);
line(&mut s, [o + 6.9, 5.0], [o + 6.9, 7.0]);
trim(&mut s, p, [o + 6.1, 7.1], None);
let got = polys(&s);
assert_eq!(got.len(), 2, "{got:?}");
let (h, closed, vs) = &got[1];
assert!(*h != p && !closed && vs.len() == 4, "{got:?}");
let last = vs[3];
assert!((last.0 - (o + 7.4)).abs() < 1e-6 && (last.1 - 6.5).abs() < 1e-6, "{last:?}");
}
#[test]
fn a_polyline_is_cut_where_a_vertex_of_it_touches_it() {
// The vertex (6, 6) lies on the first segment, which is cut there.
let v = json!([[0, 0], [10, 10], [12, 4], [6, 6], [4, 12]]);
let mut s = Session::new();
let p = pline(&mut s, v.clone(), false);
trim(&mut s, p, [3.0, 3.0], None);
expect(&s, p, &[(true, false, &[(6.0, 6.0, 0.0), (10.0, 10.0, 0.0), (12.0, 4.0, 0.0), (6.0, 6.0, 0.0), (4.0, 12.0, 0.0)])]);
let mut s = Session::new();
let p = pline(&mut s, v, false);
trim(&mut s, p, [8.0, 8.0], None);
expect(
&s,
p,
&[
(true, false, &[(0.0, 0.0, 0.0), (6.0, 6.0, 0.0)]),
(false, false, &[(10.0, 10.0, 0.0), (12.0, 4.0, 0.0), (6.0, 6.0, 0.0), (4.0, 12.0, 0.0)]),
],
);
}
#[test]
fn a_long_run_in_line_on_a_large_polyline_is_cut_where_it_is_crossed() {
// 1,000 segments in line along y = 0, then 20,002 more, the last crossing the run at x = 500.25:
// only the few segments near the run are searched, and the pick takes it from the crossing to
// the corner (1000, 0).
let mut v: Vec<Value> = (0..=1000).map(|i| json!([i, 0])).collect();
v.push(json!([1000, 200]));
v.extend((1..=20000).map(|i| json!([1000.0 - f64::from(i) * 499.75 / 20000.0, 200.0 + f64::from(i % 2)])));
v.push(json!([500.25, -10]));
let (s, p) = trimmed(json!(v), false, None, false, [999.5, 0.0]);
let got = polys(&s);
assert_eq!(got.len(), 2, "{:?}", got.iter().map(|g| g.2.len()).collect::<Vec<_>>());
assert!(got[0].0 == p && got[0].2.len() == 502 && got[0].2.last() == Some(&(500.25, 0.0, 0.0)), "{:?}", got[0].2.last());
assert_eq!((got[1].2.first().copied(), got[1].2.last().copied()), (Some((1000.0, 0.0, 0.0)), Some((500.25, -10.0, 0.0))));
}
#[test]
fn a_crossing_window_whose_nearest_point_is_a_vertex_trims_the_segment_it_ends() {
// The window's first corner is nearest the vertex (10, 0), a cut of the polyline: the segment
// before it goes, either way round the window, as in AutoCAD.
for (a, b) in [([10.5, -0.5], [8.0, 2.0]), ([8.0, 2.0], [10.5, -0.5])] {
let mut s = Session::new();
let p = pline(&mut s, json!([[0, 0], [10, 0], [10, 10]]), false);
s.execute("trim", &json!({ "crossing": [a, b], "mode": "standard" })).unwrap();
expect(&s, p, &[(true, false, &[(10.0, 0.0, 0.0), (10.0, 10.0, 0.0)])]);
}
}
@@ -0,0 +1,128 @@
//! BREAKATPOINT at the command line and from a script, with AutoCAD 2024's prompts ("Select
//! object:", then "Specify break point:"); BREAK and BREAKATPOINT end the command when a circle
//! can't be broken at one point, and refuse an object on a locked layer when it is picked. Measured
//! in AutoCAD 2024 (accoreconsole) on these drawings.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Handle};
use serde_json::{Value, json};
fn handle(v: &Value) -> Handle {
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
}
/// The model space objects in order: handle and kind.
fn objects(s: &Session) -> Vec<(Handle, EntityKind)> {
s.doc().unwrap().model.iter().map(|e| (e.handle, e.kind.clone())).collect()
}
fn line_ends(k: &EntityKind) -> ((f64, f64), (f64, f64)) {
let EntityKind::Line(l) = k else { panic!("not a line: {k:?}") };
((l.a.x, l.a.y), (l.b.x, l.b.y))
}
#[test]
fn breakatpoint_asks_for_the_object_then_the_point_and_splits_the_line_there() {
let mut s = Session::new();
let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap());
s.cmdline("BREAKATPOINT").unwrap();
assert!(s.prompt_text().ends_with("Select object:"), "{}", s.prompt_text());
s.cmdline("1002,0").unwrap();
assert!(s.prompt_text().ends_with("Specify break point:"), "{}", s.prompt_text());
// Off the line: the point projects onto it.
s.cmdline("1005,3").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let objs = objects(&s);
assert_eq!(objs.len(), 2);
assert_eq!(objs[0].0, l);
assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1005.0, 0.0)));
assert_eq!(line_ends(&objs[1].1), ((1005.0, 0.0), (1010.0, 0.0)));
}
#[test]
fn breakatpoint_from_a_script_splits_an_arc_and_a_closed_polyline() {
let mut s = Session::new();
let a = handle(&s.execute("arc", &json!({ "center": [700, 0], "radius": 10, "start": 0, "end": 90 })).unwrap());
let p = handle(&s.execute("pline", &json!({ "vertices": [[250, 0], [270, 0], [270, 20], [250, 20]], "closed": true })).unwrap());
s.script("BREAKATPOINT 707.0710678,7.0710678 707.0710678,7.0710678\nBREAKATPOINT 260,0 260,0\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let objs = objects(&s);
assert_eq!(objs.iter().map(|o| o.0).take(2).collect::<Vec<_>>(), [a, p]);
let EntityKind::Arc(arc) = &objs[0].1 else { panic!("not an arc") };
assert!((arc.start - 0.0).abs() < 1e-9 && (arc.end.to_degrees() - 45.0).abs() < 1e-6, "{arc:?}");
let EntityKind::Arc(rest) = &objs[2].1 else { panic!("not an arc") };
assert!((rest.start.to_degrees() - 45.0).abs() < 1e-6 && (rest.end.to_degrees() - 90.0).abs() < 1e-9, "{rest:?}");
let pts = |k: &EntityKind| match k {
EntityKind::LwPolyline(l) => (l.closed, l.vertices.iter().map(|v| (v.p.x, v.p.y)).collect::<Vec<_>>()),
k => panic!("not a polyline: {k:?}"),
};
assert_eq!(pts(&objs[1].1), (false, vec![(250.0, 0.0), (260.0, 0.0)]));
assert_eq!(pts(&objs[3].1), (false, vec![(260.0, 0.0), (270.0, 0.0), (270.0, 20.0), (250.0, 20.0), (250.0, 0.0)]));
}
#[test]
fn breakatpoint_and_break_at_one_point_of_a_circle_report_it_and_end() {
for script in ["BREAKATPOINT 1300,10 1300,10\n", "BREAK 1300,10 1300,10\n"] {
let mut s = Session::new();
let c = handle(&s.execute("circle", &json!({ "center": [1300, 0], "radius": 10 })).unwrap());
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
assert!(s.log.iter().any(|l| l == "Arc cannot be full 360 degrees"), "{script}: {:?}", s.log);
let objs = objects(&s);
assert_eq!(objs.len(), 1);
assert!(objs[0].0 == c && matches!(objs[0].1, EntityKind::Circle(_)), "{objs:?}");
}
}
#[test]
fn enter_ends_breakatpoint_and_leaves_nothing_selected() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
s.script("BREAKATPOINT\n\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
// Enter at the break point after picking: the line is not left selected.
s.script("BREAKATPOINT 5,0\n\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!(s.selection().is_empty());
assert_eq!(objects(&s).len(), 1);
}
#[test]
fn an_object_on_a_locked_layer_is_refused_when_picked() {
let mut s = Session::new();
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
s.execute("layer.set", &json!({ "name": "0", "locked": true })).unwrap();
for cmd in ["BREAKATPOINT", "BREAK"] {
s.cmdline(cmd).unwrap();
s.cmdline("5,0").unwrap();
assert!(s.prompt_text().ends_with("Select object:"), "{cmd}: {}", s.prompt_text());
assert!(s.log.iter().any(|l| l == "The object is on a locked layer."), "{cmd}: {:?}", s.log);
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{cmd}: {}", s.prompt_text());
}
assert_eq!(objects(&s).len(), 1);
}
#[test]
fn breakatpoint_from_lisp_with_a_bare_entity_name() {
let mut s = Session::new();
let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap());
s.cmdline("(command \"_.BREAKATPOINT\" (entlast) '(1004.0 0.0))").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let objs = objects(&s);
assert_eq!(objs.len(), 2);
assert_eq!(objs[0].0, l);
assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1004.0, 0.0)));
}
#[test]
fn breakatpoint_from_lisp_with_an_entity_and_point() {
let mut s = Session::new();
let l = handle(&s.execute("line", &json!({ "points": [[1000, 0], [1010, 0]] })).unwrap());
s.cmdline("(command \"_.BREAKATPOINT\" (list (entlast) '(1005.0 0.0)) '(1005.0 0.0))").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let objs = objects(&s);
assert_eq!(objs.len(), 2);
assert_eq!(objs[0].0, l);
assert_eq!(line_ends(&objs[0].1), ((1000.0, 0.0), (1005.0, 0.0)));
}
@@ -0,0 +1,187 @@
//! Which end of an open polyline EXTEND runs on, as AutoCAD 2024 chooses it (measured with
//! accoreconsole on these drawings): the end on the pick's side of the polyline's middle parameter.
//! The pick's parameter is the segment it is nearest, counted from 0, plus how far along that
//! segment it is; from half the number of segments on, the last end extends, below it the first.
//! Neither the end vertex nearer the pick nor the length along the polyline decides.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Handle};
use serde_json::{Value, json};
type Vertex = (f64, f64, f64);
fn handle(v: &Value) -> String {
v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_owned()
}
/// The open polyline `vertices` with lines `edges`, extended at `pick` to the lines; its vertices
/// with their bulges.
fn extended(vertices: &[Vertex], edges: &[([f64; 2], [f64; 2])], pick: [f64; 2]) -> Vec<Vertex> {
let mut s = Session::new();
let vs: Vec<Value> = vertices.iter().map(|(x, y, b)| json!({ "p": [x, y], "bulge": b })).collect();
let p = handle(&s.execute("pline", &json!({ "vertices": vs, "closed": false })).unwrap());
let es: Vec<String> = edges.iter().map(|(a, b)| handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap())).collect();
s.execute("extend", &json!({ "handle": p, "pick": pick, "edges": es })).unwrap();
match &s.doc().unwrap().entity(Handle::parse_hex(&p).unwrap()).unwrap().kind {
EntityKind::LwPolyline(l) => l.vertices.iter().map(|v| (v.p.x, v.p.y, v.bulge)).collect(),
k => panic!("{k:?}"),
}
}
fn same(got: &[Vertex], want: &[Vertex]) -> bool {
got.len() == want.len() && got.iter().zip(want).all(|(g, w)| (g.0 - w.0).abs() < 1e-6 && (g.1 - w.1).abs() < 1e-6 && (g.2 - w.2).abs() < 1e-6)
}
/// Vertical lines through x = `xs`, from `y0` to `y1`.
fn at(xs: &[f64], y0: f64, y1: f64) -> Vec<([f64; 2], [f64; 2])> {
xs.iter().map(|x| ([*x, y0], [*x, y1])).collect()
}
fn flat(pts: &[(f64, f64)]) -> Vec<Vertex> {
pts.iter().map(|(x, y)| (*x, *y, 0.0)).collect()
}
#[test]
fn the_end_on_the_picks_side_of_the_middle_parameter_extends() {
// (name, vertices, edges, pick, the vertices AutoCAD leaves). Lines at both ends, so either
// end could extend.
let cases: Vec<(&str, Vec<Vertex>, Vec<([f64; 2], [f64; 2])>, [f64; 2], Vec<(f64, f64)>)> = vec![
// 1.2 of 3 segments: the first end, though the pick is on a vertex of the middle one.
(
"1.2 of 3",
flat(&[(0.0, 160.0), (10.0, 160.0), (10.0, 165.0), (20.0, 165.0)]),
at(&[-5.0, 25.0], 155.0, 170.0),
[10.0, 161.0],
vec![(-5.0, 160.0), (10.0, 160.0), (10.0, 165.0), (20.0, 165.0)],
),
// 0.8: the first end, though the last vertex is nearer the pick.
(
"0.8, last vertex nearer",
flat(&[(0.0, 220.0), (20.0, 220.0), (20.0, 230.0), (15.0, 221.0)]),
vec![([-5.0, 215.0], [-5.0, 235.0]), ([0.0, 210.0], [30.0, 210.0])],
[16.0, 220.0],
vec![(-5.0, 220.0), (20.0, 220.0), (20.0, 230.0), (15.0, 221.0)],
),
(
"0.2",
flat(&[(0.0, 240.0), (20.0, 240.0), (20.0, 250.0), (5.0, 241.0)]),
vec![([-5.0, 235.0], [-5.0, 255.0]), ([-10.0, 230.0], [30.0, 230.0])],
[4.0, 240.0],
vec![(-5.0, 240.0), (20.0, 240.0), (20.0, 250.0), (5.0, 241.0)],
),
(
"1.9",
flat(&[(0.0, 260.0), (2.0, 260.0), (2.0, 280.0), (4.0, 280.0)]),
at(&[-5.0, 10.0], 255.0, 285.0),
[2.0, 278.0],
vec![(0.0, 260.0), (2.0, 260.0), (2.0, 280.0), (10.0, 280.0)],
),
// 0.9: the first end, though 18 of the 22 units along is nearer the last.
(
"0.9, length nearer the last",
flat(&[(0.0, 300.0), (20.0, 300.0), (20.0, 301.0), (21.0, 301.0)]),
at(&[-5.0, 25.0], 295.0, 305.0),
[18.0, 300.0],
vec![(-5.0, 300.0), (20.0, 300.0), (20.0, 301.0), (21.0, 301.0)],
),
(
"1.1",
flat(&[(0.0, 320.0), (2.0, 320.0), (2.0, 340.0), (4.0, 340.0)]),
at(&[-5.0, 10.0], 315.0, 345.0),
[2.0, 322.0],
vec![(-5.0, 320.0), (2.0, 320.0), (2.0, 340.0), (4.0, 340.0)],
),
(
"1.25",
flat(&[(0.0, 400.0), (30.0, 400.0), (30.0, 420.0), (31.0, 420.0)]),
at(&[-5.0, 40.0], 395.0, 425.0),
[30.0, 405.0],
vec![(-5.0, 400.0), (30.0, 400.0), (30.0, 420.0), (31.0, 420.0)],
),
(
"1.75",
flat(&[(0.0, 440.0), (1.0, 440.0), (1.0, 460.0), (31.0, 460.0)]),
at(&[-5.0, 40.0], 435.0, 465.0),
[1.0, 455.0],
vec![(0.0, 440.0), (1.0, 440.0), (1.0, 460.0), (40.0, 460.0)],
),
("0.6 of 1", flat(&[(0.0, 480.0), (20.0, 480.0)]), at(&[-5.0, 25.0], 475.0, 485.0), [12.0, 480.0], vec![(0.0, 480.0), (25.0, 480.0)]),
// 1.8 of 4, the end of the segment picked: the first end.
(
"1.8 of 4",
flat(&[(0.0, 500.0), (10.0, 500.0), (10.0, 510.0), (20.0, 510.0), (20.0, 520.0)]),
vec![([-5.0, 495.0], [-5.0, 525.0]), ([15.0, 530.0], [25.0, 530.0])],
[10.0, 508.0],
vec![(-5.0, 500.0), (10.0, 500.0), (10.0, 510.0), (20.0, 510.0), (20.0, 520.0)],
),
(
"2.8 of 4",
flat(&[(0.0, 540.0), (10.0, 540.0), (10.0, 550.0), (20.0, 550.0), (20.0, 560.0)]),
vec![([-5.0, 535.0], [-5.0, 565.0]), ([15.0, 570.0], [25.0, 570.0])],
[18.0, 550.0],
vec![(0.0, 540.0), (10.0, 540.0), (10.0, 550.0), (20.0, 550.0), (20.0, 570.0)],
),
// Right on the middle parameter, 1.5 of 3: the last end.
(
"1.5 of 3",
flat(&[(0.0, 600.0), (10.0, 600.0), (10.0, 610.0), (20.0, 610.0)]),
at(&[-5.0, 25.0], 595.0, 615.0),
[10.0, 605.0],
vec![(0.0, 600.0), (10.0, 600.0), (10.0, 610.0), (25.0, 610.0)],
),
];
for (name, vertices, edges, pick, want) in cases {
let got = extended(&vertices, &edges, pick);
assert!(same(&got, &flat(&want)), "{name}: {got:?}");
}
}
#[test]
fn the_parameter_runs_along_an_arc_segment_too() {
// The middle segment an arc of bulge -18, swinging round to within 2 of the first vertex:
// picked 60% along it (1.6 of 3), 3.6 from the first vertex and 18.3 from the last, the last
// end extends.
let got = extended(
&[(0.0, 0.0, 0.0), (10.0, 0.0, -18.0), (10.0, 1.0, 0.0), (20.0, 1.0, 0.0)],
&at(&[-5.0, 25.0], -10.0, 10.0),
[1.804081304825758, 3.0714821777453793],
);
assert!(same(&got, &[(0.0, 0.0, 0.0), (10.0, 0.0, -18.0), (10.0, 1.0, 0.0), (25.0, 1.0, 0.0)]), "{got:?}");
// The end segment an arc of bulge -0.5: picked on it (1.6 of 2) the last end runs on round
// its circle to x = 14.3; the same polyline turned round, picked on its first segment (0.4),
// the first end does.
let got = extended(&[(0.0, 40.0, 0.0), (10.0, 40.0, -0.5), (14.0, 40.0, 0.0)], &at(&[14.3], 30.0, 50.0), [12.0, 41.0]);
assert!(same(&got, &[(0.0, 40.0, 0.0), (10.0, 40.0, -0.5776771824075506), (14.3, 39.47979589711327, 0.0)]), "{got:?}");
let got = extended(&[(0.0, 60.0, -0.5), (4.0, 60.0, 0.0), (14.0, 60.0, 0.0)], &at(&[-0.3], 50.0, 70.0), [2.0, 61.0]);
assert!(same(&got, &[(-0.3, 59.47979589711327, -0.5776771824075504), (4.0, 60.0, 0.0), (14.0, 60.0, 0.0)]), "{got:?}");
}
#[test]
fn a_repeated_vertex_counts_as_a_segment() {
// (10, 0) twice: three segments, the middle one of no length. Picked on (10, 0), the end of
// the first, 1.0 of 3: the first end extends (counting two segments it would be the last).
// Picked 1 up the last segment, 2.1 of 3: the last end.
let vs = flat(&[(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 10.0)]);
let edges = vec![([-5.0, -10.0], [-5.0, 10.0]), ([-10.0, 15.0], [20.0, 15.0])];
let got = extended(&vs, &edges, [10.0, 0.0]);
assert!(same(&got, &flat(&[(-5.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 10.0)])), "{got:?}");
let got = extended(&vs, &edges, [10.0, 1.0]);
assert!(same(&got, &flat(&[(0.0, 0.0), (10.0, 0.0), (10.0, 0.0), (10.0, 15.0)])), "{got:?}");
}
#[test]
fn a_pick_a_hair_outside_an_arc_end_counts_as_that_end() {
// A single semicircle from (1, 0) to (-1, 0). Picked 1e-13 outside its sweep at the first
// vertex, the pick is on the arc's start, not round the circle at its end: the first end runs
// on to x = 0, three quarters of the way round.
let b = 1.0 + 2f64.sqrt();
let got = extended(&[(1.0, 0.0, 1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], -2.0, -0.5), [1.0, -1e-13]);
assert!(same(&got, &[(0.0, -1.0, b), (-1.0, 0.0, 0.0)]), "{got:?}");
// A hair past its end is the last end.
let got = extended(&[(1.0, 0.0, 1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], -2.0, -0.5), [-1.0, -1e-13]);
assert!(same(&got, &[(1.0, 0.0, b), (0.0, -1.0, 0.0)]), "{got:?}");
// Turning clockwise, the arc's start angle is the polyline's last vertex: a hair outside it is
// the last end.
let got = extended(&[(1.0, 0.0, -1.0), (-1.0, 0.0, 0.0)], &at(&[0.0], 0.5, 2.0), [-1.0, 1e-13]);
assert!(same(&got, &[(1.0, 0.0, -b), (0.0, 1.0, 0.0)]), "{got:?}");
}
@@ -1,247 +0,0 @@
//! -LAYER stAte: AutoCAD 2024's layer state prompts and messages (measured with accoreconsole on a
//! drawing with layers A, red, and B), and the `layerstate.*` commands they run.
use cadcraft_engine::doc::LayerState;
use cadcraft_engine::{Input, Session};
use serde_json::json;
const LABELS: [&str; 10] = ["On", "Frozen", "Lock", "Plot", "Newvpfreeze", "Color", "lineType", "lineWeight", "Transparency", "plotStyle"];
/// The toggles AutoCAD lists before "Enter states to change", with `no` the ones set to No.
fn table(no: &[&str]) -> Vec<String> {
let mut v = vec!["States".to_string()];
v.extend(LABELS.iter().map(|l| format!("{l:<20}{}", if no.contains(l) { "No" } else { "Yes" })));
v
}
/// Layers A (red) and B; the current layer stays 0.
fn drawing() -> Session {
let mut s = Session::new();
s.script("-LAYER N A,B C 1 A\n\n").unwrap();
s
}
/// Run `script` to its end and return what it wrote besides the commands' names and -LAYER's
/// "Current layer" line.
fn run(s: &mut Session, script: &str) -> Vec<String> {
let at = s.log.len();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script:?} ends at: {}", s.prompt_text());
s.log[at..].iter().filter(|l| !l.starts_with("Command: ") && !l.starts_with("Current layer:")).cloned().collect()
}
fn states(s: &Session) -> Vec<(String, u32)> {
s.doc().unwrap().layer_states.iter().map(|st| (st.name.clone(), st.mask)).collect()
}
fn state(name: &str, mask: u32) -> (String, u32) {
(name.to_string(), mask)
}
#[test]
fn save_asks_the_states_and_remembers_them_for_the_next_save() {
let mut s = drawing();
// Each toggle lists the states again; On off is AutoCAD's 2046.
let out = run(&mut s, "-LAYER A S S6 ON\n\n\n\nLINE 0,0 1,0\n\n");
assert_eq!(out, [table(&[]), table(&["On"])].concat());
assert_eq!(states(&s), [state("S6", 2046)]);
assert_eq!(s.doc().unwrap().model.len(), 1, "the next command runs");
// The next Save starts from the toggles the last one left: On alone is 513, then every
// toggle once more is 2046 (AutoCAD's S7 and S8).
let out = run(&mut s, "-LAYER A S S7 ON F L P N C T W TR S\n\n\n\n");
assert_eq!(out[..11], table(&["On"]));
assert_eq!(
out[out.len() - 11..],
table(&["Frozen", "Lock", "Plot", "Newvpfreeze", "Color", "lineType", "lineWeight", "Transparency", "plotStyle"])
);
run(&mut s, "-LAYER A S S8 ON F L P N C T W TR S\n\n\n\n");
run(&mut s, "-LAYER A S S9 ON\n\n\n\n");
assert_eq!(states(&s)[1..], [state("S7", 513), state("S8", 2046), state("S9", LayerState::ALL)]);
// Edit lists and changes the state's own mask (found in any case), not the next Save's
// toggles (AutoCAD: Edit S1 to 2015, then S2 is 2047).
let out = run(&mut s, "-LAYER A E s6 ON C\n\n\n\n");
assert_eq!(out, [table(&["On"]), table(&[]), table(&["Color"])].concat());
run(&mut s, "-LAYER A S S10\n\n\n\n");
assert_eq!(states(&s)[0], state("S6", 2015));
assert_eq!(states(&s)[4], state("S10", LayerState::ALL));
// Each -LAYER is one undo step.
s.undo().unwrap();
assert_eq!(states(&s).len(), 4);
s.undo().unwrap();
assert_eq!(states(&s)[0], state("S6", 2046));
// A state from AutoCAD after a restore (mask 67583 = 2047 + 65536) named as AutoCAD names a
// state renamed to "*X": `?` lists it, and Edit keeps the bit no toggle reaches.
s.doc_mut().unwrap().layer_states.push(LayerState { name: "*A1".into(), mask: 67583, ..LayerState::default() });
assert_eq!(
run(
&mut s,
"-LAYER A ?
"
)[2],
"*A1"
);
run(
&mut s,
"-LAYER A E *a1 C
",
);
assert_eq!(states(&s)[4], state("*A1", 67583 - 32));
}
#[test]
fn names_follow_autocads_rules_and_messages() {
let mut s = drawing();
run(&mut s, "-LAYER A S S1\n\n\n\n");
// A saved name in another case is refused and asked again.
let out = run(&mut s, "-LAYER A S s1 S2\n\n\n\n");
assert_eq!(out, [vec!["Layer state \"s1\" already exists.".to_string()], table(&[])].concat());
// The layer name characters, and more than 255 characters, are refused; Enter goes back.
let long = "y".repeat(256);
let out = run(&mut s, &format!("-LAYER A S *X a<b a,b {long}\n\n\n\n"));
assert_eq!(
out,
[
"\"*X\" is an invalid layer state name.",
"\"a<b\" is an invalid layer state name.",
"\"a,b\" is an invalid layer state name.",
&format!("\"{long}\" is an invalid layer state name.")
]
);
run(&mut s, &format!("-LAYER A S {}\n\n\n\n", "x".repeat(255)));
assert_eq!(states(&s).len(), 3);
run(&mut s, &format!("-LAYER A D {}\n\n\n", "x".repeat(255)));
// `?` lists by name without regard to case.
run(&mut s, "-LAYER A S b\n\n\n\n");
let list = ["Layer state", "-----------------------------", "b", "S1", "S2"];
assert_eq!(run(&mut s, "-LAYER A ?\n\n\n"), list);
// Each name prompt lists on `?`, says an unknown name and asks again, and Enter goes back.
let out = run(&mut s, "-LAYER A R ? NOSUCH\n\nE NOSUCH\n\nN NOSUCH\n\nD NOSUCH\n\n\n\n");
assert_eq!(out[..5], list);
assert_eq!(out[5..], ["Unknown layer state name."; 4]);
// Unknown options, Import and EXport.
let out = run(&mut s, "-LAYER A XYZ I EX\n\n\n");
assert_eq!(out, ["Invalid option keyword.", "-LAYER stAte Import is not available yet.", "-LAYER stAte EXport is not available yet."]);
let out = run(&mut s, "-LAYER A S T1 XYZ\n\n\n\n");
assert_eq!(out, [table(&[]), vec!["Invalid option keyword.".to_string()]].concat());
assert_eq!(states(&s).len(), 4, "T1 is saved after the invalid toggle");
run(&mut s, "-LAYER A D T1\n\n\n");
// Name: a name some state has in any case, the state's own too, is refused with two lines.
assert_eq!(run(&mut s, "-LAYER A N S1 S2\n\n\n"), ["Layer state could not be renamed.", "S2 already exists."]);
assert_eq!(run(&mut s, "-LAYER A N S1 s1\n\n\n"), ["Layer state could not be renamed.", "s1 already exists."]);
// A name with a refused character leaves the state as it is, with no message; Enter too.
assert!(run(&mut s, "-LAYER A N S1 a,b\n\n\n").is_empty());
assert!(run(&mut s, "-LAYER A N S1\n\n\n\n").is_empty());
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S1", "S2", "b"]);
// The old name in another case.
assert!(run(&mut s, "-LAYER A N s1 S9\n\n\n").is_empty());
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S9", "S2", "b"]);
assert!(run(&mut s, "-LAYER A D s9\n\n\n").is_empty());
assert_eq!(states(&s).iter().map(|st| st.0.as_str()).collect::<Vec<_>>(), ["S2", "b"]);
}
#[test]
fn esc_drops_the_state_being_saved_and_undo_takes_back_name_and_delete() {
let mut s = drawing();
run(
&mut s,
"-LAYER A S S1
",
);
// Esc at the toggles: that state isn't saved and the next Save's toggles stay as they were;
// what the same -LAYER did before Esc stays, as for the other -LAYER options.
s.script(
"-LAYER A S S2
S S3 C ON
",
)
.unwrap();
// AutoCAD 2024 asks for the toggles without "or" before them.
assert_eq!(
s.current_prompt().unwrap().display(),
"Enter states to change [On/Frozen/Lock/Plot/Newvpfreeze/Color/lineType/lineWeight/TRansparency/plotStyle]:"
);
s.input(Input::Cancel).unwrap();
assert!(s.running.is_none());
assert_eq!(states(&s), [state("S1", LayerState::ALL), state("S2", LayerState::ALL)]);
assert_eq!(s.settings.layer_state_mask, LayerState::ALL);
// Name and Delete are one undo step each, like Save.
run(
&mut s,
"-LAYER A N S1 S9
",
);
run(
&mut s,
"-LAYER A D S2
",
);
assert_eq!(states(&s), [state("S9", LayerState::ALL)]);
s.undo().unwrap();
assert_eq!(states(&s), [state("S9", LayerState::ALL), state("S2", LayerState::ALL)]);
s.undo().unwrap();
assert_eq!(states(&s), [state("S1", LayerState::ALL), state("S2", LayerState::ALL)]);
}
#[test]
fn restore_finds_the_state_in_any_case() {
let mut s = drawing();
run(&mut s, "-LAYER A S S1\n\n\n\n");
run(&mut s, "-LAYER C 3 A M C\n\n");
let d = s.doc().unwrap();
assert_eq!((d.layer("A").unwrap().color, d.header.str("CLAYER", "0")), (cadcraft_color::Color::Index(3), "C".to_string()));
assert!(run(&mut s, "-LAYER A R s1\n\n\n").is_empty());
let d = s.doc().unwrap();
assert_eq!((d.layer("A").unwrap().color, d.header.str("CLAYER", "0")), (cadcraft_color::Color::Index(1), "0".to_string()));
}
#[test]
fn json_layer_states_take_a_mask_and_find_names_in_any_case() {
let mut s = drawing();
s.execute("layerstate.save", &json!({ "name": "M" })).unwrap();
s.execute("layerstate.save", &json!({ "name": "On", "mask": LayerState::ON })).unwrap();
for bad in [json!(4096), json!(-1), json!(1.5), json!("1")] {
assert!(s.execute("layerstate.save", &json!({ "name": "X", "mask": bad })).is_err(), "{bad}");
}
assert_eq!(states(&s), [state("M", LayerState::ALL), state("On", 513)]);
// Restore, Rename and Delete find a name in another case; a name another state has in any
// case is refused, the state's own in another case too.
s.execute("layer.set", &json!({ "name": "A", "color": "3" })).unwrap();
s.execute("layerstate.restore", &json!({ "name": "m" })).unwrap();
assert_eq!(s.doc().unwrap().layer("A").unwrap().color, cadcraft_color::Color::Index(1));
assert!(s.execute("layerstate.rename", &json!({ "from": "m", "to": "ON" })).is_err());
assert!(s.execute("layerstate.rename", &json!({ "from": "m", "to": "m" })).is_err());
s.execute("layerstate.rename", &json!({ "from": "m", "to": "M2" })).unwrap();
s.execute("layerstate.delete", &json!({ "name": "on" })).unwrap();
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
// A name -LAYER stAte Save refuses is refused here too, and nothing is saved.
let long = "x".repeat(256);
for name in ["", " ", "a<b", "a\nb", long.as_str()] {
assert!(s.execute("layerstate.save", &json!({ "name": name })).is_err(), "{name:?}");
}
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
// Save onto a name another state has in another case replaces that state, as one spelled the
// same: AutoCAD 2024 keeps one state per name in any case.
s.execute("layerstate.save", &json!({ "name": "m2", "mask": LayerState::ON })).unwrap();
assert_eq!(states(&s), [state("m2", 513)]);
// Names that differ only in case (CADCraft's own record keeps the second of them, which AutoCAD
// 2024 doesn't see): Save and Delete take the one spelled so, though the other comes first, and
// leave the other.
s.doc_mut().unwrap().layer_states.insert(0, LayerState::new("M2", Vec::new(), ""));
s.execute("layerstate.save", &json!({ "name": "m2", "mask": LayerState::ON | LayerState::FROZEN })).unwrap();
assert_eq!(states(&s), [state("M2", LayerState::ALL), state("m2", 515)]);
s.execute("layerstate.delete", &json!({ "name": "m2" })).unwrap();
assert_eq!(states(&s), [state("M2", LayerState::ALL)]);
}
+8 -2
View File
@@ -4,7 +4,6 @@ mod annotate_options;
mod annotative;
mod arc_ctrl_direction;
mod array_commands;
mod array_key_point;
mod assoc_array;
mod attdef_command;
mod attdisp_attsync;
@@ -18,9 +17,12 @@ mod block_keep;
mod block_redefine;
mod blockreplace;
mod break_closed_polyline;
mod break_ends_and_closing_side;
mod break_join_locked_layers;
mod break_keeps_z;
mod break_trim_keep_handle;
mod break_trim_polyline_rules;
mod breakatpoint_command_line;
mod burst;
mod change_command;
mod chprop_command;
@@ -53,6 +55,7 @@ mod dynamic_block_data;
mod dynamic_grips;
mod explode_stretched;
mod extend_polyline_arc_end;
mod extend_polyline_end_choice;
mod fillet_chamfer;
mod fix_holds_grips;
mod followups_626;
@@ -79,7 +82,6 @@ mod join_close;
mod json_param_validation;
mod layer_cmdline;
mod layer_merge_delete;
mod layer_state_cmdline;
mod layoff_repeat;
mod layout_prompts;
mod leader_command;
@@ -172,7 +174,11 @@ mod text_left_justify;
mod tolerance;
mod transparent;
mod trim_closed_polyline;
mod trim_cut_at_the_pick;
mod trim_cut_where_an_arc_span_starts;
mod trim_extend_json_pick;
mod trim_extend_options;
mod trim_keeps_z_and_width;
mod undo_count;
mod undo_layout_tab;
mod viewport_clip;
+7 -129
View File
@@ -76,135 +76,13 @@ fn rename_prompts_type_old_and_new_name() {
assert!(d.block("Pump").is_some() && d.layer("New").is_some() && d.layer("Old").is_none(), "{:?}", s.log);
assert_eq!(insert_targets(d), ["Assy", "Pump", "Pump", "Pump"]);
assert_eq!(d.model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 1);
// A type CADCraft lacks reads both names and reports.
let n = s.log.len();
s.script("-RENAME M a b\nLINE 0,0 2,0\n\n").unwrap();
// An unknown old name re-prompts; a type CADCraft lacks reads both names and reports.
s.script("-RENAME LA Missing\nNew\nNewer\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!(s.log[n..].iter().any(|l| l.contains("Renaming a material is not available yet.")), "{:?}", &s.log[n..]);
assert!(s.doc().unwrap().layer("Newer").is_some());
let n = s.log.len();
s.script("-RENAME VP a b\nLINE 0,0 2,0\n\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert!(s.log[n..].iter().any(|l| l.contains("not available yet")), "{:?}", &s.log[n..]);
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 2);
}
/// What `script` adds to the log; the command has ended.
fn said(s: &mut Session, script: &str) -> Vec<String> {
let n = s.log.len();
s.script(script).unwrap();
assert!(s.running.is_none(), "{script}: {}", s.prompt_text());
s.log[n..].to_vec()
}
fn says(log: &[String], text: &str) -> bool {
log.iter().any(|l| l.contains(text))
}
#[test]
fn rename_ends_on_a_name_it_cannot_take_with_autocads_messages() {
// AutoCAD 2024 (accoreconsole, measured, the same for blocks, dimension styles, layers,
// linetypes, text styles, UCSs and views): `Cannot find layer "X".` for an old name that
// doesn't exist, `A layer named "X" already exists.` and `*Invalid*` for a new name that does,
// `Invalid layer name.` for one it can't take; each ends the command.
let mut s = drawing();
for name in ["A1", "A2"] {
s.execute("layer.new", &json!({ "name": name })).unwrap();
}
let log = said(&mut s, "-RENAME LA NOSUCH\nLINE 0,0 3,0\n\n");
assert!(says(&log, "Cannot find layer \"NOSUCH\"."), "{log:?}");
// The command ended there: the next input started LINE.
assert_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 1);
let log = said(&mut s, "-RENAME LA A1 A2\n");
assert!(says(&log, "A layer named \"A2\" already exists.") && says(&log, "*Invalid*"), "{log:?}");
let log = said(&mut s, "-RENAME LA A1 X<Y\n");
assert!(says(&log, "Invalid layer name."), "{log:?}");
// No new name at all is an invalid one too.
s.cmdline("-RENAME LA A1").unwrap();
let n = s.log.len();
s.cmdline("").unwrap();
assert!(s.running.is_none() && says(&s.log[n..], "Invalid layer name."), "{:?}", &s.log[n..]);
assert!(s.doc().unwrap().layer("A1").is_some());
said(&mut s, "-RENAME LA A1 B1\n");
assert!(s.doc().unwrap().layer("B1").is_some() && s.doc().unwrap().layer("A1").is_none());
// The old name in another case than stored, and the new name as typed: a rename to that case
// (AutoCAD 2024, measured: LAY1 typed lay1, new name lay1, gives lay1).
said(&mut s, "-RENAME LA b1 b1\n");
assert!(s.doc().unwrap().layers.iter().any(|l| l.name == "b1"));
// Old names AutoCAD 2024 won't rename (measured), each ending the command before the new name.
let lines = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count();
for (script, message) in [
("-RENAME LA 0\n", "Cannot rename layer \"0\"."),
("-RENAME LT continuous\n", "Cannot rename linetype \"continuous\"."),
("-RENAME LT ByLayer\n", "Invalid linetype name."),
("-RENAME LT byblock\n", "Invalid linetype name."),
("-RENAME LT CONTINUOUS\n", "Cannot rename linetype \"CONTINUOUS\"."),
("-RENAME B *Model_Space\n", "Invalid block name."),
("-RENAME B *U1\n", "Invalid block name."),
] {
let n = lines(&s);
let log = said(&mut s, &format!("{script}LINE 0,0 4,0\n\n"));
assert!(says(&log, message), "{script}: {log:?}");
assert_eq!(says(&log, "*Invalid*"), message.starts_with("Cannot"), "{script}: {log:?}");
assert_eq!(lines(&s), n + 1, "{script}: the next input starts a command");
}
// A UCS is "ucs" in the prompts and in "A ucs named", "UCS" in the other two.
for name in ["U1", "U2"] {
let ucs = cadcraft_engine::doc::Ucs { name: name.into(), origin: Default::default(), x_axis: Default::default(), y_axis: Default::default() };
s.doc_mut().unwrap().ucss.push(ucs);
}
s.cmdline("-RENAME U").unwrap();
assert!(s.prompt_text().contains("Enter old ucs name"), "{}", s.prompt_text());
s.cancel();
assert!(says(&said(&mut s, "-RENAME U NOSUCH\n"), "Cannot find UCS \"NOSUCH\"."));
assert!(says(&said(&mut s, "-RENAME U U1 U2\n"), "A ucs named \"U2\" already exists."));
assert!(says(&said(&mut s, "-RENAME U U1 X<Y\n"), "Invalid UCS name."));
}
#[test]
fn rename_takes_a_saved_viewport_configuration() {
// AutoCAD 2024 (measured): -RENAME VPort renames a saved configuration, every tile of it, old
// name in any case, and to another case of its own name; "*ACTIVE" (old or new), names with
// characters AutoCAD refuses and names already used are refused as for the other types.
let mut s = Session::new();
s.execute("-vports", &json!({ "option": "2", "arrangement": "vertical" })).unwrap();
s.execute("-vports", &json!({ "option": "save", "name": "CFG1" })).unwrap();
s.execute("-vports", &json!({ "option": "save", "name": "CFG3" })).unwrap();
let names = |s: &Session| -> Vec<(String, usize)> { s.doc().unwrap().vports.iter().map(|v| (v.name.clone(), v.tiles.len())).collect() };
said(&mut s, "-RENAME VP cfg1 CFG2\n");
assert_eq!(names(&s), [("*Active".to_string(), 2), ("CFG2".to_string(), 2), ("CFG3".to_string(), 2)]);
for (script, message) in [
// A refused old name ends the command before the new name is asked.
("-RENAME VP NOSUCH\n", "Cannot find viewport configuration \"NOSUCH\"."),
("-RENAME VP *ACTIVE\n", "Invalid viewport configuration name."),
("-RENAME VP CFG2 *ACTIVE\n", "Invalid viewport configuration name."),
("-RENAME VP CFG2 A<B\n", "Invalid viewport configuration name."),
("-RENAME VP CFG2 CFG3\n", "A viewport configuration named \"CFG3\" already exists."),
] {
let log = said(&mut s, script);
assert!(says(&log, message), "{script}: {log:?}");
// "*Invalid*" follows a name already used only.
assert_eq!(says(&log, "*Invalid*"), message.ends_with("already exists."), "{script}: {log:?}");
}
// No new name at all is an invalid one too (measured: CFG1, then Enter).
s.cmdline("-RENAME VP CFG2").unwrap();
let n = s.log.len();
s.cmdline("").unwrap();
assert!(s.running.is_none() && says(&s.log[n..], "Invalid viewport configuration name."), "{:?}", &s.log[n..]);
assert_eq!(names(&s), [("*Active".to_string(), 2), ("CFG2".to_string(), 2), ("CFG3".to_string(), 2)]);
said(&mut s, "-RENAME VP CFG2 cfg2\n");
assert_eq!(names(&s), [("*Active".to_string(), 2), ("cfg2".to_string(), 2), ("CFG3".to_string(), 2)]);
// The new name is compared with the stored one, not with the old name as typed (measured:
// CFG1 typed cfg1 to cfg1 gives cfg1; typed cfg1 to CFG1 changes nothing).
said(&mut s, "-RENAME VP CFG2 CFG2\n");
assert_eq!(names(&s)[1].0, "CFG2");
said(&mut s, "-RENAME VP cfg2 CFG2\n");
assert_eq!(names(&s)[1].0, "CFG2");
said(&mut s, "-RENAME VP cfg2 cfg2\n");
assert_eq!(names(&s)[1].0, "cfg2");
// The JSON form too, which never takes the configuration shown, and refuses a name already
// used (in any case) or with a character AutoCAD refuses, as for the other tables.
s.execute("rename", &json!({ "table": "vport", "from": "CFG3", "to": "Pair" })).unwrap();
assert_eq!(names(&s)[2].0, "Pair");
for to in ["Shown", "CFG2", "A<B"] {
let from = if to == "Shown" { "*Active" } else { "Pair" };
assert!(s.execute("rename", &json!({ "table": "vport", "from": from, "to": to })).is_err(), "{from} to {to}");
}
s.execute("rename", &json!({ "table": "vport", "from": "pair", "to": "PAIR" })).unwrap();
assert_eq!(names(&s), [("*Active".to_string(), 2), ("cfg2".to_string(), 2), ("PAIR".to_string(), 2)]);
}
@@ -123,11 +123,13 @@ fn undo_restores_the_closed_polyline() {
}
#[test]
fn a_single_cut_still_opens_the_outline_there() {
fn a_single_cut_leaves_the_outline_as_it_was() {
// As AutoCAD 2024 does (measured with accoreconsole on a 100 x 10 rectangle cut once on its
// bottom): it refuses, "Curve must intersect cutting edges at least twice."
let mut s = Session::new();
let p = handle(s.execute("pline", &json!({ "vertices": square(), "closed": true })).unwrap());
let cutter = handle(s.execute("line", &json!({ "points": [[2, -1], [2, 1]] })).unwrap());
s.execute("trim", &json!({ "handle": p, "pick": [0, 2], "edges": [cutter] })).unwrap();
let all = [(2.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 4.0, 0.0), (0.0, 4.0, 0.0), (0.0, 0.0, 0.0), (2.0, 0.0, 0.0)];
assert_eq!(polys(&s), vec![(false, all.to_vec())]);
let r = s.execute("trim", &json!({ "handle": p, "pick": [0, 2], "edges": [cutter] }));
assert!(r.is_err_and(|e| e.to_string() == "Curve must intersect cutting edges at least twice."));
assert_eq!(polys(&s), vec![(true, vec![(0.0, 0.0, 0.0), (4.0, 0.0, 0.0), (4.0, 4.0, 0.0), (0.0, 4.0, 0.0)])]);
}
@@ -0,0 +1,171 @@
//! TRIM of a line, an arc or a circle picked on a cut, as AutoCAD 2024 does it (measured with
//! accoreconsole on these drawings): a cut within 5e-7 of the pick, along the object, is passed
//! over, and the piece runs on across it to the next cut either side. With no cut left, nothing is
//! trimmed.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Handle};
use serde_json::{Value, json};
fn handle(v: &Value) -> Handle {
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
}
/// Vertical lines through x = `xs`, from y = -15 to 15; their handles.
fn edges(s: &mut Session, xs: &[f64]) -> Vec<String> {
xs.iter().map(|x| handle(&s.execute("line", &json!({ "points": [[x, -15], [x, 15]] })).unwrap()).hex()).collect()
}
/// Every object but the edges: lines as their ends, arcs and circles as their angles in degrees.
fn shapes(s: &Session, edges: &[String]) -> Vec<(Handle, Vec<f64>)> {
let r = |v: f64| (v * 1e9).round() / 1e9;
s.doc()
.unwrap()
.model
.iter()
.filter(|e| !edges.contains(&e.handle.hex()))
.map(|e| {
let v = match &e.kind {
EntityKind::Line(l) => vec![l.a.x, l.a.y, l.b.x, l.b.y],
EntityKind::Arc(a) => vec![a.start.to_degrees(), a.end.to_degrees()],
EntityKind::Circle(_) => Vec::new(),
k => panic!("{k:?}"),
};
(e.handle, v.into_iter().map(r).collect())
})
.collect()
}
/// Trim `h` at `pick` with `edges`: whether the trim was made.
fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edges: &[String]) -> bool {
s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "edges": edges })).is_ok()
}
/// A line from (0, 0) to (10, 0) with vertical lines through `xs`, trimmed at `pick`.
fn line_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec<f64>)>, Handle) {
let mut s = Session::new();
let h = handle(&s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap());
let es = edges(&mut s, xs);
let made = trim(&mut s, h, pick, &es);
(made, shapes(&s, &es), h)
}
#[test]
fn a_line_picked_on_its_only_cut_is_left_as_it_was() {
for pick in [[5.0, 0.0], [5.0000004, 0.0], [4.9999996, 0.0]] {
let (made, got, h) = line_trimmed(&[5.0], pick);
assert!(!made, "{pick:?}");
assert_eq!(got, vec![(h, vec![0.0, 0.0, 10.0, 0.0])], "{pick:?}");
}
}
#[test]
fn a_line_picked_on_one_of_two_cuts_loses_the_pieces_both_sides() {
// Cuts at x = 3 and 7: on 3, 0 to 7 goes; 4e-7 past 7, 3 to the end; between them, 3 to 7.
let (_, got, h) = line_trimmed(&[3.0, 7.0], [3.0, 0.0]);
assert_eq!(got, vec![(h, vec![7.0, 0.0, 10.0, 0.0])]);
let (_, got, h) = line_trimmed(&[3.0, 7.0], [7.0000004, 0.0]);
assert_eq!(got, vec![(h, vec![0.0, 0.0, 3.0, 0.0])]);
let (_, got, h) = line_trimmed(&[3.0, 7.0], [5.0, 0.0]);
assert_eq!(got.len(), 2);
assert_eq!(got[0], (h, vec![0.0, 0.0, 3.0, 0.0]));
assert_eq!(got[1].1, vec![7.0, 0.0, 10.0, 0.0]);
}
/// An arc of radius 10 about the origin from 0 to 180 degrees, with vertical lines through `xs`,
/// trimmed at `pick`.
fn arc_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec<f64>)>, Handle) {
let mut s = Session::new();
let h = handle(&s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 180 })).unwrap());
let es = edges(&mut s, xs);
let made = trim(&mut s, h, pick, &es);
(made, shapes(&s, &es), h)
}
#[test]
fn an_arc_picked_on_its_only_cut_is_left_as_it_was() {
// The line x = 0 cuts it at 90 degrees: on the cut and 4e-7 along from it nothing is trimmed,
// 6e-7 along the arc from 90 to 180 goes.
for pick in [[0.0, 10.0], [-4e-7, 10.0]] {
let (made, got, h) = arc_trimmed(&[0.0], pick);
assert!(!made, "{pick:?}");
assert_eq!(got, vec![(h, vec![0.0, 180.0])], "{pick:?}");
}
let (_, got, h) = arc_trimmed(&[0.0], [-6e-7, 10.0]);
assert_eq!(got, vec![(h, vec![0.0, 90.0])]);
}
#[test]
fn an_arc_picked_on_its_last_cut_loses_the_rest() {
// Cuts at 60 and 120 degrees, picked on 120: from 60 to the end goes.
let (_, got, h) = arc_trimmed(&[5.0, -5.0], [-5.0, 75f64.sqrt()]);
assert_eq!(got, vec![(h, vec![0.0, 60.0])]);
}
/// A circle of radius 10 about the origin, with vertical lines through `xs`, trimmed at `pick`.
fn circle_trimmed(xs: &[f64], pick: [f64; 2]) -> (bool, Vec<(Handle, Vec<f64>)>, Handle) {
let mut s = Session::new();
let h = handle(&s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap());
let es = edges(&mut s, xs);
let made = trim(&mut s, h, pick, &es);
(made, shapes(&s, &es), h)
}
#[test]
fn a_circle_picked_on_a_cut_loses_the_arcs_both_sides() {
// Lines at x = 5 and -5 cut it at 60, 120, 240 and 300 degrees. Picked on 60, and 4e-7 along
// from it, the arc from 300 round to 120 goes; picked at 90, the arc from 60 to 120.
let y = 75f64.sqrt();
for pick in [[5.0, y], [4.9999998, y + 2e-7 * 5.0 / y]] {
let (_, got, h) = circle_trimmed(&[5.0, -5.0], pick);
assert_eq!(got, vec![(h, vec![120.0, 300.0])], "{pick:?}");
}
let (_, got, h) = circle_trimmed(&[5.0, -5.0], [0.0, 10.0]);
assert_eq!(got, vec![(h, vec![120.0, 60.0])]);
}
#[test]
fn a_circle_picked_on_one_of_two_cuts_is_left_as_it_was() {
// One line, cutting it at 60 and 300 degrees: picked on 60, one cut is left and the trim is
// refused.
let (made, got, h) = circle_trimmed(&[5.0], [5.0, 75f64.sqrt()]);
assert!(!made);
assert_eq!(got, vec![(h, Vec::new())]);
}
#[test]
fn quick_mode_leaves_an_object_picked_on_its_only_cut() {
// The line, the arc and the circle each meet the edges, at the pick, so Quick mode doesn't
// erase them as objects no edge crosses.
let y = 75f64.sqrt();
let cases = [
("line", json!({ "points": [[0, 0], [10, 0]] }), 5.0, [5.0, 0.0]),
("arc", json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 180 }), 0.0, [0.0, 10.0]),
("circle", json!({ "center": [0, 0], "radius": 10 }), 5.0, [5.0, y]),
];
for (cmd, shape, x, pick) in cases {
let mut s = Session::new();
let h = handle(&s.execute(cmd, &shape).unwrap());
let es = edges(&mut s, &[x]);
let r = s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "mode": "quick" }));
assert!(r.is_err(), "{cmd}");
assert!(s.doc().unwrap().entity(h).is_some(), "{cmd} was erased");
assert_eq!(shapes(&s, &es).len(), 1, "{cmd}");
}
}
#[test]
fn an_arc_picked_just_off_one_end_loses_the_piece_at_that_end() {
// From 0 to 90 degrees, cut at 45: picked just before its start the piece from 0 goes, just
// past its end the piece to 90.
let x = 10.0 * std::f64::consts::FRAC_PI_4.cos();
let trimmed = |pick: [f64; 2]| {
let mut s = Session::new();
let h = handle(&s.execute("arc", &json!({ "center": [0, 0], "radius": 10, "start": 0, "end": 90 })).unwrap());
let es = edges(&mut s, &[x]);
assert!(trim(&mut s, h, pick, &es));
shapes(&s, &es)
};
assert_eq!(trimmed([10.0, -0.01])[0].1, vec![45.0, 90.0]);
assert_eq!(trimmed([-0.01, 10.0])[0].1, vec![0.0, 45.0]);
}
@@ -0,0 +1,42 @@
//! TRIM on a polyline cut through the vertex where an arc span starts: the cut is at that vertex
//! only. Where the crossing came out a hair before the arc's start angle it was also put at the
//! arc's far end, round the circle, and TRIM took out the arc alone.
use cadcraft_engine::Session;
use cadcraft_engine::doc::EntityKind;
use serde_json::json;
fn handle(v: serde_json::Value) -> String {
v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap().to_owned()
}
#[test]
fn the_cut_is_at_the_arc_spans_start_vertex_only() {
// (0, 0) to (10, 0), a semicircle round (15, 5) to (10, 10), then on to (0, 10). A line
// through (10, 0) running up to the left crosses the top span at x = 10 + 10 cot(angle);
// picked on the arc, the polyline goes from (10, 0) to there.
for k in 0..172 {
let th = (91.0 + f64::from(k) * 0.25).to_radians();
let d = [th.cos() * 30.0, th.sin() * 30.0];
let mut s = Session::new();
let p = handle(s.execute("pline", &json!({ "vertices": [[0, 0], { "p": [10, 0], "bulge": 1 }, [10, 10], [0, 10]] })).unwrap());
let e = handle(s.execute("line", &json!({ "points": [[10.0 - d[0], -d[1]], [10.0 + d[0], d[1]]] })).unwrap());
s.execute("trim", &json!({ "handle": p, "pick": [15, 5], "edges": [e] })).unwrap();
let pieces: Vec<Vec<(f64, f64)>> = s
.doc()
.unwrap()
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::LwPolyline(l) => Some(l.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()),
_ => None,
})
.collect();
let x = 10.0 + 10.0 / th.tan();
let near = |a: (f64, f64), b: (f64, f64)| (a.0 - b.0).abs() < 1e-6 && (a.1 - b.1).abs() < 1e-6;
let ok = pieces.len() == 2
&& pieces.iter().any(|v| v.len() == 2 && near(v[0], (0.0, 0.0)) && near(v[1], (10.0, 0.0)))
&& pieces.iter().any(|v| v.len() == 2 && near(v[0], (x, 10.0)) && near(v[1], (0.0, 10.0)));
assert!(ok, "{:.2} degrees: {pieces:?}", th.to_degrees());
}
}
@@ -0,0 +1,177 @@
//! JSON execute pick roles and diagnostic-only refusals (#2750).
use cadcraft_doc::{Common, EntityKind, Handle, Line, Space};
use cadcraft_engine::{Session, find_command};
use cadcraft_geom::Vec3;
use serde_json::{Value, json};
type TestResult<T = ()> = Result<T, Box<dyn std::error::Error>>;
fn fixture(end: f64, edge_x: f64) -> TestResult<(Session, Handle, Handle)> {
let mut s = Session::new();
let a = s.doc_mut()?.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(end, 0.0, 0.0) }))?;
let b = s.doc_mut()?.add(
&Space::Model,
Common::default(),
EntityKind::Line(Line { a: Vec3::new(edge_x, -20.0, 0.0), b: Vec3::new(edge_x, 20.0, 0.0) }),
)?;
Ok((s, a, b))
}
fn assert_line(s: &Session, h: Handle, start: f64, end: f64) -> TestResult {
let e = s.doc()?.entity(h).ok_or("line missing")?;
let EntityKind::Line(l) = &e.kind else { return Err("expected line".into()) };
assert_eq!((l.a, l.b), (Vec3::new(start, 0.0, 0.0), Vec3::new(end, 0.0, 0.0)));
Ok(())
}
fn failure(s: &mut Session, cmd: &str, params: Value, message: &str) -> TestResult {
let before = s.doc()?.clone();
let selection = s.state()?.selection.clone();
let error = s.execute(cmd, &params).err().ok_or("expected refusal")?;
assert_eq!(error.to_string(), message);
assert_eq!(s.doc()?, &before, "a failed JSON call must leave the whole drawing unchanged");
assert_eq!(s.state()?.selection, selection);
Ok(())
}
#[test]
fn trim_execute_pick_selects_the_portion_to_remove() -> TestResult {
// Off-object picks that already succeed by projection remain accepted.
for (pick, start, end) in [([5, 0], 25.0, 50.0), ([40, 0], 0.0, 25.0), ([5, 3], 25.0, 50.0)] {
let (mut s, a, b) = fixture(50.0, 25.0)?;
let boundary = s.doc()?.entity(b).cloned().ok_or("boundary missing")?;
let result = s.execute("trim", &json!({"handle": a.hex(), "edges": [b.hex()], "pick": pick}))?;
let handles = result["handles"].as_array().ok_or("expected handles")?;
assert_eq!(handles.len(), 1);
let h = handles.first().and_then(Value::as_str).and_then(Handle::parse_hex).ok_or("expected trimmed handle")?;
assert_eq!(h, a, "TRIM keeps the original handle on the surviving piece");
assert_line(&s, h, start, end)?;
assert_eq!(s.doc()?.entity(b), Some(&boundary));
}
Ok(())
}
#[test]
fn extend_execute_pick_selects_the_end_toward_the_boundary() -> TestResult {
for pick in [[25, 10], [25, -15], [19, 0], [40, 0]] {
let (mut s, a, b) = fixture(20.0, 25.0)?;
let boundary = s.doc()?.entity(b).cloned().ok_or("boundary missing")?;
let result = s.execute("extend", &json!({"handle": a.hex(), "edges": [b.hex()], "pick": pick}))?;
assert_eq!(result, Value::Null);
assert_line(&s, a, 0.0, 25.0)?;
assert_eq!(s.doc()?.entity(b), Some(&boundary));
}
Ok(())
}
#[test]
fn trim_execute_distinguishes_picks_at_or_projecting_onto_a_cut_from_no_cut() -> TestResult {
let (mut s, a, b) = fixture(50.0, 25.0)?;
for (pick, message) in [
([25, 10], "The `pick` point is off the line and projects onto a cutting intersection; pick away from that intersection."),
([25, 0], "The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection."),
] {
failure(&mut s, "trim", json!({"handle": a.hex(), "edges": [b.hex()], "pick": pick, "mode": "standard"}), message)?;
}
let (mut s, a, b) = fixture(50.0, 75.0)?;
failure(
&mut s,
"trim",
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [5, 0]}),
"No usable cutting-edge intersection in the interior of the object to trim.",
)
}
#[test]
fn extend_execute_distinguishes_the_wrong_end_from_no_boundary_hit() -> TestResult {
let (mut s, a, b) = fixture(20.0, 25.0)?;
failure(
&mut s,
"extend",
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [10, 0]}),
"The `pick` point selects an end with no boundary ahead; choose `pick` toward the boundary to extend to.",
)?;
s.doc_mut()?.modify_entity(b, |e| {
e.kind = EntityKind::Line(Line { a: Vec3::new(0.0, 20.0, 0.0), b: Vec3::new(25.0, 20.0, 0.0) });
})?;
failure(
&mut s,
"extend",
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [25, 20]}),
"No usable boundary intersection was found for either end of the object to extend.",
)
}
#[test]
fn quick_erasure_and_unrelated_errors_keep_their_behavior() -> TestResult {
let (mut s, a, b) = fixture(50.0, 25.0)?;
// Quick mode leaves a line picked on its only cut in place (#2648), and the JSON form explains
// the refusal as Standard mode does.
failure(
&mut s,
"trim",
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [25, 0], "mode": "quick"}),
"The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection.",
)?;
assert!(s.doc()?.entity(a).is_some());
assert!(s.doc()?.entity(b).is_some());
failure(&mut s, "trim", json!({"handle": "DEAD", "pick": [5, 0]}), "no such object")
}
#[test]
fn command_contracts_and_missing_pick_errors_explain_the_roles() -> TestResult {
let trim = find_command("trim").ok_or("trim not registered")?;
assert!(trim.params.contains("pick selects the portion of that object to remove"));
assert!(trim.params.contains("edges are the cutting edges"));
let extend = find_command("extend").ok_or("extend not registered")?;
assert!(extend.params.contains("pick points toward the boundary to extend to"));
assert!(extend.params.contains("selecting the nearer end"));
assert!(extend.params.contains("edges are the boundary edges"));
let (mut s, a, b) = fixture(20.0, 25.0)?;
failure(
&mut s,
"trim",
json!({"handle": a.hex(), "edges": [b.hex()]}),
"invalid parameters for `trim`: `pick` ([x, y]) is required: select the portion of the object to trim away",
)?;
failure(
&mut s,
"extend",
json!({"handle": a.hex(), "edges": [b.hex()]}),
"invalid parameters for `extend`: `pick` ([x, y]) is required: point toward the boundary to extend to, selecting the nearer end",
)
}
#[test]
fn a_pick_on_the_line_far_from_the_origin_is_not_called_off_the_line() -> TestResult {
// Survey coordinates: rounding there is far above 1e-9 (the pick below is 3.7e-9 off the line
// after rounding), so a pick on the line still reads as on it.
let (x0, y0, k) = (123_456_789.1, 9_876_543.3, 33.3333);
let mut s = Session::new();
let a = s.doc_mut()?.add(
&Space::Model,
Common::default(),
EntityKind::Line(Line { a: Vec3::new(x0, y0, 0.0), b: Vec3::new(x0 + 50.0, y0 + 30.0, 0.0) }),
)?;
let b = s.doc_mut()?.add(
&Space::Model,
Common::default(),
EntityKind::Line(Line { a: Vec3::new(x0 + k, y0 - 20.0, 0.0), b: Vec3::new(x0 + k, y0 + 50.0, 0.0) }),
)?;
failure(
&mut s,
"trim",
json!({"handle": a.hex(), "edges": [b.hex()], "pick": [x0 + k, y0 + k * 0.6]}),
"The `pick` point is at a cutting intersection; pick a portion of the object away from that intersection.",
)
}
#[test]
fn the_extend_contract_names_the_polyline_end_rule() -> TestResult {
// An open polyline extends the end on the pick's side of its middle parameter (#2693), not
// the nearer end.
let extend = find_command("extend").ok_or("extend not registered")?;
assert!(extend.params.contains("middle"), "{}", extend.params);
Ok(())
}
+25 -2
View File
@@ -112,10 +112,33 @@ fn crossing_window_trims_what_it_touches() {
s.script("TRIM C 4,-1 6,1\n\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (15.0, 2.0)), ((10.0, 0.0), (15.0, 0.0))]));
// A pick in empty space opens a crossing window too.
}
#[test]
fn a_pick_in_empty_space_starts_a_fence_in_quick_mode_and_a_window_in_standard_mode() {
// #1594: Quick mode's two-point fence trims what it crosses and returns to the first prompt.
for cmd in ["TRIM", "EXTEND"] {
let mut s = ladder();
s.cmdline(cmd).unwrap();
s.cmdline("4,-4").unwrap();
assert!(s.prompt_text().contains("Specify next fence point"), "{cmd}: {}", s.prompt_text());
}
let mut s = ladder();
s.script("TRIM 4,-4 6,1\n\n").unwrap();
s.script("TRIM 4,-4 6,1\n").unwrap();
assert!(s.prompt_text().contains("Select object to trim"), "{}", s.prompt_text());
s.cmdline("").unwrap();
assert_eq!(lines(&s), with_edges(&[((-5.0, 0.0), (0.0, 0.0)), ((-5.0, 2.0), (15.0, 2.0)), ((10.0, 0.0), (15.0, 0.0))]));
// EXTEND's fence extends both lines it crosses to the boundary at x = 10.
let mut s = session(&["10,-5 10,5", "0,0 4,0", "0,2 4,2"]);
s.script("EXTEND 3,-1 3,3\n").unwrap();
assert!(s.prompt_text().contains("Select object to extend"), "{}", s.prompt_text());
s.cmdline("").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
assert_eq!(lines(&s), vec![((0.0, 0.0), (10.0, 0.0)), ((0.0, 2.0), (10.0, 2.0)), ((10.0, -5.0), (10.0, 5.0))]);
// Standard mode keeps the crossing window.
let mut s = ladder();
s.script("TRIM O S\n\n4,-4\n").unwrap();
assert!(s.prompt_text().contains("Specify opposite corner"), "{}", s.prompt_text());
}
#[test]
@@ -0,0 +1,102 @@
//! TRIM keeps what the object has beyond its outline, as BREAK does: a line's Z, an arc's centre
//! Z (a circle trimmed into an arc), a polyline's elevation, and a polyline's constant width on
//! every piece. The Z cases and the width on BREAK were measured in AutoCAD 2024 (accoreconsole)
//! on these drawings.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Circle, Common, Entity, EntityKind, Handle, Line, LwPolyline};
use cadcraft_engine::geom::{PolyVertex, Vec2, Vec3};
use serde_json::json;
fn add(s: &mut Session, kind: EntityKind, thickness: f64) -> Handle {
let space = s.space();
let d = s.doc_mut().unwrap();
let handle = d.new_handle();
d.space_mut(&space).unwrap().push(Entity { handle, common: Common { thickness, ..Common::default() }, kind });
handle
}
fn line(s: &mut Session, a: [f64; 2], b: [f64; 2]) -> Handle {
let v = s.execute("line", &json!({ "points": [a, b] })).unwrap();
Handle::parse_hex(v["handles"][0].as_str().unwrap()).unwrap()
}
fn trim(s: &mut Session, h: Handle, pick: [f64; 2], edge: Handle) {
s.execute("trim", &json!({ "handle": h.hex(), "pick": pick, "edges": [edge.hex()] })).unwrap();
}
fn kind(s: &Session, h: Handle) -> EntityKind {
s.doc().unwrap().entity(h).unwrap().kind.clone()
}
fn polyline(vertices: &[(f64, f64, f64)], const_width: f64, elevation: f64, plinegen: bool) -> EntityKind {
let vertices = vertices.iter().map(|&(x, y, bulge)| PolyVertex { bulge, ..PolyVertex::new(Vec2::new(x, y)) }).collect();
EntityKind::LwPolyline(LwPolyline { vertices, closed: false, const_width, elevation, plinegen })
}
fn near(a: Vec3, b: Vec3, tol: f64) -> bool {
(a.x - b.x).abs() < tol && (a.y - b.y).abs() < tol && (a.z - b.z).abs() < tol
}
#[test]
fn trim_keeps_a_lines_z() {
let mut s = Session::new();
let a = add(&mut s, EntityKind::Line(Line { a: Vec3::new(0.5, 0.25, 0.007), b: Vec3::new(0.54, 0.25, 0.007) }), 0.0);
let b = line(&mut s, [0.52, 0.24], [0.52, 0.26]);
trim(&mut s, a, [0.53, 0.25], b);
let EntityKind::Line(l) = kind(&s, a) else { panic!("not a line") };
assert!(near(l.a, Vec3::new(0.5, 0.25, 0.007), 1e-12) && near(l.b, Vec3::new(0.52, 0.25, 0.007), 1e-12), "{l:?}");
}
#[test]
fn trim_keeps_the_centre_z_of_a_circle_made_an_arc() {
// At survey coordinates, with a thickness of 2.
let mut s = Session::new();
let c = add(&mut s, EntityKind::Circle(Circle { center: Vec3::new(612345.678, 2398765.432, 5.0), radius: 10.0 }), 2.0);
let b = line(&mut s, [612350.678, 2398745.432], [612350.678, 2398785.432]);
trim(&mut s, c, [612335.678, 2398765.432], b);
let e = s.doc().unwrap().entity(c).unwrap().clone();
let EntityKind::Arc(a) = &e.kind else { panic!("not an arc: {:?}", e.kind) };
assert!(near(a.center, Vec3::new(612345.678, 2398765.432, 5.0), 1e-9), "{a:?}");
assert!((a.start - 5.235987755978257).abs() < 1e-9 && (a.end - 1.047197551201328).abs() < 1e-9, "{a:?}");
assert_eq!(e.common.thickness, 2.0);
}
#[test]
fn trim_keeps_a_polylines_elevation() {
let mut s = Session::new();
let p = add(&mut s, polyline(&[(0.0, 0.0, 0.0), (20.0, 0.0, 0.4), (30.0, 15.0, 0.0), (5.0, 20.0, 0.0)], 0.0, 12.5, false), 1.0);
let b = line(&mut s, [10.0, -10.0], [10.0, 30.0]);
trim(&mut s, p, [5.0, 0.0], b);
let EntityKind::LwPolyline(l) = kind(&s, p) else { panic!("not a polyline") };
assert_eq!(l.elevation, 12.5);
let want = [(10.0, 0.0, 0.0), (20.0, 0.0, 0.4), (30.0, 15.0, 0.0), (5.0, 20.0, 0.0)];
assert_eq!(l.vertices.len(), want.len());
for (v, w) in l.vertices.iter().zip(want) {
assert!(near(Vec3::new(v.p.x, v.p.y, v.bulge), Vec3::new(w.0, w.1, w.2), 1e-12), "{v:?} != {w:?}");
}
}
#[test]
fn break_and_trim_keep_a_polylines_constant_width_on_every_piece() {
// Measured for BREAK: a width-2 polyline broken from (705, 0) to (735, 0) leaves two width-2
// pieces. TRIM leaves its pieces the same way. Linetype generation is the polyline's setting
// too, so the pieces keep it (not measured).
let shape = [(700.0, 0.0, 0.0), (720.0, 0.0, 0.0), (740.0, 0.0, 0.0)];
let mut s = Session::new();
let p = add(&mut s, polyline(&shape, 2.0, 0.0, true), 0.0);
let r = s.execute("break", &json!({ "handle": p.hex(), "p1": [705, 0], "p2": [735, 0] })).unwrap();
let mut s2 = Session::new();
let q = add(&mut s2, polyline(&shape, 2.0, 0.0, true), 0.0);
let k1 = line(&mut s2, [705.0, -5.0], [705.0, 5.0]);
let k2 = line(&mut s2, [735.0, -5.0], [735.0, 5.0]);
let t = s2.execute("trim", &json!({ "handle": q.hex(), "pick": [720, 0], "edges": [k1.hex(), k2.hex()] })).unwrap();
for (s, r) in [(&s, &r), (&s2, &t)] {
let hs = r["handles"].as_array().unwrap();
assert_eq!(hs.len(), 2);
for h in hs {
let EntityKind::LwPolyline(l) = kind(s, Handle::parse_hex(h.as_str().unwrap()).unwrap()) else { panic!("not a polyline") };
assert_eq!((l.const_width, l.plinegen), (2.0, true));
}
}
}
-294
View File
@@ -1,294 +0,0 @@
//! Saved layer states as AutoCAD keeps them: the LAYER table's extension dictionary holds an
//! `ACAD_LAYERSTATES` dictionary of one XRECORD per state. Measured in AutoCAD 2024 (DXFOUT of
//! states saved with -LAYER stAte), an XRECORD holds `280 1`, the mask (91), a text (301: empty
//! as -LAYER saves it; AutoCAD keeps one a file holds through restore and DXFOUT), `290 0` and
//! the current layer's name (302), then for each layer its LAYER handle (330),
//! flags (90: 1 off, 2 frozen, 4 locked, 8 plotted, 16 frozen in new viewports), colour index
//! (62), lineweight (370), for a layer of an xref 93 (0 for a newly attached one; a file can hold
//! 1, whose meaning isn't measured), LTYPE handle (331), plot style (in a drawing of colour-dependent
//! plot styles the name `Color_N` in group 1, N its colour index; of named ones the handle of its
//! placeholder object in group 390), transparency (440: 0 opaque, else `0x02000000 | alpha`) and,
//! for a true colour, 92 (`0xC2RRGGBB`).
//!
//! States AutoCAD's dictionary can't hold stay in CADCraft's own record (`CADCRAFT_LAYERSTATES`):
//! the view layer snapshots (`*VIEW name`), and a name that repeats an earlier one in another
//! case: AutoCAD 2024 opens the entries `S` and `s` of one dictionary as one state, named as the
//! first entry and holding the last one's record (measured), and so does the reader here.
use std::collections::{HashMap, HashSet};
use cadcraft_color::{Color, Rgb};
use cadcraft_doc::{Layer, LayerState, Lineweight};
use craft_dxf::Tag;
use crate::dxf_ext::{transparency_from_dxf, transparency_to_dxf};
/// The key of the states dictionary in the LAYER table's extension dictionary.
pub(crate) const KEY: &str = "ACAD_LAYERSTATES";
/// The prefix of a true colour in group 92.
const TRUE_COLOR: u32 = 0xC200_0000;
/// The bytes of layers the states of one file may copy (CWE-400). Each entry of a state is a copy
/// of the drawing's layer, its names and description included, so without a bound a small file
/// naming one layer with a long description in a great many entries would take gigabytes.
pub(crate) const MAX_COPIED_BYTES: usize = 256 << 20;
/// Which of `states` go into AutoCAD's dictionary (the others into CADCraft's record).
pub(crate) fn in_acad(states: &[LayerState]) -> Vec<bool> {
let mut seen: HashSet<String> = HashSet::with_capacity(states.len());
states.iter().map(|st| !st.name.trim().is_empty() && !st.name.starts_with('*') && seen.insert(st.name.to_lowercase())).collect()
}
/// The states CADCraft's own record keeps (those [`in_acad`] leaves out).
pub(crate) fn own(states: &[LayerState]) -> Vec<LayerState> {
states.iter().zip(in_acad(states)).filter(|(_, acad)| !acad).map(|(st, _)| st.clone()).collect()
}
/// Handles of the objects that hold the drawing's states in AutoCAD's form.
#[derive(Default)]
pub(crate) struct Plan {
/// The LAYER table, which owns the extension dictionary.
pub table: String,
/// The LAYER table's extension dictionary.
pub xdict: String,
/// The `ACAD_LAYERSTATES` dictionary.
dict: String,
/// (index in the drawing's states, XRECORD handle).
records: Vec<(usize, String)>,
}
impl Plan {
pub fn new(states: &[LayerState], mut handle: impl FnMut() -> String) -> Self {
let acad = in_acad(states);
if !acad.contains(&true) {
return Plan::default();
}
let xdict = handle();
let dict = handle();
let records = acad.iter().enumerate().filter(|(_, a)| **a).map(|(i, _)| (i, handle())).collect();
Plan { table: String::new(), xdict, dict, records }
}
pub fn is_empty(&self) -> bool {
self.records.is_empty()
}
}
/// What the state objects need from the rest of the file.
pub(crate) struct Refs<'a> {
/// Upper-case layer name → LAYER record handle.
pub layers: &'a HashMap<String, String>,
/// Upper-case linetype name → LTYPE record handle.
pub ltypes: &'a HashMap<String, String>,
/// Upper-case plot style name → its placeholder object's handle.
pub pstyles: &'a HashMap<String, String>,
/// Plot styles by colour (`$PSTYLEMODE` 1): the plot style name is `Color_N`.
pub colour_dependent: bool,
}
/// The objects of plan `p`: the extension dictionary, the `ACAD_LAYERSTATES` dictionary and one
/// XRECORD per state. Layers the drawing no longer has are left out of a state (AutoCAD names
/// layers by handle).
pub(crate) fn objects(p: &Plan, states: &[LayerState], refs: &Refs) -> Vec<Tag> {
let mut t = Vec::new();
if p.is_empty() {
return t;
}
t.extend([Tag::s(0, "DICTIONARY"), Tag::s(5, &p.xdict), Tag::s(330, &p.table), Tag::s(100, "AcDbDictionary"), Tag::i(280, 1), Tag::i(281, 1)]);
t.extend([Tag::s(3, KEY), Tag::s(360, &p.dict)]);
t.extend([Tag::s(0, "DICTIONARY"), Tag::s(5, &p.dict), Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, &p.xdict), Tag::s(102, "}")]);
t.extend([Tag::s(330, &p.xdict), Tag::s(100, "AcDbDictionary"), Tag::i(281, 1)]);
let planned = || p.records.iter().filter_map(|(i, h)| Some((states.get(*i)?, h)));
for (st, h) in planned() {
t.extend([Tag::s(3, &st.name), Tag::s(350, h)]);
}
for (st, h) in planned() {
t.extend([Tag::s(0, "XRECORD"), Tag::s(5, h), Tag::s(102, "{ACAD_REACTORS"), Tag::s(330, &p.dict), Tag::s(102, "}"), Tag::s(330, &p.dict)]);
t.extend([Tag::s(100, "AcDbXrecord"), Tag::i(280, 1), Tag::i(91, i64::from(st.mask)), Tag::s(301, &st.description), Tag::i(290, 0)]);
t.push(Tag::s(302, &st.current));
for l in &st.layers {
if let Some(lh) = refs.layers.get(&l.name.to_ascii_uppercase()) {
layer(&mut t, l, lh, refs);
}
}
}
t
}
/// One layer of a state's XRECORD.
fn layer(t: &mut Vec<Tag>, l: &Layer, handle: &str, refs: &Refs) {
let flags = i64::from(!l.on) | i64::from(l.frozen) << 1 | i64::from(l.locked) << 2 | i64::from(l.plot) << 3 | i64::from(l.vp_freeze_new) << 4;
let aci = match l.color {
Color::True(rgb) => i64::from(cadcraft_color::nearest_aci(rgb)),
c => i64::from(c.to_aci()).clamp(1, 255),
};
t.extend([Tag::s(330, handle), Tag::i(90, flags), Tag::i(62, aci), Tag::i(370, i64::from(l.lineweight.to_dxf()))]);
if crate::dxf_xref::dependent(&l.name) {
t.push(Tag::i(93, 0));
}
// A linetype the drawing no longer has: Continuous, which every drawing has.
if let Some(lt) = refs.ltypes.get(&l.linetype.to_ascii_uppercase()).or_else(|| refs.ltypes.get("CONTINUOUS")) {
t.push(Tag::s(331, lt));
}
if refs.colour_dependent {
t.push(Tag::s(1, format!("Color_{aci}")));
} else if let Some(ps) = refs.pstyles.get(&l.plot_style.trim().to_ascii_uppercase()).or_else(|| refs.pstyles.get("NORMAL")) {
t.push(Tag::s(390, ps));
}
t.push(Tag::i(440, if l.transparency == 0 { 0 } else { transparency_to_dxf(l.transparency) }));
if let Color::True(rgb) = l.color {
t.push(Tag::i(92, i64::from(i32::from_be_bytes((TRUE_COLOR | rgb.to_u32()).to_be_bytes()))));
}
}
/// What a state's handles name in the drawing being read.
pub(crate) struct Lookup<'a> {
/// The drawing's layer a LAYER handle names: a state's layer starts as a copy of it (what the
/// state doesn't hold, such as the description, is the drawing's).
pub layer: &'a dyn Fn(&str) -> Option<Layer>,
/// The linetype an LTYPE handle names.
pub ltype: &'a dyn Fn(&str) -> Option<String>,
/// The plot style a placeholder handle names.
pub pstyle: &'a dyn Fn(&str) -> Option<String>,
/// Plot styles by colour: group 1 (`Color_N`) says nothing the layer's colour doesn't.
pub colour_dependent: bool,
}
/// The state `name` from its XRECORD's groups. A layer whose record is gone (AutoCAD keeps a
/// purged layer's entry, measured) is skipped. A layer named in two entries is in the state once,
/// the later entry's groups over the earlier one's, as restoring both in turn did: AutoCAD 2024
/// restores the later one (measured with entries that each set every property). Each copy of a
/// layer is charged to `budget`, the file's [`MAX_COPIED_BYTES`]; once it is spent, the entries
/// left are left out.
pub(crate) fn read(name: &str, tags: &[Tag], lookup: &Lookup, budget: &mut usize) -> LayerState {
let mut st = LayerState { name: name.to_string(), ..LayerState::default() };
// The data follows the subclass marker (an XRECORD without one holds none).
let start = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbXrecord").map_or(tags.len(), |i| i + 1);
let body = tags.get(start..).unwrap_or_default();
let first = body.iter().position(|t| t.code == 330).unwrap_or(body.len());
for t in body.get(..first).unwrap_or_default() {
match t.code {
91 => st.mask = t.str().trim().parse::<u32>().unwrap_or(LayerState::ALL),
301 => st.description = t.str(),
302 => st.current = t.str(),
_ => {}
}
}
let rest = body.get(first..).unwrap_or_default();
// The index in the state of each layer by its LAYER handle.
let mut index: HashMap<String, usize> = HashMap::new();
let mut at = 0;
while let Some(group) = rest.get(at..) {
let Some(head) = group.first() else { break };
let len = group.iter().skip(1).position(|t| t.code == 330).map_or(group.len(), |n| n + 1);
at += len;
let groups = group.get(1..len).unwrap_or_default();
let key = head.str().trim().to_ascii_uppercase();
if let Some(slot) = index.get(&key).and_then(|&i| st.layers.get_mut(i)) {
entry(slot, groups, lookup);
} else if let Some(mut l) = (lookup.layer)(&head.str()) {
let Some(left) = budget.checked_sub(cost(&l)) else { break };
*budget = left;
entry(&mut l, groups, lookup);
index.insert(key, st.layers.len());
st.layers.push(l);
}
}
st
}
/// The bytes a copy of layer `l` takes.
fn cost(l: &Layer) -> usize {
std::mem::size_of::<Layer>() + l.name.len() + l.linetype.len() + l.description.len() + l.plot_style.len()
}
/// A layer's properties from the groups after its handle.
fn entry(l: &mut Layer, groups: &[Tag], lookup: &Lookup) {
let int = |t: &Tag| t.str().trim().parse::<i64>().ok();
let mut true_color = None;
for t in groups {
match t.code {
90 => {
if let Some(f) = int(t) {
(l.on, l.frozen, l.locked, l.plot, l.vp_freeze_new) = (f & 1 == 0, f & 2 != 0, f & 4 != 0, f & 8 != 0, f & 16 != 0);
}
}
62 => {
if let Some(c) = int(t).map(i64::abs).and_then(|c| u8::try_from(c).ok()).filter(|c| *c >= 1) {
l.color = Color::Index(c);
}
}
92 => true_color = int(t).and_then(|v| u32::try_from(v & 0xFFFF_FFFF).ok()).filter(|v| v & 0xFF00_0000 == TRUE_COLOR),
370 => {
if let Some(w) = int(t).and_then(|w| i16::try_from(w).ok()) {
l.lineweight = Lineweight::from_dxf(w);
}
}
331 => {
if let Some(lt) = (lookup.ltype)(&t.str()) {
l.linetype = lt;
}
}
390 => {
if let Some(ps) = (lookup.pstyle)(&t.str()) {
l.plot_style = ps;
}
}
1 if !lookup.colour_dependent => l.plot_style = t.str(),
440 => {
if let Some(v) = int(t) {
l.transparency = transparency_from_dxf(v).unwrap_or(0);
}
}
_ => {}
}
}
if let Some(v) = true_color {
l.color = Color::True(Rgb::from_u32(v & 0x00FF_FFFF));
}
}
#[cfg(test)]
mod tests {
use super::*;
/// A state's XRECORD groups with an entry per (layer handle, colour index).
fn tags(entries: &[(&str, i64)]) -> Vec<Tag> {
let mut t = vec![Tag::s(100, "AcDbXrecord"), Tag::i(280, 1), Tag::i(91, 2047), Tag::s(302, "0")];
for (h, aci) in entries {
t.extend([Tag::s(330, *h), Tag::i(90, 8)]);
// 0: no colour group.
if *aci != 0 {
t.push(Tag::i(62, *aci));
}
}
t
}
#[test]
fn a_layer_named_twice_takes_its_last_entry_and_copies_stop_at_the_budget() {
let layer = |h: &str| match h {
"A1" => Some(Layer::new("A")),
"B1" => Some(Layer::new("B")),
_ => None,
};
let none = |_: &str| None::<String>;
let lookup = Lookup { layer: &layer, ltype: &none, pstyle: &none, colour_dependent: true };
let colours = |st: &LayerState| st.layers.iter().map(|l| (l.name.clone(), l.color)).collect::<Vec<_>>();
// AutoCAD 2024 restores the last of two entries of one layer (measured: green, then blue,
// restores blue); it stays in the first one's place. A later entry without a colour keeps
// the earlier one's, as restoring both in turn did.
let mut budget = MAX_COPIED_BYTES;
let st = read("S", &tags(&[("A1", 3), ("B1", 2), ("A1", 5), ("B1", 0)]), &lookup, &mut budget);
assert_eq!(colours(&st), [("A".to_string(), Color::Index(5)), ("B".to_string(), Color::Index(2))]);
// Each new copy is charged (a repeated entry copies nothing); past the budget the rest of
// the entries, and of the file's states, are left out.
let one = cost(&Layer::new("A"));
let mut budget = one;
let st = read("S", &tags(&[("A1", 3), ("A1", 4), ("B1", 5)]), &lookup, &mut budget);
assert_eq!((colours(&st), budget), (vec![("A".to_string(), Color::Index(4))], 0));
let st = read("T", &tags(&[("B1", 2)]), &lookup, &mut budget);
assert!(st.layers.is_empty());
}
}
+21 -77
View File
@@ -36,11 +36,10 @@ const MODELLED_KEYS: &[&str] = &[
"ACAD_IMAGE_VARS",
];
/// Extension dictionary entries not kept raw: dimension associativity and the LAYER table's layer
/// states (CADCraft reads and rewrites them), draw order and annotation scale contexts (written
/// from their own models by the changes that model them; stale copies would contradict the
/// drawing).
const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_LAYERSTATES", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"];
/// Extension dictionary entries not kept raw: dimension associativity (CADCraft reads and
/// rewrites it), draw order and annotation scale contexts (written from their own models by the
/// changes that model them; stale copies would contradict the drawing).
const MODELLED_XDICT_KEYS: &[&str] = &["ACAD_DIMASSOC", "ACAD_SORTENTS", "ACDBCONTEXTDATAMANAGER"];
/// Applications whose xdata CADCraft reads and writes itself. `ACAD` holds dimension overrides
/// (DSTYLE) on dimensions and dimension styles; elsewhere it is kept.
@@ -990,7 +989,20 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
let root = objects.first().filter(|(k, _, _)| is_dictionary(k)).map(|(_, s, _)| *s);
let root_keys: HashSet<String> =
objects.iter().find(|(_, s, _)| Some(*s) == root).map(|(_, _, t)| entries(t).into_iter().map(|(k, _)| up(&k)).collect()).unwrap_or_default();
let (mut attached, merged) = kept_dictionaries(f, &xd, &recs, tags);
// Extension dictionaries that go on a written record (one without its own).
let mut block = String::new();
let mut attached: HashSet<String> = HashSet::new();
for r in &recs {
if r.kind == "BLOCK" {
block = up(&val(body(r), 2).unwrap_or_default());
}
if let Some(x) = extra_for(f, &xd, r, body(r), &block)
&& let Some(xd) = x.xdict
&& head(body(r)).xdict.is_none()
{
attached.insert(xd.hex());
}
}
for (_, t) in planned.values().flatten() {
let x = head(t.get(1..).unwrap_or(&[])).handle.and_then(|h| handle(&h)).and_then(|h| entity_extra(f, &xd, h));
attached.extend(x.and_then(|x| x.xdict).map(Handle::hex));
@@ -1038,7 +1050,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
if nod.contains(&owner) {
break dict_entries.get(&cur).is_some_and(|k| !root_keys.contains(&up(k))) && root.is_some();
}
if attached.contains(&cur) || merged.contains_key(&cur) {
if attached.contains(&cur) {
break true;
}
break unknown.contains(&owner) && written.contains(&owner);
@@ -1056,13 +1068,6 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
alive.insert(o.handle.hex(), format!("{next:X}"));
next = next.saturating_add(1);
}
// A merged dictionary is not written: what pointed at it points at the written one.
for (kept, own) in &merged {
if let Some(h) = alive.get_mut(kept) {
h.clone_from(own);
}
}
let merged_into: HashMap<String, &ForeignObject> = merged.iter().filter_map(|(kept, own)| Some((own.clone(), *objs.get(kept)?))).collect();
let entities: HashSet<String> = all_entities(d).map(|e| e.handle.hex()).filter(|h| written.contains(h)).collect();
let map = Map { f, alive, raw: objs.keys().cloned().collect(), roles, entities };
let mut out: Vec<Tag> = Vec::with_capacity(tags.len() + f.objects.iter().map(|o| o.tags.len() + 1).sum::<usize>());
@@ -1076,7 +1081,7 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
continue;
}
if r.kind == "ENDSEC" && r.sec == "OBJECTS" {
for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex()) && !merged.contains_key(&o.handle.hex())) {
for o in f.objects.iter().filter(|o| map.alive.contains_key(&o.handle.hex())) {
let number = is_proxy(&o.kind).then(|| renumber(class_number(o.tags.iter().map(|r| (r.code, r.value.as_str()))))).flatten();
match number {
Some(n) => {
@@ -1100,15 +1105,11 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
}
out.extend(tags.get(r.start).cloned());
let x = extra_for(f, &xd, r, b, &block);
let joined = joined_into(&merged_into, b);
if x.is_none() && Some(r.start) != root && joined.is_none() {
if x.is_none() && Some(r.start) != root {
out.extend(b.iter().cloned());
continue;
}
record(&map, r, b, x.as_deref(), None, Some(r.start) == root, &mut out);
if let Some(kept) = joined {
join_entries(&map, b, kept, &mut out);
}
}
add_appids(&mut out);
let top = max_handle(&out).saturating_add(1);
@@ -1120,32 +1121,6 @@ pub(crate) fn finish(tags: &mut Vec<Tag>, d: &Drawing, reactors: &HashMap<Handle
*tags = out;
}
/// Kept extension dictionaries of written records: those that go on a record without its own,
/// and those whose entries join the one the writer gave a table (the LAYER table's, holding the
/// layer states) as kept dictionary → the written one.
fn kept_dictionaries(f: &Foreign, xd: &XdataOf, recs: &[Rec], tags: &[Tag]) -> (HashSet<String>, HashMap<String, String>) {
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
let mut block = String::new();
let mut attached: HashSet<String> = HashSet::new();
let mut merged: HashMap<String, String> = HashMap::new();
for r in recs {
if r.kind == "BLOCK" {
block = up(&val(body(r), 2).unwrap_or_default());
}
let Some(kept) = extra_for(f, xd, r, body(r), &block).and_then(|x| x.xdict) else { continue };
match head(body(r)).xdict {
None => {
attached.insert(kept.hex());
}
Some(own) if r.sec == "TABLES" => {
merged.insert(kept.hex(), own);
}
Some(_) => {}
}
}
(attached, merged)
}
/// Complete source tables keep positional identities even when names repeat.
fn proxy_class_number(f: &Foreign, numbers: &HashMap<String, i64>, old: Option<i64>) -> Option<i64> {
if f.complete_class_table {
@@ -1377,37 +1352,6 @@ fn record(map: &Map, r: &Rec, b: &[Tag], x: Option<&ForeignExtra>, unknown: Opti
}
}
/// The kept dictionary whose entries join written dictionary `b`, if any.
fn joined_into<'a>(merged_into: &HashMap<String, &'a ForeignObject>, b: &[Tag]) -> Option<&'a ForeignObject> {
if merged_into.is_empty() {
return None;
}
head(b).handle.and_then(|h| merged_into.get(&h).copied())
}
/// The entries of kept dictionary `kept` that written dictionary `b` doesn't have (by key, without
/// regard to case), appended to it with their handles remapped; entries whose object is gone are
/// left out.
fn join_entries(map: &Map, b: &[Tag], kept: &ForeignObject, out: &mut Vec<Tag>) {
let has = |key: &str| b.iter().any(|t| t.code == 3 && up(&t.str()) == up(key));
let mut key: Option<&str> = None;
for t in kept.tags.iter().take_while(|t| t.code < 1000) {
match t.code {
3 => key = Some(t.value.as_str()),
350 | 360 => {
if let Some(k) = key.take()
&& !has(k)
&& let Some(h) = map.get(&t.value).filter(|h| h != "0")
{
out.push(Tag::s(3, k));
out.push(Tag::s(t.code, h));
}
}
_ => {}
}
}
}
/// Kept xdata of applications the record doesn't already carry, handles remapped.
fn xdata(map: &Map, x: &ForeignExtra, own: &HashSet<String>, out: &mut Vec<Tag>) {
let mut skip = false;
+5 -96
View File
@@ -8,14 +8,10 @@ use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup
pub(super) struct Objects {
/// Dictionary entry handle (upper case) → entry name.
names: HashMap<String, String>,
/// (dictionary handle, entry handle), both upper case, in the order the dictionaries list them.
entry_order: Vec<(String, String)>,
/// SCALE objects (the annotation scale list), in file order.
scales: Vec<cadcraft_doc::AnnoScale>,
/// XRECORD handle (upper case) → its groups.
xrecords: HashMap<String, Vec<Tag>>,
/// XRECORD handles in file order.
xrecord_order: Vec<String>,
/// TABLESTYLE objects: (handle, groups).
table_styles: Vec<(String, Vec<Tag>)>,
/// DIMASSOC objects.
@@ -54,11 +50,7 @@ impl Objects {
if let Some(n) = name.take()
&& self.names.len() < MAX_OBJECTS
{
let entry = t.str().trim().to_ascii_uppercase();
if self.entry_order.len() < MAX_OBJECTS {
self.entry_order.push((h.clone(), entry.clone()));
}
self.names.insert(entry, n);
self.names.insert(t.str().trim().to_ascii_uppercase(), n);
}
}
_ => {}
@@ -66,9 +58,7 @@ impl Objects {
}
}
"XRECORD" if self.xrecords.len() < MAX_OBJECTS => {
if self.xrecords.insert(h.clone(), tags.to_vec()).is_none() {
self.xrecord_order.push(h);
}
self.xrecords.insert(h, tags.to_vec());
}
"TABLESTYLE" if self.table_styles.len() < MAX_OBJECTS => self.table_styles.push((h, tags.to_vec())),
"DIMASSOC" if self.dimassocs.len() < MAX_OBJECTS => self.dimassocs.push(tags.to_vec()),
@@ -90,65 +80,6 @@ impl Objects {
}
}
/// The layer states of the LAYER table's `ACAD_LAYERSTATES` dictionary (its XRECORDs, in file
/// order), read with the drawing's layers and linetypes. Entries whose names differ only in case
/// are one state, as AutoCAD 2024 opens them (measured with `S` and `s` in both orders): named as
/// the first of them in the dictionary, holding the last one's record, where the first of their
/// records comes in the file.
fn acad_layer_states(&self, d: &Drawing, rx: &Rx) -> Vec<cadcraft_doc::LayerState> {
let dicts: std::collections::HashSet<&str> =
self.names.iter().filter(|(_, n)| n.eq_ignore_ascii_case(crate::dxf_layer_states::KEY)).map(|(h, _)| h.as_str()).collect();
if dicts.is_empty() {
return Vec::new();
}
let mut by_name: HashMap<String, &cadcraft_doc::Layer> = HashMap::with_capacity(d.layers.len());
for l in &d.layers {
by_name.entry(l.name.to_ascii_lowercase()).or_insert(l);
}
let layer_of =
|h: &str| rx.layers.get(&h.trim().to_ascii_uppercase()).and_then(|n| by_name.get(&n.to_ascii_lowercase())).map(|l| (*l).clone());
let ltype_of = |h: &str| rx.ltypes.get(&h.trim().to_ascii_uppercase()).cloned();
let pstyle_of = |h: &str| rx.pstyles.get(&h.trim().to_ascii_uppercase()).cloned();
let lookup = crate::dxf_layer_states::Lookup {
layer: &layer_of,
ltype: &ltype_of,
pstyle: &pstyle_of,
colour_dependent: d.header.i64("PSTYLEMODE", 1) != 0,
};
let ours = |tags: &[Tag]| owner(tags).is_some_and(|o| dicts.contains(o.as_str()));
// By lower-case name: the first entry's name and the last entry's record, in dictionary order.
let mut first: HashMap<String, &String> = HashMap::new();
let mut last: HashMap<String, &Vec<Tag>> = HashMap::new();
for (dict, h) in &self.entry_order {
if dicts.contains(dict.as_str())
&& let (Some(name), Some(tags)) = (self.names.get(h), self.xrecords.get(h))
&& ours(tags)
{
first.entry(name.to_ascii_lowercase()).or_insert(name);
last.insert(name.to_ascii_lowercase(), tags);
}
}
let mut out = Vec::new();
let mut taken = std::collections::HashSet::new();
let mut budget = crate::dxf_layer_states::MAX_COPIED_BYTES;
for h in &self.xrecord_order {
let (Some(tags), Some(name)) = (self.xrecords.get(h), self.names.get(h)) else { continue };
if out.len() >= crate::dxf_ext::MAX_LAYER_STATES {
break;
}
if !ours(tags) {
continue;
}
let key = name.to_ascii_lowercase();
if taken.insert(key.clone()) {
let name = first.get(&key).copied().unwrap_or(name);
let tags = last.get(&key).copied().unwrap_or(tags);
out.push(crate::dxf_layer_states::read(name, tags, &lookup, &mut budget));
}
}
out
}
/// The text of the CADCraft XRECORD stored under `key` in a dictionary (its 1/3 strings).
pub(super) fn xrecord_text(&self, key: &str) -> Option<String> {
let h = self.names.iter().find(|(_, n)| n.as_str() == key).map(|(h, _)| h)?;
@@ -277,18 +208,10 @@ impl Objects {
if let Some(p) = self.xrecord_text(crate::dxf_ext::ANNOTATION_KEY).and_then(|t| crate::dxf_ext::parse_anno(&t)) {
crate::dxf_ext::apply_anno(d, p);
}
// Saved layer states: AutoCAD's, then those of CADCraft's own record (a file of an
// earlier version keeps them all there) that AutoCAD's doesn't hold.
let mut states = self.acad_layer_states(d, rx);
if let Some(own) = self.xrecord_text(crate::dxf_ext::LAYER_STATES_KEY).and_then(|t| crate::dxf_ext::parse_layer_states(&t)) {
let mut names: std::collections::HashSet<String> = states.iter().map(|s| s.name.clone()).collect();
for st in own {
if states.len() < crate::dxf_ext::MAX_LAYER_STATES && names.insert(st.name.clone()) {
states.push(st);
}
}
// Saved layer states.
if let Some(states) = self.xrecord_text(crate::dxf_ext::LAYER_STATES_KEY).and_then(|t| crate::dxf_ext::parse_layer_states(&t)) {
d.layer_states = states;
}
d.layer_states = states;
// The drawing's plot style tables.
if let Some(tables) = self.xrecord_text(crate::dxf_ext::PLOT_STYLES_KEY).and_then(|t| crate::dxf_ext::parse_plot_styles(&t)) {
d.plot_style_tables = tables;
@@ -308,20 +231,6 @@ impl Objects {
}
}
/// An object's owner (its first group 330 outside a `102` group), upper case.
fn owner(tags: &[Tag]) -> Option<String> {
let mut inside = false;
for t in tags {
match t.code {
102 => inside = t.str().trim().starts_with('{'),
330 if !inside => return Some(t.str().trim().to_ascii_uppercase()),
100 => return None,
_ => {}
}
}
None
}
/// Page setup from a LAYOUT object's AcDbPlotSettings fields (sizes and margins in mm).
pub(super) fn page_setup(t: &T) -> PageSetup {
let mut p = PageSetup::default();
-2
View File
@@ -58,8 +58,6 @@ pub(super) struct Ctx {
pub(super) frozen_341: bool,
/// MTEXT columns as the legacy groups 75..79 even from R2018 (the groups AutoLISP lists).
pub(super) legacy_columns: bool,
/// Saved layer states in AutoCAD's form (the LAYER table's extension dictionary).
pub(super) layer_states: crate::dxf_layer_states::Plan,
}
impl Ctx {
-8
View File
@@ -143,18 +143,10 @@ pub(super) fn vport_table(w: &mut W, d: &Drawing, ext: Bounds2) {
}
pub(super) fn table_head(w: &mut W, name: &str, count: usize) -> String {
table_head_x(w, name, count, None)
}
/// A table's head, with its extension dictionary `xdict` when it has one.
pub(super) fn table_head_x(w: &mut W, name: &str, count: usize, xdict: Option<&str>) -> String {
let h = w.h();
w.s(0, "TABLE");
w.s(2, name);
w.s(5, h.clone());
if let Some(x) = xdict {
w.group("ACAD_XDICTIONARY", 360, &[x]);
}
w.s(330, "0");
w.s(100, "AcDbSymbolTable");
w.i(70, count as i64);
+8 -29
View File
@@ -4,7 +4,7 @@ use super::common::annotative_xdata;
use super::ctx::{AssocObj, Ctx};
use super::entity::{entity, hatch_reactors};
use super::header::{code_page, header_vars};
use super::layout::{paper_views, record_head, sheet_first, table_head, table_head_x, vport_table};
use super::layout::{paper_views, record_head, sheet_first, table_head, vport_table};
use super::objects::{cadcraft_fonts_name, group_obj, mleader_style_obj, scale_list, table_style_obj};
use super::{
Block, Color, DimStyle, DimVal, Drawing, Entity, EntityKind, EntityStore, Group, HVal, Handle, HashMap, Layout, MLeaderStyle, PageSetup, Space,
@@ -68,7 +68,7 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
}
}
w.s(0, "ENDTAB");
write_layer_table(w, d, &mut cx.layer_states);
write_layer_table(w, d);
// STYLE. Linetype shapes from a shape file that isn't a text style get an unnamed shape
// style record (70 bit 1) naming the file.
let mut shape_files: Vec<String> = Vec::new();
@@ -185,12 +185,8 @@ fn write_tables(w: &mut W, plan: TableWritePlan<'_>) -> HashMap<String, String>
ltype_handles
}
/// The LAYER table; when the drawing has layer states AutoCAD can hold, the table's extension
/// dictionary holds them (written with the objects, [`crate::dxf_layer_states`]).
fn write_layer_table(w: &mut W, d: &Drawing, states: &mut crate::dxf_layer_states::Plan) {
let xdict = (!states.is_empty()).then(|| states.xdict.clone());
let th = table_head_x(w, "LAYER", d.layers.len(), xdict.as_deref());
states.table.clone_from(&th);
fn write_layer_table(w: &mut W, d: &Drawing) {
let th = table_head(w, "LAYER", d.layers.len());
for l in &d.layers {
let lh = record_head(w, "LAYER", &th, "AcDbLayerTableRecord");
w.layers.insert(l.name.to_ascii_uppercase(), lh);
@@ -753,16 +749,6 @@ fn write_objects(w: &mut W, plan: ObjectWritePlan<'_>) {
write_root_group_objects(w, &plan, &groups, &group_owner, &written, &mleader_dict);
write_style_objects(w, &plan, &mleader_dict, &mleader_handles);
write_named_objects(w, &plan);
let layer_states = {
let refs = crate::dxf_layer_states::Refs {
layers: &w.layers,
ltypes: &plan.cx.ltypes,
pstyles: &w.pstyles,
colour_dependent: plan.d.header.i64("PSTYLEMODE", 1) != 0,
};
crate::dxf_layer_states::objects(&plan.cx.layer_states, &plan.d.layer_states, &refs)
};
w.t.extend(layer_states);
write_associative_objects(w, plan.cx);
write_layout_objects(w, &plan);
// Raster image definitions.
@@ -993,9 +979,7 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
if let Some(chunks) = dxf_ext::constraint_chunks(&d.constraints, &d.parametric) {
xrecords.push((dxf_ext::CONSTRAINTS_KEY, w.h(), chunks));
}
// Saved layer states: AutoCAD's dictionary holds those it can, CADCraft's record the others.
cx.layer_states = crate::dxf_layer_states::Plan::new(&d.layer_states, || w.h());
if let Some(chunks) = dxf_ext::layer_state_chunks(&crate::dxf_layer_states::own(&d.layer_states)) {
if let Some(chunks) = dxf_ext::layer_state_chunks(&d.layer_states) {
xrecords.push((dxf_ext::LAYER_STATES_KEY, w.h(), chunks));
}
if let Some(chunks) = dxf_ext::plot_style_chunks(&d.plot_style_tables) {
@@ -1007,19 +991,14 @@ pub(super) fn tags_for(d: &Drawing, version: Version, target: Version, frozen_34
// The annotation scale list: the ACAD_SCALELIST dictionary of SCALE objects.
let scale_dict = w.h();
let scales: Vec<(&cadcraft_doc::AnnoScale, String)> = d.scales.iter().filter(|s| s.is_valid()).map(|s| (s, w.h())).collect();
// Plot style names used by layers and objects (Normal always), each a placeholder object; in
// a drawing of named plot styles also those of the layers of saved layer states, which name
// theirs by placeholder.
// Plot style names used by layers and objects (Normal always), each a placeholder object.
let pstyle_dict = w.h();
let mut pstyle_names: Vec<String> = vec![cadcraft_doc::NORMAL_STYLE.to_string()];
let mut seen: std::collections::HashSet<String> = pstyle_names.iter().map(|n| n.to_ascii_uppercase()).collect();
let named_styles = d.header.i64("PSTYLEMODE", 1) == 0;
let in_states = d.layer_states.iter().filter(|_| named_styles).flat_map(|s| s.layers.iter());
let named = d.layers.iter().chain(in_states).map(|l| l.plot_style.as_str()).chain(every.iter().map(|e| e.common.plot_style.as_str()));
let named = d.layers.iter().map(|l| l.plot_style.as_str()).chain(every.iter().map(|e| e.common.plot_style.as_str()));
for n in named {
let n = n.trim();
let logical = n.is_empty() || n.eq_ignore_ascii_case("bylayer") || n.eq_ignore_ascii_case("byblock");
if !logical && pstyle_names.len() < dxf_ext::MAX_PLOT_STYLE_NAMES && seen.insert(n.to_ascii_uppercase()) {
if !logical && pstyle_names.len() < dxf_ext::MAX_PLOT_STYLE_NAMES && !pstyle_names.iter().any(|x| x.eq_ignore_ascii_case(n)) {
pstyle_names.push(n.to_string());
}
}
-1
View File
@@ -9,7 +9,6 @@ mod dxf_raw;
mod dxf_clip;
mod dxf_ext;
mod dxf_image;
mod dxf_layer_states;
mod dxf_mleader;
mod dxf_read;
mod dxf_table;
+5 -17
View File
@@ -1856,24 +1856,22 @@ fn layer_states_roundtrip_next_to_constraints() {
description: "walls \\ hidden".into(),
..Layer::default()
});
d.layer_states.push(LayerState::new("Plot", d.layers.clone(), "Wände"));
d.layer_states.push(LayerState { name: "Plot".into(), layers: d.layers.clone() });
let mut off = d.layers.clone();
for l in &mut off {
(l.on, l.frozen, l.locked, l.plot) = (false, true, true, false);
}
d.layer_states.push(LayerState::new("All off", off, ""));
d.layer_states.push(LayerState { name: "All off".into(), layers: off });
let text = write_dxf(&d);
// AutoCAD's dictionary holds both states; CADCraft's record isn't needed.
assert!(text.contains("ACAD_LAYERSTATES") && !text.contains("CADCRAFT_LAYERSTATES"));
assert!(text.contains("CADCRAFT_LAYERSTATES"));
let back = read_dxf(text.as_bytes()).unwrap();
assert_eq!(back.layer_states, d.layer_states);
assert_eq!(back.constraints, constraints);
assert_eq!(roundtrip(&back).layer_states, d.layer_states);
#[cfg(not(target_arch = "wasm32"))]
assert_eq!(read(&write(&d, "x.dwg").unwrap(), "x.dwg").unwrap().layer_states, d.layer_states);
// Drawings without saved layer states carry neither.
let none = write_dxf(&Drawing::new_imperial());
assert!(!none.contains("CADCRAFT_LAYERSTATES") && !none.contains("ACAD_LAYERSTATES"));
// Drawings without saved layer states carry no record.
assert!(!write_dxf(&Drawing::new_imperial()).contains("CADCRAFT_LAYERSTATES"));
}
fn table_sample() -> Table {
@@ -3715,13 +3713,3 @@ fn solid_hatch_keeps_angle_scale_and_double_flag() {
assert!(f("41").is_some_and(|s| (s - 2.0).abs() < 1e-12), "{h:?}");
assert_eq!(group(h, "77"), Some("0"), "{h:?}");
}
/// A layer state of CADCraft's own record from before states had a mask, a current layer and a
/// description (its JSON holds only the name and the layers) restores every property and names no
/// current layer.
#[test]
fn a_layer_state_saved_before_masks_restores_everything() {
let states = crate::dxf_ext::parse_layer_states(r#"{"version":1,"states":[{"name":"S","layers":[]}]}"#).unwrap();
let got: Vec<(&str, u32, &str, &str)> = states.iter().map(|s| (s.name.as_str(), s.mask, s.current.as_str(), s.description.as_str())).collect();
assert_eq!(got, [("S", LayerState::ALL, "", "")]);
}
-451
View File
@@ -1,451 +0,0 @@
//! Saved layer states in AutoCAD's form: the LAYER table's extension dictionary holds an
//! `ACAD_LAYERSTATES` dictionary of one XRECORD per state. The groups below are copied from
//! AutoCAD 2024's own DXFOUT of states saved with -LAYER stAte on a self-built drawing.
use cadcraft_color::{Color, Rgb};
use cadcraft_doc::{Drawing, Layer, LayerState, Lineweight};
use cadcraft_io::{read, write_dxf};
/// `(code, value)` pairs of a DXF, trimmed.
fn pairs(dxf: &str) -> Vec<(String, String)> {
let lines: Vec<&str> = dxf.lines().collect();
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
}
fn join(p: &[(String, String)]) -> String {
p.iter().map(|(c, v)| format!("{c}\n{v}\n")).collect()
}
fn g(c: &str, v: &str) -> (String, String) {
(c.to_string(), v.to_string())
}
/// The records of a DXF: (type, groups after the `0`).
fn records(p: &[(String, String)]) -> Vec<(String, Vec<(String, String)>)> {
let mut out: Vec<(String, Vec<(String, String)>)> = Vec::new();
for (c, v) in p {
if c == "0" {
out.push((v.clone(), Vec::new()));
} else if let Some(last) = out.last_mut() {
last.1.push((c.clone(), v.clone()));
}
}
out
}
fn value<'a>(groups: &'a [(String, String)], code: &str) -> Option<&'a str> {
groups.iter().find(|(c, _)| c == code).map(|(_, v)| v.as_str())
}
/// The handle of table record `kind` named `name`.
fn record_handle(p: &[(String, String)], kind: &str, name: &str) -> String {
let recs = records(p);
let (_, groups) = recs.iter().find(|(k, gs)| k == kind && value(gs, "2").is_some_and(|n| n.eq_ignore_ascii_case(name))).unwrap();
value(groups, "5").unwrap().to_string()
}
/// A handle above every handle of the file, plus `k`.
fn fresh(p: &[(String, String)], k: u64) -> String {
let top = p.iter().filter(|(c, _)| c == "5" || c == "105").filter_map(|(_, v)| u64::from_str_radix(v, 16).ok()).max().unwrap();
format!("{:X}", top + 0x100 + k)
}
/// `dxf` with the LAYER table given extension dictionary `xdict` and `objects` added at the end
/// of OBJECTS.
fn inject(dxf: &str, xdict: &str, objects: Vec<(String, String)>) -> String {
let mut p = pairs(dxf);
let table = p.iter().enumerate().position(|(i, (c, v))| c == "0" && v == "TABLE" && p.get(i + 1).is_some_and(|n| n.1 == "LAYER")).unwrap();
let at = table + p[table..].iter().position(|(c, _)| c == "5").unwrap() + 1;
p.splice(at..at, [g("102", "{ACAD_XDICTIONARY"), g("360", xdict), g("102", "}")]);
let objs = p.iter().position(|(c, v)| c == "2" && v == "OBJECTS").unwrap();
let end = objs + p[objs..].iter().position(|(c, v)| c == "0" && v == "ENDSEC").unwrap();
p.splice(end..end, objects);
join(&p)
}
/// Layers A (red) and B, and the DASHED linetype.
fn drawing() -> Drawing {
let mut d = Drawing::new_metric();
d.layers.push(Layer { color: Color::Index(1), ..Layer::new("A") });
d.layers.push(Layer::new("B"));
d.linetypes.push(cadcraft_doc::library::standard_linetypes().into_iter().find(|l| l.name == "DASHED").unwrap());
d
}
/// State S2 as AutoCAD 2024 wrote it after -LAYER: A true colour 10,20,30 (nearest index 168),
/// 50% transparent, 0.35 mm, DASHED, not plotted; B locked and frozen in new viewports. Then the
/// entry of a layer purged since (AutoCAD keeps it, pointing at handles that are gone).
fn s2(p: &[(String, String)], rec: &str, dict: &str) -> Vec<(String, String)> {
let (a, b, zero) = (record_handle(p, "LAYER", "A"), record_handle(p, "LAYER", "B"), record_handle(p, "LAYER", "0"));
let (cont, dashed) = (record_handle(p, "LTYPE", "Continuous"), record_handle(p, "LTYPE", "DASHED"));
let gone = fresh(p, 0x50);
let mut v =
vec![g("0", "XRECORD"), g("5", rec), g("102", "{ACAD_REACTORS"), g("330", dict), g("102", "}"), g("330", dict), g("100", "AcDbXrecord")];
v.extend([g("280", "1"), g("91", "2047"), g("301", ""), g("290", "0"), g("302", "0")]);
for (h, flags, aci, lw, lt, ps, tr) in [
(b.as_str(), "28", "7", "-3", cont.as_str(), "Color_7", "0"),
(a.as_str(), "0", "168", "35", dashed.as_str(), "Color_168", "33554559"),
(zero.as_str(), "8", "7", "-3", cont.as_str(), "Color_7", "0"),
(gone.as_str(), "8", "7", "-3", gone.as_str(), "Color_7", "0"),
] {
v.extend([g("330", h), g("90", flags), g("62", aci), g("370", lw), g("331", lt), g("1", ps), g("440", tr)]);
if h == a {
v.push(g("92", "-1039526882"));
}
}
v
}
/// State S7, saved with only On and restored once (AutoCAD then sets bit 65536), current layer A.
fn s7(p: &[(String, String)], rec: &str, dict: &str) -> Vec<(String, String)> {
let (a, b) = (record_handle(p, "LAYER", "A"), record_handle(p, "LAYER", "B"));
let cont = record_handle(p, "LTYPE", "Continuous");
let mut v =
vec![g("0", "XRECORD"), g("5", rec), g("102", "{ACAD_REACTORS"), g("330", dict), g("102", "}"), g("330", dict), g("100", "AcDbXrecord")];
v.extend([g("280", "1"), g("91", "66049"), g("301", "only on"), g("290", "0"), g("302", "A")]);
for (h, aci) in [(b.as_str(), "7"), (a.as_str(), "1")] {
v.extend([g("330", h), g("90", "8"), g("62", aci), g("370", "-3"), g("331", &cont), g("1", &format!("Color_{aci}")), g("440", "0")]);
}
v
}
/// The extension dictionary of the LAYER table and the states dictionary, with `extra` entries in
/// the extension dictionary.
fn dictionaries(p: &[(String, String)], x: &str, y: &str, states: &[(&str, &str)], extra: &[(&str, &str)]) -> Vec<(String, String)> {
let table = {
let recs = records(p);
let (_, gs) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
value(gs, "5").unwrap().to_string()
};
let mut v = vec![g("0", "DICTIONARY"), g("5", x), g("330", &table), g("100", "AcDbDictionary"), g("280", "1"), g("281", "1")];
for (k, h) in extra.iter().copied().chain([("ACAD_LAYERSTATES", y)]) {
v.extend([g("3", k), g("360", h)]);
}
v.extend([
g("0", "DICTIONARY"),
g("5", y),
g("102", "{ACAD_REACTORS"),
g("330", x),
g("102", "}"),
g("330", x),
g("100", "AcDbDictionary"),
g("281", "1"),
]);
for (name, h) in states {
v.extend([g("3", name), g("350", h)]);
}
v
}
fn autocad_file() -> String {
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r2, r7) = (h(1), h(2), h(3), h(4));
let mut objects = dictionaries(&p, &x, &y, &[("S2", &r2), ("S7", &r7)], &[]);
objects.extend(s2(&p, &r2, &y));
objects.extend(s7(&p, &r7, &y));
inject(&base, &x, objects)
}
#[test]
fn reads_the_layer_states_autocad_writes() {
let d = read(autocad_file().as_bytes(), "acad.dxf").unwrap();
let names: Vec<&str> = d.layer_states.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names, ["S2", "S7"]);
let s2 = &d.layer_states[0];
assert_eq!((s2.mask, s2.current.as_str(), s2.description.as_str()), (2047, "0", ""));
// The purged layer's entry is skipped.
let layers: Vec<&str> = s2.layers.iter().map(|l| l.name.as_str()).collect();
assert_eq!(layers, ["B", "A", "0"]);
let a = &s2.layers[1];
assert_eq!(a.color, Color::True(Rgb(10, 20, 30)));
assert_eq!((a.transparency, a.lineweight, a.linetype.as_str()), (50, Lineweight::from_dxf(35), "DASHED"));
assert!(a.on && !a.frozen && !a.locked && !a.plot && !a.vp_freeze_new);
// A colour-dependent drawing: the plot style stays the layer's ("Color_168" is its colour's).
assert_eq!(a.plot_style, "Normal");
let b = &s2.layers[0];
assert!(b.on && !b.frozen && b.locked && b.plot && b.vp_freeze_new, "{b:?}");
assert_eq!((b.color, b.linetype.as_str(), b.transparency), (Color::Index(7), "Continuous", 0));
let s7 = &d.layer_states[1];
assert_eq!((s7.mask, s7.current.as_str(), s7.description.as_str()), (66049, "A", "only on"));
assert_eq!(s7.layers.iter().find(|l| l.name == "A").unwrap().color, Color::Index(1));
}
#[test]
fn autocads_layer_states_are_written_back_in_its_form() {
let d = read(autocad_file().as_bytes(), "acad.dxf").unwrap();
let text = write_dxf(&d);
let p = pairs(&text);
// One states dictionary, in the LAYER table's extension dictionary, and no CADCraft copy.
assert_eq!(p.iter().filter(|(c, v)| c == "3" && v == "ACAD_LAYERSTATES").count(), 1);
assert!(!text.contains("CADCRAFT_LAYERSTATES"));
let recs = records(&p);
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
let x = table.windows(2).find(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).unwrap();
let (_, xd) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(x.as_str())).unwrap();
assert_eq!(value(xd, "330"), value(table, "5"));
let back = read(text.as_bytes(), "back.dxf").unwrap();
assert_eq!(back.layer_states, d.layer_states);
// The XRECORD of S2 as AutoCAD writes it: B, then A.
let (a_h, b_h) = (record_handle(&p, "LAYER", "A"), record_handle(&p, "LAYER", "B"));
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
let head = rec.iter().position(|(c, _)| c == "280").unwrap();
assert_eq!(rec[head..head + 5], [("280", "1"), ("91", "2047"), ("301", ""), ("290", "0"), ("302", "0")].map(|(c, v)| g(c, v)));
let cont = record_handle(&p, "LTYPE", "Continuous");
let b = [("330", b_h.as_str()), ("90", "28"), ("62", "7"), ("370", "-3"), ("331", &cont), ("1", "Color_7"), ("440", "0")];
assert_eq!(rec[head + 5..head + 12], b.map(|(c, v)| g(c, v)));
let from = rec.iter().position(|(c, v)| c == "330" && *v == a_h).unwrap();
let a: Vec<(String, String)> = rec[from..from + 9].to_vec();
let dashed = record_handle(&p, "LTYPE", "DASHED");
let want = [
("330", a_h.as_str()),
("90", "0"),
("62", "168"),
("370", "35"),
("331", &dashed),
("1", "Color_168"),
("440", "33554559"),
("92", "-1039526882"),
];
assert_eq!(a[..8], want.map(|(c, v)| g(c, v)), "{a:?}");
#[cfg(not(target_arch = "wasm32"))]
{
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
assert_eq!(read(&dwg, "x.dwg").unwrap().layer_states, d.layer_states);
}
}
#[test]
fn layer_filters_next_to_the_states_are_kept() {
// The LAYER table's extension dictionary of a drawing with layer filters holds them next to
// the states (ACAD_LAYERFILTERS, ACLYDICTIONARY): they stay, in the dictionary CADCraft writes.
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r2, f, fr, gone) = (h(1), h(2), h(3), h(4), h(5), h(6));
// Two entries whose objects the file doesn't have (a handle of nothing, and a null one): they
// aren't written into the table's dictionary.
let extra = [("ACAD_LAYERFILTERS", f.as_str()), ("OTHER_GONE", gone.as_str()), ("OTHER_NULL", "0")];
let mut objects = dictionaries(&p, &x, &y, &[("S2", &r2)], &extra);
objects.extend(s2(&p, &r2, &y));
objects.extend([g("0", "DICTIONARY"), g("5", &f), g("102", "{ACAD_REACTORS"), g("330", &x), g("102", "}"), g("330", &x)]);
objects.extend([g("100", "AcDbDictionary"), g("281", "1"), g("3", "Walls"), g("350", &fr)]);
objects.extend([g("0", "XRECORD"), g("5", &fr), g("102", "{ACAD_REACTORS"), g("330", &f), g("102", "}"), g("330", &f), g("100", "AcDbXrecord")]);
objects.extend([g("280", "1"), g("1", "A*")]);
let file = inject(&base, &x, objects);
let mut text = file;
for round in 0..2 {
let d = read(text.as_bytes(), "f.dxf").unwrap();
assert_eq!(d.layer_states.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["S2"], "round {round}");
text = write_dxf(&d);
let p = pairs(&text);
let recs = records(&p);
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
let xdicts: Vec<String> = table.windows(2).filter(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).collect();
assert_eq!(xdicts.len(), 1, "round {round}");
let xd = &xdicts[0];
let (_, dict) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(xd.as_str())).unwrap();
let keys: Vec<&str> = dict.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.as_str()).collect();
assert_eq!(keys, ["ACAD_LAYERSTATES", "ACAD_LAYERFILTERS"], "round {round}");
// The filters dictionary is owned by the written one, and so is its filter by it.
let fh = dict.windows(2).find(|w| w[0] == g("3", "ACAD_LAYERFILTERS")).map(|w| w[1].1.clone()).unwrap();
let (_, fd) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(fh.as_str())).unwrap();
let owner = fd.iter().filter(|(c, _)| c == "330").map(|(_, v)| v.as_str()).collect::<Vec<_>>();
assert_eq!(owner, [xd.as_str(), xd.as_str()], "round {round}: reactor and owner");
let walls = value(fd, "350").unwrap();
let (_, wr) = recs.iter().find(|(k, gs)| k == "XRECORD" && value(gs, "5") == Some(walls)).unwrap();
assert!(wr.contains(&g("330", &fh)) && wr.contains(&g("1", "A*")), "round {round}");
// The kept dictionary itself is not written a second time.
assert_eq!(recs.iter().filter(|(k, gs)| k == "DICTIONARY" && gs.iter().any(|(c, v)| c == "3" && v == "ACAD_LAYERFILTERS")).count(), 1);
}
// With every state deleted the filters stay, in the table's own dictionary, and AutoCAD's states
// don't come back.
let mut d = read(text.as_bytes(), "f.dxf").unwrap();
d.layer_states.clear();
let text = write_dxf(&d);
assert!(!text.contains("ACAD_LAYERSTATES"));
let p = pairs(&text);
let recs = records(&p);
let (_, table) = recs.iter().find(|(k, gs)| k == "TABLE" && value(gs, "2") == Some("LAYER")).unwrap();
let xd = table.windows(2).find(|w| w[0] == g("102", "{ACAD_XDICTIONARY")).map(|w| w[1].1.clone()).unwrap();
let (_, dict) = recs.iter().find(|(k, gs)| k == "DICTIONARY" && value(gs, "5") == Some(xd.as_str())).unwrap();
assert_eq!(dict.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.as_str()).collect::<Vec<_>>(), ["ACAD_LAYERFILTERS"]);
assert!(read(text.as_bytes(), "g.dxf").unwrap().layer_states.is_empty());
}
#[test]
fn entries_whose_names_differ_only_in_case_open_as_one_state() {
// AutoCAD 2024 opens the entries `S` and `s` of one ACAD_LAYERSTATES dictionary as one state:
// named as the first entry in the dictionary and holding the last entry's record (measured with
// the records in one file order and the entries in both dictionary orders, so the first entry's
// record came first in the file once and last once). Here S2's record (mask 2047) comes first in
// the file, then state T's, then S7's (66049); the merged state stays where S2's record is.
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r2, r7, rt) = (h(1), h(2), h(3), h(4), h(5));
let states = |d: &Drawing| d.layer_states.iter().map(|s| (s.name.clone(), s.mask)).collect::<Vec<_>>();
for (pair, name, mask) in [([("S", r2.as_str()), ("s", r7.as_str())], "S", 66049), ([("s", r7.as_str()), ("S", r2.as_str())], "s", 2047)] {
let entries = [pair[0], ("T", rt.as_str()), pair[1]];
let mut objects = dictionaries(&p, &x, &y, &entries, &[]);
objects.extend(s2(&p, &r2, &y));
objects.extend(s7(&p, &rt, &y));
objects.extend(s7(&p, &r7, &y));
let d = read(inject(&base, &x, objects).as_bytes(), "case.dxf").unwrap();
let want = [(name.to_string(), mask), ("T".to_string(), 66049)];
assert_eq!(states(&d), want, "{entries:?}");
// Written back, they are the states AutoCAD opened.
let back = read(write_dxf(&d).as_bytes(), "back.dxf").unwrap();
assert_eq!(states(&back), want, "{entries:?}");
}
// A record the dictionary lists as `s` but another object owns isn't a state, and doesn't stand
// in for S's record either.
let mut objects = dictionaries(&p, &x, &y, &[("S", r2.as_str()), ("s", r7.as_str())], &[]);
objects.extend(s2(&p, &r2, &y));
objects.extend(s7(&p, &r7, &x));
let d = read(inject(&base, &x, objects).as_bytes(), "stray.dxf").unwrap();
assert_eq!(states(&d), [("S".to_string(), 2047)]);
}
#[test]
fn view_snapshots_and_names_twice_in_another_case_stay_in_cadcrafts_record() {
let mut d = drawing();
for name in ["Plan", "*VIEW Front", "PLAN", "Wände", "WÄNDE", "", " "] {
d.layer_states.push(LayerState::new(name, d.layers.clone(), "A"));
}
let text = write_dxf(&d);
let p = pairs(&text);
let recs = records(&p);
let (_, states) =
recs.iter().find(|(k, gs)| k == "DICTIONARY" && gs.contains(&g("281", "1")) && gs.iter().any(|(c, v)| c == "3" && v == "Plan")).unwrap();
// (The DXF writes "ä" as \U+00E4.)
let keys: Vec<String> = states.iter().filter(|(c, _)| c == "3").map(|(_, v)| v.replace("\\U+00E4", "ä")).collect();
assert_eq!(keys, ["Plan", "Wände"], "AutoCAD's dictionary holds the first of each name");
assert!(text.contains("CADCRAFT_LAYERSTATES"));
let back = read(text.as_bytes(), "v.dxf").unwrap();
// AutoCAD's states first, then CADCraft's own.
// (A blank name can't be a key of AutoCAD's dictionary: those stay in CADCraft's record too.)
let want: Vec<LayerState> = [0, 3, 1, 2, 4, 5, 6].iter().map(|&i| d.layer_states[i].clone()).collect();
assert_eq!(back.layer_states, want);
#[cfg(not(target_arch = "wasm32"))]
{
let dwg = cadcraft_io::write(&d, "v.dwg").unwrap();
assert_eq!(read(&dwg, "v.dwg").unwrap().layer_states, want);
}
}
#[test]
fn a_layer_of_an_xref_gets_group_93() {
// AutoCAD 2024 writes 93 (0 for a newly attached xref) after the lineweight of an xref's layer
// only (measured with a self-built xref).
let mut d = drawing();
d.layers.push(Layer::new("XR|L1"));
d.layer_states.push(LayerState::new("X", d.layers.clone(), "0"));
let p = pairs(&write_dxf(&d));
let recs = records(&p);
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
let start = rec.iter().position(|(c, _)| c == "302").unwrap() + 1;
let mut with_93 = Vec::new();
let mut layer = String::new();
for (i, (c, v)) in rec.iter().enumerate().skip(start) {
match c.as_str() {
"330" => layer.clone_from(v),
"93" => {
assert_eq!((v.as_str(), rec[i - 1].0.as_str(), rec[i + 1].0.as_str()), ("0", "370", "331"));
with_93.push(layer.clone());
}
_ => {}
}
}
assert_eq!(with_93, [record_handle(&p, "LAYER", "XR|L1")]);
}
#[test]
fn named_plot_styles_are_written_by_placeholder() {
// In a drawing of named plot styles AutoCAD 2024 writes a layer's plot style as group 390, the
// handle of the style's placeholder object (measured); CADCraft reads it back by that handle.
let mut d = drawing();
d.header.set_i64("PSTYLEMODE", 0);
let a = d.layers.iter().position(|l| l.name == "A").unwrap();
d.layers[a].plot_style = "Thick".into();
d.layer_states.push(LayerState::new("N", d.layers.clone(), "0"));
// No layer uses Thick any more: its placeholder is written for the state.
d.layers[a].plot_style = "Normal".into();
let text = write_dxf(&d);
let p = pairs(&text);
let recs = records(&p);
let (_, names) = recs.iter().find(|(k, _)| k == "ACDBDICTIONARYWDFLT").unwrap();
let thick = names.windows(2).find(|w| w[0] == g("3", "Thick")).map(|w| w[1].1.clone()).unwrap();
let (_, rec) = recs.iter().find(|(k, gs)| k == "XRECORD" && gs.contains(&g("91", "2047"))).unwrap();
assert!(rec.contains(&g("390", &thick)) && !rec.iter().any(|(c, _)| c == "1"), "{rec:?}");
let back = read(text.as_bytes(), "n.dxf").unwrap();
assert_eq!(back.layer_states[0].layers.iter().find(|l| l.name == "A").unwrap().plot_style, "Thick");
assert_eq!(back.layer_states, d.layer_states);
#[cfg(not(target_arch = "wasm32"))]
{
let dwg = cadcraft_io::write(&d, "n.dwg").unwrap();
assert_eq!(read(&dwg, "n.dwg").unwrap().layer_states, d.layer_states);
}
}
#[test]
fn a_state_in_both_records_is_read_from_autocads() {
// A file of an earlier CADCraft keeps its states in CADCraft's record; AutoCAD then saves a state
// of the same name in its own dictionary: AutoCAD's is the one read.
let mut d = drawing();
d.layer_states.push(LayerState::new("S", d.layers.clone(), "A"));
d.layer_states.push(LayerState::new("*VIEW S", d.layers.clone(), "B"));
let text = write_dxf(&d);
assert!(text.contains("*VIEW S"));
let text = text.replace("*VIEW S", "S");
let back = read(text.as_bytes(), "both.dxf").unwrap();
assert_eq!(back.layer_states.iter().map(|s| (s.name.as_str(), s.current.as_str())).collect::<Vec<_>>(), [("S", "A")]);
}
#[test]
fn states_past_the_limit_are_left_out_and_the_rest_come_in_file_order() {
// A hostile file with one state more than the reader keeps (100 000): the last one in the file
// is left out, and the others come in file order, here the reverse of their names' order.
const LIMIT: u64 = 100_000;
let base = write_dxf(&drawing());
let p = pairs(&base);
let first = u64::from_str_radix(&fresh(&p, 0), 16).unwrap();
let h = |k: u64| format!("{:X}", first + k);
let (x, y) = (h(1), h(2));
let names: Vec<String> = (0..=LIMIT).map(|i| format!("S{:06}", LIMIT + 1 - i)).collect();
let records: Vec<String> = (0..=LIMIT).map(|i| h(3 + i)).collect();
let entries: Vec<(&str, &str)> = names.iter().map(String::as_str).zip(records.iter().map(String::as_str)).collect();
let mut objects = dictionaries(&p, &x, &y, &entries, &[]);
for r in &records {
objects.extend([g("0", "XRECORD"), g("5", r), g("330", &y), g("100", "AcDbXrecord")]);
objects.extend([g("280", "1"), g("91", "2047"), g("301", ""), g("290", "0"), g("302", "0")]);
}
let d = read(inject(&base, &x, objects).as_bytes(), "many.dxf").unwrap();
let names: Vec<&str> = d.layer_states.iter().map(|s| s.name.as_str()).collect();
assert_eq!(names.len(), 100_000);
assert_eq!((names.first().copied(), names.get(1).copied(), names.last().copied()), (Some("S100001"), Some("S100000"), Some("S000002")));
}
#[test]
fn a_record_twice_in_a_file_is_one_state() {
// A damaged file can hold an object twice under one handle: one state.
let base = write_dxf(&drawing());
let p = pairs(&base);
let h = |k| fresh(&p, k);
let (x, y, r7) = (h(1), h(2), h(4));
let mut objects = dictionaries(&p, &x, &y, &[("S7", &r7)], &[]);
objects.extend(s7(&p, &r7, &y));
objects.extend(s7(&p, &r7, &y));
let d = read(inject(&base, &x, objects).as_bytes(), "twice.dxf").unwrap();
assert_eq!(d.layer_states.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["S7"]);
}
#[test]
fn group_92_without_the_true_colour_prefix_is_not_a_true_colour() {
// AutoCAD 2024 writes 92 only for a true colour, 0xC2RRGGBB (measured); a value with another
// high byte (not seen from AutoCAD) leaves the colour index of group 62.
let text = autocad_file().replace("92\n-1039526882", "92\n-1023410175");
let d = read(text.as_bytes(), "c3.dxf").unwrap();
assert_eq!(d.layer_states[0].layers.iter().find(|l| l.name == "A").unwrap().color, Color::Index(168));
}
-1
View File
@@ -32,7 +32,6 @@ mod groups_roundtrip;
mod hatch_assoc_roundtrip;
mod hatch_pattern_def;
mod helix_roundtrip;
mod layer_states_acad;
mod layout_limits_roundtrip;
mod layout_paper_units;
mod layout_plot_window;
+1 -1
View File
@@ -185,7 +185,7 @@ pub(super) fn layer_states() -> Case {
layer.on = false;
layer.locked = true;
}
drawing.layer_states.push(LayerState::new("Saved", layers, "0"));
drawing.layer_states.push(LayerState { name: "Saved".into(), layers });
Case { name: "drawing/layer-state".into(), drawing }
}
+5 -15
View File
@@ -492,16 +492,11 @@ const OBJECTS: &str = "
330 61
100 AcDbXrecord
280 1
91 2047
91 0
301 Plan
290 0
302 0
330 11
90 8
8 WALLS
90 0
62 1
370 -3
1 Normal
440 0
0 DICTIONARY
5 63
330 10
@@ -808,19 +803,14 @@ fn ucs_layer_states_and_block_descriptions_are_kept() {
assert_eq!((u.origin.x, u.origin.y, u.origin.z), (1.0, 2.0, 3.0));
assert_eq!((u.x_axis.y, u.y_axis.x), (1.0, -1.0));
assert_eq!(d.block("DOOR").map(|b| b.description.as_str()), Some("A door leaf"));
let states: Vec<(&str, Vec<&str>)> =
d.layer_states.iter().map(|s| (s.name.as_str(), s.layers.iter().map(|l| l.name.as_str()).collect())).collect();
assert_eq!(states, [("Plan", vec!["WALLS"])]);
for o in [&a, &b] {
// Layer states live in the LAYER table's extension dictionary, each layer named by its
// handle (as AutoCAD 2024 writes them; CADCraft reads and rewrites them).
// Layer states live in the LAYER table's extension dictionary.
let table = o.of("TABLE").into_iter().find(|t| s(t, 2) == "LAYER").expect("LAYER table");
let [xd] = group(table, "ACAD_XDICTIONARY").try_into().expect("LAYER table extension dictionary");
let (_, dict) = o.handle(&xd).expect("dictionary");
let (_, states) = o.entry(dict, "ACAD_LAYERSTATES").expect("ACAD_LAYERSTATES");
let (_, plan) = o.entry(states, "Plan").expect("layer state Plan");
let layers = plan.iter().skip_while(|t| t.code != 302).filter(|t| t.code == 330).map(Tag::str).collect::<Vec<_>>();
assert_eq!((s(plan, 301), layers), ("Plan".into(), vec![h(o.named("LAYER", "WALLS"))]));
assert_eq!((s(plan, 301), s(plan, 8)), ("Plan".into(), "WALLS".into()));
}
}
+1
View File
@@ -36,6 +36,7 @@ mod selection_cycling;
mod shared_controls;
mod shortcut_menus;
mod shortcuts_checked;
mod space_at_options;
mod status_bar_toggles;
mod style_dialogs;
mod system_cursor;
@@ -0,0 +1,59 @@
//! Space is Enter at TRIM's and EXTEND's option prompts, as at AutoCAD's (#3092): typing `O`,
//! Space, `S`, Space switches to Standard mode instead of typing a space into the command line.
use cadcraft_engine::Session;
use cadcraft_ui_egui::{CadApp, Services};
use egui::{Key, Modifiers, vec2};
use egui_kittest::Harness;
fn harness() -> Harness<'static, CadApp> {
let app = CadApp::new(Session::new(), Services::default());
let mut h = Harness::builder().with_size(vec2(1600.0, 1000.0)).build_ui_state(
|ui, app: &mut CadApp| {
app.logic(ui.ctx());
app.ui(ui);
},
app,
);
h.run_steps(3);
h
}
/// Type `text` at the keyboard: a space arrives as the Space key and as text, like a real press.
fn type_keys(h: &mut Harness<'static, CadApp>, text: &str) {
for c in text.chars() {
if c == ' ' {
h.event(egui::Event::Key { key: Key::Space, physical_key: None, pressed: true, repeat: false, modifiers: Modifiers::NONE });
}
h.event(egui::Event::Text(c.to_string()));
h.run_steps(1);
}
h.run_steps(1);
}
fn header(h: &Harness<'static, CadApp>, name: &str) -> i64 {
h.state().session.doc().unwrap().header.i64(name, -1)
}
fn prompt(h: &Harness<'static, CadApp>) -> String {
h.state().session.current_prompt().map(|p| p.message).unwrap_or_default()
}
#[test]
fn space_answers_trim_and_extend_option_prompts() {
let mut h = harness();
type_keys(&mut h, "trim o s ");
assert_eq!(h.state().cmd.buffer, "", "Space typed a space instead of entering the option");
assert_eq!(header(&h, "TRIMEXTENDMODE"), 0, "S chose Standard mode");
// Standard mode asks for cutting edges; Enter selects all, then Project and Edge.
type_keys(&mut h, " p n e e ");
assert_eq!(h.state().cmd.buffer, "");
assert_eq!(header(&h, "PROJMODE"), 0, "N chose no projection");
assert_eq!(header(&h, "EDGEMODE"), 1, "E chose Extend");
assert!(prompt(&h).starts_with("Select object to trim"), "back at the trim prompt: {}", prompt(&h));
h.key_press(Key::Escape);
h.run_steps(2);
type_keys(&mut h, "extend o q ");
assert_eq!(h.state().cmd.buffer, "");
assert_eq!(header(&h, "TRIMEXTENDMODE"), 1, "Q chose Quick mode in EXTEND");
}