Compare commits

..
Author SHA1 Message Date
FredApps 8c0f7658a3 Release: CADCraft v0.21.0 (main 66931918cb)
Merge main into release. The tree equals main 66931918cb.
2026-11-28 21:39:43 +01:00
Dylan M. Taylor 66931918cb ci(nightly): enable all signed Linux package formats (deb, rpm, appimage, flatpak, oci, arch) (#3618) 2026-11-28 15:25:02 -05:00
95af8ba086 Add Russian translation (ru) (#3378)
* Add Russian translation (ru).

Update the in-app Russian catalog and add Russian strings to the
Linux desktop, AppStream, and MIME metadata.

Copyright (c) 2026 SuperSfera LLC, MIT OR Apache-2.0.

* ru: address review (metainfo license notice)

* i18n(ru): apply review suggestions from #2296

* i18n(ru): keep a single copy of the translation notice

The desktop entry, MIME file and Russian catalog repeated the same copyright line. The notice text itself is unchanged.

Co-authored-by: sesaposa1 <[email protected]>

* i18n(ru): translate Generate Boundary

The hatch command label was the one English command name still absent from the catalog. It follows the catalog's own Boundary / Create wording.

Co-authored-by: sesaposa1 <[email protected]>

* ru: state CC0-1.0 for Russian metainfo strings

* ru: remove the per-file translation notices

The translation is under the repository's licence, and authorship is in git history.

* i18n(ru): 15 strings added on main since the last catch-up

Array dialog fields and the update and right-click option hints.
Docs counts updated to 2,274 rows.

---------

Co-authored-by: Cursor Agent <[email protected]>
Co-authored-by: sesaposa1 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 21:00:12 +01:00
fcaf13da40 i18n(cs): bring the Czech catalog up to date (#1579)
* i18n(cs): translate the 115 strings added since the Czech catalog

Adds Czech rows for every key of the Ukrainian reference catalog that the
code looks up and cs.tsv was missing: the 3D mouse window and its status
messages, the Hatch and Gradient dialog, the Block Editor and dynamic block
commands, multileader editing, Options (selection, grips, selection preview
and automatic save), the MTEXT editor toolbar, palette tool sets and recent
files. 1,214 -> 1,329 rows; the i18n tests now report no Czech gaps.

"SVG drawings (SVG, SVGZ)" is left out: no production code looks it up.

Rows are inserted in the reference catalog's order; existing rows are
unchanged. Translations are original, written from the meaning of the
English strings (AI-assisted, not yet proofread by a native speaker).
docs/localization.md and docs/localization-parity.md updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): review fixes for the new Czech rows

Independent review of the 115 rows added in the previous change:

- Hatch Pick: "Výběr pro šrafy", matching the existing helper command
  QuickCalc Pick ("Výběr pro rychlou kalkulačku").
- 3D Mouse Navigation: noun form "Ovládání pohledu 3D myší", as in the
  English label and the Enable 3D mouse navigation checkbox (the command
  applies one navigation frame).
- Automatic save hint: "Výkresy, které ještě nemají soubor, ..." reads
  more naturally than "Výkresy bez souboru".
- 3D mouse busy: "obsazena", the same short form as "připojena" and
  "odpojena" in the sibling status messages.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: note the intermediate Czech baseline in the parity history

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): translate the 33 strings added on main since

Rows for UI that landed on main after this branch started, so the
Czech catalog again covers every key of the Ukrainian reference catalog
the code looks up (no gaps reported):

- Command Aliases dialog (ALIASEDIT) and Tools > Customize.
- Express Tools commands: BREAKLINE, TXT2MTXT, BURST, MOCORO.
- Options: two-click selection window, interface scale.
- HATCHEDIT: removing boundaries, the Island boundary label.
- Properties: a dimension's arrow size, overall scale and precision.
- Three command prompts (DATAEXTRACTION, TOLERANCE, APPLOAD).

Not added: the Plot dialog labels in managers.rs, which the code does
not look up yet, and the unused SVG filter label.

1,330 -> 1,363 rows; counts updated in localization.md and
localization-parity.md.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): drop the duplicate Normal row after merging main

Main's ATTDISP work (View > Attribute Display > Normal) added the row
`Normal → Normální` to cs.tsv, the same one this branch had added at the
end, so the merge left the key twice and the catalog test failed on
"duplicate key Normal". The branch's copy goes; main's stays.

Czech has 1,373 rows (main has 1,219); the counts in the docs follow.
`cargo test -p cadcraft-ui-egui` passes (307) and `translation_gaps`
reports nothing missing for cs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): put the two backup rows in the reference catalog's order

Backup copy and Create backup copy with each save follow Automatic save
file location, as in uk.tsv; the other five new keys are not in the
reference catalog and stay at the end.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): the 7 strings translation_gaps lists after merging main

Alias import confirmation, the right-click hint in Options, MINSERT and the Xref clip menu; no reference catalog has the first five yet.

* i18n(cs): the Dimension Style Manager and dimension properties

184 rows for the strings #1460 added (Dimension Style Manager, dimension
and text properties, unit formats, arrowheads), 1,653 rows in all.
translation_gaps: cs nothing missing. Docs counts and history updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* i18n(cs): 19 strings added on main since the last catch-up

Array dialog fields, the update and right-click option hints,
the unsaved-changes prompt, and Unnamed.

---------

Co-authored-by: Losminek <[email protected]>
Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 20:34:58 +01:00
348ab510b4 feat(area): add translucent fill to AREA measurement preview (#1303)
* feat(area): expose active interactive command to canvas

* feat(area): shade temporary AREA preview and add tests

* fix(area): skip ambiguous self-intersecting preview fills

Reject overlapping or touching nonadjacent polygon edges before triangulation, preserving the AREA measurement and outline. Add bowtie and degenerate-boundary regression coverage with documented behavior.

* fix(area): preserve fill when cursor repeats last selected point

Strip only the redundant cursor vertex from the temporary AREA preview before polygon validation; keep genuine duplicate selected points invalid. Add two regression tests for stationary cursor and duplicate selected clicks.

* fix(area): keep preview fill when cursor revisits any selected point

Drop only the final temporary cursor vertex when it duplicates a selected vertex. Preserve rejection of actual duplicate selections and add closure/interior-cursor regression tests.

* perf(area): cache selected-edge validation while keeping cursor checks live

* perf(area): keep preview validation cache in canvas state

* style(area): clean preview formatting and let-else layout after review

* style(area): apply rustfmt per maintainer review

---------

Co-authored-by: mrepzzz <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 18:16:01 +01:00
81ec2264d3 HATCH by internal point keeps the arcs of its boundary (#1167) (#1474)
* HATCH by internal point keeps the arcs of its boundary (#1167)

The boundary search works on flattened curves, so a hatch made by
picking inside a circle stored 158 chords and AREA came out short
(5025.22 for pi*40^2 = 5026.55).

Each traced edge now keeps the input polyline it came from
(region::Boundary::outer_edges, Island::edges, outline_edges,
enclosing_loop_edges_gap; bridged gaps are None), and each input
polyline is one piece of one object: a line, a circle, an arc or one
segment of a polyline. arcs::with_arcs turns each run of edges on the
same circular piece back into one bulged vertex and moves the corners
onto the exact curves (line-circle or circle-circle crossing nearest the
traced corner, within the reach a shallow crossing needs, else onto the
circle). Nothing is matched by proximity, so a line or an ellipse next
to a circle is never taken for it. The associative refill does the same,
so a hatch keeps its arcs when its objects move.

dedup_loops now merges only loops with the same role: a loop that is one
pick's outer loop and another's island stays twice, as the even-odd fill
needs (one hatch picked inside a circle and around it, or inside a square
within a square, left the inner shape empty once the two loops matched).
A boundary object selected twice is used once.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hatch arcs: origin from the arcs' extents; opposite-role duplicate loops cancel

- HPORIGINMODE's corners came from the loop vertices only, so a circle kept as two half-circles
  had no height and its corner origins fell on its centre line. The extents now include each
  bulged edge's arc.
- A pick inside a circle and one around it keep the circle as an outer loop and as an island.
  The renderer collapsed the two into one loop, so the circle drew empty, and AREA measured them
  by nesting. Two loops that are the same boundary now collapse only in the same role (a repeated
  loop); in opposite roles they cancel, as they do under the odd-parity fill. AREA measures the
  loops the fill keeps (`hatch_fill_loop_indices`), exactly with their arcs.
- Tests: the circle's corner origins, BOUNDARY keeping a circle's and a rounded rectangle's
  arcs, and the drawn fill and AREA of the circle inside a square.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hatch loops: same-role repeats collapse before opposite roles cancel; HATCHEDIT keeps islands

- The renderer cancelled an outer loop and an island as it met them, so the same loops in another
  order filled differently (outer, island, outer left a hole; outer, outer, island left none).
  Repeats within a role now collapse first, then an outer loop and an island that are the same
  boundary cancel, spending the same comparison budget.
- HATCHEDIT adding a boundary the hatch already has (its island) added a second copy, which then
  cancelled the island. A boundary already there is no longer added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* HATCHEDIT: a boundary already there takes the added objects' links

Adding a boundary the hatch already has dropped the added loop, and with it the objects it came
from, so an unlinked island picked with addBoundary stayed unlinked. The objects now join the
loop already there (no second copy is added).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* AREA of a hatch tests nesting at an edge's middle, as the fill does

AREA tested whether a loop is an island at its first vertex, which can lie on the loop around it
(an island touching the outer boundary): the island was then added instead of subtracted. It now
uses the fill's own test point, the middle of the first non-degenerate edge (`hatch_loop_probe`).

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Hatch loop dedup: look only at loops that could match, stop when the budget is spent

The comparison budget bounded `same_polygon`, but both passes still walked every kept loop for
each new one, O(n²) in the number of loops however few matched. Loops are now found by (role,
vertex count), so only possible matches are looked at, and once the budget is spent no more are.
A test sorts 40,000 distinct loops.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: hatch gap tolerance (HPGAPTOL) is done, not missing

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: BOUNDARY keeps the arcs of what it traces

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 17:58:38 +01:00
c370b1beb4 RENAME keeps a layer's, block's or style's xdata, extension dictionary and reactors (#1020)
* RENAME keeps a layer's, block's or style's xdata, extension dictionary and reactors

The data CADCraft keeps for a table record or block without modelling it
(Drawing.foreign.records, and the roles of its file handles in foreign.targets)
is keyed by kind and upper-case name, so a rename left it under the old name:
a renamed dynamic block lost its dynamic data, and a renamed layer, text style,
dimstyle, linetype, view, UCS, multileader style or table style lost its other
applications' xdata, extension dictionary and reactors on the next save.

Foreign::rename re-keys both maps; every rename site (layer.set newName, which
RENAME and the Layer manager use; block; style; dimstyle; linetype; view, UCS,
multileader and table style) calls it through Foreign::rename_shared, which
clones the shared Foreign only when it holds something for that name. Undo needs
nothing: foreign is part of the drawing snapshot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* A case-only rename leaves the shared foreign data uncloned

* A case-only rename test checks the saved layer and block names exactly

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* docs: RENAME keeps the foreign data of layers, blocks, linetypes, text styles and dimension styles

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 17:39:44 +01:00
07b4ceb4b5 feat(layout): New Layout from Area to pick the model area a layout shows (#2080)
* feat(layout): pick the model area a new layout shows

Creating a layout from the "+" button or the layout tab menu takes the next
free name, shows the Model tab for two corners picking the model area the new
layout's viewport shows (Enter: the whole drawing; Esc creates nothing and puts
the tab back), then shows the new layout. `layout.new` takes `window` for the
same from JSON.

Interactive::cancelled lets a command put back the view or tab it moved when it
is cancelled (forwarded by the Guarded wrapper). Rebased onto main: the tests
live in cmd/layout/tests.rs, the cancel hook in session/interactive.rs.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* fix(layout): Esc restores the starting tab only if the Model tab is still shown

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* i18n(it): the prompt that asks the model area of a new layout

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* feat(layout): keep "+" and New Layout instant; pick the area with New Layout from Area

"+" and the tab menu's New Layout create the next layout at once, as before, and
LAYOUT.NEW asks only for the name. The model-area pick moves to its own command,
layout.newarea ("New Layout from Area..."), offered in the layout tab menu. Its
code is unchanged; layout.new {window} still covers scripts.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* i18n(zh): the New Layout from Area menu item

main's Chinese test requires a label for every menu item and command.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>

* Classify layout.newarea as a no-files command

every_command_is_classified requires every registered command to be on one of the file-access lists. layout.newarea does not touch a file, so it belongs next to layout.new on NO_FILES.

---------

Co-authored-by: Claude Sonnet 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 17:26:42 +01:00
3709d68862 Draw %%c with the style font's U+2205 or Ø when it has no U+2300, else the stroke glyph (fixes #1608) (#1816)
* Stroke font: U+2205 is the diameter sign too

Files from other software store the %%c symbol as U+2205 (empty set)
rather than U+2300. The stroke font drew Ø, ø and U+2300 with its
diameter glyph but had nothing for U+2205, so a stroke-font style showed
it as a missing-glyph box, or as an installed font's ∅ when one had it.
Draw it with the same strokes.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Draw %%c with the style font's U+2205 or Ø when it has no U+2300, else the stroke glyph (fixes #1608)

%%c becomes U+2300, which most Latin TrueType fonts lack (Arial, Times,
Liberation Sans on Linux). A text style set in one of them drew the
font's missing-glyph box for the diameter sign; only when a wide-coverage
font (DejaVu Sans) happened to be installed did the per-character
fallback show a symbol, in that other font's size and look.

A character the style's face lacks is now first looked for as one of its
substitutes in the same face: U+2300 as U+2205 or Ø, U+2205 as U+2300 or
Ø (`substitutes`, a pure candidate list). All three read as the diameter
sign in drawing text, and every Latin font has Ø, so the symbol keeps the
text's font, size and weight. The existing fallback chain (FONTFALLBACK,
FONTALT, installed fonts) is unchanged and comes next, as for every other
missing character; when no font has the character and the stroke font
does, its glyph is drawn as strokes instead of the face's box. The PDF
glyph record carries the character actually drawn, so the ToUnicode map
stays one-to-one when a text has both %%c and a literal Ø. Lines with
right-to-left text (the shaped path) apply the same substitution before
itemizing.

Tests: the candidate order; the last resort's choice; and, with a real
installed font that lacks U+2300 but has Ø (Liberation Sans, Arial...),
%%c, U+2300 and U+2205 shape, measure and record the same glyph as Ø,
also on a right-to-left line. Skips cleanly without such a font; no font
file is added.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Test the Ø substitution only in a font that also lacks U+2205

The installed-font test picks a face without U+2300 that has Ø, and
expects %%c, U+2300 and U+2205 to shape as its Ø. A face that lacks
U+2300 but has U+2205 satisfied that predicate, yet in it the
substitution rightly chooses U+2205 over Ø, so the comparison with
"Ø50" failed on such a machine. Require the face to lack U+2205 too;
Liberation Sans does, so the test still runs where it ran before and
still skips cleanly when no such font is installed.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Shaped lines: draw what no font has with the stroke font too

The left-to-right path draws a character that neither the text's font,
its substitutes nor any installed font has with the stroke font's glyph
when it has one, in place of the face's missing-glyph box. The shaped
path for lines with right-to-left text stopped short: `resolve` went
from the fallback chain straight to the face's box, so %%c on such a
line in a font without a diameter sign, with no installed font to lend
one, still showed a box where a left-to-right line showed the symbol.

Select the stroke glyph before the face's box there as well. The piece
is drawn and measured as the stroke-font pieces of a stroke-font line
already are (the stroke font's advance, no PDF glyph record, since it
is strokes, not an outline), so no other site needs a case. One
difference remains deliberate: a stroke-font line leaves the trailing
gap of its last glyph out of the width, as `shape_stroke` does; a
TrueType line now keeps it, as `ttf::shape` does, so a line measures
the same whichever path lays it out.

Tests: with a face that maps nothing standing in for a font lacking
the character, `resolve` picks the stroke glyph when no installed font
has the character (the fallback font when one does), keeps the face's
missing-glyph shape for what the stroke font lacks too, and the shaped
line draws strokes rather than a box at the stroke font's advance. The
installed-font test's right-to-left part also checks the width and
that the face's Ø, not the stroke font's, is drawn.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Shaped lines: take the bidi runs from the text before substitution

A character the text's font lacks is drawn as one of its substitutes
when the font has that: %%c (U+2300) as Ø in Arial, Liberation Sans and
the like. The shaped path (lines with right-to-left text) substituted
first and then ran the bidi algorithm over the substituted characters.
U+2300 and U+2205 are bidi-neutral, Ø is left-to-right, so on a line
like "⌀50 אב", right-to-left by its first strong character (the Hebrew),
the Ø became the first strong character instead, the paragraph flipped
to left-to-right and the runs changed order: "⌀50" moved from the right
end of the line to the left, where a font with U+2300 never puts it.

Resolve the runs from the characters as decoded and draw the substitute
at the same logical index: substitution is one character for one, so
the runs index both lists alike. Itemizing, shaping, mirroring and the
widths keep using the substituted characters, since those are drawn.

Tests: a TrueType font built in the test (character map and metrics, no
outlines) gives a face whose coverage the test chooses, with or without
U+2300, whatever is installed. "%%u⌀50%%u אב" in both faces underlines
"⌀50" at the same place, the right end, at the same width. The
installed-font test compared the glyphs of "⌀50 א" with "Ø50 א", equal
only while the line flipped; it now checks that the face's Ø is the
rightmost glyph of the former and the leftmost of the latter, at the
same width and glyph count, still without stroke-font glyphs.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Skip empty glyph slots when finding the rightmost glyph in the diameter test

Main now keeps an empty outline slot for a glyph without contours (the
space), so the slot's missing x put it last in the right-to-left check.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 17:10:18 +01:00
40d7375f20 Picking reads the index topmost first when the aperture holds more than 1024 candidates (#2701) (#2822)
* Picking reads the index topmost first when the aperture holds more than 1024 candidates (#2701)

When a drawing is shown small, the pick aperture under the cursor covers most of it and the
spatial index returned nearly every entity on each pointer move: the hover highlight collected,
mapped and sorted all of them before testing the topmost. A pick now takes at most 1024
candidates from the tree as before; past that it reads the index chunks from the last one down
(skipping chunks whose bounds miss the query), stops at the first hit, and sorts the tree's
candidates only for the entities below those it examined, after 4096 of them. Picks are
identical (parity tests against the scan at every limit).

select::pick per call, 1396 px canvas, PICKBOX 3 (synthetic 374k-entity site plan / 2M lines):
  zoom 20x        0.006 / 0.005 ms  ->  0.006 / 0.005 ms
  zoom extents    0.014 / 0.112 ms  ->  0.015 / 0.115 ms
  0.005x          17.0  / 148 ms    ->  8.4   / 74 ms
  0.0005x         12.3  / 121 ms    ->  0.017 / 0.019 ms
Hovering over the 2M-line drawing at 0.0005x: 100% of a core at 7.6 frames/s before, 9% after.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Picking past 1024 candidates skips the layers frozen in the viewport

The test covers the frozen-layer filter on the topmost-first and below-floor
routes of a pick, which #3124's tests do not reach.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 16:54:04 +01:00
a67a8b5edd engine: check a paper's margins against its own axis (#1266)
* engine: check a paper's margins against its own axis

* doc: turn a paper's margins with the sheet when it is stored portrait

* fmt: keep plotters.rs rustfmt-clean

* engine: turn a device paper's margins to the page's orientation

* engine: turn a page's margins when only its orientation changes

PAGESETUP sets `landscape` before `page_device`, but a command that names no paper copies no
device paper, so the retained margins stayed on the old sheet's axes and Sheet::from_page
refused them on the new orientation, falling back to the whole sheet. Turn them with the page,
using the inverse of the rotation `set_paper` applies.

* engine: an orientation-only pagesetup turns the retained margins the way the page turns

---------

Co-authored-by: midasmatterhorn <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 16:41:14 +01:00
aljormon84andFredApps 9f553d6764 feat(engine,ui): close F1 (-ATTEDIT, -RENAME), F16 (groups), F19 (draworder) and -LAYER stAte (#2152)
* feat(engine): implement -ATTEDIT Position/Height/Angle/Style and -RENAME VPort

* docs(gaps): update F15 reflecting MVIEW Restore landed

* feat(engine): implement -LAYER stAte options (Save/Restore/Name/Delete/?)

* feat(engine,ui): implement GROUPDISPLAYMODE, group copy replication, and all-space TEXTTOFRONT/HATCHTOBACK

---------

Co-authored-by: FredApps <[email protected]>
2026-11-28 16:27:41 +01:00
c5770734e2 DXF read: fewer allocations on the per-group and per-entity paths (#1076) (#1833)
* Key the raw reader's entity map by handle, not hex text

dxf_raw::read built a HashMap<String, bool> from Handle::hex() of every
entity and probed it with the handle text of every entity record: for
the #1076 reference drawing that is 1.1 M String allocations plus
SipHash over text, and the record's handle was parsed, formatted and
parsed again. Keyed by Handle, the map is built from the entities' own
handles and probed with the handle the record's head already yields.
handle() only rejects null and absurd handles, which the lookups' users
skipped a few lines later anyway.

Reading the #1076 reference DXF: 0.34 s less of 5.85 s.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Skip the raw reader's head scan for records without 102 groups

dxf_raw::read ran head() three times per entity (its extras, the
extension-dictionary map and the per-entity handle), and each call
allocates the handle and owner text (parsed, then formatted again) even
when the record has no reactors and no extension dictionary, which is
the case for most entities of a large drawing. Both scans that only
need those two fields now first check whether the record has any 102
group at all; without one there is nothing to find.

Reading the #1076 reference DXF: 0.28 s less.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Unescape DXF text only when it holds a backslash

The ASCII parser allocated every string value twice: once in typed()
and once in unescape_unicode(), which copies its input even when there
is no \U+ or \M+ escape to resolve, after two scans for them. Half the
16.7 M groups of the #1076 reference drawing are strings, so that was
8 M needless allocation pairs. A value without a backslash cannot hold
an escape and now moves into the tag as it is. The end-of-file check
reads the value before it is pushed, as the binary parser already did,
instead of cloning the text of every record's type group.

Reading the #1076 reference DXF: tag parsing 1.22 s to 1.17 s, 0.12 s
less overall.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Size the DXF tag list from the line count

parse_with_limit already counts the file's lines to refuse an oversized
drawing before reading it; that count is the number of groups, so the
tag list is now created at that size instead of growing by doubling.
For the 16.7 M groups of the #1076 reference drawing the doubling moved
about 670 MB of tags in all and, at the last step, held the 335 MB old
list next to the 670 MB new one. The hint is capped by the tag limit
and never trusted beyond it.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Size the entity list of a DXF section from its record count

parse_entities grew its list of (owner, paper, Entity) by doubling: for
the 1.1 M entities of the #1076 reference drawing that is a list of
about 700 MB moved at every doubling and, at the last one, held beside
its 350 MB predecessor. The records come from the file but are already
in memory and bounded by the tag limit, so the list is sized to their
count once; nearly every record becomes an entity.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Borrow group text in the DXF reader's per-tag scans

Tag::str() clones the value, and the reader called it in loops that run
over every group of the file or every group of a record: the handle
seed scan over every 5/105 group (1.2 M clones for the #1076 reference
drawing), the CADCRAFT_HANDSEED probe over the OBJECTS section, the
entity plot style lookup, the handle of every entity record, the record
split of every section, the AcDbEntity marker search, the xdata brace
check and the head scan's handle, owner and group names. A private
text() helper in the io crate borrows a string or hex value instead
(the dxf crate's API is left alone), and split() keeps a record's type
as a borrowed &str, as the writer's record list already can.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Bound the tag-list reservation by the text's length

The reservation came from the newline count alone, so a file of blank
lines (`0`, `EOF`, then megabytes of newlines) reserved a tag slot per
two newlines before the parser found its one group: far more than the
grow-as-needed list would ever have taken for that input. A group is two
lines of at least two bytes each, so the text's length over four bounds
what any file of that size can hold; the reservation now stops there.

Co-Authored-By: Claude Fable 5.1 <[email protected]>

* Size the entity list by the records that can become entities

VERTEX, ATTRIB and SEQEND fold into the POLYLINE or INSERT before them,
so a heavy polyline file reserved a slot per vertex it never filled.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Reserve the tag list fallibly, so a refused reservation grows the list instead of aborting

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* Bound the entity list's reservation and make it fallible

parse_entities reserved its staging list for every record that can become
an entity, infallibly, before any record was read. The reservation now
stops at MAX_RESERVED_ENTITIES (1 << 16 entries, about 46 MiB; larger
lists grow as usual) and goes through try_reserve_exact, so a refused
reservation is a "DXF: out of memory reserving N entities" error rather
than an abort; parse_entities and read_blocks return a Result for it.
Review by FredApps on PR #1833.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Fable 5.1 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 16:14:57 +01:00
fcf353c74b Keep tiny arc sweeps instead of treating them as full circles (#2559)
Found while testing crates/geom/src/lib.rs:43-46 (ccw_sweep), used by Arc::sweep and angle_in_sweep

Co-authored-by: Claude Haiku 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
2026-11-28 15:58:20 +01:00
midasmatterhornandFredApps 5cc0a86eac doc: a mirrored dimension reflects its direction about the mirror line (#1263)
* doc: a mirrored dimension reflects its direction about the mirror line

* test(doc): set insertion_point on the mirrored-dimension fixture

main added Dimension::insertion_point in #2636. The test in this PR
constructed a Dimension without that field, so clippy failed after
merging main.

---------

Co-authored-by: FredApps <[email protected]>
2026-11-28 15:39:16 +01:00
f845ed5f72 REVCLOUD: arcs use the bulge readers need to recognise a cloud (follow-up to #1605, #1570) (#1692)
* Write RevcloudProps xdata on revision clouds

Fixes #1570

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>

* REVCLOUD: arcs use the bulge readers need to recognise a cloud (follow-up to #1605, #1570)

Readers take a closed polyline for a revision cloud only with RevcloudProps
xdata (#1605) and every bulge within 0.02 of 0.520567; clouds used 0.5,
just outside, so ezdxf's is_revcloud still said no. Clouds now use
0.520567050552 on every creation path. Tests check the reader's condition
for all six ways of drawing a cloud and after a DXF round trip.

* Parity checklist: regenerated after merging main

* Parity checklist: regenerated after merging main

* REVCLOUD: import RawTag in the revcloud module main split out of draw2

* Parity checklist: regenerated after merging main

* Revcloud: update the recognition test for main's prompts (#1692)

Main now asks for the minimum and maximum arc length and, after an object
pick, whether to reverse direction, so the old scripts left a prompt waiting
and the test read the previous entity. A helper now checks the prompts
finished and exactly one new entity was created.

* Revcloud: drop the file-format-parity.md change from this PR (#1692)

The LWPOLYLINE note and changelog entry are moved to the PR description, as review asked.

---------

Co-authored-by: NetterSilver <[email protected]>
Co-authored-by: Claude Haiku 5.5 <[email protected]>
Co-authored-by: FredApps <[email protected]>
Co-authored-by: SBaksa <[email protected]>
2026-11-28 15:22:40 +01:00
oracola91andFredApps 72a71b58df CADCraft.app ships the licence files (#1710)
Since #2119 the app bundle carries NOTICE and ATTRIBUTION.md, but not
LICENSE-MIT and LICENSE-APACHE, which the .deb, .rpm, .tar.gz, AppImage
and both zips ship. Copy them into Contents/Resources next to the
notices, before signing, so the bundle seal covers them.

Co-authored-by: FredApps <[email protected]>
2026-11-28 15:10:30 +01:00
Khuong DoanandClaude Opus 5.5 909fad52c4 fix(io): find table, multileader and multiline styles and viewport configurations without scans, so crafted files don't open or save in quadratic time (#3590)
* fix(io): look up table, multileader and multiline styles without scans

A crafted DXF made several style lookups cost N^2 name comparisons
(#1924, F-04 item 5):
- the reader's TABLESTYLE, MLEADERSTYLE and MLINESTYLE records, each
  scanning the styles read so far for an earlier one of its name, and its
  VPORT records, each scanning the viewport configurations;
- each table from another writer, scanning the table styles on read;
- each TABLE, MULTILEADER and MLINE on DXF save, for its style's handle
  and values;
- render's table_style_of, which a DXF save calls for every table;
- AUDIT's multileader and table style checks, which RECOVER runs on open.

On main, N = 40 000 MLEADERSTYLE or TABLESTYLE records took 65-69 s to
open, and the DXF save of 40 000 multileaders or foreign tables naming a
missing style ran past 300 s. With this change they take 0.4-5.5 s, and
the output is byte-identical.

- ByName (from #3562) moves to dxf_ext.rs and gains position(). The record
  dedups go through it, keeping the rule: a later record of a name
  replaces the first in place and takes its name. A VPORT record still
  adds a tile to the first configuration of its name.
- Drawing::table_styles is a NamedList, like the other style tables.
- The writer's Ctx keeps a ByName beside its table and multileader style
  lists. dxf_mline::plan and Plan keep one too. Missing names fall back as
  before.
- When no styles are planned (entity_groups, for entget), the multileader
  style is still looked up in the drawing.
- AUDIT checks multileader styles against a lower-cased BTreeSet, and
  table styles with by_name.

Tests: cost tests for each path, with behaviour checks that also hold on
the old code, and an entity_groups test for the multileader's style.

Part of #1924.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(io): trim a multiline style's name when reading it

A DXF MLINESTYLE named " Road " was kept with its spaces. Its multilines
look their style up trimmed (dxf_mline::plan, Plan::handle,
Drawing::mline_style), so a save missed it, wrote a second Road style and
pointed the multilines at that copy. main did the same: its scan compared
the trimmed query with the untrimmed name. The writer already writes the
name trimmed, and the reader's fill key trims it, so the name is now
trimmed where it is read (CodeRabbit, on #3590).

Test: a_padded_multiline_style_name_is_saved_once (fails without the
trim: the save writes STANDARD, Road and Road).

Part of #1924.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
2026-11-28 14:56:15 +01:00
Dylan M. Taylor 190d88fc03 Fix reopening CADCraft nightly after saving its profile (#3603)
* fix: reopen populated nightly profiles

* fix: validate nightly file metadata with the pinned Windows API
2026-11-27 19:04:59 -05:00
FredApps 4c4d2690d4 Parity: headless column (RFC-0052) (#3602)
* Add the RFC-0052 headless column to the parity checklist

* AGENTS.md: keep a submenu headless mark until every leaf under it is covered
2026-11-28 00:01:28 +01:00
skylar taylor-barrick f7adf3ad56 Prepare CADCraft nightly signing and Mac archive layout (#3598) 2026-11-27 15:19:23 -06:00
Dylan M. TaylorandFredApps 1981067187 ci: notify artcraft-services on release state changes (#3581)
* ci: notify artcraft-services on release state changes

* ci: pass only the dispatch token to the notify-services workflow

secrets: inherit hands the called workflow every repository secret, including
the signing credentials. The reusable workflow only reads
ARTCRAFT_SERVICES_DISPATCH_TOKEN, so map just that one.

---------

Co-authored-by: FredApps <[email protected]>
2026-11-27 09:44:56 -05:00
FredApps 717f9520d3 Merge pull request #3564 from 2ez4gcx/fix/linetype-dash-budget
Linetypes: a dash budget per build, and say when a run is drawn continuous
2026-11-27 14:43:50 +01:00
FredApps ff4de54a14 Merge remote-tracking branch 'origin/main' into real-3564
# Conflicts:
#	crates/render/src/lib.rs
#	crates/render/src/pipeline.rs
#	crates/render/src/viewports.rs
2026-11-27 20:23:57 +07:00
FredApps dd423db3a8 Merge pull request #3572 from 2ez4gcx/fix/lisp-blocking-run
LISP: an expression typed at a prompt gets a short step allowance
2026-11-27 14:23:02 +01:00
FredApps fa6e282d16 Merge pull request #3562 from 2ez4gcx/fix/table-record-dedup
fix(io): read VIEW and UCS records, and each layout's named UCS, without scanning, so crafted files don't open in quadratic time
2026-11-27 14:22:56 +01:00
FredApps 59efc33013 Merge pull request #3561 from 2ez4gcx/fix/datalink-stored-paths
Data links: read a link saved in a drawing only from its folder
2026-11-27 14:22:50 +01:00
FredApps e3418eddbc Merge pull request #3560 from 2ez4gcx/fix/dimension-block-render-cycle
fix(render): a dimension whose block leads back to its own block is drawn once, not down to the depth limit
2026-11-27 14:22:45 +01:00
FredApps 1c45f0e307 Merge remote-tracking branch 'origin/main' into pr-3572
# Conflicts:
#	crates/engine/src/lisp/tests.rs
2026-11-27 20:06:58 +07:00
FredApps 456fdacf01 Merge pull request #3589 from 2ez4gcx/fix/hatch-edge-path-chaining
DXF/DWG: chain HATCH edge-path edges that are out of order or reversed
2026-11-27 14:06:09 +01:00
FredApps 1b48b22546 Merge pull request #3588 from 2ez4gcx/fix/control-preauth-bound
Bound what the control server reads before the token check (part of #1925, F-12)
2026-11-27 14:06:04 +01:00
FredApps 1858b04c2f Merge pull request #3582 from 2ez4gcx/fix/attdef-ocs-plane
Read a tilted ATTDEF or ATTRIB at its world point (#3541)
2026-11-27 14:05:59 +01:00
FredApps 86731b23e4 Merge pull request #3576 from 2ez4gcx/fix/lisp-integer-wrap
LISP: gcd and atoi give a real past 32 bits instead of wrapping
2026-11-27 14:05:35 +01:00
2ez4gcxandClaude Opus 5.5 1aa8d9db9c Keep the lost-reply warning on the control client's retry
exchange() retries once when the first attempt was not sent (or is
read-only), but the retry dropped `sent`: a mutation the retry sent and
whose reply was lost came back as a plain transport error, without the
"may or may not have been applied" warning. The new ping before long
requests adds a way into that retry (a lost ping reply counts as not
sent). The retry now keeps `sent` and returns the same warning for
mutations; read-only methods keep the plain error.

Test: a_lost_reply_on_the_retry_still_says_a_mutation_may_have_been_applied.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 17:18:56 +07:00
2ez4gcxandClaude Opus 5.5 364881867c Hatch edge chaining: close each later outline at its exact start
A later outline was closed back to its start only when its end lay farther
than the tolerance from it (review). With the end within the tolerance but
not equal, the jump back to the first outline left from the end while the
jump out arrived at the start, so the two did not cancel under even-odd
fill and a sliver between them was filled. The start is now added whenever
the end differs from it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 16:17:07 +07:00
2ez4gcxandClaude Opus 5.5 3da5c2c319 Hatch edge chaining: ends meet only within the tolerance
The end lookup took any unused end in the 3x3 grid cells around a point,
so ends up to about 2.8 tolerances apart could be joined (review). The grid
now only gives candidates; each is checked with Vec2::near against the
tolerance and the lowest eligible end wins, as the "runs on" and closed-run
checks already did. A cell's scan stops at the best match so far, and the
ends visited are capped at 32 per end of the loop: past that, a crafted
loop is read in file order.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 15:36:01 +07:00
2ez4gcxandClaude Opus 5.5 02ea1d1c31 DXF/DWG: chain HATCH edge-path edges that are out of order or reversed
An edge path was read in file order, so an edge listed elsewhere or stored
end to start made the vertex list jump, and the even-odd fill filled the
polygon of the jumps (a square listed AB, DC, BC, AD filled as an hourglass).

Each edge is now read on its own and hatch/chain.rs joins them. A path whose
edges already run on is joined in file order as before. Otherwise edges are
chained into runs by their ends (within a millionth of the loop's extent,
at least 1e-9), turned around when needed (points reversed, bulges negated
and moved). Closed runs fill as loops of their own; open runs are joined in
order, as a path read in file order is. Ends are looked up in a sorted grid,
O(n log n).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 14:11:23 +07:00
2ez4gcxandClaude Opus 5.5 db0a4aca42 Bound what the control server reads before the token check (#1925)
The control server checks a request's token only after reading the whole
line, and clients send the token last, so a local peer without it could
make the app buffer a line of up to 256 MiB (512 MiB across connections).

Until a request on a connection has passed the token check, a request
line may be at most 64 KiB (control_token::MAX_UNAUTHENTICATED_LINE); a
longer one gets an error reply and the connection is closed. After that
the usual 256 MiB limit applies.

The MCP bridge sends a short ping with the token before a longer request
on a new connection, and sends the request only when the ping's reply
shows the token check passed; a refused or lost ping leaves the request
unsent and safe to retry. docs/control-protocol.md describes the limit.

Part of #1925 (F-12).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 14:09:23 +07:00
2ez4gcxandClaude Opus 5.5 293d79fac8 Read a tilted ATTDEF or ATTRIB at its world point (#3541)
An ATTDEF or ATTRIB in a tilted plane facing up holds its insertion
point, alignment point and rotation in that plane's OCS (DXF Reference,
ATTDEF and ATTRIB groups 10 and 11 "in OCS"; "Object Coordinate Systems
(OCS)"). The reader took them as world coordinates, and the writer saves
attributes with no group 210, so a save moved the attribute millions of
units in a drawing near survey coordinates.

flatten_tilted maps them through Mat4::ocs and turns group 50 into the
plane's direction in plan, as tilted LWPOLYLINE and HATCH are drawn
flat; an ATTDEF's extrusion is then spent. ATTRIBs of a reference that
is itself left in its tilted plane (#1158) stay as read with it; the
INSERT arm and that check share mirrored_reference. Planes facing down
(mirror_text), flat attributes and TEXT (#3296) are unchanged.

Fixes #3541

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 11:11:12 +07:00
2ez4gcxandClaude Opus 5.5 7b482c5e3b render: a pattern of gaps only draws no line on any run
e9e4b0e1f made a gaps-only pattern draw nothing past the per-run limit, but
it was still drawn as one continuous line where a pattern with a dash falls
back to continuous: a run shorter than one period, a pattern under
`min_pattern` (sub-pixel), past 50,000 periods with a level of detail, and
a run of one point (review of #3564). On screen that also differed from the
plot of the same run.

apply, apply_as and ranges now return no dashes for a pattern whose elements
are all gaps, before any of those fallbacks. Patterns with a dash or a dot
keep every fallback, and an empty (continuous) pattern is drawn whole. Texts
and shapes in a gaps-only pattern are placed as before.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 09:05:09 +07:00
2ez4gcxandClaude Opus 5.5 e9e4b0e1ff render: charge a closed run for the periods it walks; gaps only draw nothing at any length
Review of #3564:

- A closed run is stretched to round(L / period) periods and laid out from
  the period before its anchor to the one after its last, up to half a
  period more than the (L / period + 2) elements it was charged. A run of
  192 on 127 dashes and a gap (period 128) walked 508 elements for a charge
  of 448. It is now charged (round(L / period) + 2) x the pattern's length.
  The per-run limit keeps its formula, so runs under it keep their output.
- A pattern of gaps only was refused past the per-run limit, drawn as one
  continuous line and counted as undashed, while below the limit it draws
  nothing. It now draws nothing at any length, uncharged and unreported.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 01:19:53 +07:00
2ez4gcxandClaude Opus 5.5 7dfb39d3db LISP: gcd and atoi give a real past 32 bits instead of wrapping
`(gcd -2147483648 0)` gave 2147483647 (the divisor clamped to the
largest integer), and `atoi` cast its digits with `as i32`, so
"99999999999" gave 1215752191 and "99999999999999999999" gave 0.

They now follow what the reader, `fix` and JSON inputs already do with
a whole number that doesn't fit 32 bits: it is a real. `gcd` gives
2147483648.0 for its one such result; `atoi` gives the real `atof`
reads from the digits, the number the reader makes of them. Results
that fit are the same integers as before. Integer arithmetic still
wraps.

Part of #1933.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 00:47:43 +07:00
2ez4gcxandClaude Opus 5.5 a44fcd4fce engine: EXPORT, PLOT and SAVEAS to an image say when dashes were drawn continuous
The first commit made `cadcraft-cli convert` print the note, but the app's
own commands write images through IoHooks::write and ::plot, which return
bytes only, so the desktop and web apps and LISP stayed silent (#1069).

- cmd::file::set_noted_io(NotedIo { write, plot }): an optional hook beside
  IoHooks (which is built by struct literal in ~70 places), installed by the
  CLI, desktop and web apps with cadcraft_io::write_framed_noted and the new
  cadcraft_io::plotter::plot_noted / pdf::plot_noted.
- EXPORT, PLOT (so EXPORTPDF, PUBLISH and PDFBOOK per sheet), QSAVE and
  SAVEAS to an image and document.bytes echo the note and add it to the
  result's `warnings`. An image written with a `version` option goes through
  the same writer (same bytes), so it is noted too.
- report_notes adds to `warnings` instead of replacing them;
  report_dwg_notes uses it (no result had `warnings` before it, so DWG
  results don't change). Without the hook nothing changes.

Not covered: the plot preview and the canvas show no message.

Fixes #1069.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-27 00:11:22 +07:00
2ez4gcxandClaude Opus 5.5 ef42a37dcb LISP: an expression typed at a prompt gets a short step allowance
An expression typed at a command's prompt (CIRCLE, then `(while T)` as
the radius) is the prompt's answer, so it ran as a blocking run with the
500,000,000-step cap meant for programmatic calls: about 17 s on a dev
build with no frame drawn and Esc not handled.

It now runs through `lisp_eval_answer` with a 20,000,000-step cap, and
the callbacks it runs (`vl-sort`'s comparator and the other synchronous
callbacks) share what is left of that allowance instead of each taking
the 500,000,000-step callback allowance inside one step. The error says
the expression was stopped and to run long routines at Command:, where
they run a slice per frame and Esc stops them. Routines at Command:,
`c:` commands, APPLOAD, dropped files, the `lisp`/`appload` JSON calls
and startup files are unchanged.

Part of #1926 (item 3).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 23:32:33 +07:00
2ez4gcxandClaude Opus 5.5 861223423d Data links: drop the file linked longest ago at the bound
DATALINK remembers up to 1000 linked files per open drawing. At the
bound a new file dropped an arbitrary entry of a HashSet, which could be
the file linked just before it. Each remembered file now carries when it
was last linked: linking it again moves it to the newest, and a new file
at the bound drops the one linked longest ago.

Test: remembered_links_are_the_most_recent_ones.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 22:27:50 +07:00
2ez4gcxandClaude Opus 5.5 c824e5e96a render: a dash budget per build, and say when a run is drawn continuous
A dashed run is laid out over at most two million pattern elements, but
nothing bounded the total, and a pattern of mostly gaps visits many elements
for each point it draws, so the 64M-point display budget never stopped it:
1,000 lines on a 256-element pattern of gaps and one dash (a 58 KB DXF) took
11.6 s to PNG and 12.7 s to a 69 MB PDF on a dev build. A run past the
per-run limit was also drawn continuous without a word (#1069).

- MAX_DASH_ELEMENTS (64M, as many as the list's points) is charged by
  linetype::layout before a run is laid out, on a counter shared like the
  point budget's (parallel parts, XCLIP parts, viewport contents). Once a run
  does not fit, the rest of the build's dashed runs are drawn continuous.
  The per-run limit is MAX_RUN_DASH_ELEMENTS, unchanged.
- A run drawn continuous because of either limit sets DisplayList::truncated
  and counts in the new DisplayList::undashed, merged where lists are joined.
  Runs drawn continuous by rule (short, sub-pixel, the screen's 50,000-period
  level of detail) are not counted.
- cadcraft_io::write_framed_noted (and png/svg/pdf "noted" variants) return
  the note; cadcraft-cli convert and run --export print it.
- Linetype texts are placed only on a run whose dashes were laid out; phase
  checks the limits without laying the run out again.

On 11 real drawings the most a complete plot asked was 26.5M elements; a
16M total would have drawn 8,241 runs of that drawing solid. With 64M the
gap-pattern file takes 0.8 s / 0.4 s, the #1069 controls and three real
drawings export byte-identical, and the audit's dense dash/gap file stays as
on main (it fills the point budget at the same time).

Part of #1923 (F-05 f). Part of #1069: the app's EXPORT and PLOT don't show
the note yet.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 20:13:14 +07:00
2ez4gcxandClaude Opus 5.5 077a5fd247 fix(io): read VIEW and UCS records and each layout's named UCS without scans
The DXF reader looked for an earlier VIEW or UCS of the same name by
scanning the records read so far, and found each layout's named UCS by
scanning every UCS, on read and on save. A crafted file of N VIEW or N UCS
records, or of N layouts each naming one of N UCSs, cost N^2 name
comparisons (#1924, F-04 item 3): at N = 40 000 it took 67 s and 194 s to
open on main.

- ByName: the records of a table read so far by lower-cased name; a later
  record of a name replaces the first, which keeps its place and takes the
  later record's name, as before. DIMSTYLE records use it too.
- UcsNames: the drawing's UCSs by lower-cased name with their positions in
  table order; a layout's named UCS is the first of that name whose frame
  is the layout's, as named_ucs finds it. Built once per read and per save.

Tests: VIEW/UCS records (main 118.9 s, now 0.23 s) and layouts naming
UCSs, read and saved (39.9 s, now 1.6 s), against a 10 s bound; a
behaviour test compares UcsNames with named_ucs. Follows #3539.

Part of #1924

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 18:55:44 +07:00
2ez4gcxandClaude Opus 5.5 8f4f06b9fb Data links: read a link saved in a drawing only from its folder
A table's data link path is stored in the drawing, and DATALINKUPDATE
copies the linked file's text into the table, where the next save keeps
it. A stored path could name any local file (by `..` or an absolute
path), so a drawing could pull any readable file into itself.

A link the drawing itself names is now read only when its file, resolved
by the file system (`..`, symbolic links and junctions followed), lies in
the drawing's folder or a folder below it, compared by whole components;
the resolved path is the one read. A file the user links with DATALINK
is remembered for that open drawing (never saved, at most 1000, newest
kept), so it keeps updating until the drawing is opened again. Refused
links are listed in DATALINKUPDATE's errors; the other links update. The
automation roots are still checked first.

Part of #1929 (F-08).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 18:48:34 +07:00
2ez4gcxandClaude Opus 5.5 851d154843 fix(render): draw a dimension whose block leads back to its own block from its definition points
A dimension block holding dimensions of itself, directly or through block references, other
dimension blocks, multileader blocks or proxy graphics, was drawn again for every such dimension at
every level down to MAX_BLOCK_DEPTH: k of them made up to k^16 copies, a loop through many
distinct blocks one copy per ordering of them, cut only by the 2M expansion budget. A crafted
490-byte DXF took 79 s to export to PNG (dev build), 602 bytes over 300 s.

A dimension inside block C is now drawn from its own block T only if T does not lead back to C.
A short search from T (16 blocks, 256 objects) settles ordinary blocks; past it the strongly
connected components of the block graph are found once per build (iterative Tarjan, shared through
a OnceLock). A dimension on a loop is drawn from its definition points, as one whose block is
missing is. Loops made only of block references are unchanged.

Part of #1923 (F-05).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 17:45:00 +07:00
FredApps 54d1be50ba Release: CADCraft v0.21.0 (main 8e69890223) 2026-11-14 21:44:55 +01:00
FredApps 1ba86d461b Release: CADCraft v0.21.0 2026-11-14 21:44:50 +01:00
Dylan M. Taylor 7526dc62c1 Merge tested main for Flatpak update patch release 2026-11-11 15:25:57 -05:00
Dylan M. Taylor 161af2a8da Release 0.20.1: repair Flatpak update checks and self-updates (#3078)
* Release 0.20.1: fix Flatpak update permissions

* test: avoid unchecked option parsing in Flatpak regression
2026-11-11 14:27:14 -05:00
FredApps 28241abb8f Merge main into release for CADCraft v0.20.0 2026-11-11 16:38:54 +01:00
FredAppsand.CooCoo 51f5bbcc21 Fonts: the MTEXT strip test expects a short \U+ escape to keep its digits (#2954) (#3024)
strips_formatting expected `\U+12` to strip to nothing. plain_mtext
dropped every unknown code up to the next `;` when that assertion was
written. #1036 limits this to the codes in takes_arg, and `\U` is not
one of them, so plain_mtext returns `+12`. The layout and paragraph
paths give the same text, and
unicode_escapes_are_decoded_in_every_parser already expects it.

The test has failed on main since both changes merged, and the failure
stops the gate at its test step. The test module now also checks the
short escape in both layout paths.

(cherry picked from commit 6f0f1fefa8)

Co-authored-by: .CooCoo <[email protected]>
2026-11-10 19:49:24 +01:00
Dylan M. Taylor 227e3c385b Release 0.19.0 2026-11-09 06:29:44 -05:00
138 changed files with 9096 additions and 770 deletions
+3 -3
View File
@@ -4,10 +4,10 @@
"repository_id": 1408289866,
"producer_workflow_id": 429719786,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
+16 -2
View File
@@ -34,12 +34,26 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
app-name: cadcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+3 -2
View File
@@ -22,9 +22,9 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
app-name: cadcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
@@ -32,3 +32,4 @@ jobs:
# craft-common-actions main commit that merged the exact-analysis admission (#371, after #370,
# #369 and #364).
platforms: '["windows-x86_64","linux-x86_64","macos-aarch64"]'
linux-package-formats: '["deb","rpm","appimage","flatpak","oci","arch"]'
+2
View File
@@ -72,6 +72,8 @@ Layout:
Checks for the crates you changed: `cargo test -p <crate>`, `cargo clippy -p <crate> --all-targets -- -D warnings`, `cargo xtask layers`, `cargo xtask assets`, `cargo xtask wasm`, `cargo xtask parity` (regenerates `docs/parity-checklist.md`).
Headless column ([RFC-0052](https://github.com/storytold/craft-contrib/blob/main/rfcs/0052-headless-reach.md)): `cargo xtask parity` marks a covered menu item `headless: yes` because its command is in the engine registry that `cadcraft-cli` and the MCP server load. An uncovered item takes `no`/`partial` and a `reach` (`window`, `os`, `engine-gap`) from `HEADLESS` in `xtask/src/parity.rs` (a path ending in ` > ` covers its submenu), or reads `unknown`. Never write `yes` there. A covered leaf is `yes` whatever its marks say, so a submenu mark stays while any leaf under it is uncovered; drop a mark only once commands cover every leaf it matches (the check then fails on it as stale).
Paths and conventions:
- No crate allows `unsafe` (`unsafe_code = "forbid"` in the workspace).
+6
View File
@@ -45,6 +45,12 @@ fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
+5 -1
View File
@@ -145,10 +145,14 @@ pub(crate) fn export(s: &Session, out: &Path, io: &mut Streams) -> Result {
pub(crate) fn export_framed(s: &Session, out: &Path, window: Option<Bounds2>, io: &mut Streams) -> Result {
let d = s.doc()?;
let bytes = cadcraft_io::write_framed(d, out, window)?;
let (bytes, notes) = cadcraft_io::write_framed_noted(d, out, window)?;
let folder = write_atomic(out, &bytes)?;
report_new_folder(folder, io);
io.errln(format_args!("wrote {} ({} bytes)", out.display(), bytes.len()));
// What the image draws short of the drawing (dashed runs past a dash limit drawn continuous).
for note in notes {
io.errln(format_args!("{}: {note}", out.display()));
}
if cadcraft_engine::cmd::file::drops_unknown(out) {
let lost = cadcraft_engine::cmd::file::not_saved(d);
if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) {
@@ -0,0 +1,144 @@
//! `convert` to an image says how many dashed runs it drew continuous because of a dash limit
//! (#1069): a line whose DASHED pattern repeats past what one run may be laid out over. A line of
//! 50,001 periods, which an export keeps dashed, gets no note.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A DXF of one line `periods` DASHED (0.5, -0.25) periods long.
fn dashed_line(periods: f64) -> String {
format!(
"0
SECTION
2
TABLES
0
TABLE
2
LTYPE
70
1
0
LTYPE
2
DASHED
70
0
3
Dashed
72
65
73
2
40
0.75
49
0.5
74
0
49
-0.25
74
0
0
ENDTAB
0
ENDSEC
0
SECTION
2
ENTITIES
0
LINE
8
0
6
DASHED
10
0
20
0
11
{}
21
0
0
ENDSEC
0
EOF
",
periods * 0.75
)
}
#[test]
fn convert_to_an_image_notes_dashed_runs_drawn_continuous_past_the_dash_limit() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// (1,000,001 + 2) periods × 2 elements: past the two million one run may be laid out over.
let long = dir.join("long.dxf");
std::fs::write(&long, dashed_line(1_000_001.0)).unwrap();
let control = dir.join("control.dxf");
std::fs::write(&control, dashed_line(50_001.0)).unwrap();
let notes = |out: &Output| {
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("drawn continuous")).map(str::to_string).collect::<Vec<_>>()
};
for ext in ["png", "svg", "pdf"] {
let image = dir.join(format!("long.{ext}"));
let image = image.to_str().unwrap();
let got = notes(&cli(&["convert", long.to_str().unwrap(), image]));
assert!(matches!(got.as_slice(), [note] if note.starts_with(&format!("{image}: 1 dashed run "))), "{ext}: {got:?}");
let got = notes(&cli(&["convert", control.to_str().unwrap(), dir.join(format!("control.{ext}")).to_str().unwrap()]));
assert!(got.is_empty(), "{ext}: {got:?}");
}
// A DXF copy draws nothing, so there is nothing to note.
assert!(notes(&cli(&["convert", long.to_str().unwrap(), dir.join("copy.dxf").to_str().unwrap()])).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
/// The engine's commands that write an image say it too, on the command line and in the result's
/// `warnings`: EXPORT, PLOT (PDF, PNG, SVG, to a file or as data), QSAVE and SAVEAS to an image and
/// `document.bytes`.
#[test]
fn image_commands_warn_about_dashed_runs_drawn_continuous() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-cmds-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let out = |name: &str| serde_json::to_string(dir.join(name).to_str().unwrap()).unwrap();
let cmds = [
format!("export {{\"path\": {}}}", out("export.png")),
format!("plot {{\"path\": {}}}", out("plot.pdf")),
format!("plot {{\"path\": {}, \"output\": \"png\", \"resolution\": 50}}", out("plot.png")),
format!("plot {{\"path\": {}, \"output\": \"svg\"}}", out("plot.svg")),
format!("saveas {{\"path\": {}}}", out("saved.svg")),
format!("qsave {{\"path\": {}}}", out("saved.pdf")),
"plot {\"output\": \"svg\"}".to_string(),
"document.bytes {\"format\": \"pdf\"}".to_string(),
format!("saveas {{\"path\": {}, \"version\": 2018}}", out("versioned.png")),
];
for (periods, warned) in [(1_000_001.0, true), (50_001.0, false)] {
let input = dir.join(format!("line-{periods}.dxf"));
std::fs::write(&input, dashed_line(periods)).unwrap();
let mut args = vec!["run".to_string(), input.to_str().unwrap().to_string()];
for c in &cmds {
args.extend(["--cmd".to_string(), c.clone()]);
}
let run = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&args).output().unwrap();
assert!(run.status.success(), "{:?}: {}", run.status, String::from_utf8_lossy(&run.stderr));
let results: Vec<serde_json::Value> = String::from_utf8_lossy(&run.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(results.len(), cmds.len(), "{results:?}");
for (c, r) in cmds.iter().zip(&results) {
let notes: Vec<&str> = r["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()).collect();
let noted = matches!(notes.as_slice(), [n] if n.starts_with("1 dashed run ") && n.contains("drawn continuous"));
assert_eq!(noted, warned, "{periods} periods, {c}: {r}");
assert_eq!(r.get("warnings").is_some(), warned, "{periods} periods, {c}: {r}");
}
// Said on the command line once for each command.
let echoed = String::from_utf8_lossy(&run.stderr).lines().filter(|l| l.starts_with("1 dashed run ")).count();
assert_eq!(echoed, if warned { cmds.len() } else { 0 }, "{}", String::from_utf8_lossy(&run.stderr));
}
let _ = std::fs::remove_dir_all(&dir);
}
+1
View File
@@ -1,4 +1,5 @@
mod cli;
mod dash_limit_note;
mod drafting_spacing;
mod help;
// DWG output needs craft-dwg's bridge.
+6
View File
@@ -120,6 +120,12 @@ mod web {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
+78 -4
View File
@@ -4,8 +4,9 @@
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a
//! socket may sit idle or blocked on a write.
//! ([`Limits`]): simultaneous connections, request line length (shorter until a request on the
//! connection has carried the token), queued requests, and how long a socket may sit idle or
//! blocked on a write.
use std::io::{BufRead, BufReader, ErrorKind, Write};
use std::net::{TcpListener, TcpStream};
@@ -24,6 +25,9 @@ struct Limits {
max_clients: usize,
/// Longest request line in bytes (newline excluded); a longer one closes the connection.
max_line: usize,
/// Longest request line until a request on the connection has carried the right token; a
/// longer one closes the connection (#1925).
preauth_line: usize,
/// Request-line bytes buffered at once across all connections; a request that would pass it
/// is refused with an error reply.
total_bytes: usize,
@@ -43,6 +47,7 @@ impl Default for Limits {
max_clients: 16,
// Generous, so requests that carry whole drawings or images as base64 still fit.
max_line: 256 * 1024 * 1024,
preauth_line: cadcraft_mcp::control_token::MAX_UNAUTHENTICATED_LINE,
// Room for one maximal request plus smaller ones, not `max_clients` maximal ones.
total_bytes: 512 * 1024 * 1024,
queue: 64,
@@ -344,12 +349,21 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
let mut held = Held::new(budget);
// The token is checked only after the whole line is read, so until a request here has carried
// it a line is kept short: a peer without it can't make the app buffer `max_line` (#1925).
let mut authenticated = false;
loop {
let reject = match read_bounded_line(&mut reader, &mut buf, limits.max_line, &mut held) {
let max = if authenticated { limits.max_line } else { limits.preauth_line.min(limits.max_line) };
let reject = match read_bounded_line(&mut reader, &mut buf, max, &mut held) {
Ok(false) => break,
// Nothing of a line arrived (idle timeout, or the peer is gone): close without a word.
// A line nobody asked for would be read as the reply to the client's next request.
Err(_) if buf.is_empty() => break,
// Only an overlong line leaves more than `max` bytes buffered.
Err(_) if !authenticated && buf.len() > max => format!(
"request line longer than {max} bytes before a request with the control token on this connection; \
send a short request with the token (such as `ping`) first; closing the connection"
),
Err(e) => e,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
@@ -366,6 +380,7 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let _ = writeln!(out, "{r}");
break;
}
authenticated = true;
// Absent `params` is `{}`; ones that cannot be decoded (an unpaired surrogate escape) are an
// error, not a request run with defaults.
let params = match params.map(|r| serde_json::from_str::<Value>(r.get())) {
@@ -499,7 +514,12 @@ mod tests {
/// The control server on a loopback port, with a stand-in UI that echoes each method.
fn serve_echo() -> std::net::SocketAddr {
let (addr, rx) = serve_with(Limits::default());
serve_echo_with(Limits::default())
}
/// [`serve_echo`] under `limits`.
fn serve_echo_with(limits: Limits) -> std::net::SocketAddr {
let (addr, rx) = serve_with(limits);
std::thread::spawn(move || {
for req in rx {
let _ = req.reply.send(json!({"ok": true, "method": req.method}));
@@ -612,6 +632,60 @@ mod tests {
drop(first);
}
/// Small bounds for the pre-authentication tests: lines up to 1000 bytes until the connection
/// has shown the token, up to 100 000 after.
fn preauth() -> Limits {
Limits { max_line: 100_000, preauth_line: 1000, idle_timeout: Duration::from_secs(5), ..short() }
}
/// A request line carrying the test token whose parameters make it `len` bytes or longer.
fn long_req_line(id: i64, len: usize) -> String {
json!({"id": id, "method": "long", "params": {"text": "x".repeat(len)}, "token": TEST_TOKEN}).to_string() + "\n"
}
/// A peer without the token is refused once its line passes the pre-authentication bound,
/// while it is still sending: the app doesn't buffer the rest of the line to find the token
/// at its end (#1925).
#[test]
fn an_unauthenticated_long_line_is_refused_at_the_preauth_bound() {
let (addr, rx) = serve_with(preauth());
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
// Well under `max_line`, and unfinished: without the pre-authentication bound the server
// keeps reading and waiting for the rest of it. One write, so it all reaches the server's
// buffer at once and the close after the refusal leaves nothing unread to reset the reply.
let unfinished = format!(r#"{{"id":1,"method":"m","params":"{}"#, "x".repeat(5000));
c.write_all(unfinished.as_bytes()).unwrap();
let mut line = String::new();
BufReader::new(&mut c).read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!(v["ok"], json!(false));
assert!(v["error"].as_str().unwrap_or("").contains("longer than 1000 bytes before a request with the control token"), "{line}");
assert!(rx.try_recv().is_err(), "nothing was dispatched");
}
/// A long request with the token is taken once a shorter request with the token has been
/// answered on the same connection; as a connection's first line it is refused, since its
/// token comes only at the end.
#[test]
fn a_long_request_is_taken_once_the_connection_has_shown_the_token() {
let addr = serve_echo_with(preauth());
let long = long_req_line(2, 5000);
let first = exchange(addr, long.as_bytes());
assert_eq!(first.len(), 1, "{first:?}");
assert!(first[0]["error"].as_str().unwrap_or("").contains("before a request with the control token"), "{first:?}");
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(format!("{}{long}", req_line(1, "ping")).as_bytes()).unwrap();
let mut r = BufReader::new(c);
for (id, method) in [(1, "ping"), (2, "long")] {
let mut line = String::new();
r.read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!((v["id"].as_i64(), v["ok"].as_bool(), v["method"].as_str()), (Some(id), Some(true), Some(method)), "{line}");
}
}
#[test]
fn the_budget_is_given_back_when_the_connection_ends() {
let budget = Budget::new(100);
+6
View File
@@ -182,6 +182,12 @@ pub fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
+73 -1
View File
@@ -185,11 +185,56 @@ fn entries_stay_inside(root: &Path) -> Result<(), String> {
};
for entry in entries {
let entry = entry.map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
private_subdirectory(root, entry.file_name(), "profile entry")?;
let path = entry.path();
let metadata = std::fs::symlink_metadata(&path).map_err(|e| format!("cannot inspect the nightly profile: {e}"))?;
// Settings and session state are ordinary files, not directories. Keep the existing
// directory-boundary check for folders (including the known folder-only entries).
let folder_only = PROFILE_FOLDERS.iter().any(|name| entry.file_name().eq_ignore_ascii_case(name));
if metadata.is_file() && !folder_only {
private_regular_file(&path, &metadata)?;
} else {
private_subdirectory(root, entry.file_name(), "profile entry")?;
}
}
Ok(())
}
/// Persisted files must have their own ordinary file identity, not an alias to other data.
fn private_regular_file(path: &Path, metadata: &std::fs::Metadata) -> Result<(), String> {
#[cfg(unix)]
{
use std::os::unix::fs::MetadataExt as _;
if metadata.nlink() != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
#[cfg(windows)]
{
use winsafe::{HFILE, co};
let (file, _) = HFILE::CreateFile(
path.to_str().ok_or("the nightly profile file path is not textual")?,
co::GENERIC::default(),
Some(co::FILE_SHARE::READ | co::FILE_SHARE::WRITE | co::FILE_SHARE::DELETE),
None,
co::DISPOSITION::OPEN_EXISTING,
co::FILE_ATTRIBUTE::NORMAL,
Some(co::FILE_FLAG::OPEN_REPARSE_POINT),
None,
None,
)
.map_err(|e| e.to_string())?;
let info = file.GetFileInformationByHandle().map_err(|e| e.to_string())?;
if info.dwFileAttributes.has(co::FILE_ATTRIBUTE::REPARSE_POINT | co::FILE_ATTRIBUTE::DIRECTORY) {
return Err("the nightly profile file must not be an alias or directory".into());
}
if info.nNumberOfLinks != 1 {
return Err("the nightly profile file must not be shared".into());
}
}
let _ = (path, metadata);
Ok(())
}
/// Recognise the shared portable data namespace in both the supplied and resolved path.
/// This is not an inventory of arbitrary custom Stable overrides or a Launcher ownership proof.
fn is_portable_layout(path: &Path, platform: Platform) -> bool {
@@ -290,6 +335,8 @@ const EFRAME_APP_ID: &str = "ai.storyteller.cadcraft";
/// The subfolder autosave and Drawing Recovery write ([`crate::main`], `<settings>/autosave`).
pub const AUTOSAVE: &str = "autosave";
const PROFILE_FOLDERS: [&str; 6] = [AUTOSAVE, "logs", "support", "single-instance", "plotters", "crash-reports"];
#[cfg(test)]
mod tests {
use super::*;
@@ -474,6 +521,31 @@ mod tests {
assert_eq!(std::fs::read_dir(nightly).unwrap().count(), 0);
}
#[test]
fn nightly_profile_reopens_after_saving_settings_and_session_state() {
let fixture = Fixture::new();
for platform in [Platform::Mac, Platform::Linux, Platform::Windows] {
let private = fixture.root.join(format!("nightly-reopen-{platform:?}"));
assert_eq!(fixture.check(platform, &private).unwrap(), private);
for name in ["app.ron", "nightly-session.lock", "nightly-session.json"] {
std::fs::write(private.join(name), b"saved profile data").unwrap();
}
for name in PROFILE_FOLDERS {
std::fs::create_dir(private.join(name)).unwrap();
}
assert_eq!(fixture.check(platform, &private).unwrap(), private);
assert_eq!(std::fs::read(private.join("app.ron")).unwrap(), b"saved profile data");
for name in [AUTOSAVE, "logs", "support", "single-instance", "plotters", "crash-reports"] {
let path = private.join(name);
std::fs::remove_dir(&path).unwrap();
std::fs::write(&path, b"not a directory").unwrap();
assert!(fixture.check(platform, &private).is_err(), "{name} must stay a directory");
std::fs::remove_file(&path).unwrap();
std::fs::create_dir(&path).unwrap();
}
}
}
#[test]
fn mac_fences_only_app_library_subtrees_and_the_entire_bundle() {
let mut fixture = Fixture::new();
+3 -1
View File
@@ -399,7 +399,9 @@ impl EntityKind {
t3(p);
}
if let DimKind::Linear { rotation } = &mut d.kind {
*rotation = cadcraft_geom::norm_angle(*rotation + rot);
// A mirror reflects the dimension line's direction about the mirror line:
// `rot` is twice the mirror line's angle, so `a` lands at `rot - a`.
*rotation = cadcraft_geom::norm_angle(if mirror { rot - *rotation } else { *rotation + rot });
}
d.marks.transform(&t3, rot, s, mirror);
d.block = None;
+3 -1
View File
@@ -100,7 +100,9 @@ impl DimMarks {
/// Transform the points and angles (part of [`super::EntityKind::transform`]).
pub(super) fn transform(&mut self, t3: &dyn Fn(&mut Vec3), rot: f64, s: f64, mirror: bool) {
if let Some(a) = &mut self.oblique {
*a = cadcraft_geom::norm_angle(if mirror { rot - (*a - rot) } else { *a + rot });
// A mirror reflects a direction about the mirror line: `rot` is the transformed X
// axis (twice the mirror line's angle), so a direction `a` lands at `rot - a`.
*a = cadcraft_geom::norm_angle(if mirror { rot - *a } else { *a + rot });
}
if let Some(j) = &mut self.jog_line {
t3(j);
+76
View File
@@ -113,6 +113,43 @@ impl Foreign {
&& self.appids.is_empty()
}
/// Re-key what is kept for the record named `from` under each of `kinds` (e.g. `["LAYER"]`, or
/// `["BLOCK_RECORD", "BLOCK", "ENDBLK"]` for a block) to the name `to`, after a rename: its
/// extras ([`Foreign::records`]) and the roles of its file handles ([`Foreign::targets`]), so
/// saving writes its xdata, extension dictionary and reactors on the renamed record. Names
/// compare trimmed and upper-case, as the reader keys them, so a rename that only changes case
/// changes nothing.
pub fn rename(&mut self, kinds: &[&str], from: &str, to: &str) {
let (from, to) = (from.trim().to_ascii_uppercase(), to.trim().to_ascii_uppercase());
if from == to {
return;
}
for kind in kinds {
let old: ForeignKey = ((*kind).to_string(), from.clone());
let new: ForeignKey = ((*kind).to_string(), to.clone());
if let Some(extra) = self.records.remove(&old) {
self.records.insert(new.clone(), extra);
}
self.targets.values_mut().filter(|k| **k == old).for_each(|k| *k = new.clone());
}
}
/// Whether anything is kept for the record named `from` under one of `kinds`: what
/// [`Foreign::rename`] would re-key.
pub fn names(&self, kinds: &[&str], from: &str) -> bool {
let from = from.trim().to_ascii_uppercase();
let hit = |k: &ForeignKey| k.1 == from && kinds.contains(&k.0.as_str());
self.records.keys().any(hit) || self.targets.values().any(hit)
}
/// [`Foreign::rename`] on a drawing's shared copy, which is cloned only when it keeps
/// something for the renamed record and the name really changes (not only its case).
pub fn rename_shared(this: &mut std::sync::Arc<Foreign>, kinds: &[&str], from: &str, to: &str) {
if !from.trim().eq_ignore_ascii_case(to.trim()) && this.names(kinds, from) {
std::sync::Arc::make_mut(this).rename(kinds, from, to);
}
}
/// The entities with a geometry record in the data store: an `ACDSRECORD` naming the entity
/// (320) that holds its `ASM_Data`. A 320 without one doesn't keep an entity's geometry.
pub fn data_store_entities(&self) -> std::collections::BTreeSet<Handle> {
@@ -390,3 +427,42 @@ pub fn class_number<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)> +
pub fn class_index(number: Option<i64>) -> Option<usize> {
usize::try_from(number?.checked_sub(500)?).ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn key(k: &str, n: &str) -> ForeignKey {
(k.to_string(), n.to_string())
}
#[test]
fn rename_rekeys_records_and_targets_of_the_given_kinds_only() {
let mut f = Foreign::default();
let xdict = ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() };
f.records.insert(key("BLOCK_RECORD", "DOOR"), xdict.clone());
f.records.insert(key("LAYER", "DOOR"), ForeignExtra { reactors: vec![Handle(0x41)], ..ForeignExtra::default() });
f.targets.insert(Handle(0x10), key("BLOCK_RECORD", "DOOR"));
f.targets.insert(Handle(0x11), key("BLOCK", "DOOR"));
f.targets.insert(Handle(0x12), key("LAYER", "DOOR"));
f.rename(&["BLOCK_RECORD", "BLOCK", "ENDBLK"], "Door", "Gate");
assert_eq!(f.records.get(&key("BLOCK_RECORD", "GATE")), Some(&xdict));
assert!(!f.records.contains_key(&key("BLOCK_RECORD", "DOOR")));
assert!(f.records.contains_key(&key("LAYER", "DOOR")), "another kind with the same name stays");
assert_eq!(f.targets.get(&Handle(0x10)), Some(&key("BLOCK_RECORD", "GATE")));
assert_eq!(f.targets.get(&Handle(0x11)), Some(&key("BLOCK", "GATE")));
assert_eq!(f.targets.get(&Handle(0x12)), Some(&key("LAYER", "DOOR")));
}
#[test]
fn rename_shared_leaves_an_unrelated_drawing_shared() {
let mut f = Foreign::default();
f.records.insert(key("LAYER", "A"), ForeignExtra { xdict: Some(Handle(0x40)), ..ForeignExtra::default() });
let mut a = std::sync::Arc::new(f);
let snapshot = a.clone();
Foreign::rename_shared(&mut a, &["LAYER"], "B", "C");
assert!(std::sync::Arc::ptr_eq(&a, &snapshot));
Foreign::rename_shared(&mut a, &["LAYER"], "a", "c");
assert!(a.records.contains_key(&key("LAYER", "C")) && snapshot.records.contains_key(&key("LAYER", "A")));
}
}
+4 -3
View File
@@ -112,7 +112,8 @@ pub struct Drawing {
/// Dimension styles in table order; [`Drawing::dim_style`] looks them up by name.
pub dim_styles: NamedList<DimStyle>,
pub mleader_styles: Vec<MLeaderStyle>,
pub table_styles: Vec<TableStyle>,
/// Table styles in table order; looked up by name with [`NamedList::by_name`].
pub table_styles: NamedList<TableStyle>,
/// Multiline styles (MLSTYLE); STANDARD is always there.
pub mline_styles: Vec<MLineStyle>,
/// Block definitions by name; [`Drawing::block`] looks them up.
@@ -195,7 +196,7 @@ impl Drawing {
d.scales = metric_scales();
d.dim_styles.push(DimStyle::iso25());
d.mleader_styles = vec![MLeaderStyle::metric()];
d.table_styles = vec![TableStyle::metric()];
d.table_styles = vec![TableStyle::metric()].into();
d.header.set_str("DIMSTYLE", "ISO-25");
d
}
@@ -213,7 +214,7 @@ impl Drawing {
text_styles: vec![TextStyle::default()].into(),
dim_styles: vec![DimStyle::default()].into(),
mleader_styles: vec![MLeaderStyle::default()],
table_styles: vec![TableStyle::default()],
table_styles: vec![TableStyle::default()].into(),
mline_styles: vec![MLineStyle::default()],
blocks: NamedMap::default(),
model: EntityStore::new(),
+6 -6
View File
@@ -1,6 +1,6 @@
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles
//! and layouts), whose names are looked up without case through an index instead of a scan once a
//! table is large and looked up often.
//! The drawing's tables of named entries (layers, blocks, linetypes, text styles, dimension styles,
//! table styles and layouts), whose names are looked up without case through an index instead of a
//! scan once a table is large and looked up often.
//!
//! [`Drawing::layer`](crate::Drawing::layer), [`Drawing::block`](crate::Drawing::block) and the
//! other lookups by name run for every entity while a drawing is read, measured and drawn, and
@@ -117,11 +117,11 @@ macro_rules! named_by_field {
}
)*};
}
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::Layout);
named_by_field!(crate::Layer, crate::Linetype, crate::TextStyle, crate::DimStyle, crate::TableStyle, crate::Layout);
/// A list of named entries in their own order (the drawing's layers, linetypes, text styles,
/// dimension styles and layouts). It reads and changes as a `Vec`; [`NamedList::by_name`] finds the
/// first entry of a name without case.
/// dimension styles, table styles and layouts). It reads and changes as a `Vec`;
/// [`NamedList::by_name`] finds the first entry of a name without case.
pub struct NamedList<T> {
list: Vec<T>,
index: Lazy<usize>,
+12 -3
View File
@@ -79,15 +79,21 @@ impl Default for DevicePaper {
impl DevicePaper {
/// The paper with hostile values fixed: finite sizes within 1..=[`MAX_PAPER_MM`] mm
/// (portrait), margins 0..=1000 mm that leave a printable area (else none), a name of at
/// most [`MAX_PLOTTER_NAME`] characters.
/// most [`MAX_PLOTTER_NAME`] characters. A sheet wider than tall is stored turned 90° and
/// its margins turn with it, so the printable area the caller measured against the sheet it
/// named is the one the stored portrait paper holds.
pub fn sanitized(mut self) -> DevicePaper {
let side = |v: f64| if v.is_finite() { v.clamp(1.0, MAX_PAPER_MM) } else { 1.0 };
let (w, h) = (side(self.width), side(self.height));
self.width = w.min(h);
self.height = w.max(h);
for m in &mut self.margins {
*m = if m.is_finite() { m.clamp(0.0, 1000.0) } else { 0.0 };
}
if w > h {
let [l, b, r, t] = self.margins;
self.margins = [b, r, t, l];
}
self.width = w.min(h);
self.height = w.max(h);
let [l, b, r, t] = self.margins;
if l + r >= self.width || b + t >= self.height {
self.margins = [0.0; 4];
@@ -243,6 +249,9 @@ mod tests {
assert_eq!(back.papers[1].margins, [0.0, 1000.0, 0.0, 5.0], "hostile margins clamped");
let wide = DevicePaper { margins: [150.0, 0.0, 100.0, 0.0], ..DevicePaper::default() }.sanitized();
assert_eq!(wide.margins, [0.0; 4], "margins wider than the paper are dropped");
let turned = DevicePaper { name: "Banner".into(), width: 400.0, height: 200.0, margins: [150.0, 0.0, 150.0, 0.0] }.sanitized();
assert_eq!((turned.width, turned.height), (200.0, 400.0), "portrait");
assert_eq!(turned.margins, [0.0, 150.0, 0.0, 150.0], "margins turn with the sheet");
assert!(back.paper("a3 BORDERLESS").is_some());
assert!(PlotterConfig::from_file_text("{}").is_err());
assert!(PlotterConfig::from_file_text(r#"{"cadcraftPlotter": 1}"#).is_err(), "needs a name");
+41 -1
View File
@@ -29,7 +29,7 @@ fn new_metric_drawing_has_metric_multileader_and_table_styles() {
let i = Drawing::new_imperial();
assert_eq!(i.mleader_styles, vec![MLeaderStyle::default()]);
assert_eq!(i.table_styles, vec![TableStyle::default()]);
assert_eq!(*i.table_styles, vec![TableStyle::default()]);
assert_eq!((i.mleader_styles[0].text_height, i.table_styles[0].text_height), (0.18, 0.18));
}
@@ -271,6 +271,46 @@ fn transform_arc_mirror_keeps_shape() {
}
}
#[test]
fn mirroring_a_rotated_dimension_reflects_its_direction() {
let dim = |kind: DimKind, marks: DimMarks| {
EntityKind::Dimension(Dimension {
kind,
defpt: Vec3::ZERO,
text_mid: Vec3::ZERO,
p13: Vec3::ZERO,
p14: Vec3::new(7.071_067_811_865_475, 7.071_067_811_865_475, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 10.0,
text_rotation: 0.0,
user_text_pos: false,
block: None,
insertion_point: Vec3::ZERO,
overrides: Default::default(),
assoc: vec![],
marks,
})
};
// A dimension line at 45° mirrored across the X axis runs at -45° (315°) and still measures 10.
let mut k = dim(DimKind::Linear { rotation: std::f64::consts::FRAC_PI_4 }, DimMarks::default());
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::X));
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
let DimKind::Linear { rotation } = d.kind else { panic!("a linear dimension") };
assert!((rotation - 7.0 * std::f64::consts::FRAC_PI_4).abs() < 1e-9, "{rotation}");
let p2 = Vec2::new(7.071_067_811_865_475, -7.071_067_811_865_475);
assert!((p2.dot(Vec2::from_angle(rotation)).abs() - 10.0).abs() < 1e-9, "the mirrored measurement");
// Oblique extension lines reflect about the mirror line too (a 45° line here) instead of
// being double-reflected (120° rather than 30°).
let mut k = dim(DimKind::Aligned, DimMarks { oblique: Some(std::f64::consts::FRAC_PI_3), ..DimMarks::default() });
k.transform(&Mat3::mirror(Vec2::ZERO, Vec2::new(1.0, 1.0)));
let EntityKind::Dimension(d) = k else { panic!("a dimension") };
assert!((d.marks.oblique.unwrap_or(0.0) - (std::f64::consts::FRAC_PI_2 - std::f64::consts::FRAC_PI_3)).abs() < 1e-9, "{:?}", d.marks.oblique);
}
#[test]
fn insert_bounds_with_cyclic_block_terminate() {
let mut d = Drawing::new_imperial();
+6 -3
View File
@@ -7,7 +7,7 @@
//! that contain themselves lose the reference that closes the loop, and objects sharing a handle
//! get new ones.
use std::collections::{BTreeMap, HashMap, HashSet};
use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::sync::Arc;
use cadcraft_doc::{Block, DimStyle, Drawing, Entity, EntityKind, EntityStore, Handle, Layer, Linetype, MLeaderStyle, TableStyle, TextStyle};
@@ -425,6 +425,9 @@ fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
let all = all_handles(d);
let ok_text = |d: &Drawing, n: &str| d.text_style(n).is_some();
let ok_dim = |d: &Drawing, n: &str| d.dim_style(n).is_some();
// Multileader style names, lower-cased, built once: a scan per multileader made a file of N of
// them naming styles among N quadratic to audit (#1924).
let mleader_styles: BTreeSet<String> = d.mleader_styles.iter().map(|s| s.name.to_ascii_lowercase()).collect();
// Missing names, counted: (what, name) → (objects, first location).
let mut counts: BTreeMap<(&'static str, String), (usize, String)> = BTreeMap::new();
missing_layers(d, out);
@@ -462,12 +465,12 @@ fn references(d: &mut Drawing, out: &mut Vec<Issue>) {
if let Some(t) = &mut m.text {
text_style(&mut t.style);
}
if !has_name(&d.mleader_styles, &m.style, |s| &s.name) {
if !mleader_styles.contains(&m.style.to_ascii_lowercase()) {
note("multileader style", &m.style);
m.style = "Standard".into();
}
}
EntityKind::Table(t) if !has_name(&d.table_styles, &t.style, |s| &s.name) => {
EntityKind::Table(t) if d.table_styles.by_name(&t.style).is_none() => {
note("table style", &t.style);
t.style = "Standard".into();
}
+14 -2
View File
@@ -79,17 +79,27 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result<Vec<Handle>> {
let defs = s.clipboard_source.as_ref().map(|c| c.defs.clone());
let space = s.space();
let d = s.doc_mut()?;
let renames = defs.map(|x| merge(d, &x)).unwrap_or_default();
let renames = defs.as_ref().map(|x| merge(d, x)).unwrap_or_default();
let mut out = Vec::new();
let mut copies = Vec::new();
for e in &ents {
let old_h = e.handle;
let mut e = adopt(d, e, &renames);
e.kind.transform(m);
d.ensure_layer(&e.common.layer);
out.push(e.handle);
copies.push((old_h, e.handle));
if let Some(st) = d.space_mut(&space) {
st.push(e);
}
}
if let Some(c) = &defs
&& !c.groups.is_empty()
{
super::groups::replicate_groups_from(d, &c.groups, &copies);
} else {
super::groups::replicate_groups_for_copies(d, &copies);
}
s.set_selection(out.clone());
Ok(out)
}
@@ -270,8 +280,10 @@ fn defs_for(src: &Drawing, ents: &[Entity]) -> Drawing {
d.text_styles = pick(&src.text_styles, &used.text_styles, |t| &t.name).into();
d.dim_styles = pick(&src.dim_styles, &used.dim_styles, |t| &t.name).into();
d.mleader_styles = pick(&src.mleader_styles, &used.mleader_styles, |t| &t.name);
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name);
d.table_styles = pick(&src.table_styles, &used.table_styles, |t| &t.name).into();
d.blocks = src.blocks.iter().filter(|(k, _)| used.blocks.contains(&up(k))).map(|(k, b)| (k.clone(), b.clone())).collect();
let ent_handles: HashSet<Handle> = ents.iter().map(|e| e.handle).collect();
d.groups = src.groups.iter().filter(|g| !g.members.is_empty() && g.members.iter().all(|m| ent_handles.contains(m))).cloned().collect();
d.layouts.clear();
d
}
+5 -1
View File
@@ -26,6 +26,10 @@ fn default_max_arc_len(s: &Session, min: f64) -> f64 {
s.doc().ok().map_or(min, |d| d.header.f64("CADCRAFT_REVCLOUDMAXARCLEN", min)).max(min)
}
/// The bulge of every arc of a revision cloud (an arc of about 110°). Readers that check
/// `RevcloudProps` xdata and bulge accept a closed polyline whose bulges are within 0.02 of this.
const CLOUD_BULGE: f64 = 0.520567050552;
/// Bulged closed polyline vertices for a revision cloud around `boundary`.
pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, reverse: bool) -> Option<Vec<PolyVertex>> {
let mut pts: Vec<Vec2> = Vec::new();
@@ -69,7 +73,7 @@ pub(crate) fn cloud_vertices(boundary: &[Vec2], arc_len: f64, per_edge: bool, re
out.extend(chain.at_length_in(&ends, perim * j as f64 / k as f64).map(|x| x.0));
}
}
let b = if reverse { -0.5 } else { 0.5 };
let b = if reverse { -CLOUD_BULGE } else { CLOUD_BULGE };
Some(out.into_iter().map(|p| PolyVertex::with_bulge(p, b)).collect())
}
+39 -17
View File
@@ -63,19 +63,11 @@ enum Order {
Under,
}
/// Move `hs` in the current space's draw order, keeping their order among themselves. Above and
/// Under place them right over the topmost reference object or right under the lowest one.
/// Returns how many objects moved.
fn reorder(s: &mut Session, hs: &[Handle], order: Order, refs: &[Handle]) -> Result<usize> {
let space = s.space();
let d = s.doc_mut()?;
let Some(st) = d.space_mut(&space) else { return Ok(0) };
fn reorder_store(st: &mut cadcraft_doc::EntityStore, hs: &[Handle], order: Order) -> usize {
let index: HashMap<Handle, usize> = st.handles().into_iter().enumerate().map(|(i, h)| (h, i)).collect();
let mut moving: Vec<(usize, Handle)> = hs.iter().filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
moving.sort_unstable();
moving.dedup();
let set: HashSet<Handle> = moving.iter().map(|m| m.1).collect();
let refs: Vec<(usize, Handle)> = refs.iter().filter(|h| !set.contains(h)).filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
match order {
Order::Front => {
for (_, h) in &moving {
@@ -87,6 +79,29 @@ fn reorder(s: &mut Session, hs: &[Handle], order: Order, refs: &[Handle]) -> Res
st.send_to_back(*h);
}
}
Order::Above | Order::Under => {}
}
moving.len()
}
/// Move `hs` in the current space's draw order, keeping their order among themselves. Above and
/// Under place them right over the topmost reference object or right under the lowest one.
/// Returns how many objects moved.
fn reorder(s: &mut Session, hs: &[Handle], order: Order, refs: &[Handle]) -> Result<usize> {
let space = s.space();
let d = s.doc_mut()?;
let Some(st) = d.space_mut(&space) else { return Ok(0) };
if matches!(order, Order::Front | Order::Back) {
return Ok(reorder_store(st, hs, order));
}
let index: HashMap<Handle, usize> = st.handles().into_iter().enumerate().map(|(i, h)| (h, i)).collect();
let mut moving: Vec<(usize, Handle)> = hs.iter().filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
moving.sort_unstable();
moving.dedup();
let set: HashSet<Handle> = moving.iter().map(|m| m.1).collect();
let refs: Vec<(usize, Handle)> = refs.iter().filter(|h| !set.contains(h)).filter_map(|h| index.get(h).map(|i| (*i, *h))).collect();
match order {
Order::Front | Order::Back => {}
Order::Above => {
let Some(&(_, mut cur)) = refs.iter().max() else { return Err(EngineError::Other("no reference objects".into())) };
for (_, h) in &moving {
@@ -181,15 +196,23 @@ impl Annot {
}
}
/// Every object of the current space that `keep` accepts, in draw order.
fn of_kind(s: &Session, keep: impl Fn(&EntityKind) -> bool) -> Result<Vec<Handle>> {
let d = s.doc()?;
Ok(d.space(&s.space()).map(|st| st.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect()).unwrap_or_default())
/// Reorder objects across all spaces (model space and all paper space layouts).
fn reorder_all_spaces(s: &mut Session, order: Order, keep: impl Fn(&EntityKind) -> bool) -> Result<usize> {
let d = s.doc_mut()?;
let mut total = 0;
// Model space
let hs: Vec<Handle> = d.model.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect();
total += reorder_store(&mut d.model, &hs, order);
// All paper space layouts
for layout in &mut d.layouts {
let hs: Vec<Handle> = layout.entities.iter().filter(|e| keep(&e.kind)).map(|e| e.handle).collect();
total += reorder_store(&mut layout.entities, &hs, order);
}
Ok(total)
}
fn annotations_to_front(s: &mut Session, which: Annot) -> Result<Value> {
let hs = of_kind(s, |k| which.matches(k))?;
let n = reorder(s, &hs, Order::Front, &[])?;
let n = reorder_all_spaces(s, Order::Front, |k| which.matches(k))?;
Ok(json!({ "moved": n, "message": format!("{n} object(s) brought to front.") }))
}
@@ -208,8 +231,7 @@ fn run_texttofront(s: &mut Session, p: &Value) -> Result<Value> {
}
fn run_hatchtoback(s: &mut Session, _p: &Value) -> Result<Value> {
let hs = of_kind(s, |k| matches!(k, EntityKind::Hatch(_)))?;
let n = reorder(s, &hs, Order::Back, &[])?;
let n = reorder_all_spaces(s, Order::Back, |k| matches!(k, EntityKind::Hatch(_)))?;
Ok(json!({ "moved": n, "message": format!("{n} hatch object(s) sent to back.") }))
}
+3 -2
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("export", "Export...", run_export)
.menu(&["File", "Export..."])
.alias(&["exp"])
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension)} → {format, bytes, path? | data}")
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension)} → {format, bytes, path? | data, warnings?: what an image draws short of the drawing}")
.noundo(),
CommandSpec::new("preview", "Plot Preview", run_preview)
.menu(&["File", "Plot Preview"])
@@ -123,7 +123,7 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("export", "`format` must be dxf, dwg, svg, png or pdf (or give a `path` with one of those extensions)"));
}
let file = format!("export.{format}");
let bytes = (hooks.write)(s.doc()?, &file).map_err(|e| bad("export", e))?;
let (bytes, notes) = super::file::write_noted(hooks, s.doc()?, &file).map_err(|e| bad("export", e))?;
let folder = path.and_then(super::file::new_folder);
let mut r = match path {
Some(path) => {
@@ -134,6 +134,7 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
};
super::file::report_new_folder(s, &mut r, folder);
super::file::report_loss(s, &mut r, &file);
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
+91 -17
View File
@@ -49,6 +49,47 @@ pub fn io() -> Option<&'static IoHooks> {
IO.get()
}
/// [`IoHooks::write`] and [`IoHooks::plot`] that also return what an image (PNG, SVG, PDF) draws
/// short of the drawing because of a render limit, one note each, such as dashed lines drawn
/// continuous past the dash limit (installed by the app with the image writers, a lower layer;
/// see `cadcraft_io::write_framed_noted` and `cadcraft_io::plotter::plot_noted`). EXPORT, QSAVE
/// and SAVEAS to an image, `document.bytes` and PLOT (so PUBLISH and PDFBOOK, sheet by sheet)
/// report them; without the hooks they write through [`IoHooks`] with no such notes. The app
/// installs the same writers as its [`IoHooks`].
pub struct NotedIo {
pub write: fn(&Drawing, &str) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
pub plot: fn(&Drawing, &cadcraft_doc::Space, &Value) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
}
static NOTED_IO: OnceLock<NotedIo> = OnceLock::new();
pub fn set_noted_io(h: NotedIo) {
let _ = NOTED_IO.set(h);
}
/// `d` written as `name` with the image's notes ([`NotedIo::write`]), or through `hooks.write`
/// with none when the app installed no [`NotedIo`].
pub(crate) fn write_noted(hooks: &IoHooks, d: &Drawing, name: &str) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.write)(d, name),
None => (hooks.write)(d, name).map(|bytes| (bytes, Vec::new())),
}
}
/// `d` plotted with the plot's notes ([`NotedIo::plot`]), or through `hook` with none when the
/// app installed no [`NotedIo`].
pub(crate) fn plot_noted(
hook: PlotHook,
d: &Drawing,
space: &cadcraft_doc::Space,
opts: &Value,
) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.plot)(d, space, opts),
None => hook(d, space, opts).map(|bytes| (bytes, Vec::new())),
}
}
/// An entity as DXF groups and back, for AutoLISP's `entget`, `entmake` and `entmod`
/// (installed by the app with the DXF reader and writer, a lower layer).
pub struct EntityCodec {
@@ -123,6 +164,11 @@ pub fn dwg_notes(d: &Drawing) -> Vec<String> {
/// Say on the command line what the DWG just written keeps only in part (`notes`, from
/// [`dwg_notes`]), and list it in the result's `warnings`.
pub(crate) fn report_dwg_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
report_notes(s, r, notes);
}
/// Say each of `notes` on the command line and add them to the result's `warnings`.
pub(crate) fn report_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
if notes.is_empty() {
return;
}
@@ -130,7 +176,12 @@ pub(crate) fn report_dwg_notes(s: &mut Session, r: &mut Value, notes: Vec<String
s.echo(note.clone());
}
if let Some(o) = r.as_object_mut() {
o.insert("warnings".into(), json!(notes));
match o.get_mut("warnings").and_then(Value::as_array_mut) {
Some(list) => list.extend(notes.into_iter().map(Value::String)),
None => {
o.insert("warnings".into(), json!(notes));
}
}
}
}
@@ -238,9 +289,10 @@ fn is_dxf(path: &str) -> bool {
Format::from_path(path) == Some(Format::Dxf)
}
/// The drawing written to `path` with `opts`: through [`IoHooks::write`] when no option is set,
/// else through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<Vec<u8>> {
/// The drawing written to `path` with `opts`: an image, or a drawing file with no option set,
/// through [`IoHooks::write`] (with an image's notes, [`write_noted`]); a drawing file at a
/// chosen version or as binary DXF through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(Vec<u8>, Vec<String>)> {
let hooks = io().ok_or_else(|| bad(cmd, "file formats are not available in this build"))?;
if opts.binary && !is_dxf(path) {
return Err(bad(cmd, "binary applies to DXF files only"));
@@ -249,11 +301,12 @@ fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<Vec<
let d: &cadcraft_doc::Drawing = if is_drawing_file(path) { s.state()?.drawing() } else { s.doc()? };
let copy = (opts.portable_fonts && is_drawing_file(path)).then(|| Drawing { portable_fonts: true, ..d.clone() });
let d = copy.as_ref().unwrap_or(d);
let r = if opts.version.is_none() && !opts.binary {
(hooks.write)(d, path)
// An image has no version: `write_as` would write the same bytes without the notes.
let r = if !is_drawing_file(path) || (opts.version.is_none() && !opts.binary) {
write_noted(hooks, d, path)
} else {
let w = write_as().ok_or_else(|| bad(cmd, "saving at a chosen version or as binary DXF is not available in this build"))?;
w(d, path, opts)
w(d, path, opts).map(|bytes| (bytes, Vec::new()))
};
r.map_err(|e| bad(cmd, e))
}
@@ -285,7 +338,7 @@ pub fn specs() -> Vec<CommandSpec> {
.noundo(),
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
CommandSpec::new("document.bytes", "Drawing as bytes", run_bytes)
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64}")
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64, warnings?: what an image draws short of the drawing}")
.noundo(),
CommandSpec::new("script", "Run Script...", run_script)
.menu(&["Tools", "Run Script..."])
@@ -529,18 +582,19 @@ fn run_closeall(s: &mut Session, _p: &Value) -> Result<Value> {
ok()
}
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<usize> {
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<(usize, Vec<String>)> {
let opts = SaveAs { binary: s.state()?.binary_dxf && is_dxf(path), ..SaveAs::default() };
save_as(s, "save", path, &opts)
}
/// Save to `path` with `opts`. A drawing file then keeps the version and binary choice: the
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again.
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<usize> {
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again. Also an
/// image's notes ([`write_noted`]).
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usize, Vec<String>)> {
if s.doc()?.refedit.is_some() {
return Err(bad(cmd, "A block reference is being edited in place: finish with REFCLOSE (Save or Discard) before saving."));
}
let bytes = write_bytes(s, cmd, path, opts)?;
let (bytes, notes) = write_bytes(s, cmd, path, opts)?;
let n = commit_save(s, path, &bytes, store)?;
if is_drawing_file(path) {
let st = s.state_mut()?;
@@ -552,7 +606,7 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<usiz
st.saved = st.drawing().clone();
}
}
Ok(n)
Ok((n, notes))
}
/// Put saved bytes where the user gets them: natively the file at `path`; on the web, which has
@@ -842,15 +896,18 @@ fn run_save(s: &mut Session, p: &Value) -> Result<Value> {
Some(p) => p.to_string(),
None => s.state()?.path.clone().ok_or_else(|| bad("qsave", "drawing has no file name yet; use saveas {path}"))?,
};
let n = save_to(s, &path)?;
Ok(saved(&path, n))
let (n, notes) = save_to(s, &path)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
Ok(r)
}
fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("saveas", "`path` is required"))?.to_string();
let opts = save_options("saveas", p)?;
let n = save_as(s, "saveas", &path, &opts)?;
let (n, notes) = save_as(s, "saveas", &path, &opts)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
if is_drawing_file(&path) {
r["version"] = json!(opts.version.unwrap_or_else(|| drawing_version(s, &path)).year());
r["binary"] = json!(opts.binary);
@@ -899,8 +956,9 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let opts = save_options("document.bytes", p)?;
let version = opts.version.unwrap_or_else(|| drawing_version(s, &format!("drawing.{fmt}")));
let lost = not_saved_as(s.doc()?, version);
let bytes = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let (bytes, notes) = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
report_notes(s, &mut r, notes);
if drops_unknown(format!("drawing.{fmt}")) {
report_not_saved(s, &mut r, &lost);
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
@@ -1215,6 +1273,22 @@ mod tests {
use crate::Session;
use crate::temp_dir::TempDir;
/// Notes join the warnings a result already has instead of replacing them, and are said on
/// the command line.
#[test]
fn notes_are_added_to_the_warnings_a_result_has() {
let mut s = Session::new();
let mut r = json!({ "warnings": ["kept"] });
super::report_notes(&mut s, &mut r, vec!["added".into()]);
assert_eq!(r["warnings"], json!(["kept", "added"]));
let mut r = json!({});
super::report_notes(&mut s, &mut r, Vec::new());
assert!(r.get("warnings").is_none());
super::report_notes(&mut s, &mut r, vec!["first".into()]);
assert_eq!(r["warnings"], json!(["first"]));
assert!(s.log.ends_with(&["added".to_string(), "first".to_string()]), "{:?}", s.log);
}
/// Whether the `.bak` name is taken is asked without following a link there: a dangling link
/// counts as taken, so a file that doesn't look like a drawing leaves it alone.
#[cfg(unix)]
+29
View File
@@ -71,6 +71,35 @@ fn next_unnamed(d: &Drawing) -> String {
(1..=d.groups.len() + 1).map(|n| format!("*A{n}")).find(|n| !used.contains(n)).unwrap_or_else(|| format!("*A{}", d.groups.len() + 1))
}
/// When entities are copied, replicate any whole groups whose members were all copied.
pub(crate) fn replicate_groups_from(d: &mut Drawing, src_groups: &[Group], copies: &[(Handle, Handle)]) {
if copies.is_empty() || src_groups.is_empty() {
return;
}
let map: std::collections::HashMap<Handle, Handle> = copies.iter().copied().collect();
let mut new_groups = Vec::new();
for g in src_groups {
let active_members: Vec<Handle> = g.members.iter().copied().filter(|h| d.entity(*h).is_some()).collect();
if !active_members.is_empty() && active_members.iter().all(|h| map.contains_key(h)) {
let new_members: Vec<Handle> = active_members.iter().filter_map(|h| map.get(h).copied()).collect();
new_groups.push((g.description.clone(), g.selectable, new_members));
}
}
for (desc, selectable, members) in new_groups {
if d.groups.len() >= MAX_GROUPS {
break;
}
let name = next_unnamed(d);
d.groups.push(Group { name, description: desc, selectable, members });
}
}
/// When entities in the drawing `d` are copied, replicate any whole groups among them.
pub(crate) fn replicate_groups_for_copies(d: &mut Drawing, copies: &[(Handle, Handle)]) {
let groups = d.groups.clone();
replicate_groups_from(d, &groups, copies);
}
/// `hs` without repeats and without handles of objects that don't exist.
fn existing(d: &Drawing, hs: &[Handle]) -> Vec<Handle> {
let mut seen = std::collections::HashSet::new();
+41 -13
View File
@@ -17,6 +17,7 @@ use super::{CommandSpec, bad, bool_or, f64_or, point_param, points_param, size_p
use crate::{Accept, EngineError, Input, Interactive, Picker, Prompt, Result, Session, Step};
mod arcs;
mod assoc;
pub(crate) use assoc::detach;
mod edit;
@@ -54,13 +55,15 @@ pub(super) fn outline_tol(ext: Bounds2) -> f64 {
}
/// Tessellated outlines of every visible curve in the space (hatch boundary candidates), each
/// with the handle of the object it came from.
fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>>, Vec<Handle>) {
let Some(store) = d.space(space) else { return (Vec::new(), Vec::new()) };
/// with the handle of the object it came from and its exact piece ([`arcs::pieces_of`]), and
/// the flattening tolerance.
fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>>, Vec<Handle>, Vec<Option<arcs::Piece>>, f64) {
let ext = d.extents(space);
let tol = outline_tol(ext);
let Some(store) = d.space(space) else { return (Vec::new(), Vec::new(), Vec::new(), tol) };
let mut out = Vec::new();
let mut owners = Vec::new();
let mut pieces = Vec::new();
for e in store.iter() {
if !d.is_visible(e) || matches!(e.kind, EntityKind::Hatch(_) | EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Dimension(_)) {
continue;
@@ -73,9 +76,10 @@ fn outlines(d: &Drawing, space: &Space, near: Option<Bounds2>) -> (Vec<Vec<Vec2>
}
let polys = object_polys(d, e, tol, ext);
owners.extend(std::iter::repeat_n(e.handle, polys.len()));
pieces.extend(arcs::pieces_of(e, polys.len()));
out.extend(polys);
}
(out, owners)
(out, owners, pieces, tol)
}
/// An object's outline as polylines (tolerance `tol`), infinite lines clipped to a generous
@@ -193,7 +197,7 @@ impl OriginMode {
}
/// The origin for loops: `current` when the mode keeps it.
pub(crate) fn origin(self, loops: &[HatchLoop], current: Vec2) -> Vec2 {
let b = Bounds2::from_points(loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)).filter(|p| p.is_finite()));
let b = loops_bounds(loops);
if b.is_empty() {
return current;
}
@@ -208,6 +212,25 @@ impl OriginMode {
}
}
/// The extents of hatch loops with their arcs: a bulged edge reaches past its vertices (a circle
/// kept as two half-circle vertices spans its whole height).
fn loops_bounds(loops: &[HatchLoop]) -> Bounds2 {
let mut b = Bounds2::from_points(loops.iter().flat_map(|l| l.vertices.iter().map(|v| v.p)).filter(|p| p.is_finite()));
for l in loops {
let vs = &l.vertices;
for (i, v) in vs.iter().enumerate() {
let Some(next) = vs.get((i + 1) % vs.len()) else { continue };
if let Some((arc, _)) = cadcraft_geom::bulge_to_arc(v.p, next.p, v.bulge) {
let ab = arc.bounds();
if ab.min.is_finite() && ab.max.is_finite() {
b = b.union(&ab);
}
}
}
}
b
}
/// Island detection style by name (HPISLANDDETECTION 0 normal, 1 outer, 2 ignore).
pub(crate) fn island_style(t: &str) -> Option<u8> {
match t.trim().to_ascii_lowercase().as_str() {
@@ -224,15 +247,17 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
let space = s.space();
let ext = d.extents(&space);
let tol = ((ext.width() + ext.height()) * 1e-9).max(1e-9);
let (polys, owners) = outlines(d, &space, None);
let (polys, owners, pieces, ftol) = outlines(d, &space, None);
// A line that ends on a flattened curve (an ellipse) can stop short of its chords.
let polys = cadcraft_geom::region::snap_ends(&polys, outline_tol(ext), tol);
let polys = cadcraft_geom::region::snap_ends(&polys, ftol, tol);
let found = cadcraft_geom::region::boundary_at_gap(&polys, p, tol, gap_tolerance(d))
.ok_or_else(|| EngineError::Other("Valid hatch boundary not found.".into()))?;
let outer = found.outer;
let ob = Bounds2::from_points(outer.iter().copied());
let sources = handles_of(&owners, &found.outer_sources);
let mut loops = vec![HatchLoop { vertices: outer.iter().map(|q| PolyVertex::new(*q)).collect(), outer: true, boundary_flags: None, sources }];
// The traced outline is flattened: circular runs become arcs again (#1167).
let mut loops =
vec![HatchLoop { vertices: arcs::with_arcs(&outer, &found.outer_edges, &pieces, ftol), outer: true, boundary_flags: None, sources }];
// Islands: closed objects entirely inside the outer loop that don't contain the pick point.
if let Some(store) = d.space(&space) {
for e in store.iter() {
@@ -261,7 +286,7 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
if open_curves {
let sources = handles_of(&owners, &island.sources);
loops.push(HatchLoop {
vertices: island.outline.into_iter().map(PolyVertex::new).collect(),
vertices: arcs::with_arcs(&island.outline, &island.edges, &pieces, ftol),
outer: false,
boundary_flags: None,
sources,
@@ -274,7 +299,9 @@ pub(crate) fn loops_at(s: &Session, p: Vec2) -> Result<Vec<HatchLoop>> {
pub(crate) fn loops_from_handles(s: &Session, hs: &[Handle]) -> Result<Vec<HatchLoop>> {
let d = s.doc()?;
let mut loops = Vec::new();
for h in hs {
let mut seen = std::collections::HashSet::new();
// An object selected twice is one boundary.
for h in hs.iter().filter(|h| seen.insert(**h)) {
if let Some(vs) = d.entity(*h).and_then(|e| closed_loop(d, e)) {
loops.push(HatchLoop { vertices: vs, outer: loops.is_empty(), boundary_flags: None, sources: vec![*h] });
}
@@ -429,17 +456,18 @@ fn same_loop(a: &HatchLoop, b: &HatchLoop) -> bool {
})
}
/// Deduplicate boundary loops that describe the same boundary.
/// Deduplicate boundary loops that describe the same boundary in the same role. A loop that is
/// one pick's outer loop and another's island (a pick inside a circle and one around it) stays
/// twice: merged, the island would be gone and the even-odd fill would leave the circle empty.
fn dedup_loops(loops: &mut Vec<HatchLoop>) {
let mut unique: Vec<HatchLoop> = Vec::with_capacity(loops.len());
for l in loops.drain(..) {
if let Some(existing) = unique.iter_mut().find(|u| same_loop(u, &l)) {
if let Some(existing) = unique.iter_mut().find(|u| u.outer == l.outer && same_loop(u, &l)) {
for s in l.sources {
if !existing.sources.contains(&s) {
existing.sources.push(s);
}
}
existing.outer = existing.outer || l.outer;
} else {
unique.push(l);
}
+147
View File
@@ -0,0 +1,147 @@
//! Exact arcs in traced hatch boundaries (#1167).
//!
//! The boundary search works on flattened curves, so a loop traced around an internal point
//! comes out as chords: a hatch in a circle had 158 straight edges and the wrong area. Each
//! traced edge knows the input polyline it lies on, and each input polyline is one piece of one
//! object (a line, a circle, an arc or one segment of a polyline), so nothing is guessed from
//! nearby geometry: a run of edges on the same circular piece becomes one bulged vertex again,
//! and the corners move onto the exact curves (where a line or another circle crosses).
use cadcraft_doc::{Entity, EntityKind, Prim};
use cadcraft_geom::{Circle, Line, PolyVertex, Segment, Vec2, arc_to_bulge, circle_circle, line_circle, shoelace};
/// The exact curve behind one input polyline.
#[derive(Clone, Copy, Debug)]
pub(crate) enum Piece {
Line(Line),
Circle(Circle),
}
/// The exact piece behind each of `e`'s `n` outline polylines (one per primitive, in order, as
/// `select::hit_polylines` makes them), or `None` for each when `e` isn't made of lines and
/// circular arcs or the count doesn't match.
pub(crate) fn pieces_of(e: &Entity, n: usize) -> Vec<Option<Piece>> {
if !matches!(e.kind, EntityKind::Line(_) | EntityKind::Arc(_) | EntityKind::Circle(_) | EntityKind::LwPolyline(_)) {
return vec![None; n];
}
let prims = e.kind.prims();
if prims.len() != n {
return vec![None; n];
}
prims
.iter()
.map(|p| match p {
Prim::Seg(Segment::Line(l)) => Some(Piece::Line(*l)),
Prim::Seg(Segment::Arc { arc, .. }) => Some(Piece::Circle(Circle::new(arc.center, arc.radius))),
Prim::Circle(c) => Some(Piece::Circle(*c)),
_ => None,
})
.collect()
}
fn same_circle(a: &Circle, b: &Circle) -> bool {
a.center == b.center && a.radius == b.radius
}
/// The loop `pts` (edge `i` from `pts[i]` to the next vertex, closed) with its circular runs
/// as bulged vertices. `edges` names each edge's input polyline, `pieces` each polyline's exact
/// curve; `tol` is the flattening tolerance the polylines were made with. Anything that doesn't
/// check out stays as traced.
pub(crate) fn with_arcs(pts: &[Vec2], edges: &[Option<usize>], pieces: &[Option<Piece>], tol: f64) -> Vec<PolyVertex> {
let n = pts.len();
let plain = || pts.iter().map(|p| PolyVertex::new(*p)).collect::<Vec<_>>();
if n < 3 || edges.len() != n || !(tol.is_finite() && tol > 0.0) || pts.iter().any(|p| !p.is_finite()) {
return plain();
}
let at = |i: usize| pts.get(i % n).copied().unwrap_or_default();
let piece = |i: usize| edges.get(i % n).copied().flatten().and_then(|k| pieces.get(k).copied().flatten());
// A chord of a curve flattened to `tol` stays within `tol` of it; corners split where two
// chords cross may be a little further.
let slack = tol * 4.0;
let near_circle = |c: &Circle, q: Vec2| (c.center.dist(q) - c.radius).abs() <= slack;
// The circle each edge lies on: its piece is a circle and both ends and the middle are on
// it (the middle, so a long chord across the circle doesn't pass for an arc).
let circ: Vec<Option<(usize, Circle)>> = (0..n)
.map(|i| {
let k = edges.get(i).copied().flatten()?;
let Some(Piece::Circle(c)) = piece(i) else { return None };
let (a, b) = (at(i), at(i + 1));
(c.radius.is_finite() && c.radius > slack && near_circle(&c, a) && near_circle(&c, b) && near_circle(&c, a.mid(b))).then_some((k, c))
})
.collect();
let key = |i: usize| circ.get(i % n).copied().flatten().map(|(k, _)| k);
if circ.iter().all(Option::is_none) {
return plain();
}
let ccw = shoelace(pts) > 0.0;
// One whole circle: two half circles, as a hatch made by selecting the circle has.
if let Some(Some((k0, c))) = circ.first().copied()
&& (0..n).all(|i| key(i) == Some(k0))
{
let b = if ccw { 1.0 } else { -1.0 };
return vec![PolyVertex::with_bulge(c.center - Vec2::X * c.radius, b), PolyVertex::with_bulge(c.center + Vec2::X * c.radius, b)];
}
let line_of = |i: usize| match piece(i) {
Some(Piece::Line(l)) if l.a != l.b && [at(i), at(i + 1)].iter().all(|q| ((*q - l.a).cross(l.b - l.a) / l.a.dist(l.b)).abs() <= slack) => {
Some(l)
}
_ => None,
};
let onto = |c: &Circle, q: Vec2| {
let d = q - c.center;
if d.len() > 0.0 { c.center + d.normalized() * c.radius } else { q }
};
// Vertex `i` (between edges `i - 1` and `i`) on the exact curves: where the two pieces
// cross, nearest the traced corner, or else moved onto the circle it is on.
let corner = |i: usize| -> Vec2 {
let p = at(i);
let (prev, next) = (circ.get((i + n - 1) % n).copied().flatten(), circ.get(i % n).copied().flatten());
let crossings: Vec<Vec2> = match (prev, next) {
(Some((_, a)), Some((_, b))) if same_circle(&a, &b) => return onto(&a, p),
(Some((_, a)), Some((_, b))) => circle_circle(&a, &b),
(Some((_, c)), None) => line_of(i).map(|l| line_circle(&l, &c).into_iter().map(|x| x.0).collect()).unwrap_or_default(),
(None, Some((_, c))) => line_of(i + n - 1).map(|l| line_circle(&l, &c).into_iter().map(|x| x.0).collect()).unwrap_or_default(),
(None, None) => return p,
};
// Where two curves cross at a shallow angle, a corner off them by the flattening
// tolerance can be off along them by up to about √(2·r·tolerance): the crossing nearest
// the traced corner is taken within that reach, when no other crossing is as near.
let r = prev.or(next).map_or(0.0, |(_, c)| c.radius);
let reach = slack * 2.0 + (2.0 * r * slack).sqrt();
let mut xs: Vec<(f64, Vec2)> = crossings.into_iter().filter(|x| x.is_finite()).map(|x| (x.dist(p), x)).collect();
xs.sort_by(|a, b| a.0.total_cmp(&b.0));
match (xs.first(), xs.get(1)) {
(Some(&(d, x)), second) if d <= reach && second.is_none_or(|&(d2, _)| d2 > 2.0 * d + slack) => x,
_ => prev.or(next).map_or(p, |(_, c)| onto(&c, p)),
}
};
// Start where a run begins, so no run wraps past the end.
let Some(s) = (0..n).find(|&i| key(i) != key(i + n - 1)) else { return plain() };
let mut out = Vec::with_capacity(n);
let mut i = 0;
while i < n {
let e = (s + i) % n;
let p = corner(e);
let Some((k, c)) = circ.get(e).copied().flatten() else {
out.push(PolyVertex::new(p));
i += 1;
continue;
};
// The angle the run turns through about the centre, edge by edge.
let mut sweep = 0.0;
let mut a = p;
let mut j = i;
while j < n && key(s + j) == Some(k) {
let last = j + 1 >= n || key(s + j + 1) != Some(k);
let b = if last { corner(s + j + 1) } else { at(s + j + 1) };
let (u, v) = (a - c.center, b - c.center);
sweep += u.cross(v).atan2(u.dot(v));
a = b;
j += 1;
}
let bulge = arc_to_bulge(sweep);
out.push(PolyVertex::with_bulge(p, if bulge.is_finite() { bulge } else { 0.0 }));
i = j;
}
if out.len() < 2 { plain() } else { out }
}
+12 -5
View File
@@ -87,8 +87,14 @@ fn refill(before: &Drawing, after: &Drawing, l: &HatchLoop) -> Refill {
return Refill::Open;
}
let tol = super::outline_tol(nb);
let mut polys: Vec<Vec<Vec2>> = Vec::new();
let mut pieces = Vec::new();
for e in live.iter().filter_map(|h| after.entity(*h)) {
let ps = object_polys(after, e, tol, nb);
pieces.extend(super::arcs::pieces_of(e, ps.len()));
polys.extend(ps);
}
let snap = ((nb.width() + nb.height()) * 1e-9).max(1e-9);
let polys: Vec<Vec<Vec2>> = live.iter().filter_map(|h| after.entity(*h)).flat_map(|e| object_polys(after, e, tol, nb)).collect();
let polys = region::snap_ends(&polys, tol, snap);
let gap = gap_tolerance(after);
let found = if l.outer {
@@ -97,13 +103,14 @@ fn refill(before: &Drawing, after: &Drawing, l: &HatchLoop) -> Refill {
let ob = if ob.is_empty() { nb } else { ob };
let old = outline_of(&l.vertices, (ob.width() + ob.height()).max(1e-9) / 20000.0);
region::interior_point(&old)
.and_then(|q| region::enclosing_loop_gap(&polys, map_point(q, &ob, &nb), snap, gap))
.or_else(|| region::outline(&polys, snap, gap))
.and_then(|q| region::enclosing_loop_edges_gap(&polys, map_point(q, &ob, &nb), snap, gap))
.or_else(|| region::outline_edges(&polys, snap, gap))
} else {
region::outline(&polys, snap, gap)
region::outline_edges(&polys, snap, gap)
};
match found {
Some(pts) => Refill::Loop(pts.into_iter().map(PolyVertex::new).collect()),
// Traced again from flattened curves: circular runs become arcs again (#1167).
Some((pts, edges)) => Refill::Loop(super::arcs::with_arcs(&pts, &edges, &pieces, tol)),
None => Refill::Open,
}
}
+16 -2
View File
@@ -8,7 +8,7 @@ use cadcraft_geom::{Bounds2, Polyline, Vec2, point_in_polygon};
use serde_json::{Value, json};
use super::assoc::{detach, same_shape};
use super::{GRADIENT_NAMES, ORIGIN_KW, OriginMode, closed_loop, dedup_loops, gradient_name, island_style, loops_at, loops_from_handles};
use super::{GRADIENT_NAMES, ORIGIN_KW, OriginMode, closed_loop, dedup_loops, gradient_name, island_style, loops_at, loops_from_handles, same_loop};
use crate::cmd::helpers::lwpoly;
use crate::cmd::{bad, bool_or, point_param, points_param, size_param, str_param, targets};
use crate::{Accept, Input, Interactive, Picker, Prompt, Result, Session, Step};
@@ -420,7 +420,21 @@ fn edit_loops(h: &mut Hatch, added: &[HatchLoop], removed: &[usize]) -> Result<(
return Ok(());
}
h.loops = h.loops.drain(..).enumerate().filter_map(|(i, l)| (!removed.contains(&i)).then_some(l)).collect();
h.loops.extend_from_slice(added);
// A boundary the hatch already has is not added again (whatever role it has here): a second
// copy would cancel it under the odd-parity fill. Its objects join the loop there, so picking
// it links an unlinked loop to them.
for a in added {
match h.loops.iter_mut().find(|l| same_loop(l, a)) {
Some(l) => {
for s in &a.sources {
if !l.sources.contains(s) {
l.sources.push(*s);
}
}
}
None => h.loops.push(a.clone()),
}
}
dedup_loops(&mut h.loops);
if h.loops.is_empty() {
return Err(bad("hatchedit", "a hatch needs at least one boundary loop"));
+9 -4
View File
@@ -532,12 +532,17 @@ pub(super) fn object_area(s: &Session, h: Handle) -> Result<(f64, f64)> {
(cadcraft_geom::PI * a * b, arc.arc_length_from(0.0, cadcraft_geom::TAU))
}
EntityKind::Hatch(hh) => {
// Odd parity, as drawn: a loop nested inside an odd number of other loops is an unfilled island.
let geoms: Vec<Polyline> = hh.loops.iter().map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect();
let polys: Vec<Vec<Vec2>> = geoms.iter().map(|g| g.tessellate(1e-3)).collect();
// Odd parity, as drawn: a loop nested inside an odd number of other loops is an unfilled
// island. The loops the fill keeps (a repeated loop once; an outer loop and an island
// that are the same boundary cancel), each measured exactly with its arcs.
let kept = cadcraft_render::hatch_fill_loop_indices(hh, 1e-3);
let geoms: Vec<Polyline> =
kept.iter().filter_map(|(i, _)| hh.loops.get(*i)).map(|l| Polyline { vertices: l.vertices.clone(), closed: true }).collect();
let polys: Vec<Vec<Vec2>> = kept.into_iter().map(|(_, p)| p).collect();
let mut total = (0.0, 0.0);
for (i, g) in geoms.iter().enumerate() {
let probe = polys.get(i).and_then(|p| p.first().copied());
// As the fill tests nesting: an edge's middle (a vertex may touch the loop around).
let probe = polys.get(i).and_then(|p| cadcraft_render::hatch_loop_probe(p));
let depth = probe.map_or(0, |pt| polys.iter().enumerate().filter(|(j, q)| *j != i && cadcraft_geom::point_in_polygon(q, pt)).count());
total.0 += if depth % 2 == 0 { g.area().abs() } else { -g.area().abs() };
total.1 += g.len();
+1
View File
@@ -251,6 +251,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
*l = updated;
if let Some(nn) = new_name {
l.name = nn.clone();
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["LAYER"], &old, &nn);
// Re-point entities in model space, every layout and every block definition.
repoint(&mut d.model, &old, &nn);
for layout in &mut d.layouts {
+174 -8
View File
@@ -26,8 +26,12 @@ pub fn specs() -> Vec<CommandSpec> {
.interactive(|_| Ok(Box::new(prompts::LayoutM::default()))),
CommandSpec::new("layout.new", "New Layout", run_new)
.menu(&["Insert", "Layout", "New Layout"])
.params("{name?, viewport?: bool (default true)} → {name, viewport}")
.params("{name?, viewport?: bool (default true), window?: [[x1,y1],[x2,y2]] (the model area the viewport shows; default the model extents)} → {name, viewport} (typed: asks the name only; LAYOUT.NEWAREA also asks the area)")
.interactive(|_| Ok(Box::new(NewLayoutM))),
CommandSpec::new("layout.newarea", "New Layout from Area...", run_new)
.menu(&["Insert", "Layout", "New Layout from Area..."])
.params("{name?, viewport?: bool (default true), window?: [[x1,y1],[x2,y2]] (the model area the viewport shows; default the model extents)} → {name, viewport} (typed: asks the name, then the area)")
.interactive(|_| Ok(Box::new(NewLayoutAreaM::default()))),
CommandSpec::new("layout.delete", "Delete Layout", run_delete).params("{name}"),
CommandSpec::new("layout.rename", "Rename Layout", run_rename).params("{from?: current layout, to}"),
CommandSpec::new("layout.copy", "Copy Layout", run_copy).params("{from, to?}"),
@@ -225,7 +229,133 @@ impl Interactive for NewLayoutM {
}
}
/// LAYOUT.NEWAREA from the menu or command line: asks for the name (Enter takes the next free one),
/// then for the part of the model the new layout shows. The Model tab is shown for that, so it
/// can be zoomed and panned first; two corners pick the area (Enter takes the whole drawing). The
/// new layout is then shown, zoomed to that area.
#[derive(Default)]
struct NewLayoutAreaM {
/// The checked name, once it has been asked.
name: Option<String>,
/// The first corner of the model area.
first: Option<Vec2>,
/// The tab the command started in, put back when it is cancelled.
from: Option<Space>,
}
impl NewLayoutAreaM {
/// Show tab `space` (`layout.set`).
fn show(s: &mut Session, space: &Space) -> Result<()> {
let set = find_command("layout.set").ok_or_else(|| crate::EngineError::UnknownCommand("layout.set".into()))?;
(set.run)(s, &json!({ "name": space.tab_name() }))?;
Ok(())
}
}
impl Interactive for NewLayoutAreaM {
fn name(&self) -> &'static str {
"LAYOUT"
}
fn prompt(&self, s: &Session) -> Prompt {
match (&self.name, self.first) {
(None, _) => {
let next = s.doc().map(next_layout_name).unwrap_or_else(|_| "Layout1".into());
Prompt::new("Enter name of new layout", Accept::TEXT).default(next)
}
(Some(_), None) => {
Prompt::new("Specify first corner of the model area to show in the layout, or press ENTER for the whole drawing", Accept::POINT)
}
// A window's first corner: with ortho on, the opposite corner is not bent onto it.
(Some(_), Some(a)) => Prompt::new("Specify opposite corner", Accept::POINT).corner(a),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let Some(name) = self.name.clone() else {
let name = match i {
Input::Text(t) if !t.trim().is_empty() => t.trim().to_string(),
Input::Text(_) | Input::Enter => next_layout_name(s.doc()?),
_ => return Ok(Step::Continue),
};
// A taken or invalid name is an error: the session reports it and asks again.
let name = check_name("layout.newarea", s.doc()?, &name, None)?;
// The area is picked in the Model tab, where the drawing can be zoomed and panned.
self.from = Some(s.layout_space());
Self::show(s, &Space::Model)?;
self.name = Some(name);
return Ok(Step::Continue);
};
// The corners are model points. If another tab was shown meanwhile (a tab click, `layout.set`),
// a point would be read in that space, so the command ends and leaves that choice alone.
if s.layout_space() != Space::Model {
self.from = None;
return Ok(Step::Cancel);
}
let window = match (i, self.first) {
(Input::Point(p), None) => {
self.first = Some(p);
return Ok(Step::Continue);
}
(Input::Point(p), Some(a)) => Some([a, p]),
(Input::Enter, None) => None,
_ => return Ok(Step::Continue),
};
let mut p = json!({ "name": name });
if let (Some([a, b]), Some(o)) = (window, p.as_object_mut()) {
o.insert("window".into(), json!([[a.x, a.y], [b.x, b.y]]));
}
// A window without width or height is an error, reported before any layout is added:
// the session asks for the first corner again.
self.first = None;
run_new(s, &p)?;
Self::show(s, &Space::Paper(name))?;
Ok(Step::Done)
}
/// Puts back the tab the command started in.
fn cancelled(&mut self, s: &mut Session) {
// Only if the Model tab is still shown: a tab the user chose since is left alone.
if let Some(from) = self.from.take()
&& s.layout_space() == Space::Model
&& let Err(e) = Self::show(s, &from)
{
s.echo(e.to_string());
}
}
/// The rectangle following the cursor while the second corner is picked.
fn preview(&self, _s: &Session, c: Vec2) -> Vec<EntityKind> {
let Some(a) = self.first else { return Vec::new() };
let corners = [a, Vec2::new(c.x, a.y), c, Vec2::new(a.x, c.y), a];
corners
.windows(2)
.filter_map(|w| match w {
[p, q] => Some(super::helpers::line(*p, *q)),
_ => None,
})
.collect()
}
}
/// The model-space window of a `layout.new`, when it has one: `window: [[x1, y1], [x2, y2]]`.
fn window_param(p: &Value) -> Result<Option<Bounds2>> {
let Some(raw) = p.get("window").filter(|w| !w.is_null()) else { return Ok(None) };
let corners = raw.as_array();
let a = corners.and_then(|c| c.first()).and_then(point_value);
let b = corners.and_then(|c| c.get(1)).and_then(point_value);
let (Some(a), Some(b)) = (a, b) else {
return Err(bad("layout.new", "`window` needs two corners: [[x1, y1], [x2, y2]]"));
};
let w = Bounds2::new(a, b);
if w.min.is_finite() && w.max.is_finite() && w.width() > 1e-9 && w.height() > 1e-9 && w.width() < 1e12 && w.height() < 1e12 {
Ok(Some(w))
} else {
Err(bad("layout.new", "the window needs a width and a height"))
}
}
/// LAYOUT.NEW from JSON: add a layout (with a viewport unless `viewport` is false), zoomed to
/// `window` when it has one and to the model extents otherwise.
fn run_new(s: &mut Session, p: &Value) -> Result<Value> {
// Checked before anything is added, so a bad window leaves no layout behind.
let window = window_param(p)?;
let d = s.doc()?;
let name = match str_param(p, "name") {
Some(n) => check_name("layout.new", d, n, None)?,
@@ -236,16 +366,30 @@ fn run_new(s: &mut Session, p: &Value) -> Result<Value> {
s.doc_mut()?.layouts.push(Layout { page, ..Layout::new(&name, order) });
let mut vp = Value::Null;
if bool_or(p, "viewport", true) {
// AutoCAD behaviour: one viewport over the printable area, zoomed to the model extents.
// AutoCAD behaviour: one viewport over the printable area, zoomed to the model extents,
// or to the `window` when it has one.
let space = Space::Paper(name.clone());
let rect = printable(s, &name)?;
if let Some(h) = add_viewports(s, &space, rect, 1, "")?.first() {
if let Some(w) = window {
show_window(s, *h, w)?;
}
vp = json!(h.hex());
}
}
Ok(json!({ "name": name, "viewport": vp }))
}
/// Zoom viewport `h` to the model area `w`.
fn show_window(s: &mut Session, h: Handle, w: Bounds2) -> Result<()> {
s.doc_mut()?.modify_entity(h, |e| {
if let EntityKind::Viewport(v) = &mut e.kind {
(v.view_center, v.view_height) = fit_bounds(w, v.width, v.height);
}
})?;
Ok(())
}
fn run_delete(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").ok_or_else(|| bad("layout.delete", "`name` is required"))?;
let name = layout_name("layout.delete", s.doc()?, name)?;
@@ -437,6 +581,11 @@ fn fit_view(d: &Drawing, w: f64, h: f64) -> (Vec2, f64) {
let hi = d.header.point("LIMMAX").map(|p| p.xy()).unwrap_or(Vec2::new(12.0, 9.0));
ext = Bounds2::new(lo, hi);
}
fit_bounds(ext, w, h)
}
/// The view centre and height that show the model area `ext` in a viewport of size `w` × `h`.
fn fit_bounds(ext: Bounds2, w: f64, h: f64) -> (Vec2, f64) {
let aspect = (w / h.max(1e-12)).max(1e-12);
let vh = (ext.height().max(ext.width() / aspect) * 1.02).max(1e-9);
let c = ext.center();
@@ -683,8 +832,21 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
// The standard size the layout had before this call, so that resubmitting it (the Plot
// dialog's Apply to Layout always sends `paper`) keeps the layout's paper units.
let old_paper = cadcraft_render::paper_size(&page.paper).map(|ps| ps.name);
let turned = p.get("landscape").and_then(Value::as_bool).filter(|l| *l != page.landscape);
// The orientation first: a paper taken from a device turns its margins to the sheet the page
// names when `page_device` copies them.
if let Some(l) = turned {
page.landscape = l;
}
// A plotter's own papers (with their printable areas) come first.
let device_paper = super::plotters::page_device(cmd, p, &mut page)?;
// A page that keeps its paper keeps its margins, and the margins are measured against the
// sheet's axes: turning the orientation turns them too (#1266). Explicit margins are already
// on the new sheet's axes.
if turned.is_some() && !device_paper && p.get("margins").is_none() {
page.margins_mm =
if page.landscape { super::plotters::landscape_margins(page.margins_mm) } else { super::plotters::portrait_margins(page.margins_mm) };
}
if let Some(paper) = p.get("paper").filter(|_| !device_paper) {
let n = paper.as_str().ok_or_else(|| bad(cmd, "`paper` must be a paper name"))?;
let ps = cadcraft_render::paper_size(n).ok_or_else(|| {
@@ -723,9 +885,6 @@ fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
(None, None) if p.get("width").is_none() && p.get("height").is_none() => {}
_ => return Err(bad(cmd, "`width` and `height` (mm, 0-5080) are both required for a custom size")),
}
if let Some(l) = p.get("landscape").and_then(Value::as_bool) {
page.landscape = l;
}
// Paper units: what one paper-space unit is on this layout, whatever the paper's own family
// (an ARCH D sheet can be drawn in millimetres, #3249).
if let Some(v) = p.get("paperUnits") {
@@ -890,7 +1049,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
if is_image && sheets.as_ref().is_some_and(|names| names.len() > 1) {
return Err(bad(cmd, "`layouts` with several sheets needs PDF output; PNG and SVG hold one sheet, so plot each layout separately"));
}
let bytes = hook(s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let (bytes, notes) = super::file::plot_noted(hook, s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let layout = match &sheets {
Some(names) => names.first().cloned().unwrap_or_default(),
None => space.tab_name().to_string(),
@@ -909,15 +1068,22 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_new_folder(s, &mut r, folder);
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
#[cfg(target_arch = "wasm32")]
{
super::exchange::deliver_file(cmd, _path, &bytes, super::file::deliver())?;
Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format }))
let mut r = json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
}
None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })),
None => {
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
}
}
+136
View File
@@ -88,6 +88,7 @@ fn new_layout_from_the_menu_asks_for_a_name() {
s.cmdline("Layout1").unwrap();
assert!(s.running.is_some(), "a taken name asks again");
s.cmdline("Sheet A").unwrap();
// The name is all it asks: no model area, no tab change.
assert!(s.running.is_none());
s.start("layout.new").unwrap();
s.cmdline("").unwrap();
@@ -95,6 +96,141 @@ fn new_layout_from_the_menu_asks_for_a_name() {
assert!(d.layout("Sheet A").is_some() && d.layout("Layout3").is_some(), "Enter takes the default name");
}
/// LAYOUT.NEWAREA asks the name, then the area; Enter takes the whole drawing.
#[test]
fn new_layout_from_area_asks_a_name_then_the_area() {
let mut s = session_with_model();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet A").unwrap();
assert!(s.running.is_some() && s.current_prompt().is_some_and(|p| p.message.contains("first corner of the model area")));
s.cmdline("").unwrap();
assert!(s.running.is_none());
assert!(s.doc().unwrap().layout("Sheet A").is_some());
}
/// The viewport of layout `name`.
fn only_viewport(s: &Session, name: &str) -> Viewport {
let v = viewports(s, name);
assert_eq!(v.len(), 1, "one viewport");
v.into_iter().next().map(|(_, v)| v).unwrap()
}
/// A `window` zooms the new layout's viewport to that part of the model.
#[test]
fn a_new_layout_can_show_a_window_of_the_model() {
let mut s = session_with_model();
s.execute("layout.new", &json!({"name": "Sheet W", "window": [[10, 10], [30, 20]]})).unwrap();
let v = only_viewport(&s, "Sheet W");
assert!(v.view_center.dist(Vec2::new(20.0, 15.0)) < 1e-9, "centred on the window: {:?}", v.view_center);
let aspect = v.width / v.height;
assert!(v.view_height >= 10.0 && v.view_height * aspect >= 20.0, "the whole window is in view");
assert!(v.view_height <= (10.0_f64).max(20.0 / aspect) * 1.02 + 1e-9, "and not much more: {}", v.view_height);
// Without a window the viewport shows the model extents, as before.
s.execute("layout.new", &json!({"name": "Sheet E"})).unwrap();
let e = only_viewport(&s, "Sheet E");
assert!(e.view_height > v.view_height * 2.0, "extents are larger than the window");
}
/// A window without area, or not two corners, is an error that leaves no layout behind.
#[test]
fn a_bad_layout_window_adds_no_layout() {
let mut s = session_with_model();
let before = s.doc().unwrap().layouts.len();
for w in [
json!([[1, 1], [1, 9]]),
json!([[1, 1], [9, 1]]),
json!([[1, 1]]),
json!("all"),
json!([[1, 1], ["a", 2]]),
json!([[f64::MAX, 0], [-f64::MAX, 1]]),
] {
assert!(s.execute("layout.new", &json!({"name": "Bad", "window": w})).is_err(), "{w}");
}
assert_eq!(s.doc().unwrap().layouts.len(), before, "no layout is left behind");
}
/// The interactive command shows the Model tab, takes two corners and shows the new layout.
#[test]
fn new_layout_picks_the_model_area_in_the_model_tab() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet P").unwrap();
assert_eq!(s.space(), Space::Model, "the Model tab is shown to pick the area");
s.cmdline("10,10").unwrap();
assert!(s.current_prompt().is_some_and(|p| p.message == "Specify opposite corner"));
// A window without width re-asks for the first corner and adds nothing.
s.cmdline("10,30").unwrap();
assert!(s.current_prompt().is_some_and(|p| p.message.contains("first corner")), "{:?}", s.current_prompt().map(|p| p.message));
assert!(s.doc().unwrap().layout("Sheet P").is_none());
s.cmdline("10,10").unwrap();
s.cmdline("30,20").unwrap();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Sheet P".into()), "the new layout is shown");
let v = only_viewport(&s, "Sheet P");
assert!(v.view_center.dist(Vec2::new(20.0, 15.0)) < 1e-9, "{:?}", v.view_center);
s.undo().unwrap();
assert!(s.doc().unwrap().layout("Sheet P").is_none(), "one undo step");
}
/// A tab shown while the corners are picked ends the command instead of reading points in that space.
#[test]
fn new_layout_ends_if_another_tab_is_shown_while_picking() {
let mut s = session_with_model();
let before = s.doc().unwrap().layouts.len();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet T").unwrap();
assert_eq!(s.space(), Space::Model);
// A tab shown meanwhile: the next point must not be taken for a model corner.
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.cmdline("10,10").unwrap();
assert!(s.running.is_none(), "the command ended");
assert_eq!(s.layout_space(), Space::Paper("Layout1".into()), "the tab that was shown stays");
assert_eq!(s.doc().unwrap().layouts.len(), before, "no layout was added");
}
/// The opposite-corner prompt is a window corner, so ortho does not bend it.
#[test]
fn the_opposite_corner_is_not_bent_by_ortho() {
let mut s = session_with_model();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet O").unwrap();
s.cmdline("10,10").unwrap();
let p = s.current_prompt().unwrap();
assert!(p.corner && p.base == Some(Vec2::new(10.0, 10.0)), "a window's opposite corner prompt");
}
/// Esc puts back the tab the command started in and adds no layout.
#[test]
fn cancelling_new_layout_puts_the_tab_back() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout2"})).unwrap();
let before = s.doc().unwrap().layouts.len();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet C").unwrap();
assert_eq!(s.space(), Space::Model);
s.cancel();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Layout2".into()), "back in the tab it started in: {:?}", s.log);
assert_eq!(s.doc().unwrap().layouts.len(), before);
// Esc at the name prompt changes nothing either.
s.start("layout.newarea").unwrap();
s.cancel();
assert_eq!(s.space(), Space::Paper("Layout2".into()));
}
/// Esc after the user chose another tab leaves that tab shown, not the one the command started in.
#[test]
fn cancelling_new_layout_keeps_a_tab_chosen_meanwhile() {
let mut s = session_with_model();
s.execute("layout.set", &json!({"name": "Layout2"})).unwrap();
s.start("layout.newarea").unwrap();
s.cmdline("Sheet K").unwrap();
s.execute("layout.set", &json!({"name": "Layout1"})).unwrap();
s.cancel();
assert!(s.running.is_none());
assert_eq!(s.space(), Space::Paper("Layout1".into()), "the tab chosen meanwhile stays: {:?}", s.log);
}
#[test]
fn mview_arrangements_and_interactive() {
let mut s = session_with_model();
@@ -84,6 +84,7 @@ pub(crate) fn at_elevation(s: &Session, p: Vec2) -> Vec3 {
fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut Entity)) -> Result<Vec<Handle>> {
let d = s.doc_mut()?;
let mut out = Vec::new();
let mut copies = Vec::new();
for h in hs {
let Some(sp) = d.space_of(*h) else { continue };
if copy {
@@ -94,6 +95,7 @@ fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut
if let Some(st) = d.space_mut(&sp) {
st.push(ne);
out.push(nh);
copies.push((*h, nh));
}
} else {
let locked = d.entity(*h).and_then(|e| d.layer(&e.common.layer)).is_some_and(|l| l.locked);
@@ -104,6 +106,9 @@ fn edit_entities(s: &mut Session, hs: &[Handle], copy: bool, edit: impl Fn(&mut
out.push(*h);
}
}
if copy && !copies.is_empty() {
crate::cmd::groups::replicate_groups_for_copies(d, &copies);
}
Ok(out)
}
+37 -7
View File
@@ -215,11 +215,25 @@ fn device_paper<'a>(dev: &'a PlotterConfig, name: &str) -> Option<&'a DevicePape
dev.paper(name).or_else(|| dev.paper(cadcraft_render::paper_size(name)?.name))
}
/// A paper's stored portrait margins on the landscape sheet: the sheet's axes swap, so left and
/// right become bottom and top (#1266).
pub(crate) fn landscape_margins([l, b, r, t]: [f64; 4]) -> [f64; 4] {
[t, l, b, r]
}
/// The inverse: a landscape page's margins on the stored portrait sheet, for a page that keeps
/// its paper when its orientation turns (#1266).
pub(crate) fn portrait_margins([l, b, r, t]: [f64; 4]) -> [f64; 4] {
[b, r, t, l]
}
fn set_paper(page: &mut PageSetup, p: &DevicePaper) {
page.paper = p.name.clone();
page.width_mm = p.width;
page.height_mm = p.height;
page.margins_mm = p.margins;
// The paper keeps its margins for its stored portrait sheet; the page measures them against
// the sheet in the orientation it names, so they turn with it (#1266).
page.margins_mm = if page.landscape { landscape_margins(p.margins) } else { p.margins };
}
fn unknown_device(cmd: &str, name: &str) -> EngineError {
@@ -354,9 +368,16 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
o.remove("paper");
o.insert("width".into(), json!(pp.width));
o.insert("height".into(), json!(pp.height));
o.insert("margins".into(), json!(pp.margins));
// The paper's margins belong to its stored portrait sheet; the plot draws on the sheet in
// the orientation it names, so they turn to it (#1266).
let landscape = p.get("landscape").and_then(Value::as_bool).unwrap_or_else(|| match &layout {
Some(pg) => pg.landscape,
None => dev.orientation == Orientation::Landscape,
});
let [l, b, r, t] = pp.margins;
o.insert("margins".into(), json!(if landscape { [t, l, b, r] } else { [l, b, r, t] }));
if p.get("landscape").is_none() && layout.is_none() {
o.insert("landscape".into(), json!(dev.orientation == Orientation::Landscape));
o.insert("landscape".into(), json!(landscape));
}
}
Ok(out)
@@ -527,13 +548,22 @@ fn edit_device(cmd: &str, c: &mut PlotterConfig, p: &Value) -> Result<()> {
_ => return Err(bad(cmd, "`paper.width` and `paper.height` (mm) are both required")),
};
let margins = match pv.get("margins") {
None => existing.as_ref().map(|e| e.margins).unwrap_or([0.0; 4]),
None => match existing.as_ref() {
// Stored margins belong to the stored portrait sheet; naming the same sheet
// landscape turns them back, so re-saving a paper does not refuse its own
// margins.
// Naming the sheet landscape turns the stored portrait margins to it, whatever
// its new sides: sanitization turns them back for the stored (portrait) sheet.
Some(e) if w > h => {
let [l, b, r, t] = e.margins;
[t, l, b, r]
}
_ => existing.as_ref().map(|e| e.margins).unwrap_or([0.0; 4]),
},
Some(m) => {
let a: Vec<f64> = m.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
match a[..] {
[l, b, r, t] if a.iter().all(|v| v.is_finite() && (0.0..=1000.0).contains(v)) && l + r < w.min(h) && b + t < w.max(h) => {
[l, b, r, t]
}
[l, b, r, t] if a.iter().all(|v| v.is_finite() && (0.0..=1000.0).contains(v)) && l + r < w && b + t < h => [l, b, r, t],
_ => return Err(bad(cmd, "`paper.margins` must be [left, bottom, right, top] in mm, leaving a printable area")),
}
}
+3
View File
@@ -556,6 +556,7 @@ fn run_style_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
let st = d.text_styles.by_name_mut(&from).ok_or_else(|| bad("style.rename", "no such style"))?;
st.name = to.clone();
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["STYLE"], &from, &to);
// References follow the new name.
let fix = |n: &mut String| {
if n.eq_ignore_ascii_case(&from) {
@@ -794,6 +795,7 @@ fn run_dimstyle_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
let st = d.dim_styles.by_name_mut(&from).ok_or_else(|| bad("dimstyle.rename", "no such dimension style"))?;
st.name = to.clone();
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["DIMSTYLE"], &from, &to);
if d.header.str("DIMSTYLE", "Standard").eq_ignore_ascii_case(&from) {
d.header.set_str("DIMSTYLE", &to);
}
@@ -1017,6 +1019,7 @@ fn run_rename(s: &mut Session, p: &Value) -> Result<Value> {
}
let st = d.linetypes.by_name_mut(&from).ok_or_else(|| bad("rename", "no such linetype"))?;
st.name = to.clone();
cadcraft_doc::foreign::Foreign::rename_shared(&mut d.foreign, &["LTYPE"], &from, &to);
// References follow the new name.
let fix = |n: &mut String| {
if n.eq_ignore_ascii_case(&from) {
+9
View File
@@ -2,6 +2,7 @@
use std::sync::Arc;
use cadcraft_doc::foreign::Foreign;
use cadcraft_doc::{Drawing, EntityKind, EntityStore, Handle};
use serde_json::json;
@@ -54,6 +55,7 @@ pub(super) fn block(s: &mut Session, from: &str, to: &str) -> Result<()> {
let mut b = d.blocks.remove(&key).ok_or_else(|| bad("rename", "no such block"))?;
Arc::make_mut(&mut b).name = to.clone();
d.blocks.insert(to.clone(), b);
Foreign::rename_shared(&mut d.foreign, &["BLOCK_RECORD", "BLOCK", "ENDBLK"], &key, &to);
let uses = |k: &EntityKind| match k {
EntityKind::Insert(i) => i.block.eq_ignore_ascii_case(&key),
EntityKind::MLeader(m) => m.block.as_ref().is_some_and(|b| b.block.eq_ignore_ascii_case(&key)),
@@ -102,6 +104,13 @@ pub(super) fn simple(s: &mut Session, table: &str, from: &str, to: &str) -> Resu
}
let n = names.iter_mut().find(|n| n.eq_ignore_ascii_case(from)).ok_or_else(|| bad("rename", format!("no {table} `{from}`")))?;
let old = std::mem::replace(&mut **n, to.clone());
let kind = match table {
"mleaderstyle" => "NOD/ACAD_MLEADERSTYLE",
"tablestyle" => "NOD/ACAD_TABLESTYLE",
"view" => "VIEW",
_ => "UCS",
};
Foreign::rename_shared(&mut d.foreign, &[kind], &old, &to);
let current = match table {
"mleaderstyle" => "CMLEADERSTYLE",
"tablestyle" => "CTABLESTYLE",
+87 -12
View File
@@ -8,11 +8,13 @@ use super::cells::cell_of;
use super::{MAX_COLS, MAX_ROWS, anchors, edit, set_anchors, usize_param};
use crate::cmd::machines::SelectRun;
use crate::cmd::{CommandSpec, bad, bool_or, str_param};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
use crate::{Accept, DocState, Input, Interactive, Prompt, Result, Session, Step};
/// Largest linked file read (bytes).
#[cfg(not(target_arch = "wasm32"))]
const MAX_LINK_BYTES: usize = 8 << 20;
/// Most files remembered per drawing as linked by the user ([`DocState::chosen_links`]).
const MAX_CHOSEN_LINKS: usize = 1000;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -26,7 +28,10 @@ pub fn specs() -> Vec<CommandSpec> {
.menu(&["Insert", "Data Link..."])
.params("{handle, path (.csv, .txt/.tsv tab-separated), startRow? (default: below the title), remove?: bool} → {rows, cols}"),
CommandSpec::new("datalinkupdate", "Update Data Links", run_update)
.params("{handles?} (default: every linked table) → {updated}")
.params(
"{handles?} (default: every linked table) → {updated, errors}; a link saved in the drawing is read only from the drawing's \
folder or below it, unless DATALINK linked that file since the drawing was opened",
)
.interactive(|_| Ok(Box::new(SelectRun::new("datalinkupdate", "DATALINKUPDATE")))),
]
}
@@ -224,13 +229,45 @@ fn separator(path: &str, text: &str) -> char {
if first.contains(';') && !first.contains(',') { ';' } else { ',' }
}
/// The file to read for a data link: a path the user just `chosen` as given, a path stored in the
/// drawing at `host` only through [`crate::doc_path::resolve`].
fn link_file(id: &str, path: &str, host: Option<&str>, chosen: bool) -> Result<std::path::PathBuf> {
/// The file to read for a data link of the drawing `st`: a path the user just `chosen` as given;
/// a path stored in the drawing through [`crate::doc_path::resolve`], and then only as the file
/// system finds it (`..` and links followed) in the drawing's `folder`
/// ([`crate::doc_path::drawing_folder`]) or below it, or when the user linked that same file since
/// the drawing was opened ([`DocState::chosen_links`]).
fn link_file(id: &str, path: &str, st: &DocState, folder: Option<&std::path::Path>, chosen: bool) -> Result<std::path::PathBuf> {
if chosen {
return Ok(std::path::PathBuf::from(path));
}
crate::doc_path::resolve(path, host.map(std::path::Path::new)).map_err(|r| bad(id, format!("{path}: not opened, {r}")))
let host = st.path.as_deref().map(std::path::Path::new);
let file = crate::doc_path::resolve(path, host).map_err(|r| bad(id, format!("{path}: not opened, {r}")))?;
if cfg!(target_arch = "wasm32") {
// Nothing is read there; [`read_link`] says so.
return Ok(file);
}
// The automation roots first: outside them nothing about the file is asked.
crate::file_access::check_read(&file).map_err(|e| bad(id, e))?;
let real = std::fs::canonicalize(&file).map_err(|e| bad(id, format!("{path}: {e}")))?;
// Whole components: `plans-old` is not in `plans`.
if folder.is_some_and(|f| real.starts_with(f)) || st.chosen_links.contains_key(&real) {
// Read where it was checked, not through the links again.
return Ok(real);
}
Err(bad(id, format!("{path}: not read, the file is outside the drawing's folder; link it with DATALINK to read it")))
}
/// Remember `real` (resolved), the file of a link the user just gave, as theirs to read for the
/// drawing `st`, as its latest choice. At [`MAX_CHOSEN_LINKS`] files a new one makes room by
/// dropping the file chosen longest ago.
fn remember_link(st: &mut DocState, real: std::path::PathBuf) {
let links = &mut st.chosen_links;
let latest = links.values().max().map_or(0, |n| n.saturating_add(1));
if links.len() >= MAX_CHOSEN_LINKS
&& !links.contains_key(&real)
&& let Some(oldest) = links.iter().min_by_key(|(_, n)| **n).map(|(p, _)| p.clone())
{
links.remove(&oldest);
}
links.insert(real, latest);
}
/// Read a linked file through the host (natively the file system; not on the web).
@@ -288,16 +325,20 @@ fn fill(t: &mut Table, start: usize, data: &[Vec<String>]) {
}
}
/// Re-read the linked file of table `h`; `chosen` says its path was just given by the user.
fn update(s: &mut Session, h: Handle, chosen: bool) -> Result<(usize, usize)> {
/// Re-read the linked file of table `h`; `chosen` says its path was just given by the user, else
/// it is read from the drawing's `folder` ([`crate::doc_path::drawing_folder`]) or a file the user
/// linked.
fn update(s: &mut Session, h: Handle, folder: Option<&std::path::Path>, chosen: bool) -> Result<(usize, usize)> {
let id = "datalinkupdate";
let link = match s.doc()?.entity(h).map(|e| &e.kind) {
Some(EntityKind::Table(t)) => t.data_link.clone().ok_or_else(|| bad(id, "the table has no data link"))?,
_ => return Err(bad(id, "object is not a table")),
};
let host = s.state()?.path.clone();
let file = link_file(id, &link.path, host.as_deref(), chosen)?;
let file = link_file(id, &link.path, s.state()?, folder, chosen)?;
let text = read_link(id, &file)?;
if chosen && let Ok(real) = std::fs::canonicalize(&file) {
remember_link(s.state_mut()?, real);
}
let data = parse_csv(&text, separator(&link.path, &text));
let mut size = (0, 0);
edit(s, &json!({ "handle": h.hex() }), id, |t| {
@@ -325,7 +366,7 @@ fn run_datalink(s: &mut Session, p: &Value) -> Result<Value> {
Ok(())
})?;
let h = r.get("handle").and_then(Value::as_str).and_then(Handle::parse_hex).ok_or_else(|| bad(id, "no table"))?;
let (rows, cols) = update(s, h, true)?;
let (rows, cols) = update(s, h, None, true)?;
Ok(json!({ "handle": h.hex(), "rows": rows, "cols": cols }))
}
@@ -351,8 +392,10 @@ fn run_update(s: &mut Session, p: &Value) -> Result<Value> {
};
let mut updated = 0;
let mut errors = Vec::new();
// Resolved once for every table, and only when there is one.
let folder = if hs.is_empty() { None } else { crate::doc_path::drawing_folder(s.state()?.path.as_deref().map(std::path::Path::new)) };
for h in hs {
match update(s, h, false) {
match update(s, h, folder.as_deref(), false) {
Ok(_) => updated += 1,
Err(e) => errors.push(e.to_string()),
}
@@ -379,6 +422,38 @@ mod tests {
}
}
/// Whether the drawing `st` remembers `file` as linked by the user.
fn remembered(st: &DocState, file: &std::path::Path) -> bool {
st.chosen_links.contains_key(file)
}
/// However many files the user links, the drawing remembers at most [`MAX_CHOSEN_LINKS`] of
/// them: the ones linked last, a file linked again counting as just linked.
#[test]
fn remembered_links_are_the_most_recent_ones() {
let mut st = DocState::new(cadcraft_doc::Drawing::new_metric(), "t", None);
let file = |i: usize| std::path::PathBuf::from(format!("/data/{i}.csv"));
for i in 0..MAX_CHOSEN_LINKS {
remember_link(&mut st, file(i));
}
// Linked again at the bound, the second file drops nothing and becomes the newest, so two
// new files make room by dropping the first and the third.
remember_link(&mut st, file(1));
assert_eq!(st.chosen_links.len(), MAX_CHOSEN_LINKS);
assert!(remembered(&st, &file(0)));
remember_link(&mut st, file(MAX_CHOSEN_LINKS));
remember_link(&mut st, file(MAX_CHOSEN_LINKS + 1));
assert!([1, MAX_CHOSEN_LINKS, MAX_CHOSEN_LINKS + 1].iter().all(|&i| remembered(&st, &file(i))));
assert!(!remembered(&st, &file(0)) && !remembered(&st, &file(2)));
// After many more, the ones linked last are the ones remembered.
let end = 2 * MAX_CHOSEN_LINKS + 10;
for i in MAX_CHOSEN_LINKS + 2..end {
remember_link(&mut st, file(i));
}
assert_eq!(st.chosen_links.len(), MAX_CHOSEN_LINKS, "the bound is reached, not a smaller one");
assert!((end - MAX_CHOSEN_LINKS..end).all(|i| remembered(&st, &file(i))));
}
#[test]
fn csv_parsing() {
assert_eq!(parse_csv("a,b\r\n\"c,d\",\"e\"\"f\"\n", ','), vec![vec!["a", "b"], vec!["c,d", "e\"f"]]);
+1 -1
View File
@@ -258,7 +258,7 @@ fn run_cellstyle_use(s: &mut Session, p: &Value) -> Result<Value> {
Some(v) => v.as_str().map(|x| x.trim().to_string()).ok_or_else(|| bad(id, "`style` must be a cell style name"))?,
None => return Err(bad(id, "`style` (cell style name) is required")),
};
let styles: Vec<TableStyle> = s.doc()?.table_styles.clone();
let styles: Vec<TableStyle> = s.doc()?.table_styles.to_vec();
edit(s, p, id, |t| {
let st = styles.iter().find(|x| x.name.eq_ignore_ascii_case(&t.style)).cloned().unwrap_or_default();
if !name.is_empty() && !st.has_cell_style(&name) {
+15
View File
@@ -5,6 +5,12 @@
//! itself is on, are opened (see `craft_docpath`). A refused path is handled like a missing file,
//! with the reason in its status. Paths the user gives a command (XATTACH, -XREF Path, DATALINK)
//! are their own choice and are used as given.
//!
//! A data link copies its file's text into the drawing, where the next save keeps it. So a data
//! link the drawing itself names is read only from the drawing's folder or a folder below it, once
//! `..` and links are followed ([`drawing_folder`]), unless the user linked that file with
//! DATALINK since the drawing was opened. Otherwise a drawing could copy any file it names into
//! itself for whoever made it.
use std::path::{Path, PathBuf};
@@ -21,6 +27,15 @@ pub fn resolve(stored: &str, document: Option<&Path>) -> Result<PathBuf, Refused
craft_docpath::resolve_absolute(stored.trim(), document.as_deref())
}
/// The folder of the drawing saved at `document` as the file system resolves it
/// ([`std::fs::canonicalize`]: absolute, with `..` and links followed), to compare files resolved
/// the same way with. `None` for a drawing without a file, and when its folder can't be resolved.
pub fn drawing_folder(document: Option<&Path>) -> Option<PathBuf> {
let document = document.filter(|d| !d.as_os_str().is_empty())?;
let folder = std::path::absolute(document).ok()?.parent()?.to_path_buf();
std::fs::canonicalize(folder).ok()
}
#[cfg(test)]
mod tests {
use super::*;
+6
View File
@@ -48,6 +48,11 @@ pub struct DocState {
/// The fonts missing on Windows that a save last named: the next save names them again only
/// when they change.
pub(crate) fonts_noted: String,
/// The files the user linked with DATALINK since the drawing was opened, as the file system
/// resolves them, each with when it was last chosen (a larger number is later):
/// DATALINKUPDATE reads these also outside the drawing's folder ([`crate::doc_path`]). Kept
/// with the open drawing only, never saved.
pub(crate) chosen_links: std::collections::HashMap<std::path::PathBuf, u64>,
}
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
@@ -77,6 +82,7 @@ impl DocState {
ucs_tilted_noted: false,
erased: Default::default(),
fonts_noted: String::new(),
chosen_links: Default::default(),
}
}
/// The drawing has changes not saved to its file, or the Block Editor has changes not yet
@@ -359,6 +359,7 @@ pub const NO_FILES: &[&str] = &[
"laymrg",
"laydel",
"layout.new",
"layout.newarea",
"layout.delete",
"layout.rename",
"layout.copy",
+5
View File
@@ -379,6 +379,11 @@ impl Session {
v.height / self.viewport_px.1.max(1.0)
}
/// The running interactive command id, or `None` if the command line is idle.
pub fn active_command_id(&self) -> Option<&str> {
self.running.as_ref().map(|r| r.id.as_str())
}
/// Serializable summary for inspect/automation.
pub fn summary(&self) -> Value {
let docs: Vec<Value> = self
+38 -5
View File
@@ -143,7 +143,8 @@ pub struct LispState {
/// the step is charged it without charging the enclosing callback a second time.
pub(crate) callback_work: u64,
/// The `callback_used` value the callback running now (and so every one it calls) must not
/// pass: the lowest of its own and its callers' allowances.
/// pass: the lowest of its own and its callers' allowances, and of what is left to an
/// expression typed at a prompt.
pub(crate) callback_ceiling: Option<u64>,
}
@@ -200,6 +201,9 @@ struct Run {
inputs: std::collections::VecDeque<Value>,
/// Run to the end without waiting (programmatic calls): `get…` without an input gets nil.
blocking: bool,
/// An expression typed at a command's prompt ([`Session::lisp_eval_answer`]): blocking, with
/// [`ANSWER_CAP`] steps instead of [`BLOCKING_CAP`].
answer: bool,
/// Steps taken, for the cap on blocking runs.
steps: u64,
/// The `*error*` handler is the one running.
@@ -215,6 +219,10 @@ struct Run {
const SLICE: u64 = 400_000;
/// Steps a blocking run (a programmatic call) may take before it is stopped.
const BLOCKING_CAP: u64 = 500_000_000;
/// Steps an expression typed at a command's prompt may take, the callbacks it runs included. It
/// runs blocking, since its value is the prompt's answer, so the interface draws no frame and
/// Esc doesn't reach it until it ends; a routine at `Command:` runs a slice per frame instead.
const ANSWER_CAP: u64 = 20_000_000;
impl Session {
/// The LISP environment of the active drawing.
@@ -272,12 +280,19 @@ impl Session {
inputs: Vec<Value>,
) -> crate::Result<Option<std::result::Result<Value, String>>> {
let forms = read::read_all(src).map_err(|e| crate::EngineError::Other(format!("; error: {}", e.msg)))?;
self.lisp_start(Machine::forms(forms), print, blocking, inputs, "LISP".into())
self.lisp_start(Machine::forms(forms), print, blocking, inputs, "LISP".into(), false)
}
/// Evaluate an expression typed at a command's prompt, whose value is the answer: it runs to
/// the end as a programmatic call does, within [`ANSWER_CAP`] steps.
pub(crate) fn lisp_eval_answer(&mut self, src: &str) -> crate::Result<Option<std::result::Result<Value, String>>> {
let forms = read::read_all(src).map_err(|e| crate::EngineError::Other(format!("; error: {}", e.msg)))?;
self.lisp_start(Machine::forms(forms), false, true, Vec::new(), "LISP".into(), true)
}
/// Call a LISP function (`c:` commands typed at the command line).
fn lisp_call(&mut self, f: Value, label: String) -> crate::Result<Option<std::result::Result<Value, String>>> {
self.lisp_start(Machine::calling(f, Vec::new()), false, false, Vec::new(), label)
self.lisp_start(Machine::calling(f, Vec::new()), false, false, Vec::new(), label, false)
}
fn lisp_start(
@@ -287,6 +302,7 @@ impl Session {
blocking: bool,
inputs: Vec<Value>,
label: String,
answer: bool,
) -> crate::Result<Option<std::result::Result<Value, String>>> {
if self.lisp.active {
return Err(crate::EngineError::Other("a LISP routine is already running".into()));
@@ -305,6 +321,7 @@ impl Session {
before,
inputs: inputs.into(),
blocking,
answer,
steps: 0,
handler: false,
string_bytes: 0,
@@ -368,6 +385,10 @@ impl Session {
// [`Session::typed`] first, never opens a dialog. Restored after the slice, a panic
// in it included, so a person's later command keeps its own origin.
let program_input = std::mem::replace(&mut self.program_input, true);
// Set for every slice (callbacks run only inside one). An answer's callbacks
// (`vl-sort`'s comparator…) run inside one of its steps: they share what is left of
// its allowance instead of each taking a callback's own.
self.lisp.callback_ceiling = run.answer.then(|| self.lisp.callback_used.saturating_add(ANSWER_CAP.saturating_sub(run.steps)));
let outcome = {
let machine = &mut run.machine;
let mut ctx = Ctx { s: self, env: &mut env, depth: 0 };
@@ -395,9 +416,21 @@ impl Session {
// The work the slice did, which one step can take far past the slice. After a panic
// `used` is still the previous slice's; the run ends with the error anyway.
run.steps = run.steps.saturating_add(run.machine.used);
if run.blocking && run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_)) {
// An answer that failed past its cap was stopped by the cap too: a callback that ran
// out of what was left ends here past the cap, since the step that called it counts.
let past_cap = if run.answer {
run.steps > ANSWER_CAP && matches!(outcome, Outcome::Wait(_) | Outcome::Error(_))
} else {
run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_))
};
if run.blocking && past_cap {
let msg = if run.answer {
format!("expression at a prompt stopped after {ANSWER_CAP} steps; run long routines at Command:, where Esc stops them")
} else {
format!("routine stopped after {BLOCKING_CAP} steps")
};
self.lisp.run = Some(run);
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
self.lisp_error(LispError::quit(msg));
return;
}
match outcome {
+3 -1
View File
@@ -205,6 +205,8 @@ pub(super) fn float(a: &[Value]) -> R {
Ok(Value::Real(num(&a[0])?))
}
/// The greatest common divisor. The one past 32 bits, 2147483648 (of -2147483648 and 0 or
/// itself), is a real, as the reader and `fix` give such a number, not the largest integer.
pub(super) fn gcd(a: &[Value]) -> R {
arity(a, 2, 2)?;
let (mut x, mut y) = (i64::from(int(&a[0])?).abs(), i64::from(int(&a[1])?).abs());
@@ -216,7 +218,7 @@ pub(super) fn gcd(a: &[Value]) -> R {
x = y;
y = t;
}
Ok(Value::Int(i32::try_from(x).unwrap_or(i32::MAX)))
Ok(i32::try_from(x).map_or(Value::Real(x as f64), Value::Int))
}
pub(super) fn logand(a: &[Value]) -> R {
+9 -2
View File
@@ -51,13 +51,20 @@ pub(super) fn itoa(a: &[Value]) -> R {
Ok(Value::str(&int(&a[0])?.to_string()))
}
/// C's `atoi`: leading blanks, a sign, digits; 0 when there are none.
/// C's `atoi`: leading blanks, a sign, digits; 0 when there are none. Digits past the 32-bit
/// range give a real, the number `atof` reads from them, as the reader gives one for such a
/// literal: neither wrapped nor clamped to an integer.
pub(super) fn atoi(a: &[Value]) -> R {
arity(a, 1, 1)?;
let s = string(&a[0])?;
let t = s.trim_start();
let end = t.char_indices().take_while(|(i, c)| c.is_ascii_digit() || (*i == 0 && (*c == '-' || *c == '+'))).count();
Ok(Value::Int(t.get(..end).and_then(|n| n.parse::<i64>().ok()).map(|n| n as i32).unwrap_or(0)))
let digits = t.get(..end).unwrap_or_default();
match digits.parse::<i32>() {
Ok(n) => Ok(Value::Int(n)),
Err(_) if digits.bytes().any(|b| b.is_ascii_digit()) => atof(&[Value::str(digits)]),
Err(_) => Ok(Value::Int(0)),
}
}
/// C's `atof`: the number token at the start; 0.0 when there is none.
+47
View File
@@ -1602,6 +1602,53 @@ fn a_lisp_value_at_a_prompt_is_not_evaluated_again() {
assert_eq!(r, Some(4.0));
}
/// #1926: an expression typed at a command's prompt runs to the end before the prompt takes its
/// value, so the interface waits for it: it gets a far smaller allowance than a programmatic run,
/// and the callbacks it runs share that allowance instead of each taking a callback's own.
#[test]
fn an_expression_at_a_prompt_has_a_short_allowance() {
let mut s = session();
let circles = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_doc::EntityKind::Circle(_))).count();
let last_error = |s: &Session, from: usize| s.log.get(from..).and_then(|l| l.iter().rev().find(|l| l.starts_with("; error:")).cloned());
let endless = "(while (< i 2000000000) (setq i (1+ i)))";
s.cmdline(&format!("circle 0,0 (progn (setq i 0) {endless} 5)")).unwrap();
let typed: i64 = ok(&mut s, "i").parse().unwrap();
let stopped = last_error(&s, 0);
assert!(typed > 0 && stopped.is_some(), "the loop ran and was stopped");
assert_eq!(circles(&s), 0, "the stopped expression gave no radius");
assert!(s.running.is_none(), "CIRCLE ends with the failed expression");
// The same loop run programmatically goes on to twice as far.
let further = format!("(setq i 0) (while (< i {}) (setq i (1+ i))) i", typed * 2);
assert_eq!(ok(&mut s, &further), (typed * 2).to_string());
// Half the loop, then a comparator's endless loop: the comparator gets what the expression
// has left, not a callback's own allowance, and the expression stops as the loop alone did.
let half = format!("(while (< i {}) (setq i (1+ i)))", typed / 2);
let from = s.log.len();
s.cmdline(&format!("circle 0,0 (progn (setq i 0) {half} (vl-sort '(1 2) '(lambda (a b) {endless} (< a b))) 5)")).unwrap();
let with_callback: i64 = ok(&mut s, "i").parse().unwrap();
assert!(with_callback > typed / 2 && with_callback < typed * 5 / 4, "{with_callback} against {typed}");
assert_eq!(last_error(&s, from), stopped);
assert_eq!(circles(&s), 0);
}
/// #1933: a whole number past 32 bits is a real, as the reader and `fix` make one, not a wrapped
/// or clamped integer: `atoi` gives the number its digits read as, `gcd` the true divisor.
#[test]
fn atoi_and_gcd_past_32_bits_give_reals() {
let mut s = session();
for digits in ["2147483648", "-2147483649", "99999999999", "99999999999999999999"] {
assert_eq!(ok(&mut s, &format!("(= (atoi \"{digits}\") (read \"{digits}\"))")), "T", "{digits}");
}
// Past every real too: the largest, as `atof` reads it.
let huge = "9".repeat(400);
assert_eq!(ok(&mut s, &format!("(= (atoi \"{huge}\") (atof \"{huge}\"))")), "T");
// Within the range, integers as before.
assert_eq!(ok(&mut s, "(list (atoi \" -2147483648x\") (atoi \"+2147483647\") (atoi \"-\"))"), "(-2147483648 2147483647 0)");
let past = "(abs (float -2147483648))";
assert_eq!(ok(&mut s, &format!("(= (gcd -2147483648 0) (gcd 0 -2147483648) (gcd -2147483648 -2147483648) {past})")), "T");
assert_eq!(ok(&mut s, "(list (gcd -2147483648 6) (gcd 2147483647 0))"), "(2 2147483647)");
}
#[test]
fn atof_out_of_range_exponent_reads_whole_token() {
let mut s = Session::new();
+58 -11
View File
@@ -423,6 +423,13 @@ pub fn pick_in(d: &Drawing, space: &Space, frozen: &[String], p: Vec2, aperture:
pick_with(d, space, &ix, frozen, p, aperture)
}
/// Candidates [`pick_with`] takes from the tree and sorts; with more, it reads the index topmost
/// first instead (see [`SpatialIndex::top_down`]).
const PICK_SORTED_MAX: usize = 1024;
/// Entities [`pick_with`] reads topmost first before it sorts the tree's candidates after all: a
/// few microseconds when none of them is a hit.
const PICK_TOP_SCAN: usize = 4096;
pub(crate) fn pick_with(
d: &Drawing,
space: &Space,
@@ -430,22 +437,62 @@ pub(crate) fn pick_with(
frozen: &[String],
p: Vec2,
aperture: f64,
) -> Option<Handle> {
pick_scanning(d, space, ix, frozen, p, aperture, PICK_SORTED_MAX, PICK_TOP_SCAN)
}
/// [`pick_with`] with its limits: up to `sorted_max` candidates are sorted, more are read topmost
/// first, up to `budget` of them, before the rest are sorted.
#[allow(clippy::too_many_arguments)]
pub(crate) fn pick_scanning(
d: &Drawing,
space: &Space,
ix: &Option<std::sync::Arc<SpatialIndex>>,
frozen: &[String],
p: Vec2,
aperture: f64,
sorted_max: usize,
budget: usize,
) -> Option<Handle> {
let probe = Bounds2::new(p, p).expand(aperture);
let query = probe.expand(aperture);
let hit = |e: &Entity, known: Option<Bounds2>| {
selectable(d, e, frozen)
&& (is_infinite(e) || bounds_of(d, e, known).expand(aperture).intersects(&probe))
&& entity_distance(d, e, p, aperture / 4.0) <= aperture
};
// Candidates come topmost first: the first within the aperture is the one.
for (e, known) in candidates(d, space, ix, &probe.expand(aperture), true, true)? {
if !selectable(d, e, frozen) {
continue;
}
let infinite = is_infinite(e);
if !infinite && !bounds_of(d, e, known).expand(aperture).intersects(&probe) {
continue;
}
if entity_distance(d, e, p, aperture / 4.0) <= aperture {
return Some(e.handle);
let topmost = |ix: &SpatialIndex, cands: Vec<u32>, below: u32| {
cands
.into_iter()
.rev()
.filter(|i| *i < below)
.filter_map(|i| ix.entity(i).map(|e| (e, ix.bounds(i))))
.find(|(e, b)| hit(e, Some(*b)))
.map(|(e, _)| e.handle)
};
if let Some(ix) = ix {
match ix.query_at_most(&query, true, sorted_max) {
Some(Some(cands)) => return topmost(ix, cands, u32::MAX),
// Many candidates: the drawing is shown small and the aperture covers much of it. The
// topmost hit is usually near the top of the draw order: look there first, and sort
// the tree's candidates only to test the ones below those already examined.
Some(None) => {
if let Some(mut top) = ix.top_down(&query, true, budget) {
if let Some((_, e, _)) = top.by_ref().find(|(_, e, b)| hit(e, Some(*b))) {
return Some(e.handle);
}
let floor = top.floor();
if floor == 0 {
return None;
}
return topmost(ix, ix.query(&query, true)?, floor);
}
}
None => {}
}
}
None
candidates(d, space, ix, &query, true, true)?.find(|(e, known)| hit(e, *known)).map(|(e, _)| e.handle)
}
/// Every entity within `aperture` of `p`, topmost first (so the first is what [`pick`] chooses):
+3 -2
View File
@@ -89,11 +89,12 @@ impl Session {
if tt.starts_with('\'') {
return self.start(tt);
}
// A LISP expression typed at a command's prompt: its value is the answer.
// A LISP expression typed at a command's prompt: its value is the answer, so it runs to
// the end first, with a short allowance (the interface waits for it).
// Not at a free-text prompt: there the text is the answer (CAL takes "(3+4)*2").
if lisp && lisp_expression(tt) && !prompt.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo() {
let src = tt.strip_prefix('!').unwrap_or(tt).to_string();
let v = match self.lisp_eval(&src, false, true, Vec::new()) {
let v = match self.lisp_eval_answer(&src) {
Ok(Some(Ok(v))) => v,
Ok(_) => return Ok(()),
Err(e) => {
+4
View File
@@ -83,6 +83,9 @@ pub struct Settings {
/// PICKSTYLE: bit 1 picks whole selectable groups ([`cmd::groups`]), bit 2 associative hatches
/// with their boundaries (stored, not used yet).
pub pickstyle: u8,
/// GROUPDISPLAYMODE: how groups are displayed when selected:
/// 0 individual object grips only, 1 single center grip and bounding box, 2 both (default).
pub groupdisplaymode: u8,
pub gripsize: f64,
pub cursorsize: f64,
/// MAXARRAY: the most objects one array command creates (items × selected objects).
@@ -185,6 +188,7 @@ impl Default for Settings {
copymode: false,
pickdrag: true,
pickstyle: 1,
groupdisplaymode: 2,
gripsize: 5.0,
cursorsize: 5.0,
maxarray: 100_000,
+210 -12
View File
@@ -18,7 +18,7 @@ use std::sync::{Arc, Mutex};
use cadcraft_doc::{Block, BlockBoundsCache, DimStyle, Drawing, Entity, EntityKind, EntityStore, Space, entity_bounds_cached};
use cadcraft_geom::Bounds2;
use rstar::primitives::{GeomWithData, Rectangle};
use rstar::{AABB, RTree};
use rstar::{AABB, Envelope, RTree, RTreeObject};
/// Spaces with fewer entities than this are scanned directly (building an index costs more).
pub const MIN_INDEXED: usize = 256;
@@ -39,6 +39,21 @@ struct ChunkIx {
bounds: Vec<Bounds2>,
/// Local indices of xlines and rays (unbounded; always candidates for pick and crossing).
infinite: Vec<u32>,
/// The union of the chunk's tree items (`None` when none is bounded): [`TopDown`] skips a
/// chunk whose union misses the query.
envelope: Option<AABB<[f64; 2]>>,
}
/// The tree envelope of an entity's bounds, as [`ChunkIx::items`] stores it (`None` when empty).
fn rect(b: &Bounds2) -> Option<AABB<[f64; 2]>> {
(!b.is_empty()).then(|| Rectangle::from_corners([b.min.x, b.min.y], [b.max.x, b.max.y]).envelope())
}
/// Whether the tree item for bounds `b` touches `env`, by the tree's own (closed) intersection
/// test, without building the item.
fn touches(b: &Bounds2, env: &AABB<[f64; 2]>) -> bool {
let (lo, hi) = (env.lower(), env.upper());
!b.is_empty() && b.min.x <= hi[0] && b.max.x >= lo[0] && b.min.y <= hi[1] && b.max.y >= lo[1]
}
impl ChunkIx {
@@ -56,9 +71,10 @@ impl ChunkIx {
let b = entity_bounds_cached(d, e, 0, &mut cache);
crate::select::pick_bounds(d, e, b)
})
.collect();
.collect::<Vec<_>>();
let envelope = bounds.iter().filter_map(rect).reduce(|a, b| a.merged(&b));
let serial = NEXT_SERIAL.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
ChunkIx { serial, key, ents: items.to_vec(), bounds, infinite }
ChunkIx { serial, key, ents: items.to_vec(), bounds, infinite, envelope }
}
fn items(&self) -> impl Iterator<Item = Item> + '_ {
self.bounds.iter().enumerate().filter(|(_, b)| !b.is_empty()).map(|(i, b)| {
@@ -211,23 +227,120 @@ impl SpatialIndex {
/// Draw indices (ascending) of entities whose bounds touch `b`, optionally with the infinite
/// lines. Returns `None` for a non-finite query box (callers fall back to a full scan).
pub fn query(&self, b: &Bounds2, with_infinite: bool) -> Option<Vec<u32>> {
self.query_at_most(b, with_infinite, usize::MAX).map(Option::unwrap_or_default)
}
/// [`Self::query`], giving up (`Some(None)`) as soon as more than `cap` tree items touch `b`,
/// so a caller can choose another way to read a large result.
pub fn query_at_most(&self, b: &Bounds2, with_infinite: bool, cap: usize) -> Option<Option<Vec<u32>>> {
if b.is_empty() {
return Some(if with_infinite { self.infinite.clone() } else { Vec::new() });
return Some(Some(if with_infinite { self.infinite.clone() } else { Vec::new() }));
}
if !(b.min.is_finite() && b.max.is_finite()) {
return None;
let env = query_envelope(b)?;
let mut out: Vec<u32> = Vec::new();
for it in self.tree.locate_in_envelope_intersecting(env) {
if out.len() >= cap {
return Some(None);
}
if let Some(off) = self.offsets.get(&it.data.0) {
out.push(off + it.data.1);
}
}
// Pad a little so rounding in the callers' own predicates never loses a candidate.
let pad = (b.width() + b.height()) * 1e-9 + (b.min.x.abs() + b.min.y.abs() + b.max.x.abs() + b.max.y.abs()) * 1e-12 + 1e-300;
let env = AABB::from_corners([b.min.x - pad, b.min.y - pad], [b.max.x + pad, b.max.y + pad]);
let mut out: Vec<u32> =
self.tree.locate_in_envelope_intersecting(env).filter_map(|it| self.offsets.get(&it.data.0).map(|off| off + it.data.1)).collect();
if with_infinite {
out.extend_from_slice(&self.infinite);
}
out.sort_unstable();
out.dedup();
Some(out)
Some(Some(out))
}
/// The entities [`Self::query`] finds for `b`, topmost (highest draw index) first, read from
/// the chunks from the last one down instead of collected from the tree and sorted, examining
/// at most `budget` entities. A pick wants only the topmost hit: when the drawing is shown
/// small, its aperture covers most of it and the tree returns nearly every entity on each
/// pointer move, while the topmost hit is usually among the first few examined here. `None`
/// for an empty or non-finite box (callers use `query`'s own handling of those).
pub fn top_down(&self, b: &Bounds2, with_infinite: bool, budget: usize) -> Option<TopDown<'_>> {
if b.is_empty() {
return None;
}
let env = query_envelope(b)?;
let len = u32::try_from(self.len).unwrap_or(u32::MAX);
Some(TopDown { ix: self, env, infinite: with_infinite, next_chunk: self.chunks.len(), cur: None, floor: len, budget })
}
}
/// The padded tree envelope [`SpatialIndex::query`] searches for `b`; `None` when `b` isn't finite.
fn query_envelope(b: &Bounds2) -> Option<AABB<[f64; 2]>> {
if !(b.min.is_finite() && b.max.is_finite()) {
return None;
}
// Pad a little so rounding in the callers' own predicates never loses a candidate.
let pad = (b.width() + b.height()) * 1e-9 + (b.min.x.abs() + b.min.y.abs() + b.max.x.abs() + b.max.y.abs()) * 1e-12 + 1e-300;
Some(AABB::from_corners([b.min.x - pad, b.min.y - pad], [b.max.x + pad, b.max.y + pad]))
}
/// Candidates of a query box, topmost first, with their draw index and bounds (see
/// [`SpatialIndex::top_down`]). It stops when every entity is examined or the budget runs out;
/// [`TopDown::floor`] then says where the rest of the candidates begin.
pub struct TopDown<'a> {
ix: &'a SpatialIndex,
env: AABB<[f64; 2]>,
infinite: bool,
/// Chunks not entered yet: `chunks[..next_chunk]`.
next_chunk: usize,
/// The chunk being read and how many of its entities are left to examine.
cur: Option<(usize, usize)>,
/// Every entity at or above this draw index has been examined.
floor: u32,
budget: usize,
}
impl TopDown<'_> {
/// The draw index below which nothing has been examined: candidates still to test are the
/// ones [`SpatialIndex::query`] returns below it. 0 once every entity has been examined.
pub fn floor(&self) -> u32 {
self.floor
}
}
impl<'a> Iterator for TopDown<'a> {
type Item = (u32, &'a Arc<Entity>, Bounds2);
fn next(&mut self) -> Option<Self::Item> {
let ix = self.ix;
loop {
if let Some((c, left)) = self.cur
&& left > 0
{
if self.budget == 0 {
return None;
}
self.budget -= 1;
let local = left - 1;
self.cur = Some((c, local));
let (off, chunk) = ix.chunks.get(c)?;
let i = off.saturating_add(u32::try_from(local).unwrap_or(u32::MAX));
self.floor = i;
let e = chunk.ents.get(local)?;
let b = chunk.bounds.get(local).copied().unwrap_or(Bounds2::EMPTY);
let touches = touches(&b, &self.env);
if touches || (self.infinite && matches!(e.kind, EntityKind::XLine(_) | EntityKind::Ray(_))) {
return Some((i, e, b));
}
continue;
}
let c = self.next_chunk.checked_sub(1)?;
self.next_chunk = c;
let (off, chunk) = ix.chunks.get(c)?;
let touches = chunk.envelope.is_some_and(|r| r.intersects(&self.env)) || (self.infinite && !chunk.infinite.is_empty());
if touches {
self.cur = Some((c, chunk.ents.len()));
} else {
self.cur = None;
self.floor = *off;
}
}
}
}
@@ -434,6 +547,91 @@ mod tests {
}
}
/// A drawing added in spatial order (rows of short lines), so most chunks cover a small area.
fn rows(n: usize) -> Drawing {
let mut d = Drawing::new_imperial();
for i in 0..n {
let (x, y) = ((i % 100) as f64, (i / 100) as f64);
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: v3(x, y), b: v3(x + 0.6, y + 0.3) })).unwrap();
}
d
}
/// Reading candidates topmost first from the chunks finds exactly what the tree finds, in
/// reverse draw order, and `floor` marks where an interrupted read stopped.
#[test]
fn top_down_matches_query_in_reverse() {
for d in [drawing(13, 3000), rows(5000)] {
let ix = SpatialIndex::build(&d, &d.model);
assert!(ix.chunks.len() > 2, "test needs several chunks ({})", ix.chunks.len());
let mut r = Rng(77);
for k in 0..60 {
let c = Vec2::new(r.r(-10.0, 110.0), r.r(-10.0, 110.0));
let half = [0.2, 3.0, 40.0, 500.0][k % 4];
let b = Bounds2::new(c, c).expand(half);
let all: Vec<u32> = ix.query(&b, true).unwrap().into_iter().rev().collect();
let got: Vec<u32> = ix.top_down(&b, true, usize::MAX).unwrap().map(|(i, _, _)| i).collect();
assert_eq!(got, all, "box {b:?}");
for budget in [0, 1, 37, 1500] {
let mut top = ix.top_down(&b, true, budget).unwrap();
let seen: Vec<u32> = top.by_ref().map(|(i, _, _)| i).collect();
let floor = top.floor();
let mut joined = seen;
joined.extend(all.iter().copied().filter(|i| *i < floor));
assert_eq!(joined, all, "box {b:?} budget {budget}");
}
}
}
}
/// Picks with any sorting limit and top-down budget, including apertures covering most of the drawing (a
/// drawing shown small), match the scan without an index.
#[test]
fn pick_parity_with_scan_at_every_budget() {
for d in [drawing(29, 3000), rows(5000)] {
let ix = forced(&d);
let mut r = Rng(31);
let mut hits = 0;
for k in 0..240 {
let p = Vec2::new(r.r(-5.0, 105.0), r.r(-5.0, 105.0));
let ap = [0.05, 0.3, 1.5, 30.0][k % 4];
let want = select::pick_with(&d, &Space::Model, &None, &[], p, ap);
for (sorted_max, budget) in [(0, 0), (0, 1), (0, 50), (0, usize::MAX), (3, 7), (1024, 4096), (usize::MAX, 0)] {
let got = select::pick_scanning(&d, &Space::Model, &ix, &[], p, ap, sorted_max, budget);
assert_eq!(got, want, "p {p:?} ap {ap} sorted_max {sorted_max} budget {budget}");
}
hits += usize::from(want.is_some());
}
assert!(hits > 40, "test should exercise hits ({hits})");
}
}
/// Past 1,024 candidates a pick through a viewport skips the layers frozen there, both where
/// it reads the index topmost first and where it sorts the candidates below those it read.
#[test]
fn a_frozen_layer_is_skipped_on_the_topmost_first_path() {
let mut d = Drawing::new_imperial();
d.ensure_layer("FROZEN");
let mut handles = Vec::new();
for i in 0..2000 {
let common = if i >= 1990 { Common { layer: "FROZEN".into(), ..Common::default() } } else { Common::default() };
let y = f64::from(i) * 1e-4;
handles.push(d.add(&Space::Model, common, EntityKind::Line(cadcraft_doc::Line { a: v3(0.0, y), b: v3(10.0, y) })).unwrap());
}
let (topmost, shown) = (handles[1999], handles[1989]);
let ix = forced(&d);
let (p, ap) = (Vec2::new(5.0, 0.1), 0.5);
let query = Bounds2::new(p, p).expand(2.0 * ap);
assert!(matches!(ix.as_ref().unwrap().query_at_most(&query, true, 1024), Some(None)), "test needs more than 1024 candidates");
let frozen = ["frozen".to_string()];
assert_eq!(select::pick_with(&d, &Space::Model, &ix, &[], p, ap), Some(topmost));
assert_eq!(select::pick_with(&d, &Space::Model, &ix, &frozen, p, ap), Some(shown), "topmost-first read");
assert_eq!(select::pick_with(&d, &Space::Model, &None, &frozen, p, ap), Some(shown), "no index");
for budget in [0, 1, 3, 9] {
assert_eq!(select::pick_scanning(&d, &Space::Model, &ix, &frozen, p, ap, 1024, budget), Some(shown), "below the floor, budget {budget}");
}
}
#[test]
fn window_and_fence_parity_with_scan() {
for seed in [5, 23] {
+3
View File
@@ -62,6 +62,7 @@ const SESSION_VARS: &[&str] = &[
"COPYMODE",
"PICKDRAG",
"PICKSTYLE",
"GROUPDISPLAYMODE",
"GRIPSIZE",
"CURSORSIZE",
"MAXARRAY",
@@ -144,6 +145,7 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"COPYMODE" => json!(i32::from(st.copymode)),
"PICKDRAG" => json!(i32::from(st.pickdrag) * 2),
"PICKSTYLE" => json!(st.pickstyle),
"GROUPDISPLAYMODE" => json!(st.groupdisplaymode),
"GRIPSIZE" => json!(st.gripsize),
"CURSORSIZE" => json!(st.cursorsize),
"MAXARRAY" => json!(st.maxarray),
@@ -399,6 +401,7 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
"COPYMODE" => st.copymode = small(v, 1).ok_or_else(bad)? == 1,
"PICKDRAG" => st.pickdrag = as_i(v).filter(|b| matches!(b, 0 | 2)).map(|b| b == 2).ok_or_else(bad)?,
"PICKSTYLE" => st.pickstyle = as_i(v).filter(|b| (0..=3).contains(b)).and_then(|b| u8::try_from(b).ok()).ok_or_else(bad)?,
"GROUPDISPLAYMODE" => st.groupdisplaymode = small(v, 2).ok_or_else(bad)?,
"GRIPSIZE" => st.gripsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 255.0),
"CURSORSIZE" => st.cursorsize = as_f64(v).ok_or_else(bad)?.clamp(1.0, 100.0),
"MAXARRAY" => st.maxarray = as_f64(v).ok_or_else(bad)?.clamp(100.0, 10_000_000.0) as u64,
+48
View File
@@ -224,6 +224,54 @@ fn audit_at_the_command_line_asks_before_fixing() {
assert_eq!(s.execute("audit", &json!({})).unwrap()["errors"], 0);
}
/// Many multileaders and tables naming styles the drawing lacks, among many styles, are audited in
/// linear time (#1924). As before, each is set to Standard, and one naming a style in other case is
/// left as it is. The names share their first 200 bytes, so comparing two costs about that.
#[test]
fn many_objects_naming_missing_styles_audit_quickly() {
use cadcraft_engine::doc::{MLeader, MLeaderStyle, Table, TableStyle};
const N: usize = 10_000;
let name = |kind: char, i: usize| format!("{kind}{}{i:06}", "x".repeat(199));
let missing = |kind: char| format!("{kind}{}z{:05}", "x".repeat(199), 0);
let mleader = |style: String| {
EntityKind::MLeader(MLeader {
leaders: vec![vec![Vec3::ZERO, Vec3::new(1.0, 1.0, 0.0)]],
landing: Vec3::new(2.0, 1.0, 0.0),
dogleg: 0.5,
text: None,
style,
arrow_size: 1.0,
spline: false,
block: None,
})
};
let table = |style: String| EntityKind::Table(Table { style, ..Table::default() });
let mut d = Drawing::new_imperial();
d.mleader_styles.extend((0..N).map(|i| MLeaderStyle { name: name('M', i), ..MLeaderStyle::default() }));
d.table_styles.extend((0..N).map(|i| TableStyle { name: name('T', i), ..TableStyle::default() }));
for _ in 0..N {
raw(&mut d, &Space::Model, Common::default(), mleader(missing('M')));
raw(&mut d, &Space::Model, Common::default(), table(missing('T')));
}
raw(&mut d, &Space::Model, Common::default(), mleader(name('M', N - 1).to_ascii_uppercase()));
raw(&mut d, &Space::Model, Common::default(), table(name('T', N - 1).to_ascii_uppercase()));
let started = std::time::Instant::now();
cadcraft_engine::audit::repair(&mut d);
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
let styles: Vec<&str> = d
.model
.iter()
.filter_map(|e| match &e.kind {
EntityKind::MLeader(m) => Some(m.style.as_str()),
EntityKind::Table(t) => Some(t.style.as_str()),
_ => None,
})
.collect();
assert_eq!(styles.len(), 2 * N + 2);
assert!(styles[..2 * N].iter().all(|s| *s == "Standard"), "a missing style is set to Standard");
assert_eq!(styles[2 * N..], [name('M', N - 1).to_ascii_uppercase(), name('T', N - 1).to_ascii_uppercase()]);
}
#[test]
fn missing_standard_entries_and_layer_zero_are_recreated() {
let mut s = Session::new();
+50
View File
@@ -145,3 +145,53 @@ fn texttofront_and_hatchtoback() {
s.cmdline("").unwrap();
assert!(s.log.iter().any(|l| l.contains("2 object(s) brought to front")), "{:?}", s.log);
}
#[test]
fn texttofront_and_hatchtoback_across_all_spaces() {
let mut s = Session::new();
// In Model space: 1 line, 1 hatch, 1 text.
s.execute("line", &json!({ "points": [[0, 0], [10, 0]] })).unwrap();
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [10, 10] })).unwrap();
s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "SOLID" })).unwrap();
s.execute("text", &json!({ "at": [0, 0], "height": 2, "text": "MText1" })).unwrap();
// Create a paper space layout and switch to it.
s.execute("layout.new", &json!({ "name": "Sheet1", "viewport": false })).unwrap();
s.execute("layout.set", &json!({ "name": "Sheet1" })).unwrap();
// In Sheet1 paper space: 1 line, 1 hatch, 1 text.
s.execute("line", &json!({ "points": [[0, 0], [20, 0]] })).unwrap();
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [20, 20] })).unwrap();
s.execute("hatch", &json!({ "points": [[10, 10]], "pattern": "SOLID" })).unwrap();
s.execute("text", &json!({ "at": [0, 0], "height": 3, "text": "PText1" })).unwrap();
// Move hatches to the front in both spaces first.
let m_hatch = s.doc().unwrap().model.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle;
let p_layout = s.doc().unwrap().layouts.iter().find(|l| l.name == "Sheet1").unwrap();
let p_hatch = p_layout.entities.iter().find(|e| matches!(e.kind, EntityKind::Hatch(_))).unwrap().handle;
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
s.execute("draworder.front", &json!({ "handles": [m_hatch.hex()] })).unwrap();
s.execute("layout.set", &json!({ "name": "Sheet1" })).unwrap();
s.execute("draworder.front", &json!({ "handles": [p_hatch.hex()] })).unwrap();
// HATCHTOBACK acts across ALL spaces: model space AND layouts.
let r = s.execute("hatchtoback", &json!({})).unwrap();
assert_eq!(r["moved"], 2, "hatches sent to back in both model space and paper layout");
let doc = s.doc().unwrap();
let m_first = doc.model.iter().next().unwrap();
assert!(matches!(m_first.kind, EntityKind::Hatch(_)), "model space hatch is back");
let l_first = doc.layouts.iter().find(|l| l.name == "Sheet1").unwrap().entities.iter().next().unwrap();
assert!(matches!(l_first.kind, EntityKind::Hatch(_)), "paper space hatch is back");
// TEXTTOFRONT acts across ALL spaces: brings text in both model space and paper layout to front.
let r = s.execute("texttofront", &json!({ "objects": "text" })).unwrap();
assert_eq!(r["moved"], 2, "texts brought to front in both model space and paper layout");
let doc = s.doc().unwrap();
let m_last = doc.model.iter().last().unwrap();
assert!(matches!(m_last.kind, EntityKind::Text(_)), "model space text is front");
let l_last = doc.layouts.iter().find(|l| l.name == "Sheet1").unwrap().entities.iter().last().unwrap();
assert!(matches!(l_last.kind, EntityKind::Text(_)), "paper space text is front");
}
+47
View File
@@ -155,3 +155,50 @@ fn erased_members_leave_groups() {
s.cmdline("").unwrap();
assert_eq!(groups(&s).iter().map(|g| g.0.as_str()).collect::<Vec<_>>(), ["B"]);
}
#[test]
fn copy_whole_group_replicates_group() {
let (mut s, hs) = three_lines();
s.execute("group", &json!({ "name": "Pair", "description": "two lines", "handles": hex(&hs[..2]) })).unwrap();
assert_eq!(s.doc().unwrap().groups.len(), 1);
// Copying both members with COPY creates a new unnamed group *A1.
let r = s.execute("copy", &json!({ "handles": hex(&hs[..2]), "delta": [0, 20] })).unwrap();
let copied: Vec<String> = r["handles"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
assert_eq!(copied.len(), 2);
let gs = groups(&s);
assert_eq!(gs.len(), 2, "a new group was created for the copied pair");
assert_eq!(gs[1].0, "*A1");
assert_eq!(gs[1].1, "two lines");
assert_eq!(hex(&gs[1].2), copied);
// Copying only ONE member of the group does not create another group.
s.execute("copy", &json!({ "handles": [hs[0].hex()], "delta": [0, 40] })).unwrap();
assert_eq!(s.doc().unwrap().groups.len(), 2, "partial copy does not replicate group");
// Copying to clipboard and pasting also replicates the whole group.
s.set_selection(vec![hs[0], hs[1]]);
s.execute("copyclip", &json!({})).unwrap();
let r = s.execute("pasteclip", &json!({ "at": [50, 50] })).unwrap();
let pasted: Vec<String> = r["handles"].as_array().unwrap().iter().map(|v| v.as_str().unwrap().to_string()).collect();
let gs = groups(&s);
assert_eq!(gs.len(), 3, "pasting whole group replicates it");
assert_eq!(gs[2].0, "*A2");
assert_eq!(hex(&gs[2].2), pasted);
}
#[test]
fn groupdisplaymode_sysvar() {
let mut s = Session::new();
let v = s.execute("getvar", &json!({ "name": "GROUPDISPLAYMODE" })).unwrap();
assert_eq!(v["value"], 2, "GROUPDISPLAYMODE defaults to 2");
s.execute("setvar", &json!({ "name": "GROUPDISPLAYMODE", "value": 0 })).unwrap();
assert_eq!(s.settings.groupdisplaymode, 0);
s.execute("setvar", &json!({ "name": "GROUPDISPLAYMODE", "value": 1 })).unwrap();
assert_eq!(s.settings.groupdisplaymode, 1);
assert!(s.execute("setvar", &json!({ "name": "GROUPDISPLAYMODE", "value": 3 })).is_err());
assert!(s.execute("setvar", &json!({ "name": "GROUPDISPLAYMODE", "value": -1 })).is_err());
}
+298
View File
@@ -0,0 +1,298 @@
//! A hatch made by picking an internal point keeps the arcs of its boundary (#1167): the traced
//! outline comes from flattened curves, and its runs along a circle, an arc or a polyline's arc
//! segment become arcs again, so AREA on the hatch equals AREA on the objects. Only edges traced
//! from those circular pieces become arcs: a line or an ellipse near a circle stays as it is.
use std::f64::consts::PI;
use cadcraft_engine::Session;
use cadcraft_engine::doc::{EntityKind, Handle, Hatch, HatchLoop};
use cadcraft_engine::geom::Polyline;
use serde_json::{Value, json};
fn handle(v: &Value) -> String {
v["handle"].as_str().or_else(|| v["handles"][0].as_str()).unwrap().to_string()
}
fn hatch(s: &Session, h: &str) -> Hatch {
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
EntityKind::Hatch(x) => x.clone(),
k => panic!("not a hatch: {k:?}"),
}
}
fn pl(l: &HatchLoop) -> Polyline {
Polyline { vertices: l.vertices.clone(), closed: true }
}
/// Filled area, exact with bulges: outer loops minus islands.
fn area(h: &Hatch) -> f64 {
h.loops.iter().map(|l| pl(l).area().abs() * if l.outer { 1.0 } else { -1.0 }).sum()
}
fn bulges(l: &HatchLoop) -> usize {
l.vertices.iter().filter(|v| v.bulge.abs() > 1e-9).count()
}
fn close(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-6 * (1.0 + b.abs())
}
fn hatch_at(s: &mut Session, points: &[[f64; 2]]) -> String {
handle(&s.execute("hatch", &json!({ "points": points, "pattern": "SOLID" })).unwrap())
}
#[test]
fn a_circle_hatched_inside_is_two_half_circles_with_the_circles_area() {
let mut s = Session::new();
let c = handle(&s.execute("circle", &json!({ "center": [50, 50], "radius": 40 })).unwrap());
let h = {
let hh = hatch_at(&mut s, &[[50.0, 50.0]]);
hatch(&s, &hh)
};
let l = &h.loops[0];
assert_eq!(l.vertices.len(), 2, "{:?}", l.vertices);
assert!(l.vertices.iter().all(|v| (v.bulge.abs() - 1.0).abs() < 1e-12));
assert!(close(area(&h), PI * 1600.0), "{}", area(&h));
assert!(h.associative && l.sources.iter().any(|x| x.hex() == c));
// Typed at the command line, as in the report.
let mut s = Session::new();
s.script("CIRCLE 50,50 40\n-HATCH P SOLID\n50,50\n\n").unwrap();
let h = s.doc().unwrap().model.iter().find_map(|e| if let EntityKind::Hatch(x) = &e.kind { Some(x.clone()) } else { None }).unwrap();
assert!(close(area(&h), PI * 1600.0), "{}", area(&h));
}
#[test]
fn a_rounded_rectangle_keeps_its_arc_as_one_polyline_or_as_lines_and_an_arc() {
// 100 x 50 with a semicircular right side: 5000 + π·25²/2.
let want = 5000.0 + PI * 625.0 / 2.0;
let mut s = Session::new();
s.execute("pline", &json!({ "vertices": [[0, 0], { "p": [100, 0], "bulge": 1.0 }, [100, 50], [0, 50]], "closed": true })).unwrap();
let h = {
let hh = hatch_at(&mut s, &[[50.0, 25.0]]);
hatch(&s, &hh)
};
assert_eq!(h.loops[0].vertices.len(), 4, "{:?}", h.loops[0].vertices);
assert_eq!(bulges(&h.loops[0]), 1);
assert!(close(area(&h), want), "{}", area(&h));
// The same shape as three lines and an arc, then moved with its objects.
let mut s = Session::new();
let mut objs = Vec::new();
for (a, b) in [([0, 0], [100, 0]), ([100, 50], [0, 50]), ([0, 50], [0, 0])] {
objs.push(handle(&s.execute("line", &json!({ "points": [a, b] })).unwrap()));
}
objs.push(handle(&s.execute("arc", &json!({ "center": [100, 25], "radius": 25, "start": -90, "end": 90 })).unwrap()));
let hh = hatch_at(&mut s, &[[50.0, 25.0]]);
let h = hatch(&s, &hh);
assert_eq!(bulges(&h.loops[0]), 1);
assert!(close(area(&h), want), "{}", area(&h));
objs.push(hh.clone());
s.execute("move", &json!({ "handles": objs, "delta": [7, 3] })).unwrap();
let h = hatch(&s, &hh);
assert_eq!(bulges(&h.loops[0]), 1, "{:?}", h.loops[0].vertices);
assert!(close(area(&h), want), "{}", area(&h));
}
/// A circle of radius 10 at the origin cut by a line `y = c`: the cap above it and the rest.
fn cut_circle(c: f64) -> (Session, f64, f64) {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
s.execute("line", &json!({ "points": [[-20, c], [20, c]] })).unwrap();
let theta = 2.0 * (c / 10.0).acos();
let cap = 50.0 * (theta - theta.sin());
(s, cap, PI * 100.0 - cap)
}
#[test]
fn a_circle_cut_by_a_line_gives_the_exact_segments_even_for_a_shallow_cut() {
// (A cut shallower than the flattening tolerance finds no boundary, as before.)
for c in [3.0, 9.9, 9.99] {
let (mut s, cap, rest) = cut_circle(c);
let top = {
let hh = hatch_at(&mut s, &[[0.0, (c + 10.0) / 2.0]]);
hatch(&s, &hh)
};
let bottom = {
let hh = hatch_at(&mut s, &[[0.0, 0.0]]);
hatch(&s, &hh)
};
assert!(close(area(&top), cap), "cap at {c}: {} vs {cap}", area(&top));
assert!(close(area(&bottom), rest), "rest at {c}: {} vs {rest}", area(&bottom));
// Every point of both outlines stays on or inside the circle and on its side of the line.
for (h, above) in [(&top, true), (&bottom, false)] {
for q in pl(&h.loops[0]).tessellate(1e-4) {
assert!(q.len() <= 10.0 + 1e-6, "{q:?} outside the circle (cut at {c})");
assert!(if above { q.y >= c - 1e-6 } else { q.y <= c + 1e-6 }, "{q:?} past the line (cut at {c})");
}
}
}
}
#[test]
fn an_ellipse_or_a_line_next_to_a_circle_is_not_taken_for_it() {
// An ellipse a hair wider than the circle crosses it four times; the region inside both is
// bounded by circle arcs and ellipse pieces, which stay flattened.
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
s.execute("ellipse", &json!({ "center": [0, 0], "major": [10.05, 0], "ratio": 0.99 })).unwrap();
let h = {
let hh = hatch_at(&mut s, &[[0.0, 0.0]]);
hatch(&s, &hh)
};
// Within the flattening tolerance of both curves, as the flattened outline was: where the
// two cross at a shallow angle the corner is only known to that tolerance.
let tol = 2.0 * (s.doc().unwrap().extents(&cadcraft_engine::doc::Space::Model).width() + 20.1) / 20000.0;
for q in pl(&h.loops[0]).tessellate(1e-4) {
assert!(q.len() <= 10.0 + tol, "{q:?} outside the circle");
let r = 10.05 * (q.x * q.x + q.y * q.y / (0.99 * 0.99)).sqrt() / 10.05;
assert!(r <= 10.05 + tol, "{q:?} outside the ellipse");
}
// A line just outside the circle, tangent-close: the hatch inside the circle is the circle.
let mut s = Session::new();
s.execute("circle", &json!({ "center": [0, 0], "radius": 10 })).unwrap();
s.execute("line", &json!({ "points": [[-20, 10.0001], [20, 10.0001]] })).unwrap();
let h = {
let hh = hatch_at(&mut s, &[[0.0, 0.0]]);
hatch(&s, &hh)
};
assert!(close(area(&h), PI * 100.0), "{}", area(&h));
}
#[test]
fn one_hatch_inside_and_around_a_circle_fills_both() {
// Picked inside the circle and in the square around it: the circle is filled too.
let mut s = Session::new();
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [100, 100] })).unwrap();
s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap();
let hh = hatch_at(&mut s, &[[50.0, 50.0], [5.0, 5.0]]);
let h = hatch(&s, &hh);
assert!(close(filled(&h), 10000.0), "{} from {:?}", filled(&h), h.loops.iter().map(|l| (l.outer, l.vertices.len())).collect::<Vec<_>>());
// As drawn and as AREA measures it: the circle's outer loop and island cancel, the square
// is filled whole.
let drawn = cadcraft_engine::render::hatch_fill_loops(&h, 1e-3);
let centre = cadcraft_engine::geom::Vec2::new(50.0, 50.0);
assert_eq!(drawn.iter().filter(|l| cadcraft_engine::geom::point_in_polygon(l, centre)).count() % 2, 1, "the circle is filled");
let a = s.execute("area", &json!({ "handle": hh })).unwrap()["area"].as_f64().unwrap();
assert!(close(a, 10000.0), "{a}");
// The same with a square inside the square (exact on main too, so merged there).
let mut s = Session::new();
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [100, 100] })).unwrap();
s.execute("rectang", &json!({ "p1": [40, 40], "p2": [60, 60] })).unwrap();
let hh = hatch_at(&mut s, &[[50.0, 50.0], [5.0, 5.0]]);
let h = hatch(&s, &hh);
assert!(close(filled(&h), 10000.0), "{}", filled(&h));
}
/// The area the even-odd fill covers: points on a fine grid inside an odd number of loops.
fn filled(h: &Hatch) -> f64 {
let polys: Vec<Vec<cadcraft_engine::geom::Vec2>> = h.loops.iter().map(|l| pl(l).tessellate(1e-3)).collect();
let n = 400;
let step = 100.0 / n as f64;
let mut inside = 0usize;
for i in 0..n {
for j in 0..n {
let q = cadcraft_engine::geom::Vec2::new((i as f64 + 0.5) * step, (j as f64 + 0.5) * step);
if polys.iter().filter(|p| cadcraft_engine::geom::point_in_polygon(p, q)).count() % 2 == 1 {
inside += 1;
}
}
}
inside as f64 * step * step
}
/// HPORIGINMODE's corners take the circle's extents, not only its two vertices (a circle kept as
/// two half-circles spans its whole height).
#[test]
fn a_circles_hatch_origin_takes_its_extents() {
let mut s = Session::new();
s.execute("circle", &json!({ "center": [50, 50], "radius": 40 })).unwrap();
let h = handle(&s.execute("hatch", &json!({ "points": [[50, 50]], "pattern": "ANSI31", "originMode": "bottomLeft" })).unwrap());
let o = hatch(&s, &h).origin;
assert!(close(o.x, 10.0) && close(o.y, 10.0), "{o:?}");
let h = handle(&s.execute("hatch", &json!({ "points": [[50, 50]], "pattern": "ANSI31", "originMode": "topRight" })).unwrap());
let o = hatch(&s, &h).origin;
assert!(close(o.x, 90.0) && close(o.y, 90.0), "{o:?}");
}
/// The polyline BOUNDARY makes keeps the arcs: a circle gives two half-circles, a rounded
/// rectangle one arc segment, each with the object's exact area.
#[test]
fn boundary_keeps_the_arcs() {
let lw = |s: &Session, h: &str| -> Polyline {
match &s.doc().unwrap().entity(Handle::parse_hex(h).unwrap()).unwrap().kind {
EntityKind::LwPolyline(p) => Polyline { vertices: p.vertices.clone(), closed: p.closed },
k => panic!("not a polyline: {k:?}"),
}
};
let mut s = Session::new();
s.execute("circle", &json!({ "center": [50, 50], "radius": 40 })).unwrap();
let b = handle(&s.execute("boundary", &json!({ "points": [[50, 50]] })).unwrap());
let p = lw(&s, &b);
assert_eq!(p.vertices.len(), 2, "{:?}", p.vertices);
assert!(p.vertices.iter().all(|v| (v.bulge.abs() - 1.0).abs() < 1e-12));
assert!(close(p.area().abs(), PI * 1600.0), "{}", p.area());
let mut s = Session::new();
s.execute("pline", &json!({ "vertices": [[0, 0], { "p": [100, 0], "bulge": 1.0 }, [100, 50], [0, 50]], "closed": true })).unwrap();
let b = handle(&s.execute("boundary", &json!({ "points": [[50, 25]] })).unwrap());
let p = lw(&s, &b);
assert_eq!(p.vertices.iter().filter(|v| v.bulge.abs() > 1e-9).count(), 1, "{:?}", p.vertices);
assert!(close(p.area().abs(), 5000.0 + PI * 625.0 / 2.0), "{}", p.area());
}
/// HATCHEDIT adding a boundary the hatch already has (its island) changes nothing: a second copy
/// of the island would cancel it and fill the circle.
#[test]
fn hatchedit_adding_an_existing_island_keeps_it() {
let mut s = Session::new();
s.execute("rectang", &json!({ "p1": [0, 0], "p2": [100, 100] })).unwrap();
let c = handle(&s.execute("circle", &json!({ "center": [50, 50], "radius": 20 })).unwrap());
// Not associative: its island is linked to nothing until the circle is added.
let hh = handle(&s.execute("hatch", &json!({ "points": [[5, 5]], "pattern": "SOLID", "associative": false })).unwrap());
assert!(hatch(&s, &hh).loops.iter().all(|l| l.sources.is_empty()));
let before = hatch(&s, &hh).loops.len();
s.execute("hatchedit", &json!({ "handles": [hh], "addBoundary": [c] })).unwrap();
let h = hatch(&s, &hh);
assert_eq!(h.loops.len(), before, "{:?}", h.loops.iter().map(|l| (l.outer, l.vertices.len())).collect::<Vec<_>>());
let drawn = cadcraft_engine::render::hatch_fill_loops(&h, 1e-3);
let centre = cadcraft_engine::geom::Vec2::new(50.0, 50.0);
assert_eq!(drawn.iter().filter(|l| cadcraft_engine::geom::point_in_polygon(l, centre)).count() % 2, 0, "the island stays empty");
// The island is linked to the circle that was added.
assert!(
h.loops.iter().any(|l| !l.outer && l.sources.iter().any(|x| x.hex() == c)),
"{:?}",
h.loops.iter().map(|l| (l.outer, l.sources.clone())).collect::<Vec<_>>()
);
}
/// AREA tests a loop's nesting at an edge's middle, as the fill does: an island whose first vertex
/// lies on the outer loop (here on its right edge, where a vertex test says "outside") is still
/// subtracted.
#[test]
fn area_subtracts_an_island_touching_the_outer_loop() {
use cadcraft_engine::geom::{PolyVertex, Vec2};
let lp = |pts: &[(f64, f64)], outer: bool| HatchLoop {
vertices: pts.iter().map(|&(x, y)| PolyVertex::new(Vec2::new(x, y))).collect(),
outer,
boundary_flags: None,
sources: vec![],
};
let mut s = Session::new();
let h = Hatch {
loops: vec![lp(&[(0.0, 0.0), (10.0, 0.0), (10.0, 10.0), (0.0, 10.0)], true), lp(&[(10.0, 5.0), (5.0, 4.0), (5.0, 6.0)], false)],
pattern: "SOLID".into(),
solid: true,
scale: 1.0,
..hatch_template(&mut s)
};
let id = s.add_entity(EntityKind::Hatch(h)).unwrap();
let a = s.execute("area", &json!({ "handle": id.hex() })).unwrap()["area"].as_f64().unwrap();
assert!(close(a, 100.0 - 5.0), "{a}");
}
/// Any hatch's fields, to build one by hand.
fn hatch_template(s: &mut Session) -> Hatch {
s.execute("rectang", &json!({ "p1": [200, 200], "p2": [210, 210] })).unwrap();
let hh = hatch_at(s, &[[205.0, 205.0]]);
hatch(s, &hh)
}
+26
View File
@@ -71,3 +71,29 @@ fn layer_commands_reject_unloaded_linetypes_and_duplicate_renames() {
s.execute("layer.set", &json!({ "name": "A", "newName": "a", "linetype": "continuous" })).unwrap();
assert_eq!(s.doc().unwrap().layer("a").unwrap().linetype, "Continuous");
}
#[test]
fn layer_cmdline_state_save_restore_rename_delete() {
let mut s = Session::new();
s.execute("layer.new", &json!({ "name": "L1", "color": "1" })).unwrap();
// Test -LAYER A (stAte) Save
s.script("-LAYER A S St1 \n\n").unwrap();
assert!(s.doc().unwrap().layer_states.iter().any(|st| st.name == "St1"));
// Modify layer L1 color
s.execute("layer.set", &json!({ "name": "L1", "color": "2" })).unwrap();
assert_eq!(s.doc().unwrap().layer("L1").unwrap().color, cadcraft_color::Color::Index(2));
// Restore St1
s.script("-LAYER A R St1 \n\n").unwrap();
assert_eq!(s.doc().unwrap().layer("L1").unwrap().color, cadcraft_color::Color::Index(1));
// Rename St1 -> St2 (Name)
s.script("-LAYER A N St1 St2 \n\n").unwrap();
assert!(s.doc().unwrap().layer_states.iter().any(|st| st.name == "St2"));
assert!(!s.doc().unwrap().layer_states.iter().any(|st| st.name == "St1"));
// Delete St2
s.script("-LAYER A D St2 \n\n").unwrap();
assert!(!s.doc().unwrap().layer_states.iter().any(|st| st.name == "St2"));
}
+2
View File
@@ -71,6 +71,7 @@ mod grip_options;
mod grip_selection;
mod group_selection;
mod groups;
mod hatch_arcs;
mod hatch_assoc;
mod hatch_dialog_helpers;
mod hatch_generate_boundary;
@@ -157,6 +158,7 @@ mod rectang_polygon_order;
mod refedit;
mod region;
mod rename_cmdline;
mod revcloud_recognised;
mod rotate_reference;
mod rotation_grip_input;
mod scale_offset_z;
+11
View File
@@ -82,6 +82,17 @@ fn rename_prompts_type_old_and_new_name() {
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_eq!(s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, EntityKind::Line(_))).count(), 2);
// VPort configuration rename
s.doc_mut().unwrap().vports.push(cadcraft_doc::VportConfig { name: "MyVP".into(), tiles: vec![] });
s.script("-RENAME VP MyVP NewVP\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let d = s.doc().unwrap();
assert!(d.vports.iter().any(|v| v.name == "NewVP"));
assert!(!d.vports.iter().any(|v| v.name == "MyVP"));
// Cannot rename *Active viewport configuration
assert!(s.execute("rename", &json!({ "table": "vport", "from": "*Active", "to": "Active2" })).is_err());
}
/// What `script` adds to the log; the command has ended.
@@ -0,0 +1,85 @@
//! Readers recognise a saved revision cloud (#1570): a closed polyline with `RevcloudProps`
//! xdata whose every arc has bulge 0.520567 (they accept 0.02 either way; 0.5 was just outside).
use cadcraft_engine::Session;
use cadcraft_engine::doc::{Drawing, EntityKind, Handle, RawTag};
use serde_json::{Value, json};
const BULGE: f64 = 0.520567050552;
fn h(v: &Value) -> Handle {
v["handle"].as_str().and_then(Handle::parse_hex).unwrap()
}
fn last(s: &Session) -> Handle {
s.doc().unwrap().model.iter().last().map(|e| e.handle).unwrap()
}
/// Types `lines` at the command line and returns the one entity that run created. The prompt
/// sequence must have finished: a stale script leaves a prompt waiting, and `last` would then be
/// the previous entity, whose XDATA this test would wrongly accept. Counts new handles, not
/// entities: Object mode erases the picked shape as it adds the cloud.
fn typed_cloud(s: &mut Session, lines: &[&str]) -> Handle {
let before: Vec<Handle> = s.doc().unwrap().model.iter().map(|e| e.handle).collect();
for l in lines {
s.cmdline(l).unwrap();
}
assert!(!s.prompting(), "{lines:?} left a prompt waiting: {}", s.prompt_text());
let new: Vec<Handle> = s.doc().unwrap().model.iter().map(|e| e.handle).filter(|h| !before.contains(h)).collect();
assert_eq!(new.len(), 1, "{lines:?} must create exactly one entity, got {new:?}");
assert_eq!(last(s), new[0], "{lines:?}: the new cloud must be the last entity");
new[0]
}
fn props(xdata: &[RawTag]) -> Vec<(i32, String)> {
let start = xdata.iter().position(|t| t.code == 1001 && t.value == "RevcloudProps").expect("RevcloudProps xdata");
xdata[start..].iter().take_while(|t| t.code != 1001 || t.value == "RevcloudProps").map(|t| (t.code, t.value.trim().to_string())).collect()
}
/// The cloud `h` is what readers take for a cloud: closed, cloud bulges, `RevcloudProps`.
fn assert_cloud(d: &Drawing, h: Handle, arc_len: f64) {
let e = d.entity(h).unwrap();
let EntityKind::LwPolyline(p) = &e.kind else { panic!("{:?}", e.kind) };
assert!(p.closed);
assert!(p.vertices.iter().all(|v| (v.bulge.abs() - BULGE).abs() < 1e-9), "{:?}", p.vertices);
let x = props(&e.common.xdata);
assert_eq!(x.len(), 3, "{x:?}");
assert_eq!(x[1], (1070, "0".to_string()));
assert_eq!(x[2].0, 1040);
assert!((x[2].1.parse::<f64>().unwrap() - arc_len).abs() < 1e-12, "{x:?}");
}
#[test]
fn every_way_of_drawing_a_cloud_is_recognised() {
let mut s = Session::new();
let rect = h(&s.execute("revcloud", &json!({"p1": [0, 0], "p2": [100, 50], "arcLength": 15})).unwrap());
let poly = h(&s.execute("revcloud.polygonal", &json!({"points": [[0, 0], [0, 30], [30, 0]], "arcLength": 5})).unwrap());
let rev = h(&s.execute("revcloud.freehand", &json!({"freehand": [[0, 0], [50, 0], [50, 50]], "arcLength": 10, "reverse": true})).unwrap());
let circle = h(&s.execute("circle", &json!({"center": [200, 0], "radius": 20})).unwrap());
let obj = h(&s.execute("revcloud", &json!({"handle": circle, "arcLength": 4})).unwrap());
// Arc length asks the minimum and then the maximum (#1714).
let typed = typed_cloud(&mut s, &["revcloud a 2 2", "300,0 320,10"]);
s.execute("rectang", &json!({"p1": [400, 0], "p2": [420, 20]})).unwrap();
// Object then asks "Reverse direction" after the pick.
let picked = typed_cloud(&mut s, &["revcloud a 3 3 o 400,10 n"]);
let d = s.doc().unwrap();
for (h, a) in [(rect, 15.0), (poly, 5.0), (rev, 10.0), (obj, 4.0), (typed, 2.0), (picked, 3.0)] {
assert_cloud(d, h, a);
}
let EntityKind::LwPolyline(p) = &d.entity(rev).unwrap().kind else { panic!() };
assert!(p.vertices.iter().all(|v| v.bulge < 0.0), "a reversed cloud keeps its arcs turned inward");
}
#[test]
fn a_saved_cloud_reads_back_as_a_cloud() {
let mut s = Session::new();
s.execute("revcloud", &json!({"p1": [0, 0], "p2": [100, 50], "arcLength": 15})).unwrap();
let text = cadcraft_io::write_dxf(s.doc().unwrap());
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let appid = lines.windows(2).any(|w| w[0] == "0" && w[1] == "APPID")
&& lines.windows(4).any(|w| w[0] == "AcDbRegAppTableRecord" && w[1] == "2" && w[2] == "RevcloudProps");
assert!(appid, "RevcloudProps is a registered application");
let read = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
let cloud = read.model.iter().find(|e| matches!(e.kind, EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
assert_cloud(&read, cloud, 15.0);
}
+126
View File
@@ -117,6 +117,108 @@ fn page_setup_takes_a_device_and_its_papers() {
assert!(report["devices"].as_array().unwrap().iter().any(|d| d == "Plan Printer"));
}
#[test]
/// A paper stored portrait keeps its printable area when the page names it landscape: the margins
/// turn back to the axes the user gave, and PLOT hands them on that way (#1266).
fn a_landscape_page_gets_the_papers_margins_back() {
let mut s = session();
s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "pdf"})).unwrap();
let paper = json!({"name": "Banner", "width": 400, "height": 200, "margins": [150, 0, 150, 0]});
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": paper})).unwrap();
// Stored portrait, 200 x 400, the side margins on the long axis.
let stored = |s: &mut Session| {
let r = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap();
r["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").cloned().unwrap()
};
let p = stored(&mut s);
assert_eq!((p["width"].as_f64(), p["height"].as_f64()), (Some(200.0), Some(400.0)));
assert_eq!(p["margins"], json!([0.0, 150.0, 0.0, 150.0]));
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Banner Printer", "paper": "Banner", "landscape": true})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (200.0, 400.0, [150.0, 0.0, 150.0, 0.0]));
// The 400 x 200 sheet's printable area is 100 x 200 mm, not the whole sheet.
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
let mm = |v: f64| v * sheet.unit_mm;
assert_eq!((mm(sheet.size.x), mm(sheet.size.y)), (400.0, 200.0));
assert_eq!((mm(sheet.printable.min.x), mm(sheet.printable.min.y)), (150.0, 0.0));
assert_eq!((mm(sheet.printable.max.x), mm(sheet.printable.max.y)), (250.0, 200.0));
// PLOT hands the margins on in the sheet's orientation.
let o = plotted(s.execute("plot", &json!({"layout": "Layout1", "paper": "Banner"})).unwrap());
assert_eq!((o["width"].as_f64(), o["height"].as_f64()), (Some(200.0), Some(400.0)));
assert_eq!(o["margins"], json!([150.0, 0.0, 150.0, 0.0]));
// Naming the paper landscape again at a new size keeps the margins' axes as well.
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 500, "height": 200}}))
.unwrap();
let p = stored(&mut s);
assert_eq!((p["width"].as_f64(), p["height"].as_f64()), (Some(200.0), Some(500.0)));
assert_eq!(p["margins"], json!([0.0, 150.0, 0.0, 150.0]), "the margins keep the short sides");
}
#[test]
/// A page set up on a landscape device paper keeps its printable area when a later PAGESETUP only
/// changes the orientation: no paper is copied, so the retained margins turn to the new sheet
/// instead of being saved against the wrong axes (#1266).
fn an_orientation_only_pagesetup_turns_the_retained_margins() {
let mut s = session();
s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "pdf"})).unwrap();
let paper = json!({"name": "Banner", "width": 400, "height": 200, "margins": [150, 0, 150, 0]});
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": paper})).unwrap();
// The landscape page carries the margins on its 400 mm sides: 150 mm left and right.
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Banner Printer", "paper": "Banner", "landscape": true})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (200.0, 400.0, [150.0, 0.0, 150.0, 0.0]));
// A second command changes only the orientation. The paper is not copied and no margins are
// given, so the retained margins turn to the 200 x 400 portrait sheet: 150 mm top and bottom,
// leaving the same 100 x 200 mm printable area rather than falling back to the whole sheet.
s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": false})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!((page.paper.as_str(), page.margins_mm), ("Banner", [0.0, 150.0, 0.0, 150.0]));
let sheet = cadcraft_render::sheet(s.doc().unwrap(), "Layout1").unwrap();
let mm = |v: f64| v * sheet.unit_mm;
assert_eq!((mm(sheet.size.x), mm(sheet.size.y)), (200.0, 400.0));
assert_eq!((mm(sheet.printable.min.x), mm(sheet.printable.min.y)), (0.0, 150.0));
assert_eq!((mm(sheet.printable.max.x), mm(sheet.printable.max.y)), (200.0, 250.0));
}
#[test]
/// Asymmetric retained margins turn with an orientation-only PAGESETUP in the direction the page
/// turns — a portrait page turning landscape re-measures them on the landscape axes, and turning
/// back restores the stored margins — so the printable area does not depend on how the
/// orientation was reached (#1266).
fn an_orientation_turn_turns_asymmetric_margins_the_way_the_page_turns() {
let mut s = session();
// A page setup's default orientation is landscape, so the page is named portrait first.
s.execute("pagesetup", &json!({"layout": "Layout1", "paper": "A4", "landscape": false, "margins": [10, 20, 30, 80]})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (210.0, 297.0, [10.0, 20.0, 30.0, 80.0]));
// Portrait to landscape: the margins turn the way `set_paper` turns a device paper's, so the
// 10 mm left margin becomes the landscape sheet's 80 mm top margin and the printable area is
// the same rectangle on the turned sheet.
s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": true})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!(page.margins_mm, [80.0, 10.0, 20.0, 30.0], "the margins turn to the landscape axes");
// Landscape back to portrait restores the margins the page was set up with.
s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": false})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!(page.margins_mm, [10.0, 20.0, 30.0, 80.0], "the round trip keeps the margins");
// A landscape page turns the other way when it goes portrait: the margins are re-measured on
// the portrait sheet's axes, and turning back gives them the landscape reading again.
s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": true, "margins": [1, 2, 3, 4]})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": false})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!(page.margins_mm, [2.0, 3.0, 4.0, 1.0], "the landscape margins turn back to the portrait axes");
s.execute("pagesetup", &json!({"layout": "Layout1", "landscape": true})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!(page.margins_mm, [1.0, 2.0, 3.0, 4.0], "the second turn restores the landscape margins");
}
#[test]
/// PLOT and EXPORTPDF hand the hook the device's output, resolution, paper and margins, and a
/// layout plots with its own page setup; unknown devices and papers are refused.
@@ -239,3 +341,27 @@ fn plotwindow_picks_both_corners_with_ortho_on() {
let c = hover(&mut s, Vec2::new(10.0, 4.0));
assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps the line horizontal: {c:?}");
}
#[test]
fn paper_margins_are_checked_against_their_own_axis() {
let mut s = session();
s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "png"})).unwrap();
let paper = |margins: Value| json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200, "margins": margins}});
// 250 mm of bottom + top margin leaves no printable height on a 200 mm paper.
assert!(s.execute("plottermanager", &paper(json!([0, 250, 0, 0]))).is_err());
// 300 mm of left + right margin still leaves 100 mm of printable width on a 400 mm paper.
assert!(s.execute("plottermanager", &paper(json!([150, 0, 150, 0]))).is_ok());
// The paper is stored portrait and the margins turn with it: the 100 x 200 printable area
// of the requested sheet stays 200 x 100 on the stored 200 x 400 one.
let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap();
let banner = stored["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").unwrap().clone();
assert_eq!((banner["width"].as_f64().unwrap(), banner["height"].as_f64().unwrap()), (200.0, 400.0));
assert_eq!(banner["margins"], json!([0.0, 150.0, 0.0, 150.0]));
// Setting the same sheet again without margins keeps them: the stored margins belong to the
// portrait sheet and turn back before the per-axis check.
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200}}))
.unwrap();
let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap();
let banner = stored["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").unwrap().clone();
assert_eq!(banner["margins"], json!([0.0, 150.0, 0.0, 150.0]));
}
@@ -0,0 +1,90 @@
//! RENAME keeps what a renamed layer, block or style carries beyond what CADCraft models, as
//! AutoCAD does: other applications' xdata, its extension dictionary and reactors. A renamed
//! dynamic block stays dynamic, and saving writes the kept data on the new name.
use cadcraft_engine::Session;
use cadcraft_engine::doc::Drawing;
use cadcraft_engine::doc::dynblock::dynamic_block;
use serde_json::json;
/// DXF text from lines of `code value` (the value may be empty).
fn dxf(src: &str) -> String {
let mut out = String::new();
for line in src.lines().map(str::trim).filter(|l| !l.is_empty()) {
let (code, value) = line.split_once(' ').unwrap_or((line, ""));
out.push_str(&format!("{code}\n{value}\n"));
}
out
}
/// The dynamic DOOR block drawing (its BLOCK_RECORD has an extension dictionary holding the
/// block's evaluation graph), plus a layer WALLS carrying another application's xdata.
fn session() -> Session {
let layer = "0 TABLE\n2 LAYER\n5 2\n330 0\n100 AcDbSymbolTable\n70 1\n\
0 LAYER\n5 10\n330 2\n100 AcDbSymbolTableRecord\n100 AcDbLayerTableRecord\n2 Walls\n70 0\n62 3\n6 Continuous\n\
1001 ACME_TAGS\n1000 W-01\n1070 7\n0 ENDTAB\n";
let src = include_str!("../../io/tests/data/dynblock_door.txt").replace("\r\n", "\n").replacen(
"0 TABLE\n2 BLOCK_RECORD\n",
&format!("{layer}0 TABLE\n2 BLOCK_RECORD\n"),
1,
);
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
let mut s = Session::empty();
s.open_drawing(d, "rename", None);
s
}
fn layer_xdata(d: &Drawing, name: &str) -> Vec<(i32, String)> {
let key = ("LAYER".to_string(), name.to_string());
d.foreign.records.get(&key).map(|x| x.xdata.iter().map(|t| (t.code, t.value.trim().to_string())).collect()).unwrap_or_default()
}
fn saved_and_read(s: &Session) -> Drawing {
cadcraft_io::read_dxf(cadcraft_io::write_dxf(s.doc().unwrap()).as_bytes()).unwrap()
}
fn acme() -> Vec<(i32, String)> {
vec![(1001, "ACME_TAGS".into()), (1000, "W-01".into()), (1070, "7".into())]
}
#[test]
fn a_renamed_layer_keeps_its_xdata_through_a_save() {
let mut s = session();
assert_eq!(layer_xdata(s.doc().unwrap(), "WALLS"), acme());
s.execute("rename", &json!({ "table": "layer", "from": "Walls", "to": "Partitions" })).unwrap();
assert_eq!(layer_xdata(s.doc().unwrap(), "PARTITIONS"), acme());
let d = saved_and_read(&s);
assert!(d.layer("Partitions").is_some());
assert_eq!(layer_xdata(&d, "PARTITIONS"), acme());
s.execute("undo", &json!({})).unwrap();
assert_eq!(layer_xdata(s.doc().unwrap(), "WALLS"), acme(), "undo puts it back under the old name");
}
#[test]
fn a_renamed_dynamic_block_stays_dynamic_through_a_save() {
let mut s = session();
let before = dynamic_block(s.doc().unwrap(), "Door").expect("Door is a dynamic block");
s.execute("rename", &json!({ "table": "block", "from": "Door", "to": "Gate" })).unwrap();
let d = s.doc().unwrap();
assert!(d.block("Gate").is_some() && d.block("Door").is_none());
assert_eq!(dynamic_block(d, "Gate").map(|m| m.parameters.len()), Some(before.parameters.len()));
let d = saved_and_read(&s);
let after = dynamic_block(&d, "Gate").expect("Gate is still a dynamic block after a save");
assert_eq!(after.parameters.len(), before.parameters.len());
assert_eq!(after.actions.len(), before.actions.len());
}
#[test]
fn a_rename_that_only_changes_case_keeps_everything() {
let mut s = session();
s.execute("rename", &json!({ "table": "layer", "from": "Walls", "to": "WALLS" })).unwrap();
s.execute("rename", &json!({ "table": "block", "from": "Door", "to": "DOOR" })).unwrap();
let d = saved_and_read(&s);
let layers: Vec<&str> = d.layers.iter().map(|l| l.name.as_str()).filter(|n| n.eq_ignore_ascii_case("walls")).collect();
assert_eq!(layers, ["WALLS"], "the layer is saved under the new spelling");
let blocks: Vec<(&str, &str)> =
d.blocks.iter().filter(|(k, _)| k.eq_ignore_ascii_case("door")).map(|(k, b)| (k.as_str(), b.name.as_str())).collect();
assert_eq!(blocks, [("DOOR", "DOOR")], "the block is saved under the new spelling");
assert_eq!(layer_xdata(&d, "WALLS"), acme());
assert!(dynamic_block(&d, "Door").is_some());
}
+139
View File
@@ -171,3 +171,142 @@ fn data_links_saved_in_a_drawing_are_read_beside_it_or_on_this_computer_only() {
assert!(errors.iter().all(|e| e.contains("another computer")), "{errors:?}");
let _ = std::fs::remove_dir_all(&base);
}
/// Read and write drawings through `cadcraft-io`, as the app does.
fn use_file_io() {
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: None,
});
}
/// A new table, `i` rows of tables down, whose data link names `path` as a drawing file stores it.
fn linked_table(s: &mut Session, i: usize, path: &str) {
let r = s.execute("table", &json!({ "at": [0, 10.0 * i as f64], "cols": 2, "rows": 1 })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Table(t) = &mut e.kind {
t.data_link = Some(cadcraft_engine::doc::DataLink { path: path.to_string(), start_row: 0 });
}
})
.unwrap();
}
/// The text of every cell of every table in model space.
fn table_texts(s: &Session) -> String {
let mut out = String::new();
for e in s.doc().unwrap().model.iter() {
if let EntityKind::Table(t) = &e.kind {
for cell in t.cells.iter().flatten() {
out.push_str(&cell.text);
out.push('\n');
}
}
}
out
}
/// A drawing's own data link can't copy a file from outside its folder into it: not by `..`, not
/// by an absolute path, not through a folder whose name only starts the same, not through a link
/// inside the folder that leads out. Links within the folder, also by `..` back into it, still
/// update.
#[test]
fn a_saved_data_link_reads_no_file_outside_the_drawings_folder() {
use_file_io();
let base = std::env::temp_dir().join(format!("cadcraft-datalink-outside-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (dir, private, sibling) = (base.join("plans"), base.join("private"), base.join("plans-old"));
for d in [dir.join("sub"), private.clone(), sibling.clone()] {
std::fs::create_dir_all(d).unwrap();
}
let secret = "not-for-the-drawing";
std::fs::write(private.join("secret.csv"), format!("{secret},1\n")).unwrap();
std::fs::write(sibling.join("secret.csv"), format!("{secret},2\n")).unwrap();
std::fs::write(dir.join("parts.csv"), "bolt,4\n").unwrap();
std::fs::write(dir.join("sub").join("more.csv"), "nut,8\n").unwrap();
let path = |p: std::path::PathBuf| p.to_str().unwrap().to_string();
let inside = ["parts.csv".to_string(), "sub/more.csv".to_string(), "../plans/parts.csv".to_string(), path(dir.join("parts.csv"))];
let mut outside = vec!["../private/secret.csv".to_string(), path(private.join("secret.csv")), path(sibling.join("secret.csv"))];
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(private.join("secret.csv"), dir.join("link.csv")).is_ok();
// Windows lets only some accounts make symbolic links.
#[cfg(windows)]
let linked = std::os::windows::fs::symlink_file(private.join("secret.csv"), dir.join("link.csv")).is_ok();
if linked {
outside.push("link.csv".to_string());
} else {
eprintln!("symbolic links can't be made here: the link case is not checked");
}
let mut s = Session::new();
for (i, link) in inside.iter().chain(&outside).enumerate() {
linked_table(&mut s, i, link);
}
let host = dir.join("host.dxf");
s.execute("saveas", &json!({ "path": path(host.clone()) })).unwrap();
let mut s = Session::new();
s.execute("open", &json!({ "path": path(host) })).unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], inside.len(), "only the files in the drawing's folder: {r}");
let errors: Vec<&str> = r["errors"].as_array().unwrap().iter().filter_map(|e| e.as_str()).collect();
assert_eq!(errors.len(), outside.len(), "{errors:?}");
assert!(errors.iter().all(|e| e.contains("outside the drawing's folder")), "{errors:?}");
let texts = table_texts(&s);
assert!(texts.contains("bolt") && texts.contains("nut"), "the files inside are read: {texts}");
assert!(!texts.contains(secret), "{texts}");
// So the next save carries nothing of them either.
let after = dir.join("after.dxf");
s.execute("saveas", &json!({ "path": path(after.clone()) })).unwrap();
assert!(!std::fs::read_to_string(&after).unwrap().contains(secret));
let _ = std::fs::remove_dir_all(&base);
}
/// A file outside the drawing's folder that the user links with DATALINK keeps updating while
/// the drawing stays open; once it is opened again, the drawing alone can't read it until the
/// user links it again.
#[test]
fn a_file_the_user_links_outside_the_folder_updates_until_the_drawing_is_opened_again() {
use_file_io();
let base = std::env::temp_dir().join(format!("cadcraft-datalink-chosen-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (dir, data) = (base.join("plans"), base.join("data"));
std::fs::create_dir_all(&dir).unwrap();
std::fs::create_dir_all(&data).unwrap();
let bom = data.join("bom.csv");
let bom_path = bom.to_str().unwrap();
let host = dir.join("host.dxf");
let host_path = host.to_str().unwrap();
let mut s = Session::new();
let r = s.execute("table", &json!({ "at": [0, 0], "cols": 2, "rows": 1 })).unwrap();
let h = r["handle"].as_str().unwrap().to_string();
s.execute("saveas", &json!({ "path": host_path })).unwrap();
std::fs::write(&bom, "bolt,rev-a\n").unwrap();
s.execute("datalink", &json!({ "handle": h, "path": bom_path })).unwrap();
std::fs::write(&bom, "bolt,rev-b\n").unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], 1, "{r}");
assert!(table_texts(&s).contains("rev-b"));
s.execute("saveas", &json!({ "path": host_path })).unwrap();
let mut s = Session::new();
s.execute("open", &json!({ "path": host_path })).unwrap();
std::fs::write(&bom, "bolt,rev-c\n").unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], 0, "{r}");
assert!(r["errors"][0].as_str().unwrap().contains("outside the drawing's folder"), "{r}");
assert!(!table_texts(&s).contains("rev-c"));
// Linked again by the user, it reads and keeps updating.
s.execute("datalink", &json!({ "handle": h, "path": bom_path })).unwrap();
assert!(table_texts(&s).contains("rev-c"));
std::fs::write(&bom, "bolt,rev-d\n").unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], 1, "{r}");
assert!(table_texts(&s).contains("rev-d"));
let _ = std::fs::remove_dir_all(&base);
}
+122 -6
View File
@@ -83,7 +83,21 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64
let scale_x = if width_factor.is_finite() && width_factor.abs() > 1e-6 { width_factor } else { 1.0 };
let shear = oblique.tan().clamp(-10.0, 10.0);
let stroke_scale = normalized_height / stroke::CAP;
let characters: Vec<char> = chars.iter().map(|character| character.0).collect();
// A character the text's face lacks is one of its substitutes when it has one, as in the
// left-to-right path. The bidi runs come from the text as decoded, before substitution: a
// substitute may be of another bidi class (⌀ and ∅ are neutral, Ø is left-to-right), and
// the line keeps the direction its own text gives it; the substitute is drawn at the same
// logical index.
let decoded: Vec<char> = chars.iter().map(|character| character.0).collect();
let characters: Vec<char> = decoded
.iter()
.map(|&character| match primary {
Some(face) if !character.is_whitespace() && !face.has_glyph(character) => {
crate::substitutes(character).iter().copied().find(|&substitute| face.has_glyph(substitute)).unwrap_or(character)
}
_ => character,
})
.collect();
let flags = |index: usize| chars.get(index).map_or((false, false), |character| (character.1, character.2));
let mut shaped = Shaped::default();
let mut points_left = ttf::MAX_SHAPED_POINTS;
@@ -91,7 +105,7 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64
let mut pen_x = 0.0;
// Whether the rightmost glyph so far is a stroke-font glyph.
let mut stroke_last = false;
for (run, rtl) in bidi::visual_runs(&characters, base_rtl) {
for (run, rtl) in bidi::visual_runs(&decoded, base_rtl) {
let mut pieces = itemize(&characters, run, primary);
if rtl {
pieces.reverse();
@@ -150,9 +164,9 @@ fn shape_chars(primary: Option<&Face>, chars: &[(char, bool, bool)], height: f64
}
}
shaped.strokes.extend(crate::decorations(&spans, normalized_height));
// A stroke-font glyph at the right end: the width leaves out its trailing gap, like
// `shape_stroke`.
shaped.width = if stroke_last { (pen_x - stroke::GAP * stroke_scale * scale_x).max(0.0) } else { pen_x };
// A stroke-font glyph at the right end of a stroke-font line: the width leaves out its
// trailing gap, like `shape_stroke`. A TrueType line keeps it, like `ttf::shape`.
shaped.width = if stroke_last && primary.is_none() { (pen_x - stroke::GAP * stroke_scale * scale_x).max(0.0) } else { pen_x };
shaped
}
@@ -178,7 +192,9 @@ fn itemize(cs: &[char], run: Range<usize>, primary: Option<&Face>) -> Vec<(Src,
}
/// What draws `c`: the text's face when it has the character, else the previous fallback face,
/// else the first fallback font that has it (FONTFALLBACK, FONTALT, installed fonts).
/// else the first fallback font that has it (FONTFALLBACK, FONTALT, installed fonts), else the
/// stroke font when it has it; what no font has is the text's face's missing-glyph shape (a box
/// in the stroke font).
fn resolve(c: char, primary: Option<&Face>, prev: Option<&Face>) -> Src {
if let Some(p) = primary
&& (c.is_whitespace() || p.has_glyph(c))
@@ -193,6 +209,8 @@ fn resolve(c: char, primary: Option<&Face>, prev: Option<&Face>) -> Src {
}
match (ttf::fallback_for(c), primary) {
(Some(f), _) => Src::Face(f),
// No font has it: the stroke font's glyph, as in the left-to-right path.
(None, _) if stroke::glyph(c).is_some() => Src::Stroke,
// The text's font draws its own missing-glyph shape.
(None, Some(p)) => Src::Face(p.clone()),
(None, None) => Src::Missing,
@@ -438,6 +456,30 @@ mod tests {
assert!(!sh.strokes.iter().any(|s| s.len() == 5 && s.first() == s.last()), "no boxes for marks");
}
#[test]
fn a_face_lacking_what_no_font_has_gets_the_stroke_glyph() {
// A face that maps no character stands in for the text's font lacking one. What no
// installed font has either is the stroke font's glyph when it has one, as in the
// left-to-right path; what the stroke font lacks too, and whitespace, stay the face's.
let junk = Face { bytes: std::sync::Arc::new(b"not a font".to_vec()), index: 0 };
let c = '\u{2300}';
match ttf::fallback_for(c) {
None => assert!(matches!(resolve(c, Some(&junk), None), Src::Stroke), "the stroke font's glyph"),
Some(f) => assert!(matches!(resolve(c, Some(&junk), None), Src::Face(g) if g.same(&f)), "the fallback font's"),
}
assert!(matches!(resolve('\u{E000}', Some(&junk), None), Src::Face(_)), "the face's missing-glyph shape");
assert!(matches!(resolve(' ', Some(&junk), None), Src::Face(_)));
assert!(matches!(resolve(c, None, None), Src::Stroke));
if ttf::fallback_for(c).is_none() {
// Drawn as strokes, not a box, with the stroke font's advance; the trailing gap
// stays in the width, as `ttf::shape` keeps it.
let sh = shape(Some(&junk), "\u{05D0}\u{2300}", 1.0, 1.0, 0.0, None).unwrap_or_default();
assert!(sh.strokes.iter().any(|s| s.len() == 2), "the slash of the diameter sign");
assert!(!sh.strokes.iter().any(|s| s.len() == 5 && s.first() == s.last()), "no missing-glyph box");
assert!(sh.width >= crate::char_advance(c) - 1e-9, "{}", sh.width);
}
}
/// An installed font that shapes Arabic (Persian), or `None` (the test then skips).
fn arabic_face() -> Option<Face> {
ttf::fallback_for('\u{0633}').filter(|f| f.has_glyph('\u{06CC}') && f.has_glyph('\u{067E}'))
@@ -660,4 +702,78 @@ mod tests {
assert!(shape(None, &long, 1.0, 1.0, 0.0, None).is_none());
assert!(crate::shape_stroke(&long, 1.0, 1.0, 0.0).width > 0.0);
}
/// A TrueType font that maps `chars` to glyphs 1, 2, ... in code point order (each with the
/// same advance) and nothing else: a character map and metrics, no outlines. Enough for
/// `has_glyph` and the shaper, with a coverage the test chooses, whatever fonts are installed.
fn font_mapping(chars: &[char]) -> Face {
// Big-endian fields: (width in bytes, value).
fn table(fields: &[(usize, i64)]) -> Vec<u8> {
fields.iter().flat_map(|&(w, x)| x.to_be_bytes()[8 - w..].to_vec()).collect()
}
let mut chars = chars.to_vec();
chars.sort_unstable();
chars.dedup();
let n = i64::try_from(chars.len() + 1).unwrap();
// head: version 1.0, revision, checksum adjustment, magic, flags, units per em; created,
// modified and bounds (zero); mac style, lowest ppem, direction hint, loca format, glyph
// data format.
let mut head = table(&[(2, 1), (2, 0), (4, 0x1_0000), (4, 0), (4, 0x5F0F_3CF5), (2, 0), (2, 1000)]);
head.extend(table(&[(8, 0), (8, 0), (8, 0), (2, 0), (2, 8), (2, 2), (2, 0), (2, 0)]));
// hhea: version 1.0, ascender, descender, line gap, max advance, min side bearings,
// max extent, caret slope and offset, reserved, metric format, number of h metrics.
let hhea =
table(&[(2, 1), (2, 0), (2, 800), (2, -200), (2, 0), (2, 500), (2, 0), (2, 0), (2, 500), (2, 1), (2, 0), (2, 0), (8, 0), (2, 0), (2, n)]);
let maxp = table(&[(4, 0x5000), (2, n)]);
let hmtx = table(&[(2, 500), (2, 0)].repeat(chars.len() + 1));
// cmap: one (3, 10) format 12 subtable, one group per character, in code point order.
let groups: Vec<(usize, i64)> = chars
.iter()
.enumerate()
.flat_map(|(i, c)| [(4, i64::from(u32::from(*c))), (4, i64::from(u32::from(*c))), (4, i64::try_from(i + 1).unwrap())])
.collect();
let count = i64::try_from(chars.len()).unwrap();
let mut cmap = table(&[(2, 0), (2, 1), (2, 3), (2, 10), (4, 12), (2, 12), (2, 0), (4, 16 + 12 * count), (4, 0), (4, count)]);
cmap.extend(table(&groups));
let tables = [(b"cmap", cmap), (b"head", head), (b"hhea", hhea), (b"hmtx", hmtx), (b"maxp", maxp)];
let mut font = table(&[(4, 0x1_0000), (2, 5), (2, 64), (2, 2), (2, 16)]);
let mut offset = 12 + 16 * tables.len();
for (tag, t) in &tables {
font.extend_from_slice(*tag);
font.extend(table(&[(4, 0), (4, i64::try_from(offset).unwrap()), (4, i64::try_from(t.len()).unwrap())]));
offset += t.len().next_multiple_of(4);
}
for (_, t) in &tables {
font.extend_from_slice(t);
font.resize(font.len().next_multiple_of(4), 0);
}
Face { bytes: std::sync::Arc::new(font), index: 0 }
}
#[test]
fn a_substitute_does_not_change_the_direction_of_the_line() {
// ⌀ and ∅ are bidi-neutral; Ø, drawn for them in a font that lacks both, is
// left-to-right. "⌀50 אב" reads right to left (its first strong character is Hebrew),
// so "50⌀" sits at the right end of the line. A font without ⌀ lays the line out the
// same way: the runs come from the text as decoded, not from the characters
// substituted for it, which would make Ø the first strong character and flip the line.
let s = "%%u\u{2300}50%%u \u{05D0}\u{05D1}";
assert_eq!(bidi::base_rtl(&crate::decode_controls(s).iter().map(|c| c.0).collect::<String>()), Some(true));
let shared: Vec<char> = "Ø50 \u{05D0}\u{05D1}".chars().collect();
let has = font_mapping(&[&['\u{2300}'][..], &shared].concat());
let lacks = font_mapping(&shared);
assert!(has.has_glyph('\u{2300}') && !lacks.has_glyph('\u{2300}') && !lacks.has_glyph('\u{2205}') && lacks.has_glyph('Ø'));
let with = shape(Some(&has), s, 1.0, 1.0, 0.0, None).unwrap();
let without = shape(Some(&lacks), s, 1.0, 1.0, 0.0, None).unwrap();
// The underline follows "⌀50" wherever the line puts it; nothing else is a stroke.
let underline = |sh: &Shaped| {
assert_eq!(sh.strokes.len(), 1, "{:?}", sh.strokes);
(sh.strokes[0][0].x, sh.strokes[0][1].x)
};
let (x0, x1) = underline(&with);
assert!(x0 > 0.3 * with.width && (x1 - with.width).abs() < 1e-9, "at the right end: {x0}..{x1} of {}", with.width);
let (y0, y1) = underline(&without);
assert!((y0 - x0).abs() < 1e-9 && (y1 - x1).abs() < 1e-9, "{y0}..{y1}, not {x0}..{x1}");
assert!((without.width - with.width).abs() < 1e-9);
}
}
+80 -1
View File
@@ -93,6 +93,18 @@ pub fn decode_controls(text: &str) -> Vec<(char, bool, bool)> {
out
}
/// Characters a font may show in place of `c` when it lacks it, best first: the diameter sign
/// (`%%c`, U+2300), which many TrueType fonts lack, as the empty set (U+2205, what some files
/// store it as) or Ø (U+00D8, in every Latin font). All three read as the diameter sign in
/// drawing text, and any of them beats the font's missing-glyph box (#1608).
pub fn substitutes(c: char) -> &'static [char] {
match c {
'⌀' => &['∅', 'Ø'],
'∅' => &['⌀', 'Ø'],
_ => &[],
}
}
/// The character of a `\U+XXXX` escape (four hex digits) starting at `chars[i]`.
pub(crate) fn unicode_escape(chars: &[char], i: usize) -> Option<char> {
if chars.get(i) != Some(&'\\') || !matches!(chars.get(i + 1), Some('U' | 'u')) || chars.get(i + 2) != Some(&'+') {
@@ -258,7 +270,7 @@ pub fn shape_stroke_dir(text: &str, height: f64, width_factor: f64, oblique: f64
}
/// Draw stroke-font glyph `spec` with its left edge at `x` (`sc` = text height / cap height).
fn draw_stroke_glyph(out: &mut Shaped, spec: &str, x: f64, sc: f64, wf: f64, shear: f64) {
pub(crate) fn draw_stroke_glyph(out: &mut Shaped, spec: &str, x: f64, sc: f64, wf: f64, shear: f64) {
for st in stroke::strokes(spec) {
let pts: Vec<Vec2> = st.iter().map(|(gx, gy)| Vec2::new(x + (gx * sc * wf) + gy * sc * shear, gy * sc)).collect();
if pts.len() == 1 {
@@ -789,6 +801,32 @@ mod tests {
assert_eq!(decode_controls("%%").len(), 2);
}
/// #1608: the diameter sign a font lacks is shown as its empty set or Ø, in that order; no
/// other character has substitutes.
#[test]
fn diameter_sign_substitutes_in_order() {
assert_eq!(substitutes('⌀'), &['∅', 'Ø']);
assert_eq!(substitutes('∅'), &['⌀', 'Ø']);
for c in ['Ø', 'ø', 'A', '°', '\u{E000}'] {
assert!(substitutes(c).is_empty(), "{c:?}");
}
let has = |c: char| c == 'Ø';
assert_eq!(substitutes('⌀').iter().copied().find(|&s| has(s)), Some('Ø'));
let has = |c: char| c == '∅' || c == 'Ø';
assert_eq!(substitutes('⌀').iter().copied().find(|&s| has(s)), Some('∅'));
}
/// The stroke font draws U+2205 (what some files store `%%c` as) as its diameter sign, not
/// as a missing-glyph box or a fallback font's glyph.
#[test]
fn empty_set_is_the_stroke_diameter_sign() {
let a = shape_stroke("\u{2205}50", 1.0, 1.0, 0.0);
assert_eq!(a, shape_stroke("\u{2300}50", 1.0, 1.0, 0.0));
assert_eq!(a, shape_stroke("%%c50", 1.0, 1.0, 0.0));
assert!(a.glyphs.is_empty(), "no fallback glyphs");
assert!((line_width("\u{2205}50", 1.0, 1.0) - a.width).abs() < 1e-9);
}
#[test]
fn line_metrics_scale_with_height() {
let a = layout_line("HELLO", 1.0, 1.0, 0.0);
@@ -847,6 +885,47 @@ mod ttf_tests {
assert!((maxy - 1.0).abs() < 0.1, "cap height ~ text height, got {maxy}");
}
/// #1608: `%%c` in a text style whose TrueType font has neither U+2300 nor U+2205 (Arial,
/// Liberation Sans, Times...) is that font's Ø, not its missing-glyph box; so is U+2205,
/// which some files store the symbol as. Skips cleanly when no such font is installed.
#[test]
fn diameter_sign_in_a_font_without_it_is_its_o_slash() {
let fonts = ["LiberationSans-Regular", "Arial", "Helvetica", "Verdana", "Times New Roman", "LiberationSerif-Regular"];
let Some(face) =
fonts.iter().filter_map(|n| crate::ttf::find(n)).find(|f| !f.has_glyph('\u{2300}') && !f.has_glyph('\u{2205}') && f.has_glyph('Ø'))
else {
return;
};
let o_slash = crate::ttf::shape(&face, "Ø50", 1.0, 1.0, 0.0).unwrap();
for s in ["%%c50", "\u{2300}50", "\u{2205}50"] {
let sh = crate::ttf::shape(&face, s, 1.0, 1.0, 0.0).unwrap();
assert_eq!(sh.glyphs, o_slash.glyphs, "{s}");
assert_eq!(sh.text.first().map(|t| (t.gid, t.ch)), o_slash.text.first().map(|t| (t.gid, t.ch)), "{s}: the PDF glyph");
assert!((crate::ttf::width(&face, s, 1.0, 1.0).unwrap() - o_slash.width).abs() < 1e-9, "{s}");
}
// The same on a line with right-to-left text (the shaped path): the face's Ø, not the
// stroke font's last resort, at the same width. The line keeps the order its own text
// gives it: "⌀50 א" reads right to left (⌀ is bidi-neutral, Ø left-to-right), so the Ø
// is its rightmost glyph, where a font with ⌀ puts the sign; "Ø50 א" reads left to right.
let rtl = crate::complex::shape(Some(&face), "\u{2300}50 \u{5D0}", 1.0, 1.0, 0.0, None).unwrap();
let o_rtl = crate::complex::shape(Some(&face), "Ø50 \u{5D0}", 1.0, 1.0, 0.0, None).unwrap();
let x0 = |g: &[Vec<cadcraft_geom::Vec2>]| g.iter().flatten().map(|p| p.x).fold(f64::MAX, f64::min);
let same_shape = |a: &[Vec<cadcraft_geom::Vec2>], b: &[Vec<cadcraft_geom::Vec2>]| {
let (ax, bx) = (x0(a), x0(b));
a.len() == b.len()
&& a.iter().zip(b).all(|(c, d)| {
c.len() == d.len() && c.iter().zip(d).all(|(p, q)| (p.x - ax - (q.x - bx)).abs() < 1e-9 && (p.y - q.y).abs() < 1e-9)
})
};
// Empty glyphs (the space) keep a slot for text export but have no position to compare.
let rightmost = rtl.glyphs.iter().filter(|g| !g.is_empty()).max_by(|a, b| x0(a).total_cmp(&x0(b))).unwrap();
assert!(same_shape(rightmost, o_slash.glyphs.first().unwrap()), "the face's Ø at the right end");
assert!(same_shape(o_rtl.glyphs.first().unwrap(), o_slash.glyphs.first().unwrap()), "Ø at the left end of a left-to-right line");
assert_eq!(rtl.glyphs.len(), o_rtl.glyphs.len());
assert!((rtl.width - o_rtl.width).abs() < 1e-9);
assert!(rtl.strokes.is_empty(), "no stroke-font glyphs");
}
#[test]
fn stroke_names_are_not_ttf() {
assert!(crate::ttf::find("txt.shx").is_none());
+1 -1
View File
@@ -108,7 +108,7 @@ pub(crate) fn glyph(c: char) -> Option<(f64, &'static str)> {
'~' => (4.0, "0g1h3f4g"),
'°' => (2.0, "1i0h1g2h1i"),
'±' => (4.0, "2e2i 0g4g 0d4d"),
'Ø' | 'ø' | '⌀' => (4.0, "1c0d0h1i3i4h4d3c1c 0c4i"),
'Ø' | 'ø' | '⌀' | '∅' => (4.0, "1c0d0h1i3i4h4d3c1c 0c4i"),
'•' => (2.0, "1d0e1f2e1d 0e2e 1d1f"),
// Original Latin diacritics, composed from our own letter bodies and marks.
'\u{00C0}' => (4.0, concat!("0c2i4c 1f3f", " 1k3j")),
+51 -13
View File
@@ -1361,13 +1361,32 @@ pub(crate) fn fallback_glyph(c: char) -> Option<Arc<GlyphOutline>> {
Some(glyph(&f, c)).filter(|g| g.mapped)
}
/// The glyph of `c` in `face`, or from a fallback font when `face` lacks it.
fn glyph_or_fallback(face: &Face, c: char) -> Arc<GlyphOutline> {
/// The glyph of `c` in `face`, or from a fallback font when `face` lacks it, and the character
/// it shows: a character the face lacks is one of its [`crate::substitutes`] in the face when it
/// has one, before a fallback font is tried.
fn glyph_or_fallback(face: &Face, c: char) -> (Arc<GlyphOutline>, char) {
let g = glyph(face, c);
if g.mapped || c.is_whitespace() {
return g;
return (g, c);
}
fallback_glyph(c).unwrap_or(g)
if let Some(s) = crate::substitutes(c).iter().copied().find(|&s| face.has_glyph(s)) {
return (glyph(face, s), s);
}
(fallback_glyph(c).unwrap_or(g), c)
}
/// The stroke font's glyph of `c`, when no font has it (`g` is a missing-glyph shape): drawn in
/// place of the face's box.
fn stroke_glyph(g: &GlyphOutline, c: char) -> Option<&'static str> {
if g.mapped || c.is_whitespace() {
return None;
}
crate::stroke::glyph(c).map(|(_, spec)| spec)
}
/// Advance of `c` drawn as `g`, or by the stroke font when no font has it.
fn advance(g: &GlyphOutline, c: char, h: f64, wf: f64) -> f64 {
if stroke_glyph(g, c).is_some() { crate::char_advance(c) * h * wf } else { g.advance * h / g.cap * wf }
}
/// The [`crate::TextGlyph`] of a glyph placed like [`place_glyph`] does (its outline index is
@@ -1423,7 +1442,9 @@ pub(crate) fn place_glyph_at(g: &GlyphOutline, origin: Vec2, scale: f64, wf: f64
/// Shape one line with a TrueType face: closed glyph contours grouped per glyph (baseline at
/// y = 0, x from 0) plus `%%u`/`%%o` decorations as strokes. Text height = cap height.
/// Characters the face lacks come from a fallback font, scaled to its own cap height.
/// Characters the face lacks come from a fallback font, scaled to its own cap height; those no
/// font has are drawn by the stroke font when it has them (as strokes), else as the face's
/// missing-glyph shape.
pub fn shape(face: &Face, s: &str, height: f64, width_factor: f64, oblique: f64) -> Option<Shaped> {
shape_dir(face, s, height, width_factor, oblique, None)
}
@@ -1451,14 +1472,16 @@ pub fn shape_dir(face: &Face, s: &str, height: f64, width_factor: f64, oblique:
if crate::bidi::is_format_control(c) {
continue;
}
let g = glyph_or_fallback(face, c);
if !c.is_whitespace()
let (g, shown) = glyph_or_fallback(face, c);
if let Some(spec) = stroke_glyph(&g, c) {
crate::draw_stroke_glyph(&mut out, spec, x, h / crate::stroke::CAP, wf, shear);
} else if !c.is_whitespace()
&& let Some(contours) = place_glyph_budgeted(&g, x, h, wf, shear, &mut points_left)
{
// Even an empty mapped glyph needs a valid outline slot for text export.
out.push_glyph(contours, text_glyph(&g, c, x, h, wf, shear));
out.push_glyph(contours, text_glyph(&g, shown, x, h, wf, shear));
}
let adv = g.advance * h / g.cap * wf;
let adv = advance(&g, c, h, wf);
spans.push((x, x + adv, under, over));
x += adv;
}
@@ -1480,10 +1503,7 @@ pub fn width(face: &Face, s: &str, height: f64, width_factor: f64) -> Option<f64
crate::decode_controls(s)
.iter()
.filter(|(c, _, _)| !crate::bidi::is_format_control(*c))
.map(|(c, _, _)| {
let g = glyph_or_fallback(face, *c);
g.advance * height / g.cap * wf
})
.map(|(c, _, _)| advance(&glyph_or_fallback(face, *c).0, *c, height, wf))
.sum(),
)
}
@@ -1496,6 +1516,24 @@ pub fn layout_line(face: &Face, s: &str, height: f64, width_factor: f64, oblique
Some(Run { strokes, width: sh.width })
}
#[cfg(test)]
mod missing_glyph_tests {
use super::*;
/// A character no font has is drawn by the stroke font when it has it (with the stroke
/// font's advance), else as the face's missing-glyph shape.
#[test]
fn stroke_font_draws_what_no_font_has() {
let missing = GlyphOutline { advance: 500.0, cap: 700.0, ..Default::default() };
assert!(stroke_glyph(&missing, '\u{2300}').is_some());
assert!((advance(&missing, '\u{2300}', 2.0, 0.5) - crate::char_advance('\u{2300}')).abs() < 1e-9);
assert!(stroke_glyph(&missing, '\u{E000}').is_none() && stroke_glyph(&missing, ' ').is_none());
assert!((advance(&missing, '\u{E000}', 2.0, 0.5) - 500.0 * 2.0 / 700.0 * 0.5).abs() < 1e-9);
let mapped = GlyphOutline { mapped: true, ..missing };
assert!(stroke_glyph(&mapped, '\u{2300}').is_none());
}
}
#[cfg(test)]
mod family_tests {
use super::*;
+2 -1
View File
@@ -45,9 +45,10 @@ pub fn norm_angle(a: f64) -> f64 {
}
/// Counter-clockwise sweep from `start` to `end`, in `(0, 2π]`.
/// Only (numerically) equal angles give a full turn; tiny genuine sweeps are kept.
pub fn ccw_sweep(start: f64, end: f64) -> f64 {
let s = norm_angle(end - start);
if s <= EPS { TAU } else { s }
if s <= 1e-14 { TAU } else { s }
}
/// True when angle `a` lies on the CCW sweep from `start` to `end` (inclusive, with tolerance).
+72 -13
View File
@@ -33,6 +33,9 @@ pub struct Boundary {
pub islands: Vec<Island>,
/// Indices into the input polylines that make up `outer`, ascending.
pub outer_sources: Vec<usize>,
/// The input polyline of each edge of `outer` (`outer[i]` to the next vertex), `None` for a
/// gap bridged with HPGAPTOL.
pub outer_edges: Vec<Option<usize>>,
}
/// One island: the outside outline of a connected group of curves.
@@ -42,6 +45,8 @@ pub struct Island {
pub outline: Vec<Vec2>,
/// Indices into the input polylines that make up the group, ascending.
pub sources: Vec<usize>,
/// The input polyline of each edge of `outline`, as [`Boundary::outer_edges`].
pub edges: Vec<Option<usize>>,
}
#[expect(
@@ -62,6 +67,8 @@ struct Graph {
src: Vec<(usize, usize)>,
/// The input polyline of every edge (lower vertex index first).
edge_src: HashMap<(usize, usize), usize>,
/// Edges that bridge a gap between curve ends (HPGAPTOL), lower vertex index first.
gap: std::collections::HashSet<(usize, usize)>,
}
/// Records the crossing of segments `i` and `j`, if any, as split parameters on both.
@@ -210,7 +217,7 @@ fn build_with(polys: &[Vec<Vec2>], tol: f64, find_splits: impl Fn(&[(Vec2, Vec2)
let bb = Bounds2::from_points(segs.iter().flat_map(|(a, b)| [*a, *b]));
let n = segs.len();
let splits = find_splits(&segs, &bb)?;
let mut g = Graph { pts: Vec::new(), adj: Vec::new(), src: Vec::with_capacity(n), edge_src: HashMap::new() };
let mut g = Graph { pts: Vec::new(), adj: Vec::new(), src: Vec::with_capacity(n), edge_src: HashMap::new(), gap: Default::default() };
let mut index: HashMap<(i64, i64), usize> = HashMap::new();
let mut vid = |p: Vec2, g: &mut Graph| -> usize {
let k = key(p, bb.min, tol);
@@ -295,6 +302,7 @@ fn build_gap(polys: &[Vec<Vec2>], tol: f64, gap: f64) -> Option<Graph> {
if let Some(k) = owner {
g.edge_src.insert((u.min(v), u.max(v)), k);
}
g.gap.insert((u.min(v), u.max(v)));
if let Some(f) = joined.get_mut(i) {
*f = true;
}
@@ -342,6 +350,17 @@ fn points(g: &Graph, ids: &[usize]) -> Option<Vec<Vec2>> {
ids.iter().map(|&i| g.pts.get(i).copied()).collect()
}
/// The input polyline of each edge of the closed loop `ids` (`None` for a bridged gap).
fn edge_owners(g: &Graph, ids: &[usize]) -> Vec<Option<usize>> {
ids.iter()
.zip(ids.iter().cycle().skip(1))
.map(|(&u, &v)| {
let k = (u.min(v), u.max(v));
if g.gap.contains(&k) { None } else { g.edge_src.get(&k).copied() }
})
.collect()
}
/// The face around `p`, as vertex indices (counter-clockwise).
#[expect(clippy::many_single_char_names, reason = "Ray/edge traversal keeps conventional graph and point notation.")]
fn outer_face(g: &Graph, p: Vec2) -> Option<Vec<usize>> {
@@ -420,12 +439,12 @@ fn prune(g: &Graph) -> Graph {
}
}
}
Graph { pts: g.pts.clone(), adj, src: Vec::new(), edge_src: HashMap::new() }
Graph { pts: g.pts.clone(), adj, src: Vec::new(), edge_src: g.edge_src.clone(), gap: g.gap.clone() }
}
/// The outline of the outside of a group of curves on cycles, traced counter-clockwise from its
/// leftmost (then lowest) vertex `u`, giving up after `steps` edges.
fn outside(core: &Graph, u: usize, steps: usize) -> Option<Vec<Vec2>> {
fn outside(core: &Graph, u: usize, steps: usize) -> Option<(Vec<Vec2>, Vec<Option<usize>>)> {
let pu = *core.pts.get(u)?;
// Every neighbour lies to the right of the leftmost vertex; the one turned furthest
// counter-clockwise has the outside of the group on its left.
@@ -436,9 +455,9 @@ fn outside(core: &Graph, u: usize, steps: usize) -> Option<Vec<Vec2>> {
})
};
let w = core.adj.get(u).into_iter().flatten().filter_map(|w| Some((signed(w)?, *w))).max_by(|a, b| a.0.total_cmp(&b.0)).map(|(_, w)| w)?;
let mut lp = trace(core, u, w, steps).and_then(|ids| points(core, &ids))?;
lp.reverse();
Some(lp)
let mut ids = trace(core, u, w, steps)?;
ids.reverse();
Some((points(core, &ids)?, edge_owners(core, &ids)))
}
/// Outlines of the groups of curves inside the face `outer` (vertex indices into `g`).
@@ -497,7 +516,7 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option<Vec<Island>> {
continue;
}
let steps = edges.get(&c).copied().unwrap_or(0).saturating_add(4);
let Some(lp) = outside(&core, u, steps) else { continue };
let Some((lp, edges)) = outside(&core, u, steps) else { continue };
let area = shoelace(&lp);
let ib = Bounds2::from_points(lp.iter().copied());
if lp.len() < 3 || !area.is_finite() || area <= 0.0 || !ob.contains_box(&ib) {
@@ -511,7 +530,7 @@ fn islands(g: &Graph, outer: &[usize], p: Vec2) -> Option<Vec<Island>> {
let mut src = sources.remove(&c).unwrap_or_default();
src.sort_unstable();
src.dedup();
out.push(Island { outline: lp, sources: src });
out.push(Island { outline: lp, sources: src, edges });
}
Some(out)
}
@@ -619,8 +638,14 @@ pub fn enclosing_loop(polys: &[Vec<Vec2>], p: Vec2, tol: f64) -> Option<Vec<Vec2
/// [`enclosing_loop`], with gaps of up to `gap` between curve ends closed (HPGAPTOL).
pub fn enclosing_loop_gap(polys: &[Vec<Vec2>], p: Vec2, tol: f64, gap: f64) -> Option<Vec<Vec2>> {
enclosing_loop_edges_gap(polys, p, tol, gap).map(|(lp, _)| lp)
}
/// [`enclosing_loop_gap`] with the input polyline of each edge, as [`Boundary::outer_edges`].
pub fn enclosing_loop_edges_gap(polys: &[Vec<Vec2>], p: Vec2, tol: f64, gap: f64) -> Option<(Vec<Vec2>, Vec<Option<usize>>)> {
let g = build_gap(polys, tol, gap)?;
points(&g, &outer_face(&g, p)?)
let ids = outer_face(&g, p)?;
Some((points(&g, &ids)?, edge_owners(&g, &ids)))
}
/// The closed loop enclosing `p` plus the islands inside it, or `None` when `p` isn't enclosed.
@@ -638,14 +663,20 @@ pub fn boundary_at_gap(polys: &[Vec<Vec2>], p: Vec2, tol: f64, gap: f64) -> Opti
ids.iter().zip(ids.iter().cycle().skip(1)).filter_map(|(&u, &v)| g.edge_src.get(&(u.min(v), u.max(v))).copied()).collect();
outer_sources.sort_unstable();
outer_sources.dedup();
Some(Boundary { outer, islands, outer_sources })
let outer_edges = edge_owners(&g, &ids);
Some(Boundary { outer, islands, outer_sources, outer_edges })
}
/// The outside outline of curves that together enclose an area (counter-clockwise, dangling
/// ends removed), or `None` when they enclose nothing or form more than one separate group.
/// Gaps of up to `gap` between curve ends are closed (HPGAPTOL).
#[expect(clippy::float_cmp, reason = "Exact x equality is required for the deterministic lexicographic tie-break.")]
pub fn outline(polys: &[Vec<Vec2>], tol: f64, gap: f64) -> Option<Vec<Vec2>> {
outline_edges(polys, tol, gap).map(|(lp, _)| lp)
}
/// [`outline`] with the input polyline of each edge, as [`Boundary::outer_edges`].
#[expect(clippy::float_cmp, reason = "Exact x equality is required for the deterministic lexicographic tie-break.")]
pub fn outline_edges(polys: &[Vec<Vec2>], tol: f64, gap: f64) -> Option<(Vec<Vec2>, Vec<Option<usize>>)> {
let g = build_gap(polys, tol, gap)?;
let core = prune(&g);
let comp = components(&core);
@@ -667,8 +698,8 @@ pub fn outline(polys: &[Vec<Vec2>], tol: f64, gap: f64) -> Option<Vec<Vec2>> {
start = Some(u);
}
}
let lp = outside(&core, start?, edges.saturating_add(4))?;
(lp.len() >= 3 && shoelace(&lp) > 0.0).then_some(lp)
let (lp, owners) = outside(&core, start?, edges.saturating_add(4))?;
(lp.len() >= 3 && shoelace(&lp) > 0.0).then_some((lp, owners))
}
/// A point strictly inside a closed polygon (either orientation), for re-finding the face a
@@ -1075,6 +1106,34 @@ mod tests {
assert!(interior_point(&[Vec2::new(f64::NAN, 0.0); 4]).is_none());
}
#[test]
fn edges_name_their_input_polyline_and_bridged_gaps_none() {
// A square of four separate sides; the right side stops short of the top (a gap).
let sides = vec![
vec![Vec2::new(0.0, 0.0), Vec2::new(10.0, 0.0)],
vec![Vec2::new(10.0, 0.0), Vec2::new(10.0, 9.9)],
vec![Vec2::new(10.0, 10.0), Vec2::new(0.0, 10.0)],
vec![Vec2::new(0.0, 10.0), Vec2::new(0.0, 0.0)],
];
let b = boundary_at_gap(&sides, Vec2::new(5.0, 5.0), 1e-9, 0.5).unwrap();
assert_eq!(b.outer_edges.len(), b.outer.len());
// Each edge names the side it lies on; the bridged gap names none.
for (i, e) in b.outer_edges.iter().enumerate() {
let (a, c) = (b.outer[i], b.outer[(i + 1) % b.outer.len()]);
match e {
Some(k) => {
let s = &sides[*k];
let on = |q: Vec2| crate::Line::new(s[0], s[1]).closest(q).dist(q) < 1e-9;
assert!(on(a) && on(c), "edge {i} not on side {k}");
}
None => assert!(a.dist(c) < 0.5 + 1e-9, "only the gap is unnamed"),
}
}
assert_eq!(b.outer_edges.iter().filter(|e| e.is_none()).count(), 1);
let (lp, edges) = outline_edges(&sides, 1e-9, 0.5).unwrap();
assert_eq!(lp.len(), edges.len());
}
#[test]
fn gap_tolerance_closes_small_gaps() {
// Four lines with 0.5 gaps at two corners.
+13
View File
@@ -432,3 +432,16 @@ fn open_polyline_centroid_ignores_last_bulge() {
let after = pl.centroid().unwrap();
assert!(before.near(after, 1e-9), "{before:?} -> {after:?}");
}
#[test]
fn tiny_arc_sweep_is_not_a_full_circle() {
for x in [0.0, 1.0, 5.5] {
assert!(close(ccw_sweep(x, x), TAU));
}
assert!((ccw_sweep(0.0, 5e-10) - 5e-10).abs() < 1e-15, "{}", ccw_sweep(0.0, 5e-10));
let a = Arc::new(Vec2::new(0.0, 0.0), 1e6, 0.0, 5e-10);
assert!((a.len() - 5e-4).abs() < 1e-6, "{}", a.len());
assert!(a.contains_angle(2.5e-10));
assert!(!a.contains_angle(1.0));
assert!(a.mid_point().near(Vec2::new(1e6, 0.0), 1e-2));
}
+69
View File
@@ -66,6 +66,75 @@ pub(crate) fn named_ucs<'a>(
ucss.iter().find(|u| u.name.eq_ignore_ascii_case(name) && is_named_frame(u, origin, x, y))
}
/// The drawing's UCSs by name with its ASCII letters lower-cased, each name with its positions in
/// table order, so the named UCS of each of many layouts is found without scanning every UCS: a
/// file of N layouts each naming one of N UCSs cost N² name comparisons (#1924).
pub(crate) struct UcsNames<'a> {
ucss: &'a [cadcraft_doc::Ucs],
at: std::collections::BTreeMap<String, Vec<usize>>,
}
impl<'a> UcsNames<'a> {
pub(crate) fn new(ucss: &'a [cadcraft_doc::Ucs]) -> Self {
let mut at: std::collections::BTreeMap<String, Vec<usize>> = std::collections::BTreeMap::new();
for (i, u) in ucss.iter().enumerate() {
at.entry(u.name.to_ascii_lowercase()).or_default().push(i);
}
UcsNames { ucss, at }
}
/// What [`named_ucs`] finds: the first UCS named `name` (without case) whose frame is
/// `origin`, `x`, `y`.
pub(crate) fn named(
&self,
name: &str,
origin: cadcraft_geom::Vec3,
x: cadcraft_geom::Vec3,
y: cadcraft_geom::Vec3,
) -> Option<&'a cadcraft_doc::Ucs> {
let name = name.trim();
if name.is_empty() {
return None;
}
let ucss = self.ucss;
self.at.get(&name.to_ascii_lowercase())?.iter().filter_map(|&i| ucss.get(i)).find(|u| is_named_frame(u, origin, x, y))
}
}
/// The entries of a list (a table's records, a drawing's styles), by name with its ASCII letters
/// lower-cased, each name at the position of its first entry. A later record of a name replaces
/// the first, which keeps its place and takes the later record's name. Each record or lookup is
/// then a map lookup, not a scan of the list: a file of N records, or of N objects each naming one
/// of N styles, cost N² name comparisons (#1924). Ordered by name rather than hashed, so its cost
/// does not depend on hash keys.
#[derive(Default)]
pub(crate) struct ByName(std::collections::BTreeMap<String, usize>);
impl ByName {
/// The entries the list starts with; the first of a name is the one kept.
pub(crate) fn new<T>(list: &[T], name: impl Fn(&T) -> &str) -> Self {
ByName(list.iter().enumerate().rev().map(|(i, t)| (name(t).to_ascii_lowercase(), i)).collect())
}
/// Put `item`, named `name`, in place of the first entry of that name, else at the end.
pub(crate) fn put<T>(&mut self, list: &mut Vec<T>, name: &str, item: T) {
let key = name.to_ascii_lowercase();
match self.0.get(&key).and_then(|&i| list.get_mut(i)) {
Some(x) => *x = item,
None => {
self.0.insert(key, list.len());
list.push(item);
}
}
}
/// The position of the first entry named `name` (ignoring ASCII case), while the list has
/// changed only through [`ByName::put`] since [`ByName::new`].
pub(crate) fn position(&self, name: &str) -> Option<usize> {
self.0.get(&name.to_ascii_lowercase()).copied()
}
}
/// Whether `x` and `y` can be a UCS's axes: finite, not zero and not along each other (relative
/// to their lengths, so short but square axes are fine). Read and written by the same rule.
pub(crate) fn usable_axes(x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool {
+6 -3
View File
@@ -453,9 +453,12 @@ fn attribs(d: &Drawing, ins: &Insert, values: &[(String, String)]) -> Vec<Attrib
}
/// What a MULTILEADER record points at in the file being written.
pub(crate) struct Refs {
pub(crate) struct Refs<'a> {
/// MLEADERSTYLE handle.
pub style: String,
/// The drawing's style of the multileader's style name (the first of that name, ignoring
/// case), when it has one.
pub style_def: Option<&'a MLeaderStyle>,
/// STYLE record handle of the text.
pub text_style: Option<String>,
/// BLOCK_RECORD handle of the content block.
@@ -463,7 +466,7 @@ pub(crate) struct Refs {
}
/// The groups of a MULTILEADER record after its `AcDbMLeader` marker.
pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec<Tag> {
pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs<'_>) -> Vec<Tag> {
let mut t: Vec<Tag> = Vec::new();
let s = |t: &mut Vec<Tag>, c: i32, v: &str| t.push(Tag::s(c, v));
let f = |t: &mut Vec<Tag>, c: i32, v: f64| t.push(Tag::f(c, v));
@@ -473,7 +476,7 @@ pub(crate) fn entity_tags(d: &Drawing, m: &MLeader, r: &Refs) -> Vec<Tag> {
t.push(Tag::f(c + 10, v.y));
t.push(Tag::f(c + 20, v.z));
};
let style = d.mleader_styles.iter().find(|x| x.name.eq_ignore_ascii_case(&m.style)).cloned().unwrap_or_default();
let style = r.style_def.cloned().unwrap_or_default();
// Block content wins over text when an entity has both (DXF has one content type).
let block = m.block.as_ref().zip(r.block.as_ref());
let text = if block.is_some() { None } else { m.text.as_ref() };
+16 -9
View File
@@ -286,7 +286,9 @@ fn read_style(tags: &[Tag]) -> Option<MLineStyle> {
let mut fill = Color::ByLayer;
for t in body {
match t.code {
2 => st.name = t.str(),
// Trimmed, as the writer writes it and as multilines look it up: a padded name kept
// as read was missed by its multilines' lookup, so a save wrote a second style of it.
2 => st.name = t.str().trim().to_string(),
3 => st.description = t.str(),
70 => flags = t.i64(),
51 => st.start_caps.angle = t.f64().to_radians(),
@@ -345,11 +347,11 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
}
});
}
// A later style of a name replaces the first.
let mut names = crate::dxf_ext::ByName::new(&d.mline_styles, |s| &s.name);
for st in styles {
match d.mline_styles.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&st.name)) {
Some(x) => *x = st,
None => d.mline_styles.push(st),
}
let name = st.name.clone();
names.put(&mut d.mline_styles, &name, st);
}
let by_name: HashMap<String, MLineStyle> = d.mline_styles.iter().map(|s| (key(&s.name), s.clone())).collect();
fill(&mut d.model, &by_name);
@@ -384,12 +386,14 @@ pub(crate) struct Plan {
pub dict: String,
/// Each style and its MLINESTYLE handle.
styles: Vec<(MLineStyle, String)>,
/// The positions of the styles by name.
names: crate::dxf_ext::ByName,
}
impl Plan {
/// The MLINESTYLE handle of style `name` (STANDARD's when it is missing).
pub fn handle(&self, name: &str) -> String {
let find = |n: &str| self.styles.iter().find(|(s, _)| s.name.eq_ignore_ascii_case(n.trim())).map(|(_, h)| h.clone());
let find = |n: &str| self.names.position(n.trim()).and_then(|i| self.styles.get(i)).map(|(_, h)| h.clone());
find(name).or_else(|| find(STANDARD_MLINE_STYLE)).unwrap_or_else(|| "0".into())
}
}
@@ -400,15 +404,18 @@ pub(crate) fn plan<'a>(d: &Drawing, every: impl Iterator<Item = &'a Entity>, mut
if !list.iter().any(|s| s.name.eq_ignore_ascii_case(STANDARD_MLINE_STYLE)) {
list.insert(0, MLineStyle::default());
}
let mut names = crate::dxf_ext::ByName::new(&list, |s| &s.name);
for e in every {
if let EntityKind::MLine(m) = &e.kind
&& !list.iter().any(|s| s.name.eq_ignore_ascii_case(m.style.trim()))
&& names.position(m.style.trim()).is_none()
{
list.push(MLineStyle { name: m.style.trim().to_string(), ..m.def.clone() });
names.put(&mut list, m.style.trim(), MLineStyle { name: m.style.trim().to_string(), ..m.def.clone() });
}
}
let dict = new_handle();
Plan { dict, styles: list.into_iter().filter(|s| !s.name.trim().is_empty()).map(|s| (s, new_handle())).collect() }
let styles: Vec<(MLineStyle, String)> = list.into_iter().filter(|s| !s.name.trim().is_empty()).map(|s| (s, new_handle())).collect();
let names = crate::dxf_ext::ByName::new(&styles, |(s, _)| &s.name);
Plan { dict, styles, names }
}
/// The `ACAD_MLINESTYLE` dictionary (owned by the root dictionary `root`) and its styles.
+63 -50
View File
@@ -96,15 +96,15 @@ fn is_pointer(code: i32) -> bool {
}
/// The records of a run of tags: (type, index of the record's `0` group, groups after it).
fn split(tags: &[Tag]) -> Vec<(String, usize, &[Tag])> {
fn split(tags: &[Tag]) -> Recs<'_> {
let mut out = Vec::new();
let mut open: Option<(String, usize)> = None;
let mut open: Option<(&str, usize)> = None;
for (i, t) in tags.iter().enumerate() {
if t.code == 0 {
if let Some((k, s)) = open.take() {
out.push((k, s, tags.get(s + 1..i).unwrap_or(&[])));
}
open = Some((t.str(), i));
open = Some((t.str_ref().unwrap_or_default(), i));
}
}
if let Some((k, s)) = open {
@@ -113,7 +113,7 @@ fn split(tags: &[Tag]) -> Vec<(String, usize, &[Tag])> {
out
}
type Recs<'a> = Vec<(String, usize, &'a [Tag])>;
type Recs<'a> = Vec<(&'a str, usize, &'a [Tag])>;
/// A record's handle, owner, reactors and extension dictionary (groups before its xdata).
#[derive(Default)]
@@ -131,23 +131,29 @@ fn head(tags: &[Tag]) -> Head {
for t in tags.iter().take_while(|t| t.code < 1000) {
match (t.code, group.as_deref()) {
(102, _) => {
let v = t.str();
group = v.trim().strip_prefix('{').map(str::to_string);
group = t.str_ref().and_then(|v| v.trim().strip_prefix('{')).map(str::to_string);
h.has_reactors |= group.as_deref() == Some("ACAD_REACTORS");
}
(_, Some("ACAD_REACTORS")) => h.reactors.push(norm(&t.str())),
(_, Some("ACAD_REACTORS")) => h.reactors.extend(t.str_ref().map(norm)),
(_, Some("ACAD_XDICTIONARY")) if h.xdict.is_none() => {
h.xdict = Some(norm(&t.str()));
h.xdict = t.str_ref().map(norm);
}
(_, Some(_)) => {}
(5 | 105, None) if h.handle.is_none() => h.handle = Some(norm(&t.str())),
(330, None) if h.owner.is_none() => h.owner = Some(norm(&t.str())),
(5 | 105, None) if h.handle.is_none() => h.handle = t.str_ref().map(norm),
(330, None) if h.owner.is_none() => h.owner = t.str_ref().map(norm),
_ => {}
}
}
h
}
/// Whether a record has any `102` group (reactors, an extension dictionary or an application's
/// own group). Without one [`head`] finds no reactors and no extension dictionary, so the scan
/// and its handle text are spared: most entities of a large drawing have none (#1076).
fn has_groups(tags: &[Tag]) -> bool {
tags.iter().take_while(|t| t.code < 1000).any(|t| t.code == 102)
}
fn val(tags: &[Tag], code: i32) -> Option<String> {
tags.iter().take_while(|t| t.code < 1000).find(|t| t.code == code).map(Tag::str)
}
@@ -190,13 +196,13 @@ fn identities(tables: &Recs, blocks: &Recs, objects: &Recs) -> HashMap<String, F
};
for (kind, _, t) in tables {
let name = up(&val(t, 2).unwrap_or_default());
if kind == "TABLE" || !name.is_empty() {
put(head(t).handle, (if kind == "TABLE" { "TABLE".into() } else { kind.clone() }, name));
if *kind == "TABLE" || !name.is_empty() {
put(head(t).handle, (if *kind == "TABLE" { "TABLE".into() } else { kind.to_string() }, name));
}
}
let mut block = String::new();
for (kind, _, t) in blocks {
match kind.as_str() {
match *kind {
"BLOCK" => {
block = up(&val(t, 2).unwrap_or_default());
put(head(t).handle, ("BLOCK".into(), block.clone()));
@@ -207,7 +213,7 @@ fn identities(tables: &Recs, blocks: &Recs, objects: &Recs) -> HashMap<String, F
}
let Some((_, _, root)) = objects.first().filter(|(k, _, _)| is_dictionary(k)) else { return out };
put(head(root).handle, ("NOD".into(), String::new()));
let by_handle: HashMap<String, (&str, &[Tag])> = objects.iter().filter_map(|(k, _, t)| Some((head(t).handle?, (k.as_str(), *t)))).rev().collect();
let by_handle: HashMap<String, (&str, &[Tag])> = objects.iter().filter_map(|(k, _, t)| Some((head(t).handle?, (*k, *t)))).rev().collect();
for (key, h) in entries(root) {
put(Some(h.clone()), ("NOD".into(), up(&key)));
if let Some((k, t)) = by_handle.get(&h)
@@ -232,7 +238,7 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec<RawTag> {
let len = rest.get(i + 1..).map_or(0, |r| r.iter().position(|t| t.code == 1001).unwrap_or(r.len()));
let chunk = rest.get(i..i + 1 + len).unwrap_or(&[]);
i += 1 + len;
let app = up(&first.str());
let app = first.str_ref().map(up).unwrap_or_default();
let own = OWN_APPS.contains(&app.as_str()) || (app == "ACAD" && matches!(kind, "DIMENSION" | "DIMSTYLE"));
if app.is_empty() || own || out.len() + chunk.len() > MAX_XDATA_GROUPS {
continue;
@@ -240,10 +246,10 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec<RawTag> {
let mut depth = 0i32;
let mut ok = true;
for t in chunk.iter().skip(1) {
match (t.code, t.str().trim()) {
match (t.code, t.str_ref().map(str::trim)) {
(c, _) if c < 1000 => ok = false,
(1002, "{") => depth += 1,
(1002, "}") => {
(1002, Some("{")) => depth += 1,
(1002, Some("}")) => {
depth -= 1;
ok &= depth >= 0;
}
@@ -259,7 +265,7 @@ fn foreign_xdata(kind: &str, tags: &[Tag]) -> Vec<RawTag> {
/// The groups of an entity's AcDbEntity subclass (after `100 AcDbEntity`, up to the next `100`).
fn entity_groups(tags: &[Tag]) -> &[Tag] {
let Some(start) = tags.iter().position(|t| t.code == 100 && t.str().trim() == "AcDbEntity") else { return &[] };
let Some(start) = tags.iter().position(|t| t.code == 100 && t.str_ref().is_some_and(|s| s.trim() == "AcDbEntity")) else { return &[] };
let rest = tags.get(start + 1..).unwrap_or(&[]);
let end = rest.iter().position(|t| t.code == 100 || t.code >= 1000).unwrap_or(rest.len());
rest.get(..end).unwrap_or(&[])
@@ -268,7 +274,7 @@ fn entity_groups(tags: &[Tag]) -> &[Tag] {
/// What an entity record (`entity`) or a table record carries beyond the model; reactors and
/// the extension dictionary only when kept (`kept`).
fn extra(kind: &str, tags: &[Tag], entity: bool, unknown: bool, kept: &HashSet<String>) -> ForeignExtra {
let h = head(tags);
let h = if has_groups(tags) { head(tags) } else { Head::default() };
let mut x = ForeignExtra {
xdict: h.xdict.filter(|x| kept.contains(x)).and_then(|x| handle(&x)),
reactors: h.reactors.iter().filter(|r| kept.contains(*r)).filter_map(|r| handle(r)).collect(),
@@ -334,7 +340,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
// Objects by handle: the first of each, and none that has an entity's handle.
let mut by_handle: HashMap<String, usize> = HashMap::new();
for (i, (_, _, t)) in objects.iter().enumerate() {
if let Some(h) = head(t).handle.filter(|h| handle(h).is_some() && !ents.contains_key(h)) {
if let Some(h) = head(t).handle.filter(|h| handle(h).is_some_and(|hh| !ents.contains_key(&hh))) {
by_handle.entry(h).or_insert(i);
}
}
@@ -347,7 +353,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
let Some((_, _, t)) = objects.get(k) else { return false };
let hd = head(t);
let (Some(h), Some(o)) = (hd.handle, hd.owner) else { return false };
!by_handle.contains_key(&o) && xdict_of.get(&o) == Some(&h) && (ents.contains_key(&o) || ids.contains_key(&o))
!by_handle.contains_key(&o) && xdict_of.get(&o) == Some(&h) && (handle(&o).is_some_and(|oh| ents.contains_key(&oh)) || ids.contains_key(&o))
};
let memo = retained_objects(&objects, &ents, &ids, &by_handle, root.as_deref(), &root_entries, &xdict_of);
let mut f = Foreign::default();
@@ -367,18 +373,17 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
f.dictionary.push((key, h));
}
kept.insert(h.hex());
f.objects.push(ForeignObject { handle: h, kind: kind.clone(), tags });
f.objects.push(ForeignObject { handle: h, kind: kind.to_string(), tags });
}
// Extras of entities, tables, table records and blocks.
let mut xdata_of: HashMap<Handle, Vec<RawTag>> = HashMap::new();
for (kind, _, t) in blocks.iter().chain(&entities) {
if matches!(kind.as_str(), "BLOCK" | "ENDBLK") {
if matches!(*kind, "BLOCK" | "ENDBLK") {
continue;
}
let Some(h) = head(t).handle else { continue };
let Some(&unknown) = ents.get(&h) else { continue };
let Some(hh) = head(t).handle.as_deref().and_then(handle) else { continue };
let Some(&unknown) = ents.get(&hh) else { continue };
let mut x = extra(kind, t, true, unknown, &kept);
let Some(hh) = handle(&h) else { continue };
// Xdata belongs to the entity itself (it follows the entity's copies).
let xd = std::mem::take(&mut x.xdata);
if !xd.is_empty() {
@@ -389,9 +394,9 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
}
}
put_xdata(d, xdata_of);
for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| k == "BLOCK")) {
for (kind, _, t) in tables.iter().chain(blocks.iter().filter(|(k, _, _)| *k == "BLOCK")) {
let Some(key) = head(t).handle.and_then(|h| ids.get(&h).cloned()) else { continue };
let x = extra(kind, t, kind == "BLOCK", false, &kept);
let x = extra(kind, t, *kind == "BLOCK", false, &kept);
if !x.is_empty() {
f.records.entry(key).or_insert(x);
}
@@ -405,7 +410,7 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
// A proxy's class is the one its group 91 numbers in the file's CLASSES: keep it too, and the
// file's class order, by which saving renumbers the proxy.
let class_order: Vec<String> =
classes.iter().filter(|(k, _, _)| k == "CLASS").take(MAX_OBJECTS).map(|(_, _, t)| up(&val(t, 1).unwrap_or_default())).collect();
classes.iter().filter(|(k, _, _)| *k == "CLASS").take(MAX_OBJECTS).map(|(_, _, t)| up(&val(t, 1).unwrap_or_default())).collect();
let mut proxies = false;
let proxy_tags = f.objects.iter().filter(|o| is_proxy(&o.kind)).map(|o| &o.tags);
let proxy_tags = proxy_tags.chain(all_entities(d).filter_map(|e| match &e.kind {
@@ -419,11 +424,11 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
}
}
if proxies {
f.complete_class_table = classes.iter().filter(|(k, _, _)| k == "CLASS").count() <= MAX_OBJECTS;
f.complete_class_table = classes.iter().filter(|(k, _, _)| *k == "CLASS").count() <= MAX_OBJECTS;
f.class_order = class_order;
}
for (kind, _, t) in &classes {
if kind == "CLASS" && (f.complete_class_table || val(t, 1).is_some_and(|n| types.contains(&up(&n)))) && f.classes.len() < MAX_OBJECTS {
if *kind == "CLASS" && (f.complete_class_table || val(t, 1).is_some_and(|n| types.contains(&up(&n)))) && f.classes.len() < MAX_OBJECTS {
f.classes.push(t.iter().map(raw).collect());
}
}
@@ -459,10 +464,16 @@ pub(crate) fn read(secs: &[SectionRef<'_>], d: &mut Drawing) {
}
// Added after the version: registered applications alone are no kept objects whose groups
// the DWG writer must read as the file's version, and nearly every file has some (ACAD).
let appids = tables.iter().filter(|(k, _, _)| k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string());
let appids = tables.iter().filter(|(k, _, _)| *k == "APPID").filter_map(|(_, _, t)| val(t, 2)).map(|n| n.trim().to_string());
f.appids = appids.take(MAX_OBJECTS).collect();
// The file's handles of the objects CADCraft writes itself (AutoLISP's `handent`).
f.handles = ids.iter().filter(|(h, _)| !ents.contains_key(*h)).filter_map(|(h, k)| Some((handle(h)?, k.clone()))).take(MAX_OBJECTS).collect();
f.handles = ids
.iter()
.filter_map(|(h, k)| Some((handle(h)?, k)))
.filter(|(h, _)| !ents.contains_key(h))
.map(|(h, k)| (h, k.clone()))
.take(MAX_OBJECTS)
.collect();
if !f.is_empty() || !f.handles.is_empty() {
d.foreign = Arc::new(f);
}
@@ -478,22 +489,22 @@ fn file_version(secs: &[SectionRef<'_>]) -> Option<String> {
(!value.is_empty()).then(|| value.to_string())
}
fn entity_types(drawing: &Drawing) -> HashMap<String, bool> {
fn entity_types(drawing: &Drawing) -> HashMap<Handle, bool> {
let mut types = HashMap::new();
for entity in all_entities(drawing) {
types.entry(entity.handle.hex()).or_insert(matches!(entity.kind, EntityKind::Unknown(_)));
types.entry(entity.handle).or_insert(matches!(entity.kind, EntityKind::Unknown(_)));
}
types
}
fn extension_dictionaries(
tables: &[(String, usize, &[Tag])],
blocks: &[(String, usize, &[Tag])],
entities: &[(String, usize, &[Tag])],
tables: &[(&str, usize, &[Tag])],
blocks: &[(&str, usize, &[Tag])],
entities: &[(&str, usize, &[Tag])],
) -> HashMap<String, String> {
let mut dictionaries = HashMap::new();
for (kind, _, tags) in tables.iter().chain(blocks).chain(entities) {
if kind == "ENDBLK" {
if *kind == "ENDBLK" || !has_groups(tags) {
continue;
}
let header = head(tags);
@@ -516,8 +527,8 @@ fn root_key_index(root_entries: &[(String, String)]) -> HashMap<&str, &str> {
/// Determine which objects belong to unmodelled dictionary entries or owners.
fn retained_objects(
objects: &[(String, usize, &[Tag])],
entities: &HashMap<String, bool>,
objects: &[(&str, usize, &[Tag])],
entities: &HashMap<Handle, bool>,
records: &HashMap<String, ForeignKey>,
by_handle: &HashMap<String, usize>,
root: Option<&str>,
@@ -530,7 +541,9 @@ fn retained_objects(
let Some((_, _, tags)) = objects.get(index) else { return false };
let header = head(tags);
let (Some(handle), Some(owner)) = (header.handle, header.owner) else { return false };
!by_handle.contains_key(&owner) && xdict_of.get(&owner) == Some(&handle) && (entities.contains_key(&owner) || records.contains_key(&owner))
!by_handle.contains_key(&owner)
&& xdict_of.get(&owner) == Some(&handle)
&& (self::handle(&owner).is_some_and(|owner| entities.contains_key(&owner)) || records.contains_key(&owner))
};
let modelled_entry = |tags: &[Tag], handle: &str| {
entries(tags).iter().any(|(key, entry_handle)| entry_handle == handle && MODELLED_XDICT_KEYS.contains(&up(key).as_str()))
@@ -578,7 +591,7 @@ fn retained_objects(
if is_xdict(current) {
break entries(tags).iter().any(|(key, _)| !MODELLED_XDICT_KEYS.contains(&up(key).as_str()));
}
break entities.get(&owner) == Some(&true);
break self::handle(&owner).and_then(|owner| entities.get(&owner)) == Some(&true);
};
for visited in path {
retained.insert(visited, keep);
@@ -868,7 +881,7 @@ fn written_records(tags: &[Tag]) -> Vec<Rec> {
if kind == "SECTION" {
sec = body.iter().find(|t| t.code == 2).map(Tag::str).unwrap_or_default();
}
out.push(Rec { sec: sec.clone(), kind, start, end: start + 1 + body.len() });
out.push(Rec { sec: sec.clone(), kind: kind.to_string(), start, end: start + 1 + body.len() });
if out.last().is_some_and(|r| r.kind == "ENDSEC") {
sec.clear();
}
@@ -890,16 +903,16 @@ pub fn object_records(d: &Drawing) -> Vec<ObjectRecord> {
let recs = written_records(&tags);
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
let by_sec = |name: &str| -> Recs {
recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.clone(), r.start, body(r))).collect()
recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.as_str(), r.start, body(r))).collect()
};
let (tables, blocks, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("OBJECTS"));
let ids = identities(&tables, &blocks, &objects);
let tables = tables.iter().filter(|(k, _, _)| k != "ENDTAB");
let blocks = blocks.iter().filter(|(k, _, _)| k == "BLOCK");
let tables = tables.iter().filter(|(k, _, _)| *k != "ENDTAB");
let blocks = blocks.iter().filter(|(k, _, _)| *k == "BLOCK");
tables
.chain(blocks)
.chain(objects.iter())
.map(|(kind, _, t)| (kind.clone(), t.to_vec(), head(t).handle.and_then(|h| ids.get(&h).cloned())))
.map(|(kind, _, t)| (kind.to_string(), t.to_vec(), head(t).handle.and_then(|h| ids.get(&h).cloned())))
.collect()
}
@@ -1178,7 +1191,7 @@ pub(crate) fn finish(
let recs = written_records(tags);
let body = |r: &Rec| tags.get(r.start + 1..r.end).unwrap_or(&[]);
let by_sec = |name: &str| -> Recs {
recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.clone(), r.start, body(r))).collect()
recs.iter().filter(|r| r.sec == name && r.kind != "SECTION" && r.kind != "ENDSEC").map(|r| (r.kind.as_str(), r.start, body(r))).collect()
};
let (tables, blocks, objects) = (by_sec("TABLES"), by_sec("BLOCKS"), by_sec("OBJECTS"));
let mut roles: HashMap<ForeignKey, String> = HashMap::new();
+42 -6
View File
@@ -197,7 +197,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
.iter()
.filter(|s| s.name == "ENTITIES")
.flat_map(|s| record_slices(s.tags))
.filter_map(|(_, tags)| common::T(tags).s(5).and_then(|h| Handle::parse_hex(&h)))
.filter_map(|(_, tags)| tags.iter().find(|t| t.code == 5).and_then(Tag::str_ref).and_then(Handle::parse_hex))
.collect();
let mut objs = Objects::default();
// Every handle another program's file already uses is taken before anything gets a new one:
@@ -207,7 +207,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
// (#495), so for it only the entity records are reserved. Handles in the reserved band are
// reserved for allocation rather than followed (#913): a handle-less entity read before the
// section that names one is placed would otherwise be given it and replace the record (#1276).
let ours = secs.iter().any(|s| s.name == "OBJECTS" && s.tags.iter().any(|t| t.code == 3 && t.str() == crate::dxf_ext::HANDSEED_KEY));
let ours = secs.iter().any(|s| s.name == "OBJECTS" && s.tags.iter().any(|t| t.code == 3 && t.str_ref() == Some(crate::dxf_ext::HANDSEED_KEY)));
if ours {
// Its table and object records are numbered above its seed and rebuilt on save (#495),
// so only its entities are reserved. Reading is section by section: an entity that has
@@ -218,7 +218,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
if matches!(kind.as_str(), "BLOCK" | "ENDBLK") {
continue;
}
if let Some(h) = tags.iter().find(|t| t.code == 5).and_then(|t| Handle::parse_hex(t.str().trim())) {
if let Some(h) = tags.iter().find(|t| t.code == 5).and_then(Tag::str_ref).and_then(Handle::parse_hex) {
d.bump_handseed(h);
d.reserve_handle(h);
}
@@ -227,7 +227,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
for s in &secs {
let entity_section = s.name == "BLOCKS" || s.name == "ENTITIES";
for t in s.tags.iter().filter(|t| t.code == 5 || t.code == 105) {
if let Some(h) = Handle::parse_hex(t.str().trim()) {
if let Some(h) = t.str_ref().and_then(Handle::parse_hex) {
d.bump_handseed(h);
if entity_section {
d.reserve_handle(h);
@@ -243,7 +243,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
"HEADER" => header(s.tags, &mut d),
"TABLES" => tables(s.tags, &mut d, &mut rx),
"BLOCKS" => {
blocks.extend(read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped, &mut seen_handles, &reserved_entity_handles))
blocks.extend(read_blocks(s.tags, &mut d, &mut rx, &mut table_cells_left, &mut skipped, &mut seen_handles, &reserved_entity_handles)?)
}
// A damaged file may split its entities over several ENTITIES sections (#865).
"ENTITIES" => {
@@ -255,7 +255,7 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize)
&mut n,
&mut table_cells_left,
&mut HandlePolicy { seen: &mut seen_handles, reserved: &reserved_entity_handles, source_wins: true },
));
)?);
count_skipped(&mut skipped, "ENTITIES", n);
}
"OBJECTS" => read_objects(s.tags, &mut objs, &mut layout_objs),
@@ -454,3 +454,39 @@ mod hatch_budget_tests {
assert!(matches!(d.read_notes.as_slice(), [note] if note.contains("2 hatches")), "{:?}", d.read_notes);
}
}
#[cfg(test)]
mod entity_list_tests {
use super::*;
/// Vertices, attributes and SEQEND fold into the record before them, so they reserve no slots.
#[test]
fn follower_records_reserve_no_entity_slots() -> Result<()> {
let rec = |kind: &str, tags: Vec<Tag>| (kind.to_string(), tags);
let mut recs = vec![rec("POLYLINE", vec![Tag::s(8, "0"), Tag::i(66, 1)])];
for x in 0..200 {
recs.push(rec("VERTEX", vec![Tag::s(8, "0"), Tag::f(10, f64::from(x)), Tag::f(20, 0.0)]));
}
recs.push(rec("SEQEND", vec![Tag::s(8, "0")]));
recs.push(rec("LINE", vec![Tag::s(8, "0"), Tag::f(11, 1.0)]));
let recs: Vec<(String, &[Tag])> = recs.iter().map(|(kind, tags)| (kind.clone(), tags.as_slice())).collect();
let mut d = Drawing::new_imperial();
let (mut rx, mut skipped, mut cells) = (Rx::default(), 0, 100);
let (mut seen, reserved) = (HashSet::new(), HashSet::new());
let mut hp = HandlePolicy { seen: &mut seen, reserved: &reserved, source_wins: true };
let out = parse_entities(&recs, &mut d, &mut rx, &mut skipped, &mut cells, &mut hp)?;
assert_eq!(out.len(), 2, "the polyline and the line");
assert!(out.capacity() < 10, "capacity {}", out.capacity());
Ok(())
}
/// The reservation stops at its cap, and one that can't be had is an error, not an abort.
#[test]
fn entity_list_reservation_is_capped_and_fallible() -> Result<()> {
use document::entity_list;
assert_eq!(entity_list(100, 8)?.capacity(), 8);
assert_eq!(entity_list(5, 8)?.capacity(), 5);
assert_eq!(entity_list(0, 8)?.capacity(), 0);
assert!(matches!(entity_list(usize::MAX / 2, usize::MAX), Err(IoError::Format(m)) if m.contains("out of memory")));
Ok(())
}
}
+32 -9
View File
@@ -1,9 +1,10 @@
use std::collections::HashSet;
use super::common::T;
use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity};
use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity, reference_left_tilted};
use super::objects::{MAX_OBJECTS, Objects, page_setup};
use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, Vec2, record_slices};
use crate::{IoError, Result};
/// Allocate an entity handle that is unique within the DXF, including against handles assigned
/// to earlier malformed or generated entities.
@@ -45,6 +46,22 @@ pub(super) struct HandlePolicy<'a> {
pub source_wins: bool,
}
/// Most entities an entity list reserves room for before its records are read. The record count
/// is bounded by the tag limit, but a file of tiny records could still ask for gigabytes (an
/// entry takes several hundred bytes) before any record is admitted. Drawings of up to this many
/// entities are sized in one step; larger ones grow as usual. At the cap the reservation is
/// about 46 MiB (728 bytes an entry on 64-bit targets).
pub(super) const MAX_RESERVED_ENTITIES: usize = 1 << 16;
/// An empty entity list with room for `records` entities, or `cap` if that is fewer. A refused
/// reservation is an error rather than an abort.
pub(super) fn entity_list(records: usize, cap: usize) -> Result<Vec<(Option<String>, bool, Entity)>> {
let mut out = Vec::new();
let n = records.min(cap);
out.try_reserve_exact(n).map_err(|_| IoError::Format(format!("DXF: out of memory reserving {n} entities")))?;
Ok(out)
}
pub(super) fn parse_entities(
recs: &[(String, &[Tag])],
d: &mut Drawing,
@@ -52,14 +69,19 @@ pub(super) fn parse_entities(
skipped: &mut usize,
table_cells_left: &mut usize,
hp: &mut HandlePolicy<'_>,
) -> Vec<(Option<String>, bool, Entity)> {
let mut out = Vec::new();
) -> Result<Vec<(Option<String>, bool, Entity)>> {
// Every record but a polyline's vertices, a reference's attributes and their SEQEND becomes
// at most one entity (`recs` is already in memory, bounded by the tag limit), so the list is
// sized once rather than moved at every doubling, up to MAX_RESERVED_ENTITIES; past that, and
// for mesh faces past the count, it grows as usual.
let mut out =
entity_list(recs.iter().filter(|(kind, _)| !matches!(kind.as_str(), "VERTEX" | "ATTRIB" | "SEQEND")).count(), MAX_RESERVED_ENTITIES)?;
let mut i = 0;
while let Some((kind, tags)) = recs.get(i) {
let t = T(tags);
let owner = crate::dxf_ext::owner(tags);
let paper = t.i(67) == Some(1);
let handle = t.s(5).and_then(|h| Handle::parse_hex(&h));
let handle = tags.iter().find(|t| t.code == 5).and_then(Tag::str_ref).and_then(Handle::parse_hex);
if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) {
rx.paper_views_dropped.push((owner.clone(), paper, rx.block.clone()));
}
@@ -83,7 +105,8 @@ pub(super) fn parse_entities(
}
"INSERT" if t.i(66) == Some(1) => {
let ins_layer = kindent.as_ref().map(|(c, _)| c.layer.clone()).unwrap_or_default();
let attribs = insert_attribs(recs, &mut i, &ins_layer);
let left_tilted = kindent.as_ref().is_some_and(|(c, _)| reference_left_tilted(c.extrusion));
let attribs = insert_attribs(recs, &mut i, &ins_layer, left_tilted);
if let Some((_, EntityKind::Insert(ins))) = kindent.as_mut() {
ins.attribs = attribs;
}
@@ -121,7 +144,7 @@ pub(super) fn parse_entities(
*skipped = skipped.saturating_add(1);
}
}
out
Ok(out)
}
/// Read the BLOCKS section: the xref paths of external blocks, then each block's entities.
@@ -133,7 +156,7 @@ pub(super) fn read_blocks(
skipped: &mut std::collections::BTreeMap<String, usize>,
seen_handles: &mut HashSet<Handle>,
reserved_handles: &HashSet<Handle>,
) -> Vec<BlockDef> {
) -> Result<Vec<BlockDef>> {
let recs = record_slices(tags);
for (k, tg) in &recs {
let t = T(tg);
@@ -165,7 +188,7 @@ pub(super) fn read_blocks(
&mut n,
table_cells_left,
&mut HandlePolicy { seen: seen_handles, reserved: reserved_handles, source_wins: false },
);
)?;
rx.block = None;
blocks.push((name, base, description, ents, xref));
i = j + 1;
@@ -178,7 +201,7 @@ pub(super) fn read_blocks(
}
}
count_skipped(skipped, "BLOCKS", n);
blocks
Ok(blocks)
}
/// Read the OBJECTS section into `objs`, and each LAYOUT into `layout_objs`.
+32 -8
View File
@@ -1,7 +1,7 @@
use super::common::{T, common, ocs, plan_of_tilted, run_points, tilted};
use super::hatch::{CurvePoints, hatch};
use super::mtext_dxf;
use super::text::{attdef, attrib_modes, attrib_props, mtext_from, multiline_attrib, split_embedded, text_from};
use super::text::{attdef, attrib_modes, attrib_props, flatten_tilted, mtext_from, multiline_attrib, split_embedded, text_from};
use super::{
Arc, Attrib, Circle, Common, DimKind, Dimension, Ellipse, EntityKind, Face3d, Handle, HashMap, Helix, HelixConstrain, Insert, Leader, Line,
LwPolyline, MAX_FRAME_CHARS, Point, PolyVertex, Polyline3d, RawTag, RayLine, Rx, Solid, Spline, Table, TableCell, Tag, Tolerance, Unknown, Vec2,
@@ -172,16 +172,17 @@ pub(super) fn entity_with_table_budget(
"XLINE" => EntityKind::XLine(RayLine { base: t.p(10), dir: t.p(11) }),
"TEXT" => EntityKind::Text(text_from(&t)),
"MTEXT" => EntityKind::MText(mtext_from(tags, &c)),
"ATTDEF" => EntityKind::AttDef(attdef(tags, &c)),
"ATTDEF" => EntityKind::AttDef(attdef(tags, &mut c)),
"INSERT" => {
// A mirrored block reference comes with extrusion (0,0,-1): its insertion point, scale,
// rotation and column spacing are in that OCS, where x runs the other way. In the WCS that
// is the mirrored point, a negative x scale, the opposite rotation and a negative column
// spacing. Noise of up to 1e-3 in the extrusion's x/y moves the projection by ~1e-7 of the
// size, so it still counts as mirrored. A truly tilted extrusion (block plane not parallel
// to XY) needs the full 3D block transform, which Insert cannot hold; it is left as read.
// to XY) needs the full 3D block transform, which Insert cannot hold; it is left as read,
// and so are its ATTRIBs facing up (`reference_left_tilted`).
let n = c.extrusion;
let mirrored = n.z < 0.0 && n.x.hypot(n.y) <= 1e-3 * n.z.abs();
let mirrored = mirrored_reference(n);
let mut p = t.p(10);
let mut scale = Vec3::new(t.fd(41, 1.0), t.fd(42, 1.0), t.fd(43, 1.0));
let mut rotation = t.fd(50, 0.0).to_radians();
@@ -501,10 +502,10 @@ pub(super) fn entity_plot_style(tags: &[Tag], rx: &Rx) -> Option<String> {
if in_entity {
break;
}
in_entity = t.str() == "AcDbEntity";
in_entity = t.str_ref() == Some("AcDbEntity");
} else if in_entity {
match t.code {
390 => return rx.pstyles.get(&t.str().trim().to_ascii_uppercase()).cloned(),
390 => return rx.pstyles.get(&t.str_ref().unwrap_or_default().trim().to_ascii_uppercase()).cloned(),
380 => by_block = t.i64() == 1,
_ => {}
}
@@ -660,8 +661,26 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
Some((c, k, extra))
}
/// The ATTRIB records after an INSERT, advancing `i` past them and their SEQEND.
pub(super) fn insert_attribs(recs: &[(String, &[Tag])], i: &mut usize, ins_layer: &str) -> Vec<Attrib> {
/// Whether a block reference with extrusion `n` is mirrored: (0,0,-1), up to noise of 1e-3 in x and
/// y. The INSERT arm maps such a reference's point, scale, rotation and column spacing.
fn mirrored_reference(n: Vec3) -> bool {
n.z < 0.0 && n.x.hypot(n.y) <= 1e-3 * n.z.abs()
}
/// Whether a block reference with extrusion `n` is read as is although its plane is tilted: the
/// INSERT arm maps only a mirrored one, since `Insert` cannot hold the 3D transform, so its block is
/// drawn at the OCS point read. Its ATTRIBs facing up are then left as read too: mapped on their
/// own they would leave the block they belong to. (One facing down is mirrored by `text_from`, as
/// before.)
pub(super) fn reference_left_tilted(n: Vec3) -> bool {
let unit = n.normalized();
!mirrored_reference(n) && (unit.x.abs() >= 1e-12 || unit.y.abs() >= 1e-12)
}
/// The ATTRIB records after an INSERT, advancing `i` past them and their SEQEND. Those of a
/// reference read as is in its tilted plane (`left_tilted`, [`reference_left_tilted`]) stay as
/// read with it.
pub(super) fn insert_attribs(recs: &[(String, &[Tag])], i: &mut usize, ins_layer: &str, left_tilted: bool) -> Vec<Attrib> {
let mut attribs = Vec::new();
while let Some((k2, t2)) = recs.get(*i) {
if k2 == "ATTRIB" {
@@ -671,6 +690,11 @@ pub(super) fn insert_attribs(recs: &[(String, &[Tag])], i: &mut usize, ins_layer
let multiline = multiline_attrib(embedded, &common(&tt));
let own = T(own);
let mut text = text_from(&own);
// An ATTRIB keeps no plane of its own: one in a tilted plane is drawn as seen from above,
// unless its reference is left in its own tilted plane.
if !left_tilted {
flatten_tilted(&mut text, &own);
}
if let Some(m) = &multiline {
text.value.clone_from(&m.read_as);
}
+16 -6
View File
@@ -1,6 +1,8 @@
use super::common::T;
use super::{Color, EntityKind, Gradient, Handle, Hatch, HatchLoop, PolyVertex, Rgb, Spline, Tag, Vec2};
mod chain;
/// Upper bound on the points the elliptic and spline edges of one HATCH's boundary are sampled
/// into: the point budget the renderer gives one hatch's loops
/// ([`cadcraft_geom::MAX_TESSELLATED_POINTS`]).
@@ -129,25 +131,33 @@ fn polyline_boundary(tags: &[Tag], index: &mut usize) -> Option<Vec<PolyVertex>>
Some(vertices)
}
/// An edge path's vertices. Each edge is read on its own, then [`chain::chain`] joins them.
fn edge_boundary(tags: &[Tag], index: &mut usize, budget: &mut EdgeBudget) -> Option<Vec<PolyVertex>> {
let get = |i: usize| tags.get(i);
seek_code(tags, index, 93);
let count = get(*index)?.i64().clamp(0, 1_000_000) as usize;
*index += 1;
let mut vertices = Vec::new();
// Every edge's points back to back, and where each edge's are.
let (mut points, mut edges) = (Vec::new(), Vec::new());
let mut edge = Vec::new();
for _ in 0..count {
seek_code(tags, index, 72);
let kind = get(*index)?.i64();
*index += 1;
match kind {
1 => line_edge(tags, index, &mut vertices),
2 => circular_edge(tags, index, &mut vertices),
3 => elliptic_edge(tags, index, &mut vertices, budget),
4 => spline_edge(tags, index, &mut vertices, budget),
1 => line_edge(tags, index, &mut edge),
2 => circular_edge(tags, index, &mut edge),
3 => elliptic_edge(tags, index, &mut edge, budget),
4 => spline_edge(tags, index, &mut edge, budget),
_ => {}
}
if !edge.is_empty() {
let start = points.len();
points.append(&mut edge);
edges.push(start..points.len());
}
}
Some(vertices)
Some(chain::chain(&points, &edges))
}
fn edge_value(tags: &[Tag], index: usize) -> f64 {
+288
View File
@@ -0,0 +1,288 @@
//! Joining the edges of a HATCH edge path into loops.
//!
//! The DXF Reference lists a boundary path's edges one after another: group 72 gives each edge's
//! type, and the edge's own groups follow. Some files list the edges out of order, or store some
//! of them end to start. Read in file order, the vertex list of such a path jumps from edge to
//! edge, and the even-odd fill then fills the polygon those jumps make instead of the outline.
use std::collections::VecDeque;
use std::ops::Range;
use super::{PolyVertex, Vec2};
/// Points this close are one vertex where an edge meets the next. It is the tolerance the edge
/// readers used before edges were chained, so a path whose edges run on is read as before.
const SAME_POINT: f64 = 1e-9;
/// The share of a loop's extent within which two edge ends meet.
///
/// It only decides which edge follows which: no point is moved, and two ends that meet but
/// differ keep both points, so a real gap that small stays a segment of its own length. A
/// millionth is far above the rounding of the values a file stores (an arc's ends are computed
/// from its centre, radius and angles), and far below what a picture can show: a loop drawn
/// 10,000 pixels wide puts it at a hundredth of a pixel.
const MEET_SHARE: f64 = 1e-6;
/// The vertices of an edge path, from its edges in file order. Each edge is a range of `points`,
/// read on its own: its first point, the points between (a bulge on the vertex before each arc)
/// and its last point.
///
/// A path whose edges run on, each starting where the one before ends, is joined in file order,
/// as it always was. Otherwise the edges are chained into runs:
/// - A run starts with the first edge not yet used, as the file stores it.
/// - An edge with an end at the run's last point goes after it, turned around when that end is
/// its last point. Once none is left, an edge with an end at the run's first point goes before
/// it, turned around when that end is its first point. Of several, the one listed first.
/// - An edge that meets no run starts a new one.
///
/// Two ends meet when they are within the tolerance of each other (see [`MEET_SHARE`]). A loop
/// whose lookups pass their budget ([`CHECKS_PER_END`]) is joined in file order instead.
///
/// A closed run, one that ends where it starts, is a loop of its own. The runs left open make up
/// one loop together, in the order of their first edges, each joined straight to the next as a
/// path read in file order is (a path with missing edges then still closes as before). The vertex
/// list goes from the first loop's start to each later loop and back, and closes each later loop
/// straight from its last point to its first. An even-odd fill crosses each of those jumps
/// twice, so it fills each loop as a loop of its own.
pub(super) fn chain(points: &[PolyVertex], edges: &[Range<usize>]) -> Vec<PolyVertex> {
let mut out = Vec::with_capacity(points.len().saturating_add(edges.len()));
let chained = Frame::of(points)
.filter(|frame| !runs_on(points, edges, frame.tol))
.and_then(|frame| runs(&frame, points, edges, CHECKS_PER_END).map(|runs| (frame, runs)));
let Some((frame, (order, run_ends))) = chained else {
for edge in edges {
append(&mut out, edge_points(points, edge), false);
}
return out;
};
let span = |run: &[(usize, bool)]| {
let first = run.first().and_then(|&(edge, turned)| placed_ends(points, edges, edge, turned))?;
let last = run.last().and_then(|&(edge, turned)| placed_ends(points, edges, edge, turned))?;
Some((first.0, last.1))
};
// Each loop as the runs it is made of, ranges of `order`.
let mut loops: Vec<Vec<Range<usize>>> = Vec::new();
let (mut open, mut from): (Option<usize>, usize) = (None, 0);
for &to in &run_ends {
let run = from..to;
from = to;
let closed = span(order.get(run.clone()).unwrap_or_default()).is_some_and(|(start, end)| end.near(start, frame.tol));
match open.and_then(|i| loops.get_mut(i)) {
Some(runs) if !closed => runs.push(run),
_ => {
open = open.or((!closed).then_some(loops.len()));
loops.push(vec![run]);
}
}
}
let mut anchor = None;
for runs in &loops {
let placed: Vec<(usize, bool)> = runs.iter().flat_map(|run| order.get(run.clone()).unwrap_or_default().iter().copied()).collect();
let Some((start, end)) = span(&placed) else { continue };
let later = anchor.is_some();
if let Some(anchor) = anchor {
extend(&mut out, std::iter::once(PolyVertex::new(anchor)));
} else {
anchor = Some(start);
}
for (edge, turned) in placed {
append(&mut out, edges.get(edge).map_or(&[][..], |edge| edge_points(points, edge)), turned);
}
// Back at the exact start, even when the end is within the tolerance of it: the jump
// back to the anchor then retraces the jump out.
if later && end != start {
extend(&mut out, std::iter::once(PolyVertex::new(start)));
}
}
out
}
/// Whether each edge starts where the one before it ends.
fn runs_on(points: &[PolyVertex], edges: &[Range<usize>], tol: f64) -> bool {
edges.windows(2).all(|pair| match pair {
[before, after] => ends(points, before).zip(ends(points, after)).is_some_and(|((_, end), (start, _))| end.near(start, tol)),
_ => true,
})
}
/// Ends the lookups may visit, per end of the loop. A lookup visits, in up to nine cells, the
/// ends after each cell's first unused one and before the best match so far; in a drawing that
/// is a few. A crafted loop can keep many unused ends just past the tolerance of a point it
/// returns to again and again, and visit them at every return.
const CHECKS_PER_END: usize = 32;
/// The edges in the order they are chained, each with whether it is turned around, and where
/// each run ends in that list. None when the lookups visit more than `checks_per_end` ends per
/// end of the loop: the loop is then read in file order.
fn runs(frame: &Frame, points: &[PolyVertex], edges: &[Range<usize>], checks_per_end: usize) -> Option<(Vec<(usize, bool)>, Vec<usize>)> {
let mut index = EndIndex::new(frame, points, edges, checks_per_end);
let mut used = vec![false; edges.len()];
let (mut order, mut run_ends) = (Vec::with_capacity(edges.len()), Vec::new());
let mut run = VecDeque::new();
for first in 0..edges.len() {
let Some((mut head, mut tail)) = edges.get(first).and_then(|edge| ends(points, edge)) else { continue };
if !take(&mut used, first) {
continue;
}
run.push_back((first, false));
while let Some((edge, at_last)) = index.find(frame, tail, &used) {
let Some((start, end)) = edges.get(edge).and_then(|e| ends(points, e)) else { break };
if !take(&mut used, edge) {
break;
}
run.push_back((edge, at_last));
tail = if at_last { start } else { end };
}
while let Some((edge, at_last)) = index.find(frame, head, &used) {
let Some((start, end)) = edges.get(edge).and_then(|e| ends(points, e)) else { break };
if !take(&mut used, edge) {
break;
}
run.push_front((edge, !at_last));
head = if at_last { start } else { end };
}
if index.spent {
return None;
}
order.extend(run.drain(..));
run_ends.push(order.len());
}
Some((order, run_ends))
}
/// Marks an edge used; false when it already was.
fn take(used: &mut [bool], edge: usize) -> bool {
used.get_mut(edge).is_some_and(|used| !std::mem::replace(used, true))
}
/// Where a loop's edge ends are looked up: the lower corner of the box around its finite points,
/// and the distance within which two ends meet, which is also the side of a lookup cell.
struct Frame {
low: Vec2,
tol: f64,
}
impl Frame {
/// None when no point is finite, or the points span more than a double holds.
fn of(points: &[PolyVertex]) -> Option<Frame> {
let mut finite = points.iter().map(|v| v.p).filter(|p| p.is_finite());
let first = finite.next()?;
let (low, high) = finite.fold((first, first), |(low, high), p| (low.min(p), high.max(p)));
let extent = (high.x - low.x).max(high.y - low.y);
extent.is_finite().then(|| Frame { low, tol: (extent * MEET_SHARE).max(SAME_POINT) })
}
/// The cell a point is in. The box is at most a million cells across (`extent / tol`), so
/// the conversions are exact.
fn cell(&self, p: Vec2) -> Option<(i64, i64)> {
p.is_finite().then(|| (((p.x - self.low.x) / self.tol).floor() as i64, ((p.y - self.low.y) / self.tol).floor() as i64))
}
}
/// The finite edge ends of a loop, by cell. A cell is `tol` wide, so an end within `tol` of a
/// point is in the point's cell or one next to it.
struct EndIndex {
/// Each end's cell, id (twice its edge's index, plus one for the edge's last point) and
/// point, sorted by cell and id.
ends: Vec<((i64, i64), usize, Vec2)>,
/// At a cell's first entry: the cell's first entry that may still be unused.
next: Vec<usize>,
/// Ends lookups may still visit.
checks: usize,
/// The lookups visited every end they were allowed: they find nothing more.
spent: bool,
}
impl EndIndex {
fn new(frame: &Frame, points: &[PolyVertex], edges: &[Range<usize>], checks_per_end: usize) -> EndIndex {
let mut ends: Vec<((i64, i64), usize, Vec2)> = edges
.iter()
.enumerate()
.filter_map(|(i, edge)| ends(points, edge).map(|(start, end)| (i, start, end)))
.flat_map(|(i, start, end)| [(2 * i, start), (2 * i + 1, end)])
.filter_map(|(id, p)| frame.cell(p).map(|cell| (cell, id, p)))
.collect();
ends.sort_unstable_by_key(|&(cell, id, _)| (cell, id));
let next = (0..ends.len()).collect();
let checks = ends.len().saturating_mul(checks_per_end);
EndIndex { ends, next, checks, spent: false }
}
/// The unused edge listed first with an end within `tol` of `p`, and whether that end is the
/// edge's last point (its first point when both are).
fn find(&mut self, frame: &Frame, p: Vec2, used: &[bool]) -> Option<(usize, bool)> {
let (x, y) = frame.cell(p)?;
let mut best = None;
for cell in (-1..=1).flat_map(|dx| (-1..=1).map(move |dy| (x + dx, y + dy))) {
best = self.first_within(cell, p, frame.tol, used, best).or(best);
}
best.map(|id| (id / 2, id % 2 == 1))
}
/// The first end in `cell` within `tol` of `p` whose edge is unused, listed before `below`.
/// Used ends at the front of the cell are skipped once for good.
fn first_within(&mut self, cell: (i64, i64), p: Vec2, tol: f64, used: &[bool], below: Option<usize>) -> Option<usize> {
let unused = |id: usize| !used.get(id / 2).copied().unwrap_or(true);
let first = self.ends.partition_point(|(c, ..)| *c < cell);
let mut at = self.next.get(first).copied()?;
while self.ends.get(at).is_some_and(|&(c, id, _)| c == cell && !unused(id)) {
at += 1;
}
if let Some(next) = self.next.get_mut(first) {
*next = at;
}
for &(c, id, q) in self.ends.get(at..).unwrap_or_default() {
if c != cell || below.is_some_and(|below| id >= below) {
break;
}
if self.checks == 0 {
self.spent = true;
return None;
}
self.checks -= 1;
if unused(id) && q.near(p, tol) {
return Some(id);
}
}
None
}
}
fn edge_points<'a>(points: &'a [PolyVertex], edge: &Range<usize>) -> &'a [PolyVertex] {
points.get(edge.clone()).unwrap_or_default()
}
/// An edge's first and last point.
fn ends(points: &[PolyVertex], edge: &Range<usize>) -> Option<(Vec2, Vec2)> {
let points = edge_points(points, edge);
Some((points.first()?.p, points.last()?.p))
}
/// An edge's first and last point as placed, turned around or not.
fn placed_ends(points: &[PolyVertex], edges: &[Range<usize>], edge: usize, turned: bool) -> Option<(Vec2, Vec2)> {
let (start, end) = ends(points, edges.get(edge)?)?;
Some(if turned { (end, start) } else { (start, end) })
}
/// Appends an edge's vertices. Turned around, its points come in reverse order, and each arc's
/// bulge is negated and moved to the vertex that now starts the arc.
fn append(out: &mut Vec<PolyVertex>, edge: &[PolyVertex], turned: bool) {
if turned {
let before = edge.iter().rev().skip(1).map(Some).chain([None]);
extend(out, edge.iter().rev().zip(before).map(|(v, before)| PolyVertex::with_bulge(v.p, before.map_or(0.0, |b| -b.bulge))));
} else {
extend(out, edge.iter().copied());
}
}
/// Appends vertices, leaving out the first when the list already ends there; its bulge then goes
/// on the list's last vertex.
fn extend(out: &mut Vec<PolyVertex>, mut vertices: impl Iterator<Item = PolyVertex>) {
if let Some(first) = vertices.next() {
match out.last_mut() {
Some(last) if last.p.near(first.p, SAME_POINT) => last.bulge = first.bulge,
_ => out.push(first),
}
}
out.extend(vertices);
}
+12 -15
View File
@@ -2,6 +2,7 @@ use super::common::T;
use super::dimassoc::dimassoc;
use super::document::sortents_table;
use super::{Drawing, EntityKind, Group, Handle, HashMap, MLeaderStyle, PageSetup, Rx, Tag, Ucs, Vec2, Vec3};
use crate::dxf_ext::ByName;
/// Non-graphical objects applied once every entity is placed.
#[derive(Default)]
@@ -196,6 +197,7 @@ impl Objects {
/// Layouts' UCSs: the World UCS, unusable axes or no such layout leave it unset.
fn apply_layout_ucss(&self, d: &mut Drawing, rx: &Rx) {
let layout_at = super::document::layout_positions(d);
let ucs_names = crate::dxf_ext::UcsNames::new(&d.ucss);
for (name, origin, x, y, named) in &self.layout_ucss {
let usable = origin.is_finite() && crate::dxf_ext::usable_axes(*x, *y);
// The named UCS group 345 points at, only while the layout's frame is still that
@@ -203,7 +205,7 @@ impl Objects {
let ucs_name = named
.as_ref()
.and_then(|h| rx.ucss.get(&h.trim().to_ascii_uppercase()))
.and_then(|n| crate::dxf_ext::named_ucs(&d.ucss, n, *origin, *x, *y))
.and_then(|n| ucs_names.named(n, *origin, *x, *y))
.map(|u| u.name.clone())
.unwrap_or_default();
let world = origin.len() <= 1e-12 && (*x - Vec3::new(1.0, 0.0, 0.0)).len() <= 1e-12 && (*y - Vec3::new(0.0, 1.0, 0.0)).len() <= 1e-12;
@@ -217,14 +219,13 @@ impl Objects {
}
fn apply_table_styles(&self, d: &mut Drawing) {
// Table styles (named by their ACAD_TABLESTYLE dictionary entries).
// Table styles (named by their ACAD_TABLESTYLE dictionary entries); a later style of a
// name replaces the first.
let mut by_name = ByName::new(&d.table_styles, |s| &s.name);
for (h, tags) in &self.table_styles {
let Some(name) = self.names.get(h).filter(|n| !n.is_empty()) else { continue };
let st = crate::dxf_table::read_table_style(name, tags);
match d.table_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(name)) {
Some(x) => *x = st,
None => d.table_styles.push(st),
}
by_name.put(&mut d.table_styles, name, st);
}
}
@@ -235,10 +236,7 @@ impl Objects {
// style's, so every cell style height applies as it is.
let height = {
let style = name.as_deref().unwrap_or("Standard");
d.table_styles
.iter()
.find(|s| s.name.eq_ignore_ascii_case(style))
.map_or(cadcraft_doc::TableStyle::default().text_height, |s| s.text_height)
d.table_styles.by_name(style).map_or(cadcraft_doc::TableStyle::default().text_height, |s| s.text_height)
};
let _ = d.modify_entity(*h, |e| {
if let EntityKind::Table(t) = &mut e.kind {
@@ -252,7 +250,9 @@ impl Objects {
}
fn apply_mleader_styles(&self, d: &mut Drawing, rx: &Rx) {
// Multileader styles (named by their ACAD_MLEADERSTYLE dictionary entries).
// Multileader styles (named by their ACAD_MLEADERSTYLE dictionary entries); a later style
// of a name replaces the first.
let mut by_name = ByName::new(&d.mleader_styles, |s| &s.name);
for (h, tags) in &self.mleader_styles {
let Some(name) = self.names.get(h).filter(|n| !n.is_empty()) else { continue };
let t = T(tags);
@@ -268,10 +268,7 @@ impl Objects {
text_style: text_style.unwrap_or(def.text_style),
annotative: t.i(296).unwrap_or(0) != 0,
};
match d.mleader_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case(name)) {
Some(x) => *x = st,
None => d.mleader_styles.push(st),
}
by_name.put(&mut d.mleader_styles, name, st);
}
}
+20 -26
View File
@@ -4,6 +4,7 @@ use super::{
Color, DashElement, DimStyle, Drawing, HVal, HashMap, Layer, Linetype, Lineweight, NamedView, Rgb, Rx, Tag, TextStyle, Ucs, Vec2, Vec3,
VportConfig, VportTile, record_slices,
};
use crate::dxf_ext::ByName;
use cadcraft_fonts::windows::windows_font;
use craft_dxf::lin_pat::MAX_LINETYPE_ELEMENTS;
@@ -114,11 +115,12 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
// The same for linetypes (first definition wins) and text styles (last definition wins).
let mut linetype_names: std::collections::HashSet<String> = d.linetypes.iter().map(|l| l.name.to_ascii_lowercase()).collect();
let mut style_index: HashMap<String, usize> = d.text_styles.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
// And for dimension styles (a later record replaces the first of its name, which keeps its
// place); ordered by name rather than hashed, so its cost does not depend on hash keys. Built
// in reverse, so the first style of a name is the one kept.
let mut dim_style_index: std::collections::BTreeMap<String, usize> =
d.dim_styles.iter().enumerate().rev().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
// And for dimension styles, views and UCSs (a later record replaces the first of its name),
// and viewport configurations (a record adds a tile to the first of its name).
let mut dim_style_names = ByName::new(&d.dim_styles, |s| &s.name);
let mut view_names = ByName::new(&d.views, |v| &v.name);
let mut ucs_names = ByName::new(&d.ucss, |u| &u.name);
let mut vport_names = ByName::new(&d.vports, |c| &c.name);
for (kind, tg) in recs {
let t = T(tg);
match kind.as_str() {
@@ -206,7 +208,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
// The first *ACTIVE viewport holds the current snap/grid settings.
"VPORT" if !active_vport && t.s(2).is_some_and(|n| n.trim().eq_ignore_ascii_case("*ACTIVE")) => {
active_vport = true;
vport_record(d, &t, true);
vport_record(d, &mut vport_names, &t, true);
for (name, code) in [("SNAPUNIT", 14), ("GRIDUNIT", 15)] {
if let (Some(x), Some(y)) = (t.f(code), t.f(code + 10)) {
let p = Vec2::new(x, y);
@@ -245,10 +247,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
// 70 bit 1: a paper space view; its layout is CADCraft xdata.
let layout = (t.i(70).unwrap_or(0) & 1 != 0).then(|| field("LAYOUT").unwrap_or_default());
let v = NamedView { name: name.clone(), center, height: h, width: w, layer_state: field("LAYERSTATE"), twist, layout };
match d.views.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
Some(x) => *x = v,
None => d.views.push(v),
}
view_names.put(&mut d.views, &name, v);
}
"UCS" => {
let name = t.s(2).unwrap_or_default();
@@ -258,10 +257,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
continue;
}
let u = Ucs { name: name.clone(), origin, x_axis, y_axis };
match d.ucss.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
Some(x) => *x = u,
None => d.ucss.push(u),
}
ucs_names.put(&mut d.ucss, &name, u);
}
"DIMSTYLE" => {
let name = t.s(2).unwrap_or_default();
@@ -285,15 +281,9 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
fields.extend(crate::dxf_ext::read_newer_dimvars(tg, &rx.styles, &rx.brs, &rx.ltypes));
let mut st = DimStyle { name: name.clone(), annotative: annotative(tg), ..DimStyle::default() };
st.apply_fields(&fields);
match dim_style_index.get(&name.to_ascii_lowercase()).and_then(|&i| d.dim_styles.get_mut(i)) {
Some(x) => *x = st,
None => {
dim_style_index.insert(name.to_ascii_lowercase(), d.dim_styles.len());
d.dim_styles.push(st);
}
}
dim_style_names.put(&mut d.dim_styles, &name, st);
}
"VPORT" => vport_record(d, &t, false),
"VPORT" => vport_record(d, &mut vport_names, &t, false),
_ => {}
}
}
@@ -362,8 +352,9 @@ const MAX_VPORT_TILES: usize = 64;
/// A VPORT record: one tile of the configuration it names (`*ACTIVE` the one shown). Corners
/// are fractions of the drawing area; unusable tiles are skipped. `first_active`: this is the
/// file's first `*ACTIVE` record, the one whose view is the drawing's saved view.
fn vport_record(d: &mut Drawing, t: &T, first_active: bool) {
/// file's first `*ACTIVE` record, the one whose view is the drawing's saved view. `names`: the
/// configurations read so far by name.
fn vport_record(d: &mut Drawing, names: &mut ByName, t: &T, first_active: bool) {
let name = t.s(2).map(|n| n.trim().to_string()).unwrap_or_default();
// View twist (group 51, degrees).
let twist = t.f(51).map_or(0.0, |a| cadcraft_geom::norm_angle(a.to_radians()));
@@ -400,10 +391,13 @@ fn vport_record(d: &mut Drawing, t: &T, first_active: bool) {
let tile = VportTile { min: clamp(min), max: clamp(max), center, height, aspect, twist };
let name = if name.eq_ignore_ascii_case(VportConfig::ACTIVE) { VportConfig::ACTIVE.to_string() } else { name };
let room = d.vports.len() < MAX_OBJECTS;
match d.vports.iter_mut().find(|c| c.name.eq_ignore_ascii_case(&name)) {
match names.position(&name).and_then(|i| d.vports.get_mut(i)) {
Some(c) if c.tiles.len() < MAX_VPORT_TILES => c.tiles.push(tile),
Some(_) => {}
None if room => d.vports.push(VportConfig { name, tiles: vec![tile] }),
None if room => {
let config = VportConfig { name: name.clone(), tiles: vec![tile] };
names.put(&mut d.vports, &name, config);
}
None => {}
}
}
+36 -2
View File
@@ -157,13 +157,47 @@ fn mirror_text(t: &mut Text, align: Option<Vec3>, insert: Vec3) {
}
}
/// An ATTDEF, whose multiline text is embedded MTEXT after its own groups.
pub(super) fn attdef(tags: &[Tag], c: &Common) -> Attrib {
/// An attribute's text (ATTRIB or ATTDEF, read by [`text_from`] from its own groups `t`) in a
/// tilted plane, drawn as seen from above. Its insertion point, alignment point and rotation
/// (groups 10, 11 and 50) are in the OCS of its extrusion (210): the DXF Reference gives both
/// points as "in OCS" for ATTRIB and ATTDEF, and its "Object Coordinate Systems (OCS)" lists both
/// among the planar entities whose axes come from the arbitrary axis algorithm. Read as world
/// points they put the attribute millions of units from its place in a drawing near survey
/// coordinates (#3541). `Text` cannot hold the plane, so the points are mapped to the WCS and the
/// rotation becomes the way the plane's turned x axis runs in plan, as a tilted LWPOLYLINE or HATCH
/// is drawn flat (#1886); a direction seen edge-on keeps the file's turn. Returns whether the text
/// was mapped: its points are then plan coordinates, and the extrusion is spent.
///
/// A plane facing down (z < 0) is left to `mirror_text`, which has mapped the points already. On
/// the Z axis (within the `Mat4::ocs` tolerance) the OCS is the WCS, and an extrusion too short for
/// `Vec3::normalized` names no plane (`Mat4::ocs` takes it as the Z axis): nothing changes for those.
pub(super) fn flatten_tilted(text: &mut Text, t: &T) -> bool {
let n = Vec3::new(t.fd(210, 0.0), t.fd(220, 0.0), t.fd(230, 1.0));
let unit = n.normalized();
if unit.z < 0.0 || (unit.x.abs() < 1e-12 && unit.y.abs() < 1e-12) {
return false;
}
let m = cadcraft_geom::Mat4::ocs(n);
text.insert = m.apply(text.insert);
text.align_pt = text.align_pt.map(|a| m.apply(a));
let along = m.apply(Vec3::new(text.rotation.cos(), text.rotation.sin(), 0.0)).xy();
if along.len() > 1e-9 {
text.rotation = cadcraft_geom::norm_angle(along.angle());
}
true
}
/// An ATTDEF, whose multiline text is embedded MTEXT after its own groups. One in a tilted plane
/// is drawn as seen from above, and its extrusion in `c` is spent ([`flatten_tilted`]).
pub(super) fn attdef(tags: &[Tag], c: &mut Common) -> Attrib {
// A multiline definition has its text as embedded MTEXT after its own groups.
let (own, embedded) = split_embedded(tags);
let multiline = multiline_attrib(embedded, c);
let own = T(own);
let mut text = text_from(&own);
if flatten_tilted(&mut text, &own) {
c.extrusion = Vec3::Z;
}
if let Some(m) = &multiline {
text.value.clone_from(&m.read_as);
}
+22 -6
View File
@@ -1,4 +1,5 @@
use super::{DimVal, Handle, HashMap, K, Vec3, Version, dxf_ext};
use crate::dxf_ext::ByName;
/// The `DIMASSOC` object of an associative dimension (stored in the dimension's extension
/// dictionary under `ACAD_DIMASSOC`).
@@ -44,8 +45,14 @@ pub(super) struct Ctx {
pub(super) tables: HashMap<Handle, (String, String)>,
/// Table style name → TABLESTYLE handle (the first is the fallback).
pub(super) table_styles: Vec<(String, String)>,
/// Multileader style name → MLEADERSTYLE handle (the first is the fallback).
/// The positions of [`Ctx::table_styles`] by name.
pub(super) table_style_names: ByName,
/// Multileader style name → MLEADERSTYLE handle (the first is the fallback): the drawing's
/// multileader styles in order, or Standard alone when it has none.
pub(super) mleader_styles: Vec<(String, String)>,
/// The positions of [`Ctx::mleader_styles`] by name: those of the drawing's multileader styles
/// too, when it has any.
pub(super) mleader_style_names: ByName,
/// Upper-case block name → BLOCK_RECORD handle (multileader block content).
pub(super) block_records: HashMap<String, String>,
/// Raster images' IMAGEDEF, IMAGEDEF_REACTOR and dictionary handles.
@@ -76,14 +83,23 @@ impl Ctx {
self.arrows.get(&name.trim().to_ascii_uppercase()).cloned()
}
pub(super) fn table_style(&self, name: &str) -> String {
Self::named(&self.table_styles, name)
Self::named(&self.table_styles, &self.table_style_names, name)
}
pub(super) fn mleader_style(&self, name: &str) -> String {
Self::named(&self.mleader_styles, name)
Self::named(&self.mleader_styles, &self.mleader_style_names, name)
}
/// The handle of the style `name` in `styles`, or of the first one.
fn named(styles: &[(String, String)], name: &str) -> String {
styles.iter().find(|(n, _)| n.eq_ignore_ascii_case(name)).or_else(|| styles.first()).map(|(_, h)| h.clone()).unwrap_or_else(|| "0".into())
/// The drawing's multileader style named `name` (the first of that name, ignoring case).
pub(super) fn mleader_style_def<'d>(&self, d: &'d cadcraft_doc::Drawing, name: &str) -> Option<&'d cadcraft_doc::MLeaderStyle> {
if self.mleader_styles.is_empty() {
// No styles planned (one entity's groups, for AutoLISP): look in the drawing.
return d.mleader_styles.iter().find(|s| s.name.eq_ignore_ascii_case(name));
}
self.mleader_style_names.position(name).and_then(|i| d.mleader_styles.get(i))
}
/// The handle of the style `name` in `styles` (the first of that name, ignoring case, found
/// through `names`, their positions by name), or of the first one.
fn named(styles: &[(String, String)], names: &ByName, name: &str) -> String {
names.position(name).and_then(|i| styles.get(i)).or_else(|| styles.first()).map(|(_, h)| h.clone()).unwrap_or_else(|| "0".into())
}
/// A dimension variable encoded with this file's handles; integers outside the 16-bit
/// range of their groups are dropped.
+1
View File
@@ -599,6 +599,7 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap
common(w, e, owner, paper, "AcDbMLeader");
let refs = crate::dxf_mleader::Refs {
style: cx.mleader_style(&m.style),
style_def: cx.mleader_style_def(d, &m.style),
text_style: m.text.as_ref().and_then(|t| cx.style(&t.style)),
block: m.block.as_ref().and_then(|b| cx.block_records.get(&b.block.to_ascii_uppercase()).cloned()),
};
+10 -5
View File
@@ -407,6 +407,8 @@ fn write_entities(w: &mut W, d: &Drawing, ms_br: &str, ps_brs: &[(String, String
struct LayoutWriteContext<'a> {
drawing: &'a Drawing,
dictionary: &'a str,
/// The drawing's UCSs by name, for each layout's named UCS.
ucs_names: &'a dxf_ext::UcsNames<'a>,
}
struct LayoutWriteData<'a> {
@@ -457,7 +459,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
w.s(330, layout_dict.to_string());
w.s(100, "AcDbPlotSettings");
write_plot_settings(w, d, page, data.model);
write_layout_data(w, d, data, view);
write_layout_data(w, d, context.ucs_names, data, view);
}
fn write_plot_settings(w: &mut W, d: &Drawing, page: &PageSetup, model: bool) {
@@ -550,7 +552,7 @@ fn write_plot_settings(w: &mut W, d: &Drawing, page: &PageSetup, model: bool) {
}
}
fn write_layout_data(w: &mut W, d: &Drawing, data: LayoutWriteData<'_>, view: Option<(Vec2, f64)>) {
fn write_layout_data(w: &mut W, d: &Drawing, ucs_names: &dxf_ext::UcsNames<'_>, data: LayoutWriteData<'_>, view: Option<(Vec2, f64)>) {
let name = data.name;
let tab = data.tab;
let flags = data.flags;
@@ -578,7 +580,7 @@ fn write_layout_data(w: &mut W, d: &Drawing, data: LayoutWriteData<'_>, view: Op
w.i(76, 0);
w.s(330, brh);
// The named UCS it is, only while its frame is still that record's (as for model space).
let named = u.and_then(|u| dxf_ext::named_ucs(&d.ucss, &u.name, u.origin, u.x_axis, u.y_axis));
let named = u.and_then(|u| ucs_names.named(&u.name, u.origin, u.x_axis, u.y_axis));
if let Some(h) = named.and_then(|u| w.ucss.get(&u.name.to_ascii_uppercase())).cloned() {
w.s(345, h);
}
@@ -643,6 +645,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
let ms_br = plan.ms_br;
let ps_brs = plan.ps_brs;
let layout_handles = plan.layout_handles;
let ucs_names = dxf_ext::UcsNames::new(&d.ucss);
w.s(0, "DICTIONARY");
w.s(5, layout_dict.clone());
w.s(330, root_dict.clone());
@@ -661,7 +664,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
let model_page = PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..PageSetup::default() };
layout_obj(
w,
LayoutWriteContext { drawing: d, dictionary: layout_dict },
LayoutWriteContext { drawing: d, dictionary: layout_dict, ucs_names: &ucs_names },
LayoutWriteData {
handle: model_layout,
name: "Model",
@@ -679,7 +682,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
let h = layout_handles.get(i).cloned().unwrap_or_default();
layout_obj(
w,
LayoutWriteContext { drawing: d, dictionary: layout_dict },
LayoutWriteContext { drawing: d, dictionary: layout_dict, ucs_names: &ucs_names },
LayoutWriteData {
handle: &h,
name: &l.name,
@@ -1132,9 +1135,11 @@ pub(super) fn tags_kept_for(
let default_table_style = [TableStyle::default()];
let table_styles: &[TableStyle] = if d.table_styles.is_empty() { &default_table_style } else { &d.table_styles };
cx.table_styles = table_styles.iter().map(|s| (s.name.clone(), w.h())).collect();
cx.table_style_names = crate::dxf_ext::ByName::new(&cx.table_styles, |(n, _)| n);
let default_mleader_style = [MLeaderStyle::default()];
let mleader_styles: &[MLeaderStyle] = if d.mleader_styles.is_empty() { &default_mleader_style } else { &d.mleader_styles };
cx.mleader_styles = mleader_styles.iter().map(|s| (s.name.clone(), w.h())).collect();
cx.mleader_style_names = crate::dxf_ext::ByName::new(&cx.mleader_styles, |(n, _)| n);
let root_dict = w.h();
let group_dict = w.h();
let layout_dict = w.h();
+41 -10
View File
@@ -179,26 +179,50 @@ fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec<u8>, craft_dwg::Unwri
/// extents. Formats that are not images (DXF, DWG) ignore the window. The window is checked with
/// [`check_window`].
pub fn write_framed(d: &Drawing, name: impl AsRef<Path>, window: Option<Bounds2>) -> Result<Vec<u8>> {
write_framed_noted(d, name, window).map(|(bytes, _)| bytes)
}
/// [`write_framed`], also returning what an image (PNG, SVG, PDF) draws short of the drawing
/// because of a render limit, one note each: the dashed runs drawn continuous
/// ([`undashed_note`]). DXF and DWG have none.
pub fn write_framed_noted(d: &Drawing, name: impl AsRef<Path>, window: Option<Bounds2>) -> Result<(Vec<u8>, Vec<String>)> {
let name = name.as_ref();
// A drawing template (.dwt) is DWG content.
let format = Format::from_path(name);
if format == Some(Format::Dwt) {
let mut dwg = name.as_os_str().to_owned();
dwg.push(".dwg");
return write_framed(d, PathBuf::from(dwg), None);
return write_framed_noted(d, PathBuf::from(dwg), None);
}
if let Some(w) = &window
&& is_image(name)
{
check_window(w)?;
}
match format {
Some(Format::Dxf | Format::Dwg) => write_with(d, name, &SaveOptions::default()),
Some(Format::Svg) => Ok(svg::export_window(d, &Space::Model, window).into_bytes()),
Some(Format::Png) => png_framed(d, &Space::Model, 2400, 1600, window),
Some(Format::Pdf) => pdf::pdf(d, &Space::Model, &PdfOptions { compress: true, window, ..PdfOptions::default() }),
_ => Err(IoError::Unsupported(ext(name))),
}
let (bytes, undashed) = match format {
Some(Format::Dxf | Format::Dwg) => (write_with(d, name, &SaveOptions::default())?, 0),
Some(Format::Svg) => {
let (svg, undashed) = svg::export_window_noted(d, &Space::Model, window);
(svg.into_bytes(), undashed)
}
Some(Format::Png) => png_framed_noted(d, &Space::Model, 2400, 1600, window)?,
Some(Format::Pdf) => pdf::pdf_noted(d, &Space::Model, &PdfOptions { compress: true, window, ..PdfOptions::default() })?,
_ => return Err(IoError::Unsupported(ext(name))),
};
Ok((bytes, undashed_note(undashed).into_iter().collect()))
}
/// The note for `n` dashed runs an output drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]), or `None` when there are none.
pub fn undashed_note(n: usize) -> Option<String> {
let runs = if n == 1 { "run" } else { "runs" };
(n > 0).then(|| {
format!(
"{n} dashed {runs} (each a line, a curve or a polyline segment) drawn continuous: past the dash limit of {} pattern elements per run or {} per drawing",
cadcraft_render::MAX_RUN_DASH_ELEMENTS,
cadcraft_render::MAX_DASH_ELEMENTS
)
})
}
/// Whether `name` is written as an image (PNG, SVG, PDF), i.e. whether framing applies to it.
@@ -238,10 +262,17 @@ pub fn png(d: &Drawing, space: &Space, width: u32, height: u32) -> Result<Vec<u8
/// extents (5% margin) when `window` is `None`. Objects are drawn with their transparency, as on
/// screen.
pub fn png_framed(d: &Drawing, space: &Space, width: u32, height: u32, window: Option<Bounds2>) -> Result<Vec<u8>> {
png_framed_noted(d, space, width, height, window).map(|(png, _)| png)
}
/// [`png_framed`], also returning the dashed runs it drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]).
pub fn png_framed_noted(d: &Drawing, space: &Space, width: u32, height: u32, window: Option<Bounds2>) -> Result<(Vec<u8>, usize)> {
let list = cadcraft_render::build(d, space, &cadcraft_render::Options { transparency: true, ..cadcraft_render::Options::default() });
let view = png_view(&list.bounds, width, height, window);
cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default())
.ok_or_else(|| IoError::Format("render failed".into()))
let png = cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default())
.ok_or_else(|| IoError::Format("render failed".into()))?;
Ok((png, list.undashed))
}
/// The raster view a PNG export uses.
+34 -9
View File
@@ -219,6 +219,12 @@ fn window(v: Option<&Value>) -> Option<Bounds2> {
/// Plot with JSON options (the engine's `plot` hook).
pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
plot_noted(d, space, opts).map(|(bytes, _)| bytes)
}
/// [`plot`], also returning the dashed runs its pages drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]).
pub fn plot_noted(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
validate_plot_offset_json(opts)?;
// `layouts: [name | "Model"] | "all"` plots those sheets into one file, one page each,
// instead of `space`; "all" = Model if it has objects, then the layouts in tab order.
@@ -245,7 +251,7 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
Ok((Space::Model, po))
})
.collect::<Result<Vec<_>>>()?;
return pdf_items(d, &items, &o);
return pdf_items_noted(d, &items, &o);
}
match opts.get("layouts") {
Some(Value::String(a)) if a.eq_ignore_ascii_case("all") => {
@@ -253,7 +259,7 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
layouts.sort_by_key(|l| l.tab_order);
let model = (!d.model.is_empty()).then_some(Space::Model);
let spaces: Vec<Space> = model.into_iter().chain(layouts.iter().map(|l| Space::Paper(l.name.clone()))).collect();
pdf_sheets(d, &spaces, &o)
pdf_items_noted(d, &sheet_items(&spaces, &o), &o)
}
Some(v) => {
let names = v.as_array().ok_or_else(|| IoError::Format("`layouts` must be a list of layout names".into()))?;
@@ -268,9 +274,9 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
None => Err(IoError::Format("`layouts` must be a list of layout names".into())),
})
.collect::<Result<Vec<_>>>()?;
pdf_sheets(d, &spaces, &o)
pdf_items_noted(d, &sheet_items(&spaces, &o), &o)
}
None => pdf(d, space, &o),
None => pdf_noted(d, space, &o),
}
}
@@ -346,6 +352,12 @@ pub fn pdf(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<Vec<u8>> {
pdf_sheets(d, std::slice::from_ref(space), o)
}
/// [`pdf`], also returning the dashed runs it drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]).
pub fn pdf_noted(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<(Vec<u8>, usize)> {
pdf_items_noted(d, &sheet_items(std::slice::from_ref(space), o), o)
}
/// The name of a sheet: `Model` or the layout's.
fn sheet_name(space: &Space) -> String {
space.tab_name().to_string()
@@ -354,17 +366,27 @@ fn sheet_name(space: &Space) -> String {
/// Write a vector PDF with one page per space (at most [`MAX_PAGES`]), each labelled with its
/// layout name. The options apply to every sheet; layouts use their own page setups.
pub fn pdf_sheets(d: &Drawing, spaces: &[Space], o: &PdfOptions) -> Result<Vec<u8>> {
pdf_items(d, &sheet_items(spaces, o), o)
}
/// The items [`pdf_sheets`] plots: each space with `o`, at most one past [`MAX_PAGES`].
fn sheet_items(spaces: &[Space], o: &PdfOptions) -> Vec<(Space, PdfOptions)> {
// Links are file-wide (`pdf_items` reads them from `o`), so a sheet's own options carry none:
// a copy of the list per sheet multiplied it by the sheet count.
let sheet = PdfOptions { links: Vec::new(), ..o.clone() };
let items: Vec<(Space, PdfOptions)> = spaces.iter().take(MAX_PAGES + 1).map(|s| (s.clone(), sheet.clone())).collect();
pdf_items(d, &items, o)
spaces.iter().take(MAX_PAGES + 1).map(|s| (s.clone(), sheet.clone())).collect()
}
/// Write a vector PDF with one page per `(space, options)` item (at most [`MAX_PAGES`]): each
/// page plots with its own options (window, paper, orientation); `o` supplies the file-wide
/// ones (compression, title, layers, links).
pub fn pdf_items(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions) -> Result<Vec<u8>> {
pdf_items_noted(d, items, o).map(|(bytes, _)| bytes)
}
/// [`pdf_items`], also returning the dashed runs its pages drew continuous because of a dash
/// limit ([`cadcraft_render::DisplayList::undashed`]).
pub fn pdf_items_noted(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions) -> Result<(Vec<u8>, usize)> {
if items.iter().any(|(_, io)| io.offset.is_some_and(|offset| !valid_plot_offset(offset))) {
return Err(IoError::Format("plot offset must contain two finite values within ±100000 mm".into()));
}
@@ -420,8 +442,9 @@ impl Failure {
}
/// Write the file, one sheet at a time: each sheet's display list is built, written as its page
/// and dropped before the next.
fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as_geometry: bool) -> std::result::Result<Vec<u8>, Failure> {
/// and dropped before the next. Also the dashed runs the pages drew continuous because of a dash
/// limit ([`cadcraft_render::DisplayList::undashed`]).
fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as_geometry: bool) -> std::result::Result<(Vec<u8>, usize), Failure> {
write::guard(|| {
// Layers that are off plot on PDF layers that start hidden: draw them from a copy with
// them on.
@@ -456,6 +479,7 @@ fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as
// Link annotations of the whole file: each page keeps its own copy of the targets, so the
// pages times the links must not multiply without a bound.
let mut annotations_left = MAX_FILE_ANNOTATIONS;
let mut undashed = 0usize;
for (s, po) in items {
// Once the budget is spent no link is built (scanned and cloned) for later pages.
let mut page = sheet(drawn, s, po, if annotations_left == 0 { &links[..0] } else { &links })?;
@@ -467,11 +491,12 @@ fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as
// Groups are added to the document, so they must exist before the page starts.
groups.add(doc, d, &page.layers);
write_page(doc, &page, &groups, &mut fonts)?;
undashed = undashed.saturating_add(page.list.undashed);
}
if items.len() == 1 && !groups.ids.is_empty() {
writer.document_mut().set_optional_content_page_mode(true);
}
Ok(writer.finish()?)
Ok((writer.finish()?, undashed))
})
}
+22 -11
View File
@@ -22,6 +22,12 @@ pub const MAX_PNG_PIXELS: f64 = 40.0e6;
/// `svg`. `margins: [l, b, r, t]` (mm) bound the printable area of this plot (model space or a
/// layout).
pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
plot_noted(d, space, opts).map(|(bytes, _)| bytes)
}
/// [`plot`], also returning what the plot draws short of the drawing because of a render limit,
/// one note each ([`crate::undashed_note`]).
pub fn plot_noted(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, Vec<String>)> {
pdf::validate_plot_offset_json(opts)?;
if matches!(space, Space::Model)
&& opts.get("output").and_then(Value::as_str).is_some_and(|output| output.eq_ignore_ascii_case("svg"))
@@ -42,12 +48,13 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
}
_ => d,
};
match opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() {
None | Some("pdf") => pdf::plot(d, space, opts),
Some("png") => png(d, space, opts),
Some("svg") => svg(d, space, opts),
Some(other) => Err(IoError::Unsupported(other.to_string())),
}
let (bytes, undashed) = match opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() {
None | Some("pdf") => pdf::plot_noted(d, space, opts)?,
Some("png") => png(d, space, opts)?,
Some("svg") => svg(d, space, opts)?,
Some(other) => return Err(IoError::Unsupported(other.to_string())),
};
Ok((bytes, crate::undashed_note(undashed).into_iter().collect()))
}
/// The sheet a plot draws on (a model-space plot's printable area inside the device margins).
@@ -62,7 +69,8 @@ fn fit_scale(b: &Bounds2, sheet: &Sheet, o: &PdfOptions) -> f64 {
pdf::plot_scale(b, sheet, o.fit != Some(false), o.scale)
}
fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
/// The PNG plot and the dashed runs it drew continuous because of a dash limit.
fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
let o = pdf::with_saved_setup(d, space, &PdfOptions::from_json(opts));
let (sheet, page) = sheet(d, space, &o)?;
let dpi = opts.get("resolution").and_then(Value::as_f64).filter(|r| r.is_finite()).unwrap_or(300.0).clamp(50.0, 2400.0);
@@ -116,15 +124,18 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
// PDF clips a placed plot to the printable area: blank the rest of the sheet.
raster::blank_outside_printable(&mut pm, &sheet.printable, k);
}
raster::encode_png(&pm).ok_or_else(|| IoError::Format("render failed".into()))
let png = raster::encode_png(&pm).ok_or_else(|| IoError::Format("render failed".into()))?;
Ok((png, list.undashed))
}
fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
/// The SVG plot and the dashed runs it drew continuous because of a dash limit.
fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
let o = PdfOptions::from_json(opts);
let Space::Model = space else {
let (sheet, page) = sheet(d, space, &o)?;
let transparency = o.plot_transparency.unwrap_or(page.plot_transparency);
return Ok(crate::svg::export_window_with(d, space, Some(sheet.bounds()), transparency).into_bytes());
let (svg, undashed) = crate::svg::export_noted(d, space, Some(sheet.bounds()), transparency);
return Ok((svg.into_bytes(), undashed));
};
// Model space as plotted: the plot style table, lineweights, and the table's ends, joins and
// fills at the scale that fits the window (or the extents) on the device's paper.
@@ -141,7 +152,7 @@ fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
let mut list = cadcraft_render::build_plot(d, space, &ropts);
let s = fit_scale(&window.unwrap_or(list.bounds), &sheet, &o);
cadcraft_render::pen::apply(&mut list, s * sheet.unit_mm);
Ok(crate::svg::export_list(&list, window).into_bytes())
Ok((crate::svg::export_list(&list, window).into_bytes(), list.undashed))
}
#[cfg(test)]
+12 -1
View File
@@ -17,10 +17,21 @@ pub fn export_window(d: &Drawing, space: &Space, window: Option<Bounds2>) -> Str
export_window_with(d, space, window, true)
}
/// [`export_window`], also returning the dashed runs it drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]).
pub fn export_window_noted(d: &Drawing, space: &Space, window: Option<Bounds2>) -> (String, usize) {
export_noted(d, space, window, true)
}
/// [`export_window`], drawing transparency only when `transparency` is on (plots).
pub fn export_window_with(d: &Drawing, space: &Space, window: Option<Bounds2>, transparency: bool) -> String {
export_noted(d, space, window, transparency).0
}
/// [`export_window_with`] and the list's [`cadcraft_render::DisplayList::undashed`].
pub(crate) fn export_noted(d: &Drawing, space: &Space, window: Option<Bounds2>, transparency: bool) -> (String, usize) {
let list = cadcraft_render::build(d, space, &cadcraft_render::Options { transparency, ..cadcraft_render::Options::default() });
export_list(&list, window)
(export_list(&list, window), list.undashed)
}
/// Opacity for a transparent primitive (none for an opaque one or a wipeout's mask).
+577
View File
@@ -421,6 +421,400 @@ fn many_distinct_dimension_style_names_read_quickly() {
assert_eq!(styles.get(2), Some(&(name(1).as_str(), 1.0)));
}
/// Many distinct view and UCS names read in linear time, with the duplicate rule kept: a later
/// record of a name in other case replaces the first, which keeps its place and takes the later
/// record's name (#1924). The names share their first 200 bytes, so comparing two costs about that.
#[test]
fn many_distinct_view_and_ucs_names_read_quickly() {
const N: usize = 20_000;
let name = |kind: char, i: usize| format!("{kind}{}{i:06}", "x".repeat(199));
let view = |n: &str, height: u32| format!("0\nVIEW\n2\n{n}\n70\n0\n40\n{height}\n41\n1\n10\n0\n20\n0\n");
let ucs = |n: &str, x: usize| format!("0\nUCS\n2\n{n}\n70\n0\n10\n{x}\n20\n0\n30\n0\n11\n1\n21\n0\n31\n0\n12\n0\n22\n1\n32\n0\n");
let mut t = String::from("0\nSECTION\n2\nTABLES\n");
for i in 0..N {
t.push_str(&view(&name('V', i), 1));
t.push_str(&ucs(&name('U', i), i));
}
t.push_str(&view(&name('V', 0).to_ascii_uppercase(), 2));
t.push_str(&ucs(&name('U', 0).to_ascii_uppercase(), 7));
t.push_str("0\nENDSEC\n0\nEOF\n");
let started = std::time::Instant::now();
let d = read(t.as_bytes(), "many.dxf").unwrap();
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
let views: Vec<(&str, f64)> = d.views.iter().map(|v| (v.name.as_str(), v.height)).collect();
assert_eq!(views.len(), N);
assert_eq!(views.first(), Some(&(name('V', 0).to_ascii_uppercase().as_str(), 2.0)));
assert_eq!(views.get(1), Some(&(name('V', 1).as_str(), 1.0)));
let ucss: Vec<(&str, f64)> = d.ucss.iter().map(|u| (u.name.as_str(), u.origin.x)).collect();
assert_eq!(ucss.len(), N);
assert_eq!(ucss.first(), Some(&(name('U', 0).to_ascii_uppercase().as_str(), 7.0)));
assert_eq!(ucss.get(1), Some(&(name('U', 1).as_str(), 1.0)));
}
/// Layouts that each name one of many UCSs read and save in linear time, and each keeps the name of
/// its UCS (#1924). The names share their first 200 bytes, so comparing two costs about that.
#[test]
fn many_layouts_naming_many_ucss_read_and_save_quickly() {
const N: usize = 10_000;
let name = |kind: char, i: usize| format!("{kind}{}{i:06}", "x".repeat(199));
let mut t = String::from("0\nSECTION\n2\nTABLES\n");
for i in 0..N {
let u = name('U', i);
t.push_str(&format!("0\nUCS\n5\n{:X}\n2\n{u}\n70\n0\n10\n{i}\n20\n0\n30\n0\n11\n1\n21\n0\n31\n0\n12\n0\n22\n1\n32\n0\n", 0x10000 + i));
}
t.push_str("0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n");
for i in 0..N {
let l = name('L', i);
t.push_str(&format!(
"0\nLAYOUT\n5\n{:X}\n100\nAcDbPlotSettings\n100\nAcDbLayout\n1\n{l}\n71\n{}\n13\n{i}\n23\n0\n33\n0\n16\n1\n26\n0\n36\n0\n17\n0\n27\n1\n37\n0\n330\n0\n345\n{:X}\n",
0x1000 + i,
i + 1,
0x10000 + i
));
}
t.push_str("0\nENDSEC\n0\nEOF\n");
let started = std::time::Instant::now();
let d = read(t.as_bytes(), "ucss.dxf").unwrap();
let saved = write_dxf(&d);
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
let named = d.layouts.iter().filter(|l| l.ucs.as_ref().is_some_and(|u| u.name == name('U', l.tab_order as usize - 1))).count();
assert_eq!(named, N);
let again = read_dxf(saved.as_bytes()).unwrap();
assert_eq!(again.layouts.iter().filter(|l| l.ucs.as_ref().is_some_and(|u| !u.name.is_empty())).count(), N);
}
/// A layout's named UCS is the first UCS of that name, without case, whose frame is the layout's:
/// what scanning the UCSs finds, also when a name's first UCS has another frame.
#[test]
fn a_layouts_named_ucs_is_the_first_of_its_name_with_its_frame() {
use cadcraft_geom::Vec3;
let ucs = |name: &str, x: f64| Ucs {
name: name.into(),
origin: Vec3::new(x, 0.0, 0.0),
x_axis: Vec3::new(1.0, 0.0, 0.0),
y_axis: Vec3::new(0.0, 1.0, 0.0),
};
let ucss = [ucs("Front", 0.0), ucs("FRONT", 1.0), ucs("front", 1.0), ucs("Side", 2.0), ucs("", 3.0), ucs(" Pad", 4.0)];
let names = crate::dxf_ext::UcsNames::new(&ucss);
let (x, y) = (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0));
for name in ["Front", "front", "FRONT", " front ", "Side", "side", "", " ", "Pad", " Pad", "Back"] {
for origin in [0.0, 1.0, 2.0, 3.0, 4.0, 5.0].map(|o| Vec3::new(o, 0.0, 0.0)) {
let want = crate::dxf_ext::named_ucs(&ucss, name, origin, x, y).map(std::ptr::from_ref);
assert_eq!(names.named(name, origin, x, y).map(std::ptr::from_ref), want, "{name:?} {origin:?}");
}
}
assert_eq!(names.named("front", Vec3::new(1.0, 0.0, 0.0), x, y).map(|u| u.name.as_str()), Some("FRONT"));
}
/// Many distinct table and multileader style names read in linear time, with the duplicate rule
/// kept: a later style of a name in other case replaces the first, which keeps its place and takes
/// the later style's name, also the Standard style a drawing starts with (#1924). The names share
/// their first 200 bytes, so comparing two costs about that.
#[test]
fn many_distinct_table_and_multileader_style_names_read_quickly() {
const N: usize = 20_000;
let name = |kind: char, i: usize| format!("{kind}{}{i:06}", "x".repeat(199));
// Each style: a dictionary entry naming its handle, and the object (TABLESTYLE margin 40 or
// MLEADERSTYLE arrow size 44 set to `v`).
let mut entries = String::new();
let mut objects = String::new();
let mut h = 0x1000;
let mut style = |kind: &str, n: &str, v: f64| {
h += 1;
entries.push_str(&format!("3\n{n}\n350\n{h:X}\n"));
let own = if kind == "TABLESTYLE" { format!("100\nAcDbTableStyle\n40\n{v}\n") } else { format!("100\nAcDbMLeaderStyle\n44\n{v}\n") };
objects.push_str(&format!("0\n{kind}\n5\n{h:X}\n{own}"));
};
for (kind, k) in [("TABLESTYLE", 'T'), ("MLEADERSTYLE", 'M')] {
for i in 0..N {
style(kind, &name(k, i), 1.0);
}
style(kind, &name(k, 0).to_ascii_uppercase(), 2.0);
style(kind, "STANDARD", 3.0);
}
let t = format!("0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nA0\n100\nAcDbDictionary\n{entries}{objects}0\nENDSEC\n0\nEOF\n");
let started = std::time::Instant::now();
let d = read(t.as_bytes(), "many.dxf").unwrap();
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
let tables: Vec<(&str, f64)> = d.table_styles.iter().map(|s| (s.name.as_str(), s.margin)).collect();
let mleaders: Vec<(&str, f64)> = d.mleader_styles.iter().map(|s| (s.name.as_str(), s.arrow_size)).collect();
for (styles, k) in [(tables, 'T'), (mleaders, 'M')] {
assert_eq!(styles.len(), N + 1);
assert_eq!(styles.first(), Some(&("STANDARD", 3.0)));
assert_eq!(styles.get(1), Some(&(name(k, 0).to_ascii_uppercase().as_str(), 2.0)));
assert_eq!(styles.get(2), Some(&(name(k, 1).as_str(), 1.0)));
}
}
/// The most multiline styles a file can hold, with long names, read in linear time, with the
/// duplicate rule kept: a later style of a name in other case replaces the first, which keeps its
/// place and takes the later style's name, also the STANDARD style a drawing starts with (#1924).
/// The names share their first 1 000 bytes, so comparing two costs about that.
#[test]
fn many_multiline_style_names_read_quickly() {
const N: usize = 9_998;
let name = |i: usize| format!("L{}{i:06}", "x".repeat(999));
let style = |n: &str, description: &str| format!("0\nMLINESTYLE\n100\nAcDbMlineStyle\n2\n{n}\n70\n0\n3\n{description}\n71\n1\n49\n0\n");
let mut t = String::from("0\nSECTION\n2\nOBJECTS\n");
for i in 0..N {
t.push_str(&style(&name(i), "first"));
}
t.push_str(&style(&name(0).to_ascii_uppercase(), "second"));
t.push_str(&style("standard", "third"));
t.push_str("0\nENDSEC\n0\nEOF\n");
let started = std::time::Instant::now();
let d = read(t.as_bytes(), "mlines.dxf").unwrap();
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
let styles: Vec<(&str, &str)> = d.mline_styles.iter().map(|s| (s.name.as_str(), s.description.as_str())).collect();
assert_eq!(styles.len(), N + 1);
assert_eq!(styles.first(), Some(&("standard", "third")));
assert_eq!(styles.get(1), Some(&(name(0).to_ascii_uppercase().as_str(), "second")));
assert_eq!(styles.get(2), Some(&(name(1).as_str(), "first")));
}
/// Many viewport configurations read in linear time, with the rule kept: a record adds a tile to
/// the first configuration of its name, in any case, which keeps its own name, also from a later
/// TABLES section (#1924). The names share their first 200 bytes, so comparing two costs about
/// that.
#[test]
fn many_viewport_configurations_read_quickly() {
const N: usize = 20_000;
let name = |i: usize| format!("V{}{i:06}", "x".repeat(199));
let record = |n: &str, x: f64| format!("0\nVPORT\n2\n{n}\n70\n0\n10\n0\n20\n0\n11\n1\n21\n1\n12\n{x}\n22\n0\n40\n10\n41\n1\n");
let mut t = String::from("0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n");
for i in 0..N {
t.push_str(&record(&name(i), 1.0));
}
t.push_str(&record(&name(0).to_ascii_uppercase(), 2.0));
t.push_str("0\nENDTAB\n0\nENDSEC\n0\nSECTION\n2\nTABLES\n0\nTABLE\n2\nVPORT\n");
t.push_str(&record(&name(1).to_ascii_uppercase(), 3.0));
t.push_str("0\nENDTAB\n0\nENDSEC\n0\nEOF\n");
let started = std::time::Instant::now();
let d = read(t.as_bytes(), "vports.dxf").unwrap();
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
let configs: Vec<(&str, Vec<f64>)> =
d.vports.iter().filter(|c| c.name.starts_with('V')).map(|c| (c.name.as_str(), c.tiles.iter().map(|t| t.center.x).collect())).collect();
assert_eq!(configs.len(), N);
assert_eq!(configs.first(), Some(&(name(0).as_str(), vec![1.0, 2.0])));
assert_eq!(configs.get(1), Some(&(name(1).as_str(), vec![1.0, 3.0])));
assert_eq!(configs.get(2), Some(&(name(2).as_str(), vec![1.0])));
}
/// The value of group `code` in each record of type `kind` (its first, if repeated), in file order.
fn first_groups(p: &[(String, String)], kind: &str, code: &str) -> Vec<String> {
let mut out = Vec::new();
let (mut inside, mut found) = (false, false);
for (c, v) in p {
if c == "0" {
(inside, found) = (v.trim() == kind, false);
} else if inside && !found && c == code {
out.push(v.trim().to_string());
found = true;
}
}
out
}
/// Every dictionary entry: its handle to its name.
fn entry_names(p: &[(String, String)]) -> std::collections::HashMap<String, String> {
let mut out = std::collections::HashMap::new();
let (mut inside, mut name) = (false, None);
for (c, v) in p {
match c.as_str() {
"0" => (inside, name) = (v.trim() == "DICTIONARY", None),
"3" if inside => name = Some(v.trim().to_string()),
"350" | "360" if inside => {
if let Some(n) = name.take() {
out.insert(v.trim().to_string(), n);
}
}
_ => {}
}
}
out
}
/// Saving many multileaders among many multileader styles takes linear time (#1924), and each is
/// written as before: pointing at the first style of its name (ignoring case), else at the
/// drawing's first style, with the landing gap of the first style of its name, else the default
/// one. The names share their first 200 bytes, so comparing two costs about that.
#[test]
fn many_multileaders_among_many_styles_save_quickly() {
const N: usize = 10_000;
let name = |i: usize| format!("M{}{i:06}", "x".repeat(199));
let missing = |i: usize| format!("M{}z{i:05}", "x".repeat(199));
let mut d = Drawing::new_imperial();
if let Some(first) = d.mleader_styles.first_mut() {
first.landing_gap = 0.25;
}
d.mleader_styles.extend((0..N).map(|i| MLeaderStyle { name: name(i), landing_gap: 0.5, ..MLeaderStyle::default() }));
d.mleader_styles.push(MLeaderStyle { name: name(N - 1).to_ascii_uppercase(), landing_gap: 0.75, ..MLeaderStyle::default() });
let mleader = |style: String, x: f64| {
EntityKind::MLeader(MLeader {
leaders: vec![vec![Vec3::new(x, 0.0, 0.0), Vec3::new(x + 1.0, 1.0, 0.0)]],
landing: Vec3::new(x + 2.0, 1.0, 0.0),
dogleg: 0.5,
text: None,
style,
arrow_size: 1.0,
spline: false,
block: None,
})
};
for i in 0..N {
d.add(&Space::Model, Common::default(), mleader(missing(i), i as f64)).unwrap();
}
d.add(&Space::Model, Common::default(), mleader(name(N - 1).to_ascii_uppercase(), -1.0)).unwrap();
// As a MULTILEADER (R2007 and later): older files get a LEADER and its content instead.
let started = std::time::Instant::now();
let saved = dxf_2018(&d);
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
let p = pairs(&saved);
let entries = entry_names(&p);
let styles: Vec<&str> = first_groups(&p, "MULTILEADER", "340").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect();
let gaps: Vec<f64> = first_groups(&p, "MULTILEADER", "145").iter().filter_map(|v| v.parse().ok()).collect();
assert_eq!((styles.len(), gaps.len()), (N + 1, N + 1));
let default_gap = MLeaderStyle::default().landing_gap;
assert!(styles[..N].iter().all(|s| *s == "Standard"), "a missing style points at the first style");
assert!(gaps[..N].iter().all(|g| *g == default_gap), "a missing style writes the default landing gap");
assert_eq!((styles[N], gaps[N]), (name(N - 1).as_str(), 0.5), "the first style of the name");
}
/// A multileader's own groups (AutoLISP's entity data) carry its style's landing gap, found
/// without the styles a save plans.
#[test]
fn a_multileaders_entity_groups_have_its_styles_landing_gap() {
let mut d = Drawing::new_imperial();
d.mleader_styles.push(MLeaderStyle { name: "Notes".into(), landing_gap: 0.5, ..MLeaderStyle::default() });
let m = MLeader {
leaders: vec![vec![Vec3::new(0.0, 0.0, 0.0), Vec3::new(1.0, 1.0, 0.0)]],
landing: Vec3::new(2.0, 1.0, 0.0),
dogleg: 0.5,
text: None,
style: "NOTES".into(),
arrow_size: 1.0,
spline: false,
block: None,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::MLeader(m)).unwrap();
let e = d.entity(h).unwrap().clone();
let (kind, tags) = entity_groups(&d, &e);
assert_eq!(kind, "MULTILEADER");
assert_eq!(tags.iter().find(|t| t.code == 145).map(|t| t.f64()), Some(0.5));
}
/// Many tables from another writer naming a table style the file lacks, among many table styles,
/// read and save in linear time (#1924). Each table takes the text height of the style of its
/// name (ignoring case), else the default one, as before, and is saved pointing at that style,
/// else at the drawing's first one. The names share their first 200 bytes.
#[test]
fn many_tables_among_many_table_styles_read_and_save_quickly() {
const N: usize = 10_000;
let name = |i: usize| format!("T{}{i:06}", "x".repeat(199));
let missing = format!("T{}z{:05}", "x".repeat(199), 0);
let upper = name(N - 1).to_ascii_uppercase();
// Tables whose style (342) is a dictionary entry with no TABLESTYLE: the missing name for the
// first N, the last style's name in upper case for the last one.
let mut t = String::from("0\nSECTION\n2\nENTITIES\n");
for i in 0..=N {
let style = if i < N { "F0000" } else { "F0001" };
t.push_str(&format!(
"0\nACAD_TABLE\n5\n{:X}\n100\nAcDbBlockReference\n10\n{i}\n20\n0\n30\n0\n100\nAcDbTable\n342\n{style}\n91\n1\n92\n1\n141\n1\n142\n1\n",
0x100000 + i
));
}
t.push_str(&format!(
"0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n0\nDICTIONARY\n5\nA0\n100\nAcDbDictionary\n3\n{missing}\n350\nF0000\n3\n{upper}\n350\nF0001\n"
));
for i in 0..N {
t.push_str(&format!("3\n{}\n350\n{:X}\n", name(i), 0x10000 + i));
}
for i in 0..N {
t.push_str(&format!("0\nTABLESTYLE\n5\n{:X}\n100\nAcDbTableStyle\n7\n\n140\n0.5\n", 0x10000 + i));
}
t.push_str("0\nENDSEC\n0\nEOF\n");
let started = std::time::Instant::now();
let d = read(t.as_bytes(), "tables.dxf").unwrap();
let saved = write_dxf(&d);
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
let tables: Vec<(&str, f64)> =
d.model.iter().filter_map(|e| if let EntityKind::Table(t) = &e.kind { Some((t.style.as_str(), t.text_height)) } else { None }).collect();
let default_height = TableStyle::default().text_height;
assert_eq!(tables.len(), N + 1);
assert!(tables[..N].iter().all(|t| *t == (missing.as_str(), default_height)), "a missing style gives the default height");
assert_eq!(tables[N], (upper.as_str(), 0.5), "the style of the name in other case");
let p = pairs(&saved);
let entries = entry_names(&p);
let styles: Vec<&str> = first_groups(&p, "ACAD_TABLE", "342").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect();
assert_eq!(styles.len(), N + 1);
assert!(styles[..N].iter().all(|s| *s == "Standard"), "a missing style points at the first style");
assert_eq!(styles[N], name(N - 1));
}
/// Saving many multilines that each name a style the drawing lacks takes linear time (#1924). As
/// before, each missing style is written once, with the elements of the first multiline naming it,
/// and each multiline points at the first style of its name, ignoring case and surrounding spaces,
/// or at STANDARD when it names none.
#[test]
fn many_multilines_naming_missing_styles_save_quickly() {
const N: usize = 10_000;
let missing = |i: usize| format!("L{}{i:06}", "x".repeat(199));
let mut d = Drawing::new_imperial();
let mline = |style: String, x: f64| {
let def = MLineStyle { name: style.clone(), ..MLineStyle::default() };
let vertex = |x: f64| MLineVertex { p: Vec3::new(x, 0.0, 0.0), cuts: Vec::new() };
EntityKind::MLine(MLine {
style,
def,
scale: 1.0,
justification: MLineJust::default(),
closed: false,
no_start_caps: false,
no_end_caps: false,
vertices: vec![vertex(x), vertex(x + 1.0)],
})
};
for i in 0..N {
d.add(&Space::Model, Common::default(), mline(missing(i), i as f64)).unwrap();
}
d.add(&Space::Model, Common::default(), mline(missing(N - 1).to_ascii_uppercase(), -1.0)).unwrap();
let mut padded = mline(format!(" {} ", missing(0)), -2.0);
if let EntityKind::MLine(m) = &mut padded {
m.def.elements = vec![MLineElement { offset: 0.25, ..MLineElement::default() }];
}
d.add(&Space::Model, Common::default(), padded).unwrap();
d.add(&Space::Model, Common::default(), mline(" ".into(), -3.0)).unwrap();
let started = std::time::Instant::now();
let saved = write_dxf(&d);
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
let p = pairs(&saved);
let entries = entry_names(&p);
let styles: Vec<&str> = first_groups(&p, "MLINE", "340").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect();
let want: Vec<String> = (0..N).map(missing).chain([missing(N - 1), missing(0), "STANDARD".into()]).collect();
assert_eq!(styles, want);
assert_eq!(first_groups(&p, "MLINESTYLE", "2").len(), N + 1, "STANDARD and each missing style once");
let offsets: Vec<f64> = first_groups(&p, "MLINESTYLE", "49").iter().filter_map(|v| v.parse().ok()).collect();
assert!(offsets.len() == N + 1 && !offsets.contains(&0.25), "a later multiline does not change the style");
}
/// A multiline style whose name has spaces around it in the file is read with the name trimmed, so
/// its multilines, whose lookup trims, find it: a save writes it once and points them at it.
#[test]
fn a_padded_multiline_style_name_is_saved_once() {
let t = "0\nSECTION\n2\nENTITIES\n0\nMLINE\n5\n100\n100\nAcDbEntity\n8\n0\n100\nAcDbMline\n2\n Road \n40\n1\n70\n0\n71\n1\n72\n2\n73\n2\n\
10\n0\n20\n0\n30\n0\n11\n0\n21\n0\n31\n0\n12\n1\n22\n0\n32\n0\n13\n0\n23\n1\n33\n0\n74\n2\n41\n0\n41\n0\n75\n0\n74\n2\n41\n0\n41\n0\n75\n0\n\
11\n1\n21\n0\n31\n0\n12\n1\n22\n0\n32\n0\n13\n0\n23\n1\n33\n0\n74\n2\n41\n0\n41\n0\n75\n0\n74\n2\n41\n0\n41\n0\n75\n0\n\
0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n0\nMLINESTYLE\n5\n200\n100\nAcDbMlineStyle\n2\n Road \n70\n0\n3\npadded\n71\n2\n\
49\n0.25\n62\n256\n6\nBYLAYER\n49\n-0.25\n62\n256\n6\nBYLAYER\n0\nENDSEC\n0\nEOF\n";
let d = read(t.as_bytes(), "padded.dxf").unwrap();
assert_eq!(d.mline_styles.iter().map(|s| s.name.as_str()).collect::<Vec<_>>(), ["STANDARD", "Road"]);
let p = pairs(&write_dxf(&d));
let entries = entry_names(&p);
assert_eq!(first_groups(&p, "MLINESTYLE", "2"), ["STANDARD", "Road"], "one Road style");
let styles: Vec<&str> = first_groups(&p, "MLINE", "340").iter().filter_map(|h| entries.get(h)).map(String::as_str).collect();
assert_eq!(styles, ["Road"]);
}
/// Many layouts with every paper-space object in one of the last of them read in linear time.
/// Each object goes to the first layout of its exact name, as before: not to an earlier one whose
/// name differs only in case, nor to a later one of the same name (#1924).
@@ -3655,6 +4049,189 @@ fn mirrored_mtext_extrusion_keeps_its_footprint() {
assert!(b.min.x > -0.2 && b.max.x > 0.5 && b.min.y > -0.2 && b.max.y > 0.5, "box right of and above (0,0): {b:?}");
}
/// Attributes in the plane of extrusion `n` (#3541): the DXF of block BL holding two ATTDEFs that
/// start at world point `start` and turn `degrees` in that plane (LEFT, and RIGHT, right-justified,
/// whose baseline ends 20 units on), a reference to BL at the origin whose two ATTRIBs repeat
/// them, and a 100 × 60 rectangle round `start`. Groups 10 and 11 hold OCS coordinates (DXF
/// Reference, ATTDEF and ATTRIB), worked out here with the arbitrary axis algorithm. Also returns
/// the world end of RIGHT's baseline and the world direction the attributes run in.
fn tilted_attribute_dxf(n: Vec3, start: Vec3, degrees: f64) -> (String, Vec3, Vec3) {
// Ax = Wy × N when N is near the Z axis (|Nx| and |Ny| under 1/64), else Wz × N; Ay = N × Ax.
let n = n.normalized();
let near_z = n.x.abs() < 1.0 / 64.0 && n.y.abs() < 1.0 / 64.0;
let ax = if near_z { Vec3::new(0.0, 1.0, 0.0) } else { Vec3::Z }.cross(n).normalized();
let ay = n.cross(ax).normalized();
let pt = |code: i32, p: Vec3| format!("{code}\n{}\n{}\n{}\n{}\n{}\n", p.dot(ax), code + 10, p.dot(ay), code + 20, p.dot(n));
let turn = degrees.to_radians();
let dir = ax * turn.cos() + ay * turn.sin();
let end = start + dir * 20.0;
let attribute = |kind: &str, tag: &str| {
let right = if tag == "RIGHT" { format!("72\n2\n{}", pt(11, end)) } else { String::new() };
let prompt = if kind == "ATTDEF" { "3\nValue\n" } else { "" };
format!(
"0\n{kind}\n8\n0\n{}40\n3\n1\n{tag}\n50\n{degrees}\n210\n{}\n220\n{}\n230\n{}\n{prompt}2\n{tag}\n70\n0\n{right}",
pt(10, start),
n.x,
n.y,
n.z
)
};
let (x0, y0, x1, y1) = (start.x - 50.0, start.y - 30.0, start.x + 50.0, start.y + 30.0);
let text = format!(
"0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n8\n0\n2\nBL\n70\n2\n10\n0\n20\n0\n30\n0\n3\nBL\n{}{}0\nENDBLK\n8\n0\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n4\n70\n1\n10\n{x0}\n20\n{y0}\n10\n{x1}\n20\n{y0}\n10\n{x1}\n20\n{y1}\n10\n{x0}\n20\n{y1}\n\
0\nINSERT\n8\n0\n66\n1\n2\nBL\n10\n0\n20\n0\n30\n0\n{}{}0\nSEQEND\n8\n0\n0\nENDSEC\n0\nEOF\n",
attribute("ATTDEF", "LEFT"),
attribute("ATTDEF", "RIGHT"),
attribute("ATTRIB", "LEFT"),
attribute("ATTRIB", "RIGHT"),
);
(text, end, dir)
}
/// The ATTDEFs of block BL (with their extrusions) and the ATTRIBs of the first block reference.
fn attributes(d: &Drawing) -> (Vec<(Attrib, Vec3)>, Vec<Attrib>) {
let defs = d.block("BL").expect("block BL").entities.iter();
let defs = defs.filter_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some((a.clone(), e.common.extrusion)) } else { None });
let refs = first(d, |k| if let EntityKind::Insert(i) = k { Some(i.attribs.clone()) } else { None });
(defs.collect(), refs)
}
/// Issue #3541: an ATTDEF and an ATTRIB in a tilted plane near survey coordinates are read at their
/// world points, turned the way the plane runs in plan, and drawn there, not millions of units
/// away at their OCS coordinates read as world ones.
#[test]
fn tilted_attributes_are_read_at_their_world_points() {
let start = Vec3::new(550_050.0, 9_580_030.0, 0.0);
let (text, end, dir) = tilted_attribute_dxf(Vec3::new(0.3, -0.2, 0.93), start, 30.0);
let d = read(text.as_bytes(), "a.dxf").unwrap();
let plan = dir.xy().normalized();
let check = |a: &Attrib, what: &str| {
assert!((a.text.insert - start).len() < 1e-6, "{what} {} insert {:?}", a.tag, a.text.insert);
if a.tag == "RIGHT" {
let at = a.text.align_pt.expect("a right-justified attribute keeps its alignment point");
assert!((at - end).len() < 1e-6, "{what} RIGHT alignment point {at:?}, want {end:?}");
}
let runs = Vec2::new(a.text.rotation.cos(), a.text.rotation.sin());
assert!((runs - plan).len() < 1e-9, "{what} {} runs along {runs:?}, want {plan:?}", a.tag);
};
let (defs, refs) = attributes(&d);
assert_eq!((defs.len(), refs.len()), (2, 2));
for (a, extrusion) in &defs {
check(a, "ATTDEF");
// Its points are plan coordinates now, so the plane they were in is spent.
assert_eq!(*extrusion, Vec3::Z, "ATTDEF {}", a.tag);
}
for a in &refs {
check(a, "ATTRIB");
}
// The ATTRIBs are drawn inside the rectangle's neighbourhood.
let b = cadcraft_render::build(&d, &Space::Model, &cadcraft_render::Options::default()).bounds;
assert!(b.min.x > start.x - 80.0 && b.max.x < start.x + 80.0 && b.min.y > start.y - 60.0 && b.max.y < start.y + 60.0, "drawn over {b:?}");
// In a plane standing on edge (normal along X) a direction turned -90° runs straight down and
// leaves no direction in plan: the attributes keep the file's turn, at their world points.
let (text, _, _) = tilted_attribute_dxf(Vec3::new(1.0, 0.0, 0.0), start, -90.0);
let d = read(text.as_bytes(), "edge.dxf").unwrap();
let (defs, refs) = attributes(&d);
for a in defs.iter().map(|(a, _)| a).chain(&refs) {
assert!((a.text.insert - start).len() < 1e-6, "{} insert {:?}", a.tag, a.text.insert);
assert!((a.text.rotation - (-90f64).to_radians()).abs() < 1e-12, "{} rotation {}", a.tag, a.text.rotation);
}
}
/// Issue #3541, on save: tilted attributes are written at their world points with no plane
/// (groups 10 and 11 in the WCS, no 210), and reopened where they were read.
#[test]
fn tilted_attributes_are_saved_at_their_world_points_and_reopened_there() {
let start = Vec3::new(550_050.0, 9_580_030.0, 0.0);
let (text, end, _) = tilted_attribute_dxf(Vec3::new(0.3, -0.2, 0.93), start, 30.0);
let d = read(text.as_bytes(), "a.dxf").unwrap();
let out = write_dxf(&d);
let pairs = dxf_pairs(&out);
for kind in ["ATTDEF", "ATTRIB"] {
let recs = dxf_records(&pairs, kind);
assert_eq!(recs.len(), 2, "{kind}");
for r in recs {
let num = |code: i32, default: f64| group(r, &code.to_string()).map_or(default, |v| v.parse::<f64>().unwrap());
let point = |code: i32, default_z: f64| Vec3::new(num(code, 0.0), num(code + 10, 0.0), num(code + 20, default_z));
let tag = group(r, "2").unwrap_or_default();
assert_eq!(point(210, 1.0), Vec3::Z, "{kind} {tag} is written with a plane");
let (code, want) = if tag == "RIGHT" { (11, end) } else { (10, start) };
assert!((point(code, 0.0) - want).len() < 1e-6, "{kind} {tag} group {code}: {:?}, want {want:?}", point(code, 0.0));
}
}
let back = read_dxf(out.as_bytes()).unwrap();
let ((defs, refs), (defs2, refs2)) = (attributes(&d), attributes(&back));
let same = |a: &Attrib, b: &Attrib| {
assert_eq!(a.tag, b.tag);
// A justified attribute is placed by its alignment point: the writer derives its group 10
// from it (#1050), so only a baseline-left one keeps its own.
if a.text.align_pt.is_none() {
assert!((a.text.insert - b.text.insert).len() < 1e-6, "{} insert {:?} came back as {:?}", a.tag, a.text.insert, b.text.insert);
}
assert!(a.text.align_pt.zip(b.text.align_pt).is_none_or(|(p, q)| (p - q).len() < 1e-6), "{} alignment point", a.tag);
assert_eq!(a.text.align_pt.is_some(), b.text.align_pt.is_some(), "{} alignment point", a.tag);
assert!((a.text.rotation - b.text.rotation).abs() < 1e-9, "{} rotation {} came back as {}", a.tag, a.text.rotation, b.text.rotation);
};
assert_eq!((defs2.len(), refs2.len()), (2, 2));
for ((a, _), (b, extrusion)) in defs.iter().zip(&defs2) {
same(a, b);
assert_eq!(*extrusion, Vec3::Z, "ATTDEF {}", b.tag);
}
for (a, b) in refs.iter().zip(&refs2) {
same(a, b);
}
}
/// A block reference in a tilted plane is still read as is (its block drawn at the OCS point read),
/// so the ATTRIBs in that plane stay as read too, on the block's own ATTDEFs, rather than mapped
/// away from the block.
#[test]
fn attributes_of_a_tilted_reference_stay_with_its_block() {
let start = Vec3::new(50.0, 30.0, 0.0);
let (flat, _, _) = tilted_attribute_dxf(Vec3::Z, start, 30.0);
let (blocks, reference) = flat.split_once("0\nINSERT\n").unwrap();
let plane = "210\n0.3\n220\n-0.2\n230\n0.93\n";
let flat_plane = "210\n0\n220\n0\n230\n1\n";
assert_eq!(reference.matches(flat_plane).count(), 2);
let text = format!("{blocks}0\nINSERT\n{plane}{}", reference.replace(flat_plane, plane));
let d = read(text.as_bytes(), "r.dxf").unwrap();
let (defs, refs) = attributes(&d);
assert_eq!(refs.len(), 2);
for a in &refs {
let def = defs.iter().find(|(def, _)| def.tag == a.tag).expect("its definition");
assert_eq!(a.text.insert, def.0.text.insert, "{} left its definition", a.tag);
}
}
/// Attributes on the Z axis are read exactly as written, and saved so; a plane facing down keeps
/// the mirrored reading, which maps its points once (#3541 changes neither).
#[test]
fn flat_and_mirrored_attributes_read_as_before() {
let start = Vec3::new(550_050.125, 9_580_030.375, 12.5);
// A turn of -30° stays -30° (taken through the plane it would come back as 330°).
let (text, _, _) = tilted_attribute_dxf(Vec3::Z, start, -30.0);
let d = read(text.as_bytes(), "flat.dxf").unwrap();
let (defs, refs) = attributes(&d);
for a in defs.iter().map(|(a, _)| a).chain(&refs) {
assert_eq!((a.text.insert, a.text.rotation), (start, (-30f64).to_radians()), "{}", a.tag);
}
let out = write_dxf(&d);
let pairs = dxf_pairs(&out);
for r in dxf_records(&pairs, "ATTDEF").into_iter().chain(dxf_records(&pairs, "ATTRIB")).filter(|r| group(r, "2") == Some("LEFT")) {
let num = |code: &str| group(r, code).map(|v| v.parse::<f64>().unwrap());
assert_eq!((num("10"), num("20"), num("30"), num("210")), (Some(start.x), Some(start.y), Some(start.z), None));
}
// Facing down and tilted: the mirrored reading maps the start point once, to `start`.
let (text, _, _) = tilted_attribute_dxf(Vec3::new(0.6, 0.0, -0.8), start, 30.0);
let d = read(text.as_bytes(), "down.dxf").unwrap();
let (defs, refs) = attributes(&d);
for a in defs.iter().map(|(a, _)| a).chain(&refs).filter(|a| a.tag == "LEFT") {
assert!((a.text.insert - start).len() < 1e-6, "{} insert {:?}, want {start:?}", a.tag, a.text.insert);
}
}
// --- SVG import ---
/// One 20mm×10mm page whose user units are millimetres; the reader flips Y, so a point at
+277
View File
@@ -41,6 +41,283 @@ fn minsert(cols: u32, rows: u32) -> String {
)
}
/// A linear dimension drawn by block `block`, its dimension line at height `y`.
fn dimension(block: &str, y: usize) -> String {
format!("0\nDIMENSION\n2\n{block}\n3\nStandard\n10\n100\n20\n{}\n11\n50\n21\n{}\n70\n0\n13\n0\n23\n{y}\n14\n100\n24\n{y}\n", y + 5, y + 5)
}
const LINE: &str = "0\nLINE\n10\n0\n20\n0\n11\n1\n21\n1\n";
/// What dimension block `*D1` holds on its way back to itself.
#[derive(Clone, Copy, Debug)]
enum Via {
/// Dimensions drawn by `*D1`.
Nothing,
/// References to block `B`, which holds a dimension drawn by `*D1`.
Reference,
/// Dimensions drawn by `*D2`, which holds a dimension drawn by `*D1`.
Dimension,
}
/// Dimension block `*D1` holds a line and `refs` dimensions or references that lead back to `*D1`
/// (`via`); the block on the way holds a line too. Model space holds one dimension drawn by `*D1`,
/// and a reference to `B` when there is one, so the loop is also entered from `B`. With `closed`
/// false, the first dimension inside a block on the way is drawn by `*D9`, a block the file lacks,
/// so nothing leads back.
fn dimension_loop(refs: usize, via: Via, closed: bool) -> String {
let back = if closed { "*D1" } else { "*D9" };
let mut s = String::from("0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\n*D1\n70\n1\n10\n0\n20\n0\n");
for k in 0..refs {
s += &match via {
Via::Nothing => dimension(back, k * 10),
Via::Reference => format!("0\nINSERT\n2\nB\n10\n{k}\n20\n0\n"),
Via::Dimension => dimension(if closed { "*D2" } else { "*D9" }, k * 10),
};
}
s += LINE;
s += "0\nENDBLK\n";
match via {
Via::Nothing => {}
Via::Reference => s += &format!("0\nBLOCK\n2\nB\n70\n0\n10\n0\n20\n0\n{}{LINE}0\nENDBLK\n", dimension(back, 0)),
Via::Dimension => s += &format!("0\nBLOCK\n2\n*D2\n70\n1\n10\n0\n20\n0\n{}{LINE}0\nENDBLK\n", dimension("*D1", 0)),
}
s += "0\nENDSEC\n0\nSECTION\n2\nENTITIES\n";
s += &dimension("*D1", 0);
if matches!(via, Via::Reference) {
s += "0\nINSERT\n2\nB\n10\n200\n20\n0\n";
}
s + "0\nENDSEC\n0\nEOF\n"
}
/// Dimension blocks `*D1`..`*Dn` each hold a line and a reference to block `B`, which holds a
/// dimension drawn by each of them; model space holds a dimension drawn by `*D1`. Every ordering
/// of the blocks is a way round the loop.
fn loop_of_blocks(n: usize) -> String {
let mut s = String::from("0\nSECTION\n2\nBLOCKS\n");
for i in 1..=n {
s += &format!("0\nBLOCK\n2\n*D{i}\n70\n1\n10\n0\n20\n0\n0\nINSERT\n2\nB\n10\n0\n20\n0\n{LINE}0\nENDBLK\n");
}
s += "0\nBLOCK\n2\nB\n70\n0\n10\n0\n20\n0\n";
for i in 1..=n {
s += &dimension(&format!("*D{i}"), i * 10);
}
s + "0\nENDBLK\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n" + &dimension("*D1", 0) + "0\nENDSEC\n0\nEOF\n"
}
/// Dimension blocks `*D1`..`*Dn` in a ring: each holds a line and three dimensions drawn by the
/// next, the last by `*D1`. Model space holds a dimension drawn by `*D1`.
fn ring_of_blocks(n: usize) -> String {
let mut s = String::from("0\nSECTION\n2\nBLOCKS\n");
for i in 1..=n {
let next = format!("*D{}", i % n + 1);
s += &format!("0\nBLOCK\n2\n*D{i}\n70\n1\n10\n0\n20\n0\n{LINE}");
for k in 0..3 {
s += &dimension(&next, k * 10);
}
s += "0\nENDBLK\n";
}
s + "0\nENDSEC\n0\nSECTION\n2\nENTITIES\n" + &dimension("*D1", 0) + "0\nENDSEC\n0\nEOF\n"
}
/// Dimension blocks nested without a cycle. `*D3` holds the only line, from (0, 0) to (1, 1);
/// `*D2` holds a dimension drawn by `*D3`; `*D1` holds two dimensions drawn by `*D2` and a
/// reference to block `B`, which holds a dimension drawn by `*D2`. Model space holds a dimension
/// drawn by `*D1` and two references to `B`.
fn nested_dimensions() -> String {
let block = |name: &str, body: &str| format!("0\nBLOCK\n2\n{name}\n70\n{}\n10\n0\n20\n0\n{body}0\nENDBLK\n", u8::from(name.starts_with('*')));
let mut s = String::from("0\nSECTION\n2\nBLOCKS\n");
s += &block("*D3", "0\nLINE\n10\n0\n20\n0\n11\n1\n21\n1\n");
s += &block("*D2", &dimension("*D3", 0));
s += &block("B", &dimension("*D2", 0));
s += &block("*D1", &(dimension("*D2", 0) + &dimension("*D2", 10) + "0\nINSERT\n2\nB\n10\n5\n20\n0\n"));
s + "0\nENDSEC\n0\nSECTION\n2\nENTITIES\n"
+ &dimension("*D1", 0)
+ "0\nINSERT\n2\nB\n10\n20\n20\n0\n0\nINSERT\n2\nB\n10\n40\n20\n0\n0\nENDSEC\n0\nEOF\n"
}
/// A dimension inside a block whose own block leads back to that block (the same block, or
/// through a reference or another dimension block) is drawn as one whose block is missing: from
/// its definition points. It used to draw the block again at every level down to
/// `MAX_BLOCK_DEPTH` (#1923).
#[test]
fn a_dimension_whose_block_leads_back_draws_as_one_whose_block_is_missing() {
for via in [Via::Nothing, Via::Reference, Via::Dimension] {
let closed = build(&read(&dimension_loop(1, via, true)), &Space::Model, &Options::default());
let open = build(&read(&dimension_loop(1, via, false)), &Space::Model, &Options::default());
assert!(!open.prims.is_empty());
assert_eq!((closed.prims.len(), &closed.verts), (open.prims.len(), &open.verts), "via {via:?}");
}
}
/// Many dimensions that lead back to their block (directly, or through as many references or
/// dimensions), dimension blocks that lead to each other, or a long ring of them, drew the blocks
/// again at every level: up to 300^16 times, or once per ordering of the blocks, until the
/// expansion budget ran out and the rest was left out. Now nothing goes round a loop, so the
/// drawing is whole. A block of 300 references and a ring of 20 blocks are more than the search
/// near a dimension's block looks at, so the whole block graph answers for them. Their extents use
/// the shared block cache (#1850) and stay finite.
#[test]
fn dimensions_on_block_loops_draw_whole() {
let files = [Via::Nothing, Via::Reference, Via::Dimension].map(|via| dimension_loop(300, via, true));
for (i, text) in files.iter().chain([&loop_of_blocks(10), &ring_of_blocks(20)]).enumerate() {
let d = read(text);
let ext = d.extents(&Space::Model);
assert!(!ext.is_empty() && ext.min.is_finite() && ext.max.is_finite(), "{ext:?}");
let list = build(&d, &Space::Model, &Options::default());
assert!(!list.prims.is_empty() && !list.truncated, "file {i}: {} expanded", list.expanded);
}
}
/// A loop can also pass through a multileader's block or a proxy's graphics, which are drawn as
/// block contents: `*D1` holds one of them leading to block `K`, which holds a dimension drawn by
/// `*D1` (or by a block the file lacks, for comparison). The proxy's graphics also hold such a
/// dimension themselves: they are drawn as part of `*D1`.
#[test]
fn a_loop_through_a_multileader_or_proxy_graphics_is_cut_too() {
let line = |h: u64| Entity::new(Handle(h), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 1.0, 0.0) }));
let dim = |h: u64, block: &str| {
Entity::new(
Handle(h),
EntityKind::Dimension(cadcraft_doc::Dimension {
kind: cadcraft_doc::DimKind::Linear { rotation: 0.0 },
defpt: Vec3::new(100.0, 5.0, 0.0),
text_mid: Vec3::new(50.0, 5.0, 0.0),
p13: Vec3::ZERO,
p14: Vec3::new(100.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 100.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some(block.into()),
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
insertion_point: Vec3::ZERO,
}),
)
};
let to_k = Insert {
block: "K".into(),
insert: Vec3::ZERO,
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
for through_proxy in [false, true] {
let drawing = |back: &str| {
let via = if through_proxy {
EntityKind::Unknown(cadcraft_doc::Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: Vec::new(),
graphics: vec![Entity::new(Handle(0x300), EntityKind::Insert(to_k.clone())), dim(0x301, back)],
})
} else {
EntityKind::MLeader(cadcraft_doc::MLeader {
leaders: vec![vec![Vec3::new(-5.0, 0.0, 0.0)]],
landing: Vec3::ZERO,
dogleg: 1.0,
text: None,
style: "Standard".into(),
arrow_size: 1.0,
spline: false,
block: Some(to_k.clone()),
})
};
let mut d = Drawing::new_imperial();
let mut d1 = Block::new("*D1");
d1.entities.push(line(0x100));
d1.entities.push(Entity::new(Handle(0x101), via));
let mut k = Block::new("K");
k.entities.push(line(0x200));
k.entities.push(dim(0x201, back));
d.blocks.insert("*D1".into(), Arc::new(d1));
d.blocks.insert("K".into(), Arc::new(k));
let EntityKind::Dimension(top) = dim(0, "*D1").kind else { unreachable!() };
d.add(&Space::Model, Common::default(), EntityKind::Dimension(top)).unwrap();
build(&d, &Space::Model, &Options::default())
};
let (closed, open) = (drawing("*D1"), drawing("*D9"));
assert!(!open.prims.is_empty());
assert_eq!((closed.prims.len(), &closed.verts), (open.prims.len(), &open.verts), "through a proxy: {through_proxy}");
}
}
/// Dimension blocks `*E1`..`*En` in a chain: each holds `lines` lines and a dimension drawn by the
/// next; the last holds only lines. Model space holds a dimension drawn by `*E1`.
fn chain_of_blocks(n: usize, lines: usize) -> String {
let mut s = String::from(
"0
SECTION
2
BLOCKS
",
);
for i in 1..=n {
s += &format!(
"0
BLOCK
2
*E{i}
70
1
10
0
20
0
{}",
LINE.repeat(lines)
);
if i < n {
s += &dimension(&format!("*E{}", i + 1), 0);
}
s += "0
ENDBLK
";
}
s + "0
ENDSEC
0
SECTION
2
ENTITIES
" + &dimension("*E1", 0)
+ "0
ENDSEC
0
EOF
"
}
/// Dimension blocks nested without a cycle are still drawn from their blocks, on every path: two
/// dimensions deep, by sibling dimensions, and through references to a block holding one. A chain
/// of blocks with more objects than the search near a dimension's block looks at is settled by
/// the whole block graph, which finds no loop either.
#[test]
fn nested_dimension_blocks_without_a_cycle_draw_on_every_path() {
let only_lines = |list: &cadcraft_render::DisplayList| {
list.prims.iter().all(|p| {
let v = &list.verts[p.start as usize..(p.start + p.len) as usize];
matches!(v, [a, b] if *b - *a == Vec2::new(1.0, 1.0))
})
};
let list = build(&read(&nested_dimensions()), &Space::Model, &Options::default());
// `*D3`'s line, through `*D1` (two dimensions of `*D2`, and `B`) and the two `B` in model
// space; nothing else is drawn, so no dimension fell back to its definition points.
assert_eq!(list.prims.len(), 2 + 1 + 2);
assert!(only_lines(&list));
let list = build(&read(&chain_of_blocks(5, 100)), &Space::Model, &Options::default());
assert_eq!(list.prims.len(), 5 * 100);
assert!(only_lines(&list));
}
#[test]
fn block_expansion_bombs_are_bounded() {
for text in [self_referencing(4), self_referencing(12), fan_out(), minsert(10_000, 10_000)] {
+153
View File
@@ -0,0 +1,153 @@
//! The controls of #1069: one line of 49,999 or of 50,001 DASHED (0.5, -0.25) periods, as the
//! issue's generator writes it. A plot or export keeps the pattern on both: the PDF strokes a
//! subpath per dash and a close-up PNG of the line's start shows its gaps.
use cadcraft_doc::{Drawing, Space};
use cadcraft_geom::{Bounds2, Vec2};
use cadcraft_io::PdfOptions;
/// One line on layer L1 with linetype DASHED, `periods` periods long.
fn control(periods: f64) -> Drawing {
let len = periods * 0.75;
let dxf = format!(
"0
SECTION
2
HEADER
9
$ACADVER
1
AC1032
9
$INSUNITS
70
4
9
$LTSCALE
40
1.0
0
ENDSEC
0
SECTION
2
TABLES
0
TABLE
2
LTYPE
70
2
0
LTYPE
2
CONTINUOUS
70
0
3
Solid line
72
65
73
0
40
0.0
0
LTYPE
2
DASHED
70
0
3
Dashed 0.5/0.25
72
65
73
2
40
0.75
49
0.5
74
0
49
-0.25
74
0
0
ENDTAB
0
TABLE
2
LAYER
70
1
0
LAYER
2
L1
70
0
62
7
6
DASHED
0
ENDTAB
0
ENDSEC
0
SECTION
2
ENTITIES
0
LINE
8
L1
6
DASHED
10
0.0
20
0.0
30
0.0
11
{len}
21
0.0
31
0.0
0
ENDSEC
0
EOF
"
);
cadcraft_io::read(dxf.as_bytes(), "control.dxf").unwrap()
}
/// Runs of inked columns across the middle rows of `png` (a horizontal line through its centre):
/// one for a continuous line, one per dash for a dashed one.
fn dashes_across_the_middle(png: &[u8]) -> usize {
let r = cadcraft_io::raster::decode(png).unwrap();
let (w, h) = (r.width(), r.height());
let paper = r.pixel(0, 0);
let inked = |x: u32| (h / 2 - 3..=h / 2 + 3).any(|y| r.pixel(x, y) != paper);
(0..w).filter(|&x| inked(x) && (x == 0 || !inked(x - 1))).count()
}
#[test]
fn the_49_999_and_50_001_period_controls_keep_their_dashes_in_pdf_and_png() {
for periods in [49_999.0, 50_001.0] {
let d = control(periods);
let pdf = cadcraft_io::pdf(&d, &Space::Model, &PdfOptions { compress: false, ..PdfOptions::default() }).unwrap();
let doc = crate::pdf_read::read(&pdf);
let dashes = crate::pdf_read::drawn(doc.content()).iter().filter(|o| o.op == "m").count();
assert!(dashes > periods as usize, "{periods} periods: {dashes} dashes in the PDF");
// As `cadcraft-cli convert --window 0,-3,60,3`: 80 periods fill the image.
let png = cadcraft_io::write_framed(&d, "close.png", Some(Bounds2::new(Vec2::new(0.0, -3.0), Vec2::new(60.0, 3.0)))).unwrap();
let shown = dashes_across_the_middle(&png);
assert!(shown > 60, "{periods} periods: {shown} dashes across the close-up");
}
}
+360
View File
@@ -0,0 +1,360 @@
//! A HATCH edge path whose edges are listed out of order, or stored end to start, is read as the
//! outline its edges make. Read in file order, its vertex list jumps between edges, and the
//! even-odd fill fills the polygon of those jumps instead.
use cadcraft_doc::{EntityKind, HatchLoop};
use cadcraft_geom::{PolyVertex, Vec2};
/// A boundary edge as a DXF HATCH stores it (DXF Reference, HATCH boundary path data).
#[derive(Clone)]
enum Edge {
Line([f64; 2], [f64; 2]),
/// Centre, radius, start and end angle in degrees, counter-clockwise.
Arc([f64; 2], f64, f64, f64, bool),
/// Centre, major axis end relative to the centre, minor-to-major ratio, start and end angle
/// in degrees, counter-clockwise.
Ellipse([f64; 2], [f64; 2], f64, f64, f64, bool),
/// Degree, knots, control points.
Spline(u32, Vec<f64>, Vec<[f64; 2]>),
}
fn line(a: [f64; 2], b: [f64; 2]) -> Edge {
Edge::Line(a, b)
}
fn groups(edge: &Edge) -> String {
match edge {
Edge::Line(a, b) => format!("72\n1\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n", a[0], a[1], b[0], b[1]),
Edge::Arc(c, r, start, end, ccw) => format!("72\n2\n10\n{}\n20\n{}\n40\n{r}\n50\n{start}\n51\n{end}\n73\n{}\n", c[0], c[1], i32::from(*ccw)),
Edge::Ellipse(c, major, ratio, start, end, ccw) => format!(
"72\n3\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n40\n{ratio}\n50\n{start}\n51\n{end}\n73\n{}\n",
c[0],
c[1],
major[0],
major[1],
i32::from(*ccw)
),
Edge::Spline(degree, knots, control) => {
let mut s = format!("72\n4\n94\n{degree}\n73\n0\n74\n0\n95\n{}\n96\n{}\n", knots.len(), control.len());
for k in knots {
s.push_str(&format!("40\n{k}\n"));
}
for p in control {
s.push_str(&format!("10\n{}\n20\n{}\n", p[0], p[1]));
}
s
}
}
}
/// A DXF whose one solid HATCH has one edge path per entry of `paths`.
fn dxf(paths: &[Vec<Edge>]) -> String {
let mut s = String::from(
"0\nSECTION\n2\nENTITIES\n0\nHATCH\n5\n100\n100\nAcDbEntity\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n1\n2\nSOLID\n70\n1\n71\n0\n",
);
s.push_str(&format!("91\n{}\n", paths.len()));
for (i, edges) in paths.iter().enumerate() {
s.push_str(&format!("92\n{}\n93\n{}\n", i32::from(i == 0), edges.len()));
for edge in edges {
s.push_str(&groups(edge));
}
s.push_str("97\n0\n");
}
s.push_str("75\n0\n76\n1\n98\n0\n0\nENDSEC\n0\nEOF\n");
s
}
fn loops_of(d: &cadcraft_doc::Drawing) -> Vec<HatchLoop> {
let hatch = d.model.iter().find_map(|e| match &e.kind {
EntityKind::Hatch(h) => Some(h.loops.clone()),
_ => None,
});
hatch.expect("a hatch")
}
fn read_loops(paths: &[Vec<Edge>]) -> Vec<HatchLoop> {
loops_of(&cadcraft_io::read(dxf(paths).as_bytes(), "edges.dxf").expect("read DXF"))
}
/// The vertices of the one loop of a hatch with one edge path.
fn vertices(edges: &[Edge]) -> Vec<PolyVertex> {
let loops = read_loops(&[edges.to_vec()]);
assert_eq!(loops.len(), 1);
loops.into_iter().next().map(|l| l.vertices).unwrap_or_default()
}
/// The same vertices, up to the rounding of points and bulges computed from other stored values.
fn assert_same(got: &[PolyVertex], expected: &[PolyVertex]) {
let same = got.len() == expected.len() && got.iter().zip(expected).all(|(a, b)| a.p.near(b.p, 1e-9) && (a.bulge - b.bulge).abs() < 1e-12);
assert!(same, "got {got:?}\nexpected {expected:?}");
}
/// Whether the even-odd fill of loops of straight segments covers `p`.
fn filled(loops: &[HatchLoop], p: Vec2) -> bool {
let mut inside = false;
for l in loops {
assert!(l.vertices.iter().all(|v| v.bulge == 0.0), "straight segments only");
for (a, b) in l.vertices.iter().zip(l.vertices.iter().cycle().skip(1)) {
let (a, b) = (a.p, b.p);
if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) {
inside = !inside;
}
}
}
inside
}
const A: [f64; 2] = [0.0, 0.0];
const B: [f64; 2] = [10.0, 0.0];
const C: [f64; 2] = [10.0, 10.0];
const D: [f64; 2] = [0.0, 10.0];
#[test]
fn edges_listed_out_of_order_read_as_the_outline() {
let in_order = vertices(&[line(A, B), line(B, C), line(C, D), line(D, A)]);
// Read in file order, this is A, B, D, C, B, C, A, D: its even-odd fill is an hourglass.
let shuffled = vertices(&[line(A, B), line(D, C), line(B, C), line(A, D)]);
assert_same(&shuffled, &in_order);
let loops = read_loops(&[vec![line(A, B), line(D, C), line(B, C), line(A, D)]]);
for p in [[5.0, 1.0], [5.0, 9.0], [1.0, 5.0], [9.0, 5.0]] {
assert!(filled(&loops, Vec2::new(p[0], p[1])), "{p:?}");
}
}
#[test]
fn edges_stored_end_to_start_are_turned_around() {
let p = [[0.0, 0.0], [10.0, 0.0], [15.0, 8.0], [10.0, 16.0], [0.0, 16.0], [-5.0, 8.0]];
let in_order = vertices(&[line(p[0], p[1]), line(p[1], p[2]), line(p[2], p[3]), line(p[3], p[4]), line(p[4], p[5]), line(p[5], p[0])]);
// The second and third edges are both stored end to start, and the last one too.
let edges = [line(p[0], p[1]), line(p[2], p[1]), line(p[3], p[2]), line(p[3], p[4]), line(p[4], p[5]), line(p[0], p[5])];
assert_same(&vertices(&edges), &in_order);
// Around the two reversed edges in a row, a vertex list in file order (..., P1, P2, P1, P3,
// P2, P3, ...) leaves the triangle P1 P2 P3 unfilled.
let loops = read_loops(&[edges.to_vec()]);
assert!(filled(&loops, Vec2::new(11.0, 7.0)));
}
#[test]
fn arcs_ellipse_arcs_and_splines_stored_end_to_start_are_turned_around() {
// A loop round counter-clockwise: the bottom, a half circle out to the right, the top, and
// half an ellipse out to the left.
let arc = Edge::Arc([10.0, 5.0], 5.0, -90.0, 90.0, true);
let ellipse = Edge::Ellipse([0.0, 5.0], [0.0, 5.0], 0.4, 0.0, 180.0, true);
let in_order = vertices(&[line(A, B), arc, line(C, D), ellipse]);
// The same half circle from (10, 10) to (10, 0) clockwise: a clockwise arc stores its angles
// negated. The same half ellipse from (0, 0) to (0, 10) clockwise.
let arc_back = Edge::Arc([10.0, 5.0], 5.0, 270.0, 90.0, false);
let ellipse_back = Edge::Ellipse([0.0, 5.0], [0.0, 5.0], 0.4, 180.0, 360.0, false);
let got = vertices(&[line(A, B), arc_back, line(D, C), ellipse_back]);
assert_same(&got, &in_order);
assert!(in_order.iter().any(|v| v.bulge > 0.5), "the half circle is a bulge: {in_order:?}");
// The same half circle found before the run's first edge: an open path listed from its
// last edge.
let arc = Edge::Arc([10.0, 5.0], 5.0, -90.0, 90.0, true);
let in_order = vertices(&[arc, line(C, D)]);
assert_same(&vertices(&[line(C, D), Edge::Arc([10.0, 5.0], 5.0, 270.0, 90.0, false)]), &in_order);
// A Bezier spline and the same curve with its control points reversed.
let control = vec![[10.0, 0.0], [10.0, 8.0], [0.0, 8.0], [0.0, 0.0]];
let knots = vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0];
let spline = Edge::Spline(3, knots.clone(), control.clone());
let spline_back = Edge::Spline(3, knots, control.into_iter().rev().collect());
let in_order = vertices(&[line(A, B), spline]);
assert!(in_order.len() > 8, "{in_order:?}");
assert_same(&vertices(&[line(A, B), spline_back]), &in_order);
}
#[test]
fn ends_that_differ_by_rounding_still_meet() {
// A 1,000 by 10 rectangle whose corners are 5e-4 apart: half a millionth of its length,
// far more than the 1e-9 within which two points are one vertex, so each joint keeps both
// points.
let (x, y, w, h, e) = (5e5, -3e5, 1e3, 10.0, 5e-4);
let p = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]];
let q = |i: usize| [p[i][0] + e, p[i][1] - e];
let edges = [line(p[0], p[1]), line(q(1), p[2]), line(q(2), p[3]), line(q(3), q(0))];
let in_order = vertices(&edges);
assert_eq!(in_order.len(), 8, "{in_order:?}");
let shuffled = vertices(&[edges[0].clone(), line(p[3], q(2)), edges[3].clone(), line(p[2], q(1))]);
assert_same(&shuffled, &in_order);
}
#[test]
fn an_end_just_past_the_tolerance_does_not_meet() {
// A 1,000-wide path: ends meet within 1e-3. The triangle A T C is stored with a gap of 5e-4
// at T; a second triangle has a corner X 1.7e-3 from T, in the next lookup cell. Listed
// before the edge that does meet T, X's edge must still not be joined there.
let (a, t, t2, c) = ([0.0, 0.0], [500.0002, 0.0], [500.0007, 0.0], [250.0, 10.0]);
let (x, r, q) = ([500.0019, 0.0], [1000.0, 0.0], [750.0, 10.0]);
let after = vertices(&[line(a, t), line(t2, c), line(c, a), line(q, x), line(x, r), line(r, q)]);
let before = vertices(&[line(a, t), line(q, x), line(t2, c), line(c, a), line(x, r), line(r, q)]);
assert_same(&before, &after);
}
/// Line edges joined in file order: each edge's start unless the list already ends there, then
/// its end, and the closing point dropped.
fn in_file_order(edges: &[Edge]) -> Vec<PolyVertex> {
let mut out: Vec<PolyVertex> = Vec::new();
for edge in edges {
let Edge::Line(a, b) = edge else { panic!("lines only") };
for p in [a, b] {
let p = Vec2::new(p[0], p[1]);
if out.last().is_none_or(|last| !last.p.near(p, 1e-9)) {
out.push(PolyVertex::new(p));
}
}
}
if out.len() > 1 && out[0].p.near(out[out.len() - 1].p, 1e-9) {
out.pop();
}
out
}
#[test]
fn a_loop_whose_lookups_take_too_long_is_read_in_file_order() {
// Petals from a point Q out and back, and many edges from two points 1.4 tolerances either
// side of Q, listed between the first petal and the rest: every return to Q looks at those
// on one side (the other is two cells away). Past the lookup budget the loop is read in file
// order, as before chaining.
let at = |r: f64, k: usize, n: usize| {
let a = std::f64::consts::TAU * k as f64 / n as f64;
[r * a.cos(), r * a.sin()]
};
let (q, side) = ([0.0, 0.0], 2.8e-3);
let mut edges = vec![line(q, at(1000.0, 0, 1000))];
for i in 0..2000 {
edges.push(line([if i % 2 == 0 { side } else { -side }, 0.0], at(500.0, i, 2000)));
}
edges.push(line(at(1000.0, 0, 1000), q));
for k in 1..1000 {
edges.push(line(q, at(1000.0, k, 1000)));
edges.push(line(at(1000.0, k, 1000), q));
}
assert_eq!(vertices(&edges), in_file_order(&edges));
}
#[test]
fn an_open_path_is_chained_from_both_ends() {
// Three sides of the square, A to D, listed from the middle: the edges before the first
// listed one go in front, as stored or turned around.
let in_order = vertices(&[line(A, B), line(B, C), line(C, D)]);
assert_same(&vertices(&[line(B, C), line(C, D), line(B, A)]), &in_order);
assert_same(&vertices(&[line(C, D), line(B, C), line(A, B)]), &in_order);
}
#[test]
fn a_path_whose_edges_run_on_keeps_its_order_and_its_points() {
// Clockwise, starting at C, with a gap of 1e-6 at D: within a millionth of the outline
// (1e-5), so the edges run on, but more than 1e-9, so both points stay.
let d_off = [D[0], D[1] + 1e-6];
let edges = [line(C, B), line(B, A), line(A, D), line(d_off, C)];
let got = vertices(&edges);
let expected: Vec<PolyVertex> = [C, B, A, D, d_off].iter().map(|p| PolyVertex::new(Vec2::new(p[0], p[1]))).collect();
assert_eq!(got, expected);
}
#[test]
fn separate_outlines_in_one_path_fill_separately() {
let square = |x: f64, y: f64| {
let p = [[x, y], [x + 10.0, y], [x + 10.0, y + 10.0], [x, y + 10.0]];
[line(p[0], p[1]), line(p[1], p[2]), line(p[2], p[3]), line(p[3], p[0])]
};
let [a, b, c] = [square(0.0, 0.0), square(100.0, 0.0), square(50.0, 100.0)];
// In file order, the jumps from one square to the next and back to the first make a
// triangle between them, which the even-odd fill filled.
let in_order: Vec<Edge> = a.iter().chain(&b).chain(&c).cloned().collect();
// The same squares, their edges interleaved and the third square's turned around.
let mixed = vec![
a[0].clone(),
b[2].clone(),
line([60.0, 110.0], [60.0, 100.0]),
a[2].clone(),
b[0].clone(),
line([50.0, 110.0], [60.0, 110.0]),
a[1].clone(),
b[3].clone(),
line([50.0, 100.0], [50.0, 110.0]),
a[3].clone(),
b[1].clone(),
line([60.0, 100.0], [50.0, 100.0]),
];
for edges in [in_order, mixed] {
let loops = read_loops(&[edges]);
for p in [[5.0, 5.0], [105.0, 5.0], [55.0, 105.0]] {
assert!(filled(&loops, Vec2::new(p[0], p[1])), "{p:?}");
}
for p in [[50.0, 30.0], [30.0, 5.0], [55.0, 50.0]] {
assert!(!filled(&loops, Vec2::new(p[0], p[1])), "{p:?}");
}
}
}
#[test]
fn an_outline_left_open_is_closed_on_itself() {
// A square, then three sides of another listed apart from it: the second is closed by its
// missing side, not through the first square's corner.
let b = [[100.0, 0.0], [110.0, 0.0], [110.0, 10.0], [100.0, 10.0]];
let edges = vec![line(A, B), line(B, C), line(C, D), line(D, A), line(b[1], b[2]), line(b[0], b[1]), line(b[2], b[3])];
let loops = read_loops(&[edges]);
assert!(filled(&loops, Vec2::new(5.0, 5.0)));
assert!(filled(&loops, Vec2::new(105.0, 5.0)));
assert!(!filled(&loops, Vec2::new(90.0, 5.0)));
}
#[test]
fn outlines_with_missing_edges_are_joined_in_file_order() {
// The bottom from right to left, then the top and a cut corner from left to right, of an
// outline whose sides are missing: the two open runs are joined straight in the order they
// are listed, so the outline still fills.
let loops = read_loops(&[vec![line(B, A), line(D, [8.0, 10.0]), line([8.0, 10.0], [10.0, 8.0])]]);
for p in [[5.0, 5.0], [9.0, 2.0], [1.0, 8.0]] {
assert!(filled(&loops, Vec2::new(p[0], p[1])), "{p:?}");
}
assert!(!filled(&loops, Vec2::new(9.8, 9.8)));
}
#[test]
fn a_later_outline_closes_at_its_exact_start() {
// A square, then a second one 100 to the right whose last edge ends 5e-5 above its first
// corner: within the tolerance (1.1e-4), so the outline is closed. The jump back to the first
// square must start from that corner, or the jumps out and back leave a sliver between them.
let s = [100.0, 0.0];
let edges = vec![
line(A, B),
line(B, C),
line(C, D),
line(D, A),
line(s, [110.0, 0.0]),
line([110.0, 0.0], [110.0, 10.0]),
line([110.0, 10.0], [100.0, 10.0]),
line([100.0, 10.0], [100.0, 5e-5]),
];
let loops = read_loops(&[edges]);
assert!(filled(&loops, Vec2::new(5.0, 5.0)));
assert!(filled(&loops, Vec2::new(105.0, 5.0)));
assert!(!filled(&loops, Vec2::new(50.0, 1.2e-5)));
}
#[test]
fn a_chained_loop_is_saved_as_it_was_read() {
let in_order = vertices(&[line(A, B), line(B, C), line(C, D), line(D, A)]);
let shuffled = cadcraft_io::read(dxf(&[vec![line(A, B), line(D, C), line(B, C), line(A, D)]]).as_bytes(), "edges.dxf").expect("read");
let saved = cadcraft_io::write_dxf(&shuffled);
let back = loops_of(&cadcraft_io::read(saved.as_bytes(), "saved.dxf").expect("reopen"));
assert_eq!(back.len(), 1);
assert_same(&back[0].vertices, &in_order);
assert_same(&back[0].vertices, &loops_of(&shuffled)[0].vertices);
}
#[test]
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn a_dwg_edge_path_out_of_order_reads_as_the_outline() {
cadcraft_io::dwg_worker::allow_in_process();
let in_order = vertices(&[line(A, B), line(B, C), line(C, D), line(D, A)]);
let text = dxf(&[vec![line(A, B), line(D, C), line(B, C), line(A, D)]]);
let doc = acadrust::DxfReader::from_reader(std::io::Cursor::new(text.into_bytes())).expect("acadrust reads the DXF").read().expect("parse");
let dwg = acadrust::DwgWriter::write_to_vec(&doc).expect("acadrust writes a DWG");
let loops = loops_of(&cadcraft_io::read(&dwg, "edges.dwg").expect("read DWG"));
assert_eq!(loops.len(), 1);
assert_same(&loops[0].vertices, &in_order);
}
+2
View File
@@ -12,6 +12,7 @@ mod attrib_props;
mod block_expansion;
mod closed_spline;
mod codepages;
mod dash_controls;
mod dim_block_resave_roundtrip;
mod dim_block_text;
mod dim_marks_roundtrip;
@@ -36,6 +37,7 @@ mod exhausted_handseed;
mod followups_626;
mod groups_roundtrip;
mod hatch_assoc_roundtrip;
mod hatch_edge_chain;
mod hatch_elliptic_edge_dedup;
mod hatch_loop_flags;
mod hatch_pattern_def;
+244 -12
View File
@@ -30,6 +30,9 @@ pub struct Remote {
/// The per-session control token for this port, read from the owner-only token file on first
/// use so requests can authenticate (CWE-306).
token: Option<String>,
/// Whether a request on the current connection has passed the server's token check, so the
/// server takes lines longer than `MAX_UNAUTHENTICATED_LINE` on it (#1925).
authed: bool,
/// Longest reply line accepted (`MAX_REPLY_LINE`; smaller in tests).
max_reply: usize,
}
@@ -64,7 +67,7 @@ fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) ->
impl Remote {
/// Connect to a running control server; its session token is read lazily when the first request is sent.
pub fn connect(addr: &str) -> std::io::Result<Self> {
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None, max_reply: MAX_REPLY_LINE };
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None, authed: false, max_reply: MAX_REPLY_LINE };
r.reconnect()?;
Ok(r)
}
@@ -72,7 +75,7 @@ impl Remote {
/// the server before the app is open. With `launch`, a call that finds nothing at `addr`
/// opens the app with that control port first (macOS) and waits for it.
pub fn lazy(addr: &str, launch: bool) -> Self {
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, max_reply: MAX_REPLY_LINE }
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE }
}
/// The per-session token for this port, read (and cached) from the owner-only token file. A
@@ -122,6 +125,7 @@ impl Remote {
}
fn reconnect(&mut self) -> std::io::Result<()> {
self.conn = None;
self.authed = false;
let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {}", self.addr));
for sa in self.addr.to_socket_addrs()? {
match TcpStream::connect_timeout(&sa, Duration::from_millis(800)) {
@@ -216,15 +220,30 @@ fn is_read_only(method: &str) -> bool {
}
impl Remote {
/// Put the current token (if any) on `req`, replacing the one it carries.
/// Connect if needed, put the token for the peer actually connected to on `req`, and send it.
/// The server reads the token only at the end of a line and keeps lines short until one has
/// passed the check (#1925), so a long request on a new connection goes after a `ping` with the
/// token; when the `ping` is refused its reply comes back instead and the request isn't sent.
fn sign_and_send(&mut self, req: &mut Value) -> Result<String, (std::io::Error, bool)> {
if self.conn.is_none() {
self.reach().map_err(|e| (e, false))?;
}
self.set_token(req);
self.roundtrip(&req.to_string())
let line = req.to_string();
if !self.authed && line.len() > crate::control_token::MAX_UNAUTHENTICATED_LINE {
let mut ping = json!({"id": req.get("id").cloned().unwrap_or(Value::Null), "method": "ping"});
self.set_token(&mut ping);
// The request itself hasn't been sent, so a failure here is safe to retry.
let reply = self.roundtrip(&ping.to_string()).map_err(|(e, _)| (e, false))?;
if !serde_json::from_str::<Value>(&reply).is_ok_and(|v| past_the_token_check(&v)) {
// The app closes the connection after such a refusal.
self.conn = None;
return Ok(reply);
}
}
self.roundtrip(&line)
}
/// Put the current token (if any) on `req`, replacing the one it carries.
fn set_token(&mut self, req: &mut Value) {
let token = self.token().map(str::to_string);
if let Some(obj) = req.as_object_mut() {
@@ -235,7 +254,8 @@ impl Remote {
}
}
/// Send `req` and parse the reply, refreshing the token before a safe retry after a transport
/// error. A mutation that may have reached the server is never resent automatically.
/// error. A mutation that may have reached the server is never resent automatically, and when
/// its reply is lost (on the first attempt or the retry) the error says so.
fn exchange(&mut self, method: &str, req: &mut Value) -> Result<Value, String> {
let reply = match self.sign_and_send(req) {
Ok(r) => r,
@@ -244,28 +264,39 @@ impl Remote {
self.conn = None;
// A mutation whose reply was lost must never be sent twice.
if sent && !is_read_only(method) {
return Err(format!(
"CADCraft at {}: {e}; the reply was lost, so `{method}` may or may not have been applied. Inspect the drawing first",
self.addr
));
return Err(maybe_applied(&self.addr, method, &e));
}
// A restarted server may have rotated its token before dropping the old socket.
self.sign_and_send(req).map_err(|(e, _)| {
self.sign_and_send(req).map_err(|(e, sent)| {
self.token = None;
self.conn = None;
format!("CADCraft at {}: {e}", self.addr)
if sent && !is_read_only(method) { maybe_applied(&self.addr, method, &e) } else { format!("CADCraft at {}: {e}", self.addr) }
})?
}
};
serde_json::from_str(&reply).map_err(|e| format!("bad reply: {e}"))
let v = serde_json::from_str(&reply).map_err(|e| format!("bad reply: {e}"))?;
self.authed |= past_the_token_check(&v);
Ok(v)
}
}
/// The error for a mutation that may have reached the app but whose reply was lost.
fn maybe_applied(addr: &str, method: &str, e: &std::io::Error) -> String {
format!("CADCraft at {addr}: {e}; the reply was lost, so `{method}` may or may not have been applied. Inspect the drawing first")
}
/// An `unauthorized` reply (the app also closes the connection).
fn unauthorized(v: &Value) -> bool {
v.get("error").and_then(Value::as_str).is_some_and(|e| e.starts_with("unauthorized"))
}
/// A reply to a request that passed the token check, on a connection the app keeps open: a result,
/// or `busy` or a timeout (both say in `state` whether the request ran). The app's other refusals
/// (`unauthorized` aside) carry no `state` and close the connection.
fn past_the_token_check(v: &Value) -> bool {
v.get("ok").and_then(Value::as_bool) == Some(true) || (v.get("state").is_some() && !unauthorized(v))
}
impl Backend for Remote {
/// Send a control request with the token when available. A refused token is read again and the
/// request resent once, only when the app says it did not run it.
@@ -718,4 +749,205 @@ mod tests {
assert!(!server.join().unwrap(), "a failed mutation write was retried");
assert!(remote.token.is_none());
}
/// Serve connections by the app's line rules (#1925): until a request on a connection has
/// carried the valid token (`valid(n)` = `Ok(token)` for the n-th request read), a line longer
/// than `MAX_UNAUTHENTICATED_LINE` is refused; so is a request without the token. `Err(reply)`
/// answers with `reply` instead (none when null). As in the app, a refusal closes the
/// connection unless it says in `state` whether the request ran (busy, a timeout); other
/// requests are answered with their method. Returns the connection, method and length of every
/// line read, once no new connection comes for a while.
fn strict_app(
listener: TcpListener,
mut valid: impl FnMut(usize) -> Result<String, Value> + Send + 'static,
) -> std::thread::JoinHandle<Vec<(usize, String, usize)>> {
std::thread::spawn(move || {
listener.set_nonblocking(true).unwrap();
let mut seen = Vec::new();
for conn_no in 0.. {
let start = std::time::Instant::now();
let conn = loop {
match listener.accept() {
Ok((conn, _)) => break Some(conn),
Err(_) if start.elapsed() < Duration::from_millis(500) => std::thread::sleep(Duration::from_millis(10)),
Err(_) => break None,
}
};
let Some(conn) = conn else { break };
conn.set_nonblocking(false).unwrap();
let mut reader = BufReader::new(conn.try_clone().unwrap());
let mut out = conn;
let mut authed = false;
let mut line = String::new();
while reader.read_line(&mut line).unwrap_or(0) > 0 {
let req: Value = serde_json::from_str(&line).unwrap();
let len = line.trim_end().len();
line.clear();
seen.push((conn_no, req["method"].as_str().unwrap_or_default().to_string(), len));
let reply = if !authed && len > crate::control_token::MAX_UNAUTHENTICATED_LINE {
json!({"ok": false, "error": "request line too long before a request with the control token"})
} else {
match valid(seen.len() - 1) {
Ok(valid) if req["token"].as_str() == Some(valid.as_str()) => {
authed = true;
json!({"id": req["id"], "ok": true, "result": req["method"]})
}
Ok(_) => {
json!({"id": req["id"], "ok": false, "error": "unauthorized: missing or invalid control token", "state": "not-run"})
}
Err(Value::Null) => break,
Err(reply) => {
// Busy and timeouts come after the token check.
authed |= reply.get("state").is_some() && !unauthorized(&reply);
reply
}
}
};
writeln!(out, "{reply}").unwrap();
if reply["ok"] != json!(true) && (reply.get("state").is_none() || unauthorized(&reply)) {
break;
}
}
}
seen
})
}
/// Parameters that make a request line longer than the server reads before the token check.
fn long_params() -> Value {
json!({"command": "text", "params": {"text": "x".repeat(crate::control_token::MAX_UNAUTHENTICATED_LINE)}})
}
/// A long request on a new connection goes after a short `ping` with the token, so the server
/// takes it; later long requests on that connection go straight away, and one on the next
/// connection again goes after a `ping`.
#[test]
fn a_long_request_on_a_new_connection_goes_after_an_authenticating_ping() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let token = crate::control_token::issue(addr.port()).unwrap();
let server = strict_app(listener, move |_| Ok(token.clone()));
let mut remote = Remote::lazy(&addr.to_string(), false);
let mut got = vec![remote.call("engine.execute", long_params()), remote.call("engine.execute", long_params())];
// The connection drops (the app restarted, say); the client connects again.
remote.conn = None;
got.push(remote.call("engine.execute", long_params()));
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
assert_eq!(got, vec![Ok(json!("engine.execute")); 3]);
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (0, "engine.execute"), (0, "engine.execute"), (1, "ping"), (1, "engine.execute")]);
assert!(seen[0].2 <= crate::control_token::MAX_UNAUTHENTICATED_LINE, "{seen:?}");
}
/// When the `ping` before a long request is refused (a stale token, #2087), the long request
/// isn't sent on that connection; it is sent once, on a new connection, with the new token.
#[test]
fn a_refused_ping_keeps_the_long_request_back_until_the_new_token_is_read() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
crate::control_token::issue(addr.port()).unwrap();
let mut fresh = String::new();
let server = strict_app(listener, move |n| {
if n == 0 {
// The app starts and writes its own session's token.
fresh = crate::control_token::issue(addr.port()).unwrap();
}
Ok(fresh.clone())
});
let mut remote = Remote::lazy(&addr.to_string(), false);
let got = remote.call("engine.execute", long_params());
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
assert_eq!(got, Ok(json!("engine.execute")));
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (1, "ping"), (1, "engine.execute")]);
}
/// A lost reply to the `ping` before a long mutation doesn't make the mutation "maybe applied":
/// it hasn't been sent, so it is sent once on a new connection.
#[test]
fn a_lost_ping_reply_leaves_the_long_request_safe_to_send() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let token = crate::control_token::issue(addr.port()).unwrap();
// The first connection closes after reading the `ping`, without a reply.
let server = strict_app(listener, move |n| if n == 0 { Err(Value::Null) } else { Ok(token.clone()) });
let mut remote = Remote::lazy(&addr.to_string(), false);
let got = remote.call("engine.execute", long_params());
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
assert_eq!(got, Ok(json!("engine.execute")));
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (1, "ping"), (1, "engine.execute")]);
}
/// A refusal that closes the connection (here every connection slot is taken) never leaves a
/// mutation "maybe applied": a long one refused at its `ping` isn't sent, the next request goes
/// on a new connection, and a long request after a refused short one authenticates first.
#[test]
fn a_refusal_that_closes_the_connection_leaves_no_mutation_in_doubt() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let token = crate::control_token::issue(addr.port()).unwrap();
let full = json!({"ok": false, "error": "too many control connections"});
let server = strict_app(listener, move |n| if n < 2 { Err(full.clone()) } else { Ok(token.clone()) });
let mut remote = Remote::lazy(&addr.to_string(), false);
let short = json!({"command": "circle", "params": {}});
let got = [remote.call("engine.execute", long_params()), remote.call("engine.execute", short), remote.call("engine.execute", long_params())];
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
let full = Err("too many control connections".to_string());
assert_eq!(got, [full.clone(), full, Ok(json!("engine.execute"))]);
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (1, "engine.execute"), (2, "ping"), (2, "engine.execute")]);
}
/// When the retry after a lost `ping` reply sends the long request and its reply is lost too,
/// a mutation is reported as maybe applied (and not sent again); a read-only request isn't.
#[test]
fn a_lost_reply_on_the_retry_still_says_a_mutation_may_have_been_applied() {
for (method, warned) in [("engine.execute", true), ("drawing.inspect", false)] {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let token = crate::control_token::issue(addr.port()).unwrap();
// The first `ping` and then the request on the retry's connection go unanswered.
let server = strict_app(listener, move |n| if n == 1 { Ok(token.clone()) } else { Err(Value::Null) });
let mut remote = Remote::lazy(&addr.to_string(), false);
let got = remote.call(method, long_params());
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
let err = got.unwrap_err();
assert_eq!(err.contains("may or may not have been applied"), warned, "{method}: {err}");
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (1, "ping"), (1, method)], "sent once");
}
}
/// A `ping` that passed the token check but timed out in the app (it may have run) still lets
/// the long request through on that connection, instead of reporting it as maybe applied.
#[test]
fn a_ping_that_timed_out_after_the_token_check_lets_the_long_request_through() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let token = crate::control_token::issue(addr.port()).unwrap();
let server =
strict_app(
listener,
move |n| if n == 0 { Err(json!({"ok": false, "error": "timeout", "state": "may-have-run"})) } else { Ok(token.clone()) },
);
let mut remote = Remote::lazy(&addr.to_string(), false);
let got = remote.call("engine.execute", long_params());
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
assert_eq!(got, Ok(json!("engine.execute")));
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (0, "engine.execute")]);
}
}
+7
View File
@@ -14,6 +14,13 @@ use std::path::PathBuf;
/// Length of the token in bytes (256 bits), rendered as lowercase hex.
const TOKEN_BYTES: usize = 32;
/// Longest request line in bytes (newline excluded) the control server reads on a connection
/// before a request on it has carried the right token. The token is checked only once the whole
/// line is read (a client that sorts keys sends it last), so this bounds what a peer without the
/// token can make the app buffer (#1925). A client sends a longer request only after a shorter one
/// with the token has been answered on the same connection.
pub const MAX_UNAUTHENTICATED_LINE: usize = 64 * 1024;
/// The file holding the control token for `port`, inside a per-user private directory.
///
/// On Unix the runtime dir (`XDG_RUNTIME_DIR`, already `0700` and per-user) is preferred, else the
+5 -1
View File
@@ -41,6 +41,9 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> {
block_pstyle: ctx.block_pstyle,
// The reference's own, set by the caller (`Builder::transparency` while it draws).
block_transparency: ctx.block_transparency,
// Proxy graphics are drawn as part of the block they are in; a block reference or a
// dimension sets its own block instead.
block: ctx.block,
}
}
@@ -82,7 +85,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
}
let off = Vec2::new(ins.col_spacing * f64::from(c), ins.row_spacing * f64::from(r)).rotate(ins.rotation);
let m = Mat3::translate(off).then_before(ins.transform(blk.base.xy()));
let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, m) };
let sub = Ctx { block: Some(blk), block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, m) };
// XCLIP: the copy is drawn on its own, then cut to the boundary.
let clip = xclip_region(ins, &sub.xf);
let mut part = clip.as_ref().map(|_| b.part());
@@ -108,6 +111,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
if let (Some(part), Some((region, inverted))) = (part, &clip) {
b.list.expanded = part.list.expanded;
b.list.truncated |= part.list.truncated;
b.list.undashed = b.list.undashed.saturating_add(part.list.undashed);
append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) });
xclip_frame(b, ctx, region, rgb);
}
+10 -3
View File
@@ -108,10 +108,16 @@ pub struct DisplayList {
/// Block contents expanded while building (see [`MAX_BLOCK_EXPANSION`]).
pub expanded: usize,
/// The block-expansion budget or the point budget ([`crate::MAX_DISPLAY_POINTS`]) was spent:
/// block contents or objects past it are not in the list. The screen,
/// plots and exports draw what is here; the CLI and the control channel report this, so an
/// output that leaves contents out is never silent (#1070).
/// block contents or objects past it are not in the list; or a dashed run was drawn
/// continuous past a dash limit ([`DisplayList::undashed`]). The screen,
/// plots and exports draw what is here; the control channel and the MCP render report this,
/// so an output that leaves contents out is never silent (#1070).
pub truncated: bool,
/// Dashed runs drawn continuous because of a dash limit: one run repeating its pattern past
/// [`crate::MAX_RUN_DASH_ELEMENTS`], or the build past [`crate::MAX_DASH_ELEMENTS`] (#1069). Runs drawn
/// continuous by rule (shorter than one period, a pattern under two pixels or, on screen, past
/// 50,000 periods) are not counted.
pub undashed: usize,
/// Plot style end, join and fill style per primitive (parallel to `prims`; missing entries
/// are "use object"), turned into geometry by [`pen::apply`].
pub pens: Vec<Pen>,
@@ -210,4 +216,5 @@ pub(crate) fn append(dst: &mut DisplayList, src: DisplayList) {
dst.bounds = dst.bounds.union(&src.bounds);
dst.expanded = dst.expanded.saturating_add(src.expanded);
dst.truncated |= src.truncated;
dst.undashed = dst.undashed.saturating_add(src.undashed);
}
+13 -6
View File
@@ -94,7 +94,9 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
let stroke_as = |b: &mut Builder, pts: &[Vec2], how: Layout| match lt.as_ref().filter(|_| b.opts.linetypes) {
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
for dash in linetype::apply_as(pts, lt, ltscale, min, how) {
let dashes = linetype::apply_as(pts, lt, ltscale, min, how, b);
let laid = dashes.is_some();
for dash in dashes.unwrap_or_else(|| vec![pts.to_vec()]) {
if dash.len() == 1 {
if let Some(p) = dash.first() {
b.point(ctx, rgb, *p);
@@ -103,8 +105,9 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
b.polyline(ctx, rgb, lw, &dash);
}
}
// Text and shapes embedded in the linetype (shapes when their SHX file is found).
if b.opts.text {
// Text and shapes embedded in the linetype (shapes when their SHX file is found), on
// a run whose dashes were laid out.
if b.opts.text && laid {
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min, how) {
b.shaped(ctx, rgb, lw, &sh);
}
@@ -176,7 +179,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
// Dashed: each dash a filled piece of the band; dots a line across it.
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
let (tris, ticks, centres) = wide::dashed(p, tol, lt, ltscale, min);
let (tris, ticks, centres) = wide::dashed(p, tol, lt, ltscale, min, b);
b.tris(ctx, rgb, &tris);
if hairline {
for c in &centres {
@@ -366,13 +369,17 @@ fn draw_dimension(
own: u8,
) {
let (lt, ltscale) = stroke;
// A dimension inside a block whose own block leads back to that block (it is the block, or
// they lie on a loop of references, dimensions and multileaders) is drawn from its definition
// points, as one whose block is missing is (see `loops`, #1923).
if let Some(blk) = dm.block.as_ref().and_then(|n| ctx.d.block(n))
&& ctx.depth < cadcraft_doc::MAX_BLOCK_DEPTH
&& !ctx.block.is_some_and(|outer| b.leads_back(ctx.d, outer, blk))
{
// DXF group 12: a moved dimension keeps its `*D` block where it was and the offset in
// the insertion point, so the block draws translated by it (#2634).
let off = dm.insertion_point.xy();
let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::translate(off)) };
let sub = Ctx { block: Some(blk), block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::translate(off)) };
// DIMTFILL: the block's MTEXT carries no background mask here, so a background
// around each of the block's texts is drawn before the block's first text or first
// line of the text's marks, except for a text that a SOLID of the block covers.
@@ -421,7 +428,7 @@ pub(crate) fn stroke_with(b: &mut Builder, ctx: &Ctx, rgb: Ink, lw: f32, lt: Opt
match lt.filter(|_| b.opts.linetypes) {
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
for dash in linetype::apply(pts, lt, ltscale, min) {
for dash in linetype::apply(pts, lt, ltscale, min, b) {
match dash.as_slice() {
[p] => b.point(ctx, rgb, *p),
_ => b.polyline(ctx, rgb, lw, &dash),

Some files were not shown because too many files have changed in this diff Show More