Compare commits

..
Author SHA1 Message Date
FredApps 0d59521fb3 Use an absolute evidence path for hosted CadCraft plots [plot-output-only] 2026-12-02 23:29:30 +01:00
FredApps 4ac302eeaa Verify actual CadCraft layouts on Letter and A4 through a Windows file queue 2026-12-02 23:11:36 +01:00
FredApps dc6c68015d Exercise the CadCraft plotter catalog against the hosted Windows PDF driver 2026-12-02 22:47:24 +01:00
FredApps 0d17c1b811 Use craft-print for the Windows plotter paper catalog
Keep the paper display, default mapping, exact-scale submission, and existing tests from CadCraft #2171. Remove direct winprint and winsafe dependencies from the app. Stage after #2171 and a repin to a merged craft-libs revision with the rich Windows paper catalog. The published pin stays unchanged.
2026-12-02 21:16:09 +01:00
tiraelandClaude Opus 5.5 045c1d2dbf Plot dialog and preview: bound to the drawing shown, keyboard pan, detail kept
- The Plot dialog's kept settings are for the drawing shown and the block the
  Block Editor shows, so entering or leaving the editor starts over.
- A preview opened from the Plot dialog is bound to its drawing: another
  drawing shown since is not plotted with it, Print... is off, and the dialog
  plots on Print... only the settings it still keeps.
- The preview knows the sheet's plotted size from the page setup (several
  sheets leave it to the layout), so detail renders at the right resolution.
- The preview surface takes keyboard focus: arrow keys pan, + and - zoom, Tab
  leaves; a failed detail render keeps the previous detail texture.

Answers the 2026-12-01 review of #2171.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 18:33:55 +01:00
tiraelandClaude Opus 5.5 e04c7d14f2 Plot: printer listings that don't wait on one queue, stamps independent of layer 0
- System printers are asked about at once (crates/io/src/printer_queries.rs):
  a CUPS queue or Windows driver that answers late is left out of that listing
  instead of holding up the others, and one still blocked is not asked again.
- With a remote CUPS server (lpstat -H), papers come from lpoptions, which asks
  that server, not from the local PPD files.
- A timed-out lp says the job may already be queued and how to check.
- Windows: the default paper is read from the queue's default ticket (merged
  through the print ticket provider); paper names are told apart as the device
  does before a size's representative is chosen.
- The plot stamp is built against an empty drawing (layer 0 off or frozen no
  longer hides it), and its drawn length is limited after {{ is decoded.

Answers the 2026-12-01 review of #2171.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 18:24:25 +01:00
tiraelandClaude Opus 5.5 3231456e2a Plot: printers named while a listing runs, A4 by its short name, one-sheet PDF space
- A listing worker whose host hook fails clears its listing mark, so commands
  stop waiting for it and Refresh can start another.
- PAGESETUP changing the paper of a layout's saved printer, and PLOTTERMANAGER
  new from a printer, wait for the listing under way like a named device.
- A standard paper's full name finds a printer paper listed by its short name
  (A4), so the job carries the printer's own key.
- A single layouts entry is the sheet plotted for PDF too.
- Typed -PLOTTERMANAGER ? marks the default printer; PREVIEW says it draws no
  plot stamp.

Answers the 2026-12-01 review of #2171.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 18:20:20 +01:00
tiraelandClaude Opus 5.5 ca2490e3d7 Preview zoom test: install the headless UI runtime
Main's app needs it to draw a frame; the test only ran under nextest, where its own hooks win, so a plain cargo test skipped it and the panic went unseen.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 17:45:33 +01:00
tiraelandClaude Opus 5.5 6660ae2d6f Plot: answer the 2026-11-24 review of #2171
- Printer listings: a wait that runs out marks only a listing that has itself
  run the full wait as hung, not one started during the wait.
- PLOT: a single `layouts` entry resolves that layout's device and paper, like
  `layout`; several sheets without `device` go to the PDF file instead of the
  shown layout's printer.
- PLOTTERMANAGER get/save wait (bounded) for the first printer listing.
- CUPS: pipe workers start with thread::Builder; when a thread can't start,
  the command is killed and reaped and an error returned instead of a panic.
- PNG plots cut only the stamp to the printable area (raster::render_within),
  so a layout's marks in the sheet margins stay.
- Plot stamp fields are filled in one pass (cadcraft_doc::fill_stamp), values
  never filled again across the command's and the plotter's steps; `{{` is a
  literal brace.
- Windows papers: a paper dropped for its repeated name no longer stands for
  (and hides) a paper of another name.
- Plot dialog: kept settings are tied to the drawing, so another drawing starts
  from its own page setup; Plot stamp is disabled for SVG and not sent for it.
- Tests: the stamp's PDF clip is checked with content operators; the dialog's
  several-sheets payload gives a two-page PDF through PLOT; harnesses that run
  the app's UI install the headless runtime, as main's do.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 17:31:53 +01:00
tiraelandClaude Opus 5.5 22cd111b22 Merge main into plot-advanced
Conflicts:
- apps/cadcraft{,-cli}: kept main's PDF import hook and the system printer hooks.
- engine layout.rs: PAGESETUP params keep `layouts` and main's JIS paper names; PLOT
  keeps the printer sheet size and goes through main's plot_noted (the printer
  result reports the dash-limit notes too).
- engine plotters.rs, layout/tests.rs, tests/plotters.rs, render tests.rs, io lib.rs:
  both sides' additions kept.
- io pdf.rs: write_page takes portrait_media and counts main's undashed runs;
  fill_tris keeps the PR's clip argument with main's outline fill.
- io plotter.rs: the PNG crop with main's (bytes, undashed) return.
- ui-egui exchange.rs: main's PDF import dialog and escape_pressed with the
  preview's detail render.
- ui-egui managers.rs: the PR's page rows and Plot dialog, with main's switch from
  craft_ui::ComboBox to egui::ComboBox applied to them.
- it.tsv, uk.tsv: both sides' rows (no duplicate keys).
- Cargo.lock: regenerated from main's.
- After the merge: stamp Text gets main's backwards/upside_down fields, a
  DevicePaper test gets native_key.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-12-01 17:04:56 +01:00
tiraelandClaude Opus 5.5 8582019940 Plot: answer the 2026-11-21 review of #2171
- PLOT refuses several sheets on a system printer before writing or
  submitting; the printer branch checks the automation write root first.
- Printer listings: a completed listing is published unless a newer one
  was, so overlapping refreshes cannot keep the cache empty.
- CUPS: papers carry their native keyword, submission resolves it and
  refuses media whose size no longer matches the rendered sheet; on a
  display-name collision the starred (default) choice wins.
- The plot stamp is clipped to the printable area, not the plot window
  (PDF and PNG); window culling reaches a mitred corner of the widest
  lineweight, shared by the plotters and the preview.
- Page Setup's multi-selection is dropped when the drawing changes; the
  multi-sheet plot sends only `layouts`; the multi-sheet preview shows the
  stamp; a deleted target gives way to a surviving ticked sheet.
- Windows papers: unknown margins are conservative, not zero, and no
  paper is dropped without a listed paper within tolerance.
- PLOTTERMANAGER looks printers up by their whole name, a copy of a
  system printer is a user device, and `new` waits for the first listing.
- A refused print job reports the PDF already saved and its path.
- DisplayList::append keeps per-primitive layers aligned.
- The sheet sketch has an accessible description.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-24 16:58:47 +01:00
tirael 771ced822d Merge main into plot-advanced 2026-11-24 16:11:57 +01:00
tirael 868465a89b System printer tests: each starts from an empty job list
The tests share the fake spooler's job list and run in any order; the
folder-creating plot test now takes its job, and the others clear the
list first.
2026-11-21 14:56:40 +01:00
tirael eb8b51abec Merge remote-tracking branch 'origin/main' into plot-advanced
# Conflicts:
#	crates/engine/src/cmd/layout.rs
#	crates/engine/src/cmd/plotters.rs
#	crates/render/src/tests.rs
#	crates/ui-egui/src/i18n/uk.tsv
#	crates/ui-egui/src/managers.rs
#	crates/ui-egui/tests/it/main.rs
2026-11-21 14:45:06 +01:00
tirael 5d7415b20d Plot: printer routing, papers and preview follow the plotted sheet
- PAGESETUP checks the whole layouts list after removing duplicates.
- Plot to file with a printer makes a missing folder, as without one.
- Dialog device changes use the cached printer list without waiting.
- A path that selects PNG or SVG is not routed to the layout's printer.
- CUPS and Windows devices keep the spooler's printer name whole.
- CUPS refuses a job whose selected paper can't be resolved, rather
  than printing on the queue's default paper.
- Windows lists one paper per size, with margins every driver option
  of that size can print, since craft-print picks the paper by size.
- PDF window pages keep the plot stamp.
- Plot Preview rebuilds after a drawing switch or edit, can redraw
  detail after Fit, previews a sheet that OK plots, and the no-device
  plot sends the margins the preview used.
2026-11-21 14:35:08 +01:00
tirael cbcb674adf Merge current main and bound abandoned printer listings 2026-11-17 11:10:09 +01:00
KvasExpert 37a33b9993 Merge branch 'main' into plot-advanced 2026-11-15 09:48:27 +01:00
tirael 0b541c8203 Merge upstream main (ddfa833b) into plot-advanced
Main now adds cadcraft-io as a ui-egui dev-dependency too (#3048);
keep one entry for both uses.
2026-11-13 19:05:29 +01:00
tiraelandClaude Opus 5.5 97b5e91779 Merge upstream main (ca87680f) into plot-advanced
Repairs the GitHub web merge e1913b02, which kept the old crates/render/src/lib.rs
beside upstream's split modules (Kind and everything else defined twice): render is
upstream's again, with DisplayList::append on display.rs for the plot stamp.

Upstream changes taken with our behaviour on top:
- Plot dialog OK asks for the file through `pick_then` (asynchronous on macOS,
  #1534) and plots in `run_plot`, which also saves the layout's page setup first and
  reports a system printer's job; combo boxes are craft_ui's.
- run_plot: a system printer always gets the PDF, so `output`/`layouts` image checks
  don't apply to it; the param doc adds system printers and the stamp to upstream's.
- PNG plots: upstream's placement (saved windows, layouts at scale, printable-area
  blanking) with our `crop` and plot stamp.
- CLI: the system-printer hooks move to the new apps/cadcraft-cli/src/lib.rs.
- craft-print at craft-libs 92d392c, the revision upstream's craft-pdf uses.
- Layout tests: ours move to layout/tests.rs as upstream's did.
- docs/gaps.md is upstream's (maintainers update it in batches); hardware-parity
  keeps our system-printer row.
- cups.rs/winprint.rs: explicit test imports for the wildcard-import lint.
- Plot window (from the fork's ef5ba06c): only what is inside the window is plotted
  (DisplayList::retain_within, Bounds2::intersection) and the plot is cut at the
  window's edges in PDF, PNG (through the view, so crops too), SVG and the preview.
- preview_zoom test: skipped when another test of the binary set the global file
  hooks first (plain `cargo test`; nextest runs it alone).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 10:38:33 +01:00
KvasExpert e1913b0263 Merge branch 'main' into plot-advanced 2026-10-27 06:38:32 +01:00
KvasExpert 4be441ed9d Merge branch 'main' into plot-advanced 2026-10-26 11:29:06 +01:00
tiraelandClaude Opus 5.5 d02e392030 Doc comments for the functions and tests this branch adds or changes
Covers the plotting, printer, stamp and Plot dialog code, including the parts merged from #755,
#2160, #2084, #2086, #2083 and #737. Comments only.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-26 09:35:39 +01:00
tiraelandClaude Opus 5.5 a627effe1e Printers: only the latest listing writes the printer list
A listing given up after the wait, finishing after a newer one started, no longer puts its older
list (and time) back. Found by CodeRabbit on #2171.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:29:48 +01:00
tiraelandClaude Opus 5.5 d5468e38d1 Printers: a hung listing or lp no longer holds plots up
- A printer listing that never finishes (a driver that doesn't answer) is given up after the
  10 s wait: the dialog stops showing "Looking for printers…", Refresh can start a new one, and
  commands stop waiting until a listing finishes again (Refresh clears that).
- A layout whose page setup names no device ("" or "None") doesn't list printers at all.
- `lp` gets the PDF and is read on threads and is stopped after 60 s, so a CUPS that stopped
  answering can't freeze PLOT.

Found by CodeRabbit on #2171; system_printers_slow covers the second plot and the no-device plot.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 23:14:18 +01:00
tiraelandClaude Opus 5.5 92f071b2a9 PLOT: plot to file with a printer builds for wasm (the path's type is spelled out)
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 22:48:06 +01:00
tiraelandClaude Opus 5.5 1fb38a7b46 docs: system printers, plot stamp and the Plot dialog in plotters.md, gaps.md, hardware parity
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 22:40:49 +01:00
tiraelandClaude Opus 5.5 1dfbb088d1 Plot: the stamp names the real device and paper; Model and orientations translated
The dialog's stamp names the chosen device and paper itself, so the preview (an image of the
same sheet) stamps what the plot will; PLOT's own `stamp: true` names a device's paper by its
name rather than the plotter's "User (… MM)" size. "Model", the sheet summary's orientation and
style table, and the preview caption go through the catalogs.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 22:39:16 +01:00
tiraelandClaude Opus 5.5 5edeebfdd6 Plot dialog: every control works, printers found and marked, translated
The sectioned dialog keeps only controls that do something:
- Printer/plotter: the device list marks the system's default printer; "Where" says whether the
  plot prints or writes a file; Number of copies for printers; "Plot to file" with a printer also
  writes the printed PDF to a file chosen after OK (written first, see PLOT); while the system
  printers are being listed a spinner says so, and "Refresh printers" asks the system again.
- Plot style table: "Edit…" opens the Plot Style Manager on that table and brings Plot back,
  settings kept, when it closes.
- Plot options: lineweights and transparency as before; "Plot with plot styles" plots without
  the table while keeping it chosen; "Plot stamp on" stamps drawing, layout, date and time (UTC),
  device, paper and scale at the sheet's corner (preview included); "Save changes to layout"
  saves the settings in the layout's page setup on OK.
- Several sheets ticked: their summary, and the stamp, which each sheet gets with its own name.
- Left out: the placeholders that could not work (named page setups, device properties, PDF
  options, shaded viewports, background plotting, paper space order and hiding, upside-down
  plots, scaled lineweights, More options, Help).
- Every label, hint and message goes through the catalogs (it and uk rows added); managers.rs
  is now checked by `cargo xtask i18n`. The combo boxes are labelled for screen readers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 22:28:22 +01:00
tiraelandClaude Opus 5.5 6dcbac1964 PLOT stamp: a line of text at the corner of each plotted sheet
PLOT and EXPORTPDF take `stamp: true | text`: a line of text plotted 1 mm inside the lower-left
corner of the printable area, 2 mm high, in CADCraft's stroke font. `{drawing}` and `{device}`
are filled in by the engine, `{layout}`, `{paper}` and `{scale}` (1:100, 2:1) by the plotter for
each sheet, so a plot of several sheets stamps each with its own; `true` stamps "{drawing},
{layout}, {device}, {paper}, {scale}". PDF and PNG plots (and so the preview) draw it; SVG
doesn't. DisplayList::append adds the stamp's list to the sheet's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 22:20:13 +01:00
tiraelandClaude Opus 5.5 cf463a93d5 Printers: queues without a PPD, the default printer, Refresh, plot to file and print
- CUPS: a destination without a PPD file the user can read (a driverless IPP queue CUPS made on
  the fly, or a PPD readable only by root) takes its papers from `lpoptions -p NAME -l` (PWG
  names such as iso_a4_210x297mm, Adobe's w612h792, plain A4/Letter/Legal) with IPP's usual
  4.23 mm margins, and prints with `-o media=KEYWORD`; it was left out before.
- `lpstat -d` names the system's default printer; CUPS commands run in the C locale so their
  replies parse in any language. Windows' default printer is marked the same way.
  PlotterConfig.system_default (never in a file), PLOTTERMANAGER list/get report `default`.
- PLOTTERMANAGER action `refresh` asks the system for its printers again instead of using a
  list up to 5 s old.
- PLOT to a printer with `path` (plot to file) writes the PDF first, atomically, and prints
  only when that worked.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 22:15:34 +01:00
tirael dbf64ae094 Merge branch 'pr-737' into plot-advanced
The sectioned Plot dialog of #737 with the merged branches' features folded in: page_rows keeps
#737's row selection and #2083's `force`, the Layout section gains #2084's "Plot several sheets"
(with several sheets ticked their summary replaces the per-sheet sections), the printer's copies
are a real row for system printers (#755) instead of a disabled one, and Apply to Layout is for a
single layout.
2026-10-25 22:07:41 +01:00
tiraelandClaude Opus 5.5 153195452f Plot merges: the preview's state and wheel events as egui 0.37 builds them
The merged Plot dialog's PlotState carries the sheets and copies the merged branches added, and
the preview-zoom test's wheel events carry egui 0.37's event source.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 22:03:23 +01:00
tirael 76b0b633da Merge branch 'pr-2083' into plot-advanced
# Conflicts:
#	crates/ui-egui/src/i18n/it.tsv
#	crates/ui-egui/src/managers.rs
#	docs/gaps.md
2026-10-25 22:01:17 +01:00
tirael e5ea6bcb75 Merge branch 'pr-2086' into plot-advanced
# Conflicts:
#	crates/ui-egui/src/exchange.rs
#	docs/gaps.md
2026-10-25 22:00:58 +01:00
tirael b443e03542 Merge branch 'pr-2084' into plot-advanced
# Conflicts:
#	crates/ui-egui/src/managers.rs
#	docs/gaps.md
2026-10-25 22:00:38 +01:00
tirael a58a110db8 Merge branch 'pr-2160' into plot-advanced 2026-10-25 21:59:57 +01:00
Montrek22andClaude Opus 5.5 ddc81677ca Merge main: craft-print at craft-libs a0916808, with every other craft-libs crate
main moved every craft-libs crate to a0916808 (#2153); craft-print follows it. Its winprint
and winsafe pins are unchanged, so cadcraft-io's stay as they are. cargo xtask ci passes on
Windows (all 7 steps).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 20:24:08 +01:00
Montrek22andClaude Opus 5.5 aacf8ea548 xtask: tests pass on Windows
stats: `walk` is only used by the Unix-only symlink test, so import it there (an unused
import failed clippy -D warnings on Windows). parity: the year 318857 is past the end of
Windows' SystemTime (30828), so `civil_dates` checks it only where it exists, like the
u64::MAX / 2 case after it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 19:40:48 +01:00
Montrek22andClaude Opus 5.5 33ba00c16e Plot to Windows printers through the spooler (#670 step 3)
The spooler's printers become plot devices on Windows, as CUPS printers do on macOS and
Linux (#755): each with its driver's papers and printable areas, read from the driver's
PrintCapabilities. A plot to one is the PDF the PDF plotter writes, printed at its exact size
by craft-print (Windows.Data.Pdf drawn as vectors into the XPS print API; no program started,
no unsafe here). Printers and their papers are read on a thread each, papers' printable areas
8 at a time, so four printers with 138 papers list in about 4 s instead of 17.

cadcraft-cli installs the system printers too (CUPS and Windows), so scripts can print.

Tested on Windows 11 with a Canon PRO-100S: listed with its 34 papers and margins; a
100 x 50 mm rectangle plotted at 1:1 on A4 printed at exactly 100 x 50 mm.

docs/gaps.md: H3 narrowed, F14 updated.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-25 19:32:09 +01:00
Montrek22 e51c3e76be Merge branch 'pr-755' into feat/windows-printers 2026-10-25 19:12:32 +01:00
lforgiariniandClaude Sonnet 5.5 240ec04584 docs: doc comments for the functions and tests this change adds
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-25 01:19:33 +02:00
lforgiariniandClaude Sonnet 5.5 b9e0609b93 docs: doc comments for the functions and tests this change adds
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-25 01:15:53 +02:00
lforgiariniandClaude Sonnet 5.5 e50e9039d4 docs(pagesetup): doc comments for the multi-layout functions and tests
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-25 01:10:54 +02:00
lforgiariniandClaude Sonnet 5.5 d0c59b1994 fix(preview): a resized window restarts the wait before the detail is drawn again
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 19:22:19 +02:00
lforgiariniandClaude Sonnet 5.5 04ad0142a8 fix(plot): keep the target in step with the ticked sheets after deleted layouts drop out
When cleaning up leaves exactly one ticked sheet, it becomes the dialog's target
(and its page setup), so OK plots the sheet the dialog shows.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 19:16:02 +02:00
lforgiariniandClaude Sonnet 5.5 172932a490 test(plot): drop the multi-sheet plot test that went through the global plot hook
Other tests in the same process replace the hook, which made it flaky;
sheets_params is covered on its own and the engine's plot_sheets tests cover
`layouts`.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 19:07:56 +02:00
lforgiariniandClaude Sonnet 5.5 3df303c366 test(preview): do not depend on the process-wide plot hook
The style-table test calls the real plotter directly, and the zoom test only
counts PNG plots, since other tests in the same process replace or use the
global plot hook.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 18:59:37 +02:00
lforgiariniandClaude Sonnet 5.5 211437b689 feat(preview): draw plot styles as plotted, zoom and pan the preview
- The toolbar's Plot Preview draws the page setup's plot style table (colours,
  screening, lineweights, line ends and fills) like the plotters; the Plot
  dialog sends "None" as such so it overrides a layout's own table.
- The preview window is resizable and zooms (wheel, +/-, pinch) and pans (drag);
  Fit or a double click shows the whole sheet.
- The part in view is drawn again at the screen's resolution once the view
  rests: PNG plots take `crop`, a part of the sheet.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 18:47:22 +02:00
lforgiariniandClaude Sonnet 5.5 cfffee99e3 fix(pagesetup): a pick that matches the layout shown still applies to the others
With several layouts picked, choosing the paper, orientation, device, plot area or
plot style table the layout shown already has returned no change, so layouts that
differed could not be made to match. page_rows takes `force` (set when several
layouts are picked) to treat that pick as a change; the Plot dialog passes false.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 17:48:24 +02:00
lforgiariniandClaude Sonnet 5.5 973e7983c6 feat(plot): plot several sheets from the Plot dialog
The Plot dialog has a "Plot several sheets" section: tick Model and layouts (or
All layouts) and OK writes one PDF, one page per sheet, each with its own page
setup (the engine's `layouts`).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 17:33:12 +02:00
lforgiariniandClaude Sonnet 5.5 e30bc0604a feat(pagesetup): apply a change to several layouts at once
The Page Setup Manager picks several layouts (Ctrl/Cmd, Shift, Select all) and a
change applies to all of them. PAGESETUP takes `layouts` (names or "all") for
the same: one undo step, all or nothing.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 17:27:26 +02:00
Aldo ZarateandClaude Opus 5.5 ecc0a8450a Plot: a printer's PDF is set before the output's own checks
The SVG-only refusal of model-space offsets ran before a printer plot switched the output to
PDF. Through plot_options the device's output is already PDF, so this only orders the checks
safely; the system printer test covers a printer asked for with `output: "svg"` and an offset.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-24 07:39:58 -06:00
Aldo ZarateandClaude Opus 5.5 cf34c26c4f Merge upstream/main into pr/plot-cups
Main now writes PDFs with craft-pdf's krilla writer (#2029). Portrait media moves there: a
landscape sheet goes on a portrait page through the page transform (the same quarter turn,
`0 1 -1 0 h 0 cm`), with no link annotations on a turned page. The PDF test reads the file back
with the shared PDF reader instead of looking for the old writer's text.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-24 07:16:39 -06:00
Claude d8d0b5b253 Plot dialog: no device takes the no-device margins
Choosing None after a device kept that device's printable area, and Apply to Layout saved those margins into the layout's page setup. Switching to no device now restores the default margins and, for a standard paper, its size (CodeRabbit review).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01VnaJBEsWwx1aCoDEMofbXs
2026-10-24 01:56:40 +00:00
cyfung1031andClaude Haiku 5.5 b95fb287a6 Plot dialog: paper symbol with dimensions, offset and scale share a bottom edge, Plot area keeps its height
- Sheet: a paper symbol (folded corner, shadow, printable area) with width and height dimensioned on its bottom and right edges, instead of a separate size label.
- Plot offset and Plot scale sit side by side and stretch to the bottom of Drawing orientation. The right column's bottom is read from the previous pass, so the first frame can differ by one repaint.
- Plot area keeps the same rows for every option. Corner fields show only for Window; other options show a note in that space, so no values that would not be plotted appear.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-10-24 00:16:14 +00:00
cyfung1031andClaude Haiku 5.5 7e4edfe24c ui: match the Plot dialog's familiar control layout
The sectioned layout keeps main's model-space centre and X/Y offsets (#751) and plot transparency (#764):

- page_rows takes the placement argument; the Plot offset section passes st.center and st.offset_mm, so the centre checkbox and offset fields are live.
- The Plot options transparency checkbox is main's working checkbox.
- Apply to Layout saves plotTransparency, as on main.

Co-Authored-By: Claude Haiku 5.5 <[email protected]>
2026-10-24 00:16:14 +00:00
cyfung1031 d9a5606389 test: preserve Plot behavior across the dialog layout 2026-10-24 00:01:44 +00:00
Aldo ZarateandClaude Opus 5.5 806bca13e1 Plot: wait for a printer listing once per device lookup
With a listing still under way after PRINTERS_WAIT, an unknown device name waited three times
(the lookup, the system-printer fallback, and the device list in the error): about 30 s. The
lookup now waits once and then uses the printers as listed, and the unknown-device error lists
the devices without waiting.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 14:37:48 -06:00
Aldo ZarateandClaude Opus 5.5 611643be31 Plot: wait for the printer listing before resolving a named device
The first PLOT after the app starts could run while the system printers were still being listed:
a layout set to a printer then plotted to a file, and a user plotter with the printer's name won
over the printer. A command resolving a device by name (given, or from the layout's page setup)
now waits for a listing under way (up to PRINTERS_WAIT) unless the name is a built-in device,
then looks it up with the printers first. Dialogs drawing the device list still never wait.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 14:21:50 -06:00
Aldo ZarateandClaude Opus 5.5 ea546718c2 Plot: a passed printer never prints; system printers are read-only
plot_options kept a `printer` key passed with the call, so `exportpdf {"printer": …}` (from MCP or
a script) sent a print job instead of writing the PDF. Caller-supplied `printer` and
`printerPaper` are dropped; only choosing a system printer as the device prints.

PLOTTERMANAGER could "edit" or "delete" a system printer by writing or deleting a user file of
the same name, which then stayed hidden behind the printer. set, delete and the typed Paper step
now refuse a system printer (a copy made with action new can be edited), and list, get and the
typed list say which devices are system printers.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-23 11:55:54 -06:00
Aldo Zarate f205fe06df Merge remote-tracking branch 'upstream/main' into pr/plot-cups 2026-10-23 11:35:17 -06:00
Aldo ZarateandClaude Opus 5.5 1c3d8a51f8 Plot: list system printers in the background
Listing CUPS printers (lpstat -e and the PPD files) ran on the calling
thread from devices() and find_device(), so the Plot and Page Setup
dialogs, which ask every frame, could freeze while CUPS was slow, or
hang if it didn't answer. Now:

- the listing runs on a background thread; devices() and find_device()
  return the last list at once and start a new listing when it is
  missing or older than 5 s;
- while one runs the dialogs read the list again shortly, so printers
  appear as soon as it ends;
- commands that name a printer (PLOT, PAGESETUP with `device`) or report
  the devices (PLOTTERMANAGER list, PAGESETUP's listing) wait for a
  listing under way, up to 10 s;
- lpstat itself is stopped after 5 s.

A new test lists printers through a 1.5 s hook: 100 device-list calls
take no time, and a plot naming the printer still prints.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 05:57:06 -06:00
Aldo ZarateandClaude Opus 5.5 9ca6ef5010 Merge upstream/main into pr/plot-cups
Takes main's fix of the context menu test (4a9dd31), the same one this
branch carried.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 04:28:01 -06:00
Aldo ZarateandClaude Opus 5.5 ce3291b4a6 Merge upstream/main into pr/plot-cups
Keeps both sides: PDF options have portrait_media and main's
plot_transparency, and a turned landscape page wraps main's new content
stream (marks + alphas); PLOT's parameter help lists device/copies with
main's plotTransparency.

Also fixes a test main fails on its own: since #824 and #818 both landed,
a selected block reference offers "Block Editor" and "Edit Reference
In-Place", and context_menus expected only the first.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 04:22:35 -06:00
Aldo ZarateandClaude Opus 5.5 fd473225d5 Merge upstream/main into pr/plot-cups
Keeps both startup registrations in the desktop app: CUPS system
printers and main's AutoLISP entity codec.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 03:48:23 -06:00
Aldo ZarateandClaude Opus 5.5 a5009b5fc1 Merge upstream/main into pr/plot-cups
Keeps both sides: the Plot dialog's state has the system-printer copies
and main's model-space center/offset; PLOT's parameter help lists both.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-13 03:07:51 -06:00
Aldo ZarateandClaude Opus 5.5 16dd36eadc Print landscape plots turned on portrait media
Printers feed portrait sheets and macOS doesn't turn a landscape PDF page
by itself, so a landscape plot printed sideways. PDF option `portraitMedia`
draws each landscape sheet a quarter turn on a page of the paper's portrait
size (no link annotations on turned pages); PLOT sets it for system
printers. Saved PDFs are unchanged. Checked on a real printer: a 200 x 100 mm
rectangle at 1:1 on Letter landscape measures 200 x 100 mm.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 06:04:06 -06:00
Aldo ZarateandClaude Opus 5.5 c7965ebf52 Plot to system printers on macOS and Linux through CUPS (#670 step 2)
The CUPS destinations (`lpstat -e`) are devices next to the built-in ones,
each with the papers and printable areas of its PPD (PageSize,
PaperDimension, ImageableArea, DefaultPageSize). PLOT to one renders the
PDF the PDF plotter writes for that paper and sends it to `lp` with the
paper's PageSize, the copies, and no scaling (the plot's scale is already
applied); the reply is the job id. EXPORTPDF to a printer still writes the
PDF.

- doc: PlotterConfig.system (never read from or written to files).
- engine: SystemPrinters host hook (list, print), listed after the built-in
  devices and cached for a few seconds; plot_options adds `printer` and the
  paper for PLOT; run_plot prints when `printer` is given (`copies` 1..999).
- io: cups.rs with the PPD / lpstat / lp parsers (tested on text) and, on
  Unix, the commands.
- app: installs CUPS printers on Unix.
- ui: the Plot dialog prints straight to a printer (no file dialog) with a
  Number of copies field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-12 06:04:06 -06:00
125 changed files with 7189 additions and 7705 deletions
+42
View File
@@ -0,0 +1,42 @@
"""Render source and captured drawing pages and check media, sheet order and placement."""
import re
import subprocess
from pathlib import Path
from tempfile import TemporaryDirectory
from PIL import Image
def bars(pdf, expected_size):
info = subprocess.check_output(["pdfinfo", "-f", "1", "-l", "3", pdf], text=True)
assert re.search(r"^Pages:\s+3\s*$", info, re.MULTILINE), info
dims = re.findall(r"^Page\s+\d+ size:\s+([\d.]+) x ([\d.]+) pts", info, re.MULTILINE)
assert len(dims) == 3, info
for w, h in dims:
assert abs(float(w) - expected_size[0]) < 1 and abs(float(h) - expected_size[1]) < 1, (pdf, w, h)
with TemporaryDirectory() as tmp:
prefix = Path(tmp) / "sheet"
subprocess.run(["pdftoppm", "-r", "72", "-gray", "-png", pdf, prefix], check=True)
measured = []
for number in [1, 2, 3]:
with Image.open(prefix.with_name(f"sheet-{number}.png")) as image:
gray = image.convert("L")
y = gray.height // 2
ink = [x for x in range(10, gray.width - 10) if gray.getpixel((x, y)) < 165]
groups = []
for x in ink:
if groups and x <= groups[-1][-1] + 2:
groups[-1].append(x)
else:
groups.append([x])
centres = [(g[0]+g[-1])/2 for g in groups if len(g) >= 3]
assert len(centres) == number, (pdf, number, centres)
measured.extend(centres)
return measured
for media, size in [("Letter", (612, 792)), ("A4", (595.28, 841.89))]:
source = bars(Path(f"plot-evidence/{media}-source.pdf"), size)
printed = bars(Path(f"plot-evidence/{media}-printed.pdf"), size)
assert all(abs(a - b) <= 2 for a, b in zip(source, printed, strict=True)), (source, printed)
print(f"{media}: three distinct sheets, correct size and ordered markers at {printed}")
@@ -0,0 +1,60 @@
function Remove-CaptureLocalPort {
param([Parameter(Mandatory)][string]$Name)
if ($Name -notmatch '^[A-Za-z]:\\') {
throw 'A capture port must have an absolute local file path as its name.'
}
# Remove-PrinterPort interprets backslashes as part of a printer/server name.
# Pass the full path as data to the local monitor instead.
if (-not ('CraftCaptureLocalPort' -as [type])) {
Add-Type -TypeDefinition @'
using System;
using System.ComponentModel;
using System.Runtime.InteropServices;
using System.Text;
public static class CraftCaptureLocalPort
{
[StructLayout(LayoutKind.Sequential)]
private struct PrinterDefaults
{
public IntPtr DataType;
public IntPtr DevMode;
public uint DesiredAccess;
}
[DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool OpenPrinter(string name, out IntPtr printer, ref PrinterDefaults defaults);
[DllImport("winspool.drv", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern bool XcvData(IntPtr printer, string command, byte[] input, uint inputBytes,
IntPtr output, uint outputBytes, out uint bytesNeeded, out uint status);
[DllImport("winspool.drv")]
private static extern bool ClosePrinter(IntPtr printer);
public static void Remove(string name)
{
const uint ServerAccessAdminister = 1;
var defaults = new PrinterDefaults { DesiredAccess = ServerAccessAdminister };
if (!OpenPrinter(",XcvMonitor Local Port", out var printer, ref defaults))
throw new Win32Exception(Marshal.GetLastWin32Error());
try
{
byte[] input = Encoding.Unicode.GetBytes(name + "\0");
if (!XcvData(printer, "DeletePort", input, (uint)input.Length, IntPtr.Zero, 0, out _, out uint status))
throw new Win32Exception(Marshal.GetLastWin32Error());
if (status != 0)
throw new Win32Exception((int)status);
}
finally
{
ClosePrinter(printer);
}
}
}
'@
}
[CraftCaptureLocalPort]::Remove($Name)
}
+97
View File
@@ -0,0 +1,97 @@
name: Verify CadCraft plotted output on Windows
on:
push:
branches: [verify/cadcraft-plot-output-4859]
permissions:
contents: read
jobs:
catalog:
runs-on: windows-2025
timeout-minutes: 100
env:
CARGO_PROFILE_DEV_DEBUG: '0'
CARGO_PROFILE_TEST_DEBUG: '0'
CARGO_INCREMENTAL: '0'
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
- uses: storytold/craft-common-actions/actions/checkout-craft-fonts@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
ref: b076417b5880bd4154bd22f00695b1d28c6bea83
- name: Choose build volume and resolve the combined app
shell: pwsh
run: |
$disk = Get-PSDrive -PSProvider FileSystem | Where-Object { $_.Free -gt 0 -and $_.Root -match '^[A-Za-z]:\\$' } | Sort-Object -Descending Free | Select-Object -First 1
$dir = Join-Path $disk.Root "cad-print-$env:GITHUB_RUN_ID"
"CARGO_TARGET_DIR=$dir" >> $env:GITHUB_ENV
$env:CARGO_TARGET_DIR = $dir
cargo metadata --format-version 1 > "$env:RUNNER_TEMP/cad-graph.json"
- name: Run media mapping and conservative margins tests
if: "!contains(github.event.head_commit.message, '[plot-output-only]')"
shell: bash
run: |
set -eo pipefail
cargo test --locked -p cadcraft-io --lib winprint:: | tee cad-results.txt
grep -E 'driver_papers_become_a_device.*ok' cad-results.txt
grep -E 'a_borderless_variant_shares_one_entry_with_printable_margins.*ok' cad-results.txt
- name: Capture the app's plots on two paper sizes
shell: pwsh
run: |
$ErrorActionPreference = 'Stop'
. ./.github/print-probe/windows-local-port.ps1
Start-Service Spooler
$driver = 'Microsoft Print To PDF'
$out = New-Item -ItemType Directory -Path plot-evidence
$env:CADCRAFT_PLOT_OUTPUT = $out.FullName
$port = Join-Path $out.FullName 'incoming.pdf'
$queue = "CadCraft file plot $env:GITHUB_RUN_ID-$env:GITHUB_RUN_ATTEMPT"
Add-PrinterPort -Name $port
try {
Add-Printer -Name $queue -DriverName $driver -PortName $port
try {
Set-PrintConfiguration -PrinterName $queue -PaperSize Letter
$env:CADCRAFT_TEST_QUEUE = $queue
foreach ($media in 'Letter','A4') {
if (Test-Path -LiteralPath $port) { throw 'Output from previous plot is still present' }
$env:CADCRAFT_PLOT_MEDIA = $media
cargo test --locked -p cadcraft-io --test hosted_plot -- --nocapture
if ($LASTEXITCODE) { throw "Plotting $media failed" }
$deadline = [DateTime]::UtcNow.AddSeconds(50)
$complete = $false
while ([DateTime]::UtcNow -lt $deadline) {
try {
$bytes = [IO.File]::ReadAllBytes($port)
$n = [Math]::Min(40, $bytes.Length)
if ($n -gt 0 -and [Text.Encoding]::ASCII.GetString($bytes, $bytes.Length - $n, $n).TrimEnd().EndsWith('%%EOF')) {
Move-Item -LiteralPath $port -Destination (Join-Path $out.FullName "$media-printed.pdf")
$complete = $true
break
}
} catch [IO.IOException] {}
Start-Sleep -Milliseconds 250
}
if (!$complete) { throw "No complete $media spool output" }
}
} finally { Remove-Printer -Name $queue }
} finally { Remove-CaptureLocalPort -Name $port }
- uses: actions/upload-artifact@cf430e030ddbb5b0abf93d22962f4752f3646cd9
if: always()
with:
name: cadcraft-source-and-printed-plots
path: plot-evidence/*.pdf
if-no-files-found: warn
retention-days: 14
inspect:
needs: catalog
runs-on: ubuntu-24.04
timeout-minutes: 10
steps:
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1
- uses: actions/download-artifact@634f93cb2916e3fdff6788551b99b062d0335ce0
with:
name: cadcraft-source-and-printed-plots
path: plot-evidence
- uses: storytold/craft-common-actions/actions/install-apt-packages@58848078cd09e3ca182891a8b76ee979f1eb6e1c
with:
packages: poppler-utils python3-pil
- name: Render both jobs and compare their sheet order and scale
run: /usr/bin/python3 .github/print-probe/inspect-plots.py
-6
View File
@@ -22,17 +22,11 @@ Generated-in-code assets are original and have no file to list:
- the sample drawings (`crates/engine/src/sample.rs`);
- the synthetic two-hexagon hatch logo (`crates/io/tests/it/hatch_loop_flags.rs`, `logo`):
original contributor geometry, generated in code from invented points, under MIT OR Apache-2.0.
- the self-contained line drawings/DXF bytes generated by provider regressions in
`crates/ui-egui/src/file_provider_app/tests.rs` and
`apps/cadcraft-web/src/file_providers/browser_tests.rs` (CADCraft contributors, original test
code/data, MIT OR Apache-2.0; no vendor drawing, external image, font or other asset is added).
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.6](https://crates.io/crates/acadrust/0.6.6), [hakanaktt/acadrust](https://github.com/hakanaktt/acadrust), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.6 third-party notices](https://github.com/hakanaktt/acadrust/blob/v0.6.6/THIRD_PARTY_NOTICES.md), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. |
| `krilla 0.8.2 / icc/sGrey-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v4.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d`. |
Generated
+970 -98
View File
File diff suppressed because it is too large Load Diff
+3 -1
View File
@@ -45,6 +45,9 @@ craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
# Printing a plot's PDF on a Windows printer (the spooler's list and the job), from
# craft-libs (pinned at its own revision; craft-print does not depend on craft-pdf).
craft-print = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "9e4d53d6b093591a3b24ad950592caf81c702e5a" }
# foundation
thiserror = "2"
@@ -85,7 +88,6 @@ egui = { version = "0.37", default-features = false, features = ["default_fonts"
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
egui_kittest = "0.37"
wasm-bindgen-test = "0.3.79"
eframe = { version = "0.37", default-features = false }
egui-wgpu = "0.37"
# Monotonic time on native and web (performance.now on wasm).
+2 -428
View File
@@ -10,435 +10,9 @@ docs/brand/LICENSE-brand.txt.
Third-party material
Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) 0.6.6 is licensed under the
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) is licensed under the
Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source
is available from crates.io and the repository above. The licence text and upstream third-party
notices are retained in licenses/dwg/, copied verbatim from craft-libs at
8fa4db64a9bb943520259ea95331a303ba788f21, the revision this repository pins.
acadrust's DWG reader and writer include code ported and adapted from ACadSharp
(https://github.com/DomCR/ACadSharp), Copyright (c) 2021 Albert Domenech, under the MIT License.
The Mozilla Public License 2.0 text and the upstream third-party notices follow.
The following text is reproduced verbatim from licenses/dwg/acadrust-MPL-2.0.txt:
Mozilla Public License Version 2.0
==================================
1. Definitions
--------------
1.1. "Contributor"
means each individual or legal entity that creates, contributes to
the creation of, or owns Covered Software.
1.2. "Contributor Version"
means the combination of the Contributions of others (if any) used
by a Contributor and that particular Contributor's Contribution.
1.3. "Contribution"
means Covered Software of a particular Contributor.
1.4. "Covered Software"
means Source Code Form to which the initial Contributor has attached
the notice in Exhibit A, the Executable Form of such Source Code
Form, and Modifications of such Source Code Form, in each case
including portions thereof.
1.5. "Incompatible With Secondary Licenses"
means
(a) that the initial Contributor has attached the notice described
in Exhibit B to the Covered Software; or
(b) that the Covered Software was made available under the terms of
version 1.1 or earlier of the License, but not also under the
terms of a Secondary License.
1.6. "Executable Form"
means any form of the work other than Source Code Form.
1.7. "Larger Work"
means a work that combines Covered Software with other material, in
a separate file or files, that is not Covered Software.
1.8. "License"
means this document.
1.9. "Licensable"
means having the right to grant, to the maximum extent possible,
whether at the time of the initial grant or subsequently, any and
all of the rights conveyed by this License.
1.10. "Modifications"
means any of the following:
(a) any file in Source Code Form that results from an addition to,
deletion from, or modification of the contents of Covered
Software; or
(b) any new file in Source Code Form that contains any Covered
Software.
1.11. "Patent Claims" of a Contributor
means any patent claim(s), including without limitation, method,
process, and apparatus claims, in any patent Licensable by such
Contributor that would be infringed, but for the grant of the
License, by the making, using, selling, offering for sale, having
made, import, or transfer of either its Contributions or its
Contributor Version.
1.12. "Secondary License"
means either the GNU General Public License, Version 2.0, the GNU
Lesser General Public License, Version 2.1, the GNU Affero General
Public License, Version 3.0, or any later versions of those
licenses.
1.13. "Source Code Form"
means the form of the work preferred for making modifications.
1.14. "You" (or "Your")
means an individual or a legal entity exercising rights under this
License. For legal entities, "You" includes any entity that
controls, is controlled by, or is under common control with You. For
purposes of this definition, "control" means (a) the power, direct
or indirect, to cause the direction or management of such entity,
whether by contract or otherwise, or (b) ownership of more than
fifty percent (50%) of the outstanding shares or beneficial
ownership of such entity.
2. License Grants and Conditions
--------------------------------
2.1. Grants
Each Contributor hereby grants You a world-wide, royalty-free,
non-exclusive license:
(a) under intellectual property rights (other than patent or trademark)
Licensable by such Contributor to use, reproduce, make available,
modify, display, perform, distribute, and otherwise exploit its
Contributions, either on an unmodified basis, with Modifications, or
as part of a Larger Work; and
(b) under Patent Claims of such Contributor to make, use, sell, offer
for sale, have made, import, and otherwise transfer either its
Contributions or its Contributor Version.
2.2. Effective Date
The licenses granted in Section 2.1 with respect to any Contribution
become effective for each Contribution on the date the Contributor first
distributes such Contribution.
2.3. Limitations on Grant Scope
The licenses granted in this Section 2 are the only rights granted under
this License. No additional rights or licenses will be implied from the
distribution or licensing of Covered Software under this License.
Notwithstanding Section 2.1(b) above, no patent license is granted by a
Contributor:
(a) for any code that a Contributor has removed from Covered Software;
or
(b) for infringements caused by: (i) Your and any other third party's
modifications of Covered Software, or (ii) the combination of its
Contributions with other software (except as part of its Contributor
Version); or
(c) under Patent Claims infringed by Covered Software in the absence of
its Contributions.
This License does not grant any rights in the trademarks, service marks,
or logos of any Contributor (except as may be necessary to comply with
the notice requirements in Section 3.4).
2.4. Subsequent Licenses
No Contributor makes additional grants as a result of Your choice to
distribute the Covered Software under a subsequent version of this
License (see Section 10.2) or under the terms of a Secondary License (if
permitted under the terms of Section 3.3).
2.5. Representation
Each Contributor represents that the Contributor believes its
Contributions are its original creation(s) or it has sufficient rights
to grant the rights to its Contributions conveyed by this License.
2.6. Fair Use
This License is not intended to limit any rights You have under
applicable copyright doctrines of fair use, fair dealing, or other
equivalents.
2.7. Conditions
Sections 3.1, 3.2, 3.3, and 3.4 are conditions of the licenses granted
in Section 2.1.
3. Responsibilities
-------------------
3.1. Distribution of Source Form
All distribution of Covered Software in Source Code Form, including any
Modifications that You create or to which You contribute, must be under
the terms of this License. You must inform recipients that the Source
Code Form of the Covered Software is governed by the terms of this
License, and how they can obtain a copy of this License. You may not
attempt to alter or restrict the recipients' rights in the Source Code
Form.
3.2. Distribution of Executable Form
If You distribute Covered Software in Executable Form then:
(a) such Covered Software must also be made available in Source Code
Form, as described in Section 3.1, and You must inform recipients of
the Executable Form how they can obtain a copy of such Source Code
Form by reasonable means in a timely manner, at a charge no more
than the cost of distribution to the recipient; and
(b) You may distribute such Executable Form under the terms of this
License, or sublicense it under different terms, provided that the
license for the Executable Form does not attempt to limit or alter
the recipients' rights in the Source Code Form under this License.
3.3. Distribution of a Larger Work
You may create and distribute a Larger Work under terms of Your choice,
provided that You also comply with the requirements of this License for
the Covered Software. If the Larger Work is a combination of Covered
Software with a work governed by one or more Secondary Licenses, and the
Covered Software is not Incompatible With Secondary Licenses, this
License permits You to additionally distribute such Covered Software
under the terms of such Secondary License(s), so that the recipient of
the Larger Work may, at their option, further distribute the Covered
Software under the terms of either this License or such Secondary
License(s).
3.4. Notices
You may not remove or alter the substance of any license notices
(including copyright notices, patent notices, disclaimers of warranty,
or limitations of liability) contained within the Source Code Form of
the Covered Software, except that You may alter any license notices to
the extent required to remedy known factual inaccuracies.
3.5. Application of Additional Terms
You may choose to offer, and to charge a fee for, warranty, support,
indemnity or liability obligations to one or more recipients of Covered
Software. However, You may do so only on Your own behalf, and not on
behalf of any Contributor. You must make it absolutely clear that any
such warranty, support, indemnity, or liability obligation is offered by
You alone, and You hereby agree to indemnify every Contributor for any
liability incurred by such Contributor as a result of warranty, support,
indemnity or liability terms You offer. You may include additional
disclaimers of warranty and limitations of liability specific to any
jurisdiction.
4. Inability to Comply Due to Statute or Regulation
---------------------------------------------------
If it is impossible for You to comply with any of the terms of this
License with respect to some or all of the Covered Software due to
statute, judicial order, or regulation then You must: (a) comply with
the terms of this License to the maximum extent possible; and (b)
describe the limitations and the code they affect. Such description must
be placed in a text file included with all distributions of the Covered
Software under the name "LEGAL", and included in all Covered Software
distributed in Source Code Form. Except to the extent prohibited by
statute or regulation, such description must be sufficiently detailed
for a recipient of ordinary skill to be able to understand it.
5. Termination
--------------
5.1. The rights granted under this License will terminate automatically
if You fail to comply with any of its terms. However, if You become
compliant, then the rights granted under this License from a particular
Contributor are reinstated (a) provisionally, unless and until such
Contributor explicitly and finally terminates Your grants, and (b) on an
ongoing basis, if such Contributor fails to notify You of the
non-compliance by some reasonable means prior to 60 days after You have
come back into compliance. Moreover, Your grants from a particular
Contributor are reinstated on an ongoing basis if such Contributor
notifies You of the non-compliance by some reasonable means, this is the
first time You have received notice of non-compliance with this License
from such Contributor, and You become compliant prior to 30 days after
Your receipt of the notice.
5.2. If You initiate litigation against any entity by asserting a patent
infringement claim (excluding declaratory judgment actions,
counter-claims, and cross-claims) alleging that a Contributor Version
directly or indirectly infringes any patent, then the rights granted to
You by any and all Contributors for the Covered Software under Section
2.1 of this License shall terminate.
5.3. In the event of termination under Sections 5.1 or 5.2 above, all
end user license agreements (excluding distributors and resellers) which
have been validly granted by You or Your distributors under this License
prior to termination shall survive termination.
************************************************************************
* *
* 6. Disclaimer of Warranty *
* ------------------------- *
* *
* Covered Software is provided under this License on an "as is" *
* basis, without warranty of any kind, either expressed, implied, or *
* statutory, including, without limitation, warranties that the *
* Covered Software is free of defects, merchantable, fit for a *
* particular purpose or non-infringing. The entire risk as to the *
* quality and performance of the Covered Software is with You. *
* Should any Covered Software prove defective in any respect, You *
* (not any Contributor) assume the cost of any necessary servicing, *
* repair, or correction. This disclaimer of warranty constitutes an *
* essential part of this License. No use of any Covered Software is *
* authorized under this License except under this disclaimer. *
* *
************************************************************************
************************************************************************
* *
* 7. Limitation of Liability *
* -------------------------- *
* *
* Under no circumstances and under no legal theory, whether tort *
* (including negligence), contract, or otherwise, shall any *
* Contributor, or anyone who distributes Covered Software as *
* permitted above, be liable to You for any direct, indirect, *
* special, incidental, or consequential damages of any character *
* including, without limitation, damages for lost profits, loss of *
* goodwill, work stoppage, computer failure or malfunction, or any *
* and all other commercial damages or losses, even if such party *
* shall have been informed of the possibility of such damages. This *
* limitation of liability shall not apply to liability for death or *
* personal injury resulting from such party's negligence to the *
* extent applicable law prohibits such limitation. Some *
* jurisdictions do not allow the exclusion or limitation of *
* incidental or consequential damages, so this exclusion and *
* limitation may not apply to You. *
* *
************************************************************************
8. Litigation
-------------
Any litigation relating to this License may be brought only in the
courts of a jurisdiction where the defendant maintains its principal
place of business and such litigation shall be governed by laws of that
jurisdiction, without reference to its conflict-of-law provisions.
Nothing in this Section shall prevent a party's ability to bring
cross-claims or counter-claims.
9. Miscellaneous
----------------
This License represents the complete agreement concerning the subject
matter hereof. If any provision of this License is held to be
unenforceable, such provision shall be reformed only to the extent
necessary to make it enforceable. Any law or regulation which provides
that the language of a contract shall be construed against the drafter
shall not be used to construe this License against a Contributor.
10. Versions of the License
---------------------------
10.1. New Versions
Mozilla Foundation is the license steward. Except as provided in Section
10.3, no one other than the license steward has the right to modify or
publish new versions of this License. Each version will be given a
distinguishing version number.
10.2. Effect of New Versions
You may distribute the Covered Software under the terms of the version
of the License under which You originally received the Covered Software,
or under the terms of any subsequent version published by the license
steward.
10.3. Modified Versions
If you create software not governed by this License, and you want to
create a new license for such software, you may create and use a
modified version of this License if you rename the license and remove
any references to the name of the license steward (except to note that
such modified license differs from this License).
10.4. Distributing Source Code Form that is Incompatible With Secondary
Licenses
If You choose to distribute Source Code Form that is Incompatible With
Secondary Licenses under the terms of this version of the License, the
notice described in Exhibit B of this License must be attached.
Exhibit A - Source Code Form License Notice
-------------------------------------------
This Source Code Form is subject to the terms of the Mozilla Public
License, v. 2.0. If a copy of the MPL was not distributed with this
file, You can obtain one at https://mozilla.org/MPL/2.0/.
If it is not possible or desirable to put the notice in a particular
file, then You may include the notice in a location (such as a LICENSE
file in a relevant directory) where a recipient would be likely to look
for such a notice.
You may add additional accurate notices of copyright ownership.
Exhibit B - "Incompatible With Secondary Licenses" Notice
---------------------------------------------------------
This Source Code Form is "Incompatible With Secondary Licenses", as
defined by the Mozilla Public License, v. 2.0.
The following text is reproduced verbatim from licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md:
# Third-Party Notices
## ACadSharp
The DWG reader and writer include code ported and adapted from ACadSharp. The repository
history's initial DWG support commit identifies the source classes explicitly, including
`DwgStreamReaderBase`, `DwgLZ77AC21Decompressor`, `DwgFileHeaderWriterAC18`, and
`DwgObjectWriter`. Their current Rust implementations are in `src/io/dwg`.
Copyright (c) 2021 Albert Domenech
MIT License
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
## DWG Format References
DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG
specification and reverse engineering, including comparison with drawings produced by CAD
applications. LibreDWG is used as a secondary cross-check for selected field names and
layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's
`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not
translated routines. The repository history and source review found no LibreDWG routines
ported into the implementation. The source comments identify the specific cross-checks.
is available from crates.io and the repository above.
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
+11 -2
View File
@@ -56,13 +56,22 @@ fn install_io() {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
// System printers, as in the app: CUPS on macOS and Linux, the spooler on Windows.
#[cfg(unix)]
cadcraft_engine::cmd::plotters::set_system_printers(cadcraft_engine::cmd::plotters::SystemPrinters {
list: cadcraft_io::cups::printers,
print: |j| cadcraft_io::cups::print(j.printer, j.paper_key, j.size_mm, j.copies, j.title, j.pdf),
});
#[cfg(windows)]
cadcraft_engine::cmd::plotters::set_system_printers(cadcraft_engine::cmd::plotters::SystemPrinters {
list: cadcraft_io::winprint::printers,
print: |j| cadcraft_io::winprint::print(j.printer, j.paper, j.copies, j.title, j.pdf),
});
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
entity: cadcraft_io::entity_from_groups,
});
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
@@ -1,406 +0,0 @@
//! An INSERT's ATTRIBs and SEQEND reached from AutoLISP through the CLI (`entnext`, `entget`,
//! `entmod`, `entdel`): the walk, a value edit (one Undo step), names that stop holding (erase,
//! ATTSYNC, Undo, a reinsert that reuses the parent handle), edits that are refused, and the
//! name bounds.
use std::path::{Path, PathBuf};
use std::process::{Command, Output};
use serde_json::{Value, json};
/// A scratch directory, removed on drop also when an assertion fails.
struct Dir(PathBuf);
impl Dir {
fn new(tag: &str) -> Dir {
let p = std::env::temp_dir().join(format!("cc-cli-attribs-{tag}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&p);
std::fs::create_dir_all(&p).expect("create scratch dir");
Dir(p)
}
fn path(&self, name: &str) -> PathBuf {
self.0.join(name)
}
}
impl Drop for Dir {
fn drop(&mut self) {
let _ = std::fs::remove_dir_all(&self.0);
}
}
/// One `cadcraft-cli run`: a fresh profile, an optional drawing to open, and the steps to run.
struct Run {
args: Vec<String>,
}
impl Run {
fn new(dir: &Dir, file: Option<&Path>) -> Run {
let mut args: Vec<String> = vec!["run".into(), "--config-dir".into(), dir.path("profile").to_string_lossy().into_owned()];
match file {
Some(f) => args.push(f.to_string_lossy().into_owned()),
None => args.push("--metric".into()),
}
Run { args }
}
fn cmd(&mut self, id: &str, params: Value) -> &mut Run {
self.args.push("--cmd".into());
self.args.push(format!("{id} {params}"));
self
}
fn lisp(&mut self, code: &str) -> &mut Run {
self.cmd("lisp", json!({ "code": code }))
}
fn save(&mut self, path: &Path) -> &mut Run {
self.args.push("--save".into());
self.args.push(path.to_string_lossy().into_owned());
self
}
fn output(&self) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&self.args).output().expect("run cadcraft-cli")
}
/// Run it: the value each `lisp` step returned, in order (commands' own results are left out).
fn out(&self) -> Vec<Value> {
let out = self.output();
let err = String::from_utf8_lossy(&out.stderr);
assert!(out.status.success(), "{}: {}", self.args.join(" "), err);
let text = String::from_utf8_lossy(&out.stdout);
text.lines()
.map(|l| serde_json::from_str::<Value>(l).unwrap_or_else(|e| panic!("not a result: {l}: {e}")))
.filter(|v| v.get("value").is_some())
.collect()
}
}
/// The value a `lisp` step returned, as AutoLISP's `prin1` shows it.
fn value(results: &[Value], i: usize) -> String {
match results.get(i).and_then(|r| r.get("value")) {
Some(Value::String(s)) => s.clone(),
other => panic!("step {i}: no value: {other:?} in {results:?}"),
}
}
/// `value` without the quotes `prin1` puts round a string.
fn text(results: &[Value], i: usize) -> String {
value(results, i).trim_matches('"').to_string()
}
/// TAGBLK.dxf: block TAGBLK with a circle and four attribute definitions (TAG1 D1, TAG2 D2
/// verify, TAG3 P3 preset, TAG4 C4 constant). Opening the file again gives the drawing fresh
/// names.
const FIXTURE: &str = r#"(progn
(entmake '((0 . "BLOCK") (2 . "TAGBLK") (70 . 2) (10 0.0 0.0 0.0)))
(entmake '((0 . "CIRCLE") (10 -5.0 0.0 0.0) (40 . 2.0)))
(entmake '((0 . "ATTDEF") (10 0.0 0.0 0.0) (40 . 2.5) (1 . "D1") (3 . "P1") (2 . "TAG1") (70 . 0)))
(entmake '((0 . "ATTDEF") (10 0.0 5.0 0.0) (40 . 2.5) (1 . "D2") (3 . "P2") (2 . "TAG2") (70 . 4)))
(entmake '((0 . "ATTDEF") (10 0.0 10.0 0.0) (40 . 2.5) (1 . "P3") (3 . "P3") (2 . "TAG3") (70 . 8)))
(entmake '((0 . "ATTDEF") (10 0.0 15.0 0.0) (40 . 2.5) (1 . "C4") (3 . "P4") (2 . "TAG4") (70 . 2)))
(entmake '((0 . "ENDBLK"))))"#;
/// The first reference: INSERT TAGBLK at (10,10) with TAG1 "A1", TAG2 verified as "B1" and
/// TAG3 preset ("P3"); TAG4 is constant, so it is not asked.
const INSERT: &str = r#"(command "_.-INSERT" "TAGBLK" '(10 10) 1 1 0 "A1" "B1" "")"#;
fn fixture(dir: &Dir) -> PathBuf {
let file = dir.path("TAGBLK.dxf");
let mut run = Run::new(dir, None);
let out = run.lisp(FIXTURE).save(&file).out();
assert_eq!(text(&out, 0), "TAGBLK");
file
}
/// The walk from the entity named `i`: its records' tags and values, then the type of the record
/// that ends the run.
const WALK: &str = r#"(progn
(setq e (entnext i) n 0 ts nil ed nil)
(while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e))))))
(setq ts (append ts (list (cdr (assoc 2 ed)) (cdr (assoc 1 ed)))) n (1+ n) e (entnext e)))
(list n ts (cdr (assoc 0 ed))))"#;
#[test]
fn the_walk_reaches_each_attrib_and_ends_at_the_seqend() {
let dir = Dir::new("walk");
let file = fixture(&dir);
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(
r#"(progn
{INSERT}
(setq i (entlast))
(setvar "ATTREQ" 0)
(command "_.-INSERT" "TAGBLK" '(60 10) 1 1 0)
(setvar "ATTREQ" 1)
(setq second (entlast))
"inserted")"#
))
// Three attributes, then the SEQEND owned by the reference, then the next main entity.
.lisp(&format!(
r#"(progn {WALK}
(list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (equal (entnext e) second) (cdr (assoc 0 (entget (entnext e))))))"#
))
// The second reference (no attribute answers, ATTREQ 0) took the definitions' values; its
// own run ends at its SEQEND, with nothing drawn after it.
.lisp(&format!(
r#"(progn (setq i second) {WALK}
(list n ts (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i) (entnext e)))"#
))
.out();
assert_eq!(text(&out, 0), "inserted");
assert_eq!(value(&out, 1), "(3 (\"TAG1\" \"A1\" \"TAG2\" \"B1\" \"TAG3\" \"P3\") \"SEQEND\" T T \"INSERT\")");
// Its record ends with its own SEQEND, and nothing is drawn after the reference.
assert_eq!(value(&out, 2), "(3 (\"TAG1\" \"D1\" \"TAG2\" \"D2\" \"TAG3\" \"P3\") \"SEQEND\" T nil)");
}
#[test]
fn a_value_edit_changes_group_one_only_and_is_one_undo_step() {
let dir = Dir::new("value");
let file = fixture(&dir);
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 2 (entget a))) (cdr (assoc 1 (entget a)))))"#))
.lisp(
r#"(progn
(setq d (entget a) r (entmod (subst (cons 1 "A2") (assoc 1 d) d)))
(list (cdr (assoc 0 r)) (cdr (assoc 1 r)) (cdr (assoc 1 (entget a))) (cdr (assoc 2 (entget a)))
(cdr (assoc 40 (entget a))) (cdr (assoc 8 (entget a))) (equal (cdr (assoc -2 (entget a))) i)))"#,
)
.cmd("undo", json!({ "count": 1 }))
// The edit is one Undo step: the value is back, and the name given before it holds no
// longer (the drawing it was given in was restored from another state).
.lisp(
r#"(list (entget a) (progn (setq e (entnext (entlast)))
(list (cdr (assoc 2 (entget e))) (cdr (assoc 1 (entget e))))))"#,
)
.out();
assert_eq!(value(&out, 0), "(\"TAG1\" \"A1\")");
assert_eq!(value(&out, 1), "(\"ATTRIB\" \"A2\" \"A2\" \"TAG1\" 2.5 \"0\" T)");
assert_eq!(value(&out, 2), "(nil (\"TAG1\" \"A1\"))");
// Redo brings the edit back; the name given before the Undo still names nothing.
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i) d (entget a)) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#))
.cmd("undo", json!({ "count": 1 }))
.cmd("redo", json!({ "count": 1 }))
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
.out();
assert_eq!(value(&out, 1), "(nil \"A2\")");
}
#[test]
fn a_name_stops_holding_after_erase_attsync_and_undo() {
let dir = Dir::new("stale");
let file = fixture(&dir);
let mut run = Run::new(&dir, Some(&file));
let out = run.lisp(&format!(r#"(progn {INSERT} (setq i (entlast)) (cdr (assoc 5 (entget i))))"#)).out();
let handle = text(&out, 0);
// Erased: the reference's records are gone with it, and the name names nothing.
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (cdr (assoc 2 (entget a))))"#))
.cmd("erase", json!({ "handles": [handle] }))
.lisp("(list (entget a) (entnext a))")
// Undone: the reference is back, but a name given before the Undo does not come back with
// it: a walk gives its records new ones.
.cmd("undo", json!({ "count": 1 }))
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
// ATTSYNC rebuilds the reference's attributes: the name given before names nothing, and
// the rebuilt attribute keeps the value.
.lisp("(progn (setq b (entnext (entlast))) (cdr (assoc 2 (entget b))))")
.cmd("attsync", json!({ "name": "TAGBLK" }))
.lisp("(list (entget b) (cdr (assoc 1 (entget (entnext (entlast))))))")
.out();
assert_eq!(value(&out, 0), "\"TAG1\"");
assert_eq!(value(&out, 1), "(nil nil)");
assert_eq!(value(&out, 2), "(nil \"A1\")");
assert_eq!(value(&out, 3), "\"TAG1\"");
assert_eq!(value(&out, 4), "(nil \"A1\")");
// A reinsert after an Undo takes the parent handle back: the old name must not name its
// attribute.
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(r#"(progn {INSERT} (setq i (entlast) a (entnext i)) (list (cdr (assoc 5 (entget i))) (cdr (assoc 2 (entget a)))))"#))
.cmd("undo", json!({ "count": 1 }))
.lisp(&format!(r#"(progn {INSERT} (list (cdr (assoc 5 (entget (entlast)))) (entget a)))"#))
.lisp("(list (cdr (assoc 2 (entget (entnext (entlast))))) (cdr (assoc 1 (entget (entnext (entlast))))))")
.out();
assert_eq!(text(&out, 0), format!("(\"{handle}\" \"TAG1\")"));
// The same handle, and the old name names nothing in the new reference.
assert_eq!(value(&out, 1), format!("(\"{handle}\" nil)"));
assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\")");
}
#[test]
fn an_edit_of_anything_but_the_value_is_refused() {
let dir = Dir::new("refused");
let file = fixture(&dir);
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(
r#"(progn {INSERT} (setq i (entlast) a (entnext i) s (entnext (entnext (entnext a))) p0 (cdr (assoc 10 (entget a)))) "named")"#
))
.lisp(
r#"(progn
(setq d (entget a))
(list
(entmod (subst (cons 2 "TAGX") (assoc 2 d) d))
(entmod (subst (cons 40 9.0) (assoc 40 d) d))
(entmod (subst (cons 0 "SEQEND") (assoc 0 d) d))
(entmod (entget s))
(entmod (subst (cons 410 "Layout2") (assoc 410 d) d))
(entmod (subst (cons 1 "A2") (assoc 1 d) (subst (cons 410 "Layout2") (assoc 410 d) d)))
(entdel a) (entdel s)))"#,
)
// Nothing changed: the same tag, value, height and place, and the name still holds.
.lisp(
r#"(progn (setq e (entnext (entlast)) d (entget e))
(list (cdr (assoc 2 d)) (cdr (assoc 1 d)) (cdr (assoc 40 d)) (equal p0 (cdr (assoc 10 d))) (equal (entget a) d)))"#,
)
.out();
assert_eq!(text(&out, 0), "named");
assert_eq!(value(&out, 1), "(nil nil nil nil nil nil nil nil)");
assert_eq!(value(&out, 2), "(\"TAG1\" \"A1\" 2.5 T T)");
}
/// A minimal drawing: `before` (records written as they are), then an INSERT with `attribs`
/// ATTRIBs (each tag T, value V) and its SEQEND, last in the file. A header `$HANDSEED` is
/// written when `handseed` is given (a hostile file can name any next handle).
fn insert_dxf_seed(attribs: usize, before: &str, handseed: Option<&str>) -> String {
let mut s = String::with_capacity(before.len().saturating_add(attribs.saturating_mul(96)));
if let Some(seed) = handseed {
s.push_str("0\nSECTION\n2\nHEADER\n9\n$HANDSEED\n5\n");
s.push_str(seed);
s.push('\n');
s.push_str("0\nENDSEC\n");
}
s.push_str("0\nSECTION\n2\nENTITIES\n");
s.push_str(before);
s.push_str("0\nINSERT\n5\n20\n8\n0\n66\n1\n2\nTAGBLK\n10\n0\n20\n0\n30\n0\n");
for _ in 0..attribs {
s.push_str("0\nATTRIB\n5\n21\n8\n0\n10\n0\n20\n0\n30\n0\n40\n1\n1\nV\n2\nT\n70\n0\n");
}
s.push_str("0\nSEQEND\n5\n22\n0\nENDSEC\n0\nEOF\n");
s
}
fn insert_dxf(attribs: usize, before: &str) -> String {
insert_dxf_seed(attribs, before, None)
}
/// The number of records a walk from `i` reaches, counting each `entnext`.
const COUNT: &str = r#"(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)"#;
#[test]
fn a_walk_is_stable_and_its_names_are_no_handles() {
let dir = Dir::new("stable");
// A file's line one below the top of the handle range: it keeps its handle, and the
// records' names, which are no handles, never name it.
let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n";
let file = dir.path("hostile.dxf");
std::fs::write(&file, insert_dxf(2, before)).expect("write the DXF");
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(
r#"(progn
(setq i (handent "20") line (handent "FFFFFFFFFFFFFFFE") a (entnext i) b (entnext i))
(list (cdr (assoc 5 (entget line))) (equal (handent "FFFFFFFFFFFFFFFE") line)
(not (equal a line)) (cdr (assoc 0 (entget a))) (equal a b) (equal (entnext a) (entnext b))))"#,
)
.lisp(&format!(r#"(progn (setq i (handent "20")) {COUNT})"#))
.out();
assert_eq!(value(&out, 0), "(\"FFFFFFFFFFFFFFFE\" T T \"ATTRIB\" T T)");
// Two ATTRIBs and the SEQEND, then the line (it sorts last by its handle), then the end.
assert_eq!(value(&out, 1), "4");
}
#[test]
fn a_restored_reference_does_not_revive_an_old_name() {
let dir = Dir::new("restored");
let file = fixture(&dir);
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(
r#"(progn {INSERT} (setq i (entlast) a (entnext i))
(entdel i)
(setq gone (entget a))
(entdel i)
(list gone (entget a) (cdr (assoc 1 (entget (entnext i))))))"#
))
.out();
assert_eq!(value(&out, 0), "(nil nil \"A1\")", "the reference comes back, the old name does not");
// ERASE, then OOPS: the same. The old name never comes back with the reference.
let mut run = Run::new(&dir, Some(&file));
let handle = text(&run.lisp(&format!(r#"(progn {INSERT} (cdr (assoc 5 (entget (entlast)))))"#)).out(), 0);
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(&format!(r#"(progn {INSERT} (setq a (entnext (entlast))) "named")"#))
.cmd("erase", json!({ "handles": [handle] }))
.cmd("oops", json!({}))
.lisp("(list (entget a) (cdr (assoc 1 (entget (entnext (entlast))))))")
.out();
assert_eq!(value(&out, 1), "(nil \"A1\")", "OOPS restores the reference, not the old name");
}
#[test]
fn a_new_line_is_never_a_record() {
let dir = Dir::new("handseed");
let file = dir.path("hostile.dxf");
// A file's $HANDSEED in the reserved band is the file's own handle and is not followed (#913),
// so the line made after the walk gets the drawing's seed. The record's name is no handle:
// the line is the line, and the name still names the attribute. The engine's
// `a_new_object_at_any_handle_is_never_a_record` puts the seed at the top of the range.
std::fs::write(&file, insert_dxf_seed(1, "", Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF");
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(r#"(progn (setq i (handent "20") a (entnext i)) (list (cdr (assoc 0 (entget a))) (cdr (assoc 5 (entget (entlast))))))"#)
.lisp(r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#)
.lisp(r#"(list (cdr (assoc 0 (entget a))) (entdel a))"#)
.out();
assert_eq!(value(&out, 0), "(\"ATTRIB\" \"20\")");
assert_eq!(value(&out, 1), "\"100\"");
assert_eq!(value(&out, 2), "(\"ATTRIB\" nil)");
}
#[test]
fn lines_at_the_top_of_the_handle_range_walk_as_lines() {
let dir = Dir::new("walkrange");
let file = dir.path("hostile.dxf");
let before = "0\nLINE\n5\nFFFFFFFFFFFFFFFE\n8\n0\n10\n0\n20\n0\n30\n0\n11\n5\n21\n5\n31\n0\n\
0\nLINE\n5\nFFFFFFFFFFFFFFFF\n8\n0\n10\n0\n20\n0\n30\n0\n11\n6\n21\n6\n31\n0\n";
std::fs::write(&file, insert_dxf_seed(1, before, Some("FFFFFFFFFFFFFFFF"))).expect("write the DXF");
let mut run = Run::new(&dir, Some(&file));
let out = run
.lisp(r#"(progn (setq i (handent "20")) (entnext i))"#)
// The line at the top of the range is in the drawing. Without it, the walk from the line
// below would end in nil, and nil equals the nil `handent` gives for a handle not there.
.lisp(r#"(progn (setq top (handent "FFFFFFFFFFFFFFFF")) (list (cdr (assoc 0 (entget top))) (cdr (assoc 5 (entget top)))))"#)
.lisp(r#"(equal (entnext (handent "FFFFFFFFFFFFFFFE")) top)"#)
.lisp("(entnext top)")
.out();
assert_eq!(value(&out, 1), "(\"LINE\" \"FFFFFFFFFFFFFFFF\")");
assert_eq!(value(&out, 2), "T");
assert_eq!(value(&out, 3), "nil");
}
#[test]
fn the_session_names_at_most_65536_records() {
let dir = Dir::new("names");
let file = dir.path("many.dxf");
// One more attribute than the limit of names: the walk stops at the limit, and nothing in the
// drawing changed.
std::fs::write(&file, insert_dxf(65_537, "")).expect("write the DXF");
let mut run = Run::new(&dir, Some(&file));
let out = run.lisp(&format!("(progn (setq i (entlast)) {COUNT})")).lisp(&format!("(progn (setq i (entlast)) {COUNT})")).out();
assert_eq!(value(&out, 0), "65536");
// The names given by the first walk hold: the second walk is the same.
assert_eq!(value(&out, 1), "65536");
}
-1
View File
@@ -1,4 +1,3 @@
mod block_resources;
mod cli;
mod dash_limit_note;
mod drafting_spacing;
+1 -1
View File
@@ -238,7 +238,7 @@ fn plotter_settings_outside_the_roots_are_refused() {
let device = cadcraft_engine::doc::PlotterConfig {
name: "Office".into(),
description: "not the agent's".into(),
papers: vec![cadcraft_engine::doc::DevicePaper { name: "A4".into(), width: 210.0, height: 297.0, margins: [5.0; 4] }],
papers: vec![cadcraft_engine::doc::DevicePaper { native_key: None, name: "A4".into(), width: 210.0, height: 297.0, margins: [5.0; 4] }],
..Default::default()
};
let file = settings.join("Office.plotter.json");
-3
View File
@@ -37,6 +37,3 @@ wasm-bindgen = "0.2"
wasm-bindgen-futures = "0.4"
js-sys = "0.3"
web-sys = { version = "0.3", features = ["Window", "Document", "Element", "HtmlElement", "HtmlCanvasElement", "HtmlAnchorElement", "Location", "Navigator", "Blob", "BlobPropertyBag", "Url", "MessageEvent", "UrlSearchParams", "MediaQueryList", "Event", "EventTarget", "CustomEvent", "CustomEventInit"] }
[target.'cfg(target_arch = "wasm32")'.dev-dependencies]
wasm-bindgen-test = { workspace = true }
-232
View File
@@ -1,232 +0,0 @@
//! Same-origin file-provider bridge. Persistence belongs to the registered provider, not WASM.
//!
//! Callbacks enqueue commands for a later egui frame. Exporting bytes never acknowledges them.
use cadcraft_ui_egui::file_providers::{Host, Resource};
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
use wasm_bindgen::{JsCast, JsValue, closure::Closure, prelude::wasm_bindgen};
thread_local! {
static CURRENT_CONTEXT: std::cell::RefCell<Option<egui::Context>> = const { std::cell::RefCell::new(None) };
}
const API: &str = "cadcraftFileProviders";
const EVENT: &str = "cadcraft-file-provider";
const MAX_BYTES: u32 = 80 * 1024 * 1024;
#[wasm_bindgen]
extern "C" {
#[wasm_bindgen(catch, js_namespace = Uint8Array, js_name = from)]
fn copy_event_bytes(bytes: &[u8]) -> Result<Uint8Array, JsValue>;
}
fn error(message: impl ToString) -> JsValue {
JsValue::from_str(&message.to_string())
}
fn object(value: &serde_json::Value) -> Result<JsValue, JsValue> {
js_sys::JSON::parse(&value.to_string())
}
fn set(target: &JsValue, key: &str, value: &JsValue) -> Result<(), JsValue> {
if Reflect::set(target, &key.into(), value)? { Ok(()) } else { Err(error("file-provider API is not writable")) }
}
// Inspect UTF-16 length before copying a host string into WASM memory.
fn bounded_string(value: JsValue, max_units: u32) -> Result<String, JsValue> {
let text = value.dyn_into::<js_sys::JsString>().map_err(|_| error("resource fields must be strings"))?;
if text.length() > max_units {
return Err(error("resource field is too large"));
}
text.as_string().ok_or_else(|| error("invalid resource field"))
}
fn resource(value: JsValue) -> Result<Resource, JsValue> {
if value.is_null() || !value.is_object() || Array::is_array(&value) {
return Err(error("resource entries must be objects"));
}
let entry = value.dyn_into::<Object>()?;
let id = bounded_string(Reflect::get(&entry, &"id".into())?, 160)?;
let name = bounded_string(Reflect::get(&entry, &"name".into())?, 255)?;
let updated = Reflect::get(&entry, &"updatedAt".into())?;
let updated_at = if updated.is_undefined() { String::new() } else { bounded_string(updated, 100)? };
Ok(Resource { id, name, updated_at })
}
fn wake_later(ctx: &egui::Context) {
let fallback = ctx.clone();
wasm_bindgen_futures::spawn_local(async move {
CURRENT_CONTEXT.with(|current| current.borrow().as_ref().unwrap_or(&fallback).request_repaint());
});
}
/// Makes the capability discoverable without enabling it or changing the browser's writer.
pub fn install(host: Host, ctx: egui::Context) -> Result<(), JsValue> {
let window = web_sys::window().ok_or_else(|| error("no window"))?;
CURRENT_CONTEXT.with(|current| *current.borrow_mut() = Some(ctx.clone()));
if Reflect::has(&window, &API.into())? {
// A graphics restart keeps the page capability and pending requests, and renews its wake target.
return Ok(());
}
// A delayed result from an earlier page must never address a new document's request.
let crypto = Reflect::get(&window, &"crypto".into())?;
let random = Reflect::get(&crypto, &"getRandomValues".into())?.dyn_into::<Function>()?;
let nonce = Uint8Array::new_with_length(16);
random.call1(&crypto, &nonce)?;
host.set_session(nonce.to_vec().iter().map(|byte| format!("{byte:02x}")).collect()).map_err(error)?;
let api = Object::new();
set(&api, "protocolVersion", &1.into())?;
set(&api, "app", &"cadcraft".into())?;
set(&api, "capabilities", &object(&serde_json::json!(["revisionAck", "externalRecents", "saveDestination", "openBytes"]))?)?;
let h = host.clone();
let wake = ctx.clone();
let register = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<String, JsValue>>::new(move |id, label, namespace| {
let id = bounded_string(id, 160)?;
let label = bounded_string(label, 100)?;
let namespace = bounded_string(namespace, 160)?;
let connection = h.connect(id, label, namespace).map_err(error)?;
wake_later(&wake);
Ok(connection)
});
set(&api, "registerProvider", register.as_ref())?;
register.forget();
let h = host.clone();
let wake = ctx.clone();
let unregister = Closure::<dyn FnMut() -> Result<bool, JsValue>>::new(move || {
h.disconnect().map_err(error)?;
wake_later(&wake);
Ok(true)
});
set(&api, "unregisterProvider", unregister.as_ref())?;
unregister.forget();
let h = host.clone();
let wake = ctx.clone();
let enabled = Closure::<dyn FnMut(JsValue) -> Result<bool, JsValue>>::new(move |value: JsValue| {
let value = value.as_bool().ok_or_else(|| error("enabled must be a boolean"))?;
h.set_enabled(value).map_err(error)?;
wake_later(&wake);
Ok(true)
});
set(&api, "setEnabled", enabled.as_ref())?;
enabled.forget();
let h = host.clone();
let wake = ctx.clone();
let resources = Closure::<dyn FnMut(JsValue, JsValue) -> Result<(), JsValue>>::new(move |connection, value: JsValue| {
let connection = bounded_string(connection, 160)?;
if !Array::is_array(&value) {
return Err(error("resources must be an array of at most 100 entries"));
}
let entries = value.dyn_into::<Array>()?;
if entries.length() > 100 {
return Err(error("resources must be an array of at most 100 entries"));
}
// Read only bounded metadata; do not copy or serialize arbitrary host properties.
let resources = entries.iter().map(resource).collect::<Result<Vec<_>, _>>()?;
h.set_resources(&connection, resources).map_err(error)?;
wake_later(&wake);
Ok(())
});
set(&api, "setResources", resources.as_ref())?;
resources.forget();
let h = host.clone();
let wake = ctx.clone();
let request_open = Closure::<dyn FnMut(JsValue) -> Result<String, JsValue>>::new(move |resource| {
let resource = bounded_string(resource, 160)?;
let request = h.request_open(&resource).map_err(error)?;
wake_later(&wake);
Ok(request)
});
set(&api, "requestOpen", request_open.as_ref())?;
request_open.forget();
let h = host.clone();
let wake = ctx.clone();
let open = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, name, value: JsValue| {
let request = bounded_string(request, 160)?;
let name = bounded_string(name, 255)?;
let bytes = value.dyn_into::<Uint8Array>().map_err(|_| error("bytes must be a Uint8Array"))?;
if bytes.length() > MAX_BYTES {
return Err(error("file exceeds the provider limit"));
}
h.open(request, name, bytes.to_vec()).map_err(error)?;
wake_later(&wake);
Ok(())
});
set(&api, "openResource", open.as_ref())?;
open.forget();
let h = host.clone();
let wake = ctx.clone();
let cancel_open = Closure::<dyn FnMut(JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, message| {
let request = bounded_string(request, 160)?;
let message = bounded_string(message, 1024)?;
h.cancel_open(request, message).map_err(error)?;
wake_later(&wake);
Ok(())
});
set(&api, "cancelOpen", cancel_open.as_ref())?;
cancel_open.forget();
let h = host.clone();
let wake = ctx.clone();
let result = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, status, resource| {
let request = bounded_string(request, 160)?;
let status = bounded_string(status, 8)?;
let resource = bounded_string(resource, 160)?;
h.result(request, status, resource).map_err(error)?;
wake_later(&wake);
Ok(())
});
set(&api, "saveResult", result.as_ref())?;
result.forget();
let h = host.clone();
let wake = ctx.clone();
let dialog = Closure::<dyn FnMut(JsValue, JsValue, JsValue) -> Result<(), JsValue>>::new(move |request, destination, name| {
let request = bounded_string(request, 160)?;
let destination = bounded_string(destination, 8)?;
let name = bounded_string(name, 255)?;
h.resolve_dialog(&request, &destination, &name).map_err(error)?;
wake_later(&wake);
Ok(())
});
set(&api, "resolveSaveDialog", dialog.as_ref())?;
dialog.forget();
let h = host.clone();
let snapshot = Closure::<dyn FnMut() -> Result<JsValue, JsValue>>::new(move || object(&h.snapshot()));
set(&api, "snapshot", snapshot.as_ref())?;
snapshot.forget();
set(&window, API, &Object::freeze(&api))?;
dispatch(&serde_json::json!({"type": "ready", "protocolVersion": 1}), None)
}
fn dispatch(metadata: &serde_json::Value, bytes: Option<Vec<u8>>) -> Result<(), JsValue> {
let detail = object(metadata)?;
if let Some(bytes) = bytes {
set(&detail, "bytes", &copy_event_bytes(&bytes)?.into())?;
}
let init = web_sys::CustomEventInit::new();
init.set_detail(&detail);
let event = web_sys::CustomEvent::new_with_event_init_dict(EVENT, &init)?;
web_sys::window().ok_or_else(|| error("no window"))?.dispatch_event(&event)?;
Ok(())
}
pub fn publish(host: &Host) {
if host.publish_events_with(dispatch, |error| log::error!("file-provider event delivery failed: {error:?}")) {
CURRENT_CONTEXT.with(|current| {
if let Some(ctx) = current.borrow().as_ref() {
ctx.request_repaint();
}
});
}
}
#[cfg(test)]
mod browser_tests;
@@ -1,271 +0,0 @@
//! Original, self-contained DXF fixture. Rust closures create genuine JS exceptions; no JS source.
use std::cell::{Cell, RefCell};
use std::rc::Rc;
use std::sync::Arc;
use cadcraft_engine::{Session, cmd::file};
use cadcraft_ui_egui::{CadApp, Services};
use js_sys::{Array, Function, Object, Reflect, Uint8Array};
use serde_json::json;
use wasm_bindgen::{JsCast, JsValue, closure::Closure};
use wasm_bindgen_test::*;
wasm_bindgen_test_configure!(run_in_browser);
fn error(message: impl ToString) -> JsValue {
JsValue::from_str(&message.to_string())
}
fn field(object: &JsValue, name: &str) -> Result<JsValue, JsValue> {
Reflect::get(object, &name.into())
}
fn text(object: &JsValue, name: &str) -> Result<String, JsValue> {
field(object, name)?.as_string().ok_or_else(|| error(format!("missing string field {name}")))
}
fn call(object: &JsValue, name: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
let function = field(object, name)?.dyn_into::<Function>()?;
let array = Array::new();
for argument in arguments {
array.push(argument);
}
function.apply(object, &array)
}
struct Page {
window: web_sys::Window,
api: JsValue,
host: cadcraft_ui_egui::file_providers::Host,
ctx: egui::Context,
events: Rc<RefCell<Vec<JsValue>>>,
listener: Closure<dyn FnMut(web_sys::Event)>,
}
impl Page {
fn install(app: &CadApp) -> Result<Self, JsValue> {
let window = web_sys::window().ok_or_else(|| error("no browser window"))?;
if Reflect::has(&window, &super::API.into())? {
return Err(error("fixture requires a fresh owned page"));
}
let host = app.file_providers.clone();
let ctx = egui::Context::default();
let events = Rc::new(RefCell::new(Vec::new()));
let seen = events.clone();
let listener = Closure::<dyn FnMut(web_sys::Event)>::new(move |event: web_sys::Event| {
if let Ok(event) = event.dyn_into::<web_sys::CustomEvent>() {
seen.borrow_mut().push(event.detail());
}
});
window.add_event_listener_with_callback(super::EVENT, listener.as_ref().unchecked_ref())?;
let mut page = Self { window, api: JsValue::UNDEFINED, host, ctx, events, listener };
super::install(page.host.clone(), page.ctx.clone())?;
page.api = field(&page.window, super::API)?;
Ok(page)
}
fn api(&self, method: &str, arguments: &[JsValue]) -> Result<JsValue, JsValue> {
call(&self.api, method, arguments)
}
fn latest(&self, kind: &str) -> Result<JsValue, JsValue> {
self.events
.borrow()
.iter()
.rev()
.find(|event| text(event, "type").is_ok_and(|name| name == kind))
.cloned()
.ok_or_else(|| error(format!("missing real window event {kind}")))
}
fn tick(&self, app: &mut CadApp) {
self.ctx.run_ui(Default::default(), |ui| app.logic(ui.ctx())).drop_without_applying_deltas();
}
fn choose(&self, app: &mut CadApp) -> Result<String, JsValue> {
let value = app.run("qsave", serde_json::Value::Null).map_err(error)?;
value
.get("requestId")
.and_then(serde_json::Value::as_str)
.map(str::to_string)
.ok_or_else(|| error("qsave did not create a real provider choice"))
}
fn captured_save(&self, app: &mut CadApp) -> Result<String, JsValue> {
let request = self.choose(app)?;
super::publish(&self.host);
assert_eq!(text(&self.latest("saveDialog")?, "requestId")?, request);
self.api("resolveSaveDialog", &[request.clone().into(), "provider".into(), "Fixture.dxf".into()])?;
Ok(request)
}
// Both the injected callback and production publisher are entered through catch-enabled
// Function::call0. Restore the exact own descriptor (or remove our inherited-method shadow)
// BEFORE assertions, even when an uncaught production exception returns Err from call0.
fn with_replacement(&self, target: &JsValue, key: &str, replacement: &JsValue) -> Result<Result<JsValue, JsValue>, JsValue> {
let object = field(&js_sys::global(), "Object")?;
let descriptor = call(&object, "getOwnPropertyDescriptor", &[target.clone(), key.into()])?;
let original = field(target, key)?;
let host = self.host.clone();
let operation = Closure::<dyn FnMut()>::new(move || super::publish(&host));
let outcome = match Reflect::set(target, &key.into(), replacement) {
Ok(true) => operation.as_ref().unchecked_ref::<Function>().call0(&JsValue::UNDEFINED),
Ok(false) => Err(error("injected method is not writable")),
Err(error) => Err(error),
};
if descriptor.is_undefined() {
if !Reflect::delete_property(target.unchecked_ref::<Object>(), &key.into())? {
return Err(error("could not remove injected method"));
}
} else {
call(&object, "defineProperty", &[target.clone(), key.into(), descriptor.clone()])?;
}
let restored = call(&object, "getOwnPropertyDescriptor", &[target.clone(), key.into()])?;
if field(target, key)? != original || restored.is_undefined() != descriptor.is_undefined() {
return Err(error("injected property was not restored exactly"));
}
if !descriptor.is_undefined() {
for attribute in ["value", "get", "set", "writable", "enumerable", "configurable"] {
if field(&restored, attribute)? != field(&descriptor, attribute)? {
return Err(error("injected property descriptor changed"));
}
}
}
Ok(outcome)
}
fn fail_copy(&self) -> Result<u32, JsValue> {
let calls = Rc::new(Cell::new(0));
let seen = calls.clone();
let fault = Closure::<dyn FnMut(JsValue) -> Result<JsValue, JsValue>>::new(move |_| {
seen.set(seen.get() + 1);
Err(js_sys::RangeError::new("synthetic CAD byte-copy failure").into())
});
let array = field(&js_sys::global(), "Uint8Array")?;
self.with_replacement(&array, "from", fault.as_ref())??;
Ok(calls.get())
}
fn fail_dispatch(&self, kind: &str) -> Result<u32, JsValue> {
let original = field(&self.window, "dispatchEvent")?.dyn_into::<Function>()?;
let window: JsValue = self.window.clone().into();
let wanted = kind.to_string();
let calls = Rc::new(Cell::new(0));
let seen = calls.clone();
let fault = Closure::<dyn FnMut(JsValue) -> Result<JsValue, JsValue>>::new(move |event: JsValue| {
if text(&field(&event, "detail")?, "type")? == wanted {
seen.set(seen.get() + 1);
Err(js_sys::RangeError::new("synthetic CAD metadata dispatch failure").into())
} else {
original.call1(&window, &event)
}
});
self.with_replacement(&self.window, "dispatchEvent", fault.as_ref())??;
Ok(calls.get())
}
}
impl Drop for Page {
fn drop(&mut self) {
let _ = self.window.remove_event_listener_with_callback(super::EVENT, self.listener.as_ref().unchecked_ref());
let _ = Reflect::delete_property(self.window.unchecked_ref::<Object>(), &super::API.into());
}
}
#[wasm_bindgen_test]
fn real_window_delivery_recovery_preserves_dxf_and_consumes_actual_cad_actions() -> Result<(), JsValue> {
// Production codec hooks, on this fixture's fresh browser page only. Native app fixtures
// use cadcraft_io directly and never replace their process-global test hooks.
file::set_io(file::IoHooks {
read: |bytes, name| cadcraft_io::read(bytes, name).map_err(|error| error.to_string()),
write: |drawing, name| cadcraft_io::write(drawing, name).map_err(|error| error.to_string()),
plot: None,
});
file::set_write_as(|drawing, name, options| {
cadcraft_io::write_with(drawing, name, &cadcraft_io::SaveOptions { version: options.version, binary: options.binary })
.map_err(|error| error.to_string())
});
let mut app = CadApp::new(Session::new(), Services { no_file_system: true, ..Default::default() });
app.run("line", json!({"points":[[0,0],[10,10]]})).map_err(error)?;
let page = Page::install(&app)?;
let connection = page.api("registerProvider", &["fixture".into(), "Fixture storage".into(), "account-one".into()])?;
let resources = Array::new();
for id in ["file-1", "file-2"] {
let resource = Object::new();
Reflect::set(&resource, &"id".into(), &id.into())?;
Reflect::set(&resource, &"name".into(), &"Fixture.dxf".into())?;
Reflect::set(&resource, &"updatedAt".into(), &"".into())?;
resources.push(&resource);
}
page.api("setResources", &[connection.clone(), resources.into()])?;
let uid = app.session.state().map_err(error)?.uid;
let checkpoint = app.session.state().map_err(error)?.saved.clone();
let chooser = page.choose(&mut app)?;
assert_eq!(page.fail_dispatch("saveDialog")?, 1);
page.tick(&mut app);
super::publish(&page.host);
assert_eq!(text(&page.latest("saveFailed")?, "requestId")?, chooser);
assert!(page.api("resolveSaveDialog", &[chooser.into(), "provider".into(), "Late.dxf".into()]).is_err());
assert!(!page.host.busy());
assert!(Arc::ptr_eq(&app.session.state().map_err(error)?.saved, &checkpoint));
let read = page.api("requestOpen", &["file-2".into()])?;
assert_eq!(page.fail_dispatch("openRequested")?, 1);
let failed_read = page.latest("openFailed")?;
assert_eq!(field(&failed_read, "requestId")?, read);
assert_eq!(text(&failed_read, "resourceId")?, "file-2");
assert_eq!(field(&failed_read, "connectionId")?, connection);
assert!(!page.host.busy());
let failed = page.captured_save(&mut app)?;
let later_read = page.api("requestOpen", &["file-2".into()])?;
app.set_status("Awaiting the synthetic byte-copy failure");
assert_eq!(page.fail_copy()?, 1, "actual catch-enabled production copy must throw exactly once");
assert!(!page.events.borrow().iter().any(|event| text(event, "type").is_ok_and(|kind| kind == "save")));
assert_eq!(field(&page.latest("openRequested")?, "requestId")?, later_read);
assert!(page.api("saveResult", &[failed.clone().into(), "saved".into(), "file-1".into()]).is_err());
page.api("cancelOpen", &[later_read, "".into()])?;
page.tick(&mut app);
super::publish(&page.host);
assert_eq!(text(&page.latest("saveFailed")?, "requestId")?, failed);
let state = app.session.state().map_err(error)?;
assert_eq!(state.uid, uid);
assert!(state.is_dirty() && Arc::ptr_eq(&state.saved, &checkpoint));
assert!(!page.host.busy() && page.host.bound_document("file-1").is_none());
assert!(app.status.as_ref().is_some_and(|(message, _)| message.contains("File provider save failed")));
let retry = page.captured_save(&mut app)?;
assert_ne!(retry, failed);
super::publish(&page.host);
let saved = page.latest("save")?;
assert_eq!(text(&saved, "requestId")?, retry);
assert_eq!(text(&saved, "filename")?, "Fixture.dxf");
assert_eq!(text(&saved, "documentId")?, uid.to_string());
assert_eq!(field(&saved, "connectionId")?, connection);
let bytes = field(&saved, "bytes")?.dyn_into::<Uint8Array>()?;
assert!(bytes.length() > 0);
let drawing = cadcraft_io::read(&bytes.to_vec(), "Fixture.dxf").map_err(error)?;
assert_eq!(drawing.model.len(), app.session.state().map_err(error)?.doc.model.len());
assert!(!drawing.model.is_empty());
assert!(page.host.pending_for(uid) && app.session.state().map_err(error)?.is_dirty());
let captured = app.session.state().map_err(error)?.doc.clone();
let captured_revision = app.session.state().map_err(error)?.revision;
app.run("line", json!({"points":[[20,20],[30,30]]})).map_err(error)?;
page.api("saveResult", &[retry.clone().into(), "saved".into(), "file-1".into()])?;
page.tick(&mut app);
super::publish(&page.host);
let terminal = page.latest("saved")?;
assert_eq!(text(&terminal, "requestId")?, retry);
assert_eq!(text(&terminal, "resourceId")?, "file-1");
assert_eq!(text(&terminal, "revision")?, captured_revision.to_string());
let state = app.session.state().map_err(error)?;
assert!(state.is_dirty() && Arc::ptr_eq(&state.saved, &captured), "ACK owns its snapshot, never later edits");
assert_eq!(page.host.bound_document("file-1"), Some(uid));
assert!(!page.host.busy());
let open = page.api("requestOpen", &["file-2".into()])?;
super::publish(&page.host);
page.api("openResource", &[open.clone(), "Fixture.dxf".into(), bytes.into()])?;
page.tick(&mut app);
super::publish(&page.host);
let opened = page.latest("opened")?;
assert_eq!(field(&opened, "requestId")?, open);
assert_eq!(text(&opened, "resourceId")?, "file-2");
assert_eq!(field(&opened, "connectionId")?, connection);
assert_eq!(text(&opened, "namespace")?, "account-one");
let imported = app.session.state().map_err(error)?;
assert_ne!(imported.uid, uid);
assert_eq!(imported.doc.model.len(), drawing.model.len());
let original = app.session.docs.iter().find(|doc| doc.uid == uid).ok_or_else(|| error("original drawing was lost on provider open"))?;
assert!(original.is_dirty() && Arc::ptr_eq(&original.saved, &captured));
assert!(!page.host.busy());
page.api("unregisterProvider", &[])?;
Ok(())
}
-13
View File
@@ -15,8 +15,6 @@ mod api;
#[cfg(target_arch = "wasm32")]
pub mod download;
#[cfg(target_arch = "wasm32")]
mod file_providers;
#[cfg(target_arch = "wasm32")]
mod host;
#[cfg(any(target_arch = "wasm32", test))]
@@ -49,7 +47,6 @@ mod web {
self.1.drain(&mut self.0);
self.0.system_animations = self.3.as_ref().map(|reduced| !reduced.matches());
self.0.logic(ctx);
crate::file_providers::publish(&self.0.file_providers);
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);
// The crate suppresses duplicates, so reporting after every logic callback
@@ -85,7 +82,6 @@ mod web {
self.1.take_dropped(ui.ctx());
}
self.0.ui(ui);
crate::file_providers::publish(&self.0.file_providers);
}
}
@@ -140,8 +136,6 @@ mod web {
groups: cadcraft_io::entity_groups,
entity: cadcraft_io::entity_from_groups,
});
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
@@ -185,13 +179,6 @@ mod web {
let session = if app_bridge.is_some() { Session::empty() } else { Session::new() };
let control = crate::api::install(cc.egui_ctx.clone());
let mut app = CadApp::new(session, services()).with_control(control);
// The provider capability is independent of the parent and same-document host modes.
// Avoid two hosts competing for the same Save command.
if app_bridge.is_none() {
if let Err(error) = crate::file_providers::install(app.file_providers.clone(), cc.egui_ctx.clone()) {
log::error!("file provider capability could not be installed: {error:?}");
}
}
app.system_languages =
web_sys::window().map(|w| w.navigator().languages().iter().filter_map(|v| v.as_string()).collect()).unwrap_or_default();
if let Some(profile) = cc.storage.and_then(|s| s.get_string(cadcraft_ui_egui::options::PROFILE_KEY)) {
+12 -2
View File
@@ -194,13 +194,23 @@ pub fn install_io() {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
});
cadcraft_engine::cmd::exchange::set_pdf_import(|bytes, options| cadcraft_io::pdf_read::read_json(bytes, options).map_err(|e| e.to_string()));
// System printers: CUPS on macOS and Linux.
#[cfg(unix)]
cadcraft_engine::cmd::plotters::set_system_printers(cadcraft_engine::cmd::plotters::SystemPrinters {
list: cadcraft_io::cups::printers,
print: |j| cadcraft_io::cups::print(j.printer, j.paper_key, j.size_mm, j.copies, j.title, j.pdf),
});
// System printers: the Windows spooler.
#[cfg(windows)]
cadcraft_engine::cmd::plotters::set_system_printers(cadcraft_engine::cmd::plotters::SystemPrinters {
list: cadcraft_io::winprint::printers,
print: |j| cadcraft_io::winprint::print(j.printer, j.paper, j.copies, j.title, j.pdf),
});
// AutoLISP's entget, entmake and entmod see entities as DXF groups.
cadcraft_engine::cmd::file::set_entity_codec(cadcraft_engine::cmd::file::EntityCodec {
groups: cadcraft_io::entity_groups,
entity: cadcraft_io::entity_from_groups,
});
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
cadcraft_engine::cmd::file::set_entity_sub_record(cadcraft_io::entity_sub_record);
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
cadcraft_engine::cmd::file::set_object_records(cadcraft_io::object_records);
// What a DXF before 2007 leaves out for its proxies' string streams (#3229).
+14 -17
View File
@@ -213,14 +213,16 @@ mod tests {
let path = directory.join("workspace.json");
let (mut first, restored, error) = Workspace::at(Some(path.clone()));
assert!(restored.is_none() && error.is_none());
let mut ui = UiState::default();
ui.show_palettes = false;
ui.show_command_line = false;
ui.toolset_tab = "Modeling".into();
ui.collapsed_groups = vec!["Solid".into()];
ui.history_lines = 5;
ui.dialog = Some("layers".into());
ui.start_tab = true;
let ui = UiState {
show_palettes: false,
show_command_line: false,
toolset_tab: "Modeling".into(),
collapsed_groups: vec!["Solid".into()],
history_lines: 5,
dialog: Some("layers".into()),
start_tab: true,
..Default::default()
};
first.save_if_changed(&ui, Instant::now()).unwrap();
let bytes = fs::read(&path).unwrap();
let value: Value = serde_json::from_slice(&bytes).unwrap();
@@ -311,9 +313,7 @@ mod tests {
let (mut store, ui, error) = Workspace::at(Some(path.clone()));
assert!(ui.is_none());
assert!(error.as_deref().is_some_and(|error| error.contains("left unchanged")));
let mut ui = UiState::default();
ui.show_palettes = false;
store.save_if_changed(&ui, Instant::now()).unwrap();
store.save_if_changed(&UiState { show_palettes: false, ..Default::default() }, Instant::now()).unwrap();
assert_eq!(fs::read(&path).unwrap(), bytes);
}
fs::remove_dir_all(directory).unwrap();
@@ -351,8 +351,7 @@ mod tests {
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let start = Instant::now();
let mut ui = UiState::default();
ui.history_lines = 1;
let mut ui = UiState { history_lines: 1, ..Default::default() };
assert_eq!(store.save_if_changed(&ui, start).unwrap(), None);
// A drag: a new state every frame, none of them written until the interval ends.
for (frame, lines) in (2..=5).enumerate() {
@@ -376,8 +375,7 @@ mod tests {
let directory = temp_dir();
let path = directory.join("workspace.json");
let (mut store, _, _) = Workspace::at(Some(path.clone()));
let mut ui = UiState::default();
ui.show_palettes = false;
let mut ui = UiState { show_palettes: false, ..Default::default() };
store.save_if_changed(&ui, Instant::now()).unwrap();
let good = fs::read(&path).unwrap();
ui.collapsed_groups = vec!["x".repeat(257)];
@@ -393,8 +391,7 @@ mod tests {
let (mut store, _, _) = Workspace::at(Some(path.clone()));
// Simulate a destination becoming unavailable after startup.
fs::create_dir(&path).unwrap();
let mut ui = UiState::default();
ui.show_palettes = false;
let ui = UiState { show_palettes: false, ..Default::default() };
let first_error = store.save_if_changed(&ui, Instant::now()).unwrap_err();
fs::remove_dir(&path).unwrap();
assert_eq!(store.save_if_changed(&ui, Instant::now()).unwrap_err(), first_error);
-40
View File
@@ -154,43 +154,7 @@ impl AttribProps {
#[derive(Clone, Copy, Debug)]
pub struct TagKey<'a>(pub &'a str);
#[cfg(test)]
std::thread_local! {
static TAG_CROSS_PROBE: std::cell::Cell<Option<(usize, [usize; 2])>> = const { std::cell::Cell::new(None) };
}
#[cfg(test)]
fn record_tag_cross_probe(left: &str, right: &str) {
TAG_CROSS_PROBE.with(|probe| {
let Some((position, mut counts)) = probe.get() else { return };
match (left.as_bytes().get(position), right.as_bytes().get(position)) {
(Some(b'A'), Some(b'D')) => counts[0] += 1,
(Some(b'D'), Some(b'A')) => counts[1] += 1,
_ => return,
}
probe.set(Some((position, counts)));
});
}
impl TagKey<'_> {
/// Count comparisons in both directions between the A and D fixture tag sets.
#[cfg(test)]
pub(crate) fn with_cross_probes<T>(position: usize, f: impl FnOnce() -> T) -> (T, [usize; 2]) {
struct Restore(Option<(usize, [usize; 2])>);
impl Drop for Restore {
fn drop(&mut self) {
TAG_CROSS_PROBE.with(|probe| probe.set(self.0));
}
}
TAG_CROSS_PROBE.with(|probe| {
let _restore = Restore(probe.replace(Some((position, [0; 2]))));
let value = f();
(value, probe.get().map_or([0; 2], |(_, counts)| counts))
})
}
/// The tag's bytes with ASCII letters in lower case: equal for the tags `eq_ignore_ascii_case`
/// finds equal.
fn folded(&self) -> impl Iterator<Item = u8> + '_ {
@@ -200,8 +164,6 @@ impl TagKey<'_> {
impl PartialEq for TagKey<'_> {
fn eq(&self, other: &Self) -> bool {
#[cfg(test)]
record_tag_cross_probe(self.0, other.0);
self.0.eq_ignore_ascii_case(other.0)
}
}
@@ -210,8 +172,6 @@ impl Eq for TagKey<'_> {}
impl Ord for TagKey<'_> {
fn cmp(&self, other: &Self) -> Ordering {
#[cfg(test)]
record_tag_cross_probe(self.0, other.0);
self.folded().cmp(other.folded())
}
}
-5
View File
@@ -261,11 +261,6 @@ pub fn is_user_pattern(name: &str) -> bool {
name.eq_ignore_ascii_case(USER_PATTERN)
}
/// Names owned by the standard library or the native user-defined hatch form.
pub fn is_reserved_pattern_name(name: &str) -> bool {
is_user_pattern(name) || pattern(name).is_some()
}
/// Hatch pattern scales must be greater than this limit. For a user-defined hatch, the scale is its line spacing.
pub const MIN_HATCH_PATTERN_SCALE: f64 = 1e-9;
+77 -4
View File
@@ -64,6 +64,9 @@ pub enum Orientation {
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
#[serde(default, rename_all = "camelCase")]
pub struct DevicePaper {
/// Native media identifier, retained exactly for system-printer submission.
#[serde(skip)]
pub native_key: Option<String>,
pub name: String,
pub width: f64,
pub height: f64,
@@ -72,7 +75,7 @@ pub struct DevicePaper {
impl Default for DevicePaper {
fn default() -> Self {
DevicePaper { name: String::new(), width: 210.0, height: 297.0, margins: [0.0; 4] }
DevicePaper { native_key: None, name: String::new(), width: 210.0, height: 297.0, margins: [0.0; 4] }
}
}
@@ -119,9 +122,17 @@ pub struct PlotterConfig {
/// Name of the paper chosen when a page setup switches to this device.
pub default_paper: String,
pub papers: Vec<DevicePaper>,
/// A printer of the operating system (listed by the host, never read from or written to a
/// file): a plot to it is a PDF the host prints rather than a file.
#[serde(skip)]
pub system: bool,
/// With `system`: the operating system's default printer (never in a file either).
#[serde(skip)]
pub system_default: bool,
}
impl Default for PlotterConfig {
/// An unnamed PDF device at 300 dpi, landscape, with no papers: a user device before its settings are filled in.
fn default() -> Self {
PlotterConfig {
name: String::new(),
@@ -131,6 +142,8 @@ impl Default for PlotterConfig {
orientation: Orientation::Landscape,
default_paper: String::new(),
papers: Vec::new(),
system: false,
system_default: false,
}
}
}
@@ -145,6 +158,13 @@ fn key(s: &str) -> String {
s.chars().filter(|c| !c.is_whitespace() && *c != '_' && *c != '-').collect::<String>().to_ascii_lowercase()
}
/// What tells a paper's name apart from the other papers of a device once it is sanitized
/// ([`PlotterConfig::sanitized`], [`PlotterConfig::paper`]): two names with the same key are one
/// paper, and the second is dropped. Empty for a name no lookup finds.
pub fn paper_name_key(name: &str) -> String {
key(&clean_name(name))
}
impl PlotterConfig {
/// The configuration with hostile values fixed: a clean name and description, resolution
/// 50..=2400 dpi, at most [`MAX_DEVICE_PAPERS`] sanitized papers with unique names, and a
@@ -221,6 +241,46 @@ pub fn plotter_file_name(name: &str) -> Option<String> {
(!base.is_empty()).then(|| format!("{base}{PLOTTER_FILE_EXT}"))
}
/// Fill the `{name}` fields of a plot stamp in one pass over `template`, so a value is never
/// filled again: a layout named `Detail {paper}` stays as it is. `{{` stands for a literal `{`;
/// other text and fields not in `fields` are copied. A stamp is filled in steps (the command
/// knows the drawing and the device, the plotter each sheet's layout, paper and scale): before
/// the `last` step a value's braces are doubled and `{{` is kept, so a later step neither fills
/// a value nor loses a literal brace; the `last` step turns `{{` into `{`.
pub fn fill_stamp(template: &str, fields: &[(&str, &str)], last: bool) -> String {
let mut out = String::with_capacity(template.len());
let mut rest = template;
while let Some(i) = rest.find('{') {
out.push_str(&rest[..i]);
rest = &rest[i..];
if let Some(after) = rest.strip_prefix("{{") {
out.push_str(if last { "{" } else { "{{" });
rest = after;
continue;
}
let field = fields.iter().find_map(|(name, value)| {
let after = rest.strip_prefix('{')?.strip_prefix(*name)?.strip_prefix('}')?;
Some((*value, after))
});
match field {
Some((value, after)) => {
if last {
out.push_str(value);
} else {
out.push_str(&value.replace('{', "{{"));
}
rest = after;
}
None => {
out.push('{');
rest = &rest[1..];
}
}
}
out.push_str(rest);
out
}
#[cfg(test)]
mod tests {
use super::*;
@@ -233,9 +293,9 @@ mod tests {
resolution: 1_000_000,
default_paper: "nope".into(),
papers: vec![
DevicePaper { name: "A3 borderless".into(), width: 420.0, height: 297.0, margins: [0.0; 4] },
DevicePaper { native_key: None, name: "A3 borderless".into(), width: 420.0, height: 297.0, margins: [0.0; 4] },
DevicePaper { name: "a3-BORDERLESS".into(), ..DevicePaper::default() },
DevicePaper { name: String::new(), width: f64::NAN, height: 1e12, margins: [f64::INFINITY, 9e9, -1.0, 5.0] },
DevicePaper { native_key: None, name: String::new(), width: f64::NAN, height: 1e12, margins: [f64::INFINITY, 9e9, -1.0, 5.0] },
],
..PlotterConfig::default()
};
@@ -249,7 +309,8 @@ mod tests {
assert_eq!(back.papers[1].margins, [0.0, 1000.0, 0.0, 5.0], "hostile margins clamped");
let wide = DevicePaper { margins: [150.0, 0.0, 100.0, 0.0], ..DevicePaper::default() }.sanitized();
assert_eq!(wide.margins, [0.0; 4], "margins wider than the paper are dropped");
let turned = DevicePaper { name: "Banner".into(), width: 400.0, height: 200.0, margins: [150.0, 0.0, 150.0, 0.0] }.sanitized();
let turned =
DevicePaper { native_key: None, name: "Banner".into(), width: 400.0, height: 200.0, margins: [150.0, 0.0, 150.0, 0.0] }.sanitized();
assert_eq!((turned.width, turned.height), (200.0, 400.0), "portrait");
assert_eq!(turned.margins, [0.0, 150.0, 0.0, 150.0], "margins turn with the sheet");
assert!(back.paper("a3 BORDERLESS").is_some());
@@ -259,4 +320,16 @@ mod tests {
assert_eq!(plotter_file_name("../a/b:c").as_deref(), Some("___a_b_c.plotter.json"));
assert_eq!(plotter_file_name(" "), None);
}
/// Stamp fields are filled in one pass: a value that looks like a field is copied as it is,
/// through every step, and `{{` is a literal brace (#2171 review).
#[test]
fn stamp_fields_are_filled_once() {
let sheet = |t: &str| fill_stamp(t, &[("layout", "Detail {paper}"), ("paper", "A4"), ("scale", "1:50")], true);
assert_eq!(sheet("{layout} · {paper}"), "Detail {paper} · A4");
assert_eq!(sheet("{{paper}} {scale} {other} {"), "{paper}} 1:50 {other} {");
// The command's step first: a drawing named like a field stays so in the sheet's step.
let cmd = fill_stamp("{drawing}, {layout}, {{x}", &[("drawing", "Plan {layout}.dwg")], false);
assert_eq!(sheet(&cmd), "Plan {layout}.dwg, Detail {paper}, {x}");
}
}
+1 -74
View File
@@ -6,19 +6,12 @@
use std::collections::HashMap;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
use crate::{Entity, Handle};
const CHUNK_MAX: usize = 1024;
const SHARDS: usize = 64;
/// A content token no store has had: one count for the process (a `u64` does not run out).
fn next_token() -> u64 {
static NEXT: AtomicU64 = AtomicU64::new(1);
NEXT.fetch_add(1, Ordering::Relaxed)
}
#[derive(Clone, Debug, Default)]
struct Chunk {
id: u32,
@@ -31,19 +24,11 @@ pub struct EntityStore {
shards: Vec<Arc<HashMap<Handle, u32>>>,
len: usize,
next_chunk: u32,
/// This state of the entities ([`EntityStore::content_token`]). Not part of [`PartialEq`].
token: u64,
}
impl Default for EntityStore {
fn default() -> Self {
EntityStore {
chunks: Vec::new(),
shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(),
len: 0,
next_chunk: 0,
token: next_token(),
}
EntityStore { chunks: Vec::new(), shards: (0..SHARDS).map(|_| Arc::new(HashMap::new())).collect(), len: 0, next_chunk: 0 }
}
}
@@ -62,17 +47,6 @@ impl EntityStore {
pub fn new() -> Self {
Self::default()
}
/// A number for this state of the entities: a clone has it too, and every edit gives the
/// store a number no store has had, so two stores with one token hold the same entities in
/// the same order. What is derived from the entities (a block's ATTDEFs by tag) can be kept
/// under it. Not part of [`PartialEq`]: equal stores can have different tokens.
pub fn content_token(&self) -> u64 {
self.token
}
/// The entities are about to change: a new token.
fn edited(&mut self) {
self.token = next_token();
}
pub fn len(&self) -> usize {
self.len
}
@@ -127,7 +101,6 @@ impl EntityStore {
self.replace(e);
return;
}
self.edited();
let needs_new = self.chunks.last().is_none_or(|c| c.items.len() >= CHUNK_MAX);
if needs_new {
let c = self.new_chunk();
@@ -147,7 +120,6 @@ impl EntityStore {
self.replace(e);
return;
}
self.edited();
let needs_new = self.chunks.first().is_none_or(|c| c.items.len() >= CHUNK_MAX);
if needs_new {
let c = self.new_chunk();
@@ -165,7 +137,6 @@ impl EntityStore {
pub fn replace(&mut self, e: Entity) -> bool {
let Some(id) = self.chunk_id(e.handle) else { return false };
let Some(pos) = self.chunk_pos(id) else { return false };
self.edited();
let Some(c) = self.chunks.get_mut(pos) else { return false };
let chunk = Arc::make_mut(c);
if let Some(slot) = chunk.items.iter_mut().find(|x| x.handle == e.handle) {
@@ -178,7 +149,6 @@ impl EntityStore {
pub fn remove(&mut self, h: Handle) -> Option<Arc<Entity>> {
let id = self.chunk_id(h)?;
let pos = self.chunk_pos(id)?;
self.edited();
let c = self.chunks.get_mut(pos)?;
let chunk = Arc::make_mut(c);
let i = chunk.items.iter().position(|x| x.handle == h)?;
@@ -195,7 +165,6 @@ impl EntityStore {
pub fn modify<F: FnOnce(&mut Entity)>(&mut self, h: Handle, f: F) -> bool {
let Some(id) = self.chunk_id(h) else { return false };
let Some(pos) = self.chunk_pos(id) else { return false };
self.edited();
let Some(c) = self.chunks.get_mut(pos) else { return false };
let chunk = Arc::make_mut(c);
match chunk.items.iter_mut().find(|x| x.handle == h) {
@@ -250,7 +219,6 @@ impl EntityStore {
self.push(Arc::unwrap_or_clone(e));
return false;
};
self.edited();
let Some(c) = self.chunks.get_mut(pos) else {
// Unreachable in practice too; never lose the object.
self.push(Arc::unwrap_or_clone(e));
@@ -329,47 +297,6 @@ mod tests {
Entity::new(Handle(h), EntityKind::Point(Point { p: Vec2::new(h as f64, 0.0).to3(0.0), angle: 0.0 }))
}
/// One token per state of the entities: shared by clones, new after every kind of edit, and
/// different for copies edited apart (#1660's ATTDEF index is kept by it).
#[test]
fn a_content_token_names_one_state_of_the_entities() {
let mut a = EntityStore::new();
for h in 1..=3 {
a.push(ent(h));
}
assert_eq!(a.clone().content_token(), a.content_token(), "a clone holds the same entities");
let (mut b, mut c) = (a.clone(), a.clone());
assert!(b.modify(Handle(1), |e| e.common.layer = "B".into()));
assert!(c.modify(Handle(1), |e| e.common.layer = "C".into()));
assert_ne!(b.content_token(), c.content_token(), "copies edited apart");
assert_ne!(b.content_token(), a.content_token());
let edits: [fn(&mut EntityStore); 8] = [
|s| s.push(ent(9)),
|s| s.push_front(ent(8)),
|s| {
s.replace(ent(2));
},
|s| {
s.remove(Handle(3));
},
|s| {
s.bring_to_front(Handle(1));
},
|s| {
s.send_to_back(Handle(2));
},
|s| {
s.move_next_to(Handle(1), Handle(2), true);
},
|s| s.sort_by_key(|e| std::cmp::Reverse(e.handle.0)),
];
for (i, edit) in edits.iter().enumerate() {
let mut s = a.clone();
edit(&mut s);
assert_ne!(s.content_token(), a.content_token(), "edit {i}");
}
}
#[test]
fn push_get_remove() {
let mut s = EntityStore::new();
+3 -7
View File
@@ -1076,13 +1076,9 @@ fn many_attributes_and_definitions_are_matched_without_comparing_every_pair() {
let EntityKind::Insert(mut ins) = plain_insert("B") else { panic!("an insert") };
ins.attribs = (0..N).map(|i| plain_attrib(&tag('A', i))).collect();
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let (bounds, cross_probes) = crate::TagKey::with_cross_probes(1000, || d.extents(&Space::Model));
assert!(!bounds.is_empty());
// Layer inheritance and the constant-value filter each query the opposite set.
// With no matches, an unindexed scan bypasses the probe (zero) or compares every pair.
for probes in cross_probes {
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {cross_probes:?}");
}
let t = std::time::Instant::now();
assert!(!d.extents(&Space::Model).is_empty());
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
}
/// Looking a layer or a block up by name does not scan the table: a file of N layers, or of N
-6
View File
@@ -280,9 +280,6 @@ impl DocState {
self.view_history.clear();
self.block_edit = Some(be);
self.revision += 1;
// The editor's drawing is another drawing with the host's handles: a name given in the
// host must not resolve in it (BCLOSE ends the editor's names the same way, #1660).
self.expire_names();
}
/// Save the Block Editor's objects into the block (BSAVE), or into a new block `as_name`
@@ -349,9 +346,6 @@ impl DocState {
self.views = host.views;
self.view_history = host.view_history;
self.revision += 1;
// The editor's drawing shares the host's handles: a name given in it must never resolve
// to a host record (or the other way round) after the drawing comes back.
self.expire_names();
Ok(())
}
}
+2 -4
View File
@@ -117,10 +117,8 @@ fn run_recover(s: &mut Session, p: &Value) -> Result<Value> {
let st = s.state_mut()?;
let report = crate::audit::fix(Arc::make_mut(&mut st.doc));
if report.issues.is_empty() {
// Nothing to fix: the drawing opens unchanged, like OPEN. `fix` may already
// have copied it, so put the saved one back; no record name exists yet.
let saved = st.saved.clone();
st.restore_drawing(saved);
// Nothing to fix: the drawing opens unchanged, like OPEN.
st.doc = st.saved.clone();
}
if copy && !st.is_dirty() {
// An unsaved copy (Drawing Recovery): closing it asks to save it under a name.
+1 -76
View File
@@ -104,17 +104,12 @@ pub(super) fn synced(blk: &Block, defs: &[&Attrib], ins: &Insert) -> Vec<Attrib>
let m = ins.transform(blk.base.xy());
// The reference's attributes by tag, gathered once for all the definitions (#1923).
let carried = ins.attribs_by_tag();
#[cfg(test)]
let carried = carried.into_iter().map(|(tag, attrib)| (tests::MeasuredTag(tag), attrib)).collect::<std::collections::BTreeMap<_, _>>();
defs.iter()
.map(|ad| {
let mut k = EntityKind::Text(ad.text.clone());
k.transform(&m);
let mut t = if let EntityKind::Text(t) = k { t } else { ad.text.clone() };
let key = TagKey(&ad.tag);
#[cfg(test)]
let key = tests::MeasuredTag(key);
t.value = carried.get(&key).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
t.value = carried.get(&TagKey(&ad.tag)).map_or_else(|| ad.text.value.clone(), |a| a.text.value.clone());
Attrib {
tag: ad.tag.clone(),
text: t,
@@ -209,8 +204,6 @@ pub(super) fn sync(s: &mut Session, name: &str) -> Result<(String, usize)> {
let defs = attdefs(&blk);
let d = s.doc_mut()?;
let n = update_references(d, &blk.name, |ins| ins.attribs = synced(&blk, &defs, ins));
// The references have new ATTRIBs: names given to the old ones hold no longer (#1660).
s.state_mut()?.expire_names();
Ok((blk.name.clone(), n))
}
@@ -366,74 +359,6 @@ impl Interactive for AttsyncM {
mod tests {
use super::*;
std::thread_local! {
static SYNC_CROSS_PROBES: std::cell::Cell<Option<usize>> = const { std::cell::Cell::new(None) };
}
/// Use the actual tag ordering and count only probes between different fixture sets.
pub(super) struct MeasuredTag<'a>(pub(super) TagKey<'a>);
impl MeasuredTag<'_> {
fn record(&self, other: &Self) {
let TagKey(left) = self.0;
let TagKey(right) = other.0;
let sides = (left.as_bytes().first(), right.as_bytes().first());
if matches!(sides, (Some(b'A'), Some(b'D')) | (Some(b'D'), Some(b'A'))) {
SYNC_CROSS_PROBES.with(|count| count.set(count.get().map(|n| n + 1)));
}
}
}
impl PartialEq for MeasuredTag<'_> {
fn eq(&self, other: &Self) -> bool {
self.record(other);
self.0 == other.0
}
}
impl Eq for MeasuredTag<'_> {}
impl PartialOrd for MeasuredTag<'_> {
fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
Some(self.cmp(other))
}
}
impl Ord for MeasuredTag<'_> {
fn cmp(&self, other: &Self) -> std::cmp::Ordering {
self.record(other);
self.0.cmp(&other.0)
}
}
#[test]
fn sync_uses_indexed_cross_set_tag_matching() {
const N: usize = 512;
let mut s = Session::new();
s.execute("attdef", &json!({"tag":"T", "default":"d", "at":[0, 1], "height":1.0})).unwrap();
s.execute("line", &json!({"points":[[0, 0], [10, 0]]})).unwrap();
let ids: Vec<_> = s.doc().unwrap().model.iter().map(|e| e.handle.hex()).collect();
s.execute("block", &json!({"name":"B", "base":[0, 0], "keep":"delete", "handles":ids})).unwrap();
let added = s.execute("insert", &json!({"name":"B", "at":[0, 0], "attribs":{"T":"v"}})).unwrap();
let handle = Handle::parse_hex(added["handle"].as_str().unwrap()).unwrap();
let doc = s.doc().unwrap();
let blk = doc.block("B").unwrap();
let base = (*attdefs(blk)[0]).clone();
let EntityKind::Insert(mut ins) = doc.entity(handle).unwrap().kind.clone() else { panic!("insert expected") };
let value = ins.attribs[0].clone();
let defs: Vec<_> = (0..N).map(|i| Attrib { tag: format!("D{i:05}"), ..base.clone() }).collect();
let defs: Vec<_> = defs.iter().collect();
ins.attribs = (0..N).map(|i| Attrib { tag: format!("A{i:05}"), ..value.clone() }).collect();
SYNC_CROSS_PROBES.with(|count| count.set(Some(0)));
let result = synced(blk, &defs, &ins);
let probes = SYNC_CROSS_PROBES.with(|count| count.replace(None).unwrap());
assert_eq!(result.len(), N);
assert!(result.iter().all(|a| a.text.value == "d"));
// No cross-set comparisons means this lookup was bypassed, whereas a scan does N*N.
assert!((N..N * N / 8).contains(&probes), "expected indexed cross-set work, got {probes}");
}
#[test]
fn attdisp_keywords_map_to_attmode() {
assert_eq!([attmode("Normal"), attmode("on"), attmode("OFF"), attmode("x")], [Some(1), Some(2), Some(0), None]);
@@ -81,8 +81,6 @@ fn replace(s: &mut Session, old: &str, new: &str, purge: bool) -> Result<(usize,
});
let key = d.blocks.keys().find(|k| k.eq_ignore_ascii_case(&old)).cloned();
let purged = purge && !referenced(d, &old) && key.is_some_and(|k| d.blocks.remove(&k).is_some());
// Replaced references have new ATTRIBs: names given to the old ones hold no longer (#1660).
s.state_mut()?.expire_names();
Ok((n, purged))
}
+1 -1
View File
@@ -1073,7 +1073,7 @@ pub(crate) fn after_command(s: &mut Session, before: &Arc<Drawing>, id: &str) ->
.iter()
.any(|store| store.iter().any(|e| !owned.contains(&e.handle) && !st.doc.entity(e.handle).is_some_and(|a| Arc::ptr_eq(a, e))));
if touched {
st.restore_drawing(before.clone());
st.doc = before.clone();
return Some("Only the working set can be edited during REFEDIT (REFSET adds objects, REFCLOSE ends the edit).".into());
}
let seed = before.handseed;
+27 -3
View File
@@ -48,7 +48,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("preview", "Plot Preview", run_preview)
.menu(&["File", "Plot Preview"])
.alias(&["pre"])
.params("{layout?: current|\"Model\", paper?, landscape?, fit?, scale?, lineweights?, plotTransparency?, width?: pixels (default 1200)} → {data: base64 PNG, width, height, layout, paper}")
.params("{layout?: current|\"Model\", paper?, landscape?, fit?, scale?, lineweights?, plotTransparency?, width?: pixels (default 1200)} → {data: base64 PNG, width, height, layout, paper} (no plot stamp)")
.noundo(),
CommandSpec::new("publish", "Batch Publish...", run_publish)
.menu(&["File", "Batch Publish..."])
@@ -428,6 +428,9 @@ fn plot_scale(b: &Bounds2, sheet: &Sheet, fit: bool, scale: Option<f64>) -> f64
if s.is_finite() && s > 0.0 { s } else { 1.0 }
}
/// PREVIEW: a PNG of the sheet the parameters (or the layout's page setup) describe: the drawing
/// as it plots, without a plot stamp (PREVIEW takes none; the Plot dialog's preview of a stamped
/// PDF or PNG plot is a PLOT and shows it).
fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
let space = plot_space("preview", s, p)?;
let d = s.doc()?;
@@ -467,6 +470,10 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
// Curves are flattened to about half a pixel.
let est = plot_scale(&saved.window.unwrap_or_else(|| d.extents(&space)), &sheet, fit, scale);
let tol = 0.5 / (px_per_paper_unit * est);
// The plot style table the sheet plots with (the `plotStyleTable` option, else its page setup's),
// so the preview shows the printed colours, screening and lineweights.
let style_name = str_param(p, "plotStyleTable").map_or_else(|| page.plot_style_table.clone(), str::to_string);
let plot_style_table = cadcraft_doc::plot_style_table(d, &style_name).map(std::sync::Arc::new);
let ropts = cadcraft_render::Options {
tolerance: if tol.is_finite() && tol > 0.0 { tol } else { 0.01 },
min_dash: 0.0,
@@ -474,9 +481,10 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
fill: true,
lineweights,
transparency,
plot_style_table,
..Default::default()
};
let list = cadcraft_render::build_plot(d, &space, &ropts);
let mut list = cadcraft_render::build_plot(d, &space, &ropts);
let b = saved.window.unwrap_or(list.bounds);
// Paper point q shows drawing point (q - to) / k + from.
let (from, k, to) = if saved.window.is_some() {
@@ -488,6 +496,12 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
} else {
(Vec2::ZERO, plot_scale(&b, &sheet, fit, scale), Vec2::ZERO)
};
// A saved window shows only what is inside it, as the plotters plot it.
if let Some(w) = saved.window.filter(|w| !w.is_empty()) {
list.retain_within(&cadcraft_render::pen::plot_window_reach(&w, sheet.unit_mm * k));
}
// The table's line ends, joins and fill patterns at the plot scale, as the plotters draw them.
cadcraft_render::pen::apply(&mut list, k * sheet.unit_mm);
let world = Bounds2::new((Vec2::ZERO - to) / k + from, (sheet.size - to) / k + from);
if ![world.min.x, world.min.y, world.max.x, world.max.y].iter().all(|v| v.is_finite()) {
return Err(bad("preview", "the drawing is too large to preview at this scale"));
@@ -511,7 +525,17 @@ fn run_preview(s: &mut Session, p: &Value) -> Result<Value> {
(f64::from(x), f64::from(y))
};
let (min, max) = (sheet.printable.min, sheet.printable.max);
let (a, b) = (screen(Vec2::new(min.x, max.y)), screen(Vec2::new(max.x, min.y)));
let (mut a, mut b) = (screen(Vec2::new(min.x, max.y)), screen(Vec2::new(max.x, min.y)));
// A saved window also cuts the plot at its own edges.
if let Some(w) = saved.window.filter(|w| !w.is_empty()) {
let (x0, y1) = view.to_screen(w.min);
let (x1, y0) = view.to_screen(w.max);
a = (a.0.max(f64::from(x0)), a.1.max(f64::from(y0)));
b = (b.0.min(f64::from(x1)), b.1.min(f64::from(y1)));
if a.0 >= b.0 || a.1 >= b.1 {
(a, b) = ((0.0, 0.0), (0.0, 0.0));
}
}
cadcraft_render::raster::blank_outside_pixels(&mut pm, a, b);
}
let png = cadcraft_render::raster::encode_png(&pm).ok_or_else(|| bad("preview", "rendering the preview failed"))?;
-41
View File
@@ -108,47 +108,6 @@ pub fn entity_codec() -> Option<&'static EntityCodec> {
CODEC.get()
}
/// One record written after an entity's own, at `index` (an INSERT's ATTRIB, then its SEQEND):
/// its type name and the groups of its record, without its `0` group. AutoLISP's `entnext` and
/// `entget` reach an INSERT's attributes through it, one record at a time (the attributes have no
/// handle of their own in the drawing). Installed by the app with the DXF writer, a lower layer;
/// optional, so a host without one simply has no such records ([`EntityCodec`] is unchanged).
pub type EntitySubRecord = fn(&Drawing, &cadcraft_doc::Entity, usize) -> Option<(String, Vec<craft_dxf::Tag>)>;
static SUB_RECORD: OnceLock<EntitySubRecord> = OnceLock::new();
// This thread hid the optional provider ([`without_entity_sub_record`], tests only).
#[cfg(test)]
thread_local! {
static SUB_RECORD_HIDDEN: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
pub fn set_entity_sub_record(f: EntitySubRecord) {
let _ = SUB_RECORD.set(f);
}
pub fn entity_sub_record() -> Option<EntitySubRecord> {
#[cfg(test)]
if SUB_RECORD_HIDDEN.with(std::cell::Cell::get) {
return None;
}
SUB_RECORD.get().copied()
}
/// Run `f` as a host that did not install [`EntitySubRecord`]: `entnext` must walk the drawing's
/// entities as it did before the provider existed. Tests only.
#[cfg(test)]
pub(crate) fn without_entity_sub_record<R>(f: impl FnOnce() -> R) -> R {
struct Unhide;
impl Drop for Unhide {
fn drop(&mut self) {
SUB_RECORD_HIDDEN.with(|h| h.set(false));
}
}
SUB_RECORD_HIDDEN.with(|h| h.set(true));
let _unhide = Unhide;
f()
}
/// The drawing's non-graphic records as written (tables, BLOCK records, objects): each one's
/// type, groups after the type and role (see [`cadcraft_doc::foreign::ForeignKey`]). AutoLISP's
/// `namedobjdict`, `tblobjname` and `handent` of non-graphic objects read them (installed by the
+2 -3
View File
@@ -276,10 +276,9 @@ impl GripEdit {
}
"Undo" => match self.undo.pop() {
Some(doc) => {
// Settings changed meanwhile stay. The drawing put back is an earlier
// one: names of INSERT records end with it.
// Settings changed meanwhile stay.
let header = s.doc()?.header.clone();
s.state_mut()?.restore_drawing(doc);
s.state_mut()?.doc = doc;
s.doc_mut()?.header = header;
Ok(Step::Continue)
}
+12 -29
View File
@@ -1,11 +1,10 @@
//! HATCH, GRADIENT, BOUNDARY, REGION: boundaries from pick points or selected closed objects.
//! HATCHGENERATEBOUNDARY: polylines around existing hatches.
mod capture;
mod patfile;
pub(super) use edit::{set_pattern, takes_pattern};
pub use patfile::{PatternChoice, pattern_choices, pattern_choices_in, register_drawing_patterns};
pub(super) use patfile::{drawing_lines, run_patterns};
pub(super) use patfile::run_patterns;
pub use patfile::{PatternChoice, pattern_choices};
use cadcraft_color::Color;
use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_scale};
@@ -57,10 +56,6 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("hatchgenerateboundary", "Generate Boundary", edit::run_hatchgenerateboundary)
.params("{handles?} (a closed polyline around each boundary loop of the hatches, which stay as they are) → handles")
.interactive(|_| Ok(Box::new(SelectRun::new("hatchgenerateboundary", "HATCHGENERATEBOUNDARY")))),
CommandSpec::new("hatch.capture", "Capture hatch tile", capture::run)
.params("{first:[x,y], second:[x,y], name?:string} → {pattern, patternText}; capture line segments inside the tile in the active space")
.enabled(has_doc)
.noundo(),
CommandSpec::new("hatchpick", "Hatch Pick", pick::run_hatchpick)
.params("{points?: [[x,y]] (internal points), handles?: [hex] (closed objects)} (typed: Points, Objects, oRigin or Hatch, then the picks): the Hatch and Gradient dialog's picks, kept in the session; changes nothing")
.enabled(has_doc)
@@ -345,7 +340,6 @@ pub(crate) fn gradient_name(t: &str) -> Option<&'static str> {
#[derive(Clone)]
struct HatchSettings {
lines: Vec<cadcraft_doc::library::PatternLine>,
pattern: String,
scale: f64,
/// HPSPACE for user-defined patterns. The entity stores it as its scale.
@@ -378,10 +372,8 @@ impl HatchSettings {
angle: f64_or(p, "angle", 0.0).to_radians(),
centered: bool_or(p, "centered", true),
});
let lines = s.doc().ok().and_then(|d| drawing_lines(d, &pattern)).unwrap_or_else(|| patfile::lines_for(&pattern));
let scale = f64_or(p, "scale", hdr.1).max(1e-9);
HatchSettings {
lines,
pattern,
scale,
user_spacing: scale,
@@ -425,12 +417,12 @@ impl HatchSettings {
background: None,
// A user-defined hatch's families come from its angle, spacing and double flag, not
// from a pattern definition; any other hatch takes the loaded pattern's, if any.
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { self.lines.clone() },
pattern_lines: if user_defined { cadcraft_doc::library::user_defined_lines(self.double) } else { patfile::lines_for(&self.pattern) },
})
}
}
fn make(s: &mut Session, p: &Value, gradient: bool, loaded: &[String]) -> Result<Value> {
fn make(s: &mut Session, p: &Value, gradient: bool) -> Result<Value> {
// A zero or negative pattern scale would be clamped to a near-zero spacing.
size_param(if gradient { "gradient" } else { "hatch" }, p, "scale", false)?;
let cmd = if gradient { "gradient" } else { "hatch" };
@@ -443,10 +435,7 @@ fn make(s: &mut Session, p: &Value, gradient: bool, loaded: &[String]) -> Result
if gradient && str_param(p, "name").is_some_and(|t| gradient_name(t).is_none()) {
return Err(bad(cmd, format!("unknown gradient `name`; use one of {}", GRADIENT_NAMES.join(", "))));
}
let mut st = HatchSettings::from(s, p, gradient);
if loaded.iter().any(|n| n.eq_ignore_ascii_case(&st.pattern)) {
st.lines = patfile::lines_for(&st.pattern);
}
let st = HatchSettings::from(s, p, gradient);
// Loops by picked point or selected object: one hatch each when separate.
let mut groups: Vec<Vec<HatchLoop>> = Vec::new();
// Internal points and boundary objects can come together (the dialog's Pick points and
@@ -545,19 +534,18 @@ fn add_hatches(s: &mut Session, st: &HatchSettings, groups: Vec<Vec<HatchLoop>>)
}
fn run_hatch(s: &mut Session, p: &Value) -> Result<Value> {
let loaded = patfile::load_param(p)?;
patfile::load_param(p)?;
// Like the prompt: a name without a definition would be drawn as ANSI31.
if let Some(up) = str_param(p, "pattern").map(str::to_ascii_uppercase)
&& cadcraft_doc::library::pattern(&up).is_none()
&& patfile::user_pattern(&up).is_none()
&& drawing_lines(s.doc()?, &up).is_none()
{
return Err(bad("hatch", format!("unknown pattern {up}: not built in; load it with patternFile or patternText (a .pat file)")));
}
make(s, p, false, &loaded)
make(s, p, false)
}
fn run_gradient(s: &mut Session, p: &Value) -> Result<Value> {
make(s, p, true, &[])
make(s, p, true)
}
fn boundary_at(s: &mut Session, q: Vec2) -> Result<Vec<Handle>> {
@@ -586,9 +574,8 @@ fn run_boundary(s: &mut Session, p: &Value) -> Result<Value> {
for q in pts {
out.extend(boundary_at(s, q)?.into_iter().map(|h| h.hex()));
if out.len() > MAX_BOUNDARY_OUTPUT {
// The refused call leaves no partial result behind. Handles it gave out can
// be given again, so names of INSERT records end.
s.state_mut()?.restore_drawing(before);
// The refused call leaves no partial result behind.
s.state_mut()?.doc = before;
return Err(bad("boundary", format!("more than {MAX_BOUNDARY_OUTPUT} boundary polylines in one call; split the work")));
}
}
@@ -718,17 +705,13 @@ impl HatchM {
self.settings.double = s.last_used.hatch_double;
return Ok(true);
}
let file = patfile::typed_file(s, t);
let explicit = file.is_some();
let up = match file {
let up = match patfile::typed_file(s, t) {
// Nothing loaded from it: the pattern is asked again.
Some(n) if n.is_empty() => return Ok(false),
Some(n) => n,
None => t.to_ascii_uppercase(),
};
let local = if explicit { None } else { drawing_lines(s.doc()?, &up) };
if local.is_some() || pattern_exists(&up) {
self.settings.lines = local.unwrap_or_else(|| patfile::lines_for(&up));
if pattern_exists(&up) {
self.settings.pattern = up.clone();
// A named pattern, SOLID included, is not the user-defined one.
self.settings.double = false;
-205
View File
@@ -1,205 +0,0 @@
//! Capture a rectangular tile from the active drawing space as reusable PAT text.
use cadcraft_doc::{Drawing, EntityKind, Space, library::PatternLine};
use cadcraft_geom::Vec2;
use serde_json::{Value, json};
use crate::cmd::{bad, point_param};
use crate::{Result, Session};
const COMMAND: &str = "hatch.capture";
pub(super) fn run(s: &mut Session, p: &Value) -> Result<Value> {
let corner = |key| point_param(p, key).filter(|q| q.is_finite()).ok_or_else(|| bad(COMMAND, format!("give a finite {key} point [x,y]")));
let a = corner("first")?;
let b = corner("second")?;
let name = match p.get("name") {
None => "CAPTURED_TILE",
Some(v) => v.as_str().ok_or_else(|| bad(COMMAND, "name must be a string"))?,
}
.trim()
.to_ascii_uppercase();
if name.is_empty()
|| name.len() > 31
|| !name.bytes().all(|c| c.is_ascii_alphanumeric() || c == b'_')
|| cadcraft_doc::library::is_reserved_pattern_name(&name)
{
return Err(bad(COMMAND, "use a custom pattern name of 1 to 31 letters, digits or underscores"));
}
let lines = capture_lines(s.doc()?, &s.space(), a, b).map_err(|e| bad(COMMAND, e))?;
let mut text = format!("*{name}, Custom pattern\n");
for line in lines {
text.push_str(&format!("{},{},{},{},{}", line.angle, line.origin.0, line.origin.1, line.delta.0, line.delta.1));
for dash in line.dashes {
text.push_str(&format!(",{dash}"));
}
text.push('\n');
}
Ok(json!({"pattern": name, "patternText": text}))
}
/// A PAT family repeats along an integer combination of the two tile edges.
/// The perpendicular neighbour is a second combination with determinant one.
fn captured_family(start: Vec2, end: Vec2, u: Vec2, v: Vec2, m: i32, n: i32) -> PatternLine {
let along = u * f64::from(m) + v * f64::from(n);
let period = along.len();
let dir = along / period;
// Extended Euclid: a*m + b*n = 1, so the neighbour is -b*u + a*v.
let (mut r, mut t) = (m, n);
let (mut a, mut b, mut c, mut d) = (1, 0, 0, 1);
while t != 0 {
let k = r / t;
(r, t) = (t, r % t);
(a, c) = (c, a - k * c);
(b, d) = (d, b - k * d);
}
let neighbour = (v * f64::from(a) - u * f64::from(b)) / f64::from(r);
let len = start.dist(end);
PatternLine {
origin: (start.x, start.y),
angle: dir.y.atan2(dir.x).to_degrees(),
delta: (neighbour.dot(dir), u.cross(v) / period),
dashes: if len >= period { Vec::new() } else { vec![len, len - period] },
}
}
fn capture_lines(d: &Drawing, space: &Space, a: Vec2, b: Vec2) -> std::result::Result<Vec<PatternLine>, &'static str> {
let low = Vec2::new(a.x.min(b.x), a.y.min(b.y));
let w = (a.x - b.x).abs();
let h = (a.y - b.y).abs();
if !w.is_finite() || !h.is_finite() || w < 1e-9 || h < 1e-9 {
return Err("Pick two opposite corners for the tile");
}
let entities = || d.space(space).into_iter().flat_map(|store| store.iter()).filter(|entity| d.is_visible(entity));
let (mut origin, mut u, mut v) = (low, Vec2::new(w, 0.), Vec2::new(0., h));
let mut guides = Vec::new();
for entity in entities() {
let EntityKind::LwPolyline(p) = &entity.kind else { continue };
if !p.closed || p.vertices.len() != 4 || p.vertices.iter().any(|q| q.bulge != 0.) {
continue;
}
let mut corners = [None; 4];
let mut order = [0usize; 4];
for (index, vertex) in p.vertices.iter().enumerate() {
let q = vertex.p;
let right = q.x > low.x + w / 2.;
let top = q.y > low.y + h / 2.;
let target = low + Vec2::new(if right { w } else { 0. }, if top { h } else { 0. });
if (q.x - target.x).abs() <= w * 0.002 && (q.y - target.y).abs() <= h * 0.002 {
order[index] = usize::from(right) + 2 * usize::from(top);
corners[order[index]] = Some(q);
}
}
if let [Some(bl), Some(br), Some(tl), Some(tr)] = corners
&& order.iter().zip(order.iter().cycle().skip(1)).all(|(a, b)| (a ^ b).count_ones() == 1)
&& (bl + (br - bl) + (tl - bl)).dist(tr) < w.min(h) * 1e-8
{
(origin, u, v) = (bl, br - bl, tl - bl);
guides.push(entity.handle);
}
}
let area = u.cross(v);
let coords = |p: Vec2| Vec2::new(p.cross(v) / area, u.cross(p) / area);
let world = |p: Vec2| u * p.x + v * p.y;
let mut families = Vec::new();
let mut add = |a: Vec2, b: Vec2, grid: bool| -> std::result::Result<(), &'static str> {
let (mut start, mut end) = (a - origin, b - origin);
let (s, e) = (coords(start), coords(end));
let inside = |q: Vec2| (-1e-8..=1.00000001).contains(&q.x) && (-1e-8..=1.00000001).contains(&q.y);
if !inside(s) || !inside(e) || start == end {
return Ok(());
}
let delta = e - s;
// Simple LINE geometry retains its original coordinates and short dash period.
let simple = if delta.x.abs() < 1e-14 {
Some((0, delta.y.signum() as i32))
} else {
(1..=128).find_map(|m| {
let m = m * delta.x.signum() as i32;
let n = f64::from(m) * delta.y / delta.x;
(n.abs() <= 128. && (n - n.round()).abs() < 1e-10).then_some((m, n.round() as i32))
})
};
let (mut m, mut n) = if let Some(dir) = simple.filter(|_| !grid) {
dir
} else {
// Shared vertices round identically, including on neighbouring tiles.
let snap = |p: Vec2| Vec2::new((p.x * 2048.).round(), (p.y * 2048.).round());
let (s, e) = (snap(s), snap(e));
if s == e {
return Err("A segment is too small for the tile capture precision.");
}
start = world(s / 2048.);
end = world(e / 2048.);
((e.x - s.x) as i32, (e.y - s.y) as i32)
};
if m < 0 || (m == 0 && n < 0) {
std::mem::swap(&mut start, &mut end);
(m, n) = (-m, -n);
}
let (mut gcd, mut k) = (m.abs(), n.abs());
while k != 0 {
(gcd, k) = (k, gcd % k);
}
if gcd != 0 {
families.push(captured_family(start, end, u, v, m / gcd, n / gcd));
}
Ok(())
};
for entity in entities() {
match &entity.kind {
EntityKind::Line(l) => add(l.a.xy(), l.b.xy(), false)?,
EntityKind::LwPolyline(p) if !guides.contains(&entity.handle) => {
for (i, vertex) in p.vertices.iter().enumerate() {
let next = p.vertices.get(i + 1).or_else(|| if p.closed { p.vertices.first() } else { None });
if let Some(next) = next
&& vertex.bulge == 0.
{
add(vertex.p, next.p, true)?;
}
}
}
_ => {}
}
}
if families.is_empty() {
return Err("No complete line segments in the selected tile.");
}
Ok(families)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn capture_l_from_drawing_without_a_dialog() {
let mut s = Session::new();
s.execute("rectang", &json!({"p1":[30,40], "p2":[40,50]})).unwrap();
for (a, b) in [([32, 42], [35, 42]), ([32, 42], [32, 46]), ([50, 60], [57, 60])] {
s.execute("line", &json!({"points":[a,b]})).unwrap();
}
// An almost coincident hidden guide would shift the origin if it were used.
let guide = s.execute("rectang", &json!({"p1":[30.01,40.01],"p2":[40.01,50.01]})).unwrap();
s.execute("hideobjects", &json!({"handles":[guide["handle"]]})).unwrap();
s.execute("layer.new", &json!({"name":"Hidden detail","current":true})).unwrap();
s.execute("line", &json!({"points":[[33,43],[36,43]]})).unwrap();
let detail = s.doc().unwrap().model.iter().last().unwrap().handle.hex();
s.execute("layer.current", &json!({"name":"0"})).unwrap();
s.execute("layoff", &json!({"handles":[detail]})).unwrap();
let result = s.execute(COMMAND, &json!({"first":[40,50],"second":[30,40],"name":"HEADLESS_L"})).unwrap();
let dest = s.execute("rectang", &json!({"p1":[0,0],"p2":[30,20]})).unwrap();
let mut apply = result;
apply["handles"] = json!([dest["handle"]]);
s.execute("hatch", &apply).unwrap();
let drawing = s.doc().unwrap();
let hatch = drawing.model.iter().find_map(|e| if let EntityKind::Hatch(h) = &e.kind { Some(h) } else { None }).unwrap();
assert_eq!(hatch.pattern, "HEADLESS_L");
assert_eq!(hatch.pattern_lines.len(), 2, "frame and exterior segment excluded");
for (angle, ink) in [(0., 3.), (90., 4.)] {
let line = hatch.pattern_lines.iter().find(|l| (l.angle - angle).abs() < 1e-8).unwrap();
assert_eq!(line.origin, (2., 2.));
assert_eq!(line.dashes, vec![ink, ink - 10.]);
assert!((line.delta.1 - 10.).abs() < 1e-8);
}
}
}
+6 -16
View File
@@ -195,9 +195,9 @@ fn separate(s: &mut Session, handle: Handle) -> Result<Vec<Handle>> {
}
/// Pattern, scale and angle (degrees) from the parameters.
fn properties(h: &mut Hatch, p: &Value, local: Option<&[cadcraft_doc::library::PatternLine]>) {
fn properties(h: &mut Hatch, p: &Value) {
if let Some(v) = str_param(p, "pattern") {
set_pattern(h, v, local);
set_pattern(h, v);
}
if let Some(x) = p.get("scale").and_then(Value::as_f64).filter(|x| x.is_finite() && *x > 0.0) {
h.scale = x;
@@ -222,12 +222,11 @@ pub(crate) fn takes_pattern(h: &Hatch, name: &str) -> bool {
/// Give `h` the pattern called `name` (HATCHEDIT's and Properties' pattern edit); false, and
/// nothing changes, for a blank name or one the hatch can't take ([`takes_pattern`]).
pub(crate) fn set_pattern(h: &mut Hatch, name: &str, local: Option<&[cadcraft_doc::library::PatternLine]>) -> bool {
pub(crate) fn set_pattern(h: &mut Hatch, name: &str) -> bool {
let name = name.trim();
if name.is_empty() || (local.is_none() && !takes_pattern(h, name)) {
if name.is_empty() || !takes_pattern(h, name) {
return false;
}
let keep_lines = h.pattern.eq_ignore_ascii_case(name) && !h.pattern_lines.is_empty();
h.pattern = name.to_ascii_uppercase();
h.solid = h.pattern == "SOLID";
// A named pattern, SOLID included, replaces the gradient fill; the renderer draws the
@@ -238,10 +237,6 @@ pub(crate) fn set_pattern(h: &mut Hatch, name: &str, local: Option<&[cadcraft_do
// any other name is the hatch's own and keeps its definition.
if cadcraft_doc::library::pattern(&h.pattern).is_some() {
h.pattern_lines.clear();
} else if keep_lines {
return true;
} else if let Some(lines) = local {
h.pattern_lines = lines.to_vec();
} else if let Some(user) = super::patfile::user_pattern(&h.pattern) {
h.pattern_lines = user.lines;
}
@@ -484,9 +479,7 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result<Value> {
}
// Like the prompt: a pattern must be one CADCraft defines, SOLID, or the hatches' own (a
// pattern read from a file keeps its definition).
let local = str_param(p, "pattern").and_then(|n| super::drawing_lines(s.doc().ok()?, n.trim()));
if let Some(up) = str_param(p, "pattern").map(|v| v.trim().to_ascii_uppercase()).filter(|v| !v.is_empty())
&& local.is_none()
&& !defined_pattern(&up)
{
let d = s.doc()?;
@@ -514,7 +507,7 @@ pub(super) fn run_hatchedit(s: &mut Session, p: &Value) -> Result<Value> {
notes.push(format!("Hatch {}: {missing} new boundary loop(s) could not be linked; it is now non-associative.", handle.hex()));
}
}
properties(&mut h, p, local.as_deref());
properties(&mut h, p);
if let Some(g) = &grad {
g.apply(&mut h);
}
@@ -727,10 +720,7 @@ impl Interactive for HatchEditM {
(Ask::Pattern, _) => {
if let Some(t) = text.filter(|t| !t.is_empty()) {
let up = t.to_ascii_uppercase();
if cadcraft_doc::library::pattern(&up).is_none()
&& super::patfile::user_pattern(&up).is_none()
&& super::drawing_lines(s.doc()?, &up).is_none()
{
if cadcraft_doc::library::pattern(&up).is_none() && super::patfile::user_pattern(&up).is_none() {
s.echo(format!("Unknown pattern {up}."));
return Ok(Step::Continue);
}
+5 -54
View File
@@ -9,7 +9,7 @@
use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
use cadcraft_doc::library::files::{UserPattern, parse_pat};
use cadcraft_doc::library::{PatternLine, is_reserved_pattern_name, standard_patterns};
use cadcraft_doc::library::{PatternLine, pattern, standard_patterns};
use serde_json::{Value, json};
use super::super::helpers::support_text;
@@ -38,7 +38,7 @@ pub(crate) fn user_pattern_name(name: &str) -> Option<String> {
/// The line families a new hatch of pattern `name` carries: a user pattern's, else none (the
/// library's patterns are drawn and saved from the library).
pub(crate) fn lines_for(name: &str) -> Vec<PatternLine> {
if is_reserved_pattern_name(name) {
if pattern(name).is_some() {
return Vec::new();
}
user_pattern(name).map(|p| p.lines).unwrap_or_default()
@@ -70,54 +70,6 @@ pub fn pattern_choices() -> Vec<PatternChoice> {
v
}
fn embedded(d: &cadcraft_doc::Drawing) -> impl Iterator<Item = &cadcraft_doc::Hatch> {
let stores = std::iter::once(&d.model)
.chain(d.layouts.iter().map(|l| &l.entities))
.chain(d.blocks.values().filter(|b| b.xref_path.is_none()).map(|b| &b.entities));
stores.flat_map(|s| s.iter()).filter_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Hatch(h) if !h.pattern_lines.is_empty() => Some(h),
_ => None,
})
}
pub(crate) fn drawing_lines(d: &cadcraft_doc::Drawing, name: &str) -> Option<Vec<PatternLine>> {
if is_reserved_pattern_name(name) {
return None;
}
embedded(d).find(|h| h.pattern.eq_ignore_ascii_case(name)).map(|h| h.pattern_lines.clone())
}
/// An embedded definition takes precedence over the session library in its own drawing.
pub fn pattern_choices_in(d: &cadcraft_doc::Drawing) -> Vec<PatternChoice> {
let mut choices = pattern_choices();
let mut seen = std::collections::HashSet::new();
for h in embedded(d) {
if !seen.insert(h.pattern.to_ascii_uppercase()) || is_reserved_pattern_name(&h.pattern) {
continue;
}
if let Some(c) = choices.iter_mut().find(|c| c.name.eq_ignore_ascii_case(&h.pattern)) {
c.lines.clone_from(&h.pattern_lines);
} else {
choices.push(PatternChoice { name: h.pattern.clone(), description: String::new(), lines: h.pattern_lines.clone() });
}
}
choices
}
/// Make embedded custom definitions available when opening the hatch manager in an older drawing.
pub fn register_drawing_patterns(d: &cadcraft_doc::Drawing) {
let mut user = store();
let mut known: std::collections::HashSet<_> = user.iter().map(|p| p.name.to_ascii_uppercase()).collect();
for h in embedded(d) {
if user.len() >= MAX_USER_PATTERNS {
break;
}
if !h.pattern_lines.is_empty() && known.insert(h.pattern.to_ascii_uppercase()) && !is_reserved_pattern_name(&h.pattern) {
user.push(UserPattern { name: h.pattern.clone(), description: String::new(), lines: h.pattern_lines.clone() });
}
}
}
/// Add the patterns of a `.pat` file's text (a pattern loaded before under the same name is
/// replaced). Returns the names added and the file's problems.
pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
@@ -126,7 +78,7 @@ pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
let mut added = Vec::new();
let mut user = store();
for p in parsed.items {
if is_reserved_pattern_name(&p.name) {
if pattern(&p.name).is_some() {
warnings.push(format!("{} is a built-in pattern; the built-in definition is kept", p.name));
continue;
}
@@ -145,15 +97,14 @@ pub(crate) fn load(text: &str) -> (Vec<String>, Vec<String>) {
}
/// Load the pattern file a HATCH call names (`patternFile` path or `patternText` contents).
pub(super) fn load_param(p: &Value) -> Result<Vec<String>> {
pub(super) fn load_param(p: &Value) -> Result<()> {
if let Some((text, source)) = support_text("hatch", p, "patternFile", "patternText")? {
let (added, warnings) = load(&text);
if added.is_empty() {
return Err(bad("hatch", format!("no hatch pattern could be read from {source}: {}", warnings.join("; "))));
}
return Ok(added);
}
Ok(Vec::new())
Ok(())
}
/// A `.pat` file typed at HATCH's pattern prompt: load it and return the pattern to use (the
+2 -21
View File
@@ -14,7 +14,7 @@ use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
pub(crate) const MAX_PICKS: usize = 1000;
/// The first prompt's keywords: what to pick.
const MODES: [&str; 5] = ["Points", "Objects", "oRigin", "Hatch", "TileRect"];
const MODES: [&str; 4] = ["Points", "Objects", "oRigin", "Hatch"];
/// What HATCHPICK picks.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
@@ -22,8 +22,6 @@ pub enum PickMode {
/// Internal points, each inside a closed boundary.
#[default]
Points,
/// Two opposite corners of a rectangular custom-pattern tile.
TileRect,
/// Closed boundary objects.
Objects,
/// One point: the pattern origin.
@@ -46,7 +44,6 @@ pub struct HatchPicks {
fn mode_named(t: &str) -> Option<PickMode> {
Some(match t.trim().to_ascii_lowercase().as_str() {
"points" | "p" => PickMode::Points,
"tilerect" | "tile" => PickMode::TileRect,
"objects" | "o" => PickMode::Objects,
"origin" | "r" => PickMode::Origin,
"hatch" | "h" => PickMode::Hatch,
@@ -137,10 +134,6 @@ impl Interactive for HatchPickM {
match self.mode {
None => Prompt::new("Enter what to pick", Accept::TEXT).kw(&MODES),
Some(PickMode::Points) => Prompt::new("Pick internal point", Accept::POINT).kw(&["Undo"]),
Some(PickMode::TileRect) => {
Prompt::new(if self.picks.is_empty() { "Pick first corner of tile" } else { "Pick opposite corner of tile" }, Accept::POINT)
.kw(&["Undo"])
}
Some(PickMode::Objects) => Prompt::new("Select objects", Accept::SELECT).kw(&["Undo"]),
Some(PickMode::Origin) => Prompt::new("Specify the pattern origin", Accept::POINT),
Some(PickMode::Hatch) => Prompt::new("Select hatch object", Accept::SELECT),
@@ -157,13 +150,12 @@ impl Interactive for HatchPickM {
};
match (mode, i) {
(_, Input::Cancel) => Ok(Step::Cancel),
(PickMode::Points | PickMode::TileRect | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => {
(PickMode::Points | PickMode::Objects, Input::Keyword(k)) if k == "Undo" => {
if self.picks.pop().is_none() {
s.echo("Nothing to undo.");
}
Ok(Step::Continue)
}
(PickMode::TileRect, Input::Enter) => Ok(Step::Continue),
(PickMode::Points | PickMode::Objects, Input::Enter) => {
self.keep(s, mode);
Ok(Step::Done)
@@ -182,17 +174,6 @@ impl Interactive for HatchPickM {
}
Ok(Step::Continue)
}
(PickMode::TileRect, Input::Point(q)) => {
if self.count() < 2 {
self.picks.push(Pick::Point(q, Vec::new()));
}
if self.count() >= 2 {
self.keep(s, mode);
Ok(Step::Done)
} else {
Ok(Step::Continue)
}
}
(PickMode::Objects, Input::Pick(hs)) => {
let room = MAX_PICKS.saturating_sub(self.count());
let closed: Vec<Handle> = {
+120 -6
View File
@@ -18,6 +18,7 @@ mod plotstyle;
mod prompts;
mod viewports;
/// The layout, page setup, viewport and plot commands.
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("layout", "Layout", run_layout)
@@ -82,13 +83,13 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("pagesetup", "Page Setup Manager...", run_pagesetup)
.menu(&["File", "Page Setup Manager..."])
.params(
"{layout?: current, device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
"{layout?: current | layouts?: [names] | \"all\" (the same changes to each, in one step), device?: plotter name (PLOTTERMANAGER) | \"None\", paper?: the device's paper | \"A4\"|\"A3\"|\"Letter\"|\"ANSI B\"|\"B4 (JIS)\"|\"Japanese Postcard\"|…, width?, height? (mm), landscape?, paperUnits?: \"mm\"|\"inches\" (one paper-space unit on the layout), margins?: [l,b,r,t] mm, lineweights?, plotArea?, scale?, scaleToFit?, center?, plotStyleTable?: \"monochrome.ctb\"|\"grayscale.ctb\"|\"default.ctb\"|\"None\"|…, displayPlotStyles?: bool, plotTransparency?: bool}",
),
CommandSpec::new("plot", "Print...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "plot")?, "plot"))
.menu(&["File", "Print..."])
.key("Cmd+P")
.alias(&["print"])
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]]} (typed or from the menu: the Plot dialog)")
.params("{path? (else returns base64 `data`), layout?: current|\"Model\", device?: \"CADCraft PDF\"|\"CADCraft PNG\"|\"CADCraft SVG\" | a plotter from PLOTTERMANAGER | a system printer (then printed: `copies`?: 1..999, and the reply is the `job`; with `path` the PDF is also written there first: plot to file) | \"None\" (default: a layout's page setup device; Model, or \"None\": no device, PDF; a device sets the output format and the papers), paper?: the device's paper (default: a layout keeps its page setup's; Model takes the device's default), landscape?, fit?: bool, scale?: number | \"1:50\", center?: bool (Model, default true), offset?: [x,y] mm (Model, when center is false; each within ±100000), lineweights?: bool, plotTransparency?: bool (default: the page setup's; PLOTTRANSPARENCYOVERRIDE 0/2 overrides it), plotArea?: extents|display|limits|window (Model) | layout, window?: [[x1,y1],[x2,y2]], stamp?: true | text (a plot stamp at the printable area's lower-left corner; `{drawing}`, `{layout}`, `{device}`, `{paper}` and `{scale}` are filled in; true: \"{drawing}, {layout}, {device}, {paper}, {scale}\")} (typed or from the menu: the Plot dialog)")
.noundo(),
CommandSpec::new("exportpdf", "Export to PDF...", |s, p| run_plot(s, &super::plotters::plot_options(s, p, "exportpdf")?, "exportpdf"))
.menu(&["File", "Export to PDF..."])
@@ -696,6 +697,7 @@ fn viewport_json(h: Handle, v: &Viewport) -> Value {
/// VPLAYER's command-line prompts.
mod vplayer;
/// VIEWPORT.SET: change the scale, centre, lock or frozen layers of the given viewports, or of the active one inside a viewport.
fn run_viewport_set(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "viewport.set";
let d = s.doc()?;
@@ -792,7 +794,64 @@ fn run_viewport_set(s: &mut Session, p: &Value) -> Result<Value> {
// ---------- page setup ----------
/// PAGESETUP. With `layouts` (a list of layout names, or "all") the same changes are applied to
/// each of those layouts, as one step: if any of them refuses a change, none is changed.
fn run_pagesetup(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "pagesetup";
let Some(list) = p.get("layouts").filter(|v| !v.is_null()) else { return pagesetup_one(s, p) };
if p.get("layout").is_some() {
return Err(bad(cmd, "pass `layout` or `layouts`, not both"));
}
let names: Vec<String> = match list {
Value::String(a) if a.eq_ignore_ascii_case("all") => {
let mut ls: Vec<&Layout> = s.doc()?.layouts.iter().collect();
ls.sort_by_key(|l| l.tab_order);
ls.iter().map(|l| l.name.clone()).collect()
}
Value::Array(a) => {
let mut names = Vec::new();
for n in a {
let n = n.as_str().ok_or_else(|| bad(cmd, "`layouts` must be a list of layout names or \"all\""))?;
let n = layout_name(cmd, s.doc()?, n)?;
if !names.contains(&n) {
names.push(n);
if names.len() > MAX_PLOT_SHEETS {
return Err(bad(cmd, format!("at most {MAX_PLOT_SHEETS} layouts can be selected")));
}
}
}
names
}
_ => return Err(bad(cmd, "`layouts` must be a list of layout names or \"all\"")),
};
if names.is_empty() || names.len() > MAX_PLOT_SHEETS {
return Err(bad(cmd, format!("`layouts` needs between 1 and {MAX_PLOT_SHEETS} layouts")));
}
let before = s.state()?.doc.clone();
let mut done = Vec::new();
// The options for one layout, without the selection (which may be long), copied per layout.
let mut base = p.clone();
if let Some(o) = base.as_object_mut() {
o.remove("layouts");
}
for n in &names {
let mut one = base.clone();
if let Some(o) = one.as_object_mut() {
o.insert("layout".into(), json!(n));
}
match pagesetup_one(s, &one) {
Ok(r) => done.push(r),
Err(e) => {
s.state_mut()?.doc = before;
return Err(e);
}
}
}
Ok(json!({ "layouts": done }))
}
/// PAGESETUP for one layout: the changes the options ask for, reported with the resulting page setup.
fn pagesetup_one(s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "pagesetup";
let keys = [
"device",
@@ -992,14 +1051,20 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
{
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 printer = str_param(p, "printer").map(str::trim).filter(|n| !n.is_empty());
if printer.is_some() && sheets.as_ref().is_some_and(|names| names.len() > 1) {
return Err(bad(cmd, "several sheets require PDF file output; print one sheet at a time"));
}
// A printer takes the PDF, whatever `output` says.
let is_image =
printer.is_none() && 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)?),
// 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.
// A single `layouts` entry names the sheet plotted, whatever the output: its plot area
// and window are checked against it, not against whatever space the session shows.
None => match sheets.as_deref() {
Some([only]) if is_image => {
Some([only]) => {
if only.eq_ignore_ascii_case("model") {
Space::Model
} else {
@@ -1026,6 +1091,14 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
return Err(bad(cmd, "`offset` must contain exactly two finite millimetre values within ±100000"));
}
}
// A printer takes the PDF (before the output's own checks: an SVG asked for is not what prints).
if printer.is_some()
&& let Some(o) = opts.as_object_mut()
{
o.insert("output".into(), json!("pdf"));
// Printers feed portrait sheets: a landscape plot comes already turned.
o.insert("portraitMedia".into(), json!(true));
}
if matches!(space, Space::Model)
&& opts.get("output").and_then(Value::as_str).is_some_and(|output| output.eq_ignore_ascii_case("svg"))
&& opts.get("center").and_then(Value::as_bool) == Some(false)
@@ -1050,12 +1123,53 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
if is_image && sheets.as_ref().is_some_and(|names| names.len() > 1) {
return Err(bad(cmd, "`layouts` with several sheets needs PDF output; PNG and SVG hold one sheet, so plot each layout separately"));
}
if printer.is_some() {
let d = s.doc()?;
let page = space.layout().and_then(|name| d.layout(name)).map(|l| l.page.clone()).unwrap_or_else(|| cadcraft_render::paper::model_page(d));
let (w, h) = match (opts.get("width").and_then(Value::as_f64), opts.get("height").and_then(Value::as_f64)) {
(Some(w), Some(h)) if w.is_finite() && h.is_finite() && w > 0.0 && h > 0.0 => (w, h),
_ => (page.width_mm, page.height_mm),
};
opts["printerSheetSize"] = json!([w.clamp(1.0, cadcraft_doc::MAX_PAPER_MM), h.clamp(1.0, cadcraft_doc::MAX_PAPER_MM)]);
}
let (bytes, notes) = super::file::plot_noted(hook, s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let layout = match &sheets {
Some(names) => names.first().cloned().unwrap_or_default(),
None => space.tab_name().to_string(),
};
let pages = sheets.as_ref().map_or(1, Vec::len);
if let Some(printer) = printer {
// "Plot to file" too: the PDF is written first, so a file that can't be written stops
// the plot before anything is printed (and a retry doesn't print it twice).
let mut folder = None;
let saved: Option<&str> = match str_param(p, "path") {
#[cfg(not(target_arch = "wasm32"))]
Some(path) => {
crate::file_access::check_write(path).map_err(|e| bad(cmd, e))?;
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}")))?;
Some(path)
}
_ => None,
};
let copies = p.get("copies").and_then(Value::as_u64).unwrap_or(1);
let title = format!("{} - {layout}", s.state()?.title);
let paper = str_param(p, "printerPaper").or_else(|| str_param(p, "paper")).unwrap_or_default();
// The PDF is already on disk when the printer refuses the job: say so, with its path.
let job = super::plotters::print_pdf(cmd, printer, paper, copies, &title, &bytes, &opts).map_err(|e| match (saved, e) {
(Some(path), crate::EngineError::BadParams { cmd, msg }) => {
crate::EngineError::BadParams { msg: format!("the PDF was saved to {path}, but printing failed: {msg}"), cmd }
}
(_, e) => e,
})?;
let mut r = json!({ "printer": printer, "job": job, "copies": copies.clamp(1, super::plotters::MAX_COPIES), "bytes": bytes.len(), "layout": layout, "pages": pages });
if let (Some(path), Some(o)) = (saved, r.as_object_mut()) {
o.insert("path".into(), json!(path));
}
super::file::report_new_folder(s, &mut r, folder);
super::file::report_notes(s, &mut r, notes);
return Ok(r);
}
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) => {
+72
View File
@@ -603,6 +603,78 @@ fn plot_path_extension_picks_the_format_like_export() {
std::fs::remove_dir_all(&dir).ok();
}
/// The paper name of layout `name`.
fn paper_of(s: &Session, name: &str) -> String {
s.doc().unwrap().layout(name).unwrap().page.paper.clone()
}
/// One change given to several layouts is applied to each, as one undo step.
#[test]
fn pagesetup_applies_one_change_to_several_layouts_in_one_step() {
let mut s = Session::new();
s.execute("layout.new", &json!({"name": "Sheet 3"})).unwrap();
let a1 = paper_of(&s, "Layout1");
assert_ne!(a1, "ISO A3 (420.00 x 297.00 MM)", "the test needs another starting paper");
let r = s.execute("pagesetup", &json!({"layouts": ["Layout1", "layout2"], "paper": "A3", "plotStyleTable": "monochrome.ctb"})).unwrap();
assert_eq!(r["layouts"].as_array().map(Vec::len), Some(2));
for n in ["Layout1", "Layout2"] {
let page = &s.doc().unwrap().layout(n).unwrap().page;
assert_eq!((page.width_mm.max(page.height_mm), page.plot_style_table.as_str()), (420.0, "monochrome.ctb"), "{n}");
}
assert_ne!(paper_of(&s, "Sheet 3"), paper_of(&s, "Layout1"), "a layout not named keeps its settings");
// "all" takes every layout; one undo step reverts all of it.
s.execute("pagesetup", &json!({"layouts": ["Layout1", "Layout2"], "landscape": true})).unwrap();
let pages = |s: &Session| s.doc().unwrap().layouts.iter().map(|l| (l.name.clone(), l.page.clone())).collect::<Vec<_>>();
let before = pages(&s);
assert!(before.iter().filter(|(_, p)| p.landscape).count() >= 2);
s.execute("pagesetup", &json!({"layouts": "all", "landscape": false})).unwrap();
assert!(s.doc().unwrap().layouts.iter().all(|l| !l.page.landscape));
s.undo().unwrap();
assert_eq!(pages(&s), before, "the whole change is one undo step");
}
/// A change a layout refuses leaves every layout as it was.
#[test]
fn pagesetup_for_several_layouts_is_all_or_nothing() {
let mut s = Session::new();
let before: Vec<String> = ["Layout1", "Layout2"].iter().map(|n| paper_of(&s, n)).collect();
for p in [
json!({"layouts": ["Layout1", "Nope"], "paper": "A3"}),
json!({"layouts": ["Layout1", "Layout2"], "paper": "Z12"}),
json!({"layouts": ["Layout1"], "layout": "Layout2", "paper": "A3"}),
json!({"layouts": ["Model"], "paper": "A3"}),
json!({"layouts": [], "paper": "A3"}),
json!({"layouts": "Layout1", "paper": "A3"}),
json!({"layouts": [7], "paper": "A3"}),
] {
assert!(s.execute("pagesetup", &p).is_err(), "{p}");
}
let after: Vec<String> = ["Layout1", "Layout2"].iter().map(|n| paper_of(&s, n)).collect();
assert_eq!(before, after, "a refused change leaves every layout as it was");
}
#[test]
fn pagesetup_validates_the_whole_selection_after_duplicates() {
let mut s = Session::new();
let mut names = vec![json!("Layout1"); MAX_PLOT_SHEETS + 1];
names.push(json!("Layout2"));
let r = s.execute("pagesetup", &json!({ "layouts": names, "paper": "A3" })).unwrap();
assert_eq!(r["layouts"].as_array().unwrap().len(), 2);
assert_eq!(paper_of(&s, "Layout1"), paper_of(&s, "Layout2"));
names.push(json!(17));
assert!(s.execute("pagesetup", &json!({ "layouts": names, "paper": "A4" })).is_err());
}
#[test]
fn pagesetup_rolls_back_a_change_to_an_earlier_layout() {
let mut s = Session::new();
s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == "Layout1").unwrap().page.plot_area = "window".into();
let before: Vec<_> = s.doc().unwrap().layouts.iter().map(|l| l.page.clone()).collect();
assert!(s.execute("pagesetup", &json!({ "layouts": ["Layout1", "Layout2"], "paper": "A3", "plotArea": "window" })).is_err());
let after: Vec<_> = s.doc().unwrap().layouts.iter().map(|l| l.page.clone()).collect();
assert_eq!(before, after);
}
#[test]
fn layout_set_frames_extents_away_from_origin() {
let mut s = Session::new();
+1 -4
View File
@@ -267,7 +267,7 @@ pub(crate) fn explode_with(
// pieces are copies of the block's objects and keep theirs.
let own_pieces = !matches!(e.kind, EntityKind::Insert(_));
let d = s.doc_mut()?;
let Some(removed) = d.remove_entity(*h) else { continue };
d.remove_entity(*h);
for mut p in parts {
if own_pieces {
p.common.xdata.clear();
@@ -278,9 +278,6 @@ pub(crate) fn explode_with(
st.push(p);
}
}
if !own_pieces && let Some(names) = s.record_names() {
names.erased(&removed);
}
}
s.set_selection(Vec::new());
Ok(out)
+2 -3
View File
@@ -328,10 +328,9 @@ impl Interactive for FilletM {
Input::Keyword(k) if k == "Undo" => {
match self.undo.pop() {
Some(doc) => {
// Settings changed meanwhile stay. The drawing put back is an earlier
// one: names of INSERT records end with it.
// Settings changed meanwhile stay.
let header = s.doc()?.header.clone();
s.state_mut()?.restore_drawing(doc);
s.state_mut()?.doc = doc;
s.doc_mut()?.header = header;
}
None => s.echo("Nothing to undo."),
+2 -3
View File
@@ -491,10 +491,9 @@ impl Interactive for OffsetM {
(_, Input::Keyword(k)) if k == "Undo" => {
match self.undo.pop() {
Some((doc, picked)) => {
// Settings changed meanwhile stay. The drawing put back is an earlier
// one: names of INSERT records end with it.
// Settings changed meanwhile stay.
let header = s.doc()?.header.clone();
s.state_mut()?.restore_drawing(doc);
s.state_mut()?.doc = doc;
s.doc_mut()?.header = header;
self.picked = if self.multiple { picked } else { None };
if self.picked.is_none() {
-7
View File
@@ -55,13 +55,6 @@ pub(crate) fn erase_kept(s: &mut Session, hs: &[Handle]) -> Result<usize> {
// (`refedit::after_command`), so what OOPS had stays.
let refused = taken.iter().any(|t| crate::cmd::blocks::refedit::locked(d, t.entity.handle));
if n > 0 && !refused {
// The names of the erased references' records went with them: OOPS bringing them back
// brings none back. Other references' names keep holding (#1660).
if let Some(names) = s.record_names() {
for t in &taken {
names.erased(&t.entity);
}
}
s.state_mut()?.erased = Erased(taken);
}
Ok(n)
+2 -3
View File
@@ -178,10 +178,9 @@ impl MocoroM {
fn undo(&mut self, s: &mut Session) -> Result<Step> {
match self.history.pop() {
Some((doc, base)) => {
// Settings changed meanwhile (a transparent command) stay. The drawing put
// back is an earlier one: names of INSERT records end with it.
// Settings changed meanwhile (a transparent command) stay.
let header = s.doc()?.header.clone();
s.state_mut()?.restore_drawing(doc);
s.state_mut()?.doc = doc;
if s.doc()?.header != header {
s.doc_mut()?.header = header;
}
+1 -2
View File
@@ -126,8 +126,7 @@ impl PeditM {
"reverse" | "r" => self.apply_all(s, "reverse", &json!({}))?,
"undo" | "u" => match self.mundo.pop() {
Some((d, multi, morig)) => {
// The saved drawing includes its handle seed.
s.state_mut()?.restore_drawing(std::sync::Arc::new(d));
*s.doc_mut()? = d;
self.multi = multi;
self.morig = morig;
s.set_selection(self.multi.clone());
+484 -26
View File
@@ -117,6 +117,7 @@ impl PlotterStore {
}
}
/// Where user devices are kept: the settings folder natively, memory on the web (or what a host or test installed).
fn store() -> PlotterStore {
*STORE.get_or_init(|| {
#[cfg(not(target_arch = "wasm32"))]
@@ -130,6 +131,268 @@ fn store() -> PlotterStore {
})
}
/// A plot for a system printer: the PDF the PDF plotter wrote, and how to print it.
pub struct PrintJob<'a> {
pub printer: &'a str,
/// The paper's name as the printer's device lists it.
pub paper: &'a str,
pub paper_key: &'a str,
/// Sheet dimensions used to render the PDF, in millimetres.
pub size_mm: (f64, f64),
pub copies: u32,
pub title: &'a str,
pub pdf: &'a [u8],
}
/// The host's printers: `list` gives them as devices (`system` set), `print` sends a job and
/// returns its id.
#[derive(Clone, Copy)]
pub struct SystemPrinters {
pub list: fn() -> Vec<PlotterConfig>,
pub print: fn(&PrintJob) -> std::result::Result<String, String>,
}
static PRINTERS: OnceLock<SystemPrinters> = OnceLock::new();
/// Install the host's printers (first call wins). Without them only files are plotted.
pub fn set_system_printers(p: SystemPrinters) {
let _ = PRINTERS.set(p);
}
/// Most copies of one print job.
pub const MAX_COPIES: u64 = 999;
/// The system printers as last listed. Listing asks the system (CUPS can be slow, or hang), so
/// it runs on a background thread and this never waits for it: it returns the last list, and
/// starts listing again when there is none yet or it is a few seconds old. Until the first
/// listing finishes there are none; [`system_printers_pending`] says one is under way.
fn system_printers() -> Vec<PlotterConfig> {
let Some(h) = PRINTERS.get() else { return Vec::new() };
#[cfg(not(target_arch = "wasm32"))]
{
let mut c = printer_cache();
// A listing that hangs (a driver that never answers) is given up after PRINTERS_WAIT:
// a new one may start, and nothing waits for the old one any more.
if !c.listing_live() && c.workers < MAX_LISTING_WORKERS && c.at.is_none_or(|at| at.elapsed() >= PRINTERS_TTL) {
let started = std::time::Instant::now();
c.listing = Some(started);
c.workers += 1;
let list = h.list;
let spawned = std::thread::Builder::new().name("system-printers".into()).spawn(move || {
let _worker = ListingWorker { started };
let found: Vec<PlotterConfig> = list().into_iter().filter(|p| p.system && !is_builtin(&p.name)).collect();
printer_cache().complete(started, found);
});
if spawned.is_err() {
c.listing = None;
c.workers = c.workers.saturating_sub(1);
}
}
c.list.clone()
}
#[cfg(target_arch = "wasm32")]
{
(h.list)().into_iter().filter(|p| p.system && !is_builtin(&p.name)).collect()
}
}
/// How long a printer list is used before the system is asked again.
#[cfg(not(target_arch = "wasm32"))]
const PRINTERS_TTL: std::time::Duration = std::time::Duration::from_secs(5);
/// An expired driver call can remain blocked forever. Permit a replacement, but never let
/// repeated refreshes or TTL retries accumulate an unbounded number of blocked threads.
#[cfg(not(target_arch = "wasm32"))]
const MAX_LISTING_WORKERS: usize = 2;
/// Return the worker slot on completion, even if a host's listing hook panics: a listing that
/// ended without a list (the hook panicked) is no longer under way either, so nothing waits for
/// it and Refresh can start another.
#[cfg(not(target_arch = "wasm32"))]
struct ListingWorker {
/// When the listing this worker runs started: its mark in [`PrinterCache::listing`].
started: std::time::Instant,
}
#[cfg(not(target_arch = "wasm32"))]
impl Drop for ListingWorker {
fn drop(&mut self) {
printer_cache().worker_ended(self.started);
}
}
/// The last printer list, when it was made, and when a listing under way started.
#[cfg(not(target_arch = "wasm32"))]
#[derive(Default)]
struct PrinterCache {
list: Vec<PlotterConfig>,
at: Option<std::time::Instant>,
listing: Option<std::time::Instant>,
published: Option<std::time::Instant>,
/// Running calls, including expired listings whose driver has not returned yet.
workers: usize,
/// A wait for a listing ran out (a driver that never answers): commands stop waiting until a
/// listing finishes again.
hung: bool,
}
#[cfg(not(target_arch = "wasm32"))]
impl PrinterCache {
fn complete(&mut self, started: std::time::Instant, found: Vec<PlotterConfig>) {
if self.published.is_none_or(|published| started > published) {
(self.list, self.at, self.hung, self.published) = (found, Some(std::time::Instant::now()), false, Some(started));
}
if self.listing == Some(started) {
self.listing = None;
}
}
/// A listing worker ended, with or without a list: its slot is free, and its listing (not a
/// replacement started since) is no longer under way.
fn worker_ended(&mut self, started: std::time::Instant) {
self.workers = self.workers.saturating_sub(1);
if self.listing == Some(started) {
self.listing = None;
}
}
/// A wait ran out: if the listing under way has itself run for [`PRINTERS_WAIT`], its driver
/// doesn't answer and commands stop waiting for it. A listing started during the wait (after
/// an older one expired) is younger and still gets its own wait.
fn give_up(&mut self) {
if self.listing.is_some_and(|t| t.elapsed() >= PRINTERS_WAIT) {
self.hung = true;
}
}
/// Whether a listing is under way and not yet given up (younger than [`PRINTERS_WAIT`]).
fn listing_live(&self) -> bool {
self.listing.is_some_and(|t| t.elapsed() < PRINTERS_WAIT)
}
}
/// The process-wide printer cache; a panic while it was held doesn't keep the printers away.
#[cfg(not(target_arch = "wasm32"))]
fn printer_cache() -> std::sync::MutexGuard<'static, PrinterCache> {
static CACHE: OnceLock<Mutex<PrinterCache>> = OnceLock::new();
CACHE.get_or_init(Mutex::default).lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
/// Ask the system for its printers again now (a printer was just installed or switched on):
/// the next device list starts a new listing instead of using one a few seconds old. A listing
/// under way is left to finish. Returns whether there are system printers in this build.
pub fn refresh_system_printers() -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
if PRINTERS.get().is_none() {
return false;
}
{
let mut c = printer_cache();
(c.at, c.hung) = (None, false);
}
let _ = system_printers();
true
}
#[cfg(target_arch = "wasm32")]
PRINTERS.get().is_some()
}
/// Whether the system printers are being listed (a dialog showing devices redraws when it ends).
pub fn system_printers_pending() -> bool {
#[cfg(not(target_arch = "wasm32"))]
{
PRINTERS.get().is_some() && printer_cache().listing_live()
}
#[cfg(target_arch = "wasm32")]
false
}
/// The system printer called `name`, for a command that is about to use it: from the last list,
/// else, while a listing is under way (the first one, or one started because the list is old),
/// waiting for it up to [`PRINTERS_WAIT`], so a printer named before the first listing ended is
/// still found. Only a command naming a device waits, never a dialog drawing its device list.
fn system_printer(name: &str) -> Option<PlotterConfig> {
let find = |list: Vec<PlotterConfig>| list.into_iter().find(|p| p.name.eq_ignore_ascii_case(name.trim()));
if let Some(p) = find(system_printers()) {
return Some(p);
}
#[cfg(not(target_arch = "wasm32"))]
{
wait_for_printers();
find(printer_cache().list.clone())
}
#[cfg(target_arch = "wasm32")]
None
}
/// Wait (up to [`PRINTERS_WAIT`]) for a system printer listing under way, starting one when the
/// list is old: for commands that report the devices, not for dialogs drawing them.
fn wait_for_printers() {
let _ = system_printers();
#[cfg(not(target_arch = "wasm32"))]
{
if printer_cache().hung {
return;
}
let start = std::time::Instant::now();
while system_printers_pending() && start.elapsed() < PRINTERS_WAIT {
std::thread::sleep(std::time::Duration::from_millis(20));
}
// A listing still under way after the wait: given up only once it has run the full wait.
printer_cache().give_up();
}
}
/// [`devices`] for a command reporting them: the system printers listed first, if that is
/// under way.
fn listed_devices() -> Vec<PlotterConfig> {
wait_for_printers();
devices()
}
/// The device a command names (or a layout's page setup names, for a command about to plot):
/// a built-in device at once; otherwise, once a system printer listing under way has ended (up
/// to [`PRINTERS_WAIT`]), [`find_device`], so a printer is found and wins over a user device of
/// the same name even on the first plot after the app starts. Dialogs never wait.
fn named_device(name: &str) -> Option<PlotterConfig> {
let n = name.trim();
// No device ("" or "None", a page setup's usual one) needs no printer list.
let none = n.is_empty() || n.eq_ignore_ascii_case("none");
if !none && !BUILTIN.iter().any(|(b, _, _)| b.eq_ignore_ascii_case(n.strip_suffix(cadcraft_doc::PLOTTER_FILE_EXT).unwrap_or(n))) {
wait_for_printers();
}
// One wait only: the printers as listed by now (a listing still under way after the wait
// isn't waited for again here, nor by the unknown-device error).
find_device(name)
}
/// Longest a plot waits for the system printers to be listed.
#[cfg(not(target_arch = "wasm32"))]
const PRINTERS_WAIT: std::time::Duration = std::time::Duration::from_secs(10);
/// Print `pdf` on the system printer `printer`; returns the job id.
pub(crate) fn print_pdf(cmd: &str, printer: &str, paper: &str, copies: u64, title: &str, pdf: &[u8], opts: &Value) -> Result<String> {
let h = PRINTERS.get().ok_or_else(|| bad(cmd, "there are no system printers in this build"))?;
let Some(dev) = system_printer(printer) else {
return Err(bad(cmd, format!("unknown printer `{printer}`")));
};
let copies = copies.clamp(1, MAX_COPIES) as u32;
(h.print)(&PrintJob {
printer: &dev.name,
paper,
copies,
title,
pdf,
paper_key: str_param(opts, "printerPaperKey").unwrap_or(paper),
size_mm: (
opts.get("printerSheetSize").and_then(|v| v.get(0)).and_then(Value::as_f64).unwrap_or(0.0),
opts.get("printerSheetSize").and_then(|v| v.get(1)).and_then(Value::as_f64).unwrap_or(0.0),
),
})
.map_err(|e| bad(cmd, format!("{}: {e}", dev.name)))
}
/// Most user devices listed.
const MAX_DEVICES: usize = 1000;
@@ -143,10 +406,11 @@ const BUILTIN: [(&str, PlotOutput, &str); 3] = [
/// A page setup's "no device" name.
const NO_DEVICE: &str = "None";
/// A built-in device writing `output` files on every standard paper, A4 by default.
fn builtin(name: &str, output: PlotOutput, description: &str) -> PlotterConfig {
let papers = cadcraft_render::PAPER_SIZES
.iter()
.map(|p| DevicePaper { name: p.name.into(), width: p.width_mm, height: p.height_mm, margins: p.margins_mm() })
.map(|p| DevicePaper { native_key: None, name: p.name.into(), width: p.width_mm, height: p.height_mm, margins: p.margins_mm() })
.collect();
let default_paper = cadcraft_render::paper_size("A4").map(|p| p.name.to_string()).unwrap_or_default();
PlotterConfig {
@@ -157,6 +421,8 @@ fn builtin(name: &str, output: PlotOutput, description: &str) -> PlotterConfig {
orientation: Orientation::Landscape,
default_paper,
papers,
system: false,
system_default: false,
}
}
@@ -183,16 +449,20 @@ fn user_devices() -> Vec<PlotterConfig> {
out
}
/// Every device: the built-in ones first, then the user's.
/// Every device: the built-in ones first, then the system printers, then the user's.
pub fn devices() -> Vec<PlotterConfig> {
let mut v = builtins();
v.extend(user_devices());
let printers = system_printers();
v.extend(user_devices().into_iter().filter(|u| !printers.iter().any(|p| p.name.eq_ignore_ascii_case(&u.name))));
let at = BUILTIN.len();
v.splice(at..at, printers);
v
}
/// Device names, built-in ones first.
/// Device names, built-in ones first, for a command reporting them (it waits for a system
/// printer listing under way).
pub fn device_names() -> Vec<String> {
devices().into_iter().map(|c| c.name).collect()
listed_devices().into_iter().map(|c| c.name).collect()
}
/// The device called `name` (any case; a `.plotter.json` suffix is ignored).
@@ -205,14 +475,21 @@ pub fn find_device(name: &str) -> Option<PlotterConfig> {
if let Some((b, o, d)) = BUILTIN.iter().find(|(b, _, _)| b.eq_ignore_ascii_case(n)) {
return Some(builtin(b, *o, d));
}
if let Some(p) = system_printers().into_iter().find(|p| p.name.eq_ignore_ascii_case(n)) {
return Some(p);
}
let st = store();
let direct = cadcraft_doc::plotter_file_name(n).and_then(|f| PlotterConfig::from_file_text(&(st.read)(&f).ok()?).ok());
direct.filter(|c| c.name.eq_ignore_ascii_case(n)).or_else(|| user_devices().into_iter().find(|c| c.name.eq_ignore_ascii_case(n)))
}
/// The paper of `dev` called `name`, also by a standard size's short name (`A3`, `Letter`…).
/// The paper of `dev` called `name`, also by a standard size's short name (`A3`, `Letter`…):
/// either way round, so a layout's `ISO A4 (210.00 x 297.00 MM)` finds a printer's `A4`.
fn device_paper<'a>(dev: &'a PlotterConfig, name: &str) -> Option<&'a DevicePaper> {
dev.paper(name).or_else(|| dev.paper(cadcraft_render::paper_size(name)?.name))
dev.paper(name).or_else(|| {
let standard = cadcraft_render::paper_size(name)?.name;
dev.paper(standard).or_else(|| dev.papers.iter().find(|p| cadcraft_render::paper_size(&p.name).is_some_and(|s| s.name == standard)))
})
}
/// A paper's stored portrait margins on the landscape sheet: the sheet's axes swap, so left and
@@ -227,6 +504,7 @@ pub(crate) fn portrait_margins([l, b, r, t]: [f64; 4]) -> [f64; 4] {
[b, r, t, l]
}
/// Put a device paper's name, size and printable area on a page setup.
fn set_paper(page: &mut PageSetup, p: &DevicePaper) {
page.paper = p.name.clone();
page.width_mm = p.width;
@@ -236,8 +514,11 @@ fn set_paper(page: &mut PageSetup, p: &DevicePaper) {
page.margins_mm = if page.landscape { landscape_margins(p.margins) } else { p.margins };
}
/// The error for a device name not found, with the devices as listed now: it never waits for a
/// printer listing (the lookup that failed already did).
fn unknown_device(cmd: &str, name: &str) -> EngineError {
bad(cmd, format!("unknown plotter `{name}` (devices: {})", device_names().join(", ")))
let names: Vec<String> = devices().into_iter().map(|c| c.name).collect();
bad(cmd, format!("unknown plotter `{name}` (devices: {})", names.join(", ")))
}
/// PAGESETUP's `device` and the device's papers. Sets `page.device` from `device` (`"None"`:
@@ -247,6 +528,15 @@ fn unknown_device(cmd: &str, name: &str) -> EngineError {
/// `landscape` is given. Returns whether the paper was set here (else `paper`, if any, is a
/// standard size for the caller to look up).
pub fn page_device(cmd: &str, p: &Value, page: &mut PageSetup) -> Result<bool> {
page_device_with(cmd, p, page, named_device)
}
/// Apply a dialog's device change from the cached list without waiting for drivers.
pub fn page_device_now(cmd: &str, p: &Value, page: &mut PageSetup) -> Result<bool> {
page_device_with(cmd, p, page, find_device)
}
fn page_device_with(cmd: &str, p: &Value, page: &mut PageSetup, lookup: fn(&str) -> Option<PlotterConfig>) -> Result<bool> {
let given = match p.get("device") {
Some(v) => Some(v.as_str().ok_or_else(|| bad(cmd, "`device` must be a plotter name"))?.trim()),
None => None,
@@ -256,7 +546,10 @@ pub fn page_device(cmd: &str, p: &Value, page: &mut PageSetup) -> Result<bool> {
page.device = NO_DEVICE.into();
return Ok(false);
}
Some(n) => Some(find_device(n).ok_or_else(|| unknown_device(cmd, n))?),
Some(n) => Some(lookup(n).ok_or_else(|| unknown_device(cmd, n))?),
// A paper asked for on the page's own device: that device's papers, so a printer saved in
// the page setup is waited for as one named would be (a command only; a dialog never waits).
None if p.get("paper").is_some() => lookup(&page.device),
None => find_device(&page.device),
};
let Some(dev) = dev else { return Ok(false) };
@@ -300,7 +593,14 @@ fn path_output(path: &str) -> Option<PlotOutput> {
/// without a device are unchanged.
pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
let given = str_param(p, "device").map(str::trim);
let layout = match str_param(p, "layout") {
// A single `layouts` entry is the sheet plotted, as `layout` names it: its page setup gives
// the device and the paper. Several sheets plot each with its own page setup, into one PDF.
let single = match p.get("layouts") {
Some(Value::Array(a)) if a.len() == 1 => a.first().and_then(Value::as_str),
_ => None,
};
let several = single.is_none() && p.get("layouts").is_some_and(|v| !v.is_null());
let layout = match str_param(p, "layout").or(single) {
Some(n) if n.eq_ignore_ascii_case("model") => None,
Some(n) => s.doc()?.layout(n).map(|l| l.page.clone()),
None => match s.space().layout() {
@@ -310,13 +610,40 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
};
let dev = match given {
Some(n) if n.is_empty() || n.eq_ignore_ascii_case(NO_DEVICE) => None,
Some(n) => Some(find_device(n).ok_or_else(|| unknown_device(cmd, n))?),
None => layout.as_ref().and_then(|pg| find_device(&pg.device)),
Some(n) => Some(named_device(n).ok_or_else(|| unknown_device(cmd, n))?),
// The shown layout's device is not the sheets' device: it would send a set of sheets
// meant for a PDF file to that layout's printer.
None if several => None,
None => layout.as_ref().and_then(|pg| named_device(&pg.device)),
};
let mut out = if p.is_object() { p.clone() } else { json!({}) };
// Only a system printer chosen as the device prints (below): a `printer` passed with the
// call is dropped, so EXPORTPDF always writes the PDF and PLOT without one writes its file.
if let Some(o) = out.as_object_mut() {
o.remove("printer");
o.remove("printerPaper");
o.remove("printerPaperKey");
}
// The plot stamp names the drawing and the device here; the plotter fills in each sheet's
// layout, paper and scale.
// Without a device, the built-in one for the format the path or `output` asks for.
let by_path = if cmd == "exportpdf" { None } else { str_param(p, "path").and_then(path_output) };
let no_device = if cmd == "exportpdf" {
PlotOutput::Pdf
} else {
by_path.or_else(|| p.get("output").and_then(Value::as_str).and_then(PlotOutput::parse)).unwrap_or(PlotOutput::Pdf)
};
let builtin_name = BUILTIN.iter().find(|(_, o, _)| *o == no_device).map_or("CADCraft PDF", |(n, _, _)| *n);
let device_name = dev.as_ref().map_or_else(|| builtin_name.to_string(), |d| d.name.clone());
let text = stamp(s, p, cmd, &device_name)?;
if let Some(o) = out.as_object_mut() {
o.remove("stamp");
if let Some(text) = text {
o.insert("stamp".into(), json!(text));
}
}
// 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"
@@ -364,6 +691,20 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
None if layout.is_none() => dev.default_paper(),
None => None,
};
// A system printer gets the plotter's PDF, on the paper by its name on that printer
// (EXPORTPDF still writes the PDF).
if dev.system && cmd == "plot" && output == PlotOutput::Pdf {
o.insert("printer".into(), json!(dev.name));
let on = paper.map(|pp| pp.name.clone()).or_else(|| layout.as_ref().map(|pg| pg.paper.clone())).unwrap_or_default();
if let Some(key) = paper.or_else(|| device_paper(&dev, &on)).and_then(|pp| pp.native_key.as_ref()) {
o.insert("printerPaperKey".into(), json!(key));
}
o.insert("printerPaper".into(), json!(on));
}
// The stamp names the device's paper (the plotter only sees its size).
if let (Some(pp), Some(Value::String(t))) = (paper, o.get_mut("stamp")) {
*t = cadcraft_doc::fill_stamp(t, &[("paper", &pp.name)], false);
}
if let Some(pp) = paper {
o.remove("paper");
o.insert("width".into(), json!(pp.width));
@@ -383,6 +724,27 @@ pub(crate) fn plot_options(s: &Session, p: &Value, cmd: &str) -> Result<Value> {
Ok(out)
}
/// What PLOT's default plot stamp says: the drawing, the sheet, the device, the paper and the
/// scale.
pub const DEFAULT_STAMP: &str = "{drawing}, {layout}, {device}, {paper}, {scale}";
/// The plot stamp of a plot: `stamp: true` stamps [`DEFAULT_STAMP`], a text stamps that text
/// (with `{drawing}` and `{device}` filled in here, `{layout}`, `{paper}` and `{scale}` by the
/// plotter for each sheet), `false` or none doesn't stamp.
fn stamp(s: &Session, p: &Value, cmd: &str, device: &str) -> Result<Option<String>> {
let template = match p.get("stamp") {
None | Some(Value::Null) | Some(Value::Bool(false)) => return Ok(None),
Some(Value::Bool(true)) => DEFAULT_STAMP.to_string(),
Some(Value::String(t)) => t.clone(),
Some(_) => return Err(bad(cmd, "`stamp` must be true, false or the stamp's text")),
};
let drawing = s.state()?.title.clone();
// One pass, and not the last: the plotter fills each sheet's fields, never these values.
let template: String = template.chars().filter(|c| !c.is_control()).take(300).collect();
let text = cadcraft_doc::fill_stamp(&template, &[("drawing", &drawing), ("device", device)], false);
Ok((!text.trim().is_empty()).then_some(text))
}
/// Whether a plot draws transparency, as PLOTTRANSPARENCYOVERRIDE decides: 0 never, 2 always,
/// otherwise the plot's `plotTransparency` (`None` when it has none: the page setup decides).
pub(crate) fn plot_transparency(s: &Session, p: &Value) -> Option<bool> {
@@ -456,6 +818,7 @@ impl Interactive for PlotWindowM {
// ---------- PLOTTERMANAGER ----------
/// PLOTWINDOW and PLOTTERMANAGER.
pub fn specs() -> Vec<CommandSpec> {
vec![
CommandSpec::new("plotwindow", "Plot Window", run_plotwindow)
@@ -466,7 +829,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("plottermanager", "Plotter Manager...", run_plottermanager)
.menu(&["File", "Plotter Manager..."])
.params(
"{action?: list (default)|get|new|set|delete|load|save, name?: device, from?: device to copy (new), output?: pdf|png|svg, description?, resolution?: dpi, orientation?: portrait|landscape, defaultPaper?, paper?: {name, width, height (mm), margins?: [l,b,r,t] mm} (set: add or replace), removePaper?: name (set), text? (load), path? (save: native only; without it returns `text`)} (typed: option prompts)",
"{action?: list (default)|get|new|set|delete|load|save|refresh (ask the system for its printers again), name?: device, from?: device to copy (new), output?: pdf|png|svg, description?, resolution?: dpi, orientation?: portrait|landscape, defaultPaper?, paper?: {name, width, height (mm), margins?: [l,b,r,t] mm} (set: add or replace), removePaper?: name (set), text? (load), path? (save: native only; without it returns `text`)} (typed: option prompts)",
)
.enabled(always)
.noundo()
@@ -479,12 +842,22 @@ pub fn specs() -> Vec<CommandSpec> {
]
}
/// A system printer is the system's: PLOTTERMANAGER doesn't change or delete it (a user file
/// by its name would only be hidden behind it). A copy made with action `new` can be edited.
fn system_read_only(cmd: &str, name: &str) -> EngineError {
bad(cmd, format!("`{name}` is a system printer: make a copy with action new, from `{name}`"))
}
/// A device as PLOTTERMANAGER reports it: name, description, output, whether it is built in, a
/// system printer or the default one, how many papers it has and its default paper.
fn summary(c: &PlotterConfig) -> Value {
json!({
"name": c.name,
"description": c.description,
"output": c.output.as_str(),
"builtin": is_builtin(&c.name),
"system": c.system,
"default": c.system_default,
"papers": c.papers.len(),
"defaultPaper": c.default_paper,
})
@@ -492,7 +865,9 @@ fn summary(c: &PlotterConfig) -> Value {
fn device_name(cmd: &str, p: &Value) -> Result<String> {
let n = str_param(p, "name").map(str::trim).filter(|n| !n.is_empty()).ok_or_else(|| bad(cmd, "`name` (a plotter name) is required"))?;
Ok(n.chars().take(cadcraft_doc::MAX_PLOTTER_NAME).collect())
// The whole name: a system printer's may be longer than a user device's, and a shortened
// one could name another printer. `new` shortens the name it gives a user device.
Ok(n.to_string())
}
/// Write a user device to the store.
@@ -568,7 +943,7 @@ fn edit_device(cmd: &str, c: &mut PlotterConfig, p: &Value) -> Result<()> {
}
}
};
let new = DevicePaper { name: name.into(), width: w, height: h, margins };
let new = DevicePaper { native_key: None, name: name.into(), width: w, height: h, margins };
match existing.and_then(|e| c.papers.iter().position(|x| x.name == e.name)) {
Some(i) => {
if let Some(slot) = c.papers.get_mut(i) {
@@ -586,7 +961,8 @@ fn edit_device(cmd: &str, c: &mut PlotterConfig, p: &Value) -> Result<()> {
Ok(())
}
/// List, read, change, load, export and delete plotter configurations; any file is held to the automation roots.
/// PLOTTERMANAGER: list, refresh, read, change, load, export and delete plotter configurations
/// (user devices only; system printers are listed, not edited); any file is held to the automation roots.
fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
let cmd = "plottermanager";
let action = str_param(p, "action").unwrap_or("list").trim().to_ascii_lowercase();
@@ -596,19 +972,25 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
if crate::file_access::current().is_some() {
(store().list)().map_err(|e| bad(cmd, e))?;
}
Ok(json!({ "devices": devices().iter().map(summary).collect::<Vec<_>>() }))
Ok(json!({ "devices": listed_devices().iter().map(summary).collect::<Vec<_>>() }))
}
// The system's printers asked for again; `list` (or the Plot dialog) shows them once
// that listing ends.
"refresh" => Ok(json!({ "printers": refresh_system_printers(), "pending": system_printers_pending() })),
"get" => {
let n = device_name(cmd, p)?;
let c = find_device(&n).ok_or_else(|| unknown_device(cmd, &n))?;
// A printer named before the first listing ended is waited for, as PLOT does.
let c = named_device(&n).ok_or_else(|| unknown_device(cmd, &n))?;
let mut v = serde_json::to_value(&c).unwrap_or(Value::Null);
if let Some(o) = v.as_object_mut() {
o.insert("builtin".into(), json!(is_builtin(&c.name)));
o.insert("system".into(), json!(c.system));
o.insert("default".into(), json!(c.system_default));
}
Ok(v)
}
"new" => {
let name = device_name(cmd, p)?;
let name: String = device_name(cmd, p)?.chars().take(cadcraft_doc::MAX_PLOTTER_NAME).collect();
if find_device(&name).is_some() {
return Err(bad(cmd, format!("plotter `{name}` already exists")));
}
@@ -617,7 +999,9 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, format!("a plotter file `{file}` already exists")));
}
let mut c = match str_param(p, "from") {
Some(f) => find_device(f).ok_or_else(|| unknown_device(cmd, f))?,
// A system printer named before the first listing ended is waited for, as `get`
// does: it wins over a user device of the same name whenever the copy is made.
Some(f) => named_device(f).ok_or_else(|| unknown_device(cmd, f))?,
None => {
// A copy of the built-in device for the output: the standard papers.
let output = match p.get("output") {
@@ -630,6 +1014,8 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
};
c.name = name;
c.description = String::new();
// A copy of a system printer is a user device: it is neither the spooler's nor its default.
(c.system, c.system_default) = (false, false);
edit_device(cmd, &mut c, p)?;
let c = c.sanitized();
save_device(cmd, &c)?;
@@ -641,6 +1027,9 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, format!("`{name}` is built in: make a copy with action new, from `{name}`")));
}
let mut c = find_device(&name).ok_or_else(|| unknown_device(cmd, &name))?;
if c.system {
return Err(system_read_only(cmd, &c.name));
}
edit_device(cmd, &mut c, p)?;
if c.papers.is_empty() {
return Err(bad(cmd, "a plotter needs at least one paper"));
@@ -655,6 +1044,9 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad(cmd, format!("`{name}` is built in and can't be deleted")));
}
let c = find_device(&name).ok_or_else(|| unknown_device(cmd, &name))?;
if c.system {
return Err(system_read_only(cmd, &c.name));
}
let file = cadcraft_doc::plotter_file_name(&c.name).ok_or_else(|| bad(cmd, "the plotter has no name"))?;
(store().delete)(&file).map_err(|e| bad(cmd, e))?;
Ok(json!({ "deleted": c.name }))
@@ -676,7 +1068,7 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
}
"save" => {
let name = device_name(cmd, p)?;
let text = find_device(&name).ok_or_else(|| unknown_device(cmd, &name))?.to_file_text();
let text = named_device(&name).ok_or_else(|| unknown_device(cmd, &name))?.to_file_text();
match str_param(p, "path") {
None => Ok(json!({ "name": name, "text": text })),
Some(_path) => {
@@ -691,7 +1083,7 @@ fn run_plottermanager(_s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, delete, load, save)"))),
other => Err(bad(cmd, format!("unknown action `{other}` (list, get, new, set, delete, load, save, refresh)"))),
}
}
@@ -749,6 +1141,7 @@ impl Interactive for PlotterManagerM {
Stage::PaperSize(..) => Prompt::new("Enter the paper width,height in mm", Accept::TEXT),
}
}
/// The next answer at the PLOTTERMANAGER prompts: an option, then the names and sizes it asks for.
fn input(&mut self, s: &mut Session, i: Input) -> Result<Step> {
if i == Input::Cancel {
return Ok(Step::Cancel);
@@ -767,9 +1160,17 @@ impl Interactive for PlotterManagerM {
"Delete" => Stage::Delete,
"Paper" => Stage::PaperDevice,
_ => {
for c in devices() {
let kind = if is_builtin(&c.name) { "built-in" } else { "user" };
s.echo(format!("{} ({}, {kind}, {} paper sizes)", c.name, c.output.as_str().to_uppercase(), c.papers.len()));
for c in listed_devices() {
let kind = if is_builtin(&c.name) {
"built-in"
} else if c.system {
"system printer"
} else {
"user"
};
// The system's default printer says so, as in the dialogs' device lists.
let default = if c.system_default { " (default)" } else { "" };
s.echo(format!("{}{default} ({}, {kind}, {} paper sizes)", c.name, c.output.as_str().to_uppercase(), c.papers.len()));
}
return Ok(Step::Done);
}
@@ -802,6 +1203,9 @@ impl Interactive for PlotterManagerM {
if is_builtin(&c.name) {
return Err(EngineError::Other(format!("\"{}\" is built in; create a new plotter first.", c.name)));
}
if c.system {
return Err(system_read_only("plottermanager", &c.name));
}
self.stage = Stage::PaperName(c.name);
Ok(Step::Continue)
}
@@ -823,3 +1227,57 @@ impl Interactive for PlotterManagerM {
}
}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod cache_regressions {
use super::*;
#[test]
fn replacement_listings_do_not_starve_completed_results_or_overwrite_newer_lists() {
let older = std::time::Instant::now();
let newer = older + std::time::Duration::from_secs(1);
let mut cache = PrinterCache { listing: Some(newer), ..Default::default() };
let device = |name: &str| PlotterConfig { name: name.into(), ..Default::default() };
cache.complete(older, vec![device("older")]);
assert_eq!(cache.list[0].name, "older");
assert_eq!(cache.listing, Some(newer), "the replacement is still pending");
cache.complete(newer, vec![device("newer")]);
cache.complete(older, vec![device("stale")]);
assert_eq!(cache.list[0].name, "newer");
assert!(cache.listing.is_none());
}
/// A wait that runs out gives up only on a listing that has run the full wait itself, not on
/// one that started during the wait (#2171 review).
#[test]
fn only_a_listing_that_ran_the_full_wait_is_given_up() {
let now = std::time::Instant::now();
let mut fresh = PrinterCache { listing: Some(now), ..PrinterCache::default() };
fresh.give_up();
assert!(!fresh.hung, "a listing that just started is not hung");
let Some(old) = now.checked_sub(PRINTERS_WAIT + std::time::Duration::from_millis(50)) else { return };
let mut stuck = PrinterCache { listing: Some(old), ..PrinterCache::default() };
stuck.give_up();
assert!(stuck.hung, "a listing past the wait is given up");
let mut idle = PrinterCache::default();
idle.give_up();
assert!(!idle.hung, "no listing, nothing to give up");
}
}
#[cfg(test)]
mod paper_regressions {
use super::*;
/// A layout's paper by its standard full name finds the printer's paper listed by the short
/// name (`A4`), so the job carries the printer's own key (#2171 review).
#[test]
fn a_standard_full_name_finds_a_printers_short_name() {
let a4 = DevicePaper { native_key: Some("A4".into()), name: "A4".into(), width: 210.0, height: 297.0, margins: [5.0; 4] };
let dev = PlotterConfig { name: "Office".into(), papers: vec![a4], system: true, ..PlotterConfig::default() };
let full = cadcraft_render::paper_size("A4").map(|p| p.name).unwrap_or_default();
assert_ne!(full, "A4", "the standard size has a longer name");
assert_eq!(device_paper(&dev, full).and_then(|p| p.native_key.as_deref()), Some("A4"));
assert!(device_paper(&dev, "A3").is_none(), "another size is not found");
}
}
+2 -5
View File
@@ -204,7 +204,6 @@ fn set_override(dm: &mut cadcraft_doc::Dimension, field: &'static str, v: Value)
/// A `properties.set` call, checked before any object changes: the values every object takes,
/// and what the edits need to know beforehand.
struct Call<'a> {
hatch_lines: Option<Vec<cadcraft_doc::library::PatternLine>>,
p: &'a Value,
color: Option<Color>,
transparency: Option<Transparency>,
@@ -352,10 +351,8 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
}
}
let hatch_lines = str_param(p, "pattern").and_then(|n| crate::cmd::hatch::drawing_lines(d, n.trim()));
// A pattern must be one each hatch can take, as HATCHEDIT refuses others.
if let Some(v) = str_param(p, "pattern").filter(|v| !v.trim().is_empty())
&& hatch_lines.is_none()
&& hs.iter().any(|h| matches!(d.entity(*h).map(|e| &e.kind), Some(EntityKind::Hatch(x)) if !crate::cmd::hatch::takes_pattern(x, v)))
{
return Err(bad("properties.set", format!("unknown pattern {}", v.trim().to_ascii_uppercase())));
@@ -366,7 +363,7 @@ pub(super) fn run_set(s: &mut Session, p: &Value) -> Result<Value> {
}
let prep = Prepared::new(d, p, &hs);
let anno_scale = d.current_anno_scale();
let c = Call { hatch_lines, p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale };
let c = Call { p, color, transparency, thickness, lineweight, linetype, dim_style, text_style, dim_vars, prep, anno_scale };
// A failed call changes nothing (a command's error doesn't undo what it did), so the drawing
// is taken for writing, and the layer made, only after every check.
let d = s.doc_mut()?;
@@ -808,7 +805,7 @@ fn dimension_posts(dm: &mut Dimension, c: &Call<'_>, used: &mut Used<'_>) {
fn hatch(ha: &mut Hatch, c: &Call<'_>, used: &mut Used<'_>) {
// HATCHEDIT's pattern edit (a blank name changes nothing, so it's ignored).
if let Some(v) = str_param(c.p, "pattern")
&& crate::cmd::hatch::set_pattern(ha, v, c.hatch_lines.as_deref())
&& crate::cmd::hatch::set_pattern(ha, v)
{
used.insert("pattern");
}
+2 -3
View File
@@ -696,10 +696,9 @@ impl Interactive for TrimM {
}
"Undo" => match self.undo.pop() {
Some(doc) => {
// Settings changed meanwhile stay. The drawing put back is an
// earlier one: names of INSERT records end with it.
// Settings changed meanwhile stay.
let header = s.doc()?.header.clone();
s.state_mut()?.restore_drawing(doc);
s.state_mut()?.doc = doc;
s.doc_mut()?.header = header;
}
None => s.echo("Nothing to undo."),
+1 -1
View File
@@ -302,7 +302,7 @@ fn run_view_set(s: &mut Session, p: &Value) -> Result<Value> {
None => 0.0,
};
if !s.state_mut()?.set_view(View { center: c, height: h, twist }) {
s.state_mut()?.restore_drawing(before.0);
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 {
+1 -1
View File
@@ -237,7 +237,7 @@ impl DviewM {
set_twist(s, t, twist)?;
}
if !s.state_mut()?.set_view(View { twist, ..v }) {
s.state_mut()?.restore_drawing(before);
s.state_mut()?.doc = before;
return Err(EngineError::Other("The view is too large to show.".into()));
}
Ok(())
-26
View File
@@ -28,13 +28,6 @@ pub struct DocState {
pub title: String,
pub saved: Arc<Drawing>,
pub revision: u64,
/// How many times the names AutoLISP gave this drawing's INSERTs' ATTRIBs and SEQENDs ended all
/// at once (#1660): another state of the drawing was shown (Undo, Redo, opening or closing the
/// Block Editor, a change taken back, or a command putting an earlier drawing back through
/// [`DocState::restore_drawing`]), or attribute sets were rebuilt in place (ATTSYNC,
/// -BLOCKREPLACE). A name given before names nothing after one of these, never another
/// record.
pub(crate) names_epoch: u64,
pub space: Space,
/// Tiled model viewports (VPORTS).
pub tiles: ModelTiles,
@@ -78,7 +71,6 @@ impl DocState {
path,
title: title.into(),
revision: 1,
names_epoch: 0,
space: Space::Model,
tiles: ModelTiles::default(),
mspace: None,
@@ -105,26 +97,8 @@ impl DocState {
self.follow_layout(&cur.doc);
self.reconcile_untiled_twist();
self.revision += 1;
self.expire_names();
cur
}
/// Names given to records without handles (an INSERT's ATTRIBs and SEQEND) stop holding: the
/// records of the drawing they were given for may be gone or replaced. They are never given
/// to another record, so a routine's stale name names nothing (`nil`) rather than something
/// else.
pub(crate) fn expire_names(&mut self) {
self.names_epoch = self.names_epoch.wrapping_add(1);
}
/// Show `doc` again. It is a drawing this document already showed, so its handle seed can
/// give the next object a handle a removed one had. Names of INSERT records end, as they do
/// for Undo. The same drawing already on show is left as it is: nothing was given out again.
pub(crate) fn restore_drawing(&mut self, doc: Arc<Drawing>) {
if Arc::ptr_eq(&self.doc, &doc) {
return;
}
self.doc = doc;
self.expire_names();
}
/// After undo/redo replaced the drawing (`before` is the one shown until then): if the current
/// layout no longer exists, follow it to its other name when it was renamed (same tab order,
/// a name `before` did not have), else go to the Model tab.
@@ -241,7 +241,6 @@ pub const NO_FILES: &[&str] = &[
"gradient",
"boundary",
"region",
"hatch.capture",
"hatchedit",
"hatchgenerateboundary",
"hatchpick",
+1 -1
View File
@@ -26,7 +26,7 @@ impl Session {
};
let Some(st) = st.filter(|st| !Arc::ptr_eq(before, &st.doc)) else { return Ok(()) };
let Some(h) = first_non_finite(before, &st.doc) else { return Ok(()) };
st.restore_drawing(before.clone());
st.doc = before.clone();
st.selection = selection.to_vec();
Err(EngineError::BadParams {
cmd: cmd.into(),
+1 -1
View File
@@ -57,7 +57,7 @@ pub use cadcraft_geom as geom;
pub use cadcraft_render as render;
pub use cmd::blocks::WblockPicks;
pub use cmd::blocks::attedit::{AttributeRow, attributes};
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices, pattern_choices_in, register_drawing_patterns};
pub use cmd::hatch::{HatchPicks, PatternChoice, PickMode, pattern_choices};
pub use cmd::{CommandInfo, CommandSpec, command_specs, find_command};
pub use prompt::{Accept, AttribAsk, AttribEntry, DisplayOnly, Drag, EditorKind, Input, Interactive, Picker, Prompt, Step, TextEditor};
+1 -13
View File
@@ -126,11 +126,6 @@ impl Env {
#[derive(Default)]
pub struct LispState {
envs: HashMap<u64, Env>,
/// The names given to records without a handle of their own (an INSERT's ATTRIBs and SEQEND,
/// #1660), by drawing. They are the session's, not a snapshot's, so the drawing's undo states
/// and the Block Editor's drawing share them; each use checks what a name stands for against
/// the drawing.
pub(crate) records: HashMap<u64, drawing::RecordNames>,
run: Option<Box<Run>>,
/// A routine runs, from its start to its end (also while its machine is out of `run`).
active: bool,
@@ -256,13 +251,6 @@ impl Session {
pub(crate) fn lisp_forget_closed(&mut self) {
let docs = &self.docs;
self.lisp.envs.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid));
self.lisp.records.retain(|uid, _| *uid == 0 || docs.iter().any(|d| d.uid == *uid));
}
/// The active drawing's names of an INSERT's records (#1660), made on first use.
pub(crate) fn record_names(&mut self) -> Option<&mut drawing::RecordNames> {
let uid = self.state().ok()?.uid;
Some(self.lisp.records.entry(uid).or_default())
}
/// A routine is running (possibly waiting for input).
@@ -444,7 +432,7 @@ impl Session {
if let Some((doc, sel)) = self.lisp.steps.base.as_ref().or(run.before.as_ref())
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == run.uid)
{
st.restore_drawing(doc.clone());
st.doc = doc.clone();
st.selection = sel.clone();
}
run.handler = true;
+34 -378
View File
@@ -21,7 +21,7 @@ use craft_dxf::Tag;
use super::builtins::args_err;
use super::eval::{Ctx, Flow, Need};
use super::value::{PickSet, RecordName, Value, equal, to_text};
use super::value::{PickSet, Value, to_text};
use super::{BlockSlots, LispError};
use crate::{Input, Session};
@@ -119,8 +119,6 @@ pub fn command(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
}
}
Value::Ename(h) => named(ctx.s, *h, None),
// An INSERT's record (#1660) is no object of the drawing: it picks nothing.
Value::Record(_) => feed(ctx.s, Input::Pick(Vec::new())),
Value::PickSet(p) => feed(ctx.s, Input::Pick(items(p))),
Value::Cons(_) => {
if let Some(p) = arg.as_point() {
@@ -328,8 +326,8 @@ pub(super) fn groups_to_list(tags: &[Tag]) -> Vec<Value> {
const MAX_GROUP_TEXT: usize = 32 << 20;
/// An association list back to DXF groups (points split into x, y, z groups). The type
/// (`0`), the entity name (`-1`), the owner of a record (`-2`) and of the entity (`330`), the
/// handle (`5`) and the layout (`410`) are left out: they aren't the entity's to set.
/// (`0`), the entity name (`-1`), the handle (`5`), the owner (`330`) and the layout (`410`) are
/// left out: they aren't the entity's to set.
fn list_to_groups(list: &Value) -> Result<(String, Vec<Tag>), LispError> {
let mut kind = None;
let mut tags = Vec::new();
@@ -345,7 +343,7 @@ fn list_to_groups(list: &Value) -> Result<(String, Vec<Tag>), LispError> {
other => return Err(LispError::bad_arg("stringp", other)),
})
}
-1 | -2 | -3 | 5 | 330 | 360 | 410 | 102 => {}
-1 | -3 | 5 | 330 | 360 | 410 | 102 => {}
_ if point_group(code) && matches!(v, Value::Cons(_)) => {
let p = v.as_point().ok_or_else(|| LispError::bad_arg("2D/3D point", &v))?;
tags.push(Tag::f(code, p[0]));
@@ -376,310 +374,8 @@ fn space_of(d: &cadcraft_doc::Drawing, h: Handle) -> Option<Space> {
d.space_of(h)
}
// ---------------- an INSERT's ATTRIBs and SEQEND ----------------
/// The most names one drawing's LISP holds for an INSERT's records at once: a routine can't fill
/// memory by walking. At the limit `entnext` gives no *new* name (`nil`) until names end (an
/// erased reference, Undo, ATTSYNC) and make room; the names already given still hold.
const MAX_RECORD_NAMES: usize = 65_536;
/// What a name given to an INSERT's ATTRIB or SEQEND stands for, while it holds.
struct Record {
owner: Handle,
/// The record's place after the INSERT's own: an ATTRIB's index, or `attribs.len()` for the
/// SEQEND.
slot: usize,
/// The ATTRIB's tag, which can be empty. A SEQEND has no tag.
tag: Option<String>,
}
impl Record {
/// Whether the reference still has the same kind of record in this slot, with the same tag.
fn holds(&self, attribs: &[cadcraft_doc::Attrib]) -> bool {
match (attribs.get(self.slot), self.tag.as_deref()) {
(Some(a), Some(tag)) => a.tag.eq_ignore_ascii_case(tag),
(None, None) => self.slot == attribs.len(),
_ => false,
}
}
}
/// The names a drawing's LISP gave to INSERTs' ATTRIBs and SEQENDs (#1660). These records have no
/// handle of their own in the drawing, and their names are not handles ([`RecordName`]): nothing
/// a drawing, a copy of it or another session gives out can ever be one. A name holds while its
/// reference keeps the record in that place with that tag, in the drawing's name epoch it was
/// given in (`DocState::expire_names`); otherwise it names nothing (`nil`), never another record.
#[derive(Default)]
pub(crate) struct RecordNames {
/// Names by INSERT and then by slot. Removing an INSERT ends all its names, even after a
/// change to the length of its attribute run.
by_owner: HashMap<Handle, HashMap<usize, RecordName>>,
/// What each name that still holds stands for, by its number.
by_name: HashMap<u64, Record>,
/// The drawing's name epoch the names were given in.
epoch: u64,
}
impl RecordNames {
/// Forget every name once the drawing's name epoch moved on: the records they named may be
/// gone or rebuilt.
fn expire(&mut self, epoch: u64) {
if self.epoch != epoch {
self.by_owner.clear();
self.by_name.clear();
self.epoch = epoch;
}
}
/// Drop the name numbered `id`: it names nothing from now on.
fn retire(&mut self, id: u64) {
if let Some(r) = self.by_name.remove(&id)
&& let Some(slots) = self.by_owner.get_mut(&r.owner)
&& slots.get(&r.slot).is_some_and(|n| n.id == id)
{
slots.remove(&r.slot);
if slots.is_empty() {
self.by_owner.remove(&r.owner);
}
}
}
/// End the names of the removed reference. Restoring it does not revive any of its names.
pub(crate) fn erased(&mut self, e: &Entity) {
if let Some(slots) = self.by_owner.remove(&e.handle) {
for n in slots.into_values() {
self.by_name.remove(&n.id);
}
}
}
/// How many names hold now (tests).
#[cfg(test)]
pub(crate) fn count(&self) -> usize {
self.by_name.len()
}
/// The INSERT and place `name` stands for in `d` now. A name that no longer holds is dropped:
/// it names nothing from then on, also if its record comes back.
fn lookup(&mut self, epoch: u64, d: &cadcraft_doc::Drawing, name: RecordName) -> Option<(Handle, usize)> {
self.expire(epoch);
let r = self.by_name.get(&name.id)?;
let at = insert_attribs(d, r.owner).filter(|attribs| r.holds(attribs)).map(|_| (r.owner, r.slot));
if at.is_none() {
self.retire(name.id);
}
at
}
/// The name of record `slot` after INSERT `owner`'s own (its attributes, then its SEQEND),
/// given now if it has none that holds: the same one while the record holds, so a repeated
/// walk is stable. None past the SEQEND, at the limit of names, or when the numbers run out.
fn name(&mut self, epoch: u64, attribs: &[cadcraft_doc::Attrib], owner: Handle, slot: usize) -> Option<RecordName> {
self.expire(epoch);
if let Some(n) = self.by_owner.get(&owner).and_then(|slots| slots.get(&slot)).copied() {
if self.by_name.get(&n.id).is_some_and(|r| r.holds(attribs)) {
return Some(n);
}
self.retire(n.id);
}
let tag = match attribs.get(slot) {
Some(a) => Some(a.tag.clone()),
None if slot == attribs.len() => None,
None => return None,
};
if self.by_name.len() >= MAX_RECORD_NAMES {
return None;
}
let name = RecordName::fresh(owner)?;
self.by_owner.entry(owner).or_default().insert(slot, name);
self.by_name.insert(name.id, Record { owner, slot, tag });
Some(name)
}
}
/// The attributes of the block reference `h` in `d` (none for anything else, and for a reference
/// with no attributes: an empty run of records is not written).
fn insert_attribs(d: &cadcraft_doc::Drawing, h: Handle) -> Option<&[cadcraft_doc::Attrib]> {
match d.entity(h).map(|e| &e.kind) {
Some(cadcraft_doc::EntityKind::Insert(i)) if !i.attribs.is_empty() => Some(&i.attribs),
_ => None,
}
}
/// The drawing and its name epoch, without holding a borrow of the session.
fn doc_and_epoch(ctx: &Ctx<'_>) -> Option<(Arc<cadcraft_doc::Drawing>, u64)> {
let st = ctx.s.state().ok()?;
Some((st.doc.clone(), st.names_epoch))
}
/// The INSERT and record the name `name` stands for now (none when it no longer holds).
fn record_of(ctx: &mut Ctx<'_>, name: RecordName) -> Option<(Handle, usize)> {
let (d, epoch) = doc_and_epoch(ctx)?;
ctx.s.record_names()?.lookup(epoch, &d, name)
}
/// The name of record `slot` after INSERT `owner`'s own (#1660): an ATTRIB, or its SEQEND (one
/// past the last attribute). None when it has no such record, when the host has no record
/// mapping, or when no name is left to give.
fn name_record(ctx: &mut Ctx<'_>, owner: Handle, slot: usize) -> Option<RecordName> {
crate::cmd::file::entity_sub_record()?;
let (d, epoch) = doc_and_epoch(ctx)?;
let attribs = insert_attribs(&d, owner)?;
ctx.s.record_names()?.name(epoch, attribs, owner, slot)
}
/// An entity list: `head` (its name, type and, for an INSERT's record, its owner), then the
/// groups of its record with the layout name after the AcDbEntity marker, as AutoCAD lists it.
/// The layout is the one object `at` is in; without a layout of its own (an entity of a block
/// definition) it has none.
fn entity_list(d: &cadcraft_doc::Drawing, mut items: Vec<Value>, at: Handle, tags: &[Tag], in_block: bool) -> Value {
let layout = match space_of(d, at) {
Some(Space::Paper(name)) => name,
_ => "Model".into(),
};
let mut placed_layout = in_block;
for v in groups_to_list(tags) {
// The layout name follows the AcDbEntity marker, as AutoCAD lists it.
let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity");
items.push(v);
if after_marker {
items.push(Value::cons(Value::Int(410), Value::str(&layout)));
placed_layout = true;
}
}
Value::list(items)
}
/// The list of record `slot` of the reference `owner` named `name`: the DXF writer's record,
/// its name (`-1`), type (`0`) and reference (`-2`). None when the host has no record mapping.
fn record_list(d: &cadcraft_doc::Drawing, name: RecordName, owner: Handle, slot: usize) -> Option<(Value, Vec<Tag>)> {
let e = d.entity(owner)?;
let (kind, mut tags) = (crate::cmd::file::entity_sub_record()?)(d, e, slot)?;
convert_angles(&kind, &mut tags, f64::to_radians);
let head = vec![
Value::cons(Value::Int(-1), Value::Record(name)),
Value::cons(Value::Int(0), Value::str(&kind)),
Value::cons(Value::Int(-2), Value::Ename(owner)),
];
Some((entity_list(d, head, owner, &tags, false), tags))
}
/// `entget` of an INSERT's ATTRIB or SEQEND (#1660), while `name` names one.
fn record_entget(ctx: &mut Ctx<'_>, name: RecordName) -> Option<Value> {
let (owner, slot) = record_of(ctx, name)?;
let d = ctx.s.doc().ok()?;
record_list(d, name, owner, slot).map(|(list, _)| list)
}
/// What an ATTRIB's submitted list asks to change: `Some(None)` when it asks for nothing, and
/// `Some(Some(value))` for its value (group 1). `None` when it asks for any other edit: a group
/// added, dropped, moved or changed other than the attribute's own value.
fn value_edit(now: &[Tag], asked: &[Tag]) -> Option<Option<String>> {
if now.len() != asked.len() {
return None;
}
let mut value = None;
let mut seen = false;
for (n, a) in now.iter().zip(asked) {
if n.code != a.code {
return None;
}
if n.code == 1 {
// A multiline attribute's embedded text has a group 1 of its own, after its marker
// (101): only the attribute's value, before it, may differ.
match (&n.value, &a.value) {
(craft_dxf::Value::Str(old), craft_dxf::Value::Str(new)) if !seen => {
seen = true;
if old != new {
value = Some(new.clone());
}
}
_ if n == a => {}
_ => return None,
}
} else if n != a {
return None;
}
}
Some(value)
}
/// The submitted list has the items `entget` would return, in order, except at group 1 (the
/// value): `value_edit` checks which group 1 may differ. Every other group, including the ones
/// an entity cannot set (`-2`, `5`, `330`, `360`, `410`, `102`), must be the same.
fn only_value_diff(expected: &Value, asked: &Value) -> bool {
let (mut expected, mut asked) = (expected.iter(), asked.iter());
loop {
match (expected.next(), asked.next()) {
(None, None) => return true,
(Some(x), Some(y)) => {
let code = x.car().as_number();
if code != y.car().as_number() {
return false;
}
if code != Some(1.0) && !equal(&x, &y, 0.0) {
return false;
}
}
_ => return false,
}
}
}
/// `entmod` of the INSERT's record `name` stands for (#1660): only an ATTRIB's value may change,
/// the group 1 value; its tag, place, flags and properties are the reference's. A SEQEND holds
/// nothing to change, and a name that no longer holds names nothing: both give `nil`, the drawing
/// as it is.
fn entmod_attrib(ctx: &mut Ctx<'_>, list: &Value, name: RecordName) -> Value {
let Some((owner, slot)) = record_of(ctx, name) else { return Value::Nil };
// An outer list with an atom tail is not the list `entget` returned: iterating it would drop
// the tail and accept the malformed list. The group pairs inside are dotted, as DXF has them.
if !list.is_list() {
return Value::Nil;
}
let Ok((kind, asked)) = list_to_groups(list) else { return Value::Nil };
if !kind.eq_ignore_ascii_case("ATTRIB") {
return Value::Nil;
}
let Ok(d) = ctx.s.doc() else { return Value::Nil };
if crate::cmd::blocks::refedit::locked(d, owner) {
return Value::Nil;
}
let Some((expected, now)) = record_list(d, name, owner, slot) else { return Value::Nil };
// The type, layout, owner, handle and any other group are not the attribute's to change: a
// list that differs from `entget` anywhere but its group 1 value is refused (a SEQEND's
// list too), the drawing untouched.
if !only_value_diff(&expected, list) {
return Value::Nil;
}
match value_edit(&now, &asked) {
None => Value::Nil,
Some(None) => list.clone(),
Some(Some(value)) => {
let ok = ctx.s.doc_mut().is_ok_and(|d| {
d.modify_entity(owner, |e| {
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind
&& let Some(a) = i.attribs.get_mut(slot)
{
a.text.value = value.clone();
}
})
.is_ok()
});
if ok {
ctx.s.touch();
}
if ok { list.clone() } else { Value::Nil }
}
}
}
pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 1, 2)?;
// An INSERT's ATTRIB or SEQEND (#1660) is not an entity of the drawing: its name reaches it.
if let Value::Record(r) = &a[0] {
return Ok(Flow::Value(record_entget(ctx, *r).unwrap_or_default()));
}
let h = ename(&a[0])?;
// The applications whose xdata to list: names or wildcard patterns ("*": every application).
let apps: Option<Vec<String>> = match a.get(1) {
@@ -700,8 +396,21 @@ pub fn entget(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
let (kind, mut tags) = (codec()?.groups)(d, e);
let xdata = apps.map(|apps| xdata_to_list(&e.common.xdata, &apps)).filter(|v| !v.is_nil());
convert_angles(&kind, &mut tags, f64::to_radians);
let head = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))];
let mut items = entity_list(d, head, h, &tags, in_block).to_vec();
let layout = match space_of(d, h) {
Some(Space::Paper(name)) => name,
_ => "Model".into(),
};
let mut items = vec![Value::cons(Value::Int(-1), Value::Ename(h)), Value::cons(Value::Int(0), Value::str(&kind))];
let mut placed_layout = in_block;
for v in groups_to_list(&tags) {
// The layout name follows the AcDbEntity marker, as AutoCAD lists it.
let after_marker = !placed_layout && v.car().as_number() == Some(100.0) && matches!(v.cdr(), Value::Str(ref s) if &**s == "AcDbEntity");
items.push(v);
if after_marker {
items.push(Value::cons(Value::Int(410), Value::str(&layout)));
placed_layout = true;
}
}
if let Some(x) = xdata {
items.push(Value::cons(Value::Int(-3), x));
}
@@ -989,12 +698,7 @@ fn end_block(ctx: &mut Ctx<'_>) -> Value {
pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 1, 1)?;
let list = &a[0];
let name = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr());
// An INSERT's record takes a value edit only (#1660); any other edit of one is refused.
if let Some(Value::Record(r)) = name {
return Ok(Flow::Value(entmod_attrib(ctx, list, r)));
}
let Some(Value::Ename(h)) = name else {
let Some(Value::Ename(h)) = list.iter().find(|v| v.car().as_number() == Some(-1.0)).map(|v| v.cdr()) else {
return Err(LispError::bad_arg("lentityp", &Value::Nil));
};
let Some(old) = ctx.s.doc().ok().and_then(|d| d.entity(h)).cloned() else { return Ok(Flow::Value(Value::Nil)) };
@@ -1038,15 +742,9 @@ pub fn entmod(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
Ok(Flow::Value(if ok { list.clone() } else { Value::Nil }))
}
/// `(entupd ename)`: redraw an entity (the canvas redraws on its own). For an INSERT's record
/// (#1660) its reference: the record's name while it holds.
/// `(entupd ename)`: redraw an entity (the canvas redraws on its own).
pub fn entupd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 1, 1)?;
if let Value::Record(r) = &a[0] {
let holds = record_of(ctx, *r).is_some();
ctx.s.touch();
return Ok(Flow::Value(if holds { a[0].clone() } else { Value::Nil }));
}
let h = ename(&a[0])?;
ctx.s.touch();
Ok(Flow::Value(if ctx.s.doc().is_ok_and(|d| d.entity(h).is_some()) { Value::Ename(h) } else { Value::Nil }))
@@ -1055,18 +753,10 @@ pub fn entupd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
/// `(entdel ename)`: delete an entity, or bring back one this routine's drawing deleted.
pub fn entdel(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 1, 1)?;
// An INSERT's ATTRIB or SEQEND is the reference's: it is not deleted on its own (#1660).
if matches!(a[0], Value::Record(_)) {
return Ok(Flow::Value(Value::Nil));
}
let h = ename(&a[0])?;
let Ok(d) = ctx.s.doc_mut() else { return Ok(Flow::Value(Value::Nil)) };
if let Some(space) = d.space_of(h) {
if let Some(e) = d.remove_entity(h) {
// The names of its records went with it: `entdel` bringing it back brings none back.
if let Some(names) = ctx.s.record_names() {
names.erased(&e);
}
ctx.env.deleted.insert(h, (space, e));
ctx.s.touch();
return Ok(Flow::Value(Value::Ename(h)));
@@ -1162,41 +852,24 @@ pub fn entlast(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
pub fn entnext(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 0, 1)?;
let after = match a.first() {
None | Some(Value::Nil) => None,
// From a record of an INSERT (#1660): the next record of its run, and after its SEQEND the
// next main entity after the INSERT. A name that no longer holds names nothing.
Some(Value::Record(r)) => {
let Some((owner, slot)) = record_of(ctx, *r) else { return Ok(Flow::Value(Value::Nil)) };
let attribs = ctx.s.doc().ok().and_then(|d| insert_attribs(d, owner)).map_or(0, <[cadcraft_doc::Attrib]>::len);
if slot < attribs {
return Ok(Flow::Value(name_record(ctx, owner, slot.saturating_add(1)).map(Value::Record).unwrap_or_default()));
}
Some(owner)
// From an entity of a block definition: the next one in that block, nil after the last (#1700).
if let Some(v) = a.first().filter(|v| !v.is_nil()) {
let h = ename(v)?;
if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none())
&& let Some((_, next)) = block_slots(ctx).get(&h)
{
return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()));
}
}
let order = handles_in_order(ctx);
let next = match a.first() {
None | Some(Value::Nil) => order.first().copied(),
Some(v) => {
let h = ename(v)?;
// From an entity of a block definition: the next one in that block, nil after the last (#1700).
if ctx.s.doc().is_ok_and(|d| d.entity(h).is_none())
&& let Some((_, next)) = block_slots(ctx).get(&h)
{
return Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()));
}
// An INSERT with attributes is followed by its ATTRIBs and its SEQEND (#1660): its
// first ATTRIB, or nil when no name is left to give (the walk stops rather than skip
// records it can't name). A host without the optional record mapping has no such
// records: the walk goes on to the next entity, as it always did.
if crate::cmd::file::entity_sub_record().is_some() && ctx.s.doc().is_ok_and(|d| insert_attribs(d, h).is_some()) {
return Ok(Flow::Value(name_record(ctx, h, 0).map(Value::Record).unwrap_or_default()));
}
Some(h)
let i = order.partition_point(|x| *x <= h);
order.get(i).copied()
}
};
let order = handles_in_order(ctx);
let next = match after {
Some(h) => order.get(order.partition_point(|x| *x <= h)).copied(),
None => order.first().copied(),
};
Ok(Flow::Value(next.map(Value::Ename).unwrap_or_default()))
}
@@ -1478,13 +1151,6 @@ fn compare(h: f64, w: f64, op: &str) -> bool {
pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 0, 2)?;
// A selection set holds objects of the drawing; an INSERT's record (#1660) is not one.
if matches!(a.first(), Some(Value::Record(_))) {
if let Some(ss) = a.get(1) {
pickset(ss)?;
}
return Ok(Flow::Value(Value::Nil));
}
match (a.first(), a.get(1)) {
(None, _) => Ok(Flow::Value(new_pickset(ctx, Vec::new()))),
(Some(e), None) => {
@@ -1506,11 +1172,6 @@ pub fn ssadd(ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
pub fn ssdel(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 2, 2)?;
// Never in a selection set (#1660).
if matches!(a[0], Value::Record(_)) {
pickset(&a[1])?;
return Ok(Flow::Value(Value::Nil));
}
let h = ename(&a[0])?;
let p = pickset(&a[1])?;
let removed = p.items.lock().map(|mut v| {
@@ -1538,11 +1199,6 @@ pub fn ssname(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
pub fn ssmemb(_ctx: &mut Ctx<'_>, a: Vec<Value>) -> Result<Flow, LispError> {
arity(&a, 2, 2)?;
// Never in a selection set (#1660).
if matches!(a[0], Value::Record(_)) {
pickset(&a[1])?;
return Ok(Flow::Value(Value::Nil));
}
let h = ename(&a[0])?;
Ok(Flow::Value(if items(&pickset(&a[1])?).contains(&h) { Value::Ename(h) } else { Value::Nil }))
}
+1 -707
View File
@@ -1,16 +1,11 @@
#![allow(clippy::unwrap_used)]
use cadcraft_doc::Handle;
use serde_json::json;
use super::value::{Value, to_text};
use crate::Session;
use crate::cmd::file::{EntityCodec, set_entity_codec, set_entity_sub_record, set_object_records};
use crate::cmd::file::{EntityCodec, set_entity_codec, set_object_records};
pub(super) fn session() -> Session {
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
// ... and one record after an entity's own (an INSERT's ATTRIBs and SEQEND) for `entnext`.
set_entity_sub_record(cadcraft_io::entity_sub_record);
// ... and non-graphic objects (tables, dictionaries, layouts) as DXF records.
set_object_records(cadcraft_io::object_records);
Session::new()
@@ -1971,704 +1966,3 @@ fn append_checks_the_cell_cap_before_building_its_result() {
assert!(super::value::live_cells() < before + 50_000, "no oversized result was built");
assert_eq!(ok(&mut s, "(setq l nil m nil) (length (append '(1) '(2 3)))"), "3");
}
// ---------------- an INSERT's ATTRIBs and SEQEND (#1660) ----------------
/// A session with block K: a circle and attributes (tag, DXF flags, default value). `entmake`
/// goes through the DXF codec, as in the app.
fn with_attributes(defs: &[(&str, i32, &str)]) -> Session {
let mut s = session();
let mut code =
String::from("(entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 3.0)))");
for (i, (tag, flags, default)) in defs.iter().enumerate() {
let y = 5.0 + 3.0 * i as f64;
code += &format!(
" (entmake '((0 . \"ATTDEF\") (10 0.0 {y:.1} 0.0) (40 . 2.5) (1 . \"{default}\") (3 . \"P{tag}\") (2 . \"{tag}\") (70 . {flags})))"
);
}
code += " (entmake '((0 . \"ENDBLK\")))";
s.cmdline(&format!("(progn {code})")).unwrap();
s.log.clear();
s
}
/// `s` with one reference of K at (10,10), its values `attribs`, and the reference's handle; the
/// LISP global `i` names it.
fn inserted(s: &mut Session, attribs: serde_json::Value) -> Handle {
s.execute("insert", &json!({ "name": "K", "at": [10, 10], "attribs": attribs })).unwrap();
let h = *s.doc().unwrap().model.handles().last().unwrap();
ok(s, &format!("(setq i (handent \"{}\")) i", h.hex()));
h
}
/// Every reference's attributes (tag, value) from the model, in order.
fn attribute_values(s: &Session) -> Vec<(String, String)> {
let d = s.doc().unwrap();
d.model
.iter()
.filter_map(|e| match &e.kind {
cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.iter().map(|a| (a.tag.clone(), a.text.value.clone())).collect::<Vec<_>>()),
_ => None,
})
.flatten()
.collect()
}
/// The records from `i` in order: (type, tag, value) and the SEQEND's owner.
const WALK: &str = r#"(progn
(setq e (entnext i) out nil)
(while (and e (= "ATTRIB" (cdr (assoc 0 (setq ed (entget e))))))
(setq out (append out (list (list (cdr (assoc 0 ed)) (cdr (assoc 2 ed)) (cdr (assoc 1 ed))
(if (equal (cdr (assoc -2 ed)) i) T nil))))
e (entnext e)))
(list out (cdr (assoc 0 ed)) (equal (cdr (assoc -2 ed)) i)))"#;
#[test]
fn entnext_walks_an_inserts_attribs_then_the_seqend_then_the_next_entity() {
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2"), ("T3", 0, "D3")]);
inserted(&mut s, json!({ "T1": "A1", "T3": "A3" }));
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget i)))"), "\"INSERT\"");
assert_eq!(ok(&mut s, "(cdr (assoc 66 (entget i)))"), "1");
assert_eq!(ok(&mut s, WALK), "(((\"ATTRIB\" \"T1\" \"A1\" T) (\"ATTRIB\" \"T2\" \"P2\" T) (\"ATTRIB\" \"T3\" \"A3\" T)) \"SEQEND\" T)");
// After the SEQEND the main order goes on: a line made later is next, then nil.
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget (entnext (entnext (entnext (entnext (entnext i))))))))"), "\"LINE\"");
assert_eq!(ok(&mut s, "(entnext (entlast))"), "nil");
// A reference of a block without attributes is followed by the next main entity, no SEQEND.
let mut s = with_attributes(&[("T1", 0, "D1")]);
s.cmdline("(progn (entmake '((0 . \"BLOCK\") (2 . \"E\") (70 . 2) (10 0.0 0.0 0.0))) (entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (entmake '((0 . \"ENDBLK\"))))").unwrap();
s.execute("insert", &json!({ "name": "E", "at": [0, 0] })).unwrap();
let plain = *s.doc().unwrap().model.handles().last().unwrap();
s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap();
assert_eq!(ok(&mut s, &format!("(cdr (assoc 0 (entget (entnext (handent \"{}\")))))", plain.hex())), "\"LINE\"");
// The owner is group -2 in a record's list and not 330, and the reference's own list has
// neither (as `entity_groups` keeps it).
inserted(&mut s, json!({ "T1": "A1" }));
assert_eq!(ok(&mut s, "(assoc 330 (entget (entnext i)))"), "nil");
assert!(attribute_values(&s).iter().any(|(t, v)| t == "T1" && v == "A1"));
}
#[test]
fn entmod_of_an_attrib_changes_only_its_value() {
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]);
inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i) d (entget a) seq (entnext (entnext a)))");
// The value (group 1) is the one edit an ATTRIB's list takes.
let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
assert!(r.contains("(1 . \"A2\")"), "{r}");
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"");
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\"");
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]);
// A list asking for anything else, and any edit of the SEQEND, is refused and changes nothing.
for code in [
"(entmod (subst (cons 2 \"X\") (assoc 2 d) d))",
"(entmod (subst (cons 40 9.0) (assoc 40 d) d))",
"(entmod (subst (cons 8 \"L\") (assoc 8 d) d))",
"(entmod (subst (cons 0 \"SEQEND\") (assoc 0 d) d))",
"(entmod (entget seq))",
// Groups `list_to_groups` does not keep are still the reference's: an edit (or an added
// group) is refused, also when the same list changes group 1.
"(entmod (subst (cons 410 \"Layout2\") (assoc 410 d) d))",
"(entmod (subst (cons -2 a) (assoc -2 d) d))",
"(entmod (append d (list (cons 5 \"FF\"))))",
"(entmod (append d (list (cons 330 a))))",
"(entmod (append d (list (cons 360 \"FF\"))))",
"(entmod (append d (list (cons 102 \"{X\"))))",
"(entmod (subst (cons 1 \"A2\") (assoc 1 d) (subst (cons 410 \"Layout2\") (assoc 410 d) d)))",
// The same items, but the outer list ends in an atom: iterating it would drop the tail
// and accept a list `entget` never returned.
"(progn (setq r \"X\" p (reverse d)) (while p (setq r (cons (car p) r) p (cdr p))) (entmod r))",
] {
assert_eq!(ok(&mut s, code), "nil", "{code}");
}
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "no refused edit changed the value");
// `entdel` of a record, and `entdel` of the SEQEND, do nothing either.
assert_eq!(ok(&mut s, "(progn (entdel a) (entdel seq))"), "nil");
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into()), ("T2".into(), "P2".into())]);
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A2\"", "the name still holds: nothing changed");
// The edit is one undo step: the value goes back with it.
s.undo().unwrap();
assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]);
}
#[test]
fn a_subentity_name_expires_when_its_record_is_rebuilt() {
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 8, "P2")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i))");
// Erased: the records go with the reference.
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
assert_eq!(ok(&mut s, "(list (entget a) (entnext a))"), "(nil nil)");
// Undone: the reference is back, the name given before the Undo is not.
s.undo().unwrap();
assert_eq!(ok(&mut s, "(entget a)"), "nil");
assert_eq!(ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", h.hex())), "\"A1\"");
// ATTSYNC rebuilds the attributes in place: the old name names nothing, the values stay.
ok(&mut s, "(setq b (entnext i))");
s.execute("attsync", &json!({ "name": "K" })).unwrap();
assert_eq!(ok(&mut s, "(entget b)"), "nil");
assert_eq!(attribute_values(&s), [("T1".into(), "A1".into()), ("T2".into(), "P2".into())]);
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
// A name never resolves to another attribute: when the record at its place has another tag
// now, it names nothing (the change makes no new epoch), and a new walk reaches the new tag.
ok(&mut s, "(setq c (entnext i))");
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget c)))"), "\"T1\"");
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind
&& let Some(a) = i.attribs.first_mut()
{
a.tag = "T9".into();
}
})
.unwrap();
assert_eq!(ok(&mut s, "(entget c)"), "nil", "the record at that place has another tag now");
assert_eq!(ok(&mut s, "(list (cdr (assoc 0 (entget (entnext i)))) (cdr (assoc 2 (entget (entnext i)))))"), "(\"ATTRIB\" \"T9\")");
}
#[test]
fn an_empty_attrib_and_a_seqend_have_distinct_names() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i) end (entnext a))");
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget end)))"), "\"SEQEND\"");
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
let mut blank = i.attribs[0].clone();
blank.tag.clear();
i.attribs.push(blank);
}
})
.unwrap();
assert_eq!(ok(&mut s, "(entget end)"), "nil");
assert_eq!(ok(&mut s, "(setq b (entnext a)) (list (cdr (assoc 0 (entget b))) (eq b (entnext a)))"), "(\"ATTRIB\" T)");
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
i.attribs.truncate(1);
}
})
.unwrap();
assert_eq!(ok(&mut s, "(list (entget b) (cdr (assoc 0 (entget (entnext a)))))"), "(nil \"SEQEND\")");
}
#[test]
fn explode_and_burst_retire_the_removed_inserts_record_names() {
for command in ["explode", "burst"] {
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i) end (entnext (entnext a)))");
let original = s.doc().unwrap().entity(h).unwrap().as_ref().clone();
inserted(&mut s, json!({ "T1": "B1" }));
ok(&mut s, "(setq b (entnext i))");
// A host can shorten the run before removal and later reuse the handle.
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let cadcraft_doc::EntityKind::Insert(i) = &mut e.kind {
i.attribs.truncate(1);
}
})
.unwrap();
let result = s.execute(command, &json!({ "handles": [h.hex()] })).unwrap();
assert!(!result["handles"].as_array().unwrap().is_empty(), "{command} creates pieces");
assert!(s.doc().unwrap().entity(h).is_none(), "{command} removes the reference");
s.doc_mut().unwrap().model.push(original);
assert_eq!(ok(&mut s, "(list (entget a) (entget end) (cdr (assoc 1 (entget b))))"), "(nil nil \"B1\")", "{command}");
}
}
#[test]
fn entmod_obeys_the_refedit_working_set_for_attrib_owners() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
let editing = inserted(&mut s, json!({ "T1": "E1" }));
let outside = inserted(&mut s, json!({ "T1": "A1" }));
s.execute("refedit", &json!({ "handle": editing.hex() })).unwrap();
let read = "(cdr (assoc 1 (entget (entnext i))))";
let edit = r#"(progn (setq d (entget (entnext i))) (entmod (subst (cons 1 "A2") (assoc 1 d) d)))"#;
assert_eq!(ok(&mut s, read), "\"A1\"");
assert_eq!(ok(&mut s, edit), "nil");
assert_eq!(ok(&mut s, read), "\"A1\"");
s.execute("refset", &json!({ "add": [outside.hex()] })).unwrap();
assert_ne!(ok(&mut s, edit), "nil");
assert_eq!(ok(&mut s, read), "\"A2\"");
}
#[test]
fn a_restored_reference_does_not_revive_an_old_name() {
// entdel of the reference, then entdel again to bring it back: the name given before the
// first entdel names nothing, also after the reference returns.
let mut s = with_attributes(&[("T1", 0, "D1")]);
inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i))");
assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil");
assert_eq!(ok(&mut s, "(progn (entdel i) (entget a))"), "nil", "the name must not come back");
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
// ERASE, then OOPS: the same. Erasing expires the names it took with it.
let mut s = with_attributes(&[("T1", 0, "D1")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i))");
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
assert_eq!(ok(&mut s, "(entget a)"), "nil");
s.execute("oops", &json!({})).unwrap();
assert_eq!(ok(&mut s, "(entget a)"), "nil", "OOPS must not revive the name");
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
}
#[test]
fn erasing_another_object_keeps_an_attrib_name() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i) d (entget a))");
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
let line = *s.doc().unwrap().model.handles().last().unwrap();
// Erasing another object leaves the reference and its records as they were: the name holds
// and takes the value edit it always took.
s.execute("erase", &json!({ "handles": [line.hex()] })).unwrap();
assert_eq!(ok(&mut s, "(cdr (assoc 2 (entget a)))"), "\"T1\"");
let r = ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
assert!(r.contains("(1 . \"A2\")"), "{r}");
assert_eq!(attribute_values(&s), [("T1".into(), "A2".into())]);
// Erasing the reference itself ends its names, and OOPS bringing it back revives none.
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
assert_eq!(ok(&mut s, "(entget a)"), "nil");
s.execute("oops", &json!({})).unwrap();
assert_eq!(ok(&mut s, "(entget a)"), "nil", "the name of an erased reference stays dead");
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\"");
}
#[test]
fn entdel_of_another_object_keeps_an_attrib_name() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i))");
s.execute("line", &json!({ "points": [[0, -10], [10, -10]] })).unwrap();
ok(&mut s, "(setq line (entlast))");
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget line)))"), "\"LINE\"");
ok(&mut s, "(entdel line)");
assert_eq!(ok(&mut s, "(entget line)"), "nil");
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\"");
}
#[test]
fn a_name_given_in_the_block_editor_never_resolves_in_the_host() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
inserted(&mut s, json!({ "T1": "A1" }));
s.execute("bedit", &json!({ "name": "K" })).unwrap();
// A reference made in the editor's drawing, named there. The editor starts from the host's
// drawing, so its handle is the one the host gives its next new object.
s.execute("insert", &json!({ "name": "K", "at": [40, 40], "attribs": { "T1": "E1" } })).unwrap();
let editor = *s.doc().unwrap().model.handles().last().unwrap();
ok(&mut s, &format!("(setq a (entnext (handent \"{}\")))", editor.hex()));
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"E1\"");
s.execute("bclose", &json!({ "save": false })).unwrap();
// The host's next reference takes the handle the editor's reference had: the name given in
// the editor must not reach its ATTRIB, or `entmod` through it would edit the wrong one.
s.execute("insert", &json!({ "name": "K", "at": [80, 80], "attribs": { "T1": "H1" } })).unwrap();
let host = *s.doc().unwrap().model.handles().last().unwrap();
assert_eq!(host, editor, "the host takes the handle the editor's reference had");
assert_eq!(ok(&mut s, "(entget a)"), "nil");
assert_eq!(ok(&mut s, "(entdel a)"), "nil");
assert_eq!(
ok(&mut s, &format!("(cdr (assoc 1 (entget (entnext (handent \"{}\")))))", host.hex())),
"\"H1\"",
"the host's own attribute is untouched"
);
}
#[test]
fn without_a_record_provider_entnext_walks_the_next_entity() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
inserted(&mut s, json!({ "T1": "A1" }));
s.execute("line", &json!({ "points": [[0, -20], [10, -20]] })).unwrap();
// A host that installed no provider has no records to name: the walk goes on to the next
// main entity as it always did, rather than answering nil at the reference.
let next = crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(entnext i)"));
assert_ne!(next, "nil");
assert_eq!(crate::cmd::file::without_entity_sub_record(|| ok(&mut s, "(cdr (assoc 0 (entget (entnext i))))")), "\"LINE\"");
}
#[test]
fn a_redo_does_not_revive_an_old_name() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i) d (entget a))");
ok(&mut s, "(entmod (subst (cons 1 \"A2\") (assoc 1 d) d))");
s.undo().unwrap();
assert_eq!(ok(&mut s, "(entget a)"), "nil");
s.redo().unwrap();
assert_eq!(ok(&mut s, "(entget a)"), "nil", "Redo must not revive the name");
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A2\"");
}
#[test]
fn a_block_replace_expires_an_old_attrib_name() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
// A replacement block with the same tag as K's first attribute: without the expiry, the old
// name would keep naming that place and return the new record.
s.cmdline(
"(progn (entmake '((0 . \"BLOCK\") (2 . \"L\") (70 . 2) (10 0.0 0.0 0.0))) \
(entmake '((0 . \"ATTDEF\") (10 0.0 0.0 0.0) (40 . 2.5) (1 . \"Z1\") (3 . \"P\") (2 . \"T1\") (70 . 0))) \
(entmake '((0 . \"ENDBLK\"))))",
)
.unwrap();
inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i))");
s.execute("blockreplace", &json!({ "block": "K", "with": "L" })).unwrap();
assert_eq!(ok(&mut s, "(entget a)"), "nil", "-BLOCKREPLACE rebuilt the record");
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
}
#[test]
fn a_reinsert_after_undo_takes_the_handle_and_no_old_name() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i))");
// U takes the reference back; INSERT then gives a new one the handle it had.
s.undo().unwrap();
assert!(s.doc().unwrap().entity(h).is_none());
let again = inserted(&mut s, json!({ "T1": "B1" }));
assert_eq!(again, h, "the same handle");
assert_eq!(ok(&mut s, "(list (entget a) (cdr (assoc 1 (entget (entnext i)))))"), "(nil \"B1\")");
}
/// A drawing with one reference of `attribs` attributes (all value V), for the bounds.
fn drawing_with_attributes(attribs: usize) -> (Session, Handle) {
let text = |v: &str| cadcraft_doc::Text {
insert: cadcraft_geom::Vec3::ZERO,
align_pt: None,
height: 1.0,
value: v.into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: cadcraft_doc::HAlign::Left,
valign: cadcraft_doc::VAlign::Baseline,
backwards: false,
upside_down: false,
};
let mut d = cadcraft_doc::Drawing::new_metric();
let list = (0..attribs)
.map(|i| cadcraft_doc::Attrib {
tag: format!("T{i}"),
text: text("V"),
invisible: false,
constant: false,
prompt: String::new(),
props: cadcraft_doc::AttribProps::default(),
multiline: None,
modes: cadcraft_doc::AttribModes::default(),
})
.collect();
let insert = cadcraft_doc::Insert { block: "B".into(), attribs: list, ..cadcraft_doc::Insert::default() };
let h = d.add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), cadcraft_doc::EntityKind::Insert(insert)).expect("add");
let mut s = session();
s.open_drawing(d, "attributes", None);
ok(&mut s, &format!("(setq i (handent \"{}\"))", h.hex()));
(s, h)
}
/// The number of records a walk from `i` names.
const COUNT: &str = "(progn (setq e (entnext i) n 0) (while e (setq n (1+ n) e (entnext e))) n)";
#[test]
fn a_session_names_at_most_65536_records_and_nothing_changes() {
let (mut s, h) = drawing_with_attributes(65_537);
assert_eq!(ok(&mut s, COUNT), "65536");
// The names given hold: a second walk is the same, and the drawing kept every attribute.
assert_eq!(ok(&mut s, COUNT), "65536");
// Erasing and bringing the reference back frees the 65,536 names it held: the old name names
// nothing, and a new walk can name the records again.
ok(&mut s, "(setq a (entnext i))");
ok(&mut s, "(progn (entdel i) (entdel i))");
assert_eq!(ok(&mut s, "(entget a)"), "nil");
assert_eq!(ok(&mut s, COUNT), "65536");
let d = s.doc().unwrap();
let kept = d.entity(h).and_then(|e| match &e.kind {
cadcraft_doc::EntityKind::Insert(i) => Some(i.attribs.len()),
_ => None,
});
assert_eq!(kept, Some(65_537));
}
#[test]
fn a_new_object_at_any_handle_is_never_a_record() {
// A hostile $HANDSEED at the top of the range: the line made after the walk takes that
// handle, and the record keeps its own name, which is no handle.
let (mut s, _) = drawing_with_attributes(1);
s.doc_mut().unwrap().handseed = u64::MAX - 1;
ok(&mut s, "(setq a (entnext i))");
assert_eq!(
ok(&mut s, r#"(progn (entmake '((0 . "LINE") (10 0.0 0.0 0.0) (11 1.0 0.0 0.0))) (cdr (assoc 5 (entget (entlast)))))"#),
"\"FFFFFFFFFFFFFFFE\""
);
assert_eq!(
ok(&mut s, "(list (cdr (assoc 0 (entget a))) (eq a (entlast)) (entdel a) (cdr (assoc 0 (entget (entlast)))))"),
"(\"ATTRIB\" nil nil \"LINE\")"
);
}
#[test]
fn objects_at_the_top_of_the_handle_range_walk_as_objects() {
let (mut s, _) = drawing_with_attributes(1);
{
let d = s.doc_mut().unwrap();
d.handseed = u64::MAX;
for handle in [Handle(u64::MAX - 1), Handle(u64::MAX)] {
let line =
cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::ZERO, b: cadcraft_geom::Vec3::new(1.0, 0.0, 0.0) });
d.model.push(cadcraft_doc::Entity { handle, common: cadcraft_doc::Common::default(), kind: line });
}
}
ok(&mut s, "(setq a (entnext i))");
// The lines' handles are theirs: `entnext` of the first finds the second, then the end.
assert_eq!(ok(&mut s, "(equal (entnext (handent \"FFFFFFFFFFFFFFFE\")) (handent \"FFFFFFFFFFFFFFFF\"))"), "T");
assert_eq!(ok(&mut s, "(entnext (handent \"FFFFFFFFFFFFFFFF\"))"), "nil");
// The record, a table record and the lines each keep their own name.
assert_eq!(
ok(&mut s, "(list (cdr (assoc 0 (entget a))) (equal a (tblobjname \"LAYER\" \"0\")) (equal a (handent \"FFFFFFFFFFFFFFFE\")))"),
"(\"ATTRIB\" nil nil)"
);
}
#[test]
fn a_record_name_is_an_entity_name_but_no_handle() {
let mut s = with_attributes(&[("T1", 0, "D1"), ("T2", 0, "D2")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i) b (entnext a))");
assert_eq!(ok(&mut s, "(type a)"), "ENAME");
// The same record has the same name on every walk; another record and the reference have
// their own.
assert_eq!(ok(&mut s, "(list (eq a (entnext i)) (equal a (entnext i)) (eq a b) (eq a i) (equal a i))"), "(T T nil nil nil)");
// It prints as the reference's handle, a dot and its number: never a handle's text.
let printed = ok(&mut s, "a");
assert!(printed.starts_with(&format!("<Entity name: {:x}.", h.0)) && printed.ends_with('>'), "{printed}");
// No handle reaches it: its list has no group 5, and `handent` of the reference's handle is
// the reference.
assert_eq!(ok(&mut s, "(list (assoc 5 (entget a)) (eq a (handent (cdr (assoc 5 (entget i))))))"), "(nil nil)");
// A DXF group cannot point at it: `entmake` of a list that does is refused.
assert_eq!(ok(&mut s, "(entmake (list '(0 . \"LINE\") '(10 0.0 0.0 0.0) '(11 1.0 0.0 0.0) (cons 340 a)))"), "nil");
}
#[test]
fn selection_sets_and_commands_take_no_record() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i) ss (ssadd i))");
// A selection set holds objects of the drawing; a record is not one on its own.
assert_eq!(ok(&mut s, "(list (ssadd a) (ssadd a ss) (sslength ss) (ssmemb a ss) (ssdel a ss) (sslength ss))"), "(nil nil 1 nil nil 1)");
// A command given the name picks nothing: the reference stays, and the name holds.
ok(&mut s, "(command \"_.ERASE\" a \"\")");
assert!(s.doc().unwrap().entity(h).is_some());
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget a)))"), "\"A1\"");
}
#[test]
fn entupd_of_a_record_answers_its_name_while_it_holds() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i) d (entget a))");
assert_eq!(ok(&mut s, "(progn (entmod (subst (cons 1 \"A2\") (assoc 1 d) d)) (eq (entupd a) a))"), "T");
s.execute("erase", &json!({ "handles": [h.hex()] })).unwrap();
assert_eq!(ok(&mut s, "(entupd a)"), "nil");
}
#[test]
fn a_record_name_holds_while_commands_keep_its_record() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i))");
// Moving the reference, or changing its colour, keeps its records in their places.
s.execute("move", &json!({ "handles": [h.hex()], "delta": [5, 5] })).unwrap();
s.execute("chprop", &json!({ "handles": [h.hex()], "color": 1 })).unwrap();
assert_eq!(ok(&mut s, "(list (cdr (assoc 1 (entget a))) (eq a (entnext i)))"), "(\"A1\" T)");
}
#[test]
fn each_record_name_is_one_entry_and_walking_again_adds_none() {
const N: usize = 64;
let (mut s, _) = drawing_with_attributes(N);
let before = s.state().unwrap().doc.clone();
ok(&mut s, "(setq e nil)");
// The R3 pattern: each new name, then state access. Nothing is copied or replayed.
for _ in 0..=N {
ok(&mut s, "(setq e (if e (entnext e) (entnext i)))");
let _ = s.state_mut().unwrap();
}
let uid = s.state().unwrap().uid;
let held = |s: &Session| s.lisp.records.get(&uid).map_or(0, super::drawing::RecordNames::count);
assert_eq!(held(&s), N + 1, "the attributes and the SEQEND, one entry each");
assert_eq!(ok(&mut s, COUNT), (N + 1).to_string());
assert_eq!(held(&s), N + 1, "a walk again gives the same names");
assert!(std::sync::Arc::ptr_eq(&before, &s.state().unwrap().doc), "naming changes nothing in the drawing");
// Undo or redo ends them: the next walk starts over with as many.
s.execute("line", &json!({ "points": [[0, -4], [1, -4]] })).unwrap();
s.undo().unwrap();
assert_eq!(ok(&mut s, COUNT), (N + 1).to_string());
assert_eq!(held(&s), N + 1);
}
/// A saved drawing with one named attribute. The name comes from the command line, which does
/// not run the after-command pass.
fn clean_named() -> Session {
let mut s = with_attributes(&[("T1", 0, "D1")]);
inserted(&mut s, json!({ "T1": "A1" }));
{
let st = s.state_mut().unwrap();
st.saved = st.doc.clone();
st.undo.clear();
st.redo.clear();
}
s.cmdline("(setq a (entnext i))").unwrap();
assert_eq!(ok(&mut s, "(cdr (assoc 0 (entget a)))"), "\"ATTRIB\"");
assert!(!s.state().unwrap().is_dirty(), "naming from the command line saves nothing");
s
}
#[test]
fn issued_name_reads_keep_the_drawing_clean() {
let mut s = clean_named();
s.cmdline("(getvar \"DBMOD\")").unwrap();
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved));
// A programmatic read runs the after-command pass. That pass must not make a saved drawing dirty.
s.execute("lisp", &json!({ "code": "(entget a)" })).unwrap();
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &s.state().unwrap().saved));
assert_eq!(s.state().unwrap().undo.len(), 0, "a read is not an undo step");
}
#[test]
fn issued_name_selection_keeps_the_drawing_clean() {
let mut s = clean_named();
let saved = s.state().unwrap().saved.clone();
s.execute("select", &json!({ "clear": true })).unwrap();
assert!(s.state().unwrap().selection.is_empty());
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved));
assert!(!s.state().unwrap().is_dirty());
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
assert_eq!(s.state().unwrap().undo.len(), 0, "clearing an empty selection is not an undo step");
}
#[test]
fn issued_name_undo_restores_the_saved_drawing() {
let mut s = clean_named();
let saved = s.state().unwrap().saved.clone();
// A selection change writes no undo step. If it also changes the drawing, the next command
// records that copy, and undo cannot return to the saved drawing.
s.execute("select", &json!({ "clear": true })).unwrap();
assert_eq!(s.state().unwrap().undo.len(), 0);
s.execute("line", &json!({ "points": [[0, -3], [1, -3]] })).unwrap();
assert!(s.undo().unwrap().is_some());
assert!(std::sync::Arc::ptr_eq(&s.state().unwrap().doc, &saved), "undo returns the saved drawing, not a reservation copy");
assert!(!s.state().unwrap().is_dirty());
assert_eq!(ok(&mut s, "(getvar \"DBMOD\")"), "0");
}
#[test]
fn a_name_given_in_the_host_never_resolves_in_the_block_editor() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i))");
let mut same = cadcraft_doc::Entity::clone(s.doc().unwrap().entity(h).unwrap());
if let cadcraft_doc::EntityKind::Insert(ins) = &mut same.kind
&& let Some(at) = ins.attribs.first_mut()
{
at.text.value = "E1".into();
}
s.execute("bedit", &json!({ "name": "K" })).unwrap();
// An object of the editor's drawing with the handle the host's reference has: the host's
// name must not reach its ATTRIB.
s.doc_mut().unwrap().model.push(same);
assert_eq!(ok(&mut s, "(entget a)"), "nil");
s.execute("bclose", &json!({ "save": false })).unwrap();
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"A1\"");
}
#[test]
fn a_drawing_put_back_after_a_refused_change_ends_its_names() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
let before = s.state().unwrap().doc.clone();
let h = inserted(&mut s, json!({ "T1": "A1" }));
ok(&mut s, "(setq a (entnext i))");
// A change with a number that is not finite: the drawing goes back as it was, without the
// reference the name was given for.
let bad = cadcraft_doc::EntityKind::Line(cadcraft_doc::Line { a: cadcraft_geom::Vec3::new(f64::NAN, 0.0, 0.0), b: cadcraft_geom::Vec3::ZERO });
s.doc_mut().unwrap().add(&cadcraft_doc::Space::Model, cadcraft_doc::Common::default(), bad).unwrap();
assert!(s.refuse_non_finite(None, &before, &[], "line").is_err());
assert!(s.doc().unwrap().entity(h).is_none());
// The next reference takes the handle back: the old name names nothing in it.
assert_eq!(inserted(&mut s, json!({ "T1": "B1" })), h);
assert_eq!(ok(&mut s, "(entget a)"), "nil");
assert_eq!(ok(&mut s, "(cdr (assoc 1 (entget (entnext i))))"), "\"B1\"");
}
/// MOCORO's own Undo puts the drawing from before the Copy back, handle seed included.
/// The next Copy is given that handle again. The name of the removed copy's attribute
/// must not read it, walk from it, or change it.
#[test]
fn mocoro_undo_does_not_let_an_old_record_name_reach_the_next_copy() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
inserted(&mut s, json!({ "T1": "A1" }));
ok(
&mut s,
r#"(progn
(sssetfirst nil nil)
(command "_.MOCORO" i "" '(0 0) "_Copy" '(10 0))
(setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c) v (cdr (assoc 1 (entget a))))
(command "_Undo" "_Copy" '(20 0) "_eXit"))"#,
);
// The name was given for a copy with a handle of its own, and it read that copy's attribute.
// The copy made after the Undo has the removed copy's handle.
assert_eq!(ok(&mut s, "(list (= ch (cdr (assoc 5 (entget i)))) v (= ch (cdr (assoc 5 (entget (entlast))))))"), "(nil \"A1\" T)");
assert_eq!(
ok(
&mut s,
r#"(progn
(setq d (entget a) w (entnext a))
(if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d)))
(list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"#
),
"(T T \"A1\")"
);
}
/// A grip Copy's Undo is the same kind of restore: the next copy reuses the handle.
#[test]
fn grip_copy_undo_does_not_let_an_old_record_name_reach_the_next_copy() {
let mut s = with_attributes(&[("T1", 0, "D1")]);
let h = inserted(&mut s, json!({ "T1": "A1" }));
s.start_grip_edit(&[(h, 0)]).unwrap();
// Enter leaves STRETCH for MOVE, which copies the reference whole.
s.input(crate::Input::Enter).unwrap();
s.input(crate::Input::Keyword("Copy".into())).unwrap();
s.input(crate::Input::Point(cadcraft_geom::Vec2::new(20.0, 10.0))).unwrap();
// The name is given for a copy with a handle of its own, and it reads that copy's attribute.
assert_eq!(
ok(
&mut s,
r#"(progn
(setq c (entlast) ch (cdr (assoc 5 (entget c))) a (entnext c))
(list (= ch (cdr (assoc 5 (entget i)))) (cdr (assoc 1 (entget a)))))"#
),
"(nil \"A1\")"
);
s.input(crate::Input::Keyword("Undo".into())).unwrap();
s.input(crate::Input::Point(cadcraft_geom::Vec2::new(30.0, 10.0))).unwrap();
assert_eq!(ok(&mut s, "(= ch (cdr (assoc 5 (entget (entlast)))))"), "T", "the next copy takes the removed copy's handle");
assert_eq!(
ok(
&mut s,
r#"(progn
(setq d (entget a) w (entnext a))
(if d (entmod (subst (cons 1 "WRONG") (assoc 1 d) d)))
(list (null d) (null w) (cdr (assoc 1 (entget (entnext (entlast)))))))"#
),
"(T T \"A1\")"
);
}
+2 -27
View File
@@ -12,7 +12,7 @@
//! ([`charge_bytes`]).
use std::cell::Cell;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::atomic::{AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use cadcraft_doc::Handle;
@@ -207,26 +207,6 @@ pub enum BuiltinKind {
Special(super::eval::Special),
}
/// The name AutoLISP gives an INSERT's ATTRIB or SEQEND (#1660). Those records have no handle of
/// their own in the drawing, so their names are not handles: `id` comes from one count for the
/// whole process and is never given again, so no object of any drawing, and no other record,
/// ever has it. `owner` is the reference's handle, for printing. What a name stands for is kept
/// by the session; a name that no longer holds names nothing.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RecordName {
pub(crate) owner: Handle,
pub(crate) id: u64,
}
impl RecordName {
/// A name never given before, for a record of `owner`; `None` once the count runs out.
pub(crate) fn fresh(owner: Handle) -> Option<RecordName> {
static NEXT: AtomicU64 = AtomicU64::new(1);
let id = NEXT.try_update(Ordering::Relaxed, Ordering::Relaxed, |n| n.checked_add(1)).ok()?;
Some(RecordName { owner, id })
}
}
#[derive(Clone, Debug, Default)]
pub enum Value {
#[default]
@@ -237,8 +217,6 @@ pub enum Value {
Sym(Sym),
Cons(Arc<Cons>),
Ename(Handle),
/// An INSERT's ATTRIB or SEQEND (#1660): an entity name that is no handle.
Record(RecordName),
PickSet(PickSet),
File(u32),
Subr(&'static Builtin),
@@ -332,7 +310,7 @@ impl Value {
Value::Str(_) => "STR",
Value::Sym(_) => "SYM",
Value::Cons(_) => "LIST",
Value::Ename(_) | Value::Record(_) => "ENAME",
Value::Ename(_) => "ENAME",
Value::PickSet(_) => "PICKSET",
Value::File(_) => "FILE",
Value::Subr(_) => "SUBR",
@@ -445,7 +423,6 @@ fn atom_equal(a: &Value, b: &Value, fuzz: f64) -> bool {
(Value::Str(x), Value::Str(y)) => x == y,
(Value::Sym(x), Value::Sym(y)) => x == y,
(Value::Ename(x), Value::Ename(y)) => x == y,
(Value::Record(x), Value::Record(y)) => x == y,
(Value::File(x), Value::File(y)) => x == y,
(Value::PickSet(x), Value::PickSet(y)) => x.id == y.id,
(Value::Subr(x), Value::Subr(y)) => std::ptr::eq(*x, *y),
@@ -590,8 +567,6 @@ fn write_value(out: &mut String, v: &Value, escape: bool, depth: usize) {
out.push(')');
}
Value::Ename(h) => out.push_str(&format!("<Entity name: {:x}>", h.0)),
// The reference's handle, a dot and the record's number: never a handle's text.
Value::Record(r) => out.push_str(&format!("<Entity name: {:x}.{:x}>", r.owner.0, r.id)),
Value::PickSet(p) => out.push_str(&format!("<Selection set: {:x}>", p.id)),
Value::File(f) => out.push_str(&format!("#<FILE {f:x}>")),
Value::Subr(b) => out.push_str(&format!("#<SUBR @{} {}>", "0", b.name)),
+2 -2
View File
@@ -16,7 +16,7 @@ impl Session {
if let Some((doc, sel, uid)) = before
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == uid)
{
st.restore_drawing(doc);
st.doc = doc;
st.selection = sel;
}
Err(EngineError::Internal(id.into(), crate::guard::message(&*p)))
@@ -50,7 +50,7 @@ impl Session {
if let Some((doc, sel, uid)) = &before
&& let Some(st) = self.docs.iter_mut().find(|d| d.uid == *uid)
{
st.restore_drawing(doc.clone());
st.doc = doc.clone();
st.selection = sel.clone();
}
return Err(EngineError::Internal(id.into(), msg));
+2 -2
View File
@@ -479,7 +479,7 @@ impl Session {
Err(EngineError::Internal(id, m)) => {
// Restore and end the command.
if let Ok(st) = self.state_mut() {
st.restore_drawing(run.before.clone());
st.doc = run.before.clone();
}
self.echo(format!("Internal error in {id}: {m}"));
self.resume_suspended();
@@ -501,7 +501,7 @@ impl Session {
let (id, before, selection) = (run.id.clone(), run.before.clone(), run.selection_before.clone());
if let Err(p) = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| self.finish_guarded(run, cancelled))) {
if let Ok(st) = self.state_mut() {
st.restore_drawing(before);
st.doc = before;
st.selection = selection;
}
self.echo(format!("Internal error in {id}: {}", crate::guard::message(&*p)));
-203
View File
@@ -1,203 +0,0 @@
//! AutoLISP's name of an INSERT's ATTRIB keeps naming that attribute when a command, another
//! session, another document or another thread gives out handles in the drawing or in a copy of
//! it, and installs the result (#1660).
use std::sync::Arc;
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{EntityCodec, IoHooks, set_entity_codec, set_entity_sub_record, set_io, set_object_records};
use cadcraft_engine::doc::geom::Vec3;
use cadcraft_engine::doc::{Block, Common, Drawing, Entity, EntityKind, Handle, Line, Space};
use cadcraft_engine::lisp::value::to_text;
use serde_json::json;
use crate::temp_dir::TempDir;
fn session() -> Session {
set_entity_codec(EntityCodec { groups: cadcraft_io::entity_groups, entity: cadcraft_io::entity_from_groups });
set_entity_sub_record(cadcraft_io::entity_sub_record);
set_object_records(cadcraft_io::object_records);
set_io(IoHooks {
read: |bytes, name| cadcraft_io::read(bytes, name).map_err(|e| e.to_string()),
write: |drawing, name| cadcraft_io::write(drawing, name).map_err(|e| e.to_string()),
plot: None,
});
Session::new()
}
fn eval(s: &mut Session, code: &str) -> String {
match s.lisp_eval(code, false, true, Vec::new()) {
Ok(Some(Ok(v))) => to_text(&v, true),
Ok(Some(Err(e))) => panic!("{code}: {e}"),
Ok(None) => panic!("{code}: did not finish"),
Err(e) => panic!("{code}: {e}"),
}
}
/// Block K with one attribute, one reference, and `i` naming that reference.
fn attributed() -> Session {
let mut s = session();
s.cmdline(
"(progn (entmake '((0 . \"BLOCK\") (2 . \"K\") (70 . 2) (10 0.0 0.0 0.0))) \
(entmake '((0 . \"CIRCLE\") (10 0.0 0.0 0.0) (40 . 1.0))) \
(entmake '((0 . \"ATTDEF\") (10 0.0 5.0 0.0) (40 . 2.5) (1 . \"D1\") (3 . \"P\") (2 . \"T1\") (70 . 0))) \
(entmake '((0 . \"ENDBLK\"))))",
)
.unwrap();
let ins = s.execute("insert", &json!({ "name": "K", "at": [10, 10], "attribs": { "T1": "A1" } })).unwrap();
let href = ins["handle"].as_str().unwrap();
eval(&mut s, &format!("(setq i (handent \"{href}\"))"));
s
}
/// The command line names the reference's first ATTRIB `a`, with `$HANDSEED` one below the top:
/// the next handle the drawing, or a copy of it, gives out. The command line does not run the
/// after-command pass.
fn name_at_top(s: &mut Session) {
s.doc_mut().unwrap().handseed = u64::MAX - 1;
s.cmdline("(setq a (entnext i))").unwrap();
assert_eq!(eval(s, "(cdr (assoc 0 (entget a)))"), "\"ATTRIB\"");
}
/// Every object's handle: model space, layouts and block definitions.
fn every_handle(d: &Drawing) -> Vec<Handle> {
let mut v = d.model.handles();
for l in &d.layouts {
v.extend(l.entities.handles());
}
for b in d.blocks.values() {
v.extend(b.entities.handles());
}
v
}
/// `a` still names the attribute, and no object of the drawing is `a`: whatever handles were
/// given out, each object keeps its own name.
fn assert_kept(s: &mut Session) {
assert_eq!(
eval(s, "(list (cdr (assoc 0 (entget a))) (cdr (assoc 1 (entget a))))"),
"(\"ATTRIB\" \"A1\")",
"the old name still means the attribute"
);
let handles = every_handle(s.doc().unwrap());
for h in handles {
let hex = h.hex();
assert_eq!(eval(s, &format!("(eq a (handent \"{hex}\"))")), "nil", "object {hex} is not the attribute");
}
}
/// A line added to `d` with the drawing's next handle.
fn add_line(d: &mut Drawing) -> Handle {
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).unwrap()
}
/// After a copy of the drawing took `line`, the name still means the attribute and the line is
/// the line.
fn assert_line_and_name(s: &mut Session, line: Handle) {
assert_kept(s);
let hex = line.hex();
assert_eq!(eval(s, &format!("(cdr (assoc 0 (entget (handent \"{hex}\"))))")), "\"LINE\"");
}
fn one_line(dir: &TempDir) -> String {
let mut d = Drawing::new_metric();
add_line(&mut d);
dir.file("one-line.dxf", cadcraft_io::write_dxf(&d))
}
#[test]
fn another_sessions_read_leaves_a_record_name_alone() {
// Session A names an attribute and keeps a copy of its drawing; session B, which named
// nothing, is read; then A's copy gives out a handle and A installs it.
let mut a = attributed();
let b = attributed();
name_at_top(&mut a);
let mut copy = a.doc().unwrap().clone();
let _ = b.doc().unwrap();
let line = add_line(&mut copy);
*a.doc_mut().unwrap() = copy;
assert_line_and_name(&mut a, line);
}
#[test]
fn a_copy_edited_on_another_thread_leaves_a_record_name_alone() {
let mut a = attributed();
name_at_top(&mut a);
let copy = a.doc().unwrap().clone();
let (copy, line) = std::thread::spawn(move || {
let mut copy = copy;
let line = add_line(&mut copy);
(copy, line)
})
.join()
.unwrap();
*a.doc_mut().unwrap() = copy;
assert_line_and_name(&mut a, line);
}
#[test]
fn a_copy_made_while_another_document_is_current_leaves_a_record_name_alone() {
let mut s = attributed();
name_at_top(&mut s);
let first = s.active;
let mut copy = s.doc().unwrap().clone();
s.open_drawing(Drawing::new_metric(), "other", None);
let _ = s.doc().unwrap();
let line = add_line(&mut copy);
s.active = first;
*s.doc_mut().unwrap() = copy;
assert_line_and_name(&mut s, line);
}
#[test]
fn insert_from_file_keeps_an_attrib_name() {
let mut s = attributed();
name_at_top(&mut s);
let dir = TempDir::new("attrib-insert");
let path = one_line(&dir);
s.execute("insert", &json!({ "file": path, "name": "SRC", "at": [4.0, 4.0] })).unwrap();
assert_kept(&mut s);
}
#[test]
fn xattach_keeps_an_attrib_name() {
let mut s = attributed();
name_at_top(&mut s);
let dir = TempDir::new("attrib-xref");
let path = one_line(&dir);
s.execute("xattach", &json!({ "path": path, "name": "XR", "at": [8.0, 8.0] })).unwrap();
assert_kept(&mut s);
}
#[test]
fn audit_fix_keeps_an_attrib_name() {
let mut s = attributed();
{
let d = s.doc_mut().unwrap();
let line = Entity::new(Handle(0xABC), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) }));
d.model.push(line.clone());
let mut b = Block::new("DUP");
b.entities.push(line);
d.blocks.insert("DUP".into(), Arc::new(b));
}
name_at_top(&mut s);
s.execute("audit", &json!({ "fix": true })).unwrap();
assert_kept(&mut s);
}
#[test]
fn refclose_keeps_an_attrib_name() {
let mut s = attributed();
s.cmdline(
"(progn (entmake '((0 . \"BLOCK\") (2 . \"R\") (70 . 0) (10 0.0 0.0 0.0))) \
(entmake '((0 . \"LINE\") (10 0.0 0.0 0.0) (11 2.0 0.0 0.0))) \
(entmake '((0 . \"ENDBLK\"))))",
)
.unwrap();
let r = s.execute("insert", &json!({ "name": "R", "at": [0, 0] })).unwrap();
s.execute("refedit", &json!({ "handle": r["handle"] })).unwrap();
s.execute("line", &json!({ "points": [[0, 1], [3, 1]] })).unwrap();
name_at_top(&mut s);
s.execute("refclose", &json!({ "save": true })).unwrap();
assert_kept(&mut s);
}
@@ -65,9 +65,9 @@ fn burst_matches_many_attributes_without_comparing_every_pair() {
#[test]
fn attsync_matches_many_definitions_without_comparing_every_pair() {
let (mut s, h) = reference(N);
// The adjacent engine unit test checks exact indexed lookup work; this keeps
// the same end-to-end ATTSYNC fixture and its result checks.
let t = std::time::Instant::now();
s.execute("attsync", &json!({"name": "B"})).unwrap();
assert!(t.elapsed() < std::time::Duration::from_secs(5), "{:?}", t.elapsed());
// An attribute for each definition (T and the N others), with its default value: the
// reference carried none of their tags.
let a = attribs(&s, h);
+4 -1
View File
@@ -4,7 +4,10 @@
use cadcraft_engine::Session;
use serde_json::json;
use crate::temp_dir::TempDir;
#[path = "../support/temp_dir.rs"]
mod temp_dir;
use temp_dir::TempDir;
/// `(findfile name)` as LISP prints it.
fn findfile(name: &str) -> String {
-4
View File
@@ -1,6 +1,3 @@
#[path = "../support/temp_dir.rs"]
mod temp_dir;
mod angle_prompts;
mod angle_settings;
mod annotate_options;
@@ -15,7 +12,6 @@ mod attdef_command;
mod attdisp_attsync;
mod attedit_prompts;
mod attrib_modes;
mod attrib_names;
mod attrib_props;
mod attribute_tag_matching;
mod attribute_tools;
+16
View File
@@ -67,3 +67,19 @@ fn a_device_that_disagrees_with_the_extension_is_refused() {
assert_eq!(magic(&none), b"<svg ");
std::fs::remove_dir_all(&dir).ok();
}
/// The Plot dialog's payload for several sheets (`layouts` with no device) writes one PDF with a
/// page per sheet; without `device`, the shown layout's device (here a PNG one) is not used either.
#[test]
fn several_sheets_write_one_pdf_page_each_whatever_the_shown_layouts_device() {
let mut s = session();
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "CADCraft PNG" })).unwrap();
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
for p in [json!({ "layouts": ["Layout1", "Layout2"], "device": "None" }), json!({ "layouts": ["Layout1", "Layout2"] })] {
let r = s.execute("plot", &p).unwrap();
assert_eq!(r["pages"], 2, "{p}");
let pdf = cadcraft_engine::cmd::file::base64_decode(r["data"].as_str().unwrap()).unwrap();
let (_, pages) = cadcraft_io::pdf_read::read(&pdf, &cadcraft_io::pdf_read::PdfImportOptions::default()).unwrap();
assert_eq!(pages, 2, "{p}: one PDF page per sheet");
}
}
+12
View File
@@ -47,3 +47,15 @@ fn bad_sheet_lists_are_errors() {
assert!(s.execute("exportpdf", &p).is_err(), "{p}");
}
}
/// A single `layouts` entry plotted to PDF from the Model tab is that sheet, as `layout` names
/// it: its plot area is the layout's, not model space's (#2171 review).
#[test]
fn a_single_sheet_pdf_from_the_model_tab_plots_that_layout() {
let mut s = session();
assert!(s.space().layout().is_none(), "the Model tab is shown");
let r = s.execute("plot", &json!({"layouts": ["Sheet B"], "device": "CADCraft PDF", "plotArea": "layout"})).unwrap();
assert_eq!(r["layout"], "Sheet B");
let by_name = s.execute("plot", &json!({"layout": "Sheet B", "device": "CADCraft PDF", "plotArea": "layout"})).unwrap();
assert_eq!(by_name["layout"], r["layout"]);
}
+21 -17
View File
@@ -122,19 +122,19 @@ fn page_setup_takes_a_device_and_its_papers() {
/// turn back to the axes the user gave, and PLOT hands them on that way (#1266).
fn a_landscape_page_gets_the_papers_margins_back() {
let mut s = session();
s.execute("plottermanager", &json!({"action": "new", "name": "Landscape Banner Printer", "output": "pdf"})).unwrap();
s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "pdf"})).unwrap();
let paper = json!({"name": "Banner", "width": 400, "height": 200, "margins": [150, 0, 150, 0]});
s.execute("plottermanager", &json!({"action": "set", "name": "Landscape Banner Printer", "paper": paper})).unwrap();
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": paper})).unwrap();
// Stored portrait, 200 x 400, the side margins on the long axis.
let stored = |s: &mut Session| {
let r = s.execute("plottermanager", &json!({"action": "get", "name": "Landscape Banner Printer"})).unwrap();
let r = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap();
r["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").cloned().unwrap()
};
let p = stored(&mut s);
assert_eq!((p["width"].as_f64(), p["height"].as_f64()), (Some(200.0), Some(400.0)));
assert_eq!(p["margins"], json!([0.0, 150.0, 0.0, 150.0]));
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Landscape Banner Printer", "paper": "Banner", "landscape": true})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Banner Printer", "paper": "Banner", "landscape": true})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (200.0, 400.0, [150.0, 0.0, 150.0, 0.0]));
// The 400 x 200 sheet's printable area is 100 x 200 mm, not the whole sheet.
@@ -150,11 +150,8 @@ fn a_landscape_page_gets_the_papers_margins_back() {
assert_eq!(o["margins"], json!([150.0, 0.0, 150.0, 0.0]));
// Naming the paper landscape again at a new size keeps the margins' axes as well.
s.execute(
"plottermanager",
&json!({"action": "set", "name": "Landscape Banner Printer", "paper": {"name": "Banner", "width": 500, "height": 200}}),
)
.unwrap();
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 500, "height": 200}}))
.unwrap();
let p = stored(&mut s);
assert_eq!((p["width"].as_f64(), p["height"].as_f64()), (Some(200.0), Some(500.0)));
assert_eq!(p["margins"], json!([0.0, 150.0, 0.0, 150.0]), "the margins keep the short sides");
@@ -166,11 +163,11 @@ fn a_landscape_page_gets_the_papers_margins_back() {
/// instead of being saved against the wrong axes (#1266).
fn an_orientation_only_pagesetup_turns_the_retained_margins() {
let mut s = session();
s.execute("plottermanager", &json!({"action": "new", "name": "Turning Banner Printer", "output": "pdf"})).unwrap();
s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "pdf"})).unwrap();
let paper = json!({"name": "Banner", "width": 400, "height": 200, "margins": [150, 0, 150, 0]});
s.execute("plottermanager", &json!({"action": "set", "name": "Turning Banner Printer", "paper": paper})).unwrap();
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": paper})).unwrap();
// The landscape page carries the margins on its 400 mm sides: 150 mm left and right.
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Turning Banner Printer", "paper": "Banner", "landscape": true})).unwrap();
s.execute("pagesetup", &json!({"layout": "Layout1", "device": "Banner Printer", "paper": "Banner", "landscape": true})).unwrap();
let page = s.doc().unwrap().layout("Layout1").unwrap().page.clone();
assert_eq!((page.width_mm, page.height_mm, page.margins_mm), (200.0, 400.0, [150.0, 0.0, 150.0, 0.0]));
@@ -345,26 +342,33 @@ fn plotwindow_picks_both_corners_with_ortho_on() {
assert!(c.near(Vec2::new(10.0, 0.0), 1e-9), "ortho keeps the line horizontal: {c:?}");
}
/// A misspelled action reports refresh along with the other supported actions.
#[test]
fn unknown_plottermanager_action_reports_refresh() {
let error = Session::new().execute("plottermanager", &json!({ "action": "refersh" })).unwrap_err().to_string();
assert!(error.contains("refresh"), "{error}");
}
#[test]
fn paper_margins_are_checked_against_their_own_axis() {
let mut s = session();
s.execute("plottermanager", &json!({"action": "new", "name": "Margin Banner Printer", "output": "png"})).unwrap();
let paper = |margins: Value| json!({"action": "set", "name": "Margin Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200, "margins": margins}});
s.execute("plottermanager", &json!({"action": "new", "name": "Banner Printer", "output": "png"})).unwrap();
let paper = |margins: Value| json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200, "margins": margins}});
// 250 mm of bottom + top margin leaves no printable height on a 200 mm paper.
assert!(s.execute("plottermanager", &paper(json!([0, 250, 0, 0]))).is_err());
// 300 mm of left + right margin still leaves 100 mm of printable width on a 400 mm paper.
assert!(s.execute("plottermanager", &paper(json!([150, 0, 150, 0]))).is_ok());
// The paper is stored portrait and the margins turn with it: the 100 x 200 printable area
// of the requested sheet stays 200 x 100 on the stored 200 x 400 one.
let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Margin Banner Printer"})).unwrap();
let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap();
let banner = stored["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").unwrap().clone();
assert_eq!((banner["width"].as_f64().unwrap(), banner["height"].as_f64().unwrap()), (200.0, 400.0));
assert_eq!(banner["margins"], json!([0.0, 150.0, 0.0, 150.0]));
// Setting the same sheet again without margins keeps them: the stored margins belong to the
// portrait sheet and turn back before the per-axis check.
s.execute("plottermanager", &json!({"action": "set", "name": "Margin Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200}}))
s.execute("plottermanager", &json!({"action": "set", "name": "Banner Printer", "paper": {"name": "Banner", "width": 400, "height": 200}}))
.unwrap();
let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Margin Banner Printer"})).unwrap();
let stored = s.execute("plottermanager", &json!({"action": "get", "name": "Banner Printer"})).unwrap();
let banner = stored["papers"].as_array().unwrap().iter().find(|p| p["name"] == "Banner").unwrap().clone();
assert_eq!(banner["margins"], json!([0.0, 150.0, 0.0, 150.0]));
}
+341
View File
@@ -0,0 +1,341 @@
//! System printers (#670 step 2): the host lists them as devices, and PLOT to one sends the
//! plotter's PDF to the host instead of returning a file.
use std::sync::Mutex;
use cadcraft_doc::{DevicePaper, Drawing, PlotterConfig, Space};
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io};
use cadcraft_engine::cmd::plotters::{PlotterStore, PrintJob, SystemPrinters, set_plotter_store, set_system_printers};
use serde_json::{Value, json};
/// The jobs printed: printer, paper, copies, title, the options the plot hook got.
static JOBS: Mutex<Vec<(String, String, u32, String, Value)>> = Mutex::new(Vec::new());
/// The tests share [`JOBS`]: one at a time.
static SERIAL: Mutex<()> = Mutex::new(());
/// A plotter that returns its options as the file, so a print job shows what was plotted.
fn echo_plot(_: &Drawing, _: &Space, opts: &Value) -> Result<Vec<u8>, String> {
Ok(opts.to_string().into_bytes())
}
/// How many times the system was asked for its printers.
static LISTINGS: std::sync::atomic::AtomicUsize = std::sync::atomic::AtomicUsize::new(0);
/// One system printer, a roll plotter with Letter and a 24 in roll, as the system would list it.
fn printers() -> Vec<PlotterConfig> {
LISTINGS.fetch_add(1, std::sync::atomic::Ordering::SeqCst);
vec![PlotterConfig {
name: "Office_T120".into(),
description: "HP DesignJet T120".into(),
default_paper: "Letter".into(),
papers: vec![
DevicePaper { native_key: None, name: "Letter".into(), width: 215.9, height: 279.4, margins: [5.0; 4] },
DevicePaper { native_key: None, name: "Roll 24 in".into(), width: 609.6, height: 914.4, margins: [5.0; 4] },
],
system: true,
system_default: true,
..PlotterConfig::default()
}]
}
/// Records each print job (printer, paper, copies, title and plotted options) and answers with a job id.
fn print(j: &PrintJob) -> Result<String, String> {
// Thirteen copies stand for a printer that refuses the job.
if j.copies == 13 {
return Err("the printer refused the job".into());
}
let opts = serde_json::from_slice(j.pdf).map_err(|e| e.to_string())?;
JOBS.lock().unwrap().push((j.printer.into(), j.paper.into(), j.copies, j.title.into(), opts));
Ok(format!("{}-7", j.printer))
}
/// A session with the stand-in printers and plotter installed and a line to plot.
fn session() -> Session {
set_plotter_store(PlotterStore::memory());
set_system_printers(SystemPrinters { list: printers, print });
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Err("no writer in this test".into()), plot: Some(echo_plot) });
// Wait for the first listing, so every test starts with the printer listed, whichever runs first.
cadcraft_engine::cmd::plotters::page_device("pagesetup", &json!({ "device": "Office_T120" }), &mut cadcraft_doc::PageSetup::default()).unwrap();
let mut s = Session::new();
s.cmdline("line 0,0 100,0").unwrap();
s.cmdline("").unwrap();
s
}
/// System printers are listed after the built-in devices, and PLOT on one sends the job with its paper, copies and title.
#[test]
fn system_printers_are_devices_and_plot_prints_on_them() {
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut s = session();
JOBS.lock().unwrap().clear();
let r = s.execute("plottermanager", &json!({})).unwrap();
let names: Vec<&str> = r["devices"].as_array().unwrap().iter().map(|d| d["name"].as_str().unwrap()).collect();
assert_eq!(names, ["CADCraft PDF", "CADCraft PNG", "CADCraft SVG", "Office_T120"]);
let r = s.execute("plot", &json!({ "layout": "Model", "device": "office_t120", "paper": "Roll 24 in", "copies": 2 })).unwrap();
assert_eq!(r["job"], "Office_T120-7");
assert_eq!(r["copies"], 2);
assert!(r.get("data").is_none());
let (printer, paper, copies, title, opts) = JOBS.lock().unwrap().pop().unwrap();
assert_eq!((printer.as_str(), paper.as_str(), copies), ("Office_T120", "Roll 24 in", 2));
assert!(title.ends_with(" - Model"), "{title}");
// The plotter wrote a PDF on the printer's paper.
assert_eq!(opts["output"], "pdf");
assert_eq!(opts["width"], 609.6);
// EXPORTPDF to the same device still returns the PDF.
let r = s.execute("exportpdf", &json!({ "layout": "Model", "device": "Office_T120" })).unwrap();
assert!(r.get("data").is_some() && r.get("job").is_none());
assert!(JOBS.lock().unwrap().is_empty());
// A printer takes the PDF before the output's own checks: an SVG with a model-space offset
// (which SVG refuses) still prints.
let r = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "output": "svg", "center": false, "offset": [5, 5] })).unwrap();
assert_eq!(r["job"], "Office_T120-7", "{r}");
assert_eq!(JOBS.lock().unwrap().pop().unwrap().4["output"], "pdf");
// A `printer` passed with the call never prints: EXPORTPDF and PLOT without a printer
// device write their file.
let r = s.execute("exportpdf", &json!({ "layout": "Model", "printer": "Office_T120" })).unwrap();
assert!(r.get("data").is_some() && r.get("job").is_none());
let r = s.execute("plot", &json!({ "layout": "Model", "device": "CADCraft PDF", "printer": "Office_T120" })).unwrap();
assert!(r.get("job").is_none(), "{r}");
assert!(JOBS.lock().unwrap().is_empty());
// An unknown printer is refused, and copies are bounded.
assert!(s.execute("plot", &json!({ "layout": "Model", "device": "Nope" })).is_err());
let r = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "copies": 100000 })).unwrap();
assert_eq!(r["copies"], 999);
assert_eq!(JOBS.lock().unwrap().pop().unwrap().2, 999);
// A system printer is listed as one, and PLOTTERMANAGER neither edits nor deletes it.
let list = s.execute("plottermanager", &json!({ "action": "list" })).unwrap();
let t120 = list["devices"].as_array().unwrap().iter().find(|d| d["name"] == "Office_T120").cloned().unwrap();
assert_eq!(t120["system"], true);
assert_eq!(t120["default"], true, "the system's default printer says so");
let set = s.execute("plottermanager", &json!({ "action": "set", "name": "Office_T120", "description": "x" }));
assert!(set.unwrap_err().to_string().contains("system printer"));
assert!(s.execute("plottermanager", &json!({ "action": "delete", "name": "Office_T120" })).is_err());
}
/// Plot to file with a printer: the PDF is written first, then printed; a file that can't be
/// written stops the plot before anything prints (a missing folder is made, see
/// `plot_to_file_creates_missing_folders_before_submitting`). REFRESH asks for the printers again.
#[test]
fn plot_to_file_and_print_and_refresh_the_printers() {
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut s = session();
JOBS.lock().unwrap().clear();
let dir = std::env::temp_dir().join(format!("cadcraft-plot-to-file-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("plan.pdf");
let path_s = path.to_string_lossy().to_string();
let r = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "path": path_s })).unwrap();
assert_eq!(r["job"], "Office_T120-7");
assert_eq!(r["path"], path_s.as_str());
let written = std::fs::read(&path).unwrap();
let (printer, _, _, _, opts) = JOBS.lock().unwrap().pop().unwrap();
assert_eq!(printer, "Office_T120");
// The file is the PDF that was printed.
assert_eq!(serde_json::from_slice::<Value>(&written).unwrap(), opts);
// A folder can't be made under a file: the PDF can't be written, so nothing is printed.
let bad = path.join("plan.pdf");
let e = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "path": bad.to_string_lossy() })).unwrap_err();
assert!(e.to_string().contains("plan.pdf"), "{e}");
assert!(JOBS.lock().unwrap().is_empty(), "nothing printed when the file couldn't be written");
let _ = std::fs::remove_dir_all(&dir);
// The plot stamp: the drawing and the device named here, the rest left to the plotter.
s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "stamp": true })).unwrap();
let stamp = JOBS.lock().unwrap().pop().unwrap().4["stamp"].as_str().unwrap().to_string();
let title = s.state().unwrap().title.clone();
assert_eq!(stamp, format!("{title}, {{layout}}, Office_T120, Letter, {{scale}}"), "the device's paper by its name");
let r = s.execute("exportpdf", &json!({ "layout": "Model", "stamp": "Checked {device}\u{7}" })).unwrap();
let opts: Value = serde_json::from_slice(&cadcraft_engine::cmd::file::base64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(opts["stamp"], "Checked CADCraft PDF");
// Without a device, the stamp names the built-in device of the format written.
let r = s.execute("plot", &json!({ "layout": "Model", "output": "png", "stamp": "Checked {device}" })).unwrap();
let opts: Value = serde_json::from_slice(&cadcraft_engine::cmd::file::base64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
assert_eq!(opts["stamp"], "Checked CADCraft PNG");
let r = s.execute("exportpdf", &json!({ "layout": "Model", "stamp": false })).unwrap();
let opts: Value = serde_json::from_slice(&cadcraft_engine::cmd::file::base64_decode(r["data"].as_str().unwrap()).unwrap()).unwrap();
assert!(opts.get("stamp").is_none());
assert!(s.execute("plot", &json!({ "layout": "Model", "stamp": 5 })).is_err());
let asked = LISTINGS.load(std::sync::atomic::Ordering::SeqCst);
let r = s.execute("plottermanager", &json!({ "action": "refresh" })).unwrap();
assert_eq!(r["printers"], true);
// A refresh asks the system again rather than answering from the cache (bounded wait for
// the background listing).
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while LISTINGS.load(std::sync::atomic::Ordering::SeqCst) == asked && std::time::Instant::now() < deadline {
std::thread::yield_now();
}
assert!(LISTINGS.load(std::sync::atomic::Ordering::SeqCst) > asked, "refresh listed the printers again");
let list = s.execute("plottermanager", &json!({ "action": "list" })).unwrap();
assert!(list["devices"].as_array().unwrap().iter().any(|d| d["name"] == "Office_T120"));
}
#[test]
fn an_inferred_image_output_does_not_submit_to_a_layouts_printer() {
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut s = session();
JOBS.lock().unwrap().clear();
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "Office_T120" })).unwrap();
let dir = std::env::temp_dir().join(format!("cadcraft-image-no-print-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
for output in ["png", "svg"] {
let path = dir.join(format!("plan.{output}"));
let r = s.execute("plot", &json!({ "layout": "Layout1", "path": path })).unwrap();
let options: Value = serde_json::from_slice(&std::fs::read(&path).unwrap()).unwrap();
assert_eq!(options["output"], output);
assert!(r.get("job").is_none());
assert!(JOBS.lock().unwrap().is_empty());
}
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn plot_to_file_creates_missing_folders_before_submitting() {
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut s = session();
JOBS.lock().unwrap().clear();
let dir = std::env::temp_dir().join(format!("cadcraft-new-plot-folder-{}", std::process::id()));
let path = dir.join("nested/plan.pdf");
let r = s.execute("plot", &json!({ "device": "Office_T120", "path": path })).unwrap();
assert!(path.is_file());
assert!(r.get("createdFolder").is_some(), "{r}");
// Take the job: the tests share JOBS and run in any order.
assert!(JOBS.lock().unwrap().pop().is_some());
assert!(JOBS.lock().unwrap().is_empty());
std::fs::remove_dir_all(dir).unwrap();
}
#[test]
fn a_multi_sheet_printer_plot_is_refused_before_writing_or_submitting() {
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut s = session();
JOBS.lock().unwrap().clear();
let dir = std::env::temp_dir().join(format!("cadcraft-multi-print-{}", std::process::id()));
let path = dir.join("new-folder/plot.pdf");
let e = s.execute("plot", &json!({ "layouts": ["Layout1", "Layout2"], "device": "Office_T120", "path": path })).unwrap_err();
assert!(e.to_string().contains("several sheets"), "{e}");
assert!(!dir.exists());
assert!(JOBS.lock().unwrap().is_empty());
let r = s.execute("plot", &json!({ "layouts": ["Layout1", "Layout2"], "device": "CADCraft PDF" })).unwrap();
assert_eq!(r["pages"], 2);
s.execute("plot", &json!({ "layouts": ["Layout1"], "device": "Office_T120", "paper": "Letter" })).unwrap();
assert_eq!(JOBS.lock().unwrap().len(), 1);
}
#[test]
fn printer_pdf_file_output_obeys_the_write_root_before_creating_folders() {
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut s = session();
JOBS.lock().unwrap().clear();
let base = std::env::temp_dir().join(format!("cadcraft-printer-root-{}", std::process::id()));
let allowed = base.join("allowed");
std::fs::create_dir_all(&allowed).unwrap();
let roots = cadcraft_engine::file_access::AutomationRoots::new(None, Some(&allowed)).unwrap();
cadcraft_engine::file_access::confine(roots.as_ref(), || {
let outside = base.join("outside/new/plot.pdf");
let e = s.execute("plot", &json!({ "device": "Office_T120", "path": outside })).unwrap_err();
assert!(e.to_string().contains("outside the write root"), "{e}");
assert!(!base.join("outside").exists());
assert!(JOBS.lock().unwrap().is_empty());
let inside = allowed.join("new/plot.pdf");
s.execute("plot", &json!({ "device": "Office_T120", "path": inside })).unwrap();
assert!(inside.is_file());
assert_eq!(JOBS.lock().unwrap().len(), 1);
});
std::fs::remove_dir_all(base).unwrap();
}
#[test]
fn a_copy_of_a_system_printer_is_a_user_device() {
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut s = session();
let made = s.execute("plottermanager", &json!({ "action": "new", "name": "My T120", "from": "Office_T120" })).unwrap();
let got = s.execute("plottermanager", &json!({ "action": "get", "name": "My T120" })).unwrap();
for r in [&made, &got] {
assert_eq!((&r["system"], &r["default"]), (&json!(false), &json!(false)), "{r}");
}
let printer = s.execute("plottermanager", &json!({ "action": "get", "name": "Office_T120" })).unwrap();
assert_eq!((&printer["system"], &printer["default"]), (&json!(true), &json!(true)), "the printer keeps its flags");
// The device store is shared by the tests: leave it as it was.
s.execute("plottermanager", &json!({ "action": "delete", "name": "My T120" })).unwrap();
}
/// The typed device list (`-PLOTTERMANAGER ?`) marks the system's default printer, as the
/// dialogs' device lists do (#2171 review).
#[test]
fn the_typed_device_list_marks_the_default_printer() {
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut s = session();
s.cmdline("-plottermanager").unwrap();
s.cmdline("?").unwrap();
let line = s.log.iter().rev().find(|l| l.starts_with("Office_T120")).cloned().unwrap_or_default();
assert!(line.starts_with("Office_T120 (default)"), "{line:?}");
let builtin = s.log.iter().rev().find(|l| l.starts_with("CADCraft PDF")).cloned().unwrap_or_default();
assert!(!builtin.contains("(default)"), "{builtin:?}");
}
#[test]
fn a_refused_print_job_reports_the_pdf_already_saved() {
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut s = session();
JOBS.lock().unwrap().clear();
let dir = std::env::temp_dir().join(format!("cadcraft-refused-print-{}", std::process::id()));
let path = dir.join("plot.pdf");
let e = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "path": path, "copies": 13 })).unwrap_err().to_string();
assert!(path.is_file());
assert!(e.contains(path.to_str().unwrap()) && e.contains("refused"), "{e}");
let e = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "copies": 13 })).unwrap_err().to_string();
assert!(!e.contains("saved"), "nothing was saved without a path: {e}");
std::fs::remove_dir_all(dir).unwrap();
}
/// The sheets a call names decide the device: one `layouts` entry plots with that layout's own
/// page setup, as `layout` would; several sheets without a device go to the PDF file, never to
/// the printer of the layout shown.
#[test]
fn the_sheets_named_decide_the_device_not_the_layout_shown() {
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut s = session();
JOBS.lock().unwrap().clear();
s.execute("pagesetup", &json!({ "layout": "Layout1", "device": "Office_T120" })).unwrap();
s.execute("pagesetup", &json!({ "layout": "Layout2", "device": "CADCraft PDF", "paper": "A3" })).unwrap();
// Layout1 (on the printer) shown, Layout2 (the PDF device) named: a file, no print job.
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
let r = s.execute("plot", &json!({ "layouts": ["Layout2"] })).unwrap();
assert!(r.get("job").is_none() && r.get("data").is_some(), "{r}");
assert!(JOBS.lock().unwrap().is_empty());
// Layout2 shown, Layout1 named: Layout1's printer, on Layout1's paper.
s.execute("layout.set", &json!({ "name": "Layout2" })).unwrap();
let r = s.execute("plot", &json!({ "layouts": ["Layout1"] })).unwrap();
assert_eq!(r["job"], "Office_T120-7", "{r}");
let (printer, paper, ..) = JOBS.lock().unwrap().pop().unwrap();
assert_eq!((printer.as_str(), paper.as_str()), ("Office_T120", "Letter"));
// Several sheets with the printer's layout shown: one PDF of both, nothing printed.
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
let r = s.execute("plot", &json!({ "layouts": ["Layout1", "Layout2"] })).unwrap();
assert_eq!(r["pages"], 2);
assert!(r.get("job").is_none() && r.get("data").is_some(), "{r}");
assert!(JOBS.lock().unwrap().is_empty());
}
/// A drawing named like a stamp field is stamped by its name: the command fills its fields in one
/// pass, and the plotter's step leaves the filled values alone (#2171 review).
#[test]
fn a_drawing_named_like_a_field_keeps_its_name_in_the_stamp() {
let _one = SERIAL.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
let mut s = session();
JOBS.lock().unwrap().clear();
s.state_mut().unwrap().title = "Plan {paper} {layout}.dwg".into();
s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120", "stamp": "{drawing} | {paper}" })).unwrap();
let stamp = JOBS.lock().unwrap().pop().unwrap().4["stamp"].as_str().unwrap().to_string();
let sheet = cadcraft_doc::fill_stamp(&stamp, &[("layout", "Model"), ("paper", "A4"), ("scale", "1:1")], true);
assert_eq!(sheet, "Plan {paper} {layout}.dwg | Letter");
}
@@ -0,0 +1,90 @@
//! Commands that name a system printer while a listing is still under way, and a listing whose
//! host hook fails (#2171 review). Its own test binary: the system printers are set once per
//! process, and each step needs a listing that has not ended yet.
use std::sync::atomic::{AtomicUsize, Ordering};
use cadcraft_doc::{DevicePaper, PlotterConfig};
use cadcraft_engine::Session;
use cadcraft_engine::cmd::plotters::{
PlotterStore, PrintJob, SystemPrinters, refresh_system_printers, set_plotter_store, set_system_printers, system_printers_pending,
};
use serde_json::json;
static LISTINGS: AtomicUsize = AtomicUsize::new(0);
fn printer(name: &str, papers: &[(&str, f64, f64)]) -> PlotterConfig {
PlotterConfig {
name: name.into(),
default_paper: papers[0].0.into(),
papers: papers
.iter()
.map(|(n, w, h)| DevicePaper { native_key: None, name: (*n).into(), width: *w, height: *h, margins: [5.0; 4] })
.collect(),
system: true,
..PlotterConfig::default()
}
}
/// The first listing fails (the host's hook panics); the next ones answer after 300 ms, the
/// second with `Office` only, later ones with the roll plotter `Office_T120` as well.
fn printers() -> Vec<PlotterConfig> {
let n = LISTINGS.fetch_add(1, Ordering::SeqCst);
assert!(n > 0, "the first listing fails");
std::thread::sleep(std::time::Duration::from_millis(300));
let mut v = vec![printer("Office", &[("Tabloid", 279.4, 431.8)])];
if n > 1 {
v.push(printer("Office_T120", &[("Letter", 215.9, 279.4), ("Roll 24 in", 609.6, 914.4)]));
}
v
}
fn print(_: &PrintJob) -> Result<String, String> {
Err("no printing in this test".into())
}
/// Wait (at most `limit`) for the listing under way to end.
fn until_listed(limit: std::time::Duration) -> std::time::Duration {
let start = std::time::Instant::now();
while system_printers_pending() && start.elapsed() < limit {
std::thread::sleep(std::time::Duration::from_millis(20));
}
start.elapsed()
}
#[test]
fn commands_naming_a_printer_wait_for_the_listing_under_way() {
set_plotter_store(PlotterStore::memory());
// A user device named like a system printer, kept before anything is listed.
let user = PlotterConfig {
name: "Office".into(),
papers: vec![DevicePaper { native_key: None, name: "A4".into(), width: 210.0, height: 297.0, margins: [5.0; 4] }],
..PlotterConfig::default()
};
let file = cadcraft_doc::plotter_file_name("Office").unwrap();
(PlotterStore::memory().write)(&file, &user.to_file_text()).unwrap();
set_system_printers(SystemPrinters { list: printers, print });
// A listing whose hook fails ends at once: nothing waits for it the full ten seconds, and the
// next device list starts another.
assert!(refresh_system_printers());
let took = until_listed(std::time::Duration::from_secs(9));
assert!(took < std::time::Duration::from_secs(5), "a failed listing is not waited for: {took:?}");
assert_eq!(LISTINGS.load(Ordering::SeqCst), 1);
// `new` copies the system printer `Office`, not the user device of that name, though the
// listing it starts has not ended when the copy is asked for.
let mut s = Session::new();
let r = s.execute("plottermanager", &json!({ "action": "new", "name": "Office copy", "from": "Office" })).unwrap();
assert_eq!(r["defaultPaper"], "Tabloid", "a copy of the system printer: {r}");
// PAGESETUP changing the paper of the printer a layout already uses waits for the listing
// under way, as it would with the printer named: the roll is that printer's paper.
let layout = s.doc_mut().unwrap().layouts.iter_mut().find(|l| l.name == "Layout1").map(|l| l.page.device = "Office_T120".into());
assert!(layout.is_some(), "the drawing has Layout1");
assert!(refresh_system_printers());
assert!(system_printers_pending(), "a listing is under way");
s.execute("pagesetup", &json!({ "layout": "Layout1", "paper": "Roll 24 in" })).unwrap();
let page = &s.doc().unwrap().layout("Layout1").unwrap().page;
assert_eq!((page.device.as_str(), page.paper.as_str()), ("Office_T120", "Roll 24 in"));
}
@@ -0,0 +1,42 @@
//! Dialog edits use cached devices even while the refresh worker is blocked.
use cadcraft_doc::{PageSetup, PlotterConfig};
use cadcraft_engine::cmd::plotters::{self, PrintJob, SystemPrinters};
use serde_json::json;
use std::sync::{
Condvar, Mutex,
atomic::{AtomicUsize, Ordering},
};
static CALLS: AtomicUsize = AtomicUsize::new(0);
/// Refresh listings that have returned (the blocked one only after RELEASE or its timeout).
static RETURNED: AtomicUsize = AtomicUsize::new(0);
static RELEASE: (Mutex<bool>, Condvar) = (Mutex::new(false), Condvar::new());
fn list() -> Vec<PlotterConfig> {
if CALLS.fetch_add(1, Ordering::SeqCst) > 0 {
let _ = RELEASE.1.wait_timeout_while(RELEASE.0.lock().unwrap(), std::time::Duration::from_secs(10), |ready| !*ready).unwrap();
RETURNED.fetch_add(1, Ordering::SeqCst);
}
vec![PlotterConfig { name: "Cached printer".into(), system: true, ..PlotterConfig::default() }]
}
fn print(_: &PrintJob) -> Result<String, String> {
Err("not printing".into())
}
#[test]
fn dialog_device_lookup_does_not_wait_for_refresh() {
plotters::set_system_printers(SystemPrinters { list, print });
// The command path waits for the initial list.
let mut page = PageSetup::default();
plotters::page_device("pagesetup", &json!({ "device": "Cached printer" }), &mut page).unwrap();
plotters::refresh_system_printers();
// Wait (bounded, so a broken refresh fails instead of hanging) until the refresh worker is
// inside the blocked listing.
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(5);
while CALLS.load(Ordering::SeqCst) < 2 && std::time::Instant::now() < deadline {
std::thread::yield_now();
}
assert!(CALLS.load(Ordering::SeqCst) >= 2, "the refresh started a listing");
plotters::page_device_now("plot", &json!({ "device": "Cached printer" }), &mut page).unwrap();
let still_blocked = RETURNED.load(Ordering::SeqCst) == 0;
*RELEASE.0.lock().unwrap() = true;
RELEASE.1.notify_all();
assert!(still_blocked, "the dialog lookup returned while the refresh was still blocked");
}
@@ -0,0 +1,37 @@
//! PLOTTERMANAGER `get` naming a system printer while the first listing is still under way (a
//! fresh CLI process) waits for the listing instead of reporting an unknown plotter. Its own test
//! binary: the system printers are set once per process, and the listing must not have run yet.
use cadcraft_doc::{DevicePaper, PlotterConfig};
use cadcraft_engine::Session;
use cadcraft_engine::cmd::plotters::{PlotterStore, PrintJob, SystemPrinters, set_plotter_store, set_system_printers};
use serde_json::json;
/// A slow listing: the system answers after 300 ms.
fn printers() -> Vec<PlotterConfig> {
std::thread::sleep(std::time::Duration::from_millis(300));
vec![PlotterConfig {
name: "Office_T120".into(),
default_paper: "Letter".into(),
papers: vec![DevicePaper { native_key: None, name: "Letter".into(), width: 215.9, height: 279.4, margins: [5.0; 4] }],
system: true,
..PlotterConfig::default()
}]
}
/// Refuses every job: this test never prints.
fn print(_: &PrintJob) -> Result<String, String> {
Err("no printing in this test".into())
}
/// `get` and `save` wait (bounded) for the first listing, as PLOT does.
#[test]
fn get_waits_for_the_first_printer_listing() {
set_plotter_store(PlotterStore::memory());
set_system_printers(SystemPrinters { list: printers, print });
let mut s = Session::new();
let r = s.execute("plottermanager", &json!({ "action": "get", "name": "Office_T120" })).unwrap();
assert_eq!((&r["name"], &r["system"]), (&json!("Office_T120"), &json!(true)), "{r}");
let r = s.execute("plottermanager", &json!({ "action": "save", "name": "Office_T120" })).unwrap();
assert!(r["text"].as_str().is_some_and(|t| t.contains("Letter")), "{r}");
}
@@ -0,0 +1,46 @@
//! A plot that names a system printer while the printers are still being listed (the first plot
//! after the app starts) waits for the list, and the printer wins over a user device of the same
//! name. Its own test binary: the system printers are set once per process.
use cadcraft_doc::{DevicePaper, Drawing, PlotterConfig, Space};
use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io};
use cadcraft_engine::cmd::plotters::{PlotterStore, PrintJob, SystemPrinters, set_plotter_store, set_system_printers};
use serde_json::{Value, json};
/// A plotter that returns its options as the file.
fn echo_plot(_: &Drawing, _: &Space, opts: &Value) -> Result<Vec<u8>, String> {
Ok(opts.to_string().into_bytes())
}
/// A slow listing: the system answers after 300 ms.
fn printers() -> Vec<PlotterConfig> {
std::thread::sleep(std::time::Duration::from_millis(300));
vec![PlotterConfig {
name: "Office_T120".into(),
default_paper: "Letter".into(),
papers: vec![DevicePaper { native_key: None, name: "Letter".into(), width: 215.9, height: 279.4, margins: [5.0; 4] }],
system: true,
..PlotterConfig::default()
}]
}
/// Accepts every job with a fixed job id.
fn print(j: &PrintJob) -> Result<String, String> {
Ok(format!("{}-1", j.printer))
}
/// A plot naming a printer still being listed waits for the listing, and the printer wins over a user device of the same name.
#[test]
fn a_printer_still_being_listed_is_waited_for_and_wins_over_a_user_device() {
set_plotter_store(PlotterStore::memory());
set_system_printers(SystemPrinters { list: printers, print });
set_io(IoHooks { read: |_, _| Err("no reader in this test".into()), write: |_, _| Err("no writer in this test".into()), plot: Some(echo_plot) });
let mut s = Session::new();
s.cmdline("line 0,0 100,0").unwrap();
s.cmdline("").unwrap();
// A user plotter with the printer's name, made while the listing is under way.
s.execute("plottermanager", &json!({ "action": "new", "name": "Office_T120" })).unwrap();
let r = s.execute("plot", &json!({ "layout": "Model", "device": "Office_T120" })).unwrap();
assert_eq!(r["job"], "Office_T120-1", "the printer, not the user plotter: {r}");
}
@@ -0,0 +1,55 @@
//! A printer listing that doesn't end within the wait: PLOT naming an unknown device waits for it
//! once, not again for its fallback and its error message. Its own test binary: the system
//! printers are set once per process.
use cadcraft_doc::PlotterConfig;
use cadcraft_engine::Session;
use cadcraft_engine::cmd::plotters::{PlotterStore, PrintJob, SystemPrinters, refresh_system_printers, set_plotter_store, set_system_printers};
use serde_json::json;
use std::sync::atomic::{AtomicUsize, Ordering};
static LISTINGS: AtomicUsize = AtomicUsize::new(0);
/// A listing that hangs far past the wait.
fn printers() -> Vec<PlotterConfig> {
LISTINGS.fetch_add(1, Ordering::SeqCst);
std::thread::sleep(std::time::Duration::from_secs(120));
Vec::new()
}
/// Refuses every job: this test never gets as far as printing.
fn print(_: &PrintJob) -> Result<String, String> {
Err("no printing in this test".into())
}
/// A hung listing costs one wait: the unknown device's error, a second plot and a plot with no device don't wait again.
#[test]
fn an_unknown_device_waits_for_a_hung_listing_only_once() {
set_plotter_store(PlotterStore::memory());
set_system_printers(SystemPrinters { list: printers, print });
let mut s = Session::new();
s.cmdline("line 0,0 100,0").unwrap();
s.cmdline("").unwrap();
let start = std::time::Instant::now();
let r = s.execute("plot", &json!({ "layout": "Model", "device": "Nope" }));
let took = start.elapsed();
assert!(r.unwrap_err().to_string().contains("unknown plotter `Nope`"));
// One wait of PRINTERS_WAIT (10 s), not three.
assert!(took < std::time::Duration::from_secs(15), "{took:?}");
// After a wait that ran out, later plots don't wait again while the listings hang.
let start = std::time::Instant::now();
assert!(s.execute("plot", &json!({ "layout": "Model", "device": "Nope2" })).is_err());
assert!(start.elapsed() < std::time::Duration::from_secs(2), "no second wait: {:?}", start.elapsed());
let start = std::time::Instant::now();
let _ = s.execute("plot", &json!({ "layout": "Model", "device": "None" }));
assert!(start.elapsed() < std::time::Duration::from_secs(2), "no device needs no printer list: {:?}", start.elapsed());
// Even after the replacement expires, refreshes must not accumulate blocked driver threads.
std::thread::sleep(std::time::Duration::from_millis(10_100));
for _ in 0..5 {
assert!(refresh_system_printers());
}
// Let a replacement worker start if one was incorrectly spawned.
std::thread::sleep(std::time::Duration::from_millis(200));
let listings = LISTINGS.load(Ordering::SeqCst);
assert!((1..=2).contains(&listings), "at most two blocked listings, got {listings}");
}
+7
View File
@@ -79,6 +79,13 @@ impl Bounds2 {
pub fn intersects(&self, o: &Bounds2) -> bool {
!(self.is_empty() || o.is_empty() || o.min.x > self.max.x || o.max.x < self.min.x || o.min.y > self.max.y || o.max.y < self.min.y)
}
/// The part both boxes cover; [`Bounds2::EMPTY`] when they don't meet.
pub fn intersection(&self, o: &Bounds2) -> Bounds2 {
if !self.intersects(o) {
return Bounds2::EMPTY;
}
Bounds2 { min: self.min.max(o.min), max: self.max.min(o.max) }
}
pub fn expand(&self, d: f64) -> Bounds2 {
if self.is_empty() {
return *self;
+7 -4
View File
@@ -25,7 +25,13 @@ craft-pdf = { workspace = true, features = ["write", "interpret"] }
kurbo = { workspace = true }
lyon_tessellation = { workspace = true }
# System printers, paper geometry and job submission on Windows (winprint.rs).
[target.'cfg(windows)'.dependencies]
craft-print = { workspace = true }
[dev-dependencies]
# The print catalog mapping tests also run on hosts without Windows printers.
craft-print = { workspace = true }
miniz_oxide = "0.9"
tiff = "0.11"
image = { workspace = true }
@@ -35,8 +41,5 @@ craft-pdf = { workspace = true, features = ["read"] }
# Inspect DWG output only where craft-dwg builds its native bridge. An unconditional
# dev-dependency also builds acadrust during --all-targets, breaking FreeBSD aarch64 (#2526).
# The storytold/acadrust fork at tag `storytold/v0.6.6` (upstream v0.6.6), the source craft-dwg moves
# to in storytold/craft-libs#4762; until craft-libs is repinned, craft-dwg still takes the identical
# crates.io 0.6.6.
[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies]
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "5d5c482b3fcb3dc77e8281474461760f32959436" }
acadrust = "0.6.6"
+732
View File
@@ -0,0 +1,732 @@
//! System printers through CUPS (macOS and Linux): the destinations `lpstat` lists, each with
//! the papers and printable areas of its PPD, and printing a plot's PDF with `lp`. A destination
//! without a PPD file the user can read (a driverless IPP queue CUPS made on the fly, or a PPD
//! readable only by root) takes its papers from `lpoptions -l` instead, with the margins IPP
//! printers commonly report. `lpstat -d` names the system's default printer.
//!
//! The PDF is the one the PDF plotter writes for the chosen paper, so it is sent unscaled: the
//! plot's scale is already applied. The parsers take text, so they are tested without a printer.
use cadcraft_doc::{DevicePaper, Orientation, PlotOutput, PlotterConfig};
/// Most destinations listed.
const MAX_PRINTERS: usize = 64;
/// Largest PPD file read (bytes).
#[cfg_attr(not(all(unix, not(target_arch = "wasm32"))), allow(dead_code))]
const MAX_PPD: u64 = 4 << 20;
/// Most copies of one job.
pub const MAX_COPIES: u32 = 999;
/// PostScript points per millimetre.
const PT_PER_MM: f64 = 72.0 / 25.4;
/// A paper size of a PPD: its option keyword, the name shown, size and printable area (points).
#[derive(Clone, Debug, PartialEq)]
pub struct PpdPaper {
pub keyword: String,
pub name: String,
pub width: f64,
pub height: f64,
/// Printable area: lower-left x, y and upper-right x, y (points).
pub imageable: Option<[f64; 4]>,
}
/// What a PPD says about a printer's papers.
#[derive(Clone, Debug, Default, PartialEq)]
pub struct Ppd {
pub nick_name: String,
/// The default paper's keyword.
pub default_size: String,
pub papers: Vec<PpdPaper>,
}
/// A PPD main keyword line: `*Key Option/Label: Value` → (key, option, label, value).
fn ppd_line(line: &str) -> Option<(&str, &str, &str, &str)> {
let rest = line.strip_prefix('*')?;
let (head, value) = rest.split_once(':')?;
let (key, option) = head.split_once(' ').unwrap_or((head, ""));
let (option, label) = option.split_once('/').unwrap_or((option, ""));
Some((key.trim(), option.trim(), label.trim(), value.trim().trim_matches('"').trim()))
}
/// Exactly `N` finite numbers separated by spaces (a PPD's sizes and areas), else `None`.
fn numbers<const N: usize>(s: &str) -> Option<[f64; N]> {
let v: Vec<f64> = s.split_whitespace().filter_map(|t| t.parse().ok()).filter(|x: &f64| x.is_finite()).collect();
v.try_into().ok()
}
/// The name a paper is shown with: its label, else its keyword; a borderless variant
/// (`Letter.Fullbleed`) says so.
fn paper_name(keyword: &str, label: &str) -> String {
let (base, borderless) = match keyword.strip_suffix(".Fullbleed") {
Some(b) => (b, true),
None => (keyword, false),
};
let shown = if label.is_empty() { base } else { label.trim_end_matches(" (Borderless)").trim_end_matches(" Borderless") };
if borderless { format!("{shown} (borderless)") } else { shown.to_string() }
}
/// Parse a PPD's nickname, default page size and page sizes (with `PaperDimension` and
/// `ImageableArea`). Page sizes without dimensions are dropped.
pub fn parse_ppd(text: &str) -> Ppd {
let mut ppd = Ppd::default();
let mut sizes: Vec<(String, String)> = Vec::new();
let mut dims: Vec<(String, [f64; 2])> = Vec::new();
let mut areas: Vec<(String, [f64; 4])> = Vec::new();
for line in text.lines() {
let Some((key, option, label, value)) = ppd_line(line) else { continue };
match key {
"NickName" => ppd.nick_name = value.to_string(),
"DefaultPageSize" => ppd.default_size = value.to_string(),
"PageSize" if !option.is_empty() && !sizes.iter().any(|(k, _)| k == option) => sizes.push((option.into(), label.into())),
"PaperDimension" => {
if let Some(d) = numbers::<2>(value) {
dims.push((option.into(), d));
}
}
"ImageableArea" => {
if let Some(a) = numbers::<4>(value) {
areas.push((option.into(), a));
}
}
_ => {}
}
}
for (keyword, label) in sizes {
let Some((_, [w, h])) = dims.iter().find(|(k, _)| *k == keyword) else { continue };
if *w <= 0.0 || *h <= 0.0 {
continue;
}
let imageable = areas.iter().find(|(k, _)| *k == keyword).map(|(_, a)| *a);
ppd.papers.push(PpdPaper { name: paper_name(&keyword, &label), keyword, width: *w, height: *h, imageable });
}
ppd
}
/// The margin IPP printers commonly report for each edge of a sheet that is not borderless
/// (`media-*-margin` 423, in hundredths of a millimetre), used when nothing better is known.
const IPP_MARGIN_MM: f64 = 4.23;
/// The size of a media keyword `lpoptions -l` lists, in points: a PWG self-describing name
/// (`iso_a4_210x297mm`, `na_letter_8.5x11in`), Adobe's `w612h792` (points), or a standard size
/// CADCraft knows (`A4`, `Letter`, `Legal`, `Tabloid`…, shown by its keyword). `None` for custom
/// and unknown ones.
fn media_size(keyword: &str) -> Option<(String, f64, f64)> {
let k = keyword.trim();
if k.is_empty() || k.to_ascii_lowercase().starts_with("custom") {
return None;
}
// PWG 5101.1: `class_name_WxHunit`, the size as the last part.
if let Some((head, dims)) = k.rsplit_once('_') {
let (dims, mm) = match (dims.strip_suffix("mm"), dims.strip_suffix("in")) {
(Some(d), _) => (d, 1.0),
(None, Some(d)) => (d, 25.4),
(None, None) => ("", 0.0),
};
if let Some((w, h)) = dims.split_once('x')
&& let (Ok(w), Ok(h)) = (w.parse::<f64>(), h.parse::<f64>())
&& w.is_finite()
&& h.is_finite()
&& w > 0.0
&& h > 0.0
{
// `iso_a4` → "A4", `na_letter` → "Letter": the name part after the class.
let name = head.split_once('_').map_or(head, |(_, n)| n);
let shown = if name.is_empty() { k.to_string() } else { pwg_name(name) };
return Some((shown, w * mm * PT_PER_MM, h * mm * PT_PER_MM));
}
}
if let Some(rest) = k.strip_prefix('w')
&& let Some((w, h)) = rest.split_once('h')
&& let (Ok(w), Ok(h)) = (w.parse::<f64>(), h.parse::<f64>())
&& w.is_finite()
&& h.is_finite()
&& w > 0.0
&& h > 0.0
{
return Some((format!("{:.0} x {:.0} mm", w / PT_PER_MM, h / PT_PER_MM), w, h));
}
// A PPD's `B4`/`B5` are the JIS sizes, not ISO's: left out rather than guessed.
let base = k.strip_suffix(".Fullbleed").unwrap_or(k);
if base.starts_with(['B', 'b']) {
return None;
}
let p = cadcraft_render::paper_size(base)?;
Some((base.to_string(), p.width_mm * PT_PER_MM, p.height_mm * PT_PER_MM))
}
/// A PWG media name shown as people write it: `a4` → "A4", `letter` → "Letter",
/// `govt-letter` → "Govt Letter".
fn pwg_name(name: &str) -> String {
let words: Vec<String> = name
.split(['-', '.'])
.filter(|w| !w.is_empty())
.map(|w| {
// ISO and JIS sizes are written in capitals (A4, B5, C6).
if w.len() <= 3 && w.chars().next().is_some_and(|c| c.is_ascii_alphabetic()) && w.chars().skip(1).all(|c| c.is_ascii_digit()) {
w.to_ascii_uppercase()
} else {
let mut c = w.chars();
c.next().map_or(String::new(), |f| f.to_uppercase().chain(c).collect())
}
})
.collect();
words.join(" ")
}
/// `lpoptions -p NAME -l` (in the C locale): the `PageSize` (or `media`) choices as papers with
/// [`IPP_MARGIN_MM`] margins, the default (marked `*`) as the default size. Keywords whose size
/// isn't known are left out.
pub fn parse_lpoptions(text: &str) -> Ppd {
let mut ppd = Ppd::default();
let line = text
.lines()
.find(|l| l.starts_with("PageSize/") || l.starts_with("PageSize:"))
.or_else(|| text.lines().find(|l| l.starts_with("media/") || l.starts_with("media:")));
let Some((_, choices)) = line.and_then(|l| l.split_once(':')) else { return ppd };
let m = IPP_MARGIN_MM * PT_PER_MM;
for choice in choices.split_whitespace().take(MAX_LPOPTIONS_CHOICES) {
let (keyword, default) = match choice.strip_prefix('*') {
Some(k) => (k, true),
None => (choice, false),
};
let Some((name, w, h)) = media_size(keyword) else { continue };
let borderless = keyword.ends_with(".Fullbleed") || keyword.contains(".Borderless");
let name = if borderless { format!("{name} (borderless)") } else { name };
let imageable = (!borderless && w > 2.0 * m && h > 2.0 * m).then_some([m, m, w - m, h - m]);
let paper = PpdPaper { keyword: keyword.to_string(), name, width: w, height: h, imageable };
if default {
ppd.default_size = keyword.to_string();
}
// Two keywords with one display name are listed once; the starred one (the queue's
// default) wins, so the default keeps its own keyword.
match ppd.papers.iter_mut().find(|p| p.name == paper.name) {
Some(listed) if default => *listed = paper,
Some(_) => {}
None => ppd.papers.push(paper),
}
}
ppd
}
/// Most `lpoptions` choices read for one option.
const MAX_LPOPTIONS_CHOICES: usize = 500;
/// `lpstat -d` (in the C locale): the default destination, if there is one.
pub fn parse_default_destination(text: &str) -> Option<String> {
let name = text.lines().find_map(|l| l.trim().strip_prefix("system default destination:"))?.trim();
valid_name(name).then(|| name.to_string())
}
/// The device a destination becomes: a system printer (PDF in, printed with `lp`) with the
/// PPD's papers.
pub fn printer_config(name: &str, ppd: &Ppd) -> PlotterConfig {
let papers: Vec<DevicePaper> = ppd
.papers
.iter()
.map(|p| {
let margins = p.imageable.map_or([0.0; 4], |[llx, lly, urx, ury]| {
[llx / PT_PER_MM, lly / PT_PER_MM, (p.width - urx) / PT_PER_MM, (p.height - ury) / PT_PER_MM]
});
DevicePaper {
native_key: Some(p.keyword.clone()),
name: p.name.clone(),
width: p.width / PT_PER_MM,
height: p.height / PT_PER_MM,
margins,
}
})
.collect();
let default_paper = ppd.papers.iter().find(|p| p.keyword == ppd.default_size).map(|p| p.name.clone()).unwrap_or_default();
let description = if ppd.nick_name.is_empty() { "System printer".to_string() } else { ppd.nick_name.clone() };
let mut config = PlotterConfig {
name: name.to_string(),
description,
output: PlotOutput::Pdf,
resolution: 300,
orientation: Orientation::Landscape,
default_paper,
papers,
system: true,
system_default: false,
}
.sanitized();
// Queue names are routing identifiers, not display labels. Truncating a valid CUPS name
// can route a job to a different queue with the same prefix.
config.name = if valid_name(name) { name.to_string() } else { String::new() };
config
}
/// Whether `lpstat -H` (the scheduler `lp` and `lpstat` talk to, in the C locale) names this
/// computer's own CUPS: a local socket, or `localhost`. Only then are the PPD files in
/// `/etc/cups/ppd` the destinations' own; a remote server (`CUPS_SERVER`, `client.conf`) is
/// asked for its destinations' papers instead.
pub fn local_scheduler(text: &str) -> bool {
let Some(server) = text.lines().map(str::trim).find(|l| !l.is_empty()) else { return false };
if server.starts_with('/') {
return true;
}
// `host:port`, `[v6]:port` or `host`.
let host = match server.strip_prefix('[') {
Some(rest) => rest.split(']').next().unwrap_or(""),
None => server.rsplit_once(':').map_or(server, |(h, port)| if port.chars().all(|c| c.is_ascii_digit()) { h } else { server }),
};
let host = host.trim_end_matches('.').to_ascii_lowercase();
host == "localhost" || host == "::1" || host.starts_with("127.") || host.ends_with(".localhost")
}
/// `lpstat -e`: one destination per line.
pub fn parse_destinations(text: &str) -> Vec<String> {
let mut v: Vec<String> = text.lines().map(str::trim).filter(|n| valid_name(n)).map(String::from).collect();
v.dedup();
v.truncate(MAX_PRINTERS);
v
}
/// `lp`'s reply: the job id from `request id is NAME-12 (1 file(s))`.
pub fn parse_request_id(text: &str) -> Option<String> {
let rest = text.split("request id is ").nth(1)?;
rest.split_whitespace().next().map(String::from)
}
/// A destination name CUPS could have made (no path separators or control characters).
pub fn valid_name(n: &str) -> bool {
!n.is_empty() && n.len() <= 127 && !n.starts_with('.') && !n.contains(['/', '\\', '#']) && !n.chars().any(|c| c.is_control() || c.is_whitespace())
}
/// The `lp` option choosing the paper `keyword`: `PageSize` for a paper of the printer's PPD,
/// IPP's `media` for one `lpoptions` listed for a queue without one.
pub fn paper_option(keyword: &str, from_ppd: bool) -> String {
if from_ppd { format!("PageSize={keyword}") } else { format!("media={keyword}") }
}
/// Resolve the requested sheet before spawning `lp`: an absent override would print on the
/// queue's default paper instead of the paper the preview showed.
#[cfg_attr(not(all(unix, not(target_arch = "wasm32"))), allow(dead_code))]
fn required_paper(papers: Option<(Ppd, bool)>, paper: &str, size_mm: (f64, f64)) -> Result<String, String> {
let (ppd, from_ppd) = papers.ok_or_else(|| "could not read the printer's paper capabilities".to_string())?;
let selected = ppd.papers.iter().find(|p| p.keyword == paper).ok_or_else(|| format!("the printer no longer offers paper `{paper}`"))?;
let (w, h) = (selected.width / PT_PER_MM, selected.height / PT_PER_MM);
if !size_mm.0.is_finite()
|| !size_mm.1.is_finite()
|| size_mm.0 <= 0.0
|| size_mm.1 <= 0.0
|| (w.min(h) - size_mm.0.min(size_mm.1)).abs() > 0.1
|| (w.max(h) - size_mm.0.max(size_mm.1)).abs() > 0.1
{
return Err("the printer paper size changed; refresh the printer and plot again".into());
}
Ok(paper_option(&selected.keyword, from_ppd))
}
/// The `lp` arguments for a job (the PDF goes to standard input); `paper` is a
/// [`paper_option`].
pub fn lp_args(printer: &str, paper: Option<&str>, copies: u32, title: &str) -> Vec<String> {
let mut a = vec!["-d".into(), printer.into(), "-n".into(), copies.clamp(1, MAX_COPIES).to_string()];
let title: String = title.chars().filter(|c| !c.is_control()).take(100).collect();
if !title.trim().is_empty() {
a.extend(["-t".into(), title]);
}
if let Some(o) = paper {
a.extend(["-o".into(), o.to_string()]);
}
// The plot is already at its scale: no fitting to the page.
a.extend(["-o".into(), "print-scaling=none".into(), "-o".into(), "fit-to-page=false".into(), "-".into()]);
a
}
#[cfg(all(unix, not(target_arch = "wasm32")))]
mod system {
use super::{
MAX_PPD, PlotterConfig, Ppd, local_scheduler, lp_args, parse_default_destination, parse_destinations, parse_lpoptions, parse_ppd,
parse_request_id, printer_config, valid_name,
};
use std::io::Write;
use std::process::{Command, Stdio};
/// The destination's PPD from the CUPS folder, when it is readable and not too large.
fn ppd(name: &str) -> Option<Ppd> {
let path = format!("/etc/cups/ppd/{name}.ppd");
if std::fs::metadata(&path).ok()?.len() > MAX_PPD {
return None;
}
Some(parse_ppd(&std::fs::read_to_string(path).ok()?))
}
/// Longest a CUPS command may take: a CUPS that doesn't answer gives no printers instead of
/// a listing that never ends.
const CUPS_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(5);
/// Longest `lp` may take to take a job (it carries the whole PDF).
const LP_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(60);
/// Start a pipe worker, or `None` when the system refuses a thread (the caller then stops
/// its command instead of panicking).
fn worker<T: Send + 'static>(f: impl FnOnce() -> T + Send + 'static) -> Option<std::thread::JoinHandle<T>> {
#[cfg(test)]
if tests::REFUSE_THREADS.with(std::cell::Cell::get) {
return None;
}
std::thread::Builder::new().name("cups-pipe".into()).spawn(f).ok()
}
/// Stop a command and reap it, so no zombie is left behind.
fn stop(child: &mut std::process::Child) {
let _ = child.kill();
let _ = child.wait();
}
/// A CUPS command's output in the C locale (its messages untranslated, so they parse), or
/// `None` when it fails or takes longer than [`CUPS_TIMEOUT`] (then it is stopped).
fn cups_output(program: &str, args: &[&str]) -> Option<String> {
use std::io::Read;
let mut child = Command::new(program)
.args(args)
.env("LC_ALL", "C")
.env("LANG", "C")
.stdin(Stdio::null())
.stdout(Stdio::piped())
.stderr(Stdio::null())
.spawn()
.ok()?;
let Some(stdout) = child.stdout.take() else {
stop(&mut child);
return None;
};
// Read on a thread, so a full pipe can't keep the command from ending.
let Some(reader) = worker(move || {
let mut s = String::new();
let _ = stdout.take(MAX_PPD).read_to_string(&mut s);
s
}) else {
stop(&mut child);
return None;
};
let start = std::time::Instant::now();
loop {
match child.try_wait() {
Ok(Some(status)) if status.success() => return reader.join().ok(),
Ok(Some(_)) => return None,
Err(_) => {
stop(&mut child);
return None;
}
Ok(None) if start.elapsed() > CUPS_TIMEOUT => {
stop(&mut child);
return None;
}
Ok(None) => std::thread::sleep(std::time::Duration::from_millis(20)),
}
}
}
/// Whether the scheduler `lp` sends jobs to is this computer's own ([`local_scheduler`]); not
/// knowing counts as not.
fn local() -> bool {
cups_output("lpstat", &["-H"]).is_some_and(|t| local_scheduler(&t))
}
/// The papers of destination `name`: its PPD's when the scheduler is this computer's own
/// (`local`), else (a remote server, or no PPD file the user can read) the ones `lpoptions`
/// lists, which come from the server that takes the job. The flag says which.
fn papers(name: &str, local: bool) -> Option<(Ppd, bool)> {
if let Some(p) = local.then(|| ppd(name)).flatten().filter(|p| !p.papers.is_empty()) {
return Some((p, true));
}
let p = parse_lpoptions(&cups_output("lpoptions", &["-p", name, "-l"])?);
(!p.papers.is_empty()).then_some((p, false))
}
/// Destinations asked about their papers at once, so slow ones don't hold up the others.
static ASKING: crate::printer_queries::Asking = std::sync::Mutex::new(Vec::new());
/// How long the destinations' papers are waited for: a destination that answers later is
/// left out of this listing, and the engine's own wait for the listing is not run out.
const PAPERS_TIME: std::time::Duration = std::time::Duration::from_secs(6);
/// The CUPS destinations as devices (none when CUPS is missing), the system's default
/// printer marked. A destination whose papers can't be read, or are not read in time, is
/// left out.
pub fn printers() -> Vec<PlotterConfig> {
let Some(out) = cups_output("lpstat", &["-e"]) else { return Vec::new() };
let default = cups_output("lpstat", &["-d"]).and_then(|t| parse_default_destination(&t));
let local = local();
let names: Vec<(String, String)> = parse_destinations(&out).into_iter().map(|n| (n.clone(), n)).collect();
crate::printer_queries::ask_each(&ASKING, names, PAPERS_TIME, move |n: String| {
let (p, _) = papers(&n, local)?;
let mut c = printer_config(&n, &p);
c.system_default = default.as_deref() == Some(n.as_str());
Some(c)
})
}
/// Send `pdf` to `printer` on the paper called `paper` (a name [`printers`] gave).
/// Returns the job id.
pub fn print(printer: &str, paper: &str, size_mm: (f64, f64), copies: u32, title: &str, pdf: &[u8]) -> Result<String, String> {
if !valid_name(printer) {
return Err(format!("`{printer}` is not a printer name"));
}
let option = super::required_paper(papers(printer, local()), paper, size_mm)?;
let mut child = Command::new("lp")
.args(lp_args(printer, Some(&option), copies, title))
.env("LC_ALL", "C")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
.spawn()
.map_err(|e| format!("lp: {e}"))?;
// The PDF goes in and the answers come out on threads, and `lp` is stopped when it doesn't
// finish in time, so a CUPS that stopped answering can't hold PLOT (and the window) up.
let no_thread = |child: &mut std::process::Child| {
// Workers already started end when the stopped `lp`'s pipes close.
stop(child);
"lp: the system could not start a thread for the job".to_string()
};
let writer = match child.stdin.take() {
Some(mut stdin) => {
let pdf = pdf.to_vec();
Some(worker(move || stdin.write_all(&pdf)).ok_or_else(|| no_thread(&mut child))?)
}
None => None,
};
let drain = |pipe: Option<Box<dyn std::io::Read + Send>>| {
worker(move || {
let mut s = String::new();
if let Some(p) = pipe {
let _ = std::io::Read::read_to_string(&mut std::io::Read::take(p, 64 * 1024), &mut s);
}
s
})
};
let out = drain(child.stdout.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>)).ok_or_else(|| no_thread(&mut child))?;
let err = drain(child.stderr.take().map(|p| Box::new(p) as Box<dyn std::io::Read + Send>)).ok_or_else(|| no_thread(&mut child))?;
let start = std::time::Instant::now();
let status = loop {
match child.try_wait() {
Ok(Some(status)) => break status,
Err(e) => {
stop(&mut child);
return Err(format!("lp: {e}"));
}
Ok(None) if start.elapsed() > LP_TIMEOUT => {
stop(&mut child);
// Stopping `lp` cancels nothing CUPS already took: the job may be queued.
return Err(format!(
"lp did not answer within {} s; the job may already be queued: check the printer's queue (lpstat -o {printer}) before plotting again",
LP_TIMEOUT.as_secs()
));
}
Ok(None) => std::thread::sleep(std::time::Duration::from_millis(20)),
}
};
if let Some(Ok(Err(e))) = writer.map(std::thread::JoinHandle::join) {
return Err(format!("lp: {e}"));
}
let said = out.join().unwrap_or_default();
if !status.success() {
let err = err.join().unwrap_or_default().trim().to_string();
return Err(if err.is_empty() { format!("lp failed ({status})") } else { err });
}
Ok(parse_request_id(&said).unwrap_or_else(|| said.trim().to_string()))
}
#[cfg(test)]
pub(super) mod tests {
use super::*;
thread_local! {
/// Stands for a system that refuses new threads.
pub(super) static REFUSE_THREADS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
}
/// A CUPS command whose pipe reader can't start gives no output (it is stopped and
/// reaped) instead of panicking; with threads it reads as usual.
#[test]
fn a_refused_reader_thread_stops_the_command_without_panicking() {
assert_eq!(cups_output("echo", &["lpstat"]).as_deref().map(str::trim), Some("lpstat"));
REFUSE_THREADS.with(|r| r.set(true));
let start = std::time::Instant::now();
let out = cups_output("sleep", &["30"]);
REFUSE_THREADS.with(|r| r.set(false));
assert_eq!(out, None);
assert!(start.elapsed() < CUPS_TIMEOUT, "the command was stopped at once, not waited for: {:?}", start.elapsed());
}
}
}
#[cfg(all(unix, not(target_arch = "wasm32")))]
pub use system::{print, printers};
#[cfg(test)]
mod tests {
use super::*;
const PPD: &str = r#"*PPD-Adobe: "4.3"
*NickName: "EPSON Example Series-AirPrint"
*OpenUI *PageSize/Media Size: PickOne
*DefaultPageSize: Letter
*PageSize A4: "<</PageSize[595.2756 841.8898]>>setpagedevice"
*PageSize Letter/US Letter: "<</PageSize[612 792]>>setpagedevice"
*PageSize Letter.Fullbleed: "<</PageSize[612 792]>>setpagedevice"
*PageSize Roll610/Roll 24 in: "<</PageSize[1728 2592]>>setpagedevice"
*PageSize NoDims: "<</PageSize[1 1]>>setpagedevice"
*CloseUI: *PageSize
*PageRegion A4: "<</PageSize[595.2756 841.8898]>>setpagedevice"
*PaperDimension A4: "595.2756 841.8898"
*ImageableArea A4: "8.5039 8.5039 586.7717 833.3858"
*PaperDimension Letter/US Letter: "612.0000 792.0000"
*ImageableArea Letter/US Letter: "18 36 594 756"
*PaperDimension Letter.Fullbleed: "612 792"
*ImageableArea Letter.Fullbleed: "0 0 612 792"
*PaperDimension Roll610: "1728 2592"
"#;
/// A PPD gives the papers with their sizes and printable areas, borderless and roll papers named as such.
#[test]
fn ppd_papers_sizes_and_printable_areas() {
let p = parse_ppd(PPD);
assert_eq!(p.nick_name, "EPSON Example Series-AirPrint");
assert_eq!(p.default_size, "Letter");
let names: Vec<&str> = p.papers.iter().map(|x| x.name.as_str()).collect();
assert_eq!(names, ["A4", "US Letter", "Letter (borderless)", "Roll 24 in"]);
let c = printer_config("EPSON_Example", &p);
assert!(c.system);
assert_eq!(c.output, PlotOutput::Pdf);
assert_eq!(c.default_paper, "US Letter");
let letter = c.paper("US Letter").unwrap();
assert!((letter.width - 215.9).abs() < 0.01 && (letter.height - 279.4).abs() < 0.01);
let [l, b, r, t] = letter.margins;
assert!((l - 6.35).abs() < 0.01 && (b - 12.7).abs() < 0.01 && (r - 6.35).abs() < 0.01 && (t - 12.7).abs() < 0.01);
assert_eq!(c.paper("Letter (borderless)").unwrap().margins, [0.0; 4]);
// No ImageableArea: the whole sheet.
assert_eq!(c.paper("Roll 24 in").unwrap().margins, [0.0; 4]);
}
/// Destination names and job ids are read from lpstat and lp, and the lp arguments are safe and complete.
#[test]
fn lpstat_and_lp_replies() {
assert_eq!(parse_destinations("EPSON_A\nEPSON_B\n\nbad/name\n"), ["EPSON_A", "EPSON_B"]);
assert_eq!(parse_request_id("request id is EPSON_A-42 (1 file(s))\n").as_deref(), Some("EPSON_A-42"));
assert_eq!(parse_request_id("nothing"), None);
let a = lp_args("EPSON_A", Some(&paper_option("Letter", true)), 0, "Plan\u{7}.dwg - Model");
assert_eq!(
a,
[
"-d",
"EPSON_A",
"-n",
"1",
"-t",
"Plan.dwg - Model",
"-o",
"PageSize=Letter",
"-o",
"print-scaling=none",
"-o",
"fit-to-page=false",
"-"
]
);
assert_eq!(lp_args("P", None, 5000, "")[3], "999");
assert_eq!(paper_option("iso_a4_210x297mm", false), "media=iso_a4_210x297mm");
}
/// A queue without a readable PPD: its papers from `lpoptions -l`, PWG, Adobe and plain
/// keywords, the default marked, unknown and custom sizes left out.
#[test]
fn lpoptions_papers_of_a_driverless_queue() {
let text = "ColorModel/Color Mode: *RGB Gray\n\
PageSize/Media Size: iso_a3_297x420mm *iso_a4_210x297mm na_letter_8.5x11in w612h1008 Legal A4.Fullbleed Custom.WIDTHxHEIGHT EnvWeird\n\
Duplex/2-Sided Printing: *None DuplexNoTumble\n";
let p = parse_lpoptions(text);
let names: Vec<&str> = p.papers.iter().map(|x| x.name.as_str()).collect();
assert_eq!(names, ["A3", "A4", "Letter", "216 x 356 mm", "Legal", "A4 (borderless)"]);
assert_eq!(p.default_size, "iso_a4_210x297mm");
let c = printer_config("Office", &p);
assert_eq!(c.default_paper, "A4");
assert_eq!(c.description, "System printer");
let a4 = c.paper("A4").unwrap();
assert!((a4.width - 210.0).abs() < 0.01 && (a4.height - 297.0).abs() < 0.01, "{a4:?}");
assert!(a4.margins.iter().all(|m| (m - IPP_MARGIN_MM).abs() < 0.01), "{a4:?}");
let letter = c.paper("Letter").unwrap();
assert!((letter.width - 215.9).abs() < 0.01 && (letter.height - 279.4).abs() < 0.01);
assert_eq!(c.paper("A4 (borderless)").unwrap().margins, [0.0; 4]);
// A `media` option when there is no PageSize; nothing at all gives no papers.
assert_eq!(parse_lpoptions("media/Media: *na_legal_8.5x14in\n").papers.len(), 1);
assert!(parse_lpoptions("Duplex/2-Sided Printing: *None\n").papers.is_empty());
assert!(parse_lpoptions("PageSize/Media Size: iso_a4_0x0mm iso_a4_NaNxNaNmm w-1h5\n").papers.is_empty());
}
/// Only this computer's own scheduler has its destinations' PPD files in `/etc/cups/ppd`
/// (#2171 review).
#[test]
fn the_scheduler_lpstat_names() {
for local in ["/run/cups/cups.sock\n", "localhost:631\n", "127.0.0.1:631", "[::1]:631", "localhost"] {
assert!(local_scheduler(local), "{local}");
}
for remote in ["print.example.org:631\n", "10.0.0.5", "[fe80::1]:631", "", "localhost.example.org:631"] {
assert!(!local_scheduler(remote), "{remote}");
}
}
/// The default printer is read from `lpstat -d`; none, or a bad name, gives none.
#[test]
fn the_default_destination() {
assert_eq!(parse_default_destination("system default destination: Office_T120\n").as_deref(), Some("Office_T120"));
assert_eq!(parse_default_destination("no system default destination\n"), None);
assert_eq!(parse_default_destination("system default destination: bad/name\n"), None);
}
#[test]
fn native_queue_names_do_not_alias_after_one_hundred_characters() {
let name = "Q".repeat(100);
let other = format!("{name}X");
let ppd = parse_lpoptions("PageSize: *A4 A3");
assert_eq!(printer_config(&name, &ppd).name, name);
assert_eq!(printer_config(&other, &ppd).name, other);
}
#[test]
fn a_missing_selected_paper_is_not_replaced_by_the_queue_default() {
assert!(required_paper(None, "A3", (297.0, 420.0)).is_err());
let papers = || parse_lpoptions("PageSize: *A4");
assert!(required_paper(Some((papers(), true)), "A3", (297.0, 420.0)).is_err());
assert_eq!(required_paper(Some((papers(), true)), "A4", (210.0, 297.0)).unwrap(), "PageSize=A4");
assert_eq!(required_paper(Some((papers(), false)), "A4", (210.0, 297.0)).unwrap(), "media=A4");
}
}
#[cfg(test)]
mod media_regressions {
// Synthetic PPD records authored here; no printer driver files or samples are copied.
use super::*;
#[test]
fn a_shortened_display_label_keeps_its_native_media_identifier() {
let label = "A long display label ".repeat(8);
let text = format!("*PageSize Roll24/{label}: \"\"\n*PaperDimension Roll24: \"1728 2592\"\n");
let ppd = parse_ppd(&text);
let config = printer_config("Office", &ppd);
let paper = &config.papers[0];
assert!(paper.name.len() < label.len());
assert_eq!(required_paper(Some((ppd, true)), paper.native_key.as_deref().unwrap(), (paper.width, paper.height)).unwrap(), "PageSize=Roll24");
}
#[test]
fn changed_media_dimensions_are_refused_before_submission() {
let papers = || parse_ppd("*PageSize Roll24/Roll 24 in: \"\"\n*PaperDimension Roll24: \"1728 3456\"\n");
assert!(required_paper(Some((papers(), true)), "Roll24", (609.6, 914.4)).is_err());
assert!(required_paper(Some((papers(), true)), "Roll24", (609.6, 1219.2)).is_ok());
assert!(required_paper(Some((papers(), true)), "removed", (609.6, 1219.2)).is_err());
}
}
#[cfg(test)]
mod starred_collision_regressions {
use super::*;
#[test]
fn the_starred_choice_wins_a_display_name_collision() {
let ppd = parse_lpoptions("PageSize/Media Size: na_letter_8.5x11in iso_a4_210x297mm *A4\n");
let a4: Vec<&PpdPaper> = ppd.papers.iter().filter(|p| p.name == "A4").collect();
assert_eq!(a4.len(), 1, "one entry per display name");
assert_eq!(a4[0].keyword, ppd.default_size, "the default keeps its own keyword");
assert_eq!(printer_config("Office", &ppd).default_paper, "A4");
}
}
-41
View File
@@ -19,8 +19,6 @@ use crate::dxf_ext::{self, DimVal, K};
mod assoc;
mod blocks;
mod common;
#[cfg(test)]
pub(crate) use common::{attdef_definition_visits, reset_attdef_definition_visits};
mod ctx;
mod entity;
mod header;
@@ -168,45 +166,6 @@ fn tags_kept(d: &Drawing, version: Version) -> (Vec<Tag>, std::collections::Hash
(tags, kept)
}
/// One record written after an entity's own, at `index`: an INSERT's ATTRIB, then its SEQEND
/// (items of a POLYLINE's sequence are not records `entnext` reaches yet). The record's type name
/// and groups without its `0` group; its handle (5) and owner (330) are left out: it has no
/// handle of its own in the drawing (the writer makes one per file), and its owner is the entity.
/// `None` past the last record, and for an entity written as a single record. AutoLISP's
/// `entnext` and `entget` read one record at a time through it, never writing the entity's other
/// records.
pub fn entity_sub_record(d: &Drawing, e: &Entity, index: usize) -> Option<(String, Vec<Tag>)> {
let cadcraft_doc::EntityKind::Insert(i) = &e.kind else { return None };
if i.attribs.is_empty() {
return None;
}
let mut w = W {
t: Vec::new(),
next: d.handseed.max(0x100).saturating_add(0x1000),
used: HashSet::new(),
pstyles: HashMap::new(),
layers: HashMap::new(),
ucss: HashMap::new(),
vport_ucs: Vec::new(),
reactors: HashMap::new(),
xdicts: HashMap::new(),
};
let cx = Ctx { target: Version::R2018, legacy_columns: true, ..Ctx::default() };
match i.attribs.get(index) {
Some(a) => {
let base = d.block(&i.block).and_then(|b| common::attdef_base(b, &a.tag));
entity::attrib_record(&mut w, d, e, index, a, base, &cx);
}
None if index == i.attribs.len() => entity::seqend_record(&mut w, e),
None => return None,
}
let mut tags = w.t.into_iter();
let kind = tags.next().filter(|t| t.code == 0).map(|t| t.value.as_str())?;
let mut tags: Vec<Tag> = tags.filter(|t| t.code != 5 && t.code != 330).collect();
// Strings as AutoLISP sees them (`10^2`, not the file's `10^ 2`), as in `entity_groups`.
crate::dxf_read::mtext_dxf::map_text_groups(&kind, &mut tags, crate::dxf_read::mtext_dxf::decode_line);
Some((kind, tags))
}
/// The most dash elements a linetype keeps in a DWG. The DWG writer (acadrust) stores the count in
/// one byte, so a longer pattern would come back with its count modulo 256 (none at all for 256),
/// and a DWG save keeps the first 255 instead ([`dwg_notes`] says so).
+9 -135
View File
@@ -1,138 +1,9 @@
use std::cell::RefCell;
use std::collections::BTreeMap;
use super::ctx::{AssocObj, Ctx};
use super::{
Attrib, Block, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, EntityKind, HAlign, Handle, HashMap, Lineweight, Text, Transparency,
VAlign, Vec3, Version, W, dxf_ext,
Attrib, Color, Common, DimKind, DimStyle, Dimension, Drawing, Entity, HAlign, HashMap, Lineweight, Text, Transparency, VAlign, Vec3, Version, W,
dxf_ext,
};
/// The most ATTDEF tags the definition indexes on one thread hold in all (a block with none
/// counts as one). An index that fits but would pass this total drops the indexes already
/// stored, then takes their place. A definition with more distinct tags than this is not indexed:
/// its state is remembered as too large, and each read of it scans the definition for the first
/// matching ATTDEF and keeps nothing, so one block cannot grow the cache past the budget, and the
/// written file still takes its properties from the right definition.
const MAX_INDEXED_TAGS: usize = 1 << 18;
/// The most block states remembered as too large to index; past it the list starts again.
const MAX_TOO_LARGE: usize = 1 << 10;
/// For each state of a block definition's entities read on this thread, by its content token
/// ([`cadcraft_doc::EntityStore::content_token`]): the handle of the first ATTDEF of each tag
/// (upper case). A token names one state of one store, so an index is never used for another
/// copy or another edit of the block, and blocks read in turn keep their indexes. A definition
/// past [`MAX_INDEXED_TAGS`] has no entry here.
#[derive(Default)]
struct AttdefIndexes {
/// Order tags from the drawing so lookup cost does not depend on hash collisions.
by_store: HashMap<u64, BTreeMap<String, Handle>>,
/// Tags held in all, for [`MAX_INDEXED_TAGS`].
tags: usize,
/// States of definitions with more distinct tags than [`MAX_INDEXED_TAGS`], so a read of one
/// goes straight to [`scan_attdef`] without building and dropping an index again.
too_large: std::collections::HashSet<u64>,
}
thread_local! {
static ATTDEF_INDEXES: RefCell<AttdefIndexes> = RefCell::new(AttdefIndexes::default());
/// Entities of a block definition examined while matching an attribute to its ATTDEF.
#[cfg(test)]
static ATTDEF_VISITS: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
}
/// The first ATTDEF of each tag in `block`, by upper-case tag, when there are at most `budget`
/// distinct tags. `None` when another distinct tag would pass `budget`: the partial map is
/// dropped, so a prefix is not stored in place of the definition.
fn attdef_index_within(block: &Block, budget: usize) -> Option<BTreeMap<String, Handle>> {
let mut by_tag = BTreeMap::new();
for e in block.entities.iter() {
count_attdef_visit();
if let EntityKind::AttDef(ad) = &e.kind {
let key = ad.tag.to_ascii_uppercase();
if by_tag.contains_key(&key) {
continue;
}
if by_tag.len() >= budget {
return None;
}
by_tag.insert(key, e.handle);
}
}
Some(by_tag)
}
/// The first ATTDEF of `block` whose tag matches `tag`, ignoring ASCII case: one pass over the
/// definition at most, stopping at the match. Nothing from the scan is stored.
fn scan_attdef(block: &Block, tag: &str) -> Option<Handle> {
for e in block.entities.iter() {
count_attdef_visit();
if let EntityKind::AttDef(ad) = &e.kind
&& ad.tag.eq_ignore_ascii_case(tag)
{
return Some(e.handle);
}
}
None
}
/// The definition properties of the first ATTDEF in `block` whose tag matches `tag`, ignoring
/// ASCII case. Each state of a block's entities that fits in [`MAX_INDEXED_TAGS`] is read once
/// on a thread: later attributes, of this reference or another, find their definition in its
/// index. A definition with more distinct tags is not stored: the first read of that state builds
/// at most [`MAX_INDEXED_TAGS`] index entries, then gives up and remembers the state; every read
/// of it scans the definition once at most, stopping at the first match.
pub(super) fn attdef_base<'a>(block: &'a Block, tag: &str) -> Option<&'a Common> {
let token = block.entities.content_token();
let want = tag.to_ascii_uppercase();
let found = ATTDEF_INDEXES
.try_with(|cell| {
let Ok(mut ix) = cell.try_borrow_mut() else { return scan_attdef(block, tag) };
if let Some(by_tag) = ix.by_store.get(&token) {
return by_tag.get(&want).copied();
}
if ix.too_large.contains(&token) {
return scan_attdef(block, tag);
}
let Some(by_tag) = attdef_index_within(block, MAX_INDEXED_TAGS) else {
if ix.too_large.len() >= MAX_TOO_LARGE {
ix.too_large.clear();
}
ix.too_large.insert(token);
return scan_attdef(block, tag);
};
let found = by_tag.get(&want).copied();
let cost = by_tag.len().max(1);
if ix.tags.saturating_add(cost) > MAX_INDEXED_TAGS {
ix.by_store.clear();
ix.tags = 0;
}
ix.tags = ix.tags.saturating_add(cost);
ix.by_store.insert(token, by_tag);
found
})
.unwrap_or_else(|_| scan_attdef(block, tag));
block.entities.get(found?).map(|e| &e.common)
}
/// One more definition entity examined (counted in tests).
fn count_attdef_visit() {
#[cfg(test)]
ATTDEF_VISITS.with(|n| n.set(n.get().saturating_add(1)));
}
/// How many definition entities attribute reads have examined on this thread.
#[cfg(test)]
pub(crate) fn attdef_definition_visits() -> u64 {
ATTDEF_VISITS.with(std::cell::Cell::get)
}
/// Start a definition-visit count from zero.
#[cfg(test)]
pub(crate) fn reset_attdef_definition_visits() {
ATTDEF_VISITS.with(|n| n.set(0));
}
/// `AcadAnnotative` xdata marking an annotative style or block.
pub(super) fn annotative_xdata(w: &mut W) {
w.s(1001, "AcadAnnotative");
@@ -275,10 +146,13 @@ pub(super) fn layer_and_props(w: &mut W, c: &Common, base: Option<&Common>) {
}
}
/// Attribute `a` takes its own properties over its definition's. A layer 0 inherited from the
/// definition takes the reference's layer; an explicit layer 0 stays. Return both properties.
pub(super) fn attrib_common(e: &Entity, a: &Attrib, base: Option<&Common>) -> (Common, Common) {
let base = base.cloned().unwrap_or_default();
/// The properties attribute `a` of block reference `e` is drawn with: its own, else its
/// definition's, from the block's definitions by tag `defs`; an attribute that takes layer 0 from
/// its definition is on the reference's layer, one set on layer 0 itself stays there. Also the
/// definition's properties.
pub(super) fn attrib_common(e: &Entity, defs: &std::collections::BTreeMap<cadcraft_doc::TagKey<'_>, &Entity>, a: &Attrib) -> (Common, Common) {
let def = defs.get(&cadcraft_doc::TagKey(&a.tag));
let base = def.map(|de| de.common.clone()).unwrap_or_default();
let mut c = a.props.over(&base);
if a.props.layer.is_none() && c.layer == "0" {
c.layer.clone_from(&e.common.layer);
+23 -36
View File
@@ -3,8 +3,7 @@ use super::common::{attrib_common, common, common_x, dim_xdata, layer_and_props,
use super::ctx::Ctx;
use super::layout::paper_view;
use super::{
Attrib, Bounds2, Color, Common, DimKind, Drawing, Entity, EntityKind, Gradient, Handle, HashMap, Hatch, Leader, MLeader, Point, Vec2, Vec3,
Version, W, dxf_ext,
Bounds2, Color, DimKind, Drawing, Entity, EntityKind, Gradient, Handle, HashMap, Hatch, Leader, MLeader, Point, Vec2, Vec3, Version, W, dxf_ext,
};
/// The persistent reactors of boundary objects: each source object of an associative hatch in
@@ -426,45 +425,33 @@ fn write_insert_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: b
// The block's definitions by tag, gathered once for all the attributes (#1923).
let defs = d.block(&i.block).map(|b| b.attdefs_by_tag()).unwrap_or_default();
for (index, a) in i.attribs.iter().enumerate() {
let base = defs.get(&cadcraft_doc::TagKey(&a.tag)).map(|de| &de.common);
attrib_record(w, d, e, index, a, base, cx);
let ah = w.h();
w.s(0, "ATTRIB");
w.s(5, ah);
w.s(330, e.handle.hex());
w.s(100, "AcDbEntity");
let (c, base) = attrib_common(e, &defs, a);
layer_and_props(w, &c, Some(&base));
// Hidden with its definition (a dynamic block's visibility state hides it).
if !base.visible {
w.i(60, 1);
}
w.s(100, "AcDbText");
text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index));
if cx.target >= Version::R2007 {
multiline_tags(w, a, false);
}
}
seqend_record(w, e);
let sh = w.h();
w.s(0, "SEQEND");
w.s(5, sh);
w.s(330, e.handle.hex());
w.s(100, "AcDbEntity");
w.s(8, &e.common.layer);
}
}
}
/// One ATTRIB record of the block reference `e`, for its attribute `a` (as written after its
/// INSERT): its handle is a new one, its owner the reference's.
pub(super) fn attrib_record(w: &mut W, d: &Drawing, e: &Entity, index: usize, a: &Attrib, base: Option<&Common>, cx: &Ctx) {
let ah = w.h();
w.s(0, "ATTRIB");
w.s(5, ah);
w.s(330, e.handle.hex());
w.s(100, "AcDbEntity");
let (c, base) = attrib_common(e, a, base);
layer_and_props(w, &c, Some(&base));
// Hidden with its definition (a dynamic block's visibility state hides it).
if !base.visible {
w.i(60, 1);
}
w.s(100, "AcDbText");
text_tags(w, d, &a.text, Some((a, cx.target)), None, (e.handle, index));
if cx.target >= Version::R2007 {
multiline_tags(w, a, false);
}
}
/// The SEQEND record that ends a block reference's attributes (written after its last ATTRIB).
pub(super) fn seqend_record(w: &mut W, e: &Entity) {
let sh = w.h();
w.s(0, "SEQEND");
w.s(5, sh);
w.s(330, e.handle.hex());
w.s(100, "AcDbEntity");
w.s(8, &e.common.layer);
}
fn write_dimension_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bool, cx: &Ctx) {
if let EntityKind::Dimension(dm) = &e.kind {
w.s(0, "DIMENSION");
+7 -1
View File
@@ -7,6 +7,7 @@ mod dwg_hatch;
/// What a DXF file holds that CADCraft doesn't model, kept and written back (#528).
mod dxf_raw;
pub mod cups;
/// Annotative text, MText and dimensions: AutoCAD's annotation scale contexts.
mod dxf_anno;
/// XCLIP boundaries as SPATIAL_FILTER objects.
@@ -22,12 +23,17 @@ mod dxf_xref;
pub mod pdf;
pub mod pdf_read;
pub mod plotter;
/// The system's printers asked about at once, so one that doesn't answer holds up no other.
#[cfg(not(target_arch = "wasm32"))]
mod printer_queries;
/// Raster image files (PNG, JPEG, BMP, TIFF) decoded to pixels.
pub mod raster;
/// Open → save → reopen comparison and the real-file corpus harness (gaps FF1, FF5).
pub mod roundtrip;
pub mod stamp;
pub mod svg;
mod svg_read;
pub mod winprint;
/// Multilines and their styles (MLINE, MLINESTYLE).
mod dxf_mline;
@@ -40,7 +46,7 @@ pub use cadcraft_doc::Format;
pub use craft_dxf::Version;
pub use dxf_raw::{ObjectRecord, object_records};
pub use dxf_read::entity_from_groups;
pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, entity_sub_record, proxies_lost};
pub use dxf_write::{DWG_MAX_LINETYPE_ELEMENTS, dwg_compat_lost, dwg_notes, entity_groups, proxies_lost};
pub use pdf::{PdfOptions, pdf, plot};
/// How a drawing is saved as DXF or DWG.
+130 -22
View File
@@ -102,12 +102,20 @@ pub struct PdfOptions {
/// Entity hyperlinks read from a drawing file (`PE_URL` extended data) become link
/// annotations too, after [`PdfOptions::links`]. Default on.
pub hyperlinks: bool,
/// Landscape pages on portrait media: the sheet turned a quarter turn on a page of the
/// paper's portrait size (for printers, which feed portrait sheets and may not turn a
/// landscape page themselves). Link annotations are left out of turned pages.
pub portrait_media: bool,
/// Plot objects with their transparency (PDF alpha). `None` = the page setup's "Plot
/// transparency" (off for model space).
pub plot_transparency: Option<bool>,
/// The plot stamp ([`crate::stamp`]): a line of text at the lower-left corner of each
/// sheet's printable area.
pub stamp: Option<String>,
}
impl Default for PdfOptions {
/// Every option unset: the page setup's paper, orientation, scale and plot style decide.
fn default() -> Self {
PdfOptions {
plot_style_table: None,
@@ -128,7 +136,9 @@ impl Default for PdfOptions {
text_as_geometry: false,
margins: None,
hyperlinks: true,
portrait_media: false,
plot_transparency: None,
stamp: None,
}
}
}
@@ -136,7 +146,7 @@ impl Default for PdfOptions {
impl PdfOptions {
/// Parse `{paper?, width?, height?, landscape?, fit?, scale?, center?, offset?: [x,y] mm,
/// lineweights?, compress?, title?, window?: [[x1, y1], [x2, y2]], margins?: [l, b, r, t] (mm),
/// hyperlinks?: bool, plotTransparency?: bool}`.
/// hyperlinks?: bool, plotTransparency?: bool, stamp?: text}`.
pub fn from_json(v: &Value) -> PdfOptions {
let num = |k: &str| v.get(k).and_then(Value::as_f64).filter(|x| x.is_finite());
let paper_mm = match (num("width"), num("height")) {
@@ -164,7 +174,9 @@ impl PdfOptions {
window: window(v.get("window")),
margins: margins(v.get("margins")),
hyperlinks: v.get("hyperlinks").and_then(Value::as_bool).unwrap_or(true),
portrait_media: v.get("portraitMedia").and_then(Value::as_bool).unwrap_or(false),
plot_transparency: v.get("plotTransparency").and_then(Value::as_bool),
stamp: crate::stamp::stamp_text(v),
}
}
}
@@ -250,6 +262,7 @@ pub fn plot_noted(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>,
po.window = Some(w);
po.fit = Some(true);
po.compress = o.compress;
po.stamp = o.stamp.clone();
Ok((Space::Model, po))
})
.collect::<Result<Vec<_>>>()?;
@@ -492,7 +505,7 @@ fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as
let doc = writer.document_mut();
// Groups are added to the document, so they must exist before the page starts.
groups.add(doc, d, &page.layers);
write_page(doc, &page, &groups, &mut fonts)?;
write_page(doc, &page, &groups, &mut fonts, o.portrait_media)?;
undashed = undashed.saturating_add(page.list.undashed);
}
if items.len() == 1 && !groups.ids.is_empty() {
@@ -534,6 +547,8 @@ struct SheetPage {
list: cadcraft_render::DisplayList,
map: Map,
clip_pt: Bounds2,
stamp: cadcraft_render::DisplayList,
printable_pt: Bounds2,
/// The drawing layers (indices in the layer table) drawn on, in order of first use: the
/// candidates for PDF layers.
layers: Vec<u32>,
@@ -603,7 +618,8 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String
let tolerance = if tol.is_finite() && tol > 0.0 { tol } else { ropts.tolerance };
// Relative point sizes follow the plotted window (else the extents).
let view_height = window.map(|w| w.height()).unwrap_or(0.0);
let list = cadcraft_render::build_plot(d, space, &cadcraft_render::Options { tolerance, view_height, ..ropts });
let ropts = cadcraft_render::Options { tolerance, view_height, ..ropts };
let list = cadcraft_render::build_plot(d, space, &ropts);
let b = window.unwrap_or(list.bounds);
let s = plot_scale(&b, &sheet, fit, o.scale);
// A layout plotted over a window is placed like model space: the window on the printable area.
@@ -615,11 +631,33 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String
} else {
Map { from: Vec2::ZERO, s, to: Vec2::ZERO, k }
};
// Plot style ends, joins and fill patterns at the plot scale (a layout's are already drawn).
// A window plots what is inside it only: what lies wholly outside is left out of the page
// (a small window of a large drawing stays small), the rest is cut at the window's edges.
let mut list = list;
if let Some(w) = window {
list.retain_within(&window_margin(&w, map.s, unit_mm));
}
// Plot style ends, joins and fill patterns at the plot scale (a layout's are already drawn).
cadcraft_render::pen::apply(&mut list, map.s * unit_mm);
let stamp = o
.stamp
.as_ref()
.map(|text| {
let text = crate::stamp::fill(text, &sheet_name(space), &page.paper, &crate::stamp::scale_label(map.s));
let to_world = |p: Vec2| (p - map.to) / map.s + map.from;
crate::stamp::display_list(&text, sheet.printable.min, unit_mm, to_world, 1.0 / map.s, &ropts)
})
.unwrap_or_default();
let media = sheet.size * k;
let clip_pt = if placed { Bounds2::new(sheet.printable.min * k, sheet.printable.max * k) } else { Bounds2::new(Vec2::ZERO, media) };
let printable_pt = Bounds2::new(sheet.printable.min * k, sheet.printable.max * k);
let clip_pt = match window {
// A window off the printable area plots nothing: a hair-thin clip at its corner.
Some(w) => Some(window_on_paper(&w, &map).intersection(&printable_pt))
.filter(|c| !c.is_empty())
.unwrap_or_else(|| Bounds2::new(printable_pt.min, printable_pt.min + Vec2::new(1e-3, 1e-3))),
None if placed => printable_pt,
None => Bounds2::new(Vec2::ZERO, media),
};
// The layers drawn on, in order of first use.
let mut layers: Vec<u32> = Vec::new();
if o.layers {
@@ -631,7 +669,19 @@ fn sheet(d: &Drawing, space: &Space, o: &PdfOptions, links_to: &[(Handle, String
}
}
let links = links(&list, &map, &clip_pt, links_to);
Ok(SheetPage { media, list, map, clip_pt, layers, links, label: sheet_name(space) })
Ok(SheetPage { media, list, map, clip_pt, stamp, printable_pt, layers, links, label: sheet_name(space) })
}
/// `w` grown by what a plotted line may reach past it, at `s` paper units per drawing unit (see
/// [`cadcraft_render::pen::plot_window_reach`]).
pub(crate) fn window_margin(w: &Bounds2, s: f64, unit_mm: f64) -> Bounds2 {
cadcraft_render::pen::plot_window_reach(w, unit_mm * s)
}
/// A plotted window `w` on the sheet, in points: where its corners land through `map`.
fn window_on_paper(w: &Bounds2, map: &Map) -> Bounds2 {
let at = |p: Vec2| ((p - map.from) * map.s + map.to) * map.k;
Bounds2::new(at(w.min), at(w.max))
}
/// Source and destination origins for the shared model-space PDF/PNG placement behavior.
@@ -776,13 +826,24 @@ fn circle_path(x: f32, y: f32, r: f32) -> Option<Path> {
pb.finish()
}
/// Write one sheet as a page: its size, label, link annotations and marks.
fn write_page(doc: &mut kr::Document, p: &SheetPage, groups: &Groups, fonts: &mut fonts::Fonts) -> std::result::Result<(), Failure> {
/// Write one sheet as a page: its size, label, link annotations and marks. With
/// `portrait_media`, a landscape sheet goes on a page of the paper's portrait size, turned a
/// quarter turn counterclockwise (the sheet's bottom edge up the page's right edge), for
/// printers that feed portrait sheets; a turned page has no link annotations.
fn write_page(
doc: &mut kr::Document,
p: &SheetPage,
groups: &Groups,
fonts: &mut fonts::Fonts,
portrait_media: bool,
) -> std::result::Result<(), Failure> {
let (w, h) = (p.media.x as f32, p.media.y as f32);
let turned = portrait_media && w > h;
let (pw, ph) = if turned { (h, w) } else { (w, h) };
let label = PageLabel::new(None, Some(p.label.chars().take(MAX_TEXT).collect()), None);
let settings = PageSettings::from_wh(w, h).ok_or_else(|| IoError::Format("the sheet has no area".into()))?.with_page_label(label);
let settings = PageSettings::from_wh(pw, ph).ok_or_else(|| IoError::Format("the sheet has no area".into()))?.with_page_label(label);
let mut page = doc.start_page_with(settings);
for (r, url) in &p.links {
for (r, url) in p.links.iter().filter(|_| !turned) {
let Some(uri) = uri(url) else { continue };
// Annotation rectangles are given top-down, like the writer's page surface.
let Some(rect) = Rect::from_ltrb(r.min.x as f32, h - r.max.y as f32, r.max.x as f32, h - r.min.y as f32) else { continue };
@@ -790,13 +851,23 @@ fn write_page(doc: &mut kr::Document, p: &SheetPage, groups: &Groups, fonts: &mu
page.add_annotation(Annotation::new_link(link, None));
}
let mut surface = page.surface();
// The surface's y axis points down; flip it so we draw in PDF points (y up).
surface.push_transform(&Transform::from_row(1.0, 0.0, 0.0, -1.0, 0.0, h));
// The surface's y axis points down; flip it so we draw in PDF points (y up). Turned: the
// sheet's (x, y) lands at (h - y, x) on the page, y up.
let to_page = if turned { Transform::from_row(0.0, -1.0, -1.0, 0.0, h, w) } else { Transform::from_row(1.0, 0.0, 0.0, -1.0, 0.0, h) };
surface.push_transform(&to_page);
// Clip to the plot area.
let mut drawn = Ok(());
if let Some(clip) = rect_path(p.clip_pt.min, p.clip_pt.max) {
surface.push_clip_path(&clip, &FillRule::NonZero);
drawn = marks(&mut surface, p, groups, fonts);
drawn = marks(&mut surface, p, &p.list, &p.clip_pt, groups, fonts);
surface.pop();
}
if drawn.is_ok()
&& !p.stamp.prims.is_empty()
&& let Some(clip) = rect_path(p.printable_pt.min, p.printable_pt.max)
{
surface.push_clip_path(&clip, &FillRule::NonZero);
drawn = marks(&mut surface, p, &p.stamp, &p.printable_pt, groups, fonts);
surface.pop();
}
surface.pop();
@@ -873,8 +944,14 @@ fn krilla_failure(e: KrillaError) -> Failure {
/// Primitives that stand for a glyph in an embeddable font (see [`fonts::Fonts`]) are written
/// as text instead: the glyph at font size 1 under its glyph matrix (the matrix axes are one
/// em).
fn marks(s: &mut Surface<'_>, p: &SheetPage, groups: &Groups, fonts: &mut fonts::Fonts) -> std::result::Result<(), Failure> {
let list = &p.list;
fn marks(
s: &mut Surface<'_>,
p: &SheetPage,
list: &cadcraft_render::DisplayList,
clip_pt: &Bounds2,
groups: &Groups,
fonts: &mut fonts::Fonts,
) -> std::result::Result<(), Failure> {
let texts = fonts::texts(list);
let white = Rgb(255, 255, 255);
let mut batch: Option<(StrokeStyle, PathBuilder)> = None;
@@ -897,7 +974,7 @@ fn marks(s: &mut Surface<'_>, p: &SheetPage, groups: &Groups, fonts: &mut fonts:
let w = if w.is_finite() && w > 0.0 { w.min(100.0) } else { 0.0 };
let m = Mark { rgb, t, w };
match prim.kind {
Kind::Polyline | Kind::Infinite { .. } => polyline(s, &mut batch, p, prim, raw, m),
Kind::Polyline | Kind::Infinite { .. } => polyline(s, &mut batch, p, clip_pt, prim, raw, m),
Kind::Tris | Kind::Mask => {
flush(s, &mut batch);
// A wipeout's mask is paper white.
@@ -906,7 +983,7 @@ fn marks(s: &mut Surface<'_>, p: &SheetPage, groups: &Groups, fonts: &mut fonts:
u32::try_from(i).ok().and_then(|i| texts.get(&i).copied()).and_then(|text| fonts.font(&text.glyph.face).map(|font| (text, font)));
match text_font {
Some((text, font)) => glyph(s, font, text, &p.map, m.rgb, m.t),
None => fill_tris(s, p, raw, m.rgb, m.t),
None => fill_tris(s, p, clip_pt, raw, m.rgb, m.t),
}
}
Kind::Point => point(s, &mut batch, &p.map, raw, m),
@@ -927,14 +1004,22 @@ struct Mark {
}
/// Stroke a polyline or infinite line, clipped to the plot area, into the open batch.
fn polyline(s: &mut Surface<'_>, batch: &mut Option<(StrokeStyle, PathBuilder)>, p: &SheetPage, prim: &DPrim, raw: &[Vec2], m: Mark) {
let Some(pts) = polyline_points(prim, raw, &p.map, &p.clip_pt) else { return };
fn polyline(
s: &mut Surface<'_>,
batch: &mut Option<(StrokeStyle, PathBuilder)>,
p: &SheetPage,
clip_pt: &Bounds2,
prim: &DPrim,
raw: &[Vec2],
m: Mark,
) {
let Some(pts) = polyline_points(prim, raw, &p.map, clip_pt) else { return };
if pts.len() < 2 {
return;
}
// With a vertex out of range, keep the pieces inside the plot area, widened so
// a wide stroke just outside it still shows its edge.
let runs = if pts.iter().all(|q| coord(*q).is_some()) { vec![pts] } else { clip::clip_polyline(&pts, &p.clip_pt.expand(m.w + 1.0)) };
let runs = if pts.iter().all(|q| coord(*q).is_some()) { vec![pts] } else { clip::clip_polyline(&pts, &clip_pt.expand(m.w + 1.0)) };
let style = StrokeStyle { rgb: m.rgb, width: m.w as f32, transparency: m.t };
if m.t > 0 || batch.as_ref().is_some_and(|(b, _)| *b != style) {
flush(s, batch);
@@ -986,10 +1071,10 @@ fn stroke_run(s: &mut Surface<'_>, batch: &mut Option<(StrokeStyle, PathBuilder)
/// Fill a set of triangles, clipped to the plot area, as the loops of their outline (see
/// [`outline`]), which fill the same as the triangles with far less path data.
fn fill_tris(s: &mut Surface<'_>, p: &SheetPage, raw: &[Vec2], rgb: Rgb, t: u8) {
fn fill_tris(s: &mut Surface<'_>, p: &SheetPage, clip_pt: &Bounds2, raw: &[Vec2], rgb: Rgb, t: u8) {
let mapped: Vec<Vec2> = raw.iter().map(|q| p.map.pt(*q)).collect();
// With a vertex out of range, keep the parts inside the plot area.
let tris = if mapped.iter().all(|q| coord(*q).is_some()) { mapped } else { clip::clip_triangles(&mapped, &p.clip_pt) };
let tris = if mapped.iter().all(|q| coord(*q).is_some()) { mapped } else { clip::clip_triangles(&mapped, clip_pt) };
let tris: Vec<[outline::Pt; 3]> = tris.as_chunks::<3>().0.iter().filter_map(|[a, b, c]| Some([coord(*a)?, coord(*b)?, coord(*c)?])).collect();
let rings = outline::loops(&tris).unwrap_or_else(|| tris.iter().map(|t| t.to_vec()).collect());
let mut pb = PathBuilder::new();
@@ -1141,3 +1226,26 @@ mod saved_setup_tests {
assert!(m.from.dist(Vec2::new(428.0, 297.0)) < 1e-9 && m.to.dist(Vec2::new(148.5, 105.0)) < 1e-9, "still placed: {:?} {:?}", m.from, m.to);
}
}
#[cfg(test)]
mod stamp_clip_regressions {
use super::*;
use serde_json::json;
#[test]
fn a_narrow_window_and_its_stamp_have_independent_clips() {
let d = Drawing::new_metric();
let page = sheet(
&d,
&Space::Model,
&PdfOptions::from_json(&json!({
"paper": "A4", "landscape": false, "fit": true, "window": [[0, 0], [1, 100]], "stamp": "Checked"
})),
&[],
)
.unwrap();
let b = Bounds2::from_points(page.stamp.verts.iter().chain(&page.stamp.tris).map(|p| page.map.pt(*p)));
assert!(b.max.x < page.clip_pt.min.x, "the stamp is outside the drawing clip");
assert!(page.printable_pt.contains(b.min) && page.printable_pt.contains(b.max), "the stamp remains inside its printable clip");
}
}
+198 -7
View File
@@ -3,7 +3,8 @@
//!
//! PDF goes to [`crate::pdf`]. PNG draws the sheet on white paper at the device resolution
//! (capped at [`MAX_PNG_PIXELS`]), with the plot style table and lineweights as PDF uses them.
//! SVG shows the sheet of a layout or the model-space extents.
//! SVG shows the sheet of a layout or the model-space extents. PDF and PNG plots draw the plot
//! stamp (`stamp`, [`crate::stamp`]); SVG doesn't.
use std::sync::Arc;
@@ -69,21 +70,44 @@ fn fit_scale(b: &Bounds2, sheet: &Sheet, o: &PdfOptions) -> f64 {
pdf::plot_scale(b, sheet, o.fit != Some(false), o.scale)
}
/// The PNG plot and the dashed runs it drew continuous because of a dash limit.
/// The part of the sheet a PNG plot draws, from the `crop` option: `[x0, y0, x1, y1]` as fractions
/// of the sheet, measured from its top-left corner (so `[0, 0, 1, 1]` is the whole sheet). A preview
/// zoomed in on a detail asks for just that part at the resolution it needs.
fn crop(opts: &Value) -> Result<Option<[f64; 4]>> {
let Some(raw) = opts.get("crop").filter(|v| !v.is_null()) else { return Ok(None) };
let v: Vec<f64> = raw.as_array().map(|a| a.iter().filter_map(Value::as_f64).collect()).unwrap_or_default();
match v[..] {
[x0, y0, x1, y1]
if raw.as_array().is_some_and(|a| a.len() == 4)
&& [x0, y0, x1, y1].iter().all(|f| f.is_finite() && (0.0..=1.0).contains(f))
&& x1 - x0 >= 1e-6
&& y1 - y0 >= 1e-6 =>
{
Ok(Some([x0, y0, x1, y1]))
}
_ => Err(IoError::Format("`crop` must be [x0, y0, x1, y1]: fractions of the sheet from 0 to 1, with x0 < x1 and y0 < y1".into())),
}
}
/// A raster plot: the sheet at the asked resolution (capped in pixels), cropped when asked, with
/// the stamp; and the dashed runs it drew continuous because of a dash limit.
fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
let o = pdf::with_saved_setup(d, space, &PdfOptions::from_json(opts));
let (sheet, page) = sheet(d, space, &o)?;
let crop = crop(opts)?;
// The size of what is drawn, as fractions of the sheet.
let (frac_x, frac_y) = crop.map_or((1.0, 1.0), |c| (c[2] - c[0], c[3] - c[1]));
let dpi = opts.get("resolution").and_then(Value::as_f64).filter(|r| r.is_finite()).unwrap_or(300.0).clamp(50.0, 2400.0);
// Pixels per paper unit, lowered so the image stays within the caps.
let mut k = sheet.unit_mm / 25.4 * dpi;
let (w, h) = (sheet.size.x * k, sheet.size.y * k);
let (w, h) = (sheet.size.x * frac_x * k, sheet.size.y * frac_y * k);
let shrink = (MAX_PNG_PIXELS / (w * h).max(1.0)).sqrt().min(16384.0 / w.max(h).max(1.0)).min(1.0);
if !(shrink.is_finite() && shrink > 0.0) {
return Err(IoError::Format("the sheet is too large to plot as an image".into()));
}
k *= shrink;
let px = |v: f64| (v * k).round().clamp(1.0, 16384.0) as u32;
let (width, height) = (px(sheet.size.x), px(sheet.size.y));
let (width, height) = (px(sheet.size.x * frac_x), px(sheet.size.y * frac_y));
let lineweights = o.lineweights.unwrap_or(if space.is_paper() { page.lineweights } else { true });
let table = cadcraft_doc::plot_style_table(d, &page.plot_style_table).map(Arc::new);
// Paper units per drawing unit: the fitted scale for model space or a fitted layout, else the
@@ -102,9 +126,18 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
let transparency = o.plot_transparency.unwrap_or(page.plot_transparency);
let ropts = cadcraft_render::Options { tolerance, lineweights, plot_style_table: table, transparency, ..cadcraft_render::Options::default() };
let mut list = cadcraft_render::build_plot(d, space, &ropts);
let half = Vec2::new(f64::from(width), f64::from(height)) / (2.0 * k);
// The paper point at the image centre (the sheet's centre, or the middle of the crop; the
// sheet's origin is its lower-left corner and the crop's is its top-left).
let half = match crop {
Some(c) => Vec2::new((c[0] + c[2]) / 2.0 * sheet.size.x, (1.0 - (c[1] + c[3]) / 2.0) * sheet.size.y),
None => Vec2::new(f64::from(width), f64::from(height)) / (2.0 * k),
};
let b = window.unwrap_or(list.bounds);
let s = if fit { fit_scale(&b, &sheet, &o) } else { est };
// A window plots only what is inside it, as PDF does.
if let Some(w) = window {
list.retain_within(&pdf::window_margin(&w, s, sheet.unit_mm));
}
// Plot style ends, joins and fill patterns at the plot scale, as PDF draws them (a layout's
// are already drawn).
cadcraft_render::pen::apply(&mut list, s * sheet.unit_mm);
@@ -121,8 +154,31 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
let ro = raster::RasterOptions { background: Rgb(255, 255, 255), hairline: 1.0, px_per_mm, antialias: true };
let mut pm = raster::render(&list, &view, &ro).ok_or_else(|| IoError::Format("render failed".into()))?;
if placed {
// PDF clips a placed plot to the printable area: blank the rest of the sheet.
raster::blank_outside_printable(&mut pm, &sheet.printable, k);
// PDF clips a placed plot to the printable area, and a window plot to the window too:
// blank the rest. Corners go through the view, so a crop is blanked in the same place.
let to_world = |q: Vec2| (q - to) / s + from;
let printable = Bounds2::new(to_world(sheet.printable.min), to_world(sheet.printable.max));
let keep = match window {
Some(w) => w.intersection(&printable),
None => printable,
};
if keep.is_empty() {
raster::blank_outside_pixels(&mut pm, (0.0, 0.0), (0.0, 0.0));
} else {
let (x0, y1) = view.to_screen(keep.min);
let (x1, y0) = view.to_screen(keep.max);
raster::blank_outside_pixels(&mut pm, (f64::from(x0), f64::from(y0)), (f64::from(x1), f64::from(y1)));
}
}
if let Some(text) = &o.stamp {
let text = crate::stamp::fill(text, space.tab_name(), &page.paper, &crate::stamp::scale_label(s));
let to_world = |p: Vec2| (p - to) / s + from;
let stamp = crate::stamp::display_list(&text, sheet.printable.min, sheet.unit_mm, to_world, 1.0 / s, &ropts);
// Only the stamp is cut to the printable area: marks the sheet already has in its
// margins (a layout not placed keeps them, as in PDF) stay.
let (x0, y1) = view.to_screen(to_world(sheet.printable.min));
let (x1, y0) = view.to_screen(to_world(sheet.printable.max));
raster::render_within(&stamp, &view, &ro, &mut pm, (x0, y0), (x1, y1)).ok_or_else(|| IoError::Format("render failed".into()))?;
}
let png = raster::encode_png(&pm).ok_or_else(|| IoError::Format("render failed".into()))?;
Ok((png, list.undashed))
@@ -151,6 +207,9 @@ fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
let ropts = cadcraft_render::Options { tolerance, lineweights, plot_style_table: table, transparency, ..cadcraft_render::Options::default() };
let mut list = cadcraft_render::build_plot(d, space, &ropts);
let s = fit_scale(&window.unwrap_or(list.bounds), &sheet, &o);
if let Some(w) = window {
list.retain_within(&pdf::window_margin(&w, s, sheet.unit_mm));
}
cadcraft_render::pen::apply(&mut list, s * sheet.unit_mm);
Ok((crate::svg::export_list(&list, window).into_bytes(), list.undashed))
}
@@ -168,12 +227,144 @@ mod tests {
(be(16), be(20))
}
/// A drawing with one line, enough for a plot to have something on the sheet.
fn drawing() -> Drawing {
let mut d = Drawing::new_metric();
d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(100.0, 50.0, 0.0) })).unwrap();
d
}
/// A PNG plot decoded.
fn decode(bytes: &[u8]) -> tiny_skia::Pixmap {
tiny_skia::Pixmap::decode_png(bytes).unwrap()
}
/// A PNG crop is that part of the sheet at the same scale.
#[test]
fn a_png_crop_is_that_part_of_the_sheet_at_the_same_scale() {
let d = drawing();
// 127 dpi is 5 pixels per mm: a 200 x 100 mm sheet is 1000 x 500 pixels, and a crop of its
// middle half starts on whole pixels.
let base = json!({"output": "png", "resolution": 127, "width": 100, "height": 200, "landscape": true, "margins": [0, 0, 0, 0]});
let full = decode(&plot(&d, &Space::Model, &base).unwrap());
assert_eq!((full.width(), full.height()), (1000, 500));
let mut cropped = base.clone();
cropped["crop"] = json!([0.25, 0.25, 0.75, 0.75]);
let part = decode(&plot(&d, &Space::Model, &cropped).unwrap());
assert_eq!((part.width(), part.height()), (500, 250), "half the sheet each way");
let mut drawn = 0;
for y in 0..part.height() {
for x in 0..part.width() {
let (a, b) = (part.pixel(x, y).unwrap(), full.pixel(x + 250, y + 125).unwrap());
let close = |p: u8, q: u8| p.abs_diff(q) <= 2;
assert!(close(a.red(), b.red()) && close(a.green(), b.green()) && close(a.blue(), b.blue()), "pixel {x},{y}");
drawn += usize::from(a.red() < 128);
}
}
assert!(drawn > 100, "the crop shows part of the drawing ({drawn} dark pixels)");
// A layout is cropped the same way.
let layout = Space::Paper(d.layouts[0].name.clone());
let lay = json!({"output": "png", "resolution": 127, "width": 100, "height": 200, "landscape": true, "margins": [0, 0, 0, 0]});
let l_full = decode(&plot(&d, &layout, &lay).unwrap());
let mut l_crop = lay.clone();
l_crop["crop"] = json!([0.0, 0.5, 0.5, 1.0]);
let l_part = decode(&plot(&d, &layout, &l_crop).unwrap());
assert_eq!((l_part.width(), l_part.height()), (l_full.width() / 2, l_full.height() / 2));
}
/// The plot stamp is cut to the printable area on its own: a layout's marks in the sheet
/// margins (kept when the layout is not placed) stay where a stamp is drawn (#2171 review).
#[test]
fn the_stamp_keeps_a_layouts_marks_in_the_margins() {
let mut d = Drawing::new_metric();
let layout = Space::Paper(d.layouts[0].name.clone());
let line = |a: Vec3, b: Vec3| EntityKind::Line(Line { a, b });
d.add(&layout, Common::default(), line(Vec3::new(-500.0, 30.0, 0.0), Vec3::new(500.0, 30.0, 0.0))).unwrap();
d.add(&layout, Common::default(), line(Vec3::new(30.0, -500.0, 0.0), Vec3::new(30.0, 500.0, 0.0))).unwrap();
// 5 pixels per mm on a 200 x 100 mm sheet with 20 mm margins: the printable area is
// pixels 100..900 across and 100..400 down.
let opts =
json!({"output": "png", "resolution": 127, "width": 100, "height": 200, "landscape": true, "margins": [20, 20, 20, 20], "fit": false});
let plain = decode(&plot(&d, &layout, &opts).unwrap());
let mut with_stamp = opts.clone();
with_stamp["stamp"] = json!("STAMP {layout}");
let stamped = decode(&plot(&d, &layout, &with_stamp).unwrap());
assert_eq!((plain.width(), plain.height()), (1000, 500));
let (mut margin_ink, mut changed) = (0, 0);
for y in 0..plain.height() {
for x in 0..plain.width() {
let (a, b) = (plain.pixel(x, y).unwrap(), stamped.pixel(x, y).unwrap());
changed += usize::from(a != b);
if !(98..902).contains(&x) || !(98..402).contains(&y) {
assert_eq!(a, b, "pixel {x},{y} in the margin");
margin_ink += usize::from(a.red() < 128);
}
}
}
assert!(margin_ink > 0, "the layout draws in the margins");
assert!(changed > 0, "the stamp is drawn");
}
/// Bad crops are errors; no crop, or the whole sheet, is fine.
#[test]
fn a_bad_png_crop_is_an_error() {
let d = drawing();
for crop in [
json!([0.5, 0.0, 0.5, 1.0]),
json!([0.0, 0.8, 1.0, 0.2]),
json!([0, 0, 1]),
json!([0, 0, 1, 2]),
json!([-0.1, 0, 1, 1]),
json!("all"),
json!([0, 0, 1, f64::NAN]),
] {
assert!(plot(&d, &Space::Model, &json!({"output": "png", "resolution": 50, "crop": crop})).is_err(), "{crop}");
}
assert!(plot(&d, &Space::Model, &json!({"output": "png", "resolution": 50, "crop": null})).is_ok(), "no crop is the whole sheet");
assert!(plot(&d, &Space::Model, &json!({"output": "png", "resolution": 50, "crop": [0, 0, 1, 1]})).is_ok());
}
/// A drawing with a short line inside the window [0,0]-[10,10], a line outside it to the
/// right (inside the sheet once the square window is fitted on a landscape page), and many
/// circles far away.
fn windowed_drawing() -> Drawing {
let mut d = Drawing::new_metric();
let line = |a: Vec3, b: Vec3| EntityKind::Line(Line { a, b });
d.add(&Space::Model, Common::default(), line(Vec3::new(2.0, 5.0, 0.0), Vec3::new(8.0, 5.0, 0.0))).unwrap();
d.add(&Space::Model, Common::default(), line(Vec3::new(12.0, 1.0, 0.0), Vec3::new(12.0, 9.0, 0.0))).unwrap();
for i in 0..2000 {
let c =
cadcraft_doc::Circle { center: Vec3::new(1000.0 + f64::from(i % 50) * 10.0, 1000.0 + f64::from(i / 50) * 10.0, 0.0), radius: 4.0 };
d.add(&Space::Model, Common::default(), EntityKind::Circle(c)).unwrap();
}
d
}
/// A window plots only what is inside it (#window): the PNG is blank outside the window even
/// where the sheet goes on, and the PDF leaves out what lies outside instead of carrying it.
#[test]
fn a_window_plots_only_what_is_inside_it() {
let d = windowed_drawing();
let opts = json!({"output": "png", "resolution": 50, "width": 210, "height": 297, "landscape": true, "plotArea": "window", "window": [[0, 0], [10, 10]], "fit": true});
let png = decode(&plot(&d, &Space::Model, &opts).unwrap());
let dark = |x0: u32, x1: u32| {
(x0..x1).flat_map(|x| (0..png.height()).map(move |y| (x, y))).filter(|(x, y)| png.pixel(*x, *y).is_some_and(|p| p.red() < 128)).count()
};
let (w, h) = (png.width(), png.height());
// The square window fills the page's height, centred: its right edge is at w/2 + h/2.
let right_edge = w / 2 + h / 2;
assert!(dark(w / 2 - h / 4, w / 2 + h / 4) > 10, "the line inside the window is drawn");
assert_eq!(dark(right_edge + 2, w), 0, "nothing outside the window is drawn");
let mut pdf_opts = opts.clone();
pdf_opts["output"] = json!("pdf");
let windowed = plot(&d, &Space::Model, &pdf_opts).unwrap();
let mut all = pdf_opts.clone();
all["plotArea"] = json!("extents");
all.as_object_mut().unwrap().remove("window");
let whole = plot(&d, &Space::Model, &all).unwrap();
assert!(windowed.len() * 5 < whole.len(), "the window's PDF leaves out the far circles ({} vs {} bytes)", windowed.len(), whole.len());
}
#[test]
fn png_and_svg_devices() {
let d = drawing();
+120
View File
@@ -0,0 +1,120 @@
//! Asking the system about each of its printers at once: a printer whose driver (or print server)
//! is slow or never answers holds up neither the others nor the listing. Each printer is asked on
//! a thread of its own; the listing takes the answers that came within its time and leaves the
//! rest out. A printer whose question from an earlier listing is still unanswered is not asked
//! again until it is answered, so listings never pile up threads blocked in one driver.
use std::sync::{Arc, Mutex, mpsc};
use std::time::{Duration, Instant};
/// The printers being asked about, by name: a question still unanswered (perhaps forever).
pub(crate) type Asking = Mutex<Vec<String>>;
/// Takes a printer's name off [`Asking`] when its question ends, answered or not (a panic too).
struct Asked {
asking: &'static Asking,
name: String,
}
impl Drop for Asked {
fn drop(&mut self) {
let mut a = self.asking.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if let Some(i) = a.iter().position(|n| *n == self.name) {
a.swap_remove(i);
}
}
}
/// `query` asked about every printer of `items` (a name and what the query needs) at once, each
/// on a thread of its own: the answers that came within `time`, in the order of `items`. A
/// printer still being asked about since an earlier call (listed in `asking`) is left out, as
/// is one whose thread can't be started or whose query gives nothing.
pub(crate) fn ask_each<D, T, F>(asking: &'static Asking, items: Vec<(String, D)>, time: Duration, query: F) -> Vec<T>
where
D: Send + 'static,
T: Send + 'static,
F: Fn(D) -> Option<T> + Send + Sync + 'static,
{
let end = Instant::now() + time;
let query = Arc::new(query);
let (tx, rx) = mpsc::channel::<(usize, Option<T>)>();
let mut started = 0usize;
for (i, (name, item)) in items.into_iter().enumerate() {
{
let mut a = asking.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
if a.contains(&name) {
continue;
}
a.push(name.clone());
}
let guard = Asked { asking, name };
let (tx, query) = (tx.clone(), query.clone());
let spawned = std::thread::Builder::new().name("printer-query".into()).spawn(move || {
let _asked = guard;
let _ = tx.send((i, query(item)));
});
// A thread that could not start dropped its guard: the printer is free to be asked again.
if spawned.is_ok() {
started += 1;
}
}
drop(tx);
let mut answers: Vec<(usize, T)> = Vec::new();
for _ in 0..started {
let left = end.saturating_duration_since(Instant::now());
match rx.recv_timeout(left) {
Ok((i, Some(t))) => answers.push((i, t)),
Ok((_, None)) => {}
// Out of time, or every thread still running ended without an answer (a panic).
Err(_) => break,
}
}
answers.sort_by_key(|(i, _)| *i);
answers.into_iter().map(|(_, t)| t).collect()
}
#[cfg(test)]
mod tests {
use super::*;
use std::sync::atomic::{AtomicUsize, Ordering};
static ASKING: Asking = Mutex::new(Vec::new());
static ASKED_SLOW: AtomicUsize = AtomicUsize::new(0);
static RELEASE: Mutex<Option<mpsc::Receiver<()>>> = Mutex::new(None);
/// `Slow` doesn't answer until the test lets it; the others answer at once.
fn query(name: &'static str) -> Option<&'static str> {
if name == "Slow" {
ASKED_SLOW.fetch_add(1, Ordering::SeqCst);
let held = RELEASE.lock().ok().and_then(|mut r| r.take());
if let Some(rx) = held {
let _ = rx.recv();
}
}
Some(name)
}
fn items() -> Vec<(String, &'static str)> {
["Office", "Slow", "Plotter"].iter().map(|n| (n.to_string(), *n)).collect()
}
/// A printer that doesn't answer leaves the others listed, is not asked again while its
/// question is unanswered, and is listed again once it answers (#2171 review).
#[test]
fn a_printer_that_does_not_answer_holds_up_none_of_the_others() {
let (release, rx) = mpsc::channel();
*RELEASE.lock().unwrap() = Some(rx);
let first = ask_each(&ASKING, items(), Duration::from_millis(300), query);
assert_eq!(first, ["Office", "Plotter"]);
let second = ask_each(&ASKING, items(), Duration::from_millis(300), query);
assert_eq!(second, ["Office", "Plotter"]);
assert_eq!(ASKED_SLOW.load(Ordering::SeqCst), 1, "the unanswered printer is not asked again");
release.send(()).unwrap();
let start = Instant::now();
while ASKING.lock().unwrap().contains(&"Slow".to_string()) && start.elapsed() < Duration::from_secs(5) {
std::thread::sleep(Duration::from_millis(10));
}
let third = ask_each(&ASKING, items(), Duration::from_secs(5), query);
assert_eq!(third, ["Office", "Slow", "Plotter"]);
}
}
+199
View File
@@ -0,0 +1,199 @@
//! The plot stamp (PLOT's `stamp` option): one line of text plotted at the lower-left corner of
//! the printable area, as a record of what was plotted where. The text is given; `{layout}`,
//! `{paper}` and `{scale}` in it become each sheet's own, so a plot of several sheets stamps
//! every sheet with its name.
use cadcraft_color::Color;
use cadcraft_doc::{Common, Drawing, Entity, EntityKind, Handle, Text};
use cadcraft_geom::{Vec2, Vec3};
use serde_json::Value;
/// Height of the stamp's characters on paper (mm).
pub const STAMP_HEIGHT_MM: f64 = 2.0;
/// Gap between the printable area's corner and the stamp (mm).
const STAMP_GAP_MM: f64 = 1.0;
/// Most characters of a stamp, as it is drawn.
pub const MAX_STAMP: usize = 300;
/// Most characters of the `stamp` option read: the command fills in names before the plotter
/// does, writing each `{` in them as `{{`, so the text read can be longer than what is drawn.
/// [`fill`] limits the drawn text to [`MAX_STAMP`].
const MAX_STAMP_INPUT: usize = 16 * MAX_STAMP;
/// A text style no drawing is expected to have, so the stamp is always in CADCraft's own
/// stroke font (a missing style plots with the default one).
const STAMP_STYLE: &str = "CADCraft plot stamp";
/// The `stamp` option's text: printable characters, at most [`MAX_STAMP_INPUT`] (the drawn
/// text is limited once [`fill`] has decoded it); `None` without one (or an empty one).
pub fn stamp_text(opts: &Value) -> Option<String> {
let t: String = opts.get("stamp")?.as_str()?.chars().filter(|c| !c.is_control()).take(MAX_STAMP_INPUT).collect();
let t = t.trim();
(!t.is_empty()).then(|| t.to_string())
}
/// A plot scale as people write it: `1:100`, `2:1`, `1:1`.
pub fn scale_label(paper_per_drawing: f64) -> String {
if !(paper_per_drawing.is_finite() && paper_per_drawing > 0.0) {
return "1:1".into();
}
let trim = |v: f64| {
let s = format!("{v:.3}");
s.trim_end_matches('0').trim_end_matches('.').to_string()
};
if paper_per_drawing >= 1.0 { format!("{}:1", trim(paper_per_drawing)) } else { format!("1:{}", trim(1.0 / paper_per_drawing)) }
}
/// The stamp with `{layout}`, `{paper}` and `{scale}` filled in for one sheet, in one pass (a
/// layout named `Detail {paper}` is copied as it is), `{{` as a literal brace.
pub fn fill(text: &str, layout: &str, paper: &str, scale: &str) -> String {
cadcraft_doc::fill_stamp(text, &[("layout", layout), ("paper", paper), ("scale", scale)], true).chars().take(MAX_STAMP).collect()
}
/// What the stamp draws on a sheet whose printable area starts at `corner` (paper units, `unit_mm`
/// millimetres each): `to_world` maps a paper point to the coordinates the sheet is built in, where
/// one paper unit is `world_per_paper` units. The stamp is not a part of the drawing: it is built
/// against an empty drawing, so no layer, style or setting of the plotted one (layer 0 turned off
/// or frozen) hides or changes it.
pub fn display_list(
text: &str,
corner: Vec2,
unit_mm: f64,
to_world: impl Fn(Vec2) -> Vec2,
world_per_paper: f64,
opts: &cadcraft_render::Options,
) -> cadcraft_render::DisplayList {
let unit = if unit_mm.is_finite() && unit_mm > 0.0 { unit_mm } else { 1.0 };
let gap = STAMP_GAP_MM / unit;
let at = to_world(corner + Vec2::new(gap, gap));
let height = STAMP_HEIGHT_MM / unit * world_per_paper;
if !(at.x.is_finite() && at.y.is_finite() && height.is_finite() && height > 0.0) {
return cadcraft_render::DisplayList::default();
}
let t = Text {
insert: Vec3::new(at.x, at.y, 0.0),
align_pt: None,
height,
value: text.to_string(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: STAMP_STYLE.into(),
halign: Default::default(),
valign: Default::default(),
backwards: false,
upside_down: false,
};
let e = Entity { handle: Handle(0), common: Common { color: Color::Index(7), ..Common::default() }, kind: EntityKind::Text(t) };
cadcraft_render::build_entities(&Drawing::default(), [&e], opts)
}
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
/// The stamp's text is trimmed, capped and filled in, and scales read as AutoCAD writes them.
#[test]
fn stamp_text_scale_and_placeholders() {
assert_eq!(stamp_text(&json!({ "stamp": " Plan\u{7}.dwg " })).as_deref(), Some("Plan.dwg"));
assert_eq!(stamp_text(&json!({ "stamp": " " })), None);
assert_eq!(stamp_text(&json!({ "stamp": true })), None);
// Capped as drawn: the limit applies once the plotter has filled the text in.
assert_eq!(stamp_text(&json!({ "stamp": "x".repeat(1000) })).map(|s| fill(&s, "", "", "").len()), Some(MAX_STAMP));
assert_eq!(scale_label(0.01), "1:100");
assert_eq!(scale_label(2.0), "2:1");
assert_eq!(scale_label(1.0), "1:1");
assert_eq!(scale_label(1.0 / 66.6667), "1:66.667");
assert_eq!(scale_label(f64::NAN), "1:1");
assert_eq!(fill("{layout} · {paper} · {scale}", "Sheet 1", "A3", "1:50"), "Sheet 1 · A3 · 1:50");
// A sheet name that looks like a field is copied, not filled (#2171 review).
assert_eq!(fill("{layout} · {paper}", "Detail {paper}", "A4", "1:1"), "Detail {paper} · A4");
}
/// The stamp is drawn just inside the printable area's lower-left corner, about 2 mm high.
#[test]
fn the_stamp_draws_text_at_the_corner() {
let opts = cadcraft_render::Options { text: true, fill: true, ..cadcraft_render::Options::default() };
let list = display_list("Plan.dwg", Vec2::new(10.0, 20.0), 1.0, |p| p, 1.0, &opts);
assert!(!list.prims.is_empty(), "the stamp's characters are drawn");
// Just inside the printable area's lower-left corner, about 2 mm high.
assert!(list.bounds.min.x >= 10.0 && list.bounds.min.y >= 20.0, "{:?}", list.bounds);
assert!(list.bounds.max.y < 20.0 + STAMP_GAP_MM + STAMP_HEIGHT_MM * 1.5, "{:?}", list.bounds);
// A mapping that goes nowhere draws nothing rather than failing.
assert!(display_list("x", Vec2::ZERO, 1.0, |_| Vec2::new(f64::NAN, 0.0), 1.0, &opts).prims.is_empty());
}
/// PDF and PNG plots draw the stamp; without one they are as before.
#[test]
fn pdf_and_png_plots_carry_the_stamp() {
let mut d = Drawing::default();
let line = cadcraft_doc::Line { a: Vec3::new(0.0, 0.0, 0.0), b: Vec3::new(100.0, 50.0, 0.0) };
d.add(&cadcraft_doc::Space::Model, Common::default(), EntityKind::Line(line)).unwrap();
let plot = |extra: Value| {
let mut o = json!({ "paper": "A4", "compress": false });
if let (Some(o), Some(e)) = (o.as_object_mut(), extra.as_object()) {
o.extend(e.clone());
}
crate::plotter::plot(&d, &cadcraft_doc::Space::Model, &o).unwrap()
};
let pdf_plain = plot(json!({}));
let pdf_stamped = plot(json!({ "stamp": "Plan.dwg {layout} {paper} {scale}" }));
assert!(pdf_stamped.len() > pdf_plain.len() + 200, "{} vs {}", pdf_stamped.len(), pdf_plain.len());
let png_plain = plot(json!({ "output": "png", "resolution": 100 }));
let png_stamped = plot(json!({ "output": "png", "resolution": 100, "stamp": "Plan.dwg {layout}" }));
assert_ne!(png_plain, png_stamped);
// An empty stamp is no stamp.
assert_eq!(plot(json!({ "output": "png", "resolution": 100, "stamp": " " })), png_plain);
}
}
#[cfg(test)]
mod window_stamp_regressions {
use super::*;
use cadcraft_doc::Space;
use serde_json::json;
#[test]
fn a_centered_narrow_window_does_not_erase_the_png_stamp() {
let d = Drawing::new_metric();
let mut opts = json!({ "output": "png", "resolution": 100, "paper": "A4", "landscape": false, "fit": true, "window": [[0, 0], [1, 100]] });
let plain = crate::plotter::plot(&d, &Space::Model, &opts).unwrap();
opts["stamp"] = json!("Checked");
let stamped = crate::plotter::plot(&d, &Space::Model, &opts).unwrap();
assert_ne!(plain, stamped, "the stamp remains visible outside the narrow drawing window");
}
}
#[cfg(test)]
mod stamp_review_regressions {
use super::*;
use cadcraft_doc::Space;
use serde_json::json;
/// The drawn-text limit applies after `{{` is decoded: a name of 200 braces filled in by the
/// command (as 400 characters) is drawn whole (#2171 review).
#[test]
fn the_limit_counts_the_decoded_text() {
let encoded = "{{".repeat(200);
let text = stamp_text(&json!({ "stamp": encoded })).unwrap_or_default();
assert_eq!(fill(&text, "Model", "A4", "1:1"), "{".repeat(200));
// Still bounded: a hostile text is cut before it is drawn.
let long = fill(&stamp_text(&json!({ "stamp": "x".repeat(100_000) })).unwrap_or_default(), "", "", "");
assert_eq!(long.chars().count(), MAX_STAMP);
}
/// Layer 0 off or frozen in the drawing hides none of the stamp (#2171 review).
#[test]
fn layer_0_off_or_frozen_keeps_the_stamp() {
let opts = json!({ "output": "png", "resolution": 100, "paper": "A4", "landscape": false });
for hide in [|l: &mut cadcraft_doc::Layer| l.on = false, |l: &mut cadcraft_doc::Layer| l.frozen = true] {
let mut d = Drawing::new_metric();
if let Some(l) = d.layer_mut("0") {
hide(l);
}
let plain = crate::plotter::plot(&d, &Space::Model, &opts).unwrap();
let mut with = opts.clone();
with["stamp"] = json!("Checked");
assert_ne!(crate::plotter::plot(&d, &Space::Model, &with).unwrap(), plain, "the stamp is drawn");
}
}
}
+44 -314
View File
@@ -5488,323 +5488,53 @@ fn a_layer_state_saved_before_masks_restores_everything() {
assert_eq!(got, [("S", LayerState::ALL, "", "")]);
}
/// The value of group `code` in `tags`.
fn tag_text(tags: &[craft_dxf::Tag], code: i32) -> Option<String> {
tags.iter().find(|t| t.code == code).map(craft_dxf::Tag::str)
}
/// An INSERT with two attributes, for the records written after it (#1660).
fn insert_with_attribs() -> (Drawing, Handle) {
let text = |value: &str| Text {
insert: Vec3::new(1.0, 2.0, 0.0),
align_pt: None,
height: 2.5,
value: value.into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
};
let attrib = |tag: &str, value: &str| Attrib {
tag: tag.into(),
text: text(value),
invisible: false,
constant: false,
prompt: String::new(),
props: AttribProps::default(),
multiline: None,
modes: AttribModes::default(),
};
let mut d = Drawing::new_metric();
let insert =
Insert { block: "B".into(), insert: Vec3::new(10.0, 10.0, 0.0), attribs: vec![attrib("T1", "A1"), attrib("T2", "A2")], ..Insert::default() };
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
(d, h)
}
#[test]
fn an_inserts_records_are_read_one_at_a_time() {
let (mut d, h) = insert_with_attribs();
let e = d.entity(h).expect("the reference");
// The reference's own list is its record, with no attribute in it.
let (kind, own) = entity_groups(&d, e);
assert_eq!(kind, "INSERT");
assert_eq!(tag_text(&own, 66).as_deref(), Some("1"));
// The records after it: each attribute, then the SEQEND.
let first = entity_sub_record(&d, e, 0).expect("the first attribute");
assert_eq!(first.0, "ATTRIB");
assert_eq!((tag_text(&first.1, 2).as_deref(), tag_text(&first.1, 1).as_deref()), (Some("T1"), Some("A1")));
assert_eq!(tag_text(&first.1, 10).as_deref(), Some("1.0"), "its place is written as for the file");
let second = entity_sub_record(&d, e, 1).expect("the second attribute");
assert_eq!((tag_text(&second.1, 2).as_deref(), tag_text(&second.1, 1).as_deref()), (Some("T2"), Some("A2")));
let seqend = entity_sub_record(&d, e, 2).expect("the SEQEND");
assert_eq!(seqend.0, "SEQEND");
assert!(entity_sub_record(&d, e, 3).is_none(), "past the last record");
// They have no handle or owner of their own in the drawing: their names are LISP's.
for tags in [&first.1, &second.1, &seqend.1] {
assert!(tags.iter().all(|t| t.code != 5 && t.code != 330), "{tags:?}");
fn window_pages_keep_the_plot_stamp_on_every_sheet() {
let d = sample();
let mut options = serde_json::json!({ "pages": [
{ "window": [[0, 0], [10, 10]], "paper": "A4" },
{ "window": [[10, 0], [20, 10]], "paper": "A3" }
], "text": "geometry", "compress": false });
let plain = pdf_read::read(&crate::pdf::plot(&d, &Space::Model, &options).unwrap());
options["stamp"] = serde_json::json!("CADCRAFT STAMP");
let stamped = pdf_read::read(&crate::pdf::plot(&d, &Space::Model, &options).unwrap());
assert_eq!(stamped.pages.len(), 2);
for (before, after) in plain.pages.iter().zip(&stamped.pages) {
assert!(after.content_bytes.len() > before.content_bytes.len(), "each sheet must draw the stamp");
}
// An entity with no records after it has none, at any index.
let line = d.add(&Space::Model, Common::default(), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).expect("line");
let e = d.entity(line).expect("the line");
assert!(entity_sub_record(&d, e, 0).is_none());
}
#[test]
fn an_attributes_value_reads_as_lisp_text() {
let (mut d, h) = insert_with_attribs();
// A caret is written `^ ` and read back as the caret LISP typed: what `entget` lists is
// what `entmod` takes again.
d.modify_entity(h, |e| {
if let EntityKind::Insert(i) = &mut e.kind
&& let Some(a) = i.attribs.first_mut()
{
a.text.value = "10^2".into();
}
})
.expect("modify");
let e = d.entity(h).expect("the reference");
let (_, tags) = entity_sub_record(&d, e, 0).expect("the first attribute");
assert_eq!(tag_text(&tags, 1).as_deref(), Some("10^2"));
}
/// Reading every attribute of one reference examines the block definition once, and an edit of
/// the definition once more.
#[test]
fn reading_attributes_scans_the_definition_once() {
const M: usize = 32;
let tags: Vec<String> = (0..M).map(|i| format!("T{i}")).collect();
let mut d = Drawing::new_metric();
let h = add_attributed(&mut d, "B", 1, &tags, "WALLS");
crate::dxf_write::reset_attdef_definition_visits();
let e = d.entity(h).expect("the reference").clone();
for i in 0..M {
let (kind, tags) = entity_sub_record(&d, &e, i).expect("attribute");
assert_eq!(kind, "ATTRIB");
assert_eq!(tag_text(&tags, 8).as_deref(), Some("WALLS"));
}
assert_eq!(crate::dxf_write::attdef_definition_visits(), M as u64, "one pass over the definition, not one scan per attribute");
// An edit of the definition is read on the next read, with one more pass.
set_attdef_layer(&mut d, "B", "DOOR");
let before = crate::dxf_write::attdef_definition_visits();
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("DOOR"));
assert_eq!(crate::dxf_write::attdef_definition_visits() - before, M as u64, "the edit builds the index once");
}
/// An attribute with value V and `tag`, for the definition tests below.
fn plain_attrib(tag: &str) -> Attrib {
Attrib {
tag: tag.into(),
text: Text {
insert: Vec3::ZERO,
align_pt: None,
height: 1.0,
value: "V".into(),
rotation: 0.0,
width_factor: 1.0,
oblique: 0.0,
style: "Standard".into(),
halign: HAlign::Left,
valign: VAlign::Baseline,
backwards: false,
upside_down: false,
},
invisible: false,
constant: false,
prompt: String::new(),
props: AttribProps::default(),
multiline: None,
modes: AttribModes::default(),
}
}
/// Block `name` with an ATTDEF per tag on `layer`, its handles from `first` up, and a reference
/// to it with the same attributes. The reference's handle.
fn add_attributed(d: &mut Drawing, name: &str, first: u64, tags: &[String], layer: &str) -> Handle {
let mut block = Block::new(name);
for (i, tag) in tags.iter().enumerate() {
let mut e = Entity::new(Handle(first + i as u64), EntityKind::AttDef(plain_attrib(tag)));
e.common.layer = layer.into();
block.entities.push(e);
}
d.blocks.insert(name.into(), std::sync::Arc::new(block));
let insert = Insert { block: name.into(), attribs: tags.iter().map(|t| plain_attrib(t)).collect(), ..Insert::default() };
d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add")
}
/// Block `name`'s first ATTDEF moved to `layer`: one edit of the definition's store.
fn set_attdef_layer(d: &mut Drawing, name: &str, layer: &str) {
let b = std::sync::Arc::make_mut(d.blocks.get_mut(name).expect("block"));
let h = b.entities.iter().find(|e| matches!(e.kind, EntityKind::AttDef(_))).map(|e| e.handle).expect("an ATTDEF");
assert!(b.entities.modify(h, |e| e.common.layer = layer.into()));
}
/// Block B with ATTDEF T on layer BASE and ATTDEF U on layer DOOR, and a reference to it with
/// both attributes. The reference's handle.
fn add_on_two_layers(d: &mut Drawing) -> Handle {
let h = add_attributed(d, "B", 1, &["T".to_string(), "U".to_string()], "DOOR");
set_attdef_layer(d, "B", "BASE");
h
}
/// Block `name`'s ATTDEFs given `tags` in their order, so a tag can pass to another ATTDEF's
/// handle: one edit of the definition's store for each ATTDEF.
fn set_attdef_tags(d: &mut Drawing, name: &str, tags: &[&str]) {
let b = std::sync::Arc::make_mut(d.blocks.get_mut(name).expect("block"));
let handles: Vec<Handle> = b.entities.iter().filter(|e| matches!(e.kind, EntityKind::AttDef(_))).map(|e| e.handle).collect();
assert_eq!(handles.len(), tags.len(), "a tag for each ATTDEF");
for (h, tag) in handles.into_iter().zip(tags) {
assert!(b.entities.modify(h, |e| {
if let EntityKind::AttDef(ad) = &mut e.kind {
ad.tag = (*tag).into();
// The stamp's ink is outside the window: each page restores the window's clip, then paints
// the stamp under the wider printable-area clip (#2171 review).
for page in &stamped.pages {
let ops = pdf_read::ops(&page.content);
let (mut depth, mut path, mut clips) = (0i32, Vec::<Vec2>::new(), Vec::new());
for (i, o) in ops.iter().enumerate() {
match o.op.as_str() {
"q" => depth += 1,
"Q" => depth -= 1,
"m" | "l" | "c" | "v" | "y" => path.extend(o.nums.as_chunks::<2>().0.iter().map(|[x, y]| Vec2::new(*x, *y))),
"re" if o.nums.len() == 4 => {
let (x, y, w, h) = (o.nums[0], o.nums[1], o.nums[2], o.nums[3]);
path.extend([Vec2::new(x, y), Vec2::new(x + w, y + h)]);
}
"W" | "W*" => clips.push((i, depth, cadcraft_geom::Bounds2::from_points(path.iter().copied()))),
"n" | "S" | "s" | "f" | "F" | "f*" | "B" | "B*" | "b" | "b*" => path.clear(),
_ => {}
}
}));
}
}
/// The layer reference `h`'s first ATTRIB record is read on.
fn read_attrib_layer(d: &Drawing, h: Handle) -> Option<String> {
let e = d.entity(h)?;
let (_, tags) = entity_sub_record(d, e, 0)?;
tag_text(&tags, 8)
}
/// The layer the first ATTRIB of `d`'s DXF is written on.
fn written_attrib_layer(d: &Drawing) -> Option<String> {
let text = write_dxf(d);
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let at = lines.windows(2).position(|w| w == ["0", "ATTRIB"])?;
let pairs = lines.get(at + 2..)?.chunks(2);
pairs.take_while(|p| p.first() != Some(&"0")).find(|p| p.first() == Some(&"8")).and_then(|p| p.get(1)).map(|s| s.to_string())
}
/// Two copies of one drawing, each with its definition edited: each reads and writes its own
/// definition's properties, whichever was read first. T stays with the first ATTDEF in one copy
/// and passes to the second in the other, so an index kept from one copy names the wrong ATTDEF
/// in the other.
#[test]
fn copies_edited_apart_read_their_own_definitions() {
let mut d = Drawing::new_metric();
let h = add_on_two_layers(&mut d);
let (mut a, mut b) = (d.clone(), d.clone());
set_attdef_layer(&mut a, "B", "WALLS");
set_attdef_tags(&mut b, "B", &["U", "T"]);
assert_eq!(read_attrib_layer(&a, h).as_deref(), Some("WALLS"));
assert_eq!(read_attrib_layer(&b, h).as_deref(), Some("DOOR"), "the other copy's edit is its own");
assert_eq!(written_attrib_layer(&b).as_deref(), Some("DOOR"));
assert_eq!(written_attrib_layer(&a).as_deref(), Some("WALLS"));
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("BASE"), "the drawing both came from is unchanged");
}
/// Undo back to a state, then a different edit of the definition: the edit that was undone is
/// not read or written again. The second edit passes T to the other ATTDEF, so the index of
/// the undone edit names the wrong one.
#[test]
fn an_edit_after_undo_reads_its_own_definition() {
let mut d = Drawing::new_metric();
let h = add_on_two_layers(&mut d);
let mut undone = d.clone();
set_attdef_layer(&mut undone, "B", "WALLS");
assert_eq!(read_attrib_layer(&undone, h).as_deref(), Some("WALLS"));
// Undo: the drawing before the edit, then another edit, read nothing in between.
let mut redone = d.clone();
set_attdef_tags(&mut redone, "B", &["U", "T"]);
assert_eq!(written_attrib_layer(&redone).as_deref(), Some("DOOR"));
assert_eq!(read_attrib_layer(&redone, h).as_deref(), Some("DOOR"));
}
/// Reads that alternate between two references of two blocks examine each definition once.
#[test]
fn alternating_definitions_are_each_indexed_once() {
const M: usize = 64;
let tags: Vec<String> = (0..M).map(|i| format!("T{i}")).collect();
let mut d = Drawing::new_metric();
let first = add_attributed(&mut d, "B1", 1, &tags, "ONE");
let second = add_attributed(&mut d, "B2", 1 + M as u64, &tags, "TWO");
let (first, second) = (d.entity(first).expect("first").clone(), d.entity(second).expect("second").clone());
crate::dxf_write::reset_attdef_definition_visits();
for i in 0..M {
for (e, layer) in [(&first, "ONE"), (&second, "TWO")] {
let (_, tags) = entity_sub_record(&d, e, i).expect("attribute");
assert_eq!(tag_text(&tags, 8).as_deref(), Some(layer));
}
let [(window_at, window_depth, window), (stamp_at, stamp_depth, printable)] = clips[..] else {
panic!("a clip for the drawing and one for the stamp: {clips:?}");
};
let area = |b: &cadcraft_geom::Bounds2| b.width() * b.height();
assert!(printable.expand(0.01).contains_box(&window) && area(&printable) > area(&window) + 1.0, "{printable:?} vs {window:?}");
assert!(stamp_depth <= window_depth && ops[window_at..stamp_at].iter().any(|o| o.op == "Q"), "the window's clip is restored first");
let ink: Vec<Vec2> = ops[stamp_at + 1..]
.iter()
.filter(|o| matches!(o.op.as_str(), "m" | "l" | "c"))
.flat_map(|o| o.nums.as_chunks::<2>().0.iter().map(|[x, y]| Vec2::new(*x, *y)).collect::<Vec<_>>())
.collect();
assert!(
ink.iter().any(|q| !window.contains(*q) && printable.contains(*q)),
"the stamp is painted outside the window, inside the printable area"
);
}
assert_eq!(crate::dxf_write::attdef_definition_visits(), 2 * M as u64, "each definition is read once, not once per read");
}
/// Of two ATTDEFs whose tags differ only in case, the first is the attribute's definition.
#[test]
fn the_first_definition_of_a_tag_in_any_case_is_used() {
let mut block = Block::new("C");
for (i, (tag, layer)) in [("t", "FIRST"), ("T", "SECOND")].into_iter().enumerate() {
let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(tag)));
e.common.layer = layer.into();
block.entities.push(e);
}
let mut d = Drawing::new_metric();
d.blocks.insert("C".into(), std::sync::Arc::new(block));
let insert = Insert { block: "C".into(), attribs: vec![plain_attrib("T")], ..Insert::default() };
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST"));
}
/// A definition with more distinct tags than the index may store (`1 << 18`) is not cached.
/// The first read builds and drops one bounded index and remembers the state; later reads go
/// straight to one scan that stops at the first match. The first ATTDEF of the tag still wins,
/// in any case.
#[test]
fn an_oversized_definition_is_not_indexed() {
const LIMIT: usize = 1 << 18;
// One extra distinct tag past the budget, plus a second ATTDEF of the first tag in
// another case, so the first match is not the only entity of that tag.
let mut tags = Vec::with_capacity(LIMIT + 2);
tags.push("Ab".to_string());
tags.push("AB".to_string());
for i in 0..LIMIT {
tags.push(format!("U{i}"));
}
let mut block = Block::new("HUGE");
for (i, tag) in tags.iter().enumerate() {
let layer = if i == 0 { "FIRST" } else { "SECOND" };
let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(tag)));
e.common.layer = layer.into();
block.entities.push(e);
}
let mut d = Drawing::new_metric();
d.blocks.insert("HUGE".into(), std::sync::Arc::new(block));
let insert = Insert { block: "HUGE".into(), attribs: vec![plain_attrib("ab")], ..Insert::default() };
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
crate::dxf_write::reset_attdef_definition_visits();
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST"));
let first = crate::dxf_write::attdef_definition_visits();
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("FIRST"));
let second = crate::dxf_write::attdef_definition_visits() - first;
// The failed index walks every entity (the last tag is the one past the budget), then
// the scan reads the first entity, where the tag matches.
assert_eq!(first, (LIMIT as u64) + 3, "one bounded pass, then the first match");
assert_eq!(second, 1, "the state is remembered as too large: the next read scans to the first match only");
}
/// An attribute whose ATTDEF lies past the index budget, at the end of an oversized definition,
/// still reads and writes that definition's properties: the scan for a definition past the
/// budget covers all of it.
#[test]
fn a_definition_past_the_index_budget_matches_its_last_tag() {
const LIMIT: usize = 1 << 18;
let mut block = Block::new("HUGE");
for i in 0..=LIMIT {
let mut e = Entity::new(Handle(i as u64 + 1), EntityKind::AttDef(plain_attrib(&format!("U{i}"))));
e.common.layer = if i == LIMIT { "LAST".into() } else { "OTHER".into() };
block.entities.push(e);
}
let mut d = Drawing::new_metric();
d.blocks.insert("HUGE".into(), std::sync::Arc::new(block));
let insert = Insert { block: "HUGE".into(), attribs: vec![plain_attrib(&format!("u{LIMIT}"))], ..Insert::default() };
let h = d.add(&Space::Model, Common::default(), EntityKind::Insert(insert)).expect("add");
assert_eq!(read_attrib_layer(&d, h).as_deref(), Some("LAST"), "entget reads the matching definition");
assert_eq!(written_attrib_layer(&d).as_deref(), Some("LAST"), "the written ATTRIB keeps the definition's layer");
}
+294
View File
@@ -0,0 +1,294 @@
//! System printers on Windows: the spooler's printers, each with the papers its driver offers
//! and their printable areas (from the driver's PrintCapabilities), and printing a plot's PDF
//! through craft-print (Windows.Data.Pdf drawn as vectors into the XPS print API, no program
//! started). craft-print also owns the Windows driver capability queries.
//!
//! The PDF is the one the PDF plotter writes for the chosen paper, so it is printed at its exact
//! size: craft-print picks the driver's paper of that size and refuses a driver that would scale
//! it. The conversions take plain values, so they are tested without a printer.
use cadcraft_doc::{DevicePaper, Orientation, PlotOutput, PlotterConfig};
/// Most printers listed.
#[cfg_attr(not(windows), allow(dead_code))]
const MAX_PRINTERS: usize = 64;
/// Most papers of one printer.
const MAX_PAPERS: usize = 256;
/// Most copies of one job.
pub const MAX_COPIES: u32 = 999;
pub use craft_print::WindowsPaper as WinPaper;
#[cfg(test)]
use craft_print::margins_from_imageable_mm as margins_from_imageable;
/// The paper that stands for its size among the papers that can be listed (`listable`): the
/// one with the widest margins (the plain sheet rather than its borderless variant), the first
/// on a tie.
fn represents_its_size(listable: &[&WinPaper], p: &WinPaper) -> bool {
let total = |m: Option<[f64; 4]>| m.map_or(0.0, |m| m.iter().sum::<f64>());
let chosen = listable.iter().copied().filter(|o| o.same_size(p)).fold(None::<&WinPaper>, |best, o| match best {
Some(b) if total(b.margins) >= total(o.margins) => Some(b),
_ => Some(o),
});
chosen.is_some_and(|c| std::ptr::eq(c, p))
}
/// The papers that can be listed, in the driver's order: named, with a length, and the first
/// of each name as the device tells names apart ([`cadcraft_doc::paper_name_key`]: `Label X` and
/// `Label-X` are one name). A representative is chosen among these only, so a paper the device
/// would drop for its repeated name never stands for (and hides) a paper of another name.
fn listable(papers: &[WinPaper]) -> Vec<&WinPaper> {
let mut out: Vec<(String, &WinPaper)> = Vec::new();
for p in papers {
let key = cadcraft_doc::paper_name_key(&p.name);
if p.width != 0 && p.height != 0 && !key.is_empty() && !out.iter().any(|(k, _)| *k == key) {
out.push((key, p));
}
}
out.into_iter().map(|(_, p)| p).collect()
}
/// The device a printer becomes: a system printer (PDF in, printed by craft-print) with its
/// driver's papers. Roll papers (no length), unnamed papers and repeated names are dropped; the
/// default paper is the driver's default (`default_key`) when it is one of them, else the first.
/// Papers of one size are listed once (see [`represents_its_size`]) with margins every one of
/// them can print, so the preview never shows a borderless area the driver may not use.
pub fn printer_config(name: &str, default_printer: bool, papers: &[WinPaper], default_key: Option<&str>) -> PlotterConfig {
let mut device_papers: Vec<DevicePaper> = Vec::new();
let mut default_paper = String::new();
let candidates = listable(papers);
for &p in &candidates {
if device_papers.len() >= MAX_PAPERS {
break;
}
// Sizes chain within the tolerance (210.0, 210.2, 210.4 mm): leave a paper out only when
// a paper that is listed stands for it.
if !represents_its_size(&candidates, p) && candidates.iter().any(|q| p.same_size(q) && represents_its_size(&candidates, q)) {
continue;
}
if default_paper.is_empty() && default_key.is_some_and(|k| papers.iter().any(|o| o.key == k && o.same_size(p))) {
default_paper = p.name.clone();
}
let margins = p.conservative_margins(papers);
device_papers.push(DevicePaper {
native_key: None,
name: p.name.clone(),
width: f64::from(p.width) / 1000.0,
height: f64::from(p.height) / 1000.0,
margins,
});
}
if default_paper.is_empty() {
default_paper = device_papers.first().map(|p| p.name.clone()).unwrap_or_default();
}
let description = if default_printer { "Windows printer (default)" } else { "Windows printer" };
let mut config = PlotterConfig {
name: name.to_string(),
description: description.to_string(),
output: PlotOutput::Pdf,
resolution: 300,
orientation: Orientation::Landscape,
default_paper,
papers: device_papers,
system: true,
system_default: default_printer,
}
.sanitized();
// The spooler's identifier must survive display-data sanitization exactly.
config.name = if name.chars().count() <= 32_767 && !name.chars().any(char::is_control) { name.to_string() } else { String::new() };
config
}
#[cfg(windows)]
mod system {
use super::{MAX_COPIES, MAX_PRINTERS, PlotterConfig, printer_config};
fn printer(queue: craft_print::Printer) -> Option<PlotterConfig> {
let catalog = craft_print::windows_paper_catalog(&queue.name)?;
let config = printer_config(&queue.name, queue.default, &catalog.papers, catalog.default_key.as_deref());
(!config.name.is_empty() && !config.papers.is_empty()).then_some(config)
}
/// Printers whose drivers are being asked for their papers.
static ASKING: crate::printer_queries::Asking = std::sync::Mutex::new(Vec::new());
/// How long the drivers' answers are waited for: a printer whose driver answers later (or
/// never) is left out of this listing, and the engine's own wait for it is not run out.
const PRINTERS_TIME: std::time::Duration = std::time::Duration::from_secs(8);
/// The spooler's printers as devices, with a bounded wait for driver answers. A question
/// that is still outstanding from an earlier listing is left running without a retry.
/// The shared provider serializes the underlying Windows capability calls.
pub fn printers() -> Vec<PlotterConfig> {
let items: Vec<_> = craft_print::printer_queues().into_iter().take(MAX_PRINTERS).map(|queue| (queue.name.clone(), queue)).collect();
crate::printer_queries::ask_each(&ASKING, items, PRINTERS_TIME, printer)
}
/// Print `pdf` on `printer`. The paper is the PDF's own sheet size: craft-print chooses the
/// driver's paper of that size, so `paper` only names it. Returns the spooler's reply.
pub fn print(printer: &str, paper: &str, copies: u32, title: &str, pdf: &[u8]) -> Result<String, String> {
// craft-print picks the driver's paper of the PDF's size; the list offers one paper per
// size, with margins every option of that size can print (see `printer_config`).
let _ = paper;
let title: String = title.chars().filter(|c| !c.is_control()).take(100).collect();
let job = craft_print::Job {
printer: Some(printer.to_string()),
copies: copies.clamp(1, MAX_COPIES),
collate: true,
// The printer's own duplex default.
duplex: None,
// The plot is already at its scale: no fitting to the page.
scaling: craft_print::Scaling::Exact,
grayscale: false,
title: if title.trim().is_empty() { "CADCraft".into() } else { title },
..craft_print::Job::default()
};
craft_print::submit(pdf, &job).map_err(|e| e.to_string())
}
}
#[cfg(windows)]
pub use system::{print, printers};
#[cfg(test)]
mod tests {
use super::*;
/// This machine's printers and papers, and how long listing them takes
/// (`cargo test -p cadcraft-io --lib winprint -- --ignored --nocapture`).
#[cfg(windows)]
#[test]
#[ignore = "asks this machine's printer drivers"]
fn list_this_machines_printers() {
let start = std::time::Instant::now();
let names: Vec<_> = craft_print::printer_queues().into_iter().map(|queue| queue.name).collect();
println!("spooler: {names:?} ({:?})", start.elapsed());
for c in printers() {
println!("{} [{}] default paper {:?}, {} papers", c.name, c.description, c.default_paper, c.papers.len());
for p in c.papers.iter().take(8) {
println!(" {} {:.1} x {:.1} mm, margins {:?}", p.name, p.width, p.height, p.margins);
}
}
println!("listed in {:?}", start.elapsed());
}
/// The printable area's origin and size become left, bottom, right and top margins in millimetres.
#[test]
fn margins_from_the_printable_area() {
// A4 with 3.4 mm unprintable left and right, 3 mm at the top and 5 mm at the bottom.
let m = margins_from_imageable((210_000, 297_000), (3_400, 3_000), (203_200, 289_000)).unwrap();
let want = [3.4, 5.0, 3.4, 3.0];
for (a, b) in m.iter().zip(want) {
assert!((a - b).abs() < 1e-9, "{m:?}");
}
// Borderless.
assert_eq!(margins_from_imageable((210_000, 297_000), (0, 0), (210_000, 297_000)), Some([0.0; 4]));
// An area past the page's edge, or none.
assert_eq!(margins_from_imageable((210_000, 297_000), (5_000, 0), (210_000, 297_000)), None);
assert_eq!(margins_from_imageable((210_000, 297_000), (0, 0), (0, 0)), None);
}
/// Driver papers become device papers in mm with their margins, duplicate names and rolls left
/// out; the default printer is marked, and an unknown default paper falls back to the first.
#[test]
fn driver_papers_become_a_device() {
let p = |key: &str, name: &str, width, height, margins| WinPaper { key: key.into(), name: name.into(), width, height, margins };
let papers = [
p("NorthAmericaLetter", "Letter", 215_900, 279_400, Some([3.4, 5.0, 3.4, 3.0])),
p("ISOA4", "A4", 210_000, 297_000, Some([0.0; 4])),
p("Custom1", "a4", 210_000, 297_000, Some([0.0; 4])),
p("Roll", "Roll 24 in", 609_600, 0, None),
p("ISOA3", "A3", 297_000, 420_000, None),
];
let c = printer_config("HP LaserJet", true, &papers, Some("ISOA4"));
assert!(c.system);
assert_eq!(c.output, PlotOutput::Pdf);
assert_eq!(c.description, "Windows printer (default)");
assert!(c.system_default);
let names: Vec<&str> = c.papers.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, ["Letter", "A4", "A3"]);
assert_eq!(c.default_paper, "A4");
let a4 = c.paper("A4").unwrap();
assert!((a4.width - 210.0).abs() < 1e-9 && (a4.height - 297.0).abs() < 1e-9);
assert_eq!(a4.margins, [0.0; 4]);
assert_eq!(c.paper("Letter").unwrap().margins, [3.4, 5.0, 3.4, 3.0]);
// A paper past the margin queries stays listed, with margins at least the driver's widest.
let a3 = c.paper("A3").unwrap().margins;
assert!(a3.iter().zip([3.4, 5.0, 3.4, 3.0]).all(|(m, widest)| *m >= widest && *m > 0.0), "{a3:?}");
// An unknown default falls back to the first paper.
let other = printer_config("Canon", false, &papers, Some("JapanHagaki"));
assert_eq!(other.default_paper, "Letter");
assert_eq!(other.description, "Windows printer");
}
/// craft-print picks a paper by its size, so a size with a borderless variant is listed once,
/// as the plain sheet, with margins both options can print; the spooler's name is kept whole.
#[test]
fn a_borderless_variant_shares_one_entry_with_printable_margins() {
let p = |key: &str, name: &str, margins| WinPaper { key: key.into(), name: name.into(), width: 210_000, height: 297_000, margins };
let papers = [
p("Borderless", "A4 Borderless", Some([0.0; 4])),
p("ISOA4", "A4", Some([5.0, 4.0, 5.0, 3.0])),
p("ISOA4Wide", "A4 (wide top)", Some([3.0, 4.0, 3.0, 6.0])),
];
let name = format!("{}X", "Q".repeat(100));
let config = printer_config(&name, false, &papers, Some("Borderless"));
assert_eq!(config.name, name, "a long spooler name is not truncated into another printer's");
let names: Vec<&str> = config.papers.iter().map(|p| p.name.as_str()).collect();
assert_eq!(names, ["A4"]);
assert_eq!(config.default_paper, "A4", "the driver's default variant maps to its size's entry");
assert_eq!(config.papers[0].margins, [5.0, 4.0, 5.0, 6.0]);
// An unknown printable area is not advertised as borderless.
let config = printer_config("P", false, &[p("ISOA4", "A4", None)], None);
assert!(config.papers[0].margins.iter().all(|m| *m > 0.0));
}
}
#[cfg(test)]
mod unknown_margin_regressions {
use super::*;
#[test]
fn a_known_borderless_variant_does_not_hide_unknown_plain_margins() {
let papers = [
WinPaper { key: "Borderless".into(), name: "A4 Borderless".into(), width: 210_000, height: 297_000, margins: Some([0.0; 4]) },
WinPaper { key: "ISOA4".into(), name: "A4".into(), width: 210_000, height: 297_000, margins: None },
];
let config = printer_config("P", false, &papers, None);
assert_eq!(config.papers.len(), 1, "the size stays listed");
assert!(config.papers[0].margins.iter().all(|m| *m > 0.0), "{:?}", config.papers[0].margins);
}
#[test]
fn every_left_out_paper_has_a_listed_paper_within_tolerance() {
let p = |key: &str, width, total: f64| WinPaper { key: key.into(), name: key.into(), width, height: 297_000, margins: Some([total; 4]) };
let papers = [p("W0", 210_000, 1.0), p("W2", 210_200, 2.0), p("W4", 210_400, 3.0)];
let config = printer_config("P", false, &papers, None);
for o in &papers {
let w = f64::from(o.width) / 1000.0;
assert!(config.papers.iter().any(|d| (d.width - w).abs() <= 0.25), "{} has no listed paper within tolerance", o.name);
}
}
/// A paper left out for its repeated name does not stand for a paper of another name: `Label`
/// at 210 mm and again at 215 mm, and `Other` at 215.1 mm, list `Label` and `Other` (#2171 review).
#[test]
fn a_paper_dropped_for_its_name_does_not_hide_another_size() {
let p = |name: &str, width, m: f64| WinPaper { key: name.into(), name: name.into(), width, height: 297_000, margins: Some([m; 4]) };
let papers = [p("Label", 210_000, 1.0), p("Label", 215_000, 9.0), p("Other", 215_100, 2.0)];
let config = printer_config("P", false, &papers, None);
let listed: Vec<(&str, f64)> = config.papers.iter().map(|d| (d.name.as_str(), d.width)).collect();
assert_eq!(listed, [("Label", 210.0), ("Other", 215.1)]);
// Other keeps margins every option of its size prints, the left-out Label's included.
assert_eq!(config.papers[1].margins, [9.0; 4]);
}
/// Names the device tells apart the same way are one name before a representative is chosen:
/// `Label X` at 210 mm and `Label-X` at 215 mm leave `Other` at 215.1 mm listed (#2171 review).
#[test]
fn a_name_the_device_merges_does_not_hide_another_size() {
let p = |name: &str, width, m: f64| WinPaper { key: name.into(), name: name.into(), width, height: 297_000, margins: Some([m; 4]) };
let papers = [p("Label X", 210_000, 1.0), p("Label-X", 215_000, 9.0), p("Other", 215_100, 2.0)];
let config = printer_config("P", false, &papers, None);
let listed: Vec<(&str, f64)> = config.papers.iter().map(|d| (d.name.as_str(), d.width)).collect();
assert_eq!(listed, [("Label X", 210.0), ("Other", 215.1)]);
}
}
+18
View File
@@ -0,0 +1,18 @@
#![cfg(windows)]
#[test]
fn the_plot_dialog_lists_the_real_queues_papers_and_default() {
let queue = std::env::var("CADCRAFT_TEST_QUEUE").expect("selected Windows test queue");
let config = cadcraft_io::winprint::printers().into_iter().find(|item| item.name == queue).expect("queue in CadCraft plotter list");
assert!(config.paper(&config.default_paper).is_some());
for (width, height) in [(210.0, 297.0), (215.9, 279.4)] {
let form = config
.papers
.iter()
.find(|paper| (paper.width - width).abs() < 0.6 && (paper.height - height).abs() < 0.6)
.expect("driver-advertised A4 and US Letter");
assert!(form.margins.iter().all(|margin| margin.is_finite() && *margin >= 0.0));
println!("{}: {} x {} mm, margins {:?}", form.name, form.width, form.height, form.margins);
}
println!("{}: {} media, default {}", config.name, config.papers.len(), config.default_paper);
}
+50
View File
@@ -0,0 +1,50 @@
#![cfg(windows)]
use cadcraft_doc::{Common, Drawing, EntityKind, Layout, Line, PageSetup, Space};
use cadcraft_geom::Vec3;
use cadcraft_io::{pdf, winprint};
#[test]
fn plot_ordered_real_layouts_through_the_selected_file_queue() {
let queue = std::env::var("CADCRAFT_TEST_QUEUE").expect("disposable file-output queue");
let media = std::env::var("CADCRAFT_PLOT_MEDIA").unwrap();
let output = std::path::PathBuf::from(std::env::var_os("CADCRAFT_PLOT_OUTPUT").expect("plot evidence directory"));
assert!(output.is_absolute());
let (width, height) = match media.as_str() {
"Letter" => (215.9, 279.4),
"A4" => (210.0, 297.0),
_ => panic!("unknown fixture medium"),
};
let mut drawing = Drawing::new_metric();
let mut spaces = Vec::new();
for sheet in 1..=3 {
let name = format!("QA sheet {sheet}");
let mut layout = Layout::new(&name, sheet + 10);
layout.page = PageSetup {
width_mm: width,
height_mm: height,
landscape: false,
margins_mm: [0.0; 4],
plot_area: "window".into(),
plot_window: [0.0, 0.0, width, height],
scale_to_fit: false,
center: false,
scale: 1.0,
..PageSetup::default()
};
drawing.layouts.push(layout);
let space = Space::Paper(name);
for bar in 1..=sheet {
for stroke in 0..15 {
let x = 35.0 * f64::from(bar) + f64::from(stroke) * 0.17;
let geometry = Line { a: Vec3::new(x, 35.0, 0.0), b: Vec3::new(x, 225.0, 0.0) };
drawing.add(&space, Common::default(), EntityKind::Line(geometry)).unwrap();
}
}
spaces.push(space);
}
let bytes = pdf::pdf_sheets(&drawing, &spaces, &pdf::PdfOptions::default()).unwrap();
std::fs::write(output.join(format!("{media}-source.pdf")), &bytes).unwrap();
let receipt = winprint::print(&queue, &media, 1, "CadCraft numbered plot", &bytes).unwrap();
println!("{media}: {receipt}");
}
+21
View File
@@ -256,6 +256,7 @@ fn unusual_titles_are_kept() {
assert_eq!(doc.title.as_deref(), Some("Plan ü (1)\\"));
}
/// Layers beyond the PDF layer cap still print; only their PDF layers are left out.
#[test]
fn layers_past_the_cap_print_without_a_pdf_layer() {
// One more drawing layer than a file has PDF layers (4096).
@@ -273,3 +274,23 @@ fn layers_past_the_cap_print_without_a_pdf_layer() {
assert_eq!(pdf_read::drawn(c).iter().filter(|o| o.op == "m").count(), 4097);
assert_eq!((pdf_read::count(c, "BDC"), pdf_read::count(c, "EMC")), (4096, 4096));
}
/// With `portraitMedia`, a landscape sheet is drawn a quarter turn on a portrait page; without it the page stays landscape.
#[test]
fn portrait_media_turns_landscape_sheets_for_printers() {
let d = layered();
let page = |o: serde_json::Value| read(&plot(&d, &Space::Model, &o).unwrap()).pages.into_iter().next().unwrap();
// The page's transforms (`cm`): the writer's own y flip, and the quarter turn when turned.
let cms = |p: &pdf_read::Page| -> Vec<Vec<f64>> { pdf_read::ops(&p.content).into_iter().filter(|o| o.op == "cm").map(|o| o.nums).collect() };
let plain = page(json!({ "paper": "Letter", "landscape": true }));
assert_eq!(plain.media, [0.0, 0.0, 792.0, 612.0]);
assert!(cms(&plain).is_empty());
// On portrait media: a portrait page, the sheet turned a quarter turn counterclockwise.
let turned = page(json!({ "paper": "Letter", "landscape": true, "portraitMedia": true }));
assert_eq!(turned.media, [0.0, 0.0, 612.0, 792.0]);
assert!(cms(&turned).iter().any(|m| m == &[0.0, 1.0, -1.0, 0.0, 612.0, 0.0]), "{:?}", cms(&turned));
// A portrait sheet is not turned.
let portrait = page(json!({ "paper": "Letter", "landscape": false, "portraitMedia": true }));
assert_eq!(portrait.media, [0.0, 0.0, 612.0, 792.0]);
assert!(cms(&portrait).is_empty());
}
+67 -2
View File
@@ -168,6 +168,65 @@ pub fn alpha(transparency: u8) -> u8 {
pub const MAX_TRANSPARENCY: u8 = 90;
impl DisplayList {
/// Add what `other` draws (built for the same drawing, in the same coordinates) after what
/// this list draws: a plot stamp, say.
pub fn append(&mut self, other: DisplayList) {
append(self, other);
}
/// Keep only the primitives that reach into `area` (same coordinates as the list): what a
/// plot of a window draws. Infinite lines are kept (they are cut where they are drawn); text
/// glyphs, layers and pens follow their primitives. The vertex and triangle arrays are
/// compacted, so a small window of a large drawing writes and rasterises only its part.
pub fn retain_within(&mut self, area: &Bounds2) {
if area.is_empty() || !area.min.is_finite() || !area.max.is_finite() {
return;
}
let keep: Vec<bool> = self
.prims
.iter()
.map(|p| matches!(p.kind, Kind::Infinite { .. }) || Bounds2::from_points(self.points(p).iter().copied()).intersects(area))
.collect();
if keep.iter().all(|k| *k) {
return;
}
let (mut prims, mut verts, mut tris) = (Vec::new(), Vec::new(), Vec::new());
let (mut layers, mut pens) = (Vec::new(), Vec::new());
// The new index of each old primitive that is kept.
let mut moved: Vec<Option<u32>> = Vec::with_capacity(self.prims.len());
for (i, (p, k)) in self.prims.iter().zip(&keep).enumerate() {
let tri = matches!(p.kind, Kind::Tris | Kind::Mask);
let (src, dst) = if tri { (&self.tris, &mut tris) } else { (&self.verts, &mut verts) };
let (Ok(index), Ok(start), true) = (u32::try_from(prims.len()), u32::try_from(dst.len()), *k) else {
moved.push(None);
continue;
};
let from = p.start as usize;
dst.extend_from_slice(src.get(from..from.saturating_add(p.len as usize)).unwrap_or(&[]));
if let Some(pen) = self.pens.get(i) {
pens.resize(prims.len(), Pen::default());
pens.push(*pen);
}
prims.push(DPrim { start, ..*p });
if let Some(l) = self.prim_layers.get(i) {
layers.push(*l);
}
moved.push(Some(index));
}
self.texts.retain_mut(|t| {
if t.prim >= PlotText::CLIPPED {
return t.bounds.intersects(area);
}
match moved.get(t.prim as usize).copied().flatten() {
Some(i) => {
t.prim = i;
true
}
None => false,
}
});
(self.prims, self.verts, self.tris, self.prim_layers, self.pens) = (prims, verts, tris, layers, pens);
}
pub fn segment_count(&self) -> usize {
self.prims.iter().filter(|p| p.kind == Kind::Polyline).map(|p| p.len.saturating_sub(1) as usize).sum()
}
@@ -189,10 +248,10 @@ impl DisplayList {
}
/// Append `src` to `dst`: its primitives index into `dst`'s vertex and triangle arrays.
#[cfg(not(target_arch = "wasm32"))]
pub(crate) fn append(dst: &mut DisplayList, src: DisplayList) {
let (verts, tris, prims) = (dst.verts.len() as u32, dst.tris.len() as u32, dst.prims.len() as u32);
let images = dst.images.len() as u32;
let src_prims = src.prims.len();
// Pens are parallel to the primitives, with missing entries meaning "use object".
if !src.pens.is_empty() {
dst.pens.resize(dst.prims.len(), Pen::default());
@@ -207,7 +266,13 @@ pub(crate) fn append(dst: &mut DisplayList, src: DisplayList) {
dst.images.extend(src.images);
dst.verts.extend(src.verts);
dst.tris.extend(src.tris);
dst.prim_layers.extend(src.prim_layers);
// Layers are parallel to the primitives too: when either list has them, a primitive without
// one gets NO_LAYER, so every later primitive keeps its own layer.
if !src.prim_layers.is_empty() || !dst.prim_layers.is_empty() {
dst.prim_layers.resize(prims as usize, NO_LAYER);
dst.prim_layers.extend(src.prim_layers.into_iter().take(src_prims));
dst.prim_layers.resize(prims as usize + src_prims, NO_LAYER);
}
dst.texts.extend(src.texts.into_iter().map(|mut t| {
if t.prim < PlotText::CLIPPED {
t.prim += prims;
+9 -46
View File
@@ -553,29 +553,15 @@ const MAX_SWATCH_WORK: u64 = 2_000_000;
/// A preview of a pattern for a pattern picker: the runs of its line families `lines` inside the
/// `side` × `side` square with a corner at the origin, at a scale that shows a few repeats of the
/// pattern. For sparse, staggered tile edges the area per mark sets the preview scale. Empty for a pattern
/// pattern (each family's line spacing or dash repeat, whichever is longer). Empty for a pattern
/// with no lines (SOLID).
pub fn pattern_swatch(lines: &[PatternLine], side: f64) -> Vec<Vec<Vec2>> {
let estimate = |sparse: bool| {
lines
.iter()
.map(|l| {
let spacing = l.delta.1.abs();
let period = l.dashes.iter().map(|d| d.abs()).sum::<f64>();
if sparse && l.delta.0 != 0. && matches!(l.dashes.as_slice(), [ink, gap] if *ink > 0. && -*gap > 32. * spacing) {
(period * spacing).sqrt()
} else {
spacing.max(period)
}
})
.filter(|r| r.is_finite())
.fold(0.0, f64::max)
};
let repeat = estimate(true);
let repeat =
lines.iter().map(|l| l.delta.1.abs().max(l.dashes.iter().map(|d| d.abs()).sum::<f64>())).filter(|r| r.is_finite()).fold(0.0, f64::max);
if !side.is_finite() || side <= 0.0 || repeat < 1e-9 {
return Vec::new();
}
let mut h = Hatch {
let h = Hatch {
pattern: String::new(),
solid: false,
loops: Vec::new(),
@@ -592,16 +578,7 @@ pub fn pattern_swatch(lines: &[PatternLine], side: f64) -> Vec<Vec<Vec2>> {
let square = vec![Vec2::new(0.0, 0.0), Vec2::new(side, 0.0), Vec2::new(side, side), Vec2::new(0.0, side)];
// The generator stops at the swatch's own limits, so a compact pattern is never made in full
// (about a million runs) to keep a few thousand.
let loops = [square];
let render = |h: &Hatch| pattern_lines_within(&Drawing::default(), h, &loops, 0.0, None, None, MAX_SWATCH_RUNS, MAX_SWATCH_WORK);
let mut runs = render(&h);
if runs.is_empty() {
let full = estimate(false);
if full > repeat {
h.scale = side / (SWATCH_REPEATS * full);
runs = render(&h);
}
}
let mut runs = pattern_lines_within(&Drawing::default(), &h, &[square], 0.0, None, None, MAX_SWATCH_RUNS, MAX_SWATCH_WORK);
runs.truncate(MAX_SWATCH_RUNS);
runs.shrink_to_fit();
runs
@@ -667,18 +644,14 @@ impl Family<'_> {
let k0 = (lo.y / self.spacing).floor() as i64;
let k1 = (hi.y / self.spacing).ceil() as i64;
let max_lines = if view.is_some() { MAX_VIEW_FAMILY_LINES } else { MAX_FAMILY_LINES };
let many_rows = k1.saturating_sub(k0) > max_lines;
if k1.saturating_sub(k0) > max_lines {
return;
}
let pat_len: f64 = self.dashes.iter().map(|d| d.abs()).sum();
// Level of detail: a whole repeat under two pixels reads as a continuous line (when the
// family draws anything at all).
let draws = self.dashes.iter().any(|d| *d >= 0.0);
let solid_line = self.dashes.is_empty() || pat_len < 1e-12 || (px > 0.0 && pat_len < 2.0 * px && draws);
// Captured tile edges can have many tightly spaced rows, each with a long empty gap.
// Reject empty rows by dash phase before walking or sorting any boundary edges.
let sparse = matches!(self.dashes, [ink, gap] if *ink >= 0. && -*gap > hi.x - lo.x) && !solid_line;
if many_rows && (!sparse || k1.abs_diff(k0) >= *work) {
return;
}
// Each scanline visits every boundary edge and sorts the intersections. Charge both the
// traversal and an n*ceil(log2(n)) upper bound for sorting, scaled to one unit per eight
// operations, whether or not any dash is made.
@@ -689,20 +662,10 @@ impl Family<'_> {
if out.len() >= self.max_runs || crossings_charge > *work || is_set(cancel) {
return;
}
let offset = shift_per_line * k as f64;
if many_rows {
*work -= 1;
let phase = (lo.x - offset).rem_euclid(pat_len);
if phase > self.dashes[0] && pat_len - phase > hi.x - lo.x {
continue;
}
if crossings_charge > *work {
return;
}
}
*work -= crossings_charge;
let y = k as f64 * self.spacing;
let xs = crossings(&local, y);
let offset = shift_per_line * k as f64;
for span in xs.chunks(2) {
let [x0, x1] = span else { continue };
let (x0, x1) = match span_cut {
+13
View File
@@ -64,6 +64,19 @@ pub const MAX_PATTERN_CELLS: usize = 2_000_000;
/// Miters longer than this many half widths are drawn bevelled (as PDF's default miter limit).
pub(crate) const MITER_LIMIT: f64 = 10.0;
/// The widest plotted lineweight, in paper millimetres.
const MAX_PLOT_WIDTH_MM: f64 = 2.11;
/// `w` (in drawing units) grown by the most a plotted stroke can reach past the line it draws:
/// a sharp mitred corner of the widest lineweight (half its width times [`MITER_LIMIT`]) and a
/// millimetre more, at `mm_per_unit` paper millimetres per drawing unit, plus 1 % of the window.
/// What a window plot keeps ([`crate::DisplayList::retain_within`]); the final clip stays at `w`.
pub fn plot_window_reach(w: &cadcraft_geom::Bounds2, mm_per_unit: f64) -> cadcraft_geom::Bounds2 {
let reach = (MAX_PLOT_WIDTH_MM / 2.0 * MITER_LIMIT + 1.0) / mm_per_unit;
let margin = if reach.is_finite() && reach > 0.0 { reach } else { 0.0 };
w.expand(margin + w.width().max(w.height()) * 0.01)
}
/// Segments of a half circle (round ends and joins).
const ROUND_STEPS: usize = 12;
+46 -6
View File
@@ -82,6 +82,15 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixm
}
let mut pm = Pixmap::new(view.width, view.height)?;
pm.fill(tiny_skia::Color::from_rgba8(o.background.0, o.background.1, o.background.2, 255));
render_into(list, view, o, &mut pm)?;
Some(pm)
}
/// Draw onto an existing pixmap, preserving its background and earlier marks.
pub fn render_into(list: &DisplayList, view: &View, o: &RasterOptions, pm: &mut Pixmap) -> Option<()> {
if pm.width() != view.width || pm.height() != view.height {
return None;
}
let vis = view.world_bounds();
let mut hairlines = Hairlines::default();
let mut screen: Vec<(f32, f32)> = Vec::new();
@@ -93,7 +102,7 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixm
paint.anti_alias = o.antialias;
let pts = list.points(p);
if p.kind != Kind::Polyline {
hairlines.flush(&mut pm, o.antialias);
hairlines.flush(pm, o.antialias);
}
match p.kind {
Kind::Polyline => {
@@ -105,10 +114,10 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixm
screen.clear();
screen.extend(pts.iter().map(|q| view.to_screen(*q)));
if is_hairline(w, o.antialias) && screen.len() >= 2 && screen.iter().all(|&(x, y)| batchable(x) && batchable(y)) {
hairlines.add(&mut pm, [c.0, c.1, c.2, p.alpha()], w, &screen, o.antialias);
hairlines.add(pm, [c.0, c.1, c.2, p.alpha()], w, &screen, o.antialias);
continue;
}
hairlines.flush(&mut pm, o.antialias);
hairlines.flush(pm, o.antialias);
let mut pb = PathBuilder::new();
for (i, (x, y)) in screen.iter().enumerate() {
if i == 0 {
@@ -156,7 +165,7 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixm
if let Some(img) = list.images.get(index as usize)
&& Bounds2::from_points(pts.iter().copied()).intersects(&vis)
{
image(&mut pm, img, view, p.alpha(), o.antialias);
image(pm, img, view, p.alpha(), o.antialias);
}
}
Kind::Infinite { ray } => {
@@ -175,8 +184,39 @@ pub fn render(list: &DisplayList, view: &View, o: &RasterOptions) -> Option<Pixm
}
}
}
hairlines.flush(&mut pm, o.antialias);
Some(pm)
hairlines.flush(pm, o.antialias);
Some(())
}
/// Draw onto an existing pixmap, but only inside the pixel rectangle from `top_left` to
/// `bottom_right` (image coordinates, y down; rounded and clamped to the image): what the list
/// draws outside it is cut, and what the pixmap already holds there stays as it is.
pub fn render_within(
list: &DisplayList,
view: &View,
o: &RasterOptions,
pm: &mut Pixmap,
top_left: (f32, f32),
bottom_right: (f32, f32),
) -> Option<()> {
if pm.width() != view.width || pm.height() != view.height {
return None;
}
let edge = |v: f32, max: u32| f64::from(v).round().clamp(0.0, f64::from(max)) as u32;
let (x0, x1) = (edge(top_left.0, view.width), edge(bottom_right.0, view.width));
let (y0, y1) = (edge(top_left.1, view.height), edge(bottom_right.1, view.height));
if x1 <= x0 || y1 <= y0 {
return Some(());
}
let (w, h) = (x1 - x0, y1 - y0);
// The same view, cut to the rectangle: its centre is the world point at the rectangle's centre.
let dx = (f64::from(x0) + f64::from(w) / 2.0 - f64::from(view.width) / 2.0) / view.scale;
let dy = (f64::from(y0) + f64::from(h) / 2.0 - f64::from(view.height) / 2.0) / view.scale;
let sub = View { center: view.center + Vec2::new(dx, -dy), scale: view.scale, width: w, height: h };
let mut layer = Pixmap::new(w, h)?;
render_into(list, &sub, o, &mut layer)?;
pm.draw_pixmap(i32::try_from(x0).ok()?, i32::try_from(y0).ok()?, layer.as_ref(), &tiny_skia::PixmapPaint::default(), Transform::identity(), None);
Some(())
}
/// Whether tiny-skia strokes a line `width` pixels wide (untransformed) as a hairline: zero
+62
View File
@@ -1907,6 +1907,68 @@ fn rotated_and_reversed_copies_of_a_curved_loop_fill_once() {
assert_eq!(loops_of(&h).len(), 2);
}
/// `retain_within` keeps the primitives that reach into the area, with their layers, and
/// compacts the vertex arrays; one that is all inside or all outside decides alone.
#[test]
fn retain_within_keeps_what_reaches_the_area() {
let mut d = Drawing::new_metric();
let line = |a: Vec3, b: Vec3| EntityKind::Line(cadcraft_doc::Line { a, b });
d.add(&Space::Model, Common::default(), line(Vec3::new(0.0, 0.0, 0.0), Vec3::new(10.0, 0.0, 0.0))).unwrap();
d.add(&Space::Model, Common::default(), line(Vec3::new(100.0, 100.0, 0.0), Vec3::new(110.0, 100.0, 0.0))).unwrap();
d.add(&Space::Model, Common::default(), line(Vec3::new(-5.0, -50.0, 0.0), Vec3::new(-5.0, 50.0, 0.0))).unwrap();
let mut list = build_plot(&d, &Space::Model, &Options::default());
assert_eq!(list.prims.len(), 3);
// Distinct layers, so compaction is seen to keep each primitive's own.
list.prim_layers = vec![10, 11, 12];
list.retain_within(&Bounds2::new(Vec2::new(-10.0, -1.0), Vec2::new(20.0, 1.0)));
assert_eq!(list.prims.len(), 2, "the far line goes, the one crossing the area stays");
assert_eq!(list.prim_layers, [10, 12]);
assert!(list.verts.iter().all(|p| p.x < 50.0), "the far line's vertices are gone");
for p in &list.prims {
assert_eq!(list.points(p).len(), p.len as usize);
}
// An empty or non-finite area keeps everything.
let before = list.prims.len();
list.retain_within(&Bounds2::EMPTY);
assert_eq!(list.prims.len(), before);
}
/// A window plot keeps a line whose sharp mitred corner (the widest lineweight, 2.11 mm, at the
/// miter limit) reaches into the window from outside the old 3 mm margin.
#[test]
fn the_window_reach_covers_a_mitred_corner() {
let w = Bounds2::new(Vec2::ZERO, Vec2::new(100.0, 100.0));
let kept = crate::pen::plot_window_reach(&w, 1.0);
// Points (-15, 48.5), (-5, 50), (-15, 51.5): the miter tip reaches about 7.1 mm right of (-5, 50).
let corner = Bounds2::from_points([Vec2::new(-15.0, 48.5), Vec2::new(-5.0, 50.0), Vec2::new(-15.0, 51.5)]);
assert!(corner.intersects(&kept));
// At a smaller plot scale (fewer paper mm per unit) the same reach covers more drawing units.
assert!(crate::pen::plot_window_reach(&w, 0.1).width() > kept.width());
}
/// Appending keeps each primitive's layer, whichever list had layers.
#[test]
fn append_keeps_layers_aligned_with_primitives() {
let mut d = Drawing::new_metric();
d.add(&Space::Model, Common::default(), EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(1.0, 0.0, 0.0) })).unwrap();
let one = || build_plot(&d, &Space::Model, &Options::default());
let (mut plain, mut layered) = (one(), one());
plain.prim_layers.clear();
layered.prim_layers = vec![7];
plain.append(layered.clone());
assert_eq!(plain.prim_layers, [NO_LAYER, 7]);
let mut first = layered;
let mut other = one();
other.prim_layers.clear();
first.append(other);
assert_eq!(first.prim_layers, [7, NO_LAYER]);
let (mut a, mut b) = (one(), one());
a.prim_layers.clear();
b.prim_layers.clear();
a.append(b);
assert!(a.prim_layers.is_empty(), "lists without layers stay without");
}
#[test]
fn mtext_background_mask_emits_mask_before_text() {
let mut d = Drawing::new_metric();
+4 -4
View File
@@ -84,7 +84,7 @@ enum Tab {
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub(crate) enum View {
enum View {
ExtraLarge,
Large,
#[default]
@@ -95,10 +95,10 @@ pub(crate) enum View {
}
impl View {
pub(crate) const ALL: [View; 6] = [View::ExtraLarge, View::Large, View::Medium, View::Small, View::Details, View::List];
const ALL: [View; 6] = [View::ExtraLarge, View::Large, View::Medium, View::Small, View::Details, View::List];
/// The name shown on the view's button.
pub(crate) fn label(self) -> &'static str {
fn label(self) -> &'static str {
match self {
View::ExtraLarge => crate::tl!("Extra Large Icons"),
View::Large => crate::tl!("Large Icons"),
@@ -110,7 +110,7 @@ impl View {
}
/// The side of a gallery tile, for the icon views.
pub(crate) fn tile(self) -> Option<f32> {
fn tile(self) -> Option<f32> {
match self {
View::ExtraLarge => Some(150.0),
View::Large => Some(104.0),
+2 -16
View File
@@ -552,23 +552,9 @@ pub fn start_page(app: &mut CadApp, ui: &mut egui::Ui) {
y += 44.0;
}
let main = Rect::from_min_max(pos2(left.right() + 36.0, r.top() + 40.0), r.max);
let mut local_top = main.top();
if app.file_providers.enabled() {
let mut provider_ui = ui.new_child(egui::UiBuilder::new().max_rect(main).layout(egui::Layout::top_down(egui::Align::Min)));
let resource = egui::ScrollArea::vertical()
.id_salt("provider-recents")
.max_height((r.height() * 0.4).clamp(80.0, 240.0))
.show(&mut provider_ui, |ui| app.file_providers.provider_recent_ui(ui))
.inner;
app.file_providers.device_recent_ui(&mut provider_ui);
local_top += provider_ui.min_rect().height() + 20.0;
if let Some(resource) = resource {
let _ = app.run(crate::menus::PROVIDER_RECENT_OPEN, serde_json::json!({"resource":resource}));
}
}
p.text(pos2(main.left(), local_top), egui::Align2::LEFT_TOP, crate::tl!("Recent"), egui::FontId::proportional(22.0), t.text);
p.text(main.min, egui::Align2::LEFT_TOP, crate::tl!("Recent"), egui::FontId::proportional(22.0), t.text);
let mut recent = None;
let mut y = local_top + 44.0;
let mut y = main.top() + 44.0;
for (i, path) in app.ui.recent_files.iter().enumerate() {
let row = Rect::from_min_size(pos2(main.left(), y), vec2((r.right() - main.left() - 36.0).clamp(0.0, 640.0), 42.0));
let resp = ui.interact(row, ui.scope_id().with(("recent", i)), Sense::click());
-8
View File
@@ -68,10 +68,6 @@ impl CadApp {
/// about each drawing first and quit once all are dealt with. Returns whether the close has to
/// wait (the caller then cancels the window close).
pub fn request_quit(&mut self) -> bool {
if self.file_providers.busy() {
self.set_status("Finish or cancel the pending file provider operation before quitting");
return true;
}
if self.quit_confirmed || !self.session.docs.iter().any(|d| d.is_dirty()) {
return false;
}
@@ -175,10 +171,6 @@ impl CadApp {
}
fn begin_close(&mut self, uids: Vec<u64>) {
if self.file_providers.busy() {
self.set_status("Finish or cancel the pending file provider operation before closing");
return;
}
if self.closing.is_some() {
// A prompt is already open; it has to be answered first.
return;
+478 -54
View File
@@ -4,9 +4,10 @@
use std::sync::atomic::{AtomicU32, Ordering};
use egui::TextureHandle;
use egui::{Pos2, Rect, Sense, TextureHandle, Vec2, pos2, vec2};
use serde_json::{Value, json};
use crate::managers::PreviewRequest;
use crate::{CadApp, Pick};
/// Bumped each time PREVIEW is started, so the window renders the drawing as it is now.
@@ -167,84 +168,345 @@ pub(crate) fn version_params(ui: &crate::UiState, path: &str) -> Value {
}
}
/// Without a file dialog, say on the command line how to run the command with parameters.
fn no_picker(app: &mut CadApp, name: &str, example: &str) -> Result<Value, String> {
let msg = format!("{name}: there is no file dialog here; run it with parameters, e.g. {example}");
app.session.echo(msg.clone());
Err(msg)
}
/// How far the preview can be zoomed in, as a multiple of the whole sheet fitting its area.
const MAX_ZOOM: f32 = 24.0;
/// How long (seconds) the view must rest before the part in view is drawn again in more detail.
const SETTLE: f64 = 0.15;
/// How the sheet's image sits in the preview area: `zoom` 1 fits the whole sheet, `pan` moves the
/// image's centre from the area's centre (points).
#[derive(Clone, Copy, Debug, PartialEq)]
struct PanZoom {
zoom: f32,
pan: Vec2,
}
impl Default for PanZoom {
/// The whole sheet in view.
fn default() -> Self {
PanZoom { zoom: 1.0, pan: Vec2::ZERO }
}
}
impl PanZoom {
/// Points per image pixel when the whole image fits `area`.
fn fit(area: Rect, image: Vec2) -> f32 {
(area.width() / image.x.max(1.0)).min(area.height() / image.y.max(1.0)).max(1e-6)
}
/// Where the whole image is drawn.
fn image_rect(&self, area: Rect, image: Vec2) -> Rect {
Rect::from_center_size(area.center() + self.pan, image * (Self::fit(area, image) * self.zoom))
}
/// Keep the zoom in range and the image over the area: it can't be dragged away, and is
/// centred along an axis where it is smaller than the area.
fn clamp(&mut self, area: Rect, image: Vec2) {
self.zoom = if self.zoom.is_finite() { self.zoom.clamp(1.0, MAX_ZOOM) } else { 1.0 };
let size = image * (Self::fit(area, image) * self.zoom);
let room = |image: f32, area: f32| ((image - area) / 2.0).max(0.0);
let (rx, ry) = (room(size.x, area.width()), room(size.y, area.height()));
self.pan =
if self.pan.x.is_finite() && self.pan.y.is_finite() { vec2(self.pan.x.clamp(-rx, rx), self.pan.y.clamp(-ry, ry)) } else { Vec2::ZERO };
}
/// Zoom by `factor` about the screen point `at`, which stays over the same point of the image.
fn zoom_at(&mut self, area: Rect, image: Vec2, at: Pos2, factor: f32) {
if !(factor.is_finite() && factor > 0.0) {
return;
}
let centre = self.image_rect(area, image).center();
let zoom = (self.zoom * factor).clamp(1.0, MAX_ZOOM);
let moved = at + (centre - at) * (zoom / self.zoom);
self.zoom = zoom;
self.pan = moved - area.center();
self.clamp(area, image);
}
}
/// The part of the image drawn at `shown` that is inside `area`, as fractions of the image from its
/// top-left corner `[x0, y0, x1, y1]`; `None` when none of it is.
fn visible_crop(area: Rect, shown: Rect) -> Option<[f32; 4]> {
let v = area.intersect(shown);
if shown.width() < 1.0 || shown.height() < 1.0 || v.width() < 1.0 || v.height() < 1.0 {
return None;
}
let (w, h) = (shown.width(), shown.height());
Some([(v.min.x - shown.min.x) / w, (v.min.y - shown.min.y) / h, (v.max.x - shown.min.x) / w, (v.max.y - shown.min.y) / h])
}
/// `crop` grown by a quarter of its size on each side (within the sheet): what is drawn in detail,
/// so that a small pan stays sharp.
fn with_margin(c: [f32; 4]) -> [f32; 4] {
let (mx, my) = ((c[2] - c[0]) / 4.0, (c[3] - c[1]) / 4.0);
[(c[0] - mx).max(0.0), (c[1] - my).max(0.0), (c[2] + mx).min(1.0), (c[3] + my).min(1.0)]
}
/// Whether crop `outer` covers crop `inner`.
fn covers(outer: [f32; 4], inner: [f32; 4]) -> bool {
outer[0] <= inner[0] + 1e-4 && outer[1] <= inner[1] + 1e-4 && outer[2] >= inner[2] - 1e-4 && outer[3] >= inner[3] - 1e-4
}
/// The sheet as plotted: the whole of it drawn once, and what the preview needs to draw parts of it
/// again in more detail.
#[derive(Clone)]
struct Shown {
base: TextureHandle,
info: String,
/// The sheet's width and height in mm, as plotted (the orientation applied).
sheet_mm: Vec2,
/// The `plot` parameters of the whole sheet.
params: Value,
}
/// A part of the sheet drawn at the resolution of the screen it is shown on.
#[derive(Clone)]
struct Detail {
tex: TextureHandle,
/// The part, as fractions of the sheet from its top-left corner.
crop: [f32; 4],
/// The width in points the whole sheet had on screen when it was drawn.
sheet_width: f32,
}
impl Detail {
/// Whether it is drawn at the scale the sheet has on screen now.
fn matches(&self, sheet_width: f32) -> bool {
sheet_width > 0.0 && (self.sheet_width / sheet_width - 1.0).abs() < 0.01
}
}
#[derive(Clone)]
struct Preview {
generation: u32,
shown: Result<(TextureHandle, String), String>,
}
/// A preview the Plot dialog asked for: its PLOT parameters (PNG output) and a caption.
#[derive(Clone)]
struct FromPlot {
params: Value,
info: String,
document: (u64, Option<(u64, u64)>),
shown: Result<Shown, String>,
view: PanZoom,
detail: Option<Detail>,
/// When the view, or the size the sheet is drawn at, last changed (seconds), to draw in detail
/// once it rests.
changed: f64,
/// Where the sheet was drawn last: a resized window changes it with the view unchanged.
drawn: Rect,
/// The part and scale last drawn in detail, so a failure is not retried every frame.
tried: Option<([i32; 4], i32)>,
}
/// Where the preview the Plot dialog asked for is kept ([`PreviewRequest`]).
const FROM_PLOT: &str = "cc_plot_preview_from_plot";
/// Show the Plot dialog's settings as they plot (PLOT with `params`, a PNG); Print... and Close
/// return to the dialog.
pub(crate) fn preview_plot(app: &mut CadApp, ctx: &egui::Context, params: Value, info: String) {
/// Show the Plot dialog's settings as they plot (PLOT with the request's parameters, a PNG);
/// Print... and Close return to the dialog.
pub(crate) fn preview_plot(app: &mut CadApp, ctx: &egui::Context, request: PreviewRequest) {
PREVIEW_GEN.fetch_add(1, Ordering::Relaxed);
ctx.data_mut(|d| d.insert_temp(egui::Id::unique(FROM_PLOT), FromPlot { params, info }));
ctx.data_mut(|d| d.insert_temp(egui::Id::unique(FROM_PLOT), request));
app.ui.dialog = Some("preview".into());
}
/// Render the plot preview of the current layout (or model), or of the Plot dialog's settings,
/// as a texture.
fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<(TextureHandle, String), String> {
if let Some(f) = ctx.data(|d| d.get_temp::<FromPlot>(egui::Id::unique(FROM_PLOT))) {
let r = app.session.execute("plot", &f.params).map_err(|e| e.to_string())?;
let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?;
let tex = preview_texture(ctx, &png)?;
return Ok((tex, f.info));
}
let r = app.session.execute("preview", &json!({ "width": 1600 })).map_err(|e| e.to_string())?;
let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?;
let tex = preview_texture(ctx, &png)?;
let mut info = format!("{} · {}", r["layout"].as_str().unwrap_or(""), r["paper"].as_str().unwrap_or(""));
if r["landscape"].as_bool() == Some(true) {
info.push_str(" · landscape");
}
Ok((tex, info))
/// The preview the Plot dialog asked for, if this preview is one.
fn from_plot(ctx: &egui::Context) -> Option<PreviewRequest> {
ctx.data(|d| d.get_temp::<PreviewRequest>(egui::Id::unique(FROM_PLOT)))
}
fn preview_texture(ctx: &egui::Context, png: &[u8]) -> Result<TextureHandle, String> {
/// Whether a preview the Plot dialog asked for is of another drawing than the one shown now (the
/// user switched drawings, or entered or left the Block Editor): it is not plotted with the
/// drawing shown, and Print... is off.
fn stale(app: &CadApp, request: Option<&PreviewRequest>) -> bool {
request.is_some_and(|r| r.drawing != crate::managers::plot_drawing(app))
}
/// Plot `params` (a PNG) and load it as a texture called `name`.
fn plot_texture(app: &mut CadApp, ctx: &egui::Context, params: &Value, name: &str) -> Result<TextureHandle, String> {
let r = app.session.execute("plot", params).map_err(|e| e.to_string())?;
let png = r["data"].as_str().and_then(cadcraft_engine::cmd::file::base64_decode).ok_or("the preview has no image")?;
preview_texture(ctx, &png, name)
}
fn preview_texture(ctx: &egui::Context, png: &[u8], name: &str) -> Result<TextureHandle, String> {
if !png.starts_with(b"\x89PNG\r\n\x1a\n") {
return Err("the preview is not a PNG".into());
}
let img = cadcraft_io::raster::decode(png).map_err(|e| e.to_string())?;
let size = [img.width() as usize, img.height() as usize];
Ok(ctx.load_texture("plot-preview", egui::ColorImage::from_rgba_unmultiplied(size, img.rgba()), egui::TextureOptions::LINEAR))
Ok(ctx.load_texture(name, egui::ColorImage::from_rgba_unmultiplied(size, img.rgba()), egui::TextureOptions::LINEAR))
}
/// The Plot Preview window: the sheet as it plots, with Print and Close.
/// Render the plot preview of the tab being shown, or of the Plot dialog's settings, as it plots
/// (page setup, plot style table, lineweights): the whole sheet at about 1600 pixels.
fn render(app: &mut CadApp, ctx: &egui::Context) -> Result<Shown, String> {
let request = match from_plot(ctx) {
Some(r) if stale(app, Some(&r)) => {
return Err(
crate::tl!("This preview is of another drawing than the one shown now. Close it and preview again from the Plot dialog.").to_string()
);
}
Some(r) => r,
None => crate::managers::current_preview(app)?,
};
let base = plot_texture(app, ctx, &request.params, "plot-preview")?;
// The sheet's size as plotted comes with the request: a preview of one of several sheets
// leaves the size to the layout's page setup, so its parameters don't hold it.
Ok(Shown { base, info: request.info, sheet_mm: request.sheet_mm, params: request.params })
}
/// Draw the part `crop` of the sheet again at the resolution of the screen, where the whole sheet is
/// `sheet_width` points wide.
fn render_detail(app: &mut CadApp, ctx: &egui::Context, shown: &Shown, crop: [f32; 4], sheet_width: f32) -> Result<Detail, String> {
// One image pixel per screen pixel: the sheet's pixel width over its width in inches.
let pixels = f64::from(sheet_width) * f64::from(ctx.pixels_per_point());
let dpi = (pixels / (f64::from(shown.sheet_mm.x) / 25.4)).clamp(50.0, 2400.0);
let mut params = shown.params.clone();
if let Some(o) = params.as_object_mut() {
o.insert("resolution".into(), json!(dpi));
o.insert("crop".into(), json!(crop));
}
let tex = plot_texture(app, ctx, &params, "plot-preview-detail")?;
Ok(Detail { tex, crop, sheet_width })
}
/// The Plot Preview window: the sheet as it plots, with Print and Close. The mouse wheel zooms
/// about the pointer, dragging pans and a double click shows the whole sheet again; the part in
/// view is drawn again at the screen's resolution once the view rests.
pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
let id = egui::Id::unique("cc_plot_preview");
let generation = PREVIEW_GEN.load(Ordering::Relaxed);
let cached = ctx.data(|d| d.get_temp::<Preview>(id)).filter(|p| p.generation == generation);
let preview = match cached {
let now = ctx.input(|i| i.time);
let document = (app.session.doc_epoch, app.session.state().ok().map(|s| (s.uid, s.revision)));
let cached = ctx.data(|d| d.get_temp::<Preview>(id)).filter(|p| p.generation == generation && p.document == document);
let mut pv = match cached {
Some(p) => p,
None => {
let p = Preview { generation, shown: render(app, ctx) };
ctx.data_mut(|d| d.insert_temp(id, p.clone()));
p
}
None => Preview {
generation,
document,
shown: render(app, ctx),
view: PanZoom::default(),
detail: None,
changed: now,
drawn: Rect::NOTHING,
tried: None,
},
};
let (mut close, mut print) = (false, false);
egui::Window::new("Plot Preview").open(open).collapsible(false).resizable(false).show(ctx, |ui| {
match &preview.shown {
Ok((tex, info)) => {
ui.label(info);
let size = tex.size_vec2();
let k = (760.0 / size.x).min(540.0 / size.y).min(1.0);
ui.image((tex.id(), size * k));
let stale_request = stale(app, from_plot(ctx).as_ref());
// What to draw in detail after the window: the part and the sheet's width on screen.
let mut want: Option<([f32; 4], f32)> = None;
egui::Window::new("Plot Preview").open(open).collapsible(false).resizable(true).default_size(vec2(900.0, 680.0)).show(ctx, |ui| {
match &pv.shown {
Ok(shown) => {
let image = shown.base.size_vec2();
let mut view = pv.view;
let (mut zoom_out, mut fit, mut zoom_in) = (false, false, false);
ui.horizontal(|ui| {
ui.label(&shown.info);
ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
ui.label(format!("{:.0}%", view.zoom * 100.0));
fit = ui.small_button("Fit").on_hover_text("The whole sheet (or double-click)").clicked();
zoom_in = ui.small_button("+").on_hover_text("Zoom in (or the mouse wheel)").clicked();
zoom_out = ui.small_button("−").on_hover_text("Zoom out").clicked();
});
});
let size = vec2(ui.available_width().max(160.0), (ui.available_height() - 36.0).max(160.0));
let (area, resp) = ui.allocate_exact_size(size, Sense::click_and_drag());
let name = crate::tl!("Sheet preview (arrow keys move the view, + and − zoom)");
resp.widget_info(|| egui::WidgetInfo::labeled(egui::Role::Image, true, name));
if resp.clicked() || resp.drag_started() {
resp.request_focus();
}
// With the keyboard: Tab reaches the sheet, the arrow keys move the view over it
// (Right shows more of its right side) and + and − zoom; Tab leaves it again.
if resp.has_focus() {
let arrows = egui::EventFilter { horizontal_arrows: true, vertical_arrows: true, tab: false, escape: false };
ui.memory_mut(|m| m.set_focus_lock_filter(resp.id, arrows));
let step = area.width().min(area.height()) * 0.1;
ui.input(|i| {
let pressed = |k: egui::Key| i.key_pressed(k);
if pressed(egui::Key::ArrowLeft) {
view.pan.x += step;
}
if pressed(egui::Key::ArrowRight) {
view.pan.x -= step;
}
if pressed(egui::Key::ArrowUp) {
view.pan.y += step;
}
if pressed(egui::Key::ArrowDown) {
view.pan.y -= step;
}
zoom_in |= pressed(egui::Key::Plus) || pressed(egui::Key::Equals);
zoom_out |= pressed(egui::Key::Minus);
});
}
let hover = ui.input(|i| i.pointer.hover_pos()).filter(|p| area.contains(*p));
if resp.hovered() {
let (scroll, pinch) = ui.input(|i| (i.smooth_scroll_delta.y, i.zoom_delta()));
if let Some(at) = hover {
view.zoom_at(area, image, at, (scroll * 0.002).exp() * pinch);
}
}
if resp.dragged() {
view.pan += resp.drag_delta();
}
if resp.double_clicked() || fit {
view = PanZoom::default();
}
if zoom_in {
view.zoom_at(area, image, area.center(), 1.5);
}
if zoom_out {
view.zoom_at(area, image, area.center(), 1.0 / 1.5);
}
view.clamp(area, image);
if resp.dragged() || resp.hovered() {
ui.ctx().set_cursor_icon(if resp.dragged() { egui::CursorIcon::Grabbing } else { egui::CursorIcon::Grab });
}
let sheet = view.image_rect(area, image);
let painter = ui.painter_at(area);
painter.rect_filled(area, 0.0, egui::Color32::from_gray(70));
let full = Rect::from_min_max(Pos2::ZERO, pos2(1.0, 1.0));
painter.image(shown.base.id(), sheet, full, egui::Color32::WHITE);
if let Some(d) = pv.detail.as_ref().filter(|d| d.matches(sheet.width())) {
let [x0, y0, x1, y1] = d.crop;
let (w, h) = (sheet.width(), sheet.height());
let part = Rect::from_min_max(sheet.min + vec2(x0 * w, y0 * h), sheet.min + vec2(x1 * w, y1 * h));
painter.image(d.tex.id(), part, full, egui::Color32::WHITE);
}
painter.rect_stroke(sheet, 0.0, egui::Stroke::new(1.0, egui::Color32::from_gray(120)), egui::StrokeKind::Outside);
if resp.has_focus() {
let t = crate::theme::Tokens::get();
painter.rect_stroke(area, 0.0, egui::Stroke::new(2.0, t.accent), egui::StrokeKind::Inside);
}
// A change of the view or of the size the sheet is drawn at (the window was resized)
// restarts the wait, so the detail is not drawn again at every step of a resize.
if view != pv.view || sheet != pv.drawn {
pv.changed = now;
pv.view = view;
pv.drawn = sheet;
}
// Drawn in detail when the sheet is shown larger than its image, once the view rests.
let larger = sheet.width() * ui.ctx().pixels_per_point() > image.x * 1.1;
if let Some(crop) = visible_crop(area, sheet).filter(|_| larger) {
let covered = pv.detail.as_ref().is_some_and(|d| d.matches(sheet.width()) && covers(d.crop, crop));
let key = (crop.map(|v| (v * 1000.0) as i32), sheet.width() as i32);
if !covered && pv.tried != Some(key) {
if now - pv.changed >= SETTLE {
want = Some((with_margin(crop), sheet.width()));
pv.tried = Some(key);
} else {
ui.ctx().request_repaint_after(std::time::Duration::from_secs_f64(SETTLE));
}
}
} else {
pv.detail = None;
// Fit discarded the texture; the same zoom must be able to request it again.
pv.tried = None;
}
}
Err(e) => {
ui.label(e);
@@ -252,26 +514,36 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, open: &mut bool) {
}
ui.add_space(4.0);
ui.horizontal(|ui| {
print = ui.button("Print...").clicked();
print = ui.add_enabled(!stale_request, egui::Button::new("Print...")).clicked();
close = ui.button("Close").clicked();
});
});
if let (Some((crop, width)), Ok(shown)) = (want, pv.shown.as_ref()) {
// A failure keeps the sheet as it is, and the part already drawn in detail, and is not
// tried again for this view.
if let Ok(detail) = render_detail(app, ctx, shown, crop, width) {
pv.detail = Some(detail);
}
ctx.request_repaint();
}
ctx.data_mut(|d| d.insert_temp(id, pv));
if crate::framework::escape_pressed(ctx) {
close = true;
}
if close || print {
*open = false;
}
let from_plot = ctx.data(|d| d.get_temp::<FromPlot>(egui::Id::unique(FROM_PLOT))).is_some();
let from_plot = from_plot(ctx).is_some();
if !*open {
ctx.data_mut(|d| {
d.remove::<Preview>(id);
d.remove::<FromPlot>(egui::Id::unique(FROM_PLOT));
d.remove::<PreviewRequest>(egui::Id::unique(FROM_PLOT));
});
}
if from_plot && !*open {
// Back to the Plot dialog with its settings; Print... plots them.
crate::managers::set_flag(ctx, crate::managers::PLOT_NOW, print);
// Back to the Plot dialog with its settings; Print... plots them (the dialog checks they
// are still its settings for the drawing shown).
crate::managers::set_flag(ctx, crate::managers::PLOT_NOW, print && !stale_request);
app.ui.dialog = Some("plot".into());
} else if print {
app.start("plot");
@@ -311,9 +583,9 @@ mod tests {
let ctx = egui::Context::default();
let mut png = Vec::new();
cadcraft_render::raster::write_rgba_png(&mut png, 1, 1, &[10, 20, 30, 255]).unwrap();
let texture = super::preview_texture(&ctx, &png).unwrap();
let texture = super::preview_texture(&ctx, &png, "test-preview").unwrap();
assert_eq!(texture.size(), [1, 1]);
assert!(super::preview_texture(&ctx, b"not a PNG").is_err());
assert!(super::preview_texture(&ctx, b"not a PNG", "test-preview").is_err());
}
#[test]
@@ -343,6 +615,129 @@ mod tests {
assert!(e.contains("not available yet"), "{e}");
}
use egui::{Rect, Vec2, pos2, vec2};
use super::{MAX_ZOOM, PanZoom, covers, visible_crop, with_margin};
/// The preview area the zoom tests use.
fn area() -> Rect {
Rect::from_min_size(pos2(10.0, 20.0), vec2(800.0, 600.0))
}
const IMAGE: Vec2 = vec2(1600.0, 1000.0);
/// The sheet fits the area and is centred until zoomed.
#[test]
fn the_sheet_fits_the_area_and_is_centred_until_zoomed() {
let r = PanZoom::default().image_rect(area(), IMAGE);
assert!((r.width() - 800.0).abs() < 1e-3 && (r.height() - 500.0).abs() < 1e-3, "fits by width: {r:?}");
assert!((r.center() - area().center()).length() < 1e-3);
}
/// Zooming keeps the image point under the pointer in place.
#[test]
fn zoom_keeps_the_point_under_the_pointer() {
let mut v = PanZoom::default();
let at = pos2(430.0, 330.0);
let r = v.image_rect(area(), IMAGE);
let u = ((at.x - r.min.x) / r.width(), (at.y - r.min.y) / r.height());
v.zoom_at(area(), IMAGE, at, 3.0);
assert!((v.zoom - 3.0).abs() < 1e-5);
let r = v.image_rect(area(), IMAGE);
let now = pos2(r.min.x + u.0 * r.width(), r.min.y + u.1 * r.height());
assert!((now - at).length() < 0.01, "the point under the pointer stayed: {now:?} vs {at:?}");
// And back out: the whole sheet again, centred.
v.zoom_at(area(), IMAGE, at, 1.0 / 3.0);
assert_eq!(v, PanZoom::default());
}
/// The zoom is limited and the sheet stays over the area.
#[test]
fn zoom_is_limited_and_the_sheet_stays_over_the_area() {
let mut v = PanZoom::default();
v.zoom_at(area(), IMAGE, area().center(), 1e6);
assert_eq!(v.zoom, MAX_ZOOM);
v.zoom_at(area(), IMAGE, area().center(), 1e-6);
assert_eq!(v.zoom, 1.0, "no further out than the whole sheet");
// Dragged far away, the sheet still covers the area along the axes where it is larger.
v.zoom_at(area(), IMAGE, area().center(), 4.0);
v.pan = vec2(1e6, -1e6);
v.clamp(area(), IMAGE);
let r = v.image_rect(area(), IMAGE);
assert!(
r.min.x <= area().min.x + 1e-3 && r.max.x >= area().max.x - 1e-3 && r.min.y <= area().min.y + 1e-3 && r.max.y >= area().max.y - 1e-3,
"{r:?}"
);
// Nonsense values change nothing or reset.
let before = v;
v.zoom_at(area(), IMAGE, area().center(), f32::NAN);
v.zoom_at(area(), IMAGE, area().center(), -2.0);
assert_eq!(v, before);
v.pan = vec2(f32::NAN, 0.0);
v.zoom = f32::INFINITY;
v.clamp(area(), IMAGE);
assert!(v.zoom == 1.0 && v.pan == Vec2::ZERO);
}
/// The part in view is what is drawn again in detail.
#[test]
fn the_visible_part_is_what_is_drawn_again_in_detail() {
// Whole sheet in view: all of it.
let whole = PanZoom::default().image_rect(area(), IMAGE);
assert_eq!(visible_crop(area(), whole), Some([0.0, 0.0, 1.0, 1.0]));
// Zoomed 4x on the centre: the middle eighth... of each side.
let mut v = PanZoom::default();
v.zoom_at(area(), IMAGE, area().center(), 4.0);
let c = visible_crop(area(), v.image_rect(area(), IMAGE)).unwrap();
assert!((c[0] - 0.375).abs() < 1e-4 && (c[2] - 0.625).abs() < 1e-4, "{c:?}");
assert!(c[1] > 0.0 && c[3] < 1.0 && c[1] < c[3]);
// The detail drawn covers it with a margin all round, within the sheet.
let d = with_margin(c);
assert!(covers(d, c) && !covers(c, d));
assert!(d.iter().all(|v| (0.0..=1.0).contains(v)));
assert_eq!(with_margin([0.0, 0.0, 1.0, 1.0]), [0.0, 0.0, 1.0, 1.0], "the margin stays inside the sheet");
// Nothing of the sheet in the area: no part.
let away = Rect::from_min_size(pos2(5000.0, 5000.0), vec2(100.0, 100.0));
assert_eq!(visible_crop(area(), away), None);
}
/// The red-looking pixels of a plotted PNG, and its size.
fn red_pixels(png: &[u8]) -> (usize, u32, u32) {
let img = image::load_from_memory_with_format(png, image::ImageFormat::Png).unwrap().to_rgba8();
let red = img.pixels().filter(|p| p.0[0] > 180 && p.0[1] < 90 && p.0[2] < 90).count();
(red, img.width(), img.height())
}
/// The preview draws the page setup's plot style table, and `None` overrides it.
#[test]
fn the_preview_draws_the_plot_style_table_of_the_page_setup() {
let (mut app, _) = app();
app.run("color", json!({ "color": 1 })).unwrap();
app.run("line", json!({ "points": [[0, 0], [100, 60]] })).unwrap();
app.run("mview", json!({ "layout": "Layout1" })).unwrap();
app.run("layout.set", json!({ "name": "Layout1" })).unwrap();
// The real plotter is called directly: the plot hook is global to the test process, which
// other tests replace.
let plot = |app: &CadApp, params: &serde_json::Value| {
cadcraft_io::plotter::plot(app.session.doc().unwrap(), &cadcraft_doc::Space::Paper("Layout1".into()), params).unwrap()
};
let crate::managers::PreviewRequest { params, info, .. } = crate::managers::current_preview(&app).unwrap();
assert!(info.starts_with("Layout1"), "{info}");
let (plain, w, h) = red_pixels(&plot(&app, &params));
assert!(plain > 50, "without a table the red line is drawn red ({plain} red pixels)");
// The page setup's table is what the preview shows, as it is what plots.
app.run("pagesetup", json!({ "layout": "Layout1", "plotStyleTable": "monochrome.ctb" })).unwrap();
let mut params = crate::managers::current_preview(&app).unwrap().params;
assert_eq!(red_pixels(&plot(&app, &params)).0, 0, "monochrome.ctb prints it black");
// The Plot dialog's "None" is sent as such, so it overrides the layout's own table.
params["plotStyleTable"] = json!("None");
assert!(red_pixels(&plot(&app, &params)).0 > 50, "None overrides the page setup's table");
// A crop is that part of the sheet, at the same scale.
params["crop"] = json!([0.25, 0.25, 0.75, 0.75]);
let (_, cw, ch) = red_pixels(&plot(&app, &params));
assert!((i64::from(cw) - i64::from(w) / 2).abs() <= 1 && (i64::from(ch) - i64::from(h) / 2).abs() <= 1, "{cw}x{ch} of {w}x{h}");
}
type Done = Box<dyn FnOnce(Option<String>) + Send>;
/// An app whose host shows its dialogs without waiting (macOS, #1527): the dialogs asked
@@ -518,4 +913,33 @@ mod tests {
assert_eq!(app.session.running.as_ref().map(|r| r.id.as_str()), Some("line"), "LINE was not cancelled");
assert!(status(&app).starts_with("APPLOAD: another command started"), "{:?}", app.status);
}
/// A preview the Plot dialog asked for in one drawing is not plotted with another drawing
/// shown since, and its Print... sends nothing back to the Plot dialog (#2171 review).
#[test]
fn a_plot_preview_is_bound_to_its_drawing() {
let (mut app, _) = app();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let request = crate::managers::PreviewRequest {
params: json!({ "layout": "Model", "output": "png", "resolution": 50 }),
info: "Model · A4".into(),
sheet_mm: egui::vec2(297.0, 210.0),
drawing: crate::managers::plot_drawing(&app),
};
super::preview_plot(&mut app, &ctx, request);
app.run("new", json!({})).unwrap();
let raw = egui::RawInput { screen_rect: Some(egui::Rect::from_min_size(egui::Pos2::ZERO, egui::vec2(1200.0, 900.0))), ..Default::default() };
let mut out = ctx.run_ui(raw, |ui| {
let mut open = true;
super::dialog(&mut app, &ui.ctx().clone(), &mut open);
});
out.textures_delta.clear();
let shown = ctx.data(|d| d.get_temp::<super::Preview>(egui::Id::unique("cc_plot_preview"))).and_then(|p| p.shown.err());
assert!(
shown.as_deref().is_some_and(|e| e.contains("another drawing")),
"the other drawing is not plotted with the preview's settings: {shown:?}"
);
assert!(super::stale(&app, super::from_plot(&ctx).as_ref()), "Print... is off");
}
}
-133
View File
@@ -1,133 +0,0 @@
//! DXF capture over the existing format hooks; no storage backend or filesystem authority.
use crate::{CadApp, file_providers::Action};
use cadcraft_engine::cmd::file::{self, SaveAs};
use serde_json::{Value, json};
pub(crate) fn save(app: &mut CadApp, save_as: bool) -> Result<Value, String> {
let result = capture(app, save_as);
if let Err(error) = &result {
app.session.echo(error.clone());
app.set_status(error.clone());
}
result
}
/// Queue a provider read through CadApp::run without creating a filesystem picker.
pub(crate) fn open_recent(app: &mut CadApp, params: &Value) -> Result<Value, String> {
let result = params
.get("resource")
.and_then(Value::as_str)
.ok_or_else(|| "a file provider resource ID is required".to_string())
.and_then(|resource| app.file_providers.request_open(resource))
.map(|request| json!({"pending":"fileProvider","requestId":request}));
if let Err(error) = &result {
app.session.echo(error.clone());
app.set_status(error.clone());
}
result
}
fn capture(app: &mut CadApp, save_as: bool) -> Result<Value, String> {
let host = app.file_providers.clone();
let state = app.session.state().map_err(|e| e.to_string())?;
if host.pending_for(state.uid) {
return Err("a provider save is already pending for this drawing".into());
}
if state.block_unsaved() {
return Err("save or discard Block Editor changes before saving with a provider".into());
}
let drawing = state.drawing();
// This single-file transfer does not upload external image or drawing bytes.
if has_external_files(drawing) {
return Err(
"DXF references external images or drawings; make a self-contained drawing before provider save (external files are not uploaded)".into(),
);
}
let mut name = host.bound_filename(state.uid).unwrap_or_else(|| match state.title.rsplit_once('.') {
Some((_, extension)) if extension.eq_ignore_ascii_case("dxf") => state.title.clone(),
Some((stem, extension)) if extension.eq_ignore_ascii_case("dwg") => format!("{stem}.dxf"),
_ => format!("{}.dxf", state.title),
});
if name.trim() == ".dxf" {
name = "Drawing.dxf".into();
}
let bytes = match file::write_as() {
Some(writer) => writer(drawing, &name, &SaveAs::default())?,
None => (file::io().ok_or("file formats are unavailable")?.write)(drawing, &name)?,
};
let request = host.begin(vec![state.clone()], state.uid, state.revision, name, bytes, save_as)?;
app.set_status("Choose where to save the DXF drawing");
Ok(json!({"pending":"fileProvider","requestId":request}))
}
pub(crate) fn tick(app: &mut CadApp) {
let host = app.file_providers.clone();
if !host.connected() {
return;
}
for action in host.take_actions() {
match action {
Action::Save { request, capture, status, resource } => {
let alive = app.session.docs.iter().any(|d| d.uid == capture.doc);
if status == "saved" {
for snapshot in &capture.snapshots {
if let Some(doc) = app.session.docs.iter_mut().find(|d| d.uid == snapshot.uid) {
doc.saved = snapshot.drawing().clone();
doc.path = None;
}
}
app.set_status("Drawing saved with file provider");
} else if status == "failed" {
app.set_status("File provider save failed; drawing remains unsaved");
}
host.finish_save(&request, &capture, &status, &resource, alive);
}
Action::Open { request, resource, name, bytes } => {
let result = open_resource(app, &resource, &name, &bytes);
if let Err(error) = &result {
app.open_failed(error);
}
host.finish_open(&request, &resource, &name, result);
}
}
}
host.refresh(app.session.docs.iter().map(|d| (d.uid, d.revision, d.title.clone(), d.is_dirty())).collect());
}
/// The same modeled dependency boundary applies before provider Save and Open. In particular,
/// provider bytes must not reach native OPEN's automatic IMAGE/XREF filesystem loaders.
fn has_external_files(drawing: &cadcraft_doc::Drawing) -> bool {
drawing
.model
.iter()
.chain(drawing.layouts.iter().flat_map(|layout| layout.entities.iter()))
.chain(drawing.blocks.values().flat_map(|block| block.entities.iter()))
.any(|entity| matches!(&entity.kind, cadcraft_doc::EntityKind::Image(image) if !image.path.is_empty()))
|| drawing.blocks.values().any(|block| block.xref_path.as_ref().is_some_and(|path| !path.is_empty()))
}
fn open_resource(app: &mut CadApp, resource: &str, name: &str, bytes: &[u8]) -> Result<u64, String> {
if let Some((index, uid)) =
app.file_providers.bound_document(resource).and_then(|uid| app.session.docs.iter().position(|doc| doc.uid == uid).map(|index| (index, uid)))
{
return app.run("document.switch", json!({"index":index})).map(|_| uid);
}
// Host admission already bounds these bytes. Preflight with the installed native decoder,
// before any document is opened or the unchanged native command follows external paths.
// The actual Open still runs through CadApp's existing command route and format hooks.
let hooks = file::io().ok_or("file formats are unavailable")?;
// `catch_unwind` only helps native builds: a panic aborts on wasm, where this bridge runs, so the
// readers must stay panic-free and nothing here may rely on recovering from one.
let drawing = std::panic::catch_unwind(|| (hooks.read)(bytes, name)).map_err(|_| "file provider drawing decoder failed".to_string())??;
if has_external_files(&drawing) {
return Err(
"DXF references external images or drawings; open a self-contained drawing with the file provider (external files are not loaded)".into(),
);
}
drop(drawing);
app.run("open", json!({"data":file::base64_encode(bytes),"name":name})).and_then(|value| {
app.opened(Ok(value));
app.session.state().map(|doc| doc.uid).map_err(|error| error.to_string())
})
}
#[cfg(test)]
mod tests;
@@ -1,210 +0,0 @@
#![allow(clippy::unwrap_used)]
use super::*;
use cadcraft_engine::Session;
fn pending() -> (CadApp, String, u64) {
let app = CadApp::new(Session::new(), crate::Services::default());
app.file_providers.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
app.file_providers.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
let doc = app.session.state().unwrap().clone();
let uid = doc.uid;
// Lifecycle fixture: a fake capture is isolated from the engine's process-global format hooks.
let request = app.file_providers.begin(vec![doc.clone()], uid, doc.revision, "Drawing.dxf".into(), vec![1], false).unwrap();
(app, request, uid)
}
#[test]
fn rejected_provider_save_is_reported_without_consuming_the_capture() {
let (mut app, _, uid) = pending();
let error = save(&mut app, false).unwrap_err();
assert!(error.contains("already pending"));
assert_eq!(app.status.as_ref().map(|(text, _)| text.as_str()), Some(error.as_str()));
assert_eq!(app.session.log.last(), Some(&error));
assert!(app.file_providers.pending_for(uid));
}
#[test]
fn ack_owns_its_document_and_does_not_clean_newer_edits() {
let (mut app, request, uid) = pending();
app.file_providers.resolve_dialog(&request, "provider", "Drawing.dxf").unwrap();
let doc = app.session.docs.iter_mut().find(|d| d.uid == uid).unwrap();
std::sync::Arc::make_mut(&mut doc.doc).handseed += 1;
app.session.new_drawing(false);
app.file_providers.result(request, "saved".into(), "drawing-1".into()).unwrap();
tick(&mut app);
assert!(app.session.docs.iter().find(|d| d.uid == uid).unwrap().is_dirty());
assert_eq!(app.file_providers.bound_document("drawing-1"), Some(uid));
}
#[test]
fn device_result_is_terminal_without_claiming_durable_storage() {
let (mut app, request, uid) = pending();
let doc = app.session.docs.iter_mut().find(|d| d.uid == uid).unwrap();
std::sync::Arc::make_mut(&mut doc.doc).handseed += 1;
app.file_providers.resolve_dialog(&request, "device", "Drawing.dxf").unwrap();
app.file_providers.result(request, "download".into(), String::new()).unwrap();
tick(&mut app);
assert!(app.session.docs.iter().find(|d| d.uid == uid).unwrap().is_dirty());
assert!(app.file_providers.bound_document("drawing-1").is_none());
}
#[test]
fn real_dxf_delivery_failure_preserves_the_owned_drawing_and_later_edits_through_retry() {
let mut app = CadApp::new(Session::new(), crate::Services::default());
app.run("line", json!({"points":[[0,0],[10,10]]})).unwrap();
let host = app.file_providers.clone();
host.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
host.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
let snapshot = app.session.state().unwrap().clone();
let uid = snapshot.uid;
let checkpoint = snapshot.saved.clone();
// Use the actual native drawing codec without mutating process-global engine hooks.
let bytes = cadcraft_io::write(&snapshot.doc, "Owned.dxf").unwrap();
assert_eq!(cadcraft_io::read(&bytes, "Owned.dxf").unwrap().model.len(), snapshot.doc.model.len());
let request = host.begin(vec![snapshot.clone()], uid, snapshot.revision, "Owned.dxf".into(), bytes, false).unwrap();
host.take_events();
host.resolve_dialog(&request, "provider", "Owned.dxf").unwrap();
app.run("line", json!({"points":[[20,20],[30,30]]})).unwrap();
let later_revision = app.session.state().unwrap().revision;
app.session.new_drawing(false);
let active = app.session.state().unwrap().uid;
assert!(host.publish_events_with(
|metadata, bytes| {
assert_eq!(metadata["type"], "save");
assert_eq!(metadata["requestId"], request);
assert!(bytes.is_some_and(|bytes| !bytes.is_empty()));
Err("synthetic native delivery exception")
},
|_| {},
));
assert!(host.pending_for(uid));
tick(&mut app);
let owned = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap();
assert_eq!(owned.revision, later_revision);
assert!(owned.is_dirty() && std::sync::Arc::ptr_eq(&owned.saved, &checkpoint));
assert_eq!(app.session.state().unwrap().uid, active);
assert!(app.status.as_ref().unwrap().0.contains("File provider save failed"));
assert!(host.result(request.clone(), "saved".into(), "late".into()).is_err());
let mut failed = 0;
assert!(!host.publish_events_with(
|metadata, _| {
assert_eq!(metadata["type"], "saveFailed");
assert_eq!(metadata["requestId"], request);
assert_eq!(metadata["documentId"], uid.to_string());
failed += 1;
Ok::<(), &str>(())
},
|_| {},
));
assert_eq!(failed, 1);
assert!(!host.busy());
let retry_snapshot = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap().clone();
let bytes = cadcraft_io::write(&retry_snapshot.doc, "Owned.dxf").unwrap();
let retry = host.begin(vec![retry_snapshot.clone()], uid, retry_snapshot.revision, "Owned.dxf".into(), bytes, false).unwrap();
host.take_events();
host.resolve_dialog(&retry, "provider", "Owned.dxf").unwrap();
assert!(!host.publish_events_with(
|metadata, bytes| {
assert_eq!(metadata["requestId"], retry);
assert_eq!(cadcraft_io::read(&bytes.unwrap(), "Owned.dxf").unwrap().model.len(), retry_snapshot.doc.model.len());
Ok::<(), &str>(())
},
|_| {},
));
let index = app.session.docs.iter().position(|doc| doc.uid == uid).unwrap();
app.run("document.switch", json!({"index":index})).unwrap();
app.run("line", json!({"points":[[40,40],[50,50]]})).unwrap();
let current_revision = app.session.state().unwrap().revision;
let back = app.session.docs.iter().position(|doc| doc.uid == active).unwrap();
app.run("document.switch", json!({"index":back})).unwrap();
host.result(retry.clone(), "saved".into(), "file-1".into()).unwrap();
tick(&mut app);
let owned = app.session.docs.iter().find(|doc| doc.uid == uid).unwrap();
assert_eq!(owned.revision, current_revision);
assert!(owned.is_dirty() && std::sync::Arc::ptr_eq(&owned.saved, &retry_snapshot.doc));
assert_eq!(app.session.state().unwrap().uid, active);
assert_eq!(host.bound_document("file-1"), Some(uid));
assert_eq!(host.take_events()[0].metadata["type"], "saved");
assert!(!host.busy());
}
fn recent_provider_app() -> CadApp {
let app = CadApp::new(Session::new(), crate::Services::default());
app.file_providers.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
let connection = app.file_providers.connect("test".into(), "Test storage".into(), "account".into()).unwrap();
app.file_providers
.set_resources(
&connection,
vec![
crate::file_providers::Resource { id: "owned".into(), name: "Owned.dxf".into(), updated_at: String::new() },
crate::file_providers::Resource { id: "other".into(), name: "Other.dxf".into(), updated_at: String::new() },
],
)
.unwrap();
app.file_providers.take_events();
app
}
#[test]
fn provider_recent_command_queues_only_the_selected_resource_without_retargeting_the_drawing() {
let mut app = recent_provider_app();
let before = app.session.state().unwrap().clone();
let local = app.ui.recent_files.clone();
assert!(crate::menus::is_ui_command(crate::menus::PROVIDER_RECENT_OPEN));
let result = app.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap();
assert_eq!(result["pending"], "fileProvider");
let events = app.file_providers.take_events();
assert_eq!(events.len(), 1);
assert_eq!(events[0].metadata["type"], "openRequested");
assert_eq!(events[0].metadata["resourceId"], "owned");
assert_eq!(events[0].metadata["requestId"], result["requestId"]);
let after = app.session.state().unwrap();
assert_eq!((after.uid, after.revision), (before.uid, before.revision));
assert!(std::sync::Arc::ptr_eq(&after.doc, &before.doc));
assert_eq!(after.path, before.path);
assert_eq!(app.ui.recent_files, local);
}
#[test]
fn provider_recent_command_backpressure_remains_in_status_and_command_history() {
let mut app = recent_provider_app();
let mut full = false;
for _ in 0..128 {
if app.file_providers.request_open("owned").is_err() {
full = true;
break;
}
app.file_providers.take_events();
}
assert!(full, "the fixture must reach the actual bounded read capacity");
let before = app.session.state().unwrap().clone();
let error = app.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap_err();
assert!(app.file_providers.take_events().is_empty(), "a refused command cannot publish a partial read");
let ctx = egui::Context::default();
let mut output = ctx.run_pass(egui::RawInput::default(), |ctx| app.logic(ctx));
output.textures_delta.clear();
assert_eq!(app.status.as_ref().map(|(text, _)| text.as_str()), Some(error.as_str()));
assert_eq!(app.session.log.last(), Some(&error));
assert_eq!((app.session.state().unwrap().uid, app.session.state().unwrap().revision), (before.uid, before.revision));
}
#[test]
fn provider_recent_command_rejects_malformed_and_disabled_requests_without_opening_files() {
let mut app = CadApp::new(Session::new(), crate::Services::default());
let before = app.session.state().unwrap().clone();
for params in [Value::Null, json!({}), json!({"resource":42}), json!({"resource":""}), json!({"resource":"owned"})] {
assert!(app.run(crate::menus::PROVIDER_RECENT_OPEN, params).is_err());
assert!(!app.file_providers.enabled());
assert!(app.file_providers.take_events().is_empty());
assert_eq!((app.session.state().unwrap().uid, app.session.state().unwrap().revision), (before.uid, before.revision));
assert!(std::sync::Arc::ptr_eq(&app.session.state().unwrap().doc, &before.doc));
}
let mut connected = recent_provider_app();
let before = connected.session.state().unwrap().clone();
let connection = connected.file_providers.snapshot()["connectionId"].clone();
connected.file_providers.set_enabled(false).unwrap();
connected.file_providers.take_events();
let error = connected.run(crate::menus::PROVIDER_RECENT_OPEN, json!({"resource":"owned"})).unwrap_err();
assert!(connected.file_providers.connected() && !connected.file_providers.enabled());
assert_eq!(connected.file_providers.snapshot()["connectionId"], connection);
assert!(connected.file_providers.take_events().is_empty());
assert!(std::sync::Arc::ptr_eq(&connected.session.state().unwrap().doc, &before.doc));
assert_eq!(connected.session.log.last(), Some(&error));
}
-541
View File
@@ -1,541 +0,0 @@
//! Optional same-origin storage capability. No provider is enabled by default.
//!
//! Requests own immutable native project captures. A host result never selects a live tab,
//! revision, filesystem path or account. This module contains no storage or authentication.
use cadcraft_engine::DocState;
use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::collections::{HashMap, HashSet, VecDeque};
use std::sync::{Arc, Mutex, MutexGuard};
const MAX_BYTES: usize = 80 * 1024 * 1024;
const MAX_PENDING: usize = 16;
const MAX_EVENTS: usize = 64;
const MAX_RESOURCES: usize = 100;
const EXTENSION: &str = ".dxf";
#[derive(Clone, Debug, Deserialize, Serialize, PartialEq, Eq)]
#[serde(rename_all = "camelCase", deny_unknown_fields)]
pub struct Resource {
pub id: String,
pub name: String,
#[serde(default)]
pub updated_at: String,
}
pub struct Event {
pub metadata: Value,
pub bytes: Option<Vec<u8>>,
}
impl Event {
fn terminal(&self) -> bool {
matches!(
self.metadata.get("type").and_then(Value::as_str),
Some("saved" | "downloaded" | "saveCancelled" | "saveFailed" | "opened" | "openFailed" | "openCancelled")
)
}
}
#[derive(Clone, PartialEq, Eq)]
struct Identity {
provider_id: String,
label: String,
namespace: String,
}
/// The exact states encoded at Save, including a main document's branch tabs where applicable.
pub(crate) struct Capture {
pub doc: u64,
pub revision: u64,
pub snapshots: Vec<DocState>,
pub name: String,
intent: String,
destination: String,
bytes: Option<Vec<u8>>,
}
pub(crate) enum Action {
Save { request: String, capture: Capture, status: String, resource: String },
Open { request: String, resource: String, name: String, bytes: Vec<u8> },
}
#[derive(Clone, Copy)]
enum TerminalOwner {
Open,
Save,
}
#[derive(Clone)]
struct Terminal {
request: String,
metadata: Value,
owner: TerminalOwner,
}
#[derive(Default)]
struct State {
provider: Option<Identity>,
enabled: bool,
nonce: String,
serial: u64,
connection: String,
resources: Vec<Resource>,
bindings: HashMap<u64, String>,
names: HashMap<u64, String>,
dialogs: HashMap<String, Capture>,
pending: HashMap<String, Capture>,
// Keep every captured document alias owned until its terminal event can be queued.
finishing_saves: HashMap<String, Vec<u64>>,
opens: HashMap<String, String>,
queued_opens: HashSet<String>,
actions: Vec<Action>,
// Only captures already admitted in dialogs/pending enter this inbox: at most 16, no bytes.
delivery_failures: Vec<Action>,
events: Vec<Event>,
// At most MAX_PENDING saves plus MAX_PENDING reads; never stores transfer bytes.
finished: VecDeque<Terminal>,
publishing_terminals: usize,
documents: Value,
}
impl State {
fn busy(&self) -> bool {
!self.dialogs.is_empty()
|| !self.pending.is_empty()
|| !self.finishing_saves.is_empty()
|| !self.opens.is_empty()
|| !self.actions.is_empty()
|| !self.delivery_failures.is_empty()
|| !self.finished.is_empty()
|| self.events.iter().any(Event::terminal)
|| self.publishing_terminals != 0
}
fn next(&mut self, kind: &str) -> Result<String, String> {
if self.nonce.is_empty() {
return Err("file provider session is not initialized".into());
}
self.serial = self.serial.checked_add(1).ok_or("file provider request counter exhausted")?;
Ok(format!("{}-{kind}-{}", self.nonce, self.serial))
}
fn event(&mut self, mut metadata: Value, bytes: Option<Vec<u8>>) {
if let (Some(provider), Some(fields)) = (&self.provider, metadata.as_object_mut()) {
fields.insert("providerId".into(), provider.provider_id.clone().into());
fields.insert("namespace".into(), provider.namespace.clone().into());
fields.insert("connectionId".into(), self.connection.clone().into());
}
self.events.push(Event { metadata, bytes });
}
fn retained_bytes(&self) -> usize {
let captures = self.dialogs.values().chain(self.pending.values()).map(|p| p.bytes.as_ref().map_or(0, Vec::len));
let events = self.events.iter().map(|e| e.bytes.as_ref().map_or(0, Vec::len));
let actions = self.actions.iter().chain(&self.delivery_failures).map(|a| match a {
Action::Open { bytes, .. } => bytes.len(),
_ => 0,
});
captures.chain(events).chain(actions).fold(0, usize::saturating_add)
}
fn pending_for(&self, doc: u64) -> bool {
self.dialogs.values().chain(self.pending.values()).any(|c| c.snapshots.iter().any(|d| d.uid == doc))
|| self.finishing_saves.values().any(|aliases| aliases.contains(&doc))
|| self.actions.iter().any(|a| matches!(a, Action::Save { capture, .. } if capture.snapshots.iter().any(|d| d.uid == doc)))
}
fn flush_finished(&mut self) {
while self.events.len() < MAX_EVENTS {
let Some(terminal) = self.finished.pop_front() else { break };
self.event(terminal.metadata, None);
match terminal.owner {
TerminalOwner::Open => {
self.opens.remove(&terminal.request);
self.queued_opens.remove(&terminal.request);
}
TerminalOwner::Save => {
self.finishing_saves.remove(&terminal.request);
}
}
}
}
fn take_events(&mut self) -> Vec<Event> {
let events = std::mem::take(&mut self.events);
self.flush_finished();
if events.is_empty() { std::mem::take(&mut self.events) } else { events }
}
fn fail_delivery(&mut self, metadata: &Value) {
let Some(request) = metadata.get("requestId").and_then(Value::as_str) else { return };
match metadata.get("type").and_then(Value::as_str) {
Some(kind @ ("save" | "saveDialog")) => {
let capture = if kind == "save" { self.pending.remove(request) } else { self.dialogs.remove(request) };
if let Some(mut capture) = capture {
capture.bytes = None;
self.finishing_saves.insert(request.into(), capture.snapshots.iter().map(|doc| doc.uid).collect());
self.delivery_failures.push(Action::Save { request: request.into(), capture, status: "failed".into(), resource: String::new() });
}
}
Some("openRequested") if !self.queued_opens.contains(request) => {
if let Some(resource) = self.opens.get(request).cloned() {
// The terminal can wait behind a full event queue. Reject late payloads
// now, while retaining the read's account owner until it can be queued.
self.queued_opens.insert(request.into());
self.finished.push_back(Terminal {
request: request.into(),
metadata: json!({"type":"openFailed","requestId":request,"resourceId":resource,"error":"file-provider event delivery failed"}),
owner: TerminalOwner::Open,
});
self.flush_finished();
}
}
_ => {}
}
}
}
#[derive(Clone, Default)]
pub struct Host(Arc<Mutex<State>>);
struct PublishingBatch {
host: Host,
terminals: usize,
}
impl Drop for PublishingBatch {
fn drop(&mut self) {
let mut state = self.host.state();
state.publishing_terminals = state.publishing_terminals.saturating_sub(self.terminals);
}
}
impl Host {
fn state(&self) -> MutexGuard<'_, State> {
self.0.lock().unwrap_or_else(std::sync::PoisonError::into_inner)
}
pub fn set_session(&self, nonce: String) -> Result<(), String> {
let mut s = self.state();
if !s.nonce.is_empty() || s.provider.is_some() || !valid_id(&nonce) || nonce.len() < 16 {
return Err("invalid or already initialized file provider session".into());
}
s.nonce = nonce;
Ok(())
}
pub fn connect(&self, provider_id: String, label: String, namespace: String) -> Result<String, String> {
if !valid_id(&provider_id) || !valid_label(&label) || !valid_id(&namespace) {
return Err("invalid file provider identity".into());
}
let mut s = self.state();
let identity = Identity { provider_id, label, namespace };
if let Some(current) = &s.provider {
return if *current == identity { Ok(s.connection.clone()) } else { Err("unregister before changing provider or account".into()) };
}
s.connection = s.next("connection")?;
s.provider = Some(identity);
s.enabled = true;
Ok(s.connection.clone())
}
pub fn disconnect(&self) -> Result<(), String> {
let mut s = self.state();
if s.busy() {
return Err("finish or cancel pending operations and consume completion events before unregistering".into());
}
s.provider = None;
s.enabled = false;
s.connection.clear();
s.resources.clear();
s.bindings.clear();
s.names.clear();
s.events.clear();
s.documents = Value::Null;
Ok(())
}
pub fn connected(&self) -> bool {
self.state().provider.is_some()
}
pub fn enabled(&self) -> bool {
let s = self.state();
s.provider.is_some() && s.enabled
}
pub fn set_enabled(&self, enabled: bool) -> Result<(), String> {
let mut s = self.state();
if s.provider.is_none() {
return Err("file provider is not connected".into());
}
s.enabled = enabled;
Ok(())
}
pub fn busy(&self) -> bool {
self.state().busy()
}
pub fn pending_for(&self, doc: u64) -> bool {
self.state().pending_for(doc)
}
pub fn bound_document(&self, resource: &str) -> Option<u64> {
self.state().bindings.iter().find(|(_, r)| r.as_str() == resource).map(|(d, _)| *d)
}
pub fn bound_filename(&self, doc: u64) -> Option<String> {
self.state().names.get(&doc).cloned()
}
/// Captures are produced synchronously by the editor before this event is issued.
pub(crate) fn begin(
&self,
snapshots: Vec<DocState>,
doc: u64,
revision: u64,
name: String,
bytes: Vec<u8>,
save_as: bool,
) -> Result<String, String> {
let mut s = self.state();
if s.provider.is_none()
|| !s.enabled
|| !valid_native_name(&name)
|| bytes.is_empty()
|| bytes.len() > MAX_BYTES
|| s.retained_bytes().saturating_add(bytes.len()) > MAX_BYTES
|| s.pending_for(doc)
|| s.dialogs.len() + s.pending.len() + s.finishing_saves.len() >= MAX_PENDING
|| s.events.len() >= MAX_EVENTS
|| !snapshots.iter().any(|snapshot| snapshot.uid == doc)
{
return Err("provider unavailable, a save is pending, or capture exceeds 80 MiB".into());
}
let request = s.next("dialog")?;
let intent = if save_as { "saveAs" } else { "save" }.to_string();
s.event(json!({"type":"saveDialog","requestId":request,"documentId":doc.to_string(),"revision":revision.to_string(),"intent":intent,"filename":name}), None);
s.dialogs.insert(request.clone(), Capture { doc, revision, snapshots, name, intent, destination: String::new(), bytes: Some(bytes) });
Ok(request)
}
pub fn resolve_dialog(&self, request: &str, destination: &str, name: &str) -> Result<(), String> {
if !matches!(destination, "provider" | "device" | "cancel") || (destination != "cancel" && !valid_native_name(name)) {
return Err("choose provider, device or cancel and a native project filename".into());
}
let mut s = self.state();
if s.events.len() >= MAX_EVENTS {
return Err("provider event queue is full".into());
}
let mut capture = s.dialogs.remove(request).ok_or("unknown or completed save dialog")?;
if destination == "cancel" {
capture.bytes = None;
s.finishing_saves.insert(request.into(), capture.snapshots.iter().map(|doc| doc.uid).collect());
s.actions.push(Action::Save { request: request.into(), capture, status: "cancel".into(), resource: String::new() });
return Ok(());
}
capture.name = name.into();
capture.destination = destination.into();
let resource = if capture.intent == "save" { s.bindings.get(&capture.doc).cloned() } else { None };
let bytes = capture.bytes.take();
s.event(json!({"type":"save","requestId":request,"documentId":capture.doc.to_string(),"revision":capture.revision.to_string(),"intent":capture.intent,"filename":name,"resourceId":resource,"destination":destination}), bytes);
s.pending.insert(request.into(), capture);
Ok(())
}
pub fn result(&self, request: String, status: String, resource: String) -> Result<(), String> {
if !matches!(status.as_str(), "saved" | "download" | "failed" | "cancel") || (!resource.is_empty() && !valid_id(&resource)) {
return Err("invalid provider result".into());
}
let mut s = self.state();
let capture = s.pending.get(&request).ok_or("unknown or completed save request")?;
if (status == "saved" && (capture.destination != "provider" || !valid_id(&resource)))
|| (status == "download" && capture.destination != "device")
{
return Err("result does not match the chosen destination".into());
}
if status == "saved" && s.bindings.iter().any(|(doc, id)| *doc != capture.doc && *id == resource) {
return Err("resource is bound to another open document".into());
}
if status == "saved" && capture.intent == "saveAs" && s.bindings.get(&capture.doc) == Some(&resource) {
return Err("Save As must produce a distinct resource".into());
}
if s.actions.len() >= MAX_PENDING {
return Err("provider command queue is full".into());
}
let capture = s.pending.remove(&request).ok_or("unknown save request")?;
s.finishing_saves.insert(request.clone(), capture.snapshots.iter().map(|doc| doc.uid).collect());
s.actions.push(Action::Save { request, capture, status, resource });
Ok(())
}
pub fn set_resources(&self, connection: &str, resources: Vec<Resource>) -> Result<(), String> {
let mut seen = HashSet::new();
if resources.len() > MAX_RESOURCES
|| resources.iter().any(|r| !valid_id(&r.id) || !valid_native_name(&r.name) || r.updated_at.len() > 100 || !seen.insert(r.id.clone()))
{
return Err("invalid native project resource list".into());
}
let mut s = self.state();
if s.provider.is_none() || s.connection != connection {
return Err("resource list belongs to another connection".into());
}
s.resources = resources;
Ok(())
}
pub fn request_open(&self, resource: &str) -> Result<String, String> {
let mut s = self.state();
if !s.enabled
|| s.provider.is_none()
|| s.opens.len() >= MAX_PENDING
|| s.events.len() >= MAX_EVENTS
|| !s.resources.iter().any(|r| r.id == resource)
{
return Err("resource is unavailable in the current provider account".into());
}
let request = s.next("open")?;
s.opens.insert(request.clone(), resource.into());
s.event(json!({"type":"openRequested","requestId":request,"resourceId":resource}), None);
Ok(request)
}
pub fn open(&self, request: String, name: String, bytes: Vec<u8>) -> Result<(), String> {
if !valid_native_name(&name) || bytes.is_empty() || bytes.len() > MAX_BYTES {
return Err("invalid native project resource".into());
}
let mut s = self.state();
if s.actions.len() >= MAX_PENDING || s.retained_bytes().saturating_add(bytes.len()) > MAX_BYTES {
return Err("provider command queue is full".into());
}
if s.queued_opens.contains(&request) {
return Err("open response already queued".into());
}
let resource = s.opens.get(&request).cloned().ok_or("unknown or completed open request")?;
s.queued_opens.insert(request.clone());
s.actions.push(Action::Open { request, resource, name, bytes });
Ok(())
}
pub fn cancel_open(&self, request: String, error: String) -> Result<(), String> {
if error.len() > 1024 {
return Err("invalid open result".into());
}
let mut s = self.state();
if s.queued_opens.contains(&request) {
return Err("open response already queued".into());
}
if s.events.len() >= MAX_EVENTS {
return Err("provider event queue is full".into());
}
let resource = s.opens.remove(&request).ok_or("unknown or completed open request")?;
s.event(json!({"type":if error.is_empty(){"openCancelled"}else{"openFailed"},"requestId":request,"resourceId":resource,"error":error}), None);
Ok(())
}
pub(crate) fn take_actions(&self) -> Vec<Action> {
let mut state = self.state();
let mut actions = std::mem::take(&mut state.actions);
actions.append(&mut state.delivery_failures);
actions
}
pub fn take_events(&self) -> Vec<Event> {
self.state().take_events()
}
/// Failed publication consumes only a still-owned request, never an accepted callback.
/// Recovery actions retain captured aliases until the real application produces a terminal.
/// Returns whether the platform must request a repaint for failure consumption.
pub fn publish_events_with<E>(&self, mut dispatch: impl FnMut(&Value, Option<Vec<u8>>) -> Result<(), E>, mut on_error: impl FnMut(E)) -> bool {
let mut failed = false;
for _ in 0..2 {
let (events, _publishing) = {
let mut state = self.state();
let events = state.take_events();
let terminals = events.iter().filter(|event| event.terminal()).count();
state.publishing_terminals = state.publishing_terminals.saturating_add(terminals);
(events, PublishingBatch { host: self.clone(), terminals })
};
if events.is_empty() {
break;
}
for event in events {
if let Err(error) = dispatch(&event.metadata, event.bytes) {
failed = true;
self.state().fail_delivery(&event.metadata);
on_error(error);
}
}
}
failed
}
pub fn snapshot(&self) -> Value {
let s = self.state();
json!({"protocolVersion":1,"enabled":s.enabled && s.provider.is_some(),"provider":s.provider.as_ref().map(|p|json!({"id":p.provider_id,"label":p.label,"namespace":p.namespace})),"connectionId":s.connection,"resources":s.resources,"documents":s.documents,"pending":s.busy()})
}
pub(crate) fn refresh(&self, docs: Vec<(u64, u64, String, bool)>) {
let mut s = self.state();
let live: HashSet<_> = docs.iter().map(|d| d.0).collect();
s.bindings.retain(|id, _| live.contains(id));
s.names.retain(|id, _| live.contains(id));
s.documents = json!(docs.into_iter().map(|(id,rev,name,dirty)|json!({"id":id.to_string(),"revision":rev.to_string(),"name":name,"dirty":dirty,"resourceId":s.bindings.get(&id)})).collect::<Vec<_>>());
}
pub(crate) fn finish_save(&self, request: &str, capture: &Capture, status: &str, resource: &str, alive: bool) {
let mut s = self.state();
if !s.finishing_saves.get(request).is_some_and(|aliases| aliases.contains(&capture.doc))
|| s.finished.iter().any(|terminal| terminal.request == request)
{
return;
}
if status == "saved" {
if alive {
s.bindings.insert(capture.doc, resource.into());
s.names.insert(capture.doc, capture.name.clone());
}
s.resources.retain(|r| r.id != resource);
s.resources.insert(0, Resource { id: resource.into(), name: capture.name.clone(), updated_at: String::new() });
s.resources.truncate(MAX_RESOURCES);
}
let metadata = json!({"type":match status { "saved"=>"saved", "download"=>"downloaded", "cancel"=>"saveCancelled", _=>"saveFailed" },"requestId":request,"documentId":capture.doc.to_string(),"revision":capture.revision.to_string(),"resourceId":resource,"filename":capture.name,"documentOpen":alive});
s.finished.push_back(Terminal { request: request.into(), metadata, owner: TerminalOwner::Save });
s.flush_finished();
}
pub(crate) fn finish_open(&self, request: &str, resource: &str, name: &str, result: Result<u64, String>) {
let mut s = self.state();
if !s.opens.get(request).is_some_and(|owned| owned == resource)
|| !s.queued_opens.contains(request)
|| s.finished.iter().any(|terminal| terminal.request == request)
{
return;
}
let metadata = match result {
Ok(doc) => {
s.bindings.insert(doc, resource.into());
s.names.insert(doc, name.into());
json!({"type":"opened","requestId":request,"resourceId":resource,"documentId":doc.to_string()})
}
Err(error) => json!({"type":"openFailed","requestId":request,"resourceId":resource,"error":bounded_error(&error)}),
};
s.finished.push_back(Terminal { request: request.into(), metadata, owner: TerminalOwner::Open });
s.flush_finished();
}
/// Draw the recent lists and return a selected resource; the caller dispatches its command.
pub fn recent_ui(&self, ui: &mut egui::Ui) -> Option<String> {
let selected = self.provider_recent_ui(ui);
self.device_recent_ui(ui);
selected
}
pub(crate) fn provider_recent_ui(&self, ui: &mut egui::Ui) -> Option<String> {
let (label, resources, enabled) = {
let s = self.state();
(s.provider.as_ref().map(|p| p.label.clone()), s.resources.clone(), s.enabled)
};
let label = label.filter(|_| enabled)?;
ui.add_space(12.0);
ui.strong(format!("Recent files — {label}"));
if resources.is_empty() {
ui.weak("No recent files from this provider");
}
let mut selected = None;
for resource in resources {
if ui.button(&resource.name).on_hover_text(&resource.updated_at).clicked() {
selected = Some(resource.id);
ui.ctx().request_repaint();
}
}
selected
}
pub(crate) fn device_recent_ui(&self, ui: &mut egui::Ui) {
if self.enabled() {
ui.separator();
ui.weak("Recent files on this device");
}
}
}
fn bounded_error(message: &str) -> String {
let mut error = String::new();
for ch in message.chars().filter(|ch| !ch.is_control()) {
if error.len().saturating_add(ch.len_utf8()) > 1024 {
break;
}
error.push(ch);
}
error
}
fn valid_id(value: &str) -> bool {
!value.is_empty() && value.len() <= 160 && value.bytes().all(|b| b.is_ascii_alphanumeric() || matches!(b, b'-' | b'_' | b'.' | b':'))
}
fn valid_label(value: &str) -> bool {
!value.trim().is_empty() && value.len() <= 100 && !value.chars().any(char::is_control)
}
fn valid_native_name(value: &str) -> bool {
!value.trim().is_empty()
&& value.len() <= 255
&& !value.chars().any(|c| c.is_control() || matches!(c, '/' | '\\'))
&& value.to_ascii_lowercase().ends_with(EXTENSION)
}
#[cfg(test)]
mod tests;
-518
View File
@@ -1,518 +0,0 @@
#![allow(clippy::unwrap_used)]
use super::*;
use cadcraft_engine::Session;
fn host() -> Host {
let h = Host::default();
h.set_session("0123456789abcdef0123456789abcdef".into()).unwrap();
h.connect("test".into(), "Test storage".into(), "account-a".into()).unwrap();
h
}
fn capture(h: &Host, save_as: bool) -> (String, u64) {
let mut session = Session::new();
session.execute("new", &json!({})).unwrap();
let doc = session.state().unwrap().clone();
let uid = doc.uid;
(h.begin(vec![doc.clone()], uid, doc.revision, "example.dxf".into(), vec![1, 2, 3], save_as).unwrap(), uid)
}
#[test]
fn off_until_explicit_registration_and_session_is_single_use() {
let h = Host::default();
assert!(!h.enabled());
assert!(!h.connected());
assert!(h.connect("test".into(), "Test".into(), "a".into()).is_err());
assert!(host().set_session("0123456789abcdef".into()).is_err());
}
#[test]
fn each_save_has_a_choice_and_cancel_never_acknowledges_a_document() {
let h = host();
let (request, uid) = capture(&h, false);
assert_eq!(h.take_events()[0].metadata["type"], "saveDialog");
assert!(h.pending_for(uid));
h.resolve_dialog(&request, "cancel", "").unwrap();
let actions = h.take_actions();
assert!(matches!(&actions[..],[Action::Save { status, .. }] if status == "cancel"));
assert!(h.state().bindings.is_empty());
assert!(h.result(request, "saved".into(), "file".into()).is_err());
}
#[test]
fn durable_ack_owns_its_capture_and_is_single_use() {
let h = host();
let (request, uid) = capture(&h, false);
h.take_events();
assert!(h.disconnect().is_err());
h.resolve_dialog(&request, "provider", "durable.dxf").unwrap();
let event = h.take_events().remove(0);
assert_eq!(event.metadata["type"], "save");
assert_eq!(event.bytes, Some(vec![1, 2, 3]));
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
assert!(h.result(request, "saved".into(), "file-1".into()).is_err());
assert!(matches!(h.take_actions().as_slice(),[Action::Save { capture,resource,.. }] if capture.doc==uid && resource=="file-1"));
}
#[test]
fn replies_cannot_cross_the_chosen_destination_or_an_open_resource_alias() {
let h = host();
let (request, uid) = capture(&h, false);
h.resolve_dialog(&request, "device", "local.dxf").unwrap();
assert!(h.result(request.clone(), "saved".into(), "remote".into()).is_err());
h.result(request, "download".into(), String::new()).unwrap();
h.take_actions();
h.take_events();
let (request, _) = capture(&h, false);
h.state().bindings.insert(uid, "already-open".into());
h.resolve_dialog(&request, "provider", "new.dxf").unwrap();
assert!(h.result(request, "saved".into(), "already-open".into()).is_err());
}
#[test]
fn unregister_clears_cached_account_documents_before_reconnect() {
let h = host();
h.state().bindings.insert(42, "account-a-resource".into());
h.state().names.insert(42, "Account A.dxf".into());
h.refresh(vec![(42, 1, "Account A.dxf".into(), false)]);
assert_eq!(h.snapshot()["documents"][0]["resourceId"], "account-a-resource");
h.disconnect().unwrap();
let disconnected = h.snapshot();
assert!(disconnected["documents"].is_null());
assert!(disconnected["resources"].as_array().unwrap().is_empty());
assert!(h.state().bindings.is_empty());
assert!(h.state().names.is_empty());
h.connect("test".into(), "Test storage".into(), "account-b".into()).unwrap();
assert!(h.snapshot()["documents"].is_null());
}
#[test]
fn resource_reads_and_lists_are_scoped_to_current_account_connection() {
let h = host();
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
let rows = vec![Resource { id: "file-1".into(), name: "remote.dxf".into(), updated_at: String::new() }];
assert!(h.set_resources("another-connection", rows.clone()).is_err());
h.set_resources(&connection, rows).unwrap();
assert!(h.request_open("unknown").is_err());
let request = h.request_open("file-1").unwrap();
assert!(h.open("forged".into(), "remote.dxf".into(), vec![1]).is_err());
h.open(request.clone(), "remote.dxf".into(), vec![1]).unwrap();
assert!(h.open(request.clone(), "remote.dxf".into(), vec![1]).is_err());
assert!(h.cancel_open(request.clone(), String::new()).is_err());
assert!(h.disconnect().is_err());
h.take_actions();
h.finish_open(&request, "file-1", "remote.dxf", Err("invalid archive".into()));
assert!(h.disconnect().is_err());
let completion = h.take_events();
assert!(completion.iter().any(|event| event.metadata["type"] == "openFailed" && event.metadata["requestId"] == request));
h.disconnect().unwrap();
let next = h.connect("test".into(), "Test storage".into(), "account-b".into()).unwrap();
assert_ne!(connection, next);
assert!(h.set_resources(&connection, Vec::new()).is_err());
assert!(h.snapshot()["resources"].as_array().unwrap().is_empty());
}
#[test]
fn names_are_native_filenames_and_resource_ids_are_opaque() {
assert!(valid_native_name("with accents áé.dxf"));
assert!(!valid_native_name("../project.dxf"));
assert!(!valid_native_name("project.svg"));
assert!(!valid_id("../../project"));
assert!(!valid_native_name("project.dxf\0"));
}
#[test]
fn disabled_provider_does_not_discard_a_capture_already_awaiting_ack() {
let h = host();
let (request, uid) = capture(&h, false);
h.set_enabled(false).unwrap();
assert!(!h.enabled());
assert!(h.pending_for(uid));
h.resolve_dialog(&request, "provider", "in-flight.dxf").unwrap();
h.result(request, "saved".into(), "file-1".into()).unwrap();
assert!(matches!(h.take_actions().as_slice(),[Action::Save { status,.. }] if status=="saved"));
}
fn fill_transport_event_queue(h: &Host) {
let mut state = h.state();
for ordinal in state.events.len()..MAX_EVENTS {
state.event(json!({"type":"queued","ordinal":ordinal}), None);
}
}
fn terminal_resource(h: &Host) -> String {
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
let filename = format!("Remote{EXTENSION}");
h.set_resources(&connection, vec![Resource { id: "file-1".into(), name: filename.clone(), updated_at: String::new() }]).unwrap();
filename
}
#[test]
fn full_event_queue_retains_open_terminals_until_ordered_drain() {
let h = host();
let filename = terminal_resource(&h);
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
let success = h.request_open("file-1").unwrap();
h.open(success.clone(), filename.clone(), vec![1]).unwrap();
let failure = h.request_open("file-1").unwrap();
h.open(failure.clone(), filename.clone(), vec![1]).unwrap();
h.take_actions();
fill_transport_event_queue(&h);
h.finish_open(&success, "file-1", &filename, Ok(42));
h.finish_open(&failure, "file-1", &filename, Err("é\n".repeat(1000)));
h.finish_open(&success, "file-1", &filename, Err("duplicate".into()));
h.finish_open("unowned", "file-1", &filename, Ok(99));
assert_eq!(h.state().events.len(), MAX_EVENTS);
assert_eq!(h.state().finished.len(), 2);
assert!(h.disconnect().is_err());
let first = h.take_events();
assert_eq!(first.len(), MAX_EVENTS);
assert!(!first.iter().any(|event| matches!(event.metadata["type"].as_str(), Some("opened" | "openFailed"))));
let terminals = h.take_events();
assert_eq!(terminals.len(), 2);
assert_eq!(terminals[0].metadata["type"], "opened");
assert_eq!(terminals[1].metadata["type"], "openFailed");
assert_eq!(terminals.iter().map(|event| event.metadata["requestId"].as_str().unwrap()).collect::<Vec<_>>(), [success.as_str(), failure.as_str()]);
for event in &terminals {
assert_eq!(event.metadata["connectionId"], connection);
assert_eq!(event.metadata["namespace"], "account-a");
}
let error = terminals[1].metadata["error"].as_str().unwrap();
assert!(error.len() <= 1024 && error.chars().all(|ch| !ch.is_control()));
assert_eq!(h.bound_document("file-1"), Some(42));
assert!(!h.busy());
assert!(h.take_events().is_empty());
}
#[test]
fn full_event_queue_retains_save_failure_without_duplicate_or_unowned_terminals() {
let h = host();
let (request, uid) = capture(&h, false);
h.resolve_dialog(&request, "provider", &format!("Failed{EXTENSION}")).unwrap();
h.result(request.clone(), "failed".into(), String::new()).unwrap();
let Action::Save { capture, .. } = h.take_actions().remove(0) else { panic!("expected save action") };
fill_transport_event_queue(&h);
h.finish_save(&request, &capture, "failed", "", true);
h.finish_save(&request, &capture, "failed", "", true);
h.finish_save("unowned", &capture, "failed", "", true);
assert_eq!(h.state().events.len(), MAX_EVENTS);
assert_eq!(h.state().finished.len(), 1);
assert!(h.pending_for(uid));
assert_eq!(h.take_events().len(), MAX_EVENTS);
let terminals = h.take_events();
assert_eq!(terminals.len(), 1);
assert_eq!(terminals[0].metadata["type"], "saveFailed");
assert_eq!(terminals[0].metadata["requestId"], request);
assert!(!h.pending_for(uid));
assert!(!h.busy());
assert!(h.take_events().is_empty());
}
#[test]
fn retained_terminals_are_bounded_by_admitted_reads_and_saves() {
let h = host();
let filename = terminal_resource(&h);
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
for _ in 0..MAX_PENDING {
let (request, _) = capture(&h, false);
h.resolve_dialog(&request, "provider", &format!("Failed{EXTENSION}")).unwrap();
h.result(request, "failed".into(), String::new()).unwrap();
}
let saves: Vec<_> = h
.take_actions()
.into_iter()
.map(|action| match action {
Action::Save { request, capture, .. } => (request, capture),
_ => panic!("expected save action"),
})
.collect();
assert!(h.state().events.len() < MAX_EVENTS);
let mut extra = saves[0].1.snapshots.clone();
extra[0].uid = u64::MAX;
assert!(h.begin(extra, u64::MAX, 1, format!("Extra{EXTENSION}"), vec![1], false).is_err());
let mut reads = Vec::new();
for _ in 0..MAX_PENDING {
let request = h.request_open("file-1").unwrap();
h.open(request.clone(), filename.clone(), vec![1]).unwrap();
reads.push(request);
}
h.take_actions();
fill_transport_event_queue(&h);
for (request, capture) in &saves {
h.finish_save(request, capture, "failed", "", true);
}
for request in &reads {
h.finish_open(request, "file-1", &filename, Err("read failed".into()));
}
assert_eq!(h.state().finished.len(), 2 * MAX_PENDING);
assert_eq!(h.state().finishing_saves.len(), MAX_PENDING);
assert_eq!(h.state().opens.len(), MAX_PENDING);
assert!(h.request_open("file-1").is_err());
assert!(h.disconnect().is_err());
assert_eq!(h.take_events().len(), MAX_EVENTS);
let terminals = h.take_events();
assert_eq!(terminals.len(), 2 * MAX_PENDING);
let expected: Vec<_> = saves.iter().map(|(request, _)| request.as_str()).chain(reads.iter().map(String::as_str)).collect();
assert_eq!(terminals.iter().map(|event| event.metadata["requestId"].as_str().unwrap()).collect::<Vec<_>>(), expected);
for event in &terminals {
assert_eq!(event.metadata["connectionId"], connection);
assert_eq!(event.metadata["namespace"], "account-a");
}
assert!(!h.busy());
assert!(h.take_events().is_empty());
}
#[test]
fn capture_target_must_belong_to_its_snapshot_aliases() {
let h = host();
let (request, _) = capture(&h, false);
let snapshots = h.state().dialogs.get(&request).unwrap().snapshots.clone();
assert!(h.begin(snapshots, u64::MAX, 1, format!("Other{EXTENSION}"), vec![1], false).is_err());
assert!(!h.pending_for(u64::MAX));
}
#[test]
fn failed_save_delivery_has_a_bounded_inbox_and_keeps_all_captured_aliases() {
let h = host();
let mut session = Session::new();
session.execute("new", &json!({})).unwrap();
let first = session.state().unwrap().clone();
session.execute("new", &json!({})).unwrap();
let alias = session.state().unwrap().clone();
let request = h.begin(vec![first.clone(), alias.clone()], first.uid, first.revision, "Captured.dxf".into(), vec![1, 2, 3], false).unwrap();
h.take_events();
h.resolve_dialog(&request, "provider", "Captured.dxf").unwrap();
let name = terminal_resource(&h);
for _ in 0..MAX_PENDING {
let read = h.request_open("file-1").unwrap();
h.open(read, name.clone(), vec![1]).unwrap();
}
assert!(h.result(request.clone(), "saved".into(), "file-1".into()).unwrap_err().contains("queue is full"));
let mut errors = 0;
assert!(h.publish_events_with(
|metadata, bytes| {
if metadata["type"] == "save" {
assert_eq!(metadata["requestId"], request);
assert_eq!(bytes, Some(vec![1, 2, 3]));
Err("copy failed")
} else {
Ok(())
}
},
|_| errors += 1,
));
assert_eq!(errors, 1);
assert_eq!(h.state().actions.len(), MAX_PENDING, "ordinary admission capacity is unchanged");
assert_eq!(h.state().delivery_failures.len(), 1);
assert!(h.pending_for(first.uid) && h.pending_for(alias.uid));
assert!(h.result(request.clone(), "saved".into(), "late".into()).is_err());
let actions = h.take_actions();
assert_eq!(actions.len(), MAX_PENDING + 1);
for action in actions {
match action {
Action::Save { request: owned, capture, status, resource } => {
assert_eq!(owned, request);
assert_eq!((capture.doc, capture.revision), (first.uid, first.revision));
assert_eq!(capture.snapshots.iter().map(|doc| doc.uid).collect::<Vec<_>>(), vec![first.uid, alias.uid]);
assert!(Arc::ptr_eq(&capture.snapshots[0].doc, &first.doc));
assert!(capture.bytes.is_none() && resource.is_empty());
assert_eq!(status, "failed");
h.finish_save(&owned, &capture, &status, &resource, true);
}
Action::Open { request, resource, name, .. } => h.finish_open(&request, &resource, &name, Err("fixture complete".into())),
}
}
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
assert!(!h.busy() && !h.pending_for(first.uid) && !h.pending_for(alias.uid));
assert!(h.bound_document("file-1").is_none());
h.disconnect().unwrap();
}
#[test]
fn successful_and_reentrant_save_results_are_not_replaced_by_delivery_recovery() {
for reentrant in [false, true] {
let h = host();
let (request, uid) = capture(&h, false);
h.take_events();
h.resolve_dialog(&request, "provider", "Original.dxf").unwrap();
let failed = h.publish_events_with(
|metadata, _| {
assert_eq!(metadata["type"], "save");
if reentrant {
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
Err("dispatch failed after an accepted result")
} else {
Ok(())
}
},
|_| {},
);
assert_eq!(failed, reentrant);
assert!(h.state().delivery_failures.is_empty());
if !reentrant {
assert!(h.pending_for(uid), "successful delivery is not an ACK");
h.result(request.clone(), "saved".into(), "file-1".into()).unwrap();
}
let Action::Save { request: owned, capture, status, resource } = h.take_actions().remove(0) else { panic!("expected save action") };
assert_eq!((owned.as_str(), status.as_str(), resource.as_str()), (request.as_str(), "saved", "file-1"));
h.finish_save(&owned, &capture, &status, &resource, true);
assert!(h.disconnect().is_err(), "the queued saved terminal still owns its account");
assert_eq!(h.take_events()[0].metadata["type"], "saved");
assert_eq!(h.bound_document("file-1"), Some(uid));
assert!(!h.busy());
}
}
#[test]
fn failed_chooser_delivery_preserves_capacity_errors_and_synchronous_resolution() {
for accepted in [false, true] {
let h = host();
let (request, uid) = capture(&h, false);
if !accepted {
fill_transport_event_queue(&h);
assert!(h.resolve_dialog(&request, "provider", "Retry.dxf").is_err());
assert!(h.state().dialogs.contains_key(&request));
}
assert!(h.publish_events_with(
|metadata, _| {
if metadata["type"] == "saveDialog" {
if accepted {
h.resolve_dialog(&request, "provider", "Accepted.dxf").unwrap();
}
Err("chooser delivery failed")
} else {
Ok(())
}
},
|_| {},
));
if accepted {
assert!(h.state().pending.contains_key(&request));
assert!(h.state().delivery_failures.is_empty());
h.result(request.clone(), "failed".into(), String::new()).unwrap();
} else {
assert!(h.resolve_dialog(&request, "provider", "Late.dxf").is_err());
assert_eq!(h.state().delivery_failures.len(), 1);
}
let Action::Save { request: owned, capture, status, resource } = h.take_actions().remove(0) else { panic!("expected failure action") };
assert_eq!(owned, request);
assert_eq!(status, "failed");
assert!(capture.bytes.is_none());
h.finish_save(&owned, &capture, &status, &resource, true);
let terminal = h.take_events();
assert_eq!(terminal[0].metadata["type"], "saveFailed");
assert_eq!(terminal[0].metadata["requestId"], request);
assert!(!h.busy() && !h.pending_for(uid));
let retry = h.begin(capture.snapshots.clone(), capture.doc, capture.revision, "Retry.dxf".into(), vec![1], false).unwrap();
assert_ne!(retry, request);
}
}
#[test]
fn failed_read_delivery_releases_only_unconsumed_owners_and_preserves_queued_open() {
let h = host();
let name = terminal_resource(&h);
let failed = h.request_open("file-1").unwrap();
let accepted = h.request_open("file-1").unwrap();
let mut terminals = Vec::new();
assert!(h.publish_events_with(
|metadata, _| {
if metadata["type"] == "openRequested" {
if metadata["requestId"] == accepted {
h.open(accepted.clone(), name.clone(), vec![7]).unwrap();
}
Err("open request delivery failed")
} else {
terminals.push(metadata.clone());
Ok(())
}
},
|_| {},
));
assert_eq!(terminals.len(), 1);
assert_eq!(terminals[0]["type"], "openFailed");
assert_eq!(terminals[0]["requestId"], failed);
assert_eq!(terminals[0]["resourceId"], "file-1");
assert!(h.open(failed, name.clone(), vec![1]).is_err());
let actions = h.take_actions();
assert_eq!(actions.len(), 1);
let Action::Open { request, resource, name, bytes } = &actions[0] else { panic!("expected accepted open") };
assert_eq!(request, &accepted);
assert_eq!(bytes.as_slice(), [7]);
h.finish_open(request, resource, name, Err("fixture complete".into()));
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
assert!(!h.busy());
let retry = h.request_open("file-1").unwrap();
h.cancel_open(retry, String::new()).unwrap();
assert!(!h.publish_events_with(|_, _| Ok::<(), &str>(()), |_| {}));
h.disconnect().unwrap();
}
#[test]
fn current_batch_and_nested_terminal_delivery_keep_the_original_account_owned() {
let h = host();
let name = terminal_resource(&h);
let connection = h.snapshot()["connectionId"].as_str().unwrap().to_string();
let request = h.request_open("file-1").unwrap();
h.open(request.clone(), name.clone(), vec![7]).unwrap();
h.take_actions();
h.finish_open(&request, "file-1", &name, Ok(42));
let mut delivered = Vec::new();
assert!(!h.publish_events_with(
|metadata, _| {
assert!(h.disconnect().is_err());
assert_eq!(h.snapshot()["connectionId"], connection);
if metadata["type"] == "openRequested" {
let nested = h.request_open("file-1").unwrap();
h.cancel_open(nested, String::new()).unwrap();
assert!(!h.publish_events_with(
|_, _| {
assert!(h.disconnect().is_err(), "nested delivery cannot release an outer taken terminal");
Ok::<(), &str>(())
},
|_| {},
));
assert!(h.disconnect().is_err());
} else {
delivered.push(metadata.clone());
}
Ok::<(), &str>(())
},
|_| {},
));
assert_eq!(delivered.len(), 1);
assert_eq!(delivered[0]["type"], "opened");
assert_eq!(delivered[0]["requestId"], request);
assert_eq!(delivered[0]["connectionId"], connection);
assert_eq!(h.bound_document("file-1"), Some(42));
assert!(!h.busy());
h.disconnect().unwrap();
}
#[test]
fn read_delivery_recovery_retains_its_terminal_through_a_reentrant_full_event_queue() {
let h = host();
terminal_resource(&h);
let request = h.request_open("file-1").unwrap();
assert!(h.publish_events_with(
|metadata, _| {
if metadata["type"] == "openRequested" {
fill_transport_event_queue(&h);
Err("delivery failed after another callback filled the queue")
} else {
assert_eq!(metadata["type"], "queued");
assert!(h.disconnect().is_err());
Ok(())
}
},
|_| {
assert!(h.open(request.clone(), "Remote.dxf".into(), vec![1]).is_err(), "a retained failure cannot accept a late payload");
assert!(h.cancel_open(request.clone(), String::new()).is_err());
},
));
assert!(h.busy() && h.disconnect().is_err(), "bounded drains leave the undelivered terminal owned for the next call");
let mut seen = 0;
assert!(!h.publish_events_with(
|metadata, _| {
assert_eq!(metadata["type"], "openFailed");
assert_eq!(metadata["requestId"], request);
assert!(h.disconnect().is_err());
seen += 1;
Ok::<(), &str>(())
},
|_| {},
));
assert_eq!(seen, 1);
assert!(!h.busy());
h.disconnect().unwrap();
}

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