Compare commits

..
Author SHA1 Message Date
skylar taylor-barrick f7adf3ad56 Prepare CADCraft nightly signing and Mac archive layout (#3598) 2026-11-27 15:19:23 -06:00
Dylan M. TaylorandFredApps 1981067187 ci: notify artcraft-services on release state changes (#3581)
* ci: notify artcraft-services on release state changes

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

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

---------

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

Test: a_lost_reply_on_the_retry_still_says_a_mutation_may_have_been_applied.

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

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

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

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

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

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

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

Part of #1925 (F-12).

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

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

Fixes #3541

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

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

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

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

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

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

Part of #1933.

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

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

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

Fixes #1069.

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

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

Part of #1926 (item 3).

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

Test: remembered_links_are_the_most_recent_ones.

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

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

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

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

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

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

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

Part of #1924

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

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

Part of #1929 (F-08).

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

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

Part of #1923 (F-05).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-26 17:45:00 +07:00
61 changed files with 3498 additions and 222 deletions
+3 -3
View File
@@ -4,10 +4,10 @@
"repository_id": 1408289866,
"producer_workflow_id": 429719786,
"producer_workflow_path": ".github/workflows/nightly.yml",
"producer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"producer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"producer_workflow_ref": "storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"signer_workflow_path": ".github/workflows/nightly-sign.yml",
"signer_tooling_revision": "be00e5ccd18b68e950c8a08532f2230e7c3d0cba",
"signer_tooling_revision": "bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3",
"release_branch": "nightly-signer",
"manual_actors": [
"bflatastic",
+16 -2
View File
@@ -34,12 +34,26 @@ jobs:
checks: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-release.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
app-name: cadcraft
producer_run_id: ${{ inputs.producer_run_id }}
producer_run_attempt: ${{ inputs.producer_run_attempt }}
secrets:
APPLE_CERTIFICATE: ${{ secrets.APPLE_CERTIFICATE }}
APPLE_CERTIFICATE_PASSWORD: ${{ secrets.APPLE_CERTIFICATE_PASSWORD }}
KEYCHAIN_PASSWORD: ${{ secrets.KEYCHAIN_PASSWORD }}
APPLE_ID: ${{ secrets.APPLE_ID }}
APPLE_PASSWORD: ${{ secrets.APPLE_PASSWORD }}
APPLE_TEAM_ID: ${{ secrets.APPLE_TEAM_ID }}
AZURE_TENANT_ID: ${{ secrets.AZURE_TENANT_ID }}
AZURE_CLIENT_ID: ${{ secrets.AZURE_CLIENT_ID }}
AZURE_CLIENT_SECRET: ${{ secrets.AZURE_CLIENT_SECRET }}
AZURE_SIGNING_ENDPOINT: ${{ secrets.AZURE_SIGNING_ENDPOINT }}
AZURE_SIGNING_ACCOUNT: ${{ secrets.AZURE_SIGNING_ACCOUNT }}
AZURE_CERT_PROFILE: ${{ secrets.AZURE_CERT_PROFILE }}
LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}
# No secrets: inherit or raw platform values in this caller. Only the isolated native
# callee job may bind the release environment and export its keys; that environment must
# admit nightly-signer alongside release before the first dispatch.
+2 -2
View File
@@ -22,9 +22,9 @@ jobs:
actions: read
attestations: write
id-token: write
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@be00e5ccd18b68e950c8a08532f2230e7c3d0cba
uses: storytold/craft-common-actions/.github/workflows/nightly-unsigned.yml@bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
with:
tooling-revision: be00e5ccd18b68e950c8a08532f2230e7c3d0cba
tooling-revision: bf94b15b708089b95c4e2d1c978e66ecf1f2f4f3
app-name: cadcraft
manual-actors: '["bflatastic","dylanmtaylor","echelon","FredApps","skylartaylor"]'
craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83
+6
View File
@@ -45,6 +45,12 @@ fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
+5 -1
View File
@@ -145,10 +145,14 @@ pub(crate) fn export(s: &Session, out: &Path, io: &mut Streams) -> Result {
pub(crate) fn export_framed(s: &Session, out: &Path, window: Option<Bounds2>, io: &mut Streams) -> Result {
let d = s.doc()?;
let bytes = cadcraft_io::write_framed(d, out, window)?;
let (bytes, notes) = cadcraft_io::write_framed_noted(d, out, window)?;
let folder = write_atomic(out, &bytes)?;
report_new_folder(folder, io);
io.errln(format_args!("wrote {} ({} bytes)", out.display(), bytes.len()));
// What the image draws short of the drawing (dashed runs past a dash limit drawn continuous).
for note in notes {
io.errln(format_args!("{}: {note}", out.display()));
}
if cadcraft_engine::cmd::file::drops_unknown(out) {
let lost = cadcraft_engine::cmd::file::not_saved(d);
if let Some(m) = cadcraft_engine::cmd::file::not_saved_message(&lost) {
@@ -0,0 +1,144 @@
//! `convert` to an image says how many dashed runs it drew continuous because of a dash limit
//! (#1069): a line whose DASHED pattern repeats past what one run may be laid out over. A line of
//! 50,001 periods, which an export keeps dashed, gets no note.
use std::process::{Command, Output};
fn cli(args: &[&str]) -> Output {
Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(args).output().unwrap()
}
/// A DXF of one line `periods` DASHED (0.5, -0.25) periods long.
fn dashed_line(periods: f64) -> String {
format!(
"0
SECTION
2
TABLES
0
TABLE
2
LTYPE
70
1
0
LTYPE
2
DASHED
70
0
3
Dashed
72
65
73
2
40
0.75
49
0.5
74
0
49
-0.25
74
0
0
ENDTAB
0
ENDSEC
0
SECTION
2
ENTITIES
0
LINE
8
0
6
DASHED
10
0
20
0
11
{}
21
0
0
ENDSEC
0
EOF
",
periods * 0.75
)
}
#[test]
fn convert_to_an_image_notes_dashed_runs_drawn_continuous_past_the_dash_limit() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
// (1,000,001 + 2) periods × 2 elements: past the two million one run may be laid out over.
let long = dir.join("long.dxf");
std::fs::write(&long, dashed_line(1_000_001.0)).unwrap();
let control = dir.join("control.dxf");
std::fs::write(&control, dashed_line(50_001.0)).unwrap();
let notes = |out: &Output| {
assert!(out.status.success(), "{:?}: {}", out.status, String::from_utf8_lossy(&out.stderr));
String::from_utf8_lossy(&out.stderr).lines().filter(|l| l.contains("drawn continuous")).map(str::to_string).collect::<Vec<_>>()
};
for ext in ["png", "svg", "pdf"] {
let image = dir.join(format!("long.{ext}"));
let image = image.to_str().unwrap();
let got = notes(&cli(&["convert", long.to_str().unwrap(), image]));
assert!(matches!(got.as_slice(), [note] if note.starts_with(&format!("{image}: 1 dashed run "))), "{ext}: {got:?}");
let got = notes(&cli(&["convert", control.to_str().unwrap(), dir.join(format!("control.{ext}")).to_str().unwrap()]));
assert!(got.is_empty(), "{ext}: {got:?}");
}
// A DXF copy draws nothing, so there is nothing to note.
assert!(notes(&cli(&["convert", long.to_str().unwrap(), dir.join("copy.dxf").to_str().unwrap()])).is_empty());
let _ = std::fs::remove_dir_all(&dir);
}
/// The engine's commands that write an image say it too, on the command line and in the result's
/// `warnings`: EXPORT, PLOT (PDF, PNG, SVG, to a file or as data), QSAVE and SAVEAS to an image and
/// `document.bytes`.
#[test]
fn image_commands_warn_about_dashed_runs_drawn_continuous() {
let dir = std::env::temp_dir().join(format!("cc-cli-dash-limit-cmds-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let out = |name: &str| serde_json::to_string(dir.join(name).to_str().unwrap()).unwrap();
let cmds = [
format!("export {{\"path\": {}}}", out("export.png")),
format!("plot {{\"path\": {}}}", out("plot.pdf")),
format!("plot {{\"path\": {}, \"output\": \"png\", \"resolution\": 50}}", out("plot.png")),
format!("plot {{\"path\": {}, \"output\": \"svg\"}}", out("plot.svg")),
format!("saveas {{\"path\": {}}}", out("saved.svg")),
format!("qsave {{\"path\": {}}}", out("saved.pdf")),
"plot {\"output\": \"svg\"}".to_string(),
"document.bytes {\"format\": \"pdf\"}".to_string(),
format!("saveas {{\"path\": {}, \"version\": 2018}}", out("versioned.png")),
];
for (periods, warned) in [(1_000_001.0, true), (50_001.0, false)] {
let input = dir.join(format!("line-{periods}.dxf"));
std::fs::write(&input, dashed_line(periods)).unwrap();
let mut args = vec!["run".to_string(), input.to_str().unwrap().to_string()];
for c in &cmds {
args.extend(["--cmd".to_string(), c.clone()]);
}
let run = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli")).args(&args).output().unwrap();
assert!(run.status.success(), "{:?}: {}", run.status, String::from_utf8_lossy(&run.stderr));
let results: Vec<serde_json::Value> = String::from_utf8_lossy(&run.stdout).lines().map(|l| serde_json::from_str(l).unwrap()).collect();
assert_eq!(results.len(), cmds.len(), "{results:?}");
for (c, r) in cmds.iter().zip(&results) {
let notes: Vec<&str> = r["warnings"].as_array().into_iter().flatten().filter_map(|w| w.as_str()).collect();
let noted = matches!(notes.as_slice(), [n] if n.starts_with("1 dashed run ") && n.contains("drawn continuous"));
assert_eq!(noted, warned, "{periods} periods, {c}: {r}");
assert_eq!(r.get("warnings").is_some(), warned, "{periods} periods, {c}: {r}");
}
// Said on the command line once for each command.
let echoed = String::from_utf8_lossy(&run.stderr).lines().filter(|l| l.starts_with("1 dashed run ")).count();
assert_eq!(echoed, if warned { cmds.len() } else { 0 }, "{}", String::from_utf8_lossy(&run.stderr));
}
let _ = std::fs::remove_dir_all(&dir);
}
+1
View File
@@ -1,4 +1,5 @@
mod cli;
mod dash_limit_note;
mod drafting_spacing;
mod help;
// DWG output needs craft-dwg's bridge.
+6
View File
@@ -120,6 +120,12 @@ mod web {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
+78 -4
View File
@@ -4,8 +4,9 @@
//! The server only reads requests: a line that is not a JSON object with a string `method` (an
//! HTTP request line, a stray `nc`, binary data) gets one error reply and the connection is
//! closed, so nothing sent after it runs. Every resource a client can hold is bounded
//! ([`Limits`]): simultaneous connections, request line length, queued requests, and how long a
//! socket may sit idle or blocked on a write.
//! ([`Limits`]): simultaneous connections, request line length (shorter until a request on the
//! connection has carried the token), queued requests, and how long a socket may sit idle or
//! blocked on a write.
use std::io::{BufRead, BufReader, ErrorKind, Write};
use std::net::{TcpListener, TcpStream};
@@ -24,6 +25,9 @@ struct Limits {
max_clients: usize,
/// Longest request line in bytes (newline excluded); a longer one closes the connection.
max_line: usize,
/// Longest request line until a request on the connection has carried the right token; a
/// longer one closes the connection (#1925).
preauth_line: usize,
/// Request-line bytes buffered at once across all connections; a request that would pass it
/// is refused with an error reply.
total_bytes: usize,
@@ -43,6 +47,7 @@ impl Default for Limits {
max_clients: 16,
// Generous, so requests that carry whole drawings or images as base64 still fit.
max_line: 256 * 1024 * 1024,
preauth_line: cadcraft_mcp::control_token::MAX_UNAUTHENTICATED_LINE,
// Room for one maximal request plus smaller ones, not `max_clients` maximal ones.
total_bytes: 512 * 1024 * 1024,
queue: 64,
@@ -344,12 +349,21 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let mut reader = BufReader::new(read);
let mut buf = Vec::new();
let mut held = Held::new(budget);
// The token is checked only after the whole line is read, so until a request here has carried
// it a line is kept short: a peer without it can't make the app buffer `max_line` (#1925).
let mut authenticated = false;
loop {
let reject = match read_bounded_line(&mut reader, &mut buf, limits.max_line, &mut held) {
let max = if authenticated { limits.max_line } else { limits.preauth_line.min(limits.max_line) };
let reject = match read_bounded_line(&mut reader, &mut buf, max, &mut held) {
Ok(false) => break,
// Nothing of a line arrived (idle timeout, or the peer is gone): close without a word.
// A line nobody asked for would be read as the reply to the client's next request.
Err(_) if buf.is_empty() => break,
// Only an overlong line leaves more than `max` bytes buffered.
Err(_) if !authenticated && buf.len() > max => format!(
"request line longer than {max} bytes before a request with the control token on this connection; \
send a short request with the token (such as `ping`) first; closing the connection"
),
Err(e) => e,
Ok(true) => match parse_line(&buf) {
Line::Blank => continue,
@@ -366,6 +380,7 @@ fn serve(stream: TcpStream, tx: &SyncSender<ControlRequest>, ctx: &egui::Context
let _ = writeln!(out, "{r}");
break;
}
authenticated = true;
// Absent `params` is `{}`; ones that cannot be decoded (an unpaired surrogate escape) are an
// error, not a request run with defaults.
let params = match params.map(|r| serde_json::from_str::<Value>(r.get())) {
@@ -499,7 +514,12 @@ mod tests {
/// The control server on a loopback port, with a stand-in UI that echoes each method.
fn serve_echo() -> std::net::SocketAddr {
let (addr, rx) = serve_with(Limits::default());
serve_echo_with(Limits::default())
}
/// [`serve_echo`] under `limits`.
fn serve_echo_with(limits: Limits) -> std::net::SocketAddr {
let (addr, rx) = serve_with(limits);
std::thread::spawn(move || {
for req in rx {
let _ = req.reply.send(json!({"ok": true, "method": req.method}));
@@ -612,6 +632,60 @@ mod tests {
drop(first);
}
/// Small bounds for the pre-authentication tests: lines up to 1000 bytes until the connection
/// has shown the token, up to 100 000 after.
fn preauth() -> Limits {
Limits { max_line: 100_000, preauth_line: 1000, idle_timeout: Duration::from_secs(5), ..short() }
}
/// A request line carrying the test token whose parameters make it `len` bytes or longer.
fn long_req_line(id: i64, len: usize) -> String {
json!({"id": id, "method": "long", "params": {"text": "x".repeat(len)}, "token": TEST_TOKEN}).to_string() + "\n"
}
/// A peer without the token is refused once its line passes the pre-authentication bound,
/// while it is still sending: the app doesn't buffer the rest of the line to find the token
/// at its end (#1925).
#[test]
fn an_unauthenticated_long_line_is_refused_at_the_preauth_bound() {
let (addr, rx) = serve_with(preauth());
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(3))).unwrap();
// Well under `max_line`, and unfinished: without the pre-authentication bound the server
// keeps reading and waiting for the rest of it. One write, so it all reaches the server's
// buffer at once and the close after the refusal leaves nothing unread to reset the reply.
let unfinished = format!(r#"{{"id":1,"method":"m","params":"{}"#, "x".repeat(5000));
c.write_all(unfinished.as_bytes()).unwrap();
let mut line = String::new();
BufReader::new(&mut c).read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!(v["ok"], json!(false));
assert!(v["error"].as_str().unwrap_or("").contains("longer than 1000 bytes before a request with the control token"), "{line}");
assert!(rx.try_recv().is_err(), "nothing was dispatched");
}
/// A long request with the token is taken once a shorter request with the token has been
/// answered on the same connection; as a connection's first line it is refused, since its
/// token comes only at the end.
#[test]
fn a_long_request_is_taken_once_the_connection_has_shown_the_token() {
let addr = serve_echo_with(preauth());
let long = long_req_line(2, 5000);
let first = exchange(addr, long.as_bytes());
assert_eq!(first.len(), 1, "{first:?}");
assert!(first[0]["error"].as_str().unwrap_or("").contains("before a request with the control token"), "{first:?}");
let mut c = TcpStream::connect(addr).unwrap();
c.set_read_timeout(Some(Duration::from_secs(5))).unwrap();
c.write_all(format!("{}{long}", req_line(1, "ping")).as_bytes()).unwrap();
let mut r = BufReader::new(c);
for (id, method) in [(1, "ping"), (2, "long")] {
let mut line = String::new();
r.read_line(&mut line).unwrap();
let v: Value = serde_json::from_str(&line).unwrap();
assert_eq!((v["id"].as_i64(), v["ok"].as_bool(), v["method"].as_str()), (Some(id), Some(true), Some(method)), "{line}");
}
}
#[test]
fn the_budget_is_given_back_when_the_connection_ends() {
let budget = Budget::new(100);
+6
View File
@@ -182,6 +182,12 @@ pub fn install_io() {
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: Some(|d, space, opts| cadcraft_io::plotter::plot(d, space, opts).map_err(|e| e.to_string())),
});
// The same writers, with what an image draws short of the drawing (dashed lines past the
// dash limit), so EXPORT, SAVEAS and PLOT can say so.
cadcraft_engine::cmd::file::set_noted_io(cadcraft_engine::cmd::file::NotedIo {
write: |d, name| cadcraft_io::write_framed_noted(d, name, None).map_err(|e| e.to_string()),
plot: |d, space, opts| cadcraft_io::plotter::plot_noted(d, space, opts).map_err(|e| e.to_string()),
});
cadcraft_engine::cmd::file::set_image_decoder(|b| cadcraft_io::raster::decode(b).map_err(|e| e.to_string()));
cadcraft_engine::cmd::file::set_write_as(|d, name, o| {
cadcraft_io::write_with(d, name, &cadcraft_io::SaveOptions { version: o.version, binary: o.binary }).map_err(|e| e.to_string())
+3 -2
View File
@@ -43,7 +43,7 @@ pub fn specs() -> Vec<CommandSpec> {
CommandSpec::new("export", "Export...", run_export)
.menu(&["File", "Export..."])
.alias(&["exp"])
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension)} → {format, bytes, path? | data}")
.params("{path? (else returns base64 `data`), format?: dxf|dwg|svg|png|pdf (default: the path's extension)} → {format, bytes, path? | data, warnings?: what an image draws short of the drawing}")
.noundo(),
CommandSpec::new("preview", "Plot Preview", run_preview)
.menu(&["File", "Plot Preview"])
@@ -123,7 +123,7 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
return Err(bad("export", "`format` must be dxf, dwg, svg, png or pdf (or give a `path` with one of those extensions)"));
}
let file = format!("export.{format}");
let bytes = (hooks.write)(s.doc()?, &file).map_err(|e| bad("export", e))?;
let (bytes, notes) = super::file::write_noted(hooks, s.doc()?, &file).map_err(|e| bad("export", e))?;
let folder = path.and_then(super::file::new_folder);
let mut r = match path {
Some(path) => {
@@ -134,6 +134,7 @@ fn run_export(s: &mut Session, p: &Value) -> Result<Value> {
};
super::file::report_new_folder(s, &mut r, folder);
super::file::report_loss(s, &mut r, &file);
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
+91 -17
View File
@@ -49,6 +49,47 @@ pub fn io() -> Option<&'static IoHooks> {
IO.get()
}
/// [`IoHooks::write`] and [`IoHooks::plot`] that also return what an image (PNG, SVG, PDF) draws
/// short of the drawing because of a render limit, one note each, such as dashed lines drawn
/// continuous past the dash limit (installed by the app with the image writers, a lower layer;
/// see `cadcraft_io::write_framed_noted` and `cadcraft_io::plotter::plot_noted`). EXPORT, QSAVE
/// and SAVEAS to an image, `document.bytes` and PLOT (so PUBLISH and PDFBOOK, sheet by sheet)
/// report them; without the hooks they write through [`IoHooks`] with no such notes. The app
/// installs the same writers as its [`IoHooks`].
pub struct NotedIo {
pub write: fn(&Drawing, &str) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
pub plot: fn(&Drawing, &cadcraft_doc::Space, &Value) -> std::result::Result<(Vec<u8>, Vec<String>), String>,
}
static NOTED_IO: OnceLock<NotedIo> = OnceLock::new();
pub fn set_noted_io(h: NotedIo) {
let _ = NOTED_IO.set(h);
}
/// `d` written as `name` with the image's notes ([`NotedIo::write`]), or through `hooks.write`
/// with none when the app installed no [`NotedIo`].
pub(crate) fn write_noted(hooks: &IoHooks, d: &Drawing, name: &str) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.write)(d, name),
None => (hooks.write)(d, name).map(|bytes| (bytes, Vec::new())),
}
}
/// `d` plotted with the plot's notes ([`NotedIo::plot`]), or through `hook` with none when the
/// app installed no [`NotedIo`].
pub(crate) fn plot_noted(
hook: PlotHook,
d: &Drawing,
space: &cadcraft_doc::Space,
opts: &Value,
) -> std::result::Result<(Vec<u8>, Vec<String>), String> {
match NOTED_IO.get() {
Some(n) => (n.plot)(d, space, opts),
None => hook(d, space, opts).map(|bytes| (bytes, Vec::new())),
}
}
/// An entity as DXF groups and back, for AutoLISP's `entget`, `entmake` and `entmod`
/// (installed by the app with the DXF reader and writer, a lower layer).
pub struct EntityCodec {
@@ -123,6 +164,11 @@ pub fn dwg_notes(d: &Drawing) -> Vec<String> {
/// Say on the command line what the DWG just written keeps only in part (`notes`, from
/// [`dwg_notes`]), and list it in the result's `warnings`.
pub(crate) fn report_dwg_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
report_notes(s, r, notes);
}
/// Say each of `notes` on the command line and add them to the result's `warnings`.
pub(crate) fn report_notes(s: &mut Session, r: &mut Value, notes: Vec<String>) {
if notes.is_empty() {
return;
}
@@ -130,7 +176,12 @@ pub(crate) fn report_dwg_notes(s: &mut Session, r: &mut Value, notes: Vec<String
s.echo(note.clone());
}
if let Some(o) = r.as_object_mut() {
o.insert("warnings".into(), json!(notes));
match o.get_mut("warnings").and_then(Value::as_array_mut) {
Some(list) => list.extend(notes.into_iter().map(Value::String)),
None => {
o.insert("warnings".into(), json!(notes));
}
}
}
}
@@ -238,9 +289,10 @@ fn is_dxf(path: &str) -> bool {
Format::from_path(path) == Some(Format::Dxf)
}
/// The drawing written to `path` with `opts`: through [`IoHooks::write`] when no option is set,
/// else through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<Vec<u8>> {
/// The drawing written to `path` with `opts`: an image, or a drawing file with no option set,
/// through [`IoHooks::write`] (with an image's notes, [`write_noted`]); a drawing file at a
/// chosen version or as binary DXF through the [`write_as`] hook.
fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(Vec<u8>, Vec<String>)> {
let hooks = io().ok_or_else(|| bad(cmd, "file formats are not available in this build"))?;
if opts.binary && !is_dxf(path) {
return Err(bad(cmd, "binary applies to DXF files only"));
@@ -249,11 +301,12 @@ fn write_bytes(s: &Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<Vec<
let d: &cadcraft_doc::Drawing = if is_drawing_file(path) { s.state()?.drawing() } else { s.doc()? };
let copy = (opts.portable_fonts && is_drawing_file(path)).then(|| Drawing { portable_fonts: true, ..d.clone() });
let d = copy.as_ref().unwrap_or(d);
let r = if opts.version.is_none() && !opts.binary {
(hooks.write)(d, path)
// An image has no version: `write_as` would write the same bytes without the notes.
let r = if !is_drawing_file(path) || (opts.version.is_none() && !opts.binary) {
write_noted(hooks, d, path)
} else {
let w = write_as().ok_or_else(|| bad(cmd, "saving at a chosen version or as binary DXF is not available in this build"))?;
w(d, path, opts)
w(d, path, opts).map(|bytes| (bytes, Vec::new()))
};
r.map_err(|e| bad(cmd, e))
}
@@ -285,7 +338,7 @@ pub fn specs() -> Vec<CommandSpec> {
.noundo(),
CommandSpec::new("document.switch", "Switch Drawing", run_switch).params("{index}").enabled(always).noundo(),
CommandSpec::new("document.bytes", "Drawing as bytes", run_bytes)
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64}")
.params("{format?: dxf, version?: 2000…2018, binary?: bool, portableFonts?: bool} → {data: base64, warnings?: what an image draws short of the drawing}")
.noundo(),
CommandSpec::new("script", "Run Script...", run_script)
.menu(&["Tools", "Run Script..."])
@@ -529,18 +582,19 @@ fn run_closeall(s: &mut Session, _p: &Value) -> Result<Value> {
ok()
}
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<usize> {
pub(crate) fn save_to(s: &mut Session, path: &str) -> Result<(usize, Vec<String>)> {
let opts = SaveAs { binary: s.state()?.binary_dxf && is_dxf(path), ..SaveAs::default() };
save_as(s, "save", path, &opts)
}
/// Save to `path` with `opts`. A drawing file then keeps the version and binary choice: the
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again.
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<usize> {
/// version goes into the drawing's `$ACADVER`, so later saves (QSAVE) write it again. Also an
/// image's notes ([`write_noted`]).
fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<(usize, Vec<String>)> {
if s.doc()?.refedit.is_some() {
return Err(bad(cmd, "A block reference is being edited in place: finish with REFCLOSE (Save or Discard) before saving."));
}
let bytes = write_bytes(s, cmd, path, opts)?;
let (bytes, notes) = write_bytes(s, cmd, path, opts)?;
let n = commit_save(s, path, &bytes, store)?;
if is_drawing_file(path) {
let st = s.state_mut()?;
@@ -552,7 +606,7 @@ fn save_as(s: &mut Session, cmd: &str, path: &str, opts: &SaveAs) -> Result<usiz
st.saved = st.drawing().clone();
}
}
Ok(n)
Ok((n, notes))
}
/// Put saved bytes where the user gets them: natively the file at `path`; on the web, which has
@@ -842,15 +896,18 @@ fn run_save(s: &mut Session, p: &Value) -> Result<Value> {
Some(p) => p.to_string(),
None => s.state()?.path.clone().ok_or_else(|| bad("qsave", "drawing has no file name yet; use saveas {path}"))?,
};
let n = save_to(s, &path)?;
Ok(saved(&path, n))
let (n, notes) = save_to(s, &path)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
Ok(r)
}
fn run_saveas(s: &mut Session, p: &Value) -> Result<Value> {
let path = str_param(p, "path").ok_or_else(|| bad("saveas", "`path` is required"))?.to_string();
let opts = save_options("saveas", p)?;
let n = save_as(s, "saveas", &path, &opts)?;
let (n, notes) = save_as(s, "saveas", &path, &opts)?;
let mut r = saved(&path, n);
report_notes(s, &mut r, notes);
if is_drawing_file(&path) {
r["version"] = json!(opts.version.unwrap_or_else(|| drawing_version(s, &path)).year());
r["binary"] = json!(opts.binary);
@@ -899,8 +956,9 @@ fn run_bytes(s: &mut Session, p: &Value) -> Result<Value> {
let opts = save_options("document.bytes", p)?;
let version = opts.version.unwrap_or_else(|| drawing_version(s, &format!("drawing.{fmt}")));
let lost = not_saved_as(s.doc()?, version);
let bytes = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let (bytes, notes) = write_bytes(s, "document.bytes", &format!("drawing.{fmt}"), &opts)?;
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len() });
report_notes(s, &mut r, notes);
if drops_unknown(format!("drawing.{fmt}")) {
report_not_saved(s, &mut r, &lost);
let notes = s.state().map(|st| dwg_notes(st.drawing())).unwrap_or_default();
@@ -1215,6 +1273,22 @@ mod tests {
use crate::Session;
use crate::temp_dir::TempDir;
/// Notes join the warnings a result already has instead of replacing them, and are said on
/// the command line.
#[test]
fn notes_are_added_to_the_warnings_a_result_has() {
let mut s = Session::new();
let mut r = json!({ "warnings": ["kept"] });
super::report_notes(&mut s, &mut r, vec!["added".into()]);
assert_eq!(r["warnings"], json!(["kept", "added"]));
let mut r = json!({});
super::report_notes(&mut s, &mut r, Vec::new());
assert!(r.get("warnings").is_none());
super::report_notes(&mut s, &mut r, vec!["first".into()]);
assert_eq!(r["warnings"], json!(["first"]));
assert!(s.log.ends_with(&["added".to_string(), "first".to_string()]), "{:?}", s.log);
}
/// Whether the `.bak` name is taken is asked without following a link there: a dangling link
/// counts as taken, so a file that doesn't look like a drawing leaves it alone.
#[cfg(unix)]
+10 -3
View File
@@ -890,7 +890,7 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
if is_image && sheets.as_ref().is_some_and(|names| names.len() > 1) {
return Err(bad(cmd, "`layouts` with several sheets needs PDF output; PNG and SVG hold one sheet, so plot each layout separately"));
}
let bytes = hook(s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let (bytes, notes) = super::file::plot_noted(hook, s.doc()?, &space, &opts).map_err(|e| bad(cmd, e))?;
let layout = match &sheets {
Some(names) => names.first().cloned().unwrap_or_default(),
None => space.tab_name().to_string(),
@@ -909,15 +909,22 @@ fn run_plot(s: &mut Session, p: &Value, cmd: &str) -> Result<Value> {
crate::atomic_write::write_atomic_making_folders(std::path::Path::new(path), &bytes).map_err(|e| bad(cmd, format!("{path}: {e}")))?;
let mut r = json!({ "path": path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_new_folder(s, &mut r, folder);
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
#[cfg(target_arch = "wasm32")]
{
super::exchange::deliver_file(cmd, _path, &bytes, super::file::deliver())?;
Ok(json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format }))
let mut r = json!({ "path": _path, "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
}
None => Ok(json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format })),
None => {
let mut r = json!({ "data": base64_encode(&bytes), "bytes": bytes.len(), "layout": layout, "pages": pages, "format": format });
super::file::report_notes(s, &mut r, notes);
Ok(r)
}
}
}
+87 -12
View File
@@ -8,11 +8,13 @@ use super::cells::cell_of;
use super::{MAX_COLS, MAX_ROWS, anchors, edit, set_anchors, usize_param};
use crate::cmd::machines::SelectRun;
use crate::cmd::{CommandSpec, bad, bool_or, str_param};
use crate::{Accept, Input, Interactive, Prompt, Result, Session, Step};
use crate::{Accept, DocState, Input, Interactive, Prompt, Result, Session, Step};
/// Largest linked file read (bytes).
#[cfg(not(target_arch = "wasm32"))]
const MAX_LINK_BYTES: usize = 8 << 20;
/// Most files remembered per drawing as linked by the user ([`DocState::chosen_links`]).
const MAX_CHOSEN_LINKS: usize = 1000;
pub fn specs() -> Vec<CommandSpec> {
vec![
@@ -26,7 +28,10 @@ pub fn specs() -> Vec<CommandSpec> {
.menu(&["Insert", "Data Link..."])
.params("{handle, path (.csv, .txt/.tsv tab-separated), startRow? (default: below the title), remove?: bool} → {rows, cols}"),
CommandSpec::new("datalinkupdate", "Update Data Links", run_update)
.params("{handles?} (default: every linked table) → {updated}")
.params(
"{handles?} (default: every linked table) → {updated, errors}; a link saved in the drawing is read only from the drawing's \
folder or below it, unless DATALINK linked that file since the drawing was opened",
)
.interactive(|_| Ok(Box::new(SelectRun::new("datalinkupdate", "DATALINKUPDATE")))),
]
}
@@ -224,13 +229,45 @@ fn separator(path: &str, text: &str) -> char {
if first.contains(';') && !first.contains(',') { ';' } else { ',' }
}
/// The file to read for a data link: a path the user just `chosen` as given, a path stored in the
/// drawing at `host` only through [`crate::doc_path::resolve`].
fn link_file(id: &str, path: &str, host: Option<&str>, chosen: bool) -> Result<std::path::PathBuf> {
/// The file to read for a data link of the drawing `st`: a path the user just `chosen` as given;
/// a path stored in the drawing through [`crate::doc_path::resolve`], and then only as the file
/// system finds it (`..` and links followed) in the drawing's `folder`
/// ([`crate::doc_path::drawing_folder`]) or below it, or when the user linked that same file since
/// the drawing was opened ([`DocState::chosen_links`]).
fn link_file(id: &str, path: &str, st: &DocState, folder: Option<&std::path::Path>, chosen: bool) -> Result<std::path::PathBuf> {
if chosen {
return Ok(std::path::PathBuf::from(path));
}
crate::doc_path::resolve(path, host.map(std::path::Path::new)).map_err(|r| bad(id, format!("{path}: not opened, {r}")))
let host = st.path.as_deref().map(std::path::Path::new);
let file = crate::doc_path::resolve(path, host).map_err(|r| bad(id, format!("{path}: not opened, {r}")))?;
if cfg!(target_arch = "wasm32") {
// Nothing is read there; [`read_link`] says so.
return Ok(file);
}
// The automation roots first: outside them nothing about the file is asked.
crate::file_access::check_read(&file).map_err(|e| bad(id, e))?;
let real = std::fs::canonicalize(&file).map_err(|e| bad(id, format!("{path}: {e}")))?;
// Whole components: `plans-old` is not in `plans`.
if folder.is_some_and(|f| real.starts_with(f)) || st.chosen_links.contains_key(&real) {
// Read where it was checked, not through the links again.
return Ok(real);
}
Err(bad(id, format!("{path}: not read, the file is outside the drawing's folder; link it with DATALINK to read it")))
}
/// Remember `real` (resolved), the file of a link the user just gave, as theirs to read for the
/// drawing `st`, as its latest choice. At [`MAX_CHOSEN_LINKS`] files a new one makes room by
/// dropping the file chosen longest ago.
fn remember_link(st: &mut DocState, real: std::path::PathBuf) {
let links = &mut st.chosen_links;
let latest = links.values().max().map_or(0, |n| n.saturating_add(1));
if links.len() >= MAX_CHOSEN_LINKS
&& !links.contains_key(&real)
&& let Some(oldest) = links.iter().min_by_key(|(_, n)| **n).map(|(p, _)| p.clone())
{
links.remove(&oldest);
}
links.insert(real, latest);
}
/// Read a linked file through the host (natively the file system; not on the web).
@@ -288,16 +325,20 @@ fn fill(t: &mut Table, start: usize, data: &[Vec<String>]) {
}
}
/// Re-read the linked file of table `h`; `chosen` says its path was just given by the user.
fn update(s: &mut Session, h: Handle, chosen: bool) -> Result<(usize, usize)> {
/// Re-read the linked file of table `h`; `chosen` says its path was just given by the user, else
/// it is read from the drawing's `folder` ([`crate::doc_path::drawing_folder`]) or a file the user
/// linked.
fn update(s: &mut Session, h: Handle, folder: Option<&std::path::Path>, chosen: bool) -> Result<(usize, usize)> {
let id = "datalinkupdate";
let link = match s.doc()?.entity(h).map(|e| &e.kind) {
Some(EntityKind::Table(t)) => t.data_link.clone().ok_or_else(|| bad(id, "the table has no data link"))?,
_ => return Err(bad(id, "object is not a table")),
};
let host = s.state()?.path.clone();
let file = link_file(id, &link.path, host.as_deref(), chosen)?;
let file = link_file(id, &link.path, s.state()?, folder, chosen)?;
let text = read_link(id, &file)?;
if chosen && let Ok(real) = std::fs::canonicalize(&file) {
remember_link(s.state_mut()?, real);
}
let data = parse_csv(&text, separator(&link.path, &text));
let mut size = (0, 0);
edit(s, &json!({ "handle": h.hex() }), id, |t| {
@@ -325,7 +366,7 @@ fn run_datalink(s: &mut Session, p: &Value) -> Result<Value> {
Ok(())
})?;
let h = r.get("handle").and_then(Value::as_str).and_then(Handle::parse_hex).ok_or_else(|| bad(id, "no table"))?;
let (rows, cols) = update(s, h, true)?;
let (rows, cols) = update(s, h, None, true)?;
Ok(json!({ "handle": h.hex(), "rows": rows, "cols": cols }))
}
@@ -351,8 +392,10 @@ fn run_update(s: &mut Session, p: &Value) -> Result<Value> {
};
let mut updated = 0;
let mut errors = Vec::new();
// Resolved once for every table, and only when there is one.
let folder = if hs.is_empty() { None } else { crate::doc_path::drawing_folder(s.state()?.path.as_deref().map(std::path::Path::new)) };
for h in hs {
match update(s, h, false) {
match update(s, h, folder.as_deref(), false) {
Ok(_) => updated += 1,
Err(e) => errors.push(e.to_string()),
}
@@ -379,6 +422,38 @@ mod tests {
}
}
/// Whether the drawing `st` remembers `file` as linked by the user.
fn remembered(st: &DocState, file: &std::path::Path) -> bool {
st.chosen_links.contains_key(file)
}
/// However many files the user links, the drawing remembers at most [`MAX_CHOSEN_LINKS`] of
/// them: the ones linked last, a file linked again counting as just linked.
#[test]
fn remembered_links_are_the_most_recent_ones() {
let mut st = DocState::new(cadcraft_doc::Drawing::new_metric(), "t", None);
let file = |i: usize| std::path::PathBuf::from(format!("/data/{i}.csv"));
for i in 0..MAX_CHOSEN_LINKS {
remember_link(&mut st, file(i));
}
// Linked again at the bound, the second file drops nothing and becomes the newest, so two
// new files make room by dropping the first and the third.
remember_link(&mut st, file(1));
assert_eq!(st.chosen_links.len(), MAX_CHOSEN_LINKS);
assert!(remembered(&st, &file(0)));
remember_link(&mut st, file(MAX_CHOSEN_LINKS));
remember_link(&mut st, file(MAX_CHOSEN_LINKS + 1));
assert!([1, MAX_CHOSEN_LINKS, MAX_CHOSEN_LINKS + 1].iter().all(|&i| remembered(&st, &file(i))));
assert!(!remembered(&st, &file(0)) && !remembered(&st, &file(2)));
// After many more, the ones linked last are the ones remembered.
let end = 2 * MAX_CHOSEN_LINKS + 10;
for i in MAX_CHOSEN_LINKS + 2..end {
remember_link(&mut st, file(i));
}
assert_eq!(st.chosen_links.len(), MAX_CHOSEN_LINKS, "the bound is reached, not a smaller one");
assert!((end - MAX_CHOSEN_LINKS..end).all(|i| remembered(&st, &file(i))));
}
#[test]
fn csv_parsing() {
assert_eq!(parse_csv("a,b\r\n\"c,d\",\"e\"\"f\"\n", ','), vec![vec!["a", "b"], vec!["c,d", "e\"f"]]);
+15
View File
@@ -5,6 +5,12 @@
//! itself is on, are opened (see `craft_docpath`). A refused path is handled like a missing file,
//! with the reason in its status. Paths the user gives a command (XATTACH, -XREF Path, DATALINK)
//! are their own choice and are used as given.
//!
//! A data link copies its file's text into the drawing, where the next save keeps it. So a data
//! link the drawing itself names is read only from the drawing's folder or a folder below it, once
//! `..` and links are followed ([`drawing_folder`]), unless the user linked that file with
//! DATALINK since the drawing was opened. Otherwise a drawing could copy any file it names into
//! itself for whoever made it.
use std::path::{Path, PathBuf};
@@ -21,6 +27,15 @@ pub fn resolve(stored: &str, document: Option<&Path>) -> Result<PathBuf, Refused
craft_docpath::resolve_absolute(stored.trim(), document.as_deref())
}
/// The folder of the drawing saved at `document` as the file system resolves it
/// ([`std::fs::canonicalize`]: absolute, with `..` and links followed), to compare files resolved
/// the same way with. `None` for a drawing without a file, and when its folder can't be resolved.
pub fn drawing_folder(document: Option<&Path>) -> Option<PathBuf> {
let document = document.filter(|d| !d.as_os_str().is_empty())?;
let folder = std::path::absolute(document).ok()?.parent()?.to_path_buf();
std::fs::canonicalize(folder).ok()
}
#[cfg(test)]
mod tests {
use super::*;
+6
View File
@@ -48,6 +48,11 @@ pub struct DocState {
/// The fonts missing on Windows that a save last named: the next save names them again only
/// when they change.
pub(crate) fonts_noted: String,
/// The files the user linked with DATALINK since the drawing was opened, as the file system
/// resolves them, each with when it was last chosen (a larger number is later):
/// DATALINKUPDATE reads these also outside the drawing's folder ([`crate::doc_path`]). Kept
/// with the open drawing only, never saved.
pub(crate) chosen_links: std::collections::HashMap<std::path::PathBuf, u64>,
}
static NEXT_UID: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);
@@ -77,6 +82,7 @@ impl DocState {
ucs_tilted_noted: false,
erased: Default::default(),
fonts_noted: String::new(),
chosen_links: Default::default(),
}
}
/// The drawing has changes not saved to its file, or the Block Editor has changes not yet
+38 -5
View File
@@ -143,7 +143,8 @@ pub struct LispState {
/// the step is charged it without charging the enclosing callback a second time.
pub(crate) callback_work: u64,
/// The `callback_used` value the callback running now (and so every one it calls) must not
/// pass: the lowest of its own and its callers' allowances.
/// pass: the lowest of its own and its callers' allowances, and of what is left to an
/// expression typed at a prompt.
pub(crate) callback_ceiling: Option<u64>,
}
@@ -200,6 +201,9 @@ struct Run {
inputs: std::collections::VecDeque<Value>,
/// Run to the end without waiting (programmatic calls): `get…` without an input gets nil.
blocking: bool,
/// An expression typed at a command's prompt ([`Session::lisp_eval_answer`]): blocking, with
/// [`ANSWER_CAP`] steps instead of [`BLOCKING_CAP`].
answer: bool,
/// Steps taken, for the cap on blocking runs.
steps: u64,
/// The `*error*` handler is the one running.
@@ -215,6 +219,10 @@ struct Run {
const SLICE: u64 = 400_000;
/// Steps a blocking run (a programmatic call) may take before it is stopped.
const BLOCKING_CAP: u64 = 500_000_000;
/// Steps an expression typed at a command's prompt may take, the callbacks it runs included. It
/// runs blocking, since its value is the prompt's answer, so the interface draws no frame and
/// Esc doesn't reach it until it ends; a routine at `Command:` runs a slice per frame instead.
const ANSWER_CAP: u64 = 20_000_000;
impl Session {
/// The LISP environment of the active drawing.
@@ -272,12 +280,19 @@ impl Session {
inputs: Vec<Value>,
) -> crate::Result<Option<std::result::Result<Value, String>>> {
let forms = read::read_all(src).map_err(|e| crate::EngineError::Other(format!("; error: {}", e.msg)))?;
self.lisp_start(Machine::forms(forms), print, blocking, inputs, "LISP".into())
self.lisp_start(Machine::forms(forms), print, blocking, inputs, "LISP".into(), false)
}
/// Evaluate an expression typed at a command's prompt, whose value is the answer: it runs to
/// the end as a programmatic call does, within [`ANSWER_CAP`] steps.
pub(crate) fn lisp_eval_answer(&mut self, src: &str) -> crate::Result<Option<std::result::Result<Value, String>>> {
let forms = read::read_all(src).map_err(|e| crate::EngineError::Other(format!("; error: {}", e.msg)))?;
self.lisp_start(Machine::forms(forms), false, true, Vec::new(), "LISP".into(), true)
}
/// Call a LISP function (`c:` commands typed at the command line).
fn lisp_call(&mut self, f: Value, label: String) -> crate::Result<Option<std::result::Result<Value, String>>> {
self.lisp_start(Machine::calling(f, Vec::new()), false, false, Vec::new(), label)
self.lisp_start(Machine::calling(f, Vec::new()), false, false, Vec::new(), label, false)
}
fn lisp_start(
@@ -287,6 +302,7 @@ impl Session {
blocking: bool,
inputs: Vec<Value>,
label: String,
answer: bool,
) -> crate::Result<Option<std::result::Result<Value, String>>> {
if self.lisp.active {
return Err(crate::EngineError::Other("a LISP routine is already running".into()));
@@ -305,6 +321,7 @@ impl Session {
before,
inputs: inputs.into(),
blocking,
answer,
steps: 0,
handler: false,
string_bytes: 0,
@@ -368,6 +385,10 @@ impl Session {
// [`Session::typed`] first, never opens a dialog. Restored after the slice, a panic
// in it included, so a person's later command keeps its own origin.
let program_input = std::mem::replace(&mut self.program_input, true);
// Set for every slice (callbacks run only inside one). An answer's callbacks
// (`vl-sort`'s comparator…) run inside one of its steps: they share what is left of
// its allowance instead of each taking a callback's own.
self.lisp.callback_ceiling = run.answer.then(|| self.lisp.callback_used.saturating_add(ANSWER_CAP.saturating_sub(run.steps)));
let outcome = {
let machine = &mut run.machine;
let mut ctx = Ctx { s: self, env: &mut env, depth: 0 };
@@ -395,9 +416,21 @@ impl Session {
// The work the slice did, which one step can take far past the slice. After a panic
// `used` is still the previous slice's; the run ends with the error anyway.
run.steps = run.steps.saturating_add(run.machine.used);
if run.blocking && run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_)) {
// An answer that failed past its cap was stopped by the cap too: a callback that ran
// out of what was left ends here past the cap, since the step that called it counts.
let past_cap = if run.answer {
run.steps > ANSWER_CAP && matches!(outcome, Outcome::Wait(_) | Outcome::Error(_))
} else {
run.steps > BLOCKING_CAP && matches!(outcome, Outcome::Wait(_))
};
if run.blocking && past_cap {
let msg = if run.answer {
format!("expression at a prompt stopped after {ANSWER_CAP} steps; run long routines at Command:, where Esc stops them")
} else {
format!("routine stopped after {BLOCKING_CAP} steps")
};
self.lisp.run = Some(run);
self.lisp_error(LispError::quit(format!("routine stopped after {BLOCKING_CAP} steps")));
self.lisp_error(LispError::quit(msg));
return;
}
match outcome {
+3 -1
View File
@@ -205,6 +205,8 @@ pub(super) fn float(a: &[Value]) -> R {
Ok(Value::Real(num(&a[0])?))
}
/// The greatest common divisor. The one past 32 bits, 2147483648 (of -2147483648 and 0 or
/// itself), is a real, as the reader and `fix` give such a number, not the largest integer.
pub(super) fn gcd(a: &[Value]) -> R {
arity(a, 2, 2)?;
let (mut x, mut y) = (i64::from(int(&a[0])?).abs(), i64::from(int(&a[1])?).abs());
@@ -216,7 +218,7 @@ pub(super) fn gcd(a: &[Value]) -> R {
x = y;
y = t;
}
Ok(Value::Int(i32::try_from(x).unwrap_or(i32::MAX)))
Ok(i32::try_from(x).map_or(Value::Real(x as f64), Value::Int))
}
pub(super) fn logand(a: &[Value]) -> R {
+9 -2
View File
@@ -51,13 +51,20 @@ pub(super) fn itoa(a: &[Value]) -> R {
Ok(Value::str(&int(&a[0])?.to_string()))
}
/// C's `atoi`: leading blanks, a sign, digits; 0 when there are none.
/// C's `atoi`: leading blanks, a sign, digits; 0 when there are none. Digits past the 32-bit
/// range give a real, the number `atof` reads from them, as the reader gives one for such a
/// literal: neither wrapped nor clamped to an integer.
pub(super) fn atoi(a: &[Value]) -> R {
arity(a, 1, 1)?;
let s = string(&a[0])?;
let t = s.trim_start();
let end = t.char_indices().take_while(|(i, c)| c.is_ascii_digit() || (*i == 0 && (*c == '-' || *c == '+'))).count();
Ok(Value::Int(t.get(..end).and_then(|n| n.parse::<i64>().ok()).map(|n| n as i32).unwrap_or(0)))
let digits = t.get(..end).unwrap_or_default();
match digits.parse::<i32>() {
Ok(n) => Ok(Value::Int(n)),
Err(_) if digits.bytes().any(|b| b.is_ascii_digit()) => atof(&[Value::str(digits)]),
Err(_) => Ok(Value::Int(0)),
}
}
/// C's `atof`: the number token at the start; 0.0 when there is none.
+47
View File
@@ -1602,6 +1602,53 @@ fn a_lisp_value_at_a_prompt_is_not_evaluated_again() {
assert_eq!(r, Some(4.0));
}
/// #1926: an expression typed at a command's prompt runs to the end before the prompt takes its
/// value, so the interface waits for it: it gets a far smaller allowance than a programmatic run,
/// and the callbacks it runs share that allowance instead of each taking a callback's own.
#[test]
fn an_expression_at_a_prompt_has_a_short_allowance() {
let mut s = session();
let circles = |s: &Session| s.doc().unwrap().model.iter().filter(|e| matches!(e.kind, cadcraft_doc::EntityKind::Circle(_))).count();
let last_error = |s: &Session, from: usize| s.log.get(from..).and_then(|l| l.iter().rev().find(|l| l.starts_with("; error:")).cloned());
let endless = "(while (< i 2000000000) (setq i (1+ i)))";
s.cmdline(&format!("circle 0,0 (progn (setq i 0) {endless} 5)")).unwrap();
let typed: i64 = ok(&mut s, "i").parse().unwrap();
let stopped = last_error(&s, 0);
assert!(typed > 0 && stopped.is_some(), "the loop ran and was stopped");
assert_eq!(circles(&s), 0, "the stopped expression gave no radius");
assert!(s.running.is_none(), "CIRCLE ends with the failed expression");
// The same loop run programmatically goes on to twice as far.
let further = format!("(setq i 0) (while (< i {}) (setq i (1+ i))) i", typed * 2);
assert_eq!(ok(&mut s, &further), (typed * 2).to_string());
// Half the loop, then a comparator's endless loop: the comparator gets what the expression
// has left, not a callback's own allowance, and the expression stops as the loop alone did.
let half = format!("(while (< i {}) (setq i (1+ i)))", typed / 2);
let from = s.log.len();
s.cmdline(&format!("circle 0,0 (progn (setq i 0) {half} (vl-sort '(1 2) '(lambda (a b) {endless} (< a b))) 5)")).unwrap();
let with_callback: i64 = ok(&mut s, "i").parse().unwrap();
assert!(with_callback > typed / 2 && with_callback < typed * 5 / 4, "{with_callback} against {typed}");
assert_eq!(last_error(&s, from), stopped);
assert_eq!(circles(&s), 0);
}
/// #1933: a whole number past 32 bits is a real, as the reader and `fix` make one, not a wrapped
/// or clamped integer: `atoi` gives the number its digits read as, `gcd` the true divisor.
#[test]
fn atoi_and_gcd_past_32_bits_give_reals() {
let mut s = session();
for digits in ["2147483648", "-2147483649", "99999999999", "99999999999999999999"] {
assert_eq!(ok(&mut s, &format!("(= (atoi \"{digits}\") (read \"{digits}\"))")), "T", "{digits}");
}
// Past every real too: the largest, as `atof` reads it.
let huge = "9".repeat(400);
assert_eq!(ok(&mut s, &format!("(= (atoi \"{huge}\") (atof \"{huge}\"))")), "T");
// Within the range, integers as before.
assert_eq!(ok(&mut s, "(list (atoi \" -2147483648x\") (atoi \"+2147483647\") (atoi \"-\"))"), "(-2147483648 2147483647 0)");
let past = "(abs (float -2147483648))";
assert_eq!(ok(&mut s, &format!("(= (gcd -2147483648 0) (gcd 0 -2147483648) (gcd -2147483648 -2147483648) {past})")), "T");
assert_eq!(ok(&mut s, "(list (gcd -2147483648 6) (gcd 2147483647 0))"), "(2 2147483647)");
}
#[test]
fn atof_out_of_range_exponent_reads_whole_token() {
let mut s = Session::new();
+3 -2
View File
@@ -89,11 +89,12 @@ impl Session {
if tt.starts_with('\'') {
return self.start(tt);
}
// A LISP expression typed at a command's prompt: its value is the answer.
// A LISP expression typed at a command's prompt: its value is the answer, so it runs to
// the end first, with a short allowance (the interface waits for it).
// Not at a free-text prompt: there the text is the answer (CAL takes "(3+4)*2").
if lisp && lisp_expression(tt) && !prompt.accept.text && self.lisp_prompt().is_none() && !self.lisp_groups_undo() {
let src = tt.strip_prefix('!').unwrap_or(tt).to_string();
let v = match self.lisp_eval(&src, false, true, Vec::new()) {
let v = match self.lisp_eval_answer(&src) {
Ok(Some(Ok(v))) => v,
Ok(_) => return Ok(()),
Err(e) => {
+139
View File
@@ -171,3 +171,142 @@ fn data_links_saved_in_a_drawing_are_read_beside_it_or_on_this_computer_only() {
assert!(errors.iter().all(|e| e.contains("another computer")), "{errors:?}");
let _ = std::fs::remove_dir_all(&base);
}
/// Read and write drawings through `cadcraft-io`, as the app does.
fn use_file_io() {
cadcraft_engine::cmd::file::set_io(cadcraft_engine::cmd::file::IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
plot: None,
});
}
/// A new table, `i` rows of tables down, whose data link names `path` as a drawing file stores it.
fn linked_table(s: &mut Session, i: usize, path: &str) {
let r = s.execute("table", &json!({ "at": [0, 10.0 * i as f64], "cols": 2, "rows": 1 })).unwrap();
let h = Handle::parse_hex(r["handle"].as_str().unwrap()).unwrap();
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
if let EntityKind::Table(t) = &mut e.kind {
t.data_link = Some(cadcraft_engine::doc::DataLink { path: path.to_string(), start_row: 0 });
}
})
.unwrap();
}
/// The text of every cell of every table in model space.
fn table_texts(s: &Session) -> String {
let mut out = String::new();
for e in s.doc().unwrap().model.iter() {
if let EntityKind::Table(t) = &e.kind {
for cell in t.cells.iter().flatten() {
out.push_str(&cell.text);
out.push('\n');
}
}
}
out
}
/// A drawing's own data link can't copy a file from outside its folder into it: not by `..`, not
/// by an absolute path, not through a folder whose name only starts the same, not through a link
/// inside the folder that leads out. Links within the folder, also by `..` back into it, still
/// update.
#[test]
fn a_saved_data_link_reads_no_file_outside_the_drawings_folder() {
use_file_io();
let base = std::env::temp_dir().join(format!("cadcraft-datalink-outside-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (dir, private, sibling) = (base.join("plans"), base.join("private"), base.join("plans-old"));
for d in [dir.join("sub"), private.clone(), sibling.clone()] {
std::fs::create_dir_all(d).unwrap();
}
let secret = "not-for-the-drawing";
std::fs::write(private.join("secret.csv"), format!("{secret},1\n")).unwrap();
std::fs::write(sibling.join("secret.csv"), format!("{secret},2\n")).unwrap();
std::fs::write(dir.join("parts.csv"), "bolt,4\n").unwrap();
std::fs::write(dir.join("sub").join("more.csv"), "nut,8\n").unwrap();
let path = |p: std::path::PathBuf| p.to_str().unwrap().to_string();
let inside = ["parts.csv".to_string(), "sub/more.csv".to_string(), "../plans/parts.csv".to_string(), path(dir.join("parts.csv"))];
let mut outside = vec!["../private/secret.csv".to_string(), path(private.join("secret.csv")), path(sibling.join("secret.csv"))];
#[cfg(unix)]
let linked = std::os::unix::fs::symlink(private.join("secret.csv"), dir.join("link.csv")).is_ok();
// Windows lets only some accounts make symbolic links.
#[cfg(windows)]
let linked = std::os::windows::fs::symlink_file(private.join("secret.csv"), dir.join("link.csv")).is_ok();
if linked {
outside.push("link.csv".to_string());
} else {
eprintln!("symbolic links can't be made here: the link case is not checked");
}
let mut s = Session::new();
for (i, link) in inside.iter().chain(&outside).enumerate() {
linked_table(&mut s, i, link);
}
let host = dir.join("host.dxf");
s.execute("saveas", &json!({ "path": path(host.clone()) })).unwrap();
let mut s = Session::new();
s.execute("open", &json!({ "path": path(host) })).unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], inside.len(), "only the files in the drawing's folder: {r}");
let errors: Vec<&str> = r["errors"].as_array().unwrap().iter().filter_map(|e| e.as_str()).collect();
assert_eq!(errors.len(), outside.len(), "{errors:?}");
assert!(errors.iter().all(|e| e.contains("outside the drawing's folder")), "{errors:?}");
let texts = table_texts(&s);
assert!(texts.contains("bolt") && texts.contains("nut"), "the files inside are read: {texts}");
assert!(!texts.contains(secret), "{texts}");
// So the next save carries nothing of them either.
let after = dir.join("after.dxf");
s.execute("saveas", &json!({ "path": path(after.clone()) })).unwrap();
assert!(!std::fs::read_to_string(&after).unwrap().contains(secret));
let _ = std::fs::remove_dir_all(&base);
}
/// A file outside the drawing's folder that the user links with DATALINK keeps updating while
/// the drawing stays open; once it is opened again, the drawing alone can't read it until the
/// user links it again.
#[test]
fn a_file_the_user_links_outside_the_folder_updates_until_the_drawing_is_opened_again() {
use_file_io();
let base = std::env::temp_dir().join(format!("cadcraft-datalink-chosen-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&base);
let (dir, data) = (base.join("plans"), base.join("data"));
std::fs::create_dir_all(&dir).unwrap();
std::fs::create_dir_all(&data).unwrap();
let bom = data.join("bom.csv");
let bom_path = bom.to_str().unwrap();
let host = dir.join("host.dxf");
let host_path = host.to_str().unwrap();
let mut s = Session::new();
let r = s.execute("table", &json!({ "at": [0, 0], "cols": 2, "rows": 1 })).unwrap();
let h = r["handle"].as_str().unwrap().to_string();
s.execute("saveas", &json!({ "path": host_path })).unwrap();
std::fs::write(&bom, "bolt,rev-a\n").unwrap();
s.execute("datalink", &json!({ "handle": h, "path": bom_path })).unwrap();
std::fs::write(&bom, "bolt,rev-b\n").unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], 1, "{r}");
assert!(table_texts(&s).contains("rev-b"));
s.execute("saveas", &json!({ "path": host_path })).unwrap();
let mut s = Session::new();
s.execute("open", &json!({ "path": host_path })).unwrap();
std::fs::write(&bom, "bolt,rev-c\n").unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], 0, "{r}");
assert!(r["errors"][0].as_str().unwrap().contains("outside the drawing's folder"), "{r}");
assert!(!table_texts(&s).contains("rev-c"));
// Linked again by the user, it reads and keeps updating.
s.execute("datalink", &json!({ "handle": h, "path": bom_path })).unwrap();
assert!(table_texts(&s).contains("rev-c"));
std::fs::write(&bom, "bolt,rev-d\n").unwrap();
let r = s.execute("datalinkupdate", &json!({})).unwrap();
assert_eq!(r["updated"], 1, "{r}");
assert!(table_texts(&s).contains("rev-d"));
let _ = std::fs::remove_dir_all(&base);
}
+35
View File
@@ -66,6 +66,41 @@ pub(crate) fn named_ucs<'a>(
ucss.iter().find(|u| u.name.eq_ignore_ascii_case(name) && is_named_frame(u, origin, x, y))
}
/// The drawing's UCSs by name with its ASCII letters lower-cased, each name with its positions in
/// table order, so the named UCS of each of many layouts is found without scanning every UCS: a
/// file of N layouts each naming one of N UCSs cost N² name comparisons (#1924).
pub(crate) struct UcsNames<'a> {
ucss: &'a [cadcraft_doc::Ucs],
at: std::collections::BTreeMap<String, Vec<usize>>,
}
impl<'a> UcsNames<'a> {
pub(crate) fn new(ucss: &'a [cadcraft_doc::Ucs]) -> Self {
let mut at: std::collections::BTreeMap<String, Vec<usize>> = std::collections::BTreeMap::new();
for (i, u) in ucss.iter().enumerate() {
at.entry(u.name.to_ascii_lowercase()).or_default().push(i);
}
UcsNames { ucss, at }
}
/// What [`named_ucs`] finds: the first UCS named `name` (without case) whose frame is
/// `origin`, `x`, `y`.
pub(crate) fn named(
&self,
name: &str,
origin: cadcraft_geom::Vec3,
x: cadcraft_geom::Vec3,
y: cadcraft_geom::Vec3,
) -> Option<&'a cadcraft_doc::Ucs> {
let name = name.trim();
if name.is_empty() {
return None;
}
let ucss = self.ucss;
self.at.get(&name.to_ascii_lowercase())?.iter().filter_map(|&i| ucss.get(i)).find(|u| is_named_frame(u, origin, x, y))
}
}
/// Whether `x` and `y` can be a UCS's axes: finite, not zero and not along each other (relative
/// to their lengths, so short but square axes are fine). Read and written by the same rule.
pub(crate) fn usable_axes(x: cadcraft_geom::Vec3, y: cadcraft_geom::Vec3) -> bool {
+3 -2
View File
@@ -1,7 +1,7 @@
use std::collections::HashSet;
use super::common::T;
use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity};
use super::entities::{entity_extras, entity_plot_style, entity_with_table_budget, insert_attribs, polyline_entity, reference_left_tilted};
use super::objects::{MAX_OBJECTS, Objects, page_setup};
use super::{Block, BlockDef, Drawing, Entity, EntityKind, Handle, HashMap, Layout, LayoutDef, Rx, Tag, Vec2, record_slices};
@@ -83,7 +83,8 @@ pub(super) fn parse_entities(
}
"INSERT" if t.i(66) == Some(1) => {
let ins_layer = kindent.as_ref().map(|(c, _)| c.layer.clone()).unwrap_or_default();
let attribs = insert_attribs(recs, &mut i, &ins_layer);
let left_tilted = kindent.as_ref().is_some_and(|(c, _)| reference_left_tilted(c.extrusion));
let attribs = insert_attribs(recs, &mut i, &ins_layer, left_tilted);
if let Some((_, EntityKind::Insert(ins))) = kindent.as_mut() {
ins.attribs = attribs;
}
+30 -6
View File
@@ -1,7 +1,7 @@
use super::common::{T, common, ocs, plan_of_tilted, run_points, tilted};
use super::hatch::{CurvePoints, hatch};
use super::mtext_dxf;
use super::text::{attdef, attrib_modes, attrib_props, mtext_from, multiline_attrib, split_embedded, text_from};
use super::text::{attdef, attrib_modes, attrib_props, flatten_tilted, mtext_from, multiline_attrib, split_embedded, text_from};
use super::{
Arc, Attrib, Circle, Common, DimKind, Dimension, Ellipse, EntityKind, Face3d, Handle, HashMap, Helix, HelixConstrain, Insert, Leader, Line,
LwPolyline, MAX_FRAME_CHARS, Point, PolyVertex, Polyline3d, RawTag, RayLine, Rx, Solid, Spline, Table, TableCell, Tag, Tolerance, Unknown, Vec2,
@@ -172,16 +172,17 @@ pub(super) fn entity_with_table_budget(
"XLINE" => EntityKind::XLine(RayLine { base: t.p(10), dir: t.p(11) }),
"TEXT" => EntityKind::Text(text_from(&t)),
"MTEXT" => EntityKind::MText(mtext_from(tags, &c)),
"ATTDEF" => EntityKind::AttDef(attdef(tags, &c)),
"ATTDEF" => EntityKind::AttDef(attdef(tags, &mut c)),
"INSERT" => {
// A mirrored block reference comes with extrusion (0,0,-1): its insertion point, scale,
// rotation and column spacing are in that OCS, where x runs the other way. In the WCS that
// is the mirrored point, a negative x scale, the opposite rotation and a negative column
// spacing. Noise of up to 1e-3 in the extrusion's x/y moves the projection by ~1e-7 of the
// size, so it still counts as mirrored. A truly tilted extrusion (block plane not parallel
// to XY) needs the full 3D block transform, which Insert cannot hold; it is left as read.
// to XY) needs the full 3D block transform, which Insert cannot hold; it is left as read,
// and so are its ATTRIBs facing up (`reference_left_tilted`).
let n = c.extrusion;
let mirrored = n.z < 0.0 && n.x.hypot(n.y) <= 1e-3 * n.z.abs();
let mirrored = mirrored_reference(n);
let mut p = t.p(10);
let mut scale = Vec3::new(t.fd(41, 1.0), t.fd(42, 1.0), t.fd(43, 1.0));
let mut rotation = t.fd(50, 0.0).to_radians();
@@ -660,8 +661,26 @@ pub(super) fn polyline_entity(recs: &[(String, &[Tag])], i: &mut usize, t: &T) -
Some((c, k, extra))
}
/// The ATTRIB records after an INSERT, advancing `i` past them and their SEQEND.
pub(super) fn insert_attribs(recs: &[(String, &[Tag])], i: &mut usize, ins_layer: &str) -> Vec<Attrib> {
/// Whether a block reference with extrusion `n` is mirrored: (0,0,-1), up to noise of 1e-3 in x and
/// y. The INSERT arm maps such a reference's point, scale, rotation and column spacing.
fn mirrored_reference(n: Vec3) -> bool {
n.z < 0.0 && n.x.hypot(n.y) <= 1e-3 * n.z.abs()
}
/// Whether a block reference with extrusion `n` is read as is although its plane is tilted: the
/// INSERT arm maps only a mirrored one, since `Insert` cannot hold the 3D transform, so its block is
/// drawn at the OCS point read. Its ATTRIBs facing up are then left as read too: mapped on their
/// own they would leave the block they belong to. (One facing down is mirrored by `text_from`, as
/// before.)
pub(super) fn reference_left_tilted(n: Vec3) -> bool {
let unit = n.normalized();
!mirrored_reference(n) && (unit.x.abs() >= 1e-12 || unit.y.abs() >= 1e-12)
}
/// The ATTRIB records after an INSERT, advancing `i` past them and their SEQEND. Those of a
/// reference read as is in its tilted plane (`left_tilted`, [`reference_left_tilted`]) stay as
/// read with it.
pub(super) fn insert_attribs(recs: &[(String, &[Tag])], i: &mut usize, ins_layer: &str, left_tilted: bool) -> Vec<Attrib> {
let mut attribs = Vec::new();
while let Some((k2, t2)) = recs.get(*i) {
if k2 == "ATTRIB" {
@@ -671,6 +690,11 @@ pub(super) fn insert_attribs(recs: &[(String, &[Tag])], i: &mut usize, ins_layer
let multiline = multiline_attrib(embedded, &common(&tt));
let own = T(own);
let mut text = text_from(&own);
// An ATTRIB keeps no plane of its own: one in a tilted plane is drawn as seen from above,
// unless its reference is left in its own tilted plane.
if !left_tilted {
flatten_tilted(&mut text, &own);
}
if let Some(m) = &multiline {
text.value.clone_from(&m.read_as);
}
+16 -6
View File
@@ -1,6 +1,8 @@
use super::common::T;
use super::{Color, EntityKind, Gradient, Handle, Hatch, HatchLoop, PolyVertex, Rgb, Spline, Tag, Vec2};
mod chain;
/// Upper bound on the points the elliptic and spline edges of one HATCH's boundary are sampled
/// into: the point budget the renderer gives one hatch's loops
/// ([`cadcraft_geom::MAX_TESSELLATED_POINTS`]).
@@ -129,25 +131,33 @@ fn polyline_boundary(tags: &[Tag], index: &mut usize) -> Option<Vec<PolyVertex>>
Some(vertices)
}
/// An edge path's vertices. Each edge is read on its own, then [`chain::chain`] joins them.
fn edge_boundary(tags: &[Tag], index: &mut usize, budget: &mut EdgeBudget) -> Option<Vec<PolyVertex>> {
let get = |i: usize| tags.get(i);
seek_code(tags, index, 93);
let count = get(*index)?.i64().clamp(0, 1_000_000) as usize;
*index += 1;
let mut vertices = Vec::new();
// Every edge's points back to back, and where each edge's are.
let (mut points, mut edges) = (Vec::new(), Vec::new());
let mut edge = Vec::new();
for _ in 0..count {
seek_code(tags, index, 72);
let kind = get(*index)?.i64();
*index += 1;
match kind {
1 => line_edge(tags, index, &mut vertices),
2 => circular_edge(tags, index, &mut vertices),
3 => elliptic_edge(tags, index, &mut vertices, budget),
4 => spline_edge(tags, index, &mut vertices, budget),
1 => line_edge(tags, index, &mut edge),
2 => circular_edge(tags, index, &mut edge),
3 => elliptic_edge(tags, index, &mut edge, budget),
4 => spline_edge(tags, index, &mut edge, budget),
_ => {}
}
if !edge.is_empty() {
let start = points.len();
points.append(&mut edge);
edges.push(start..points.len());
}
}
Some(vertices)
Some(chain::chain(&points, &edges))
}
fn edge_value(tags: &[Tag], index: usize) -> f64 {
+288
View File
@@ -0,0 +1,288 @@
//! Joining the edges of a HATCH edge path into loops.
//!
//! The DXF Reference lists a boundary path's edges one after another: group 72 gives each edge's
//! type, and the edge's own groups follow. Some files list the edges out of order, or store some
//! of them end to start. Read in file order, the vertex list of such a path jumps from edge to
//! edge, and the even-odd fill then fills the polygon those jumps make instead of the outline.
use std::collections::VecDeque;
use std::ops::Range;
use super::{PolyVertex, Vec2};
/// Points this close are one vertex where an edge meets the next. It is the tolerance the edge
/// readers used before edges were chained, so a path whose edges run on is read as before.
const SAME_POINT: f64 = 1e-9;
/// The share of a loop's extent within which two edge ends meet.
///
/// It only decides which edge follows which: no point is moved, and two ends that meet but
/// differ keep both points, so a real gap that small stays a segment of its own length. A
/// millionth is far above the rounding of the values a file stores (an arc's ends are computed
/// from its centre, radius and angles), and far below what a picture can show: a loop drawn
/// 10,000 pixels wide puts it at a hundredth of a pixel.
const MEET_SHARE: f64 = 1e-6;
/// The vertices of an edge path, from its edges in file order. Each edge is a range of `points`,
/// read on its own: its first point, the points between (a bulge on the vertex before each arc)
/// and its last point.
///
/// A path whose edges run on, each starting where the one before ends, is joined in file order,
/// as it always was. Otherwise the edges are chained into runs:
/// - A run starts with the first edge not yet used, as the file stores it.
/// - An edge with an end at the run's last point goes after it, turned around when that end is
/// its last point. Once none is left, an edge with an end at the run's first point goes before
/// it, turned around when that end is its first point. Of several, the one listed first.
/// - An edge that meets no run starts a new one.
///
/// Two ends meet when they are within the tolerance of each other (see [`MEET_SHARE`]). A loop
/// whose lookups pass their budget ([`CHECKS_PER_END`]) is joined in file order instead.
///
/// A closed run, one that ends where it starts, is a loop of its own. The runs left open make up
/// one loop together, in the order of their first edges, each joined straight to the next as a
/// path read in file order is (a path with missing edges then still closes as before). The vertex
/// list goes from the first loop's start to each later loop and back, and closes each later loop
/// straight from its last point to its first. An even-odd fill crosses each of those jumps
/// twice, so it fills each loop as a loop of its own.
pub(super) fn chain(points: &[PolyVertex], edges: &[Range<usize>]) -> Vec<PolyVertex> {
let mut out = Vec::with_capacity(points.len().saturating_add(edges.len()));
let chained = Frame::of(points)
.filter(|frame| !runs_on(points, edges, frame.tol))
.and_then(|frame| runs(&frame, points, edges, CHECKS_PER_END).map(|runs| (frame, runs)));
let Some((frame, (order, run_ends))) = chained else {
for edge in edges {
append(&mut out, edge_points(points, edge), false);
}
return out;
};
let span = |run: &[(usize, bool)]| {
let first = run.first().and_then(|&(edge, turned)| placed_ends(points, edges, edge, turned))?;
let last = run.last().and_then(|&(edge, turned)| placed_ends(points, edges, edge, turned))?;
Some((first.0, last.1))
};
// Each loop as the runs it is made of, ranges of `order`.
let mut loops: Vec<Vec<Range<usize>>> = Vec::new();
let (mut open, mut from): (Option<usize>, usize) = (None, 0);
for &to in &run_ends {
let run = from..to;
from = to;
let closed = span(order.get(run.clone()).unwrap_or_default()).is_some_and(|(start, end)| end.near(start, frame.tol));
match open.and_then(|i| loops.get_mut(i)) {
Some(runs) if !closed => runs.push(run),
_ => {
open = open.or((!closed).then_some(loops.len()));
loops.push(vec![run]);
}
}
}
let mut anchor = None;
for runs in &loops {
let placed: Vec<(usize, bool)> = runs.iter().flat_map(|run| order.get(run.clone()).unwrap_or_default().iter().copied()).collect();
let Some((start, end)) = span(&placed) else { continue };
let later = anchor.is_some();
if let Some(anchor) = anchor {
extend(&mut out, std::iter::once(PolyVertex::new(anchor)));
} else {
anchor = Some(start);
}
for (edge, turned) in placed {
append(&mut out, edges.get(edge).map_or(&[][..], |edge| edge_points(points, edge)), turned);
}
// Back at the exact start, even when the end is within the tolerance of it: the jump
// back to the anchor then retraces the jump out.
if later && end != start {
extend(&mut out, std::iter::once(PolyVertex::new(start)));
}
}
out
}
/// Whether each edge starts where the one before it ends.
fn runs_on(points: &[PolyVertex], edges: &[Range<usize>], tol: f64) -> bool {
edges.windows(2).all(|pair| match pair {
[before, after] => ends(points, before).zip(ends(points, after)).is_some_and(|((_, end), (start, _))| end.near(start, tol)),
_ => true,
})
}
/// Ends the lookups may visit, per end of the loop. A lookup visits, in up to nine cells, the
/// ends after each cell's first unused one and before the best match so far; in a drawing that
/// is a few. A crafted loop can keep many unused ends just past the tolerance of a point it
/// returns to again and again, and visit them at every return.
const CHECKS_PER_END: usize = 32;
/// The edges in the order they are chained, each with whether it is turned around, and where
/// each run ends in that list. None when the lookups visit more than `checks_per_end` ends per
/// end of the loop: the loop is then read in file order.
fn runs(frame: &Frame, points: &[PolyVertex], edges: &[Range<usize>], checks_per_end: usize) -> Option<(Vec<(usize, bool)>, Vec<usize>)> {
let mut index = EndIndex::new(frame, points, edges, checks_per_end);
let mut used = vec![false; edges.len()];
let (mut order, mut run_ends) = (Vec::with_capacity(edges.len()), Vec::new());
let mut run = VecDeque::new();
for first in 0..edges.len() {
let Some((mut head, mut tail)) = edges.get(first).and_then(|edge| ends(points, edge)) else { continue };
if !take(&mut used, first) {
continue;
}
run.push_back((first, false));
while let Some((edge, at_last)) = index.find(frame, tail, &used) {
let Some((start, end)) = edges.get(edge).and_then(|e| ends(points, e)) else { break };
if !take(&mut used, edge) {
break;
}
run.push_back((edge, at_last));
tail = if at_last { start } else { end };
}
while let Some((edge, at_last)) = index.find(frame, head, &used) {
let Some((start, end)) = edges.get(edge).and_then(|e| ends(points, e)) else { break };
if !take(&mut used, edge) {
break;
}
run.push_front((edge, !at_last));
head = if at_last { start } else { end };
}
if index.spent {
return None;
}
order.extend(run.drain(..));
run_ends.push(order.len());
}
Some((order, run_ends))
}
/// Marks an edge used; false when it already was.
fn take(used: &mut [bool], edge: usize) -> bool {
used.get_mut(edge).is_some_and(|used| !std::mem::replace(used, true))
}
/// Where a loop's edge ends are looked up: the lower corner of the box around its finite points,
/// and the distance within which two ends meet, which is also the side of a lookup cell.
struct Frame {
low: Vec2,
tol: f64,
}
impl Frame {
/// None when no point is finite, or the points span more than a double holds.
fn of(points: &[PolyVertex]) -> Option<Frame> {
let mut finite = points.iter().map(|v| v.p).filter(|p| p.is_finite());
let first = finite.next()?;
let (low, high) = finite.fold((first, first), |(low, high), p| (low.min(p), high.max(p)));
let extent = (high.x - low.x).max(high.y - low.y);
extent.is_finite().then(|| Frame { low, tol: (extent * MEET_SHARE).max(SAME_POINT) })
}
/// The cell a point is in. The box is at most a million cells across (`extent / tol`), so
/// the conversions are exact.
fn cell(&self, p: Vec2) -> Option<(i64, i64)> {
p.is_finite().then(|| (((p.x - self.low.x) / self.tol).floor() as i64, ((p.y - self.low.y) / self.tol).floor() as i64))
}
}
/// The finite edge ends of a loop, by cell. A cell is `tol` wide, so an end within `tol` of a
/// point is in the point's cell or one next to it.
struct EndIndex {
/// Each end's cell, id (twice its edge's index, plus one for the edge's last point) and
/// point, sorted by cell and id.
ends: Vec<((i64, i64), usize, Vec2)>,
/// At a cell's first entry: the cell's first entry that may still be unused.
next: Vec<usize>,
/// Ends lookups may still visit.
checks: usize,
/// The lookups visited every end they were allowed: they find nothing more.
spent: bool,
}
impl EndIndex {
fn new(frame: &Frame, points: &[PolyVertex], edges: &[Range<usize>], checks_per_end: usize) -> EndIndex {
let mut ends: Vec<((i64, i64), usize, Vec2)> = edges
.iter()
.enumerate()
.filter_map(|(i, edge)| ends(points, edge).map(|(start, end)| (i, start, end)))
.flat_map(|(i, start, end)| [(2 * i, start), (2 * i + 1, end)])
.filter_map(|(id, p)| frame.cell(p).map(|cell| (cell, id, p)))
.collect();
ends.sort_unstable_by_key(|&(cell, id, _)| (cell, id));
let next = (0..ends.len()).collect();
let checks = ends.len().saturating_mul(checks_per_end);
EndIndex { ends, next, checks, spent: false }
}
/// The unused edge listed first with an end within `tol` of `p`, and whether that end is the
/// edge's last point (its first point when both are).
fn find(&mut self, frame: &Frame, p: Vec2, used: &[bool]) -> Option<(usize, bool)> {
let (x, y) = frame.cell(p)?;
let mut best = None;
for cell in (-1..=1).flat_map(|dx| (-1..=1).map(move |dy| (x + dx, y + dy))) {
best = self.first_within(cell, p, frame.tol, used, best).or(best);
}
best.map(|id| (id / 2, id % 2 == 1))
}
/// The first end in `cell` within `tol` of `p` whose edge is unused, listed before `below`.
/// Used ends at the front of the cell are skipped once for good.
fn first_within(&mut self, cell: (i64, i64), p: Vec2, tol: f64, used: &[bool], below: Option<usize>) -> Option<usize> {
let unused = |id: usize| !used.get(id / 2).copied().unwrap_or(true);
let first = self.ends.partition_point(|(c, ..)| *c < cell);
let mut at = self.next.get(first).copied()?;
while self.ends.get(at).is_some_and(|&(c, id, _)| c == cell && !unused(id)) {
at += 1;
}
if let Some(next) = self.next.get_mut(first) {
*next = at;
}
for &(c, id, q) in self.ends.get(at..).unwrap_or_default() {
if c != cell || below.is_some_and(|below| id >= below) {
break;
}
if self.checks == 0 {
self.spent = true;
return None;
}
self.checks -= 1;
if unused(id) && q.near(p, tol) {
return Some(id);
}
}
None
}
}
fn edge_points<'a>(points: &'a [PolyVertex], edge: &Range<usize>) -> &'a [PolyVertex] {
points.get(edge.clone()).unwrap_or_default()
}
/// An edge's first and last point.
fn ends(points: &[PolyVertex], edge: &Range<usize>) -> Option<(Vec2, Vec2)> {
let points = edge_points(points, edge);
Some((points.first()?.p, points.last()?.p))
}
/// An edge's first and last point as placed, turned around or not.
fn placed_ends(points: &[PolyVertex], edges: &[Range<usize>], edge: usize, turned: bool) -> Option<(Vec2, Vec2)> {
let (start, end) = ends(points, edges.get(edge)?)?;
Some(if turned { (end, start) } else { (start, end) })
}
/// Appends an edge's vertices. Turned around, its points come in reverse order, and each arc's
/// bulge is negated and moved to the vertex that now starts the arc.
fn append(out: &mut Vec<PolyVertex>, edge: &[PolyVertex], turned: bool) {
if turned {
let before = edge.iter().rev().skip(1).map(Some).chain([None]);
extend(out, edge.iter().rev().zip(before).map(|(v, before)| PolyVertex::with_bulge(v.p, before.map_or(0.0, |b| -b.bulge))));
} else {
extend(out, edge.iter().copied());
}
}
/// Appends vertices, leaving out the first when the list already ends there; its bulge then goes
/// on the list's last vertex.
fn extend(out: &mut Vec<PolyVertex>, mut vertices: impl Iterator<Item = PolyVertex>) {
if let Some(first) = vertices.next() {
match out.last_mut() {
Some(last) if last.p.near(first.p, SAME_POINT) => last.bulge = first.bulge,
_ => out.push(first),
}
}
out.extend(vertices);
}
+2 -1
View File
@@ -196,6 +196,7 @@ impl Objects {
/// Layouts' UCSs: the World UCS, unusable axes or no such layout leave it unset.
fn apply_layout_ucss(&self, d: &mut Drawing, rx: &Rx) {
let layout_at = super::document::layout_positions(d);
let ucs_names = crate::dxf_ext::UcsNames::new(&d.ucss);
for (name, origin, x, y, named) in &self.layout_ucss {
let usable = origin.is_finite() && crate::dxf_ext::usable_axes(*x, *y);
// The named UCS group 345 points at, only while the layout's frame is still that
@@ -203,7 +204,7 @@ impl Objects {
let ucs_name = named
.as_ref()
.and_then(|h| rx.ucss.get(&h.trim().to_ascii_uppercase()))
.and_then(|n| crate::dxf_ext::named_ucs(&d.ucss, n, *origin, *x, *y))
.and_then(|n| ucs_names.named(n, *origin, *x, *y))
.map(|u| u.name.clone())
.unwrap_or_default();
let world = origin.len() <= 1e-12 && (*x - Vec3::new(1.0, 0.0, 0.0)).len() <= 1e-12 && (*y - Vec3::new(0.0, 1.0, 0.0)).len() <= 1e-12;
+33 -20
View File
@@ -114,11 +114,10 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
// The same for linetypes (first definition wins) and text styles (last definition wins).
let mut linetype_names: std::collections::HashSet<String> = d.linetypes.iter().map(|l| l.name.to_ascii_lowercase()).collect();
let mut style_index: HashMap<String, usize> = d.text_styles.iter().enumerate().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
// And for dimension styles (a later record replaces the first of its name, which keeps its
// place); ordered by name rather than hashed, so its cost does not depend on hash keys. Built
// in reverse, so the first style of a name is the one kept.
let mut dim_style_index: std::collections::BTreeMap<String, usize> =
d.dim_styles.iter().enumerate().rev().map(|(i, s)| (s.name.to_ascii_lowercase(), i)).collect();
// And for dimension styles, views and UCSs (a later record replaces the first of its name).
let mut dim_style_names = ByName::new(&d.dim_styles, |s| &s.name);
let mut view_names = ByName::new(&d.views, |v| &v.name);
let mut ucs_names = ByName::new(&d.ucss, |u| &u.name);
for (kind, tg) in recs {
let t = T(tg);
match kind.as_str() {
@@ -245,10 +244,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
// 70 bit 1: a paper space view; its layout is CADCraft xdata.
let layout = (t.i(70).unwrap_or(0) & 1 != 0).then(|| field("LAYOUT").unwrap_or_default());
let v = NamedView { name: name.clone(), center, height: h, width: w, layer_state: field("LAYERSTATE"), twist, layout };
match d.views.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
Some(x) => *x = v,
None => d.views.push(v),
}
view_names.put(&mut d.views, &name, v);
}
"UCS" => {
let name = t.s(2).unwrap_or_default();
@@ -258,10 +254,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
continue;
}
let u = Ucs { name: name.clone(), origin, x_axis, y_axis };
match d.ucss.iter_mut().find(|x| x.name.eq_ignore_ascii_case(&name)) {
Some(x) => *x = u,
None => d.ucss.push(u),
}
ucs_names.put(&mut d.ucss, &name, u);
}
"DIMSTYLE" => {
let name = t.s(2).unwrap_or_default();
@@ -285,13 +278,7 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
fields.extend(crate::dxf_ext::read_newer_dimvars(tg, &rx.styles, &rx.brs, &rx.ltypes));
let mut st = DimStyle { name: name.clone(), annotative: annotative(tg), ..DimStyle::default() };
st.apply_fields(&fields);
match dim_style_index.get(&name.to_ascii_lowercase()).and_then(|&i| d.dim_styles.get_mut(i)) {
Some(x) => *x = st,
None => {
dim_style_index.insert(name.to_ascii_lowercase(), d.dim_styles.len());
d.dim_styles.push(st);
}
}
dim_style_names.put(&mut d.dim_styles, &name, st);
}
"VPORT" => vport_record(d, &t, false),
_ => {}
@@ -303,6 +290,32 @@ pub(super) fn tables(tags: &[Tag], d: &mut Drawing, rx: &mut Rx) {
d.vports.retain(|c| c.tiles.len() > usize::from(c.is_active()) || c.tiles.first().is_some_and(|t| t.twist != 0.0));
}
/// The records of one table read so far, by name with its ASCII letters lower-cased. A later
/// record of a name replaces the first, which keeps its place and takes the later record's name.
/// Each record is then a map lookup, not a scan of the records before it: a file of N records cost
/// N² name comparisons (#1924). Ordered by name rather than hashed, so its cost does not depend on
/// hash keys.
struct ByName(std::collections::BTreeMap<String, usize>);
impl ByName {
/// The entries the table starts with; the first of a name is the one kept.
fn new<T>(list: &[T], name: impl Fn(&T) -> &str) -> Self {
ByName(list.iter().enumerate().rev().map(|(i, t)| (name(t).to_ascii_lowercase(), i)).collect())
}
/// Put `item`, named `name`, in place of the first entry of that name, else at the end.
fn put<T>(&mut self, list: &mut Vec<T>, name: &str, item: T) {
let key = name.to_ascii_lowercase();
match self.0.get(&key).and_then(|&i| list.get_mut(i)) {
Some(x) => *x = item,
None => {
self.0.insert(key, list.len());
list.push(item);
}
}
}
}
fn index_table_handles(recs: &[(String, &[Tag])], rx: &mut Rx) {
for (kind, tags) in recs {
let table = T(tags);
+36 -2
View File
@@ -157,13 +157,47 @@ fn mirror_text(t: &mut Text, align: Option<Vec3>, insert: Vec3) {
}
}
/// An ATTDEF, whose multiline text is embedded MTEXT after its own groups.
pub(super) fn attdef(tags: &[Tag], c: &Common) -> Attrib {
/// An attribute's text (ATTRIB or ATTDEF, read by [`text_from`] from its own groups `t`) in a
/// tilted plane, drawn as seen from above. Its insertion point, alignment point and rotation
/// (groups 10, 11 and 50) are in the OCS of its extrusion (210): the DXF Reference gives both
/// points as "in OCS" for ATTRIB and ATTDEF, and its "Object Coordinate Systems (OCS)" lists both
/// among the planar entities whose axes come from the arbitrary axis algorithm. Read as world
/// points they put the attribute millions of units from its place in a drawing near survey
/// coordinates (#3541). `Text` cannot hold the plane, so the points are mapped to the WCS and the
/// rotation becomes the way the plane's turned x axis runs in plan, as a tilted LWPOLYLINE or HATCH
/// is drawn flat (#1886); a direction seen edge-on keeps the file's turn. Returns whether the text
/// was mapped: its points are then plan coordinates, and the extrusion is spent.
///
/// A plane facing down (z < 0) is left to `mirror_text`, which has mapped the points already. On
/// the Z axis (within the `Mat4::ocs` tolerance) the OCS is the WCS, and an extrusion too short for
/// `Vec3::normalized` names no plane (`Mat4::ocs` takes it as the Z axis): nothing changes for those.
pub(super) fn flatten_tilted(text: &mut Text, t: &T) -> bool {
let n = Vec3::new(t.fd(210, 0.0), t.fd(220, 0.0), t.fd(230, 1.0));
let unit = n.normalized();
if unit.z < 0.0 || (unit.x.abs() < 1e-12 && unit.y.abs() < 1e-12) {
return false;
}
let m = cadcraft_geom::Mat4::ocs(n);
text.insert = m.apply(text.insert);
text.align_pt = text.align_pt.map(|a| m.apply(a));
let along = m.apply(Vec3::new(text.rotation.cos(), text.rotation.sin(), 0.0)).xy();
if along.len() > 1e-9 {
text.rotation = cadcraft_geom::norm_angle(along.angle());
}
true
}
/// An ATTDEF, whose multiline text is embedded MTEXT after its own groups. One in a tilted plane
/// is drawn as seen from above, and its extrusion in `c` is spent ([`flatten_tilted`]).
pub(super) fn attdef(tags: &[Tag], c: &mut Common) -> Attrib {
// A multiline definition has its text as embedded MTEXT after its own groups.
let (own, embedded) = split_embedded(tags);
let multiline = multiline_attrib(embedded, c);
let own = T(own);
let mut text = text_from(&own);
if flatten_tilted(&mut text, &own) {
c.extrusion = Vec3::Z;
}
if let Some(m) = &multiline {
text.value.clone_from(&m.read_as);
}
+8 -5
View File
@@ -407,6 +407,8 @@ fn write_entities(w: &mut W, d: &Drawing, ms_br: &str, ps_brs: &[(String, String
struct LayoutWriteContext<'a> {
drawing: &'a Drawing,
dictionary: &'a str,
/// The drawing's UCSs by name, for each layout's named UCS.
ucs_names: &'a dxf_ext::UcsNames<'a>,
}
struct LayoutWriteData<'a> {
@@ -457,7 +459,7 @@ fn layout_obj(w: &mut W, context: LayoutWriteContext<'_>, data: LayoutWriteData<
w.s(330, layout_dict.to_string());
w.s(100, "AcDbPlotSettings");
write_plot_settings(w, d, page, data.model);
write_layout_data(w, d, data, view);
write_layout_data(w, d, context.ucs_names, data, view);
}
fn write_plot_settings(w: &mut W, d: &Drawing, page: &PageSetup, model: bool) {
@@ -550,7 +552,7 @@ fn write_plot_settings(w: &mut W, d: &Drawing, page: &PageSetup, model: bool) {
}
}
fn write_layout_data(w: &mut W, d: &Drawing, data: LayoutWriteData<'_>, view: Option<(Vec2, f64)>) {
fn write_layout_data(w: &mut W, d: &Drawing, ucs_names: &dxf_ext::UcsNames<'_>, data: LayoutWriteData<'_>, view: Option<(Vec2, f64)>) {
let name = data.name;
let tab = data.tab;
let flags = data.flags;
@@ -578,7 +580,7 @@ fn write_layout_data(w: &mut W, d: &Drawing, data: LayoutWriteData<'_>, view: Op
w.i(76, 0);
w.s(330, brh);
// The named UCS it is, only while its frame is still that record's (as for model space).
let named = u.and_then(|u| dxf_ext::named_ucs(&d.ucss, &u.name, u.origin, u.x_axis, u.y_axis));
let named = u.and_then(|u| ucs_names.named(&u.name, u.origin, u.x_axis, u.y_axis));
if let Some(h) = named.and_then(|u| w.ucss.get(&u.name.to_ascii_uppercase())).cloned() {
w.s(345, h);
}
@@ -643,6 +645,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
let ms_br = plan.ms_br;
let ps_brs = plan.ps_brs;
let layout_handles = plan.layout_handles;
let ucs_names = dxf_ext::UcsNames::new(&d.ucss);
w.s(0, "DICTIONARY");
w.s(5, layout_dict.clone());
w.s(330, root_dict.clone());
@@ -661,7 +664,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
let model_page = PageSetup { plot_area: "extents".into(), scale_to_fit: true, ..PageSetup::default() };
layout_obj(
w,
LayoutWriteContext { drawing: d, dictionary: layout_dict },
LayoutWriteContext { drawing: d, dictionary: layout_dict, ucs_names: &ucs_names },
LayoutWriteData {
handle: model_layout,
name: "Model",
@@ -679,7 +682,7 @@ fn write_layout_objects(w: &mut W, plan: &ObjectWritePlan<'_>) {
let h = layout_handles.get(i).cloned().unwrap_or_default();
layout_obj(
w,
LayoutWriteContext { drawing: d, dictionary: layout_dict },
LayoutWriteContext { drawing: d, dictionary: layout_dict, ucs_names: &ucs_names },
LayoutWriteData {
handle: &h,
name: &l.name,
+41 -10
View File
@@ -179,26 +179,50 @@ fn write_dwg(d: &Drawing, version: Version) -> Result<(Vec<u8>, craft_dwg::Unwri
/// extents. Formats that are not images (DXF, DWG) ignore the window. The window is checked with
/// [`check_window`].
pub fn write_framed(d: &Drawing, name: impl AsRef<Path>, window: Option<Bounds2>) -> Result<Vec<u8>> {
write_framed_noted(d, name, window).map(|(bytes, _)| bytes)
}
/// [`write_framed`], also returning what an image (PNG, SVG, PDF) draws short of the drawing
/// because of a render limit, one note each: the dashed runs drawn continuous
/// ([`undashed_note`]). DXF and DWG have none.
pub fn write_framed_noted(d: &Drawing, name: impl AsRef<Path>, window: Option<Bounds2>) -> Result<(Vec<u8>, Vec<String>)> {
let name = name.as_ref();
// A drawing template (.dwt) is DWG content.
let format = Format::from_path(name);
if format == Some(Format::Dwt) {
let mut dwg = name.as_os_str().to_owned();
dwg.push(".dwg");
return write_framed(d, PathBuf::from(dwg), None);
return write_framed_noted(d, PathBuf::from(dwg), None);
}
if let Some(w) = &window
&& is_image(name)
{
check_window(w)?;
}
match format {
Some(Format::Dxf | Format::Dwg) => write_with(d, name, &SaveOptions::default()),
Some(Format::Svg) => Ok(svg::export_window(d, &Space::Model, window).into_bytes()),
Some(Format::Png) => png_framed(d, &Space::Model, 2400, 1600, window),
Some(Format::Pdf) => pdf::pdf(d, &Space::Model, &PdfOptions { compress: true, window, ..PdfOptions::default() }),
_ => Err(IoError::Unsupported(ext(name))),
}
let (bytes, undashed) = match format {
Some(Format::Dxf | Format::Dwg) => (write_with(d, name, &SaveOptions::default())?, 0),
Some(Format::Svg) => {
let (svg, undashed) = svg::export_window_noted(d, &Space::Model, window);
(svg.into_bytes(), undashed)
}
Some(Format::Png) => png_framed_noted(d, &Space::Model, 2400, 1600, window)?,
Some(Format::Pdf) => pdf::pdf_noted(d, &Space::Model, &PdfOptions { compress: true, window, ..PdfOptions::default() })?,
_ => return Err(IoError::Unsupported(ext(name))),
};
Ok((bytes, undashed_note(undashed).into_iter().collect()))
}
/// The note for `n` dashed runs an output drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]), or `None` when there are none.
pub fn undashed_note(n: usize) -> Option<String> {
let runs = if n == 1 { "run" } else { "runs" };
(n > 0).then(|| {
format!(
"{n} dashed {runs} (each a line, a curve or a polyline segment) drawn continuous: past the dash limit of {} pattern elements per run or {} per drawing",
cadcraft_render::MAX_RUN_DASH_ELEMENTS,
cadcraft_render::MAX_DASH_ELEMENTS
)
})
}
/// Whether `name` is written as an image (PNG, SVG, PDF), i.e. whether framing applies to it.
@@ -238,10 +262,17 @@ pub fn png(d: &Drawing, space: &Space, width: u32, height: u32) -> Result<Vec<u8
/// extents (5% margin) when `window` is `None`. Objects are drawn with their transparency, as on
/// screen.
pub fn png_framed(d: &Drawing, space: &Space, width: u32, height: u32, window: Option<Bounds2>) -> Result<Vec<u8>> {
png_framed_noted(d, space, width, height, window).map(|(png, _)| png)
}
/// [`png_framed`], also returning the dashed runs it drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]).
pub fn png_framed_noted(d: &Drawing, space: &Space, width: u32, height: u32, window: Option<Bounds2>) -> Result<(Vec<u8>, usize)> {
let list = cadcraft_render::build(d, space, &cadcraft_render::Options { transparency: true, ..cadcraft_render::Options::default() });
let view = png_view(&list.bounds, width, height, window);
cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default())
.ok_or_else(|| IoError::Format("render failed".into()))
let png = cadcraft_render::raster::render_png(&list, &view, &cadcraft_render::raster::RasterOptions::default())
.ok_or_else(|| IoError::Format("render failed".into()))?;
Ok((png, list.undashed))
}
/// The raster view a PNG export uses.
+34 -9
View File
@@ -219,6 +219,12 @@ fn window(v: Option<&Value>) -> Option<Bounds2> {
/// Plot with JSON options (the engine's `plot` hook).
pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
plot_noted(d, space, opts).map(|(bytes, _)| bytes)
}
/// [`plot`], also returning the dashed runs its pages drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]).
pub fn plot_noted(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
validate_plot_offset_json(opts)?;
// `layouts: [name | "Model"] | "all"` plots those sheets into one file, one page each,
// instead of `space`; "all" = Model if it has objects, then the layouts in tab order.
@@ -245,7 +251,7 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
Ok((Space::Model, po))
})
.collect::<Result<Vec<_>>>()?;
return pdf_items(d, &items, &o);
return pdf_items_noted(d, &items, &o);
}
match opts.get("layouts") {
Some(Value::String(a)) if a.eq_ignore_ascii_case("all") => {
@@ -253,7 +259,7 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
layouts.sort_by_key(|l| l.tab_order);
let model = (!d.model.is_empty()).then_some(Space::Model);
let spaces: Vec<Space> = model.into_iter().chain(layouts.iter().map(|l| Space::Paper(l.name.clone()))).collect();
pdf_sheets(d, &spaces, &o)
pdf_items_noted(d, &sheet_items(&spaces, &o), &o)
}
Some(v) => {
let names = v.as_array().ok_or_else(|| IoError::Format("`layouts` must be a list of layout names".into()))?;
@@ -268,9 +274,9 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
None => Err(IoError::Format("`layouts` must be a list of layout names".into())),
})
.collect::<Result<Vec<_>>>()?;
pdf_sheets(d, &spaces, &o)
pdf_items_noted(d, &sheet_items(&spaces, &o), &o)
}
None => pdf(d, space, &o),
None => pdf_noted(d, space, &o),
}
}
@@ -346,6 +352,12 @@ pub fn pdf(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<Vec<u8>> {
pdf_sheets(d, std::slice::from_ref(space), o)
}
/// [`pdf`], also returning the dashed runs it drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]).
pub fn pdf_noted(d: &Drawing, space: &Space, o: &PdfOptions) -> Result<(Vec<u8>, usize)> {
pdf_items_noted(d, &sheet_items(std::slice::from_ref(space), o), o)
}
/// The name of a sheet: `Model` or the layout's.
fn sheet_name(space: &Space) -> String {
space.tab_name().to_string()
@@ -354,17 +366,27 @@ fn sheet_name(space: &Space) -> String {
/// Write a vector PDF with one page per space (at most [`MAX_PAGES`]), each labelled with its
/// layout name. The options apply to every sheet; layouts use their own page setups.
pub fn pdf_sheets(d: &Drawing, spaces: &[Space], o: &PdfOptions) -> Result<Vec<u8>> {
pdf_items(d, &sheet_items(spaces, o), o)
}
/// The items [`pdf_sheets`] plots: each space with `o`, at most one past [`MAX_PAGES`].
fn sheet_items(spaces: &[Space], o: &PdfOptions) -> Vec<(Space, PdfOptions)> {
// Links are file-wide (`pdf_items` reads them from `o`), so a sheet's own options carry none:
// a copy of the list per sheet multiplied it by the sheet count.
let sheet = PdfOptions { links: Vec::new(), ..o.clone() };
let items: Vec<(Space, PdfOptions)> = spaces.iter().take(MAX_PAGES + 1).map(|s| (s.clone(), sheet.clone())).collect();
pdf_items(d, &items, o)
spaces.iter().take(MAX_PAGES + 1).map(|s| (s.clone(), sheet.clone())).collect()
}
/// Write a vector PDF with one page per `(space, options)` item (at most [`MAX_PAGES`]): each
/// page plots with its own options (window, paper, orientation); `o` supplies the file-wide
/// ones (compression, title, layers, links).
pub fn pdf_items(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions) -> Result<Vec<u8>> {
pdf_items_noted(d, items, o).map(|(bytes, _)| bytes)
}
/// [`pdf_items`], also returning the dashed runs its pages drew continuous because of a dash
/// limit ([`cadcraft_render::DisplayList::undashed`]).
pub fn pdf_items_noted(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions) -> Result<(Vec<u8>, usize)> {
if items.iter().any(|(_, io)| io.offset.is_some_and(|offset| !valid_plot_offset(offset))) {
return Err(IoError::Format("plot offset must contain two finite values within ±100000 mm".into()));
}
@@ -420,8 +442,9 @@ impl Failure {
}
/// Write the file, one sheet at a time: each sheet's display list is built, written as its page
/// and dropped before the next.
fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as_geometry: bool) -> std::result::Result<Vec<u8>, Failure> {
/// and dropped before the next. Also the dashed runs the pages drew continuous because of a dash
/// limit ([`cadcraft_render::DisplayList::undashed`]).
fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as_geometry: bool) -> std::result::Result<(Vec<u8>, usize), Failure> {
write::guard(|| {
// Layers that are off plot on PDF layers that start hidden: draw them from a copy with
// them on.
@@ -456,6 +479,7 @@ fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as
// Link annotations of the whole file: each page keeps its own copy of the targets, so the
// pages times the links must not multiply without a bound.
let mut annotations_left = MAX_FILE_ANNOTATIONS;
let mut undashed = 0usize;
for (s, po) in items {
// Once the budget is spent no link is built (scanned and cloned) for later pages.
let mut page = sheet(drawn, s, po, if annotations_left == 0 { &links[..0] } else { &links })?;
@@ -467,11 +491,12 @@ fn write_pdf(d: &Drawing, items: &[(Space, PdfOptions)], o: &PdfOptions, text_as
// Groups are added to the document, so they must exist before the page starts.
groups.add(doc, d, &page.layers);
write_page(doc, &page, &groups, &mut fonts)?;
undashed = undashed.saturating_add(page.list.undashed);
}
if items.len() == 1 && !groups.ids.is_empty() {
writer.document_mut().set_optional_content_page_mode(true);
}
Ok(writer.finish()?)
Ok((writer.finish()?, undashed))
})
}
+22 -11
View File
@@ -22,6 +22,12 @@ pub const MAX_PNG_PIXELS: f64 = 40.0e6;
/// `svg`. `margins: [l, b, r, t]` (mm) bound the printable area of this plot (model space or a
/// layout).
pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
plot_noted(d, space, opts).map(|(bytes, _)| bytes)
}
/// [`plot`], also returning what the plot draws short of the drawing because of a render limit,
/// one note each ([`crate::undashed_note`]).
pub fn plot_noted(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, Vec<String>)> {
pdf::validate_plot_offset_json(opts)?;
if matches!(space, Space::Model)
&& opts.get("output").and_then(Value::as_str).is_some_and(|output| output.eq_ignore_ascii_case("svg"))
@@ -42,12 +48,13 @@ pub fn plot(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
}
_ => d,
};
match opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() {
None | Some("pdf") => pdf::plot(d, space, opts),
Some("png") => png(d, space, opts),
Some("svg") => svg(d, space, opts),
Some(other) => Err(IoError::Unsupported(other.to_string())),
}
let (bytes, undashed) = match opts.get("output").and_then(Value::as_str).map(str::to_ascii_lowercase).as_deref() {
None | Some("pdf") => pdf::plot_noted(d, space, opts)?,
Some("png") => png(d, space, opts)?,
Some("svg") => svg(d, space, opts)?,
Some(other) => return Err(IoError::Unsupported(other.to_string())),
};
Ok((bytes, crate::undashed_note(undashed).into_iter().collect()))
}
/// The sheet a plot draws on (a model-space plot's printable area inside the device margins).
@@ -62,7 +69,8 @@ fn fit_scale(b: &Bounds2, sheet: &Sheet, o: &PdfOptions) -> f64 {
pdf::plot_scale(b, sheet, o.fit != Some(false), o.scale)
}
fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
/// The PNG plot and the dashed runs it drew continuous because of a dash limit.
fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
let o = pdf::with_saved_setup(d, space, &PdfOptions::from_json(opts));
let (sheet, page) = sheet(d, space, &o)?;
let dpi = opts.get("resolution").and_then(Value::as_f64).filter(|r| r.is_finite()).unwrap_or(300.0).clamp(50.0, 2400.0);
@@ -116,15 +124,18 @@ fn png(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
// PDF clips a placed plot to the printable area: blank the rest of the sheet.
raster::blank_outside_printable(&mut pm, &sheet.printable, k);
}
raster::encode_png(&pm).ok_or_else(|| IoError::Format("render failed".into()))
let png = raster::encode_png(&pm).ok_or_else(|| IoError::Format("render failed".into()))?;
Ok((png, list.undashed))
}
fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
/// The SVG plot and the dashed runs it drew continuous because of a dash limit.
fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result<(Vec<u8>, usize)> {
let o = PdfOptions::from_json(opts);
let Space::Model = space else {
let (sheet, page) = sheet(d, space, &o)?;
let transparency = o.plot_transparency.unwrap_or(page.plot_transparency);
return Ok(crate::svg::export_window_with(d, space, Some(sheet.bounds()), transparency).into_bytes());
let (svg, undashed) = crate::svg::export_noted(d, space, Some(sheet.bounds()), transparency);
return Ok((svg.into_bytes(), undashed));
};
// Model space as plotted: the plot style table, lineweights, and the table's ends, joins and
// fills at the scale that fits the window (or the extents) on the device's paper.
@@ -141,7 +152,7 @@ fn svg(d: &Drawing, space: &Space, opts: &Value) -> Result<Vec<u8>> {
let mut list = cadcraft_render::build_plot(d, space, &ropts);
let s = fit_scale(&window.unwrap_or(list.bounds), &sheet, &o);
cadcraft_render::pen::apply(&mut list, s * sheet.unit_mm);
Ok(crate::svg::export_list(&list, window).into_bytes())
Ok((crate::svg::export_list(&list, window).into_bytes(), list.undashed))
}
#[cfg(test)]
+12 -1
View File
@@ -17,10 +17,21 @@ pub fn export_window(d: &Drawing, space: &Space, window: Option<Bounds2>) -> Str
export_window_with(d, space, window, true)
}
/// [`export_window`], also returning the dashed runs it drew continuous because of a dash limit
/// ([`cadcraft_render::DisplayList::undashed`]).
pub fn export_window_noted(d: &Drawing, space: &Space, window: Option<Bounds2>) -> (String, usize) {
export_noted(d, space, window, true)
}
/// [`export_window`], drawing transparency only when `transparency` is on (plots).
pub fn export_window_with(d: &Drawing, space: &Space, window: Option<Bounds2>, transparency: bool) -> String {
export_noted(d, space, window, transparency).0
}
/// [`export_window_with`] and the list's [`cadcraft_render::DisplayList::undashed`].
pub(crate) fn export_noted(d: &Drawing, space: &Space, window: Option<Bounds2>, transparency: bool) -> (String, usize) {
let list = cadcraft_render::build(d, space, &cadcraft_render::Options { transparency, ..cadcraft_render::Options::default() });
export_list(&list, window)
(export_list(&list, window), list.undashed)
}
/// Opacity for a transparent primitive (none for an opaque one or a wipeout's mask).
+268
View File
@@ -421,6 +421,91 @@ fn many_distinct_dimension_style_names_read_quickly() {
assert_eq!(styles.get(2), Some(&(name(1).as_str(), 1.0)));
}
/// Many distinct view and UCS names read in linear time, with the duplicate rule kept: a later
/// record of a name in other case replaces the first, which keeps its place and takes the later
/// record's name (#1924). The names share their first 200 bytes, so comparing two costs about that.
#[test]
fn many_distinct_view_and_ucs_names_read_quickly() {
const N: usize = 20_000;
let name = |kind: char, i: usize| format!("{kind}{}{i:06}", "x".repeat(199));
let view = |n: &str, height: u32| format!("0\nVIEW\n2\n{n}\n70\n0\n40\n{height}\n41\n1\n10\n0\n20\n0\n");
let ucs = |n: &str, x: usize| format!("0\nUCS\n2\n{n}\n70\n0\n10\n{x}\n20\n0\n30\n0\n11\n1\n21\n0\n31\n0\n12\n0\n22\n1\n32\n0\n");
let mut t = String::from("0\nSECTION\n2\nTABLES\n");
for i in 0..N {
t.push_str(&view(&name('V', i), 1));
t.push_str(&ucs(&name('U', i), i));
}
t.push_str(&view(&name('V', 0).to_ascii_uppercase(), 2));
t.push_str(&ucs(&name('U', 0).to_ascii_uppercase(), 7));
t.push_str("0\nENDSEC\n0\nEOF\n");
let started = std::time::Instant::now();
let d = read(t.as_bytes(), "many.dxf").unwrap();
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
let views: Vec<(&str, f64)> = d.views.iter().map(|v| (v.name.as_str(), v.height)).collect();
assert_eq!(views.len(), N);
assert_eq!(views.first(), Some(&(name('V', 0).to_ascii_uppercase().as_str(), 2.0)));
assert_eq!(views.get(1), Some(&(name('V', 1).as_str(), 1.0)));
let ucss: Vec<(&str, f64)> = d.ucss.iter().map(|u| (u.name.as_str(), u.origin.x)).collect();
assert_eq!(ucss.len(), N);
assert_eq!(ucss.first(), Some(&(name('U', 0).to_ascii_uppercase().as_str(), 7.0)));
assert_eq!(ucss.get(1), Some(&(name('U', 1).as_str(), 1.0)));
}
/// Layouts that each name one of many UCSs read and save in linear time, and each keeps the name of
/// its UCS (#1924). The names share their first 200 bytes, so comparing two costs about that.
#[test]
fn many_layouts_naming_many_ucss_read_and_save_quickly() {
const N: usize = 10_000;
let name = |kind: char, i: usize| format!("{kind}{}{i:06}", "x".repeat(199));
let mut t = String::from("0\nSECTION\n2\nTABLES\n");
for i in 0..N {
let u = name('U', i);
t.push_str(&format!("0\nUCS\n5\n{:X}\n2\n{u}\n70\n0\n10\n{i}\n20\n0\n30\n0\n11\n1\n21\n0\n31\n0\n12\n0\n22\n1\n32\n0\n", 0x10000 + i));
}
t.push_str("0\nENDSEC\n0\nSECTION\n2\nOBJECTS\n");
for i in 0..N {
let l = name('L', i);
t.push_str(&format!(
"0\nLAYOUT\n5\n{:X}\n100\nAcDbPlotSettings\n100\nAcDbLayout\n1\n{l}\n71\n{}\n13\n{i}\n23\n0\n33\n0\n16\n1\n26\n0\n36\n0\n17\n0\n27\n1\n37\n0\n330\n0\n345\n{:X}\n",
0x1000 + i,
i + 1,
0x10000 + i
));
}
t.push_str("0\nENDSEC\n0\nEOF\n");
let started = std::time::Instant::now();
let d = read(t.as_bytes(), "ucss.dxf").unwrap();
let saved = write_dxf(&d);
assert!(started.elapsed() < std::time::Duration::from_secs(10), "took {:?}", started.elapsed());
let named = d.layouts.iter().filter(|l| l.ucs.as_ref().is_some_and(|u| u.name == name('U', l.tab_order as usize - 1))).count();
assert_eq!(named, N);
let again = read_dxf(saved.as_bytes()).unwrap();
assert_eq!(again.layouts.iter().filter(|l| l.ucs.as_ref().is_some_and(|u| !u.name.is_empty())).count(), N);
}
/// A layout's named UCS is the first UCS of that name, without case, whose frame is the layout's:
/// what scanning the UCSs finds, also when a name's first UCS has another frame.
#[test]
fn a_layouts_named_ucs_is_the_first_of_its_name_with_its_frame() {
use cadcraft_geom::Vec3;
let ucs = |name: &str, x: f64| Ucs {
name: name.into(),
origin: Vec3::new(x, 0.0, 0.0),
x_axis: Vec3::new(1.0, 0.0, 0.0),
y_axis: Vec3::new(0.0, 1.0, 0.0),
};
let ucss = [ucs("Front", 0.0), ucs("FRONT", 1.0), ucs("front", 1.0), ucs("Side", 2.0), ucs("", 3.0), ucs(" Pad", 4.0)];
let names = crate::dxf_ext::UcsNames::new(&ucss);
let (x, y) = (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0));
for name in ["Front", "front", "FRONT", " front ", "Side", "side", "", " ", "Pad", " Pad", "Back"] {
for origin in [0.0, 1.0, 2.0, 3.0, 4.0, 5.0].map(|o| Vec3::new(o, 0.0, 0.0)) {
let want = crate::dxf_ext::named_ucs(&ucss, name, origin, x, y).map(std::ptr::from_ref);
assert_eq!(names.named(name, origin, x, y).map(std::ptr::from_ref), want, "{name:?} {origin:?}");
}
}
assert_eq!(names.named("front", Vec3::new(1.0, 0.0, 0.0), x, y).map(|u| u.name.as_str()), Some("FRONT"));
}
/// Many layouts with every paper-space object in one of the last of them read in linear time.
/// Each object goes to the first layout of its exact name, as before: not to an earlier one whose
/// name differs only in case, nor to a later one of the same name (#1924).
@@ -3655,6 +3740,189 @@ fn mirrored_mtext_extrusion_keeps_its_footprint() {
assert!(b.min.x > -0.2 && b.max.x > 0.5 && b.min.y > -0.2 && b.max.y > 0.5, "box right of and above (0,0): {b:?}");
}
/// Attributes in the plane of extrusion `n` (#3541): the DXF of block BL holding two ATTDEFs that
/// start at world point `start` and turn `degrees` in that plane (LEFT, and RIGHT, right-justified,
/// whose baseline ends 20 units on), a reference to BL at the origin whose two ATTRIBs repeat
/// them, and a 100 × 60 rectangle round `start`. Groups 10 and 11 hold OCS coordinates (DXF
/// Reference, ATTDEF and ATTRIB), worked out here with the arbitrary axis algorithm. Also returns
/// the world end of RIGHT's baseline and the world direction the attributes run in.
fn tilted_attribute_dxf(n: Vec3, start: Vec3, degrees: f64) -> (String, Vec3, Vec3) {
// Ax = Wy × N when N is near the Z axis (|Nx| and |Ny| under 1/64), else Wz × N; Ay = N × Ax.
let n = n.normalized();
let near_z = n.x.abs() < 1.0 / 64.0 && n.y.abs() < 1.0 / 64.0;
let ax = if near_z { Vec3::new(0.0, 1.0, 0.0) } else { Vec3::Z }.cross(n).normalized();
let ay = n.cross(ax).normalized();
let pt = |code: i32, p: Vec3| format!("{code}\n{}\n{}\n{}\n{}\n{}\n", p.dot(ax), code + 10, p.dot(ay), code + 20, p.dot(n));
let turn = degrees.to_radians();
let dir = ax * turn.cos() + ay * turn.sin();
let end = start + dir * 20.0;
let attribute = |kind: &str, tag: &str| {
let right = if tag == "RIGHT" { format!("72\n2\n{}", pt(11, end)) } else { String::new() };
let prompt = if kind == "ATTDEF" { "3\nValue\n" } else { "" };
format!(
"0\n{kind}\n8\n0\n{}40\n3\n1\n{tag}\n50\n{degrees}\n210\n{}\n220\n{}\n230\n{}\n{prompt}2\n{tag}\n70\n0\n{right}",
pt(10, start),
n.x,
n.y,
n.z
)
};
let (x0, y0, x1, y1) = (start.x - 50.0, start.y - 30.0, start.x + 50.0, start.y + 30.0);
let text = format!(
"0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n8\n0\n2\nBL\n70\n2\n10\n0\n20\n0\n30\n0\n3\nBL\n{}{}0\nENDBLK\n8\n0\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n0\nLWPOLYLINE\n8\n0\n90\n4\n70\n1\n10\n{x0}\n20\n{y0}\n10\n{x1}\n20\n{y0}\n10\n{x1}\n20\n{y1}\n10\n{x0}\n20\n{y1}\n\
0\nINSERT\n8\n0\n66\n1\n2\nBL\n10\n0\n20\n0\n30\n0\n{}{}0\nSEQEND\n8\n0\n0\nENDSEC\n0\nEOF\n",
attribute("ATTDEF", "LEFT"),
attribute("ATTDEF", "RIGHT"),
attribute("ATTRIB", "LEFT"),
attribute("ATTRIB", "RIGHT"),
);
(text, end, dir)
}
/// The ATTDEFs of block BL (with their extrusions) and the ATTRIBs of the first block reference.
fn attributes(d: &Drawing) -> (Vec<(Attrib, Vec3)>, Vec<Attrib>) {
let defs = d.block("BL").expect("block BL").entities.iter();
let defs = defs.filter_map(|e| if let EntityKind::AttDef(a) = &e.kind { Some((a.clone(), e.common.extrusion)) } else { None });
let refs = first(d, |k| if let EntityKind::Insert(i) = k { Some(i.attribs.clone()) } else { None });
(defs.collect(), refs)
}
/// Issue #3541: an ATTDEF and an ATTRIB in a tilted plane near survey coordinates are read at their
/// world points, turned the way the plane runs in plan, and drawn there, not millions of units
/// away at their OCS coordinates read as world ones.
#[test]
fn tilted_attributes_are_read_at_their_world_points() {
let start = Vec3::new(550_050.0, 9_580_030.0, 0.0);
let (text, end, dir) = tilted_attribute_dxf(Vec3::new(0.3, -0.2, 0.93), start, 30.0);
let d = read(text.as_bytes(), "a.dxf").unwrap();
let plan = dir.xy().normalized();
let check = |a: &Attrib, what: &str| {
assert!((a.text.insert - start).len() < 1e-6, "{what} {} insert {:?}", a.tag, a.text.insert);
if a.tag == "RIGHT" {
let at = a.text.align_pt.expect("a right-justified attribute keeps its alignment point");
assert!((at - end).len() < 1e-6, "{what} RIGHT alignment point {at:?}, want {end:?}");
}
let runs = Vec2::new(a.text.rotation.cos(), a.text.rotation.sin());
assert!((runs - plan).len() < 1e-9, "{what} {} runs along {runs:?}, want {plan:?}", a.tag);
};
let (defs, refs) = attributes(&d);
assert_eq!((defs.len(), refs.len()), (2, 2));
for (a, extrusion) in &defs {
check(a, "ATTDEF");
// Its points are plan coordinates now, so the plane they were in is spent.
assert_eq!(*extrusion, Vec3::Z, "ATTDEF {}", a.tag);
}
for a in &refs {
check(a, "ATTRIB");
}
// The ATTRIBs are drawn inside the rectangle's neighbourhood.
let b = cadcraft_render::build(&d, &Space::Model, &cadcraft_render::Options::default()).bounds;
assert!(b.min.x > start.x - 80.0 && b.max.x < start.x + 80.0 && b.min.y > start.y - 60.0 && b.max.y < start.y + 60.0, "drawn over {b:?}");
// In a plane standing on edge (normal along X) a direction turned -90° runs straight down and
// leaves no direction in plan: the attributes keep the file's turn, at their world points.
let (text, _, _) = tilted_attribute_dxf(Vec3::new(1.0, 0.0, 0.0), start, -90.0);
let d = read(text.as_bytes(), "edge.dxf").unwrap();
let (defs, refs) = attributes(&d);
for a in defs.iter().map(|(a, _)| a).chain(&refs) {
assert!((a.text.insert - start).len() < 1e-6, "{} insert {:?}", a.tag, a.text.insert);
assert!((a.text.rotation - (-90f64).to_radians()).abs() < 1e-12, "{} rotation {}", a.tag, a.text.rotation);
}
}
/// Issue #3541, on save: tilted attributes are written at their world points with no plane
/// (groups 10 and 11 in the WCS, no 210), and reopened where they were read.
#[test]
fn tilted_attributes_are_saved_at_their_world_points_and_reopened_there() {
let start = Vec3::new(550_050.0, 9_580_030.0, 0.0);
let (text, end, _) = tilted_attribute_dxf(Vec3::new(0.3, -0.2, 0.93), start, 30.0);
let d = read(text.as_bytes(), "a.dxf").unwrap();
let out = write_dxf(&d);
let pairs = dxf_pairs(&out);
for kind in ["ATTDEF", "ATTRIB"] {
let recs = dxf_records(&pairs, kind);
assert_eq!(recs.len(), 2, "{kind}");
for r in recs {
let num = |code: i32, default: f64| group(r, &code.to_string()).map_or(default, |v| v.parse::<f64>().unwrap());
let point = |code: i32, default_z: f64| Vec3::new(num(code, 0.0), num(code + 10, 0.0), num(code + 20, default_z));
let tag = group(r, "2").unwrap_or_default();
assert_eq!(point(210, 1.0), Vec3::Z, "{kind} {tag} is written with a plane");
let (code, want) = if tag == "RIGHT" { (11, end) } else { (10, start) };
assert!((point(code, 0.0) - want).len() < 1e-6, "{kind} {tag} group {code}: {:?}, want {want:?}", point(code, 0.0));
}
}
let back = read_dxf(out.as_bytes()).unwrap();
let ((defs, refs), (defs2, refs2)) = (attributes(&d), attributes(&back));
let same = |a: &Attrib, b: &Attrib| {
assert_eq!(a.tag, b.tag);
// A justified attribute is placed by its alignment point: the writer derives its group 10
// from it (#1050), so only a baseline-left one keeps its own.
if a.text.align_pt.is_none() {
assert!((a.text.insert - b.text.insert).len() < 1e-6, "{} insert {:?} came back as {:?}", a.tag, a.text.insert, b.text.insert);
}
assert!(a.text.align_pt.zip(b.text.align_pt).is_none_or(|(p, q)| (p - q).len() < 1e-6), "{} alignment point", a.tag);
assert_eq!(a.text.align_pt.is_some(), b.text.align_pt.is_some(), "{} alignment point", a.tag);
assert!((a.text.rotation - b.text.rotation).abs() < 1e-9, "{} rotation {} came back as {}", a.tag, a.text.rotation, b.text.rotation);
};
assert_eq!((defs2.len(), refs2.len()), (2, 2));
for ((a, _), (b, extrusion)) in defs.iter().zip(&defs2) {
same(a, b);
assert_eq!(*extrusion, Vec3::Z, "ATTDEF {}", b.tag);
}
for (a, b) in refs.iter().zip(&refs2) {
same(a, b);
}
}
/// A block reference in a tilted plane is still read as is (its block drawn at the OCS point read),
/// so the ATTRIBs in that plane stay as read too, on the block's own ATTDEFs, rather than mapped
/// away from the block.
#[test]
fn attributes_of_a_tilted_reference_stay_with_its_block() {
let start = Vec3::new(50.0, 30.0, 0.0);
let (flat, _, _) = tilted_attribute_dxf(Vec3::Z, start, 30.0);
let (blocks, reference) = flat.split_once("0\nINSERT\n").unwrap();
let plane = "210\n0.3\n220\n-0.2\n230\n0.93\n";
let flat_plane = "210\n0\n220\n0\n230\n1\n";
assert_eq!(reference.matches(flat_plane).count(), 2);
let text = format!("{blocks}0\nINSERT\n{plane}{}", reference.replace(flat_plane, plane));
let d = read(text.as_bytes(), "r.dxf").unwrap();
let (defs, refs) = attributes(&d);
assert_eq!(refs.len(), 2);
for a in &refs {
let def = defs.iter().find(|(def, _)| def.tag == a.tag).expect("its definition");
assert_eq!(a.text.insert, def.0.text.insert, "{} left its definition", a.tag);
}
}
/// Attributes on the Z axis are read exactly as written, and saved so; a plane facing down keeps
/// the mirrored reading, which maps its points once (#3541 changes neither).
#[test]
fn flat_and_mirrored_attributes_read_as_before() {
let start = Vec3::new(550_050.125, 9_580_030.375, 12.5);
// A turn of -30° stays -30° (taken through the plane it would come back as 330°).
let (text, _, _) = tilted_attribute_dxf(Vec3::Z, start, -30.0);
let d = read(text.as_bytes(), "flat.dxf").unwrap();
let (defs, refs) = attributes(&d);
for a in defs.iter().map(|(a, _)| a).chain(&refs) {
assert_eq!((a.text.insert, a.text.rotation), (start, (-30f64).to_radians()), "{}", a.tag);
}
let out = write_dxf(&d);
let pairs = dxf_pairs(&out);
for r in dxf_records(&pairs, "ATTDEF").into_iter().chain(dxf_records(&pairs, "ATTRIB")).filter(|r| group(r, "2") == Some("LEFT")) {
let num = |code: &str| group(r, code).map(|v| v.parse::<f64>().unwrap());
assert_eq!((num("10"), num("20"), num("30"), num("210")), (Some(start.x), Some(start.y), Some(start.z), None));
}
// Facing down and tilted: the mirrored reading maps the start point once, to `start`.
let (text, _, _) = tilted_attribute_dxf(Vec3::new(0.6, 0.0, -0.8), start, 30.0);
let d = read(text.as_bytes(), "down.dxf").unwrap();
let (defs, refs) = attributes(&d);
for a in defs.iter().map(|(a, _)| a).chain(&refs).filter(|a| a.tag == "LEFT") {
assert!((a.text.insert - start).len() < 1e-6, "{} insert {:?}, want {start:?}", a.tag, a.text.insert);
}
}
// --- SVG import ---
/// One 20mm×10mm page whose user units are millimetres; the reader flips Y, so a point at
+277
View File
@@ -41,6 +41,283 @@ fn minsert(cols: u32, rows: u32) -> String {
)
}
/// A linear dimension drawn by block `block`, its dimension line at height `y`.
fn dimension(block: &str, y: usize) -> String {
format!("0\nDIMENSION\n2\n{block}\n3\nStandard\n10\n100\n20\n{}\n11\n50\n21\n{}\n70\n0\n13\n0\n23\n{y}\n14\n100\n24\n{y}\n", y + 5, y + 5)
}
const LINE: &str = "0\nLINE\n10\n0\n20\n0\n11\n1\n21\n1\n";
/// What dimension block `*D1` holds on its way back to itself.
#[derive(Clone, Copy, Debug)]
enum Via {
/// Dimensions drawn by `*D1`.
Nothing,
/// References to block `B`, which holds a dimension drawn by `*D1`.
Reference,
/// Dimensions drawn by `*D2`, which holds a dimension drawn by `*D1`.
Dimension,
}
/// Dimension block `*D1` holds a line and `refs` dimensions or references that lead back to `*D1`
/// (`via`); the block on the way holds a line too. Model space holds one dimension drawn by `*D1`,
/// and a reference to `B` when there is one, so the loop is also entered from `B`. With `closed`
/// false, the first dimension inside a block on the way is drawn by `*D9`, a block the file lacks,
/// so nothing leads back.
fn dimension_loop(refs: usize, via: Via, closed: bool) -> String {
let back = if closed { "*D1" } else { "*D9" };
let mut s = String::from("0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\n*D1\n70\n1\n10\n0\n20\n0\n");
for k in 0..refs {
s += &match via {
Via::Nothing => dimension(back, k * 10),
Via::Reference => format!("0\nINSERT\n2\nB\n10\n{k}\n20\n0\n"),
Via::Dimension => dimension(if closed { "*D2" } else { "*D9" }, k * 10),
};
}
s += LINE;
s += "0\nENDBLK\n";
match via {
Via::Nothing => {}
Via::Reference => s += &format!("0\nBLOCK\n2\nB\n70\n0\n10\n0\n20\n0\n{}{LINE}0\nENDBLK\n", dimension(back, 0)),
Via::Dimension => s += &format!("0\nBLOCK\n2\n*D2\n70\n1\n10\n0\n20\n0\n{}{LINE}0\nENDBLK\n", dimension("*D1", 0)),
}
s += "0\nENDSEC\n0\nSECTION\n2\nENTITIES\n";
s += &dimension("*D1", 0);
if matches!(via, Via::Reference) {
s += "0\nINSERT\n2\nB\n10\n200\n20\n0\n";
}
s + "0\nENDSEC\n0\nEOF\n"
}
/// Dimension blocks `*D1`..`*Dn` each hold a line and a reference to block `B`, which holds a
/// dimension drawn by each of them; model space holds a dimension drawn by `*D1`. Every ordering
/// of the blocks is a way round the loop.
fn loop_of_blocks(n: usize) -> String {
let mut s = String::from("0\nSECTION\n2\nBLOCKS\n");
for i in 1..=n {
s += &format!("0\nBLOCK\n2\n*D{i}\n70\n1\n10\n0\n20\n0\n0\nINSERT\n2\nB\n10\n0\n20\n0\n{LINE}0\nENDBLK\n");
}
s += "0\nBLOCK\n2\nB\n70\n0\n10\n0\n20\n0\n";
for i in 1..=n {
s += &dimension(&format!("*D{i}"), i * 10);
}
s + "0\nENDBLK\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n" + &dimension("*D1", 0) + "0\nENDSEC\n0\nEOF\n"
}
/// Dimension blocks `*D1`..`*Dn` in a ring: each holds a line and three dimensions drawn by the
/// next, the last by `*D1`. Model space holds a dimension drawn by `*D1`.
fn ring_of_blocks(n: usize) -> String {
let mut s = String::from("0\nSECTION\n2\nBLOCKS\n");
for i in 1..=n {
let next = format!("*D{}", i % n + 1);
s += &format!("0\nBLOCK\n2\n*D{i}\n70\n1\n10\n0\n20\n0\n{LINE}");
for k in 0..3 {
s += &dimension(&next, k * 10);
}
s += "0\nENDBLK\n";
}
s + "0\nENDSEC\n0\nSECTION\n2\nENTITIES\n" + &dimension("*D1", 0) + "0\nENDSEC\n0\nEOF\n"
}
/// Dimension blocks nested without a cycle. `*D3` holds the only line, from (0, 0) to (1, 1);
/// `*D2` holds a dimension drawn by `*D3`; `*D1` holds two dimensions drawn by `*D2` and a
/// reference to block `B`, which holds a dimension drawn by `*D2`. Model space holds a dimension
/// drawn by `*D1` and two references to `B`.
fn nested_dimensions() -> String {
let block = |name: &str, body: &str| format!("0\nBLOCK\n2\n{name}\n70\n{}\n10\n0\n20\n0\n{body}0\nENDBLK\n", u8::from(name.starts_with('*')));
let mut s = String::from("0\nSECTION\n2\nBLOCKS\n");
s += &block("*D3", "0\nLINE\n10\n0\n20\n0\n11\n1\n21\n1\n");
s += &block("*D2", &dimension("*D3", 0));
s += &block("B", &dimension("*D2", 0));
s += &block("*D1", &(dimension("*D2", 0) + &dimension("*D2", 10) + "0\nINSERT\n2\nB\n10\n5\n20\n0\n"));
s + "0\nENDSEC\n0\nSECTION\n2\nENTITIES\n"
+ &dimension("*D1", 0)
+ "0\nINSERT\n2\nB\n10\n20\n20\n0\n0\nINSERT\n2\nB\n10\n40\n20\n0\n0\nENDSEC\n0\nEOF\n"
}
/// A dimension inside a block whose own block leads back to that block (the same block, or
/// through a reference or another dimension block) is drawn as one whose block is missing: from
/// its definition points. It used to draw the block again at every level down to
/// `MAX_BLOCK_DEPTH` (#1923).
#[test]
fn a_dimension_whose_block_leads_back_draws_as_one_whose_block_is_missing() {
for via in [Via::Nothing, Via::Reference, Via::Dimension] {
let closed = build(&read(&dimension_loop(1, via, true)), &Space::Model, &Options::default());
let open = build(&read(&dimension_loop(1, via, false)), &Space::Model, &Options::default());
assert!(!open.prims.is_empty());
assert_eq!((closed.prims.len(), &closed.verts), (open.prims.len(), &open.verts), "via {via:?}");
}
}
/// Many dimensions that lead back to their block (directly, or through as many references or
/// dimensions), dimension blocks that lead to each other, or a long ring of them, drew the blocks
/// again at every level: up to 300^16 times, or once per ordering of the blocks, until the
/// expansion budget ran out and the rest was left out. Now nothing goes round a loop, so the
/// drawing is whole. A block of 300 references and a ring of 20 blocks are more than the search
/// near a dimension's block looks at, so the whole block graph answers for them. Their extents use
/// the shared block cache (#1850) and stay finite.
#[test]
fn dimensions_on_block_loops_draw_whole() {
let files = [Via::Nothing, Via::Reference, Via::Dimension].map(|via| dimension_loop(300, via, true));
for (i, text) in files.iter().chain([&loop_of_blocks(10), &ring_of_blocks(20)]).enumerate() {
let d = read(text);
let ext = d.extents(&Space::Model);
assert!(!ext.is_empty() && ext.min.is_finite() && ext.max.is_finite(), "{ext:?}");
let list = build(&d, &Space::Model, &Options::default());
assert!(!list.prims.is_empty() && !list.truncated, "file {i}: {} expanded", list.expanded);
}
}
/// A loop can also pass through a multileader's block or a proxy's graphics, which are drawn as
/// block contents: `*D1` holds one of them leading to block `K`, which holds a dimension drawn by
/// `*D1` (or by a block the file lacks, for comparison). The proxy's graphics also hold such a
/// dimension themselves: they are drawn as part of `*D1`.
#[test]
fn a_loop_through_a_multileader_or_proxy_graphics_is_cut_too() {
let line = |h: u64| Entity::new(Handle(h), EntityKind::Line(Line { a: Vec3::ZERO, b: Vec3::new(1.0, 1.0, 0.0) }));
let dim = |h: u64, block: &str| {
Entity::new(
Handle(h),
EntityKind::Dimension(cadcraft_doc::Dimension {
kind: cadcraft_doc::DimKind::Linear { rotation: 0.0 },
defpt: Vec3::new(100.0, 5.0, 0.0),
text_mid: Vec3::new(50.0, 5.0, 0.0),
p13: Vec3::ZERO,
p14: Vec3::new(100.0, 0.0, 0.0),
p15: Vec3::ZERO,
p16: Vec3::ZERO,
text: String::new(),
style: "Standard".into(),
measurement: 100.0,
text_rotation: 0.0,
user_text_pos: false,
block: Some(block.into()),
overrides: Default::default(),
assoc: Vec::new(),
marks: Default::default(),
insertion_point: Vec3::ZERO,
}),
)
};
let to_k = Insert {
block: "K".into(),
insert: Vec3::ZERO,
scale: Vec3::new(1.0, 1.0, 1.0),
rotation: 0.0,
attribs: Vec::new(),
cols: 1,
rows: 1,
col_spacing: 0.0,
row_spacing: 0.0,
clip: None,
};
for through_proxy in [false, true] {
let drawing = |back: &str| {
let via = if through_proxy {
EntityKind::Unknown(cadcraft_doc::Unknown {
dxf_type: "ACAD_PROXY_ENTITY".into(),
tags: Vec::new(),
graphics: vec![Entity::new(Handle(0x300), EntityKind::Insert(to_k.clone())), dim(0x301, back)],
})
} else {
EntityKind::MLeader(cadcraft_doc::MLeader {
leaders: vec![vec![Vec3::new(-5.0, 0.0, 0.0)]],
landing: Vec3::ZERO,
dogleg: 1.0,
text: None,
style: "Standard".into(),
arrow_size: 1.0,
spline: false,
block: Some(to_k.clone()),
})
};
let mut d = Drawing::new_imperial();
let mut d1 = Block::new("*D1");
d1.entities.push(line(0x100));
d1.entities.push(Entity::new(Handle(0x101), via));
let mut k = Block::new("K");
k.entities.push(line(0x200));
k.entities.push(dim(0x201, back));
d.blocks.insert("*D1".into(), Arc::new(d1));
d.blocks.insert("K".into(), Arc::new(k));
let EntityKind::Dimension(top) = dim(0, "*D1").kind else { unreachable!() };
d.add(&Space::Model, Common::default(), EntityKind::Dimension(top)).unwrap();
build(&d, &Space::Model, &Options::default())
};
let (closed, open) = (drawing("*D1"), drawing("*D9"));
assert!(!open.prims.is_empty());
assert_eq!((closed.prims.len(), &closed.verts), (open.prims.len(), &open.verts), "through a proxy: {through_proxy}");
}
}
/// Dimension blocks `*E1`..`*En` in a chain: each holds `lines` lines and a dimension drawn by the
/// next; the last holds only lines. Model space holds a dimension drawn by `*E1`.
fn chain_of_blocks(n: usize, lines: usize) -> String {
let mut s = String::from(
"0
SECTION
2
BLOCKS
",
);
for i in 1..=n {
s += &format!(
"0
BLOCK
2
*E{i}
70
1
10
0
20
0
{}",
LINE.repeat(lines)
);
if i < n {
s += &dimension(&format!("*E{}", i + 1), 0);
}
s += "0
ENDBLK
";
}
s + "0
ENDSEC
0
SECTION
2
ENTITIES
" + &dimension("*E1", 0)
+ "0
ENDSEC
0
EOF
"
}
/// Dimension blocks nested without a cycle are still drawn from their blocks, on every path: two
/// dimensions deep, by sibling dimensions, and through references to a block holding one. A chain
/// of blocks with more objects than the search near a dimension's block looks at is settled by
/// the whole block graph, which finds no loop either.
#[test]
fn nested_dimension_blocks_without_a_cycle_draw_on_every_path() {
let only_lines = |list: &cadcraft_render::DisplayList| {
list.prims.iter().all(|p| {
let v = &list.verts[p.start as usize..(p.start + p.len) as usize];
matches!(v, [a, b] if *b - *a == Vec2::new(1.0, 1.0))
})
};
let list = build(&read(&nested_dimensions()), &Space::Model, &Options::default());
// `*D3`'s line, through `*D1` (two dimensions of `*D2`, and `B`) and the two `B` in model
// space; nothing else is drawn, so no dimension fell back to its definition points.
assert_eq!(list.prims.len(), 2 + 1 + 2);
assert!(only_lines(&list));
let list = build(&read(&chain_of_blocks(5, 100)), &Space::Model, &Options::default());
assert_eq!(list.prims.len(), 5 * 100);
assert!(only_lines(&list));
}
#[test]
fn block_expansion_bombs_are_bounded() {
for text in [self_referencing(4), self_referencing(12), fan_out(), minsert(10_000, 10_000)] {
+153
View File
@@ -0,0 +1,153 @@
//! The controls of #1069: one line of 49,999 or of 50,001 DASHED (0.5, -0.25) periods, as the
//! issue's generator writes it. A plot or export keeps the pattern on both: the PDF strokes a
//! subpath per dash and a close-up PNG of the line's start shows its gaps.
use cadcraft_doc::{Drawing, Space};
use cadcraft_geom::{Bounds2, Vec2};
use cadcraft_io::PdfOptions;
/// One line on layer L1 with linetype DASHED, `periods` periods long.
fn control(periods: f64) -> Drawing {
let len = periods * 0.75;
let dxf = format!(
"0
SECTION
2
HEADER
9
$ACADVER
1
AC1032
9
$INSUNITS
70
4
9
$LTSCALE
40
1.0
0
ENDSEC
0
SECTION
2
TABLES
0
TABLE
2
LTYPE
70
2
0
LTYPE
2
CONTINUOUS
70
0
3
Solid line
72
65
73
0
40
0.0
0
LTYPE
2
DASHED
70
0
3
Dashed 0.5/0.25
72
65
73
2
40
0.75
49
0.5
74
0
49
-0.25
74
0
0
ENDTAB
0
TABLE
2
LAYER
70
1
0
LAYER
2
L1
70
0
62
7
6
DASHED
0
ENDTAB
0
ENDSEC
0
SECTION
2
ENTITIES
0
LINE
8
L1
6
DASHED
10
0.0
20
0.0
30
0.0
11
{len}
21
0.0
31
0.0
0
ENDSEC
0
EOF
"
);
cadcraft_io::read(dxf.as_bytes(), "control.dxf").unwrap()
}
/// Runs of inked columns across the middle rows of `png` (a horizontal line through its centre):
/// one for a continuous line, one per dash for a dashed one.
fn dashes_across_the_middle(png: &[u8]) -> usize {
let r = cadcraft_io::raster::decode(png).unwrap();
let (w, h) = (r.width(), r.height());
let paper = r.pixel(0, 0);
let inked = |x: u32| (h / 2 - 3..=h / 2 + 3).any(|y| r.pixel(x, y) != paper);
(0..w).filter(|&x| inked(x) && (x == 0 || !inked(x - 1))).count()
}
#[test]
fn the_49_999_and_50_001_period_controls_keep_their_dashes_in_pdf_and_png() {
for periods in [49_999.0, 50_001.0] {
let d = control(periods);
let pdf = cadcraft_io::pdf(&d, &Space::Model, &PdfOptions { compress: false, ..PdfOptions::default() }).unwrap();
let doc = crate::pdf_read::read(&pdf);
let dashes = crate::pdf_read::drawn(doc.content()).iter().filter(|o| o.op == "m").count();
assert!(dashes > periods as usize, "{periods} periods: {dashes} dashes in the PDF");
// As `cadcraft-cli convert --window 0,-3,60,3`: 80 periods fill the image.
let png = cadcraft_io::write_framed(&d, "close.png", Some(Bounds2::new(Vec2::new(0.0, -3.0), Vec2::new(60.0, 3.0)))).unwrap();
let shown = dashes_across_the_middle(&png);
assert!(shown > 60, "{periods} periods: {shown} dashes across the close-up");
}
}
+360
View File
@@ -0,0 +1,360 @@
//! A HATCH edge path whose edges are listed out of order, or stored end to start, is read as the
//! outline its edges make. Read in file order, its vertex list jumps between edges, and the
//! even-odd fill fills the polygon of those jumps instead.
use cadcraft_doc::{EntityKind, HatchLoop};
use cadcraft_geom::{PolyVertex, Vec2};
/// A boundary edge as a DXF HATCH stores it (DXF Reference, HATCH boundary path data).
#[derive(Clone)]
enum Edge {
Line([f64; 2], [f64; 2]),
/// Centre, radius, start and end angle in degrees, counter-clockwise.
Arc([f64; 2], f64, f64, f64, bool),
/// Centre, major axis end relative to the centre, minor-to-major ratio, start and end angle
/// in degrees, counter-clockwise.
Ellipse([f64; 2], [f64; 2], f64, f64, f64, bool),
/// Degree, knots, control points.
Spline(u32, Vec<f64>, Vec<[f64; 2]>),
}
fn line(a: [f64; 2], b: [f64; 2]) -> Edge {
Edge::Line(a, b)
}
fn groups(edge: &Edge) -> String {
match edge {
Edge::Line(a, b) => format!("72\n1\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n", a[0], a[1], b[0], b[1]),
Edge::Arc(c, r, start, end, ccw) => format!("72\n2\n10\n{}\n20\n{}\n40\n{r}\n50\n{start}\n51\n{end}\n73\n{}\n", c[0], c[1], i32::from(*ccw)),
Edge::Ellipse(c, major, ratio, start, end, ccw) => format!(
"72\n3\n10\n{}\n20\n{}\n11\n{}\n21\n{}\n40\n{ratio}\n50\n{start}\n51\n{end}\n73\n{}\n",
c[0],
c[1],
major[0],
major[1],
i32::from(*ccw)
),
Edge::Spline(degree, knots, control) => {
let mut s = format!("72\n4\n94\n{degree}\n73\n0\n74\n0\n95\n{}\n96\n{}\n", knots.len(), control.len());
for k in knots {
s.push_str(&format!("40\n{k}\n"));
}
for p in control {
s.push_str(&format!("10\n{}\n20\n{}\n", p[0], p[1]));
}
s
}
}
}
/// A DXF whose one solid HATCH has one edge path per entry of `paths`.
fn dxf(paths: &[Vec<Edge>]) -> String {
let mut s = String::from(
"0\nSECTION\n2\nENTITIES\n0\nHATCH\n5\n100\n100\nAcDbEntity\n8\n0\n100\nAcDbHatch\n10\n0\n20\n0\n30\n0\n210\n0\n220\n0\n230\n1\n2\nSOLID\n70\n1\n71\n0\n",
);
s.push_str(&format!("91\n{}\n", paths.len()));
for (i, edges) in paths.iter().enumerate() {
s.push_str(&format!("92\n{}\n93\n{}\n", i32::from(i == 0), edges.len()));
for edge in edges {
s.push_str(&groups(edge));
}
s.push_str("97\n0\n");
}
s.push_str("75\n0\n76\n1\n98\n0\n0\nENDSEC\n0\nEOF\n");
s
}
fn loops_of(d: &cadcraft_doc::Drawing) -> Vec<HatchLoop> {
let hatch = d.model.iter().find_map(|e| match &e.kind {
EntityKind::Hatch(h) => Some(h.loops.clone()),
_ => None,
});
hatch.expect("a hatch")
}
fn read_loops(paths: &[Vec<Edge>]) -> Vec<HatchLoop> {
loops_of(&cadcraft_io::read(dxf(paths).as_bytes(), "edges.dxf").expect("read DXF"))
}
/// The vertices of the one loop of a hatch with one edge path.
fn vertices(edges: &[Edge]) -> Vec<PolyVertex> {
let loops = read_loops(&[edges.to_vec()]);
assert_eq!(loops.len(), 1);
loops.into_iter().next().map(|l| l.vertices).unwrap_or_default()
}
/// The same vertices, up to the rounding of points and bulges computed from other stored values.
fn assert_same(got: &[PolyVertex], expected: &[PolyVertex]) {
let same = got.len() == expected.len() && got.iter().zip(expected).all(|(a, b)| a.p.near(b.p, 1e-9) && (a.bulge - b.bulge).abs() < 1e-12);
assert!(same, "got {got:?}\nexpected {expected:?}");
}
/// Whether the even-odd fill of loops of straight segments covers `p`.
fn filled(loops: &[HatchLoop], p: Vec2) -> bool {
let mut inside = false;
for l in loops {
assert!(l.vertices.iter().all(|v| v.bulge == 0.0), "straight segments only");
for (a, b) in l.vertices.iter().zip(l.vertices.iter().cycle().skip(1)) {
let (a, b) = (a.p, b.p);
if (a.y > p.y) != (b.y > p.y) && p.x < a.x + (p.y - a.y) / (b.y - a.y) * (b.x - a.x) {
inside = !inside;
}
}
}
inside
}
const A: [f64; 2] = [0.0, 0.0];
const B: [f64; 2] = [10.0, 0.0];
const C: [f64; 2] = [10.0, 10.0];
const D: [f64; 2] = [0.0, 10.0];
#[test]
fn edges_listed_out_of_order_read_as_the_outline() {
let in_order = vertices(&[line(A, B), line(B, C), line(C, D), line(D, A)]);
// Read in file order, this is A, B, D, C, B, C, A, D: its even-odd fill is an hourglass.
let shuffled = vertices(&[line(A, B), line(D, C), line(B, C), line(A, D)]);
assert_same(&shuffled, &in_order);
let loops = read_loops(&[vec![line(A, B), line(D, C), line(B, C), line(A, D)]]);
for p in [[5.0, 1.0], [5.0, 9.0], [1.0, 5.0], [9.0, 5.0]] {
assert!(filled(&loops, Vec2::new(p[0], p[1])), "{p:?}");
}
}
#[test]
fn edges_stored_end_to_start_are_turned_around() {
let p = [[0.0, 0.0], [10.0, 0.0], [15.0, 8.0], [10.0, 16.0], [0.0, 16.0], [-5.0, 8.0]];
let in_order = vertices(&[line(p[0], p[1]), line(p[1], p[2]), line(p[2], p[3]), line(p[3], p[4]), line(p[4], p[5]), line(p[5], p[0])]);
// The second and third edges are both stored end to start, and the last one too.
let edges = [line(p[0], p[1]), line(p[2], p[1]), line(p[3], p[2]), line(p[3], p[4]), line(p[4], p[5]), line(p[0], p[5])];
assert_same(&vertices(&edges), &in_order);
// Around the two reversed edges in a row, a vertex list in file order (..., P1, P2, P1, P3,
// P2, P3, ...) leaves the triangle P1 P2 P3 unfilled.
let loops = read_loops(&[edges.to_vec()]);
assert!(filled(&loops, Vec2::new(11.0, 7.0)));
}
#[test]
fn arcs_ellipse_arcs_and_splines_stored_end_to_start_are_turned_around() {
// A loop round counter-clockwise: the bottom, a half circle out to the right, the top, and
// half an ellipse out to the left.
let arc = Edge::Arc([10.0, 5.0], 5.0, -90.0, 90.0, true);
let ellipse = Edge::Ellipse([0.0, 5.0], [0.0, 5.0], 0.4, 0.0, 180.0, true);
let in_order = vertices(&[line(A, B), arc, line(C, D), ellipse]);
// The same half circle from (10, 10) to (10, 0) clockwise: a clockwise arc stores its angles
// negated. The same half ellipse from (0, 0) to (0, 10) clockwise.
let arc_back = Edge::Arc([10.0, 5.0], 5.0, 270.0, 90.0, false);
let ellipse_back = Edge::Ellipse([0.0, 5.0], [0.0, 5.0], 0.4, 180.0, 360.0, false);
let got = vertices(&[line(A, B), arc_back, line(D, C), ellipse_back]);
assert_same(&got, &in_order);
assert!(in_order.iter().any(|v| v.bulge > 0.5), "the half circle is a bulge: {in_order:?}");
// The same half circle found before the run's first edge: an open path listed from its
// last edge.
let arc = Edge::Arc([10.0, 5.0], 5.0, -90.0, 90.0, true);
let in_order = vertices(&[arc, line(C, D)]);
assert_same(&vertices(&[line(C, D), Edge::Arc([10.0, 5.0], 5.0, 270.0, 90.0, false)]), &in_order);
// A Bezier spline and the same curve with its control points reversed.
let control = vec![[10.0, 0.0], [10.0, 8.0], [0.0, 8.0], [0.0, 0.0]];
let knots = vec![0.0, 0.0, 0.0, 0.0, 1.0, 1.0, 1.0, 1.0];
let spline = Edge::Spline(3, knots.clone(), control.clone());
let spline_back = Edge::Spline(3, knots, control.into_iter().rev().collect());
let in_order = vertices(&[line(A, B), spline]);
assert!(in_order.len() > 8, "{in_order:?}");
assert_same(&vertices(&[line(A, B), spline_back]), &in_order);
}
#[test]
fn ends_that_differ_by_rounding_still_meet() {
// A 1,000 by 10 rectangle whose corners are 5e-4 apart: half a millionth of its length,
// far more than the 1e-9 within which two points are one vertex, so each joint keeps both
// points.
let (x, y, w, h, e) = (5e5, -3e5, 1e3, 10.0, 5e-4);
let p = [[x, y], [x + w, y], [x + w, y + h], [x, y + h]];
let q = |i: usize| [p[i][0] + e, p[i][1] - e];
let edges = [line(p[0], p[1]), line(q(1), p[2]), line(q(2), p[3]), line(q(3), q(0))];
let in_order = vertices(&edges);
assert_eq!(in_order.len(), 8, "{in_order:?}");
let shuffled = vertices(&[edges[0].clone(), line(p[3], q(2)), edges[3].clone(), line(p[2], q(1))]);
assert_same(&shuffled, &in_order);
}
#[test]
fn an_end_just_past_the_tolerance_does_not_meet() {
// A 1,000-wide path: ends meet within 1e-3. The triangle A T C is stored with a gap of 5e-4
// at T; a second triangle has a corner X 1.7e-3 from T, in the next lookup cell. Listed
// before the edge that does meet T, X's edge must still not be joined there.
let (a, t, t2, c) = ([0.0, 0.0], [500.0002, 0.0], [500.0007, 0.0], [250.0, 10.0]);
let (x, r, q) = ([500.0019, 0.0], [1000.0, 0.0], [750.0, 10.0]);
let after = vertices(&[line(a, t), line(t2, c), line(c, a), line(q, x), line(x, r), line(r, q)]);
let before = vertices(&[line(a, t), line(q, x), line(t2, c), line(c, a), line(x, r), line(r, q)]);
assert_same(&before, &after);
}
/// Line edges joined in file order: each edge's start unless the list already ends there, then
/// its end, and the closing point dropped.
fn in_file_order(edges: &[Edge]) -> Vec<PolyVertex> {
let mut out: Vec<PolyVertex> = Vec::new();
for edge in edges {
let Edge::Line(a, b) = edge else { panic!("lines only") };
for p in [a, b] {
let p = Vec2::new(p[0], p[1]);
if out.last().is_none_or(|last| !last.p.near(p, 1e-9)) {
out.push(PolyVertex::new(p));
}
}
}
if out.len() > 1 && out[0].p.near(out[out.len() - 1].p, 1e-9) {
out.pop();
}
out
}
#[test]
fn a_loop_whose_lookups_take_too_long_is_read_in_file_order() {
// Petals from a point Q out and back, and many edges from two points 1.4 tolerances either
// side of Q, listed between the first petal and the rest: every return to Q looks at those
// on one side (the other is two cells away). Past the lookup budget the loop is read in file
// order, as before chaining.
let at = |r: f64, k: usize, n: usize| {
let a = std::f64::consts::TAU * k as f64 / n as f64;
[r * a.cos(), r * a.sin()]
};
let (q, side) = ([0.0, 0.0], 2.8e-3);
let mut edges = vec![line(q, at(1000.0, 0, 1000))];
for i in 0..2000 {
edges.push(line([if i % 2 == 0 { side } else { -side }, 0.0], at(500.0, i, 2000)));
}
edges.push(line(at(1000.0, 0, 1000), q));
for k in 1..1000 {
edges.push(line(q, at(1000.0, k, 1000)));
edges.push(line(at(1000.0, k, 1000), q));
}
assert_eq!(vertices(&edges), in_file_order(&edges));
}
#[test]
fn an_open_path_is_chained_from_both_ends() {
// Three sides of the square, A to D, listed from the middle: the edges before the first
// listed one go in front, as stored or turned around.
let in_order = vertices(&[line(A, B), line(B, C), line(C, D)]);
assert_same(&vertices(&[line(B, C), line(C, D), line(B, A)]), &in_order);
assert_same(&vertices(&[line(C, D), line(B, C), line(A, B)]), &in_order);
}
#[test]
fn a_path_whose_edges_run_on_keeps_its_order_and_its_points() {
// Clockwise, starting at C, with a gap of 1e-6 at D: within a millionth of the outline
// (1e-5), so the edges run on, but more than 1e-9, so both points stay.
let d_off = [D[0], D[1] + 1e-6];
let edges = [line(C, B), line(B, A), line(A, D), line(d_off, C)];
let got = vertices(&edges);
let expected: Vec<PolyVertex> = [C, B, A, D, d_off].iter().map(|p| PolyVertex::new(Vec2::new(p[0], p[1]))).collect();
assert_eq!(got, expected);
}
#[test]
fn separate_outlines_in_one_path_fill_separately() {
let square = |x: f64, y: f64| {
let p = [[x, y], [x + 10.0, y], [x + 10.0, y + 10.0], [x, y + 10.0]];
[line(p[0], p[1]), line(p[1], p[2]), line(p[2], p[3]), line(p[3], p[0])]
};
let [a, b, c] = [square(0.0, 0.0), square(100.0, 0.0), square(50.0, 100.0)];
// In file order, the jumps from one square to the next and back to the first make a
// triangle between them, which the even-odd fill filled.
let in_order: Vec<Edge> = a.iter().chain(&b).chain(&c).cloned().collect();
// The same squares, their edges interleaved and the third square's turned around.
let mixed = vec![
a[0].clone(),
b[2].clone(),
line([60.0, 110.0], [60.0, 100.0]),
a[2].clone(),
b[0].clone(),
line([50.0, 110.0], [60.0, 110.0]),
a[1].clone(),
b[3].clone(),
line([50.0, 100.0], [50.0, 110.0]),
a[3].clone(),
b[1].clone(),
line([60.0, 100.0], [50.0, 100.0]),
];
for edges in [in_order, mixed] {
let loops = read_loops(&[edges]);
for p in [[5.0, 5.0], [105.0, 5.0], [55.0, 105.0]] {
assert!(filled(&loops, Vec2::new(p[0], p[1])), "{p:?}");
}
for p in [[50.0, 30.0], [30.0, 5.0], [55.0, 50.0]] {
assert!(!filled(&loops, Vec2::new(p[0], p[1])), "{p:?}");
}
}
}
#[test]
fn an_outline_left_open_is_closed_on_itself() {
// A square, then three sides of another listed apart from it: the second is closed by its
// missing side, not through the first square's corner.
let b = [[100.0, 0.0], [110.0, 0.0], [110.0, 10.0], [100.0, 10.0]];
let edges = vec![line(A, B), line(B, C), line(C, D), line(D, A), line(b[1], b[2]), line(b[0], b[1]), line(b[2], b[3])];
let loops = read_loops(&[edges]);
assert!(filled(&loops, Vec2::new(5.0, 5.0)));
assert!(filled(&loops, Vec2::new(105.0, 5.0)));
assert!(!filled(&loops, Vec2::new(90.0, 5.0)));
}
#[test]
fn outlines_with_missing_edges_are_joined_in_file_order() {
// The bottom from right to left, then the top and a cut corner from left to right, of an
// outline whose sides are missing: the two open runs are joined straight in the order they
// are listed, so the outline still fills.
let loops = read_loops(&[vec![line(B, A), line(D, [8.0, 10.0]), line([8.0, 10.0], [10.0, 8.0])]]);
for p in [[5.0, 5.0], [9.0, 2.0], [1.0, 8.0]] {
assert!(filled(&loops, Vec2::new(p[0], p[1])), "{p:?}");
}
assert!(!filled(&loops, Vec2::new(9.8, 9.8)));
}
#[test]
fn a_later_outline_closes_at_its_exact_start() {
// A square, then a second one 100 to the right whose last edge ends 5e-5 above its first
// corner: within the tolerance (1.1e-4), so the outline is closed. The jump back to the first
// square must start from that corner, or the jumps out and back leave a sliver between them.
let s = [100.0, 0.0];
let edges = vec![
line(A, B),
line(B, C),
line(C, D),
line(D, A),
line(s, [110.0, 0.0]),
line([110.0, 0.0], [110.0, 10.0]),
line([110.0, 10.0], [100.0, 10.0]),
line([100.0, 10.0], [100.0, 5e-5]),
];
let loops = read_loops(&[edges]);
assert!(filled(&loops, Vec2::new(5.0, 5.0)));
assert!(filled(&loops, Vec2::new(105.0, 5.0)));
assert!(!filled(&loops, Vec2::new(50.0, 1.2e-5)));
}
#[test]
fn a_chained_loop_is_saved_as_it_was_read() {
let in_order = vertices(&[line(A, B), line(B, C), line(C, D), line(D, A)]);
let shuffled = cadcraft_io::read(dxf(&[vec![line(A, B), line(D, C), line(B, C), line(A, D)]]).as_bytes(), "edges.dxf").expect("read");
let saved = cadcraft_io::write_dxf(&shuffled);
let back = loops_of(&cadcraft_io::read(saved.as_bytes(), "saved.dxf").expect("reopen"));
assert_eq!(back.len(), 1);
assert_same(&back[0].vertices, &in_order);
assert_same(&back[0].vertices, &loops_of(&shuffled)[0].vertices);
}
#[test]
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
fn a_dwg_edge_path_out_of_order_reads_as_the_outline() {
cadcraft_io::dwg_worker::allow_in_process();
let in_order = vertices(&[line(A, B), line(B, C), line(C, D), line(D, A)]);
let text = dxf(&[vec![line(A, B), line(D, C), line(B, C), line(A, D)]]);
let doc = acadrust::DxfReader::from_reader(std::io::Cursor::new(text.into_bytes())).expect("acadrust reads the DXF").read().expect("parse");
let dwg = acadrust::DwgWriter::write_to_vec(&doc).expect("acadrust writes a DWG");
let loops = loops_of(&cadcraft_io::read(&dwg, "edges.dwg").expect("read DWG"));
assert_eq!(loops.len(), 1);
assert_same(&loops[0].vertices, &in_order);
}
+2
View File
@@ -12,6 +12,7 @@ mod attrib_props;
mod block_expansion;
mod closed_spline;
mod codepages;
mod dash_controls;
mod dim_block_resave_roundtrip;
mod dim_block_text;
mod dim_marks_roundtrip;
@@ -36,6 +37,7 @@ mod exhausted_handseed;
mod followups_626;
mod groups_roundtrip;
mod hatch_assoc_roundtrip;
mod hatch_edge_chain;
mod hatch_elliptic_edge_dedup;
mod hatch_loop_flags;
mod hatch_pattern_def;
+244 -12
View File
@@ -30,6 +30,9 @@ pub struct Remote {
/// The per-session control token for this port, read from the owner-only token file on first
/// use so requests can authenticate (CWE-306).
token: Option<String>,
/// Whether a request on the current connection has passed the server's token check, so the
/// server takes lines longer than `MAX_UNAUTHENTICATED_LINE` on it (#1925).
authed: bool,
/// Longest reply line accepted (`MAX_REPLY_LINE`; smaller in tests).
max_reply: usize,
}
@@ -64,7 +67,7 @@ fn read_reply_line(reader: &mut impl BufRead, reply: &mut String, max: usize) ->
impl Remote {
/// Connect to a running control server; its session token is read lazily when the first request is sent.
pub fn connect(addr: &str) -> std::io::Result<Self> {
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None, max_reply: MAX_REPLY_LINE };
let mut r = Self { addr: addr.to_string(), conn: None, next_id: 1, launch: false, token: None, authed: false, max_reply: MAX_REPLY_LINE };
r.reconnect()?;
Ok(r)
}
@@ -72,7 +75,7 @@ impl Remote {
/// the server before the app is open. With `launch`, a call that finds nothing at `addr`
/// opens the app with that control port first (macOS) and waits for it.
pub fn lazy(addr: &str, launch: bool) -> Self {
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, max_reply: MAX_REPLY_LINE }
Self { addr: addr.to_string(), conn: None, next_id: 1, launch, token: None, authed: false, max_reply: MAX_REPLY_LINE }
}
/// The per-session token for this port, read (and cached) from the owner-only token file. A
@@ -122,6 +125,7 @@ impl Remote {
}
fn reconnect(&mut self) -> std::io::Result<()> {
self.conn = None;
self.authed = false;
let mut last = std::io::Error::new(std::io::ErrorKind::NotFound, format!("cannot resolve {}", self.addr));
for sa in self.addr.to_socket_addrs()? {
match TcpStream::connect_timeout(&sa, Duration::from_millis(800)) {
@@ -216,15 +220,30 @@ fn is_read_only(method: &str) -> bool {
}
impl Remote {
/// Put the current token (if any) on `req`, replacing the one it carries.
/// Connect if needed, put the token for the peer actually connected to on `req`, and send it.
/// The server reads the token only at the end of a line and keeps lines short until one has
/// passed the check (#1925), so a long request on a new connection goes after a `ping` with the
/// token; when the `ping` is refused its reply comes back instead and the request isn't sent.
fn sign_and_send(&mut self, req: &mut Value) -> Result<String, (std::io::Error, bool)> {
if self.conn.is_none() {
self.reach().map_err(|e| (e, false))?;
}
self.set_token(req);
self.roundtrip(&req.to_string())
let line = req.to_string();
if !self.authed && line.len() > crate::control_token::MAX_UNAUTHENTICATED_LINE {
let mut ping = json!({"id": req.get("id").cloned().unwrap_or(Value::Null), "method": "ping"});
self.set_token(&mut ping);
// The request itself hasn't been sent, so a failure here is safe to retry.
let reply = self.roundtrip(&ping.to_string()).map_err(|(e, _)| (e, false))?;
if !serde_json::from_str::<Value>(&reply).is_ok_and(|v| past_the_token_check(&v)) {
// The app closes the connection after such a refusal.
self.conn = None;
return Ok(reply);
}
}
self.roundtrip(&line)
}
/// Put the current token (if any) on `req`, replacing the one it carries.
fn set_token(&mut self, req: &mut Value) {
let token = self.token().map(str::to_string);
if let Some(obj) = req.as_object_mut() {
@@ -235,7 +254,8 @@ impl Remote {
}
}
/// Send `req` and parse the reply, refreshing the token before a safe retry after a transport
/// error. A mutation that may have reached the server is never resent automatically.
/// error. A mutation that may have reached the server is never resent automatically, and when
/// its reply is lost (on the first attempt or the retry) the error says so.
fn exchange(&mut self, method: &str, req: &mut Value) -> Result<Value, String> {
let reply = match self.sign_and_send(req) {
Ok(r) => r,
@@ -244,28 +264,39 @@ impl Remote {
self.conn = None;
// A mutation whose reply was lost must never be sent twice.
if sent && !is_read_only(method) {
return Err(format!(
"CADCraft at {}: {e}; the reply was lost, so `{method}` may or may not have been applied. Inspect the drawing first",
self.addr
));
return Err(maybe_applied(&self.addr, method, &e));
}
// A restarted server may have rotated its token before dropping the old socket.
self.sign_and_send(req).map_err(|(e, _)| {
self.sign_and_send(req).map_err(|(e, sent)| {
self.token = None;
self.conn = None;
format!("CADCraft at {}: {e}", self.addr)
if sent && !is_read_only(method) { maybe_applied(&self.addr, method, &e) } else { format!("CADCraft at {}: {e}", self.addr) }
})?
}
};
serde_json::from_str(&reply).map_err(|e| format!("bad reply: {e}"))
let v = serde_json::from_str(&reply).map_err(|e| format!("bad reply: {e}"))?;
self.authed |= past_the_token_check(&v);
Ok(v)
}
}
/// The error for a mutation that may have reached the app but whose reply was lost.
fn maybe_applied(addr: &str, method: &str, e: &std::io::Error) -> String {
format!("CADCraft at {addr}: {e}; the reply was lost, so `{method}` may or may not have been applied. Inspect the drawing first")
}
/// An `unauthorized` reply (the app also closes the connection).
fn unauthorized(v: &Value) -> bool {
v.get("error").and_then(Value::as_str).is_some_and(|e| e.starts_with("unauthorized"))
}
/// A reply to a request that passed the token check, on a connection the app keeps open: a result,
/// or `busy` or a timeout (both say in `state` whether the request ran). The app's other refusals
/// (`unauthorized` aside) carry no `state` and close the connection.
fn past_the_token_check(v: &Value) -> bool {
v.get("ok").and_then(Value::as_bool) == Some(true) || (v.get("state").is_some() && !unauthorized(v))
}
impl Backend for Remote {
/// Send a control request with the token when available. A refused token is read again and the
/// request resent once, only when the app says it did not run it.
@@ -718,4 +749,205 @@ mod tests {
assert!(!server.join().unwrap(), "a failed mutation write was retried");
assert!(remote.token.is_none());
}
/// Serve connections by the app's line rules (#1925): until a request on a connection has
/// carried the valid token (`valid(n)` = `Ok(token)` for the n-th request read), a line longer
/// than `MAX_UNAUTHENTICATED_LINE` is refused; so is a request without the token. `Err(reply)`
/// answers with `reply` instead (none when null). As in the app, a refusal closes the
/// connection unless it says in `state` whether the request ran (busy, a timeout); other
/// requests are answered with their method. Returns the connection, method and length of every
/// line read, once no new connection comes for a while.
fn strict_app(
listener: TcpListener,
mut valid: impl FnMut(usize) -> Result<String, Value> + Send + 'static,
) -> std::thread::JoinHandle<Vec<(usize, String, usize)>> {
std::thread::spawn(move || {
listener.set_nonblocking(true).unwrap();
let mut seen = Vec::new();
for conn_no in 0.. {
let start = std::time::Instant::now();
let conn = loop {
match listener.accept() {
Ok((conn, _)) => break Some(conn),
Err(_) if start.elapsed() < Duration::from_millis(500) => std::thread::sleep(Duration::from_millis(10)),
Err(_) => break None,
}
};
let Some(conn) = conn else { break };
conn.set_nonblocking(false).unwrap();
let mut reader = BufReader::new(conn.try_clone().unwrap());
let mut out = conn;
let mut authed = false;
let mut line = String::new();
while reader.read_line(&mut line).unwrap_or(0) > 0 {
let req: Value = serde_json::from_str(&line).unwrap();
let len = line.trim_end().len();
line.clear();
seen.push((conn_no, req["method"].as_str().unwrap_or_default().to_string(), len));
let reply = if !authed && len > crate::control_token::MAX_UNAUTHENTICATED_LINE {
json!({"ok": false, "error": "request line too long before a request with the control token"})
} else {
match valid(seen.len() - 1) {
Ok(valid) if req["token"].as_str() == Some(valid.as_str()) => {
authed = true;
json!({"id": req["id"], "ok": true, "result": req["method"]})
}
Ok(_) => {
json!({"id": req["id"], "ok": false, "error": "unauthorized: missing or invalid control token", "state": "not-run"})
}
Err(Value::Null) => break,
Err(reply) => {
// Busy and timeouts come after the token check.
authed |= reply.get("state").is_some() && !unauthorized(&reply);
reply
}
}
};
writeln!(out, "{reply}").unwrap();
if reply["ok"] != json!(true) && (reply.get("state").is_none() || unauthorized(&reply)) {
break;
}
}
}
seen
})
}
/// Parameters that make a request line longer than the server reads before the token check.
fn long_params() -> Value {
json!({"command": "text", "params": {"text": "x".repeat(crate::control_token::MAX_UNAUTHENTICATED_LINE)}})
}
/// A long request on a new connection goes after a short `ping` with the token, so the server
/// takes it; later long requests on that connection go straight away, and one on the next
/// connection again goes after a `ping`.
#[test]
fn a_long_request_on_a_new_connection_goes_after_an_authenticating_ping() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let token = crate::control_token::issue(addr.port()).unwrap();
let server = strict_app(listener, move |_| Ok(token.clone()));
let mut remote = Remote::lazy(&addr.to_string(), false);
let mut got = vec![remote.call("engine.execute", long_params()), remote.call("engine.execute", long_params())];
// The connection drops (the app restarted, say); the client connects again.
remote.conn = None;
got.push(remote.call("engine.execute", long_params()));
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
assert_eq!(got, vec![Ok(json!("engine.execute")); 3]);
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (0, "engine.execute"), (0, "engine.execute"), (1, "ping"), (1, "engine.execute")]);
assert!(seen[0].2 <= crate::control_token::MAX_UNAUTHENTICATED_LINE, "{seen:?}");
}
/// When the `ping` before a long request is refused (a stale token, #2087), the long request
/// isn't sent on that connection; it is sent once, on a new connection, with the new token.
#[test]
fn a_refused_ping_keeps_the_long_request_back_until_the_new_token_is_read() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
crate::control_token::issue(addr.port()).unwrap();
let mut fresh = String::new();
let server = strict_app(listener, move |n| {
if n == 0 {
// The app starts and writes its own session's token.
fresh = crate::control_token::issue(addr.port()).unwrap();
}
Ok(fresh.clone())
});
let mut remote = Remote::lazy(&addr.to_string(), false);
let got = remote.call("engine.execute", long_params());
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
assert_eq!(got, Ok(json!("engine.execute")));
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (1, "ping"), (1, "engine.execute")]);
}
/// A lost reply to the `ping` before a long mutation doesn't make the mutation "maybe applied":
/// it hasn't been sent, so it is sent once on a new connection.
#[test]
fn a_lost_ping_reply_leaves_the_long_request_safe_to_send() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let token = crate::control_token::issue(addr.port()).unwrap();
// The first connection closes after reading the `ping`, without a reply.
let server = strict_app(listener, move |n| if n == 0 { Err(Value::Null) } else { Ok(token.clone()) });
let mut remote = Remote::lazy(&addr.to_string(), false);
let got = remote.call("engine.execute", long_params());
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
assert_eq!(got, Ok(json!("engine.execute")));
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (1, "ping"), (1, "engine.execute")]);
}
/// A refusal that closes the connection (here every connection slot is taken) never leaves a
/// mutation "maybe applied": a long one refused at its `ping` isn't sent, the next request goes
/// on a new connection, and a long request after a refused short one authenticates first.
#[test]
fn a_refusal_that_closes_the_connection_leaves_no_mutation_in_doubt() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let token = crate::control_token::issue(addr.port()).unwrap();
let full = json!({"ok": false, "error": "too many control connections"});
let server = strict_app(listener, move |n| if n < 2 { Err(full.clone()) } else { Ok(token.clone()) });
let mut remote = Remote::lazy(&addr.to_string(), false);
let short = json!({"command": "circle", "params": {}});
let got = [remote.call("engine.execute", long_params()), remote.call("engine.execute", short), remote.call("engine.execute", long_params())];
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
let full = Err("too many control connections".to_string());
assert_eq!(got, [full.clone(), full, Ok(json!("engine.execute"))]);
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (1, "engine.execute"), (2, "ping"), (2, "engine.execute")]);
}
/// When the retry after a lost `ping` reply sends the long request and its reply is lost too,
/// a mutation is reported as maybe applied (and not sent again); a read-only request isn't.
#[test]
fn a_lost_reply_on_the_retry_still_says_a_mutation_may_have_been_applied() {
for (method, warned) in [("engine.execute", true), ("drawing.inspect", false)] {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let token = crate::control_token::issue(addr.port()).unwrap();
// The first `ping` and then the request on the retry's connection go unanswered.
let server = strict_app(listener, move |n| if n == 1 { Ok(token.clone()) } else { Err(Value::Null) });
let mut remote = Remote::lazy(&addr.to_string(), false);
let got = remote.call(method, long_params());
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
let err = got.unwrap_err();
assert_eq!(err.contains("may or may not have been applied"), warned, "{method}: {err}");
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (1, "ping"), (1, method)], "sent once");
}
}
/// A `ping` that passed the token check but timed out in the app (it may have run) still lets
/// the long request through on that connection, instead of reporting it as maybe applied.
#[test]
fn a_ping_that_timed_out_after_the_token_check_lets_the_long_request_through() {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let addr = listener.local_addr().unwrap();
let token = crate::control_token::issue(addr.port()).unwrap();
let server =
strict_app(
listener,
move |n| if n == 0 { Err(json!({"ok": false, "error": "timeout", "state": "may-have-run"})) } else { Ok(token.clone()) },
);
let mut remote = Remote::lazy(&addr.to_string(), false);
let got = remote.call("engine.execute", long_params());
drop(remote);
let seen = server.join().unwrap();
crate::control_token::revoke(addr.port());
assert_eq!(got, Ok(json!("engine.execute")));
let methods: Vec<(usize, &str)> = seen.iter().map(|(c, m, _)| (*c, m.as_str())).collect();
assert_eq!(methods, [(0, "ping"), (0, "engine.execute")]);
}
}
+7
View File
@@ -14,6 +14,13 @@ use std::path::PathBuf;
/// Length of the token in bytes (256 bits), rendered as lowercase hex.
const TOKEN_BYTES: usize = 32;
/// Longest request line in bytes (newline excluded) the control server reads on a connection
/// before a request on it has carried the right token. The token is checked only once the whole
/// line is read (a client that sorts keys sends it last), so this bounds what a peer without the
/// token can make the app buffer (#1925). A client sends a longer request only after a shorter one
/// with the token has been answered on the same connection.
pub const MAX_UNAUTHENTICATED_LINE: usize = 64 * 1024;
/// The file holding the control token for `port`, inside a per-user private directory.
///
/// On Unix the runtime dir (`XDG_RUNTIME_DIR`, already `0700` and per-user) is preferred, else the
+5 -1
View File
@@ -41,6 +41,9 @@ pub(crate) fn sub_ctx<'a>(ctx: &Ctx<'a>, e: &Entity, m: Mat3) -> Ctx<'a> {
block_pstyle: ctx.block_pstyle,
// The reference's own, set by the caller (`Builder::transparency` while it draws).
block_transparency: ctx.block_transparency,
// Proxy graphics are drawn as part of the block they are in; a block reference or a
// dimension sets its own block instead.
block: ctx.block,
}
}
@@ -82,7 +85,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
}
let off = Vec2::new(ins.col_spacing * f64::from(c), ins.row_spacing * f64::from(r)).rotate(ins.rotation);
let m = Mat3::translate(off).then_before(ins.transform(blk.base.xy()));
let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, m) };
let sub = Ctx { block: Some(blk), block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, m) };
// XCLIP: the copy is drawn on its own, then cut to the boundary.
let clip = xclip_region(ins, &sub.xf);
let mut part = clip.as_ref().map(|_| b.part());
@@ -108,6 +111,7 @@ pub(crate) fn insert(b: &mut Builder, ctx: &Ctx, e: &Entity, ins: &cadcraft_doc:
if let (Some(part), Some((region, inverted))) = (part, &clip) {
b.list.expanded = part.list.expanded;
b.list.truncated |= part.list.truncated;
b.list.undashed = b.list.undashed.saturating_add(part.list.undashed);
append_clipped_keep(&mut b.list, &part.list, &if *inverted { Clip::Outside(region) } else { Clip::Poly(region) });
xclip_frame(b, ctx, region, rgb);
}
+10 -3
View File
@@ -108,10 +108,16 @@ pub struct DisplayList {
/// Block contents expanded while building (see [`MAX_BLOCK_EXPANSION`]).
pub expanded: usize,
/// The block-expansion budget or the point budget ([`crate::MAX_DISPLAY_POINTS`]) was spent:
/// block contents or objects past it are not in the list. The screen,
/// plots and exports draw what is here; the CLI and the control channel report this, so an
/// output that leaves contents out is never silent (#1070).
/// block contents or objects past it are not in the list; or a dashed run was drawn
/// continuous past a dash limit ([`DisplayList::undashed`]). The screen,
/// plots and exports draw what is here; the control channel and the MCP render report this,
/// so an output that leaves contents out is never silent (#1070).
pub truncated: bool,
/// Dashed runs drawn continuous because of a dash limit: one run repeating its pattern past
/// [`crate::MAX_RUN_DASH_ELEMENTS`], or the build past [`crate::MAX_DASH_ELEMENTS`] (#1069). Runs drawn
/// continuous by rule (shorter than one period, a pattern under two pixels or, on screen, past
/// 50,000 periods) are not counted.
pub undashed: usize,
/// Plot style end, join and fill style per primitive (parallel to `prims`; missing entries
/// are "use object"), turned into geometry by [`pen::apply`].
pub pens: Vec<Pen>,
@@ -210,4 +216,5 @@ pub(crate) fn append(dst: &mut DisplayList, src: DisplayList) {
dst.bounds = dst.bounds.union(&src.bounds);
dst.expanded = dst.expanded.saturating_add(src.expanded);
dst.truncated |= src.truncated;
dst.undashed = dst.undashed.saturating_add(src.undashed);
}
+13 -6
View File
@@ -94,7 +94,9 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
let stroke_as = |b: &mut Builder, pts: &[Vec2], how: Layout| match lt.as_ref().filter(|_| b.opts.linetypes) {
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
for dash in linetype::apply_as(pts, lt, ltscale, min, how) {
let dashes = linetype::apply_as(pts, lt, ltscale, min, how, b);
let laid = dashes.is_some();
for dash in dashes.unwrap_or_else(|| vec![pts.to_vec()]) {
if dash.len() == 1 {
if let Some(p) = dash.first() {
b.point(ctx, rgb, *p);
@@ -103,8 +105,9 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
b.polyline(ctx, rgb, lw, &dash);
}
}
// Text and shapes embedded in the linetype (shapes when their SHX file is found).
if b.opts.text {
// Text and shapes embedded in the linetype (shapes when their SHX file is found), on
// a run whose dashes were laid out.
if b.opts.text && laid {
for sh in linetype_text::texts(ctx.d, pts, lt, ltscale, min, how) {
b.shaped(ctx, rgb, lw, &sh);
}
@@ -176,7 +179,7 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
// Dashed: each dash a filled piece of the band; dots a line across it.
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
let (tris, ticks, centres) = wide::dashed(p, tol, lt, ltscale, min);
let (tris, ticks, centres) = wide::dashed(p, tol, lt, ltscale, min, b);
b.tris(ctx, rgb, &tris);
if hairline {
for c in &centres {
@@ -366,13 +369,17 @@ fn draw_dimension(
own: u8,
) {
let (lt, ltscale) = stroke;
// A dimension inside a block whose own block leads back to that block (it is the block, or
// they lie on a loop of references, dimensions and multileaders) is drawn from its definition
// points, as one whose block is missing is (see `loops`, #1923).
if let Some(blk) = dm.block.as_ref().and_then(|n| ctx.d.block(n))
&& ctx.depth < cadcraft_doc::MAX_BLOCK_DEPTH
&& !ctx.block.is_some_and(|outer| b.leads_back(ctx.d, outer, blk))
{
// DXF group 12: a moved dimension keeps its `*D` block where it was and the offset in
// the insertion point, so the block draws translated by it (#2634).
let off = dm.insertion_point.xy();
let sub = Ctx { block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::translate(off)) };
let sub = Ctx { block: Some(blk), block_pstyle: b.named, block_transparency: own, ..sub_ctx(ctx, e, Mat3::translate(off)) };
// DIMTFILL: the block's MTEXT carries no background mask here, so a background
// around each of the block's texts is drawn before the block's first text or first
// line of the text's marks, except for a text that a SOLID of the block covers.
@@ -421,7 +428,7 @@ pub(crate) fn stroke_with(b: &mut Builder, ctx: &Ctx, rgb: Ink, lw: f32, lt: Opt
match lt.filter(|_| b.opts.linetypes) {
Some(lt) => {
let min = b.opts.min_dash / ctx.xf.scale_factor().max(1e-12);
for dash in linetype::apply(pts, lt, ltscale, min) {
for dash in linetype::apply(pts, lt, ltscale, min, b) {
match dash.as_slice() {
[p] => b.point(ctx, rgb, *p),
_ => b.polyline(ctx, rgb, lw, &dash),
+49
View File
@@ -13,6 +13,7 @@ mod fill;
mod hatch;
mod linetype;
mod linetype_text;
mod loops;
mod mline;
mod outline;
pub mod paper;
@@ -100,6 +101,9 @@ struct Ctx<'a> {
block_pstyle: Option<usize>,
/// Transparency (percent) of the block reference being expanded, for `ByBlock`.
block_transparency: u8,
/// The block whose contents are being drawn (`None` at the top level): a dimension in it whose
/// own block leads back to it is drawn from its definition points (see [`loops`]).
block: Option<&'a cadcraft_doc::Block>,
}
impl Ctx<'_> {
@@ -130,6 +134,13 @@ struct Builder<'a> {
points: &'a std::sync::atomic::AtomicUsize,
/// The most points the build may hold: [`MAX_DISPLAY_POINTS`] (less in tests).
max_points: usize,
/// Dash pattern elements the whole build has laid out so far, shared like `points`.
dashes: &'a std::sync::atomic::AtomicUsize,
/// The most dash pattern elements the build may lay out: [`MAX_DASH_ELEMENTS`] (less in tests).
max_dashes: usize,
/// The loops of the drawing's block graph, worked out once for the whole build when a search
/// near a dimension's block does not settle whether it leads back (see [`loops`]).
loops: &'a std::sync::OnceLock<loops::BlockLoops>,
}
/// Upper bound on the block contents drawn per display list (each block reference, MINSERT copy
@@ -148,6 +159,21 @@ pub const MAX_BLOCK_EXPANSION: usize = 2_000_000;
/// for a plot) is expected to hold a few tens of millions.
pub const MAX_DISPLAY_POINTS: usize = 64_000_000;
/// Upper bound on the dash pattern elements one dashed run (a line, an arc, a polyline segment or
/// a PLINEGEN polyline) is laid out over: a longer pattern repeated more often is drawn
/// continuous, and [`DisplayList::undashed`] counts it. A plot keeps the dashes of a run of any
/// number of periods up to this (#1069).
pub const MAX_RUN_DASH_ELEMENTS: usize = 2_000_000;
/// Upper bound on the dash pattern elements one display list lays out over all its dashed runs.
/// Each run may visit up to [`MAX_RUN_DASH_ELEMENTS`], and a pattern of mostly gaps visits many
/// elements for each point it draws, so a small file of many long lines walked millions of
/// elements per line with nothing to stop it, [`MAX_DISPLAY_POINTS`] included (#1923). The limit is
/// as many elements as the list may hold points: a dash and its gap make about one point per
/// element, so a drawing whose dashes fit the point budget keeps them. Past it later dashed runs
/// are drawn continuous, and [`DisplayList::undashed`] counts them.
pub const MAX_DASH_ELEMENTS: usize = 64_000_000;
impl<'a> Builder<'a> {
/// `color` and `lw` as the plot style table prints them.
fn styled(&self, color: Ink, lw: f32) -> (Ink, f32) {
@@ -380,8 +406,16 @@ impl<'a> Builder<'a> {
transparency: self.transparency,
points: self.points,
max_points: self.max_points,
dashes: self.dashes,
max_dashes: self.max_dashes,
loops: self.loops,
}
}
/// Whether block `to` leads back to block `from` in `d`, the drawing being built (see
/// [`loops`]).
fn leads_back(&self, d: &Drawing, from: &cadcraft_doc::Block, to: &cadcraft_doc::Block) -> bool {
loops::leads_back(d, self.loops, from, to)
}
/// Take one unit of the block-expansion budget; false once it is spent, or once the build
/// holds all the points it may ([`MAX_DISPLAY_POINTS`]), so block copies stop being visited.
fn expand(&mut self) -> bool {
@@ -414,6 +448,21 @@ impl<'a> Builder<'a> {
}
}
/// The build's dash budget ([`MAX_DASH_ELEMENTS`]), charged as [`Builder::charge`] charges
/// points: once a run does not fit, the count is past the limit and every later run is drawn
/// continuous. The runs laid out never pass the limit; the count itself passes it by at most one
/// run per thread building in parallel.
impl linetype::Budget for Builder<'_> {
fn take(&mut self, visits: usize) -> bool {
use std::sync::atomic::Ordering::Relaxed;
self.dashes.load(Relaxed) < self.max_dashes && self.dashes.fetch_add(visits, Relaxed).saturating_add(visits) <= self.max_dashes
}
fn refused(&mut self) {
self.list.undashed = self.list.undashed.saturating_add(1);
self.list.truncated = true;
}
}
/// The clip boundary of image `i` as a closed outline, or `None` when the whole image shows.
/// `place` gives the position of a point of the entity's pixel grid (x right, y down from the
/// top-left corner of the image).
+185 -41
View File
@@ -35,20 +35,38 @@ pub enum Layout {
const MAX_PERIODS: f64 = 50_000.0;
/// Most pattern elements a run is laid out over (a long pattern repeated many times); beyond
/// that it is drawn continuous too.
const MAX_ELEMENTS: f64 = 2_000_000.0;
/// that it is drawn continuous too, and the build says so ([`Budget::refused`]).
const MAX_ELEMENTS: f64 = crate::MAX_RUN_DASH_ELEMENTS as f64;
/// The drawn stretches of a run `len` long, as (start, end) along it (a dot: start == end), in
/// order; `None` when it is drawn continuous (shorter than one period, or repeating too often).
/// `pattern` is scaled; `min_pattern` is the caller's (see [`MAX_PERIODS`]).
fn layout(len: f64, pattern: &[f64], how: Layout, min_pattern: f64) -> Option<Vec<(f64, f64)>> {
/// Where a build's dash work is charged ([`crate::Builder`], against
/// [`crate::MAX_DASH_ELEMENTS`]): asked before a run's pattern elements are visited.
pub(crate) trait Budget {
/// Take `visits` pattern elements for one run; false when the build may not spend them, and
/// the run is drawn continuous.
fn take(&mut self, visits: usize) -> bool;
/// A run is drawn continuous because of a limit: its own ([`MAX_ELEMENTS`]) or the build's.
fn refused(&mut self);
}
/// The pattern elements [`layout`] visits on a run `len` long, or `None` when the run is drawn
/// continuous whatever the limits: shorter than one period, or past [`MAX_PERIODS`] in a display
/// build. `pattern` is scaled.
fn visits(len: f64, pattern: &[f64], min_pattern: f64) -> Option<f64> {
let period: f64 = pattern.iter().map(|d| d.abs()).sum();
if !(len.is_finite() && period > 1e-12) || len < period || (min_pattern > 0.0 && len / period > MAX_PERIODS) {
return None;
}
if (len / period + 2.0) * pattern.len() as f64 > MAX_ELEMENTS {
return None;
}
Some((len / period + 2.0) * pattern.len() as f64)
}
/// The drawn stretches of a run `len` long, as (start, end) along it (a dot: start == end), in
/// order; `None` when it is drawn continuous (see [`visits`]), also when it repeats past
/// [`MAX_ELEMENTS`] or `budget` refuses it. A pattern of gaps only draws nothing, without a charge
/// (the callers return before this for one, see [`gaps_only`]). `pattern` is scaled; `min_pattern`
/// is the caller's.
fn layout(len: f64, pattern: &[f64], how: Layout, min_pattern: f64, budget: &mut impl Budget) -> Option<Vec<(f64, f64)>> {
let elements = visits(len, pattern, min_pattern)?;
let period: f64 = pattern.iter().map(|d| d.abs()).sum();
let mut drawn = Vec::new();
let mut at = 0.0;
for &d in pattern {
@@ -57,9 +75,25 @@ fn layout(len: f64, pattern: &[f64], how: Layout, min_pattern: f64) -> Option<Ve
}
at += d.abs();
}
// Gaps only: nothing to draw or walk (and `% drawn.len()` below needs one).
if drawn.is_empty() {
return Some(Vec::new());
}
if elements > MAX_ELEMENTS {
budget.refused();
return None;
}
// A closed run walks its periods rounded to a whole number (up to half a period more than
// `elements` counts), from the one before its anchor to the one after its last.
let walked = match how {
Layout::Closed { .. } => elements.max(((len / period).round().max(1.0) + 2.0) * pattern.len() as f64),
Layout::Open => elements,
};
// At most MAX_ELEMENTS and half a period here, so the cast is exact enough to charge.
if !budget.take(walked.ceil() as usize) {
budget.refused();
return None;
}
let first = pattern.first().copied().unwrap_or(0.0);
let out = match how {
Layout::Closed { anchor } => {
@@ -166,6 +200,13 @@ fn scaled(lt: &Linetype, scale: f64, min_pattern: f64) -> Option<Vec<f64>> {
(total > 1e-12 && total >= min_pattern).then(|| lt.pattern.iter().map(|d| d.length * scale).collect())
}
/// Whether `lt` is a pattern of gaps only: it draws no line on any run, also where a pattern with
/// a dash or a dot is drawn continuous (shorter than a period, sub-pixel, past a limit). Texts and
/// shapes in it are placed as [`phase`] says.
fn gaps_only(lt: &Linetype) -> bool {
!lt.pattern.is_empty() && lt.pattern.iter().all(|e| e.length < 0.0)
}
/// The pieces of `pts` over `ranges` (in order along it), a dot as a single point.
fn cut(pts: &[Vec2], ranges: &[(f64, f64)]) -> Vec<Vec<Vec2>> {
let mut cum = Vec::with_capacity(pts.len());
@@ -208,34 +249,45 @@ fn cut(pts: &[Vec2], ranges: &[(f64, f64)]) -> Vec<Vec<Vec2>> {
}
/// Split `pts`, an open run, into dashes. Dots come back as single-point runs. A run shorter than
/// one period, or with a scaled pattern shorter than `min_pattern` (sub-pixel), comes back whole.
pub fn apply(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64) -> Vec<Vec<Vec2>> {
apply_as(pts, lt, scale, min_pattern, Layout::Open)
/// one period, or with a scaled pattern shorter than `min_pattern` (sub-pixel), comes back whole,
/// as does one past a limit (see [`layout`]). A pattern of gaps only gives nothing.
pub(crate) fn apply(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64, budget: &mut impl Budget) -> Vec<Vec<Vec2>> {
apply_as(pts, lt, scale, min_pattern, Layout::Open, budget).unwrap_or_else(|| vec![pts.to_vec()])
}
/// [`apply`] with the run laid out as `how` says.
pub fn apply_as(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Vec<Vec<Vec2>> {
let laid = if pts.len() >= 2 { scaled(lt, scale, min_pattern).and_then(|p| layout(length(pts), &p, how, min_pattern)) } else { None };
match laid {
Some(r) => cut(pts, &r),
None => vec![pts.to_vec()],
/// [`apply`] with the run laid out as `how` says; `None` when the run is drawn continuous, and no
/// pieces for a pattern of gaps only.
pub(crate) fn apply_as(pts: &[Vec2], lt: &Linetype, scale: f64, min_pattern: f64, how: Layout, budget: &mut impl Budget) -> Option<Vec<Vec<Vec2>>> {
if gaps_only(lt) {
return Some(Vec::new());
}
if pts.len() < 2 {
return None;
}
let pattern = scaled(lt, scale, min_pattern)?;
layout(length(pts), &pattern, how, min_pattern, budget).map(|r| cut(pts, &r))
}
/// The dashes of the pattern along a run of length `len` laid out as `how` says, as (start, end)
/// distances; a dot has start == end. Laid out like [`apply_as`]. `None` when the run is drawn
/// continuous: shorter than one period, a scaled pattern shorter than `min_pattern`, or too many
/// repeats (see [`MAX_PERIODS`]).
pub fn ranges(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Option<Vec<(f64, f64)>> {
if len > 0.0 { scaled(lt, scale, min_pattern).and_then(|p| layout(len, &p, how, min_pattern)) } else { None }
/// continuous: shorter than one period, a scaled pattern shorter than `min_pattern`, too many
/// repeats (see [`MAX_PERIODS`]), or past a limit (see [`layout`]). A pattern of gaps only has no
/// dashes on any run.
pub(crate) fn ranges(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout, budget: &mut impl Budget) -> Option<Vec<(f64, f64)>> {
if gaps_only(lt) {
return Some(Vec::new());
}
if len > 0.0 { scaled(lt, scale, min_pattern).and_then(|p| layout(len, &p, how, min_pattern, budget)) } else { None }
}
/// Where the pattern starts on a run `len` long laid out as `how`, and how much it is stretched:
/// period `k` starts at `start + k · period · stretch`. `None` when the run is drawn continuous.
/// period `k` starts at `start + k · period · stretch`. `None` when the run is drawn continuous
/// whatever the build's budget ([`visits`], [`MAX_ELEMENTS`]); the caller places texts only on a
/// run whose dashes were laid out.
pub fn phase(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout) -> Option<(f64, f64)> {
let pattern = scaled(lt, scale, min_pattern)?;
let period: f64 = pattern.iter().map(|d| d.abs()).sum();
layout(len, &pattern, how, min_pattern)?;
visits(len, &pattern, min_pattern).filter(|v| *v <= MAX_ELEMENTS)?;
let first = pattern.first().copied().unwrap_or(0.0);
Some(match how {
Layout::Open => {
@@ -256,18 +308,28 @@ pub fn phase(len: f64, lt: &Linetype, scale: f64, min_pattern: f64, how: Layout)
mod tests {
use super::*;
/// No build: every run within its own limit is laid out.
struct Free;
impl Budget for Free {
fn take(&mut self, _: usize) -> bool {
true
}
fn refused(&mut self) {}
}
/// This gap-only pattern draws nothing, and `ranges` returns before cycling through its repeats.
#[test]
fn an_all_gap_pattern_draws_nothing_without_spinning() {
let lt = Linetype::simple("GAPS", "", &[-0.001, -0.002]);
assert_eq!(ranges(1.0, &lt, 1.0, 0.0, Layout::Open), Some(Vec::new()));
assert!(apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0).is_empty());
assert_eq!(ranges(1.0, &lt, 1.0, 0.0, Layout::Open, &mut Free), Some(Vec::new()));
assert!(apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0, &mut Free).is_empty());
}
#[test]
fn dashes_split_line() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 0.0);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 0.0, &mut Free);
// 3.0 / 0.75 = 4 periods, centred: a half dash at each end and four whole ones between.
assert_eq!(d.len(), 5);
assert!((d[0][1].x - 0.25).abs() < 1e-9);
@@ -278,7 +340,7 @@ mod tests {
#[test]
fn dots_are_single_points() {
let lt = Linetype::simple("DOT", "", &[0.0, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0);
let d = apply(&[Vec2::ZERO, Vec2::new(1.0, 0.0)], &lt, 1.0, 0.0, &mut Free);
assert!(d.iter().all(|r| r.len() == 1));
assert!(d.len() >= 4);
}
@@ -286,21 +348,21 @@ mod tests {
#[test]
fn tiny_pattern_is_continuous() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 10.0);
let d = apply(&[Vec2::ZERO, Vec2::new(3.0, 0.0)], &lt, 1.0, 10.0, &mut Free);
assert_eq!(d.len(), 1);
}
#[test]
fn dash_continues_across_vertices() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
let d = apply(&[Vec2::ZERO, Vec2::new(0.3, 0.0), Vec2::new(0.3, 1.0)], &lt, 1.0, 0.0);
let d = apply(&[Vec2::ZERO, Vec2::new(0.3, 0.0), Vec2::new(0.3, 1.0)], &lt, 1.0, 0.0, &mut Free);
assert_eq!(d[0].len(), 3); // the first dash turns the corner
}
/// The drawn stretches of a run, a continuous one as one stretch, with stretches that touch
/// joined (a plot draws them as one stroke).
fn drawn(len: f64, pattern: &[f64], how: Layout) -> Vec<(f64, f64)> {
let mut out: Vec<(f64, f64)> = Vec::new();
for (a, b) in layout(len, pattern, how, 0.0).unwrap_or_else(|| vec![(0.0, len)]) {
for (a, b) in layout(len, pattern, how, 0.0, &mut Free).unwrap_or_else(|| vec![(0.0, len)]) {
match out.last_mut() {
Some(last) if (last.1 - a).abs() < 1e-9 && b > a && last.1 > last.0 => last.1 = b,
_ => out.push((a, b)),
@@ -380,8 +442,12 @@ mod tests {
let (start, f) = phase(len, &lt, 1.0, 0.0, Layout::Open).unwrap();
assert_eq!(f, 1.0);
// Every whole dash starts a gap (1) after a period (3) starts.
let whole: Vec<f64> =
ranges(len, &lt, 1.0, 0.0, Layout::Open).unwrap().into_iter().filter(|(a, b)| (b - a - 2.0).abs() < 1e-9).map(|(a, _)| a).collect();
let whole: Vec<f64> = ranges(len, &lt, 1.0, 0.0, Layout::Open, &mut Free)
.unwrap()
.into_iter()
.filter(|(a, b)| (b - a - 2.0).abs() < 1e-9)
.map(|(a, _)| a)
.collect();
assert!(!whole.is_empty(), "{len}");
for a in whole {
let k = (a - 1.0 - start) / 3.0;
@@ -414,8 +480,8 @@ mod tests {
#[test]
fn a_run_shorter_than_one_period_is_continuous() {
let lt = Linetype::simple("DASHED", "", &[2.0, -1.0]);
assert_eq!(apply(&[Vec2::ZERO, Vec2::new(2.99, 0.0)], &lt, 1.0, 0.0).len(), 1);
assert_eq!(ranges(2.99, &lt, 1.0, 0.0, Layout::Open), None);
assert_eq!(apply(&[Vec2::ZERO, Vec2::new(2.99, 0.0)], &lt, 1.0, 0.0, &mut Free).len(), 1);
assert_eq!(ranges(2.99, &lt, 1.0, 0.0, Layout::Open, &mut Free), None);
}
/// A long pattern repeated many times is drawn continuous rather than laid out element by
@@ -425,11 +491,89 @@ mod tests {
let pattern: Vec<f64> = (0..100).map(|i| if i % 2 == 0 { 0.001 } else { -0.001 }).collect();
let lt = Linetype::simple("MANY", "", &pattern);
for how in [Layout::Open, Layout::Closed { anchor: 0.0 }] {
assert_eq!(ranges(4000.0, &lt, 1.0, 0.0, how), None, "{how:?}");
assert!(ranges(40.0, &lt, 1.0, 0.0, how).is_some_and(|r| r.len() > 10_000), "{how:?}");
assert_eq!(ranges(4000.0, &lt, 1.0, 0.0, how, &mut Free), None, "{how:?}");
assert!(ranges(40.0, &lt, 1.0, 0.0, how, &mut Free).is_some_and(|r| r.len() > 10_000), "{how:?}");
// Linetype text follows: none on the continuous run.
assert_eq!(phase(4000.0, &lt, 1.0, 0.0, how), None, "{how:?}");
assert!(phase(40.0, &lt, 1.0, 0.0, how).is_some(), "{how:?}");
}
}
/// A budget of `left` elements that counts the runs it is told were refused.
struct Left {
left: usize,
refused: usize,
}
impl Budget for Left {
fn take(&mut self, visits: usize) -> bool {
self.left.checked_sub(visits).map(|left| self.left = left).is_some()
}
fn refused(&mut self) {
self.refused += 1;
}
}
/// A run is charged to the build's budget before it is laid out, and drawn whole and refused
/// when it does not fit. A run past its own limit is refused without being charged; one
/// drawn continuous by rule, or a pattern of gaps only, is neither charged nor refused.
#[test]
fn runs_are_charged_to_the_budget_and_refused_past_it() {
let lt = Linetype::simple("DASHED", "", &[0.5, -0.25]);
// 1,000 periods: 2,000 elements and more.
let pts = [Vec2::ZERO, Vec2::new(750.0, 0.0)];
let mut b = Left { left: 3000, refused: 0 };
assert!(apply(&pts, &lt, 1.0, 0.0, &mut b).len() > 1000);
assert!(b.left <= 1000 && b.refused == 0, "{}", b.left);
assert_eq!(apply(&pts, &lt, 1.0, 0.0, &mut b), vec![pts.to_vec()]);
assert_eq!(apply_as(&pts, &lt, 1.0, 0.0, Layout::Closed { anchor: 0.0 }, &mut b), None);
assert_eq!(b.refused, 2);
let mut b = Left { left: usize::MAX, refused: 0 };
assert_eq!(ranges(1_000_001.0 * 0.75, &lt, 1.0, 0.0, Layout::Open, &mut b), None);
assert_eq!((b.left, b.refused), (usize::MAX, 1));
// Shorter than a period, and past 50,000 periods with a level of detail.
assert_eq!(ranges(0.5, &lt, 1.0, 0.0, Layout::Open, &mut b), None);
assert_eq!(ranges(50_001.0 * 0.75, &lt, 1.0, 1e-9, Layout::Open, &mut b), None);
assert_eq!((b.left, b.refused), (usize::MAX, 1));
// Gaps only draw nothing on every path where a pattern with a dash is drawn continuous:
// shorter than a period, a pattern under `min_pattern` (sub-pixel), past 50,000 periods
// with a level of detail, past the run's own limit; and on a run within them.
let gaps = Linetype::simple("GAPS", "", &[-0.5, -0.25]);
let mut b = Left { left: 0, refused: 0 };
for (len, min) in [(0.5, 0.0), (750.0, 10.0), (50_001.0 * 0.75, 1e-9), (750_000.0, 0.0), (750.0, 0.0)] {
assert_eq!(ranges(len, &gaps, 1.0, min, Layout::Open, &mut b), Some(Vec::new()), "{len} {min}");
assert_eq!(ranges(len, &gaps, 1.0, min, Layout::Closed { anchor: 0.0 }, &mut b), Some(Vec::new()), "{len} {min}");
assert!(apply(&[Vec2::ZERO, Vec2::new(len, 0.0)], &gaps, 1.0, min, &mut b).is_empty(), "{len} {min}");
}
assert!(apply(&[Vec2::ZERO], &gaps, 1.0, 0.0, &mut b).is_empty(), "a run of one point");
assert_eq!(b.refused, 0);
// A pattern with a dash keeps those fallbacks: drawn whole.
for (len, min) in [(0.5, 0.0), (750.0, 10.0), (50_001.0 * 0.75, 1e-9)] {
let pts = [Vec2::ZERO, Vec2::new(len, 0.0)];
assert_eq!(apply(&pts, &lt, 1.0, min, &mut b), vec![pts.to_vec()], "{len} {min}");
}
assert_eq!(apply(&[Vec2::ZERO], &lt, 1.0, 0.0, &mut b), vec![vec![Vec2::ZERO]]);
// So does a pattern of no elements (continuous), which is not a pattern of gaps.
let pts = [Vec2::ZERO, Vec2::new(750.0, 0.0)];
assert_eq!(apply(&pts, &Linetype::continuous(), 1.0, 0.0, &mut b), vec![pts.to_vec()]);
}
/// A closed run is stretched to a whole number of periods, rounded: 192 is 1.5 periods of 128
/// here, laid out as 2, and walked from the period before its anchor to the one after the
/// last (4 periods of 127 dashes). The build is charged at least that.
#[test]
fn a_closed_run_is_charged_for_the_periods_it_walks() {
let mut pattern = vec![1.0; 127];
pattern.push(-1.0);
let lt = Linetype::simple("LONG", "", &pattern);
let mut b = Left { left: usize::MAX, refused: 0 };
assert!(ranges(192.0, &lt, 1.0, 0.0, Layout::Closed { anchor: 0.0 }, &mut b).is_some());
let (charged, walked) = (usize::MAX - b.left, 4 * 127);
assert!(charged >= walked, "charged {charged} for {walked} elements walked");
}
/// A plot or export keeps the dashes of a run more than 50,000 periods long; a display build,
/// with a level of detail, draws it continuous (#1069).
#[test]
@@ -438,14 +582,14 @@ mod tests {
let len = 50_001.0 * 0.75;
// Centred, the first and last dashes are halves: one more dash than periods.
for (how, dashes) in [(Layout::Open, 50_002), (Layout::Closed { anchor: 0.0 }, 50_001)] {
assert_eq!(ranges(len, &lt, 1.0, 0.0, how).map(|r| r.len()), Some(dashes), "{how:?}");
assert_eq!(ranges(len, &lt, 1.0, 1e-9, how), None, "{how:?}");
assert_eq!(ranges(len, &lt, 1.0, 0.0, how, &mut Free).map(|r| r.len()), Some(dashes), "{how:?}");
assert_eq!(ranges(len, &lt, 1.0, 1e-9, how, &mut Free), None, "{how:?}");
// Where linetype texts are placed from.
assert!(phase(len, &lt, 1.0, 0.0, how).is_some(), "{how:?}");
assert_eq!(phase(len, &lt, 1.0, 1e-9, how), None, "{how:?}");
}
let pts = [Vec2::ZERO, Vec2::new(len, 0.0)];
assert_eq!(apply(&pts, &lt, 1.0, 0.0).len(), 50_002);
assert_eq!(apply(&pts, &lt, 1.0, 1e-9).len(), 1);
assert_eq!(apply(&pts, &lt, 1.0, 0.0, &mut Free).len(), 50_002);
assert_eq!(apply(&pts, &lt, 1.0, 1e-9, &mut Free).len(), 1);
}
}
+219
View File
@@ -0,0 +1,219 @@
//! Loops in the block graph, for dimensions inside blocks (#1923).
//!
//! A block leads to the blocks that drawing its contents draws in turn: those of its block
//! references, dimensions and multileaders, also inside proxy graphics. A dimension inside block
//! `C` whose own block leads back to `C` is part of a loop: drawn from its block, it would draw `C`
//! again, and every such dimension again at each level down to `MAX_BLOCK_DEPTH`. With k of them
//! in the loop that is up to k^16 copies, or one per ordering of the distinct blocks on the loop,
//! which only the expansion budget cuts. Such a dimension is drawn from its definition points
//! instead, as one whose block is missing is. The loops are those of the drawing's data: an
//! object on the way that is hidden or on a layer that is off still closes one.
use std::collections::HashMap;
use std::sync::OnceLock;
use cadcraft_doc::{Block, Drawing, Entity, EntityKind};
/// The most blocks, and objects in them, that the search from a dimension's block looks at before
/// the whole block graph is searched instead: room for a dimension's block and the blocks of its
/// arrowheads, which is what such a search usually meets.
const NEARBY_BLOCKS: usize = 16;
const NEARBY_OBJECTS: usize = 256;
/// Whether block `to` leads back to block `from` in `d`: it is `from`, or drawing `to` draws
/// `from` again. A short search from `to` answers for ordinary blocks. Past it, the loops of the
/// whole block graph are found, once per build (`loops`), and answer from then on.
pub(crate) fn leads_back(d: &Drawing, loops: &OnceLock<BlockLoops>, from: &Block, to: &Block) -> bool {
if std::ptr::eq(from, to) {
return true;
}
if let Some(l) = loops.get() {
return l.on_one_loop(from, to);
}
match reaches_nearby(d, to, from) {
Some(found) => found,
None => loops.get_or_init(|| BlockLoops::new(d)).on_one_loop(from, to),
}
}
/// Whether `start` leads to `target`, when looking at no more than [`NEARBY_BLOCKS`] blocks and
/// [`NEARBY_OBJECTS`] objects in them settles it.
fn reaches_nearby(d: &Drawing, start: &Block, target: &Block) -> Option<bool> {
let mut found: Vec<&Block> = vec![start];
let mut objects = NEARBY_OBJECTS;
let mut drawn = Vec::new();
let mut next = 0;
while let Some(b) = found.get(next).copied() {
next += 1;
for e in b.entities.iter() {
if !drawn_blocks(d, e, &mut drawn, &mut objects) {
return None;
}
}
for t in drawn.drain(..) {
if std::ptr::eq(t, target) {
return Some(true);
}
if !found.iter().any(|f| std::ptr::eq(*f, t)) {
if found.len() >= NEARBY_BLOCKS {
return None;
}
found.push(t);
}
}
}
Some(false)
}
/// The blocks that lie on a loop, numbered by their strongly connected component: two blocks
/// lead to each other exactly when they have the same number.
pub(crate) struct BlockLoops {
/// The component of each block that shares one with another block, by the block's address.
component: HashMap<usize, usize>,
}
impl BlockLoops {
fn new(d: &Drawing) -> Self {
let blocks: Vec<&Block> = d.blocks.values().map(|b| &**b).collect();
let index: HashMap<usize, usize> = blocks.iter().enumerate().map(|(i, b)| (address(b), i)).collect();
let edges: Vec<Vec<usize>> = blocks
.iter()
.map(|b| {
let (mut drawn, mut unlimited) = (Vec::new(), usize::MAX);
for e in b.entities.iter() {
drawn_blocks(d, e, &mut drawn, &mut unlimited);
}
drawn.into_iter().filter_map(|t| index.get(&address(t)).copied()).collect()
})
.collect();
let mut component = HashMap::new();
for (n, members) in components(&edges).into_iter().filter(|c| c.len() > 1).enumerate() {
for i in members {
if let Some(b) = blocks.get(i) {
component.insert(address(b), n);
}
}
}
BlockLoops { component }
}
/// Whether blocks `a` and `b` lie on one loop (so each leads to the other).
fn on_one_loop(&self, a: &Block, b: &Block) -> bool {
self.component.get(&address(a)).is_some_and(|c| self.component.get(&address(b)) == Some(c))
}
}
fn address(b: &Block) -> usize {
std::ptr::from_ref(b) as usize
}
/// Push each block that `e` draws itself, as the renderer finds it by name, counting the objects
/// looked at (`e` and its proxy graphics) against `objects`: false when they run out.
fn drawn_blocks<'d>(d: &'d Drawing, e: &Entity, drawn: &mut Vec<&'d Block>, objects: &mut usize) -> bool {
// Proxy graphics wait here (no allocation for other objects).
let mut pending: Vec<&Entity> = Vec::new();
let mut next = Some(e);
while let Some(e) = next.take().or_else(|| pending.pop()) {
let Some(left) = objects.checked_sub(1) else { return false };
*objects = left;
let name = match &e.kind {
EntityKind::Insert(i) => Some(i.block.as_str()),
EntityKind::Dimension(dm) => dm.block.as_deref(),
EntityKind::MLeader(m) => m.block.as_ref().map(|i| i.block.as_str()),
EntityKind::Unknown(u) => {
pending.extend(u.graphics.iter());
None
}
_ => None,
};
if let Some(b) = name.and_then(|n| d.block(n)) {
drawn.push(&**b);
}
}
true
}
/// The strongly connected components of the graph with `edges[i]` leaving node `i` (Tarjan's
/// algorithm, with an explicit stack so a long chain of blocks can't overflow the call stack).
fn components(edges: &[Vec<usize>]) -> Vec<Vec<usize>> {
const UNSEEN: usize = usize::MAX;
let n = edges.len();
let (mut order, mut low, mut on_stack) = (vec![UNSEEN; n], vec![0; n], vec![false; n]);
let (mut next, mut stack, mut out) = (0, Vec::new(), Vec::new());
let mut visit = |v: usize, order: &mut [usize], low: &mut [usize], on_stack: &mut [bool], stack: &mut Vec<usize>| {
if let (Some(o), Some(l), Some(s)) = (order.get_mut(v), low.get_mut(v), on_stack.get_mut(v)) {
(*o, *l, *s) = (next, next, true);
next += 1;
stack.push(v);
}
};
for root in 0..n {
if order.get(root) != Some(&UNSEEN) {
continue;
}
visit(root, &mut order, &mut low, &mut on_stack, &mut stack);
// Nodes being visited, each with the position of its next edge.
let mut path: Vec<(usize, usize)> = vec![(root, 0)];
while let Some((v, at)) = path.last_mut() {
let v = *v;
if let Some(&w) = edges.get(v).and_then(|es| es.get(*at)) {
*at += 1;
match order.get(w).copied() {
Some(UNSEEN) => {
visit(w, &mut order, &mut low, &mut on_stack, &mut stack);
path.push((w, 0));
}
Some(ow) if on_stack.get(w) == Some(&true) => {
if let Some(l) = low.get_mut(v) {
*l = (*l).min(ow);
}
}
_ => {}
}
continue;
}
path.pop();
let low_v = low.get(v).copied().unwrap_or(0);
if let Some(l) = path.last().and_then(|(u, _)| low.get_mut(*u)) {
*l = (*l).min(low_v);
}
if order.get(v) == Some(&low_v) {
let mut members = Vec::new();
while let Some(w) = stack.pop() {
if let Some(s) = on_stack.get_mut(w) {
*s = false;
}
members.push(w);
if w == v {
break;
}
}
out.push(members);
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::components;
fn sorted(mut c: Vec<Vec<usize>>) -> Vec<Vec<usize>> {
c.iter_mut().for_each(|m| m.sort_unstable());
c.sort();
c
}
#[test]
fn components_group_exactly_the_nodes_that_reach_each_other() {
// 0 -> 1 -> 2 -> 0 is a loop; 2 -> 3 -> 4 -> 3 is another, reached from the first; 5
// reaches 0 but nothing reaches 5; 6 holds only a loop to itself.
let edges = vec![vec![1], vec![2], vec![0, 3], vec![4], vec![3], vec![0], vec![6]];
assert_eq!(sorted(components(&edges)), vec![vec![0, 1, 2], vec![3, 4], vec![5], vec![6]]);
// A long chain closing on its start is one component, without deep recursion.
let n = 200_000;
let chain: Vec<Vec<usize>> = (0..n).map(|i| vec![(i + 1) % n]).collect();
assert_eq!(components(&chain).iter().map(Vec::len).collect::<Vec<_>>(), vec![n]);
}
}
+1 -1
View File
@@ -61,7 +61,7 @@ pub(super) fn draw(b: &mut Builder, ctx: &Ctx, e: &Entity, m: &MLine, rgb: Ink,
fn stroke(b: &mut Builder, ctx: &Ctx, rgb: Ink, lw: f32, lt: Option<&cadcraft_doc::Linetype>, scale: f64, min: f64, pts: &[Vec2]) {
match lt.filter(|_| b.opts.linetypes) {
Some(lt) => {
for dash in linetype::apply(pts, lt, scale, min) {
for dash in linetype::apply(pts, lt, scale, min, b) {
match dash.as_slice() {
[p] => b.point(ctx, rgb, *p),
_ => b.polyline(ctx, rgb, lw, &dash),
+22 -8
View File
@@ -4,8 +4,8 @@ use super::display::{DisplayList, Kind, NO_LAYER, PlotText, VIEWPORT_CONTENT};
use super::draw::entity;
use super::viewports::{MAX_VIEWPORTS, viewport};
use super::{
Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Handle, Lineweight, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper, pen, plotstyle,
point,
Bounds2, Builder, Color, Ctx, Drawing, Entity, EntityKind, Handle, Lineweight, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, Mat3, Space, Vec2, paper,
pen, plotstyle, point,
};
/// Build options.
@@ -102,18 +102,21 @@ pub(crate) fn top_ctx<'a>(d: &'a Drawing, xf: Mat3, top: Handle, frozen: &'a [St
lt_factor: 1.0,
block_pstyle: None,
block_transparency: 0,
block: None,
}
}
fn build_space(d: &Drawing, space: &Space, opts: &Options, plotting: bool) -> DisplayList {
build_space_within(d, space, opts, plotting, MAX_DISPLAY_POINTS)
build_space_within(d, space, opts, plotting, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS)
}
/// [`build_space`] holding at most `max_points` points.
pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plotting: bool, max_points: usize) -> DisplayList {
/// [`build_space`] holding at most `max_points` points and laying out at most `max_dashes` dash
/// pattern elements.
pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plotting: bool, max_points: usize, max_dashes: usize) -> DisplayList {
let opts = &with_point_view(d, space, opts);
let styler = style_table(d, space, opts, plotting).map(|t| plotstyle::Styler::new(d, t));
let points = std::sync::atomic::AtomicUsize::new(0);
let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
let loops = std::sync::OnceLock::new();
let mut b = Builder {
list: DisplayList::default(),
opts,
@@ -124,6 +127,9 @@ pub(crate) fn build_space_within(d: &Drawing, space: &Space, opts: &Options, plo
transparency: 0,
points: &points,
max_points,
dashes: &dashes,
max_dashes,
loops: &loops,
};
if let Space::Paper(name) = space {
b.list.sheet = paper::sheet(d, name);
@@ -171,7 +177,8 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor
use rayon::prelude::*;
let ents: Vec<&std::sync::Arc<Entity>> = store.iter().collect();
let budget = std::sync::atomic::AtomicUsize::new(0);
let (opts, plotting, points, max_points) = (b.opts, b.plotting, b.points, b.max_points);
let (opts, plotting, points, max_points, dashes, max_dashes, loops) =
(b.opts, b.plotting, b.points, b.max_points, b.dashes, b.max_dashes, b.loops);
let parts: Vec<DisplayList> = ents
.par_chunks(PARALLEL_CHUNK)
.map(|chunk| {
@@ -185,6 +192,9 @@ fn build_parallel(b: &mut Builder, d: &Drawing, store: &cadcraft_doc::EntityStor
transparency: 0,
points,
max_points,
dashes,
max_dashes,
loops,
};
for e in chunk {
entity(&mut part, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e);
@@ -237,7 +247,8 @@ pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents:
} else {
opts
};
let points = std::sync::atomic::AtomicUsize::new(0);
let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
let loops = std::sync::OnceLock::new();
let mut b = Builder {
list: DisplayList::default(),
opts,
@@ -248,6 +259,9 @@ pub fn build_entities<'a, I: IntoIterator<Item = &'a Entity>>(d: &Drawing, ents:
transparency: 0,
points: &points,
max_points: MAX_DISPLAY_POINTS,
dashes: &dashes,
max_dashes: MAX_DASH_ELEMENTS,
loops: &loops,
};
for e in ents {
entity(&mut b, &top_ctx(d, Mat3::IDENTITY, e.handle, &[], &[]), e);
+135 -2
View File
@@ -1551,7 +1551,7 @@ fn block_copies_stop_at_the_point_budget_and_say_so() {
let d = arrayed_circles();
let full = build(&d, &Space::Model, &Options::default());
assert!(!full.truncated && points(&full) > 100_000, "{}", points(&full));
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000);
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, crate::MAX_DASH_ELEMENTS);
assert!(l.truncated);
assert!(points(&l) > 0 && points(&l) <= 10_000, "{}", points(&l));
assert!(l.prims.iter().all(|p| p.start as usize + p.len as usize <= l.verts.len()));
@@ -1564,7 +1564,140 @@ fn objects_built_on_all_cores_stop_at_the_point_budget_and_say_so() {
for _ in 0..600 {
d.add(&Space::Model, Common::default(), circle()).unwrap();
}
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000);
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, 10_000, crate::MAX_DASH_ELEMENTS);
assert!(l.truncated);
assert!(points(&l) > 0 && points(&l) <= 10_000, "{}", points(&l));
}
// ---------- dash budget (#1069, #1923) ----------
/// A drawing of lines on DASHED (0.5, -0.25), one per entry of `periods` and that many periods
/// long, on rows 1 apart.
fn dashed_lines(periods: &[f64]) -> Drawing {
let mut d = Drawing::new_imperial();
d.linetypes.push(cadcraft_doc::Linetype::simple("DASHED", "", &[0.5, -0.25]));
for (row, n) in periods.iter().enumerate() {
let y = row as f64;
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(n * 0.75, y, 0.0) });
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, line).unwrap();
}
d
}
/// The primitives drawn for each top-level entity, in drawing order.
fn prims_per_entity(l: &DisplayList) -> Vec<usize> {
let mut out: Vec<(Handle, usize)> = Vec::new();
for p in &l.prims {
match out.last_mut() {
Some((h, n)) if *h == p.handle => *n += 1,
_ => out.push((p.handle, 1)),
}
}
out.into_iter().map(|(_, n)| n).collect()
}
/// A run whose pattern repeats past [`MAX_RUN_DASH_ELEMENTS`] is drawn continuous, and the list
/// says so: 1,000,001 DASHED periods are (n + 2) × 2 elements, past two million (#1069). A plot
/// keeps the dashes of 50,001 periods and says nothing.
#[test]
fn a_run_past_its_dash_limit_is_drawn_continuous_and_says_so() {
let l = build_plot(&dashed_lines(&[1_000_001.0]), &Space::Model, &Options::default());
assert_eq!(l.prims.len(), 1);
assert!(l.truncated);
let l = build_plot(&dashed_lines(&[50_001.0]), &Space::Model, &Options::default());
assert!(l.prims.len() > 50_001 && !l.truncated, "{}", l.prims.len());
// The band of a wide polyline as well.
let mut d = dashed_lines(&[]);
let vertices = vec![PolyVertex::new(Vec2::ZERO), PolyVertex::new(Vec2::new(1_000_001.0 * 0.75, 0.0))];
let band = cadcraft_doc::LwPolyline { vertices, closed: false, const_width: 0.1, elevation: 0.0, plinegen: false };
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, EntityKind::LwPolyline(band)).unwrap();
assert!(build_plot(&d, &Space::Model, &Options::default()).truncated);
}
/// Past the build's dash budget the rest of the dashed runs are drawn continuous and counted
/// (#1923): 40 lines of 1,000 periods, 2,004 elements each, against a budget of 40,000.
#[test]
fn dashed_runs_past_the_build_dash_budget_are_drawn_continuous_and_counted() {
let d = dashed_lines(&[1000.0; 40]);
let full = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, MAX_DASH_ELEMENTS);
assert!(!full.truncated && full.undashed == 0);
let each = prims_per_entity(&full);
assert!(each.len() == 40 && each.iter().all(|n| *n > 1000), "{each:?}");
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, 40_000);
let dashed = 40 - l.undashed;
assert!(l.truncated && l.undashed > 0 && dashed > 0, "{}", l.undashed);
assert!(dashed * 2004 <= 40_000, "{dashed} lines dashed");
// The first lines keep their dashes; from the first that does not fit, each is one stroke.
let got = prims_per_entity(&l);
assert_eq!(got[..dashed], each[..dashed]);
assert!(got[dashed..].iter().all(|n| *n == 1), "{got:?}");
}
/// Parts built on all cores spend one dash budget, and their counts add up.
#[test]
fn dashed_runs_built_on_all_cores_share_the_dash_budget() {
// 600 lines of 100 periods (204 elements each): enough for the parallel build.
let d = dashed_lines(&[100.0; 600]);
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), false, MAX_DISPLAY_POINTS, 20_000);
let dashed = 600 - l.undashed;
assert!(l.truncated && l.undashed > 0 && dashed > 0, "{}", l.undashed);
assert!(dashed * 204 <= 20_000, "{dashed} lines dashed");
let each = prims_per_entity(&l);
assert_eq!(each.iter().filter(|n| **n == 1).count(), l.undashed, "{each:?}");
}
/// Model space seen through a layout viewport reports a run it draws continuous on the layout's
/// list too, and spends the layout's dash budget.
#[test]
fn runs_seen_through_a_viewport_are_counted_and_spend_the_layout_dash_budget() {
let mut d = dashed_lines(&[]);
// 3,000,000 periods, past the limit also at the viewport's linetype scale (PSLTSCALE); and
// 1,000 periods, within it.
for (y, len) in [(5.0, 2_250_000.0), (6.0, 750.0)] {
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(len, y, 0.0) });
d.add(&Space::Model, Common { linetype: "DASHED".into(), ..Default::default() }, line).unwrap();
}
let paper = Space::Paper("Layout1".into());
d.add(&paper, Common::default(), EntityKind::Viewport(vp(Vec2::new(5.0, 4.0), 4.0, 4.0, Vec2::new(5.0, 5.0), 8.0, 2))).unwrap();
let l = build_plot(&d, &paper, &Options::default());
assert!(l.prims.iter().any(|p| p.handle == VIEWPORT_CONTENT), "the lines show in the viewport");
assert!(l.truncated && l.undashed == 1, "{}", l.undashed);
let l = crate::pipeline::build_space_within(&d, &paper, &Options::default(), true, MAX_DISPLAY_POINTS, 100);
assert_eq!(l.undashed, 2);
}
/// A block reference cut by an XCLIP boundary is drawn apart and then joined: a run in it drawn
/// continuous is still counted.
#[test]
fn a_run_past_its_dash_limit_in_a_clipped_block_reference_is_counted() {
let mut d = dashed_lines(&[]);
let mut blk = cadcraft_doc::Block::new("B");
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::ZERO, b: Vec3::new(1_000_001.0 * 0.75, 0.0, 0.0) });
blk.entities.push(block_entity(1, Common { linetype: "DASHED".into(), ..Default::default() }, line));
d.blocks.insert("B".into(), std::sync::Arc::new(blk));
let EntityKind::Insert(mut ins) = insert_of("B") else { panic!("an insert") };
ins.clip = Some(cadcraft_doc::ClipBoundary::new(vec![Vec2::new(-1.0, -1.0), Vec2::new(10.0, 1.0)]));
d.add(&Space::Model, Common::default(), EntityKind::Insert(ins)).unwrap();
let l = build_plot(&d, &Space::Model, &Options::default());
assert!(!l.prims.is_empty() && l.truncated && l.undashed == 1, "{}", l.undashed);
}
/// Text in a linetype is placed only on a run whose dashes were laid out: a line past the build's
/// dash budget is one stroke, without its texts.
#[test]
fn linetype_text_is_left_off_a_run_past_the_dash_budget() {
use cadcraft_doc::DashElement;
let mut d = Drawing::new_imperial();
let text = DashElement { text: Some("GAS".into()), style: Some("Standard".into()), scale: 0.1, ..DashElement::dash(-0.2) };
let pattern = vec![DashElement::dash(0.5), text, DashElement::dash(-0.25)];
d.linetypes.push(cadcraft_doc::Linetype { name: "GAS".into(), description: String::new(), pattern });
// Two lines of 100 periods, 306 elements each: the budget fits the first.
for y in [0.0, 1.0] {
let line = EntityKind::Line(cadcraft_doc::Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(95.0, y, 0.0) });
d.add(&Space::Model, Common { linetype: "GAS".into(), ..Default::default() }, line).unwrap();
}
let l = crate::pipeline::build_space_within(&d, &Space::Model, &Options::default(), true, MAX_DISPLAY_POINTS, 400);
let each = prims_per_entity(&l);
assert!(matches!(each.as_slice(), [first, 1] if *first > 101), "{each:?}");
assert_eq!(l.undashed, 1);
}
+15 -4
View File
@@ -6,8 +6,8 @@ use super::draw::entity;
use super::pipeline::PARALLEL_CHUNK;
use super::pipeline::{Options, style_table, top_ctx, with_point_view};
use super::{
Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_EXPANSION, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2, clip, paper, pen,
plotstyle,
Bounds2, Builder, Ctx, Drawing, Entity, EntityKind, Handle, MAX_BLOCK_EXPANSION, MAX_DASH_ELEMENTS, MAX_DISPLAY_POINTS, Mat3, Pen, Space, Vec2,
clip, paper, pen, plotstyle,
};
/// Upper bound on viewports drawn per layout (hostile files).
@@ -70,7 +70,8 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds
}
let opts = &with_point_view(d, space, opts);
let styler = style_table(d, space, opts, false).map(|t| plotstyle::Styler::new(d, t));
let points = std::sync::atomic::AtomicUsize::new(0);
let (points, dashes) = (std::sync::atomic::AtomicUsize::new(0), std::sync::atomic::AtomicUsize::new(0));
let loops = std::sync::OnceLock::new();
let mut b = Builder {
list: DisplayList::default(),
opts,
@@ -81,6 +82,9 @@ pub fn viewport_content(d: &Drawing, space: &Space, handle: Handle, area: Bounds
transparency: 0,
points: &points,
max_points: MAX_DISPLAY_POINTS,
dashes: &dashes,
max_dashes: MAX_DASH_ELEMENTS,
loops: &loops,
};
contents(&mut b, d, vp, area, &Clip::Rect(area), paper::unit_mm_of(d, handle));
b.list
@@ -135,6 +139,9 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
transparency: 0,
points: b.points,
max_points: b.max_points,
dashes: b.dashes,
max_dashes: b.max_dashes,
loops: b.loops,
};
#[cfg(not(target_arch = "wasm32"))]
let parallel = !b.plotting && b.styles.is_none() && d.model.len() >= 2 * PARALLEL_CHUNK;
@@ -146,7 +153,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
// As `build_parallel`: chunks built side by side, joined in drawing order.
use rayon::prelude::*;
let ents: Vec<&std::sync::Arc<Entity>> = d.model.iter().collect();
let (opts, points, max_points) = (b.opts, b.points, b.max_points);
let (opts, points, max_points, dashes, max_dashes, loops) = (b.opts, b.points, b.max_points, b.dashes, b.max_dashes, b.loops);
let parts: Vec<DisplayList> = ents
.par_chunks(PARALLEL_CHUNK)
.map(|chunk| {
@@ -160,6 +167,9 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
transparency: 0,
points,
max_points,
dashes,
max_dashes,
loops,
};
let c = ctx();
for me in chunk.iter().filter(|me| seen(me)) {
@@ -193,6 +203,7 @@ fn contents(b: &mut Builder, d: &Drawing, vp: &cadcraft_doc::Viewport, area: Bou
pen::apply(&mut sub.list, unit_mm);
b.list.expanded = b.list.expanded.saturating_add(sub.list.expanded);
b.list.truncated |= sub.list.truncated;
b.list.undashed = b.list.undashed.saturating_add(sub.list.undashed);
append_clipped(&mut b.list, &sub.list, clip);
}
+12 -3
View File
@@ -78,8 +78,17 @@ pub(crate) fn second_vertex_at(p: &LwPolyline, tol: f64) -> f64 {
/// Triangles for the dashes of a wide polyline drawn with `lt` at `scale`, a line across the band
/// for each dot, and the centre line of each dash. With PLINEGEN the pattern runs along the whole
/// polyline (stretched around a closed one from its second vertex, as a thin one is); otherwise
/// it restarts at every vertex. A pattern shorter than `min_pattern` fills the whole band.
pub fn dashed(p: &LwPolyline, tol: f64, lt: &Linetype, scale: f64, min_pattern: f64) -> (Vec<Vec2>, Vec<Vec<Vec2>>, Vec<Vec<Vec2>>) {
/// it restarts at every vertex. A pattern shorter than `min_pattern` fills the whole band, as does
/// a run past a dash limit (`dash_budget`, see [`linetype::Budget`]); a pattern of gaps only draws
/// nothing.
pub(crate) fn dashed(
p: &LwPolyline,
tol: f64,
lt: &Linetype,
scale: f64,
min_pattern: f64,
dash_budget: &mut impl linetype::Budget,
) -> (Vec<Vec2>, Vec<Vec<Vec2>>, Vec<Vec<Vec2>>) {
let mut budget = MAX_TESSELLATED_POINTS;
let mut runs = segments(p, tol, &mut budget);
let mut how = Layout::Open;
@@ -99,7 +108,7 @@ pub fn dashed(p: &LwPolyline, tol: f64, lt: &Linetype, scale: f64, min_pattern:
let mut centres = Vec::new();
for run in &runs {
let len = run.last().map(|x| x.s).unwrap_or(0.0);
let dashes = linetype::ranges(len, lt, scale, min_pattern, how).unwrap_or_else(|| vec![(0.0, len)]);
let dashes = linetype::ranges(len, lt, scale, min_pattern, how, dash_budget).unwrap_or_else(|| vec![(0.0, len)]);
for (a, b) in dashes {
if b - a <= 1e-12 {
if let Some(x) = at(run, a) {
+48
View File
@@ -0,0 +1,48 @@
//! A small file of many long lines on a pattern of mostly gaps (#1923, F-05 f). Laying a run out
//! visits every element of every period, two million here, but draws one dash in 256 of them, so
//! the point budget (`MAX_DISPLAY_POINTS`) never stops the build: each line used to cost two
//! million steps. The build's dash budget lays a few dozen out and draws the rest continuous.
use cadcraft_doc::{Common, DashElement, Drawing, EntityKind, Handle, Line, Linetype, Space};
use cadcraft_geom::Vec3;
use cadcraft_render::{DisplayList, Options, build_plot};
const LINES: usize = 1000;
/// `LINES` lines 1,999 long on a pattern of 255 gaps and a dash, each 0.001: 7,808 periods of 256
/// elements a line, just under the two million one run may be laid out over.
fn sparse() -> Drawing {
let mut d = Drawing::new_imperial();
let pattern = (0..256).map(|i| DashElement::dash(if i == 255 { 0.001 } else { -0.001 })).collect();
d.linetypes.push(Linetype { name: "SPARSE".into(), description: String::new(), pattern });
for row in 0..LINES {
let y = row as f64;
let line = EntityKind::Line(Line { a: Vec3::new(0.0, y, 0.0), b: Vec3::new(1999.0, y, 0.0) });
d.add(&Space::Model, Common { linetype: "SPARSE".into(), ..Default::default() }, line).unwrap();
}
d
}
/// The primitives drawn for each top-level entity, in drawing order.
fn prims_per_entity(l: &DisplayList) -> Vec<usize> {
let mut out: Vec<(Handle, usize)> = Vec::new();
for p in &l.prims {
match out.last_mut() {
Some((h, n)) if *h == p.handle => *n += 1,
_ => out.push((p.handle, 1)),
}
}
out.into_iter().map(|(_, n)| n).collect()
}
#[test]
fn many_long_runs_of_a_pattern_of_gaps_stop_at_the_dash_budget() {
let l = build_plot(&sparse(), &Space::Model, &Options::default());
let each = prims_per_entity(&l);
let dashed = each.iter().filter(|n| **n > 1).count();
assert_eq!(each.len(), LINES);
// Every line used to be laid out; a few dozen fit the budget and the rest are one stroke.
assert!(dashed > 0 && dashed * 4 < LINES, "{dashed} of {LINES} lines dashed");
assert!(each.iter().skip(dashed).all(|n| *n == 1), "{each:?}");
assert!(l.truncated, "the lines drawn continuous are reported");
}
+1
View File
@@ -1,6 +1,7 @@
mod aci7_display;
mod annotative_orientation;
mod annotative_viewport;
mod dash_budget;
mod dim_angular_centre;
mod dim_post_tolerance;
mod dim_text_fill;
+2 -1
View File
@@ -587,7 +587,8 @@ fn render_view(bounds: &cadcraft_geom::Bounds2, center: Vec2, height: f64, fit:
}
/// The `ui.render` reply, matching the headless backend (`pngBase64`, `width`, `height`), plus
/// `bytes`, `path` and `truncated` (the build left block contents out, see #1070).
/// `bytes`, `path` and `truncated` (the build left contents out, see #1070, or drew dashed runs
/// continuous past a dash limit, #1069).
fn render_reply(png: &[u8], w: u32, h: u32, path: Option<&str>, truncated: bool) -> Value {
let mut v =
json!({"pngBase64": cadcraft_engine::cmd::file::base64_encode(png), "width": w, "height": h, "bytes": png.len(), "truncated": truncated});
+7 -4
View File
@@ -18,7 +18,9 @@ CADCraft runs AutoLISP routines (`.lsp` files). What is here and what is not yet
keep their names.
- **At the command line**, `(expression)` evaluates and shows the value, and `!variable` shows a
variable. Typed at a command's prompt (not a free-text one), an expression's value answers it:
`CIRCLE 0,0 (* 2 r)`.
`CIRCLE 0,0 (* 2 r)`. The prompt waits for that value, so the window doesn't redraw and Esc
doesn't reach the expression until it ends: one that takes more than 20 million steps (its
callbacks included) stops with an error. Run long routines at `Command:` instead.
- **Programmatically** (scripts, the control channel, MCP, the CLI): `lisp {code, inputs?}` and
`appload {path} | {name, text | data}` run to the end and return `{value, output, error?}`.
`appload` also returns `commands`, the `c:` commands the file defined, and a JSON call never
@@ -48,9 +50,10 @@ frame, so the window stays live and Esc stops it too.
## The language
Integers are 32-bit and wrap as AutoLISP's do; any real makes arithmetic real. Variables are
dynamically scoped: a function's arguments and its locals (after `/`) are bound while it runs.
Symbols are case-insensitive. Reals print with six significant digits.
Integers are 32-bit and wrap as AutoLISP's do; any real makes arithmetic real. A whole number
past that range read from text (source, `read`, `atoi`) or JSON, or made by `fix` or `gcd`, is a
real instead. Variables are dynamically scoped: a function's arguments and its locals (after `/`)
are bound while it runs. Symbols are case-insensitive. Reals print with six significant digits.
Nothing a routine does can crash the program: deep recursion is the error "internal stack limit
reached", malformed source is a reader error, and every built-in checks its arguments.
+8 -1
View File
@@ -17,6 +17,12 @@ is `cadcraft-control-<port>.token` in the per-user runtime directory (`$XDG_RUNT
from that file — which requires the desktop user's own filesystem access — and includes it on each
line. The MCP bridge (`cadcraft-cli mcp --connect`) does this automatically.
The server checks the token only once it has read the whole line, so until a request on a
connection has carried the right token, a line may be at most 64 KiB; a longer one gets an error
reply and the connection is closed. To send a longer request (a script, a drawing as base64) on a
new connection, first send a short one with the token, such as `ping`, and wait for its reply.
The MCP bridge does this too.
Errors come back as `{"id": …, "ok": false, "error": "message"}`. An unknown method's error points
to `control.methods`, which lists the methods the server answers.
@@ -25,7 +31,8 @@ bytes that aren't UTF-8) gets one error reply and the server closes the connecti
after it runs. Blank lines are skipped.
The server bounds what a client can hold: 16 connections at once (more get an error line and are
closed), 256 MiB per request line (longer closes the connection), 64 queued requests (more are
closed), 256 MiB per request line (64 KiB until the connection has shown the token; longer closes
the connection), 64 queued requests (more are
answered `{"ok": false, "error": "busy: …", "state": "not-run"}`), and 10 minutes idle or 30 seconds
per blocked reply write before the socket is closed.
+3 -2
View File
@@ -33,11 +33,12 @@ OUTPUT="$DIST/cadcraft-$VERSION-macos-aarch64-nightly.zip"
nightly_compile_gui
APP="$NIGHTLY_WORK/stage/$MAC_NIGHTLY_APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources/docs"
cp "$NIGHTLY_GUI" "$APP/Contents/MacOS/CADCraft"
chmod 755 "$APP/Contents/MacOS/CADCraft"
cp "$ROOT/assets/app-icon/cadcraft-nightly.icns" "$APP/Contents/Resources/cadcraft-nightly.icns"
nightly_copy_notices "$APP/Contents/Resources"
# Launcher admits notices under Resources/docs, not beside the icon.
nightly_copy_notices "$APP/Contents/Resources/docs"
# The private mktemp cwd is the helper authority root: stage the template inside it.
cp "$HERE/Info.plist.in" "$NIGHTLY_WORK/Info.plist.in"
(cd "$NIGHTLY_WORK" && python3 "$HERE/nightly_plist.py" --template Info.plist.in \
+82 -2
View File
@@ -1,8 +1,8 @@
#!/usr/bin/env python3
"""The macOS Nightly signing and verification scripts, run on any POSIX host against generated
fixtures and stand-in Apple tools (codesign, notarytool, stapler, spctl, security, ditto, plutil,
lipo) that log their arguments. This proves the scripts' order, refusals and cleanup; it is not a
real signature, notarization or Mac run."""
lipo) that log their arguments. The unsigned producer also runs with a stub GUI build. These
check the scripts and bundle layout, not native signing, notarization or Mac execution."""
import base64
import importlib.util
import json
@@ -27,6 +27,8 @@ COMMIT = "b" * 40
VERSION = "0.23.1-nightly.20261123.4567.1.g" + COMMIT[:12]
ASSET = f"cadcraft-{VERSION}-macos-aarch64-nightly.zip"
APP = "CADCraft Nightly.app"
APP_NOTICES = ("README.md", "LICENSE-MIT", "LICENSE-APACHE", "NOTICE", "ATTRIBUTION.md")
OPTIONAL_NOTICES = ("LICENSE", "COPYRIGHT")
TEAM = "ABCDE12345"
IDENTITY = "0123456789ABCDEF0123456789ABCDEF01234567"
SECRETS = {
@@ -183,6 +185,50 @@ class Fixture:
z.writestr(info, b"" if path.is_dir() else path.read_bytes())
return self.input
def package(self, font_licences):
"""Drive the real producer from a clean fixture checkout, without Cargo or Apple tools."""
source = HERE.parents[1]
checkout = self.root / "source"
checkout.mkdir()
notices = APP_NOTICES + tuple(name for name in OPTIONAL_NOTICES if (source / name).is_file())
for relative in (*notices, "packaging/env.sh", "packaging/nightly-common.sh", "packaging/nightly_paths.py",
"packaging/macos/nightly.sh", "packaging/macos/nightly-lib.sh",
"packaging/macos/Info.plist.in", "packaging/macos/nightly_plist.py",
"assets/app-icon/cadcraft-nightly.icns"):
target = checkout / relative
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(source / relative, target)
env = self.env(**dict.fromkeys(SECRETS))
def git(*args):
return subprocess.run(["git", "-c", "core.hooksPath=/dev/null", "-c", "commit.gpgsign=false", *args],
cwd=checkout, env=env, check=True, capture_output=True, text=True, timeout=30).stdout
git("init", "-q")
git("add", "--", ".")
git("-c", "user.name=Fixture", "-c", "[email protected]", "commit", "-qm", "Packaging fixture")
commit = git("rev-parse", "HEAD").strip()
version = VERSION[:-12] + commit[:12]
# Generated licence text exercises the copier without depending on a font checkout.
fonts = self.root / "craft-fonts"
for family, data in font_licences.items():
licence = fonts / "fonts" / family / "OFL.txt"
licence.parent.mkdir(parents=True)
licence.write_bytes(data)
# The existing cargo stub fails for every invocation. Only this producer fixture emits a GUI.
(self.bin / "cargo").write_text(
'#!/bin/sh\nset -eu\n'
'gui="$CARGO_TARGET_DIR/aarch64-apple-darwin/release/cadcraft"\n'
'mkdir -p "$(dirname "$gui")"\n'
"printf \"#!/bin/sh\\necho 'CADCraft %s (nightly-v1)'\\n\" \"$CADCRAFT_VERSION\" >\"$gui\"\n",
)
result = self.run(checkout / "packaging/macos/nightly.sh", "--arch", "aarch64", **dict.fromkeys(SECRETS),
DIST=str(self.dist), CARGO_TARGET_DIR=str(self.root / "target"), CRAFT_FONTS_DIR=str(fonts),
CADCRAFT_BUILD_CHANNEL="nightly-v1", CADCRAFT_VERSION=version,
CADCRAFT_BUILD_SHA=commit, CADCRAFT_BUILD_DATE="2026-11-23")
assert result.returncode == 0, result.stdout
return self.dist / ASSET.replace(VERSION, version)
def env(self, **changes):
env = {"PATH": f"{self.bin}:{os.environ['PATH']}", "HOME": str(self.root), "SHIM_LOG": str(self.log),
"SHIM_TEAM": TEAM, "SHIM_IDENTITY": IDENTITY, "RUNNER_TEMP": str(self.temp), **SECRETS}
@@ -410,6 +456,40 @@ class Verify(unittest.TestCase):
class Build(unittest.TestCase):
def test_unsigned_archive_has_launcher_layout_and_keeps_all_notices(self):
f = Fixture(self)
fonts = {"fixture-one": b"generated font notice one", "fixture-two": b"generated font notice two"}
archive = f.package(fonts)
source = HERE.parents[1]
resources = f"{APP}/Contents/Resources"
icon = "cadcraft-nightly.icns"
notice_files = {name: (source / name).read_bytes() for name in APP_NOTICES}
notice_files.update({name: (source / name).read_bytes() for name in OPTIONAL_NOTICES if (source / name).is_file()})
notice_files.update({f"OFL-{family}.txt": data for family, data in fonts.items()})
# Shipped Launcher v0.20.3 accepts these leaves only in Resources/docs, except for the root icon.
expected_files = {f"{resources}/docs/{name}": data for name, data in notice_files.items()}
expected_files[f"{resources}/{icon}"] = (source / "assets/app-icon" / icon).read_bytes()
contents = f"{APP}/Contents"
gui = f"{contents}/MacOS/CADCraft"
with zipfile.ZipFile(archive) as zipped:
entries = zipped.infolist()
names = {entry.filename for entry in entries}
self.assertEqual(len(entries), len({name.casefold() for name in names}), "unique paths, ignoring case")
self.assertEqual({entry.filename for entry in entries if not entry.is_dir()},
set(expected_files) | {gui, f"{contents}/Info.plist", f"{contents}/PkgInfo"})
self.assertTrue({entry.filename for entry in entries if entry.is_dir()} <= {
f"{APP}/", f"{contents}/", f"{contents}/MacOS/", f"{resources}/", f"{resources}/docs/"})
for path, data in expected_files.items():
with self.subTest(path=path):
self.assertEqual(zipped.read(path), data)
mode = zipped.getinfo(path).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode))
self.assertFalse(mode & 0o111)
mode = zipped.getinfo(gui).external_attr >> 16
self.assertTrue(stat.S_ISREG(mode) and mode & stat.S_IXUSR)
result = f.run("nightly-verify.sh", "--input", archive, "--expect", "unsigned", **dict.fromkeys(SECRETS))
self.assertEqual(result.returncode, 0, result.stdout)
def test_compilation_refuses_signing_material_before_building(self):
f = Fixture(self)
for name in ("APPLE_CERTIFICATE", "APPLE_PASSWORD", "MACOS_SIGN_IDENTITY", "WINDOWS_CERTIFICATE", "AZURE_CLIENT_SECRET", "LINUX_SIGNING_KEY"):
+92 -2
View File
@@ -13,6 +13,12 @@ INSTALLED_POLICY = ROOT / ".github/nightly-signing-policy.json"
SIGNER_BRANCH = "nightly-signer"
NIGHTLY_PLATFORMS = ("windows-x86_64", "linux-x86_64", "macos-aarch64")
# The pinned shared registry enables Windows, Linux and macOS for CADCraft.
SIGNER_SECRETS = {
"AZURE_CERT_PROFILE", "AZURE_CLIENT_ID", "AZURE_CLIENT_SECRET", "AZURE_SIGNING_ACCOUNT",
"AZURE_SIGNING_ENDPOINT", "AZURE_TENANT_ID", "LINUX_SIGNING_KEY", "APPLE_CERTIFICATE",
"APPLE_CERTIFICATE_PASSWORD", "APPLE_ID", "APPLE_PASSWORD", "APPLE_TEAM_ID", "KEYCHAIN_PASSWORD",
}
# Each platform's one trust field in policy v3, and the public stable identity it must name.
NIGHTLY_TRUST = {
"windows-x86_64": ("publisher_subject",
@@ -46,6 +52,49 @@ def assert_nightly_serialization(source):
raise ValueError("nightly serialization must use its stable group and no cancellation")
def caller_entries(lines, indent):
"""Split the callers' plain YAML block entries; refuse other forms at checked levels."""
entries = {}
children = None
for line in lines:
if children is not None and line.startswith(" " * (indent + 1)):
children.append(line)
continue
row = re.fullmatch(r" " * indent + r"([A-Za-z0-9_-]+):(?: (.*))?", line)
if row is None or row[1] in entries:
raise ValueError("malformed or duplicate caller mapping entry")
children = []
entries[row[1]] = row[2], children
return entries
def assert_caller_secrets(source, job_name, names):
"""Check the actual caller's root, job and secret blocks without a YAML dependency."""
lines = [line for line in source.splitlines() if line.strip() and not line.lstrip().startswith("#")]
root = caller_entries(lines, 0)
job_marker, job_lines = root.pop("jobs", (None, []))
jobs = caller_entries(job_lines, 2)
if job_marker is not None or set(jobs) != {job_name} or jobs[job_name][0] is not None:
raise ValueError("the caller must have one plain job block")
job = caller_entries(jobs[job_name][1], 4)
if "environment" in job or "environment" in root or "secrets" in root:
raise ValueError("only the native callee may bind the environment")
if names:
if "secrets" not in job:
raise ValueError("signer requires an explicit target-specific secret map")
mode, secret_lines = job.pop("secrets")
expected = {name: ("${{ secrets." + name + " }}", []) for name in names}
if mode is not None or caller_entries(secret_lines, 6) != expected:
raise ValueError("signer must forward exactly the reviewed same-name secret references")
elif "secrets" in job:
raise ValueError("unsigned caller must not pass secrets")
for value, children in (*root.values(), *job.values()):
outside_map = "\n".join([value or "", *children])
# Scan all remaining text: quoted braces can appear before a secret reference.
if re.search(r"(?im)^\s*environment:|\bsecrets\b", outside_map):
raise ValueError("secret bindings belong only in the signer map")
def job_conditions(jobs):
"""Each job-level `if:` as (block indicator or None, the whole expression YAML would read)."""
lines = jobs.splitlines()
@@ -182,8 +231,49 @@ class TrustedSourcePreparation(unittest.TestCase):
with self.subTest(workflow=name):
self.assertNotRegex(executable, r"(?im)^\s*(?:-\s*)?uses:\s*[^\n]*cache")
self.assertNotRegex(executable, r"(?im)^\s*[^\s:#]*cache[^\s:#]*:")
self.assertNotRegex(executable, r"(?im)^\s*(?:environment|secrets):")
self.assertNotIn("secrets.", executable)
def test_signer_forwards_exactly_the_reviewed_secret_names(self):
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
assert_caller_secrets(signer, "release", SIGNER_SECRETS)
def test_signer_refuses_missing_extra_alias_duplicate_or_inherited_secrets(self):
signer = (ROOT / ".github/workflows/nightly-sign.yml").read_text()
header = " secrets:\n"
linux = " LINUX_SIGNING_KEY: ${{ secrets.LINUX_SIGNING_KEY }}\n"
self.assertIn(linux, signer)
mutations = {
"missing name": signer.replace(linux, ""),
"extra name": signer + " EXTRA: ${{ secrets.EXTRA }}\n",
"renamed source": signer.replace(linux, linux.replace("secrets.LINUX_SIGNING_KEY", "secrets.APPLE_ID")),
"duplicate name": signer.replace(linux, linux + linux),
"duplicate map": signer + header + linux,
"quoted duplicate map": signer + ' "secrets": inherit\n',
"inherit": signer.split(header)[0] + " secrets: inherit\n",
"yaml alias": signer.replace(linux, " LINUX_SIGNING_KEY: *other\n"),
"yaml merge": signer + " <<: *other\n",
"environment": signer + " environment: release\n",
"secret outside map": signer.replace("${{ inputs.producer_run_id }}", "${{ secrets.APPLE_ID }}"),
}
for change, source in mutations.items():
with self.subTest(change=change), self.assertRaises(ValueError):
assert_caller_secrets(source, "release", SIGNER_SECRETS)
def test_unsigned_caller_has_no_secrets(self):
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
assert_caller_secrets(producer, "unsigned", set())
for suffix in (" secrets: {}\n", " secrets: inherit\n",
" secrets:\n EXTRA: ${{ secrets.EXTRA }}\n",
" extra: ${{ secrets['EXTRA'] }}\n", " secrets: inherit\n"):
with self.subTest(suffix=suffix), self.assertRaises(ValueError):
assert_caller_secrets(producer + suffix, "unsigned", set())
def test_unsigned_caller_refuses_secret_after_format_brace(self):
producer = (ROOT / ".github/workflows/nightly.yml").read_text()
# This inert fixture is never dispatched; the brace is part of the format string.
env = "env:\n EXAMPLE: ${{ format('value {0}', secrets.EXAMPLE_ONLY) }}\n\n"
source = producer.replace("jobs:\n", env + "jobs:\n", 1)
with self.assertRaisesRegex(ValueError, "secret bindings belong only in the signer map"):
assert_caller_secrets(source, "unsigned", set())
class NightlyTrustAnchors(unittest.TestCase):