Compare commits

..
Author SHA1 Message Date
Tanish Manku 3b7eb1b7bc Merge pull request #2842 from storytold/stack/s2
Stage 1 stack 2: land #2587, #2585, #2608
2026-11-05 20:36:21 -07:00
Tanish Manku 1f11d4f701 Stage 1 stack 2: review fixes on #2587, #2585, #2608
- #2587: a frame turned by anything but a quarter turn keeps its size about its turned
  centre; the box of its two mapped corners collapsed it (a 10 x 10 square turned 45° became
  14.14 x 0, and the OLE header with it) for EXPLODE, REFEDIT, paste and array placement
  (austin62jake, CodeRabbit). Moves, scales, mirrors and quarter turns keep the exact
  corner mapping. `recase` reads only the rewritten digits and a few after them, not the
  whole 310 line (austin62jake). The PR's rotated-frame test expects the kept size.
- #2585: an `output` that contradicts the path's extension is refused, as a device that
  does is; it lost silently to the extension.
- #2608: the window's state is dropped when another dialog took its place (it missed a UI
  pass), so reopening reads the drawing instead of an old unsent edit (CodeRabbit); TEXT and
  ATTDEF get a one-line field (Enter commits), so a line break can't turn into a space on
  save; the module comment says the shortcut menu opens it.
2026-11-05 20:16:44 -07:00
Tanish Manku 412eb84282 Merge branch 'stk-2608' into stack/s2
# Conflicts:
#	crates/ui-egui/src/i18n/zh.tsv
2026-11-05 19:22:54 -07:00
Tanish Manku 173aa38f35 Merge branch 'stk-2585' into stack/s2
# Conflicts:
#	crates/engine/src/cmd/layout.rs
#	crates/engine/src/cmd/layout/tests.rs
2026-11-05 19:22:47 -07:00
Tanish Manku 7218285443 Merge branch 'stk-2587' into stack/s2
# Conflicts:
#	crates/doc/src/extents.rs
2026-11-05 19:22:25 -07:00
Tanish Manku 8e899eef63 Merge pull request #2837 from storytold/stack/s1
Stage 1 stack: land #2584, #1626, #2028, #2107, #2471, #1026, #2612, #2545, #2658
2026-11-05 19:16:39 -07:00
Tanish Manku 417f195cc3 Stage 1 stack: CodeRabbit on #2837 (CLASS places, the first *ACTIVE record)
- #2471: an unnamed CLASS record keeps its place in the class list a DWG maps proxies by,
  so the classes after it keep theirs; a proxy of the unnamed class is left out instead of
  taking the next class's name (the ODA refuses such a DWG).
- #1626: the first *ACTIVE VPORT record is the caller's to say. A first record with a
  usable view but an unusable tile kept no tile, so the next *ACTIVE record was taken for
  the first and its view replaced the saved one (also austin62jake on #1626).
2026-11-05 18:57:19 -07:00
Tanish Manku 2b88b22949 Stage 1 stack: review fixes on #2584, #2471, #1626, #2028, #1026, #2658, #2612
- #2584: a tilted LWPOLYLINE/HATCH run is flattened to at most a million vertices, then
  its arcs stay chords (a hostile file of arcs asked for gigabytes; austin62jake). The
  file-format-parity.md hunk is dropped: maintainers update the parity docs.
- #2471: another program's proxy objects are in the DWG loss report as its proxy entities
  are (left out before 2013, or when their class can't be named); they went silently.
- #1626: a drawing saved at a view keeps it in the desktop app and when it has xrefs: the
  app's first frame and the xref pass both fitted the extents over it. OPEN's result says
  `saved_view`; one `view::saved_view` replaces the copy of `usable_view` in files.rs.
  A misplaced doc comment goes back to its test.
- #2028: a plot rotation (73) outside 0-3 is written back as 0, not as read.
- #1026: the binary code-page retry drops the first pass's tags before it runs (the peak
  doubled near the tag limit); a float spelling of an integer group clamps to what the
  width holds unsigned too, so 65535.0 reads as 65535 does, not 32767.
- #2658: the reference names Undo by the last command ("Undo Group of commands"); Undo
  matched nothing and went to the end of Edit. Ordering and its test share one rule.
- #2612: its test's Insert gets `clip: None` (XCLIP landed after it was written).
2026-11-05 18:34:43 -07:00
Tanish Manku c96d6b2db8 Merge branch 'stk-2658' into stack/s1 2026-11-05 17:23:13 -07:00
Tanish Manku 12db7237cc Merge branch 'stk-2545' into stack/s1 2026-11-05 17:23:13 -07:00
Tanish Manku 831a437f1e Merge branch 'stk-2612' into stack/s1 2026-11-05 17:23:13 -07:00
Tanish Manku b676dd5510 Merge branch 'stk-1026' into stack/s1 2026-11-05 17:23:12 -07:00
Tanish Manku 577b2f74d6 Merge branch 'stk-2471' into stack/s1 2026-11-05 17:23:12 -07:00
Tanish Manku 6554ea3dd5 Merge branch 'stk-2107' into stack/s1 2026-11-05 17:23:12 -07:00
Tanish Manku 2c8eaf2901 Merge branch 'stk-2028' into stack/s1 2026-11-05 17:23:11 -07:00
Tanish Manku 214f1b263c Merge branch 'stk-1626' into stack/s1 2026-11-05 17:23:11 -07:00
Tanish Manku 97136cf316 Merge branch 'stk-2584' into stack/s1 2026-11-05 17:23:11 -07:00
Tanish Manku 1b39fbbabe Merge pull request #2835 from storytold/fix/unused-patches
build: drop three egui patches nothing uses
2026-11-05 16:31:42 -07:00
Tanish Manku 2611bc5f5b Merge pull request #2833 from storytold/land/2016
Land #1971 and #2016: Georgian font and Georgian interface language
2026-11-05 16:31:28 -07:00
Tanish Manku deb1468d08 build: drop three egui patches nothing uses
egui_system_font_provider, egui_demo_lib and egui_inspection were patched to the egui fork
with the rest of its family (#2119), but no crate here depends on them: Cargo.lock lists
them as [[patch.unused]] and cargo warns on every build. A vendored offline build (Nix's
importCargoLock) refuses an unused git patch, so the flakes in #794 and #1814 can't build
main. Reported by @mbolling on #1814.
2026-11-05 16:10:30 -07:00
Tanish Manku befb9b6f61 Merge branch 'pr-2016' into land/2016 2026-11-05 14:36:35 -07:00
Tanish Manku ec0decfd5c Merge branch 'pr-1971' into land/2016 2026-11-05 14:36:35 -07:00
Tanish Manku fc157ea91f Merge pull request #2831 from storytold/land/1031
Land #1031: Latin accents in the CADCraft Stroke font
2026-11-05 14:17:44 -07:00
Tanish Manku 0d125d6a8f Merge remote-tracking branch 'origin/main' into land/1031 2026-11-05 13:08:56 -07:00
Tanish Manku 6d39cf2297 Merge #1031 (Latin accents in the stroke font) onto main
#1031's SHX reader, TextFont::Shx wiring and doc edits are superseded by main's SHX support
(#2751, which landed #1944) and resolved to main's. Kept from #1031: the accented Latin
letters of CADCraft Stroke (stroke.rs, composed from its own letter bodies and marks), their
test (fonts/tests/latin_accents.rs) and a synthetic SHX text-through-DXF test
(io/tests/shx_text.rs), which passes against main's reader.
2026-11-05 13:08:55 -07:00
FredApps df65974458 Merge pull request #2818 from ZIDAN44/fix/803-mcp-render-background
fix(mcp): render takes a background and a plot style (#803)
2026-11-05 15:04:04 +01:00
FredApps 74485a71b1 Merge branch 'main' into fix/803-mcp-render-background 2026-11-05 14:52:29 +01:00
FredApps 6ca414c344 Merge pull request #2180 from helenkwok/web/host-page
feat(web): page host mode, so a page can host CADCraft in its own document (#2178)
2026-11-05 14:10:58 +01:00
Zinadin ZidanandClaude Opus 5.5 75175c807d refactor(render): one constant for the dark canvas; the render error limits say they are limits (#803)
render_look's DARK repeated the rasteriser's default background; both now
read RasterOptions::DARK_BACKGROUND. ECHO and LISTED_TABLES are renamed
MAX_ECHO_CHARS and MAX_LISTED_TABLES. No change in behaviour.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 19:10:58 +06:00
Hamza c667dfea26 Merge remote-tracking branch 'origin/main' into stored-model-view
main added view twist. Kept from both: a drawing opens on the view it was saved at, with its saved twist; one that stores none fits its extents through main's twisted box. The VPORT reader takes main's twisted view centre and keeps this PR's first-*ACTIVE view; the writer writes the saved view, else main's twisted fit, with the fallback still fitting the width through the record's aspect.
2026-11-05 16:03:19 +05:00
Helen Kwok 0902a13b88 cadcraft-web: speak the host messages through craft-web-host
The transports, the message types and the origin checks come from the shared crate (storytold/craft-libs#420); CADCraft keeps the engine delivery hook, the open size limit and the upload inbox.
2026-11-05 17:50:59 +08:00
Helen Kwok afea2be761 packaging/web: document what page host mode trusts, the limits on host files, and the stable event names 2026-11-05 16:59:08 +08:00
Helen Kwok ea79be1309 ROADMAP: leave the roadmap rows to the maintainers (AGENTS.md) 2026-11-05 16:59:08 +08:00
Helen Kwok e5cac11426 packaging/web: the README example reports an init failure 2026-11-05 16:59:08 +08:00
Helen Kwok 1c3975523d feat(web): page host mode, so a page can host CADCraft in its own document (#2178)
data-host="page" on the canvas opts a page that loads the module into its own document into the host bridge. The ?host=parent messages travel as non-bubbling CustomEvents on the canvas; the bridge holds a Transport (Parent or Page) with one send, and the open, save, dirty, ready and failure handling is shared. ?host=parent is checked first and unchanged, including no bridge for an unframed page. The hosting guide documents both modes.
2026-11-05 16:59:08 +08:00
Helen Kwok 4b47a04a09 Contributors: credit helenkwok as Helen Kwok 2026-11-05 16:59:08 +08:00
Zinadin ZidanandClaude Opus 5.5 04a279cff0 fix(mcp): a render with a plot style plots on white; "none" turns plot styles off (#803)
A plot style alone drew black lines on the dark canvas: the tables that
change colours print colour 7 (and, in monochrome.ctb, every colour)
black. With `plot_style` and no `background`, the render now draws on
white, as a plot prints on paper; a given background still wins.

`plot_style: "none"` (or "") draws every object with its own
properties, also in a layout that shows its own plot styles. An unknown
table's error lists the built-in tables and at most ten of the
drawing's own. The app's ui.render test now draws a red line, so it
fails if the plot style isn't passed on.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 12:09:31 +06:00
Zinadin ZidanandClaude Opus 5.5 017cc9b1fc fix(mcp): render takes a background and a plot style (#803)
The MCP render tool and ui.render, in the app and headless, always drew
on the dark canvas with no plot style, so a PNG placed on a page needed
the SVG export instead.

They now take `background` ("dark", the default; "white", "paper" or
"#rrggbb") and `plot_style` (a built-in plot style table such as
monochrome.ctb or grayscale.ctb, or one the drawing holds). Colour 7 is
drawn black on a light background and white on a dark one, as on a plot.
An unknown value is refused with what is accepted. Both copies of
ui.render read the options through one function in the engine
(render_look). The render tool's description also says it returns an
image block, not text.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 11:20:52 +06:00
SBaksa 62d1c806f7 OLE2FRAME: a frame with no width or height is picked as the line it is drawn as (review)
The renderer draws a zero-width frame as a line, so leaving it out of the hit geometry made a
visible object unpickable. Also corrects where the corner tolerance switches to ulps (4 ulps
pass 1e-6 near 1.1e9).
2026-11-05 16:06:13 +11:00
Davit MatchakhelidzeandClaude Sonnet 5.5 fe67c048ec Leave ROADMAP.md and docs/localization-parity.md to maintainers
CLAUDE.md: PRs don't edit these docs. The affected rows are named in the PR description.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-11-05 09:01:04 +04:00
Davit MatchakhelidzeandClaude Sonnet 5.5 40f060018d Leave .github/workflows/release.yml to a maintainer
CLAUDE.md: no CI changes in a feature or fix PR. The web-craft-fonts line is described in the PR description.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-11-05 09:01:04 +04:00
Davit Matchakhelidze 2c0fe29a02 Merge remote-tracking branch 'origin/main' into ka-language 2026-11-05 09:00:31 +04:00
Davit Matchakhelidze 7af5718b20 Merge remote-tracking branch 'origin/main' into fonts-georgian 2026-11-05 09:00:31 +04:00
SBaksa 35e85f8694 OLE2FRAME: comments match the tolerance; case lookup in one pass (review on #2587)
The ulp term takes over from CORNER_EPS from about 1.1e9, and the doc now says
so. The case of the nearest letter for each hex digit is found in two linear
passes instead of a search per digit; same result, covered by
moving_an_ole_frame_keeps_each_hex_digits_case.
2026-11-05 15:34:23 +11:00
SBaksa 63f53f6ed6 ARRAY, ARRAYPATH: one OLE frame check, after the matrices (review on #2587)
A matrix every frame accepts (a rectangular array, plain translations) now needs no
look at the objects, and an empty matrix list never touches the drawing. ARRAYPATH
scans the selection once instead of once per item.
Covered by the existing refusal tests; copy_all is not reachable without a drawing
through any command, so there is no no-drawing test.
2026-11-05 15:34:23 +11:00
SBaksa 95396c032d OLE2FRAME: only picking sees the frame edges (review on #2587)
Putting the frame in prims() also made it a TRIM/EXTEND edge, an object snap
target and dimension geometry. prims() is back to nothing for it, the extents
arm is restored, and select::hit_polylines adds the frame's outline for picking
(none for a frame with no width or height or a bad corner).
Tests: clicking_an_ole_frame_edge_selects_it (now also a frame with no width),
ole_frame_is_not_a_trim_edge_or_snap_target.
2026-11-05 15:34:08 +11:00
FredAppsandClaude Opus 5.5 c4d9e6ac64 fix(ui): About credits tables fit without side-scrolling and their columns resize (#2747)
* fix(ui): About credits tables fit without side-scrolling and their columns resize

The Contributors table and the Models table were egui Grids inside a
two-way scroll area: they opened wider than the dialog, so they scrolled
sideways, and Company and Model sat almost touching. Both are now
egui_extras tables. Each column opens at the width of its header and widest
cell, the spare width goes to the text columns (Name; Company and Model),
and every column edge can be dragged. Widening a column grows the table
like a spreadsheet, and only then does it scroll sideways; the header stays
put while the rows scroll. Counts and dates are right-aligned and every
cell is vertically centred.

The sorted column stays highlighted and its direction shows on the
toolbar's sort-order button, so headers no longer reserve room for an
arrow. The opening widths come from fit_widths, a pure function with unit
tests that a fitted table fills its room exactly and that only the text
columns give way when room is short.

The About dialog opens 820 points wide, so every column fits at its natural width.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Let every credits column be dragged, and refit changed tables

The last column was egui's remainder column, which has no drag handle, so
it could only be resized from the edge before it. It is now an ordinary
column with its own handle.

A table keeps its column widths, so switching to a longer name left the
Name column at its old width and clipped the text. The table now goes
back to the opening fit whenever that fit changes: a longer widest cell
or a resized window. Dragged widths are dropped at that point.

fit_widths could overflow the room when one column hit the minimum,
because the other columns did not take up its share. Columns now give
way in proportion to their width above the minimum.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

* Refit credits tables on what they measure, not the fitted widths

Comparing the fitted widths missed the case it was meant for. Name is the
only growing column, so a longer name takes its extra width from the
spare room and the fit comes out the same: a dragged Name width stayed,
clipping the longer name.

It could also drop dragged widths by accident. The fit comes from the
available width inside the scroll area, which scrolling can nudge, so
scrolling a widened table could reset it.

The table now compares the natural widths and the clip rect's width,
which scrolling does not move.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 04:33:26 +01:00
Tanish Manku 2569dbd58f Merge pull request #2803 from storytold/land/2316
Land #2316: Hebrew SHX fonts, font-change redraw, user font folders (fonts crate)
2026-11-04 20:20:01 -07:00
SBaksa 485c74da6b ARRAY: check OLE frames once (review on #2587)
copy_all scanned the selection for an OLE frame once per matrix before copying.
It now looks at the objects once and then only tests each matrix.
Covered by the existing refusal tests (classic_polar_array_refuses_a_turned_frame_but_not_an_upright_one).
2026-11-05 14:00:28 +11:00
Tanish Manku 843ffb6507 Fonts: a registered font outlives a rescan, also beside a file of the same stem (CodeRabbit on #2803) 2026-11-04 19:58:44 -07:00
SBaksa a779dadad5 OLE2FRAME: corner match and rotation bound scale with the coordinates; hex keeps its case (review on #2587)
The corner match was capped at 1e-6, under one ulp above about 8.6e9, so a frame
there never matched its header; a few ulps of the larger value now also match.
The rotation bound had a floor of 1 on the scale, so a small real turn at a tiny
scale passed; it is now purely relative. Hex digits are re-encoded in the case of
the digit at the same place, so untouched bytes keep their text.
Tests: ole_frame_moves_at_2e10_with_a_one_ulp_text_corner, ole_frame_refuses_a_small_turn_at_a_tiny_scale, moving_an_ole_frame_keeps_each_hex_digits_case.
2026-11-05 13:57:06 +11:00
SBaksa c397ab1e9e OLE2FRAME: the frame can be picked by its edges (review on #2587)
An OLE2FRAME is drawn but prims() gave nothing for it, so hit testing never saw
it and a click on its outline picked nothing. prims() now returns the frame's four
edges from the same corner helper the extents use, so the extents arm is gone.
The renderer keeps its closed-polyline arm (one joined outline, not four segments).
Test: clicking_an_ole_frame_edge_selects_it.
2026-11-05 13:55:27 +11:00
Tanish Manku 5b2c7bb0fb Fonts: a font's family name falls back to the family when the typographic one is blank (CodeRabbit on #2803) 2026-11-04 19:34:32 -07:00
Tanish Manku f7fbf41e61 Merge remote-tracking branch 'origin/main' into land/2316 2026-11-04 19:13:47 -07:00
Tanish Manku 1947e4e09e Fonts: review fixes on #2803 (Unix clippy, the degree sign in DOS Hebrew fonts, font-keyed caches)
- The linked-folder test (Unix only) passes a slice without a clone (clippy
  cloned_ref_to_slice_refs, which failed the Linux gate).
- In a DOS 862 Hebrew SHX font, %%d still draws from the old degree shape 127: only 128-129
  are letters there.
- The viewport highlight, drag preview and command preview caches key on the font set too,
  so text in them is drawn again when fonts change.
2026-11-04 19:13:39 -07:00
vangel76andClaude Sonnet 5.5 37eb21effe Merge upstream/main into fix/dxf-hostile-input-hardening
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-05 02:59:38 +01:00
3c123fd61c New and redrawn icons (drawn in code); clicks on painted controls keep the keyboard with the drawing (#2319)
* New and redrawn icons (drawn in code); a click on a painted control leaves the keyboard with the drawing

Split out of #2034. No image files: every icon is drawn in code.

- New: Zoom In / Zoom Out / Zoom to Fit, Move to Top / Up / Down /
  Bottom, Text Style and Dimension Style (with a small gear); redrawn:
  Undo, Redo, Plot, Preview, the dimension tools and others.
- icons::button_bare: a button without its hover text, for callers that
  show a richer tooltip.
- Clicking a painted control (a file tab) no longer takes keyboard focus,
  so Ctrl+C in one drawing and Ctrl+V in another keep working; Tab still
  reaches it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V

* Undo/Redo icons of our own design; the clipboard test requires the copied text

Review (CodeRabbit): the Undo/Redo comment named another product's icons as
the model. The icons are redrawn to our own design (a straight run and a
half-turn back, in the icon colour) and the reference is gone.

The cross-drawing clipboard test no longer falls back to placeholder text:
it installs a DXF writer and requires the copy to reach the system
clipboard.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V

* Icons: fit upstream's split icon painter (the pen's painter, theme colours, dim flag)

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V

* Icons: drop the dangling tool_button doc link; describe the tab click focus as it behaves

---------

Co-authored-by: Claude <noreply@anthropic.com>
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
2026-11-05 02:56:40 +01:00
Tanish Manku d12c87ca56 Fonts: review fixes on #2316 (load budget, linked font folders, a test in its own binary)
- A face found by family name in the user's font folders is loaded within the font-byte
  budget: no uncharged read past it (CodeRabbit on #2316).
- Linked font folders are followed again, as before #2316, in the system scan, the user
  scan and the SHX folder search; each real folder is read once, so a circle of links
  can't use up the scan's entry budget (CodeRabbit on #2316).
- The user-font-folder test changes process-wide font settings and emptied the font table
  under tests running beside it (2 of 3 runs failed): it moves to its own test binary,
  tests/ttf_font_folders.rs; that a list keeps no font bytes is checked on a local table.
2026-11-04 18:48:06 -07:00
SBaksa b2ded20888 OLE2FRAME: the axis-aligned check scales its tolerance with the matrix (review on #2587)
ALIGN builds its matrix from two angles that agree only to rounding, so a large
scale leaves a rotation part of about scale * 1e-16 that an absolute 1e-12 bound
refused as a turn. The bound now grows with the scale; a real turn is still refused.
Test: ole_frame_accepts_a_large_scale_with_rounding_noise_in_its_rotation.
2026-11-05 12:36:59 +11:00
Tanish Manku c56fcfc419 Merge branch 'pr-2316' into land/2316 2026-11-04 17:53:39 -07:00
Tanish Manku 5bfcee6299 Merge pull request #2795 from storytold/fix/array-extents
fix(doc): a rotated MINSERT array's extents reach its side copies
2026-11-04 17:51:22 -07:00
Dylan M. Taylor 594c30ae2d Pass the Linux signing key to the release workflow (#2798) 2026-11-04 17:45:46 -05:00
Tanish Manku fb6178b178 fix(doc): a rotated MINSERT array's extents reach its side copies
The extents took the first copy and the far corner copy only. Turned, the grid's
other two corner copies lie outside that box, so ZOOM Extents cut them off. All
four corner copies count now, and the counts are clamped to the 10,000 columns
and rows the renderer draws. Found by CodeRabbit on #2756.
2026-11-04 14:31:19 -07:00
Claude 962cebf9f6 Merge upstream main into split/shx-fonts
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V
2026-11-04 22:44:02 +02:00
Claude 7ea06a86db SHX fonts: list the ones in the user's font folders, for font lists
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V
2026-11-04 22:43:42 +02:00
Tanish Manku 3083b5b47f Merge pull request #2756 from storytold/land/2354
XCLIP and XCLIPFRAME; invert flag as AutoCAD's group 290 (#2354)
2026-11-04 13:41:12 -07:00
Tanish Manku f554de28b5 XCLIP: ON/OFF checks without copying boundaries and sets each reference once (CodeRabbit on #2756) 2026-11-04 13:02:38 -07:00
ffishman 190a44d3eb Merge main into fix/dwg-render-settings-class-version
main's #2673 runs the DWG writer in a child process. The kept version now goes with the request
(encode_kept_noted, worker protocol 2), so the worker reads the bridge DXF as that version too.
The proxies proxy_classes leaves out are now counted in Unwritten, as ACAD_PROXY_OBJECT and
ACAD_PROXY_ENTITY.
2026-11-04 15:46:24 -03:00
Claude 2c979eb14b Fonts: user font folders, Hebrew SHX fonts, redraw when fonts change (on #1944's SHX)
Rebuilt on main after #1944 (SHX shape fonts, big fonts, unifonts) landed: this part now
keeps only what #1944 doesn't do.

- User font folders (Options > Fonts, fontFolders): TrueType and OpenType files in them are
  found before the system's and listed first (ttf::set_font_dirs, installed, available,
  rescan); a face is found by its family name in any file there. SHX files in them, or in a
  folder under them, are found by the SHX font table too (shx::set_font_dirs), after the
  drawings' folders and before the search path. Folders are cleaned and capped, links to
  folders are not followed.
- Hebrew SHX fonts: a one-byte font with the letters at their Windows-1255 or DOS 862 places
  draws Hebrew text from them; a Cyrillic font with letters at those places is not taken for
  Hebrew. In a DOS 862 font, %%d %%p %%c come from shapes 256-258 only.
- The canvas draws text again when the TrueType or SHX font set changes (a font folder, a
  rescan, a drawing folder), the active viewport's model space included.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RzTHYMZTCtkW9FExLCKj5V
2026-11-04 20:21:02 +02:00
assamaralandClaude Opus 5.5 2872c05162 fix(io): read VIEWPORT ids outside 1..=32767 as unknown
Group 69 is a 16-bit code. Large values passed the filter and `as u32`
truncated them, so 69 = 4294967297 read as a second id 1. Also drop the
docs/file-format-parity.md row: PRs name affected rows in the description.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 13:47:19 -03:00
assamaralandClaude Opus 5.5 0642d34244 Merge upstream/main into fix/dxf-viewport-id-unknown
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 09:24:42 -03:00
霁伪 e49ece380c Merge upstream/main into feat/text-edit-window
Upstream kept adding catalog strings (viewports, raster images, named views),
which landed next to this branch's textdlg rows in the same catalogs. Both
sides kept, upstream's rows first.
2026-11-04 17:42:02 +08:00
Tanish Manku 371e8b9e02 XCLIP: ON/OFF checks every selected reference before changing any (CodeRabbit on #2756) 2026-11-03 21:56:58 -07:00
Tanish Manku ff5b55842e XCLIP: bound a filter's vertex count before allocating (CodeRabbit on #2756) 2026-11-03 21:34:23 -07:00
Tanish Manku 064f58f252 XCLIP: write an inverted clip as AutoCAD does in a file (no group 290)
AutoCAD 2024 writes no group 290 on a SPATIAL_FILTER in a DXF and discards a file whose
filter has one (measured by 2ez4gcx, #2756). An inverted clip's filter now gets an
extension dictionary with the ACAD_XREC_ROUNDTRIP XRECORD (ACAD_INVERTEDCLIP_ROUNDTRIP,
then ..._COMPARE). Reading takes the ROUNDTRIP list as the boundary while COMPARE matches
the filter's vertices, so AutoCAD's keyhole filters read as the clip drawn; 290 is still
read when present. The record survives DWG, so CADCraft's own CADCRAFT_XCLIP flag is gone.
2026-11-03 21:16:55 -07:00
Tanish Manku ef4b4f7e6c XCLIP: review fixes from CodeRabbit on #2756
- objects are found through a handle index when reading and writing clips, and removed in one pass (no scan per reference)
- the writer's handle seed starts past the clip objects, so a drawing with many clipped references gets no duplicate handles
- a clipped copy that runs out of the block budget marks the list truncated, like an unclipped one
- clipped block contents keep their own layers in plots
2026-11-03 19:34:20 -07:00
Tanish Manku 510b7283cb XCLIP: Chinese labels for Clip Xref, Xref and Xref Clip Frame 2026-11-03 19:11:23 -07:00
Tanish Manku 0d72152142 Merge main into land/2354 2026-11-03 18:21:00 -07:00
Tanish Manku 639c2e9825 XCLIP: clip on DVIEW's preview reference 2026-11-03 18:20:48 -07:00
Tanish Manku 2099288f54 Merge pull request #2751 from storytold/land/1944
SHX fonts, big fonts and unifonts; linetype shapes (#1944)
2026-11-03 18:20:27 -07:00
Tanish Manku 100d812155 Merge main into land/2354 2026-11-03 18:07:17 -07:00
Tanish Manku e90a197365 XCLIP: keep CADCraft's inverted flag beside group 290 for DWG, whose bridge drops 290; the flag is read only when 290 is absent 2026-11-03 18:07:00 -07:00
Tanish Manku de753897c4 Merge main into land/1944 2026-11-03 18:00:03 -07:00
Tanish Manku 39ee2e5960 SHX fonts: review fixes (search the current folder for a bare drawing name, one lock for the font cache generation, no split_paths on wasm, MTEXT \U+ upper case as the layout, a point budget for repeated linetype shapes, web picks report skipped files and cap bytes read at once) 2026-11-03 17:59:52 -07:00
Tanish Manku 5f8999f303 Merge pull request #2748 from storytold/land/1230
View twist: DVIEW, twisted views, tiles and layout viewports (#1230, #2022)
2026-11-03 17:59:40 -07:00
Tanish Manku 75049718c9 View twist: build with raster images from main (an axis rectangle is turned on a twisted screen, so it cuts an image as an outline) 2026-11-03 17:35:23 -07:00
Aldo ZarateandClaude Opus 5.5 8d1ab2aad6 Merge upstream/main into fix/tilted-2d-read
The revision history keeps both rows. Main's new dynamic block test
expected a polyline in a tilted plane to keep that plane's coordinates;
this branch reads it as seen from above, so its stretch now tests the frame
against those points and moves it whole. The slight tilt below the
projection threshold still uses the stored vertex list.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 18:32:44 -06:00
Tanish Manku 76d09aaddf Merge remote-tracking branch 'origin/main' into land/2354 2026-11-03 17:22:36 -07:00
Tanish Manku d1e6f4df96 XCLIP: invert flag as group 290, extents are the boundary's box, Delete with no boundary asks again; clip on main's new Insert literals 2026-11-03 17:22:36 -07:00
Tanish Manku c2d62a2842 Merge main into land/1944 2026-11-03 17:11:42 -07:00
Tanish Manku 68e01dd487 Merge main into land/1230 2026-11-03 17:11:25 -07:00
Tanish Manku 6d3507f98d Merge pull request #2749 from storytold/land/2505
Raster images drawn on screen and in PNG output (#2505)
2026-11-03 17:10:59 -07:00
Tanish Manku 26e96cfb56 View twist: a locked viewport keeps its twist; the untwisted file view fits the extents as the turned view sees them
Review fixes from CodeRabbit on #2748:
- DVIEW TWist and view.set refuse to turn a locked active viewport ("The viewport is locked.")
- the untiled *Active VPORT record fits the extents rotated by the twist it writes, with the twist normalised
2026-11-03 17:10:20 -07:00
Tanish Manku 945c7f456b Merge remote-tracking branch 'origin/main' into land/1944 2026-11-03 16:52:21 -07:00
Tanish Manku f10e41409d Images: read no more than the limit, keep plot bounds to what a viewport shows, free textures with no images left
Review fixes from CodeRabbit on #2749:
- the image file is read through read_capped, so a file that grows after the size check can't exhaust memory
- an image cut by a layout viewport widens the sheet's bounds only by the part inside it, as other primitives do
- uploaded tiles of closed drawings are dropped also when the next list has no images
2026-11-03 16:52:11 -07:00
Tanish Manku 5bd563caac Merge main into land/2354: charge every block visit in the clipped copy too 2026-11-03 16:42:36 -07:00
Tanish Manku bd22363d5e Merge remote-tracking branch 'origin/main' into land/2505 2026-11-03 16:40:52 -07:00
Tanish Manku a6ef259fec Merge remote-tracking branch 'origin/main' into land/1230 2026-11-03 16:40:36 -07:00
Dylan M. Taylor dad7d1c138 fix(render): charge every block entry, index attribute definitions, and walk dashes and outlines in linear time (#2724)
* fix(render): charge every block entry, index attribute definitions, and walk dashes and outlines in linear time

Array copies skipped ATTDEF entries before charging the expansion budget, each attribute searched its block for a definition, each dash scanned every centreline sample, and outline chaining searched a vertex's segment list from its start on every visit. Each is now charged, indexed or cursored.

* address review: drop wall-clock bound from outline test
2026-11-03 18:11:23 -05:00
Dylan M. Taylor b1b3754ffa fix(engine): autosave files are owner-only and lock files are never written through a link (#2717)
The heartbeat opened <instance>.lock with a create-and-truncate that followed symlinks, and fell back to std::fs::write, so another account sharing SAVEFILEPATH could plant a link and have the app truncate a file of the victim's. The lock is now opened with O_NOFOLLOW|O_NONBLOCK and must be a plain file, and unlocked writes replace the file through the atomic writer. Autosave files are created 0600 regardless of umask. Lock pruning parses the folder's autosave names once instead of once per lock.
2026-11-03 18:11:06 -05:00
Tanish Manku 0e19f9d1d1 SHX fonts: build on main (a bottom-justified SHX text sits a third of the height down; explicit render imports after #2239) 2026-11-03 15:41:48 -07:00
Tanish Manku 8232290830 View twist: a window too large to turn saves no view, and the saved one stays 2026-11-03 15:40:39 -07:00
Tanish Manku 457fc2319e View twist: review fixes
- Every engine twist (DVIEW, view.set, opening a drawing, the untiled view) goes through norm_angle, so a tiny negative twist is 0, not a full turn.
- VIEW Window in a twisted view stores the window's size along the view's axes (View::twisted_box), so a restore shows all of it.
- A deferred tangent or perpendicular snap on an arc in a twisted layout viewport turns the arc's angles with its centre.
- The active viewport's cached drawing is rebuilt when its twist changes; moving and scaling it can't turn it.
2026-11-03 15:14:10 -07:00
Tanish Manku 15afc47296 Images: Chinese labels for IMAGEATTACH and IMAGE 2026-11-03 15:12:28 -07:00
Tanish Manku d3226e629e Images: the highlight outline uses main's world-point line helper 2026-11-03 15:04:12 -07:00
Tanish Manku 238aa1789c Images: draw an IMAGE in its own function, under the complexity limit 2026-11-03 15:03:06 -07:00
Tanish Manku f1312113d2 Images: format after the merge with main 2026-11-03 15:01:55 -07:00
Tanish Manku 8cdcd6f85c Merge #2354 (XCLIP and XCLIPFRAME) onto main 2026-11-03 15:00:20 -07:00
Tanish Manku 28421dd1d7 Merge #1944 (SHX shape fonts, big fonts and unifonts; linetype shapes) onto main 2026-11-03 14:59:22 -07:00
Tanish Manku 162cc4792b View twist: read and write every twist within one turn, so #2022's hostile-angle checks hold
A twist of -1e-20 degrees read as a full turn (2π), and a huge twist set from JSON or MCP was written as a huge angle. Readers and writers of VIEWPORT 51, VPORT 51 and VIEW 50 now go through norm_angle.
2026-11-03 14:58:37 -07:00
Tanish Manku 4c00b6732f Merge #2505 (raster images drawn on screen and in PNG output) onto main 2026-11-03 14:52:15 -07:00
Tanish Manku 58bb1e065e docs: date the view twist revision rows to the day they land 2026-11-03 14:50:59 -07:00
Tanish Manku 0955078f56 Merge #1230 (view twist: DVIEW, twisted views, tiles and layout viewports) over #2022 2026-11-03 14:50:43 -07:00
mattlafyandClaude Opus 5.5 f04be0548f fix: new Viewport, VportTile and Xf initializers from main set the view twist; DView has its Chinese label
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 14:56:46 -05:00
mattlafy 852688e000 Merge remote-tracking branch 'upstream/main' into wt-dview 2026-11-03 14:17:57 -05:00
ATARYS-LABandClaude Opus 5.5 6d31491952 Viewport twist: the viewport of main's block expansion test has no twist
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XkJ8y75DE7yLZ7utxSRDeP
2026-11-03 18:35:48 +01:00
ATARYS-LABandClaude Opus 5.5 c8e1671eb4 Viewport twist: normalise with norm_angle on read and write; test the untwisted case on a real viewport
From CodeRabbit's review: a tiny negative angle no longer reads as a full turn, a huge finite
twist from JSON or MCP no longer writes an infinite group 51, and the "no group 51" check now
looks at a viewport that exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DRnJvmr59vS3DS5p2E8FhG
2026-11-03 18:32:40 +01:00
ATARYS-LABandClaude Opus 5.5 f7494840dc A layout viewport keeps its view twist through DXF and DWG (part of #1316)
VIEWPORT group 51 was not read, so a twisted viewport came back untwisted and a DXF or DWG
saved by CADCraft wrote it without its twist; AutoCAD then showed the sheet rotated. The twist
is now read (finite angles only, brought into one turn) and written when it isn't zero; the DWG
bridge already carries group 51 both ways. The display and plots don't apply it yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DRnJvmr59vS3DS5p2E8FhG
2026-11-03 18:32:40 +01:00
assamaralandClaude Opus 5.5 9ef9bdb55e Merge upstream/main into fix/dxf-viewport-id-unknown
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:58:24 -03:00
Hamza 44700c5a36 Merge remote-tracking branch 'origin/main' into stored-model-view
# Conflicts:
#	crates/io/src/dxf_read/tables.rs
2026-11-03 18:48:16 +05:00
assamaralandClaude Opus 5.5 714e1db0aa Merge upstream/main into fix/dxf-viewport-id-unknown
Conflict in crates/io/src/tests.rs: both sides kept.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 06:22:10 -03:00
Davit MatchakhelidzeandClaude Opus 5.5 f9cb70500d docs: Georgian font fallback in the Georgian section
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:17:59 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 e8408851cd docs: the Georgian face paragraph describes glyph support only
Choosing ka, its English fallback and the picker name come with the
language PR (#2016), which registers ka; this PR alone doesn't.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 11:17:59 +04:00
SBaksa 457627df33 OLE2FRAME: validate hex strictly, rewrite only the header groups, cheaper corner lookup (review on #2587)
A sign in a hex pair is no longer accepted; only the 310 groups holding the 98-byte header are decoded and rewritten, in place and without cloning the payload; the corner lookup is one allocation-free pass; the io ole_frame test module is not built for wasm like its DWG siblings; Unknown::is_ole_frame replaces five copies of the type check. Tests: a_plus_sign_in_ole_data_is_not_hex, a_large_ole_payload_only_rewrites_its_leading_groups.
2026-11-03 16:44:30 +11:00
SBaksa be413af026 OLE2FRAME: arrays refuse before adding copies; clearer refusal (review on #2587)
ARRAYPATH with align and polar arrays that rotate items refused part way, leaving the earlier copies in the drawing. Every copy's matrix is now checked before the first copy is made. The refusal text names the other unsupported transforms. Test: arraypath_refuses_before_adding_any_copy.
2026-11-03 16:37:51 +11:00
SBaksa 0a0a820759 OLE2FRAME: any transform leaves the frame axis-aligned and its data consistent (review on #2587)
EXPLODE, REFEDIT, paste and array placement call EntityKind::transform with rotations and mirrors, which left groups 10/20 not upper-left and the data header not matching. ole_frame_transform now takes the box of the two mapped corners (upper-left, lower-right) and writes the header as UL, UR, LR, LL of that box. Test: a_rotated_frame_stays_axis_aligned_and_consistent (rotate 30 and mirror).
2026-11-03 16:36:05 +11:00
SBaksa 42e3d964dc Merge remote-tracking branch 'origin/main' into ole-frame 2026-11-03 16:22:22 +11:00
SBaksa 48165e6cd9 io tests: order the ole_frame module as rustfmt wants after the merge 2026-11-03 16:15:10 +11:00
SBaksa 8cc2c4e847 OLE2FRAME: corner match has a fixed ceiling at large coordinates (review on #2587)
The relative tolerance grew with the coordinate: at 1e9 a payload 0.5 off the frame still matched and was rewritten. It is now capped at CORNER_EPS (1e-6), still above an ulp at 1e9. Tests: a_half_unit_offset_at_large_coordinates_is_not_the_frame, exact_corners_at_large_coordinates_still_move.
2026-11-03 15:45:20 +11:00
SBaksa 9bd5c479e3 OLE2FRAME: SCALE carries a frame with a uniform positive factor (review on #2587)
ole_frame_accepts took only a translation, so SCALE on a selection with a frame failed as a whole. A uniform positive scale keeps the frame axis-aligned and upper-left, so the corner rewrite handles it; rotation and mirroring are still refused. Tests: scale_carries_an_ole_frame_with_the_rest_of_the_selection, mocoro_scales_an_ole_frame, ole_frame_accepts_translations_and_uniform_positive_scales_only.
2026-11-03 15:45:05 +11:00
霁伪 faaa12df3f Merge upstream/main into feat/text-edit-window
#2607 (FIND) landed first, so this keeps both sides of the i18n rows: the
finddlg entries upstream brought and the textdlg entries this branch adds.
2026-11-03 12:19:25 +08:00
Davit MatchakhelidzeandClaude Opus 5.5 4b532f6c24 i18n(ka): translate the strings added upstream; prompts without the trailing "or"
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 08:01:13 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 891e87a7db Merge upstream main into ka-language
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 08:01:13 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 e931787a64 Merge upstream main into fonts-georgian
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-03 08:00:05 +04:00
mattlafy cbc9db75b1 Merge remote-tracking branch 'upstream/main' into pr/dview
# Conflicts:
#	crates/engine/src/prompt.rs
#	crates/engine/src/session/execute.rs
#	crates/io/src/dxf_read/entities.rs
#	crates/ui-egui/src/canvas.rs
#	crates/ui-egui/src/cmdline.rs
2026-11-02 21:53:26 -05:00
SBaksa a9dbc50ce2 Merge origin/main into ole-frame (drop parity-checklist change) 2026-11-03 13:46:27 +11:00
ffishman 6c80e04faa Merge main into fix/dwg-render-settings-class-version
main's #2474 and #2582 change not_saved_as next to the proxy class check, and #1725 adds a test next to ours; all are kept.
2026-11-02 21:38:02 -03:00
ffishman 3e3ac42b60 Merge main into fix/page-setup-media-orientation
main's #2623 adds PageSetup::image_origin next to file_paper; both are kept.
2026-11-02 21:37:02 -03:00
Slopapalooza 5155c9aea8 Merge remote-tracking branch 'origin/main' into properties-set-locked
# Conflicts:
#	crates/engine/tests/it/main.rs
2026-11-02 16:54:16 -05:00
assamaralandClaude Fable 5.1 dd3ffe7ae7 Menus list their items in the reference menu tree's order
menus::tree sorts every menu, at every level, by xtask/data/menu-catalog.txt
(embedded with include_str!, so the parity oracle is the one source): the
items the reference has come first, in its order; the rest keep registration
order. The in-window menu bar, the native macOS menu and ui.menu.list all
follow. Labels are unchanged.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 17:38:28 -03:00
assamaralandClaude Fable 5.1 e8e76d2e60 Menus: test that every menu follows the reference menu tree's order
Reads xtask/data/menu-catalog.txt (the parity oracle) into a tree and
checks menus::tree against it at every level. Fails on main: 19 menus
and submenus list their items in command registration order.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-11-02 17:38:25 -03:00
ffishman 319351578e A proxy whose number names no class is left out of the DWG
dxf_to_dwg_as kept a proxy whose class number names no class of the DXF's CLASSES with that
number, which names some other class of the DWG. It is now left out and counted, as a binary
DXF's proxies are, and as CADCraft's own save already does.
2026-11-02 10:28:26 -03:00
ffishman 5d0b723ddb Merge main into fix/dwg-render-settings-class-version
main's #2619 adds Foreign::tree and adopt_tree next to the proxy class helpers.
2026-11-02 10:27:56 -03:00
Hamza 5224f067e0 Carry the saved view onto the first tile only when there is one
My previous commit put `center` and `height` on the first `*ACTIVE` tile
unconditionally. Those two are the extents fallback when the header holds no
saved view, and a tiled drawing can hold none -- `-VPORTS` splits the current
view into tiles without setting one -- so the override replaced the first tile's
own good view with a fit to the extents, and the drawing opened somewhere else
(noted in review).

Guarded on `saved_view().is_some()` now: with a view it is carried, without one
the tiles are written as they stand, which is what they were before.

`a_tiled_drawing_with_no_saved_view_keeps_its_first_tiles_view` asserts the
first tile keeps its centre and height, the second keeps its own, and that the
header read back is the tile's view rather than the writer's extents fit.
2026-11-02 17:38:20 +05:00
ffishman 946af87458 A proxy whose class the file doesn't name is reported as not saved
From 2013 the DWG keeps another program's proxy entity with the class its group 91 names, so the
loss report skipped every ACAD_PROXY_ENTITY. Saving drops a proxy whose group 91 names no class of
the file's CLASSES, though, so that one is now counted. The group 91 helpers move to
cadcraft_doc::foreign so the engine can ask Foreign::proxy_class.
2026-11-02 08:54:58 -03:00
ffishman 36e8c02682 Leave the parity docs to the maintainers
AGENTS.md: PRs name the affected rows and maintainers update docs/file-format-parity.md in batches.
2026-11-02 08:54:11 -03:00
Hamza 04f06a2f87 A tile's rectangle and the view it shows are judged apart
Two from review, both about one `*ACTIVE` record carrying two separate things:
where the tile sits on the screen (10/11) and the view it shows (12/22, 40).

Reading: the two were one `ok`, and the early return came before the view was
read. A first `*ACTIVE` with a usable view and an unusable rectangle therefore
lost the view, and a file whose header carries none opened on the extent fit
instead of where it was saved. They are judged apart now -- `view_ok` decides
the saved view, `tile_ok` decides the tile -- so the rectangle is still refused
while the view it holds is kept.

Writing: the tiled branch emitted the stored tiles as they stand, so updating
`header.set_saved_view` on a drawing with several tiles wrote the new view in
HEADER and the old one in the first `*ACTIVE`. The read takes its view from
that record, so the update did not survive a round trip. The first record now
carries the saved view while keeping its own place on the screen, and the tiles
after it are untouched.

Three tests: a bad rectangle still gives its view (and the rectangle is still
refused), a record with no usable view leaves the header alone, and a view set
on a two-tile drawing comes back from a round trip with both tiles still there,
the first keeping its half of the screen and the second its own view.
2026-11-02 15:25:55 +05:00
霁伪 322c5e9bbf TEXTEDIT: the field keeps its undo history per object, and the shortcut works on macOS
The multiline field is keyed by drawing and handle, so two edits never share
a Ctrl+Z trail, and the field's persisted state is removed with the window -
otherwise the undo history would offer a previous object's text to whoever
is edited next. The commit shortcut now checks Control rather than the
platform Command modifier, matching the Ctrl+Enter the window advertises.
2026-11-02 07:52:05 +08:00
霁伪 44950708ba TEXTEDIT: the context-menu test follows the window entry, several texts keep the command 2026-11-02 07:23:09 +08:00
霁伪 df26fc5197 TEXTEDIT: the window opens from the shortcut menu; the double-click keeps its in-place editing
The double-click on a text object goes back to starting the in-place TEXTEDIT
(#842), which the text_double_click tests guard. The window is what the
shortcut menu's Edit Text entry opens for a single selected text, mtext or
attribute definition; with several objects selected the command line still
runs.

The window records the drawing it was opened for and refuses to commit into
another one, and its state now lives exactly as long as the window does, so a
cancelled edit cannot resurface.
2026-11-02 06:34:15 +08:00
霁伪 9dc39260b8 Merge upstream/main into feat/text-edit-window 2026-11-02 06:13:11 +08:00
SlopapaloozaandClaude Opus 5.5 7e386a2cc4 Review fix: test that an edit only outside the working set changes nothing
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 14:38:15 -05:00
SlopapaloozaandClaude Opus 5.5 8b91646795 Review fix: CHPROP says what it left out; the working set is read once
Interactive CHPROP threw away properties.set's message, so an edit to an
object it had just moved onto a locked layer was left out without a word.
It now shows the message.

properties.set looked each object up in REFEDIT's working set, a list,
twice; it now builds the set once and checks the layer directly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 14:10:07 -05:00
SlopapaloozaandClaude Opus 5.5 e82dede24a Review fix: properties.set counts each object once and refuses missing ones first
`targets` keeps a handle listed twice, so it was counted twice as left
out. During REFEDIT, a handle that names no object counted as outside the
working set instead of being refused. properties.set now takes each
object once, and refuses a handle that names no object before anything
changes; before, the objects ahead of it in the list had already been
changed when the error came.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:48:18 -05:00
SlopapaloozaandClaude Opus 5.5 c311ec6b77 Review fix: CHPROP's parameter text says what properties.set now returns
CHPROP's JSON form is properties.set, so its description now names the
REFEDIT working set too and lists `message` in the result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:38:01 -05:00
ffishman 02cc5c8853 Merge main into fix/dwg-render-settings-class-version
main now gates the DWG bridge on cfg(no_dwg_bridge) (FreeBSD aarch64 has no acadrust); dxf_to_dwg_kept_as and its tests follow it.
2026-11-01 15:22:27 -03:00
ffishman 582758adc1 Merge main into fix/page-setup-media-orientation
main's conformance matrix (#2237) compares page setups across saves; file_paper is the file's own groups 44/45/73, so it compares the setting without it, as tables_objects_roundtrip already does.
2026-11-01 15:21:45 -03:00
SlopapaloozaandClaude Opus 5.5 5787b3634f Review fix: properties.set checks every value before leaving all objects out
With every object on a locked layer, properties.set returned before it
checked the linetype, the dimension style and the dimension overrides, so
it accepted bad values there. They're now checked first, reading the
drawing without writing to it; the drawing is taken for writing, and a new
layer made, only when there are objects to change.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 13:06:16 -05:00
SlopapaloozaandClaude Opus 5.5 0dcdf8d7a9 properties.set leaves objects on locked layers out and says how many
The Properties palette, Quick Properties and CHPROP's JSON form all edit
through properties.set, which changed objects on locked layers. It now
leaves them out and changes the rest, as CHPROP, MATCHPROP, MOVE and
CUTCLIP already do. During REFEDIT, objects outside the working set are
left out too, instead of the whole edit being refused.

The result gains `locked`, and a `message`, which app.run shows at the
command line, says how many were left out. When every object is left out,
the drawing doesn't change and no undo step is added.

CHPROP's JSON form was properties.set on the unlocked objects; it is now
properties.set itself.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 12:02:37 -05:00
霁伪 6b707c89e4 TEXTEDIT: edit text in a window, from a double-click
TEXTEDIT took over the command line: the caret left the drawing, the prompt asked for a point, and the text was edited where you could no longer see it. The shortcut menu offered Edit Text on text, mtext and attribute definitions, and that is exactly where a user expects to type.

A double-click on one of those objects now opens a small window holding the object's text, its type and its handle, with OK and Cancel. Ctrl+Enter applies. Text that has not changed sends no command, so the undo stack stays clean.

The TEXTEDIT command itself is untouched: scripts, LISP and the command line still drive it as before, and the window is a second surface on the same edit.
2026-11-01 23:14:16 +08:00
Aldo ZarateandClaude Opus 5.5 9735b23227 Tilted planes: decide by how far points would move; spread arc widths
An object counts as tilted when drawing its OCS points as plan
coordinates would put some of them off their place seen from above by
more than a billionth of its size and distance from the origin, sampled
along its arcs too. A slight tilt far from the origin is now projected,
and noise in a plan normal still leaves the object (and its arcs) alone.

A flattened tilted arc spreads its start and end widths evenly over its
segments, as a tapered segment does.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 06:41:10 -06:00
SBaksa b54adc5976 OLE2FRAME: MOCORO checks before it changes anything; a locked frame doesn't block in-place edits (review on #2587)
MOCORO refuses a rotate or scale step on an OLE frame up front, before an earlier move or copy
is applied. refuse_ole_frames ignores a frame on a locked layer for in-place edits, as
edit_entities does. Tests: mocoro_refuses_before_it_changes_anything,
a_locked_ole_frame_does_not_block_an_in_place_rotation.
2026-11-01 23:32:59 +11:00
SBaksa c9ffc3e394 OLE2FRAME: a frame without usable corners counts as not drawn in an image export (review on #2587)
The renderer draws nothing for it, so it is no longer reported as shown as the frame only.
Test: an_ole_frame_without_corners_is_counted_as_not_drawn.
2026-11-01 23:32:58 +11:00
SBaksa 7fdda542d3 OLE2FRAME: MOVE rewrites the corners in the OLE data only when they are the frame's corners (review on #2587)
The data layout is only known when its corners match the frame's groups; any other
header is left byte-identical while the tags still move. Test: move_leaves_ole_data_that_is_not_the_frames_corners_alone.
2026-11-01 23:32:58 +11:00
Aldo ZarateandClaude Opus 5.5 90806a7476 Tilted LWPOLYLINE: flatten each arc within a tolerance from its own size
A long edge elsewhere in the run made the tolerance larger than a small
arc, which then flattened to its chord.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 06:25:21 -06:00
SBaksa 64644ebc1c Merge remote-tracking branch 'origin/main' into plot-device-from-extension 2026-11-01 22:28:12 +11:00
SBaksa 0c486e337a Engine: refuse rotating, scaling or mirroring an OLE frame on main's transform paths (#2587)
Main moved the edit loop into edit_entities and gave SCALE its own scale_entities, so the
merged check no longer compiled (CI: m not in scope). The refusal is now one helper that
transform_entities and scale_entities call before anything changes.
2026-11-01 22:25:36 +11:00
SBaksa d6555e5bdf Plot: an unknown extension needs a real format selector (review on #2585)
device None and a null or unknown output no longer bypass the refusal
and write a PDF under the odd name; only a recognised output or a
device that resolves does. Test: plot_path_extension_picks_the_format_like_export.
2026-11-01 22:20:10 +11:00
SBaksa 0e871873e7 Plot: refuse layout and layouts that name different sheets (review on #2585)
layout picked the rendered space while layouts filled the reply, so a
request could render Model and report Layout1. Both selectors must now
agree, for every output. Test: plot_goes_through_the_hook.
2026-11-01 22:20:09 +11:00
SBaksa 63bc538113 Parity checklist: regenerated after merging main 2026-11-01 22:09:49 +11:00
SBaksa 1c66fa2338 Merge remote-tracking branch 'origin/main' into ole-frame 2026-11-01 22:02:19 +11:00
SBaksa afb24ee6e5 OLE2FRAME: MOVE also moves the corners inside the OLE data (review on #2587)
The OLE data (310 groups) starts with the frame's four corners. MOVE shifted groups 10/20/11/21 only, so
a DXF save wrote new corner groups beside a data header with the old position. The transform now
rewrites those doubles (x, y; z kept) in the decoded hex, keeping each chunk's length; malformed or
short data is left untouched.
2026-11-01 21:08:47 +11:00
SBaksa c1b88a6cbc OLE2FRAME: an image export notes that the OLE content is not drawn (review on #2587) 2026-11-01 19:21:22 +11:00
SBaksa 09b5fb9328 Plot: refuse a path whose extension names no format (review on #2585)
A path like x.txt (or one with no extension) wrote a PDF under that name. Like EXPORT, PLOT now refuses it unless output or a device says what to write. Test: plot_path_extension_picks_the_format_like_export.
2026-11-01 19:13:53 +11:00
SBaksa 87f3c087b2 OLE2FRAME: corners skip application groups; MOVE/COPY carry the frame, rotate/scale/mirror refuse it (review on #2587)
ole_frame read 10/20 and 11/21 from inside 102 groups; it now skips them as the DXF reader does.
A window-selected OLE2FRAME was left in place by MOVE/COPY. A DWG save writes the position from
the corner groups (checked by write + read-back), so MOVE/COPY now shift them; transforms that
would not keep it axis aligned return an error before anything changes.
2026-11-01 18:12:57 +11:00
SBaksa 12ce66889e Plot: a single layouts entry picks the sheet for PNG and SVG (review on #2585)
run_plot rendered the session space for image output while the reply named the layout. The one-entry list now resolves to the render space, as the PDF path does. Test: plot_goes_through_the_hook.
2026-11-01 18:06:41 +11:00
SBaksa 8dc927e01c Format: rustfmt after the clippy fix (review on #2587) 2026-11-01 16:57:17 +11:00
SBaksa b51318003b Parity checklist: regenerated after merging main 2026-11-01 16:21:24 +11:00
Aldo ZarateandClaude Opus 5.5 a49e4ff941 Tilted LWPOLYLINE: straight edges keep their widths next to flattened arcs
Only bulged edges are flattened now, each on its own; the vertices that
start straight edges keep their widths.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:45:35 -06:00
SBaksa ad609fab02 OLE2FRAME: the frame counts in the drawing extents; CLI test uses a self-cleaning dir (review on #2587)
bounds_in now takes the frame from its corner tags (shared ole_frame in the doc crate), so zoom extents shows a frame outside other geometry. The undrawn_entities tests clean up on drop.
2026-11-01 15:38:48 +11:00
Aldo ZarateandClaude Opus 5.5 756946c4d6 Tilted LWPOLYLINE keeps its widths; a tilted hatch's gradient turns too
Straight runs carry each vertex's widths onto its projected vertex
(flattened arcs still have none). The gradient direction is projected
like the pattern's. A pattern keeps the spacing and dashes of its plane,
noted in the parity doc.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 22:29:03 -06:00
SBaksa c22700d3af Plot: refuse several layouts for PNG and SVG output (review on #2585)
An image holds one sheet, so layouts with more than one entry now report a clear error instead of pages:N with one render.
2026-11-01 15:27:09 +11:00
Aldo ZarateandClaude Opus 5.5 d19df49fcf HATCH and LWPOLYLINE in a tilted plane are read as seen from above (#1886)
Their boundary and vertices are in the object's plane (OCS). Only a
mirrored plane (0,0,-1) was handled, by flipping x; a tilted plane whose
normal points down was taken for a mirror too, and one pointing up kept
its plane coordinates, so each face landed turned about the origin by
its own angle. A tilted one is now mapped to the WCS and drawn as seen
from above at its mean height: bulged edges are flattened (they are
elliptical there), and a hatch's pattern direction and origin follow.
Its extrusion becomes Z, since its points are plan coordinates now.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 19:01:28 -06:00
SBaksa 26c24c5bb0 Parity checklist: regenerated after merging main 2026-11-01 11:08:06 +11:00
SBaksa 62e70432e7 Plot: choose the output format from the path extension (#2556)
plot ignored the extension of `path` and wrote PDF unless a device said otherwise.
Without a device, png/svg/pdf is now taken from the extension (any case), like export;
a device that writes another format is refused, and the reply carries `format`.
Tests plot_format.rs check magic bytes, the mismatch error and the reply format.
2026-11-01 11:05:33 +11:00
vangel76andClaude Sonnet 5.5 1a0ef86aeb Merge upstream/main into fix/dxf-hostile-input-hardening
Resolve the dxf ascii() conflict: keep upstream's byte output and
push_string, and the branch's hex chunking so a hostile value can't
inject tags.

The binary reader keeps upstream's policy: pre-R2007 binary strings
are read from the code page, because a binary DXF cannot escape to
UTF-8; the ASCII reader keeps this branch's per-line UTF-8 rule.
The two branch tests that assumed UTF-8 in binary strings are
updated to the code-page reading.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-31 11:25:10 +01:00
2ez4gcxandClaude Opus 5.5 156d117dd8 fix(modify): BREAK and TRIM keep the object's handle, as AutoCAD does
BREAK, BREAKATPOINT and TRIM erased the object and added every piece as
a new object. AutoCAD 2024 changes the object itself: the piece holding
its start (or the only piece left: a circle becomes an arc, a closed
polyline is opened) keeps its handle, drawing-order place, groups and
extended data; the other pieces are new objects added at the end.

Associative dimensions follow the measured rule: an attachment still at a
point of the object stays, one on a new piece moves to it, any other
follows the object's new end. Constraints on the object are removed, as
before. New pieces go to the object's own space.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-31 16:34:08 +07:00
SBaksa a8d05d6894 CLI: an OLE2FRAME is not reported as undrawn by an image export (#2422)
Found end to end: convert to PNG drew the frame outline but still said '1 entity
not drawn (OLE2FRAME: 1)'.
2026-10-31 15:14:32 +11:00
SBaksa 74ddfb377f Test: a DWG keeps an OLE2FRAME's data and frame corners (#2422)
The DWG object has no corner fields; the position travels in the start of the OLE
data, which the bridge keeps. The test builds that header with known corners and
checks them at 2000, 2010 and 2018.
2026-10-31 14:49:13 +11:00
SBaksa ada99e613d Parity checklist: regenerated after merging main 2026-10-31 14:31:00 +11:00
SBaksa 4caf26ee60 OLE2FRAME: draw its frame outline; a DWG save no longer lists it as left out (#2422)
The frame is the rectangle from the entity's two corner points (groups 10/20 and
11/21). A DWG write and read-back keeps the OLE data (ole_frame.rs), so the DWG
note leaves the type out of notSaved.
2026-10-31 14:27:48 +11:00
Davit MatchakhelidzeandClaude Opus 5.5 5f6dbede5c docs: Georgian row count after the block-editor prompt
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-31 06:00:43 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 651615e5c2 docs: Greek and Bosnian in the language lists; Georgian on the web comes with #1971
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-31 05:00:18 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 66f65b763e docs: list bs beside ka in the supported interface languages
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-31 04:38:42 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 126a734b5c Merge origin/main into ka-language
Keeps Bosnian and Georgian side by side; adds the new block-editor save prompt to ka.tsv.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-31 02:52:48 +04:00
Davit Matchakhelidze 6135745a1a Merge upstream main into fonts-georgian 2026-10-31 02:44:27 +04:00
vangel76andClaude Haiku 5.5 c62c302b01 Merge upstream/main into fix/dxf-hostile-input-hardening
Resolve crates/dxf/src/lib.rs: keep upstream's blank-line-aware group-code
count (#2408) using a byte-level line split that also honours lone CR, and
keep the branch's ascii_lines reader.

Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
2026-10-30 23:35:40 +01:00
9d4b3bb091 Raster images are drawn on screen and in PNG output (#1756)
An IMAGE whose file exists was drawn as a frame with two diagonals. Now
its pixels are loaded when a drawing opens and drawn on screen and in PNG
output, with rotation, clip boundary, fade and object transparency. A file
that can't be read keeps the crossed-out frame and reports a message.

Ported from the raster commit of #1029 onto the split render and canvas
modules. New here: large images are drawn from a pyramid of levels cut
into tiles uploaded as they come into view, instead of one texture with
pixels skipped, so a large scan stays sharp zoomed in and doesn't shimmer
zoomed out.

Limits are listed in docs/gaps.md (FF10): PDF and SVG output write only
the frame, and on screen images lie under all other objects.

Co-Authored-By: Chanthawat Kiriyadee <enwuft@icloud.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 17:05:02 +01:00
ffishman 6ae7c156b8 fix(io): take the kept groups' version from the file's own HEADER
A new drawing starts with $ACADVER AC1032, and the reader applies the file's
header over it, so a file without $ACADVER left AC1032 in Foreign::version and
the bridge read its kept groups with 2018 rules. The version now comes from the
file's HEADER section, and is None when the file has no $ACADVER (the bridge
then reads the kept groups as R2000, as before). Reported by CodeRabbit on #2471.
2026-10-30 10:23:06 -03:00
ffishman cef9ee4b10 fix(dwg): read kept objects as the file's version on every save, not just the first
The bridge took the version of the kept groups from $ACADVER, but SAVEAS writes
the saved version there and the kept groups stay as they were read. After a 2018
drawing was saved as a 2004 DWG, the next save read its mental ray render
settings as 2004 (class version 2, which the ODA File Converter rejects) and a
2004 field lost its cached value. Foreign now records the $ACADVER of the file
the kept data was read from (Foreign::version), and the DWG save passes that.

The new declare_version test also moves out of the doc comment it was pasted
into. Both reported by austin62jake on #2471.
2026-10-30 09:42:40 -03:00
ffishman 1a322faa0b fix(dwg): scan the bridge header in one pass; leave out proxies of a binary DXF
header_value kept an offset for every line up to the first ENDSEC: an input
without one cost about 24 bytes per line (0.8 GB for 32 MiB of short lines,
some 25 GB at the 1 GiB input limit). It now reads (group code, value) pairs in
one pass and stops at 0/ENDSEC, so memory no longer grows with the input
(36 MB for the same 32 MiB, the input itself).

dxf_class_names doesn't read a binary DXF's CLASSES, so its proxies kept their
DXF numbers, which name other classes in the DWG. CADCraft's own bridge is always
ASCII; for a binary DXF given to the conversion functions, the proxies are now
left out, as a pre-2013 DWG leaves them, instead of naming the wrong classes.

Both reported by CodeRabbit on #2471.
2026-10-30 09:08:20 -03:00
ffishman c52dd70824 Merge upstream main into fix/dwg-render-settings-class-version
crates/dwg/src/lib.rs: main's current_layer fix-up and guarded() wrapper around the
DXF to DWG fix-ups keep this branch's convert(kept) and run proxy_classes first
inside the guard.
2026-10-30 08:54:03 -03:00
assamaralandClaude Sonnet 5.5 77e26cc1ac Merge upstream/main into fix/dxf-viewport-id-unknown
Only conflict: contributors/people.toml (both sides appended entries; kept both).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-30 08:40:02 -03:00
ffishmanandClaude Opus 5.5 bf137e2c44 fix(dwg): give proxies their own class in the DWG
A DXF proxy object or entity names its class by number: 500 plus the class's
place in the DXF's CLASSES (DXF Reference, ACAD_PROXY_OBJECT, group 91).
acadrust's DXF reader puts its default classes first and numbers the DXF's
after them, and its DWG writer keeps the proxy's DXF number, so in the DWG
the number named another class. A 2018 drawing with an MEP plugin's piping
proxies wrote them as LARGE_RADIAL_DIMENSION and SECTIONOBJECT, and the ODA
File Converter refused the whole file ("AcDbProxyObject can't be cast to
AcDbBlockTableRecord").

The DWG bridge now reads the DXF's class names in CLASSES order and gives
each proxy the number acadrust writes for its class. Before 2013 (AC1027)
acadrust writes only the classes it knows such a DWG needs, and a proxy's is
not one of them, so the proxy would name a missing class ("No ClassId") or,
by its old number, another one; such a DWG now leaves the proxies out, and
the save report lists the proxy entities as not kept only for those
versions (from 2013 the DWG keeps them).

Tests: #1812's proxy drawing saved as 2018, 2013, 2010 and 2004 DWG keeps
its proxies' classes from 2013 and leaves them out before (fails before
this change: the classes came out as MESH and SCALE); unit test for the
CLASSES order; the not-saved report counts proxy entities only before 2013.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 18:46:31 -03:00
ffishmanandClaude Opus 5.5 33019677a8 fix(dwg): read kept objects as the version they came from when saving DWG
CADCraft saves DWG through an R2000 DXF bridge, and the objects it keeps
without modelling them (render settings, fields, associative and dynamic
block data) are written into that bridge in the groups of the file they were
read from. acadrust reads several of those differently by version, so reading
them as R2000 changed them:

- mental ray render settings from a 2013+ file came out one class version too
  high; the ODA File Converter then refuses the whole DWG ("Object improperly
  read: AcDbMentalRayRenderSettings");
- RapidRT render settings from a 2013 file came out one class version too low;
- a field lost its value flags, format and cached value.

The bridge is now read as the version the kept groups came from (the
drawing's $ACADVER) when that is newer than R2000: cadcraft_dwg gains
dxf_to_dwg_kept_as, which sets $ACADVER before acadrust reads the DXF,
decoding a code page to UTF-8 first when the kept version is 2007 or later.
Drawings without $ACADVER, or from an R2000 or older file, save as before.

Tests: a synthetic DXF (render settings and a field in the named object
dictionary) saved as 2018, 2013 and 2004 DWG must hold the same objects as
acadrust's own conversion of that DXF; three of the four cases fail without
this change. Unit tests cover the $ACADVER rewrite (CRLF, code pages, binary
DXF, a $ACADVER outside the header, unknown versions).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 17:57:01 -03:00
Francesco BVandClaude Opus 5.5 7917afce5d render: explicit imports for XCLIP clipping after #2239
#2239 replaced the glob imports in blocks.rs and viewports.rs with explicit
lists; the XCLIP code relied on the globs for `Clip`, `append_clipped_keep`,
`clip` and `Pen`. Import them by name.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 11:42:25 +01:00
Francesco BVandClaude Opus 5.5 14296dc4f5 blocks: XCLIP and XCLIPFRAME, clipped references kept through DXF and DWG
XCLIP clips block and xref references to a rectangular, polygonal or
closed-polyline boundary (Invert clip, ON/OFF, Delete, generate Polyline;
Clipdepth is ignored in 2D). The boundary is Insert::clip, in block
coordinates, so it follows its reference; other references stay whole.
Clipped references are drawn, plotted and framed (XCLIPFRAME 0/1/2) cut
to the boundary, attributes included, and their extents are cut to it.
DXF and DWG read and write it as the reference's ACAD_FILTER/SPATIAL
SPATIAL_FILTER; filters the model can't hold stay foreign data. Gap F2.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-29 11:06:23 +01:00
ffishmanandClaude Opus 5.5 42503a8ecd Keep a file's own paper size and plot rotation when saving DXF/DWG
A media named wider than tall is stored two ways: AutoCAD writes a portrait size
and a quarter turn (ISO_A4_(297.00_x_210.00_MM) as 210 x 297, 73 = 1), ZWCAD the
media's own size and no turn (420 x 297, 73 = 0). Deriving the groups from the
name alone turned the AutoCAD form into the ZWCAD one. The reader now keeps
groups 44, 45 and 73 as read (PageSetup::file_paper, not serialized), and the
writer puts them back while they still describe the page setup's size and
orientation; page setups made or changed in CADCraft are derived from the media
name as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-28 18:46:19 -03:00
Davit Matchakhelidze b5f0890b95 Docs: Georgian needs the embedded craft-fonts Geor face 2026-10-29 00:58:26 +04:00
mattlafy 2a85653976 Split the DVIEW prompt-steps test under the complexity limit 2026-10-28 15:41:01 -04:00
mattlafy 12fd74a60f Use explicit imports in DVIEW 2026-10-28 15:35:20 -04:00
mattlafy e1d0a4747e Fix imports after merging upstream/main 2026-10-28 15:34:34 -04:00
mattlafy b7c62eb93d Merge remote-tracking branch 'upstream/main' into pr/dview
# Conflicts:
#	crates/doc/src/entity.rs
#	crates/engine/src/cmd/layout.rs
#	crates/engine/src/cmd/modify2.rs
#	crates/engine/src/lib.rs
#	crates/io/src/dxf_read.rs
#	crates/io/src/dxf_write.rs
#	crates/render/src/lib.rs
#	crates/ui-egui/src/canvas.rs
#	docs/gaps.md
2026-10-28 15:30:03 -04:00
Hamza 9244ffda5d Open a drawing on the view it was saved at (#1602)
A drawing opened fitted to its extents, so one whose extents are dominated by
far-off geometry opened at a view hundreds of times its content: the drawing
was sub-pixel and there was no way to zoom in. Every other reader opens on the
view the file was saved at.

The saved view is read from HEADER (`VIEWCTR`/`VIEWSIZE`) and from the first
`*ACTIVE` VPORT record, which is the newer of the two and wins -- as it already
does for snap and grid spacing. A record that leaves the centre out has no view
to give, so the header pair stands. The extents remain the fallback for a
drawing that stores no view, and that fallback now fits the width too, through
the aspect the record is written with: a drawing 100 wide and 10 tall was given
a view 11 tall, a sliver of it, and a horizontal line got 1e-6.

Writing keeps it, so a read-and-write round trip no longer loses the view.

Rebased onto main, 310 commits on: `open_drawing` and `usable_view` are in
engine/src/session/files.rs, the VPORT reading in io/src/dxf_read/tables.rs,
the HEADER pair list in io/src/dxf_write/header.rs and the VPORT writing in
io/src/dxf_write/layout.rs. The two io tests were already carried by their
hunk, so only the engine one needed placing.
2026-10-28 20:50:16 +05:00
assamaralandClaude Fable 5.1 474df8ede8 Resolve a dropped sheet by its paper-space block, not its owner group
A PAPERVIEW sheet inside a *Paper_SpaceN block whose owner group (330) is missing or unknown belongs to that block's layout, where place_blocks puts the block's other viewports; resolving it by owner sent it to the active layout and left the real one open to numbering (CodeRabbit on #2107). The reader now records the enclosing block of each dropped sheet, and a test strips the owner from the sheet of a second layout.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 10:07:24 -03:00
assamaralandClaude Fable 5.1 d6cc051d99 Keep the generated sheet of a layout whose viewports lack ids
The reader drops the PAPERVIEW sheet viewport the writer adds to a layout with no id-1 viewport. Numbering that layout's remaining viewports from 1 would then make the first of them the sheet on the next save, losing the generated sheet (CodeRabbit, ffishman on #2107). Layouts whose generated sheet was dropped are now left alone, and a write-read-write test with a single id-0 viewport covers it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-28 08:07:05 -03:00
Davit Matchakhelidze 151d30b2f2 Merge upstream main into ka-language
# Conflicts:
#	crates/ui-egui/src/menus.rs
2026-10-28 04:45:10 +04:00
Davit Matchakhelidze 8715e78650 Merge upstream main into fonts-georgian
# Conflicts:
#	crates/ui-egui/src/menus.rs
2026-10-28 04:45:05 +04:00
ffishmanandClaude Opus 5.5 589e9113bc Merge upstream main into fix/page-setup-media-orientation
LAYOUT writing moved into layout_obj (2721aa8): the groups 44/45/73 change and
plot_paper/media_is_landscape follow it in dxf_write/sections.rs. No logic change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 20:02:59 -03:00
Davit MatchakhelidzeandClaude Opus 5.5 f948acd30b i18n(ka): bring the Georgian catalog up to date
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-27 23:32:16 +04:00
Davit Matchakhelidze 6967a79c34 Merge upstream main into ka-language 2026-10-27 23:32:16 +04:00
assamaralandClaude Fable 5.1 f42ac67e2a Merge upstream main into fix/dxf-viewport-id-unknown
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 16:21:00 -03:00
Francesco BVandClaude Opus 5.5 52c1e6de98 fonts: read SHX shape fonts, big fonts and unifonts; draw linetype shapes (FF8, FF9)
SHX files referenced by text styles are found by file name through a
font map, registered bytes, an app provider, the drawing's folder and a
search path (CADCRAFT_SHXPATH); never in a CAD program's install folder.
TEXT, MTEXT, attributes, dimension text and table cells draw with the
style's font, big font and vertical flag; linetype shape elements are
drawn when their file is found. The web build registers .shx files
picked or dropped with a drawing. All test fonts are compiled in code
from shape source.

Plain MTEXT text decodes \U+XXXX escapes as the layout does, and an SHX
file whose name differs in case from the one asked for is found on
case-sensitive file systems too (the folder is looked through).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 18:10:33 +01:00
assamaralandClaude Fable 5.1 c3f4a91132 Merge upstream main into fix/dxf-viewport-id-unknown
The VIEWPORT reader moved to dxf_read/entities.rs and the read steps are
separate functions: the 69 filter goes there and the numbering runs after
place_entities. Also covers a layout where only the sheet viewport lacks an
id: with no id 1 present, the first viewport becomes the sheet.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-27 12:11:08 -03:00
ffishmanandClaude Opus 5.5 235737d45d Merge upstream main into fix/page-setup-media-orientation
main split dxf_write.rs into dxf_write/ (736a834): plot_paper, media_is_landscape
and the LAYOUT groups 44/45/73 change move to dxf_write/sections.rs. No logic
change.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-27 11:41:10 -03:00
Davit MatchakhelidzeandClaude Opus 5.5 b98c55c7fa i18n(ka): translate Font (the text editor's font field)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-27 16:09:18 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 53c7d25ee0 i18n(ka): bring the Georgian catalog up to date
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-27 15:43:32 +04:00
Davit Matchakhelidze 0dd5d5af31 Merge upstream main into ka-language
# Conflicts:
#	crates/ui-egui/src/i18n.rs
2026-10-27 15:42:59 +04:00
mattlafy 1823eeab19 fix(view): twist follows named views in viewports, undo, screen-direction crossing, clipped DVIEW preview, DCS target
- VIEW Save inside an MSPACE viewport stores the viewport's twist; VIEW Restore into an
  unlocked viewport turns the viewport to the saved twist (one undo step).
- Undo and redo keep the untiled Model view's twist record in step with the live view.
- A selection window is a crossing window when dragged leftwards on screen, also in a
  twisted view (preview and selection alike).
- DVIEW's preview inside a clipped viewport is clipped to the viewport's outline.
- DXF view centres are read relative to the view target (VIEWPORT/VPORT group 17, VIEW
  group 12), the origin of display coordinates.
2026-10-26 16:19:28 -04:00
assamaralandClaude Fable 5.1 36272cdd28 contributors: key the entry by the renamed username (assamaral)
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-26 07:28:29 -03:00
mattlafy 97761eb2bf io: view-centre helpers before the test module 2026-10-25 16:43:05 -04:00
mattlafy 8b97b4f47e Merge remote-tracking branch 'upstream/main' into pr/dview
# Conflicts:
#	crates/engine/src/sysvars.rs
#	crates/io/src/dxf_read.rs
#	crates/io/tests/pdf_layers.rs
#	crates/ui-egui/src/canvas.rs
2026-10-25 16:26:25 -04:00
mattlafyandClaude Opus 5.5 4c61c3c889 A twisted view's centre is read and written in display coordinates
VIEWPORT and VPORT group 12 and VIEW group 10 hold the view centre turned
by the view twist. The reader turns it back to the drawing point at the
middle of the view and the writer turns it again, so a twisted view far
from the origin shows its own part of the drawing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 15:48:01 -04:00
Davit MatchakhelidzeandClaude Opus 5.5 1fba38238f i18n(ka): shorter wording for labels that were cut off
Decided in the native-speaker review of the screens (all-t01).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-25 22:09:24 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 af6ff7f3a2 Merge main into ka-language
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-25 21:40:37 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 963267abe8 docs: list tr and el among the ui.language values
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-25 21:30:23 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 4cd88a3815 docs: ka joins the supported ui.language values with the language PR, not this one (CodeRabbit)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:57:06 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 9c8519da2f docs: ka among the supported ui.language values
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:57:06 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 8e84e57ac8 theme: the Georgian glyph test asks FontsView::has_glyph (egui 0.37 made its fonts field private)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:17:17 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 d11c418fe6 theme: the Georgian glyph test asks FontsView::has_glyph (egui 0.37 made its fonts field private)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-25 19:17:07 +04:00
Davit Matchakhelidze 335e50b6a7 Merge upstream main into ka-language
# Conflicts:
#	crates/ui-egui/src/i18n/tests.rs
2026-10-25 19:01:01 +04:00
Davit Matchakhelidze 90fd1329e9 Merge upstream main into fonts-georgian
# Conflicts:
#	.github/workflows/freebsd.yml
#	.github/workflows/release.yml
2026-10-25 19:00:51 +04:00
assamaralemanandClaude Fable 5.1 9431ad6ad9 contributors: add assamaraleman
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 21:22:23 -03:00
assamaralemanandClaude Fable 5.1 84ba9a8040 DXF read: number viewports in file order when every id is unknown (#1463)
ZWCAD writes every paper-space VIEWPORT with id (69) -1. The reader cast
it to u32, so no viewport was the sheet (id 1); on save paper_views()
added a second sheet viewport ahead of the real one, which DWG readers
then numbered 2: a model viewport showing the whole sheet, inflating
the layout's extents.

A non-positive 69 now reads as 0, and a layout whose viewports all have
id 0 gets them numbered in file order, the first being the sheet. A
layout mixing known ids with -1 is left as before (pinned by a test).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
2026-10-24 21:19:43 -03:00
ffishmanandClaude Opus 5.5 b52d5fbdff io: put the CLASS group 91 doc comment back on its function
plot_paper had been inserted between add_class_instance_counts and its doc
comment (review on #2028).

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 19:09:52 -03:00
vangel76andClaude Opus 5.5 4ad7ef64e7 Merge upstream/main into fix/dxf-hostile-input-hardening
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-24 20:07:08 +02:00
ffishmanandClaude Opus 5.5 e27a839fa9 Merge upstream main into fix/page-setup-media-orientation
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-24 10:09:30 -03:00
Davit MatchakhelidzeandClaude Opus 5.5 2409afe7f0 i18n(ka): translate the six strings main added (Analyze Usage, Implied Loops, units of new drawings)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-24 14:15:14 +04:00
Davit Matchakhelidze 4c2d228d89 Merge remote-tracking branch 'origin/main' into ka-language
# Conflicts:
#	docs/localization-parity.md
2026-10-24 13:58:32 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 6a5e8eda35 fonts: test the Georgian face in the face order and its glyphs in a ka and an en interface
Same tests as #1971: embedded_ui_faces yields the Geor face for ka (and for every interface,
which names the language ქართული in the picker), can_show("ka") follows the embedded face, and
with a craft-fonts that carries Geor every Mkhedruli letter renders in both families.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-24 13:16:07 +04:00
ffishmanandClaude Opus 5.5 241aad2425 docs: file-format parity status line for the page setup change
Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-23 23:35:10 -03:00
ffishmanandClaude Opus 5.5 f84e458ccf Keep a landscape media's size order and rotation when saving DXF/DWG
Page setups keep a portrait size and a landscape flag, so a layout read
with 44 = 420, 45 = 297, 73 = 0 and the media
ISO_full_bleed_A3_(420.00_x_297.00_MM) was written back as 297 x 420
with rotation 1. ZWCAD takes the media's size from its name and turns it
a quarter on top, so the sheet plotted as a shrunk portrait page (#1463).

When the media's name gives it wider than tall, write 44/45 in that
order and the rotation relative to it. Other media are written as before.

Co-Authored-By: Claude Opus 5.5 (1M context) <noreply@anthropic.com>
2026-10-23 23:18:29 -03:00
Davit MatchakhelidzeandClaude Opus 5.5 a5391d6ebb fonts: load the embedded Georgian face where can_show accepts it; parity status line
The same embedded_ui_faces lines as #1971, so a build whose craft-fonts has the Geor
face draws Georgian instead of boxes whichever PR lands first (CodeRabbit).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-24 00:12:13 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 c8c160a4b6 Merge upstream main into ka
Georgian joins the shared i18n tests #2013 introduced (locale table, look-alike codes,
font coverage for scripts egui's bundled faces lack) in place of its own copies. The
can_show gate and the language command's no-font message for ka match #1971, so this
branch alone keeps the interface in English without a Georgian face.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-23 23:47:03 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 85df54b88c i18n(ka): apply the second terminology review
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-23 13:33:34 +04:00
Davit Matchakhelidze daa9ab982d Merge remote-tracking branch 'origin/main' into ka-language 2026-10-23 12:28:33 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 096e20629e i18n(ka): apply the native speaker's terminology review
Draw = ხატვა, Bind = მიბმა, Elevation = დონე, zoom In/Out = მოახლოება/დაშორება,
Latin ViewCube compass letters, and the other decided terms; credit the review.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-23 12:28:32 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 93e4ff10c4 fonts: draw the Georgian interface with the craft-fonts Georgian face
Bump craft-fonts-ref to a71c20e3, which adds Noto Sans Georgian (`Geor`),
and build the web release with craft-fonts (`web-craft-fonts: true`).
The interface loads the embedded `Geor` face after the CJK faces in every
language (the picker names ქართული), and the web build embeds it too
(232 KB). Without it `can_show("ka")` is false: the saved choice is kept,
the interface stays English and the language command says why.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-23 04:39:13 +04:00
Davit MatchakhelidzeandClaude Opus 5.5 6c72999361 i18n: add Georgian (ka) interface language
Add a Georgian catalog (ka.tsv, 1,383 rows): the union of the existing
catalogs, four menu headings (ზომების დატანა for the Dimension menu, ზომა
for the object) and single-form counts, since a Georgian noun stays
singular after a numeral. No marked UI literal falls back to English.
Prompts read "მიუთითეთ …" for Specify and "შეიყვანეთ …" for Enter;
clickable keywords keep the spelling the engine accepts. No Mtavruli.

Register the language (Preference::Georgian, `ka`, ქართული) and add
locale, preference, count, menu-heading, live-switch, dialog and
no-Mtavruli tests. Docs, README and ATTRIBUTION list it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01YMTAbGNRxnMEzRvYnQGphF
2026-10-23 04:39:13 +04:00
mattlafy 94b6c485b4 DVIEW records a viewport twist as one undo step when cancelled 2026-10-20 00:00:47 -04:00
mattlafy 4c75916c75 Keep the saved view twist when a template opens or xrefs load after open 2026-10-19 22:40:23 -04:00
mattlafy ecd1bdc214 Merge remote-tracking branch 'upstream/main' into fix/dview
# Conflicts:
#	crates/engine/src/prompt.rs
#	docs/file-format-parity.md
#	docs/gaps.md
2026-10-19 22:19:12 -04:00
mattlafyandClaude Opus 5.5 212f6cc988 View twist: DVIEW, VIEWTWIST, per-tile, named-view and layout-viewport twist
A model space view carries a twist (radians CCW, View.twist, serde default
0). VIEWTWIST reports it read-only. Each VPORTS tile keeps its own twist
(VportTile.twist, DXF VPORT group 51 read and written; a single untiled
Model view's twist is kept as a lone *Active VPORT tile). VIEW Save stores
and Restore applies NamedView::twist. ZOOM fits in the twisted screen frame;
zooms, pans, the 3D mouse and view.set keep it; ZOOM Previous turns it back.

DVIEW starts with "Select objects or <use DVIEWBLOCK>:" (the picked objects,
or the DVIEWBLOCK sample, are the only things drawn while it runs) and
repeats the "Enter option [CAmera/TArget/Distance/POints/PAn/Zoom/
TWist/CLip/Hide/Off/Undo]:" prompt. TWist, PAn, Zoom, Off and Undo work on
2D views; the 3D options say they are not available yet (docs/gaps.md F1).

DVIEW works inside an active layout viewport: the doc Viewport gains a view
twist (DXF VIEWPORT group 51), drawn turned on screen and in plots, mapped
through MSPACE views, snaps and CHSPACE; a twist made there is one undo
step. A layout with no active viewport refuses it, as does view.set's twist.

Canvas: the model view and every VPORTS tile draw turned by their twist.
`Xf` gains `twist`: `to_screen` turns (p - centre) by it before scaling,
`to_world` is its exact inverse, `world_bounds` is the box of the four
turned rect corners. The GPU needs no shader change: `Xf::gpu_xform` builds
the callback xform for the drawing, drag, highlight, viewport and mask
layers. Pans map screen deltas back through the twist; clicks, hover, snaps,
grips and wheel zoom go through `to_world`/`to_screen`. Grid lines and axes
stay world-aligned; the selection window is drawn as the world box it
selects.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-14 10:23:53 -04:00
Leonardo Pires BatistaandCodex 0de6ec8706 fonts: read user SHX text fonts and keep Latin accents single-stroke
Co-Authored-By: Codex <noreply@openai.com>
2026-10-13 16:41:59 -03:00
vangel76andClaude Sonnet 5.5 7716430948 DXF: multi-byte East Asian code pages read from the code page unless the whole file is UTF-8 (#1025)
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 21:18:54 +02:00
vangel76andClaude Sonnet 5.5 043073808f fix(dxf): hostile-input hardening in the DXF reader and writer (#1025)
Binary reals are finite-filtered like ASCII ones; ASCII reads a UTF-8 BOM and
CR-only/mixed line ends (and the tag-count precheck counts the same lines);
text is decoded per line/string, valid UTF-8 first, else the code page, in both
readers; trailing spaces no longer hide SECTION/ENDSEC/EOF; integer groups
reject inf/NaN and clamp to their width; hex groups pad an odd digit and drop
non-hex characters in reader and writers; the ASCII writer sanitises hex and
splits it at 254 digits; write_binary wraps in-range unsigned 16/32-bit values.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-10-13 21:14:29 +02:00
264 changed files with 17462 additions and 922 deletions
+1
View File
@@ -85,3 +85,4 @@ jobs:
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 }}
+1
View File
@@ -78,3 +78,4 @@ Generated-in-code assets are original and have no file to list:
| `crates/ui-egui/src/i18n/tr.tsv` | @ogzhnklvz (AI-assisted) | Original Turkish translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; the running app reviewed by a native speaker |
| `crates/ui-egui/src/i18n/el.tsv` | @Camthalion77 with ChatGPT (AI-assisted) | Original Greek translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; independent native proofreading pending |
| `crates/ui-egui/src/i18n/vi.tsv` | @2ez4gcx with Claude Code (AI-assisted) | Original Vietnamese translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; terminology chosen with a native speaker, full proofreading pending |
| `crates/ui-egui/src/i18n/ka.tsv` | Davit Matchakhelidze (@devius), native speaker, with Claude Code | Original Georgian translations of CADCraft English strings | MIT OR Apache-2.0 (`LICENSE-MIT`, `LICENSE-APACHE`) | No proprietary localization resources copied; written from the English strings, no other catalog used as a source; terminology and doubtful strings decided by a native Georgian speaker; no font assets added (the Georgian face comes from craft-fonts) |
Generated
+48 -20
View File
@@ -729,6 +729,7 @@ name = "cadcraft-fonts"
version = "0.17.0"
dependencies = [
"cadcraft-geom",
"encoding_rs",
"harfrust 0.14.0",
"icu_segmenter",
"skrifa 0.48.0",
@@ -755,6 +756,7 @@ dependencies = [
"cadcraft-geom",
"cadcraft-render",
"craft-pdf",
"image",
"miniz_oxide 0.9.1",
"quick-xml 0.42.0",
"serde",
@@ -774,6 +776,7 @@ dependencies = [
"getrandom 0.4.3",
"log",
"serde_json",
"tiny-skia",
]
[[package]]
@@ -806,6 +809,7 @@ dependencies = [
"craft-window",
"egui",
"egui-wgpu",
"egui_extras",
"egui_kittest",
"image",
"log",
@@ -821,8 +825,10 @@ name = "cadcraft-web"
version = "0.17.0"
dependencies = [
"cadcraft-engine",
"cadcraft-fonts",
"cadcraft-io",
"cadcraft-ui-egui",
"craft-web-host",
"eframe",
"egui",
"log",
@@ -1226,6 +1232,15 @@ dependencies = [
"zip",
]
[[package]]
name = "craft-web-host"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=2e2312ddaf21bc3d85cd3395d0955c7d239306f6#2e2312ddaf21bc3d85cd3395d0955c7d239306f6"
dependencies = [
"wasm-bindgen",
"web-sys",
]
[[package]]
name = "craft-window"
version = "0.1.0"
@@ -1510,6 +1525,19 @@ dependencies = [
"winit",
]
[[package]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
dependencies = [
"ahash",
"egui",
"enum-map",
"itertools",
"log",
"profiling",
]
[[package]]
name = "egui_glow"
version = "0.37.0"
@@ -1578,6 +1606,26 @@ version = "1.1.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "66b7e2430c6dff6a955451e2cfc438f09cea1965a9d6f87f7e3b90decc014099"
[[package]]
name = "enum-map"
version = "3.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "d4532960034c15ba2f55e9eee631040ecc473c32e6c4b200828c759840f13a06"
dependencies = [
"enum-map-derive",
]
[[package]]
name = "enum-map-derive"
version = "1.0.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7127272f64b3e098f7d81f350d672081b879bff896d219c42370dc858b1af9ff"
dependencies = [
"proc-macro2",
"quote",
"syn 3.0.9",
]
[[package]]
name = "enumflags2"
version = "0.7.12"
@@ -6244,23 +6292,3 @@ dependencies = [
"syn 3.0.9",
"winnow",
]
[[patch.unused]]
name = "egui_demo_lib"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
[[patch.unused]]
name = "egui_extras"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
[[patch.unused]]
name = "egui_inspection"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
[[patch.unused]]
name = "egui_system_font_provider"
version = "0.37.0"
source = "git+https://github.com/storytold/egui.git?rev=6d518fc799681571963842f95b55a6b68431b15a#6d518fc799681571963842f95b55a6b68431b15a"
+3 -4
View File
@@ -54,7 +54,7 @@ unicode-bidi = "0.3.18"
# Line-break opportunities between Thai words for MTEXT word wrap (Thai writes no spaces between
# words): UAX #14 with ICU4X's compiled-in LSTM word model (not its dictionaries).
icu_segmenter = { version = "~2.3", default-features = false, features = ["compiled_data", "lstm"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg"] }
image = { version = "0.25", default-features = false, features = ["png", "jpeg", "bmp", "tiff"] }
encoding_rs = "0.8.35"
# XML for the SVG reader (streaming parser, no entity expansion beyond the five predefined ones)
quick-xml = "0.42"
@@ -63,6 +63,8 @@ quick-xml = "0.42"
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["serde"] }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "92d392cff132eaf53e13afff77f38b5c11b73aa0", features = ["egui"] }
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
egui_kittest = "0.37"
eframe = { version = "0.37", default-features = false }
egui-wgpu = "0.37"
@@ -116,8 +118,5 @@ egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "6d518fc79968
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "6d518fc799681571963842f95b55a6b68431b15a" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
+1 -1
View File
@@ -118,7 +118,7 @@ numbers):
| Layouts & plotting | Paper-space layouts, viewports (scale, lock, per-viewport layer freeze), MSPACE/PSPACE through viewports, page setups, PLOT and EXPORTPDF |
| Parametric | Geometric and dimensional constraints, AUTOCONSTRAIN, PARAMETERS with expressions, conflict detection; constraints re-solve after every edit |
| Grips | Hot grips with Space to cycle Stretch, Move, Rotate, Scale and Mirror |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar) and Turkish (Türkçe), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Interface languages | English, Ukrainian (Українська), Brazilian Portuguese (Português (Brasil)), German (Deutsch), Spanish (Español), Czech (Čeština), Russian (Русский), French (Français), Simplified Chinese (简体中文, with an installed CJK font), Italian (Italiano), Korean (한국어, with an installed Hangul font), Swedish (Svenska), Arabic (العربية, with an installed Arabic font), Hungarian (Magyar), Turkish (Türkçe), Greek (Ελληνικά), Bosnian (Bosanski) and Georgian (ქართული), live switching and a remembered Auto/system-language choice; [details](docs/localization.md) |
| Automation | MCP server, JSON control channel, `cadcraft-cli` (info, convert, run, commands, mcp) |
## Quick start
+1
View File
@@ -45,6 +45,7 @@ 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())),
});
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())
});
+17 -5
View File
@@ -162,19 +162,31 @@ pub(crate) fn export_framed(s: &Session, out: &Path, window: Option<Bounds2>, io
/// as unknown objects, `Proxy` in `info`), or `None` when there are none.
pub(crate) fn undrawn_message(d: &cadcraft_engine::doc::Drawing, path: &str) -> Option<String> {
let mut types: std::collections::BTreeMap<&str, usize> = std::collections::BTreeMap::new();
let mut ole = 0usize;
for e in d.model.iter() {
// An OLE2FRAME's frame outline is drawn, so it isn't an undrawn entity; its content is
// not, which gets a note of its own.
if let cadcraft_engine::doc::EntityKind::Unknown(u) = &e.kind {
if u.is_ole_frame() && cadcraft_engine::doc::ole_frame(&u.tags).is_some() {
ole = ole.saturating_add(1);
continue;
}
let n = types.entry(u.dxf_type.as_str()).or_insert(0);
*n = n.saturating_add(1);
}
}
let n = types.values().fold(0usize, |a, n| a.saturating_add(*n));
if n == 0 {
return None;
let mut lines = Vec::new();
if n > 0 {
let list: Vec<String> = types.iter().map(|(t, n)| format!("{t}: {n}")).collect();
let entities = if n == 1 { "entity" } else { "entities" };
lines.push(format!("{path}: {n} {entities} not drawn ({})", list.join(", ")));
}
let list: Vec<String> = types.iter().map(|(t, n)| format!("{t}: {n}")).collect();
let entities = if n == 1 { "entity" } else { "entities" };
Some(format!("{path}: {n} {entities} not drawn ({})", list.join(", ")))
if ole > 0 {
let objects = if ole == 1 { "object" } else { "objects" };
lines.push(format!("{path}: {ole} OLE {objects} shown as the frame only (the OLE content is not drawn)"));
}
if lines.is_empty() { None } else { Some(lines.join("\n")) }
}
/// The reader's notes on what it left out of `path` (a damaged DWG's unreadable object records,
+7
View File
@@ -16,6 +16,13 @@ fn a_real_worker_reads_and_writes_and_its_death_is_an_error_here() {
let read = cadcraft_io::read(&written, "a.dwg").unwrap();
assert_eq!(read.model.len(), drawing.model.len());
// A drawing whose kept objects came from a 2018 file: the worker gets that version with the
// request and reads the bridge DXF as it, as this process does.
let mut kept = drawing.clone();
kept.foreign = std::sync::Arc::new(cadcraft_engine::doc::foreign::Foreign { version: Some("AC1032".into()), ..Default::default() });
let written = cadcraft_io::write(&kept, "a.dwg").unwrap();
assert_eq!(cadcraft_io::read(&written, "a.dwg").unwrap().model.len(), drawing.model.len());
// A decode error comes back as that error, not as the worker stopping.
let mut bad = in_process.clone();
bad.truncate(64);
+54 -3
View File
@@ -7,6 +7,25 @@ fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A fresh scratch directory that is removed on drop, also when an assertion fails.
struct Scratch(std::path::PathBuf);
impl Scratch {
fn new(tag: &str) -> Self {
let dir = std::env::temp_dir().join(format!("cc-cli-{tag}-{}", std::process::id()));
// A directory left behind by an earlier run with the same process id must not leak in.
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir(&dir).expect("create scratch dir");
Scratch(dir)
}
}
impl Drop for Scratch {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// A line, two foreign REGIONs and a PDF underlay: the last three are kept as unknown entities.
const PROXIES: &str = "0\nSECTION\n2\nENTITIES\n\
0\nLINE\n8\n0\n10\n0\n20\n0\n11\n5\n21\n5\n\
@@ -17,8 +36,8 @@ const PROXIES: &str = "0\nSECTION\n2\nENTITIES\n\
#[test]
fn convert_to_an_image_warns_about_entities_it_cannot_draw() {
let dir = std::env::temp_dir().join(format!("cc-cli-undrawn-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let scratch = Scratch::new("undrawn");
let dir = scratch.0.clone();
let input = dir.join("proxies.dxf");
std::fs::write(&input, PROXIES).unwrap();
let input = input.to_str().unwrap();
@@ -49,5 +68,37 @@ fn convert_to_an_image_warns_about_entities_it_cannot_draw() {
let out = cli(&["convert", sample.to_str().unwrap(), dir.join("sample.svg").to_str().unwrap()]);
assert!(out.status.success());
assert!(!String::from_utf8_lossy(&out.stderr).contains("not drawn"), "{}", String::from_utf8_lossy(&out.stderr));
let _ = std::fs::remove_dir_all(&dir);
}
/// An OLE2FRAME's frame outline is drawn, so an image export doesn't call it an undrawn entity (#2422); it
/// says once that the OLE content inside the frame is not drawn (review on #2587).
#[test]
fn an_ole_frame_is_noted_as_frame_only() {
let scratch = Scratch::new("ole");
let dir = scratch.0.clone();
let input = dir.join("ole.dxf");
let ole = "0\nSECTION\n2\nENTITIES\n0\nOLE2FRAME\n8\n0\n100\nAcDbOle2Frame\n10\n0\n20\n0\n30\n0\n11\n5\n21\n-3\n31\n0\n0\nENDSEC\n0\nEOF\n";
std::fs::write(&input, ole).unwrap();
let out = cli(&["convert", input.to_str().unwrap(), dir.join("out.png").to_str().unwrap()]);
assert!(out.status.success());
let err = String::from_utf8_lossy(&out.stderr);
assert!(!err.contains("entity not drawn") && !err.contains("entities not drawn"), "{err}");
let notes: Vec<&str> = err.lines().filter(|l| l.contains("OLE")).collect();
assert_eq!(notes, [format!("{}: 1 OLE object shown as the frame only (the OLE content is not drawn)", input.display())], "{err}");
}
/// An OLE2FRAME without usable corners (here group 11/21 missing) has no outline to draw, so it is
/// an undrawn entity, not "shown as the frame only" (review on #2587).
#[test]
fn an_ole_frame_without_corners_is_counted_as_not_drawn() {
let scratch = Scratch::new("ole-nocorner");
let dir = scratch.0.clone();
let input = dir.join("ole.dxf");
let ole = "0\nSECTION\n2\nENTITIES\n0\nOLE2FRAME\n8\n0\n100\nAcDbOle2Frame\n10\n0\n20\n0\n30\n0\n0\nENDSEC\n0\nEOF\n";
std::fs::write(&input, ole).unwrap();
let out = cli(&["convert", input.to_str().unwrap(), dir.join("out.png").to_str().unwrap()]);
assert!(out.status.success());
let err = String::from_utf8_lossy(&out.stderr);
assert!(err.contains(&format!("{}: 1 entity not drawn (OLE2FRAME: 1)", input.display())), "{err}");
assert!(!err.contains("frame only"), "{err}");
}
+4 -1
View File
@@ -18,6 +18,9 @@ path = "src/main.rs"
cadcraft-engine = { workspace = true }
cadcraft-ui-egui = { workspace = true }
cadcraft-io = { workspace = true }
cadcraft-fonts = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "2e2312ddaf21bc3d85cd3395d0955c7d239306f6", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
@@ -30,4 +33,4 @@ web-sys = { version = "0.3", features = ["HtmlInputElement", "FileList", "File"]
eframe = { workspace = true, features = ["persistence", "wgpu", "accesskit"] }
wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url", "MessageEvent", "UrlSearchParams", "MediaQueryList"] }
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url", "MessageEvent", "UrlSearchParams", "MediaQueryList", "Event", "EventTarget", "CustomEvent", "CustomEventInit"] }
+62 -102
View File
@@ -1,28 +1,37 @@
//! The `postMessage` bridge to a same-origin parent page (`?host=parent`), for pages that embed
//! CADCraft in an `<iframe>` (such as a Nextcloud app). Messages are plain objects with a `type`:
//! Host modes: a page that runs CADCraft opens drawings in it and stores what it saves instead
//! of the browser downloading. The messages and the two transports are `craft-web-host`'s
//! (storytold/craft-libs), the same contract as the other Craft apps' bridges, with the
//! `cadcraft:` prefix. This module is CADCraft's part of it.
//!
//! - `cadcraft:ready` (to the parent): `{ version }`, the app is listening; send a drawing now.
//! - `cadcraft:open` (from the parent): `{ name, bytes }`, bytes an `ArrayBuffer` or
//! `Uint8Array`. It opens like a file picked with File › Open or dropped on the window.
//! - `cadcraft:save` (to the parent): `{ name, bytes }` (a transferred `ArrayBuffer`) for every
//! file CADCraft would otherwise download (SAVE, SAVEAS, exports): it replaces the engine's
//! delivery hook. The parent stores the file and reports failures itself.
//! - `cadcraft:dirty` (to the parent): `{ dirty }` whenever unsaved changes appear or go away.
//! - `cadcraft:failed` (to the parent): `{ error }` when the app couldn't start.
//! - `?host=parent` (an `<iframe>`, such as a Nextcloud app) talks to the same-origin parent over
//! `postMessage`; `data-host="page"` on the canvas (the page's own document, no iframe) uses
//! DOM `CustomEvent`s on the canvas instead. `?host=parent` wins when both are present. With no
//! parent, or a parent on another origin, there is no bridge: the normal app with downloads.
//! - `cadcraft:ready` once the app is listening; send a drawing now. CADCraft reads bytes, so it
//! says `file: false` and a host sends `bytes`.
//! - `cadcraft:open` (from the host): `{ name, bytes }`. It opens like a file picked with
//! File › Open or dropped on the window; an oversized drawing is refused before it is copied.
//! - `cadcraft:save` (to the host): `{ name, saveAs, bytes }` for every file CADCraft would
//! otherwise download (SAVE, SAVEAS, exports): it replaces the engine's delivery hook. The host
//! stores the file and reports failures itself. CADCraft doesn't tell the host which saves
//! make a file the document, so `saveAs` is always `false`.
//! - `cadcraft:dirty` whenever unsaved changes appear or go away, `cadcraft:failed` when the app
//! couldn't start.
//!
//! Only the parent window on the page's own origin is heard or answered. In host mode the app
//! starts on the Start tab rather than an empty Drawing1, and the parent guards leaving the page.
//! In both host modes the app starts on the Start tab rather than an empty Drawing1, and the
//! host guards leaving the page.
use std::cell::{Cell, RefCell};
use std::cell::RefCell;
use std::rc::Rc;
use cadcraft_ui_egui::CadApp;
use wasm_bindgen::JsCast as _;
use wasm_bindgen::JsValue;
use wasm_bindgen::closure::Closure;
use web_sys::js_sys;
use craft_web_host::web::{FileData, Host, Message};
/// Longest file name taken from the parent page.
const MAX_NAME_CHARS: usize = 255;
/// The app id in the host messages (`cadcraft:ready`).
const APP: &str = "cadcraft";
/// The name a drawing gets when the host sent none (the crate says `document` for a blank name).
const DEFAULT_NAME: &str = "Drawing.dxf";
thread_local! {
/// The bridge [`deliver`] posts through (the engine's hook is a plain `fn`).
@@ -31,25 +40,15 @@ thread_local! {
#[derive(Clone)]
pub struct Bridge {
window: web_sys::Window,
parent: web_sys::Window,
origin: String,
host: Rc<Host>,
}
/// The unsaved-changes state last reported to the parent.
#[derive(Default)]
pub struct DirtyReport(Cell<Option<bool>>);
impl Bridge {
/// `None` when the page isn't framed (there is no parent to talk to).
pub fn new() -> Option<Self> {
let window = web_sys::window()?;
let parent = window.parent().ok().flatten()?;
if js_sys::Object::is(&parent, &window) {
return None;
}
let origin = window.location().origin().ok()?;
Some(Self { window, parent, origin })
/// The bridge for this page, or `None` when CADCraft isn't hosted: no `?host=parent` and no
/// `data-host="page"` on the canvas, an unframed `?host=parent` page (it stays the normal app
/// with downloads), or a parent on another origin.
pub fn connect(canvas: &web_sys::HtmlCanvasElement) -> Option<Self> {
Some(Self { host: Rc::new(Host::connect(APP, canvas)?) })
}
/// Make this the bridge [`deliver`] uses.
@@ -58,94 +57,55 @@ impl Bridge {
}
pub fn post_ready(&self) {
self.send(&[("type", "cadcraft:ready".into()), ("version", env!("CARGO_PKG_VERSION").into())]);
let _ = self.host.post_ready(env!("CARGO_PKG_VERSION"), false);
}
pub fn post_failed(&self, error: &str) {
self.send(&[("type", "cadcraft:failed".into()), ("error", error.into())]);
let _ = self.host.post_failed(error, None);
}
/// Hear drawings from the parent; they arrive through the upload inbox.
/// Hear drawings from the host; they arrive through the upload inbox.
pub fn listen(&self, inbox: crate::upload::Inbox) {
let parent = self.parent.clone();
let origin = self.origin.clone();
let on_message = Closure::<dyn FnMut(web_sys::MessageEvent)>::new(move |event: web_sys::MessageEvent| {
if event.origin() != origin || !event.source().is_some_and(|s| js_sys::Object::is(&s, &parent)) {
return;
self.host.listen(move |message| {
if let Message::Open { name, data } = message {
receive_open(&name, &data, &inbox);
}
let data = event.data();
if string(&data, "type").as_deref() != Some("cadcraft:open") {
return;
}
let name = string(&data, "name")
.filter(|n| !n.trim().is_empty())
.map(|n| n.chars().take(MAX_NAME_CHARS).collect())
.unwrap_or_else(|| "Drawing.dxf".to_string());
// Refuse an oversized drawing before copying it into the app's memory.
let Some(array) = byte_array(&data) else { return };
if let Some(e) = CadApp::open_size_error(&name, u64::from(array.length())) {
inbox.refuse(e);
return;
}
inbox.receive(name, array.to_vec());
});
if self.window.add_event_listener_with_callback("message", on_message.as_ref().unchecked_ref()).is_ok() {
// The listener lives as long as the page.
on_message.forget();
}
}
/// After each logic callback (including a hidden tab's): tell the parent when unsaved changes
/// appear or go away. `DirtyReport` suppresses duplicates, so this is idempotent.
pub fn report_dirty(&self, app: &CadApp, reported: &DirtyReport) {
let dirty = app.session.docs.iter().any(|d| d.is_dirty());
if reported.0.get() != Some(dirty) && self.send(&[("type", "cadcraft:dirty".into()), ("dirty", dirty.into())]) {
reported.0.set(Some(dirty));
}
/// After each logic callback (including a hidden tab's): tell the host when unsaved changes
/// appear or go away. The crate does not repeat a state it already reported, so this is
/// idempotent.
pub fn report_dirty(&self, app: &CadApp) {
self.host.post_dirty(app.session.docs.iter().any(|d| d.is_dirty()));
}
fn post_save(&self, name: &str, bytes: &[u8]) -> Result<(), String> {
let buffer = js_sys::Uint8Array::from(bytes).buffer();
let message = message(&[("type", "cadcraft:save".into()), ("name", name.into()), ("bytes", buffer.clone().into())])
.ok_or_else(|| "couldn't build the message".to_string())?;
self.parent
.post_message_with_transfer(&message, &self.origin, &js_sys::Array::of1(&buffer))
.map_err(|e| e.as_string().unwrap_or_else(|| format!("{e:?}")))
}
/// Post a message to the parent; false if it couldn't be sent.
fn send(&self, fields: &[(&str, JsValue)]) -> bool {
message(fields).is_some_and(|m| self.parent.post_message(&m, &self.origin).is_ok())
self.host.post_save(name, bytes, None, false)
}
}
/// The engine's delivery hook in host mode ([`cadcraft_engine::cmd::file::set_deliver`]): hand
/// the file to the parent page. `Ok` once it was posted; the engine then counts a drawing as saved.
/// the file to the host page. `Ok` once it was sent; the engine then counts a drawing as saved.
pub fn deliver(name: &str, _mime: &str, bytes: &[u8]) -> Result<(), String> {
let bridge = BRIDGE.with(|b| b.borrow().clone()).ok_or("the page that embeds CADCraft is gone")?;
bridge.post_save(name, bytes)
}
fn message(fields: &[(&str, JsValue)]) -> Option<js_sys::Object> {
let m = js_sys::Object::new();
for (key, value) in fields {
js_sys::Reflect::set(&m, &JsValue::from_str(key), value).ok()?;
}
Some(m)
}
fn string(data: &JsValue, key: &str) -> Option<String> {
js_sys::Reflect::get(data, &JsValue::from_str(key)).ok()?.as_string()
}
/// `bytes` (an `ArrayBuffer` or `Uint8Array`) as a view, not yet copied.
fn byte_array(data: &JsValue) -> Option<js_sys::Uint8Array> {
let bytes = js_sys::Reflect::get(data, &JsValue::from_str("bytes")).ok()?;
if let Some(array) = bytes.dyn_ref::<js_sys::Uint8Array>() {
Some(array.clone())
} else if bytes.is_instance_of::<js_sys::ArrayBuffer>() {
Some(js_sys::Uint8Array::new(&bytes))
} else {
None
/// The `cadcraft:open` payload, `{ name, bytes }` where `bytes` holds a drawing: it opens like a
/// file picked with File › Open or dropped on the window. The crate has cleaned the name (and cut
/// it to 255 characters); a blank one comes as `document` and becomes `Drawing.dxf`. An oversized
/// drawing is refused before it is copied.
fn receive_open(name: &str, data: &FileData, inbox: &crate::upload::Inbox) {
let name = if name == "document" { DEFAULT_NAME } else { name }.to_string();
let FileData::Bytes(array) = data else {
inbox.refuse(format!("Open: {name} came as a File; CADCraft reads bytes"));
return;
};
// Refuse an oversized drawing before copying it into the app's memory (the data's own length).
if let Some(e) = CadApp::open_size_error(&name, data.size() as u64) {
inbox.refuse(e);
return;
}
inbox.receive(name, array.to_vec());
}
+25 -24
View File
@@ -6,7 +6,8 @@
//! with egui shapes instead of the GPU canvas, `?sample` opens the sample drawing. Saving downloads
//! the drawing through the browser (`download.rs`). With `?host=parent` (inside an `<iframe>`), a
//! same-origin parent page sends the drawing to open and stores what CADCraft saves instead
//! (`host.rs`).
//! (`host.rs`); a page can also host CADCraft in its own document (no iframe) with
//! `data-host="page"` on the canvas, talking over DOM `CustomEvent`s on it (`host.rs`).
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#[cfg(target_arch = "wasm32")]
@@ -27,16 +28,11 @@ mod web {
const LOADING_ID: &str = "cadcraft_loading";
/// The app, the files File > Open… and drag and drop read for it in the background, the
/// page embedding it (`?host=parent`), the browser's `prefers-reduced-motion` (it stays
/// host page (`?host=parent`, or `data-host="page"` on the canvas), the browser's
/// `prefers-reduced-motion` (it stays
/// live, so View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting follows a change),
/// and the document title last written to the page.
struct Shell(
CadApp,
crate::upload::Inbox,
Option<(crate::host::Bridge, crate::host::DirtyReport)>,
Option<web_sys::MediaQueryList>,
Option<String>,
);
struct Shell(CadApp, crate::upload::Inbox, Option<crate::host::Bridge>, Option<web_sys::MediaQueryList>, Option<String>);
impl eframe::App for Shell {
/// Runs one frame: takes in files dropped on or picked for the page, drains the background
@@ -51,10 +47,10 @@ mod web {
self.0.logic(ctx);
let drawing = self.0.session.state().ok();
crate::push_title(&mut self.4, drawing.map(|d| d.title.as_str()), drawing.is_some_and(|d| d.is_dirty()), set_page_title);
// `DirtyReport` suppresses duplicates, so reporting after every logic callback
// The crate suppresses duplicates, so reporting after every logic callback
// (including a hidden tab's) is idempotent and keeps the parent's guard current.
if let Some((bridge, reported)) = &self.2 {
bridge.report_dirty(&self.0, reported);
if let Some(bridge) = &self.2 {
bridge.report_dirty(&self.0);
}
}
/// Forward raw input to the web `CadApp` and capture Tab at the command line.
@@ -100,8 +96,10 @@ mod web {
web_sys::window().and_then(|w| w.location().search().ok()).unwrap_or_default()
}
fn query_param(key: &str) -> Option<String> {
web_sys::UrlSearchParams::new_with_str(&query()).ok()?.get(key)
/// The app's canvas: the one element `index.html` and every embedding page must provide,
/// with the id the app looks up.
fn app_canvas() -> Option<web_sys::HtmlCanvasElement> {
web_sys::window()?.document()?.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok())
}
/// No file picker on the web: Save / Save As from the menu (and the close prompt) download the
@@ -119,6 +117,7 @@ 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())),
});
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())
});
@@ -127,10 +126,17 @@ mod web {
groups: cadcraft_io::entity_groups,
entity: cadcraft_io::entity_from_groups,
});
let Some(canvas) = app_canvas() else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
};
// `?host=parent`: a same-origin page framing CADCraft (such as a Nextcloud app) opens
// drawings in it and stores what it saves. Otherwise there is no file system here: saved
// files reach the user as browser downloads.
let bridge = if query_param("host").as_deref() == Some("parent") { crate::host::Bridge::new() } else { None };
// drawings in it and stores what it saves. Otherwise `data-host="page"` on the canvas
// opts in a page that runs CADCraft in its own document (no iframe) and talks over DOM
// `CustomEvent`s on the canvas (`host`). With neither, there is no file system here:
// saved files reach the user as browser downloads; an unframed `?host=parent` stays
// that normal app.
let bridge = crate::host::Bridge::connect(&canvas);
match &bridge {
Some(bridge) => {
bridge.install();
@@ -141,10 +147,6 @@ mod web {
let app_bridge = bridge.clone();
wasm_bindgen_futures::spawn_local(async move {
let Some(document) = web_sys::window().and_then(|w| w.document()) else { return };
let Some(canvas) = document.get_element_by_id(CANVAS_ID).and_then(|e| e.dyn_into::<web_sys::HtmlCanvasElement>().ok()) else {
log::error!("missing <canvas id=\"{CANVAS_ID}\">");
return;
};
let mut options = eframe::WebOptions::default();
if query().contains("webgl")
&& let eframe::egui_wgpu::WgpuSetup::CreateNew(create) = &mut options.wgpu_options.wgpu_setup
@@ -156,7 +158,7 @@ mod web {
canvas,
options,
Box::new(move |cc| {
// Embedded, the parent sends the drawing: start on the Start tab, not Drawing1.
// Embedded, the host sends the drawing: start on the Start tab, not Drawing1.
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
let mut app = CadApp::new(session, services());
app.system_languages =
@@ -191,10 +193,9 @@ mod web {
picker.pick();
None
}));
let host = app_bridge.map(|bridge| {
let host = app_bridge.inspect(|bridge| {
bridge.listen(inbox.clone());
bridge.post_ready();
(bridge, crate::host::DirtyReport::default())
});
let reduced_motion = web_sys::window().and_then(|w| w.match_media("(prefers-reduced-motion: reduce)").ok().flatten());
Ok(Box::new(Shell(app, inbox, host, reduced_motion, None)))
+54 -8
View File
@@ -2,6 +2,11 @@
//! a path from, so the picker is a hidden `<input type="file">`; the chosen file (or one dropped on
//! the page) is read in the background and handed to the app on its next frame, which opens it
//! with OPEN `{data, name}` ([`CadApp::open_bytes`]).
//!
//! SHX fonts (text fonts, big fonts, shape files) chosen or dropped with a drawing are the web
//! build's font folder: they are registered with the font table
//! ([`cadcraft_fonts::shx::register`]) under their file name, so the styles and linetypes that
//! name them draw with them, and the drawings are regenerated.
use std::cell::Cell;
use std::rc::Rc;
@@ -12,8 +17,14 @@ use web_sys::js_sys;
/// The hidden file input (one at a time; a cancelled pick leaves it until the next one).
const INPUT_ID: &str = "cadcraft_open_input";
/// What the picker offers: the formats OPEN reads.
const ACCEPT: &str = ".dxf,.dwg";
/// What the picker offers: the formats OPEN reads, and the SHX fonts drawings name.
const ACCEPT: &str = ".dxf,.dwg,.shx";
/// Most files taken from one pick.
const MAX_PICKED: u32 = 64;
/// Most bytes being read at once, all files together: a large pick must not exhaust the page's
/// memory (each file is copied once more into the app).
const MAX_READING_BYTES: u64 = 512 << 20;
/// A file read in the browser (name, contents), or why it couldn't be read.
type Upload = Result<(String, Vec<u8>), String>;
@@ -22,12 +33,14 @@ type Upload = Result<(String, Vec<u8>), String>;
#[derive(Clone)]
pub struct Inbox {
files: Rc<Cell<Vec<Upload>>>,
/// Bytes of the files being read now.
reading: Rc<Cell<u64>>,
ctx: egui::Context,
}
impl Inbox {
pub fn new(ctx: &egui::Context) -> Self {
Inbox { files: Rc::default(), ctx: ctx.clone() }
Inbox { files: Rc::default(), reading: Rc::default(), ctx: ctx.clone() }
}
/// Show the browser's file picker and return at once. A chosen file arrives through
@@ -51,13 +64,23 @@ impl Inbox {
.map_err(|_| "could not create a file input".to_string())?;
input.set_type("file");
input.set_accept(ACCEPT);
// A drawing and the fonts it uses can be chosen together.
input.set_multiple(true);
input.set_id(INPUT_ID);
input.set_attribute("style", "display:none").map_err(js_error)?;
let (inbox, chosen) = (self.clone(), input.clone());
// Called once, when a file was chosen (browsers don't fire `change` on cancel).
// Called once, when files were chosen (browsers don't fire `change` on cancel).
let on_change = wasm_bindgen::closure::Closure::once_into_js(move || {
if let Some(file) = chosen.files().and_then(|f| f.get(0)) {
inbox.read(file);
if let Some(files) = chosen.files() {
for i in 0..files.length().min(MAX_PICKED) {
if let Some(file) = files.get(i) {
inbox.read(file);
}
}
let skipped: Vec<String> = (MAX_PICKED..files.length()).filter_map(|i| files.get(i)).map(|f| f.name()).collect();
if !skipped.is_empty() {
inbox.push(Err(format!("Open: at most {MAX_PICKED} files at a time; not opened: {}", skipped.join(", "))));
}
}
chosen.remove();
});
@@ -87,12 +110,18 @@ impl Inbox {
if let Some(e) = CadApp::open_size_error(&name, len) {
return self.push(Err(e));
}
let reading = self.reading.get();
if reading.saturating_add(len) > MAX_READING_BYTES {
return self.push(Err(format!("Open: {name} was not read: the files being read together are too large; open it on its own")));
}
self.reading.set(reading.saturating_add(len));
let inbox = self.clone();
wasm_bindgen_futures::spawn_local(async move {
let r = match wasm_bindgen_futures::JsFuture::from(file.array_buffer()).await {
Ok(buf) => Ok((name, js_sys::Uint8Array::new(&buf).to_vec())),
Err(e) => Err(format!("Open: could not read {name}: {}", js_error(e))),
};
inbox.reading.set(inbox.reading.get().saturating_sub(len));
inbox.push(r);
});
}
@@ -118,9 +147,21 @@ impl Inbox {
self.ctx.request_repaint();
}
/// Open what arrived since the last frame (or report why it couldn't be read).
/// Open what arrived since the last frame (or report why it couldn't be read). Fonts are
/// registered first, so drawings opened with them draw with them.
pub fn drain(&self, app: &mut CadApp) {
for upload in self.files.take() {
let (fonts, files): (Vec<Upload>, Vec<Upload>) = self.files.take().into_iter().partition(|u| u.as_ref().is_ok_and(|(n, _)| is_shx(n)));
let mut registered = false;
for (name, bytes) in fonts.into_iter().flatten() {
match cadcraft_fonts::shx::register(&name, &bytes) {
Ok(()) => registered = true,
Err(e) => app.open_failed(format!("{name}: {e}")),
}
}
if registered {
let _ = app.run("regenall", serde_json::json!({}));
}
for upload in files {
match upload {
Ok((name, bytes)) => app.open_bytes(&name, &bytes),
Err(e) => app.open_failed(e),
@@ -129,6 +170,11 @@ impl Inbox {
}
}
/// Whether `name` is an SHX font or shape file.
fn is_shx(name: &str) -> bool {
name.to_ascii_lowercase().ends_with(".shx")
}
fn js_error(e: wasm_bindgen::JsValue) -> String {
e.as_string().unwrap_or_else(|| format!("{e:?}"))
}
+1
View File
@@ -146,6 +146,7 @@ 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())),
});
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())
});
+7
View File
@@ -88,6 +88,10 @@ sync_github_name = false
real_name = "Robert Lee"
sync_github_name = true
[people.assamaral]
real_name = "assamaral"
sync_github_name = false
[people.2ez4gcx]
real_name = "Doan Huynh Huu Khuong"
display_name = "Doan Huynh Huu Khuong"
@@ -109,3 +113,6 @@ real_name = "Andrea Brandi"
[people.qinshah]
sync_github_name = true
[people.helenkwok]
real_name = "Helen Kwok"
+1
View File
@@ -800,6 +800,7 @@ mod budget_tests {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}
}
+2
View File
@@ -302,6 +302,7 @@ fn block_reference_moves_rigidly() {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}),
);
assert_eq!(obj_dof(&d, ins), Some(3));
@@ -343,6 +344,7 @@ fn hostile_new_geometry_never_panics() {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}),
);
let l = line(&mut d, (0.0, 0.0), (0.0, 0.0));
+1
View File
@@ -228,6 +228,7 @@ impl ArrayParams {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
out.push(Entity { handle: d.new_handle(), common: common.clone(), kind: EntityKind::Insert(ins) });
}
+8
View File
@@ -60,6 +60,13 @@ pub struct Unknown {
pub tags: Vec<RawTag>,
}
impl Unknown {
/// Whether this is an OLE2FRAME (the type name is matched without regard to case).
pub fn is_ole_frame(&self) -> bool {
self.dxf_type.eq_ignore_ascii_case("OLE2FRAME")
}
}
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(tag = "type", rename_all = "camelCase")]
pub enum EntityKind {
@@ -469,6 +476,7 @@ impl EntityKind {
let a = if mirror { t.rotation() } else { t.rotation() + rot };
t.dir = Vec2::from_angle(cadcraft_geom::norm_angle(a)).to3(0.0);
}
EntityKind::Unknown(u) if u.is_ole_frame() => crate::ole_frame_transform(&mut u.tags, m),
EntityKind::Unknown(_) => {}
}
}
+19
View File
@@ -161,6 +161,25 @@ pub struct Insert {
pub col_spacing: f64,
#[serde(default)]
pub row_spacing: f64,
/// XCLIP boundary of this reference (other references to the block are not clipped).
#[serde(default, skip_serializing_if = "Option::is_none")]
pub clip: Option<crate::ClipBoundary>,
}
impl Default for Insert {
fn default() -> Self {
Insert {
block: String::new(),
insert: Vec3::ZERO,
scale: unit_scale(),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}
}
}
fn unit_scale() -> Vec3 {
+39 -2
View File
@@ -1,3 +1,5 @@
use cadcraft_geom::Mat3;
use super::common::Handle;
use super::{Color, Deserialize, Serialize, Vec2, Vec3, standard, yes};
@@ -25,6 +27,39 @@ pub struct Viewport {
/// Display on (MVIEW ON/OFF). An off viewport shows its border but no model space.
#[serde(default = "yes")]
pub on: bool,
/// The view twist (DVIEW TWist inside the viewport; DXF group 51): radians counterclockwise,
/// the model view seen through the viewport is turned on the sheet by it. 0 is untwisted.
#[serde(default, skip_serializing_if = "is_zero_twist")]
pub twist: f64,
}
fn is_zero_twist(v: &f64) -> bool {
*v == 0.0
}
impl Viewport {
/// The view twist, usable: 0 when it isn't finite.
pub fn view_twist(&self) -> f64 {
if self.twist.is_finite() { self.twist } else { 0.0 }
}
/// Paper units per model unit.
pub fn scale(&self) -> f64 {
self.height / self.view_height
}
/// Where model point `m` is on the sheet: `center + scale · R(twist)(m − view_center)`.
pub fn model_to_paper(&self, m: Vec2) -> Vec2 {
self.center.xy() + (m - self.view_center).rotate(self.view_twist()) * self.scale()
}
/// The model point at sheet point `p` (the inverse of [`Viewport::model_to_paper`]).
pub fn paper_to_model(&self, p: Vec2) -> Vec2 {
self.view_center + ((p - self.center.xy()) / self.scale()).rotate(-self.view_twist())
}
/// [`Viewport::model_to_paper`] as a matrix.
pub fn model_to_paper_matrix(&self) -> Mat3 {
let s = self.scale();
Mat3::translate(self.center.xy())
.then_before(Mat3::scale(s, s))
.then_before(Mat3::rotate(self.view_twist()))
.then_before(Mat3::translate(-self.view_center))
}
}
impl Default for Viewport {
@@ -41,6 +76,7 @@ impl Default for Viewport {
layer_colors: Vec::new(),
clip: None,
on: true,
twist: 0.0,
}
}
}
@@ -59,8 +95,9 @@ pub struct Image {
/// The image definition's name (its key in the drawing's image dictionary).
#[serde(default, skip_serializing_if = "String::is_empty")]
pub name: String,
/// Clip boundary in pixel coordinates (origin at the top-left corner of the image, y down):
/// two opposite corners of a rectangle, or a polygon's vertices. Empty: the whole image.
/// Clip boundary in pixel coordinates (y down, counted from pixel centres: the centre of the
/// top-left pixel is the origin, so the whole image is -0.5 to size - 0.5): two opposite
/// corners of a rectangle, or a polygon's vertices. Empty: the whole image.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub clip: Vec<Vec2>,
/// The clip boundary is applied.
+605 -4
View File
@@ -9,6 +9,239 @@ use crate::{Drawing, Entity, EntityKind, LwPolyline, Prim};
/// Nested block references deeper than this are ignored (cyclic or hostile files).
pub const MAX_BLOCK_DEPTH: usize = 16;
/// Positions in `tags` of the groups outside application-defined `102 {` .. `102 }` groups, whose
/// codes are the application's own and not the entity's.
fn outside_app(tags: &[crate::RawTag]) -> impl Iterator<Item = usize> + '_ {
let mut in_app = false;
tags.iter().enumerate().filter_map(move |(i, t)| {
if t.code == 102 {
in_app = t.value.starts_with('{');
None
} else {
(!in_app).then_some(i)
}
})
}
/// The positions of the frame's corner groups 10, 20, 11, 21 (in that order) and their values:
/// the first of each outside application groups, found in one pass that stops at the last.
fn ole_corner_groups(tags: &[crate::RawTag]) -> Option<[(usize, f64); 4]> {
let mut found: [Option<(usize, f64)>; 4] = [None; 4];
for i in outside_app(tags) {
let Some(t) = tags.get(i) else { continue };
let slot = match t.code {
10 => 0,
20 => 1,
11 => 2,
21 => 3,
_ => continue,
};
if let Some(f) = found.get_mut(slot).filter(|f| f.is_none()) {
*f = Some((i, t.value.trim().parse::<f64>().ok().filter(|v| v.is_finite())?));
if found.iter().all(Option::is_some) {
break;
}
}
}
let [Some(a), Some(b), Some(c), Some(d)] = found else { return None };
Some([a, b, c, d])
}
/// The closed outline of an OLE2FRAME from its upper-left (groups 10, 20) and lower-right
/// (groups 11, 21) corners (DXF Reference, OLE2FRAME); `None` when either is missing or not finite.
pub fn ole_frame(tags: &[crate::RawTag]) -> Option<[Vec2; 5]> {
let [(_, x1), (_, y1), (_, x2), (_, y2)] = ole_corner_groups(tags)?;
let (a, b) = (Vec2::new(x1, y1), Vec2::new(x2, y2));
Some([a, Vec2::new(b.x, a.y), b, Vec2::new(a.x, b.y), a])
}
/// The bytes of the OLE data before its corners: a 2-byte marker.
const OLE_HEADER: usize = 2;
/// The corners in the OLE data: four of x, y, z as little-endian doubles (upper left, upper right,
/// lower right, lower left).
const OLE_CORNERS: usize = 12;
/// Replace the four corners at the start of the OLE data (the 310 groups' hex, in order) by `new`
/// (upper left, upper right, lower right, lower left), keeping z and every group's length and
/// letter case. Only the groups that cover the header are decoded and rewritten; the rest of the
/// payload is not touched. Data that is not valid hex, too short, or whose corners are not the old
/// `frame`'s is left alone.
fn ole_data_transform(tags: &mut [crate::RawTag], new: [Vec2; 4], frame: [f64; 4]) {
const END: usize = OLE_HEADER + OLE_CORNERS * 8;
let mut bytes: Vec<u8> = Vec::with_capacity(END);
// The groups read, and how many leading bytes of each belong to the header.
let mut spans: Vec<(usize, usize)> = Vec::new();
for i in outside_app(tags).filter(|&i| tags.get(i).is_some_and(|t| t.code == 310)) {
if bytes.len() >= END {
break;
}
let Some(t) = tags.get(i) else { return };
let s = t.value.trim();
if s.len() % 2 != 0 || !s.is_ascii() {
return;
}
let take = (s.len() / 2).min(END - bytes.len());
for k in 0..take {
// `from_str_radix` also takes a sign, so each digit is checked first.
let Some(h) = s.get(2 * k..2 * k + 2).filter(|h| h.bytes().all(|b| b.is_ascii_hexdigit())) else { return };
let Ok(b) = u8::from_str_radix(h, 16) else { return };
bytes.push(b);
}
spans.push((i, take));
}
if bytes.len() < END {
return;
}
// Only data whose corners are this frame's corners (UL, UR, LR, LL) has the layout above; any
// other header is not ours to rewrite.
let [x1, y1, x2, y2] = frame;
let want = [(x1, y1), (x2, y1), (x2, y2), (x1, y2)];
// Two corners match within a fixed tolerance for ordinary coordinates (CORNER_EPS at most), or
// within a few ulps of the coordinate where that is larger, which is from about 1.1e9 up.
let near = |a: f64, b: f64| {
let m = a.abs().max(b.abs());
(a - b).abs() <= (1e-9 * m.max(1.0)).min(CORNER_EPS).max(4.0 * f64::EPSILON * m)
};
for (c, (wx, wy)) in want.iter().enumerate() {
let at = OLE_HEADER + c * 24;
let rd = |o: usize| bytes.get(o..o + 8).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes);
let (Some(x), Some(y)) = (rd(at), rd(at + 8)) else { return };
if !(near(x, *wx) && near(y, *wy)) {
return;
}
}
for (c, p) in new.iter().enumerate() {
let at = OLE_HEADER + c * 24;
if let Some(s) = bytes.get_mut(at..at + 8) {
s.copy_from_slice(&p.x.to_le_bytes());
}
if let Some(s) = bytes.get_mut(at + 8..at + 16) {
s.copy_from_slice(&p.y.to_le_bytes());
}
}
let mut pos = 0;
for (i, n) in spans {
let (Some(t), Some(chunk)) = (tags.get_mut(i), bytes.get(pos..pos + n)) else { return };
// Leave any padding around the digits, and the digits after the header, as they were.
let start = t.value.len() - t.value.trim_start().len();
// Only the rewritten digits and a few after them, for the case of the nearest letter: a
// hostile 310 line can be as long as the file (the value is checked to be ASCII above).
let end = start.saturating_add(2 * n + 64).min(t.value.len());
let hex = recase(chunk, t.value.get(start..end).unwrap_or_default());
t.value.replace_range(start..start + 2 * n, &hex);
pos += n;
}
}
/// The hex of `chunk`, each digit in the case of the digit at the same place in `old`. A digit that
/// was a number and becomes a letter takes the case of the nearest letter in `old`, upper when there
/// is none, so bytes that did not change keep their exact text.
fn recase(chunk: &[u8], old: &str) -> String {
let old = old.as_bytes();
// For each place, whether the letter nearest to it (the one at it, else the closest before or
// after; the one before on a tie) is lower case: one pass for the next letter at or after each
// place, one for the previous, then the nearer of the two.
let mut next: Vec<Option<(usize, bool)>> = vec![None; old.len()];
let mut seen: Option<(usize, bool)> = None;
for (i, c) in old.iter().enumerate().rev() {
if c.is_ascii_alphabetic() {
seen = Some((i, c.is_ascii_lowercase()));
}
if let Some(slot) = next.get_mut(i) {
*slot = seen;
}
}
let mut lower_at = vec![false; old.len()];
let mut prev: Option<(usize, bool)> = None;
for (i, c) in old.iter().enumerate() {
if c.is_ascii_alphabetic() {
prev = Some((i, c.is_ascii_lowercase()));
}
let after = next.get(i).copied().flatten();
let lower = match (prev, after) {
(Some((p, lp)), Some((q, lq))) => {
if i - p <= q - i {
lp
} else {
lq
}
}
(Some((_, l)), None) | (None, Some((_, l))) => l,
(None, None) => false,
};
if let Some(slot) = lower_at.get_mut(i) {
*slot = lower;
}
}
let mut out = String::with_capacity(chunk.len() * 2);
for (k, b) in chunk.iter().enumerate() {
for (j, d) in [b >> 4, b & 15].into_iter().enumerate() {
let digit = char::from_digit(d.into(), 16).unwrap_or('0');
out.push(if lower_at.get(2 * k + j).copied().unwrap_or(false) { digit } else { digit.to_ascii_uppercase() });
}
}
out
}
/// The fixed part of the tolerance when matching the corners in the OLE data to the frame's. The
/// header holds the same f64 the frame groups print, so they agree to a few ulps. Up to about 1.1e9
/// a fixed tolerance of at most this decides, so that distinct geometry does not match; above that,
/// four ulps of the coordinate (`4 * EPSILON * |x|`) exceed it and decide instead.
const CORNER_EPS: f64 = 1e-6;
/// Transform an OLE2FRAME by `m`: its two corners are mapped through `m` (a DWG save writes the
/// frame's position from these groups), and so are the corners at the start of its OLE data (310
/// groups), which a reader of the saved file may trust instead. The frame stays axis aligned with
/// its upper-left corner first. A matrix that keeps the axes or swaps them (a move, scale, mirror or
/// quarter turn) gives the box of the two mapped corners. Any other turn would collapse that box
/// (a square turned 45° maps its two corners level), so the frame's centre is mapped and its size
/// kept, scaled by `m`'s, its sides swapped when the turn is nearer a quarter turn. Commands refuse
/// a rotation or mirror (see [`ole_frame_accepts`]), but internal callers such as EXPLODE, REFEDIT
/// and paste still apply them, and must leave a consistent frame. A frame with no usable corners is
/// left alone.
pub fn ole_frame_transform(tags: &mut [crate::RawTag], m: &cadcraft_geom::Mat3) {
let Some([(ix1, x1), (iy1, y1), (ix2, x2), (iy2, y2)]) = ole_corner_groups(tags) else { return };
let frame = [x1, y1, x2, y2];
let t = 1e-12 * (m.a.abs() + m.b.abs() + m.c.abs() + m.d.abs());
let axes_kept = (m.b.abs() <= t && m.c.abs() <= t) || (m.a.abs() <= t && m.d.abs() <= t);
let (a, b) = if axes_kept {
(m.apply(Vec2::new(x1, y1)), m.apply(Vec2::new(x2, y2)))
} else {
let center = m.apply(Vec2::new((x1 + x2) / 2.0, (y1 + y2) / 2.0));
// A plain turn keeps the size exactly; cos² + sin² can miss 1 by an ulp or two.
let s = (m.a * m.d - m.b * m.c).abs().sqrt();
let scale = if (s - 1.0).abs() < 1e-12 { 1.0 } else { s };
let (mut w, mut h) = ((x2 - x1).abs() * scale, (y2 - y1).abs() * scale);
// Where the frame's x axis goes: nearer to y than to x is nearer a quarter turn.
if m.b.abs() > m.a.abs() {
std::mem::swap(&mut w, &mut h);
}
(center - Vec2::new(w, h) / 2.0, center + Vec2::new(w, h) / 2.0)
};
if !(a.x.is_finite() && a.y.is_finite() && b.x.is_finite() && b.y.is_finite()) {
return;
}
let (lo, hi) = (Vec2::new(a.x.min(b.x), a.y.min(b.y)), Vec2::new(a.x.max(b.x), a.y.max(b.y)));
let (ul, lr) = (Vec2::new(lo.x, hi.y), Vec2::new(hi.x, lo.y));
for (i, v) in [(ix1, ul.x), (iy1, ul.y), (ix2, lr.x), (iy2, lr.y)] {
if let Some(t) = tags.get_mut(i) {
t.value = v.to_string();
}
}
ole_data_transform(tags, [ul, Vec2::new(lr.x, ul.y), lr, Vec2::new(ul.x, lr.y)], frame);
}
/// Whether `m` can move an OLE2FRAME: a translation (move, copy, stretch of the whole frame) or a
/// uniform scale with a positive factor, which keep the frame axis aligned and its upper-left corner
/// upper-left.
pub fn ole_frame_accepts(m: &cadcraft_geom::Mat3) -> bool {
const T: f64 = 1e-12;
// The tolerance grows with the scale: a matrix built from two angles (ALIGN) leaves rounding noise
// in b and c of about `scale * 1e-16`.
let t = T * m.a.abs();
m.b.abs() < t && m.c.abs() < t && m.a > 0.0 && (m.a - m.d).abs() <= t
}
/// Bounds of a single-line TEXT / ATTDEF / ATTRIB of `len` characters, following its justification
/// the same way the renderer places it (the stroke font is about 0.88 of the height per character).
fn text_box(t: &crate::Text, len: usize) -> Bounds2 {
@@ -179,11 +412,23 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
}
};
b = if inner.is_empty() { Bounds2::EMPTY } else { Bounds2::from_points(inner.corners().map(|c| m.apply(c))) };
// XCLIP: the reference app takes the boundary's box, also where it reaches past the
// block or misses it (an inverted clip can show anything, so it keeps the block's).
if let Some(c) = ins.clip.as_ref().filter(|c| c.active() && !c.inverted)
&& !b.is_empty()
{
b = Bounds2::from_points(c.polygon().into_iter().map(|p| m.apply(p)));
}
if ins.cols > 1 || ins.rows > 1 {
let off =
Vec2::new(ins.col_spacing * f64::from(ins.cols.saturating_sub(1)), ins.row_spacing * f64::from(ins.rows.saturating_sub(1)))
.rotate(ins.rotation);
b = b.union(&Bounds2::from_points(b.corners().map(|c| c + off)));
// The grid's four corner copies (as many as are drawn): turned, the far corner
// alone misses the side ones.
let (cols, rows) =
(f64::from(ins.cols.clamp(1, 10_000).saturating_sub(1)), f64::from(ins.rows.clamp(1, 10_000).saturating_sub(1)));
let one = b;
for (c, r) in [(cols, 0.0), (0.0, rows), (cols, rows)] {
let off = Vec2::new(ins.col_spacing * c, ins.row_spacing * r).rotate(ins.rotation);
b = b.union(&Bounds2::from_points(one.corners().map(|p| p + off)));
}
}
}
for a in &ins.attribs {
@@ -271,6 +516,8 @@ fn bounds_in<'a>(d: &'a Drawing, e: &Entity, depth: usize, blocks: &mut HashMap<
Bounds2::from_points([o, o + u, o + v, o + u + v])
}
EntityKind::LwPolyline(p) => lwpolyline_bounds(p),
// An OLE object's content is not drawn, but its frame is, so the frame counts (#2422).
EntityKind::Unknown(u) if u.is_ole_frame() => ole_frame(&u.tags).map_or(Bounds2::EMPTY, Bounds2::from_points),
kind => {
let mut b = Bounds2::EMPTY;
for p in kind.prims() {
@@ -466,6 +713,41 @@ mod tests {
assert!(bounds(EntityKind::MLeader(empty)).max.x < 26.0);
}
/// An OLE2FRAME counts in the extents through its corner tags (#2422); a missing or
/// non-finite corner counts as nothing.
#[test]
fn ole_frame_counts_in_extents() {
let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() };
let frame = |tags: Vec<crate::RawTag>| EntityKind::Unknown(crate::Unknown { dxf_type: "OLE2FRAME".into(), tags });
let b = bounds(frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")]));
assert_eq!((b.min, b.max), (Vec2::new(30.0, -22.0), Vec2::new(35.0, -19.0)));
assert!(bounds(frame(vec![tag(10, "1"), tag(20, "2")])).is_empty(), "one corner is not a frame");
assert!(bounds(frame(vec![tag(10, "NaN"), tag(20, "0"), tag(11, "1"), tag(21, "inf")])).is_empty());
assert!(bounds(EntityKind::Unknown(crate::Unknown { dxf_type: "OTHER".into(), tags: vec![tag(10, "5"), tag(20, "5")] })).is_empty());
}
/// Groups 10/20 inside an application-defined `102 {...}` group belong to the application, not
/// to the frame: the real corners come after it (review on #2587).
#[test]
fn ole_frame_skips_application_groups() {
let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() };
let tags = vec![
tag(102, "{ACAD_REACTORS"),
tag(10, "900"),
tag(20, "900"),
tag(11, "901"),
tag(21, "901"),
tag(102, "}"),
tag(10, "30"),
tag(20, "-19"),
tag(11, "35"),
tag(21, "-22"),
];
let q = ole_frame(&tags).expect("frame");
assert_eq!((q[0], q[2]), (Vec2::new(30.0, -19.0), Vec2::new(35.0, -22.0)));
assert!(ole_frame(&tags[..6]).is_none(), "corners only inside the group are not a frame");
}
#[test]
fn a_shared_block_cache_measures_as_a_fresh_one_for_each_entity() {
let line = |a: (f64, f64), b: (f64, f64), layer: &str| {
@@ -486,6 +768,7 @@ mod tests {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}),
)
};
@@ -514,4 +797,322 @@ mod tests {
assert!(extents.width() > drawn.width());
}
}
/// A turned array of references reaches its side copies, not only the first and the last;
/// a hostile count measures only the copies that are drawn.
#[test]
fn a_rotated_array_counts_every_corner_copy() {
let mut d = Drawing::new_metric();
let mut b = crate::Block::new("B");
b.entities.push(Entity::new(crate::Handle(1), EntityKind::Line(crate::Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })));
d.blocks.insert("B".into(), std::sync::Arc::new(b));
let array = |cols: u32, rows: u32, rotation: f64| {
let ins = crate::Insert {
block: "B".into(),
scale: Vec3::new(1.0, 1.0, 1.0),
rotation,
cols,
rows,
col_spacing: 10.0,
row_spacing: 10.0,
..crate::Insert::default()
};
Entity::new(crate::Handle(2), EntityKind::Insert(ins))
};
// Turned 45°: the copies sit at (0, 0), (7.07, 7.07), (-7.07, 7.07) and (0, 14.14).
let b = entity_bounds(&d, &array(2, 2, std::f64::consts::FRAC_PI_4), 0);
let side = 10.0 * std::f64::consts::FRAC_1_SQRT_2;
assert!((b.min.x + side).abs() < 1e-9 && b.max.x >= side, "{b:?}");
assert!((b.max.y - 2.0 * side - std::f64::consts::FRAC_1_SQRT_2).abs() < 1e-9, "{b:?}");
// The renderer draws at most 10,000 columns.
let b = entity_bounds(&d, &array(u32::MAX, 1, 0.0), 0);
assert!((b.max.x - (10.0 * 9_999.0 + 1.0)).abs() < 1e-6, "{b:?}");
}
/// An OLE2FRAME at large coordinates, with its OLE data header holding the frame's corners
/// shifted by `dx` in x.
fn big_frame(dx: f64) -> Vec<crate::RawTag> {
let (x1, y1, x2, y2) = (1e9, 1e9, 1e9 + 10.0, 1e9 + 5.0);
let mut blob = vec![1u8, 0];
for (x, y) in [(x1, y1), (x2, y1), (x2, y2), (x1, y2)] {
for v in [x + dx, y, 7.0] {
blob.extend_from_slice(&v.to_le_bytes());
}
}
let tag = |code: i32, value: String| crate::RawTag { code, value };
vec![
tag(10, x1.to_string()),
tag(20, y1.to_string()),
tag(11, x2.to_string()),
tag(21, y2.to_string()),
tag(310, blob.iter().map(|b| format!("{b:02X}")).collect()),
]
}
/// The x of the first corner in the OLE data of a [`big_frame`].
fn data_x(tags: &[crate::RawTag]) -> f64 {
let hex = tags.last().map(|t| t.value.as_str()).unwrap_or_default();
let bytes: Vec<u8> = (0..hex.len() / 2).filter_map(|i| u8::from_str_radix(hex.get(2 * i..2 * i + 2)?, 16).ok()).collect();
bytes.get(2..10).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes).unwrap_or(f64::NAN)
}
/// The match between the frame and the corners in its OLE data does not loosen with the
/// coordinate: half a unit off at 1e9 is not the frame, so the bytes stay as they are (review
/// on #2587).
#[test]
fn a_half_unit_offset_at_large_coordinates_is_not_the_frame() {
let mut tags = big_frame(0.5);
let before = tags.last().cloned();
ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(1.0, 1.0)));
assert_eq!(tags.first().map(|t| t.value.as_str()), Some("1000000001"), "the frame tags move");
assert_eq!(tags.last().map(|t| &t.value), before.as_ref().map(|t| &t.value), "the 310 bytes stay identical");
}
#[test]
fn exact_corners_at_large_coordinates_still_move() {
let mut tags = big_frame(0.0);
ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(1.0, 1.0)));
assert_eq!(data_x(&tags), 1e9 + 1.0);
}
/// A translation, and a uniform positive scale about any point, keep a frame axis aligned and
/// upper-left; a rotation, a mirror, a non-uniform or non-positive scale do not.
#[test]
fn ole_frame_accepts_translations_and_uniform_positive_scales_only() {
use cadcraft_geom::Mat3;
let p = Vec2::new(3.0, -4.0);
assert!(ole_frame_accepts(&Mat3::translate(p)));
assert!(ole_frame_accepts(&Mat3::scale_about(p, 2.5)));
assert!(ole_frame_accepts(&Mat3::scale_about(p, 1e-3)));
assert!(!ole_frame_accepts(&Mat3::scale(2.0, 3.0)));
assert!(!ole_frame_accepts(&Mat3::scale_about(p, -1.0)));
assert!(!ole_frame_accepts(&Mat3::scale_about(p, 0.0)));
assert!(!ole_frame_accepts(&Mat3::rotate_about(p, 0.5)));
assert!(!ole_frame_accepts(&Mat3::mirror(Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0))));
}
/// ALIGN with a scale builds its matrix from two angles that agree only to rounding, so a large
/// scale leaves a rotation part of about `scale * 1e-16`. That is a scale, not a turn: the
/// tolerance for it grows with the scale, while a real turn is still refused (review on #2587).
#[test]
fn ole_frame_accepts_a_large_scale_with_rounding_noise_in_its_rotation() {
use cadcraft_geom::Mat3;
let p = Vec2::new(3.0, -4.0);
let noisy = Mat3::scale_about(p, 1e6).then_before(Mat3::rotate_about(p, 2e-16));
assert!(noisy.b.abs() > 1e-12, "the setup must exceed an absolute tolerance: {}", noisy.b);
assert!(ole_frame_accepts(&noisy));
let turned = Mat3::scale_about(p, 1e6).then_before(Mat3::rotate_about(p, 1e-6));
assert!(!ole_frame_accepts(&turned));
}
/// The corners (x, y) in the OLE data header of a frame built by [`big_frame`]-style tags.
fn header_corners(tags: &[crate::RawTag]) -> Vec<(f64, f64)> {
let hex: String = tags.iter().filter(|t| t.code == 310).map(|t| t.value.as_str()).collect();
let bytes: Vec<u8> = (0..hex.len() / 2).filter_map(|i| u8::from_str_radix(hex.get(2 * i..2 * i + 2)?, 16).ok()).collect();
let f = |o: usize| bytes.get(o..o + 8).and_then(|s| <[u8; 8]>::try_from(s).ok()).map(f64::from_le_bytes).unwrap_or(f64::NAN);
(0..4).map(|c| (f(2 + c * 24), f(10 + c * 24))).collect()
}
fn small_frame() -> Vec<crate::RawTag> {
let mut blob = vec![1u8, 0];
for (x, y) in [(30.0f64, -19.0f64), (35.0, -19.0), (35.0, -22.0), (30.0, -22.0)] {
for v in [x, y, 7.0] {
blob.extend_from_slice(&v.to_le_bytes());
}
}
let tag = |code: i32, value: &str| crate::RawTag { code, value: value.into() };
vec![
tag(10, "30"),
tag(20, "-19"),
tag(11, "35"),
tag(21, "-22"),
crate::RawTag { code: 310, value: blob.iter().map(|b| format!("{b:02X}")).collect() },
]
}
/// Internal callers (EXPLODE, REFEDIT, paste, array placement) transform a frame by any matrix.
/// It stays axis aligned: groups 10/20 are the upper-left of its box, 11/21 the lower-right,
/// and the OLE data holds the same box (review on #2587). A mirror keeps the axes, so the box
/// is that of the mapped corners; a 30° turn keeps the frame's own 5 x 3 about its turned
/// centre, where the corners' box would flatten it.
#[test]
fn a_rotated_frame_stays_axis_aligned_and_consistent() {
use cadcraft_geom::Mat3;
let rotate = Mat3::rotate_about(Vec2::new(1.0, 2.0), 30f64.to_radians());
let mirror = Mat3::mirror(Vec2::new(0.0, 0.0), Vec2::new(1.0, 0.0));
for (m, turned) in [(rotate, true), (mirror, false)] {
let mut tags = small_frame();
let mapped = if turned {
let c = m.apply(Vec2::new(32.5, -20.5));
[c - Vec2::new(2.5, 1.5), c + Vec2::new(2.5, 1.5)]
} else {
[m.apply(Vec2::new(30.0, -19.0)), m.apply(Vec2::new(35.0, -22.0))]
};
let (minx, maxx) = (mapped[0].x.min(mapped[1].x), mapped[0].x.max(mapped[1].x));
let (miny, maxy) = (mapped[0].y.min(mapped[1].y), mapped[0].y.max(mapped[1].y));
ole_frame_transform(&mut tags, &m);
let g = |code: i32| tags.iter().find(|t| t.code == code).and_then(|t| t.value.parse::<f64>().ok()).unwrap_or(f64::NAN);
assert_eq!((g(10), g(20), g(11), g(21)), (minx, maxy, maxx, miny));
assert_eq!(header_corners(&tags), vec![(minx, maxy), (maxx, maxy), (maxx, miny), (minx, miny)]);
}
}
/// `from_str_radix` accepts a leading sign, so "+A" must not count as a hex byte (review on
/// #2587): data with one is not valid and MOVE leaves its bytes alone.
#[test]
fn a_plus_sign_in_ole_data_is_not_hex() {
let mut tags = small_frame();
let hex = tags.last().map(|t| t.value.clone()).unwrap_or_default();
// The marker's first byte is 01: "+1" would decode to the same byte.
let signed = format!("+1{}", hex.get(2..).unwrap_or_default());
if let Some(t) = tags.last_mut() {
t.value = signed.clone();
}
ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(10.0, 5.0)));
assert_eq!(tags.first().map(|t| t.value.as_str()), Some("40"), "the frame tags still move");
assert_eq!(tags.last().map(|t| t.value.as_str()), Some(signed.as_str()));
}
/// A payload of 1,000 groups of 127 bytes: only the group(s) holding the 98-byte header are
/// rewritten. Later groups stay as they were, even ones that are not valid hex or have padding
/// (the old code re-encoded the whole payload and gave up on any bad group).
#[test]
fn a_large_ole_payload_only_rewrites_its_leading_groups() {
let mut tags = small_frame();
let first = tags.pop().map(|t| t.value).unwrap_or_default();
let mut head = first.clone();
// Fill the first group up to 127 bytes.
head.push_str(&"ab".repeat(127 - first.len() / 2));
tags.push(crate::RawTag { code: 310, value: head });
for g in 1..1000 {
let value = match g {
2 => format!(" {} ", "Ab".repeat(127)),
500 => "ZZ".repeat(127),
_ => "ab".repeat(127),
};
tags.push(crate::RawTag { code: 310, value });
}
let rest: Vec<String> = tags.iter().skip(5).map(|t| t.value.clone()).collect();
ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(10.0, 5.0)));
assert_eq!(header_corners(&tags[..5]), vec![(40.0, -14.0), (45.0, -14.0), (45.0, -17.0), (40.0, -17.0)]);
let after: Vec<String> = tags.iter().skip(5).map(|t| t.value.clone()).collect();
assert_eq!(after, rest, "every group after the first is string-identical");
assert_eq!(tags.get(4).map(|t| t.value.len()), Some(254), "the first group keeps its length");
}
/// Above about 8.6e9 one ulp of an f64 is more than the fixed ceiling on the corner match, so a
/// text corner one ulp from the header double must still count as the same corner (review on
/// #2587).
#[test]
fn ole_frame_moves_at_2e10_with_a_one_ulp_text_corner() {
let mut tags = big_frame(0.0);
// Rebuild the frame at 2e10: the header keeps the exact corners, the text is one ulp off.
let (x1, y1, x2, y2) = (2e10f64, 2e10f64, 2e10 + 10.0, 2e10 + 5.0);
let mut blob = vec![1u8, 0];
for (x, y) in [(x1, y1), (x2, y1), (x2, y2), (x1, y2)] {
for v in [x, y, 7.0] {
blob.extend_from_slice(&v.to_le_bytes());
}
}
let text_x1 = f64::from_bits(x1.to_bits() + 1);
tags[0].value = text_x1.to_string();
tags[1].value = y1.to_string();
tags[2].value = x2.to_string();
tags[3].value = y2.to_string();
if let Some(t) = tags.last_mut() {
t.value = blob.iter().map(|b| format!("{b:02X}")).collect();
}
ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(1e4, 1e4)));
assert_eq!(header_corners(&tags)[0].0, text_x1 + 1e4, "the header moved with the frame");
}
/// Below scale 1 the rotation bound is still relative to the scale: a small real turn at a tiny
/// scale is refused, and so is a non-uniform scale whose two factors differ by more than a
/// relative 1e-12 (review on #2587).
#[test]
fn ole_frame_refuses_a_small_turn_at_a_tiny_scale() {
use cadcraft_geom::Mat3;
let p = Vec2::new(3.0, -4.0);
let turned = Mat3::scale_about(p, 1e-9).then_before(Mat3::rotate_about(p, 0.05f64.to_radians()));
assert!(!ole_frame_accepts(&turned));
assert!(ole_frame_accepts(&Mat3::scale_about(p, 1e-9)));
assert!(!ole_frame_accepts(&Mat3::scale(1e-6, 1e-6 + 5e-13)));
}
/// Hex digits keep the case they had: bytes the transform does not change come back as the
/// identical text, also in a group that mixes upper and lower case (review on #2587).
#[test]
fn moving_an_ole_frame_keeps_each_hex_digits_case() {
let mut tags = small_frame();
let old = tags.last().map(|t| t.value.clone()).unwrap_or_default();
let mixed: String = old.chars().enumerate().map(|(i, c)| if i < 24 { c.to_ascii_lowercase() } else { c }).collect();
assert_ne!(mixed, old);
if let Some(t) = tags.last_mut() {
t.value = mixed.clone();
}
ole_frame_transform(&mut tags, &cadcraft_geom::Mat3::translate(Vec2::new(10.0, 5.0)));
let new = tags.last().map(|t| t.value.clone()).unwrap_or_default();
assert_eq!(new.len(), mixed.len());
let byte = |s: &str, i: usize| s.get(2 * i..2 * i + 2).and_then(|h| u8::from_str_radix(h, 16).ok());
let mut same = 0;
for i in 0..mixed.len() / 2 {
if byte(&mixed, i) == byte(&new, i) {
same += 1;
assert_eq!(mixed.get(2 * i..2 * i + 2), new.get(2 * i..2 * i + 2), "byte {i}");
}
}
assert!(same > 40, "most of the header is unchanged: {same}");
assert_eq!(header_corners(&tags)[0], (40.0, -14.0));
}
/// A frame from `(x1, y1)` (upper left) to `(x2, y2)` (lower right), its OLE header holding the
/// same corners.
fn frame_at(x1: f64, y1: f64, x2: f64, y2: f64) -> Vec<crate::RawTag> {
let mut blob = vec![1u8, 0];
for (x, y) in [(x1, y1), (x2, y1), (x2, y2), (x1, y2)] {
for v in [x, y, 0.0] {
blob.extend_from_slice(&v.to_le_bytes());
}
}
let tag = |code: i32, value: String| crate::RawTag { code, value };
vec![
tag(10, x1.to_string()),
tag(20, y1.to_string()),
tag(11, x2.to_string()),
tag(21, y2.to_string()),
tag(310, blob.iter().map(|b| format!("{b:02X}")).collect()),
]
}
fn size(tags: &[crate::RawTag]) -> (f64, f64, Vec2) {
let o = ole_frame(tags).unwrap();
let b = Bounds2::from_points(o);
(b.width(), b.height(), b.center())
}
/// A frame turned by an angle that isn't a quarter turn keeps its size about its turned
/// centre instead of collapsing to the box of its two corners (a 10 x 10 square turned 45°
/// became 14.14 x 0), and the OLE header follows (#2587 review).
#[test]
fn a_frame_turned_off_the_axes_keeps_its_size() {
use cadcraft_geom::Mat3;
let close = |a: f64, b: f64| (a - b).abs() < 1e-9;
let mut tags = frame_at(0.0, 10.0, 10.0, 0.0);
ole_frame_transform(&mut tags, &Mat3::rotate(std::f64::consts::FRAC_PI_4));
let (w, h, c) = size(&tags);
assert!(close(w, 10.0) && close(h, 10.0), "{w} x {h}");
assert!(close(c.x, 0.0) && close(c.y, 50f64.sqrt()), "{c:?}");
let (ul, lr) = (header_corners(&tags)[0], header_corners(&tags)[2]);
assert!(close(ul.0, -5.0) && close(lr.1, 50f64.sqrt() - 5.0), "the header follows: {ul:?} {lr:?}");
// Nearer a quarter turn, the sides swap: a 10 wide, 4 tall frame turned 100° is 4 x 10.
let mut tags = frame_at(0.0, 4.0, 10.0, 0.0);
ole_frame_transform(&mut tags, &Mat3::rotate(100f64.to_radians()));
let (w, h, _) = size(&tags);
assert!(close(w, 4.0) && close(h, 10.0), "{w} x {h}");
// A turn and its inverse bring the frame back.
let mut tags = frame_at(2.0, 9.0, 7.0, 3.0);
let m = Mat3::rotate(0.3);
ole_frame_transform(&mut tags, &m);
ole_frame_transform(&mut tags, &m.inverse().unwrap());
let (w, h, c) = size(&tags);
assert!(close(w, 5.0) && close(h, 6.0) && close(c.x, 4.5) && close(c.y, 6.0), "{w} x {h} at {c:?}");
}
}
+36
View File
@@ -75,9 +75,19 @@ pub struct Foreign {
/// surfaces, which from 2013 on those entities don't carry themselves: each `ACDSRECORD`
/// names its entity with a 320 handle (see [`Foreign::data_store_entities`]).
pub data_store: Vec<RawTag>,
/// The `$ACADVER` of the file all this was read from: its groups are in that version's form.
/// The drawing's own `$ACADVER` is the version it is saved as, which SAVEAS changes, so a
/// later save must not take it for this one (#2471).
pub version: Option<String>,
}
impl Foreign {
/// The class of the file's CLASSES a proxy's group 91 names (see [`class_number`]), if any.
/// Saving as DWG keeps a proxy with that class and leaves out one whose class it can't name.
pub fn proxy_class(&self, tags: &[RawTag]) -> Option<&str> {
class_index(class_number(tags.iter().map(|r| (r.code, r.value.as_str())))).and_then(|i| self.class_order.get(i)).map(String::as_str)
}
pub fn is_empty(&self) -> bool {
self.objects.is_empty()
&& self.dictionary.is_empty()
@@ -256,3 +266,29 @@ impl Foreign {
}
}
}
/// Where a proxy's class number is: its first group 91 outside the `102 {NAME` … `102 }` groups
/// (an application's can hold a 91 of its own) and before any xdata.
pub fn class_group<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)>) -> Option<usize> {
let mut in_group = false;
for (i, (code, value)) in groups.into_iter().enumerate() {
match code {
1000.. => return None,
102 => in_group = value.as_ref().trim().starts_with('{'),
91 if !in_group => return Some(i),
_ => {}
}
}
None
}
/// A proxy's class number (see [`class_group`]).
pub fn class_number<S: AsRef<str>>(groups: impl IntoIterator<Item = (i32, S)> + Clone) -> Option<i64> {
let i = class_group(groups.clone())?;
groups.into_iter().nth(i).and_then(|(_, v)| v.as_ref().trim().parse().ok())
}
/// The place in CLASSES a class number names (500 is the first class).
pub fn class_index(number: Option<i64>) -> Option<usize> {
usize::try_from(number?.checked_sub(500)?).ok()
}
+17
View File
@@ -90,6 +90,23 @@ impl Header {
.filter(|p| p.is_finite() && if allow_zero { p.x >= 0.0 && p.y >= 0.0 } else { p.x > 0.0 && p.y > 0.0 })
.unwrap_or(Vec2::new(0.5, 0.5))
}
/// The model view the drawing was saved at: `$VIEWCTR` (centre) and `$VIEWSIZE` (height, in
/// drawing units), when both are present and usable. A DXF file keeps the pair in HEADER and
/// repeats it in the `*ACTIVE` VPORT record (12/22 and 40); a reader opens the drawing on it
/// rather than on the extents, so a drawing saved on one detail of a large sheet opens there.
pub fn saved_view(&self) -> Option<(Vec2, f64)> {
let center = self.point("VIEWCTR")?.xy();
let height = self.get("VIEWSIZE").and_then(HVal::as_f64)?;
(center.is_finite() && height.is_finite() && height > 1e-9).then_some((center, height))
}
/// Record the view the drawing is saved at (see [`Header::saved_view`]). A view that cannot
/// be shown is not recorded, so a usable stored view is never replaced by an unusable one.
pub fn set_saved_view(&mut self, center: Vec2, height: f64) {
if center.is_finite() && height.is_finite() && height > 1e-9 {
self.set("VIEWCTR", HVal::Point(center.to3(0.0)));
self.set_f64("VIEWSIZE", height);
}
}
pub fn set_f64(&mut self, name: &str, v: f64) {
self.set(name, HVal::Real(v));
}
+11 -1
View File
@@ -16,9 +16,11 @@ mod header;
pub mod library;
mod plotstyle;
mod plotter;
mod raster;
mod refedit;
mod store;
mod tables;
mod xclip;
use std::collections::{BTreeMap, BTreeSet};
@@ -27,15 +29,20 @@ pub use cadcraft_color as color;
pub use cadcraft_geom as geom;
pub use constraint::*;
pub use entity::*;
pub use extents::{BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached};
pub use extents::{
BlockBoundsCache, MAX_BLOCK_DEPTH, entity_bounds, entity_bounds_cached, extent_bounds, extent_bounds_cached, ole_frame, ole_frame_accepts,
ole_frame_transform,
};
pub use format::Format;
pub use gdt::*;
pub use header::{HVal, Header};
pub use plotstyle::*;
pub use plotter::*;
pub use raster::{Raster, Rasters};
pub use refedit::{RefEdit, WorkItem};
pub use store::EntityStore;
pub use tables::*;
pub use xclip::{ClipBoundary, MAX_CLIP_VERTICES};
/// File data CADCraft doesn't model, kept for saving (#528).
pub mod dynblock;
@@ -136,6 +143,8 @@ pub struct Drawing {
/// for the Linux fonts of text styles, and each style keeps its own in CADCraft xdata, so the
/// drawing reopens with it. Never set on an open drawing.
pub portable_fonts: bool,
/// The pixels of the raster images that are loaded (IMAGE). Never written to a file.
pub rasters: Rasters,
}
impl Default for Drawing {
@@ -196,6 +205,7 @@ impl Drawing {
refedit: None,
skipped_records: BTreeMap::new(),
portable_fonts: false,
rasters: Rasters::default(),
}
}
+93
View File
@@ -0,0 +1,93 @@
//! Decoded raster image pixels (IMAGE entities). The drawing keeps them for the session only:
//! they are loaded from the image files after a drawing opens and are never written to a file.
use std::collections::BTreeMap;
use std::sync::Arc;
/// The pixels of a raster image: 8-bit RGBA, not premultiplied, rows from the top.
#[derive(Clone, PartialEq)]
pub struct Raster {
width: u32,
height: u32,
rgba: Vec<u8>,
opaque: bool,
}
impl Raster {
/// `None` unless both sides are at least one pixel and `rgba` holds exactly four bytes per pixel.
pub fn new(width: u32, height: u32, rgba: Vec<u8>) -> Option<Raster> {
let pixels = usize::try_from(width).ok()?.checked_mul(usize::try_from(height).ok()?)?;
if pixels == 0 || rgba.len() != pixels.checked_mul(4)? {
return None;
}
let opaque = rgba.as_chunks::<4>().0.iter().all(|[_, _, _, alpha]| *alpha == u8::MAX);
Some(Raster { width, height, rgba, opaque })
}
pub fn width(&self) -> u32 {
self.width
}
pub fn height(&self) -> u32 {
self.height
}
/// Four bytes per pixel (red, green, blue, alpha), `width * height` pixels.
pub fn rgba(&self) -> &[u8] {
&self.rgba
}
/// No pixel is transparent.
pub fn opaque(&self) -> bool {
self.opaque
}
/// The pixel in column `x` of row `y` (from the top): red, green, blue, alpha.
pub fn pixel(&self, x: u32, y: u32) -> Option<[u8; 4]> {
if x >= self.width || y >= self.height {
return None;
}
let (x, y, width) = (usize::try_from(x).ok()?, usize::try_from(y).ok()?, usize::try_from(self.width).ok()?);
let pixels = self.rgba.as_chunks::<4>().0;
pixels.get(y.checked_mul(width)?.checked_add(x)?).copied()
}
}
impl std::fmt::Debug for Raster {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Raster({}x{})", self.width, self.height)
}
}
/// The loaded pixels of a drawing's raster images, by image file path ([`crate::Image::path`]).
/// Session data: two drawings are equal whatever images they have loaded, and copying a drawing
/// (undo) shares the pixels.
#[derive(Clone, Default)]
pub struct Rasters(Arc<BTreeMap<String, Arc<Raster>>>);
impl Rasters {
pub fn get(&self, path: &str) -> Option<&Arc<Raster>> {
self.0.get(path)
}
pub fn insert(&mut self, path: &str, raster: Arc<Raster>) {
Arc::make_mut(&mut self.0).insert(path.to_string(), raster);
}
pub fn remove(&mut self, path: &str) {
if self.0.contains_key(path) {
Arc::make_mut(&mut self.0).remove(path);
}
}
pub fn len(&self) -> usize {
self.0.len()
}
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl PartialEq for Rasters {
fn eq(&self, _: &Rasters) -> bool {
true
}
}
impl std::fmt::Debug for Rasters {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "Rasters({})", self.0.len())
}
}
+12 -1
View File
@@ -799,6 +799,13 @@ pub struct PageSetup {
/// The layout's paper units are millimetres (plot paper units 1 in DXF) whatever the
/// drawing's MEASUREMENT says; otherwise paper units follow MEASUREMENT (#1058).
pub paper_mm: bool,
/// Paper size (DXF groups 44, 45) and plot rotation (group 73) as the file stored them.
/// Saving writes them back while they still describe `width_mm`, `height_mm` and
/// `landscape`, so each program's convention for media defined wider than tall survives a
/// round trip: AutoCAD stores a portrait size and a quarter turn, ZWCAD the media's own size
/// and no turn (#1463). `None` for page setups made in CADCraft.
#[serde(skip)]
pub file_paper: Option<(f64, f64, i64)>,
/// The paper image origin (DXF groups 148/149, in plot paper units) as the file had it, so a
/// save keeps where the sheet sits; `None` for a page CADCraft made, written as 0,0 (#2109).
#[serde(skip_serializing_if = "Option::is_none")]
@@ -824,6 +831,7 @@ impl Default for PageSetup {
show_plot_styles: false,
plot_transparency: false,
paper_mm: false,
file_paper: None,
image_origin: None,
}
}
@@ -863,7 +871,7 @@ pub struct NamedView {
/// The layer state restored with the view (its layer snapshot).
#[serde(default)]
pub layer_state: Option<String>,
/// View twist (radians, counterclockwise); kept for files, not applied to the 2D display.
/// View twist (radians, counterclockwise); VIEW Restore applies it to the model space view.
#[serde(default)]
pub twist: f64,
/// The layout a paper space view belongs to (`None`: a model space view; an empty name: a
@@ -884,6 +892,9 @@ pub struct VportTile {
/// Width / height of the tile on screen when it was saved (0: unknown).
#[serde(default)]
pub aspect: f64,
/// The tile's view twist (radians, counterclockwise; DXF VPORT group 51 in degrees).
#[serde(default)]
pub twist: f64,
}
/// A model space viewport configuration (VPORTS): `*Active` is the one shown, other names are
+5
View File
@@ -189,6 +189,7 @@ fn inserts_of_missing_or_empty_blocks_do_not_stretch_extents() {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
})
};
d.blocks.insert("Empty".into(), std::sync::Arc::new(Block::new("Empty")));
@@ -242,6 +243,7 @@ fn visible_attributes_of_a_missing_block_still_count() {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}),
)
};
@@ -285,6 +287,7 @@ fn insert_bounds_with_cyclic_block_terminate() {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}),
));
b.entities.push(Entity::new(Handle(2), line((0.0, 0.0), (1.0, 1.0))));
@@ -303,6 +306,7 @@ fn insert_bounds_with_cyclic_block_terminate() {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}),
)
.unwrap();
@@ -420,6 +424,7 @@ fn plain_insert(block: &str) -> EntityKind {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
})
}
+85
View File
@@ -0,0 +1,85 @@
//! XCLIP: the clipping boundary of one block or xref reference.
//!
//! The boundary is kept in the referenced block's coordinates, so it moves, rotates and scales
//! with its reference; the block definition and other references to it are untouched. In a file
//! it is the reference's `ACAD_FILTER` / `SPATIAL` extension-dictionary entry (a SPATIAL_FILTER
//! object, DXF Reference), read and written by the io crate.
use cadcraft_geom::Vec2;
use serde::{Deserialize, Serialize};
/// Most boundary vertices a clip keeps (hostile files and parameters are capped to this).
pub const MAX_CLIP_VERTICES: usize = 4096;
/// A reference's clipping boundary.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct ClipBoundary {
/// Vertices in the block's coordinates: two opposite corners for a rectangle, three or more
/// for a closed polygon (not repeating the first vertex).
pub points: Vec<Vec2>,
/// Whether clipping is on (XCLIP ON/OFF); an off boundary is kept but nothing is clipped.
#[serde(default = "on")]
pub enabled: bool,
/// Inverted clip: what is inside the boundary is hidden, what is outside shows.
#[serde(default)]
pub inverted: bool,
}
fn on() -> bool {
true
}
impl ClipBoundary {
/// A boundary from `points` (block coordinates), on and not inverted.
pub fn new(points: Vec<Vec2>) -> Self {
ClipBoundary { points, enabled: true, inverted: false }
}
/// The closed outline in block coordinates: a rectangle's four corners or the polygon's
/// vertices. Empty when the boundary has fewer than two vertices, more than
/// [`MAX_CLIP_VERTICES`] or a non-finite one.
pub fn polygon(&self) -> Vec<Vec2> {
if self.points.len() > MAX_CLIP_VERTICES || !self.points.iter().all(|p| p.is_finite()) {
return Vec::new();
}
match self.points.as_slice() {
[a, b] => vec![
Vec2::new(a.x.min(b.x), a.y.min(b.y)),
Vec2::new(a.x.max(b.x), a.y.min(b.y)),
Vec2::new(a.x.max(b.x), a.y.max(b.y)),
Vec2::new(a.x.min(b.x), a.y.max(b.y)),
],
[_, _, _, ..] => self.points.clone(),
_ => Vec::new(),
}
}
/// Whether the boundary is a rectangle given by two corners.
pub fn is_rectangle(&self) -> bool {
self.points.len() == 2
}
/// Whether drawing the reference is clipped by it now (on, with a usable outline).
pub fn active(&self) -> bool {
self.enabled && self.polygon().len() >= 3
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rectangle_and_polygon_outlines() {
let r = ClipBoundary::new(vec![Vec2::new(2.0, 3.0), Vec2::new(0.0, 0.0)]);
assert_eq!(r.polygon(), vec![Vec2::new(0.0, 0.0), Vec2::new(2.0, 0.0), Vec2::new(2.0, 3.0), Vec2::new(0.0, 3.0)]);
assert!(r.active() && r.is_rectangle());
let bad = ClipBoundary::new(vec![Vec2::new(f64::NAN, 0.0), Vec2::new(1.0, 1.0)]);
assert!(bad.polygon().is_empty() && !bad.active());
let one = ClipBoundary::new(vec![Vec2::ZERO]);
assert!(!one.active());
let off = ClipBoundary { enabled: false, ..r };
assert!(!off.active());
}
}
+363 -8
View File
@@ -65,7 +65,7 @@ fn mb(n: u64) -> String {
#[cfg(not(no_dwg_bridge))]
pub mod worker;
#[cfg(not(no_dwg_bridge))]
pub use worker::{WORKER_ARG, crash_worker_for_test, decode, encode_as, encode_noted, serve_if_asked, use_own_worker, use_worker};
pub use worker::{WORKER_ARG, crash_worker_for_test, decode, encode_as, encode_kept_noted, encode_noted, serve_if_asked, use_own_worker, use_worker};
#[cfg(not(no_dwg_bridge))]
mod native {
@@ -652,7 +652,7 @@ mod native {
/// Convert DXF bytes into a DWG file of the DXF's version, and at least AutoCAD 2004
/// (AC1018).
pub fn dxf_to_dwg(dxf: &[u8]) -> Result<Vec<u8>, String> {
convert(dxf, None).map(|(dwg, _)| dwg)
convert(dxf, None, None).map(|(dwg, _)| dwg)
}
/// Convert DXF bytes into a DWG file of `version`, a code from [`super::VERSIONS`] ("AC1032"),
@@ -665,7 +665,32 @@ mod native {
/// DXF type it can't write (other programs' custom entities and objects that the DWG reader
/// didn't read from a DWG of this version), empty when the DWG keeps everything.
pub fn dxf_to_dwg_noted(dxf: &[u8], version: &str) -> Result<(Vec<u8>, super::Unwritten), String> {
let v = match version.trim().to_ascii_uppercase().as_str() {
convert(dxf, Some(writable(version)?), None)
}
/// Like [`dxf_to_dwg_as`], for a DXF that declares an older version than the groups it carries
/// over from another file. CADCraft's R2000 DWG bridge holds the objects it keeps without
/// modelling them (render settings, fields, associative and dynamic block data) as they were
/// read from a file of version `kept` ("AC1032"), and acadrust reads several of those
/// differently by version: read as R2000, an AC1032 file's mental ray render settings came out
/// a class version too high, for which the ODA rejects the whole DWG, and a field lost its
/// cached value. So the DXF is read as `kept` declares. A `kept` version that is unknown, or
/// not newer than the DXF's own, changes nothing.
pub fn dxf_to_dwg_kept_as(dxf: &[u8], version: &str, kept: &str) -> Result<Vec<u8>, String> {
dxf_to_dwg_kept_noted(dxf, version, kept).map(|(dwg, _)| dwg)
}
/// [`dxf_to_dwg_kept_as`], also returning what the DWG writer left out, as
/// [`dxf_to_dwg_noted`] does.
pub fn dxf_to_dwg_kept_noted(dxf: &[u8], version: &str, kept: &str) -> Result<(Vec<u8>, super::Unwritten), String> {
let kept = acadrust::DxfVersion::from_version_string(kept.trim().to_ascii_uppercase().as_str());
let kept = (kept != acadrust::DxfVersion::Unknown).then_some(kept);
convert(dxf, Some(writable(version)?), kept)
}
/// The DWG version for a code from [`super::VERSIONS`].
fn writable(version: &str) -> Result<acadrust::DxfVersion, String> {
Ok(match version.trim().to_ascii_uppercase().as_str() {
"AC1015" => acadrust::DxfVersion::AC1015,
"AC1018" => acadrust::DxfVersion::AC1018,
"AC1021" => acadrust::DxfVersion::AC1021,
@@ -673,8 +698,72 @@ mod native {
"AC1027" => acadrust::DxfVersion::AC1027,
"AC1032" => acadrust::DxfVersion::AC1032,
_ => return Err(super::unsupported(version)),
})
}
/// The ASCII DXF with its `$ACADVER` set to `kept` when that is newer than the version it
/// declares, or `None` to read it as it is (binary, no `$ACADVER`, or non-ASCII text without a
/// `$DWGCODEPAGE` to decode it by). From AutoCAD 2007 (AC1021) a DXF is UTF-8, so other bytes
/// are first decoded with the code page the DXF declares; `\U+XXXX` escapes read the same in
/// every version, and CADCraft's R2000 DXF is ASCII with such escapes.
pub(super) fn declare_version(dxf: &[u8], kept: acadrust::DxfVersion) -> Option<Vec<u8>> {
if dxf.starts_with(b"AutoCAD Binary DXF") {
return None;
}
let (_, declared) = header_value(dxf, b"$ACADVER")?;
let declared = acadrust::DxfVersion::from_version_string(std::str::from_utf8(declared).ok()?);
if declared >= kept {
return None;
}
let text: std::borrow::Cow<'_, [u8]> = if dxf.is_ascii() || kept < acadrust::DxfVersion::AC1021 {
std::borrow::Cow::Borrowed(dxf)
} else {
// As acadrust decodes an older DXF: by its code page, Windows-1252 for one it doesn't
// know; a code page that names UTF-8 needs no decoding.
let (_, code_page) = header_value(dxf, b"$DWGCODEPAGE")?;
match acadrust::io::dxf::code_page::encoding_from_code_page(std::str::from_utf8(code_page).ok()?) {
Some(encoding) => {
let (text, errors) = encoding.decode_without_bom_handling(dxf);
if errors {
return None;
}
std::borrow::Cow::Owned(text.into_owned().into_bytes())
}
None => std::borrow::Cow::Borrowed(std::str::from_utf8(dxf).ok()?.as_bytes()),
}
};
convert(dxf, Some(v))
let (at, value) = header_value(&text, b"$ACADVER")?;
let code = kept.to_string();
let mut out = Vec::with_capacity(text.len().saturating_add(code.len()));
out.extend_from_slice(text.get(..at)?);
out.extend_from_slice(code.as_bytes());
out.extend_from_slice(text.get(at.checked_add(value.len())?..)?);
Some(out)
}
/// The byte offset and the trimmed value of header variable `name` in an ASCII DXF: the value
/// of the group that follows the `9` group naming it. The file is read as (group code,
/// value) line pairs, in one pass with no buffering, up to the first `0`/`ENDSEC`, the end
/// of the HEADER section: a large input without one costs time, not memory (a line index of
/// a 32 MiB file used 0.8 GB). Lines may end in `\r\n`.
fn header_value<'a>(dxf: &'a [u8], name: &[u8]) -> Option<(usize, &'a [u8])> {
let mut offset = 0usize;
let mut lines = dxf.split(|b| *b == b'\n').map(|line| {
let at = offset.saturating_add(line.len() - line.trim_ascii_start().len());
offset = offset.saturating_add(line.len()).saturating_add(1);
(at, line.trim_ascii())
});
while let (Some((_, code)), Some((_, value))) = (lines.next(), lines.next()) {
if code == b"0" && value == b"ENDSEC" {
return None;
}
if code == b"9" && value == name {
let (_, code) = lines.next()?;
let (at, value) = lines.next()?;
return (code != b"0" && code != b"9").then_some((at, value));
}
}
None
}
/// The current dimension and text styles' names from their handles: a DWG stores the
@@ -711,6 +800,141 @@ mod native {
}
}
/// The DXF names of an ASCII DXF's CLASS records, in CLASSES order: a proxy's class number
/// (group 91) is 500 plus its class's place here (DXF Reference, ACAD_PROXY_OBJECT). Empty for
/// one without a CLASSES section. `None` for a binary DXF, whose classes this doesn't read:
/// CADCraft's own bridge DXF is always ASCII, and only a binary DXF given to the public
/// conversion functions comes here.
pub(super) fn dxf_class_names(dxf: &[u8]) -> Option<Vec<String>> {
let mut names = Vec::new();
if dxf.starts_with(b"AutoCAD Binary DXF") {
return None;
}
let mut lines = dxf.split(|b| *b == b'\n').map(|l| l.trim_ascii());
let (mut in_classes, mut in_class) = (false, false);
while let (Some(code), Some(value)) = (lines.next(), lines.next()) {
match (code, value) {
(b"0", b"ENDSEC") if in_classes => break,
(b"2", b"CLASSES") => in_classes = true,
(b"0", v) if in_classes => {
in_class = v == b"CLASS";
// Every record keeps its place, named or not: a proxy numbers its class by
// place, so a record without a name must not move the ones after it. An empty
// name matches no class, and such a proxy is left out.
if in_class {
names.push(String::new());
}
}
(b"1", v) if in_class => {
if let Some(last) = names.last_mut() {
*last = String::from_utf8_lossy(v).into_owned();
}
in_class = false;
}
_ => {}
}
}
Some(names)
}
/// Proxy objects' and entities' class numbers as the DWG numbers its classes. A DXF proxy
/// names its class by its place in the DXF's CLASSES (`classes`, from 500), but acadrust's
/// reader puts its own default classes first and numbers the DXF's after them, so the DXF
/// number named another class in the DWG: a 2018 drawing's piping proxies became
/// LARGE_RADIAL_DIMENSION and SECTIONOBJECT, and the ODA File Converter refused the file. A
/// proxy whose number names no class of the DXF is left out: kept as it is, its number would
/// name some other class of the DWG, for the same reason.
///
/// Before 2013 (AC1027) acadrust writes only the classes it knows a pre-2013 DWG needs, and a
/// proxy's class is not one of them: the proxy would name a missing class (the ODA refuses
/// the file: "No ClassId") or, by its old number, some other class. Such a DWG leaves the
/// proxies out instead, as it does other programs' data it can't write (`not_saved` reports
/// the entities). So does a DXF whose classes are unknown (`classes` is `None`, a binary
/// DXF): its proxies' numbers can't be mapped, and kept as they are they would name the
/// wrong classes and the ODA would refuse the file. Returns the proxies left out, by DXF type, for
/// what the DWG writer left out ([`super::Unwritten`]).
fn proxy_classes(doc: &mut acadrust::CadDocument, classes: Option<&[String]>) -> super::Unwritten {
let classes = match classes {
Some(c) if doc.version >= acadrust::DxfVersion::AC1027 => c,
_ => {
let entities: Vec<acadrust::Handle> = doc
.entities()
.filter_map(|e| match e {
acadrust::entities::EntityType::Extended(x) if matches!(x.data, acadrust::entities::ExtendedEntityData::Proxy(_)) => {
Some(x.common.handle)
}
_ => None,
})
.collect();
let objects: Vec<acadrust::Handle> =
doc.objects.iter().filter_map(|(h, o)| matches!(o, acadrust::objects::ObjectType::ProxyObject(_)).then_some(*h)).collect();
for h in &entities {
doc.remove_entity(*h);
}
for h in &objects {
doc.objects.remove(h);
}
return left_out(objects.len(), entities.len());
}
};
let number = |id: i32| -> Option<i32> {
let name = classes.get(usize::try_from(id.checked_sub(500)?).ok()?)?;
doc.classes.get_by_name(name).map(|c| i32::from(c.class_number))
};
let objects: Vec<(acadrust::Handle, Option<i32>)> = doc
.objects
.iter()
.filter_map(|(h, o)| match o {
acadrust::objects::ObjectType::ProxyObject(p) => Some((*h, number(p.class_id))),
_ => None,
})
.collect();
let entities: Vec<(acadrust::Handle, Option<i32>)> = doc
.entities()
.filter_map(|e| match e {
acadrust::entities::EntityType::Extended(x) => match &x.data {
acadrust::entities::ExtendedEntityData::Proxy(p) => Some((x.common.handle, number(p.class_id))),
_ => None,
},
_ => None,
})
.collect();
let unmapped = |list: &[(acadrust::Handle, Option<i32>)]| list.iter().filter(|(_, n)| n.is_none()).map(|(h, _)| *h).collect::<Vec<_>>();
let (gone_objects, gone_entities) = (unmapped(&objects), unmapped(&entities));
for h in &gone_objects {
doc.objects.remove(h);
}
for h in &gone_entities {
doc.remove_entity(*h);
}
let objects = objects.into_iter().filter_map(|(h, n)| Some((h, n?)));
let entities = entities.into_iter().filter_map(|(h, n)| Some((h, n?)));
for (h, n) in objects {
if let Some(acadrust::objects::ObjectType::ProxyObject(p)) = doc.objects.get_mut(&h) {
p.class_id = n;
}
}
let entities: std::collections::HashMap<acadrust::Handle, i32> = entities.into_iter().collect();
for e in doc.entities_mut() {
if let acadrust::entities::EntityType::Extended(x) = e {
let Some(n) = entities.get(&x.common.handle).copied() else { continue };
if let acadrust::entities::ExtendedEntityData::Proxy(p) = &mut x.data {
p.class_id = n;
}
}
}
left_out(gone_objects.len(), gone_entities.len())
}
/// Proxy objects and entities left out of the DWG, by their DXF types.
fn left_out(objects: usize, entities: usize) -> super::Unwritten {
[("ACAD_PROXY_OBJECT", objects), ("ACAD_PROXY_ENTITY", entities)]
.into_iter()
.filter(|(_, n)| *n > 0)
.map(|(t, n)| (t.to_string(), n))
.collect()
}
/// The current layer (`$CLAYER`) by its name, the same way as [`current_dimstyle`]: a DWG
/// stores the handle of the layer, and the one read with the DXF needn't be the layer's in
/// the document, so the drawing reopened with layer "0" current (#2252).
@@ -722,7 +946,8 @@ mod native {
}
}
fn convert(dxf: &[u8], version: Option<acadrust::DxfVersion>) -> Result<(Vec<u8>, super::Unwritten), String> {
/// `kept`: the version the DXF's carried-over groups were read from ([`dxf_to_dwg_kept_as`]).
fn convert(dxf: &[u8], version: Option<acadrust::DxfVersion>, kept: Option<acadrust::DxfVersion>) -> Result<(Vec<u8>, super::Unwritten), String> {
// Reject a pathologically large DXF before handing it to the third-party decoder, which
// allocates tables and section buffers from the input's declared sizes and cannot be
// interrupted once it starts (CWE-789). This bounds the large-input variant; the decoder
@@ -734,7 +959,19 @@ mod native {
mb(Limits::DEFAULT.max_dxf_bytes as u64)
));
}
let data = dxf.to_vec();
// Decoding a code page to UTF-8 can grow the text, so the limit applies again.
let data = match kept.and_then(|k| declare_version(dxf, k)) {
Some(d) if d.len() > Limits::DEFAULT.max_dxf_bytes => {
return Err(format!(
"DXF: the input is {} as UTF-8, larger than the {} CADCraft converts to DWG",
mb(d.len() as u64),
mb(Limits::DEFAULT.max_dxf_bytes as u64)
));
}
Some(d) => d,
None => dxf.to_vec(),
};
let classes = dxf_class_names(&data);
let mut doc = std::panic::catch_unwind(move || acadrust::DxfReader::from_reader(Cursor::new(data)).and_then(|r| r.read()))
.map_err(|_| "the DXF→DWG conversion failed".to_string())?
.map_err(|e| format!("DXF: {e}"))?;
@@ -749,10 +986,15 @@ mod native {
// The fix-ups run on the third-party reader's document, so a panic in one is an error, not a crash.
let unwritten = guarded(AssertUnwindSafe(|| {
super::fail_in_test("convert");
let proxies = proxy_classes(&mut doc, classes.as_deref());
other_layout_owners(&mut doc);
table_style_rows(&mut doc, true);
dimension_flags(&mut doc);
let unwritten = drop_unwritable(&mut doc);
let mut unwritten = drop_unwritable(&mut doc);
for (kind, n) in proxies {
let total = unwritten.entry(kind).or_insert(0);
*total = total.saturating_add(n);
}
current_dimstyle(&mut doc);
add_variable_dictionary(&mut doc);
current_text_style(&mut doc);
@@ -920,7 +1162,9 @@ mod native {
}
#[cfg(not(no_dwg_bridge))]
pub use native::{dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as, dxf_to_dwg_noted};
pub use native::{
dwg_to_dxf, dwg_to_dxf_noted, dwg_to_dxf_with, dxf_to_dwg, dxf_to_dwg_as, dxf_to_dwg_kept_as, dxf_to_dwg_kept_noted, dxf_to_dwg_noted,
};
/// What saving as DWG left out: how many records of each DXF type (upper case) the DWG writer
/// can't write.
@@ -975,6 +1219,13 @@ pub fn encode_as(dxf: &[u8], version: &str) -> Result<Vec<u8>, String> {
pub fn encode_noted(dxf: &[u8], version: &str) -> Result<(Vec<u8>, Unwritten), String> {
dxf_to_dwg_noted(dxf, version)
}
#[cfg(no_dwg_bridge)]
pub fn encode_kept_noted(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec<u8>, Unwritten), String> {
match kept {
Some(kept) => dxf_to_dwg_kept_noted(dxf, version, kept),
None => dxf_to_dwg_noted(dxf, version),
}
}
#[cfg(no_dwg_bridge)]
pub fn dwg_to_dxf(_bytes: &[u8]) -> Result<Vec<u8>, String> {
@@ -1000,6 +1251,14 @@ pub fn dxf_to_dwg_as(_dxf: &[u8], _version: &str) -> Result<Vec<u8>, String> {
pub fn dxf_to_dwg_noted(_dxf: &[u8], _version: &str) -> Result<(Vec<u8>, Unwritten), String> {
Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF"))
}
#[cfg(no_dwg_bridge)]
pub fn dxf_to_dwg_kept_as(_dxf: &[u8], _version: &str, _kept: &str) -> Result<Vec<u8>, String> {
Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF"))
}
#[cfg(no_dwg_bridge)]
pub fn dxf_to_dwg_kept_noted(_dxf: &[u8], _version: &str, _kept: &str) -> Result<(Vec<u8>, Unwritten), String> {
Err(format!("DWG files can't be written in the {NO_BRIDGE_BUILD} build yet; save as DXF"))
}
#[cfg(test)]
mod tests {
@@ -1285,6 +1544,102 @@ mod tests {
assert_eq!(notes, ["DWG: 3 DGN line style components that no line style definition uses were left out"]);
}
/// An R2000 DXF header (`\r\n` lines, as CADCraft writes them) with `extra` after `$ACADVER`.
#[cfg(not(no_dwg_bridge))]
fn r2000(extra: &[u8]) -> Vec<u8> {
let mut dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n 9\r\n$DWGCODEPAGE\r\n 3\r\nANSI_1252\r\n".to_vec();
dxf.extend_from_slice(b" 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\n");
dxf.extend_from_slice(extra);
dxf.extend_from_slice(b"\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n");
dxf
}
/// The kept version replaces only the `$ACADVER` value; everything else stays byte for byte.
#[cfg(not(no_dwg_bridge))]
#[test]
fn declare_version_changes_only_acadver() {
let dxf = r2000(b"A\\U+00E7\\U+00E3o");
let out = native::declare_version(&dxf, acadrust::DxfVersion::AC1032).unwrap();
assert_eq!(String::from_utf8(out).unwrap(), String::from_utf8(dxf).unwrap().replacen("AC1015", "AC1032", 1));
}
/// A kept version not newer than the declared one, a binary DXF and a DXF without `$ACADVER`
/// are read as they are.
#[cfg(not(no_dwg_bridge))]
#[test]
fn declare_version_leaves_what_it_need_not_change() {
let dxf = r2000(b"x");
assert_eq!(native::declare_version(&dxf, acadrust::DxfVersion::AC1015), None);
assert_eq!(native::declare_version(&dxf, acadrust::DxfVersion::AC1009), None);
assert_eq!(native::declare_version(b"AutoCAD Binary DXF\r\n\x1a\0", acadrust::DxfVersion::AC1032), None);
let no_version = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n";
assert_eq!(native::declare_version(no_version, acadrust::DxfVersion::AC1032), None);
// A `$ACADVER` outside the HEADER section is not the file's version.
let late = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 9\r\n$ACADVER\r\n 1\r\nAC1015\r\n";
assert_eq!(native::declare_version(late, acadrust::DxfVersion::AC1032), None);
}
/// The header is read as group code and value pairs up to the first `0`/`ENDSEC`: a `$ACADVER`
/// name whose value would come after it, or a file that never ends its HEADER, is no version
/// to replace, and `\r\n` lines keep the value's offset right.
#[cfg(not(no_dwg_bridge))]
#[test]
fn declare_version_reads_the_header_in_pairs_up_to_endsec() {
let cut = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 0\r\nENDSEC\r\n 1\r\nAC1015\r\n";
assert_eq!(native::declare_version(cut, acadrust::DxfVersion::AC1032), None);
let endless = vec![b'\n'; 1 << 20];
assert_eq!(native::declare_version(&endless, acadrust::DxfVersion::AC1032), None);
let crlf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1015\r\n 0\r\nENDSEC\r\n";
let out = native::declare_version(crlf, acadrust::DxfVersion::AC1032).unwrap();
assert_eq!(out, b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 9\r\n$ACADVER\r\n 1\r\n AC1032\r\n 0\r\nENDSEC\r\n");
}
/// Declared as 2007 or later, a DXF is UTF-8: code page text is decoded first. Declared as an
/// older version, the code page bytes stay as they are.
#[cfg(not(no_dwg_bridge))]
#[test]
fn declare_version_decodes_a_code_page_for_utf8_versions() {
let dxf = r2000(b"A\xe7\xe3o");
let utf8 = native::declare_version(&dxf, acadrust::DxfVersion::AC1032).unwrap();
let text = String::from_utf8(utf8).unwrap();
assert!(text.contains("\r\nAção\r\n") && text.contains("$ACADVER\r\n 1\r\nAC1032\r\n"), "{text}");
let legacy = native::declare_version(&dxf, acadrust::DxfVersion::AC1018).unwrap();
assert!(legacy.windows(4).any(|w| w == b"A\xe7\xe3o"), "the code page bytes stay");
assert!(legacy.windows(6).any(|w| w == b"AC1018"));
// A code page it doesn't know is read as Windows-1252, as acadrust reads an older DXF.
let at = dxf.windows(9).position(|w| w == b"ANSI_1252").unwrap();
let unknown = [&dxf[..at], b"NO_SUCH_CP".as_slice(), &dxf[at + 9..]].concat();
let text = String::from_utf8(native::declare_version(&unknown, acadrust::DxfVersion::AC1032).unwrap()).unwrap();
assert!(text.contains("\r\nAção\r\n"), "{text}");
// Without a `$DWGCODEPAGE` there is nothing to decode it by: it is read as it is.
let none = [&dxf[..at - 21], &dxf[at + 11..]].concat();
assert!(!none.windows(12).any(|w| w == b"$DWGCODEPAGE"), "{}", String::from_utf8_lossy(&none));
assert_eq!(native::declare_version(&none, acadrust::DxfVersion::AC1032), None);
}
/// An unknown kept version converts as [`dxf_to_dwg_as`] does.
#[cfg(not(no_dwg_bridge))]
#[test]
fn unknown_kept_version_converts_as_before() {
let dxf = r2000(b"x");
assert_eq!(dxf_to_dwg_kept_as(&dxf, "AC1032", "AC9999"), dxf_to_dwg_as(&dxf, "AC1032"));
assert!(dxf_to_dwg_kept_as(&dxf, "AC0000", "AC1032").is_err(), "an unwritable version is still an error");
}
/// The CLASS names in CLASSES order; nothing for a binary DXF or one without CLASSES.
#[cfg(not(no_dwg_bridge))]
#[test]
fn dxf_class_names_in_classes_order() {
let dxf = b" 0\r\nSECTION\r\n 2\r\nHEADER\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 1\r\nWIDGETA\r\n 2\r\nAcDbWidgetA\r\n 3\r\nApp\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 2\r\nAcDbWidgetB\r\n 0\r\nENDSEC\r\n 0\r\nSECTION\r\n 2\r\nENTITIES\r\n 0\r\nTEXT\r\n 1\r\nNOT_A_CLASS\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n";
assert_eq!(native::dxf_class_names(dxf).unwrap(), ["WIDGETA", "WIDGETB"]);
// A CLASS record without a name keeps its place, so the classes after it keep theirs
// (#2837 review).
let unnamed = b" 0\r\nSECTION\r\n 2\r\nCLASSES\r\n 0\r\nCLASS\r\n 2\r\nAcDbNoName\r\n 0\r\nCLASS\r\n 1\r\nWIDGETB\r\n 0\r\nENDSEC\r\n 0\r\nEOF\r\n";
assert_eq!(native::dxf_class_names(unnamed).unwrap(), ["", "WIDGETB"]);
assert_eq!(native::dxf_class_names(b" 0\nSECTION\n 2\nHEADER\n 0\nENDSEC\n 0\nEOF\n"), Some(Vec::new()));
assert_eq!(native::dxf_class_names(b"AutoCAD Binary DXF\r\n\x1a\0"), None);
}
/// AutoCAD's DWG scale action (BLOCKSCALEACTION) ends with a byte after its three
/// connections that DXF doesn't carry. acadrust 0.6.4 neither read nor wrote it, so AutoCAD
/// read past the object and refused every DWG CADCraft wrote with a dynamic block that scales
+50 -5
View File
@@ -26,7 +26,7 @@ use super::Limits;
/// The argument that makes the app a worker.
pub const WORKER_ARG: &str = "--dwg-worker";
/// Bumped when the messages change: an app updated while running may start a newer copy.
const PROTOCOL: u8 = 1;
const PROTOCOL: u8 = 2;
const DECODE: u8 = 1;
const ENCODE: u8 = 2;
const CRASH: u8 = 0xff;
@@ -88,11 +88,29 @@ pub fn encode_as(dxf: &[u8], version: &str) -> Result<Vec<u8>, String> {
/// [`super::dxf_to_dwg_noted`] in the worker, when there is one. What the writer left out comes
/// back as notes of `TYPE<tab>count`.
pub fn encode_noted(dxf: &[u8], version: &str) -> Result<(Vec<u8>, super::Unwritten), String> {
encode_kept_noted(dxf, version, None)
}
/// [`encode_noted`] for a DXF whose carried-over groups were read from a file of version `kept`
/// ([`super::dxf_to_dwg_kept_noted`]); `None` is [`encode_noted`].
pub fn encode_kept_noted(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec<u8>, super::Unwritten), String> {
if u8::try_from(version.len()).is_err() {
return Err(super::unsupported(version));
}
match call(&request(ENCODE, Limits::DEFAULT, version), dxf, MAX_DWG_REPLY, "writing this file") {
// A kept version too long to send is no version CADCraft knows: it changes nothing.
let kept = kept.filter(|k| u8::try_from(k.len()).is_ok());
let mut header = request(ENCODE, Limits::DEFAULT, version);
push_str(&mut header, kept.unwrap_or(""));
match call(&header, dxf, MAX_DWG_REPLY, "writing this file") {
Some(reply) => reply?.map(|(dwg, notes)| (dwg, unwritten_from(&notes))),
None => encode_here(dxf, version, kept),
}
}
/// The conversion in this process.
fn encode_here(dxf: &[u8], version: &str, kept: Option<&str>) -> Result<(Vec<u8>, super::Unwritten), String> {
match kept {
Some(kept) => super::dxf_to_dwg_kept_noted(dxf, version, kept),
None => super::dxf_to_dwg_noted(dxf, version),
}
}
@@ -117,11 +135,16 @@ fn request(op: u8, limits: Limits, version: &str) -> Vec<u8> {
let mut r = vec![PROTOCOL, op];
r.extend((limits.max_dwg_bytes as u64).to_le_bytes());
r.extend((limits.max_dxf_bytes as u64).to_le_bytes());
r.push(u8::try_from(version.len()).unwrap_or(0));
r.extend(version.as_bytes());
push_str(&mut r, version);
r
}
/// `text` with a one-byte length before it; callers keep it under 256 bytes.
fn push_str(r: &mut Vec<u8>, text: &str) {
r.push(u8::try_from(text.len()).unwrap_or(0));
r.extend(text.as_bytes());
}
type Reply = Result<(Vec<u8>, Vec<String>), String>;
/// Run one request in a worker. `None`: none could be started, so the caller does the work.
@@ -257,7 +280,13 @@ fn handle(mut b: &[u8]) -> Reply {
let version = take(&mut b, usize::from(version_len)).and_then(|v| std::str::from_utf8(v).ok()).ok_or_else(bad)?;
match op {
DECODE => super::dwg_to_dxf_noted(b, Limits { max_dwg_bytes, max_dxf_bytes }),
ENCODE => super::dxf_to_dwg_noted(b, version).map(|(dwg, left_out)| (dwg, left_out.iter().map(|(kind, n)| format!("{kind}\t{n}")).collect())),
ENCODE => {
// The version the DXF's carried-over groups were read from; empty for none.
let kept_len = take(&mut b, 1).and_then(<[u8]>::first).copied().ok_or_else(bad)?;
let kept = take(&mut b, usize::from(kept_len)).and_then(|v| std::str::from_utf8(v).ok()).ok_or_else(bad)?;
encode_here(b, version, (!kept.is_empty()).then_some(kept))
.map(|(dwg, left_out)| (dwg, left_out.iter().map(|(kind, n)| format!("{kind}\t{n}")).collect()))
}
CRASH => std::process::abort(),
_ => Err(bad()),
}
@@ -322,6 +351,22 @@ mod tests {
}
}
/// An encode request carries the kept version after the target one; a request without it is
/// one it can't read, and one with it reaches the converter.
#[test]
fn an_encode_request_carries_the_kept_version() {
let bad = "the DWG worker got a request it can't read (a different CADCraft version?)";
let short = self::request(ENCODE, Limits::DEFAULT, "AC1032");
assert_eq!(handle(&short).unwrap_err(), bad);
for kept in ["", "AC1032"] {
let mut request = self::request(ENCODE, Limits::DEFAULT, "AC1032");
push_str(&mut request, kept);
request.extend(b"not a drawing");
let err = handle(&request).unwrap_err();
assert_ne!(err, bad, "kept {kept:?}");
}
}
#[test]
fn serving_reports_a_decode_failure_as_a_reply() {
let mut request = self::request(DECODE, Limits::DEFAULT, "");
+78 -10
View File
@@ -129,7 +129,7 @@ pub(crate) fn decode(bytes: &[u8], d: Decoder) -> Cow<'_, str> {
/// line (the group code `3` between them), looked for in the HEADER section only (the scan stops
/// at the first `ENDSEC`). Works on the raw bytes, before they are decoded.
fn ascii_code_page(bytes: &[u8]) -> Option<&[u8]> {
let mut lines = bytes.split(|&b| b == b'\n').map(<[u8]>::trim_ascii);
let mut lines = bytes.split(|&b| b == b'\n' || b == b'\r').map(<[u8]>::trim_ascii).filter(|l| !l.is_empty());
while let Some(line) = lines.next() {
if line == b"ENDSEC" {
return None;
@@ -144,10 +144,35 @@ fn ascii_code_page(bytes: &[u8]) -> Option<&[u8]> {
None
}
/// Decode a whole ASCII DXF file. Valid UTF-8 is read as UTF-8: R2007+ files, pure-ASCII files,
/// and older files from writers that ignored the code page. Anything else is decoded from the
/// file's `$DWGCODEPAGE`, or from Windows-1252 (the usual `ANSI_1252`) when the header has none
/// or names a code page CADCraft doesn't know, which is logged as a warning.
impl Decoder {
/// True for the multi-byte East Asian code pages (Shift-JIS, GBK, EUC-KR/Wansung, Big5).
/// Their short double-byte strings are often also valid UTF-8, so UTF-8 is only trusted for
/// a whole file there (see [`decode_ascii_file`] and [`BinaryText`]).
fn is_east_asian(self) -> bool {
use encoding_rs as e;
matches!(self, Decoder::Encoding(x) if x == e::SHIFT_JIS || x == e::GBK || x == e::EUC_KR || x == e::BIG5)
}
}
/// Decode one line of an ASCII DXF file: valid UTF-8 is read as UTF-8 (R2007+ files, pure-ASCII
/// text, and older files from writers that ignored the code page); anything else comes from the
/// code page `d`, so one stray byte spoils one line, not the whole file. Binary strings don't use
/// this rule: a pre-R2007 binary file has no way to escape to UTF-8, so its strings are read
/// from the code page (see [`BinaryText::string`]).
pub(crate) fn decode_text(bytes: &[u8], d: Decoder) -> Cow<'_, str> {
match std::str::from_utf8(bytes) {
Ok(s) => Cow::Borrowed(s),
Err(_) => decode(bytes, d),
}
}
/// Decode a whole ASCII DXF file. A file that is valid UTF-8 throughout is UTF-8. Otherwise, for
/// a single-byte code page, each line is decoded on its own (see [`decode_text`]): lines that
/// aren't valid UTF-8 come from the file's `$DWGCODEPAGE`, or from Windows-1252 (the usual
/// `ANSI_1252`) when the header has none or names a code page CADCraft doesn't know, which is
/// logged as a warning. For a multi-byte East Asian code page the whole file is decoded from
/// that code page, because a short double-byte string (two half-width katakana, many kanji
/// pairs) can be valid UTF-8 by accident and must not be misread line by line.
pub(crate) fn decode_ascii_file(bytes: &[u8]) -> Cow<'_, str> {
if let Ok(s) = std::str::from_utf8(bytes) {
return Cow::Borrowed(s);
@@ -162,10 +187,19 @@ pub(crate) fn decode_ascii_file(bytes: &[u8]) -> Cow<'_, str> {
}
None => Decoder::Utf8,
};
decode(bytes, d)
if d.is_east_asian() {
return decode(bytes, d);
}
// Split after each line terminator (CR, LF or CRLF are all ASCII, so they never occur inside
// a multi-byte character of the supported code pages) and decode each line on its own.
let mut out = String::with_capacity(bytes.len());
for line in bytes.split_inclusive(|&b| b == b'\n' || b == b'\r') {
out.push_str(&decode_text(line, d));
}
Cow::Owned(out)
}
/// The text state of a binary DXF file, learnt from its header as the tags go by: `$ACADVER`
/// The text state of a binary DXF file, learnt from the header as the tags go by: `$ACADVER`
/// (R2007+ strings are UTF-8) and `$DWGCODEPAGE` (the code page of older files). Both come
/// first in the HEADER section and are ASCII, so every later string is decoded right.
#[derive(Default)]
@@ -174,6 +208,12 @@ pub(crate) struct BinaryText {
var: Option<HeaderVar>,
utf8: bool,
code_page: Option<Decoder>,
/// Decode every string of an East Asian code page file from the code page, never as UTF-8
/// (the second pass of [`BinaryText::needs_code_page_pass`]).
code_page_only: bool,
/// Non-ASCII strings seen under an East Asian code page: valid UTF-8 / not valid UTF-8.
ea_utf8: bool,
ea_other: bool,
}
#[derive(Clone, Copy, PartialEq)]
@@ -183,12 +223,40 @@ enum HeaderVar {
}
impl BinaryText {
/// The state for the second pass over a file whose strings are a mix of valid UTF-8 and
/// not: every string of an East Asian code page is decoded from that code page.
pub(crate) fn code_page_pass() -> Self {
Self { code_page_only: true, ..Self::default() }
}
/// True when the file declared a multi-byte East Asian code page and its non-ASCII strings are
/// not all valid UTF-8 although some are: those can be short double-byte strings that look
/// like UTF-8 by accident, so the file must be parsed again with [`Self::code_page_pass`]. (A
/// file whose strings are all valid UTF-8 is UTF-8; one with none is plainly the code page.)
pub(crate) fn needs_code_page_pass(&self) -> bool {
!self.code_page_only && self.ea_utf8 && self.ea_other
}
/// Decode one string value of group `code` and update the state from it. Strings of R2007+
/// files, and of files without a code page, are UTF-8 when valid (else Windows-1252); older
/// files' strings are in their code page.
/// files, and of files without a code page, are UTF-8 when valid (else Windows-1252); a
/// pre-R2007 file's strings are in its code page, which a binary DXF cannot escape to, so
/// they are read from the code page even when their bytes are valid UTF-8 by accident —
/// except under an East Asian code page, where a file of all-valid-UTF-8 strings is taken
/// as UTF-8 (see [`Self::needs_code_page_pass`]).
pub(crate) fn string(&mut self, code: i32, raw: &[u8]) -> String {
let d = if self.utf8 { Decoder::Utf8 } else { self.code_page.unwrap_or(Decoder::Utf8) };
let s = decode(raw, d).into_owned();
let s = if d.is_east_asian() && !self.code_page_only {
if !raw.is_ascii() {
if std::str::from_utf8(raw).is_ok() {
self.ea_utf8 = true;
} else {
self.ea_other = true;
}
}
decode_text(raw, d).into_owned()
} else {
decode(raw, d).into_owned()
};
match (code, self.var.take()) {
(9, _) => {
self.var = match s.trim() {
+118 -20
View File
@@ -65,7 +65,9 @@ impl Value {
match self {
Value::Int(i) => *i,
Value::Real(r) if r.is_finite() => *r as i64,
Value::Str(s) => s.trim().parse::<i64>().unwrap_or_else(|_| s.trim().parse::<f64>().map(|f| f as i64).unwrap_or(0)),
Value::Str(s) => {
s.trim().parse::<i64>().unwrap_or_else(|_| s.trim().parse::<f64>().ok().filter(|f| f.is_finite()).map_or(0, |f| f as i64))
}
Value::Bool(b) => i64::from(*b),
_ => 0,
}
@@ -157,15 +159,26 @@ fn typed(code: i32, text: &str) -> Value {
match kind_of(code) {
Kind::Real => t.parse::<f64>().ok().filter(|v| v.is_finite()).map(Value::Real).unwrap_or(Value::Real(0.0)),
Kind::Int16 | Kind::Int32 | Kind::Int64 => {
t.parse::<i64>().map(Value::Int).unwrap_or_else(|_| Value::Int(t.parse::<f64>().map(|f| f as i64).unwrap_or(0)))
// A float spelling ("1e3", "12.0") is accepted when finite, clamped to what the
// group's width holds, signed or unsigned (files write 16-bit flags up to 65535, as
// the integer spelling reads them); NaN, inf and text become 0.
let (lo, hi) = match kind_of(code) {
Kind::Int16 => (i64::from(i16::MIN), i64::from(u16::MAX)),
Kind::Int32 => (i64::from(i32::MIN), i64::from(u32::MAX)),
_ => (i64::MIN, i64::MAX),
};
t.parse::<i64>()
.map(Value::Int)
.unwrap_or_else(|_| Value::Int(t.parse::<f64>().ok().filter(|f| f.is_finite()).map_or(0, |f| (f as i64).clamp(lo, hi))))
}
Kind::Bool => Value::Bool(t.parse::<i64>().unwrap_or(0) != 0),
Kind::Hex => Value::Hex(t.to_string()),
Kind::Hex => Value::Hex(normalize_hex(t)),
Kind::Str => Value::Str(text.trim_end_matches(['\r', '\n']).to_string()),
}
}
const BINARY_SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0";
const UTF8_BOM: &[u8] = b"\xEF\xBB\xBF";
/// Most group codes read from one file by default. A `Tag` takes 40 bytes plus its text, so this
/// bounds the tag list to about 4 GB plus text. 50 million rejected large DWGs that converted fine
/// (a 172 MB drawing has 56 million, issue #1948). The file-size limits bound memory too: 512 MB
@@ -201,8 +214,10 @@ pub fn parse_with_limit(bytes: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
if let Some(body) = bytes.strip_prefix(BINARY_SENTINEL) {
return parse_binary_with_limit(body, max_tags);
}
// Count nonblank group-code/value pairs, stopping at EOF just as the parser does.
let mut lines = bytes.split(|&b| b == b'\n');
let bytes = bytes.strip_prefix(UTF8_BOM).unwrap_or(bytes);
// Count nonblank group-code/value pairs (LF, CRLF and a lone CR each end a line), stopping at
// EOF just as the parser does. Blank lines do not count toward the limit.
let mut lines = byte_lines(bytes);
let mut tags = 0;
while let Some(code) = lines.next() {
let code = code.trim_ascii();
@@ -289,6 +304,39 @@ fn unescape_unicode(s: &str) -> String {
out
}
/// The lines of an ASCII DXF text: LF, CRLF and a lone CR (old Mac files) all end a line, like
/// [`str::lines`] otherwise (no empty line after a final terminator).
fn ascii_lines(text: &str) -> impl Iterator<Item = &str> {
let mut rest = text;
std::iter::from_fn(move || {
if rest.is_empty() {
return None;
}
let end = rest.find(['\r', '\n']).unwrap_or(rest.len());
let line = rest.get(..end).unwrap_or_default();
let after = rest.get(end..).unwrap_or_default();
rest = after.strip_prefix("\r\n").or_else(|| after.strip_prefix(['\r', '\n'])).unwrap_or(after);
Some(line)
})
}
/// Byte-level twin of [`ascii_lines`] for the up-front limit check, so the count matches the parser.
fn byte_lines(mut rest: &[u8]) -> impl Iterator<Item = &[u8]> {
std::iter::from_fn(move || {
if rest.is_empty() {
return None;
}
let end = rest.iter().position(|&b| b == b'\r' || b == b'\n').unwrap_or(rest.len());
let line = &rest[..end];
let after = &rest[end..];
rest = match after {
[b'\r', b'\n', tail @ ..] | [b'\r' | b'\n', tail @ ..] => tail,
_ => after,
};
Some(line)
})
}
pub fn parse_ascii(text: &str) -> Result<Vec<Tag>> {
parse_ascii_counted(text, max_tags(), 0)
}
@@ -301,7 +349,7 @@ pub fn parse_ascii(text: &str) -> Result<Vec<Tag>> {
fn parse_ascii_counted(text: &str, max_tags: usize, expected: usize) -> Result<Vec<Tag>> {
let mut tags = Vec::new();
tags.try_reserve_exact(expected.min(max_tags)).map_err(|_| DxfError::OutOfMemory { tags: expected })?;
let mut lines = text.strip_prefix('\u{feff}').unwrap_or(text).lines().enumerate();
let mut lines = ascii_lines(text.strip_prefix('\u{feff}').unwrap_or(text)).enumerate();
loop {
let Some((ln, code_line)) = lines.next() else { break };
let ct = code_line.trim();
@@ -319,7 +367,7 @@ fn parse_ascii_counted(text: &str, max_tags: usize, expected: usize) -> Result<V
if tags.len() > max_tags {
return Err(DxfError::TooLarge { tags: tags.len(), limit: max_tags });
}
if code == 0 && tags.last().is_some_and(|t| t.str() == "EOF") {
if code == 0 && tags.last().is_some_and(|t| t.str().trim_end() == "EOF") {
break;
}
}
@@ -385,8 +433,19 @@ pub fn parse_binary(b: &[u8]) -> Result<Vec<Tag>> {
}
fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
let mut c = Cur { b, p: 0 };
let mut text = codepage::BinaryText::default();
let tags = parse_binary_pass(b, max_tags, &mut text)?;
if !text.needs_code_page_pass() {
return Ok(tags);
}
// The first pass's tags go before the second pass runs: both held at once would double
// the peak near the tag limit.
drop(tags);
parse_binary_pass(b, max_tags, &mut codepage::BinaryText::code_page_pass())
}
fn parse_binary_pass(b: &[u8], max_tags: usize, text: &mut codepage::BinaryText) -> Result<Vec<Tag>> {
let mut c = Cur { b, p: 0 };
let mut tags = Vec::new();
while c.p < b.len() {
let mut code = i32::from(c.i16()?);
@@ -395,7 +454,7 @@ fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
}
let v = match kind_of(code) {
Kind::Str => Value::Str(unescape_unicode(&text.string(code, c.cstr()?))),
Kind::Real => Value::Real(c.f64()?),
Kind::Real => Value::Real(Some(c.f64()?).filter(|v| v.is_finite()).unwrap_or(0.0)),
Kind::Int16 => Value::Int(i64::from(c.i16()?)),
Kind::Int32 => Value::Int(i64::from(c.i32()?)),
Kind::Int64 => Value::Int(c.i64()?),
@@ -410,7 +469,7 @@ fn parse_binary_with_limit(b: &[u8], max_tags: usize) -> Result<Vec<Tag>> {
Value::Hex(s)
}
};
let eof = code == 0 && matches!(&v, Value::Str(s) if s == "EOF");
let eof = code == 0 && matches!(&v, Value::Str(s) if s.trim_end() == "EOF");
tags.push(Tag { code, value: v });
if tags.len() > max_tags {
return Err(DxfError::TooLarge { tags: tags.len(), limit: max_tags });
@@ -485,7 +544,22 @@ fn ascii(tags: &[Tag], strings: Strings) -> Vec<u8> {
Value::Real(r) => out.extend_from_slice(format_real(*r).as_bytes()),
Value::Int(i) => out.extend_from_slice(i.to_string().as_bytes()),
Value::Bool(b) => out.extend_from_slice(i64::from(*b).to_string().as_bytes()),
Value::Hex(h) => out.extend_from_slice(h.as_bytes()),
Value::Hex(h) => {
// The DXF Reference limits a binary chunk line to 254 hex digits (127 bytes);
// longer data continues in further groups of the same code. Only hex digits are
// written, so a hostile value can't inject tags.
let digits = normalize_hex(h);
let mut chunks: Vec<&str> = digits.as_bytes().chunks(254).map(|c| std::str::from_utf8(c).unwrap_or_default()).collect();
if chunks.is_empty() {
chunks.push("");
}
for (n, chunk) in chunks.into_iter().enumerate() {
if n > 0 {
let _ = write!(out, "\r\n{:>3}\r\n", t.code);
}
out.extend_from_slice(chunk.as_bytes());
}
}
}
out.extend_from_slice(b"\r\n");
}
@@ -533,13 +607,11 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec<u8> {
}
Kind::Int16 => {
out.extend_from_slice(&code_bytes);
let v = t.value.as_i64().clamp(i64::from(i16::MIN), i64::from(i16::MAX));
out.extend_from_slice(&i16::try_from(v).unwrap_or_default().to_le_bytes());
out.extend_from_slice(&wrap_i16(t.value.as_i64()));
}
Kind::Int32 => {
out.extend_from_slice(&code_bytes);
let v = t.value.as_i64().clamp(i64::from(i32::MIN), i64::from(i32::MAX));
out.extend_from_slice(&i32::try_from(v).unwrap_or_default().to_le_bytes());
out.extend_from_slice(&wrap_i32(t.value.as_i64()));
}
Kind::Int64 => {
out.extend_from_slice(&code_bytes);
@@ -567,12 +639,38 @@ fn binary(tags: &[Tag], strings: Strings) -> Vec<u8> {
out
}
/// The bytes of hex text, two digits each; anything that isn't a pair of hex digits is skipped.
/// Hex text cleaned up: only the hex digits are kept, and an odd trailing digit is padded with
/// `0` (so the bytes before it are never shifted). Used by the reader and both writers.
fn normalize_hex(s: &str) -> String {
let mut out: String = s.chars().filter(char::is_ascii_hexdigit).collect();
if out.len() % 2 == 1 {
out.push('0');
}
out
}
/// The bytes of hex text, two digits each (see [`normalize_hex`]).
fn hex_bytes(s: &str) -> Vec<u8> {
let digits: Vec<u8> = s.bytes().filter_map(|b| char::from(b).to_digit(16).and_then(|d| u8::try_from(d).ok())).collect();
let digits: Vec<u8> = normalize_hex(s).bytes().filter_map(|b| char::from(b).to_digit(16).and_then(|d| u8::try_from(d).ok())).collect();
digits.as_chunks::<2>().0.iter().map(|[hi, lo]| (hi << 4) | lo).collect()
}
/// A 16- or 32-bit integer for binary DXF: values that fit the unsigned width wrap into the
/// signed one (65535 is -1, as writers that store unsigned flags expect); anything else clamps.
fn wrap_i16(v: i64) -> [u8; 2] {
match u16::try_from(v) {
Ok(u) => u.to_le_bytes(),
Err(_) => i16::try_from(v.clamp(i64::from(i16::MIN), i64::from(i16::MAX))).unwrap_or_default().to_le_bytes(),
}
}
fn wrap_i32(v: i64) -> [u8; 4] {
match u32::try_from(v) {
Ok(u) => u.to_le_bytes(),
Err(_) => i32::try_from(v.clamp(i64::from(i32::MIN), i64::from(i32::MAX))).unwrap_or_default().to_le_bytes(),
}
}
/// Whether `bytes` are a binary DXF file (they start with the binary sentinel).
pub fn is_binary(bytes: &[u8]) -> bool {
bytes.starts_with(BINARY_SENTINEL)
@@ -634,12 +732,12 @@ pub fn sections(tags: &[Tag]) -> Vec<Section> {
let mut out = Vec::new();
let mut i = 0;
while i < tags.len() {
let is_sec = tags.get(i).is_some_and(|t| t.code == 0 && t.str() == "SECTION");
let is_sec = tags.get(i).is_some_and(|t| t.code == 0 && t.str().trim_end() == "SECTION");
if is_sec {
let name = tags.get(i + 1).filter(|t| t.code == 2).map(Tag::str).unwrap_or_default();
let name = tags.get(i + 1).filter(|t| t.code == 2).map(|t| t.str().trim_end().to_string()).unwrap_or_default();
let start = i + 2;
let mut j = start;
while j < tags.len() && !(tags.get(j).is_some_and(|t| t.code == 0 && t.str() == "ENDSEC")) {
while j < tags.len() && !(tags.get(j).is_some_and(|t| t.code == 0 && t.str().trim_end() == "ENDSEC")) {
j += 1;
}
out.push(Section { name, tags: tags.get(start..j).unwrap_or(&[]).to_vec() });
+220
View File
@@ -0,0 +1,220 @@
//! Hostile-input hardening of the DXF reader and writer (#1025): one regression test per finding.
use cadcraft_dxf::{Tag, Value, parse, parse_with_limit, sections, write_ascii, write_binary};
const SENTINEL: &[u8] = b"AutoCAD Binary DXF\r\n\x1a\0";
fn bin_with(f: impl FnOnce(&mut Vec<u8>)) -> Vec<u8> {
let mut b = SENTINEL.to_vec();
f(&mut b);
b.extend_from_slice(&0i16.to_le_bytes());
b.extend_from_slice(b"EOF\0");
b
}
#[test]
fn binary_reals_that_are_not_finite_become_zero() {
for bits in [f64::NAN, f64::INFINITY, f64::NEG_INFINITY] {
let b = bin_with(|b| {
b.extend_from_slice(&10i16.to_le_bytes());
b.extend_from_slice(&bits.to_le_bytes());
});
let tags = parse(&b).unwrap();
assert_eq!(tags[0], Tag::f(10, 0.0), "{bits}");
}
}
#[test]
fn ascii_accepts_bom_and_cr_only_line_ends() {
let want = vec![Tag::s(0, "SECTION"), Tag::s(2, "ENTITIES"), Tag::s(0, "ENDSEC"), Tag::s(0, "EOF")];
let text = "0\rSECTION\r2\rENTITIES\r0\rENDSEC\r0\rEOF\r";
assert_eq!(parse(text.as_bytes()).unwrap(), want);
let mut bom = b"\xEF\xBB\xBF".to_vec();
bom.extend_from_slice(text.replace('\r', "\r\n").as_bytes());
assert_eq!(parse(&bom).unwrap(), want);
// Mixed terminators.
assert_eq!(parse(b"0\r\nSECTION\r2\nENTITIES\n0\rENDSEC\r\n0\nEOF").unwrap(), want);
}
#[test]
fn cr_only_files_count_against_the_tag_limit() {
let mut text = String::new();
for _ in 0..50 {
text.push_str("999\rcomment\r");
}
text.push_str("0\rEOF\r");
assert!(parse_with_limit(text.as_bytes(), 10).is_err());
assert_eq!(parse_with_limit(text.as_bytes(), 100).unwrap().len(), 51);
}
#[test]
fn one_bad_byte_spoils_one_line_not_the_file() {
// Header says ANSI_1251; one line is UTF-8, one is Windows-1251, one has a stray byte.
let mut b = b"9\n$DWGCODEPAGE\n3\nANSI_1251\n1\n".to_vec();
b.extend_from_slice("Größe".as_bytes());
b.extend_from_slice(b"\n1\n\xCF\xF0\xE8\xE2\xE5\xF2\n0\nEOF\n");
let t = parse(&b).unwrap();
assert_eq!(t[1].str(), "ANSI_1251");
assert_eq!(t[2].str(), "Größe");
assert_eq!(t[3].str(), "Привет");
}
#[test]
fn ascii_uses_utf8_per_line_and_binary_stays_in_the_code_page() {
// ANSI_1252 file with UTF-8 bytes in one string and a Latin-1 byte in another. The ASCII
// reader takes a line that is valid UTF-8 as UTF-8; the binary reader reads every string
// from the code page, because a pre-R2007 binary file has no way to escape to UTF-8.
let utf8 = "Größe".as_bytes();
let latin = b"Caf\xE9";
let mut a = b"9\n$DWGCODEPAGE\n3\nANSI_1252\n1\n".to_vec();
a.extend_from_slice(utf8);
a.extend_from_slice(b"\n1\n");
a.extend_from_slice(latin);
a.extend_from_slice(b"\n0\nEOF\n");
let from_ascii = parse(&a).unwrap();
let b = bin_with(|b| {
for (code, s) in [(9i16, &b"$DWGCODEPAGE"[..]), (3, b"ANSI_1252"), (1, utf8), (1, latin)] {
b.extend_from_slice(&code.to_le_bytes());
b.extend_from_slice(s);
b.push(0);
}
});
let from_binary = parse(&b).unwrap();
assert_eq!(from_ascii[2].str(), "Größe");
assert_eq!(from_ascii[3].str(), "Café");
assert_eq!(from_binary[2].str(), "Größe");
assert_eq!(from_binary[3].str(), "Café");
}
#[test]
fn trailing_spaces_keep_sections_and_eof() {
let t = parse(b"0\nSECTION \n2\nENTITIES \n0\nLINE\n0\nENDSEC \n0\nEOF \n0\nSECTION\n2\nX\n0\nENDSEC\n").unwrap();
// The EOF with a trailing space still ends the file.
assert_eq!(t.len(), 5);
let s = sections(&t);
assert_eq!(s.len(), 1);
assert_eq!(s[0].name, "ENTITIES");
assert_eq!(s[0].tags.len(), 1);
// Binary EOF too.
let mut b = SENTINEL.to_vec();
b.extend_from_slice(&0i16.to_le_bytes());
b.extend_from_slice(b"EOF \0");
b.extend_from_slice(&1i16.to_le_bytes());
b.extend_from_slice(b"after\0");
assert_eq!(parse(&b).unwrap().len(), 1);
}
#[test]
fn integer_groups_reject_non_finite_and_clamp() {
let t = parse(b"70\ninf\n70\nNaN\n70\n1e30\n70\n-1e30\n90\n1e30\n160\n1e30\n160\n-inf\n62\n12.0\n0\nEOF\n").unwrap();
assert_eq!(t[0], Tag::i(70, 0));
assert_eq!(t[1], Tag::i(70, 0));
// Clamped to what the group's width holds, unsigned values included (the binary writer
// keeps up to 65535 and 4294967295 as their bit patterns).
assert_eq!(t[2], Tag::i(70, i64::from(u16::MAX)));
assert_eq!(t[3], Tag::i(70, i64::from(i16::MIN)));
assert_eq!(t[4], Tag::i(90, i64::from(u32::MAX)));
assert_eq!(t[5], Tag::i(160, i64::MAX));
assert_eq!(t[6], Tag::i(160, 0));
assert_eq!(t[7], Tag::i(62, 12));
assert_eq!(Value::Str("inf".into()).as_i64(), 0);
}
/// An unsigned value spelled as a float reads as the same spelled as an integer (#1026 review):
/// `65535.0` is 65535 like `65535`, not 32767.
#[test]
fn unsigned_values_read_the_same_in_either_spelling() {
let t = parse(b"70\n65535.0\n70\n65535\n90\n4294967295.0\n90\n4294967295\n0\nEOF\n").unwrap();
assert_eq!(t[0], t[1]);
assert_eq!(t[0], Tag::i(70, 65535));
assert_eq!(t[2], t[3]);
assert_eq!(t[2], Tag::i(90, 4_294_967_295));
}
#[test]
fn hex_groups_pad_odd_digits_and_drop_junk() {
let t = parse(b"310\nABC\n310\nA-B zC1\n310\n\n1004\n0aF\n0\nEOF\n").unwrap();
assert_eq!(t[0].value, Value::Hex("ABC0".into()));
assert_eq!(t[1].value, Value::Hex("ABC1".into()));
assert_eq!(t[2].value, Value::Hex(String::new()));
assert_eq!(t[3].value, Value::Hex("0aF0".into()));
// The binary writer agrees with the reader: the odd digit is padded, nothing shifts.
let back = parse(&write_binary(&[Tag::new(310, Value::Hex("ABC".into())), Tag::s(0, "EOF")], true)).unwrap();
assert_eq!(back[0].value, Value::Hex("ABC0".into()));
}
#[test]
fn ascii_hex_cannot_inject_tags_and_is_split_at_254_digits() {
let evil = Tag::new(310, Value::Hex("AB\r\n0\r\nEOF".into()));
let text = write_ascii(&[evil, Tag::s(0, "EOF")]);
let back = parse(text.as_bytes()).unwrap();
assert_eq!(back.len(), 2, "{text:?}");
assert_eq!(back[0].value, Value::Hex("AB0EF0".into()));
let long = "AB".repeat(300);
let back = parse(write_ascii(&[Tag::new(310, Value::Hex(long)), Tag::s(0, "EOF")]).as_bytes()).unwrap();
let sizes: Vec<usize> = back.iter().filter(|t| t.code == 310).map(|t| t.str().len()).collect();
assert_eq!(sizes, vec![254, 254, 92]);
// An empty chunk is still one group.
let back = parse(write_ascii(&[Tag::new(310, Value::Hex(String::new())), Tag::s(0, "EOF")]).as_bytes()).unwrap();
assert_eq!(back[0].code, 310);
}
#[test]
fn binary_sixteen_and_thirty_two_bit_values_wrap_in_range_and_clamp_outside() {
let tags = [
Tag::i(70, 65535),
Tag::i(70, 40000),
Tag::i(70, 70000),
Tag::i(70, -40000),
Tag::i(90, 0xFFFF_FFFF),
Tag::i(90, 1 << 40),
Tag::i(90, -(1 << 40)),
Tag::s(0, "EOF"),
];
let back = parse(&write_binary(&tags, true)).unwrap();
assert_eq!(back[0], Tag::i(70, -1));
assert_eq!(back[1], Tag::i(70, 40000 - 65536));
assert_eq!(back[2], Tag::i(70, i64::from(i16::MAX)));
assert_eq!(back[3], Tag::i(70, i64::from(i16::MIN)));
assert_eq!(back[4], Tag::i(90, -1));
assert_eq!(back[5], Tag::i(90, i64::from(i32::MAX)));
assert_eq!(back[6], Tag::i(90, i64::from(i32::MIN)));
}
/// Strings of a `$DWGCODEPAGE`-declared file as ASCII text and as a binary file.
fn both_forms(code_page: &str, strings: &[&[u8]]) -> [Vec<Tag>; 2] {
let mut a = format!("9\n$DWGCODEPAGE\n3\n{code_page}\n").into_bytes();
for s in strings {
a.extend_from_slice(b"1\n");
a.extend_from_slice(s);
a.push(b'\n');
}
a.extend_from_slice(b"0\nEOF\n");
let b = bin_with(|b| {
for (code, s) in [(9i16, &b"$DWGCODEPAGE"[..]), (3, code_page.as_bytes())].into_iter().chain(strings.iter().map(|s| (1, *s))) {
b.extend_from_slice(&code.to_le_bytes());
b.extend_from_slice(s);
b.push(0);
}
});
[parse(&a).unwrap(), parse(&b).unwrap()]
}
#[test]
fn east_asian_short_strings_that_look_like_utf8_stay_in_the_code_page() {
// C3 B1 is valid UTF-8 ("ñ") but is also two half-width katakana in Shift-JIS; the second
// string is plainly Shift-JIS, so the file is not UTF-8.
for t in both_forms("ANSI_932", &[b"\xC3\xB1", b"\x90\x7D\x96\xCA"]) {
assert_eq!(t[2].str(), "\u{FF83}\u{FF71}");
assert_eq!(t[3].str(), "図面");
}
}
#[test]
fn east_asian_file_that_is_all_utf8_reads_as_utf8() {
for t in both_forms("ANSI_932", &["図面".as_bytes(), b"\xC3\xB1", b"plain"]) {
assert_eq!(t[2].str(), "図面");
assert_eq!(t[3].str(), "ñ");
assert_eq!(t[4].str(), "plain");
}
}
+75 -10
View File
@@ -40,8 +40,12 @@ fn arc_geom(a: &cadcraft_doc::Arc) -> cadcraft_geom::Arc {
/// Where a snap sits on an object now.
pub fn snap_point(d: &Drawing, a: &DimAssoc) -> Option<Vec2> {
let e = d.entity(a.handle)?;
match (&e.kind, &a.snap) {
snap_on(d, &d.entity(a.handle)?.kind, &a.snap)
}
/// Where `snap` sits on an object of kind `kind` (an intersection finds its other line in `d`).
fn snap_on(d: &Drawing, kind: &EntityKind, snap: &AssocSnap) -> Option<Vec2> {
match (kind, snap) {
(EntityKind::Line(l), AssocSnap::Start) => Some(l.a.xy()),
(EntityKind::Line(l), AssocSnap::End) => Some(l.b.xy()),
(EntityKind::Line(l), AssocSnap::Mid) => Some(l.a.xy().mid(l.b.xy())),
@@ -88,6 +92,61 @@ fn candidates(kind: &EntityKind) -> Vec<(AssocSnap, Vec2)> {
}
}
/// Whether two snaps are the same kind of object point: an endpoint or vertex, a centre, or a
/// midpoint.
fn same_kind(a: &AssocSnap, b: &AssocSnap) -> bool {
matches!(
(a, b),
(AssocSnap::Start | AssocSnap::End | AssocSnap::Vertex { .. }, AssocSnap::Start | AssocSnap::End | AssocSnap::Vertex { .. })
| (AssocSnap::Center, AssocSnap::Center)
| (AssocSnap::Mid, AssocSnap::Mid)
)
}
/// BREAK or TRIM reshaped the object `pieces[0]` (which was `old`) and added the other pieces:
/// move the dimension attachments on it as AutoCAD 2024 does. An attachment whose point is still
/// a point of the same kind on the object stays there (a closed polyline opened by BREAK numbers
/// its vertices from the break); one whose point is on a new piece moves to that piece, so a
/// dimension across a line broken in its middle stays where it was; any other is left as it was,
/// so the dimension follows the object's new end when that end was cut off. Attachments at an
/// angle on a circle or arc and at an intersection stay on the object. [`update`] moves the
/// definition points after the command.
pub fn follow_pieces(d: &mut Drawing, old: &EntityKind, pieces: &[Handle]) {
let Some(&h) = pieces.first() else { return };
let mut changes: Vec<(Handle, Vec<DimAssoc>)> = Vec::new();
for store in std::iter::once(&d.model).chain(d.layouts.iter().map(|l| &l.entities)) {
for e in store.iter() {
let EntityKind::Dimension(dm) = &e.kind else { continue };
if !dm.assoc.iter().any(|a| a.handle == h) {
continue;
}
let assoc: Vec<DimAssoc> = dm.assoc.iter().map(|a| on_piece(d, old, pieces, a).unwrap_or_else(|| a.clone())).collect();
if assoc != dm.assoc {
changes.push((e.handle, assoc));
}
}
}
for (dh, assoc) in changes {
let _ = d.modify_entity(dh, |e| {
if let EntityKind::Dimension(dm) = &mut e.kind {
dm.assoc = assoc;
}
});
}
}
/// The piece attachment `a` moves to when its object became `pieces` (see [`follow_pieces`]).
fn on_piece(d: &Drawing, old: &EntityKind, pieces: &[Handle], a: &DimAssoc) -> Option<DimAssoc> {
if pieces.first() != Some(&a.handle) || matches!(a.snap, AssocSnap::OnCircle { .. } | AssocSnap::Intersection { .. }) {
return None;
}
let p = snap_on(d, old, &a.snap)?;
pieces.iter().find_map(|&ph| {
let (snap, _) = candidates(&d.entity(ph)?.kind).into_iter().find(|(s, q)| same_kind(&a.snap, s) && close(p, *q))?;
Some(DimAssoc { point: a.point.clone(), handle: ph, snap })
})
}
/// An object point exactly at `p` (an endpoint, vertex, centre or midpoint) to attach to.
pub fn find_snap(d: &Drawing, space: &Space, p: Vec2) -> Option<(Handle, AssocSnap)> {
if !p.is_finite() {
@@ -244,8 +303,10 @@ pub fn recompute(dm: &Dimension, prev: Option<&Dimension>, before: &Drawing, aft
let was = prev.unwrap_or(dm);
nd.assoc.retain(|a| {
let Some(old) = def_point(was, &a.point) else { return false };
// Only follow if the point sat on the object before the change.
if let Some(prev) = snap_point(before, a)
// Only follow if the point sat on the object before the change, as attached then (BREAK
// and TRIM may have moved the attachment to a piece of the object since).
let held = was.assoc.iter().find(|o| o.point == a.point).unwrap_or(a);
if let Some(prev) = snap_point(before, held)
&& !close(prev, old.xy())
{
return false;
@@ -304,16 +365,20 @@ pub fn update(after: &mut Arc<Drawing>, before: &Drawing) -> usize {
if dm.assoc.is_empty() {
continue;
}
let touched = dm.assoc.iter().any(|a| {
src_changed(before, d, a.handle) || matches!(a.snap, AssocSnap::Intersection { other } if src_changed(before, d, other))
});
if !touched {
continue;
}
let prev = match before.entity(e.handle).map(|x| &x.kind) {
Some(EntityKind::Dimension(p)) => Some(p),
_ => None,
};
// Its objects changed, or the command moved an attachment (BREAK and TRIM move them
// to new pieces, which a later pick of the same TRIM may reshape again).
let touched = dm.assoc.iter().any(|a| {
src_changed(before, d, a.handle)
|| matches!(a.snap, AssocSnap::Intersection { other } if src_changed(before, d, other))
|| prev.is_some_and(|p| !p.assoc.contains(a))
});
if !touched {
continue;
}
let nd = recompute(dm, prev, before, d);
if nd != *dm {
changes.push((e.handle, nd));
+58 -6
View File
@@ -405,10 +405,11 @@ mod native {
pub fn prune_locks(dir: &Path) {
let Ok(entries) = std::fs::read_dir(dir) else { return };
let names: Vec<String> = entries.flatten().take(10_000).map(|e| e.file_name().to_string_lossy().to_string()).collect();
// The instances that own autosave files, parsed once rather than once per lock file.
let with_files: std::collections::HashSet<&str> = names.iter().filter_map(|f| parse_file_name(f)).map(|(_, i, _)| i).collect();
for n in &names {
let Some(instance) = parse_lock_name(n) else { continue };
let has_files = names.iter().any(|f| parse_file_name(f).is_some_and(|(_, i, _)| i == instance));
if !has_files && !owner_alive(dir, instance) {
if !with_files.contains(instance) && !owner_alive(dir, instance) {
let _ = std::fs::remove_file(dir.join(n));
}
}
@@ -435,7 +436,22 @@ mod native {
}
// Create a fresh temporary file exclusively and rename it into place, so a planted
// `<path>.tmp` symlink in a shared autosave directory cannot redirect the write (CWE-59).
crate::atomic_write::write_atomic(Path::new(path), &bytes).map_err(|e| e.to_string())
// The file holds unsaved work: owner-only from its creation, whatever the umask.
crate::atomic_write::write_atomic_with(Path::new(path), private_mode(), |f| f.write_all(&bytes)).map_err(|e| e.to_string())
}
/// Owner read/write only (`None` where file modes don't exist).
fn private_mode() -> Option<std::fs::Permissions> {
#[cfg(unix)]
return Some(std::os::unix::fs::PermissionsExt::from_mode(0o600));
#[cfg(not(unix))]
None
}
/// Write this app's lock file at `path` without following a link planted there: the file is
/// replaced (exclusive temporary file, then rename), never written through (CWE-59).
fn write_lock(path: &Path, id: u32) -> std::io::Result<()> {
crate::atomic_write::write_atomic_with(path, private_mode(), |f| f.write_all(id.to_string().as_bytes()))
}
impl Autosaver {
@@ -586,7 +602,7 @@ mod native {
for (held, file) in &self.locks {
let refreshed = match file {
Some(file) => file.set_modified(SystemTime::now()),
None => std::fs::write(held, id.to_string()),
None => write_lock(held, id),
};
if held == path {
current = Some(refreshed);
@@ -595,10 +611,22 @@ mod native {
if let Some(refreshed) = current {
return refreshed;
}
let mut file = OpenOptions::new().write(true).create(true).truncate(false).open(path)?;
let mut options = OpenOptions::new();
options.write(true).create(true).truncate(false);
#[cfg(unix)]
{
use std::os::unix::fs::OpenOptionsExt;
// A symlink planted at the lock path must not be opened (and truncated) through,
// nor a FIFO wait for a reader.
options.custom_flags(libc::O_NOFOLLOW | libc::O_NONBLOCK).mode(0o600);
}
let mut file = options.open(path)?;
if !file.metadata()?.is_file() {
return Err(std::io::Error::new(std::io::ErrorKind::InvalidInput, "the lock file is not a plain file"));
}
if file.try_lock().is_err() {
self.locks.push((path.to_path_buf(), None));
return std::fs::write(path, id.to_string());
return write_lock(path, id);
}
file.set_len(0)?;
file.write_all(format!("{id}{LOCK_HELD}").as_bytes())?;
@@ -627,6 +655,30 @@ mod native {
}
}
}
#[cfg(all(test, unix))]
mod tests {
use super::*;
/// A symlink planted at the lock path is neither opened through nor written through.
#[test]
fn lock_writes_do_not_follow_a_planted_link() {
let dir = std::env::temp_dir().join(format!("cadcraft-lock-link-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let victim = dir.join("victim.txt");
std::fs::write(&victim, b"precious").unwrap();
let link = dir.join("1-a.lock");
std::os::unix::fs::symlink(&victim, &link).unwrap();
let mut a = Autosaver::new("1-a");
assert!(a.refresh_lock(&link).is_err());
assert_eq!(std::fs::read(&victim).unwrap(), b"precious");
write_lock(&link, 42).unwrap();
assert_eq!(std::fs::read(&victim).unwrap(), b"precious");
assert!(!std::fs::symlink_metadata(&link).unwrap().file_type().is_symlink());
assert_eq!(std::fs::read(&link).unwrap(), b"42");
std::fs::remove_dir_all(dir).unwrap();
}
}
}
#[cfg(test)]
+2
View File
@@ -18,6 +18,7 @@ mod gripcmds;
mod griphot;
pub(crate) mod groups;
pub(crate) mod hatch;
mod image;
mod inquiry;
mod layer;
mod layout;
@@ -200,6 +201,7 @@ pub fn command_specs() -> &'static [CommandSpec] {
v.extend(layer::specs());
v.extend(layout::specs());
v.extend(exchange::specs());
v.extend(image::specs());
v.extend(props::specs());
v.extend(inquiry::specs());
v.extend(settings::specs());
+10 -2
View File
@@ -159,6 +159,7 @@ pub(crate) fn make_assoc(s: &mut Session, objs: &[Handle], base: Vec2, mut p: Ar
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}))
}
@@ -247,9 +248,16 @@ fn max_count(s: &Session, others: u64, objs: usize) -> u64 {
}
fn copy_all(s: &mut Session, hs: &[Handle], mats: impl Iterator<Item = Mat3>) -> Result<usize> {
// Every copy is checked before the first is made: a refusal part way would leave the copies
// already added in the drawing (a failed command is not rolled back).
let mats: Vec<Mat3> = mats.collect();
// A matrix every frame accepts needs no look at the objects; otherwise they are looked at once.
if mats.iter().any(|m| !cadcraft_doc::ole_frame_accepts(m)) && super::modify::holds_ole_frame(s, hs, true)? {
return Err(super::modify::ole_refusal());
}
let mut n = 0;
for m in mats {
n += transform_entities(s, hs, &m, true)?.len();
for m in &mats {
n += transform_entities(s, hs, m, true)?.len();
}
Ok(n)
}
+3
View File
@@ -25,6 +25,7 @@ mod dyngrip;
mod extract;
pub(crate) mod refedit;
mod wblock;
mod xclip;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -92,6 +93,7 @@ pub fn specs() -> Vec<CommandSpec> {
.chain(attribs::attdisp_menu_specs())
.chain(xref::specs())
.chain(refedit::specs())
.chain(xclip::specs())
.chain(bedit::specs())
.collect()
}
@@ -228,6 +230,7 @@ fn insert_entity(blk: &Block, at: Vec2, scale: Vec3, rotation: f64, base: Option
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
if let Some(b) = base {
let landed = ins.transform(blk.base.xy()).apply(b);
+484
View File
@@ -0,0 +1,484 @@
//! XCLIP and XCLIPFRAME: clip block and xref references to a boundary.
//!
//! A boundary belongs to one reference ([`cadcraft_doc::Insert::clip`]), in the block's own
//! coordinates, so it moves, rotates and scales with the reference and other references of the
//! block stay whole. It is a rectangle, a polygon or the outline of a closed polyline, can hide
//! what is inside instead of what is outside (Invert clip), and can be turned off, deleted or
//! turned into a polyline. Clip depth (front and back clipping planes) has no meaning in a 2D
//! drawing and is ignored. XCLIPFRAME says whether the boundary is drawn and plotted.
use cadcraft_doc::{ClipBoundary, EntityKind, Handle, MAX_CLIP_VERTICES};
use cadcraft_geom::{PolyVertex, Vec2};
use serde_json::{Value, json};
use super::super::machines::{SelOutcome, SelectPhase};
use crate::cmd::{CommandSpec, bad, bool_or, has_doc, point_value, str_param, targets};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub(super) fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("xclip", "Clip Xref", run)
.menu(&["Modify", "Clip", "Xref"])
.alias(&["xc"])
.params("{handles? | handle? (block or xref references, default the selection), option?: new|on|off|delete|polyline|clipdepth|query (default new with a boundary, else query), rectangle?: [[x,y],[x,y]] | points?: [[x,y],…] (3 to 4096, drawing coordinates) | polyline?: handle of a closed polyline, invert?: bool (hide what is inside)} → {handles, option} (query: {clips: [{handle, boundary, enabled, inverted}]}; polyline: {polylines})")
.enabled(has_doc)
.interactive(|_| Ok(Box::new(XclipM::default()))),
CommandSpec::new("xclipframe", "Xref Clip Frame", run_frame)
.params("{value?: 0 (frames hidden) | 1 (shown and plotted) | 2 (shown, not plotted; the default)} → {XCLIPFRAME}")
.enabled(has_doc)
.interactive(|_| Ok(Box::new(FrameM))),
]
}
/// The block references among `hs` (other objects are ignored, as XCLIP's selection does).
fn references(s: &Session, hs: &[Handle]) -> Vec<Handle> {
let Ok(d) = s.doc() else { return Vec::new() };
hs.iter().copied().filter(|h| d.entity(*h).is_some_and(|e| matches!(e.kind, EntityKind::Insert(_)))).collect()
}
/// A rectangle's two corners as a closed outline.
fn rectangle(a: Vec2, b: Vec2) -> Vec<Vec2> {
vec![
Vec2::new(a.x.min(b.x), a.y.min(b.y)),
Vec2::new(a.x.max(b.x), a.y.min(b.y)),
Vec2::new(a.x.max(b.x), a.y.max(b.y)),
Vec2::new(a.x.min(b.x), a.y.max(b.y)),
]
}
/// The boundary a JSON call gives, in drawing coordinates, and whether it is a rectangle.
fn world_boundary(s: &Session, p: &Value) -> Result<(Vec<Vec2>, bool)> {
if let Some(r) = p.get("rectangle") {
let pts: Vec<Vec2> = r.as_array().map(|a| a.iter().filter_map(point_value).collect()).unwrap_or_default();
let [a, b] = pts.as_slice() else { return Err(bad("xclip", "`rectangle` needs two finite corners [[x,y],[x,y]]")) };
if (a.x - b.x).abs() <= 1e-12 || (a.y - b.y).abs() <= 1e-12 {
return Err(bad("xclip", "the clipping rectangle must have a width and a height"));
}
return Ok((vec![*a, *b], true));
}
if let Some(v) = p.get("polyline") {
let h = v
.as_str()
.and_then(Handle::parse_hex)
.or_else(|| v.as_u64().map(Handle))
.ok_or_else(|| bad("xclip", "`polyline` must be an object handle"))?;
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| bad("xclip", format!("no object {}", h.hex())))?;
let closed = matches!(&e.kind, EntityKind::LwPolyline(pl) if pl.closed) || matches!(&e.kind, EntityKind::Polyline3d(pl) if pl.closed);
if !closed {
return Err(bad("xclip", "select a closed polyline"));
}
let pts = cadcraft_render::clip::boundary_polygon(&e.kind).ok_or_else(|| bad("xclip", "the polyline does not enclose an area"))?;
return Ok((pts, false));
}
let pts = p.get("points").and_then(Value::as_array).ok_or_else(|| bad("xclip", "a boundary is required: `rectangle`, `points` or `polyline`"))?;
if !(3..=MAX_CLIP_VERTICES).contains(&pts.len()) {
return Err(bad("xclip", format!("a polygonal boundary needs 3 to {MAX_CLIP_VERTICES} points")));
}
let pts: Vec<Vec2> =
pts.iter().map(|v| point_value(v).ok_or_else(|| bad("xclip", "every boundary point must be a finite [x, y]"))).collect::<Result<_>>()?;
Ok((pts, false))
}
fn run(s: &mut Session, p: &Value) -> Result<Value> {
let hs = references(s, &targets(s, p)?);
if hs.is_empty() {
return Err(bad("xclip", "select block or xref references"));
}
let has_boundary = ["rectangle", "points", "polyline"].iter().any(|k| p.get(*k).is_some());
let option = str_param(p, "option").map(str::to_ascii_lowercase).unwrap_or_else(|| if has_boundary { "new".into() } else { "query".into() });
match option.as_str() {
"new" | "n" => {
let (world, rect) = world_boundary(s, p)?;
let outline = if rect { world.first().zip(world.get(1)).map(|(a, b)| rectangle(*a, *b)).unwrap_or_default() } else { world.clone() };
if cadcraft_render::clip::PolyClip::new(&outline).is_none() {
return Err(bad("xclip", "the clipping boundary encloses no area"));
}
let invert = bool_or(p, "invert", false);
let mut clips = Vec::with_capacity(hs.len());
{
let d = s.doc()?;
for h in &hs {
let Some(EntityKind::Insert(ins)) = d.entity(*h).map(|e| &e.kind) else { continue };
let base = d.block(&ins.block).map(|b| b.base.xy()).ok_or_else(|| bad("xclip", format!("block \"{}\" is missing", ins.block)))?;
let inv = ins.transform(base).inverse().ok_or_else(|| bad("xclip", "a reference with a zero scale can't be clipped"))?;
let points: Vec<Vec2> = world.iter().map(|q| inv.apply(*q)).collect();
// A rotated or skewed reference sees the rectangle as a polygon.
let r = ins.rotation.rem_euclid(std::f64::consts::FRAC_PI_2);
let square = r < 1e-9 || std::f64::consts::FRAC_PI_2 - r < 1e-9;
let points = if rect && !square { outline.iter().map(|q| inv.apply(*q)).collect() } else { points };
clips.push((*h, ClipBoundary { points, enabled: true, inverted: invert }));
}
}
for (h, c) in clips {
set_clip(s, h, Some(c))?;
}
}
"on" | "off" => {
let on = option == "on";
// Every reference is checked before any changes: an error leaves the drawing as it was.
let d = s.doc()?;
if !hs.iter().all(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Insert(i)) if i.clip.is_some())) {
return Err(bad("xclip", "no clipping boundary on the selected reference"));
}
// Only the flag changes, once per reference (a selection may name one many times).
let mut seen = std::collections::HashSet::new();
for h in hs.iter().filter(|h| seen.insert(**h)) {
s.doc_mut()?
.modify_entity(*h, |e| {
if let EntityKind::Insert(i) = &mut e.kind
&& let Some(c) = &mut i.clip
{
c.enabled = on;
}
})
.map_err(|e| bad("xclip", e.to_string()))?;
}
}
"delete" | "d" => {
for h in &hs {
set_clip(s, *h, None)?;
}
}
"polyline" | "p" | "generate" => {
let mut made = Vec::new();
for h in &hs {
let Some(world) = world_outline(s, *h) else { continue };
let vertices = world.into_iter().map(|p| PolyVertex { p, bulge: 0.0, start_width: 0.0, end_width: 0.0 }).collect();
let pl = cadcraft_doc::LwPolyline { vertices, closed: true, const_width: 0.0, elevation: 0.0, plinegen: false };
made.push(s.add_entity(EntityKind::LwPolyline(pl))?.hex());
}
if made.is_empty() {
return Err(bad("xclip", "no clipping boundary on the selected references"));
}
return Ok(json!({ "handles": hexes(&hs), "option": "polyline", "polylines": made }));
}
// Front and back clipping planes have no meaning in 2D: nothing changes.
"clipdepth" | "c" => return Ok(json!({ "handles": hexes(&hs), "option": "clipdepth", "ignored": true })),
"query" | "?" => {
let clips: Vec<Value> = hs
.iter()
.map(|h| {
let c = clip_of(s, *h);
json!({
"handle": h.hex(),
"boundary": world_outline(s, *h).map(|w| w.iter().map(|p| [p.x, p.y]).collect::<Vec<_>>()),
"enabled": c.as_ref().is_some_and(|c| c.enabled),
"inverted": c.as_ref().is_some_and(|c| c.inverted),
})
})
.collect();
return Ok(json!({ "clips": clips }));
}
o => return Err(bad("xclip", format!("unknown option \"{o}\" (new, on, off, delete, polyline, clipdepth or query)"))),
}
Ok(json!({ "handles": hexes(&hs), "option": option }))
}
fn hexes(hs: &[Handle]) -> Vec<String> {
hs.iter().map(|h| h.hex()).collect()
}
fn clip_of(s: &Session, h: Handle) -> Option<ClipBoundary> {
match &s.doc().ok()?.entity(h)?.kind {
EntityKind::Insert(i) => i.clip.clone(),
_ => None,
}
}
/// Reference `h`'s boundary outline in drawing coordinates.
fn world_outline(s: &Session, h: Handle) -> Option<Vec<Vec2>> {
let d = s.doc().ok()?;
let EntityKind::Insert(i) = &d.entity(h)?.kind else { return None };
let c = i.clip.as_ref()?;
let m = i.transform(d.block(&i.block)?.base.xy());
let poly = c.polygon();
(poly.len() >= 3).then(|| poly.into_iter().map(|p| m.apply(p)).collect())
}
fn set_clip(s: &mut Session, h: Handle, c: Option<ClipBoundary>) -> Result<()> {
s.doc_mut()?
.modify_entity(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind {
i.clip = c;
}
})
.map_err(|e| bad("xclip", e.to_string()))
}
// ---------------- XCLIPFRAME ----------------
fn run_frame(s: &mut Session, p: &Value) -> Result<Value> {
let v = match p.get("value").or_else(|| p.get("XCLIPFRAME")) {
None | Some(Value::Null) => return Ok(json!({ "XCLIPFRAME": s.doc()?.header.i64("XCLIPFRAME", 2) })),
Some(v) => v.as_i64().or_else(|| v.as_str().and_then(|t| t.trim().parse().ok())),
};
let v = v.filter(|v| (0..=2).contains(v)).ok_or_else(|| bad("xclipframe", "`value` must be 0, 1 or 2"))?;
s.doc_mut()?.header.set_i64("XCLIPFRAME", v);
Ok(json!({ "XCLIPFRAME": v }))
}
struct FrameM;
impl Interactive for FrameM {
fn name(&self) -> &'static str {
"XCLIPFRAME"
}
fn prompt(&self, s: &Session) -> Prompt {
let cur = s.doc().map(|d| d.header.i64("XCLIPFRAME", 2)).unwrap_or(2);
Prompt::new("Enter new value for XCLIPFRAME", Accept::TEXT).kw(&["0", "1", "2"]).default(cur.to_string())
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
let t = match i {
Input::Cancel => return Ok(Step::Cancel),
Input::Enter => return Ok(Step::Done),
Input::Text(t) | Input::Keyword(t) => t,
_ => return Ok(Step::Continue),
};
match run_frame(s, &json!({ "value": t.trim() })) {
Ok(_) => Ok(Step::Done),
Err(_) => {
s.echo("Requires an integer between 0 and 2.");
Ok(Step::Continue)
}
}
}
}
// ---------------- interactive XCLIP ----------------
#[derive(Default, Clone, Copy, PartialEq, Eq)]
enum Stage {
#[default]
Select,
Option,
DeleteOld,
Boundary,
Corner1,
Corner2,
Polygon,
Polyline,
}
#[derive(Default)]
struct XclipM {
stage: Stage,
sel: SelectPhase,
refs: Vec<Handle>,
invert: bool,
pts: Vec<Vec2>,
}
impl XclipM {
fn selected(&mut self, s: &mut Session, hs: &[Handle]) -> Result<Step> {
self.refs = references(s, hs);
if self.refs.is_empty() {
s.echo("No block or xref references selected.");
return Ok(Step::Done);
}
self.stage = Stage::Option;
Ok(Step::Continue)
}
fn apply(&mut self, s: &mut Session, mut p: Value) -> Result<Step> {
p["handles"] = json!(hexes(&self.refs));
let r = run(s, &p);
s.set_selection(Vec::new());
match r {
Ok(_) => Ok(Step::Done),
Err(e) => {
s.echo(e.to_string());
Ok(Step::Done)
}
}
}
/// Delete: as the reference app, with nothing to delete it says so and asks again.
fn delete(&mut self, s: &mut Session) -> Result<Step> {
if !self.any_clipped(s) {
s.echo("No clip boundary found.");
return Ok(Step::Continue);
}
self.apply(s, json!({ "option": "delete" }))
}
fn any_clipped(&self, s: &Session) -> bool {
self.refs.iter().any(|h| clip_of(s, *h).is_some())
}
}
fn kw(i: &Input) -> Option<String> {
match i {
Input::Keyword(k) | Input::Text(k) => Some(k.trim().to_ascii_lowercase()),
_ => None,
}
}
impl Interactive for XclipM {
fn name(&self) -> &'static str {
"XCLIP"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.sel = SelectPhase::begin(s);
if self.sel.done {
let hs = self.sel.picked.clone();
return self.selected(s, &hs);
}
Ok(Step::Continue)
}
fn prompt(&self, _s: &Session) -> Prompt {
match self.stage {
Stage::Select => self.sel.prompt(),
Stage::Option => Prompt::new("Enter clipping option", Accept::TEXT)
.kw(&["ON", "OFF", "Clipdepth", "Delete", "generate Polyline", "New boundary"])
.default("New"),
Stage::DeleteOld => Prompt::new("Delete old boundary(s)?", Accept::TEXT).kw(&["Yes", "No"]).default("Yes"),
Stage::Boundary => Prompt::new("Specify clipping boundary or select invert option", Accept::POINT)
.kw(&["Select polyline", "Polygonal", "Rectangular", "Invert clip"])
.default("Rectangular"),
Stage::Corner1 => Prompt::new("Specify first corner", Accept::POINT),
Stage::Corner2 => {
let p = Prompt::new("Specify opposite corner", Accept::POINT);
match self.pts.first() {
Some(a) => p.corner(*a),
None => p,
}
}
Stage::Polygon => {
let msg = if self.pts.is_empty() { "Specify first point" } else { "Specify next point" };
let p = Prompt::new(msg, Accept::POINT).base_opt(self.pts.last().copied());
if self.pts.is_empty() { p } else { p.kw(&["Undo"]) }
}
Stage::Polyline => Prompt::new("Select polyline", Accept::SELECT),
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if matches!(i, Input::Cancel) {
return Ok(Step::Cancel);
}
match self.stage {
Stage::Select => match self.sel.feed(s, &i)? {
SelOutcome::More => Ok(Step::Continue),
SelOutcome::Empty => Ok(Step::Done),
SelOutcome::Done(hs) => self.selected(s, &hs),
},
Stage::Option => {
let k = if matches!(i, Input::Enter) { Some("new".to_string()) } else { kw(&i) };
match k.as_deref() {
Some("on") => self.apply(s, json!({ "option": "on" })),
Some("off") => self.apply(s, json!({ "option": "off" })),
Some(k) if k.starts_with('c') => {
s.echo("Clip depth does not apply to a 2D drawing: front and back clipping planes are ignored.");
Ok(Step::Done)
}
Some(k) if k.starts_with('d') => self.delete(s),
Some(k) if k.starts_with('p') || k.starts_with('g') => self.apply(s, json!({ "option": "polyline" })),
Some(k) if k.starts_with('n') => {
self.stage = if self.any_clipped(s) { Stage::DeleteOld } else { Stage::Boundary };
Ok(Step::Continue)
}
_ => {
s.echo("Invalid option keyword.");
Ok(Step::Continue)
}
}
}
Stage::DeleteOld => match kw(&i).as_deref() {
None if matches!(i, Input::Enter) => {
self.stage = Stage::Boundary;
Ok(Step::Continue)
}
Some(k) if k.starts_with('y') => {
self.stage = Stage::Boundary;
Ok(Step::Continue)
}
Some(k) if k.starts_with('n') => Ok(Step::Done),
_ => Ok(Step::Continue),
},
Stage::Boundary => match (&i, kw(&i).as_deref()) {
(Input::Enter, _) => {
self.stage = Stage::Corner1;
Ok(Step::Continue)
}
(Input::Point(p), _) => {
// A point starts the default rectangle.
self.pts = vec![*p];
self.stage = Stage::Corner2;
Ok(Step::Continue)
}
(_, Some(k)) if k.starts_with('i') => {
self.invert = !self.invert;
s.echo(if self.invert {
"Inside mode - Objects inside boundary will be hidden."
} else {
"Outside mode - Objects outside boundary will be hidden."
});
Ok(Step::Continue)
}
(_, Some(k)) if k.starts_with('s') => {
self.stage = Stage::Polyline;
Ok(Step::Continue)
}
(_, Some(k)) if k.starts_with('p') => {
self.pts.clear();
self.stage = Stage::Polygon;
Ok(Step::Continue)
}
(_, Some(k)) if k.starts_with('r') => {
self.stage = Stage::Corner1;
Ok(Step::Continue)
}
_ => Ok(Step::Continue),
},
Stage::Corner1 => match i {
Input::Point(p) => {
self.pts = vec![p];
self.stage = Stage::Corner2;
Ok(Step::Continue)
}
_ => Ok(Step::Continue),
},
Stage::Corner2 => match (i, self.pts.first().copied()) {
(Input::Point(b), Some(a)) => self.apply(s, json!({ "option": "new", "rectangle": [[a.x, a.y], [b.x, b.y]], "invert": self.invert })),
_ => Ok(Step::Continue),
},
Stage::Polygon => match i {
Input::Point(p) if self.pts.len() < MAX_CLIP_VERTICES => {
self.pts.push(p);
Ok(Step::Continue)
}
Input::Point(_) => {
s.echo(format!("A boundary has at most {MAX_CLIP_VERTICES} points."));
Ok(Step::Continue)
}
Input::Keyword(_) | Input::Text(_) => {
self.pts.pop();
Ok(Step::Continue)
}
Input::Enter if self.pts.len() >= 3 => {
let pts: Vec<[f64; 2]> = self.pts.iter().map(|p| [p.x, p.y]).collect();
self.apply(s, json!({ "option": "new", "points": pts, "invert": self.invert }))
}
Input::Enter => {
s.echo("A polygonal boundary needs at least three points.");
Ok(Step::Continue)
}
_ => Ok(Step::Continue),
},
Stage::Polyline => match i {
Input::Pick(hs) => match hs.first() {
Some(h) => {
let h = *h;
self.apply(s, json!({ "option": "new", "polyline": h.hex(), "invert": self.invert }))
}
None => Ok(Step::Continue),
},
Input::Enter => Ok(Step::Done),
_ => Ok(Step::Continue),
},
}
}
}
+12 -3
View File
@@ -50,7 +50,7 @@ pub(super) fn specs() -> Vec<CommandSpec> {
}
/// Load the xrefs of drawing `i`, just opened (OPEN): the opened state counts as saved, and the
/// view frames the drawing with them.
/// view frames the drawing with them, unless the drawing opened on the view it was saved at.
pub(crate) fn after_open(s: &mut Session, i: usize) {
let px = s.viewport_px;
let Some(st) = s.docs.get_mut(i) else { return };
@@ -61,12 +61,21 @@ pub(crate) fn after_open(s: &mut Session, i: usize) {
let out = load::load_all(Arc::make_mut(&mut st.doc), path.as_deref());
st.saved = st.doc.clone();
let ext = st.doc.extents(&cadcraft_doc::Space::Model);
if !ext.is_empty() {
st.set_view_quiet(crate::View { center: ext.center(), height: (ext.height().max(ext.width() * px.1 / px.0.max(1.0)) * 1.1).max(1e-6) });
if !ext.is_empty() && crate::view::saved_view(&st.doc).is_none() {
// Fit in the frame of the saved twist, which open_drawing has restored.
let twist = st.view().twist;
let (center, w, h) = crate::View::twisted_box(ext, twist);
st.set_view_quiet(crate::View { center, height: (h.max(w * px.1 / px.0.max(1.0)) * 1.1).max(1e-6), twist });
}
echo_all(s, &out);
}
/// The file a reference saved as `path` in a drawing at `host` is read from, if there is one
/// (xrefs and raster images look in the same places).
pub(crate) fn find_file(path: &str, host: Option<&str>) -> Option<std::path::PathBuf> {
load::find(path, host.map(std::path::Path::new), false).ok()
}
/// The open drawing's path (xref paths are relative to its folder).
fn host(s: &Session) -> Option<String> {
s.state().ok().and_then(|st| st.path.clone())
+5 -4
View File
@@ -55,11 +55,11 @@ pub fn specs() -> Vec<CommandSpec> {
.alias(&["printpdf", "pdfb"])
.params("{path?: \"DIR/NAME^NAME2.pdf\" (default: the drawing's file; a `^` splits the name into one book name per row of frames; else returns base64 `data` per book), names?: [book names], frameHeight?: mm (default 297), unit?: mm per drawing unit (default 1)} → {books: [{name, pages, bytes, path? | data}], skipped}: closed polylines of the frame height in model space are sheet frames; each row (same lower edge, bottom to top) is one PDF, its frames left to right one page each on the paper (ISO A-series, either orientation) they match")
.noundo(),
CommandSpec::new("attach", "Attach", |_, _| {
Err(EngineError::Other("ATTACH is not available yet: raster images and PDF/DWF/DGN underlays can't be shown yet".into()))
CommandSpec::new("attach", "Attach", |s, p| match str_param(p, "path").map(extension) {
Some(e) if super::image::is_image_ext(&e) => super::image::run_imageattach(s, p),
_ => Err(EngineError::Other("ATTACH is not available yet for this file: only raster images (PNG, JPEG, BMP, TIFF; see IMAGEATTACH) can be attached, PDF/DWF/DGN underlays can't be shown yet".into())),
})
.params("not available yet")
.noundo(),
.params("{path: image file, …} as IMAGEATTACH; other file types are not available yet"),
CommandSpec::new("share", "Share", |_, _| {
Err(EngineError::Other("SHARE is not available yet: there is no online service to share through; EXPORT or PUBLISH the drawing and send the file".into()))
})
@@ -642,6 +642,7 @@ mod tests {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
})
}
+41 -3
View File
@@ -70,6 +70,19 @@ pub fn entity_codec() -> Option<&'static EntityCodec> {
/// COMPARE (drawing comparison).
pub mod compare;
/// Decode a raster image file (PNG, JPEG, BMP, TIFF) to pixels: installed by the app with the
/// image reader, a lower layer.
pub type ImageHook = fn(&[u8]) -> std::result::Result<cadcraft_doc::Raster, String>;
static IMAGE: OnceLock<ImageHook> = OnceLock::new();
pub fn set_image_decoder(h: ImageHook) {
let _ = IMAGE.set(h);
}
pub fn image_decoder() -> Option<ImageHook> {
IMAGE.get().copied()
}
/// Hand finished file bytes to the user where there is no file system (the browser: a download).
/// Arguments: file name, MIME type, bytes. `Ok` only once the delivery was actually started.
pub type DeliverHook = fn(&str, &str, &[u8]) -> std::result::Result<(), String>;
@@ -311,6 +324,7 @@ pub fn finish_open(s: &mut Session, f: ReadFile) -> Result<Value> {
let ReadFile { drawing, binary_dxf, name, path } = f;
let i = add_read(s, drawing, binary_dxf, &name, path);
super::blocks::xref::after_open(s, i);
super::image::after_open(s, i);
Ok(opened(s, i, true))
}
@@ -320,6 +334,12 @@ fn read_bytes(bytes: &[u8], name: &str, path: Option<String>) -> Result<ReadFile
// A file that isn't a drawing (an imported SVG) gives the drawing no file name: QSAVE then
// asks where to save instead of exporting over the original.
let path = path.filter(|p| is_drawing_file(p));
// The SHX fonts its text styles name are looked for beside the drawing too.
if let Some(dir) = path.as_deref().and_then(|p| std::path::Path::new(p).parent()) {
// A bare file name is in the current folder.
let dir = if dir.as_os_str().is_empty() { std::path::Path::new(".") } else { dir };
cadcraft_fonts::shx::add_drawing_dir(&std::path::absolute(dir).unwrap_or_else(|_| dir.to_path_buf()));
}
Ok(ReadFile { drawing, binary_dxf: cadcraft_dxf::is_binary(bytes), name: name.to_string(), path })
}
@@ -345,10 +365,12 @@ pub(crate) fn open_bytes(s: &mut Session, bytes: &[u8], name: &str, path: Option
fn opened(s: &Session, i: usize, entities: bool) -> Value {
let d = s.docs.get(i).map(|st| &st.doc);
let warnings = d.map(|d| d.read_notes.clone()).unwrap_or_default();
// Opened on the view it was saved at: a viewer keeps it instead of fitting the extents.
let saved_view = d.is_some_and(|d| crate::view::saved_view(d).is_some());
if entities {
json!({ "index": i, "entities": d.map(|d| d.entity_count()), "warnings": warnings })
json!({ "index": i, "entities": d.map(|d| d.entity_count()), "warnings": warnings, "saved_view": saved_view })
} else {
json!({ "index": i, "warnings": warnings })
json!({ "index": i, "warnings": warnings, "saved_view": saved_view })
}
}
@@ -363,6 +385,7 @@ fn run_open(s: &mut Session, p: &Value) -> Result<Value> {
crate::capped_read::read_capped(std::path::Path::new(path), MAX_DRAWING_BYTES).map_err(|e| bad("open", format!("{path}: {e}")))?;
let i = open_bytes(s, &bytes, path, Some(path.to_string()))?;
super::blocks::xref::after_open(s, i);
super::image::after_open(s, i);
return Ok(opened(s, i, true));
}
#[cfg(target_arch = "wasm32")]
@@ -373,6 +396,7 @@ fn run_open(s: &mut Session, p: &Value) -> Result<Value> {
let name = str_param(p, "name").unwrap_or("Drawing.dxf");
let i = open_bytes(s, &bytes, name, None)?;
super::blocks::xref::after_open(s, i);
super::image::after_open(s, i);
Ok(opened(s, i, false))
}
@@ -755,7 +779,10 @@ const MODELER_TYPES: [&str; 3] = ["3DSOLID", "REGION", "BODY"];
const DWG_WRITES: [&str; 1] = ["OLE2FRAME"];
/// [`not_saved`] for a file saved as `version`. From 2013 on, a 3D solid, region or body the data
/// store has a record for keeps its geometry and is not counted; neither are [`DWG_WRITES`].
/// store has a record for keeps its geometry and is not counted; neither are [`DWG_WRITES`], nor
/// another program's proxy entity whose class the file names: the DWG writes it with that class.
/// Before 2013, or when its group 91 names no class of the file, the DWG leaves the proxy out and
/// it is counted.
pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap<String, usize> {
let mut out: std::collections::BTreeMap<String, usize> = std::collections::BTreeMap::new();
let stored = if version >= Version::R2013 { d.foreign.data_store_entities() } else { Default::default() };
@@ -772,10 +799,21 @@ pub fn not_saved_as(d: &Drawing, version: Version) -> std::collections::BTreeMap
if DWG_WRITES.contains(&u.dxf_type.as_str()) {
continue;
}
if version >= Version::R2013 && u.dxf_type.eq_ignore_ascii_case("ACAD_PROXY_ENTITY") && d.foreign.proxy_class(&u.tags).is_some() {
continue;
}
let n = out.entry(u.dxf_type.clone()).or_insert(0);
*n = n.saturating_add(1);
}
}
// Another program's proxy objects (in the OBJECTS section) follow the same rule as its proxy
// entities: the DWG writer leaves them out before 2013, or when their class can't be named.
for o in d.foreign.objects.iter().filter(|o| o.kind.eq_ignore_ascii_case("ACAD_PROXY_OBJECT")) {
if version < Version::R2013 || d.foreign.proxy_class(&o.tags).is_none() {
let n = out.entry("ACAD_PROXY_OBJECT".to_string()).or_insert(0);
*n = n.saturating_add(1);
}
}
out
}
+2 -1
View File
@@ -59,7 +59,8 @@ pub(super) fn run_new(s: &mut Session, p: &Value) -> Result<Option<Value>> {
&& hi.y > lo.y
{
let center = cadcraft_geom::Vec2::new((lo.x + hi.x) / 2.0, (lo.y + hi.y) / 2.0);
st.set_view_quiet(crate::View { center, height: (hi.y - lo.y).max(1e-6) });
let twist = st.view().twist;
st.set_view_quiet(crate::View { center, height: (hi.y - lo.y).max(1e-6), twist });
}
Ok(Some(json!({ "index": i, "title": title, "template": path })))
}
+353
View File
@@ -0,0 +1,353 @@
//! Raster images (IMAGEATTACH, IMAGE). An IMAGE entity names its file; the pixels are decoded
//! when the drawing opens or the image is attached and kept with the open drawing
//! ([`Drawing::rasters`]), never in the file. An image whose file can't be found or read stays in
//! the drawing as a crossed-out frame.
use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use cadcraft_doc::{Drawing, EntityKind, Image, Raster};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
use super::file::base64_decode;
use super::{CommandSpec, bad, f64_or, point_param, str_param};
use crate::{Result, Session};
/// Most image files loaded per drawing.
const MAX_IMAGE_FILES: usize = 1000;
/// Largest image file read (bytes).
#[cfg(not(target_arch = "wasm32"))]
const MAX_IMAGE_BYTES: u64 = 256 << 20;
/// Most decoded pixel bytes kept per drawing; images past it stay unloaded.
const MAX_LOADED_BYTES: u64 = 2 << 30;
/// Most image files decoded at the same time when a drawing opens.
const MAX_LOADERS: usize = 4;
/// Longest image path taken from a caller.
const MAX_PATH: usize = 4096;
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("imageattach", "Raster Image Reference...", run_imageattach).alias(&["iat"]).params(
"{path: PNG/JPEG/BMP/TIFF file (saved as given; a relative path is relative to this drawing's folder), data?: base64 file contents \
(instead of reading `path`), at?: [x,y] lower-left corner (default 0,0), scale?: number (default 1: the image is one drawing unit \
wide), width?: width in drawing units (instead of `scale`), rotation? (degrees), name? (default: the file name)} → {name, handle, \
path, pixels: [w, h], size: [w, h]}",
),
CommandSpec::new("image", "Raster Images", run_image)
.alias(&["im"])
.params("{} → {images: [{name, path, foundAt, status: Loaded|Not Found|Not loaded, references, pixels?: [w, h]}]}")
.noundo(),
]
}
/// Whether `ext` (lower case, no dot) is an image file type IMAGEATTACH reads.
pub(crate) fn is_image_ext(ext: &str) -> bool {
matches!(ext, "png" | "jpg" | "jpeg" | "bmp" | "tif" | "tiff")
}
/// Every IMAGE entity of `d`: in model space, on the layouts and in the blocks.
fn images(d: &Drawing) -> impl Iterator<Item = &Image> {
let model = std::iter::once(&d.model);
let layouts = d.layouts.iter().map(|l| &l.entities);
let blocks = d.blocks.values().map(|b| &b.entities);
model.chain(layouts).chain(blocks).flat_map(|store| store.iter()).filter_map(|e| match &e.kind {
EntityKind::Image(i) => Some(i),
_ => None,
})
}
/// The image files `d` names, each once, in the order they are first used.
fn paths(d: &Drawing) -> Vec<String> {
let mut seen = BTreeSet::new();
let mut paths = Vec::new();
for i in images(d) {
if !i.path.trim().is_empty() && seen.insert(i.path.as_str()) {
paths.push(i.path.clone());
}
}
paths
}
/// The contents of the image file saved as `path` in a drawing at `host`.
fn read_file(path: &str, host: Option<&str>) -> std::result::Result<Vec<u8>, String> {
#[cfg(not(target_arch = "wasm32"))]
{
let file = super::blocks::xref::find_file(path, host).ok_or("file not found")?;
let len = std::fs::metadata(&file).map_err(|e| e.to_string())?.len();
if len > MAX_IMAGE_BYTES {
return Err(format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20));
}
// Read no more than the limit: the file can grow or change after the check above.
let limit = usize::try_from(MAX_IMAGE_BYTES).unwrap_or(usize::MAX);
crate::capped_read::read_capped(&file, limit).map_err(|e| {
if e.kind() == std::io::ErrorKind::InvalidData { format!("the file is larger than {} MB", MAX_IMAGE_BYTES >> 20) } else { e.to_string() }
})
}
#[cfg(target_arch = "wasm32")]
{
let _ = (path, host);
Err("files are not available on the web".into())
}
}
/// Decode an image file. A decoder that panics on a damaged file fails this image only: the
/// drawing it belongs to must still open.
fn decode(bytes: &[u8]) -> std::result::Result<Raster, String> {
let hook = super::file::image_decoder().ok_or("image files can't be read in this build")?;
match std::panic::catch_unwind(|| hook(bytes)) {
Ok(r) => r,
Err(_) => Err("the file is damaged and can't be read".into()),
}
}
fn bytes_of(r: &Raster) -> u64 {
u64::try_from(r.rgba().len()).unwrap_or(u64::MAX)
}
/// Load the images of drawing `i`, just opened. Those that can't be loaded are reported and
/// stay crossed-out frames; opening never fails over an image.
pub(crate) fn after_open(s: &mut Session, i: usize) {
let Some(st) = s.docs.get_mut(i) else { return };
let paths = paths(&st.doc);
if paths.is_empty() {
return;
}
let mut rasters = st.doc.rasters.clone();
let notes = load_missing(&paths, st.path.as_deref(), &mut rasters);
if !rasters.is_empty() {
// Loading pixels is not a change to the drawing. A drawing counts as unchanged while
// it is the very one that was saved, so the saved one follows.
let unchanged = Arc::ptr_eq(&st.doc, &st.saved);
Arc::make_mut(&mut st.doc).rasters = rasters;
if unchanged {
st.saved = st.doc.clone();
}
}
for n in notes {
s.echo(n);
}
}
/// Read and decode into `rasters` the files of `paths` that are not in it yet, for a drawing at
/// `host`. Returns one message per file that could not be loaded.
fn load_missing(paths: &[String], host: Option<&str>, rasters: &mut cadcraft_doc::Rasters) -> Vec<String> {
let mut notes = Vec::new();
let mut missing: Vec<&str> = paths.iter().map(String::as_str).filter(|p| rasters.get(p).is_none()).collect();
if missing.len() > MAX_IMAGE_FILES {
missing.truncate(MAX_IMAGE_FILES);
notes.push(format!("Images: only the first {MAX_IMAGE_FILES} image files are loaded"));
}
let decoded = decode_files(&missing, host);
// Kept in the order the drawing uses them, up to the memory limit.
let mut kept_bytes = 0u64;
for (path, result) in missing.iter().zip(decoded) {
match result {
Ok(r) => {
kept_bytes = kept_bytes.saturating_add(bytes_of(&r));
if kept_bytes > MAX_LOADED_BYTES {
notes.push(over_limit(path));
break;
}
rasters.insert(path, Arc::new(r));
}
Err(e) => notes.push(format!("Image {path}: {e}")),
}
}
notes
}
fn over_limit(path: &str) -> String {
format!("Image {path}: not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20)
}
/// Read and decode the image files `paths` of a drawing at `host`, a few at a time (decoding is
/// what opening a drawing with large images waits for). The results are in the order of `paths`.
fn decode_files(paths: &[&str], host: Option<&str>) -> Vec<std::result::Result<Raster, String>> {
// Decoded bytes so far, shared by the loaders: past the limit no further file is started.
let decoded_bytes = AtomicU64::new(0);
let load = |path: &str| -> std::result::Result<Raster, String> {
if decoded_bytes.load(Ordering::Relaxed) > MAX_LOADED_BYTES {
return Err(format!("not loaded (more than {} MB of images)", MAX_LOADED_BYTES >> 20));
}
let r = read_file(path, host).and_then(|bytes| decode(&bytes))?;
decoded_bytes.fetch_add(bytes_of(&r), Ordering::Relaxed);
Ok(r)
};
let mut results: Vec<Option<std::result::Result<Raster, String>>> = paths.iter().map(|_| None).collect();
let loaders = loader_count(paths.len());
if loaders > 1 {
// Each loader takes the next file nobody has started.
let next = AtomicUsize::new(0);
let work = || {
let mut done = Vec::new();
loop {
let index = next.fetch_add(1, Ordering::Relaxed);
let Some(path) = paths.get(index) else { break };
done.push((index, load(path)));
}
done
};
let finished: Vec<_> = std::thread::scope(|scope| {
let started: Vec<_> = (0..loaders).filter_map(|_| std::thread::Builder::new().spawn_scoped(scope, work).ok()).collect();
started.into_iter().filter_map(|loader| loader.join().ok()).flatten().collect()
});
for (index, result) in finished {
if let Some(slot) = results.get_mut(index) {
*slot = Some(result);
}
}
}
// One loader, or files a loader that could not start or finish left behind.
results.into_iter().zip(paths).map(|(result, path)| result.unwrap_or_else(|| load(path))).collect()
}
/// How many files are decoded at once: one per processor, at most [`MAX_LOADERS`] (each large
/// image needs several hundred megabytes while it is decoded) and no more than there are files.
fn loader_count(files: usize) -> usize {
#[cfg(not(target_arch = "wasm32"))]
let processors = std::thread::available_parallelism().map(std::num::NonZero::get).unwrap_or(1);
#[cfg(target_arch = "wasm32")]
let processors = 1;
processors.min(MAX_LOADERS).min(files)
}
/// The file name without folders and extension (either separator).
fn stem(path: &str) -> String {
let file = path.rsplit(['/', '\\']).next().unwrap_or(path);
match file.rsplit_once('.') {
Some((stem, _)) if !stem.is_empty() => stem.to_string(),
_ => file.to_string(),
}
}
/// The definition name for a new image of `path`: the name that file already has in `d`, else
/// `wanted`, numbered (`wanted_2`, `wanted_3`, …) when another file has taken it.
fn def_name(d: &Drawing, path: &str, wanted: &str) -> String {
if let Some(i) = images(d).find(|i| i.path == path && !i.name.is_empty()) {
return i.name.clone();
}
// The names other files have, compared without regard to case.
let taken: BTreeSet<String> = images(d).filter(|i| i.path != path).map(|i| i.name.to_ascii_lowercase()).collect();
let free = |name: &str| !taken.contains(&name.to_ascii_lowercase());
if free(wanted) {
return wanted.to_string();
}
// One of these is free: there are more candidates than names taken.
let candidates = 2..taken.len().saturating_add(3);
candidates.map(|n| format!("{wanted}_{n}")).find(|name| free(name)).unwrap_or_else(|| wanted.to_string())
}
const ID: &str = "imageattach";
pub(crate) fn run_imageattach(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").map(str::trim).filter(|x| !x.is_empty()).ok_or_else(|| bad(ID, "`path` is required"))?.to_string();
if path.len() > MAX_PATH {
return Err(bad(ID, "`path` is too long"));
}
let place = placement(p)?;
let raster = pixels(s, p, &path)?;
let (w, h) = (f64::from(raster.width()), f64::from(raster.height()));
// One pixel in drawing units, along the image's bottom edge (`u`) and its left edge (`v`).
let pixel = place.width / w;
let u = Vec2::from_angle(place.rotation) * pixel;
let v = u.perp();
if !(pixel.is_normal() && (pixel * h).is_normal() && u.x.is_finite() && u.y.is_finite()) {
return Err(bad(ID, "the image would be too small or too large to draw"));
}
let wanted = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).map(str::to_string).unwrap_or_else(|| stem(&path));
let name = def_name(s.doc()?, &path, &wanted);
let image = Image {
insert: place.at.to3(0.0),
u: u.to3(0.0),
v: v.to3(0.0),
size: Vec2::new(w, h),
path: path.clone(),
name: name.clone(),
..Image::default()
};
s.doc_mut()?.rasters.insert(&path, raster);
let handle = s.add_entity(EntityKind::Image(image))?;
Ok(json!({ "name": name, "handle": handle.hex(), "path": path, "pixels": [w, h], "size": [place.width, pixel * h] }))
}
/// Where and how large IMAGEATTACH puts the image.
struct Placement {
/// The lower-left corner.
at: Vec2,
/// Radians, counter-clockwise.
rotation: f64,
/// The image's width in drawing units.
width: f64,
}
/// `at`, `rotation` and the width (`width`, else `scale`: an image is one unit wide at scale 1).
fn placement(p: &Value) -> Result<Placement> {
let at = point_param(p, "at").unwrap_or(Vec2::ZERO);
if !(at.x.is_finite() && at.y.is_finite()) {
return Err(bad(ID, "`at` must be a point"));
}
let width = match p.get("width") {
Some(v) => v.as_f64().filter(|w| w.is_finite()).ok_or_else(|| bad(ID, "`width` must be a number"))?,
None => f64_or(p, "scale", 1.0),
};
if !(width.is_finite() && width > 0.0) {
return Err(bad(ID, "`scale` and `width` must be greater than zero"));
}
Ok(Placement { at, rotation: f64_or(p, "rotation", 0.0).to_radians(), width })
}
/// The pixels of the image at `path`: decoded from `data` when the caller hands the file over,
/// else the ones already loaded for that path, else read from the file.
fn pixels(s: &Session, p: &Value, path: &str) -> Result<Arc<Raster>> {
let bytes = match p.get("data") {
Some(data) => {
let text = data.as_str().ok_or_else(|| bad(ID, "`data` must be base64 text"))?;
base64_decode(text).ok_or_else(|| bad(ID, "`data` is not valid base64"))?
}
None => {
if let Some(loaded) = s.doc()?.rasters.get(path) {
return Ok(loaded.clone());
}
let host = s.state()?.path.clone();
read_file(path, host.as_deref()).map_err(|e| bad(ID, format!("{path}: {e}")))?
}
};
Ok(Arc::new(decode(&bytes).map_err(|e| bad(ID, format!("{path}: {e}")))?))
}
fn run_image(s: &mut Session, _p: &Value) -> Result<Value> {
let host = s.state()?.path.clone();
let d = s.doc()?;
// Per file: its definition name and how many images show it.
let mut uses: BTreeMap<&str, (&str, usize)> = BTreeMap::new();
for i in images(d) {
uses.entry(i.path.as_str()).or_insert((i.name.as_str(), 0)).1 += 1;
}
let rows: Vec<Value> = paths(d)
.iter()
.map(|path| {
let (name, references) = uses.get(path.as_str()).copied().unwrap_or_default();
let mut row = describe(d, path, host.as_deref());
row["name"] = json!(name);
row["references"] = json!(references);
row
})
.collect();
Ok(json!({ "images": rows }))
}
/// The state of image file `path` of drawing `d` (saved at `host`): where it is and whether its
/// pixels are loaded.
fn describe(d: &Drawing, path: &str, host: Option<&str>) -> Value {
let loaded = d.rasters.get(path);
let found_at = super::blocks::xref::find_file(path, host).map(|f| f.to_string_lossy().into_owned());
let status = match (loaded, &found_at) {
(Some(_), _) => "Loaded",
(None, None) => "Not Found",
// The file is there but could not be read as an image.
(None, Some(_)) => "Not loaded",
};
json!({ "path": path, "foundAt": found_at, "status": status, "pixels": loaded.map(|r| json!([r.width(), r.height()])) })
}
+28 -4
View File
@@ -524,6 +524,7 @@ fn viewport_json(h: Handle, v: &Viewport) -> Value {
"height": v.height,
"viewCenter": [v.view_center.x, v.view_center.y],
"viewHeight": v.view_height,
"twist": v.view_twist().to_degrees(),
"scale": if v.view_height > 0.0 { v.height / v.view_height } else { 0.0 },
"locked": v.locked,
"on": v.on,
@@ -785,10 +786,28 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
// Checked here for a clear error; the plotter resolves the names the same way.
let sheets = p.get("layouts").map(|v| plot_sheets(cmd, s.doc()?, v)).transpose()?;
// `layout` and `layouts` must name the same sheet(s), or the reply would name one sheet and the render another.
if let (Some(n), Some(names)) = (str_param(p, "layout"), sheets.as_deref())
&& !matches!(names, [only] if only.eq_ignore_ascii_case(n))
{
return Err(bad(cmd, "`layout` and `layouts` name different sheets; give only one of them"));
}
let is_image = p.get("output").and_then(Value::as_str).is_some_and(|o| o.eq_ignore_ascii_case("png") || o.eq_ignore_ascii_case("svg"));
let space = match str_param(p, "layout") {
Some(n) if n.eq_ignore_ascii_case("model") => Space::Model,
Some(n) => Space::Paper(layout_name(cmd, s.doc()?, n)?),
None => s.space(),
// A PNG or SVG holds one render: a single `layouts` entry names the sheet to draw (the PDF
// path resolves `layouts` itself), not whatever space the session happens to show.
None => match sheets.as_deref() {
Some([only]) if is_image => {
if only.eq_ignore_ascii_case("model") {
Space::Model
} else {
Space::Paper(only.clone())
}
}
_ => s.space(),
},
};
let mut opts = if p.is_object() { p.clone() } else { json!({}) };
if let Some(raw) = p.get("offset") {
@@ -827,12 +846,17 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
None => o.remove("plotTransparency"),
};
}
// A PNG or SVG holds one render: several sheets would report `pages: N` but write only one.
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 layout = match &sheets {
Some(names) => names.first().cloned().unwrap_or_default(),
None => space.tab_name().to_string(),
};
let pages = sheets.as_ref().map_or(1, Vec::len);
let format = opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).unwrap_or_else(|| "pdf".into());
match str_param(p, "path") {
Some(_path) => {
#[cfg(not(target_arch = "wasm32"))]
@@ -842,17 +866,17 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
// `<path>.cadcraft-tmp` symlink cannot redirect the plot write (CWE-59).
let folder = super::file::new_folder(path);
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 });
let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_new_folder(s, &mut r, folder);
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 }))
Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format }))
}
}
None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages })),
None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })),
}
}
+66 -1
View File
@@ -230,6 +230,24 @@ fn plot_goes_through_the_hook() {
assert!(s.execute("plot", &json!({"layout": "Model", "plotArea": "window"})).is_err(), "window needs corners");
assert!(s.execute("plot", &json!({"layout": "Layout1", "plotArea": "display"})).is_err(), "layouts plot their sheet");
assert!(s.execute("plot", &json!({"layout": "Model", "scale": -1})).is_err());
// Image output holds one sheet: several `layouts` would report pages:N but write one render.
for out in ["x.png", "x.svg"] {
let e = s.execute("plot", &json!({"path": out, "layouts": ["Layout1", "Layout2"]})).unwrap_err();
assert!(e.to_string().contains("layouts"), "{e}");
}
assert!(s.execute("plot", &json!({"output": "png", "layouts": ["Layout1", "Layout2"]})).is_err());
// `layout` and `layouts` naming different sheets are refused (the reply would name one sheet and the render another); agreeing ones pass.
for p in
[json!({"output": "png", "layout": "Model", "layouts": ["Layout1"]}), json!({"output": "pdf", "layout": "Layout1", "layouts": ["Model"]})]
{
let e = s.execute("plot", &p).unwrap_err().to_string();
assert!(e.contains("different"), "{e}");
}
assert_eq!(s.execute("plot", &json!({"output": "png", "layout": "layout1", "layouts": ["Layout1"]})).unwrap()["layout"], "Layout1");
let one = s.execute("plot", &json!({"output": "png", "layouts": ["Layout1"]})).unwrap();
assert_eq!(one["layout"], "Layout1");
let text = String::from_utf8(super::super::file::base64_decode(one["data"].as_str().unwrap()).unwrap()).unwrap();
assert!(text.contains("Paper(\"Layout1\")"), "one sheet renders that layout, not the session space: {text}");
#[cfg(not(target_arch = "wasm32"))]
{
let path = std::env::temp_dir().join(format!("cadcraft-plot-test-{}.pdf", std::process::id()));
@@ -283,7 +301,7 @@ fn mspace_edits_model_through_viewport() {
s.cmdline("circle 10,10 3").unwrap();
assert_eq!(s.doc().unwrap().model.len(), before + 1);
// Zooming changes the viewport's model view, not the sheet.
s.state_mut().unwrap().set_view(crate::View { center: v.center, height: v.height / 2.0 });
s.state_mut().unwrap().set_view(crate::View { center: v.center, height: v.height / 2.0, twist: v.twist });
let vp2 = viewports(&s, "L").into_iter().find(|(x, _)| *x == h).unwrap().1;
assert!((vp2.view_height - vp.view_height / 2.0).abs() < 1e-9);
assert_eq!(s.state().unwrap().paper_view(), pv);
@@ -307,3 +325,50 @@ fn plot_help_names_the_device_and_the_built_in_devices() {
assert!(help.contains(name), "plot help lacks {name}");
}
}
/// The path's extension picks the plot format as EXPORT does, in any case; one that names no
/// format (or none) is refused instead of writing a PDF under that name, and a device that writes
/// another format is refused.
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn plot_path_extension_picks_the_format_like_export() {
super::super::file::set_io(super::super::file::IoHooks {
read: |_, _| Err("no reader in tests".into()),
write: |_, _| Err("no writer in tests".into()),
plot: Some(fake_plot),
});
if io().and_then(|h| h.plot).is_none() {
return; // another test installed hooks without a plotter first
}
let mut s = session_with_model();
let dir = std::env::temp_dir().join(format!("cadcraft-plot-ext-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = |n: &str| dir.join(n).to_string_lossy().to_string();
let upper = s.execute("plot", &json!({"path": path("X.PNG")})).unwrap();
assert_eq!(upper["format"], "png", "an upper-case extension still picks png");
let e = s.execute("plot", &json!({"path": path("x.txt")})).unwrap_err().to_string();
assert!(e.contains("png") && e.contains("svg") && e.contains("pdf"), "{e}");
assert!(!dir.join("x.txt").exists(), "nothing written under an unknown extension");
let e = s.execute("plot", &json!({"path": path("noext")})).unwrap_err().to_string();
assert!(e.contains("png") && e.contains("svg") && e.contains("pdf"), "{e}");
assert!(!dir.join("noext").exists());
let e = s.execute("plot", &json!({"path": path("y.png"), "device": "CADCraft PDF"})).unwrap_err().to_string();
assert!(e.contains("writes pdf") && e.contains("png"), "{e}");
// A device that resolves to none, or a null/unknown `output`, names no format: the refusal stands.
for p in [
json!({"path": path("x.txt"), "device": "None"}),
json!({"path": path("x.txt"), "output": null}),
json!({"path": path("x.txt"), "output": "bogus"}),
] {
let e = s.execute("plot", &p).unwrap_err().to_string();
assert!(e.contains("png") && e.contains("svg") && e.contains("pdf"), "{e}");
assert!(!dir.join("x.txt").exists(), "nothing written under an unknown extension");
}
// An explicit output still decides for an odd name.
assert_eq!(s.execute("plot", &json!({"path": path("z.txt"), "output": "pdf"})).unwrap()["format"], "pdf");
// But one that contradicts the extension is refused, as a device that does is (#2585 review).
let e = s.execute("plot", &json!({"path": path("w.png"), "output": "svg"})).unwrap_err().to_string();
assert!(e.contains("svg") && e.contains("png"), "{e}");
assert!(!dir.join("w.png").exists(), "nothing written when `output` and the path disagree");
std::fs::remove_dir_all(&dir).ok();
}
+1 -1
View File
@@ -329,7 +329,7 @@ pub(super) fn run_vpclip(s: &mut Session, p: &Value) -> Result<Value> {
let k = cur.view_height / cur.height.max(1e-12);
let mut v = cur;
let c = b.center();
let view_center = v.view_center + (c - v.center.xy()) * k;
let view_center = v.paper_to_model(c);
let view_height = b.height() * k;
if view_center.is_finite() && view_height.is_finite() && view_height > 0.0 {
v.view_center = view_center;
+1 -1
View File
@@ -109,7 +109,7 @@ fn parse_color(t: &str) -> Result<Color> {
fn viewport_at(s: &Session, p: Vec2) -> Option<Handle> {
let st = s.state().ok()?;
let at = match st.active_viewport() {
Some((_, vp)) => vp.center.xy() + (p - vp.view_center) * (vp.height / vp.view_height),
Some((_, vp)) => vp.model_to_paper(p),
None => p,
};
super::viewports::viewport_at(s, at)
+1
View File
@@ -54,6 +54,7 @@ pub(super) fn apply(s: &Session, k: EntityKind, c: &Content) -> Result<EntityKin
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
if *center {
// Move the block so the centre of its extents lands on the anchor.
+4 -4
View File
@@ -35,7 +35,7 @@ use oops::run_oops;
pub(crate) use oops::{Erased, erase_kept};
use select_then::{DisplaceM, Op, SelectThen};
use stretch::{StretchM, run_stretch};
pub(crate) use transform::transform_entities;
pub(crate) use transform::{holds_ole_frame, ole_refusal, refuse_ole_frames, transform_entities};
use transform::{run_copy, run_erase, run_mirror, run_move, run_rotate, run_scale};
pub(crate) use trim::{Edges, extend, trim};
@@ -86,7 +86,7 @@ pub fn specs() -> Vec<CommandSpec> {
.menu(&["Modify", "Trim"])
.alias(&["tr"])
.params(
"{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"}",
"{handle, pick: [x,y] | fence: [[x,y],...] | crossing: [[x,y],[x,y]], edges?: [hex], edgeMode?: \"extend\"|\"none\", mode?: \"quick\"|\"standard\"} → {handles: the object (kept, reshaped) then the new pieces; none when it was erased} (pick) | {trimmed} (fence, crossing)",
)
.interactive(|_| Ok(Box::new(TrimM::new(false)))),
CommandSpec::new("extend", "Extend", trimextend::run_extend)
@@ -112,9 +112,9 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("break", "Break", run_break)
.menu(&["Modify", "Break"])
.alias(&["br"])
.params("{handle, p1, p2}")
.params("{handle, p1, p2} → {handles: the object (kept, reshaped) then the new pieces; none when nothing is left}")
.interactive(|_| Ok(Box::new(BreakM::default()))),
CommandSpec::new("breakatpoint", "Break At Point", run_breakat).menu(&["Modify", "Break At Point"]).params("{handle, at}"),
CommandSpec::new("breakatpoint", "Break At Point", run_breakat).menu(&["Modify", "Break At Point"]).params("{handle, at} → {handles: the object (kept, reshaped) then the new piece}"),
CommandSpec::new("join", "Join", run_join)
.menu(&["Modify", "Join"])
.alias(&["j"])
+2 -14
View File
@@ -1,4 +1,4 @@
use super::trim::{param_on, sub_polyline};
use super::trim::{param_on, replace_with_pieces, sub_polyline};
use super::{
Accept, Arc, EngineError, Entity, EntityKind, Handle, Input, Interactive, Line, PolyVertex, Polyline, Prompt, Result, Segment, Session, Step,
Value, Vec2, arc, bad, json, lwpoly, norm_angle, point_param, point_req, targets,
@@ -105,19 +105,7 @@ pub(crate) fn break_entity(s: &mut Session, h: Handle, p1: Vec2, p2: Vec2) -> Re
}
_ => return Err(EngineError::Other("Cannot break that object.".into())),
};
let common = e.common.clone();
let space = s.space();
let d = s.doc_mut()?;
d.remove_entity(h);
let mut out = Vec::new();
for k in pieces {
let nh = d.new_handle();
if let Some(st) = d.space_mut(&space) {
st.push(Entity { handle: nh, common: common.clone(), kind: k });
out.push(nh);
}
}
Ok(out)
replace_with_pieces(s, h, pieces)
}
pub(super) fn run_break(s: &mut Session, p: &Value) -> Result<Value> {
+30
View File
@@ -5,6 +5,7 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, er
// ---------------- core operations ----------------
pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Vec<Handle>> {
refuse_ole_frames(s, hs, m, copy)?;
edit_entities(s, hs, copy, |e| e.kind.transform(m))
}
@@ -12,6 +13,7 @@ pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy:
/// and every height of the objects about its Z, their thickness too.
pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64, copy: bool) -> Result<Vec<Handle>> {
let m = Mat3::scale_about(base.xy(), f);
refuse_ole_frames(s, hs, &m, copy)?;
edit_entities(s, hs, copy, |e| {
e.kind.transform(&m);
e.kind.scale_heights(base.z, f);
@@ -19,6 +21,34 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64,
})
}
/// An OLE2FRAME only translates or scales uniformly (its corners stay axis aligned): refuse any other `m` before anything
/// changes, instead of reporting success and leaving the frame where it was.
pub(crate) fn refuse_ole_frames(s: &Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<()> {
if cadcraft_doc::ole_frame_accepts(m) || !holds_ole_frame(s, hs, copy)? {
return Ok(());
}
Err(ole_refusal())
}
/// The refusal for a transform an OLE2FRAME cannot take.
pub(crate) fn ole_refusal() -> crate::EngineError {
crate::EngineError::Other(
"An OLE object can only be moved, copied or scaled uniformly; other transforms (rotation, mirroring, non-uniform scale, alignment) are not supported.".into(),
)
}
/// Whether `hs` holds an OLE2FRAME a transform would touch. An in-place edit (`copy` false) skips
/// an object on a locked layer (see edit_entities), so such a frame cannot be refused.
pub(crate) fn holds_ole_frame(s: &Session, hs: &[Handle], copy: bool) -> Result<bool> {
let d = s.doc()?;
Ok(hs.iter().any(|h| {
d.entity(*h).is_some_and(|e| {
let locked = !copy && d.layer(&e.common.layer).is_some_and(|l| l.locked);
!locked && matches!(&e.kind, cadcraft_doc::EntityKind::Unknown(u) if u.is_ole_frame())
})
}))
}
/// `p` at the current elevation (ELEVATION), the Z AutoCAD gives a point entered without one.
pub(crate) fn at_elevation(s: &Session, p: Vec2) -> Vec3 {
let z = s.doc().map(|d| d.header.f64("ELEVATION", 0.0)).ok().filter(|z| z.is_finite());
+36 -8
View File
@@ -170,18 +170,46 @@ pub(crate) fn trim(s: &mut Session, h: Handle, pick: Vec2, edges: Edges) -> Resu
EntityKind::LwPolyline(p) => trim_polyline(p, &cut, pick)?,
k => crate::cmd::modify2::trim_other(k, &cut, pick)?,
};
let common = e.common.clone();
let space = s.space();
replace_with_pieces(s, h, pieces)
}
/// Put `pieces` in place of object `h` as AutoCAD 2024's BREAK and TRIM leave them: the first
/// piece (the one holding the object's start, or the only piece of a circle or closed polyline)
/// is the object itself, keeping its handle, its place in the drawing order, its groups and its
/// extended data; the others are new objects with its properties, added at the end of its space
/// (`entlast`); with no pieces the object is erased. Returns the pieces' handles. (A line broken
/// in its middle keeps its handle on the piece from its start point, the piece to its end point is
/// new; a circle broken or trimmed becomes an arc with the circle's handle.)
///
/// Dimensions attached to the object follow [`crate::assoc::follow_pieces`]. Its parametric
/// constraints are removed: its new shape no longer meets them, and solving them again would move
/// the objects they tie it to.
pub(super) fn replace_with_pieces(s: &mut Session, h: Handle, pieces: Vec<EntityKind>) -> Result<Vec<Handle>> {
let d = s.doc_mut()?;
d.remove_entity(h);
let mut out = Vec::new();
for k in pieces {
let nh = d.new_handle();
let mut pieces = pieces.into_iter();
let Some(first) = pieces.next() else {
d.remove_entity(h);
return Ok(Vec::new());
};
let (Some(space), Some(old)) = (d.space_of(h), d.entity(h).cloned()) else {
return Err(EngineError::Other("no such object".into()));
};
d.modify_entity(h, |e| e.kind = first)?;
let mut out = vec![h];
for kind in pieces {
let handle = d.new_handle();
if let Some(st) = d.space_mut(&space) {
st.push(Entity { handle: nh, common: common.clone(), kind: k });
out.push(nh);
st.push(Entity { handle, common: old.common.clone(), kind });
out.push(handle);
}
}
crate::assoc::follow_pieces(d, &old.kind, &out);
let n = d.constraints.len();
d.constraints.retain(|c| c.refs.iter().all(|r| r.handle != h));
let removed = n - d.constraints.len();
if removed > 0 {
s.echo(format!("{removed} constraint(s) of the broken or trimmed object removed."));
}
Ok(out)
}
+10 -1
View File
@@ -16,7 +16,7 @@ use super::other;
use crate::cmd::curves::KW;
use crate::cmd::helpers::line;
use crate::cmd::machines::{SelOutcome, SelectPhase, number};
use crate::cmd::modify::transform_entities;
use crate::cmd::modify::{refuse_ole_frames, transform_entities};
use crate::cmd::{bad, point_req, point_value, targets};
use crate::prompt::Drag;
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
@@ -108,6 +108,15 @@ pub(super) fn run_mocoro(s: &mut Session, p: &Value) -> Result<Value> {
}
// Every option is checked before the drawing changes.
let ops = list.iter().enumerate().map(|(i, v)| parse_op(i, v)).collect::<Result<Vec<_>>>()?;
// An OLE frame only translates or scales uniformly: a rotate step (or any step) that would refuse it must do so before an
// earlier move or copy changes the drawing (a refused command is not rolled back).
for op in &ops {
match *op {
Op::Rotate(a) => refuse_ole_frames(s, &objs, &Mat3::rotate_about(base, a), false)?,
Op::Scale(f) => refuse_ole_frames(s, &objs, &Mat3::scale_about(base, f), false)?,
_ => {}
}
}
let mut copies = Vec::new();
for op in ops {
copies.extend(apply(s, &objs, &mut base, op)?);
+11 -2
View File
@@ -35,14 +35,23 @@ pub(crate) fn arraypath(
};
crate::cmd::array::check_size(s, n as u64, objs.len())?;
let Some((p0, t0)) = c.at_length(0.0) else { return Ok(Vec::new()) };
let mut out = Vec::new();
let mut mats = Vec::new();
for i in 1..n {
let Some((p, t)) = c.at_length(step * i as f64) else { continue };
let mut m = Mat3::translate(p - p0);
if align {
m = Mat3::rotate_about(p, t.angle() - t0.angle()).then_before(m);
}
out.extend(crate::cmd::modify::transform_entities(s, &objs, &m, true)?);
mats.push(m);
}
// Every copy is checked before the first is made: a refusal part way would leave the copies
// already added in the drawing (a failed command is not rolled back).
if mats.iter().any(|m| !cadcraft_doc::ole_frame_accepts(m)) && crate::cmd::modify::holds_ole_frame(s, &objs, true)? {
return Err(crate::cmd::modify::ole_refusal());
}
let mut out = Vec::new();
for m in &mats {
out.extend(crate::cmd::modify::transform_entities(s, &objs, m, true)?);
}
Ok(out)
}
+1 -2
View File
@@ -182,8 +182,7 @@ fn chspace(s: &mut Session, hs: &[Handle], to: Option<&str>, vp: Option<Handle>)
};
let m = match viewport_of(s, &layout, vp) {
Some(v) => {
let k = v.view_height / v.height;
let to_paper = Mat3::translate(v.center.xy()).then_before(Mat3::scale(1.0 / k, 1.0 / k)).then_before(Mat3::translate(-v.view_center));
let to_paper = v.model_to_paper_matrix();
if target == Space::Model { to_paper.inverse().unwrap_or(Mat3::IDENTITY) } else { to_paper }
}
None => Mat3::IDENTITY,
+1
View File
@@ -411,6 +411,7 @@ fn chspace_json_and_command_line() {
layer_colors: Vec::new(),
clip: None,
on: true,
twist: 0.0,
};
s.doc_mut().unwrap().add(&Space::Paper("Layout1".into()), Default::default(), EntityKind::Viewport(vp)).unwrap();
let r = s.execute("chspace", &json!({"handles": [l]})).unwrap();
+40 -2
View File
@@ -265,6 +265,11 @@ pub fn page_device(cmd: &str, p: &Value, page: &mut PageSetup) -> Result<bool> {
Ok(false)
}
/// The output a path's extension (any case) asks for: png, svg or pdf; other extensions ask for none.
fn path_output(path: &str) -> Option<PlotOutput> {
PlotOutput::parse(&std::path::Path::new(path).extension()?.to_string_lossy())
}
/// The options PLOT / EXPORTPDF hand the plotter with `device` and the device's papers
/// resolved: `device` (else the layout's page setup device) picks the output (`output`: pdf,
/// png or svg; EXPORTPDF always writes PDF) and `resolution`; a paper of the device becomes
@@ -286,9 +291,42 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
None => layout.as_ref().and_then(|pg| find_device(&pg.device)),
};
let mut out = if p.is_object() { p.clone() } else { json!({}) };
let (Some(dev), Some(o)) = (dev, out.as_object_mut()) else { return Ok(out) };
// The path's extension names the format, like EXPORT, unless a device is given; a given
// device that writes another format is refused. EXPORTPDF always writes PDF.
let by_path = if cmd == "exportpdf" { None } else { str_param(p, "path").and_then(path_output) };
// A path whose extension names no format (or has none) would hold a PDF under that name:
// refuse it, as EXPORT does, unless `output` or a device says what to write.
if cmd == "plot"
&& by_path.is_none()
&& !p.get("output").and_then(Value::as_str).is_some_and(|o| PlotOutput::parse(o).is_some())
&& !(dev.is_some() && given.is_some_and(|n| !n.is_empty()))
&& let Some(path) = str_param(p, "path")
{
return Err(bad(
cmd,
format!("can't tell the format of `{path}`: give a path ending in .png, .svg or .pdf, or set `output` to png, svg or pdf"),
));
}
if let (Some(want), Some(dev), true) = (by_path, &dev, given.is_some_and(|n| !n.is_empty()))
&& dev.output != want
{
return Err(bad(cmd, format!("plotter `{}` writes {}, but the path asks for {}", dev.name, dev.output.as_str(), want.as_str())));
}
// An `output` that says another format than the path's extension is refused too, as a device
// that does is: either way the file would not hold what its name says.
if let (Some(want), Some(asked)) = (by_path, p.get("output").and_then(Value::as_str).and_then(PlotOutput::parse))
&& asked != want
{
return Err(bad(cmd, format!("`output` is {}, but the path asks for {}", asked.as_str(), want.as_str())));
}
let (Some(dev), Some(o)) = (dev, out.as_object_mut()) else {
if let (Some(want), Some(o)) = (by_path, out.as_object_mut()) {
o.insert("output".into(), json!(want.as_str()));
}
return Ok(out);
};
o.remove("device");
let output = if cmd == "exportpdf" { PlotOutput::Pdf } else { dev.output };
let output = if cmd == "exportpdf" { PlotOutput::Pdf } else { by_path.unwrap_or(dev.output) };
o.insert("output".into(), json!(output.as_str()));
o.insert("resolution".into(), json!(dev.resolution));
let paper = match str_param(p, "paper") {
+77 -9
View File
@@ -10,7 +10,7 @@ mod rename;
pub use matchprop::MatchProps;
use cadcraft_color::Color;
use cadcraft_doc::{EntityKind, Lineweight, Transparency};
use cadcraft_doc::{EntityKind, Handle, Lineweight, Transparency};
use cadcraft_geom::Vec3;
use serde_json::{Value, json};
@@ -21,9 +21,9 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("properties", "Properties", run_get).menu(&["Modify", "Properties"]).alias(&["pr", "props", "ch"]).params("{handles?} → properties of the selection").noundo(),
CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, <geometry fields: radius, center, start, end, text, height, rotation…>; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)}"),
CommandSpec::new("chprop", "Change Properties", chprop::run_chprop)
.params("as properties.set, leaving out objects on locked layers → {changed, locked} (the command line asks Color, LAyer, LType, ltScale, LWeight, Thickness and TRansparency in turn)")
CommandSpec::new("properties.set", "Set Properties", run_set).params("{handles?, layer?, color?, linetype?, lineweight?, ltscale?, thickness?, transparency?: \"ByLayer\" | \"ByBlock\" | 0..90, visible?, <geometry fields: radius, center, start, end, text, height, rotation…>; dimensions: textOverride, dimStyle, textHeight, arrowSize, dimScale, precision (per-dimension overrides)} → {changed, locked, message?}: objects on locked layers (and, during REFEDIT, outside the working set) are left out, and `message` says how many"),
CommandSpec::new("chprop", "Change Properties", run_set)
.params("as properties.set, leaving out objects on locked layers (and, during REFEDIT, outside the working set) → {changed, locked, message?} (the command line asks Color, LAyer, LType, ltScale, LWeight, Thickness and TRansparency in turn)")
.interactive(|_| Ok(Box::new(chprop::ChpropM::new()))),
CommandSpec::new("change", "Change", change::run_change)
.alias(&["-ch"])
@@ -196,11 +196,74 @@ fn set_xy(p: &mut Vec3, v: &Value) {
}
}
/// The objects `properties.set` leaves alone, as CHPROP, MATCHPROP and MOVE do: those on locked
/// layers and, while a reference is edited in place, those outside the working set.
#[derive(Default)]
struct LeftOut {
locked: usize,
outside: usize,
}
impl LeftOut {
/// `hs` without the objects that can't be edited, each object once, and how many those were. A
/// handle that names no object is an error, before anything changes.
fn split(s: &Session, hs: Vec<Handle>) -> Result<(Vec<Handle>, LeftOut)> {
let d = s.doc()?;
// The working set, once: `RefEdit::is_working` searches a list.
let working: Option<std::collections::HashSet<Handle>> = d.refedit.as_ref().map(|r| r.items.iter().map(|i| i.copy).collect());
let mut seen = std::collections::HashSet::new();
let mut out = LeftOut::default();
let mut free = Vec::new();
for h in hs {
let Some(e) = d.entity(h) else {
return Err(cadcraft_doc::DocError::NoEntity(h).into());
};
if !seen.insert(h) {
continue;
}
if working.as_ref().is_some_and(|w| !w.contains(&h)) {
out.outside += 1;
} else if d.layer(&e.common.layer).is_some_and(|l| l.locked) {
out.locked += 1;
} else {
free.push(h);
}
}
Ok((free, out))
}
/// `{changed, locked}`, and a message saying how many were left out when any were.
fn result(&self, changed: usize) -> Value {
let mut notes = Vec::new();
match self.locked {
0 => {}
1 => notes.push("1 object was on a locked layer.".to_string()),
n => notes.push(format!("{n} objects were on a locked layer.")),
}
match self.outside {
0 => {}
1 => notes.push("1 object was not in the working set.".to_string()),
n => notes.push(format!("{n} objects were not in the working set.")),
}
if changed == 0 && !notes.is_empty() {
notes.push("Nothing was changed.".to_string());
}
let mut r = json!({ "changed": changed, "locked": self.locked + self.outside });
if !notes.is_empty()
&& let Some(o) = r.as_object_mut()
{
o.insert("message".into(), json!(notes.join(" ")));
}
r
}
}
fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
if hs.is_empty() {
return Err(bad("properties.set", "nothing selected"));
}
let (hs, left_out) = LeftOut::split(s, hs)?;
let color = p.get("color").map(|c| parse_color(c).ok_or_else(|| bad("properties.set", "bad colour"))).transpose()?;
let transparency = p
.get("transparency")
@@ -211,7 +274,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
.map(|v| v.as_f64().filter(|x| x.is_finite()).ok_or_else(|| bad("properties.set", "thickness must be a finite number")))
.transpose()?;
let lw = p.get("lineweight").map(|v| super::layer::parse_lw(v).ok_or_else(|| bad("properties.set", "bad lineweight"))).transpose()?;
let d = s.doc_mut()?;
let d = s.doc()?;
// An explicit object linetype must be ByLayer, ByBlock or a loaded definition (as `linetype current` requires).
let linetype = str_param(p, "linetype")
.map(|n| {
@@ -222,13 +285,18 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
})
.transpose()?;
if let Some(l) = str_param(p, "layer") {
d.ensure_layer(l);
}
let dim_style = str_param(p, "dimStyle")
.map(|n| d.dim_style(n).map(|st| st.name.clone()).ok_or_else(|| bad("properties.set", format!("dimension style `{n}` not found"))))
.transpose()?;
let dim_over = dim_overrides(p)?;
if hs.is_empty() {
// Every object was left out: the drawing stays as it was, with no undo step.
return Ok(left_out.result(0));
}
let d = s.doc_mut()?;
if let Some(l) = str_param(p, "layer") {
d.ensure_layer(l);
}
let anno_scale = d.current_anno_scale();
let common = CommonEntityProperties { anno_scale: &anno_scale, color, linetype: linetype.as_deref(), lineweight: lw, transparency, thickness };
for h in &hs {
@@ -237,7 +305,7 @@ fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
apply_kind_properties(e, p, dim_style.as_ref(), &dim_over);
})?;
}
Ok(json!({ "changed": hs.len() }))
Ok(left_out.result(hs.len()))
}
fn apply_kind_properties(
+7 -30
View File
@@ -23,7 +23,6 @@ use serde_json::{Value, json};
use super::super::curves::{KW, is_locked};
use super::super::machines::{SelOutcome, SelectPhase, number};
use super::super::targets;
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
const PROPERTIES: [&str; 7] = ["Color", "LAyer", "LType", "ltScale", "LWeight", "Thickness", "TRansparency"];
@@ -90,13 +89,18 @@ impl ChpropM {
if vals.all(|v| v == first) { first } else { "varies".into() }
}
/// Apply `props` to the selection through `properties.set`.
/// Apply `props` to the selection through `properties.set`, saying what it left out: objects
/// this command moved onto a locked layer, say.
fn apply(&self, s: &mut Session, props: Value) -> Result<()> {
let mut p = json!({ "handles": self.handles.iter().map(|h| h.hex()).collect::<Vec<_>>() });
if let (Some(p), Value::Object(props)) = (p.as_object_mut(), props) {
p.extend(props);
}
super::run_set(s, &p).map(|_| ())
let r = super::run_set(s, &p)?;
if let Some(m) = r.get("message").and_then(Value::as_str) {
s.echo(m.to_string());
}
Ok(())
}
/// Take an answer to `ask`; `false` when it was refused (the prompt comes again).
@@ -237,33 +241,6 @@ pub(super) fn feed_unlocked(select: &mut SelectPhase, s: &mut Session, i: Input)
Ok(outcome)
}
/// CHPROP's JSON form: `properties.set` on the objects that are not on locked layers, which the
/// command leaves out too; "locked" says how many were.
pub(super) fn run_chprop(s: &mut Session, p: &Value) -> Result<Value> {
let hs = targets(s, p)?;
let locked = locked(s, &hs);
if locked.is_empty() {
return super::run_set(s, p).map(|r| with_locked(r, 0));
}
let free: Vec<Handle> = hs.into_iter().filter(|h| !locked.contains(h)).collect();
let r = if free.is_empty() {
json!({ "changed": 0 })
} else {
let mut q = p.as_object().cloned().unwrap_or_default();
q.insert("handles".into(), json!(free.iter().map(|h| h.hex()).collect::<Vec<_>>()));
super::run_set(s, &Value::Object(q))?
};
Ok(with_locked(r, locked.len()))
}
/// `r` with how many objects were left out on locked layers.
fn with_locked(mut r: Value, n: usize) -> Value {
if let Some(o) = r.as_object_mut() {
o.insert("locked".into(), json!(n));
}
r
}
/// A colour typed at CHPROP: 1–255, a name, BYLAYER or BYBLOCK (not 0 or 256, which COLOR takes).
fn color(t: &str) -> Option<Color> {
if t.bytes().all(|b| b.is_ascii_digit()) {
+3 -3
View File
@@ -36,7 +36,7 @@ fn misses_edges(e: &EngineError) -> bool {
}
/// Trim or extend `h` at `at`. A Quick-mode (`quick`) trim of an object no cutting edge crosses
/// erases it. Returns the handles that replace `h` (none when it was erased).
/// erases it. Returns what `h` became: its pieces, `h` itself first (none when it was erased).
fn apply(s: &mut Session, h: Handle, at: Vec2, extending: bool, edges: Edges, quick: bool) -> Result<Vec<Handle>> {
if extending {
extend(s, h, at, edges)?;
@@ -118,8 +118,8 @@ fn crossing(s: &mut Session, a: Vec2, b: Vec2, extending: bool, edges: Edges, qu
run_picks(s, work, extending, edges, quick, tol)
}
/// Trim (or extend) each object at its pick points. A trim replaces the object with pieces, so
/// later picks go to the piece within `tol` of the point (none: that part is already gone).
/// Trim (or extend) each object at its pick points. A trim leaves the object in pieces, so later
/// picks go to the piece within `tol` of the point (none: that part is already gone).
fn run_picks(s: &mut Session, work: Vec<(Handle, Vec<Vec2>)>, extending: bool, edges: Edges, quick: bool, tol: f64) -> Result<usize> {
let mut n = 0;
let mut last_err = None;
+50 -18
View File
@@ -1,5 +1,5 @@
//! View menu: ZOOM (with Realtime and Dynamic), PAN, REGEN, REDRAW, named views (VIEW), layout
//! switching.
//! View menu: ZOOM (with Realtime and Dynamic), PAN, REGEN, REDRAW, named views (VIEW), the view
//! twist (DVIEW TWist), layout switching.
use cadcraft_doc::{Space, entity_bounds};
use cadcraft_geom::{Bounds2, Vec2};
@@ -10,6 +10,7 @@ use super::{CommandSpec, bad, bool_or, f64_or, f64_req, ok, point_param, point_r
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step, View};
mod dview;
mod named_views;
mod vports;
@@ -95,10 +96,13 @@ pub fn specs() -> Vec<CommandSpec> {
.alias(&["r"])
.noundo()
.transparent(),
CommandSpec::new("view.set", "Set View", run_view_set).params("{center: [x,y], height}").noundo(),
dview::spec(),
CommandSpec::new("view.set", "Set View", run_view_set)
.params("{center: [x,y], height, twist?: degrees (default: keep the current twist; in a layout viewport it is the viewport's twist, an undoable edit; not in Paper space)}")
.noundo(),
CommandSpec::new("view.get", "Get View", |s, _| {
let v = s.state()?.view();
Ok(json!({"center": [v.center.x, v.center.y], "height": v.height, "viewportPx": [s.viewport_px.0, s.viewport_px.1]}))
Ok(json!({"center": [v.center.x, v.center.y], "height": v.height, "twist": v.twist.to_degrees(), "viewportPx": [s.viewport_px.0, s.viewport_px.1]}))
})
.noundo(),
CommandSpec::new("layout.set", "Switch Layout", run_layout_set).params("{name: \"Model\" | layout name}").noundo(),
@@ -120,8 +124,11 @@ fn fit(s: &mut Session, b: Bounds2) -> Result<()> {
let (w, h) = s.viewport_px;
let st = s.state_mut()?;
let aspect = st.zoom_aspect(w / h.max(1.0));
let height = b.height().max(b.width() / aspect.max(1e-6)).max(1e-9);
st.set_zoom_frame(View { center: b.center(), height });
// A twisted view fits the box the bounds make on screen.
let twist = st.zoom_frame().twist;
let (center, bw, bh) = View::twisted_box(b, twist);
let height = bh.max(bw / aspect.max(1e-6)).max(1e-9);
st.set_zoom_frame(View { center, height, twist });
Ok(())
}
@@ -150,18 +157,18 @@ pub(crate) fn zoom(s: &mut Session, p: &Value) -> Result<Value> {
let f = if mode == "in" { 2.0 } else { 0.5 };
let st = s.state_mut()?;
let v = st.zoom_frame();
st.set_zoom_frame(View { center: v.center, height: v.height / f });
st.set_zoom_frame(View { height: v.height / f, ..v });
}
"center" | "c" | "dynamic" | "d" => {
let c = point_req("zoom", p, "center")?;
let cur = s.state()?.zoom_frame().height;
let h = if p.get("factor").is_some() { factor_height(s, p, cur)? } else { f64_or(p, "height", cur) };
s.state_mut()?.set_zoom_frame(View { center: c, height: h.max(1e-9) });
let cur = s.state()?.zoom_frame();
let h = if p.get("factor").is_some() { factor_height(s, p, cur.height)? } else { f64_or(p, "height", cur.height) };
s.state_mut()?.set_zoom_frame(View { center: c, height: h.max(1e-9), ..cur });
}
"scale" | "s" => {
let v = s.state()?.zoom_frame();
let height = factor_height(s, p, v.height)?;
s.state_mut()?.set_zoom_frame(View { center: v.center, height });
s.state_mut()?.set_zoom_frame(View { height, ..v });
}
"realtime" => {
let v = s.state()?.zoom_frame();
@@ -169,7 +176,7 @@ pub(crate) fn zoom(s: &mut Session, p: &Value) -> Result<Value> {
if f <= 0.0 {
return Err(bad("zoom", "factor must be positive"));
}
s.state_mut()?.set_zoom_frame(View { center: v.center, height: (v.height / f).clamp(1e-9, 1e12) });
s.state_mut()?.set_zoom_frame(View { height: (v.height / f).clamp(1e-9, 1e12), ..v });
}
"object" | "o" => {
let hs = targets(s, p)?;
@@ -242,7 +249,8 @@ fn pan_frac(s: &mut Session, f: Vec2) -> Result<Value> {
let st = s.state_mut()?;
let v = st.view();
let ww = v.height * w / h.max(1.0);
st.set_view(View { center: v.center + Vec2::new(f.x * ww, f.y * v.height), height: v.height });
// Screen directions: in a twisted view the drawing is turned by the twist.
st.set_view(View { center: v.center + Vec2::new(f.x * ww, f.y * v.height).rotate(-v.twist), ..v });
ok()
}
@@ -258,7 +266,7 @@ fn run_pan(s: &mut Session, p: &Value) -> Result<Value> {
let b = point_req("pan", p, "to")?;
v.center - (b - a)
};
st.set_view(View { center: c, height: v.height });
st.set_view(View { center: c, ..v });
ok()
}
@@ -268,9 +276,33 @@ fn run_view_set(s: &mut Session, p: &Value) -> Result<Value> {
if h <= 0.0 {
return Err(bad("view.set", "height must be positive"));
}
if !s.state_mut()?.set_view(View { center: c, height: h }) {
let twist = match p.get("twist") {
Some(t) => t.as_f64().filter(|t| t.is_finite()).ok_or_else(|| bad("view.set", "twist must be a number of degrees"))?.to_radians(),
None => s.state()?.view().twist,
};
// As DVIEW TWist: the Model tab's view or the active layout viewport turns; a layout sheet
// (paper space) is never twisted.
let target = match dview::target(s) {
Ok(t) => Some(t),
Err(_) if twist == 0.0 => None,
Err(e) => return Err(e),
};
let before = (s.state()?.doc.clone(), s.state()?.selection.clone());
let twist = match target {
Some(t @ dview::Target::Viewport(_)) => {
dview::set_twist(s, t, twist)?;
s.state()?.view().twist
}
Some(dview::Target::Model) => cadcraft_geom::norm_angle(twist),
None => 0.0,
};
if !s.state_mut()?.set_view(View { center: c, height: h, twist }) {
s.state_mut()?.doc = before.0;
return Err(bad("view.set", "the view is too large to show. Nothing was changed"));
}
if let Some(dview::Target::Viewport(h)) = target {
dview::record_viewport_edit(s, before, h)?;
}
ok()
}
@@ -294,7 +326,7 @@ fn run_layout_set(s: &mut Session, p: &Value) -> Result<Value> {
let page = st.doc.layout(n).map(|l| l.page.clone()).unwrap_or_default();
let (w, h) = if page.landscape { (page.height_mm, page.width_mm) } else { (page.width_mm, page.height_mm) };
let unit = if st.doc.header.i64("MEASUREMENT", 0) == 1 { 1.0 } else { 1.0 / 25.4 };
st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15 });
st.set_view_quiet(View { center: Vec2::new(w * unit / 2.0, h * unit / 2.0), height: h * unit * 1.15, twist: 0.0 });
}
s.touch();
ok()
@@ -441,7 +473,7 @@ impl Interactive for ZoomM {
if st.view_history.last() == Some(&b.screen) {
st.view_history.pop();
}
st.set_zoom_frame(View { center: b.center, height: b.height });
st.set_zoom_frame(View { center: b.center, height: b.height, twist: b.frame.twist });
return Ok(Step::Done);
}
(ZoomStage::Dynamic(mut b), Input::Point(p)) => {
@@ -565,7 +597,7 @@ impl Session {
let f = 2f64.powf((-dy / half).clamp(-16.0, 16.0));
let st = self.state_mut()?;
let v = st.view();
st.set_view_quiet(View { center: v.center, height: (v.height / f).clamp(1e-9, 1e12) });
st.set_view_quiet(View { height: (v.height / f).clamp(1e-9, 1e12), ..v });
self.touch();
Ok(())
}
+441
View File
@@ -0,0 +1,441 @@
//! DVIEW: the dynamic view, on CADCraft's 2D plan views.
//!
//! It starts with "Select objects or <use DVIEWBLOCK>:": the objects
//! picked are the preview set, and Enter with nothing picked previews the DVIEWBLOCK block (the
//! drawing's own block of that name, else a built-in sample house). While DVIEW runs only the
//! preview set is drawn ([`Interactive::display_only`]); the whole drawing is regenerated when it
//! ends. Then it repeats "Enter option [CAmera/TArget/Distance/POints/PAn/Zoom/TWist/CLip/Hide/
//! Off/Undo]:" until Enter. TWist, PAn, Zoom, Off and Undo work; the options that need a 3D
//! camera say they are not available yet and stay at the option prompt.
//!
//! DVIEW works on the Model tab's view, or on the active (double-clicked) layout viewport; on a
//! layout with no active viewport it is not available. A Model tab twist is a view change like
//! ZOOM (view history, not undo). A layout viewport's twist belongs to the viewport entity, so a
//! DVIEW that changed it is one undo step.
use std::sync::Arc;
use cadcraft_doc::{Entity, EntityKind, Handle, Insert, Line, Space};
use cadcraft_geom::{Vec2, Vec3};
use serde_json::{Value, json};
use super::super::machines::{SelOutcome, SelectPhase, number};
use super::super::{CommandSpec, bad, f64_req};
use crate::{Accept, DisplayOnly, EngineError, Input, Interactive, Prompt, Result, Session, Snapshot, Step, View};
/// What DVIEW (and a view twist asked for anywhere) says on a layout with no active viewport.
pub(super) const PAPER_SPACE: &str = "This command is not available in Paper space.";
/// The option prompt's keywords, in prompt order.
const OPTIONS: &[&str] = &["CAmera", "TArget", "Distance", "POints", "PAn", "Zoom", "TWist", "CLip", "Hide", "Off", "Undo"];
/// The block DVIEW previews when nothing is selected.
const DVIEWBLOCK: &str = "DVIEWBLOCK";
pub(super) fn spec() -> CommandSpec {
CommandSpec::new("dview", "DView", run_dview)
.alias(&["dv"])
.params("{twist: degrees counterclockwise} (DVIEW TWist: the Model tab's view twist, or the active layout viewport's, an undoable edit; not in Paper space)")
.noundo()
.interactive(|s| {
// Refused as it starts on a layout with no active viewport.
target(s)?;
Ok(Box::new(DviewM::default()))
})
}
/// The view DVIEW changes.
#[derive(Clone, Copy, Debug, PartialEq)]
pub(super) enum Target {
/// The Model tab's view.
Model,
/// The active (MSPACE) layout viewport: its own view twist.
Viewport(Handle),
}
/// The view DVIEW changes: the active layout viewport, else the Model tab's view. A layout with
/// no active viewport has none.
pub(super) fn target(s: &Session) -> Result<Target> {
let st = s.state()?;
if let Some((h, _)) = st.active_viewport() {
return Ok(Target::Viewport(h));
}
if st.space == Space::Model {
return Ok(Target::Model);
}
Err(EngineError::Other(PAPER_SPACE.into()))
}
/// A twist kept as files hold it: [0, 2π).
fn normal(twist: f64) -> f64 {
cadcraft_geom::norm_angle(twist)
}
/// The active viewport's twist, if it is `h`.
fn viewport_twist(s: &Session, h: Handle) -> Option<f64> {
s.state().ok()?.active_viewport().filter(|(vh, _)| *vh == h).map(|(_, vp)| vp.view_twist())
}
/// Turn `target`'s view to `twist` radians. The Model tab's twist is a view change (view
/// history, like ZOOM); a viewport's is a change to the viewport entity, which the caller
/// records as an undo step ([`record_viewport_edit`]).
pub(super) fn set_twist(s: &mut Session, target: Target, twist: f64) -> Result<()> {
if !twist.is_finite() {
return Err(bad("dview", "the twist must be a finite angle"));
}
let twist = normal(twist);
match target {
Target::Model => {
let st = s.state_mut()?;
let v = st.view();
st.set_view(View { twist, ..v });
}
Target::Viewport(h) => {
if viewport_twist(s, h) == Some(twist) {
return Ok(());
}
// A locked viewport keeps its view, the twist with it.
if s.state()?.active_viewport().is_some_and(|(vh, vp)| vh == h && vp.locked) {
return Err(EngineError::Other("The viewport is locked.".into()));
}
let space = s.state()?.space.clone();
let d = s.doc_mut()?;
if let Some(store) = d.space_mut(&space) {
store.modify(h, |e| {
if let EntityKind::Viewport(vp) = &mut e.kind {
vp.twist = twist;
}
});
}
}
}
Ok(())
}
/// Record a layout viewport's twist change as one undo step, `before` being the drawing (and
/// selection) before it. Nothing when the twist did not change, and nothing inside a LISP routine
/// (its own single step holds it).
pub(super) fn record_viewport_edit(s: &mut Session, before: (Arc<cadcraft_doc::Drawing>, Vec<Handle>), h: Handle) -> Result<()> {
let old = before.0.entity(h).and_then(|e| match &e.kind {
EntityKind::Viewport(vp) => Some(vp.view_twist()),
_ => None,
});
if old == viewport_twist(s, h) || s.lisp_groups_undo() {
return Ok(());
}
let st = s.state_mut()?;
if !Arc::ptr_eq(&before.0, &st.doc) {
st.push_undo(Snapshot { label: "DView".into(), doc: before.0, selection: before.1 });
st.revision += 1;
}
Ok(())
}
/// The drawing and selection now, for [`record_viewport_edit`].
fn snapshot(s: &Session) -> Result<(Arc<cadcraft_doc::Drawing>, Vec<Handle>)> {
let st = s.state()?;
Ok((st.doc.clone(), st.selection.clone()))
}
fn run_dview(s: &mut Session, p: &Value) -> Result<Value> {
let t = target(s)?;
let deg = f64_req("dview", p, "twist")?;
let before = snapshot(s)?;
set_twist(s, t, deg.to_radians())?;
if let Target::Viewport(h) = t {
record_viewport_edit(s, before, h)?;
}
let v = s.state()?.view();
Ok(json!({ "twist": v.twist.to_degrees() }))
}
/// The built-in DVIEWBLOCK: a house front in the unit square, origin at the lower-left corner
/// (the size and origin a DVIEWBLOCK of one's own is expected to have). CADCraft's own drawing.
fn sample_house() -> Vec<(Vec2, Vec2)> {
let p = Vec2::new;
let mut lines = Vec::new();
let mut poly = |pts: &[Vec2], closed: bool| {
for w in pts.windows(2) {
lines.push((w[0], w[1]));
}
if closed && let (Some(a), Some(b)) = (pts.last(), pts.first()) {
lines.push((*a, *b));
}
};
// Walls.
poly(&[p(0.1, 0.0), p(0.9, 0.0), p(0.9, 0.6), p(0.1, 0.6)], true);
// Roof with eaves, and a chimney on its right slope.
poly(&[p(0.0, 0.55), p(0.5, 1.0), p(1.0, 0.55)], false);
poly(&[p(0.7, 0.82), p(0.7, 0.95), p(0.8, 0.95), p(0.8, 0.73)], false);
// Door.
poly(&[p(0.42, 0.0), p(0.42, 0.35), p(0.58, 0.35), p(0.58, 0.0)], false);
// Two windows with their bars.
for x in [0.17, 0.67] {
poly(&[p(x, 0.25), p(x + 0.16, 0.25), p(x + 0.16, 0.45), p(x, 0.45)], true);
poly(&[p(x + 0.08, 0.25), p(x + 0.08, 0.45)], false);
poly(&[p(x, 0.35), p(x + 0.16, 0.35)], false);
}
lines
}
#[derive(Clone, Copy, Debug, Default, PartialEq)]
enum Stage {
#[default]
Select,
Option,
Twist,
PanBase,
PanSecond(Vec2),
Zoom,
}
/// DVIEW, interactive.
#[derive(Default)]
struct DviewM {
stage: Stage,
sel: SelectPhase,
/// The preview set; empty with `sample` set: the DVIEWBLOCK.
preview: Vec<Handle>,
/// Where the DVIEWBLOCK preview stands: its lower-left corner and size (drawing units), fixed
/// as the options start so that PAn and Zoom move the view, not the house.
sample: Option<(Vec2, f64)>,
/// The views before each DVIEW action, for Undo.
undo: Vec<View>,
/// What DVIEW works on, and the drawing as it started (a viewport's twist change is one
/// undo step).
target: Option<Target>,
before: Option<(Arc<cadcraft_doc::Drawing>, Vec<Handle>)>,
}
impl DviewM {
fn target(&self, s: &Session) -> Result<Target> {
match self.target {
Some(t) => Ok(t),
None => target(s),
}
}
/// Start the options with this preview set (empty: the DVIEWBLOCK).
fn options(&mut self, s: &mut Session, picked: Vec<Handle>) -> Result<Step> {
// Objects picked at the prompt don't stay selected.
s.set_selection(Vec::new());
if picked.is_empty() {
let v = s.state()?.view();
let size = v.height * 0.5;
self.sample = Some((v.center - Vec2::new(size, size) * 0.5, size));
}
self.preview = picked;
self.stage = Stage::Option;
Ok(Step::Continue)
}
/// Show view `v` (centre, height and twist) on the target.
fn show(&self, s: &mut Session, v: View) -> Result<()> {
let t = self.target(s)?;
let before = s.state()?.doc.clone();
let twist = normal(v.twist);
if let Target::Viewport(_) = t {
// The twist is the viewport's; the view inside it then moves as asked.
set_twist(s, t, twist)?;
}
if !s.state_mut()?.set_view(View { twist, ..v }) {
s.state_mut()?.doc = before;
return Err(EngineError::Other("The view is too large to show.".into()));
}
Ok(())
}
/// Apply a view as one DVIEW action (Undo takes it back).
fn change(&mut self, s: &mut Session, f: impl FnOnce(View) -> View) -> Result<()> {
let v = s.state()?.view();
self.show(s, f(v))?;
self.undo.push(v);
Ok(())
}
/// The command ends: a viewport twist change becomes one undo step, and the whole drawing is
/// regenerated.
fn end(&mut self, s: &mut Session) -> Result<()> {
if let (Some(Target::Viewport(h)), Some(before)) = (self.target, self.before.take()) {
record_viewport_edit(s, before, h)?;
}
s.touch();
Ok(())
}
}
impl Interactive for DviewM {
fn name(&self) -> &'static str {
"DVIEW"
}
fn begin(&mut self, s: &mut Session) -> Result<Step> {
self.target = Some(target(s)?);
self.before = Some(snapshot(s)?);
Ok(Step::Continue)
}
fn prompt(&self, s: &Session) -> Prompt {
match self.stage {
Stage::Select if self.sel.removing => self.sel.prompt(),
Stage::Select => Prompt::new("Select objects or", Accept::SELECT).default("use DVIEWBLOCK"),
Stage::Option => Prompt::new("Enter option", Accept::TEXT).kw(OPTIONS),
Stage::Twist => {
let (au, ap) = s.doc().map(|d| (d.header.i64("AUNITS", 0), d.header.i64("AUPREC", 0))).unwrap_or((0, 0));
let cur = s.state().map(|st| st.view().twist).unwrap_or(0.0);
// Offered as it would be typed: clockwise is positive when ANGDIR is 1.
let cur = if s.angle_settings().clockwise { -cur } else { cur };
let center = s.state().map(|st| st.view().center).ok();
Prompt::new("Specify view twist angle", Accept::POINT_OR_NUMBER).default(crate::units::format_angle(cur, au, ap)).base_opt(center)
}
Stage::PanBase => Prompt::new("Specify displacement base point", Accept::POINT),
Stage::PanSecond(b) => Prompt::new("Specify second point", Accept::POINT).base(b),
Stage::Zoom => Prompt::new("Specify zoom scale factor", Accept::NUMBER).default("1"),
}
}
fn cancelled(&mut self, s: &mut Session) {
if let Err(e) = self.end(s) {
s.echo(e.to_string());
}
}
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
match self.stage {
Stage::Select => match self.sel.feed(s, &i)? {
SelOutcome::More => Ok(Step::Continue),
SelOutcome::Empty => self.options(s, Vec::new()),
SelOutcome::Done(hs) => self.options(s, hs),
},
Stage::Option => {
let word = match &i {
Input::Enter => {
self.end(s)?;
return Ok(Step::Done);
}
Input::Keyword(t) | Input::Text(t) => self.prompt(s).match_keyword(t),
_ => None,
};
match word.as_deref() {
Some("TWist") => self.stage = Stage::Twist,
Some("PAn") => self.stage = Stage::PanBase,
Some("Zoom") => self.stage = Stage::Zoom,
// Perspective is never on in a 2D view: there is nothing to turn off.
Some("Off") => {}
Some("Undo") => {
if let Some(v) = self.undo.pop() {
self.show(s, v)?;
}
}
// CAmera, TArget, Distance, POints, CLip and Hide need a 3D view.
Some(other) => s.echo(format!("DVIEW {other} is not available yet.")),
None => return Err(EngineError::Other("Invalid option keyword.".into())),
}
Ok(Step::Continue)
}
Stage::Twist => {
let twist = match &i {
Input::Enter => None,
Input::Point(p) => {
let c = s.state()?.view().center;
let d = *p - c;
if d.len() < 1e-12 {
return Err(EngineError::Other("Requires a valid angle.".into()));
}
Some(d.y.atan2(d.x))
}
Input::Text(t) | Input::Keyword(t) if t.trim().is_empty() => None,
Input::Text(t) | Input::Keyword(t) => {
Some(s.angle_settings().rotation(t).ok_or_else(|| EngineError::Other("Requires a valid angle.".into()))?)
}
_ => return Ok(Step::Continue),
};
if let Some(a) = twist {
self.change(s, |v| View { twist: normal(a), ..v })?;
}
self.stage = Stage::Option;
Ok(Step::Continue)
}
Stage::PanBase => match i {
Input::Point(p) => {
self.stage = Stage::PanSecond(p);
Ok(Step::Continue)
}
Input::Enter => {
self.stage = Stage::Option;
Ok(Step::Continue)
}
_ => Err(EngineError::Other("Invalid point.".into())),
},
Stage::PanSecond(b) => match i {
Input::Point(p) => {
self.change(s, |v| View { center: v.center - (p - b), ..v })?;
self.stage = Stage::Option;
Ok(Step::Continue)
}
Input::Enter => {
self.stage = Stage::Option;
Ok(Step::Continue)
}
_ => Err(EngineError::Other("Invalid point.".into())),
},
Stage::Zoom => {
let f = match &i {
Input::Enter => None,
Input::Text(t) | Input::Keyword(t) if t.trim().is_empty() => None,
Input::Text(t) | Input::Keyword(t) => match number(t) {
Some(f) if f.is_finite() && f > 0.0 => Some(f),
_ => return Err(EngineError::Other("Requires a positive number.".into())),
},
_ => return Ok(Step::Continue),
};
if let Some(f) = f.filter(|f| *f != 1.0) {
self.change(s, |v| View { height: v.height / f, ..v })?;
}
self.stage = Stage::Option;
Ok(Step::Continue)
}
}
}
fn display_only(&self, s: &Session) -> Option<DisplayOnly> {
if self.stage == Stage::Select {
return None;
}
let mut extra = Vec::new();
if let Some((corner, size)) = self.sample {
let common = s.current_common();
let d = s.doc().ok()?;
if d.block(DVIEWBLOCK).is_some() {
// The drawing's own DVIEWBLOCK, defined in a 1 by 1 unit area.
let ins = Insert {
block: DVIEWBLOCK.into(),
insert: corner.to3(0.0),
scale: Vec3::new(size, size, size),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
extra.push(Entity { handle: Handle(0), common, kind: EntityKind::Insert(ins) });
} else {
extra.extend(sample_house().into_iter().map(|(a, b)| Entity {
handle: Handle(0),
common: common.clone(),
kind: EntityKind::Line(Line { a: (corner + a * size).to3(0.0), b: (corner + b * size).to3(0.0) }),
}));
}
}
Some(DisplayOnly { handles: self.preview.clone(), extra })
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_sample_house_fits_the_unit_square() {
let lines = sample_house();
assert!(lines.len() > 10);
for (a, b) in lines {
for q in [a, b] {
assert!((0.0..=1.0).contains(&q.x) && (0.0..=1.0).contains(&q.y), "{q:?}");
}
}
}
}
+18 -5
View File
@@ -110,15 +110,25 @@ fn save(s: &mut Session, name: &str, window: Option<Bounds2>, snapshot: bool) ->
(Space::Paper(l), false) => Some(l.clone()),
_ => None,
};
// The view this saves: the viewport's model view inside an MSPACE viewport, else the screen.
let frame = if in_viewport { st.zoom_frame() } else { st.view() };
// The view twist goes with the view (paper space has none).
let twist = if layout.is_some() { 0.0 } else { frame.twist };
let (center, height, width) = match window {
Some(b) => {
if !(b.width() > 1e-12 && b.height() > 1e-12 && b.min.is_finite() && b.max.is_finite()) {
return Err(EngineError::Other("The window has no area.".into()));
}
(b.center(), b.height(), b.width())
// In a twisted view the window's box on screen is larger than its world box.
let (center, width, height) = crate::View::twisted_box(b, twist);
// Turning corners near the number limit can overflow: save no view that can't be restored.
if !(center.is_finite() && width.is_finite() && height.is_finite() && width > 1e-12 && height > 1e-12) {
return Err(EngineError::Other("The window is too large for a twisted view.".into()));
}
(center, height, width)
}
None => {
let f = if in_viewport { st.zoom_frame() } else { st.view() };
let f = frame;
let aspect = if in_viewport { st.zoom_aspect(w / h.max(1.0)) } else { w / h.max(1.0) };
(f.center, f.height, f.height * aspect)
}
@@ -139,7 +149,7 @@ fn save(s: &mut Session, name: &str, window: Option<Bounds2>, snapshot: bool) ->
}
d.views.retain(|v| !v.name.eq_ignore_ascii_case(old));
}
d.views.push(NamedView { name: name.to_string(), center, height, width, layer_state, twist: 0.0, layout });
d.views.push(NamedView { name: name.to_string(), center, height, width, layer_state, twist, layout });
let msg = if replaced.is_some() { format!("View \"{name}\" replaced.") } else { format!("View \"{name}\" saved.") };
Ok(json!({ "name": name, "center": [center.x, center.y], "height": height, "width": width, "message": msg }))
}
@@ -168,7 +178,7 @@ fn restore(s: &mut Session, name: &str) -> Result<Value> {
let st = s.state_mut()?;
st.mspace = None;
let height = v.height.max(v.width / (w / h.max(1.0)).max(1e-9));
st.set_view(View { center: v.center, height });
st.set_view(View { center: v.center, height, twist: 0.0 });
}
None => {
// A model space view: into the active MSPACE viewport, else on the Model tab.
@@ -177,8 +187,11 @@ fn restore(s: &mut Session, name: &str) -> Result<Value> {
}
let (w, h) = s.viewport_px;
let st = s.state_mut()?;
// In an unlocked MSPACE viewport the saved twist turns the viewport (an edit of the
// viewport, recorded as the command's undo step).
let aspect = st.zoom_aspect(w / h.max(1.0)).max(1e-9);
st.set_zoom_frame(View { center: v.center, height: v.height.max(v.width / aspect) });
let twist = cadcraft_geom::norm_angle(v.twist);
st.set_zoom_frame(View { center: v.center, height: v.height.max(v.width / aspect), twist });
}
}
let mut msg = format!("View \"{}\" restored.", v.name);
+5 -5
View File
@@ -104,7 +104,7 @@ fn rect(t: &VportTile) -> Rect {
}
fn view_of(t: &VportTile) -> View {
View { center: t.center, height: t.height }
View { center: t.center, height: t.height, twist: if t.twist.is_finite() { t.twist } else { 0.0 } }
}
fn active_config(d: &Drawing) -> Option<&VportConfig> {
@@ -117,7 +117,7 @@ fn live(st: &DocState, px: (f64, f64)) -> (Vec<VportTile>, usize) {
let now = st.views.iter().find(|(sp, _)| *sp == Space::Model).map(|(_, v)| *v).unwrap_or_default();
let Some(cfg) = active_config(&st.doc) else {
let aspect = px.0 / px.1.max(1.0);
return (vec![VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center: now.center, height: now.height, aspect }], 0);
return (vec![VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center: now.center, height: now.height, aspect, twist: now.twist }], 0);
};
let mut tiles = cfg.tiles.clone();
let synced =
@@ -125,11 +125,11 @@ fn live(st: &DocState, px: (f64, f64)) -> (Vec<VportTile>, usize) {
let active = if synced { st.tiles.active.min(tiles.len() - 1) } else { 0 };
if synced {
for (t, v) in tiles.iter_mut().zip(&st.tiles.views) {
(t.center, t.height) = (v.center, v.height);
(t.center, t.height, t.twist) = (v.center, v.height, v.twist);
}
}
if let Some(t) = tiles.get_mut(active) {
(t.center, t.height) = (now.center, now.height);
(t.center, t.height, t.twist) = (now.center, now.height, now.twist);
}
// Screen aspects from the current tile's size in pixels.
if let Some(cur) = tiles.get(active).copied() {
@@ -171,7 +171,7 @@ fn summary(s: &Session) -> Result<Value> {
let rows: Vec<Value> = tiles
.iter()
.enumerate()
.map(|(i, t)| json!({ "index": i + 1, "min": [t.min.x, t.min.y], "max": [t.max.x, t.max.y], "center": [t.center.x, t.center.y], "height": t.height, "current": i == active }))
.map(|(i, t)| json!({ "index": i + 1, "min": [t.min.x, t.min.y], "max": [t.max.x, t.max.y], "center": [t.center.x, t.center.y], "height": t.height, "twist": t.twist.to_degrees(), "current": i == active }))
.collect();
Ok(json!({ "tiles": rows }))
}
+46 -9
View File
@@ -1,5 +1,5 @@
use super::view::{ModelTiles, View, usable_view};
use super::{Arc, Drawing, Handle, Space, blockedit, undoctl};
use super::{Arc, Drawing, Handle, Space, Vec2, blockedit, undoctl};
#[derive(Clone, Debug)]
pub struct Snapshot {
@@ -80,6 +80,7 @@ impl DocState {
pub(crate) fn swap_in(&mut self, snap: Snapshot) -> Snapshot {
let cur = Snapshot { label: snap.label, doc: std::mem::replace(&mut self.doc, snap.doc), selection: std::mem::take(&mut self.selection) };
self.follow_layout(&cur.doc);
self.reconcile_untiled_twist();
self.revision += 1;
cur
}
@@ -135,7 +136,8 @@ impl DocState {
match self.active_viewport() {
Some((_, vp)) => {
let k = vp.view_height / vp.height;
View { center: vp.view_center + (pv.center - vp.center.xy()) * k, height: pv.height * k }
// The viewport's twist turns the model view inside it.
View { center: vp.paper_to_model(pv.center), height: pv.height * k, twist: vp.view_twist() }
}
None => pv,
}
@@ -150,16 +152,18 @@ impl DocState {
if vp.locked {
// A locked viewport keeps its scale: pan/zoom the sheet instead.
let k0 = vp.view_height / vp.height;
let pc = vp.center.xy() + (v.center - vp.view_center) / k0;
let paper = View { center: pc, height: v.height / k0 };
let pc = vp.model_to_paper(v.center);
let paper = View { center: pc, height: v.height / k0, twist: pv.twist };
if !usable_view(&paper) {
return false;
}
self.put_paper_view(paper);
} else {
let center = v.center - (pv.center - vp.center.xy()) * k;
// `v`'s twist is the one the viewport shows (a non-finite one keeps its own).
let twist = if v.twist.is_finite() { v.twist } else { vp.view_twist() };
let center = v.center - ((pv.center - vp.center.xy()) * k).rotate(-twist);
let height = vp.height * k;
if !usable_view(&View { center, height }) {
if !usable_view(&View { center, height, twist }) {
return false;
}
let doc = Arc::make_mut(&mut self.doc);
@@ -168,6 +172,7 @@ impl DocState {
if let cadcraft_doc::EntityKind::Viewport(x) = &mut e.kind {
x.view_center = center;
x.view_height = height;
x.twist = twist;
}
});
}
@@ -182,6 +187,36 @@ impl DocState {
Some((_, slot)) => *slot = v,
None => self.views.push((self.space.clone(), v)),
}
if self.space == Space::Model {
self.keep_untiled_twist(v);
}
}
/// An untiled Model tab keeps its view twist in the drawing as a lone `*Active` VPORT tile
/// (written as that record's group 51 and read back), so it survives save and reopen. Only a
/// change of twist touches the drawing; an untwisted view keeps no record.
/// After undo or redo has put back another drawing: its untiled-twist record follows the
/// Model tab's live view again (views are not part of the drawing's undo).
pub(crate) fn reconcile_untiled_twist(&mut self) {
if let Some(v) = self.views.iter().find(|(s, _)| *s == Space::Model).map(|(_, v)| *v) {
self.keep_untiled_twist(v);
}
}
fn keep_untiled_twist(&mut self, v: View) {
use cadcraft_doc::{VportConfig, VportTile};
let twist = cadcraft_geom::norm_angle(v.twist);
let active = self.doc.vports.iter().find(|c| c.is_active());
if active.is_some_and(|c| c.tiles.len() > 1) {
return;
}
if active.and_then(|c| c.tiles.first()).map_or(0.0, |t| t.twist) == twist {
return;
}
let d = Arc::make_mut(&mut self.doc);
d.vports.retain(|c| !c.is_active());
if twist != 0.0 {
let tile = VportTile { min: Vec2::ZERO, max: Vec2::new(1.0, 1.0), center: v.center, height: v.height, aspect: 1.0, twist };
d.vports.insert(0, VportConfig { name: VportConfig::ACTIVE.into(), tiles: vec![tile] });
}
}
/// Set the view, recording view history. Returns false, changing nothing, when the view (or,
/// in MSPACE, the viewport view it maps to) isn't finite with a positive height.
@@ -210,7 +245,7 @@ impl DocState {
/// The view ZOOM starts from: the model view of the active unlocked viewport, else [`Self::view`].
pub fn zoom_frame(&self) -> View {
match self.zoom_viewport() {
Some(v) => View { center: v.view_center, height: v.view_height },
Some(v) => View { center: v.view_center, height: v.view_height, twist: v.view_twist() },
None => self.view(),
}
}
@@ -225,7 +260,9 @@ impl DocState {
Some(vp) => {
let pv = self.paper_view();
let k = f.height / vp.height;
View { center: f.center + (pv.center - vp.center.xy()) * k, height: pv.height * k }
// The frame's twist turns the viewport (a non-finite one keeps the viewport's).
let twist = if f.twist.is_finite() { f.twist } else { vp.view_twist() };
View { center: f.center + ((pv.center - vp.center.xy()) * k).rotate(-twist), height: pv.height * k, twist }
}
None => f,
};
@@ -233,7 +270,7 @@ impl DocState {
}
/// Set without recording view history (realtime pan/zoom frames).
pub fn set_view_quiet(&mut self, v: View) {
if !(v.center.is_finite() && v.height.is_finite() && v.height > 1e-12) {
if !usable_view(&v) {
return;
}
self.store_view(v);
+17
View File
@@ -66,6 +66,14 @@ impl Interactive for Guarded {
fn begin(&mut self, s: &mut Session) -> Result<Step> {
catch_unwind(AssertUnwindSafe(|| self.inner.begin(s))).unwrap_or_else(|p| Err(self.internal(&*p)))
}
fn cancelled(&mut self, s: &mut Session) {
if self.broken.get().is_none()
&& let Err(p) = catch_unwind(AssertUnwindSafe(|| self.inner.cancelled(s)))
{
let e = self.internal(&*p);
s.echo(e.to_string());
}
}
fn preview(&self, s: &Session, cursor: Vec2) -> Vec<EntityKind> {
if self.broken.get().is_some() {
return Vec::new();
@@ -102,6 +110,15 @@ impl Interactive for Guarded {
None
})
}
fn display_only(&self, s: &Session) -> Option<crate::prompt::DisplayOnly> {
if self.broken.get().is_some() {
return None;
}
catch_unwind(AssertUnwindSafe(|| self.inner.display_only(s))).unwrap_or_else(|_| {
self.broken.set(Some("panic in preview"));
None
})
}
}
#[cfg(test)]
+2 -1
View File
@@ -27,6 +27,7 @@ pub mod mtext_edit;
pub mod pointmod;
pub mod prompt;
mod recent;
pub mod render_look;
pub mod sample;
pub mod select;
pub mod settings_dir;
@@ -49,7 +50,7 @@ pub use cadcraft_geom as geom;
pub use cadcraft_render as render;
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, Drag, Input, Interactive, Picker, Prompt, Step};
pub use prompt::{Accept, DisplayOnly, Drag, Input, Interactive, Picker, Prompt, Step};
mod doc_state;
mod error;
+21 -1
View File
@@ -31,7 +31,7 @@ impl Accept {
/// [Truecolor/COlorbook] <BYLAYER>:". A prompt asking for something else besides its keywords has
/// it: "Enter block name or [?]:", "Specify insertion base point or [Basepoint/…]:". Read from
/// AutoCAD's command line over measured runs, where no prompt was written both ways.
const NO_OR: [&str; 27] = [
const NO_OR: [&str; 28] = [
"Bring to front",
"Calculate rectangle dimensions based on",
"Choose mode for selected object conversion",
@@ -47,6 +47,7 @@ const NO_OR: [&str; 27] = [
"Enter leader format option",
"Enter line spacing type",
"Enter object ordering option",
"Enter option",
"Enter polyline linetype generation option",
"Enter property to change",
"Enter the type of array",
@@ -266,6 +267,9 @@ pub trait Interactive: Send {
fn begin(&mut self, _s: &mut Session) -> Result<Step> {
Ok(Step::Continue)
}
/// Called when the command is cancelled from outside (Esc, or another command starting),
/// before it finishes: what it records on every exit path.
fn cancelled(&mut self, _s: &mut Session) {}
/// Rubber-band geometry for the cursor position.
fn preview(&self, _s: &Session, _cursor: Vec2) -> Vec<EntityKind> {
Vec::new()
@@ -287,6 +291,22 @@ pub trait Interactive: Send {
fn editing_mtext(&self) -> Option<cadcraft_doc::MText> {
None
}
/// What the drawing area shows in place of the drawing while the command runs (DVIEW draws
/// only its preview set); `None` shows the drawing.
fn display_only(&self, _s: &Session) -> Option<DisplayOnly> {
None
}
}
/// See [`Interactive::display_only`]: the only things drawn in the current view while a command
/// runs. The whole drawing is drawn again when it ends.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct DisplayOnly {
/// Objects of the drawing, drawn as they are.
pub handles: Vec<Handle>,
/// Geometry that is not in the drawing (DVIEW's sample house, or an insert of the drawing's
/// DVIEWBLOCK block), with its own properties.
pub extra: Vec<cadcraft_doc::Entity>,
}
/// See [`Interactive::drag`].
+196
View File
@@ -0,0 +1,196 @@
//! How a render request draws: its `background` and `plot_style` (#803). The app's control
//! channel and the headless MCP backend both answer `ui.render`, and both read these here.
//!
//! Colour 7 (white/black) follows the background, as on a plot: the rasteriser draws it white on
//! a dark background and black on a light one ([`cadcraft_color::display_rgb`]).
//!
//! A render with a plot style table draws on white unless `background` says otherwise, as a plot
//! prints on paper: the tables that change colours print colour 7 (and, in `monochrome.ctb`,
//! every colour) black, which can hardly be seen on the dark canvas.
//!
//! `plot_style: "none"` (or `""`) draws every object with its own properties, also in a layout
//! whose page setup has "Display plot styles" on; without `plot_style` such a layout draws with
//! its own table, as on screen.
use std::sync::Arc;
use cadcraft_color::Rgb;
use cadcraft_doc::{Drawing, PlotStyleTable};
use cadcraft_render::raster::RasterOptions;
use serde_json::Value;
/// The background a render draws on without `background`: the dark canvas.
pub const DARK: Rgb = RasterOptions::DARK_BACKGROUND;
/// The background of `"white"` and `"paper"`.
pub const WHITE: Rgb = Rgb(255, 255, 255);
/// What `background` accepts, for the error message and the docs.
pub const BACKGROUNDS: &str = "\"dark\" (the default without a plot style), \"white\" (the default with one), \"paper\" or \"#rrggbb\"";
/// Most table names an unknown `plot_style` error lists from the drawing's own tables (the
/// built-in ones are always listed).
const MAX_LISTED_TABLES: usize = 10;
/// Longest part of a refused value repeated in its error message, in characters.
const MAX_ECHO_CHARS: usize = 40;
/// The look of a render: what it draws on and with which plot style table.
#[derive(Clone, Debug)]
pub struct RenderLook {
pub background: Rgb,
/// `None` = draw with the objects' own properties (or, in a layout showing plot styles, its
/// page setup's table). `plot_style: "none"` is a table that keeps every property, so such a
/// layout's table doesn't apply either.
pub plot_style_table: Option<Arc<PlotStyleTable>>,
}
impl Default for RenderLook {
fn default() -> Self {
RenderLook { background: DARK, plot_style_table: None }
}
}
impl RenderLook {
/// `background` and `plot_style` of a request's params for drawing `d`; absent or `null`
/// keeps the default. `Err` says what is accepted.
pub fn from_params(d: &Drawing, p: &Value) -> Result<RenderLook, String> {
let text = |key: &str| match p.get(key) {
None | Some(Value::Null) => Ok(None),
Some(Value::String(s)) => Ok(Some(s.as_str())),
Some(_) => Err(format!("`{key}` must be a string")),
};
let mut look = RenderLook::default();
if let Some(name) = text("plot_style")? {
look.plot_style_table = Some(Arc::new(match plot_style(d, name)? {
Some(t) => {
// Plotted on paper, unless `background` says otherwise.
look.background = WHITE;
t
}
None => object_properties(),
}));
}
if let Some(b) = text("background")? {
look.background = background(b).ok_or_else(|| format!("unknown background `{}`: use {BACKGROUNDS}", echo(b)))?;
}
Ok(look)
}
/// The raster options of a render with this look.
pub fn raster(&self) -> RasterOptions {
RasterOptions { background: self.background, ..RasterOptions::default() }
}
}
/// The colour of a `background` value (any case): `dark`, `white`, `paper` or `#rrggbb`.
pub fn background(v: &str) -> Option<Rgb> {
let v = v.trim();
match v.to_ascii_lowercase().as_str() {
"dark" => Some(DARK),
"white" | "paper" => Some(WHITE),
hex if hex.starts_with('#') => Rgb::parse_hex(hex),
_ => None,
}
}
/// The plot style table `name` names: one the drawing holds, or a built-in one (`.ctb` may be
/// left out); `none` or an empty name is no table. `Err` lists the tables there are.
fn plot_style(d: &Drawing, name: &str) -> Result<Option<PlotStyleTable>, String> {
if cadcraft_doc::no_plot_style_table(name) {
return Ok(None);
}
cadcraft_doc::plot_style_table(d, name.trim())
.map(Some)
.ok_or_else(|| format!("unknown plot style table `{}`: use none or one of {}", echo(name), table_list(d)))
}
/// The tables a drawing can use, for an error message: the built-in ones, then at most
/// [`MAX_LISTED_TABLES`] of the drawing's own and how many more there are.
fn table_list(d: &Drawing) -> String {
let builtin = |n: &String| cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES.iter().any(|b| b.eq_ignore_ascii_case(n));
let names = cadcraft_doc::plot_style_table_names(d);
let own: Vec<String> = names.iter().filter(|n| !builtin(n)).map(|n| echo(n)).collect();
let mut list: Vec<String> = cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES.iter().map(|b| (*b).to_string()).collect();
list.extend(own.iter().take(MAX_LISTED_TABLES).cloned());
let mut text = list.join(", ");
if own.len() > MAX_LISTED_TABLES {
text.push_str(&format!(" and {} more of the drawing's", own.len() - MAX_LISTED_TABLES));
}
text
}
/// A table that prints every object with its own properties: what `plot_style: "none"` draws
/// with, so a layout's own table doesn't apply either.
fn object_properties() -> PlotStyleTable {
PlotStyleTable::color_dependent("None", "Object properties", |_| None)
}
/// The start of a refused value, to repeat in its error message.
fn echo(v: &str) -> String {
v.chars().take(MAX_ECHO_CHARS).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
#[test]
fn backgrounds() {
assert_eq!(background("dark"), Some(DARK));
assert_eq!(DARK, RasterOptions::default().background, "the default is the rasteriser's canvas");
assert_eq!(background(" Paper "), Some(WHITE));
assert_eq!(background("WHITE"), Some(WHITE));
assert_eq!(background("#336699"), Some(Rgb(0x33, 0x66, 0x99)));
for bad in ["", "purple", "336699", "#12345", "#1234567", "##336699", "#33669g"] {
assert_eq!(background(bad), None, "{bad}");
}
}
#[test]
fn from_params() {
let d = Drawing::new_imperial();
let look = RenderLook::from_params(&d, &json!({})).unwrap();
assert_eq!(look.background, DARK);
assert!(look.plot_style_table.is_none());
// "none" keeps the dark canvas and draws every object with its own properties, also in a
// layout that shows its own plot styles.
for none in ["none", "", " None "] {
let look = RenderLook::from_params(&d, &json!({"background": null, "plot_style": none})).unwrap();
assert_eq!(look.background, DARK, "{none:?}");
let t = look.plot_style_table.unwrap();
assert!(t.is_color_dependent() && t.styles.iter().all(|s| s.keeps_color() && s.lineweight.is_none()), "{none:?}");
}
let look = RenderLook::from_params(&d, &json!({"background": "white", "plot_style": "Monochrome"})).unwrap();
assert_eq!(look.raster().background, WHITE);
assert_eq!(look.plot_style_table.map(|t| t.name.clone()).as_deref(), Some("monochrome.ctb"));
// A plot style plots on paper unless `background` says otherwise.
for table in ["monochrome.ctb", "grayscale.ctb", "default.stb"] {
assert_eq!(RenderLook::from_params(&d, &json!({"plot_style": table})).unwrap().background, WHITE, "{table}");
let look = RenderLook::from_params(&d, &json!({"plot_style": table, "background": "dark"})).unwrap();
assert_eq!(look.background, DARK, "{table}");
}
let e = RenderLook::from_params(&d, &json!({"plot_style": "nope.ctb"})).unwrap_err();
assert!(e.contains("nope.ctb") && e.contains("grayscale.ctb") && e.contains("none"), "{e}");
let e = RenderLook::from_params(&d, &json!({"background": "x".repeat(10_000)})).unwrap_err();
assert!(e.len() < 200 && e.contains("#rrggbb"), "{e}");
assert!(RenderLook::from_params(&d, &json!({"background": 1})).is_err());
assert!(RenderLook::from_params(&d, &json!({"plot_style": {}})).is_err());
}
/// An unknown plot style lists the built-in tables and only some of the drawing's own.
#[test]
fn unknown_plot_style_lists_a_few_tables() {
let mut d = Drawing::new_imperial();
for i in 0..500 {
d.plot_style_tables.push(PlotStyleTable::color_dependent(&format!("{}{i}.ctb", "own".repeat(30)), "", |_| None));
}
let e = RenderLook::from_params(&d, &json!({"plot_style": "nope.ctb"})).unwrap_err();
for b in cadcraft_doc::BUILTIN_PLOT_STYLE_TABLES {
assert!(e.contains(b), "{b}: {e}");
}
assert!(e.contains("and 490 more"), "{e}");
assert!(e.len() < 1000, "{} bytes: {e}", e.len());
assert!(RenderLook::from_params(&d, &json!({"plot_style": d.plot_style_tables[7].name.clone()})).is_ok());
}
}
+25
View File
@@ -36,6 +36,13 @@ pub fn hit_polylines(d: &Drawing, e: &Entity, tol: f64) -> Vec<Vec<Vec2>> {
}
v
}
// An OLE object's frame is drawn, so it is picked on its outline (the corners the extents and
// the renderer use); a frame with no width or height is drawn as a line, so it is picked as
// one. It stays out of prims(), which TRIM, object snap and the dimension commands read.
EntityKind::Unknown(u) if u.is_ole_frame() => match cadcraft_doc::ole_frame(&u.tags) {
Some(q) => vec![q.to_vec()],
None => Vec::new(),
},
kind => {
let mut out = Vec::new();
for p in kind.prims() {
@@ -507,6 +514,23 @@ mod tests {
assert_eq!(pick(&d, &Space::Model, Vec2::new(41.3, 50.0), 1.0), Some(line));
}
/// An OLE2FRAME draws as its frame, so a click on an edge picks it (review on #2587); a click in
/// the middle of the frame, or on a frame without both corners, does not.
#[test]
fn clicking_an_ole_frame_edge_selects_it() {
let tag = |code: i32, value: &str| cadcraft_doc::RawTag { code, value: value.into() };
let frame = |tags: Vec<cadcraft_doc::RawTag>| EntityKind::Unknown(cadcraft_doc::Unknown { dxf_type: "OLE2FRAME".into(), tags });
let mut d = Drawing::new_metric();
let h = d.add(&Space::Model, Common::default(), frame(vec![tag(10, "30"), tag(20, "-19"), tag(11, "35"), tag(21, "-22")])).unwrap();
d.add(&Space::Model, Common::default(), frame(vec![tag(10, "80"), tag(20, "80")])).unwrap();
let line = d.add(&Space::Model, Common::default(), frame(vec![tag(10, "60"), tag(20, "-19"), tag(11, "60"), tag(21, "-22")])).unwrap();
assert_eq!(pick(&d, &Space::Model, Vec2::new(32.5, -19.0), 0.2), Some(h), "top edge");
assert_eq!(pick(&d, &Space::Model, Vec2::new(35.0, -20.5), 0.2), Some(h), "right edge");
assert_eq!(pick(&d, &Space::Model, Vec2::new(32.5, -20.5), 0.2), None, "inside the frame");
assert_eq!(pick(&d, &Space::Model, Vec2::new(80.0, 80.0), 0.2), None, "a frame without a second corner");
assert_eq!(pick(&d, &Space::Model, Vec2::new(60.0, -20.0), 0.2), Some(line), "a frame with no width is drawn as a line and picked as one");
}
/// A block holding a diagonal dashed line, inserted at `scale`.
fn dashed_block(length: f64, scale: f64) -> (Drawing, Handle) {
let mut d = Drawing::new_imperial();
@@ -527,6 +551,7 @@ mod tests {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
(d, h)
+15 -6
View File
@@ -6,7 +6,7 @@ impl Session {
self.untitled_counter += 1;
let d = if metric { Drawing::new_metric() } else { Drawing::new_imperial() };
let mut st = DocState::new(d, &format!("Drawing{}", self.untitled_counter), None);
st.set_view_quiet(if metric { View { center: Vec2::new(210.0, 148.5), height: 297.0 } } else { View::default() });
st.set_view_quiet(if metric { View { center: Vec2::new(210.0, 148.5), height: 297.0, twist: 0.0 } } else { View::default() });
self.end_running();
self.docs.push(st);
self.active = self.docs.len() - 1;
@@ -17,12 +17,21 @@ impl Session {
/// Append a loaded drawing, fit the view to its model extents (aspect-corrected, minimum height 1e-6) when non-empty, end a running command, make it active, bump the epoch and return its index.
pub fn open_drawing(&mut self, d: Drawing, title: &str, path: Option<String>) -> usize {
let mut st = DocState::new(d, title, path);
// The view the file was saved at is the one every other reader opens on. Fitting the
// extents instead showed a drawing whose extents are dominated by far-off geometry at a
// view hundreds of times its content, with the drawing sub-pixel and no way to zoom in
// (#1602). The extents remain the fallback for a drawing that stores no view.
let saved = crate::view::saved_view(&st.doc);
let ext = st.doc.extents(&Space::Model);
if !ext.is_empty() {
st.set_view_quiet(View {
center: ext.center(),
height: (ext.height().max(ext.width() * self.viewport_px.1 / self.viewport_px.0.max(1.0)) * 1.1).max(1e-6),
});
// The current tile (the first), or the lone untiled view, keeps its saved twist.
let twist = cadcraft_geom::norm_angle(st.doc.vports.iter().find(|c| c.is_active()).and_then(|c| c.tiles.first()).map_or(0.0, |t| t.twist));
if let Some(v) = saved {
st.set_view_quiet(View { twist, ..v });
} else if ext.is_empty() {
st.set_view_quiet(View { twist, ..st.view() });
} else {
let (center, w, h) = View::twisted_box(ext, twist);
st.set_view_quiet(View { center, height: (h.max(w * self.viewport_px.1 / self.viewport_px.0.max(1.0)) * 1.1).max(1e-6), twist });
}
self.end_running();
self.docs.push(st);
+16 -3
View File
@@ -1,3 +1,5 @@
use crate::DisplayOnly;
use super::{
Arc, Bounds2, Drag, Drawing, EngineError, Entity, Handle, Input, PendingWindow, Prompt, Result, Running, Session, Snapshot, Step, Value, Vec2,
assoc, cmd, find_command, guard, pointmod, select, snap, sysvars,
@@ -199,7 +201,7 @@ impl Session {
Input::Point(p) => {
let ap = self.pixel_size() * self.settings.pickbox.max(1.0) * 1.5;
if let Some(pw) = self.pending_window.take() {
let crossing = p.x < pw.corner.x;
let crossing = self.window_is_crossing(pw.corner, p);
let hs = select::select_window(self.doc()?, &space, Bounds2::new(pw.corner, p), crossing);
return Ok(Some(Input::Pick(cmd::groups::expand(self, hs))));
}
@@ -279,7 +281,10 @@ impl Session {
let base = if matches!(input, Some(Input::Point(_))) { self.current_prompt().and_then(|p| p.base) } else { None };
let Some(mut run) = self.running.take() else { return Ok(()) };
let step = match input {
Some(Input::Cancel) => Ok(Step::Cancel),
Some(Input::Cancel) => {
run.machine.cancelled(self);
Ok(Step::Cancel)
}
Some(i) => {
if let Input::Point(p) = &i {
self.last_point = *p;
@@ -438,7 +443,8 @@ impl Session {
}
if self.running.is_some() {
if self.suspended.is_some() {
if let Some(nested) = self.running.take() {
if let Some(mut nested) = self.running.take() {
nested.machine.cancelled(self);
self.finish(nested, true);
}
self.running = self.suspended.take();
@@ -523,6 +529,13 @@ impl Session {
out
}
/// What the drawing area shows in place of the drawing while a command runs (DVIEW's preview
/// set, see [`Interactive::display_only`]), also while a transparent command interrupts it.
/// `None`: the drawing.
pub fn display_only(&self) -> Option<DisplayOnly> {
[&self.running, &self.suspended].into_iter().flatten().find_map(|r| r.machine.display_only(self))
}
/// The active command's preview as a transform of existing objects (see
/// [`Interactive::drag`]), with its extra rubber-band geometry as entities.
pub fn drag(&self, cursor: Vec2) -> Option<(Drag, Vec<Entity>)> {
+8 -1
View File
@@ -16,6 +16,13 @@ impl Session {
true
}
/// Whether a selection window from `corner` to `p` is a crossing window: it was dragged
/// leftwards on screen (in a twisted view, not along the drawing's X axis).
pub fn window_is_crossing(&self, corner: Vec2, p: Vec2) -> bool {
let twist = self.state().map_or(0.0, |st| st.view().twist);
(p - corner).rotate(twist).x < 0.0
}
/// A click with no command running: pick/toggle objects or start a selection window.
///
/// PICKADD on (the default): picks add to the selection and Shift removes. PICKADD off: each pick
@@ -24,7 +31,7 @@ impl Session {
let space = self.space();
let pickadd = self.settings.pickadd;
if let Some(pw) = self.pending_window.take() {
let crossing = p.x < pw.corner.x;
let crossing = self.window_is_crossing(pw.corner, p);
let hs = select::select_window(self.doc()?, &space, Bounds2::new(pw.corner, p), crossing);
let hs = cmd::groups::expand(self, hs);
let mut sel = if pickadd || shift { self.selection() } else { Vec::new() };
+5 -3
View File
@@ -23,8 +23,10 @@ impl Session {
let ext = if ext.is_empty() { self.zoom_limits()? } else { ext };
let st = self.state_mut()?;
let aspect = st.zoom_aspect(w / h.max(1.0));
let height = ext.height().max(ext.width() / aspect.max(1e-6)).max(1e-6) * 1.05;
st.set_zoom_frame(View { center: ext.center(), height });
let twist = st.zoom_frame().twist;
let (center, bw, bh) = View::twisted_box(ext, twist);
let height = bh.max(bw / aspect.max(1e-6)).max(1e-6) * 1.05;
st.set_zoom_frame(View { center, height, twist });
Ok(())
}
@@ -38,7 +40,7 @@ impl Session {
let h = (v.height / factor).clamp(1e-9, 1e12);
let k = h / v.height;
let c = about + (v.center - about) * k;
st.set_view_quiet(View { center: c, height: h });
st.set_view_quiet(View { center: c, height: h, twist: v.twist });
Ok(())
}
}
+1
View File
@@ -714,6 +714,7 @@ impl Sink<'_> {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
block_leaves(d, &ins, &Mat3::IDENTITY, 0, budget, frozen, &mut |k, m| self.object(k, Some(m)));
}
+7 -4
View File
@@ -40,7 +40,8 @@ impl<'a> Projection<'a> {
}
let half = Vec2::new(viewport.width / 2.0, viewport.height / 2.0);
let paper_clip = Bounds2::new(center - half, center + half);
let model_clip = Bounds2::new(viewport.view_center - half / scale, viewport.view_center + half / scale);
// The model box the viewport shows (turned, with a view twist).
let model_clip = Bounds2::from_points(paper_clip.corners().map(|p| viewport.paper_to_model(p)));
if ![paper_clip.min, paper_clip.max, model_clip.min, model_clip.max].into_iter().all(Vec2::is_finite) {
return None;
}
@@ -48,11 +49,11 @@ impl<'a> Projection<'a> {
}
pub fn to_model(&self, point: Vec2) -> Vec2 {
self.viewport.view_center + (point - self.viewport.center.xy()) / self.scale
self.viewport.paper_to_model(point)
}
fn to_paper(&self, point: Vec2) -> Vec2 {
self.viewport.center.xy() + (point - self.viewport.view_center) * self.scale
self.viewport.model_to_paper(point)
}
pub fn hit(&self, mut hit: SnapHit) -> Option<SnapHit> {
@@ -76,7 +77,9 @@ impl<'a> Projection<'a> {
if !(center.is_finite() && radius.is_finite() && radius > 0.0) {
return None;
}
SnapCurve::Arc { center, radius, start, end }
// The arc turns on the sheet with the viewport's twist.
let twist = self.viewport.view_twist();
SnapCurve::Arc { center, radius, start: start + twist, end: end + twist }
}
SnapCurve::Line { a, b } => {
let (a, b) = (self.to_paper(a), self.to_paper(b));
+2
View File
@@ -364,6 +364,7 @@ mod tests {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}),
8 if i % 40 == 8 => EntityKind::XLine(cadcraft_doc::RayLine { base: v3(x, y), dir: v3(r.r(-1.0, 1.0), 1.0) }),
8 if i % 40 == 18 => EntityKind::Ray(cadcraft_doc::RayLine { base: v3(x, y), dir: v3(1.0, r.r(-1.0, 1.0)) }),
@@ -546,6 +547,7 @@ mod tests {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).unwrap();
let small = Bounds2::new(Vec2::new(-2.0, -2.0), Vec2::new(2.0, 2.0));
+3
View File
@@ -184,6 +184,8 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
json!([v.center.x, v.center.y, 0.0])
}
"VIEWSIZE" => json!(s.state().ok()?.view().height),
// The view twist (DVIEW TWist), in degrees counterclockwise.
"VIEWTWIST" => json!(s.state().ok()?.view().twist.to_degrees()),
"EXTMIN" | "EXTMAX" => {
let d = s.doc().ok()?;
let e = d.extents(&s.space());
@@ -260,6 +262,7 @@ const READ_ONLY: &[&str] = &[
"DISTANCE",
"VIEWCTR",
"VIEWSIZE",
"VIEWTWIST",
"EXTMIN",
"EXTMAX",
"UNDOCTL",
+2
View File
@@ -74,6 +74,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
("TRIMEXTENDMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
("TRIMMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
("WIPEOUTFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
// XCLIP boundaries: 0 hidden, 1 shown and plotted, 2 shown but not plotted.
("XCLIPFRAME", Kind::Choice(&[0, 1, 2]), Def::Int(2)),
];
/// The standard lineweights in hundredths of a millimetre.
+62 -1
View File
@@ -179,13 +179,74 @@ fn json_execute_and_errors() {
assert_eq!(s.state().unwrap().undo.len(), 1);
}
/// A drawing is opened on the view it was saved at, as every other reader opens it. Fitting the
/// extents instead showed a drawing whose extents are dominated by far-off geometry at a view
/// hundreds of thousands of times its content: sub-pixel, and `ZOOM Extents` fits the same box
/// (#1602). The extents are still the fallback for a drawing that stores no view.
#[test]
fn a_drawing_opens_on_the_view_it_was_saved_at() {
let mut d = cadcraft_doc::Drawing::new_metric();
for (a, b) in [([0.0, 0.0], [100.0, 60.0]), ([5e6, 5e6], [5e6 + 100.0, 5e6 + 60.0])] {
let line = cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(a[0], a[1], 0.0), b: cadcraft_geom::Vec3::new(b[0], b[1], 0.0) };
d.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap();
}
d.header.set_saved_view(Vec2::new(50.0, 50.0), 20.0);
let mut s = Session::new();
s.open_drawing(d.clone(), "saved-view.dxf", None);
assert_eq!(s.state().unwrap().view(), View { center: Vec2::new(50.0, 50.0), height: 20.0, twist: 0.0 });
// No stored view: the extents, as before. They are what makes this drawing unusable without
// the stored one -- the fit is more than a hundred thousand times taller than the detail.
let mut plain = d.clone();
plain.header.vars.remove("VIEWCTR");
plain.header.vars.remove("VIEWSIZE");
let mut s = Session::new();
s.open_drawing(plain, "no-view.dxf", None);
assert!(s.state().unwrap().view().height > 5e6, "{:?}", s.state().unwrap().view());
// A stored view that cannot be shown is no view at all.
let mut broken = d;
broken.header.set("VIEWSIZE", cadcraft_doc::HVal::Real(0.0));
let mut s = Session::new();
s.open_drawing(broken, "broken-view.dxf", None);
assert!(s.state().unwrap().view().height > 5e6, "{:?}", s.state().unwrap().view());
}
/// Resolving a drawing's xrefs after OPEN refits the view only for a drawing that stores none:
/// one saved at a view keeps it, xref or not (#1626 review).
#[test]
fn a_drawing_with_an_xref_keeps_the_view_it_was_saved_at() {
let mut d = cadcraft_doc::Drawing::new_metric();
let line = cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(5e6, 5e6, 0.0) };
d.add(&Space::Model, cadcraft_doc::Common::default(), EntityKind::Line(line)).unwrap();
let mut xref = cadcraft_doc::Block::new("XR");
xref.xref_path = Some("missing-xref.dxf".into());
d.blocks.insert("XR".into(), std::sync::Arc::new(xref));
let mut plain = d.clone();
d.header.set_saved_view(Vec2::new(50.0, 50.0), 20.0);
let mut s = Session::new();
let i = s.open_drawing(d, "saved-view.dxf", None);
crate::cmd::blocks::xref::after_open(&mut s, i);
assert_eq!(s.state().unwrap().view(), View { center: Vec2::new(50.0, 50.0), height: 20.0, twist: 0.0 });
// With no stored view, the xrefs' pass still frames the drawing.
plain.header.vars.remove("VIEWCTR");
plain.header.vars.remove("VIEWSIZE");
let mut s = Session::new();
let i = s.open_drawing(plain, "no-view.dxf", None);
crate::cmd::blocks::xref::after_open(&mut s, i);
assert!(s.state().unwrap().view().height > 5e6, "{:?}", s.state().unwrap().view());
}
#[test]
fn move_with_pickfirst_and_window_selection() {
let mut s = Session::new();
s.execute("line", &json!({"points": [[0, 0], [1, 0]]})).unwrap();
s.execute("line", &json!({"points": [[5, 5], [6, 5]]})).unwrap();
s.viewport_px = (1000.0, 1000.0);
s.state_mut().unwrap().set_view(View { center: Vec2::new(3.0, 3.0), height: 10.0 });
s.state_mut().unwrap().set_view(View { center: Vec2::new(3.0, 3.0), height: 10.0, twist: 0.0 });
// Window selection from left to right picks only the first line.
s.cmdline("move").unwrap();
s.input(Input::Point(Vec2::new(-1.0, -1.0))).unwrap();
+27 -3
View File
@@ -1,20 +1,44 @@
use cadcraft_geom::Bounds2;
use super::{Deserialize, Serialize, Vec2};
/// A 2D view of a space: world centre and visible height in drawing units.
/// A 2D view of a space: world centre and visible height in drawing units, and the view twist
/// (VIEWTWIST, DVIEW TWist): how far the view is turned on screen, in radians counterclockwise
/// (the drawing appears turned by `twist`; 0 is the plain plan view).
#[derive(Clone, Copy, Debug, PartialEq, Serialize, Deserialize)]
pub struct View {
pub center: Vec2,
pub height: f64,
#[serde(default)]
pub twist: f64,
}
impl Default for View {
fn default() -> Self {
View { center: Vec2::new(6.0, 4.5), height: 10.0 }
View { center: Vec2::new(6.0, 4.5), height: 10.0, twist: 0.0 }
}
}
impl View {
/// Box `b` (world) as a view turned by `twist` shows it: the world centre of the box it
/// makes on screen, and that box's width and height (`b`'s own when there is no twist).
pub fn twisted_box(b: Bounds2, twist: f64) -> (Vec2, f64, f64) {
if twist == 0.0 || !twist.is_finite() {
return (b.center(), b.width(), b.height());
}
let r = Bounds2::from_points(b.corners().map(|p| p.rotate(twist)));
(r.center().rotate(-twist), r.width(), r.height())
}
}
pub(crate) fn usable_view(v: &View) -> bool {
v.center.is_finite() && v.height.is_finite() && v.height > 1e-12
v.center.is_finite() && v.height.is_finite() && v.height > 1e-12 && v.twist.is_finite()
}
/// The view drawing `d` was saved at, when it records a usable one: OPEN opens on it, and nothing
/// after the open (resolving xrefs, the UI's first frame) fits the extents over it.
pub(crate) fn saved_view(d: &cadcraft_doc::Drawing) -> Option<View> {
d.header.saved_view().map(|(center, height)| View { center, height, twist: 0.0 }).filter(usable_view)
}
/// Tiled model viewports (VPORTS): the session side of the drawing's `*Active` configuration.
+1
View File
@@ -24,6 +24,7 @@ fn insert(block: &str) -> EntityKind {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
})
}
+1
View File
@@ -487,6 +487,7 @@ fn a_block_editor_that_cannot_be_composed_is_not_autosaved_as_the_old_host() {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
});
d.model.push(Entity::new(h, kind));
assert!(s.state().unwrap().recovery_drawing().is_err());
+1
View File
@@ -28,6 +28,7 @@ fn insert(d: &mut Drawing, block: &str, at: (f64, f64)) -> Entity {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
});
Entity { handle: d.new_handle(), common: Common::default(), kind }
}
+2
View File
@@ -124,6 +124,7 @@ fn hooks() {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).map_err(|e| e.to_string())?;
return Ok(d);
@@ -175,6 +176,7 @@ fn hostile_inputs_are_errors() {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
b.entities.push(Entity::new(cadcraft_engine::doc::Handle(0x900), EntityKind::Insert(ins.clone())));
let d = s.doc_mut().unwrap();
+381
View File
@@ -0,0 +1,381 @@
//! DVIEW starts with "Select objects or <use DVIEWBLOCK>:", then the option prompt;
//! TWist, PAn, Zoom, Off and Undo on a 2D view; the 3D options not available yet. It works on the
//! Model tab and inside an active layout viewport (whose twist is an undoable edit of the
//! viewport), and not on a layout sheet.
use cadcraft_doc::{EntityKind, Handle, Viewport};
use cadcraft_engine::geom::Vec2;
use cadcraft_engine::{Input, Session, View};
use serde_json::json;
const SELECT: &str = "Select objects or <use DVIEWBLOCK>:";
const OPTION: &str = "Enter option [CAmera/TArget/Distance/POints/PAn/Zoom/TWist/CLip/Hide/Off/Undo]:";
const PAPER: &str = "This command is not available in Paper space.";
fn session() -> Session {
let mut s = Session::new();
s.viewport_px = (1200.0, 800.0);
s.execute("line", &json!({ "points": [[0, 0], [100, 50]] })).unwrap();
s.execute("view.set", &json!({ "center": [10, 10], "height": 20 })).unwrap();
s
}
fn prompt(s: &Session) -> String {
s.current_prompt().map(|p| p.display()).unwrap_or_default()
}
fn view(s: &Session) -> View {
s.state().unwrap().view()
}
fn near(a: f64, b: f64) -> bool {
(a - b).abs() < 1e-9
}
fn twist_deg(s: &Session) -> f64 {
view(s).twist.to_degrees()
}
fn logged(s: &Session, m: &str) -> bool {
s.log.iter().any(|l| l == m)
}
#[test]
fn every_prompt_step_on_the_model_tab() {
let mut s = session();
let undo = s.state().unwrap().undo.len();
s.cmdline("dview").unwrap();
assert_eq!(prompt(&s), SELECT);
// The whole drawing shows while objects are picked.
assert!(s.display_only().is_none());
// Enter with nothing selected: the DVIEWBLOCK sample (a house of lines) is the preview set.
s.cmdline("").unwrap();
assert_eq!(prompt(&s), OPTION);
let only = s.display_only().unwrap();
assert!(only.handles.is_empty());
assert!(only.extra.len() > 10 && only.extra.iter().all(|e| matches!(e.kind, EntityKind::Line(_))));
twist_pan_and_zoom(&mut s);
// The sample house stays where it was put: the view moves over it.
assert_eq!(s.display_only().unwrap(), only);
off_and_unavailable_options(&mut s);
undo_steps(&mut s);
// An unknown option is refused and asked again.
assert!(s.cmdline("bogus").is_ok());
assert_eq!(prompt(&s), OPTION);
// Enter ends DVIEW; the whole drawing shows again, and a Model tab twist is no undo step.
s.cmdline("tw").unwrap();
s.cmdline("45").unwrap();
s.cmdline("").unwrap();
assert!(s.current_prompt().is_none());
assert!(s.display_only().is_none());
assert!(near(twist_deg(&s), 45.0));
assert_eq!(s.state().unwrap().undo.len(), undo);
}
/// DVIEW's TWist, PAn and Zoom steps from the option prompt of a fresh Model tab session.
fn twist_pan_and_zoom(s: &mut Session) {
// TWist: the current twist is the default; a typed angle turns the view.
s.cmdline("tw").unwrap();
assert_eq!(prompt(s), "Specify view twist angle <0>:");
s.cmdline("30").unwrap();
assert!(near(twist_deg(s), 30.0));
assert_eq!(prompt(s), OPTION);
s.cmdline("TWist").unwrap();
assert_eq!(prompt(s), "Specify view twist angle <30>:");
// Enter keeps it.
s.cmdline("").unwrap();
assert!(near(twist_deg(s), 30.0));
// PAn: base point, second point.
s.cmdline("pa").unwrap();
assert_eq!(prompt(s), "Specify displacement base point:");
s.cmdline("0,0").unwrap();
assert_eq!(prompt(s), "Specify second point:");
s.cmdline("4,0").unwrap();
assert_eq!(view(s).center, Vec2::new(6.0, 10.0));
assert_eq!(prompt(s), OPTION);
// Zoom: a scale factor of the current view.
s.cmdline("z").unwrap();
assert_eq!(prompt(s), "Specify zoom scale factor <1>:");
s.cmdline("2").unwrap();
assert!(near(view(s).height, 10.0));
}
/// DVIEW's Off option and the options that need a 3D camera.
fn off_and_unavailable_options(s: &mut Session) {
// Off: perspective is never on in a 2D view, so nothing changes.
let before = view(s);
s.cmdline("o").unwrap();
assert_eq!(prompt(s), OPTION);
assert_eq!(view(s), before);
// The options that need a 3D camera are not available yet and stay at the option prompt.
for (typed, name) in [("ca", "CAmera"), ("ta", "TArget"), ("d", "Distance"), ("po", "POints"), ("cl", "CLip"), ("h", "Hide")] {
s.cmdline(typed).unwrap();
assert!(logged(s, &format!("DVIEW {name} is not available yet.")), "{name}: {:?}", s.log);
assert_eq!(prompt(s), OPTION);
}
assert!(!s.log.iter().any(|l| l.contains("Only the view twist")));
}
/// DVIEW's Undo after [`twist_pan_and_zoom`].
fn undo_steps(s: &mut Session) {
// Undo takes back one DVIEW action at a time: zoom, pan, twist.
s.cmdline("u").unwrap();
assert!(near(view(s).height, 20.0));
s.cmdline("u").unwrap();
assert_eq!(view(s).center, Vec2::new(10.0, 10.0));
assert!(near(twist_deg(s), 30.0));
s.cmdline("u").unwrap();
assert_eq!(view(s).twist, 0.0);
// Nothing left to undo: still at the option prompt.
s.cmdline("u").unwrap();
assert_eq!(prompt(s), OPTION);
}
#[test]
fn selected_objects_are_the_preview_set() {
let mut s = session();
let line = s.doc().unwrap().model.iter().next().map(|e| e.handle).unwrap();
s.execute("line", &json!({ "points": [[0, 10], [10, 10]] })).unwrap();
s.cmdline("dview").unwrap();
s.input(Input::Pick(vec![line])).unwrap();
assert_eq!(prompt(&s), SELECT);
s.cmdline("").unwrap();
assert_eq!(prompt(&s), OPTION);
let only = s.display_only().unwrap();
assert_eq!(only.handles, vec![line]);
assert!(only.extra.is_empty(), "no sample house with a selection");
// Picked at the prompt, the objects don't stay selected.
assert!(s.selection().is_empty());
// Escape ends it too, and the drawing shows again.
s.input(Input::Cancel).unwrap();
assert!(s.current_prompt().is_none());
assert!(s.display_only().is_none());
}
#[test]
fn a_dviewblock_of_the_drawings_own_is_previewed() {
let mut s = session();
s.execute("circle", &json!({ "center": [0.5, 0.5], "radius": 0.5 })).unwrap();
let c = s.doc().unwrap().model.iter().last().map(|e| e.handle).unwrap();
s.execute("block", &json!({ "name": "DVIEWBLOCK", "base": [0, 0], "handles": [c.hex()], "keep": "delete" })).unwrap();
s.cmdline("dview").unwrap();
s.cmdline("").unwrap();
let only = s.display_only().unwrap();
assert_eq!(only.extra.len(), 1);
match &only.extra[0].kind {
EntityKind::Insert(i) => {
assert_eq!(i.block, "DVIEWBLOCK");
// Scaled from its 1 by 1 unit area to half the view's height.
assert!(near(i.scale.x, 10.0) && near(i.scale.y, 10.0));
}
k => panic!("{k:?}"),
}
s.cmdline("").unwrap();
}
/// A layout with one viewport, `(session, viewport handle)`.
fn layout_session() -> (Session, Handle) {
let mut s = session();
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
let r = s.execute("mview", &json!({ "p1": [20, 20], "p2": [220, 120] })).unwrap();
let h = Handle::parse_hex(r["viewports"][0].as_str().unwrap()).unwrap();
(s, h)
}
fn vp(s: &Session, h: Handle) -> Viewport {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Viewport(v) => v.clone(),
_ => panic!("not a viewport"),
}
}
#[test]
fn on_a_layout_sheet_it_is_not_available() {
let (mut s, _) = layout_session();
assert_eq!(s.execute("dview", &json!({ "twist": 10 })).unwrap_err().to_string(), PAPER);
assert_eq!(s.cmdline("dview").unwrap_err().to_string(), PAPER);
assert!(s.current_prompt().is_none());
// view.set can't turn the sheet either; an untwisted view is fine.
assert_eq!(s.execute("view.set", &json!({ "center": [0, 0], "height": 5, "twist": 15 })).unwrap_err().to_string(), PAPER);
s.execute("view.set", &json!({ "center": [0, 0], "height": 5 })).unwrap();
}
#[test]
fn inside_an_active_viewport_it_twists_that_viewport_as_one_undo_step() {
let (mut s, h) = layout_session();
s.execute("mspace", &json!({ "handle": h.hex() })).unwrap();
let undo = s.state().unwrap().undo.len();
let pv = s.state().unwrap().paper_view();
s.cmdline("dview").unwrap();
assert_eq!(prompt(&s), SELECT);
s.cmdline("").unwrap();
s.cmdline("tw").unwrap();
s.cmdline("30").unwrap();
// The viewport entity carries the twist, and the model view inside it is turned by it.
assert!(near(vp(&s, h).twist.to_degrees(), 30.0));
assert!(near(twist_deg(&s), 30.0));
// The sheet itself is not turned.
assert_eq!(s.state().unwrap().paper_view(), pv);
s.cmdline("tw").unwrap();
s.cmdline("50").unwrap();
s.cmdline("").unwrap();
assert!(s.current_prompt().is_none());
assert!(near(vp(&s, h).twist.to_degrees(), 50.0));
// One undo step for the whole DVIEW, which turns the viewport back.
assert_eq!(s.state().unwrap().undo.len(), undo + 1);
s.execute("undo", &json!({})).unwrap();
assert_eq!(vp(&s, h).twist, 0.0);
// The JSON form and view.set twist the viewport the same way, each one undo step.
s.execute("dview", &json!({ "twist": -90 })).unwrap();
assert!(near(vp(&s, h).twist.to_degrees(), 270.0));
assert_eq!(s.state().unwrap().undo.len(), undo + 1);
let v = view(&s);
s.execute("view.set", &json!({ "center": [v.center.x, v.center.y], "height": v.height, "twist": 15 })).unwrap();
assert!(near(vp(&s, h).twist.to_degrees(), 15.0));
assert_eq!(s.state().unwrap().undo.len(), undo + 2);
// Setting a view without a twist keeps the viewport's.
s.execute("view.set", &json!({ "center": [v.center.x, v.center.y], "height": v.height })).unwrap();
assert!(near(vp(&s, h).twist.to_degrees(), 15.0));
assert_eq!(s.state().unwrap().undo.len(), undo + 2);
// Back on the sheet, DVIEW is not available again.
s.execute("pspace", &json!({})).unwrap();
assert_eq!(s.cmdline("dview").unwrap_err().to_string(), PAPER);
}
#[test]
fn a_locked_viewport_keeps_its_twist() {
let (mut s, h) = layout_session();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Viewport(v) = &mut e.kind {
v.locked = true;
}
})
.unwrap();
s.execute("mspace", &json!({ "handle": h.hex() })).unwrap();
let undo = s.state().unwrap().undo.len();
assert!(s.execute("dview", &json!({ "twist": 30 })).is_err());
let v = view(&s);
assert!(s.execute("view.set", &json!({ "center": [v.center.x, v.center.y], "height": v.height, "twist": 30 })).is_err());
assert_eq!(vp(&s, h).twist, 0.0);
assert_eq!(s.state().unwrap().undo.len(), undo);
// A view with the twist it already has is fine.
s.execute("view.set", &json!({ "center": [v.center.x, v.center.y], "height": v.height })).unwrap();
}
#[test]
fn escape_inside_an_active_viewport_keeps_the_twist_as_one_undo_step() {
let (mut s, h) = layout_session();
s.execute("mspace", &json!({ "handle": h.hex() })).unwrap();
let undo = s.state().unwrap().undo.len();
for l in ["dview", "", "tw", "30"] {
s.cmdline(l).unwrap();
}
s.input(Input::Cancel).unwrap();
assert!(s.current_prompt().is_none());
assert!(near(vp(&s, h).twist.to_degrees(), 30.0));
assert_eq!(s.state().unwrap().undo.len(), undo + 1);
s.execute("undo", &json!({})).unwrap();
assert_eq!(vp(&s, h).twist, 0.0);
}
#[test]
fn the_view_inside_a_twisted_viewport_maps_the_screen_like_the_sheet() {
let (mut s, h) = layout_session();
s.execute("mspace", &json!({ "handle": h.hex() })).unwrap();
s.execute("dview", &json!({ "twist": 30 })).unwrap();
let st = s.state().unwrap();
let (vpe, pv, v) = (vp(&s, h), st.paper_view(), st.view());
// The model view's centre is the model point at the sheet's view centre.
assert!((vpe.model_to_paper(v.center) - pv.center).len() < 1e-9);
assert!(near(v.twist, vpe.twist));
// Panning the view inside the viewport moves its model view, keeping the twist.
let moved = View { center: v.center + Vec2::new(5.0, -2.0), ..v };
s.state_mut().unwrap().set_view(moved);
let after = view(&s);
assert!((after.center - moved.center).len() < 1e-9, "{after:?}");
assert!(near(after.twist, vpe.twist));
assert_eq!(s.state().unwrap().paper_view(), pv);
// ZOOM Extents fits the turned box of the drawing in the viewport.
s.execute("zoom", &json!({ "mode": "extents" })).unwrap();
assert!(near(view(&s).twist, vpe.twist));
}
#[test]
fn a_viewport_twist_survives_a_dxf_round_trip() {
let (mut s, h) = layout_session();
s.execute("mspace", &json!({ "handle": h.hex() })).unwrap();
s.execute("dview", &json!({ "twist": 30 })).unwrap();
let dxf = cadcraft_io::write_dxf(s.doc().unwrap());
let back = cadcraft_io::read_dxf(dxf.as_bytes()).unwrap();
let twists: Vec<f64> = back
.layouts
.iter()
.flat_map(|l| l.entities.iter())
.filter_map(|e| match &e.kind {
EntityKind::Viewport(v) if v.id != 1 => Some(v.twist.to_degrees()),
_ => None,
})
.collect();
assert_eq!(twists.len(), 1);
assert!((twists[0] - 30.0).abs() < 1e-9, "{twists:?}");
}
#[test]
fn a_view_saved_in_a_twisted_viewport_restores_its_twist_as_one_undo_step() {
let (mut s, h) = layout_session();
s.execute("mspace", &json!({ "handle": h.hex() })).unwrap();
s.execute("dview", &json!({ "twist": 30 })).unwrap();
s.execute("view", &json!({ "option": "save", "name": "Turned" })).unwrap();
let saved = s.doc().unwrap().views.iter().find(|v| v.name == "Turned").map(|v| v.twist.to_degrees()).unwrap();
assert!(near(saved, 30.0), "saved twist {saved}");
let center = vp(&s, h).view_center;
s.execute("dview", &json!({ "twist": 0 })).unwrap();
s.execute("view.set", &json!({ "center": [80, 40], "height": 3 })).unwrap();
let undo = s.state().unwrap().undo.len();
s.execute("view", &json!({ "option": "restore", "name": "Turned" })).unwrap();
assert!(near(vp(&s, h).twist.to_degrees(), 30.0), "viewport twist {}", vp(&s, h).twist.to_degrees());
assert!(near(twist_deg(&s), 30.0));
assert!((vp(&s, h).view_center - center).len() < 1e-6, "{:?} vs {center:?}", vp(&s, h).view_center);
// The viewport's twist changed: one undo step, which turns it back.
assert_eq!(s.state().unwrap().undo.len(), undo + 1);
s.execute("undo", &json!({})).unwrap();
assert_eq!(vp(&s, h).twist, 0.0);
}
#[test]
fn undoing_a_drawing_change_keeps_the_untiled_twist_saved() {
let mut s = session();
s.execute("line", &json!({ "points": [[0, 10], [5, 10]] })).unwrap();
// A Model tab twist is a view change, not an undo step.
s.execute("dview", &json!({ "twist": 30 })).unwrap();
s.execute("undo", &json!({})).unwrap();
assert!(near(twist_deg(&s), 30.0));
let saved = |s: &Session| s.doc().unwrap().vports.iter().find(|c| c.is_active()).and_then(|c| c.tiles.first()).map(|t| t.twist.to_degrees());
assert!(saved(&s).is_some_and(|t| near(t, 30.0)), "{:?}", saved(&s));
s.execute("redo", &json!({})).unwrap();
assert!(saved(&s).is_some_and(|t| near(t, 30.0)), "{:?}", saved(&s));
}
#[test]
fn a_leftward_drag_on_a_turned_screen_is_a_crossing_window() {
let mut s = session();
let r = s.execute("line", &json!({ "points": [[200, 0], [260, 0]] })).unwrap();
let line = Handle::parse_hex(r["handles"][0].as_str().unwrap()).unwrap();
s.execute("dview", &json!({ "twist": 180 })).unwrap();
// Turned half way round, a drag towards +X in the drawing runs leftwards on screen.
assert!(s.window_is_crossing(Vec2::new(210.0, -5.0), Vec2::new(230.0, 5.0)));
assert!(!s.window_is_crossing(Vec2::new(230.0, -5.0), Vec2::new(210.0, 5.0)));
// A crossing window takes the line it only partly covers.
s.idle_click(Vec2::new(210.0, -5.0), false).unwrap();
s.idle_click(Vec2::new(230.0, 5.0), false).unwrap();
assert_eq!(s.selection(), vec![line]);
}
+376
View File
@@ -0,0 +1,376 @@
//! Raster images (#956): IMAGEATTACH from a file and from handed-over bytes, the pixels loaded
//! again when the drawing is reopened, a missing file left as a frame, and bad input refused.
use std::path::{Path, PathBuf};
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, base64_encode, set_image_decoder, set_io};
use cadcraft_engine::doc::{Drawing, EntityKind, Image, Raster};
use serde_json::{Value, json};
fn hooks() {
set_io(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,
});
set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
}
/// A fresh folder for one test.
fn folder(tag: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("cadcraft-image-{}-{tag}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// A PNG file of 4 x 2 pixels.
fn png() -> Vec<u8> {
let px: Vec<u8> = (0..8u8).flat_map(|i| [i * 30, 255 - i * 30, 7, 255]).collect();
cadcraft_io::raster::encode_png(&Raster::new(4, 2, px).unwrap()).unwrap()
}
fn images(s: &Session) -> Vec<Image> {
let d = s.doc().unwrap();
d.model.iter().filter_map(|e| if let EntityKind::Image(i) = &e.kind { Some(i.clone()) } else { None }).collect()
}
fn open(s: &mut Session, path: &Path) {
s.execute("open", &json!({ "path": path.to_string_lossy() })).unwrap();
}
fn listed(s: &mut Session) -> Value {
s.execute("image", &json!({})).unwrap()["images"].clone()
}
#[test]
fn attach_from_bytes_places_the_image() {
hooks();
let mut s = Session::new();
let r = s.execute("imageattach", &json!({ "path": "maps/site.png", "data": base64_encode(&png()), "at": [10, 20], "width": 100 })).unwrap();
assert_eq!((r["name"].as_str(), r["pixels"].clone(), r["size"].clone()), (Some("site"), json!([4.0, 2.0]), json!([100.0, 50.0])));
let i = images(&s).pop().unwrap();
assert_eq!((i.insert.x, i.insert.y, i.u.x, i.u.y, i.v.x, i.v.y), (10.0, 20.0, 25.0, 0.0, 0.0, 25.0));
assert_eq!((i.size.x, i.size.y, i.path.as_str(), i.name.as_str()), (4.0, 2.0, "maps/site.png", "site"));
assert_eq!(s.doc().unwrap().rasters.get("maps/site.png").map(|r| (r.width(), r.height())), Some((4, 2)));
let l = listed(&mut s);
assert_eq!((l[0]["status"].as_str(), l[0]["references"].as_u64(), l[0]["pixels"].clone()), (Some("Loaded"), Some(1), json!([4, 2])));
// A second reference to the same file shares the definition and the pixels; another file
// with the same file name gets its own name.
s.execute("imageattach", &json!({ "path": "maps/site.png", "at": [200, 0], "rotation": 90, "scale": 8 })).unwrap();
let r = s.execute("attach", &json!({ "path": "other/site.png", "data": base64_encode(&png()) })).unwrap();
assert_eq!(r["name"], "site_2");
let all = images(&s);
assert_eq!(all.len(), 3);
assert_eq!(all[1].name, "site");
assert!((all[1].u.x).abs() < 1e-12 && (all[1].u.y - 2.0).abs() < 1e-12 && (all[1].v.x + 2.0).abs() < 1e-12, "{:?}", all[1]);
assert_eq!(listed(&mut s)[0]["references"], 2);
// Undo takes the reference away; the drawing draws with its pixels.
s.execute("undo", &json!({})).unwrap();
assert_eq!(images(&s).len(), 2);
let list = cadcraft_engine::render::build(s.doc().unwrap(), &cadcraft_engine::doc::Space::Model, &cadcraft_engine::render::Options::default());
assert_eq!(list.images.len(), 2);
}
#[test]
fn a_file_is_found_next_to_the_drawing_and_loaded_again_on_open() {
hooks();
let dir = folder("file");
std::fs::write(dir.join("map.png"), png()).unwrap();
let host = dir.join("host.dxf");
std::fs::write(&host, cadcraft_io::write(&Drawing::new_metric(), "host.dxf").unwrap()).unwrap();
let mut s = Session::new();
open(&mut s, &host);
let r = s.execute("imageattach", &json!({ "path": "map.png" })).unwrap();
assert_eq!(r["size"], json!([1.0, 0.5]), "one drawing unit wide by default");
s.execute("qsave", &json!({})).unwrap();
// Reopened: the pixels come back from the file.
let mut s = Session::new();
open(&mut s, &host);
assert_eq!(images(&s).len(), 1);
assert!(s.doc().unwrap().rasters.get("map.png").is_some());
assert!(!s.state().unwrap().is_dirty(), "loading images is not a change");
let l = listed(&mut s);
assert_eq!(l[0]["status"], "Loaded");
assert!(l[0]["foundAt"].as_str().is_some_and(|f| f.ends_with("map.png")));
// The file gone: the drawing still opens, says so, and keeps the reference.
std::fs::remove_file(dir.join("map.png")).unwrap();
let mut s = Session::new();
open(&mut s, &host);
assert_eq!(images(&s).len(), 1);
assert!(s.doc().unwrap().rasters.get("map.png").is_none());
assert!(s.log.iter().any(|l| l.contains("map.png") && l.contains("file not found")), "{:?}", s.log);
assert_eq!(listed(&mut s)[0]["status"], "Not Found");
// A file that is not an image is reported the same way.
std::fs::write(dir.join("map.png"), b"not an image").unwrap();
let mut s = Session::new();
open(&mut s, &host);
assert!(s.doc().unwrap().rasters.get("map.png").is_none());
assert!(s.log.iter().any(|l| l.contains("map.png")), "{:?}", s.log);
assert_eq!(listed(&mut s)[0]["status"], "Not loaded");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn bad_input_is_refused_and_changes_nothing() {
hooks();
let mut s = Session::new();
let data = base64_encode(&png());
for p in [
json!({}),
json!({ "path": " " }),
json!({ "path": "nowhere/missing.png" }),
json!({ "path": "a.png", "data": "***" }),
json!({ "path": "a.png", "data": 5 }),
json!({ "path": "a.png", "data": base64_encode(b"plain text") }),
json!({ "path": "a.png", "data": data, "scale": 0 }),
json!({ "path": "a.png", "data": data, "width": -3 }),
json!({ "path": "a.png", "data": data, "width": "wide" }),
json!({ "path": "a.png", "data": data, "width": 1e-320 }),
json!({ "path": "x".repeat(5000), "data": data }),
] {
assert!(s.execute("imageattach", &p).is_err(), "{p}");
}
assert!(images(&s).is_empty());
assert!(s.execute("attach", &json!({ "path": "plan.pdf" })).unwrap_err().to_string().contains("not available yet"));
assert_eq!(listed(&mut s), json!([]));
}
#[test]
fn an_image_among_many_objects_keeps_its_pixels() {
// More objects than one build task takes: the display list is built in parts and joined,
// and the image must still point at its own pixels.
hooks();
let mut s = Session::new();
for i in 0..700 {
s.execute("line", &json!({ "points": [[i, 0], [i, 1]] })).unwrap();
}
s.execute("imageattach", &json!({ "path": "a.png", "data": base64_encode(&png()), "at": [0, 5], "width": 4 })).unwrap();
for i in 0..700 {
s.execute("line", &json!({ "points": [[i, 2], [i, 3]] })).unwrap();
}
s.execute("imageattach", &json!({ "path": "b.png", "data": base64_encode(&png()), "at": [10, 5], "width": 8 })).unwrap();
let list = cadcraft_engine::render::build(s.doc().unwrap(), &cadcraft_engine::doc::Space::Model, &cadcraft_engine::render::Options::default());
let widths: Vec<f64> = list
.prims
.iter()
.filter_map(|p| match p.kind {
cadcraft_engine::render::Kind::Image { index } => list.images.get(index as usize).map(|i| i.right.x * 4.0),
_ => None,
})
.collect();
assert_eq!(widths, [4.0, 8.0]);
}
fn drawn_images(s: &Session) -> usize {
cadcraft_engine::render::build(s.doc().unwrap(), &cadcraft_engine::doc::Space::Model, &cadcraft_engine::render::Options::default()).images.len()
}
#[test]
fn editing_commands_work_on_images_and_undo_keeps_the_pixels() {
hooks();
let mut s = Session::new();
let r = s.execute("imageattach", &json!({ "path": "a.png", "data": base64_encode(&png()), "at": [10, 0], "width": 4 })).unwrap();
let h = r["handle"].as_str().unwrap().to_string();
// Move, then a quarter turn about the origin: the corner and both axes follow.
s.execute("move", &json!({ "handles": [h], "delta": [0, 5] })).unwrap();
s.execute("rotate", &json!({ "handles": [h], "base": [0, 0], "angle": 90 })).unwrap();
let i = images(&s).pop().unwrap();
let close = |a: f64, b: f64| (a - b).abs() < 1e-9;
assert!(close(i.insert.x, -5.0) && close(i.insert.y, 10.0), "{i:?}");
assert!(close(i.u.x, 0.0) && close(i.u.y, 1.0) && close(i.v.x, -1.0) && close(i.v.y, 0.0), "{i:?}");
assert_eq!(drawn_images(&s), 1);
// A copy is a second reference to the same file.
s.execute("copy", &json!({ "handles": [h], "delta": [20, 0] })).unwrap();
assert_eq!((images(&s).len(), drawn_images(&s)), (2, 2));
assert_eq!(listed(&mut s)[0]["references"], 2);
assert_eq!(listed(&mut s).as_array().map(Vec::len), Some(1));
// Scaled about its corner: twice the size, still the same pixels.
s.execute("scale", &json!({ "handles": [h], "base": [-5, 10], "factor": 2 })).unwrap();
let i = images(&s).into_iter().find(|i| close(i.insert.x, -5.0)).unwrap();
assert!(close(i.u.y, 2.0) && close(i.size.x, 4.0), "{i:?}");
// Erased, then brought back by undo, with its picture; redo erases again.
s.execute("erase", &json!({ "handles": [h] })).unwrap();
assert_eq!((images(&s).len(), drawn_images(&s)), (1, 1));
s.execute("undo", &json!({})).unwrap();
assert_eq!((images(&s).len(), drawn_images(&s)), (2, 2));
s.execute("redo", &json!({})).unwrap();
assert_eq!(images(&s).len(), 1);
// Everything undone: no image, and nothing left to draw.
for _ in 0..10 {
let _ = s.execute("undo", &json!({}));
}
assert!(images(&s).is_empty());
assert_eq!(drawn_images(&s), 0);
assert_eq!(listed(&mut s), json!([]));
}
#[test]
fn the_alias_and_the_command_line_reach_the_command() {
hooks();
assert_eq!(cadcraft_engine::cmd::resolve_alias("IAT"), "imageattach");
assert_eq!(cadcraft_engine::cmd::resolve_alias("im"), "image");
let spec = |id: &str| cadcraft_engine::cmd::command_specs().iter().find(|c| c.id == id).unwrap();
assert!(!spec("imageattach").params.is_empty() && !spec("image").params.is_empty());
// Typed without a file it has nothing to attach: an error, not a crash or a stuck prompt.
let mut s = Session::new();
let _ = s.cmdline("imageattach");
let _ = s.cmdline("");
s.cancel();
assert!(s.running.is_none() && images(&s).is_empty());
}
#[test]
fn images_in_blocks_and_layouts_are_loaded_on_open() {
use cadcraft_engine::doc::geom::{Vec2, Vec3};
use cadcraft_engine::doc::{Block, Common, Entity, Space};
hooks();
let dir = folder("spaces");
std::fs::create_dir_all(dir.join("maps")).unwrap();
std::fs::write(dir.join("maps").join("a.png"), png()).unwrap();
std::fs::write(dir.join("b.png"), png()).unwrap();
let image = |path: &str, name: &str| {
EntityKind::Image(Image {
u: Vec3::new(1.0, 0.0, 0.0),
v: Vec3::new(0.0, 1.0, 0.0),
size: Vec2::new(4.0, 2.0),
path: path.into(),
name: name.into(),
..Image::default()
})
};
let mut d = Drawing::new_metric();
// The same file in model space, in a block and on a layout; another only on the layout,
// saved with a folder that no longer exists (found by its name next to the drawing); and
// one that is nowhere.
d.add(&Space::Model, Common::default(), image("maps/a.png", "a")).unwrap();
let mut blk = Block::new("MAP");
let bh = d.new_handle();
blk.entities.push(Entity::new(bh, image("maps/a.png", "a")));
d.blocks.insert("MAP".into(), std::sync::Arc::new(blk));
let layout = Space::Paper("Layout1".into());
d.add(&layout, Common::default(), image("maps/a.png", "a")).unwrap();
d.add(&layout, Common::default(), image("C:\\old\\place\\b.png", "b")).unwrap();
d.add(&layout, Common::default(), image("gone.png", "gone")).unwrap();
let host = dir.join("host.dxf");
std::fs::write(&host, cadcraft_io::write(&d, "host.dxf").unwrap()).unwrap();
let mut s = Session::new();
open(&mut s, &host);
let doc = s.doc().unwrap();
assert_eq!(doc.rasters.len(), 2, "each file once");
assert!(doc.rasters.get("maps/a.png").is_some() && doc.rasters.get("C:\\old\\place\\b.png").is_some());
assert!(!s.state().unwrap().is_dirty());
assert_eq!(s.log.iter().filter(|l| l.starts_with("Image ")).count(), 1, "{:?}", s.log);
let l = listed(&mut s);
let row = |name: &str| l.as_array().unwrap().iter().find(|r| r["name"] == name).cloned().unwrap();
assert_eq!((row("a")["status"].clone(), row("a")["references"].clone()), (json!("Loaded"), json!(3)));
assert_eq!(row("b")["status"], "Loaded");
assert_eq!(row("gone")["status"], "Not Found");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_drawing_opened_from_bytes_gets_its_pixels_handed_over() {
// The web app's way: no file system, the drawing arrives as bytes and so do the images.
use cadcraft_engine::doc::geom::{Vec2, Vec3};
use cadcraft_engine::doc::{Common, Space};
hooks();
let mut d = Drawing::new_metric();
let i = Image {
u: Vec3::new(1.0, 0.0, 0.0),
v: Vec3::new(0.0, 1.0, 0.0),
size: Vec2::new(4.0, 2.0),
path: "no-such-folder/web.png".into(),
name: "web".into(),
..Image::default()
};
d.add(&Space::Model, Common::default(), EntityKind::Image(i)).unwrap();
let dxf = cadcraft_io::write(&d, "plan.dxf").unwrap();
let mut s = Session::new();
s.execute("open", &json!({ "data": base64_encode(&dxf), "name": "plan.dxf" })).unwrap();
assert_eq!(images(&s).len(), 1, "opened with its image reference");
assert!(s.doc().unwrap().rasters.is_empty());
assert!(s.log.iter().any(|l| l.contains("web.png")), "{:?}", s.log);
assert_eq!(listed(&mut s)[0]["status"], "Not Found");
assert_eq!(drawn_images(&s), 0);
// The same file handed over as bytes: the reference that was there draws too.
s.execute("imageattach", &json!({ "path": "no-such-folder/web.png", "data": base64_encode(&png()), "at": [10, 0] })).unwrap();
assert_eq!((images(&s).len(), drawn_images(&s)), (2, 2));
let l = listed(&mut s);
assert_eq!((l[0]["status"].clone(), l[0]["references"].clone(), l[0]["name"].clone()), (json!("Loaded"), json!(2), json!("web")));
// Saved and read back: the references are kept, the pixels are not in the file.
let bytes = cadcraft_io::write(s.doc().unwrap(), "plan.dxf").unwrap();
let back = cadcraft_io::read(&bytes, "plan.dxf").unwrap();
assert!(back.rasters.is_empty());
assert_eq!(back.model.iter().filter(|e| matches!(e.kind, EntityKind::Image(_))).count(), 2);
}
#[test]
fn many_files_are_loaded_together_and_reported_in_order() {
// More files than loaders, with missing and unreadable ones among them: each good file is
// loaded, each bad one reported once, in the order the drawing uses them.
use cadcraft_engine::doc::geom::{Vec2, Vec3};
use cadcraft_engine::doc::{Common, Space};
hooks();
let dir = folder("many");
let mut d = Drawing::new_metric();
let mut expected_notes = Vec::new();
for n in 0..60u32 {
let name = format!("tile{n:02}.png");
match n % 10 {
3 => expected_notes.push(format!("Image {name}: file not found")),
7 => {
std::fs::write(dir.join(&name), b"not an image").unwrap();
expected_notes.push(format!("Image {name}: "));
}
_ => {
// A different width per file, so a mix-up would show.
let px = vec![200u8; (n as usize + 1) * 4];
std::fs::write(dir.join(&name), cadcraft_io::raster::encode_png(&Raster::new(n + 1, 1, px).unwrap()).unwrap()).unwrap();
}
}
let i = Image {
insert: Vec3::new(f64::from(n) * 3.0, 0.0, 0.0),
u: Vec3::new(1.0, 0.0, 0.0),
v: Vec3::new(0.0, 1.0, 0.0),
size: Vec2::new(f64::from(n + 1), 1.0),
path: name.clone(),
name: format!("tile{n:02}"),
..Image::default()
};
d.add(&Space::Model, Common::default(), EntityKind::Image(i)).unwrap();
}
let host = dir.join("host.dxf");
std::fs::write(&host, cadcraft_io::write(&d, "host.dxf").unwrap()).unwrap();
for _ in 0..3 {
let mut s = Session::new();
open(&mut s, &host);
let doc = s.doc().unwrap();
assert_eq!(doc.rasters.len(), 48);
for n in 0..60u32 {
let loaded = doc.rasters.get(&format!("tile{n:02}.png")).map(|r| r.width());
assert_eq!(loaded, if matches!(n % 10, 3 | 7) { None } else { Some(n + 1) }, "tile {n}");
}
let notes: Vec<&String> = s.log.iter().filter(|l| l.starts_with("Image ")).collect();
assert_eq!(notes.len(), expected_notes.len(), "{notes:?}");
assert!(notes.iter().zip(&expected_notes).all(|(got, want)| got.starts_with(want.as_str())), "{notes:?}");
assert!(!s.state().unwrap().is_dirty());
}
let _ = std::fs::remove_dir_all(&dir);
}
@@ -0,0 +1,55 @@
//! A raster image decoder that panics on a damaged file fails that image only (#956): the
//! drawing it belongs to still opens, and IMAGEATTACH reports an error.
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, base64_encode, set_image_decoder, set_io};
use cadcraft_engine::doc::geom::{Vec2, Vec3};
use cadcraft_engine::doc::{Common, Drawing, EntityKind, Image, Line, Space};
use serde_json::json;
fn hooks() {
set_io(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,
});
set_image_decoder(|_| panic!("decoder bug"));
}
#[test]
fn a_panicking_decoder_fails_the_image_not_the_drawing() {
hooks();
let dir = std::env::temp_dir().join(format!("cadcraft-image-panic-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
std::fs::write(dir.join("map.png"), b"anything").unwrap();
let mut d = Drawing::new_metric();
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(5.0, 5.0, 0.0) })).unwrap();
let i = Image {
u: Vec3::new(1.0, 0.0, 0.0),
v: Vec3::new(0.0, 1.0, 0.0),
size: Vec2::new(4.0, 2.0),
path: "map.png".into(),
name: "map".into(),
..Image::default()
};
d.add(&Space::Model, Common::default(), EntityKind::Image(i)).unwrap();
let host = dir.join("host.dxf");
std::fs::write(&host, cadcraft_io::write(&d, "host.dxf").unwrap()).unwrap();
let mut s = Session::new();
s.execute("open", &json!({ "path": host.to_string_lossy() })).unwrap();
let doc = s.doc().unwrap();
assert_eq!(doc.model.len(), 2, "the drawing opened with everything in it");
assert!(doc.rasters.is_empty());
assert!(s.log.iter().any(|l| l.contains("map.png") && l.contains("damaged")), "{:?}", s.log);
let before = s.doc().unwrap().model.len();
let e = s.execute("imageattach", &json!({ "path": "other.png", "data": base64_encode(b"bytes") })).unwrap_err().to_string();
assert!(e.contains("damaged"), "{e}");
assert_eq!(s.doc().unwrap().model.len(), before);
// The session still works.
s.execute("line", &json!({ "points": [[0, 0], [1, 1]] })).unwrap();
assert_eq!(s.doc().unwrap().model.len(), before + 1);
let _ = std::fs::remove_dir_all(&dir);
}
+1
View File
@@ -40,6 +40,7 @@ fn read(bytes: &[u8], _name: &str) -> Result<Drawing, String> {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
d.model.push(Entity::new(Handle(0x61), EntityKind::Insert(ins)));
Ok(d)
+1
View File
@@ -40,6 +40,7 @@ fn drawing() -> (Session, Handle) {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
s.doc_mut().unwrap().add(&Space::Paper("Layout1".into()), Common::default(), EntityKind::Insert(ins)).unwrap();
(s, Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap())
@@ -45,7 +45,8 @@ fn break_and_breakatpoint_refuse_a_locked_line() {
let unlocked = snapshot(&s);
let r = s.execute("break", &json!({"handle": a, "p1": [3, 0], "p2": [7, 0]})).unwrap();
assert_eq!(r["handles"].as_array().unwrap().len(), 2);
assert!(s.doc().unwrap().entity(cadcraft_engine::doc::Handle::parse_hex(&a).unwrap()).is_none());
// The line keeps its handle as the piece from its start.
assert_eq!(r["handles"][0].as_str(), Some(a.as_str()));
assert!(s.doc().unwrap().entity(cadcraft_engine::doc::Handle::parse_hex(&control).unwrap()).is_some());
let broken = snapshot(&s);
s.execute("undo", &json!({})).unwrap();
@@ -0,0 +1,444 @@
//! BREAK, BREAKATPOINT and TRIM change the object itself, as AutoCAD 2024 does: the piece from
//! the object's start, or the only piece left, keeps its handle and its place in the drawing
//! order, and the other pieces are new objects added at the end (`entlast`). Groups keep the
//! object, an associative hatch whose boundary no longer closes keeps its shape and its link
//! ends, and a dimension attached to the object stays on the point it measured, or follows the
//! object's new end where that point was cut off.
//!
//! The two chains, the group, the two hatches and the three dimensions on a line were measured in
//! AutoCAD 2024 (accoreconsole) on the same drawings: the objects in database order (`entnext`)
//! after each chain, a new handle marked `+`, and the dimensions' DIMASSOC references. The other
//! cases follow from those rules, or say what they check.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{AssocSnap, Common, DimAssoc, Dimension, EntityKind, Handle, Hatch, Line, Space};
use cadcraft_engine::geom::{Vec2, Vec3};
use serde_json::{Value, json};
fn first_handle(v: &Value) -> Handle {
Handle::parse_hex(v.get("handle").unwrap_or(&v["handles"][0]).as_str().unwrap()).unwrap()
}
/// Adds the object `cmd` makes from `p`, on layer `name`.
fn add(s: &mut Session, name: &str, cmd: &str, p: Value) -> Handle {
let h = first_handle(&s.execute(cmd, &p).unwrap());
s.execute("properties.set", &json!({ "handles": [h.hex()], "layer": name })).unwrap();
h
}
fn line(s: &mut Session, name: &str, a: [f64; 2], b: [f64; 2]) -> Handle {
add(s, name, "line", json!({ "points": [a, b] }))
}
fn arc(s: &mut Session, name: &str, c: [f64; 2], start: f64, end: f64) -> Handle {
add(s, name, "arc", json!({ "center": c, "radius": 10, "start": start, "end": end }))
}
fn pline(s: &mut Session, name: &str, vertices: Value, closed: bool) -> Handle {
add(s, name, "pline", json!({ "vertices": vertices, "closed": closed }))
}
/// The drawing the chains were measured on, each object on a layer named after it, made in this
/// order.
fn drawing() -> Session {
let mut s = Session::new();
line(&mut s, "LA", [0.0, 50.0], [100.0, 50.0]);
line(&mut s, "LB", [50.0, 0.0], [50.0, 100.0]);
pline(&mut s, "LP", json!([[0, 200], [20, 200], [20, 220]]), false);
line(&mut s, "LE", [200.0, 0.0], [210.0, 0.0]);
line(&mut s, "LF", [210.0, 0.0], [220.0, 0.0]);
line(&mut s, "LC", [0.0, 0.0], [100.0, 100.0]);
line(&mut s, "LD", [0.0, 100.0], [100.0, 0.0]);
arc(&mut s, "LR", [300.0, 0.0], 0.0, 180.0);
add(&mut s, "LO", "circle", json!({ "center": [400, 0], "radius": 10 }));
pline(&mut s, "LK", json!([[500, 0], [520, 0], [520, 20], [500, 20]]), true);
line(&mut s, "LG", [600.0, 0.0], [600.0, 100.0]);
line(&mut s, "LH", [590.0, 40.0], [610.0, 40.0]);
line(&mut s, "LI", [590.0, 60.0], [610.0, 60.0]);
line(&mut s, "LT", [650.0, 0.0], [650.0, 100.0]);
line(&mut s, "LU", [640.0, 40.0], [660.0, 40.0]);
line(&mut s, "LW", [395.0, -20.0], [395.0, 20.0]);
line(&mut s, "LX", [10.0, 190.0], [10.0, 210.0]);
line(&mut s, "LY", [15.0, 190.0], [15.0, 210.0]);
arc(&mut s, "LJ", [700.0, 0.0], 0.0, 90.0);
arc(&mut s, "LL", [700.0, 0.0], 90.0, 360.0);
line(&mut s, "LM", [800.0, 0.0], [810.0, 0.0]);
arc(&mut s, "LN", [810.0, 10.0], 270.0, 360.0);
pline(&mut s, "LQ", json!([[900, 0], [910, 0]]), false);
line(&mut s, "LS", [910.0, 0.0], [910.0, 10.0]);
line(&mut s, "LZ", [1000.0, 0.0], [1010.0, 0.0]);
s
}
/// `v` to `places` decimals without trailing zeros, as `rtos` printed the measurements.
fn num(v: f64, places: usize) -> String {
let t = format!("{v:.places$}");
let t = if t.contains('.') { t.trim_end_matches('0').trim_end_matches('.') } else { &t };
if t == "-0" { "0".into() } else { t.into() }
}
fn pt(p: Vec2) -> String {
format!("{},{}", num(p.x, 4), num(p.y, 4))
}
/// An angle in degrees in [0, 360).
fn deg(a: f64) -> String {
let d = a.to_degrees().rem_euclid(360.0);
num(if d >= 360.0 - 5e-4 { 0.0 } else { d }, 3)
}
/// The model space objects in order as `layer[+]:TYPE:shape`, `+` marking a handle that wasn't in
/// `original`.
fn table(s: &Session, original: &[Handle]) -> Vec<String> {
s.doc()
.unwrap()
.model
.iter()
.map(|e| {
let shape = match &e.kind {
EntityKind::Line(l) => format!("LINE:{}>{}", pt(l.a.xy()), pt(l.b.xy())),
EntityKind::Arc(a) => format!("ARC:c{}r{}a{}>{}", pt(a.center.xy()), num(a.radius, 4), deg(a.start), deg(a.end)),
EntityKind::Circle(c) => format!("CIRCLE:c{}r{}", pt(c.center.xy()), num(c.radius, 4)),
EntityKind::LwPolyline(p) => {
format!("LWPOLYLINE:f{}{}", u8::from(p.closed), p.vertices.iter().map(|v| format!(";{}", pt(v.p))).collect::<String>())
}
k => format!("{k:?}"),
};
let new = if original.contains(&e.handle) { "" } else { "+" };
format!("{}{new}:{shape}", e.common.layer)
})
.collect()
}
fn handles(s: &Session) -> Vec<Handle> {
s.doc().unwrap().model.iter().map(|e| e.handle).collect()
}
/// The object on layer `name` that was there first.
fn named(s: &Session, name: &str) -> Handle {
s.doc().unwrap().model.iter().find(|e| e.common.layer == name).unwrap().handle
}
/// Runs `commands` on the command line one by one, each to its end.
fn run(s: &mut Session, commands: &[&str]) {
for c in commands {
s.script(&format!("{c}\n")).unwrap();
assert!(s.running.is_none(), "{c}: {}", s.prompt_text());
}
}
/// The objects AutoCAD leaves untouched in the middle of both tables.
const UNTOUCHED: [&str; 8] = [
"LG:LINE:600,0>600,100",
"LH:LINE:590,40>610,40",
"LI:LINE:590,60>610,60",
"LT:LINE:650,0>650,100",
"LU:LINE:640,40>660,40",
"LW:LINE:395,-20>395,20",
"LX:LINE:10,190>10,210",
"LY:LINE:15,190>15,210",
];
/// The measured `entnext` table after the chain of breaks below. (LL and LN end at 360°, written
/// 0° here.)
fn after_breaks() -> Vec<&'static str> {
let mut v = vec![
"LA:LINE:10,50>100,50",
"LB:LINE:50,0>50,20",
"LP:LWPOLYLINE:f0;0,200;10,200",
"LE:LINE:200,0>210,0",
"LF:LINE:210,0>220,0",
"LC:LINE:0,0>100,100",
"LD:LINE:0,100>100,0",
"LR:ARC:c300,0r10a0>45",
"LO:ARC:c400,0r10a90>0",
"LK:LWPOLYLINE:f0;520,10;520,20;500,20;500,0;510,0",
];
v.extend(UNTOUCHED);
v.extend([
"LJ:ARC:c700,0r10a0>45",
"LL:ARC:c700,0r10a90>0",
"LM:LINE:800,0>810,0",
"LN:ARC:c810,10r10a270>0",
"LQ:LWPOLYLINE:f0;900,0;910,0",
"LS:LINE:910,0>910,10",
"LZ:LINE:1000,0>1005,0",
"LB+:LINE:50,30>50,100",
"LR+:ARC:c300,0r10a135>180",
"LP+:LWPOLYLINE:f0;20,210;20,220",
"LZ+:LINE:1005,0>1010,0",
"LJ+:ARC:c700,0r10a45>90",
]);
v
}
#[test]
fn a_chain_of_breaks_leaves_the_objects_in_autocads_order() {
let mut s = drawing();
let original = handles(&s);
run(
&mut s,
&[
// A line picked nearer its end: the piece from its start still keeps the handle.
"BREAK 50,30 50,20",
// Off the start: one piece, the line itself.
"BREAK 10,50 -10,50",
"BREAK 307.0710678,7.0710678 292.9289322,7.0710678",
// A circle becomes an arc with its handle.
"BREAK 410,0 400,10",
"BREAK 5,200 F 10,200 20,210",
// A closed polyline opens with its handle.
"BREAK 510,0 520,10",
],
);
// BREAKATPOINT, picking each object at the point it is broken at.
for (name, at) in [("LZ", [1005.0, 0.0]), ("LJ", [707.0710678, 7.0710678])] {
s.execute("breakatpoint", &json!({ "handle": named(&s, name).hex(), "at": at })).unwrap();
}
assert_eq!(table(&s, &original), after_breaks());
}
#[test]
fn a_chain_of_trims_leaves_the_objects_in_autocads_order() {
let mut s = drawing();
let original = handles(&s);
// Quick mode: every object cuts. Each pick is between the measured cutting edges.
run(&mut s, &["TRIM 600,50\n", "TRIM 650,80\n", "TRIM 50,10\n", "TRIM 390,0\n", "TRIM 12,200\n"]);
let mut want = vec![
"LA:LINE:0,50>100,50",
"LB:LINE:50,50>50,100",
"LP:LWPOLYLINE:f0;0,200;10,200",
"LE:LINE:200,0>210,0",
"LF:LINE:210,0>220,0",
"LC:LINE:0,0>100,100",
"LD:LINE:0,100>100,0",
"LR:ARC:c300,0r10a0>180",
"LO:ARC:c400,0r10a240>120",
"LK:LWPOLYLINE:f1;500,0;520,0;520,20;500,20",
"LG:LINE:600,0>600,40",
];
want.extend(&UNTOUCHED[1..3]);
want.push("LT:LINE:650,0>650,40");
want.extend(&UNTOUCHED[4..]);
want.extend([
"LJ:ARC:c700,0r10a0>90",
"LL:ARC:c700,0r10a90>0",
"LM:LINE:800,0>810,0",
"LN:ARC:c810,10r10a270>0",
"LQ:LWPOLYLINE:f0;900,0;910,0",
"LS:LINE:910,0>910,10",
"LZ:LINE:1000,0>1010,0",
"LG+:LINE:600,60>600,100",
"LP+:LWPOLYLINE:f0;15,200;20,200;20,220",
]);
assert_eq!(table(&s, &original), want);
}
#[test]
fn the_json_forms_return_the_kept_object_first() {
let mut s = Session::new();
let l = first_handle(&s.execute("line", &json!({ "points": [[0, 0], [100, 0]] })).unwrap());
let r = s.execute("break", &json!({ "handle": l.hex(), "p1": [20, 0], "p2": [30, 0] })).unwrap();
let hs = r["handles"].as_array().unwrap();
assert_eq!(hs.len(), 2);
assert_eq!(hs[0], l.hex());
assert_eq!(handles(&s), vec![l, Handle::parse_hex(hs[1].as_str().unwrap()).unwrap()]);
let r = s.execute("breakatpoint", &json!({ "handle": l.hex(), "at": [10, 0] })).unwrap();
assert_eq!(r["handles"][0], l.hex());
// Undo puts the line back, whole, under its own handle.
s.execute("u", &json!({})).unwrap();
s.execute("u", &json!({})).unwrap();
assert_eq!(table(&s, &[l]), ["0:LINE:0,0>100,0"]);
}
#[test]
fn the_new_piece_goes_to_the_space_of_the_object() {
// A paper space line broken through the JSON form while model space is current.
let mut s = Session::new();
let paper = Space::Paper("Layout1".into());
let line = EntityKind::Line(Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(100.0, 0.0, 0.0) });
let l = s.doc_mut().unwrap().add(&paper, Common::default(), line).unwrap();
s.execute("break", &json!({ "handle": l.hex(), "p1": [20, 0], "p2": [30, 0] })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.model.iter().count(), 0);
let pieces: Vec<Handle> = d.space(&paper).unwrap().iter().map(|e| e.handle).collect();
assert_eq!(pieces.len(), 2);
assert_eq!(pieces[0], l);
}
#[test]
fn a_group_keeps_the_broken_object_and_not_the_new_piece() {
let mut s = Session::new();
let a = first_handle(&s.execute("line", &json!({ "points": [[0, 50], [100, 50]] })).unwrap());
let b = first_handle(&s.execute("line", &json!({ "points": [[50, 0], [50, 100]] })).unwrap());
s.execute("group", &json!({ "name": "G1", "handles": [a.hex(), b.hex()] })).unwrap();
s.execute("break", &json!({ "handle": b.hex(), "p1": [50, 20], "p2": [50, 30] })).unwrap();
let d = s.doc().unwrap();
assert_eq!(d.model.iter().count(), 3);
assert_eq!(d.groups.iter().find(|g| g.name == "G1").unwrap().members, vec![a, b]);
}
fn hatch(s: &Session, h: Handle) -> Hatch {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Hatch(x) => x.clone(),
k => panic!("not a hatch: {k:?}"),
}
}
fn loop_points(h: &Hatch) -> Vec<Vec<(f64, f64)>> {
h.loops.iter().map(|l| l.vertices.iter().map(|v| (v.p.x, v.p.y)).collect()).collect()
}
#[test]
fn a_hatch_whose_polyline_is_broken_open_keeps_its_shape_and_loses_its_link() {
let mut s = Session::new();
let k = first_handle(&s.execute("pline", &json!({ "vertices": [[500, 0], [520, 0], [520, 20], [500, 20]], "closed": true })).unwrap());
let h = first_handle(&s.execute("hatch", &json!({ "handles": [k.hex()] })).unwrap());
assert!(hatch(&s, h).associative);
let square = loop_points(&hatch(&s, h));
s.execute("break", &json!({ "handle": k.hex(), "p1": [510, 0], "p2": [520, 10] })).unwrap();
assert!(matches!(&s.doc().unwrap().entity(k).unwrap().kind, EntityKind::LwPolyline(p) if !p.closed));
let after = hatch(&s, h);
assert!(!after.associative);
assert_eq!(loop_points(&after), square);
s.execute("u", &json!({})).unwrap();
assert!(hatch(&s, h).associative);
}
#[test]
fn a_hatch_whose_boundary_line_is_trimmed_keeps_its_shape_and_loses_its_link() {
let mut s = Session::new();
let sides = [
line(&mut s, "0", [500.0, 0.0], [520.0, 0.0]),
line(&mut s, "0", [520.0, 0.0], [520.0, 20.0]),
line(&mut s, "0", [520.0, 20.0], [500.0, 20.0]),
line(&mut s, "0", [500.0, 20.0], [500.0, 0.0]),
];
let h = first_handle(&s.execute("hatch", &json!({ "points": [[510, 10]] })).unwrap());
assert!(hatch(&s, h).associative);
let square = loop_points(&hatch(&s, h));
let k1 = line(&mut s, "0", [505.0, -5.0], [505.0, 5.0]);
let k2 = line(&mut s, "0", [515.0, -5.0], [515.0, 5.0]);
let before = handles(&s);
s.execute("trim", &json!({ "handle": sides[0].hex(), "pick": [510, 0], "edges": [k1.hex(), k2.hex()] })).unwrap();
let after = handles(&s);
assert_eq!(after[..before.len()], before[..]);
assert_eq!(after.len(), before.len() + 1);
let hh = hatch(&s, h);
assert!(!hh.associative);
assert_eq!(loop_points(&hh), square);
}
fn dim(s: &Session, h: Handle) -> Dimension {
match &s.doc().unwrap().entity(h).unwrap().kind {
EntityKind::Dimension(d) => d.clone(),
k => panic!("not a dimension: {k:?}"),
}
}
fn attachments(d: &Dimension) -> Vec<(String, Handle, AssocSnap)> {
let mut v: Vec<(String, Handle, AssocSnap)> = d.assoc.iter().map(|a: &DimAssoc| (a.point.clone(), a.handle, a.snap.clone())).collect();
v.sort_by(|a, b| a.0.cmp(&b.0));
v
}
fn origins(d: &Dimension) -> [(f64, f64); 2] {
[(d.p13.x, d.p13.y), (d.p14.x, d.p14.y)]
}
/// A vertical line from (x, 0) to (x, 100) with a linear dimension attached to both its ends.
fn dimensioned_line(s: &mut Session, x: f64) -> (Handle, Handle) {
let l = first_handle(&s.execute("line", &json!({ "points": [[x, 0], [x, 100]] })).unwrap());
let d = first_handle(&s.execute("dimlinear", &json!({ "p1": [x, 0], "p2": [x, 100], "at": [x + 20.0, 50] })).unwrap());
assert_eq!(attachments(&dim(s, d)), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]);
(l, d)
}
#[test]
fn a_dimension_across_a_line_broken_in_its_middle_stays_on_both_ends() {
// Measured: the reference to the line's end moves to the new piece, the dimension is unchanged.
let mut s = Session::new();
let (l, d) = dimensioned_line(&mut s, 50.0);
run(&mut s, &["BREAK 50,20 50,30"]);
let piece = *handles(&s).last().unwrap();
assert!(piece != l && piece != d);
let dm = dim(&s, d);
assert_eq!(attachments(&dm), [("p13".into(), l, AssocSnap::Start), ("p14".into(), piece, AssocSnap::End)]);
assert_eq!(origins(&dm), [(50.0, 0.0), (50.0, 100.0)]);
s.execute("u", &json!({})).unwrap();
assert_eq!(attachments(&dim(&s, d)), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]);
}
#[test]
fn a_dimension_on_a_trimmed_off_end_follows_the_new_end() {
// Measured: the references stay on the line, the dimension measures 40 instead of 100.
let mut s = Session::new();
let (l, d) = dimensioned_line(&mut s, 650.0);
let edge = first_handle(&s.execute("line", &json!({ "points": [[640, 40], [660, 40]] })).unwrap());
s.execute("trim", &json!({ "handle": l.hex(), "pick": [650, 80], "edges": [edge.hex()] })).unwrap();
let dm = dim(&s, d);
assert_eq!(attachments(&dm), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]);
assert_eq!(origins(&dm), [(650.0, 0.0), (650.0, 40.0)]);
}
#[test]
fn a_dimension_on_a_broken_off_start_follows_the_new_start() {
// Measured: BREAK from the start to (650, 20); the dimension starts at (650, 20).
let mut s = Session::new();
let (l, d) = dimensioned_line(&mut s, 650.0);
run(&mut s, &["BREAK 650,10 F 650,0 650,20"]);
assert_eq!(handles(&s), [l, d]);
let dm = dim(&s, d);
assert_eq!(attachments(&dm), [("p13".into(), l, AssocSnap::Start), ("p14".into(), l, AssocSnap::End)]);
assert_eq!(origins(&dm), [(650.0, 20.0), (650.0, 100.0)]);
}
#[test]
fn a_dimension_follows_a_piece_a_later_pick_of_the_same_trim_shortens() {
// The measured rules pick by pick: the first pick moves the reference to the line's end onto
// the new piece, the second cuts that end off, so the dimension ends at the piece's new end.
let mut s = Session::new();
let other = first_handle(&s.execute("line", &json!({ "points": [[0, 20], [0, 30]] })).unwrap());
let l = first_handle(&s.execute("line", &json!({ "points": [[0, 0], [100, 0]] })).unwrap());
for x in [40, 60, 80] {
s.execute("line", &json!({ "points": [[x, -5], [x, 5]] })).unwrap();
}
let d = first_handle(&s.execute("dimlinear", &json!({ "p1": [0, 30], "p2": [100, 0], "at": [50, 60] })).unwrap());
assert_eq!(attachments(&dim(&s, d)), [("p13".into(), other, AssocSnap::End), ("p14".into(), l, AssocSnap::End)]);
s.script("TRIM 50,0 90,0\n\n").unwrap();
assert!(s.running.is_none(), "{}", s.prompt_text());
let piece = *handles(&s).last().unwrap();
assert_eq!(table(&s, &[l]).last().unwrap(), "0+:LINE:60,0>80,0");
let dm = dim(&s, d);
assert_eq!(attachments(&dm), [("p13".into(), other, AssocSnap::End), ("p14".into(), piece, AssocSnap::End)]);
assert_eq!(origins(&dm), [(0.0, 30.0), (80.0, 0.0)]);
}
#[test]
fn a_dimension_on_a_closed_polyline_opened_by_break_keeps_its_vertices() {
// The vertices it measured are still vertices of the polyline, numbered from the break.
let mut s = Session::new();
let k = first_handle(&s.execute("pline", &json!({ "vertices": [[500, 0], [520, 0], [520, 20], [500, 20]], "closed": true })).unwrap());
let d = first_handle(&s.execute("dimlinear", &json!({ "p1": [500, 20], "p2": [520, 20], "at": [510, 40] })).unwrap());
assert_eq!(attachments(&dim(&s, d)), [("p13".into(), k, AssocSnap::Vertex { index: 3 }), ("p14".into(), k, AssocSnap::Vertex { index: 2 })]);
s.execute("break", &json!({ "handle": k.hex(), "p1": [510, 0], "p2": [520, 10] })).unwrap();
let dm = dim(&s, d);
assert_eq!(attachments(&dm), [("p13".into(), k, AssocSnap::Vertex { index: 2 }), ("p14".into(), k, AssocSnap::Vertex { index: 1 })]);
assert_eq!(origins(&dm), [(500.0, 20.0), (520.0, 20.0)]);
// Still attached: moving the polyline takes the dimension along.
s.execute("move", &json!({ "handles": [k.hex()], "delta": [0, 10] })).unwrap();
assert_eq!(origins(&dim(&s, d)), [(500.0, 30.0), (520.0, 30.0)]);
}
#[test]
fn constraints_on_a_broken_object_go_and_leave_the_others_where_they_are() {
let mut s = Session::new();
let a = first_handle(&s.execute("line", &json!({ "points": [[0, 0], [100, 0]] })).unwrap());
let b = first_handle(&s.execute("line", &json!({ "points": [[100, 0], [100, 50]] })).unwrap());
s.execute("geomconstraint", &json!({ "type": "coincident", "h1": a.hex(), "p1": "end", "h2": b.hex(), "p2": "start" })).unwrap();
s.execute("break", &json!({ "handle": a.hex(), "p1": [40, 0], "p2": [60, 0] })).unwrap();
let d = s.doc().unwrap();
assert!(d.constraints.is_empty());
let original = [a, b];
assert_eq!(table(&s, &original), ["0:LINE:0,0>40,0", "0:LINE:100,0>100,50", "0+:LINE:60,0>100,0"]);
}
+1
View File
@@ -21,6 +21,7 @@ fn insert(block: &str) -> Insert {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
}
}
+1
View File
@@ -20,6 +20,7 @@ fn insert(block: &str, x: f64, cols: u32, rows: u32) -> EntityKind {
rows,
col_spacing: 5.0,
row_spacing: 5.0,
clip: None,
})
}
+3 -3
View File
@@ -135,9 +135,9 @@ fn mview_restore_puts_a_saved_configuration_on_a_layout() {
fn mview_restore_ignores_unusable_tiles_from_files() {
let (mut s, _) = two_tiles();
let bad = [
VportTile { min: v(f64::NAN, 0.0), max: v(1.0, 1.0), center: v(0.0, 0.0), height: 1.0, aspect: 1.0 },
VportTile { min: v(0.5, 0.5), max: v(0.5, 0.9), center: v(0.0, 0.0), height: 1.0, aspect: 1.0 },
VportTile { min: v(-3.0, -3.0), max: v(9.0, 9.0), center: v(f64::INFINITY, 0.0), height: -1.0, aspect: f64::NAN },
VportTile { min: v(f64::NAN, 0.0), max: v(1.0, 1.0), center: v(0.0, 0.0), height: 1.0, aspect: 1.0, twist: 0.0 },
VportTile { min: v(0.5, 0.5), max: v(0.5, 0.9), center: v(0.0, 0.0), height: 1.0, aspect: 1.0, twist: 0.0 },
VportTile { min: v(-3.0, -3.0), max: v(9.0, 9.0), center: v(f64::INFINITY, 0.0), height: -1.0, aspect: f64::NAN, twist: 0.0 },
];
if let Some(c) = s.doc_mut().unwrap().vports.iter_mut().find(|c| c.name == "Two") {
c.tiles = bad.to_vec();
+3
View File
@@ -19,6 +19,7 @@ mod blockreplace;
mod break_closed_polyline;
mod break_join_locked_layers;
mod break_keeps_z;
mod break_trim_keep_handle;
mod burst;
mod change_command;
mod chprop_command;
@@ -112,6 +113,7 @@ mod polyface_explode;
mod post_command_passes;
mod prompt_keywords;
mod prompt_or_once;
mod properties_set_locked;
mod props_bad_lineweight;
mod props_insert_scale_attribs;
mod purge_mlinestyles;
@@ -165,6 +167,7 @@ mod viewport_clip;
mod vplayer_prompts;
mod vports;
mod wipeout_grips;
mod xclip;
mod xdata_follows_entity;
mod zoom_keywords;
mod zoom_viewport;
@@ -27,6 +27,7 @@ fn drawing() -> (Drawing, Space) {
layer_colors: Vec::new(),
clip: None,
on: true,
twist: 0.0,
}),
)
.unwrap();
@@ -310,6 +311,7 @@ fn viewport_frozen_layers_apply_inside_nested_block_references() {
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
})
};
let mut outer = Block::new("Outer");
+19 -5
View File
@@ -46,7 +46,7 @@ fn typed_save_restore_list_delete() {
// Saving is an undo step; a view change is not.
set_view(&mut s, 0.0, 0.0, 500.0);
typed(&mut s, &["view", "r", "front"]);
assert_eq!(view(&s), View { center: Vec2::new(10.0, 20.0), height: 30.0 });
assert_eq!(view(&s), View { center: Vec2::new(10.0, 20.0), height: 30.0, twist: 0.0 });
// Zoom Previous goes back to the view before the restore.
s.execute("zoom.previous", &json!({})).unwrap();
assert_eq!(view(&s).height, 500.0);
@@ -84,6 +84,20 @@ fn window_option_and_json_forms() {
assert!(s.execute("view", &json!({ "option": "orthographic" })).is_err());
}
#[test]
fn a_window_saved_in_a_twisted_view_restores_whole() {
let mut s = session();
s.execute("view.set", &json!({ "center": [0, 0], "height": 10, "twist": 45 })).unwrap();
s.execute("view", &json!({ "option": "window", "name": "Turned", "p1": [0, 0], "p2": [10, 10] })).unwrap();
let v = s.doc().unwrap().views.first().cloned().unwrap();
// A 10 x 10 world square seen at 45° is 10√2 across on screen.
assert!(close(v.width, 200f64.sqrt()) && close(v.height, 200f64.sqrt()), "{} x {}", v.width, v.height);
// Corners near the number limit overflow when turned: an error, and the saved view stays.
let huge = json!({ "option": "window", "name": "Turned", "p1": [1.4e308, 1.4e308], "p2": [1.5e308, 1.5e308] });
assert!(s.execute("view", &huge).is_err());
assert!(close(s.doc().unwrap().views.first().unwrap().width, 200f64.sqrt()));
}
#[test]
fn layer_snapshot_restores_layers_and_the_setting_turns_it_off() {
let mut s = session();
@@ -112,7 +126,7 @@ fn paper_space_view_switches_to_its_layout() {
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
s.execute("view", &json!({ "option": "restore", "name": "Sheet" })).unwrap();
assert_eq!(s.layout_space(), Space::Paper(layout));
assert_eq!(view(&s), View { center: Vec2::new(5.0, 4.0), height: 6.0 });
assert_eq!(view(&s), View { center: Vec2::new(5.0, 4.0), height: 6.0, twist: 0.0 });
}
#[test]
@@ -138,7 +152,7 @@ fn zoom_realtime_drags_and_enter_ends() {
assert_eq!(view(&s).height, 100.0);
// The JSON form zooms by a factor about the centre.
s.execute("zoom.realtime", &json!({ "factor": 4 })).unwrap();
assert_eq!(view(&s), View { center: Vec2::ZERO, height: 25.0 });
assert_eq!(view(&s), View { center: Vec2::ZERO, height: 25.0, twist: 0.0 });
}
#[test]
@@ -158,10 +172,10 @@ fn zoom_dynamic_places_and_sizes_the_view_box() {
assert!(close(v.height, 40.0), "{v:?}");
// Zoom Previous skips the overview.
s.execute("zoom.previous", &json!({})).unwrap();
assert_eq!(view(&s), View { center: Vec2::new(10.0, 10.0), height: 20.0 });
assert_eq!(view(&s), View { center: Vec2::new(10.0, 10.0), height: 20.0, twist: 0.0 });
// JSON: like Center.
s.execute("zoom.dynamic", &json!({ "center": [1, 2], "height": 3 })).unwrap();
assert_eq!(view(&s), View { center: Vec2::new(1.0, 2.0), height: 3.0 });
assert_eq!(view(&s), View { center: Vec2::new(1.0, 2.0), height: 3.0, twist: 0.0 });
}
#[test]

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