Compare commits

..
Author SHA1 Message Date
FredApps 2d08ea7b74 Cover both render setting class versions through SAVEAS and QSAVE 2026-12-04 06:07:12 +01:00
FredApps 9d85a971f4 Treat implicit and explicit ByBlock dimension linetypes alike 2026-12-04 05:35:56 +01:00
FredApps 40d4098375 Preserve native viewport lighting across DXF and DWG exports 2026-12-04 05:11:51 +01:00
FredApps a24fb6f930 Use the shared winit fork for Wayland window activation 2026-12-04 04:52:40 +01:00
FredApps 586f3d38b5 Pin CADCraft to the merged DWG bridge and matching fork graph 2026-12-04 04:45:07 +01:00
FredApps d327547208 Preserve repeated viewport lighting tags and limit the DWG test to supported targets 2026-12-04 04:34:12 +01:00
FredApps 246aaf35de Canonicalize default viewport lighting as a unit 2026-12-04 04:25:12 +01:00
FredApps c15cec8a98 Keep exact circle angles and avoid division on narrow ellipses 2026-12-04 04:21:02 +01:00
FredApps 5586822f8a Read hatch ellipse angles as circular rays 2026-12-04 04:20:10 +01:00
FredApps f48ae711e1 Use saved OLE frame headers in roundtrip fixtures 2026-12-04 04:18:08 +01:00
FredApps f78ca4e722 Omit default DWG viewport style and icon settings 2026-12-04 04:18:08 +01:00
FredApps 52ab5d2549 Check round-tripped proxy classes and interpolated spline geometry 2026-12-04 04:18:08 +01:00
FredApps 3b95d0510c Preserve table title suppression and render settings across file versions 2026-12-04 04:18:08 +01:00
FredApps 07bec9df31 Read DWG hatch angles once with the 0.6.9 decoder 2026-12-04 04:18:08 +01:00
FredApps e785adb63d Merge remote-tracking branch 'origin/main' into review/cadcraft-repin-3645-20261204 2026-12-04 04:14:30 +01:00
FredApps c870f83900 fix(engine): use placed annotative text in selection (#3808) 2026-12-04 10:02:38 +07:00
FredApps 0be750a98a Reconcile the shared dependency repin with current CADCraft main 2026-12-04 03:58:29 +01:00
aiongg 20ad85efc4 Merge pull request #3772 from davidmann4/feat/macos-cli-in-app
packaging(macos): ship cadcraft-cli inside CADCraft.app
2026-12-03 18:53:10 -05:00
aiongg d9f7de77e0 Merge pull request #3770 from davidmann4/feat/agents-open-window
feat(automation): agents in the open window through the ArtCraft Launcher's switch
2026-12-03 18:52:55 -05:00
Dimitrios Vidalis 6681531546 refactor(render,io): move the dimension block generator from the DXF writer to render (#2421) (#3777)
`dim_block_entities` makes the contents of a dimension's anonymous `*D`
block from the dimension's drawn geometry. It lived in the DXF writer
(`crates/io/src/dxf_write/blocks.rs`) and only the writer could call it.
It moves to `crates/render/src/dim_block.rs`, beside the geometry it reads,
and is exported as `cadcraft_render::dim_block_entities`. The writer calls
it there.

The body is unchanged: the three `cadcraft_render::` paths in it lose their
prefix and `pub(super)` becomes `pub`. No behaviour changes.
2026-12-03 15:36:36 +01:00
97fed2970c Annotative objects keep a position per scale; ANNORESET synchronizes them (stacked on #1370) (#1373)
* DXF: a block record keeps its annotative flag and uniform scaling

A BLOCK_RECORD's AcadAnnotative xdata (references to the block are
annotative) was dropped on reading, AcadAnnotative being among the
applications CADCraft writes itself, and never written: a saved drawing's
annotative blocks came back plain, and AutoCAD then scaled their references
by units instead of the annotation scale (a metre block showed Unit factor
1000 and Scale 0.005). Group 281 (scale uniformly) was dropped too. Both are
now read into the block (`Block::annotative`, `Block::scale_uniformly`) and
written back.

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

* DXF: a block reference keeps its annotation scale contexts, following the reference

A reference to an annotative block holds its scale at each annotation scale in
its extension dictionary (AcDbContextDataManager, ACDB_ANNOTATIONSCALES).
CADCraft dropped it with the other annotation contexts it means to write from
its model, but it models none for references: with the block's annotative
flag kept, AutoCAD then scaled the reference once more by the current
annotation scale (5 became 25). A reference's contexts are now kept, and
refreshed on writing: each moves, turns and scales by what the reference did
since the file was read (its default context was the reference then), so a
reference left alone keeps them as read. The scales they name are found by
name (SCALE group 300), as the scale list is written again from the model.

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

* Block literals in tests take scale_uniformly; a test helper's lifetime is elided

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

* DXF: a block reference's attributes keep their annotation scale contexts

The attributes of an annotative reference hold their own contexts (insertion
and alignment points and rotation at each annotation scale, under the ATTRIB's
extension dictionary), dropped like the reference's were. CADCraft writes
attributes with new handles, so their extension dictionaries are now kept by
attribute, as its reference's handle and tag, and put back on the attribute
written with that reference and tag. On writing each context keeps its own
place in the block at its scale, moves by what the attribute did in the block
since (its default context then, the attribute now), and is placed by the
reference's context for that scale as it is now: a reference left alone keeps
them as read; one moved, turned or scaled carries them exactly.

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

* DWG: block reference annotation contexts keep their rotation, insertion and scales

AutoCAD's DXF has a block reference context's rotation (50, degrees),
insertion point and scales straight after its scale (340). acadrust 0.6.4
reads them after an AcDbBlkRefObjectContextData marker, with the rotation in
radians, and without the marker read zeros: a drawing saved as DWG had every
annotative reference at scale 0 at its other annotation scales, where
AutoCAD then drew nothing. The DWG bridge now gives acadrust the contexts its
way (marker, radians) and turns its DXF back into AutoCAD's (no marker,
degrees).

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

* DXF: kept reference contexts follow the drawing's and the reference's scales

A kept block reference or attribute context whose SCALE is no longer in the
drawing's list is not written (its dictionary entry goes with it), so no
context points at a null scale. A reference CADCraft's model keeps annotative
has a context for exactly the scales it supports: contexts of scales it
dropped go, and one per new scale is made from the default context, scaled
by the ratio of the scales about the reference's insertion point. One
context stays the default.

Attributes are identified by reference, tag and their place among the
reference's attributes with that tag, so two attributes with one tag keep
their own extension dictionaries and contexts.

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

* DXF: new reference contexts come from one whose scale is still written

When the default context's scale had been deleted from the drawing's list,
a reference CADCraft keeps annotative got no new contexts for its added
scales; the template is now its default context, else its first, among
those whose SCALE is written.

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

* DXF: kept reference contexts follow the reference as read; one default rule

A kept context is brought up to date by what its block reference did since
the file was read. That baseline was the default context, which needn't be
where the reference was (an unchanged save then moved every context); the
reference and its attributes as read are now kept (`Foreign::placements`)
and used, the default context only for data without them.

A context's own offset from the reference now scales and mirrors with it
(back into the reference's frame then, scaled, turned to its frame now), not
only turns.

The default context is the one whose first 290 group is 1 everywhere (an
attribute context has a later 290 of its own).

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

* DXF: new reference contexts take handles above every handle in use

Upstream now believes handles above 2^48 (AutoCAD writes them), so new
annotation contexts can no longer take stand-in handles from 2^48 up: they
start above the written handles, $HANDSEED, the kept objects and their targets.

Test: a drawing whose reference sits at 2^48 + 1 gains a scale and every
written handle stays unique (red with the old 2^48 base).

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

* DXF: an attribute as read is found by its tag and place, and keeps its rotation

A kept attribute placement was looked up by its index among the reference's
attributes now, which differs once they are reordered or replaced (ATTSYNC).
It is now found by tag and place among that tag, like the attribute's contexts.
The rotation change is measured from the attribute as read too, not from its
default context, so an unchanged save no longer turns every context when the
ATTRIB (at the current scale) and the default context differ.

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

* DXF: the kept-context code in read and finish moves into helpers

main now denies cognitive_complexity over 30 and too_many_arguments over 7.
This PR's additions took read to 32 and finish to 31, and retained_objects
to 8 arguments: the block-reference and attribute bookkeeping now lives in
insert_handles, of_insert, keep_attrib_dictionaries, keep_placements,
written_attribs and refreshed_contexts, and retained_objects takes the root
and its entries as one pair.

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

* DXF/DWG: annotative text, MText and dimensions keep their annotation scales on save

AutoCAD keeps an annotative object's size at each annotation scale it
supports in scale contexts (extension dictionary AcDbContextDataManager,
ACDB_ANNOTATIONSCALES, one *OBJECTCONTEXTDATA_CLASS per scale), with the
object's own groups at its default scale. CADCraft dropped AutoCAD's contexts
on read, so those objects opened as plain text at the default scale's size
and lost their scales on save; its own annotative objects went out with only
CADCraft's private record, so AutoCAD showed them at one size at every scale.

Text, MText and dimensions in model space and layouts are now written at
their default scale (the current one when supported) with AcadAnnotative
xdata and a context per scale: text insertion and alignment points, MText
width and columns, a dimension's text position and a *D block with its
geometry at that scale (sharing the DIMASSOC's extension dictionary when
there is one). Scales missing from the list are added. Reading takes the
scales from the contexts and the sizes back to paper size. Files before the
2007 format keep CADCraft's record as before. The DWG bridge gives acadrust
text contexts its way (marker, radians) and dimension contexts' blocks as
BLOCK_RECORD handles, and turns them back.

Checked in AutoCAD: it opens the output, keeps both contexts of each
object, and draws the dimension at 0.18 / 9.0 text height at 1:1 / 1:50.

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

* DXF test: a justified text's start point is recomputed on save (since #1062)

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

* DXF: only annotative dimensions get a *D block per scale

Annotative text and MText went through the dimension block planning too and
left one empty anonymous *D block per scale in every saved file. The hostile
contexts test now saves, opens the file again and checks the scales and that
every context names a written SCALE.

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

* DXF/DWG: annotative multileaders keep their annotation scales on save

An annotative multileader's scale context (ACDB_MLEADEROBJECTCONTEXTDATA_CLASS)
holds the multileader's whole CONTEXT_DATA body at that scale: overall scale
(40), text height, arrowhead size, landing gap, content position and the
leaders. CADCraft dropped AutoCAD's on read and wrote none, so annotative
multileaders came back plain at the default scale's size, and AutoCAD showed
CADCraft's at one size at every scale.

Multileaders now go through the annotation scale contexts like text, MText
and dimensions: written at the default scale with AcadAnnotative xdata and a
context per scale (the entity writer's CONTEXT_DATA at that scale, with its
overall scale and landing gap set), read back at paper size. The DWG bridge
gives acadrust the CONTEXT_DATA{ group it reads the context after, and takes
acadrust's braces and marker out again.

Checked in AutoCAD: its own annotative multileader reads back at 1:2 and
1:10 at paper size, and the saved file reopens with text 0.18 / 0.9 as
before; one made in CADCraft opens with text 2.5 / 25 at 1:1 / 1:10, the text
moved with the scale.

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

* DXF: the current annotation scale is AutoCAD's CANNOSCALE variable

AutoCAD keeps the current annotation scale in the named object dictionary's
AcDbVariableDictionary, as a DICTIONARYVAR CANNOSCALE naming the scale.
CADCraft read only its own record, so AutoCAD's drawings opened at 1:1
whatever their scale (annotative objects then showed at their first scale),
and the variable was written back as read, so AutoCAD reopened a drawing at
its old scale after CADCraft changed it.

The variable is read when the scale is in the list (after CADCraft's record:
AutoCAD keeps that record as it was, so the variable is the newer one), and
the kept variable is written with the drawing's current scale. Annotative
objects are written at that scale.

Checked in CADCraft and AutoCAD: an AutoCAD drawing at 1:2 opens at 1:2;
switched to 1:10 and saved as DXF and DWG, AutoCAD opens both at 1:10.

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

* DXF test: an annotative multileader has no *D block

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

* DXF: AutoCAD's CANNOSCALE names the scale the contexts are written at

A CANNOSCALE naming none of the drawing's scales wrote that name to the
variable dictionary while the default contexts were written at 1:1; the
variable now names the resolved scale too.

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

* DWG: a multileader context's body closes (301 }) before the next record

As acadrust writes it; its reader stops at the next record either way.

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

* Annotative objects keep a position per scale; ANNORESET synchronizes them

An annotative object that supports several scales can now sit somewhere
else at one of them, as in AutoCAD: its position grip moves it at the
current annotation scale only, MOVE/ROTATE/SCALE/MIRROR/paste/CHSPACE move
every scale, and ANNORESET puts every scale back where the current one is
(it was a no-op). The offset is kept per scale name (Common::anno_moves)
and applied where an object is drawn at a scale (anno_placed), so drawing,
extents, explode and grips all see it. Grips now show where the object is
drawn at the current scale; a shape grip's edit is taken back to paper size.

What moves per kind: text, MText and block references as a whole; a
multileader's landing and content (arrowheads stay); a dimension's text.

DXF/DWG: each scale context is written at the object's position at that
scale, and a context placing the object elsewhere reads back as its offset.

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

* DXF: an annotative multileader has annotation scale enabled (293)

The MULTILEADER entity's 293 after its CONTEXT_DATA block is the DXF
reference's "Enable Annotation Scale". CADCraft wrote 0, so AutoCAD kept
the multileader's per-scale contexts (and showed each scale's position)
but its ANNORESET passed the multileader over. With 293 = 1, as AutoCAD
writes for its own annotative multileaders, ANNORESET at either scale
moves the other context to the current scale's position.

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

* Annotative grips and ANNORESET in a viewport use the viewport's scale

In MSPACE the renderer draws model space at the active viewport's scale,
while grips, grip stretches, the hot-grip preview, grip dimensions and
ANNORESET looked up the object at CANNOSCALE: with the two different, grips
sat on another scale's representation and a position grip moved the wrong
scale. They now take the viewport's scale (`DocState::anno_view`,
`Drawing::anno_draw_in`); CANNOSCALE still applies in model space and on
paper outside a viewport.

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

* Annotative scales: import Vec2 after upstream's explicit-import cleanup

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

* Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)

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

* Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)

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

* Docs: leave the parity docs to the maintainers (AGENTS.md: PRs don't edit them)

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

* Annotative text contexts test: Dimension gains insertion_point on main

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

* io: dxf_anno uses craft_dxf, as main's DXF crate now is

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

* io: dxf_anno uses craft_dxf, as main's DXF crate now is

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

* io: dxf_anno uses craft_dxf, as main's DXF crate now is

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

* Tests: the DWG annotation scale round trip waits for craft-libs#2005

Without the bridge's annotation context conversion, a text context read back
from a DWG has its fields from the wrong groups (at the origin), which per-scale
positions read as a move. Ignored until the pinned craft-dwg has the conversion.

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

* fmt: dxf_anno's craft_dxf import in order

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

* fmt: dxf_anno's craft_dxf import in order

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

* fmt: dxf_anno's craft_dxf import in order

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

* io: dxf_anno reads main's borrowed DXF sections (SectionRef)

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

* Annotative positions: main's text editor box and extents take the placed object (AnnoDraw::Scaled carries its offset)

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

* DXF writer: annotation scale planning in two helpers (main's tags_kept_for passed the complexity limit)

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

* Select: a blank MText frame is where its annotation scale places it (main's AnnoDraw use, with the offset)

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

* DXF: a block reference moved in elevation takes its contexts along, at their own heights

block_contexts compared the reference with the one read in X and Y only, so a
reference moved only in Z kept its contexts at their old heights; and any
other change set every context's group 30 to the reference's Z, losing a
context's own height. Z is part of the change check now, and each context
keeps its offset from the reference as read, scaled with the reference's Z
scale as X and Y follow theirs.

FredApps on #1244.

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

* Tests: the annotative block context tests join the io test binary (AGENTS.md rule 30)

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

* Tests: the annotative text context tests join the io test binary (AGENTS.md rule 30)

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

* Tests: the annotative position tests join the engine's test binary (AGENTS.md rule 30)

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

* DWG: block reference contexts and the block's annotative flag stay DXF-only until the bridge converts them

The DWG bridge doesn't carry annotation scale contexts into a DWG yet
(storytold/craft-libs#2005): the DWG reader read them back as zeros, a
reference at scale 0 at its other scales. A save through the bridge now
leaves the kept block reference and attribute contexts out, as before they
were kept, and the block's AcadAnnotative flag too (without its references'
contexts AutoCAD would scale them by the annotation scale once more). DXF
keeps both.

The DWG round-trip test that waited for craft-libs#2005 (ignored,
a_reference_s_contexts_survive_dwg) is replaced by one that runs: a DWG save
leaves the contexts out and the reference reads back at its own scale. The
round trip of the contexts through DWG follows once the bridge converts
them.

FredApps on #1362 (rule 31).

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

* DWG: annotative text, MText and dimensions keep their scales in CADCraft's record until the bridge converts contexts

A save through the DWG bridge writes no annotation scale contexts now: the
bridge doesn't convert them yet (storytold/craft-libs#2005), so CADCraft's own
record carries the scales, as for an older format. DXF from 2007 on writes the
contexts as before.

The DWG test that waited for craft-libs#2005 (ignored) now runs: the scales,
paper height and rotation come back through DWG from the record, and the DWG
holds no contexts. The contexts' own round trip through DWG follows with the
bridge.

FredApps on #1362 (rule 31).

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

* Tests: the multileader's DWG round trip runs, through CADCraft's record

The multileader DWG test that waited for craft-libs#2005 (ignored) now runs:
its scales and paper text height come back through DWG from CADCraft's own
record, and the DWG holds no multileader contexts. The contexts' round trip
through DWG follows with the bridge.

FredApps on #1362 (rule 31).

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

* DWG: per-scale positions travel in CADCraft's record; main's annotation_scales round trip runs again

A DWG save writes no annotation scale contexts while the bridge can't convert
them (storytold/craft-libs#2005), so an object moved at one scale alone would
lose that move through DWG. CADCraft's annotative record now carries each
object's moves next to its scales (only for scales it keeps, finite, at most
MAX_SCALES), as it does for formats before 2007.

The roundtrip/dwg annotation_scales test this PR had marked ignored (main's
own test) runs again, unchanged, and passes; the multileader moved-at-one-scale
DWG test runs too, through the record.

FredApps on #1362 (rule 31).

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

* DXF writer: the DWG bridge's context choice in contexts_for (finish passed the complexity limit)

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

* Keep annotative I/O fixture at normal text orientation

---------

Co-authored-by: Cody Vogt <18035288+codyvogt@users.noreply.github.com>
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Co-authored-by: FredApps <FredApps@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-03 15:30:30 +01:00
44fa197bcc Linux: native Wayland by default, with in-app window buttons on GNOME (#1853)
* Linux: native Wayland by default; CADCRAFT_X11=1 for XWayland

On a Wayland desktop CADCraft forced winit's X11 backend (XWayland)
whenever DISPLAY was set. The deb and rpm only recommend the X11
libraries, and without libxkbcommon-x11 winit panicked at startup:
"Library libxkbcommon-x11.so could not be loaded".

Run natively on Wayland instead: sharp at fractional scales, with
working input methods. File drops from the file manager work there too,
through storytold/winit's W15 patch. CADCRAFT_X11=1 opts into XWayland
as a fallback, and only when the X11 libraries load; otherwise it logs
what is missing and stays on Wayland. It is read with the other
variables in env.rs and replaces CADCRAFT_WAYLAND.
The deb and rpm recommend libxkbcommon-x11 (and rpm libX11-xcb) too.

Ported from WordCraft (storytold/wordcraft#3359).

* GNOME Wayland: draw the window buttons and resize edges in the app

GNOME's compositor offers no zxdg_decoration_manager_v1, so with native
Wayland it draws no frame for CADCraft. Where the protocol is missing,
the window opens without winit's frame and the app draws a title row as
GNOME's header bar: the drawing's name centred, and minimize, maximize
and close in the order GNOME's button-layout names (read once through
the XDG Desktop Portal). Thin zones along the window's edges resize it.
KDE, Sway, Hyprland, COSMIC and X11 keep the desktop's frame.

Options > Display > Use system title bar (OPTIONS key systemTitleBar)
brings back winit's frame at once. It is kept in workspace.json, which
is now read before the window opens. CADCRAFT_TITLEBAR=app or =system
overrides the detection. The new strings are translated in all 15
catalogs.

Ported from WordCraft (storytold/wordcraft#3361).

* Linux: decide the window frame from the backend winit runs on

On an X11-only session winit picks X11 without CADCRAFT_X11, so x11
stayed false and CADCRAFT_TITLEBAR=app drew the app's window buttons on
X11, whose window manager draws the frame. runs_on_x11 follows winit's
own choice (WAYLAND_DISPLAY or WAYLAND_SOCKET set and not empty).

* Linux: leave WAYLAND_SOCKET to winit; empty DISPLAY; TITLEBAR=app wins

Three CodeRabbit findings on #1853:

- The decorations probe connected with Connection::connect_to_env, which,
  given WAYLAND_SOCKET, takes that descriptor, removes the variable and
  closes it when the probe's connection drops, so winit had no Wayland
  connection left. The probe now connects only to WAYLAND_DISPLAY's
  socket (display_socket, found as wayland-client finds it); with only
  WAYLAND_SOCKET it doesn't probe and the desktop keeps the frame.
- An empty DISPLAY counted as an X display, so CADCRAFT_X11=1 forced X11
  with nothing to connect to. DISPLAY is now read as winit reads the
  Wayland variables: set and not empty.
- CADCRAFT_TITLEBAR=app chose the app's buttons, but a saved Use system
  title bar still kept winit's frame, at startup and in
  CadApp::draws_window_frame. Both now decide with app_draws_frame, which
  the override wins (CadApp::frame_forced), and Options doesn't offer the
  setting while it's overridden.

Tests: display_socket and forces_app (decorations), an empty DISPLAY
(main), and titlebar_app_overrides_the_saved_system_title_bar.

* i18n: window button and title bar rows for bs, ka, pl and vi

These catalogs arrived on main after this branch added "Minimize",
"Maximize", "Use system title bar" and its tooltip to the others, so
every catalog now has all four rows.

* Drop the parity-doc edits; the rows go in the PR description

AGENTS.md: PRs don't edit ROADMAP.md or docs/ui-parity.md.

---------

Co-authored-by: bmh129 <11478682+bmh129@users.noreply.github.com>
Co-authored-by: FredApps <153173854+FredApps@users.noreply.github.com>
2026-12-03 15:07:20 +01:00
FredApps 36e8c31f0d Merge pull request #3781 from storytold/fix/metal-language-version-1631
macOS: compile shaders with the newest Metal version the system compiler accepts (#1631)
2026-12-03 07:35:05 +01:00
FredApps 17fb7a3c43 Read Cargo.lock with CRLF line endings too in the wgpu-hal patch test (#1631) 2026-12-03 13:03:35 +07:00
FredApps 5ab5e6f343 Merge pull request #3768 from storytold/stack/e6
Land 4 reviewed PRs (stack e6)
2026-12-03 06:45:42 +01:00
FredApps 5a7182240e Merge remote-tracking branch 'origin/main' into fix/metal-language-version-1631
# Conflicts:
#	crates/ui-egui/src/gpu.rs
2026-12-03 12:33:50 +07:00
FredApps e7d05e1b42 sonar: leave the vendored wgpu-hal out of the analysis (#1631) 2026-12-03 05:42:47 +01:00
FredApps d55ac7ba7a wgpu-hal patch: log Metal versions as major.minor (#1631) 2026-12-03 05:16:38 +01:00
FredApps 0623c42d10 macOS: compile shaders with the newest Metal version the system compiler accepts (#1631) 2026-12-03 05:15:12 +01:00
FredApps 738230f7ea vendor: wgpu-hal 30.0.1 unchanged, as published on crates.io (#1631) 2026-12-03 05:15:12 +01:00
David MannandClaude Opus 5.5 db4f07655b fix(agents): the frame that starts the agent server schedules its first check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 03:13:26 +01:00
David MannandClaude Opus 5.5 5c2a897abc fix(agents): a serving window schedules its next connection check
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 02:50:23 +01:00
David MannandClaude Opus 5.5 b760962907 fix(agents): survive a start race; a tab an agent used saves nothing
- A serving window publishes its connection again when the one the file
  names has closed (two windows that started together both serve).
- The AI Agents tab shown with agent folders in force refuses every save
  until the person shows it afresh, so a later unconfined pass (focus
  loss) can't commit what an agent typed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 02:22:10 +01:00
David MannandClaude Opus 5.5 489df47647 test(agents): the same-frame LISP test must see the request run; --control stays unconfined
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 02:03:43 +01:00
David MannandClaude Opus 5.5 23354c91f5 fix(agents): confine an agent's LISP slices from the same frame on; clearer refusal
- lisp_tick runs under the stored agent roots, so the slice right after
  the request that started the routine (same logic call) is held too.
- The AI Agents tab says saving waits until the agent's work has finished.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 01:52:46 +01:00
David MannandClaude Opus 5.5 901e5fb6fd fix(agents): review findings on the agent link
- mcp --when-closed: a typed parse error (ast-grep string-error).
- mcp honours --config-dir when it looks for the window.
- A second window with the same settings folder leaves the first one's
  connection alone and takes over once that window has closed.
- An agent's LISP routine that runs past its first slice stays held to the
  agent folders until it ends.
- The AI Agents settings refuse changes while agent folders are in force,
  so an agent can't widen them by clicking in Options.
- Docs: a usable write folder still allows reads; the test dir is reset.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 01:37:37 +01:00
David MannandClaude Opus 5.5 16b3732b63 fix(agents): keep the agent folders in force for input an agent queued
ui.click, ui.key and ui.text are handled frames after the request, outside
its confinement; keep the agent's roots in force over logic and UI passes
until that input has gone through a UI pass.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:36:15 +01:00
David MannandClaude Opus 5.5 272dc5cecf feat(automation): agents in the open window through the ArtCraft Launcher's switch
While ArtCraft Launcher > Settings > AI agents names CADCraft, the open
window serves its control channel for agents (craft_automation's
AgentLink: token file, agent-connection.json, the switch, retries), and
plain `cadcraft-cli mcp` reaches it through the shared live client
(craft_control::agents::Live) with the challenge handshake; otherwise it
works headless as before.

- Agent requests in the window run inside the agent folders of the new
  Options > AI Agents tab (the shared Agents page), like headless roots;
  ui.render and ui.screenshot paths are checked too.
- The agent settings are saved in agent-settings.json for the CLI; no
  command changes them.
- `mcp --headless`, `--when-closed`; `--connect` deprecated for a release.
- New `agent_folders` tool.

Closes #3769.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-03 00:29:51 +01:00
David MannandClaude Opus 5.5 c6974ad9dd packaging(macos): ship cadcraft-cli inside CADCraft.app
The ArtCraft Launcher lists an app for AI agents only when <id>-cli sits
beside its executable, so on macOS CADCraft was left out. Copy the CLI
into Contents/MacOS and sign it before the bundle.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:47:50 +01:00
David MannandClaude Opus 5.5 bf0936ff65 wip: agents in the open window through the ArtCraft Launcher's switch (#3769)
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 23:07:55 +01:00
Dylan M. Taylor 41928f5611 Complete shared dependency API compatibility 2026-11-29 12:17:16 -05:00
Dylan M. Taylor f9c31fe169 Adapt to repinned craft-libs APIs and checks 2026-11-29 11:45:38 -05:00
Dylan M. Taylor 9f7d3fa401 Repin craft-libs to main 9949e08 2026-11-29 11:19:03 -05:00
203 changed files with 60536 additions and 665 deletions
+3 -2
View File
@@ -30,9 +30,10 @@ Generated-in-code assets are original and have no file to list:
| Asset | Author | Source | Licence | Notes |
|---|---|---|---|---|
| `crates/ui-egui/src/i18n/zh_shared.tsv` | @V1dalTheAbidal | [craft-i18n #444](https://github.com/storytold/craft-i18n/pull/444), [pinned Simplified Chinese CADCraft catalog](https://github.com/storytold/craft-i18n/blob/9fa32aecf2759cd61bb216a958df68da619798f3/locales/zh-hans/cadcraft.tsv#L201) | MIT OR Apache-2.0 | Exact generated one-row projection for offline builds; AI-assisted, not native-speaker reviewed. |
| `vendor/wgpu-hal/` | wgpu developers; Metal language probe by CADCraft contributors | [wgpu-hal 30.0.1](https://crates.io/crates/wgpu-hal/30.0.1) ([gfx-rs/wgpu 40f4a34e](https://github.com/gfx-rs/wgpu/tree/40f4a34ebaf56f9a046231f54125ad046239d3f3/wgpu-hal)), same patch as [storytold/craft-anything vendor/wgpu-hal](https://github.com/storytold/craft-anything/tree/6c7d1f07f9f33643714bd203e1e004f04481f28e/vendor/wgpu-hal) | MIT OR Apache-2.0 | Graphics dependency, patched in `src/metal/adapter.rs` only (#1631); see `vendor/wgpu-hal/CADCRAFT.md`. |
| `licenses/jpeg-encoder-0.6.1/` | jpeg-encoder contributors and Independent JPEG Group | [jpeg-encoder 0.6.1](https://crates.io/crates/jpeg-encoder/0.6.1) | (MIT OR Apache-2.0) AND IJG | Dependency license and SIMD notices; source hashes in SOURCE.json. |
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.6](https://crates.io/crates/acadrust/0.6.6), [hakanaktt/acadrust](https://github.com/hakanaktt/acadrust), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.6 third-party notices](https://github.com/hakanaktt/acadrust/blob/v0.6.6/THIRD_PARTY_NOTICES.md), copied from [craft-libs 8fa4db64 licenses/dwg](https://github.com/storytold/craft-libs/tree/8fa4db64a9bb943520259ea95331a303ba788f21/licenses/dwg) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
| `licenses/dwg/acadrust-MPL-2.0.txt` | acadrust contributors | [acadrust 0.6.9](https://github.com/storytold/acadrust/blob/468b9d8e317755209020d5d3f2f1c8a76210c47f/LICENSE) | MPL-2.0 | DWG read/write dependency, used unmodified through craft-dwg. Full licence text is also in NOTICE. |
| `licenses/dwg/acadrust-THIRD_PARTY_NOTICES.md` | Albert Domenech (ACadSharp) and acadrust contributors | [ACadSharp](https://github.com/DomCR/ACadSharp), via [acadrust 0.6.9 third-party notices](https://github.com/storytold/acadrust/blob/468b9d8e317755209020d5d3f2f1c8a76210c47f/THIRD_PARTY_NOTICES.md) | MIT (ACadSharp, via acadrust) | Upstream notice for MIT code ported into acadrust's DWG reader and writer. Full text is also in NOTICE. |
| `epaint_default_fonts::EGUI_ICONS`, `epaint_default_fonts::EMOJI_ICON` (dependency font inputs) | John Slegers | [egui 173cc737](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [emoji-icon-font](https://github.com/jslegers/emoji-icon-font) | MIT (Copyright (c) 2014 John Slegers; full upstream text in `NOTICE`) | egui-icons.ttf is the five-glyph subset; emoji-icon-font.ttf is the full monochrome fallback. Registered by the production default font definitions; dependency assets unmodified here, no font file copied into this repository. |
| `krilla 0.8.2 / icc/sGrey-v2-magic.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v2-magic.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v2-magic.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `4110169287e5f1b5149ca9f1da1814d32943905bba8030e849d1a3b729a19481`. |
| `krilla 0.8.2 / icc/sGrey-v4.icc` (dependency-embedded) | Clinton Ingram | [craft-libs 9f89fe8 vendor/krilla/icc/sGrey-v4.icc](https://github.com/storytold/craft-libs/blob/9f89fe8f6d72ab4db4cc06f186381a6a254463ab/vendor/krilla/icc/sGrey-v4.icc) (Krilla 0.8.2 upstream 3ffdf0588cf98050aad6edba51ca70162e1fb5b5) | CC0-1.0 | Embedded by the pinned PDF writer (`craft-pdf` 0.1.0, Krilla 0.8.2); unmodified dependency asset, no file copied into this repository. SHA-256 `00c0f94e09127520a17dc0e1d9264b5702081d96dbdb1549ee88e3631ce42a9d`. |
Generated
+396 -139
View File
File diff suppressed because it is too large Load Diff
+49 -38
View File
@@ -1,6 +1,8 @@
[workspace]
resolver = "3"
members = ["crates/*", "apps/*", "xtask"]
# Patched third-party crates under [patch.crates-io], not ours to lint or test.
exclude = ["vendor/wgpu-hal"]
# default-members
[workspace.package]
@@ -14,12 +16,12 @@ repository = "https://github.com/storytold/cadcraft"
# internal
cadcraft-geom = { path = "crates/geom" }
# DXF tags: the shared reader and writer (moved from crates/dxf; craft-libs#791).
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8945bdb09b36245a1d442438ce8876377ef430d0" }
craft-dxf = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-dwg = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-shx = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-image-codecs = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-mime = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-nightly = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
cadcraft-color = { path = "crates/color" }
cadcraft-doc = { path = "crates/doc" }
cadcraft-constraints = { path = "crates/constraints" }
@@ -29,19 +31,24 @@ cadcraft-io = { path = "crates/io" }
cadcraft-engine = { path = "crates/engine" }
cadcraft-ui-egui = { path = "crates/ui-egui" }
cadcraft-mcp = { path = "crates/mcp" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-mcp = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-jsonrpc = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# Agents in the open window: the agent settings, the ArtCraft Launcher's switch, the connection file and
# the CLI's live client (`agents`), shared by every Craft app.
craft-control = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# The agent link host (the window's control server for agents) and the Agents page of Options.
craft-automation = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-docpath = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# PDF writing (krilla) for plots, and reading them back in tests. The root patches below pin
# craft-pdf's patched backends to the same revision (Cargo ignores dependency-local patches).
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
craft-pdf = { version = "=0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", default-features = false }
# TrueType embedding-permission classification for plotted fonts (craft-libs#778).
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", default-features = false }
craft-font-catalog = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", default-features = false }
# Delimited text (CSV/TSV) parsing (shared Craft library).
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-csv = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
clap = { version = "4", features = ["derive", "env"] }
clap_complete = "4.6.11"
clap_mangen = { version = "0.3.3", features = ["env"] }
@@ -75,12 +82,12 @@ encoding_rs = "0.8.35"
quick-xml = "0.42"
# ui
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-ui = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-behavior = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-host = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-keymap = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-theme = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
craft-window = { version = "0.1.0", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", features = ["ui"] }
egui = { version = "0.37", default-features = false, features = ["default_fonts", "monochrome_emoji_fonts"] }
# Resizable table columns (About ▸ Contributors / Models); no image loaders.
egui_extras = { version = "0.37", default-features = false }
@@ -91,7 +98,7 @@ egui-wgpu = "0.37"
# Monotonic time on native and web (performance.now on wasm).
web-time = "1.1"
# craft-update: app-specific pretend versions apply to startup and manual checks.
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-update = { git = "https://github.com/storytold/craft-libs", version = "=0.1.0", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", features = ["ui"] }
rfd = "0.18"
arboard = { version = "3.6", default-features = false }
@@ -123,23 +130,27 @@ debug = 0
# PDF backends for craft-pdf: pinned to the same reviewed craft-libs revision as craft-pdf itself
# (Cargo ignores dependency-local patches).
[patch.crates-io]
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
krilla = { version = "=0.8.2", git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-syntax = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-jbig2 = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-interpret = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-cmap = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
hayro-postscript = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e" }
# wgpu-hal that picks a Metal language version the system compiler accepts, not the OS's alone
# (#1631; upstream gfx-rs/wgpu#10687). See vendor/wgpu-hal/CADCRAFT.md for when to remove it.
wgpu-hal = { path = "vendor/wgpu-hal" }
# Keep the complete egui family and native event bridge on reviewed fork commits.
ecolor = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
emath = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "b9770908e0f304896f9658d239a7b29cf8af1564" }
winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" }
ecolor = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
emath = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
epaint_default_fonts = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-winit = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui-wgpu = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_glow = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_extras = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
egui_kittest = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
eframe = { git = "https://github.com/storytold/egui.git", rev = "399fc6e0ea65059e37de680f11ebbd177bf7d4ff" }
winit = { git = "https://github.com/storytold/winit.git", rev = "3fd7ae64762f82a73b78bd24f453f82c4291067d" }
+10 -12
View File
@@ -10,11 +10,10 @@ docs/brand/LICENSE-brand.txt.
Third-party material
Software dependencies are listed in Cargo.lock. One is under a weak-copyleft licence: the acadrust
crate (DWG reading and writing, https://github.com/hakanaktt/acadrust) 0.6.6 is licensed under the
Mozilla Public License 2.0 and is used unmodified as a separate library via craft-dwg. Its source
is available from crates.io and the repository above. The licence text and upstream third-party
notices are retained in licenses/dwg/, copied verbatim from craft-libs at
8fa4db64a9bb943520259ea95331a303ba788f21, the revision this repository pins.
crate (DWG reading and writing) 0.6.9 is licensed under the Mozilla Public License 2.0
and is used as a separate library via craft-dwg. Its source is available at
https://github.com/storytold/acadrust/tree/468b9d8e317755209020d5d3f2f1c8a76210c47f. The licence text and
upstream third-party notices are retained in licenses/dwg/.
acadrust's DWG reader and writer include code ported and adapted from ACadSharp
(https://github.com/DomCR/ACadSharp), Copyright (c) 2021 Albert Domenech, under the MIT License.
@@ -432,13 +431,12 @@ SOFTWARE.
## DWG Format References
DWG field layouts and version behavior are based on the Open Design Alliance (ODA) DWG
specification and reverse engineering, including comparison with drawings produced by CAD
applications. LibreDWG is used as a secondary cross-check for selected field names and
layouts. The Reed-Solomon tests cite numeric reference values from LibreDWG's
`src/reedsolomon.c` to validate the Rust implementation; those values are test data, not
translated routines. The repository history and source review found no LibreDWG routines
ported into the implementation. The source comments identify the specific cross-checks.
The Open Design Alliance (ODA) DWG specification is the primary published reference for
the binary layouts documented by this project. Where the specification is incomplete or
ambiguous, implementation details are checked against native DWG files produced by CAD
applications. Source comments and regression tests identify the evidence used for each
layout and behavior. ACadSharp remains the attributed origin of the existing reader and
writer code described above.
CADCraft's icons, drafting font, hatch patterns and linetypes are drawn or defined in code.
+14
View File
@@ -396,6 +396,20 @@ RISC-V (riscv64) packages are `cadcraft-<ver>-linux-riscv64.deb`,
`cadcraft-<ver>-linux-riscv64.rpm`, and `cadcraft-<ver>-linux-riscv64.tar.gz`. They are
cross-compiled and need glibc 2.39 or newer (Ubuntu 24.04+, Debian 13+).
**Wayland:** on a Wayland desktop the app uses the native Wayland backend, which is sharp at
fractional scales, works with input methods and accepts files dropped from the file manager. If
the native backend misbehaves on your desktop, run the app through XWayland instead with
`CADCRAFT_X11=1` (this needs the X11 libraries: libX11, libX11-xcb, libXcursor, libXi and
libxkbcommon-x11):
```sh
CADCRAFT_X11=1 cadcraft
```
GNOME on Wayland draws no window frames, so there CADCraft's title bar carries the window
buttons, in GNOME's order. **Options ▸ Display ▸ Use system title bar** shows a basic frame
instead. `CADCRAFT_TITLEBAR=app` or `CADCRAFT_TITLEBAR=system` overrides the detection.
### FreeBSD
| Build | File |
+48 -8
View File
@@ -11,6 +11,7 @@ use std::path::{Path, PathBuf};
use cadcraft_engine::geom::{Bounds2, Vec2};
use cadcraft_io::Format;
use cadcraft_mcp::args::{blank_env_is_unset, name_env_vars};
use cadcraft_mcp::live::WhenAppClosed;
use clap::builder::{OsStringValueParser, PathBufValueParser, TypedValueParser};
use clap::error::ErrorKind;
use clap::parser::ValueSource;
@@ -262,12 +263,23 @@ pub(crate) struct CommandsArgs {
pub(crate) compact: bool,
}
/// Run the MCP server on stdio: a headless drawing session, or a bridge to the running app
/// Run the MCP server on stdio: the open CADCraft window while ArtCraft Launcher › Settings › AI
/// agents lets agents use it, otherwise a headless drawing session
#[derive(Args)]
pub(crate) struct McpArgs {
/// Bridge to the app's control channel (its --control port, e.g. 127.0.0.1:7979)
/// Deprecated: plain `mcp` finds the open window by itself while the ArtCraft Launcher lets
/// agents use CADCraft. Bridges to the app's --control port (e.g. 127.0.0.1:7979); goes in a
/// later release
#[arg(long, value_name = "HOST:PORT", value_parser = connect_addr)]
pub(crate) connect: Option<String>,
/// Never the open window: a headless drawing session, also while the ArtCraft Launcher lets
/// agents use CADCraft
#[arg(long, conflicts_with = "connect")]
pub(crate) headless: bool,
/// While agents may use CADCraft but it is closed: `launch` (open it and wait), `headless`
/// (work without a window) or `error`. Default: Options › AI Agents › When CADCraft is closed
#[arg(long, value_name = "CHOICE", value_parser = when_closed, conflicts_with_all = ["connect", "headless"])]
pub(crate) when_closed: Option<WhenAppClosed>,
/// Reach the app at the first call instead of at startup, so the server can start before the
/// app is open
#[arg(long, requires = "connect")]
@@ -404,6 +416,8 @@ pub(crate) enum ValueError {
CmdJson(#[from] serde_json::Error),
#[error("expected a number of 0 or more, got `{0}`")]
Tolerance(String),
#[error("expected one of launch, headless, error, got `{0}`")]
WhenClosed(String),
}
/// Why `parse` refuses flags clap accepted: clap prints it as a usage error (exit 2).
@@ -523,8 +537,12 @@ fn out_is_input(cli: &Cli) -> Option<UsageError> {
/// The backend `cadcraft-cli mcp` serves from.
#[derive(Debug, PartialEq, Eq)]
pub(crate) enum McpTarget {
/// An in-process drawing session (no `--connect`), optionally confined to the two folders.
/// An in-process drawing session (`--headless`), optionally confined to the two folders.
Headless { read_root: Option<String>, write_root: Option<String> },
/// Plain `mcp`: the open window while the ArtCraft Launcher's switch lets agents use CADCraft,
/// otherwise a headless session with the two folders (`cadcraft_mcp::Live`); headless without
/// the suite's `AI-MCP` flag, as before.
Live { read_root: Option<String>, write_root: Option<String>, when_closed: Option<WhenAppClosed> },
/// The running app's control channel at `HOST:PORT`; `lazy`: reached at the first call;
/// `launch`: opened then if it isn't running.
Connect { addr: String, lazy: bool, launch: bool },
@@ -533,10 +551,12 @@ pub(crate) enum McpTarget {
impl McpArgs {
/// What these arguments ask the server to talk to.
pub(crate) fn target(&self) -> McpTarget {
let (read_root, write_root) = (self.automation_read_root.clone(), self.automation_write_root.clone());
match &self.connect {
// `--launch` connects at the first call too (the app opens then).
Some(addr) => McpTarget::Connect { addr: addr.clone(), lazy: self.lazy || self.launch, launch: self.launch },
None => McpTarget::Headless { read_root: self.automation_read_root.clone(), write_root: self.automation_write_root.clone() },
None if self.headless => McpTarget::Headless { read_root, write_root },
None => McpTarget::Live { read_root, write_root, when_closed: self.when_closed },
}
}
}
@@ -553,6 +573,11 @@ fn connect_addr(s: &str) -> Result<String, ValueError> {
if valid { Ok(s.to_string()) } else { Err(ValueError::Connect) }
}
/// `mcp --when-closed`: one of [`WhenAppClosed::NAMES`].
fn when_closed(s: &str) -> Result<WhenAppClosed, ValueError> {
WhenAppClosed::parse(s.trim()).ok_or_else(|| ValueError::WhenClosed(s.to_string()))
}
/// The values of `id` with their command-line indices.
fn indexed<'a, T: Clone + Send + Sync + 'static>(m: &'a ArgMatches, id: &str) -> impl Iterator<Item = (usize, &'a T)> {
let at = m.indices_of(id).into_iter().flatten();
@@ -665,10 +690,21 @@ mod tests {
}
}
/// Without `--connect` the server runs headless, confining nothing unless asked.
/// Plain `mcp` looks for the open window (headless while the launcher doesn't let agents in);
/// `--headless` never does. Neither confines anything unless asked.
#[test]
fn mcp_without_connect_is_headless() {
assert_eq!(mcp(&[]).unwrap(), McpTarget::Headless { read_root: None, write_root: None });
fn plain_mcp_looks_for_the_window_and_headless_never_does() {
assert_eq!(mcp(&[]).unwrap(), McpTarget::Live { read_root: None, write_root: None, when_closed: None });
assert_eq!(mcp(&["--headless"]).unwrap(), McpTarget::Headless { read_root: None, write_root: None });
assert_eq!(
mcp(&["--when-closed", "headless"]).unwrap(),
McpTarget::Live { read_root: None, write_root: None, when_closed: Some(WhenAppClosed::Headless) }
);
assert!(mcp(&["--when-closed", "later"]).unwrap_err().to_string().contains("launch, headless, error"));
// A closed-app choice means nothing without the window, and --connect names its own app.
for conflict in [&["--headless", "--when-closed", "error"][..], &["--headless", "--connect", "127.0.0.1:7979"]] {
assert_eq!(mcp(conflict).unwrap_err().kind(), clap::error::ErrorKind::ArgumentConflict, "{conflict:?}");
}
}
/// The automation roots confine a headless server; `--connect` is refused with the reason
@@ -676,9 +712,13 @@ mod tests {
#[test]
fn mcp_automation_roots_confine_a_headless_server_only() {
assert_eq!(
mcp(&["--automation-read-root", "/work", "--automation-write-root=/work/out"]).unwrap(),
mcp(&["--headless", "--automation-read-root", "/work", "--automation-write-root=/work/out"]).unwrap(),
McpTarget::Headless { read_root: Some("/work".into()), write_root: Some("/work/out".into()) }
);
assert_eq!(
mcp(&["--automation-read-root", "/work"]).unwrap(),
McpTarget::Live { read_root: Some("/work".into()), write_root: None, when_closed: None }
);
let e = mcp(&["--connect", "127.0.0.1:7979", "--automation-read-root", "/work"]).unwrap_err().to_string();
assert!(e.contains("headless MCP server") && e.contains("#1585"), "{e}");
let e = mcp(&["--automation-write-root=/work", "--connect", "127.0.0.1:7979"]).unwrap_err().to_string();
+84 -13
View File
@@ -1,25 +1,96 @@
use std::path::{Path, PathBuf};
use super::args::{McpArgs, McpTarget};
use super::error::{CliError, Result};
/// Serve MCP on stdin and stdout against the running app or a headless session held to any roots given.
/// Serve MCP on stdin and stdout: plain `mcp` against the open window while the ArtCraft Launcher
/// lets agents use CADCraft, otherwise (and with `--headless`) a headless session held to any roots
/// given; `--connect` against an app's `--control` port.
pub(crate) fn mcp(a: &McpArgs) -> Result {
let backend: Box<dyn cadcraft_mcp::Backend> = match a.target() {
McpTarget::Connect { addr, lazy: true, launch } => Box::new(cadcraft_mcp::Remote::lazy(&addr, launch)),
McpTarget::Connect { addr, .. } => match cadcraft_mcp::Remote::connect(&addr) {
Ok(r) => Box::new(r),
Err(source) => return Err(CliError::McpConnect { addr, source }),
},
McpTarget::Headless { read_root, write_root } => {
let roots = cadcraft_engine::file_access::AutomationRoots::new(
read_root.as_deref().map(std::path::Path::new),
write_root.as_deref().map(std::path::Path::new),
)
.map_err(CliError::AutomationRoots)?;
Box::new(cadcraft_mcp::Headless::default().with_automation_roots(roots))
McpTarget::Connect { addr, lazy, launch } => {
let remote = if lazy {
cadcraft_mcp::Remote::lazy(&addr, launch)
} else {
cadcraft_mcp::Remote::connect(&addr).map_err(|source| CliError::McpConnect { addr, source })?
};
// Once the bridge serves: a failed start says only why it failed.
eprintln!(
"cadcraft-cli: `mcp --connect` is deprecated and goes in a later release; plain `cadcraft-cli mcp` finds the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it"
);
Box::new(remote)
}
McpTarget::Live { read_root, write_root, when_closed } => {
match config_dir(a.settings.config_dir.as_deref()).filter(|_| cadcraft_mcp::live::mcp_flag()) {
Some(dir) => {
// Roots that can't be opened stop the server now, as they do headless.
headless(read_root.as_deref(), write_root.as_deref())?;
let mut cfg = cadcraft_mcp::LiveConfig::new(dir);
cfg.when_closed = when_closed;
cfg.read_root = read_root.map(PathBuf::from);
cfg.write_root = write_root.map(PathBuf::from);
cfg.launch = std::env::current_exe().ok().and_then(|cli| cadcraft_mcp::live::launcher(&cli));
Box::new(cadcraft_mcp::Live::new(cfg))
}
// Without the suite's flag (or a settings folder) agents work without a window, as before.
None => headless(read_root.as_deref(), write_root.as_deref())?,
}
}
McpTarget::Headless { read_root, write_root } => headless(read_root.as_deref(), write_root.as_deref())?,
};
let stdin = std::io::stdin();
let stdout = std::io::stdout();
cadcraft_mcp::Server::new(backend).serve(stdin.lock(), stdout.lock())?;
Ok(())
}
/// A headless session held to the roots given, if any.
fn headless(read_root: Option<&str>, write_root: Option<&str>) -> Result<Box<dyn cadcraft_mcp::Backend>> {
let roots =
cadcraft_engine::file_access::AutomationRoots::new(read_root.map(Path::new), write_root.map(Path::new)).map_err(CliError::AutomationRoots)?;
Ok(Box::new(cadcraft_mcp::Headless::default().with_automation_roots(roots)))
}
/// The app's settings folder, where it publishes the agent connection: `--config-dir` or
/// `CADCRAFT_CONFIG_DIR` (`given`; blank: none), else a portable copy's `CADCraftData` beside the
/// CLI, else the platform's, as the app resolves it.
fn config_dir(given: Option<&Path>) -> Option<PathBuf> {
let exe_dir = std::env::current_exe().ok().and_then(|p| p.parent().map(Path::to_path_buf));
config_dir_from(given, exe_dir.as_deref(), |k| std::env::var_os(k))
}
/// [`config_dir`] with the CLI in `exe_dir` and `var` looking the platform's variables up.
fn config_dir_from(given: Option<&Path>, exe_dir: Option<&Path>, var: impl Fn(&str) -> Option<std::ffi::OsString>) -> Option<PathBuf> {
match given {
Some(dir) if dir.to_str().is_some_and(|d| d.trim().is_empty()) => None,
Some(dir) => Some(dir.to_path_buf()),
None => match exe_dir.filter(|d| d.join("portable.txt").is_file()) {
Some(exe) => Some(exe.join("CADCraftData")),
None => cadcraft_engine::settings_dir::platform(var),
},
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::ffi::OsString;
/// The CLI looks for the connection where the app publishes it: `--config-dir` (or its
/// variable), a portable copy's folder beside it, or the platform's.
#[test]
fn the_settings_folder_is_the_apps() {
let exe = std::env::temp_dir().join(format!("cadcraft-cli-portable-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&exe);
std::fs::create_dir_all(&exe).unwrap();
let none = |_: &str| None::<OsString>;
let given = Path::new("/private/cc");
assert_eq!(config_dir_from(Some(given), Some(&exe), none), Some(given.to_path_buf()));
assert_eq!(config_dir_from(Some(Path::new(" ")), Some(&exe), none), None);
assert_eq!(config_dir_from(None, Some(&exe), none), cadcraft_engine::settings_dir::platform(none));
std::fs::write(exe.join("portable.txt"), b"").unwrap();
assert_eq!(config_dir_from(None, Some(&exe), none), Some(exe.join("CADCraftData")));
assert_eq!(config_dir_from(Some(given), Some(&exe), none), Some(given.to_path_buf()), "the folder given wins");
std::fs::remove_dir_all(exe).unwrap();
}
}
@@ -14,6 +14,9 @@ fn mcp(args: &[&str], input: &str) -> Output {
let mut child = Command::new(env!("CARGO_BIN_EXE_cadcraft-cli"))
.arg("mcp")
.args(args)
// No settings folder: plain `mcp` can't find a window and serves headless, whatever the
// ArtCraft Launcher's switch says on this computer.
.env("CADCRAFT_CONFIG_DIR", "")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.stderr(Stdio::piped())
@@ -81,6 +84,8 @@ fn connect_with_address_routes_to_that_endpoint() {
assert!(instructions.contains(&format!("connected to CADCraft at {addr}")), "{instructions}");
let text = r.iter().find(|v| v["id"] == 2).and_then(|v| v["result"]["content"][0]["text"].as_str()).unwrap_or_default();
assert!(text.contains("loopback"), "{r:?}");
// Still served for one release, with the way forward on stderr.
assert!(String::from_utf8_lossy(&out.stderr).contains("`mcp --connect` is deprecated"));
}
#[test]
+3 -1
View File
@@ -151,7 +151,9 @@ fn subcommand_help_requests() {
"mcp --help",
&["mcp", "--help"],
0,
Line("Run the MCP server on stdio: a headless drawing session, or a bridge to the running app"),
Line(
"Run the MCP server on stdio: the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it, otherwise a headless drawing session",
),
Empty,
),
case(
+2 -2
View File
@@ -21,8 +21,8 @@ cadcraft-io = { workspace = true }
cadcraft-fonts = { workspace = true }
# The host messages (storytold/craft-libs): one contract and one bridge for the web builds.
# The page command API (storytold/craft-libs#413): window.cadcraft over the control channel.
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", version = "0.1.0" }
craft-web-api = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", version = "0.1.0" }
craft-web-host = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", version = "0.1.0" }
egui = { workspace = true }
log = { workspace = true }
serde_json = { workspace = true }
+9 -1
View File
@@ -40,6 +40,12 @@ winresource = "0.1"
[target.'cfg(all(unix, not(target_os = "macos")))'.dependencies]
winit = { version = "0.30", default-features = false, features = ["x11"] }
# Checks that the X11 libraries are installed before choosing XWayland (see main.rs). Already in
# the build through winit, at this version.
x11-dl = "2.21"
# Checks for libxkbcommon-x11 too, which winit's X11 backend needs for the keyboard and panics
# without. Already in the build through winit, at this version and with this feature.
xkbcommon-dl = { version = "0.4.2", features = ["x11"] }
# View ▸ Theme ▸ System: the desktop's light/dark choice from the XDG desktop portal
# (desktop_theme.rs). Already in Cargo.lock through accesskit; pinned to that version so nothing
# is built twice.
@@ -47,13 +53,15 @@ zbus = { version = "=5.19.0", default-features = false, features = ["async-io",
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-update = { workspace = true }
# The ArtCraft Launcher's switch and the agent link (main.rs `agents`).
craft-automation = { workspace = true, features = ["ui", "agents"] }
rfd = { workspace = true }
sys-locale = "0.3"
[target.'cfg(target_os = "macos")'.dependencies]
muda = { version = "0.22", default-features = false }
# Quit CADCraft as a close request of the main window, so the unsaved-changes question runs (#2157).
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21", features = ["ui"] }
craft-quit = { git = "https://github.com/storytold/craft-libs", rev = "8678a11602697e0f2e39440dd3df2dc5d7d9a93e", features = ["ui"] }
# View ▸ Accessibility ▸ Animation Effects ▸ Use System Setting: the system's Reduce motion
# (system_animations.rs). Already in Cargo.lock through muda.
objc2-app-kit = { version = "0.3", default-features = false, features = ["std", "NSWorkspace", "NSAccessibility"] }
+8 -8
View File
@@ -12,7 +12,7 @@ const CONFIG_DIR: &str = "CADCRAFT_CONFIG_DIR";
const LOCALE: &str = "CADCRAFT_LOCALE";
const VSYNC: &str = "CADCRAFT_VSYNC";
const STENCIL: &str = "CADCRAFT_STENCIL";
const WAYLAND: &str = "CADCRAFT_WAYLAND";
const X11: &str = "CADCRAFT_X11";
const NO_NATIVE_MENU: &str = "CADCRAFT_NO_NATIVE_MENU";
const SYSTEM_CURSOR: &str = "CADCRAFT_SYSTEM_CURSOR";
const FONTALT: &str = "CADCRAFT_FONTALT";
@@ -27,7 +27,7 @@ pub(crate) const VARS: &[(&str, &str)] = &[
STENCIL,
"0 opens the window without a stencil buffer, 1 keeps it on every attempt; unset, a start that can't draw with it drops it (clipped layout viewports then draw unclipped)",
),
(WAYLAND, "1 keeps the native Wayland backend instead of XWayland; 0 or unset is off"),
(X11, "1 runs through XWayland instead of the native Wayland backend, as a fallback, when the X11 libraries load; 0 or unset is off"),
(NO_NATIVE_MENU, "macOS: 1 keeps the menus inside the window; 0 or unset is off"),
(SYSTEM_CURSOR, "1 uses the system cursor instead of the drawn crosshair; 0 or unset is off"),
(FONTALT, "the font that replaces a missing one"),
@@ -54,9 +54,9 @@ pub(crate) struct Env {
/// `renderer`). Some old drivers (Mesa on Intel HD 4000, old Intel drivers on Windows) accept a
/// stencil pass and then present a black window.
pub(crate) stencil: Switch,
/// Keep the native Wayland backend instead of XWayland.
/// Run through XWayland instead of the native Wayland backend.
#[cfg_attr(not(all(unix, not(target_os = "macos"))), allow(dead_code))]
pub(crate) wayland: Switch,
pub(crate) x11: Switch,
/// macOS: keep the menus inside the window.
#[cfg_attr(not(target_os = "macos"), allow(dead_code))]
pub(crate) no_native_menu: Switch,
@@ -121,7 +121,7 @@ impl Env {
locale: text(LOCALE),
vsync: switch(VSYNC),
stencil: switch(STENCIL),
wayland: switch(WAYLAND),
x11: switch(X11),
no_native_menu: switch(NO_NATIVE_MENU),
system_cursor: switch(SYSTEM_CURSOR),
font_alt: text(FONTALT),
@@ -223,7 +223,7 @@ mod tests {
(LOCALE, "cs-CZ"),
(VSYNC, " On "),
(STENCIL, "No"),
(WAYLAND, "0"),
(X11, "0"),
(NO_NATIVE_MENU, "yes"),
(SYSTEM_CURSOR, "maybe"),
(FONTALT, "Noto Sans"),
@@ -238,7 +238,7 @@ mod tests {
locale: Some("cs-CZ".into()),
vsync: Switch::On,
stencil: Switch::Off,
wayland: Switch::Off,
x11: Switch::Off,
no_native_menu: Switch::On,
system_cursor: Switch::Default,
font_alt: Some("Noto Sans".into()),
@@ -249,7 +249,7 @@ mod tests {
let read = Env::from_vars(env(&blank));
assert_eq!(read.config_dir, None, "an empty variable means no directory, not the working directory");
assert_eq!((read.locale, read.font_alt, read.font_fallback), (None, None, None));
assert_eq!([read.vsync, read.stencil, read.wayland, read.no_native_menu, read.system_cursor], [Switch::Default; 5]);
assert_eq!([read.vsync, read.stencil, read.x11, read.no_native_menu, read.system_cursor], [Switch::Default; 5]);
}
#[test]
+108 -7
View File
@@ -428,6 +428,32 @@ fn log_version() -> String {
format!("{} ({})", reported_version(), option_env!("CADCRAFT_BUILD_SHA").unwrap_or("dev"))
}
/// Agents in the open window: while the ArtCraft Launcher's switch (Settings › AI agents) names
/// CADCraft, the agent link serves the control channel for `cadcraft-cli mcp` and publishes
/// `agent-connection.json` in the settings folder (`cadcraft_ui_egui::agents`). `--control` manages
/// its own server for the whole run instead. A Nightly build is not the app the launcher's switch
/// names, so it takes no agents this way.
fn agents(control_port: Option<u16>, settings_dir: Option<std::path::PathBuf>, ctx: &egui::Context) -> cadcraft_ui_egui::agents::Agents {
use craft_automation::agents::{AgentLink, AgentSwitch, remove_stale_connection};
if is_nightly() {
return Default::default();
}
// A file a crashed launch left behind names a port nothing serves.
if let Some(dir) = &settings_dir {
remove_stale_connection(dir);
}
let wake = ctx.clone();
// The launcher's app list names CADCraft by its catalog id.
let switch = AgentSwitch::watch(profile_root::APP_ID, move || wake.request_repaint());
match control_port {
Some(port) => cadcraft_ui_egui::agents::Agents::managed_by_launch(port, switch, settings_dir),
None => {
let link = AgentLink::new(settings_dir.clone(), format!("CADCraft {}", cadcraft_engine::build_version()));
cadcraft_ui_egui::agents::Agents::new(link, switch, settings_dir)
}
}
}
/// Whether this start runs the isolated Nightly flavor.
fn is_nightly() -> bool {
launch_profile::current().is_nightly()
@@ -498,6 +524,38 @@ fn prepare_launch() -> Option<Vec<std::ffi::OsString>> {
Some(launch.passthrough_args)
}
/// Whether the libraries winit's X11 backend opens at startup are installed (libX11, libXcursor,
/// libX11-xcb and libXi; libX11-xcb brings in libxcb; and libxkbcommon-x11, for the keyboard).
/// The deb and rpm only recommend them, and a forced X11 backend without them fails to start
/// (winit panics when libxkbcommon-x11 is missing).
#[cfg(all(unix, not(target_os = "macos")))]
fn x11_libraries_load() -> bool {
use x11_dl::{xcursor::Xcursor, xinput2::XInput2, xlib::Xlib, xlib_xcb::Xlib_xcb};
let missing = [Xlib::open().err(), Xcursor::open().err(), Xlib_xcb::open().err(), XInput2::open().err()];
let mut missing: Vec<String> = missing.into_iter().flatten().map(|e| e.to_string()).collect();
if xkbcommon_dl::x11::xkbcommon_x11_option().is_none() {
missing.push("libxkbcommon-x11.so.0 could not be loaded".into());
}
if !missing.is_empty() {
log::warn!("CADCRAFT_X11: X11 libraries missing, using the native Wayland backend: {}", missing.join("; "));
}
missing.is_empty()
}
/// Whether to force winit's X11 backend (XWayland on a Wayland desktop): an X display is there,
/// `CADCRAFT_X11` is on, and the X11 libraries load. The libraries are probed last, only when X11
/// would otherwise be chosen.
#[cfg(all(unix, not(target_os = "macos")))]
fn use_x11(display: bool, setting: Switch, x11_libraries_load: impl FnOnce() -> bool) -> bool {
display && setting == Switch::On && x11_libraries_load()
}
/// Whether a display variable names something: set and not empty, as winit reads them.
#[cfg(all(unix, not(target_os = "macos")))]
fn set(v: Option<&std::ffi::OsStr>) -> bool {
v.is_some_and(|v| !v.is_empty())
}
/// Parse CLI options (`--control`, `--sample`, files, `--version`), install logging and I/O hooks, build the services and app, and run eframe.
fn main() -> eframe::Result {
// A copy of this program started to read or write a DWG file does only that. It is started
@@ -589,9 +647,21 @@ fn main() -> eframe::Result {
cadcraft_engine::fonts::ttf::set_fallback_fonts(list);
}
let surface = cadcraft_ui_egui::gpu::surface_config(vars.vsync, cfg!(all(unix, not(target_os = "macos"))));
// XWayland when it's there (see below), unless CADCRAFT_WAYLAND=1 keeps the native Wayland backend.
let forced_x11 = cfg!(all(unix, not(target_os = "macos"))) && std::env::var_os("DISPLAY").is_some() && vars.wayland != Switch::On;
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11);
// winit runs natively on a Wayland desktop: sharp at fractional scales, with working input
// methods, and file drops from the file manager through storytold/winit's W15 patch.
// CADCRAFT_X11=1 runs through XWayland instead, as a fallback where the native backend
// misbehaves; 0, off or unset leaves it off. The X11 libraries are only recommended by the
// packages, so without them the setting is ignored rather than failing.
#[cfg(all(unix, not(target_os = "macos")))]
let forced_x11 = use_x11(set(std::env::var_os("DISPLAY").as_deref()), vars.x11, x11_libraries_load);
#[cfg(not(all(unix, not(target_os = "macos"))))]
let forced_x11 = false;
// Read before the window opens: Use system title bar decides the window's frame.
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
// Where the desktop leaves the window frame to the app (GNOME on Wayland), the framework's title
// bar carries the window buttons, unless Options ▸ Display ▸ Use system title bar is on.
let title_bar = cadcraft_ui_egui::title_bar::decide(forced_x11, restored.as_ref().is_some_and(|ui| ui.system_title_bar));
let frame = cadcraft_ui_egui::framework::frame_decision(forced_x11).or_else(|| title_bar.as_ref().map(|t| t.decision().clone()));
let persistence_path = vars
.portable_storage_file
.clone()
@@ -620,9 +690,6 @@ fn main() -> eframe::Result {
d
});
}
// winit has no file drag-and-drop on Wayland (only on X11), so dropping files from the file
// manager showed a "no" cursor. Run through XWayland when it's there; CADCRAFT_WAYLAND=1
// keeps the native Wayland backend.
#[cfg(all(unix, not(target_os = "macos")))]
if forced_x11 {
options.event_loop_builder = Some(Box::new(|b| {
@@ -666,7 +733,6 @@ fn main() -> eframe::Result {
{
app.services.start_pick = Some(start_pick(cc.egui_ctx.clone()));
}
let (workspace, restored, workspace_error) = workspace::Workspace::load(vars.config_dir.as_deref());
if let Some(ui) = restored {
app.ui = ui;
}
@@ -716,6 +782,9 @@ fn main() -> eframe::Result {
app.session.set_lisp_support_dir(Some(support));
}
app.integrated_titlebar = cadcraft_ui_egui::framework::draws_title_row(frame.as_ref());
if let Some(title_bar) = title_bar {
app.set_title_bar(title_bar);
}
if surface.present_mode == eframe::wgpu::PresentMode::AutoNoVsync {
app.frame_cap = Some(cadcraft_ui_egui::gpu::FrameCap::new(240));
}
@@ -725,6 +794,7 @@ fn main() -> eframe::Result {
let rx = control_server::start(port, cc.egui_ctx.clone());
app = app.with_control(rx);
}
app.agents = agents(control_port, vars.config_dir.clone(), &cc.egui_ctx);
if sample {
let _ = app.run("ui.sample", serde_json::json!({}));
}
@@ -781,6 +851,37 @@ mod tests {
use super::{filters_for_save, follow_desktop, nightly_version_line, saved_window, version_string, window_options, without_tiny_window};
use crate::renderer::STENCIL_BITS;
/// A Wayland desktop without the X11 libraries (libxkbcommon-x11 removed, or a package
/// installed without its recommendations) crashed at startup: X11 was forced through XWayland
/// and winit panicked loading them. Native Wayland is now the default, `CADCRAFT_X11=1` asks
/// for X11 only when the libraries load, and probing them never panics, whichever of them
/// this machine has.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn x11_only_when_asked_for_and_the_libraries_load() {
use super::{use_x11, x11_libraries_load};
use cadcraft_ui_egui::switch::Switch;
let unprobed = || -> bool { panic!("the libraries are probed only when X11 would be chosen") };
assert!(!use_x11(true, Switch::Default, unprobed), "native Wayland by default");
assert!(!use_x11(true, Switch::Off, unprobed), "CADCRAFT_X11=0 leaves it off");
assert!(!use_x11(false, Switch::On, unprobed), "no X display");
assert!(use_x11(true, Switch::On, || true));
assert!(!use_x11(true, Switch::On, || false), "missing X11 libraries: native Wayland, no crash");
let loaded = x11_libraries_load();
assert_eq!(use_x11(true, Switch::On, || loaded), loaded);
}
/// An empty `DISPLAY` names no X server, so `CADCRAFT_X11=1` can't force X11 with it.
#[test]
#[cfg(all(unix, not(target_os = "macos")))]
fn an_empty_display_is_no_display() {
use super::set;
use std::ffi::OsStr;
assert!(set(Some(OsStr::new(":0"))));
assert!(!set(Some(OsStr::new(""))));
assert!(!set(None));
}
#[test]
fn save_dialog_offers_dwg_with_the_drawing_format_first() {
let first = |name: &str| filters_for_save(name)[0].1;
+4
View File
@@ -50,6 +50,7 @@ fn snapshot(ui: &UiState) -> Result<Value, String> {
"propertiesAll": ui.properties_all,
"inWindowMenu": ui.in_window_menu,
"historyLines": ui.history_lines,
"systemTitleBar": ui.system_title_bar,
}))
}
@@ -219,6 +220,7 @@ mod tests {
ui.toolset_tab = "Modeling".into();
ui.collapsed_groups = vec!["Solid".into()];
ui.history_lines = 5;
ui.system_title_bar = true;
ui.dialog = Some("layers".into());
ui.start_tab = true;
first.save_if_changed(&ui, Instant::now()).unwrap();
@@ -226,6 +228,7 @@ mod tests {
let value: Value = serde_json::from_slice(&bytes).unwrap();
assert!(value["workspace"].get("dialog").is_none());
assert!(value["workspace"].get("startTab").is_none());
assert_eq!(value["workspace"]["systemTitleBar"], true, "read before the window opens");
let (_, restored, error) = Workspace::at(Some(path.clone()));
assert!(error.is_none());
let restored = restored.unwrap();
@@ -340,6 +343,7 @@ mod tests {
assert_eq!(restored.toolset_tab, "Modeling");
assert_eq!(restored.collapsed_groups, ["Draw"]);
assert_eq!(restored.history_lines, 7);
assert!(!restored.system_title_bar, "older files keep the app's window buttons");
assert_eq!(serde_json::to_value(restored.docking).unwrap(), serde_json::to_value(UiState::default().docking).unwrap());
}
fs::remove_dir_all(directory).unwrap();
+131 -6
View File
@@ -7,9 +7,15 @@
//! it draws at paper size × that view's annotation scale, and only in views whose scale it
//! supports unless `ANNOALLVISIBLE` is 1. Model space is seen at `CANNOSCALE`, a layout viewport
//! at its viewport scale, and paper space itself at 1:1.
//!
//! An object supporting several scales can sit somewhere else at one of them ([`AnnoMove`]): its
//! grips move it at the current scale only, and ANNORESET puts every scale back where the current
//! one is. What moves is the object's position ([`shift_position`]).
use serde::{Deserialize, Serialize};
use cadcraft_geom::{Mat3, Vec2};
use crate::{Common, Drawing, Entity, EntityKind};
/// A named annotation scale: `paper_units` on paper show `drawing_units` of the drawing.
@@ -87,6 +93,13 @@ pub fn imperial_scales() -> Vec<AnnoScale> {
v
}
/// How far an annotative object sits from its shared position at the scale named `scale`.
#[derive(Clone, Debug, PartialEq, Serialize, Deserialize)]
pub struct AnnoMove {
pub scale: String,
pub by: Vec2,
}
/// Kinds that can be annotative.
pub fn can_be_annotative(k: &EntityKind) -> bool {
matches!(
@@ -105,6 +118,7 @@ pub fn is_annotative(e: &Entity) -> bool {
pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
if !on {
e.common.anno_scales.clear();
e.common.anno_moves.clear();
} else if can_be_annotative(&e.kind) && e.common.anno_scales.is_empty() {
e.common.anno_scales.push(current.clone());
}
@@ -115,8 +129,9 @@ pub fn set_annotative(e: &mut Entity, on: bool, current: &AnnoScale) {
pub enum AnnoDraw {
/// Not annotative: as stored.
Plain,
/// Annotative, at this factor (drawing units per paper unit).
Scaled(f64),
/// Annotative, at `factor` (drawing units per paper unit), its position moved `by` at that
/// scale.
Scaled { factor: f64, by: Vec2 },
/// Annotative and not supporting the view's scale, with `ANNOALLVISIBLE` 0.
Hidden,
}
@@ -130,6 +145,76 @@ impl Common {
pub fn supports_scale(&self, name: &str) -> bool {
self.anno_scales.iter().any(|s| s.name.eq_ignore_ascii_case(name))
}
/// How far the object sits from its shared position at the scale named `name`.
pub fn moved_at(&self, name: &str) -> Vec2 {
self.anno_moves.iter().find(|m| m.scale.eq_ignore_ascii_case(name)).map(|m| m.by).filter(|v| v.is_finite()).unwrap_or(Vec2::ZERO)
}
/// How far the object sits from its shared position at its scale with the ratio `factor`.
pub fn moved_at_factor(&self, factor: f64) -> Vec2 {
self.anno_scales.iter().find(|s| s.has_factor(factor)).map_or(Vec2::ZERO, |s| self.moved_at(&s.name))
}
/// Move the object `by` at the scale named `name` only (an offset that comes to nothing is
/// dropped).
pub fn move_at(&mut self, name: &str, by: Vec2) {
if !by.is_finite() {
return;
}
let to = self.moved_at(name) + by;
self.anno_moves.retain(|m| !m.scale.eq_ignore_ascii_case(name));
if to.len() > 1e-12 * (1.0 + by.len()) && self.anno_moves.len() < MAX_SCALES {
self.anno_moves.push(AnnoMove { scale: name.to_string(), by: to });
}
}
/// Turn the offsets with `m`'s linear part (MOVE leaves them, ROTATE turns them, SCALE sizes
/// them, MIRROR mirrors them), as the shared position goes through `m`.
pub fn transform_moves(&mut self, m: &Mat3) {
for mv in &mut self.anno_moves {
let v = m.apply_vec(mv.by);
mv.by = if v.is_finite() { v } else { Vec2::ZERO };
}
}
}
/// Move the position of `k` by `by`: a text's, MText's or block reference's whole object, a
/// multileader's landing and content (its arrowheads stay), a dimension's text. Other kinds stay.
pub fn shift_position(k: &mut EntityKind, by: Vec2) {
if !by.is_finite() || by == Vec2::ZERO {
return;
}
let add = |p: &mut cadcraft_geom::Vec3| {
p.x += by.x;
p.y += by.y;
};
match k {
EntityKind::Text(_) | EntityKind::MText(_) | EntityKind::Insert(_) => k.transform(&Mat3::translate(by)),
EntityKind::MLeader(m) => {
add(&mut m.landing);
if let Some(t) = &mut m.text {
add(&mut t.insert);
}
if let Some(b) = &mut m.block {
add(&mut b.insert);
}
}
EntityKind::Dimension(d) => {
add(&mut d.text_mid);
d.user_text_pos = true;
d.block = None;
}
_ => {}
}
}
/// Whether grip `index` of `k` is its position grip: moving it moves what [`shift_position`]
/// moves.
pub fn is_position_grip(k: &EntityKind, index: usize) -> bool {
match k {
EntityKind::Text(_) | EntityKind::MText(_) => true,
EntityKind::Insert(_) => index == 0,
EntityKind::Dimension(_) => index == 3,
EntityKind::MLeader(m) => index == m.leaders.iter().map(Vec::len).sum::<usize>(),
_ => false,
}
}
/// How `e` draws in a view whose annotation scale is `view` (drawing units per paper unit). An
@@ -139,14 +224,23 @@ pub fn anno_draw(e: &Entity, view: f64, all_visible: bool) -> AnnoDraw {
return AnnoDraw::Plain;
}
if e.common.supports_factor(view) {
return AnnoDraw::Scaled(if view.is_finite() && view > 0.0 { view } else { 1.0 });
let factor = if view.is_finite() && view > 0.0 { view } else { 1.0 };
return AnnoDraw::Scaled { factor, by: e.common.moved_at_factor(view) };
}
match e.common.anno_scales.first() {
Some(s) if all_visible => AnnoDraw::Scaled(s.factor()),
Some(s) if all_visible => AnnoDraw::Scaled { factor: s.factor(), by: e.common.moved_at(&s.name) },
_ => AnnoDraw::Hidden,
}
}
/// `e` as it draws at annotation scale `f` with its position moved `by` there: [`anno_scaled`],
/// then [`shift_position`].
pub fn anno_placed(e: &Entity, f: f64, by: Vec2) -> Entity {
let mut out = anno_scaled(e, f);
shift_position(&mut out.kind, by);
out
}
/// `e` as it draws at annotation scale `f`: its paper sizes (text height and width, dimension
/// overall scale, multileader arrow, landing and content, hatch pattern scale, block scale and
/// attributes) multiplied by `f`. A dimension is drawn from its definition at that scale, not
@@ -225,13 +319,44 @@ impl Drawing {
/// (paper space shows every annotative object), elsewhere (model space, or an object not in
/// the drawing yet) as [`anno_draw`] at the current annotation scale.
pub fn anno_draw(&self, e: &Entity) -> AnnoDraw {
self.anno_draw_in(e, None)
}
/// How top-level object `e` draws where it is edited: through an active viewport whose
/// annotation scale is `view` (drawing units per paper unit, the viewport's scale, as the
/// renderer draws model space there), else as [`Drawing::anno_draw`].
pub fn anno_draw_in(&self, e: &Entity, view: Option<f64>) -> AnnoDraw {
if !is_annotative(e) {
return AnnoDraw::Plain;
}
if !self.model.contains(e.handle) && self.layouts.iter().any(|l| l.entities.contains(e.handle)) {
return AnnoDraw::Scaled(1.0);
return AnnoDraw::Scaled { factor: 1.0, by: e.common.moved_at_factor(1.0) };
}
let view = view.filter(|f| f.is_finite() && *f > 0.0).unwrap_or_else(|| self.current_anno_scale().factor());
anno_draw(e, view, self.anno_all_visible())
}
/// The scale `e` shows at outside a viewport (see [`Drawing::anno_draw`]): its name and
/// factor, `None` when `e` isn't annotative or doesn't show.
pub fn anno_shown_scale(&self, e: &Entity) -> Option<AnnoScale> {
self.anno_shown_scale_in(e, None)
}
/// The scale `e` shows at in view `view` (see [`Drawing::anno_draw_in`]).
pub fn anno_shown_scale_in(&self, e: &Entity, view: Option<f64>) -> Option<AnnoScale> {
match self.anno_draw_in(e, view) {
AnnoDraw::Scaled { factor, .. } => e.common.anno_scales.iter().find(|s| s.has_factor(factor)).cloned(),
_ => None,
}
}
/// `e` as it draws outside a viewport: an annotative object at its scale and position there,
/// anything else (and a hidden annotative object) as stored.
pub fn anno_shown(&self, e: &Entity) -> EntityKind {
self.anno_shown_in(e, None)
}
/// `e` as it draws in view `view` (see [`Drawing::anno_draw_in`]).
pub fn anno_shown_in(&self, e: &Entity, view: Option<f64>) -> EntityKind {
match self.anno_draw_in(e, view) {
AnnoDraw::Scaled { factor, by } => anno_placed(e, factor, by).kind,
_ => e.kind.clone(),
}
anno_draw(e, self.current_anno_scale().factor(), self.anno_all_visible())
}
/// Whether new objects of this kind are annotative: text and MText with an annotative text
/// style, dimensions with an annotative dimension style, multileaders with an annotative
+5
View File
@@ -98,6 +98,10 @@ pub struct Common {
/// The annotation scales an annotative object supports (empty: not annotative).
#[serde(skip_serializing_if = "Vec::is_empty")]
pub anno_scales: Vec<crate::AnnoScale>,
/// Where an annotative object sits apart from its shared position at some of its scales
/// (moved with its grips at that scale; ANNORESET clears them).
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub anno_moves: Vec<crate::AnnoMove>,
/// Other applications' extended data (xdata) as read from the drawing file: whole
/// applications, each from its `1001` group on. It is part of the object, so a copy of the
/// object (COPY, MIRROR, ARRAY, paste) carries it, as in AutoCAD.
@@ -119,6 +123,7 @@ impl Default for Common {
extrusion: Vec3::Z,
plot_style: "ByLayer".into(),
anno_scales: Vec::new(),
anno_moves: Vec::new(),
xdata: Vec::new(),
}
}
+3 -1
View File
@@ -645,7 +645,9 @@ fn bounds_of<'a>(
match d.anno_draw(e) {
crate::AnnoDraw::Plain => {}
crate::AnnoDraw::Hidden => return Bounds2::EMPTY,
crate::AnnoDraw::Scaled(f) => return bounds_in(d, &crate::anno_scaled(e, f), 0, blocks, in_drawing, off_counts, frozen),
crate::AnnoDraw::Scaled { factor, by } => {
return bounds_in(d, &crate::anno_placed(e, factor, by), 0, blocks, in_drawing, off_counts, frozen);
}
}
}
bounds_in(d, e, depth, blocks, in_drawing, off_counts, frozen)
+9 -12
View File
@@ -367,19 +367,16 @@ impl Drawing {
}
let Some(cv) = serde_json::to_value(&cand).ok().and_then(|c| c.get(*field).cloned()) else { continue };
let same = match (base.get(*field), &cv) {
// Text style and arrow block names compare without case.
// An empty dimension linetype names ByBlock. DWG can spell that builtin explicitly.
(Some(serde_json::Value::String(a)), serde_json::Value::String(b))
if matches!(
*field,
"textStyle"
| "arrowBlock"
| "arrowBlock1"
| "arrowBlock2"
| "leaderArrowBlock"
| "dimLinetype"
| "extLinetype1"
| "extLinetype2"
) =>
if matches!(*field, "dimLinetype" | "extLinetype1" | "extLinetype2") =>
{
let a = if a.is_empty() { "ByBlock" } else { a };
let b = if b.is_empty() { "ByBlock" } else { b };
a.eq_ignore_ascii_case(b)
}
(Some(serde_json::Value::String(a)), serde_json::Value::String(b))
if matches!(*field, "textStyle" | "arrowBlock" | "arrowBlock1" | "arrowBlock2" | "leaderArrowBlock") =>
{
a.eq_ignore_ascii_case(b)
}
+18
View File
@@ -1160,3 +1160,21 @@ fn layout_lookups_by_name_cost_about_the_same_for_any_table_size() {
d.layouts = long_names("L").zip(1..).map(|(n, tab)| Layout::new(&n, tab)).collect();
lookups_by_name_are_quick("L", |n| d.layout(n).is_some());
}
#[test]
fn dimension_linetype_overrides_compare_effective_names() {
let mut d = Drawing::default();
for var in ["DIMLTYPE", "DIMLTEX1", "DIMLTEX2"] {
d.header.set_str(var, "byBLOCK");
}
assert!(d.dim_overrides().is_empty());
let style = d.dim_styles.iter_mut().find(|s| s.name.eq_ignore_ascii_case("Standard")).unwrap();
style.dim_linetype = "ByBlock".into();
style.ext_linetype1 = "DASHED".into();
style.ext_linetype2 = "ByLayer".into();
d.header.set_str("DIMLTYPE", "");
d.header.set_str("DIMLTEX1", "dashed");
d.header.set_str("DIMLTEX2", "ByBlock");
assert_eq!(d.dim_overrides(), serde_json::Map::from_iter([("extLinetype2".into(), serde_json::json!("ByBlock"))]));
}
+2
View File
@@ -19,6 +19,8 @@ cadcraft-constraints = { workspace = true }
cadcraft-fonts = { workspace = true }
cadcraft-render = { workspace = true }
craft-docpath = { workspace = true }
# The agent settings (Options › AI Agents) the app and `cadcraft-cli mcp` share.
craft-control = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+104
View File
@@ -0,0 +1,104 @@
//! The agent settings of Options › AI Agents, shared by the app and `cadcraft-cli mcp`: the
//! control port agents connect on, the folders they may open from and save to, and what the CLI
//! does while CADCraft is closed. They are kept in [`FILE`] in the settings folder, beside the
//! connection file the app publishes for agents, so the CLI reads them without the app.
//!
//! Only the person changes them, in the Options dialog: the OPTIONS JSON form has no such keys,
//! so an agent can't widen its own folders through a command.
use std::io;
use std::path::Path;
use std::sync::Arc;
pub use craft_control::agents::{AgentSettings, WhenAppClosed};
use crate::file_access::AutomationRoots;
/// The settings file in the settings folder.
pub const FILE: &str = "agent-settings.json";
/// The largest settings file read; the settings are a few short fields.
const MAX_BYTES: usize = 64 * 1024;
/// The agent settings saved in the settings folder `dir`; the defaults when none are saved or the
/// file can't be read (the reason is logged), so neither the app nor the CLI fails over them.
pub fn load(dir: &Path) -> AgentSettings {
let path = dir.join(FILE);
match crate::capped_read::read_capped(&path, MAX_BYTES) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
log::warn!("agent settings {}: {e}; using the defaults", path.display());
AgentSettings::default()
}),
Err(e) if e.kind() == io::ErrorKind::NotFound => AgentSettings::default(),
Err(e) => {
log::warn!("agent settings {}: {e}; using the defaults", path.display());
AgentSettings::default()
}
}
}
/// Saves `settings` in the settings folder `dir` (made if missing), replacing the file whole.
pub fn save(dir: &Path, settings: &AgentSettings) -> io::Result<()> {
let json = serde_json::to_vec_pretty(settings).map_err(io::Error::other)?;
crate::atomic_write::write_atomic_making_folders(&dir.join(FILE), &json)
}
/// The roots agent requests run in, for the agent folders `read` and `write`. A folder that is
/// missing or can't be opened grants nothing in its direction, and with neither every file is
/// refused: leaving the roots out would confine nothing. The error names the folders that could
/// not be used.
pub fn roots(read: Option<&Path>, write: Option<&Path>) -> (Arc<AutomationRoots>, Option<String>) {
let mut problems = Vec::new();
let read = read.filter(|r| AutomationRoots::new(Some(r), None).map_err(|e| problems.push(e)).is_ok());
let write = write.filter(|w| AutomationRoots::new(None, Some(w)).map_err(|e| problems.push(e)).is_ok());
let roots = AutomationRoots::new(read, write).ok().flatten().unwrap_or_else(AutomationRoots::none);
(roots, (!problems.is_empty()).then(|| problems.join("; ")))
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::file_access::{check_read, check_write, confine};
fn temp(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("cadcraft-agent-settings-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// What the dialog saves is what the CLI reads; a damaged file reads as the defaults.
#[test]
fn saved_settings_read_back_and_a_damaged_file_is_the_defaults() {
let dir = temp("round-trip");
let mut settings = AgentSettings::default();
settings.read_root = "/agents/in".into();
settings.when_app_closed = WhenAppClosed::Headless;
save(&dir, &settings).unwrap();
assert_eq!(load(&dir), settings);
std::fs::write(dir.join(FILE), b"{not json").unwrap();
assert_eq!(load(&dir), AgentSettings::default());
std::fs::remove_dir_all(dir).unwrap();
}
/// Agent folders that can't be used refuse every file instead of confining nothing.
#[test]
fn folders_that_cannot_be_used_refuse_every_file() {
let dir = temp("roots");
let file = dir.join("plan.dxf");
let (roots, problem) = roots(Some(&dir.join("missing")), None);
assert!(problem.is_some());
confine(Some(&roots), || {
assert!(check_read(&file).is_err());
assert!(check_write(&file).is_err());
});
let (roots, problem) = super::roots(Some(&dir), Some(&dir.join("gone")));
assert!(problem.is_some(), "the missing write folder is named");
confine(Some(&roots), || {
assert!(check_read(&file).is_ok(), "the usable read folder still applies");
assert!(check_write(&file).is_err());
});
std::fs::remove_dir_all(dir).unwrap();
}
}
+23 -2
View File
@@ -3,6 +3,7 @@
//! objects show (ANNOALLVISIBLE) and the current annotation scale (CANNOSCALE with
//! ANNOAUTOSCALE).
use cadcraft_doc::geom::Vec2;
use cadcraft_doc::{AnnoScale, Drawing, EntityKind, Handle, MAX_SCALES, is_annotative};
use serde_json::{Value, json};
@@ -136,6 +137,7 @@ fn remove_scale(d: &mut Drawing, h: Handle, name: &str) -> Removed {
return;
}
e.common.anno_scales.retain(|s| !s.name.eq_ignore_ascii_case(name));
e.common.anno_moves.retain(|m| !m.scale.eq_ignore_ascii_case(name));
r = Removed::Yes;
});
r
@@ -216,8 +218,27 @@ fn with_handles(s: &Session, p: &Value, mut extra: Value) -> Value {
fn run_annoreset(s: &mut Session, p: &Value) -> Result<Value> {
let (hs, _) = annotative_targets(s, p, "annoreset")?;
// One position serves every scale of an object, so they are always in step.
Ok(json!({ "objects": hs.len(), "message": format!("{} annotative object(s) synchronized", hs.len()) }))
// Every scale goes where the object shows now (in the active viewport, at its scale): that
// offset becomes the shared position.
let view = s.anno_view();
let d = s.doc_mut()?;
let mut moved = 0;
for h in &hs {
let Some(e) = d.entity(*h) else { continue };
if e.common.anno_moves.is_empty() || d.layer(&e.common.layer).is_some_and(|l| l.locked) {
continue;
}
let by = match d.anno_draw_in(e, view) {
cadcraft_doc::AnnoDraw::Scaled { by, .. } => by,
_ => Vec2::ZERO,
};
d.modify_entity(*h, |e| {
cadcraft_doc::shift_position(&mut e.kind, by);
e.common.anno_moves.clear();
})?;
moved += 1;
}
Ok(json!({ "objects": hs.len(), "reset": moved, "message": format!("{} annotative object(s) synchronized", hs.len()) }))
}
fn run_annoupdate(s: &mut Session, p: &Value) -> Result<Value> {
+1
View File
@@ -86,6 +86,7 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result<Vec<Handle>> {
let old_h = e.handle;
let mut e = adopt(d, e, &renames);
e.kind.transform(m);
e.common.transform_moves(m);
d.ensure_layer(&e.common.layer);
out.push(e.handle);
copies.push((old_h, e.handle));
+43 -26
View File
@@ -1,13 +1,13 @@
//! `grip.*` commands: the undoable, scriptable form of grip editing (see `crate::grips`).
use cadcraft_doc::{Entity, EntityKind, Handle};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde_json::{Value, json};
use super::curves;
use super::{CommandSpec, bad, bool_or, point_param, point_req, str_param, targets};
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, stretch_grip};
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, shown_grips, stretch_shown};
use crate::{EngineError, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
@@ -46,25 +46,28 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
return Err(EngineError::Other("The object is on a locked layer.".into()));
}
let e = curves::entity(s, h)?;
let k = stretch_grip(&e.kind, i, to).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
let mut edits = vec![(h, k)];
let view = s.anno_view();
let doc = s.doc()?;
let ne = stretch_shown(doc, &e, i, to, view).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
let mut edits = vec![(h, ne)];
// The other `handles` with a grip on the same point stretch with it (connected objects stay
// connected); locked ones and edits that would be degenerate are left alone.
let from = e.kind.grips().get(i).copied().unwrap_or(to);
let from = shown_grips(doc, &e, view).get(i).copied().unwrap_or(to);
let tol = 1e-9 * (1.0 + from.len());
for o in targets(s, p)? {
if o == h || edits.iter().any(|(x, _)| *x == o) || curves::is_locked(s, o) {
continue;
}
let Ok(oe) = curves::entity(s, o) else { continue };
if let Some(j) = oe.kind.grips().iter().position(|g| g.near(from, tol))
&& let Some(k) = stretch_grip(&oe.kind, j, to)
if let Some(j) = shown_grips(doc, &oe, view).iter().position(|g| g.near(from, tol))
&& let Some(ne) = stretch_shown(doc, &oe, j, to, view)
{
edits.push((o, k));
edits.push((o, ne));
}
}
let d = s.doc_mut()?;
for (o, k) in &mut edits {
for (o, ne) in &mut edits {
let (k, moves) = (&mut ne.kind, &ne.common.anno_moves);
// A dimension's text moved by its grip: with DIMTMOVE 0 the dimension line follows.
if let cadcraft_doc::EntityKind::Dimension(dm) = k
&& let Some(cadcraft_doc::EntityKind::Dimension(old)) = d.entity(*o).map(|e| &e.kind)
@@ -73,14 +76,17 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
st.follow_text(dm, d.header.f64("DIMSCALE", 1.0));
}
d.modify_entity(*o, |e| e.kind = k.clone())?;
d.modify_entity(*o, |e| {
e.kind = k.clone();
e.common.anno_moves = moves.clone();
})?;
}
Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::<Vec<_>>() }))
}
/// Z coordinate of grip `index` on `kind` (matching `EntityKind::grips()` order), when the
/// entity stores a 3D position for that grip.
pub(super) fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
let text_z = |t: &cadcraft_doc::Text| match (t.halign, t.valign) {
(cadcraft_doc::HAlign::Left, cadcraft_doc::VAlign::Baseline) | (cadcraft_doc::HAlign::Aligned | cadcraft_doc::HAlign::Fit, _) => t.insert.z,
_ => t.align_pt.unwrap_or(t.insert).z,
@@ -151,10 +157,17 @@ fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2>
.or_else(|| hs.first().copied())
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
let i = index_param(cmd, p)?;
let g = curves::entity(s, h)?.kind.grips();
let g = shown_grips(s.doc()?, &curves::entity(s, h)?, s.anno_view());
g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))
}
/// The displayed grip's planar point and its Z, when the entity has one.
pub(super) fn shown_grip_location(d: &Drawing, e: &Entity, index: usize, view: Option<f64>) -> Option<(Vec2, Option<f64>)> {
let kind = d.anno_shown_in(e, view);
let point = kind.grips().get(index).copied()?;
Some((point, grip_z(&kind, index)))
}
/// 3D base point for SCALE: explicit `base` (with optional Z or ELEVATION), or the selected grip's
/// full 3D position so the grip stays stationary in all three coordinates.
fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec3> {
@@ -169,8 +182,8 @@ fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
let i = index_param(cmd, p)?;
let e = curves::entity(s, h)?;
let g = e.kind.grips().get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))?;
Ok(match grip_z(&e.kind, i) {
let (g, z) = shown_grip_location(s.doc()?, &e, i, s.anno_view()).ok_or_else(|| bad(cmd, "no such grip"))?;
Ok(match z {
Some(z) => Vec3::new(g.x, g.y, z),
None => super::modify::at_elevation(s, g),
})
@@ -201,7 +214,7 @@ fn run_grip_stretch(s: &mut Session, p: &Value) -> Result<Value> {
None => {
let base = match point_param(p, "base") {
Some(b) => b,
None => curves::entity(s, h0)?.kind.grips().get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
None => shown_grips(s.doc()?, &curves::entity(s, h0)?, s.anno_view()).get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
};
point_req(cmd, p, "to")? - base
}
@@ -245,8 +258,9 @@ const MAX_GRIPS: usize = 1000;
/// The objects as they'd be after moving the grips `hot` by `delta`, with the grips of `others`
/// that sit on a hot grip's point (connected objects stay connected). Locked objects and edits
/// that would be degenerate are left out; several hot grips of one object move together.
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, EntityKind)> {
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, Entity)> {
let Ok(d) = s.doc() else { return Vec::new() };
let view = s.anno_view();
// Every grip to move, per object, with its target point.
let mut moves: Vec<(Handle, Vec<(usize, Vec2)>)> = Vec::new();
let mut add = |h: Handle, i: usize, to: Vec2| match moves.iter_mut().find(|(x, _)| *x == h) {
@@ -258,14 +272,14 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
None => moves.push((h, vec![(i, to)])),
};
for &(h, i) in hot.iter().take(MAX_GRIPS) {
let Some(from) = d.entity(h).and_then(|e| e.kind.grips().get(i).copied()) else { continue };
let Some(from) = d.entity(h).and_then(|e| shown_grips(d, e, view).get(i).copied()) else { continue };
add(h, i, from + delta);
let tol = 1e-9 * (1.0 + from.len());
for &o in others.iter().take(MAX_GRIPS) {
if o == h {
continue;
}
if let Some(j) = d.entity(o).and_then(|e| e.kind.grips().iter().position(|g| g.near(from, tol))) {
if let Some(j) = d.entity(o).and_then(|e| shown_grips(d, e, view).iter().position(|g| g.near(from, tol))) {
add(o, j, from + delta);
}
}
@@ -276,16 +290,16 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
continue;
}
let Some(e) = d.entity(h) else { continue };
let mut k = e.kind.clone();
let mut ne = (**e).clone();
let mut changed = false;
for (i, to) in mv {
if let Some(nk) = stretch_grip(&k, i, to) {
k = nk;
if let Some(n) = stretch_shown(d, &ne, i, to, view) {
ne = n;
changed = true;
}
}
if changed {
out.push((h, k));
out.push((h, ne));
}
}
out
@@ -297,16 +311,19 @@ pub(super) fn stretch_grips(s: &mut Session, hot: &[(Handle, usize)], others: &[
let edits = stretched(s, hot, others, delta);
let d = s.doc_mut()?;
let mut out = Vec::new();
for (h, k) in edits {
for (h, ne) in edits {
if copy {
let (Some(sp), Some(e)) = (d.space_of(h), d.entity(h).map(|e| (**e).clone())) else { continue };
let Some(sp) = d.space_of(h) else { continue };
let nh = d.new_handle();
if let Some(st) = d.space_mut(&sp) {
st.push(Entity { handle: nh, kind: k, ..e });
st.push(Entity { handle: nh, ..ne });
out.push(nh);
}
} else {
d.modify_entity(h, |e| e.kind = k)?;
d.modify_entity(h, |e| {
e.kind = ne.kind;
e.common.anno_moves = ne.common.anno_moves;
})?;
out.push(h);
}
}
+10 -4
View File
@@ -104,14 +104,16 @@ impl GripEdit {
if self.hot.contains(&(h, i)) || self.hot.len() >= MAX_HOT {
return Ok(());
}
let p = s.grips_of(h)?.get(i).copied().ok_or_else(|| other("no such grip"))?;
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| other("no such object"))?;
let (p, z) = super::gripcmds::shown_grip_location(d, e, i, s.anno_view()).ok_or_else(|| other("no such grip"))?;
// After the lookup: a missing object or grip stays the error it was.
if !shown(s, h) {
return Ok(());
}
if self.hot.is_empty() {
self.base = p;
self.base_z = s.doc().ok().and_then(|d| d.entity(h)).and_then(|e| super::gripcmds::grip_z(&e.kind, i));
self.base_z = z;
self.targets.push(h);
self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x)));
} else if !self.targets.contains(&h) {
@@ -131,7 +133,7 @@ impl GripEdit {
continue;
}
let Some(e) = st.doc.entity(h).filter(|e| st.shows(e)) else { continue };
let gs = e.kind.grips();
let gs = crate::grips::shown_grips(&st.doc, e, s.anno_view());
// The nearest grip of this object within the tolerance.
let best = gs
.iter()
@@ -491,7 +493,11 @@ impl Interactive for GripEdit {
};
let Ok(d) = s.doc() else { return Vec::new() };
let mut out: Vec<EntityKind> = if self.mode == GripMode::Stretch {
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base).into_iter().take(500).map(|(_, k)| k).collect()
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base)
.into_iter()
.take(500)
.map(|(_, e)| d.anno_shown_in(&e, s.anno_view()))
.collect()
} else {
match self.matrix(c) {
Some(m) => self
+2 -1
View File
@@ -190,10 +190,11 @@ pub(crate) fn explode_kind(d: &cadcraft_doc::Drawing, e: &Entity) -> Option<Vec<
// An annotative object explodes into plain objects as it draws at the current annotation scale.
if cadcraft_doc::is_annotative(e) {
let mut se = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Scaled(f) => cadcraft_doc::anno_scaled(e, f),
cadcraft_doc::AnnoDraw::Scaled { factor, by } => cadcraft_doc::anno_placed(e, factor, by),
_ => e.clone(),
};
se.common.anno_scales.clear();
se.common.anno_moves.clear();
return explode_kind(d, &se);
}
match &e.kind {
+5 -1
View File
@@ -7,7 +7,10 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, er
pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Vec<Handle>> {
refuse_ole_frames(s, hs, m, copy)?;
edit_entities(s, hs, copy, |e| e.kind.transform(m))
edit_entities(s, hs, copy, |e| {
e.kind.transform(m);
e.common.transform_moves(m);
})
}
/// MIRROR's default hatch policy retains the fill direction while reflecting its boundary.
@@ -40,6 +43,7 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64,
refuse_ole_frames(s, hs, &m, copy)?;
edit_entities(s, hs, copy, |e| {
e.kind.transform(&m);
e.common.transform_moves(&m);
e.kind.scale_heights(base.z, f);
e.common.thickness *= f;
})
+1
View File
@@ -202,6 +202,7 @@ fn chspace(s: &mut Session, hs: &[Handle], to: Option<&str>, vp: Option<Handle>)
}
let mut e = e;
e.kind.transform(&m);
e.common.transform_moves(&m);
d.remove_entity(*h);
if let Some(st) = d.space_mut(&target) {
st.push(e);
+2 -2
View File
@@ -70,8 +70,8 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
// Annotative text and dimensions are drawn scaled to the current annotation scale: the box
// follows what is drawn. Multiline text keeps its stored height (it is written back from it).
let scaled = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Scaled(f) if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
Some(cadcraft_doc::anno_scaled(e, f))
cadcraft_doc::AnnoDraw::Scaled { factor, by } if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
Some(cadcraft_doc::anno_placed(e, factor, by))
}
_ => None,
};
+6
View File
@@ -171,6 +171,12 @@ impl DocState {
_ => None,
}
}
/// The annotation scale model space is edited at in the active MSPACE viewport: the
/// viewport's scale (drawing units per paper unit, as the renderer draws it there); `None`
/// outside one (the current annotation scale applies).
pub fn anno_view(&self) -> Option<f64> {
self.active_viewport().map(|(_, v)| v.view_height / v.height).filter(|f| f.is_finite() && *f > 0.0)
}
/// The layers frozen in the active MSPACE viewport (VPLAYER, "VP Freeze"): that viewport does
/// not draw their objects, so picks, selections and grips made through it leave them out.
/// Empty in paper space and on the Model tab.
+6
View File
@@ -74,6 +74,12 @@ impl AutomationRoots {
Ok(Some(Arc::new(Self { read, write })))
}
/// Roots that grant nothing: every read and write is refused. For agents whose folders can't
/// be used, where leaving the roots out would confine nothing.
pub fn none() -> Arc<Self> {
Arc::new(Self { read: None, write: None })
}
/// The read root, absolute with its links followed.
pub fn read_root(&self) -> Option<&Path> {
self.read.as_deref()
+3 -2
View File
@@ -185,8 +185,9 @@ pub fn grip_dims(s: &Session) -> Vec<GripDim> {
return Vec::new();
}
let Some((h, i)) = s.current_prompt().and_then(|p| p.grip) else { return Vec::new() };
let Some(e) = s.doc().ok().and_then(|d| d.entity(h)) else { return Vec::new() };
let all = dims_of(&e.kind, i);
let Ok(d) = s.doc() else { return Vec::new() };
let Some(e) = d.entity(h) else { return Vec::new() };
let all = dims_of(&d.anno_shown_in(e, s.anno_view()), i);
let st = &s.settings;
match st.dyndivis {
0 => all.into_iter().take(1).collect(),
+51 -2
View File
@@ -4,7 +4,7 @@
//! The UI calls [`Session::grip_edit`]; every edit runs through a `grip.*` command so it is
//! undoable and reachable from scripts, the control channel and MCP.
use cadcraft_doc::{DimKind, EntityKind, Handle, LwPolyline};
use cadcraft_doc::{DimKind, Drawing, Entity, EntityKind, Handle, LwPolyline};
use cadcraft_geom::{Arc, EPS, Mat3, Polyline, Vec2, Vec3, norm_angle};
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -564,10 +564,59 @@ impl Session {
/// Grip points of an object (the indices `grip_edit` takes).
pub fn grips_of(&self, handle: Handle) -> Result<Vec<Vec2>> {
self.doc()?.entity(handle).map(|e| e.kind.grips()).ok_or_else(|| EngineError::Other("no such object".into()))
let d = self.doc()?;
d.entity(handle).map(|e| shown_grips(d, e, self.anno_view())).ok_or_else(|| EngineError::Other("no such object".into()))
}
}
/// The grip points of `e` as it shows (the indices `grip_edit` takes): an annotative object's at
/// the annotation scale it shows at and its position there. `view`: the active viewport's scale
/// in MSPACE ([`crate::DocState::anno_view`]), else the current annotation scale applies.
pub fn shown_grips(d: &Drawing, e: &Entity, view: Option<f64>) -> Vec<Vec2> {
d.anno_shown_in(e, view).grips()
}
/// `e` with grip `index` of [`shown_grips`] moved to `to`, or `None` when that grip can't move
/// there. An annotative object's position grip moves it at the scale it shows at only when it
/// supports several scales; its other grips change its shape at every scale (the edit is taken
/// back to paper size).
pub fn stretch_shown(d: &Drawing, e: &Entity, index: usize, to: Vec2, view: Option<f64>) -> Option<Entity> {
let with = |kind: EntityKind| Some(Entity { kind, ..e.clone() });
let (Some(scale), cadcraft_doc::AnnoDraw::Scaled { factor, by }) = (d.anno_shown_scale_in(e, view), d.anno_draw_in(e, view)) else {
return with(stretch_grip(&e.kind, index, to)?);
};
let shown = cadcraft_doc::anno_placed(e, factor, by).kind;
let from = *shown.grips().get(index)?;
let delta = to - from;
if !delta.is_finite() {
return None;
}
if cadcraft_doc::is_position_grip(&e.kind, index) {
if e.common.anno_scales.len() > 1 {
let mut out = e.clone();
out.common.move_at(&scale.name, delta);
return Some(out);
}
let stored = *e.kind.grips().get(index)?;
return with(stretch_grip(&e.kind, index, stored + delta)?);
}
// A shape grip: stretch the object as it shows, then take it back to paper size.
let mut k = stretch_grip(&shown, index, to)?;
cadcraft_doc::shift_position(&mut k, -by);
let k = match (k, &e.kind) {
(EntityKind::Dimension(mut dm), EntityKind::Dimension(old)) => {
// A dimension's geometry isn't scaled: only its style scale was.
dm.overrides = old.overrides.clone();
if by != Vec2::ZERO {
dm.user_text_pos = old.user_text_pos;
}
EntityKind::Dimension(dm)
}
(k, _) => cadcraft_doc::anno_scaled(&Entity { kind: k, ..e.clone() }, 1.0 / factor).kind,
};
with(k)
}
/// Polyline helper kept public for the UI: segment midpoints are grips too.
pub fn polyline_grip_count(p: &LwPolyline) -> usize {
p.vertices.len() + Polyline { vertices: p.vertices.clone(), closed: p.closed }.segments().len().min(p.vertices.len())
+7
View File
@@ -7,6 +7,8 @@
//! [`Session::input`], [`Session::cmdline`]) exactly like typing at AutoCAD's command line.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
#[cfg(not(target_arch = "wasm32"))]
pub mod agent_settings;
pub mod array_live;
pub mod assoc;
@@ -416,6 +418,11 @@ impl Session {
Ok(h)
}
/// The annotation scale of the active MSPACE viewport ([`DocState::anno_view`]).
pub fn anno_view(&self) -> Option<f64> {
self.state().ok().and_then(DocState::anno_view)
}
/// World units per pixel at the current view.
pub fn pixel_size(&self) -> f64 {
let v = self.state().map(DocState::view).unwrap_or_default();
+1 -1
View File
@@ -286,7 +286,7 @@ fn convert_angles(kind: &str, tags: &mut [Tag], f: fn(f64) -> f64) {
fn tag_value(t: &Tag) -> Value {
match &t.value {
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) => Value::str(s),
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) | craft_dxf::Value::Invalid(s) => Value::str(s),
craft_dxf::Value::Real(r) => Value::Real(*r),
craft_dxf::Value::Int(i) => Value::Int(i32::try_from(*i).unwrap_or(if *i < 0 { i32::MIN } else { i32::MAX })),
craft_dxf::Value::Bool(b) => Value::Int(i32::from(*b)),
+9 -8
View File
@@ -360,15 +360,16 @@ fn blank_mtext_frame(d: &Drawing, e: &Entity) -> Option<(Vec2, f64, [f64; 4])> {
if !is_blank_mtext(text) {
return None;
}
let f = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => 1.0,
cadcraft_doc::AnnoDraw::Scaled(f) if f.is_finite() && f > 0.0 => f,
cadcraft_doc::AnnoDraw::Scaled(_) => 1.0,
// As it is drawn: at the current scale, where that scale places it.
let (f, by) = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => (1.0, Vec2::ZERO),
cadcraft_doc::AnnoDraw::Scaled { factor, by } if factor.is_finite() && factor > 0.0 => (factor, by),
cadcraft_doc::AnnoDraw::Scaled { .. } => (1.0, Vec2::ZERO),
cadcraft_doc::AnnoDraw::Hidden => return None,
};
let scaled;
let e = if f != 1.0 {
scaled = cadcraft_doc::anno_scaled(e, f);
let e = if f != 1.0 || by != Vec2::ZERO {
scaled = cadcraft_doc::anno_placed(e, f, by);
&scaled
} else {
e
@@ -497,8 +498,8 @@ fn drawn_text(d: &Drawing, e: &Entity) -> Option<Vec<Vec<Vec2>>> {
let e = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Plain => e,
cadcraft_doc::AnnoDraw::Hidden => return None,
cadcraft_doc::AnnoDraw::Scaled(f) => {
scaled = cadcraft_doc::anno_scaled(e, f);
cadcraft_doc::AnnoDraw::Scaled { factor, by } => {
scaled = cadcraft_doc::anno_placed(e, factor, by);
&scaled
}
};
+1 -1
View File
@@ -81,7 +81,7 @@ fn unsupported_scale_hides_unless_annoallvisible() {
let (mut s, h) = with_text();
setvar(&mut s, "CANNOSCALE", json!("1:20"));
// ANNOALLVISIBLE 1 (the default): shown, at the object's own scale.
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled(1.0));
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled { factor: 1.0, by: cadcraft_engine::geom::Vec2::ZERO });
assert!(drawn_height(s.doc().unwrap(), h).is_some());
s.execute("annovisible.current", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().header.i64("ANNOALLVISIBLE", 1), 0);
@@ -0,0 +1,221 @@
//! An annotative object can sit somewhere else at one of its scales: its grips move it at the
//! current annotation scale only (when it supports several), MOVE and ROTATE move every scale,
//! and ANNORESET puts every scale back where the current one is.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{AnnoDraw, Entity, EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use serde_json::{Value, json};
fn setvar(s: &mut Session, name: &str, value: Value) {
s.execute("setvar", &json!({ "name": name, "value": value })).unwrap();
}
fn handle(r: &Value) -> Handle {
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).and_then(Handle::parse_hex).unwrap()
}
fn entity(s: &Session, h: Handle) -> Entity {
(**s.doc().unwrap().entity(h).unwrap()).clone()
}
/// Annotative text at the origin supporting 1:1 and 1:50, with 1:50 current.
fn two_scales() -> (Session, Handle) {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:50"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).unwrap();
(s, h)
}
/// Where `h` shows at annotation scale `name`.
fn shown_at(s: &mut Session, h: Handle, name: &str) -> Vec2 {
setvar(s, "CANNOSCALE", json!(name));
let d = s.doc().unwrap();
match d.anno_shown(d.entity(h).unwrap()) {
EntityKind::Text(t) => t.insert.xy(),
EntityKind::MText(t) => t.insert.xy(),
EntityKind::MLeader(m) => m.landing.xy(),
EntityKind::Dimension(dm) => dm.text_mid.xy(),
k => panic!("{k:?}"),
}
}
fn near(a: Vec2, b: Vec2) -> bool {
a.dist(b) < 1e-9
}
#[test]
fn a_grip_moves_text_at_the_current_scale_only() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
// The grips show where the object is.
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::ZERO));
}
#[test]
fn grip_scale_keeps_the_displayed_annotation_pivot_and_its_elevation() {
let (mut s, h) = two_scales();
let (z, other_z) = (7.0, 2.0);
s.doc_mut().unwrap().header.set_f64("ELEVATION", other_z);
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::Text(t) = &mut e.kind else { panic!("expected text") };
t.insert.z = z;
})
.unwrap();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
let pivot = s.grips_of(h).unwrap()[0];
assert!(near(pivot, Vec2::new(5.0, 5.0)));
let EntityKind::Text(before) = entity(&s, h).kind else { panic!("expected text") };
s.execute("grip.scale", &json!({ "handles": [h.hex()], "baseHandle": h.hex(), "index": 0, "factor": 2.0 })).unwrap();
let EntityKind::Text(after) = entity(&s, h).kind else { panic!("expected text") };
assert!(near(s.grips_of(h).unwrap()[0], pivot), "the displayed grip is stationary");
assert!((after.insert.z - z).abs() < 1e-9, "the selected grip's Z is stationary, not ELEVATION");
assert!((after.height - 2.0 * before.height).abs() < 1e-9, "the scale operation actually took effect");
}
#[test]
fn undo_takes_a_move_at_one_scale_back() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
assert_eq!(entity(&s, h).common.anno_moves.len(), 1);
s.execute("undo", &json!({})).unwrap();
assert!(entity(&s, h).common.anno_moves.is_empty());
}
#[test]
fn move_and_rotate_carry_every_scale() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
s.execute("move", &json!({ "handles": [h.hex()], "delta": [1, 0] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(6.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(1.0, 0.0)));
s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 90 })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(-5.0, 6.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(0.0, 1.0)));
}
#[test]
fn annoreset_puts_every_scale_at_the_current_one() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let r = s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
assert_eq!(r["reset"], 1, "{r}");
assert!(entity(&s, h).common.anno_moves.is_empty());
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
}
#[test]
fn removing_a_scale_drops_its_position() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
s.execute("objectscale", &json!({ "handles": [h.hex()], "delete": "1:50" })).unwrap();
assert!(entity(&s, h).common.anno_moves.is_empty());
}
#[test]
fn an_object_with_one_scale_moves_everywhere() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
let e = entity(&s, h);
assert!(e.common.anno_moves.is_empty());
let EntityKind::Text(t) = &e.kind else { panic!() };
assert!(near(t.insert.xy(), Vec2::new(5.0, 5.0)));
}
#[test]
fn a_multileader_moves_its_content_and_keeps_its_arrowhead() {
let mut s = Session::new();
s.execute("mleaderstyle", &json!({ "name": "Anno", "annotative": true })).unwrap();
let h = handle(&s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:50"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).unwrap();
let EntityKind::MLeader(m) = entity(&s, h).kind else { panic!() };
let landing = m.leaders.iter().map(Vec::len).sum::<usize>();
let to = m.landing.xy() + Vec2::new(2.0, 1.0);
s.execute("grip.move", &json!({ "handle": h.hex(), "index": landing, "to": [to.x, to.y] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), to));
assert!(near(shown_at(&mut s, h, "1:1"), m.landing.xy()));
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let d = s.doc().unwrap();
let EntityKind::MLeader(shown) = d.anno_shown(d.entity(h).unwrap()) else { panic!() };
assert!(near(shown.leaders[0][0].xy(), Vec2::ZERO), "the arrowhead stays");
}
#[test]
fn a_dimension_moves_its_text_at_one_scale() {
let mut s = Session::new();
s.execute("dimstyle", &json!({ "name": "Anno", "annotative": true, "current": true })).unwrap();
let h = handle(&s.execute("dimaligned", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 2] })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:2"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:2" })).unwrap();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 3, "to": [20, 20] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:2"), Vec2::new(20.0, 20.0)));
let e = entity(&s, h);
let EntityKind::Dimension(dm) = &e.kind else { panic!() };
assert!(!near(dm.text_mid.xy(), Vec2::new(20.0, 20.0)), "the shared text position stays");
assert_eq!(e.common.anno_moves.len(), 1);
}
#[test]
fn shown_draws_through_the_offset() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let d = s.doc().unwrap();
assert!(matches!(d.anno_draw(d.entity(h).unwrap()), AnnoDraw::Scaled { by, .. } if near(by, Vec2::new(5.0, 5.0))));
let b = cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0);
assert!(b.min.x > 4.0 && b.min.y > 4.0, "{b:?}");
}
#[test]
fn hostile_offsets_never_panic() {
let (mut s, h) = two_scales();
for to in [json!([1e308, -1e308]), json!([f64::MAX, 0]), json!(["x", 1])] {
let _ = s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": to }));
}
s.doc_mut().unwrap().modify_entity(h, |e| e.common.move_at("1:50", Vec2::new(f64::NAN, 1.0))).unwrap();
let _ = s.execute("annoreset", &json!({ "handles": [h.hex()] }));
let _ = s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 1e300 }));
let d = s.doc().unwrap();
let _ = cadcraft_engine::render::build(d, &cadcraft_engine::doc::Space::Model, &Default::default());
let _ = bounds(d, h);
}
fn bounds(d: &cadcraft_engine::doc::Drawing, h: Handle) -> cadcraft_engine::geom::Bounds2 {
cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0)
}
#[test]
fn in_a_viewport_grips_and_annoreset_use_the_viewport_s_scale() {
// The text moved at 1:50; CANNOSCALE is 1:1 while a 1:50 viewport is active (MSPACE): the
// grips show where the viewport draws it, a grip moves it at 1:50, ANNORESET takes 1:50's place.
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:1"));
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
let vp = s.execute("mview", &json!({ "p1": [0, 0], "p2": [200, 100] })).unwrap();
let vh = vp["viewports"][0].as_str().and_then(Handle::parse_hex).unwrap();
s.execute("viewport.set", &json!({ "handle": vh.hex(), "scale": "1:50", "center": [0, 0] })).unwrap();
s.execute("mspace", &json!({ "handle": vh.hex() })).unwrap();
assert!((s.anno_view().unwrap() - 50.0).abs() < 1e-9);
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)), "{:?}", s.grips_of(h));
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [7, 7] })).unwrap();
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(7.0, 7.0)));
s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
s.execute("pspace", &json!({})).unwrap();
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
// 1:1 was never moved by the grips, and now sits where 1:50 is.
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(7.0, 7.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(7.0, 7.0)));
}
+1 -1
View File
@@ -23,7 +23,7 @@ fn groups(d: &cadcraft_engine::doc::Drawing, e: &Entity) -> (String, Vec<(i32, V
.into_iter()
.map(|t| {
let v = match t.value {
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) => json!(s),
craft_dxf::Value::Str(s) | craft_dxf::Value::Hex(s) | craft_dxf::Value::Invalid(s) => json!(s),
craft_dxf::Value::Real(r) => json!(r),
craft_dxf::Value::Int(i) => json!(i),
craft_dxf::Value::Bool(b) => json!(i32::from(b)),
+1
View File
@@ -6,6 +6,7 @@ mod angle_prompts;
mod angle_settings;
mod annotate_options;
mod annotative;
mod annotative_positions;
mod arc_ctrl_direction;
mod array_commands;
mod array_counts;
+15 -14
View File
@@ -7,23 +7,24 @@ use cadcraft_engine::Session;
use cadcraft_engine::cmd::file::{IoHooks, set_io, set_write_as};
use serde_json::json;
/// A 2018 DXF with one mental ray render settings object, stored as `90 2` (class version 1 in the
/// 2013+ form).
/// A 2018 DXF with plain and mental ray settings. Both store base class version 2.
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1032\n9\n$HANDSEED\n5\n100\n0\nENDSEC\n\
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
0\nSECTION\n2\nCLASSES\n0\nCLASS\n1\nRENDERSETTINGS\n2\nAcDbRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nCLASS\n1\nMENTALRAYRENDERSETTINGS\n2\nAcDbMentalRayRenderSettings\n3\nSCENEOE\n90\n1024\n91\n1\n280\n0\n281\n0\n0\nENDSEC\n\
0\nSECTION\n2\nOBJECTS\n\
0\nDICTIONARY\n5\nC\n330\n0\n100\nAcDbDictionary\n3\nACAD_RENDER_SETTINGS\n350\n20\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n\
0\nDICTIONARY\n5\n20\n330\nC\n100\nAcDbDictionary\n281\n1\n3\nMedium\n350\n21\n3\nPlain\n350\n22\n\
0\nMENTALRAYRENDERSETTINGS\n5\n21\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nMedium\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n\
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nENDSEC\n0\nEOF\n";
100\nAcDbMentalRayRenderSettings\n90\n2\n0\nRENDERSETTINGS\n5\n22\n330\n20\n100\nAcDbRenderSettings\n90\n2\n1\nPlain\n290\n1\n290\n1\n290\n1\n290\n1\n1\n\n1\n\n90\n3\n0\nENDSEC\n0\nEOF\n";
/// The `AcDbRenderSettings` class version in a written DXF.
fn class_version(path: &std::path::Path) -> Option<i64> {
fn class_versions(path: &std::path::Path) -> [Option<i64>; 2] {
let text = std::fs::read_to_string(path).unwrap();
let l: Vec<&str> = text.lines().map(str::trim).collect();
let at = l.windows(2).position(|w| w == ["0", "MENTALRAYRENDERSETTINGS"])?;
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
["RENDERSETTINGS", "MENTALRAYRENDERSETTINGS"].map(|kind| {
let at = l.windows(2).position(|w| w == ["0", kind])?;
let base = l[at..].windows(2).position(|w| w == ["100", "AcDbRenderSettings"])? + at;
l[base..].windows(2).find(|w| w[0] == "90").map(|w| w[1].parse().unwrap())
})
}
#[test]
@@ -43,13 +44,13 @@ fn saveas_down_and_back_up_keeps_the_render_settings_class_version() {
let save = |s: &mut Session, name: &str, version: &str| {
let path = dir.join(name);
s.execute("saveas", &json!({ "path": path.to_string_lossy(), "version": version })).unwrap();
class_version(&path)
class_versions(&path)
};
assert_eq!(save(&mut s, "2018.dxf", "2018"), Some(2), "same version: as read");
assert_eq!(save(&mut s, "2000.dxf", "2000"), Some(1), "the 2000 form is one lower");
assert_eq!(save(&mut s, "2018.dxf", "2018"), [Some(2), Some(2)], "same version: as read");
assert_eq!(save(&mut s, "2000.dxf", "2000"), [Some(1), Some(2)], "only plain settings have a lower 2000 form");
s.execute("qsave", &json!({})).unwrap();
assert_eq!(class_version(&dir.join("2000.dxf")), Some(1), "QSAVE keeps the 2000 form");
assert_eq!(save(&mut s, "back.dxf", "2018"), Some(2), "back to 2018: the 2018 file's value, not one higher");
assert_eq!(class_versions(&dir.join("2000.dxf")), [Some(1), Some(2)], "QSAVE keeps both 2000 forms");
assert_eq!(save(&mut s, "back.dxf", "2018"), [Some(2), Some(2)], "back to 2018: the 2018 file's value, not one higher");
let _ = std::fs::remove_dir_all(&dir);
}
+2 -4
View File
@@ -35,8 +35,6 @@ craft-pdf = { workspace = true, features = ["read"] }
# Inspect DWG output only where craft-dwg builds its native bridge. An unconditional
# dev-dependency also builds acadrust during --all-targets, breaking FreeBSD aarch64 (#2526).
# The storytold/acadrust fork at tag `storytold/v0.6.6` (upstream v0.6.6), the source craft-dwg moves
# to in storytold/craft-libs#4762; until craft-libs is repinned, craft-dwg still takes the identical
# crates.io 0.6.6.
# Use the same fork revision as craft-dwg so these fixtures exercise its DWG representation.
[target.'cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))'.dev-dependencies]
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "5d5c482b3fcb3dc77e8281474461760f32959436" }
acadrust = { git = "https://github.com/storytold/acadrust.git", rev = "468b9d8e317755209020d5d3f2f1c8a76210c47f" }
-106
View File
@@ -1,106 +0,0 @@
//! The angles of a hatch's elliptic boundary edges in the DXF a DWG is read through.
//!
//! A DWG holds an elliptic edge's start and end angles in radians, and so does the DXF the DWG
//! decoder writes (groups 50 and 51 of an edge of type 3). DXF itself keeps them in degrees, which
//! is how [`crate::dxf_read`] reads them: a circle stored as an elliptic edge with the end angle
//! 6.2832 became an arc of 6.28 degrees, and the hatch covered the hole it should have left open.
//! Only the DWG path needs this; a DXF file is read as written.
use std::f64::consts::PI;
/// `dxf` with the start and end angles (groups 50 and 51) of every elliptic hatch edge (edge type
/// 3, group 72) turned from radians to degrees. The text is handled as bytes: a drawing from
/// before 2007 is written in its code page, which is not UTF-8, and every other byte is kept as it
/// was. Binary DXF, and text with no such edge, come back as they were.
pub(crate) fn elliptic_edge_degrees(dxf: Vec<u8>) -> Vec<u8> {
if dxf.starts_with(b"AutoCAD Binary DXF") || !dxf.windows(5).any(|w| w == b"HATCH") {
return dxf;
}
let mut out = Vec::with_capacity(dxf.len());
let mut lines = dxf.split_inclusive(|b| *b == b'\n');
let mut in_hatch = false;
// After an elliptic edge's type, until the next edge or loop: the angles still to convert.
let mut ellipse = false;
let mut changed = false;
while let Some(code_line) = lines.next() {
let Some(value_line) = lines.next() else {
out.extend_from_slice(code_line);
break;
};
let code = code_line.trim_ascii();
let value = value_line.trim_ascii();
match code {
b"0" => {
in_hatch = value == b"HATCH";
ellipse = false;
}
b"72" if in_hatch => ellipse = value == b"3",
b"92" | b"97" if in_hatch => ellipse = false,
b"50" | b"51" if in_hatch && ellipse => {
if let Some(radians) = std::str::from_utf8(value).ok().and_then(|v| v.parse::<f64>().ok()).filter(|v| v.is_finite()) {
let ending = &value_line[value_line.trim_ascii_end().len()..];
out.extend_from_slice(code_line);
out.extend_from_slice(format!("{}", radians * 180.0 / PI).as_bytes());
out.extend_from_slice(ending);
changed = true;
continue;
}
}
_ => {}
}
out.extend_from_slice(code_line);
out.extend_from_slice(value_line);
}
if changed { out } else { dxf }
}
#[cfg(test)]
mod tests {
use super::*;
fn pairs(text: &str) -> Vec<(String, String)> {
let lines: Vec<&str> = text.lines().collect();
lines.chunks(2).filter_map(|c| Some((c.first()?.trim().to_string(), c.get(1)?.trim().to_string()))).collect()
}
const HATCH: &str = "0\r\nHATCH\r\n91\r\n1\r\n92\r\n1\r\n93\r\n2\r\n72\r\n3\r\n10\r\n5.0\r\n20\r\n6.0\r\n11\r\n-55.5\r\n21\r\n0.0\r\n40\r\n1.0\r\n50\r\n0.0\r\n51\r\n6.283185307179586\r\n73\r\n1\r\n72\r\n1\r\n10\r\n1.0\r\n20\r\n2.0\r\n11\r\n3.0\r\n21\r\n4.0\r\n50\r\n7.0\r\n0\r\nLINE\r\n50\r\n9.0\r\n";
#[test]
fn an_elliptic_edge_gets_its_angles_in_degrees_and_nothing_else_changes() {
let out = String::from_utf8(elliptic_edge_degrees(HATCH.as_bytes().to_vec())).unwrap();
let p = pairs(&out.replace("\r\n", "\n"));
let value = |code: &str, n: usize| p.iter().filter(|(c, _)| c == code).nth(n).map(|(_, v)| v.parse::<f64>().unwrap());
assert!((value("51", 0).unwrap() - 360.0).abs() < 1e-9);
assert_eq!(value("50", 0), Some(0.0));
// A line edge's 50 and another entity's are left alone, as is the line ending.
assert_eq!(value("50", 1), Some(7.0));
assert_eq!(value("50", 2), Some(9.0));
assert!(out.contains("\r\n") && !out.replace("\r\n", "").contains('\r'));
}
/// A drawing from before 2007 is written in its code page: an accented letter is one byte that
/// is not valid UTF-8, and it must not stop the angles being converted or change.
#[test]
fn a_code_page_drawing_still_has_its_angles_converted() {
let mut dxf = b"0\r\nTEXT\r\n1\r\ncaf".to_vec();
dxf.push(0xE9);
dxf.extend_from_slice(b"\r\n");
dxf.extend_from_slice(HATCH.as_bytes());
let out = elliptic_edge_degrees(dxf.clone());
assert!(std::str::from_utf8(&dxf).is_err(), "the input is not UTF-8");
assert!(out.windows(4).any(|w| w == b"caf\xE9"), "the accented byte is kept");
let text: String = out.iter().map(|b| char::from(*b)).collect();
assert!(text.contains("51\r\n360"), "the end angle is 360 degrees: {text}");
}
#[test]
fn text_without_a_hatch_ellipse_comes_back_untouched() {
let dxf = b"0\nLINE\n50\n1.5\n".to_vec();
assert_eq!(elliptic_edge_degrees(dxf.clone()), dxf);
let binary = b"AutoCAD Binary DXF\r\n\x1a\x00HATCH".to_vec();
assert_eq!(elliptic_edge_degrees(binary.clone()), binary);
// A hatch with no elliptic edge is left as it is.
let plain = "0\nHATCH\n72\n1\n50\n2.0\n".as_bytes().to_vec();
assert_eq!(elliptic_edge_degrees(plain.clone()), plain);
}
}
+85 -3
View File
@@ -11,8 +11,9 @@
//! CADCraft keeps an annotative object at paper size with the list of scales it supports
//! ([`cadcraft_doc::Common::anno_scales`]). It writes the object at its default scale with a
//! context per scale ([`plan`], [`objects`]), and reads the scales and paper size back from the
//! contexts ([`resolve`]). An object's position at each scale is the one the scale gives it:
//! AutoCAD lets a context move an object at one scale only, which CADCraft doesn't model.
//! contexts ([`resolve`]). A context can place the object somewhere else at its scale (moved with
//! grips at that scale in AutoCAD or CADCraft): that is the object's offset at the scale
//! ([`cadcraft_doc::AnnoMove`]), written into and read back from the context's position.
//!
//! Objects inside block definitions are left alone, and files older than AutoCAD 2007's format
//! (before annotation scaling) don't get contexts.
@@ -67,8 +68,16 @@ fn by_alignment(t: &Text) -> bool {
/// `e` at annotation scale `f`, as its groups are written there: sizes scaled (see
/// [`cadcraft_doc::anno_scaled`]) and justified text's start point moved with its size about its
/// alignment point. A dimension's definition gets that scale (DIMSCALE).
/// alignment point. A dimension's definition gets that scale (DIMSCALE). The object's offset at
/// that scale moves it there.
pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity {
let mut out = shared_at_scale(e, f);
cadcraft_doc::shift_position(&mut out.kind, e.common.moved_at_factor(f));
out
}
/// [`at_scale`] at the object's shared position (without its offset there).
fn shared_at_scale(e: &Entity, f: f64) -> Entity {
let mut out = cadcraft_doc::anno_scaled(e, f);
if let (EntityKind::Text(t), EntityKind::Text(paper)) = (&mut out.kind, &e.kind)
&& by_alignment(paper)
@@ -79,6 +88,47 @@ pub(crate) fn at_scale(e: &Entity, f: f64) -> Entity {
out
}
/// The point that places `e` (as written at some scale): a text's start or alignment point, an
/// MText's insertion point, a dimension's text position, a multileader's landing.
fn anchor(d: &Drawing, e: &Entity) -> Option<cadcraft_geom::Vec2> {
let p = match &e.kind {
EntityKind::Text(t) if by_alignment(t) => t.align_pt?.xy(),
EntityKind::Text(t) => t.insert.xy(),
EntityKind::MText(t) => t.insert.xy(),
EntityKind::Dimension(dm) if dm.user_text_pos => dm.text_mid.xy(),
EntityKind::Dimension(dm) => cadcraft_render::dimension_in(d, dm).text_pos,
EntityKind::MLeader(m) => m.landing.xy(),
_ => return None,
};
p.is_finite().then_some(p)
}
/// The same point as a context of `e` holds it (`g`: the context's groups after its SCALE
/// handle).
fn context_anchor(e: &Entity, g: &[Tag]) -> Option<cadcraft_geom::Vec2> {
let xy = |code: i32| -> Option<cadcraft_geom::Vec2> {
let i = g.iter().position(|t| t.code == code)?;
let y = g.get(i + 1).filter(|t| t.code == code + 10)?;
let v = cadcraft_geom::Vec2::new(g.get(i)?.f64(), y.f64());
v.is_finite().then_some(v)
};
match &e.kind {
EntityKind::Text(t) if by_alignment(t) => xy(11),
EntityKind::Text(_) => xy(10),
EntityKind::MText(_) => xy(11),
// Only a text the user placed (294 = 0) holds its own position.
EntityKind::Dimension(_) => g.iter().find(|t| t.code == 294).is_some_and(|t| t.i64() == 0).then(|| xy(10)).flatten(),
EntityKind::MLeader(_) => {
let mut tags = vec![Tag::s(100, "AcDbMLeader"), Tag::s(300, "CONTEXT_DATA{")];
tags.extend(g.iter().cloned());
tags.push(Tag::s(301, "}"));
let p = crate::dxf_mleader::read(&tags).landing.xy();
p.is_finite().then_some(p)
}
_ => None,
}
}
/// One context: its handle, the SCALE object's handle and the scale.
pub(crate) struct Context {
handle: String,
@@ -347,6 +397,16 @@ pub(crate) fn mleader_at(tags: &mut [Tag], f: f64) {
}
}
/// A multileader's groups (as [`crate::dxf_mleader::entity_tags`] writes them) marked annotative:
/// the entity's "enable annotation scale" (its 293, after the `CONTEXT_DATA{` block) is on.
/// Without it AutoCAD keeps the contexts but its ANNORESET passes the multileader over.
pub(crate) fn mleader_annotative(tags: &mut [Tag]) {
let Some(close) = tags.iter().position(|t| t.code == 301) else { return };
if let Some(t) = tags.iter_mut().skip(close + 1).find(|t| t.code == 293) {
*t = Tag::i(293, 1);
}
}
// ---------------------------------------------------------------------------------------------
// Reading
@@ -422,6 +482,7 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
.and_then(|s| objs.get(&s));
let Some((_, dict)) = dict else { continue };
let mut list: Vec<(AnnoScale, bool)> = Vec::new();
let mut placed: Vec<(String, f64, cadcraft_geom::Vec2)> = Vec::new();
for c in all_entries(dict) {
let Some((_, t)) = objs.get(&c).filter(|(k, _)| k.ends_with("OBJECTCONTEXTDATA_CLASS")) else { continue };
let g = own(t);
@@ -431,6 +492,10 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
&& !list.iter().any(|(x, _)| x.name.eq_ignore_ascii_case(&s.name))
{
list.push((s.clone(), default));
let after = g.iter().position(|t| t.code == 340).map_or(&[][..], |i| g.get(i + 1..).unwrap_or(&[]));
if let Some(at) = context_anchor(e, after) {
placed.push((s.name.clone(), s.factor(), at));
}
}
}
if list.is_empty() {
@@ -443,6 +508,23 @@ pub(crate) fn resolve(secs: &[SectionRef<'_>], d: &mut Drawing) {
e.common.anno_scales = list;
to_paper(e, f);
});
// A context placing the object elsewhere than its scale would: its offset there.
let Some(e) = d.entity(h).map(|e| (**e).clone()) else { continue };
let moves: Vec<(String, cadcraft_geom::Vec2)> = placed
.iter()
.filter_map(|(name, f, at)| {
let by = *at - anchor(d, &shared_at_scale(&e, *f))?;
let tol = 1e-6 * (1.0 + at.len());
(by.is_finite() && by.len() > tol).then(|| (name.clone(), by))
})
.collect();
if !moves.is_empty() {
let _ = d.modify_entity(h, |e| {
for (name, by) in &moves {
e.common.move_at(name, *by);
}
});
}
}
}
+15 -1
View File
@@ -1024,6 +1024,11 @@ pub(crate) struct AnnoPayload {
struct AnnoObject {
handle: String,
scales: Vec<cadcraft_doc::AnnoScale>,
/// Where the object sits at a scale when it was moved there alone (see `Common::anno_moves`):
/// a format without annotation scale contexts (or a DWG, whose bridge doesn't convert them
/// yet) keeps them here.
#[serde(default, skip_serializing_if = "Vec::is_empty")]
moves: Vec<cadcraft_doc::AnnoMove>,
}
/// Most annotative objects read from one file.
@@ -1041,7 +1046,7 @@ pub(crate) fn anno_chunks(d: &cadcraft_doc::Drawing, contexts: bool) -> Option<V
.iter()
.chain(d.layouts.iter().flat_map(|l| l.entities.iter()))
.filter(|e| cadcraft_doc::is_annotative(e) && !(contexts && crate::dxf_anno::has_contexts(e)))
.map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone() })
.map(|e| AnnoObject { handle: e.handle.hex(), scales: e.common.anno_scales.clone(), moves: e.common.anno_moves.clone() })
.collect();
if cannoscale == "1:1" && annoallvisible == 1 && blocks.is_empty() && objects.is_empty() {
return None;
@@ -1102,9 +1107,18 @@ pub(crate) fn apply_anno(d: &mut cadcraft_doc::Drawing, p: AnnoPayload) {
scales.push(s);
}
}
// Each move once, for a scale the object keeps, by a finite offset.
let mut moves: Vec<cadcraft_doc::AnnoMove> = Vec::new();
for m in o.moves.into_iter().take(cadcraft_doc::MAX_SCALES) {
let known = scales.iter().any(|s| s.name.eq_ignore_ascii_case(&m.scale));
if known && m.by.is_finite() && !moves.iter().any(|x| x.scale.eq_ignore_ascii_case(&m.scale)) {
moves.push(m);
}
}
store.modify(h, |e| {
if cadcraft_doc::can_be_annotative(&e.kind) {
e.common.anno_scales = scales;
e.common.anno_moves = moves;
}
});
}
+12 -24
View File
@@ -1861,37 +1861,25 @@ fn unknown_handles(d: &Drawing) -> HashSet<String> {
all_entities(d).filter(|e| matches!(e.kind, EntityKind::Unknown(_))).map(|e| e.handle.hex()).collect()
}
/// Render settings (`RENDERSETTINGS`, `MENTALRAYRENDERSETTINGS`, `RAPIDRTRENDERSETTINGS`) store
/// their `AcDbRenderSettings` class version (the first group 90 after that marker) in the form of
/// the file's version: a 2013+ file stores it one higher, and a 2013 file stores a rapid RT one
/// one lower, as acadrust reads and writes them (`write_render_settings_dxf` in acadrust 0.6.6's
/// `io/dxf/writer/section_writer.rs`, and its DWG class-object reader and writer; the test
/// `render_settings_class_version_matches_what_acadrust_writes` fails if the two drift apart). A
/// kept object carries the form of the file it was read from ([`Foreign::version`], not the
/// drawing's `$ACADVER`, which SAVEAS changes); written into a file read as another version, it
/// takes that version's form. The DWG bridge's R2000 text is read as the version the kept objects
/// came from (craft-dwg's `encode_kept_noted`), so there they stay as read (#907, #2471).
///
/// Only that first group 90 is converted, on purpose: the group 90 that starts a kind's own
/// subclass (`AcDbMentalRayRenderSettings`, `AcDbRapidRTRenderSettings`) is that kind's version,
/// stored the same in every file version, and is left as read.
/// Plain RENDERSETTINGS stores its base class version one higher in 2013+ files.
/// Mental ray and rapid RT settings store their base version verbatim in every file version.
/// Use the source of the retained objects, since SAVEAS can change the drawing's header.
pub(crate) fn render_settings_versions(tags: &mut [Tag], source: Option<Version>, declared: Version) {
let Some(source) = source.filter(|s| *s != declared) else { return };
let shift = |rapid: bool, v: Version| if rapid { -i64::from(v == Version::R2013) } else { i64::from(v >= Version::R2013) };
let (mut kind, mut in_base) = (String::new(), false);
let Some(source) = source else { return };
let delta = i64::from(declared >= Version::R2013) - i64::from(source >= Version::R2013);
if delta == 0 {
return;
}
let (mut plain, mut in_base) = (false, false);
for t in tags.iter_mut() {
match t.code {
0 => {
kind = up(&t.str());
plain = t.str().trim().eq_ignore_ascii_case("RENDERSETTINGS");
in_base = false;
}
100 if matches!(kind.as_str(), "RENDERSETTINGS" | "MENTALRAYRENDERSETTINGS" | "RAPIDRTRENDERSETTINGS") => {
in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings");
}
100 if plain => in_base = t.str().trim().eq_ignore_ascii_case("AcDbRenderSettings"),
90 if in_base => {
let rapid = kind == "RAPIDRTRENDERSETTINGS";
let logical = t.i64().saturating_sub(shift(rapid, source));
*t = Tag::i(90, logical.saturating_add(shift(rapid, declared)));
*t = Tag::i(90, t.i64().saturating_add(delta));
in_base = false;
}
_ => {}
+25 -8
View File
@@ -48,6 +48,7 @@ struct BlockProps {
/// Handle maps and references gathered while reading.
#[derive(Default)]
struct Rx {
from_dwg: bool,
/// STYLE record handle (upper case) → text style name.
styles: HashMap<String, String>,
/// BLOCK_RECORD handle (upper case) → block name.
@@ -177,7 +178,12 @@ fn draw_kept_dimensions_from_their_blocks(d: &mut Drawing) {
/// Read a DXF file into a drawing.
pub fn read(bytes: &[u8]) -> Result<Drawing> {
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS, None)
read_with_origin(bytes, false)
}
/// The DWG bridge emits explicit viewport defaults that are absent from its source.
pub(super) fn read_with_origin(bytes: &[u8], from_dwg: bool) -> Result<Drawing> {
read_budgeted(bytes, 4_000_000, hatch::MAX_READ_CURVE_POINTS, None, from_dwg)
}
/// A block definition read from BLOCKS: name, base point, description, entities (owner, paper
@@ -191,7 +197,13 @@ type LayoutDef = (String, u32, String, PageSetup, Option<(Vec2, Vec2)>, Option<i
/// Import DXF sections while sharing one materialized-table-cell budget and one hatch curve-point
/// budget across blocks and entity sections. `entities_refused_past` is for tests (see `Rx`).
fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize, entities_refused_past: Option<usize>) -> Result<Drawing> {
fn read_budgeted(
bytes: &[u8],
mut table_cells_left: usize,
curve_points: usize,
entities_refused_past: Option<usize>,
from_dwg: bool,
) -> Result<Drawing> {
let tags = craft_dxf::parse(bytes).map_err(|e| IoError::Format(e.to_string()))?;
let secs = section_slices(&tags);
if secs.is_empty() {
@@ -201,8 +213,13 @@ fn read_budgeted(bytes: &[u8], mut table_cells_left: usize, curve_points: usize,
d.layouts.clear();
// A file without $INSUNITS declares no units (#1209); only new drawings take the template's.
d.header.set_i64("INSUNITS", 0);
let mut rx =
Rx { pstyles: plot_style_names(&secs), curves: hatch::CurvePoints { left: curve_points, cut: 0 }, entities_refused_past, ..Rx::default() };
let mut rx = Rx {
pstyles: plot_style_names(&secs),
curves: hatch::CurvePoints { left: curve_points, cut: 0 },
entities_refused_past,
from_dwg,
..Rx::default()
};
let mut blocks: Vec<BlockDef> = Vec::new();
let mut layout_objs: Vec<LayoutDef> = Vec::new();
let mut entities = Vec::new();
@@ -426,7 +443,7 @@ mod table_budget_tests {
let dxf = format!(
"0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\nTEST\n10\n0\n20\n0\n{table}0\nENDBLK\n0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nSECTION\n2\nENTITIES\n{table}0\nENDSEC\n0\nEOF\n"
);
let d = read_budgeted(dxf.as_bytes(), 2, hatch::MAX_READ_CURVE_POINTS, None).unwrap();
let d = read_budgeted(dxf.as_bytes(), 2, hatch::MAX_READ_CURVE_POINTS, None, false).unwrap();
let block = d.block("TEST").unwrap();
let count = |e: &Entity| match &e.kind {
EntityKind::Table(t) => t.cells.iter().map(Vec::len).sum::<usize>(),
@@ -470,10 +487,10 @@ mod hatch_budget_tests {
#[test]
fn hatch_curves_stop_at_the_read_budget_and_say_so() {
let dxf = format!("0\nSECTION\n2\nENTITIES\n{}{}0\nENDSEC\n0\nEOF\n", spline_hatch(10), spline_hatch(10));
let full = read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, None).unwrap();
let full = read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, None, false).unwrap();
assert!(full.read_notes.is_empty(), "{:?}", full.read_notes);
assert!(hatch_points(&full) > 20_000, "{}", hatch_points(&full));
let d = read_budgeted(dxf.as_bytes(), 4_000_000, 1000, None).unwrap();
let d = read_budgeted(dxf.as_bytes(), 4_000_000, 1000, None, false).unwrap();
// The budget is checked before each edge: the last one sampled may pass it by its own
// points (at most about 4,000); every edge after it is its four control points.
assert!(hatch_points(&d) <= 1000 + 4001 + 20 * 4, "{}", hatch_points(&d));
@@ -604,7 +621,7 @@ mod entity_list_tests {
let block = |name: &str| format!("0\nSECTION\n2\nBLOCKS\n0\nBLOCK\n2\n{name}\n10\n0\n20\n0\n{lines}0\nENDBLK\n0\nENDSEC\n0\nEOF\n");
let files = [format!("0\nSECTION\n2\nENTITIES\n{lines}0\nENDSEC\n0\nEOF\n"), block("*Model_Space"), block("*Paper_Space"), block("B")];
for dxf in &files {
let open = |refused_past| read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, refused_past);
let open = |refused_past| read_budgeted(dxf.as_bytes(), 4_000_000, hatch::MAX_READ_CURVE_POINTS, refused_past, false);
let d = open(Some(3)).unwrap();
let in_layouts: usize = d.layouts.iter().map(|l| l.entities.len()).sum();
assert_eq!(d.model.len() + in_layouts + d.block("B").map_or(0, |b| b.entities.len()), 3, "{dxf}");
+1 -1
View File
@@ -143,7 +143,7 @@ pub(super) fn parse_entities(
if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) {
rx.paper_views_dropped.push((owner.clone(), paper, rx.block.clone()));
}
let mut kindent = entity_with_table_budget(kind, tags, table_cells_left, &mut rx.curves);
let mut kindent = entity_with_table_budget(kind, tags, table_cells_left, &mut rx.curves, rx.from_dwg);
if let Some((c, _)) = kindent.as_mut()
&& let Some(n) = entity_plot_style(tags, rx)
{
+15 -4
View File
@@ -117,7 +117,7 @@ fn viewport_ucs(tags: &[Tag]) -> Option<ViewportUcs> {
/// A VIEWPORT's groups CADCraft doesn't model, as read ([`VIEWPORT_NOT_EXTRA`]), plus those of
/// CADCraft's xdata copy that the record lacks (a DWG drops some).
fn viewport_extra(tags: &[Tag]) -> Vec<RawTag> {
fn viewport_extra(tags: &[Tag], from_dwg: bool) -> Vec<RawTag> {
// Only groups that can stand inside the AcDbViewport subclass: no record start (0), handle (5,
// 105), subclass (100), group brace (102) or xdata (1000 on), which written back would break
// the record or give it a second handle.
@@ -137,7 +137,17 @@ fn viewport_extra(tags: &[Tag]) -> Vec<RawTag> {
out.push(RawTag { code, value });
}
}
let keep: Vec<bool> = out.iter().map(|t| !at_default(&out, t.code, &t.value)).collect();
// The DWG bridge writes an empty style sheet and UCS-at-origin 0 even for a viewport
// without its own UCS. Keep nonempty styles and nondefault UCS-icon settings.
let no_ucs = viewport_ucs(tags).is_none();
let keep: Vec<bool> = out
.iter()
.map(|t| {
!at_default(&out, t.code, &t.value)
&& !(from_dwg && t.code == 1 && t.value.is_empty())
&& !(from_dwg && no_ucs && t.code == 74 && t.value.trim().parse::<i32>().ok() == Some(0))
})
.collect();
let mut keep = keep.into_iter();
out.retain(|_| keep.next().unwrap_or(true));
out
@@ -145,7 +155,7 @@ fn viewport_extra(tags: &[Tag]) -> Vec<RawTag> {
/// Parse one entity record. POLYLINE/INSERT followers are handled by the caller.
pub(super) fn entity(kind: &str, tags: &[Tag]) -> Option<(Common, EntityKind)> {
entity_with_table_budget(kind, tags, &mut 4_000_000, &mut CurvePoints::default())
entity_with_table_budget(kind, tags, &mut 4_000_000, &mut CurvePoints::default(), false)
}
/// Parse one entity while charging materialized table cells to the caller's shared import budget.
@@ -286,6 +296,7 @@ pub(super) fn entity_with_table_budget(
tags: &[Tag],
table_cells_left: &mut usize,
curves: &mut CurvePoints,
from_dwg: bool,
) -> Option<(Common, EntityKind)> {
// The paper-space viewport our writer adds (dxf_write::paper_view) stays implicit.
if kind == "VIEWPORT" && crate::dxf_ext::is_paper_view(tags) {
@@ -493,7 +504,7 @@ pub(super) fn entity_with_table_budget(
twist,
ucs: viewport_ucs(tags),
ucs_per_viewport: t.i(71) == Some(1),
extra: viewport_extra(tags),
extra: viewport_extra(tags, from_dwg),
}
}),
"WIPEOUT" => {
+12 -2
View File
@@ -215,12 +215,22 @@ fn circular_edge(tags: &[Tag], index: &mut usize, vertices: &mut Vec<PolyVertex>
/// as the edge has groups.
const COARSE_ELLIPSE_POINTS: u32 = 8;
/// HATCH groups 50/51 are circular ray angles; an ellipse uses eccentric parameters.
/// Keep the same revolution so full turns and negative angles retain their sweep.
fn ellipse_parameter(angle: f64, ratio: f64) -> f64 {
if ratio == 1.0 || !(ratio > 0.0 && ratio.is_finite() && angle.is_finite()) {
return angle;
}
let param = angle.sin().atan2(ratio * angle.cos());
param + ((angle - param) / std::f64::consts::TAU).round() * std::f64::consts::TAU
}
fn elliptic_edge(tags: &[Tag], index: &mut usize, vertices: &mut Vec<PolyVertex>, budget: &mut EdgeBudget) {
let center = Vec2::new(edge_value(tags, *index), edge_value(tags, *index + 1));
let major = Vec2::new(edge_value(tags, *index + 2), edge_value(tags, *index + 3));
let ratio = edge_value(tags, *index + 4);
let start_angle = edge_value(tags, *index + 5).to_radians();
let end_angle = edge_value(tags, *index + 6).to_radians();
let start_angle = ellipse_parameter(edge_value(tags, *index + 5).to_radians(), ratio);
let end_angle = ellipse_parameter(edge_value(tags, *index + 6).to_radians(), ratio);
let ccw = tags.get(*index + 7).filter(|tag| tag.code == 73).map(Tag::i64).unwrap_or(1) != 0;
*index += 8;
let (start, end) = if ccw { (start_angle, end_angle) } else { (-end_angle, -start_angle) };
+4 -1
View File
@@ -96,11 +96,14 @@ pub(crate) fn read_table_style(name: &str, tags: &[Tag]) -> TableStyle {
i = next;
}
let data_h = blocks.first().and_then(|b| first(140, b)).filter(|h| *h > 0.0);
// A group 280 before the description (3) is the class version. Title suppression
// uses another 280 after it. Older writers sometimes omit the description.
let properties = head.iter().position(|t| t.code == 3).map_or(head, |i| &head[i + 1..]);
let mut st = TableStyle {
name: name.to_string(),
text_height: data_h.unwrap_or(def.text_height),
margin: first(40, head).filter(|m| *m >= 0.0).unwrap_or(def.margin),
title: head.iter().find(|t| t.code == 280).map(Tag::i64).unwrap_or(0) == 0,
title: properties.iter().find(|t| t.code == 280).map(Tag::i64).unwrap_or(0) == 0,
header: head.iter().find(|t| t.code == 281).map(Tag::i64).unwrap_or(0) == 0,
cell_styles: Vec::new(),
};
+1 -78
View File
@@ -1,6 +1,4 @@
use super::{
Block, Color, Common, Dimension, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext,
};
use super::{Block, Color, Common, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext};
/// What happens to the dimension blocks read from a file (#495): a dimension that still names
/// its block is written with that block, under its name, and `*D` blocks nothing else
@@ -79,81 +77,6 @@ pub(super) fn reuse_handles(ents: &mut [Entity], old: &Block, taken: &mut std::c
}
}
/// Anonymous dimension blocks (`*D1`…) with the rendered geometry, as consumers expect.
pub(super) fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Vec<Entity> {
// The dimension as drawn: its overrides, DIMSCALE (0 = the drawing's) and text font.
let style = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
let g = cadcraft_render::dimension_in(d, dm);
let mut out = Vec::new();
// Each part in its style colour (DIMCLRD, DIMCLRE, DIMCLRT), ByBlock when the style says so,
// as AutoCAD writes them: readers that draw the block drew every part ByBlock, i.e. in the
// dimension's own colour (#1052).
let in_color = |color: Color| Common { layer: layer.into(), color, ..Common::default() };
let (dim_c, ext_c, text_c) = (in_color(style.dim_line_color), in_color(style.ext_line_color), in_color(style.text_color));
let line_entities = |i: usize, l: &[Vec2]| -> Vec<Entity> {
let c = match g.line_roles.get(i) {
Some(cadcraft_render::LineRole::Ext) => &ext_c,
_ => &dim_c,
};
l.windows(2)
.filter_map(|seg| match seg {
[a, b] => Some(Entity { handle: Handle(0), common: c.clone(), kind: EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) }) }),
_ => None,
})
.collect()
};
// The text's marks (arc length symbol, DIMINSPECT frame) go after the text background.
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| !g.text_marks.contains(i)) {
out.extend(line_entities(i, l));
}
for t in &g.fills {
if let [a, b, cc] = t.as_slice() {
out.push(Entity {
handle: Handle(0),
common: dim_c.clone(),
kind: EntityKind::Solid(Solid { corners: [a.to3(0.0), b.to3(0.0), cc.to3(0.0), cc.to3(0.0)] }),
});
}
}
// DIMTFILL 2: the text background in DIMTFILLCLR, under the text and its marks (SOLID
// corners go 1, 2, 4, 3).
if style.text_fill == 2
&& let [p0, p1, p2, p3] = g.text_fill.as_slice()
{
out.push(Entity {
handle: Handle(0),
common: in_color(style.text_fill_color),
kind: EntityKind::Solid(Solid { corners: [p0.to3(0.0), p1.to3(0.0), p3.to3(0.0), p2.to3(0.0)] }),
});
}
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| g.text_marks.contains(i)) {
out.extend(line_entities(i, l));
}
// The text, and the part after `\X` below the dimension line as a second MTEXT, as AutoCAD
// writes it (#1055).
let texts = std::iter::once((g.value.clone(), g.text_pos)).chain(g.below.clone());
for (contents, at) in texts.filter(|(t, _)| !t.is_empty()) {
out.push(Entity {
handle: Handle(0),
common: text_c.clone(),
kind: EntityKind::MText(MText {
insert: at.to3(0.0),
height: g.text_height,
width: 0.0,
attach: 5,
rotation: g.text_angle,
style: style.text_style.clone(),
contents: cadcraft_render::DimGeometry::mtext_code(&contents),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}),
});
}
out
}
/// Rows and columns written for a table (bounded like the renderer).
pub(super) fn table_size(t: &Table) -> (usize, usize) {
(t.row_heights.len().min(10_000), t.col_widths.len().min(10_000))
+1
View File
@@ -678,6 +678,7 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap
let mut tags = cx.mleader_tags(d, m);
if let Some(o) = cx.anno.objs.get(&e.handle) {
crate::dxf_anno::mleader_at(&mut tags, crate::dxf_anno::default_factor(o));
crate::dxf_anno::mleader_annotative(&mut tags);
}
w.t.extend(tags);
cx.anno_xdata(w, e);
+2 -1
View File
@@ -1,5 +1,5 @@
use super::assoc::std_assoc_refs;
use super::blocks::{arrow_block_entities, dim_block_entities, dim_block_plan, reuse_handles, table_block_entities};
use super::blocks::{arrow_block_entities, dim_block_plan, reuse_handles, table_block_entities};
use super::common::annotative_xdata;
use super::ctx::{AssocObj, Ctx};
use super::entity::{entity, hatch_reactors};
@@ -11,6 +11,7 @@ use super::{
Space, TableStyle, Tag, Ucs, Vec2, Vec3, Version, W, dxf_ext,
};
use super::{entity_handles, structural_start};
use cadcraft_render::dim_block_entities;
struct TableWritePlan<'a> {
d: &'a Drawing,
+3 -7
View File
@@ -2,8 +2,6 @@
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
/// A DWG hatch's elliptic boundary edge angles, in degrees in the DXF the DWG is read through (#3332).
mod dwg_hatch;
/// What a DXF file holds that CADCraft doesn't model, kept and written back (#528).
mod dxf_raw;
@@ -103,9 +101,7 @@ pub fn read(bytes: &[u8], name: impl AsRef<Path>) -> Result<Drawing> {
pub(crate) fn read_source(bytes: &[u8], name: &Path) -> Result<(Drawing, Option<Vec<u8>>)> {
if craft_dwg::is_dwg(bytes) {
let (dxf, notes) = craft_dwg::decode(bytes, craft_dwg::Limits::DEFAULT).map_err(dwg_error)?;
// The decoder writes an elliptic hatch edge's angles in radians; DXF keeps degrees.
let dxf = dwg_hatch::elliptic_edge_degrees(dxf);
let mut d = dxf_read::read(&dxf).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?;
let mut d = dxf_read::read_with_origin(&dxf, true).map_err(|e| IoError::Format(format!("{e} (in the DXF converted from this DWG)")))?;
d.read_notes = notes.into_iter().map(|note| cadcraft_dwg_message(&note)).collect();
return Ok((d, Some(dxf)));
}
@@ -136,8 +132,8 @@ pub fn write_with(d: &Drawing, name: impl AsRef<Path>, opts: &SaveOptions) -> Re
// Before 2007 the text is in the code page the header declares.
let code_page = dxf_write::code_page(d, version);
Ok(match (opts.binary, version.utf8()) {
(true, true) => craft_dxf::write_binary(&tags, true),
(true, false) => craft_dxf::write_binary_in(&tags, &code_page),
(true, true) => craft_dxf::write_binary(&tags, true).map_err(|e| IoError::Format(e.to_string()))?,
(true, false) => craft_dxf::write_binary_in(&tags, &code_page).map_err(|e| IoError::Format(e.to_string()))?,
(false, true) => craft_dxf::write_ascii_as(&tags, true).into_bytes(),
(false, false) => craft_dxf::write_ascii_in(&tags, &code_page),
})
+14 -3
View File
@@ -1,6 +1,6 @@
//! A hatch boundary stored in a DWG as an elliptic edge keeps its sweep: a circle (0 to 2π) stays a
//! circle, so the hatch leaves the hole open. The DWG decoder writes the edge's angles in radians
//! and DXF reads degrees, so the circle used to come out as an arc of 6.28 degrees.
//! circle, so the hatch leaves the hole open. The DWG decoder used to write the edge's angles in radians
//! while DXF reads degrees, so the circle came out as an arc of 6.28 degrees.
// The DWG bridge is unavailable on wasm and FreeBSD ARM64 (#2526); DXF still works.
#![cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
@@ -16,6 +16,10 @@ fn line(a: (f64, f64), b: (f64, f64)) -> BoundaryEdge {
/// A DWG with a pattern hatch over a 100 x 100 square with a round hole of radius 10 stored as an
/// elliptic edge from `start` to `end` radians.
fn dwg_with_hole(start: f64, end: f64) -> Vec<u8> {
dwg_with_elliptic_hole(start, end, 1.0)
}
fn dwg_with_elliptic_hole(start: f64, end: f64, ratio: f64) -> Vec<u8> {
let mut hatch = Hatch::new();
hatch.is_solid = false;
let mut outer = BoundaryPath::new();
@@ -27,7 +31,7 @@ fn dwg_with_hole(start: f64, end: f64) -> Vec<u8> {
hole.edges = vec![BoundaryEdge::EllipticArc(EllipticArcEdge {
center: Vector2::new(50.0, 50.0),
major_axis_endpoint: Vector2::new(-10.0, 0.0),
minor_axis_ratio: 1.0,
minor_axis_ratio: ratio,
start_angle: start,
end_angle: end,
counter_clockwise: true,
@@ -66,3 +70,10 @@ fn a_quarter_arc_stored_as_an_elliptic_edge_keeps_its_quarter() {
// From the point at 0 degrees (60, 50) to the one at 90 degrees (50, 60), closed by a chord: x spans 10.
assert!(max - min > 9.9 && max - min < 10.5, "the arc spans {} in x", max - min);
}
#[test]
fn a_non_circular_elliptic_arc_keeps_its_dwg_endpoints() {
let (min, max) = hole_extent(&dwg_with_elliptic_hole(std::f64::consts::FRAC_PI_4, std::f64::consts::FRAC_PI_2, 0.5));
let expected_min = 50.0 - 10.0 / 2.0_f64.sqrt();
assert!((min - expected_min).abs() < 0.02 && (max - 50.0).abs() < 0.02, "arc x range {min}..{max}");
}
@@ -798,3 +798,121 @@ fn the_current_scale_is_autocad_s_and_saving_keeps_it_current() {
let var = recs.iter().find(|(k, _)| k == "DICTIONARYVAR").unwrap();
assert_eq!(get(&var.1, 1), Some("1:1"));
}
#[test]
fn a_context_placing_the_object_elsewhere_reads_as_its_offset_there() {
// The text sits 5 further right at 1:10 than its 1:2 position would put it.
let src = FIXTURE.replacen("10 -40\n20 0\n11 30", "10 -35\n20 0\n11 35", 1);
assert_ne!(src, FIXTURE);
let d = cadcraft_io::read_dxf(dxf(&src).as_bytes()).unwrap();
let e = d.entity(Handle::parse_hex("30").unwrap()).unwrap();
assert_eq!(e.common.anno_moves.len(), 1, "{:?}", e.common.anno_moves);
assert_eq!(e.common.anno_moves[0].scale, "1:10");
assert!(e.common.anno_moves[0].by.dist(cadcraft_geom::Vec2::new(5.0, 0.0)) < 1e-9);
// An unmoved fixture has none.
assert!(read().model.iter().all(|e| e.common.anno_moves.is_empty()));
// Written back, the 1:10 context keeps its own position.
let text = save(&d);
let starts: Vec<f64> = contexts_of(&text, "30").iter().map(|c| num(&c.tags, 11)).collect();
assert_eq!(starts, [30.0, 35.0]);
}
#[test]
fn offsets_made_in_cadcraft_survive_a_save() {
let mut d = made();
let hs: Vec<Handle> = d.model.iter().map(|e| e.handle).collect();
for h in &hs {
d.modify_entity(*h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(3.0, 4.0))).unwrap();
}
let back = cadcraft_io::read_dxf(save(&d).as_bytes()).unwrap();
for h in &hs {
let (a, b) = (d.entity(*h).unwrap(), back.entity(*h).unwrap());
for f in [1.0, 50.0] {
let shown = |d: &Drawing, e: &cadcraft_doc::Entity| match cadcraft_doc::anno_draw(e, f, true) {
cadcraft_doc::AnnoDraw::Scaled { factor, by } => match cadcraft_doc::anno_placed(e, factor, by).kind {
EntityKind::Text(t) => t.insert.xy(),
EntityKind::Dimension(dm) if dm.user_text_pos => dm.text_mid.xy(),
EntityKind::Dimension(dm) => cadcraft_render::dimension_in(d, &dm).text_pos,
k => panic!("{k:?}"),
},
m => panic!("{m:?}"),
};
let (p, q) = (shown(&d, a), shown(&back, b));
assert!(p.dist(q) < 1e-6, "{h:?} at {f}: {p:?} vs {q:?}");
}
}
}
/// The landing and text of multileader `e` as it shows at annotation scale `f`.
fn mleader_shown(e: &cadcraft_doc::Entity, f: f64) -> (cadcraft_geom::Vec2, cadcraft_geom::Vec2) {
let cadcraft_doc::AnnoDraw::Scaled { factor, by } = cadcraft_doc::anno_draw(e, f, true) else { panic!("hidden") };
let EntityKind::MLeader(m) = cadcraft_doc::anno_placed(e, factor, by).kind else { panic!("multileader") };
(m.landing.xy(), m.text.unwrap().insert.xy())
}
#[test]
fn a_multileader_moved_at_one_scale_keeps_it_through_dxf() {
let (mut d, h) = with_mleader();
d.modify_entity(h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(2.0, -1.0))).unwrap();
let dxf_back = cadcraft_io::read_dxf(save(&d).as_bytes()).unwrap();
let a = d.entity(h).unwrap();
{
let back = &dxf_back;
let b = back.model.iter().find(|e| matches!(e.kind, EntityKind::MLeader(_))).unwrap();
for f in [1.0, 10.0] {
let ((la, ta), (lb, tb)) = (mleader_shown(a, f), mleader_shown(b, f));
assert!(la.dist(lb) < 1e-6 && ta.dist(tb) < 1e-6, "at {f}: {la:?} {ta:?} vs {lb:?} {tb:?}");
}
}
}
/// A multileader moved at one scale alone is there again after a DWG round trip, carried by
/// CADCraft's own record (the DWG bridge doesn't convert contexts yet, storytold/craft-libs#2005).
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_multileader_moved_at_one_scale_keeps_it_through_dwg() {
cadcraft_io::dwg_worker::allow_in_process();
let (mut d, h) = with_mleader();
d.modify_entity(h, |e| e.common.move_at("1:1", cadcraft_geom::Vec2::new(2.0, -1.0))).unwrap();
let dwg = cadcraft_io::write(&d, "x.dwg").unwrap();
let dwg_back = cadcraft_io::read(&dwg, "x.dwg").unwrap();
let a = d.entity(h).unwrap();
{
let back = &dwg_back;
let b = back.model.iter().find(|e| matches!(e.kind, EntityKind::MLeader(_))).unwrap();
for f in [1.0, 10.0] {
let ((la, ta), (lb, tb)) = (mleader_shown(a, f), mleader_shown(b, f));
assert!(la.dist(lb) < 1e-6 && ta.dist(tb) < 1e-6, "at {f}: {la:?} {ta:?} vs {lb:?} {tb:?}");
}
}
}
/// The MULTILEADER entity's own 293 ("enable annotation scale", after its `CONTEXT_DATA{` block).
fn mleader_enable_annotation_scale(text: &str) -> Option<String> {
let recs = records(text);
let (_, t) = recs.iter().find(|(k, _)| k == "MULTILEADER")?;
let close = t.iter().position(|(c, _)| *c == 301)?;
t.iter().skip(close + 1).find(|(c, _)| *c == 293).map(|(_, v)| v.trim().to_string())
}
#[test]
fn an_annotative_multileader_has_annotation_scale_enabled() {
// AutoCAD's ANNORESET passes over a multileader whose 293 is off, even with its contexts.
let (d, h) = with_mleader();
assert_eq!(mleader_enable_annotation_scale(&save(&d)).as_deref(), Some("1"));
let mut plain = d.clone();
plain.modify_entity(h, |e| e.common.anno_scales.clear()).unwrap();
assert_eq!(mleader_enable_annotation_scale(&save(&plain)).as_deref(), Some("0"));
}
#[test]
fn hostile_context_positions_do_not_panic() {
for bad in ["10 1e309\n20 nan\n11 inf", "10 x\n20 0\n11 -1e308", "10 -40\n20 0\n11 1e308"] {
let src = FIXTURE.replacen("10 -40\n20 0\n11 30", bad, 1);
let Ok(d) = cadcraft_io::read_dxf(dxf(&src).as_bytes()) else { continue };
for e in d.model.iter() {
assert!(e.common.anno_moves.iter().all(|m| m.by.is_finite()), "{:?}", e.common.anno_moves);
}
let _ = save(&d);
}
}
+19
View File
@@ -83,6 +83,25 @@ fn vertices(edges: &[Edge]) -> Vec<PolyVertex> {
loops.into_iter().next().map(|l| l.vertices).unwrap_or_default()
}
/// HATCH ellipse endpoints are circular ray angles, not the ellipse's eccentric parameters.
#[test]
fn a_non_circular_ellipse_edge_uses_ray_angles_in_both_directions() {
let expected = 10.0 / 5.0_f64.sqrt(); // x = y at 45 degrees on x²/100 + y²/25 = 1
let bounds = |l: &HatchLoop| l.vertices.iter().fold((f64::NEG_INFINITY, f64::INFINITY), |(max_x, min_y), v| (max_x.max(v.p.x), min_y.min(v.p.y)));
for (start, end, ccw) in [(45.0, 90.0, true), (270.0, 315.0, false), (405.0, 450.0, true)] {
let edge = Edge::Ellipse([0.0, 0.0], [10.0, 0.0], 0.5, start, end, ccw);
let drawing = cadcraft_io::read(dxf(&[vec![edge]]).as_bytes(), "ellipse.dxf").unwrap();
let loops = loops_of(&drawing);
let (max_x, min_y) = bounds(&loops[0]);
assert!((max_x - expected).abs() < 1e-8 && (min_y - expected).abs() < 1e-8, "{start} {end} {ccw}: {max_x} {min_y}");
// CADCraft writes the sampled contour as a polyline; the geometry survives a DXF save.
let saved = cadcraft_io::write_dxf(&drawing);
let reopened = cadcraft_io::read(saved.as_bytes(), "ellipse.dxf").unwrap();
let (x2, y2) = bounds(&loops_of(&reopened)[0]);
assert!((x2 - max_x).abs() < 1e-6 && (y2 - min_y).abs() < 1e-6);
}
}
/// 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);
+11 -6
View File
@@ -5,20 +5,25 @@
use cadcraft_doc::EntityKind;
/// Stand-in OLE data as a DWG carries it: a two-byte marker, the frame's four corners (upper
/// left, upper right, lower right, lower left; x, y, z doubles), then the object's bytes, here
/// opaque text long enough to take several 310 groups.
/// A saved-layout OLE frame header followed by opaque stand-in object bytes, long enough to
/// take several 310 groups. The payload is not claimed to be a valid compound file.
fn payload() -> Vec<u8> {
let mut data = vec![0x80, 0x00];
let mut data = 0x5580u16.to_le_bytes().to_vec();
for [x, y] in [[10.0f64, 40.0], [70.0, 40.0], [70.0, 5.0], [10.0, 5.0]] {
for v in [x, y, 0.0] {
data.extend_from_slice(&v.to_le_bytes());
}
}
let mut extension = [0u8; 26];
extension[16..20].copy_from_slice(&1u32.to_le_bytes()); // embedded object
data.extend_from_slice(&extension);
let mut object = vec![];
for i in 0..12u8 {
data.extend_from_slice(b"synthetic embedded object ");
data.push(i);
object.extend_from_slice(b"synthetic embedded object ");
object.push(i);
}
data.extend_from_slice(&(object.len() as u32).to_le_bytes());
data.extend_from_slice(&object);
data
}
+5 -1
View File
@@ -12,12 +12,16 @@ const LR: (f64, f64) = (35.27, -22.39);
/// The OLE data: the envelope with the frame's corners.
fn blob() -> Vec<u8> {
let mut b = vec![1u8, 0];
let mut b = 0x5580u16.to_le_bytes().to_vec();
for (x, y) in [UL, (LR.0, UL.1), LR, (UL.0, LR.1)] {
for v in [x, y, 0.0] {
b.extend_from_slice(&v.to_le_bytes());
}
}
let mut extension = [0u8; 26];
extension[16..20].copy_from_slice(&1u32.to_le_bytes()); // embedded object
b.extend_from_slice(&extension);
b.extend_from_slice(&0u32.to_le_bytes()); // no compound-file bytes
b
}
+9 -15
View File
@@ -1,10 +1,5 @@
//! Render settings store their `AcDbRenderSettings` class version in the form of the file's
//! version: a 2013+ file stores it one higher (a 2013 file stores a rapid RT one one lower), as
//! acadrust reads and writes them. A kept object carries the form of the file it came from; written
//! into a file declaring another version, it takes that version's form. The DWG bridge is an R2000
//! DXF for a 2018 DWG: without this, a 2018 drawing's MENTALRAYRENDERSETTINGS went in with the 2018
//! form, the DWG writer raised it once more, and BricsCAD refused the DWG ("Object improperly
//! read", #907).
//! Plain render settings use a version-specific base class version. Mental ray and rapid RT
//! settings keep their stored value across both DXF and DWG versions (#907, #2471).
use cadcraft_io::{SaveOptions, Version};
@@ -50,7 +45,7 @@ fn written(d: &cadcraft_doc::Drawing, version: Version) -> String {
#[test]
fn render_settings_class_version_takes_the_declared_versions_form() {
let kind = "MENTALRAYRENDERSETTINGS";
let kind = "RENDERSETTINGS";
// From a 2018 file (stored 2 = class version 1 in the 2013+ form).
let d = cadcraft_io::read_dxf(dxf("AC1032", kind, 2).as_bytes()).unwrap();
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2), "same version: as read");
@@ -61,19 +56,19 @@ fn render_settings_class_version_takes_the_declared_versions_form() {
let d = cadcraft_io::read_dxf(dxf("AC1015", kind, 1).as_bytes()).unwrap();
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
// Rapid RT settings: the 2013 file alone stores one lower.
// Rapid RT keeps the stored base class version across file versions.
let kind = "RAPIDRTRENDERSETTINGS";
let d = cadcraft_io::read_dxf(dxf("AC1027", kind, 1).as_bytes()).unwrap();
assert_eq!(class_version(&written(&d, Version::R2013), kind), Some(1));
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(2));
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(2));
assert_eq!(class_version(&written(&d, Version::R2018), kind), Some(1));
assert_eq!(class_version(&written(&d, Version::R2000), kind), Some(1));
}
/// A file that declares no `$ACADVER` gives no source form: its kept objects are written as read,
/// not as if the new drawing's 2018 were their form.
#[test]
fn render_settings_without_a_declared_version_are_written_as_read() {
let kind = "MENTALRAYRENDERSETTINGS";
let kind = "RENDERSETTINGS";
let text = dxf("AC1032", kind, 1).replace("9\n$ACADVER\n1\nAC1032\n", "");
assert!(!text.contains("$ACADVER"));
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
@@ -110,8 +105,7 @@ fn render_settings_class_version_matches_what_acadrust_writes() {
(DxfVersion::AC1027, Version::R2013),
(DxfVersion::AC1032, Version::R2018),
];
// As a 2018 file stores them: mental ray one higher than its class version, rapid RT as is.
for (kind, stored) in [("MENTALRAYRENDERSETTINGS", 2), ("RAPIDRTRENDERSETTINGS", 2)] {
for (kind, stored) in [("RENDERSETTINGS", 2), ("MENTALRAYRENDERSETTINGS", 2), ("RAPIDRTRENDERSETTINGS", 2)] {
let source = std::io::Cursor::new(dxf("AC1032", kind, stored).into_bytes());
let mut doc = acadrust::DxfReader::from_reader(source).unwrap().read().unwrap();
let by_acadrust: Vec<(Version, String)> = versions
@@ -122,7 +116,7 @@ fn render_settings_class_version_matches_what_acadrust_writes() {
})
.collect();
let forms: Vec<Option<i64>> = by_acadrust.iter().map(|(_, text)| class_version(text, kind)).collect();
let expected = if kind == "RAPIDRTRENDERSETTINGS" { [2, 2, 1, 2] } else { [1, 1, 2, 2] };
let expected = if kind == "RENDERSETTINGS" { [1, 1, 2, 2] } else { [2, 2, 2, 2] };
assert_eq!(forms, expected.map(Some), "{kind}: acadrust's own forms for 2000, 2010, 2013, 2018");
for (read_from, text) in &by_acadrust {
let d = cadcraft_io::read_dxf(text.as_bytes()).unwrap();
+42 -14
View File
@@ -1,5 +1,5 @@
//! Shared preservation assertions for ordered entities, authored blocks and referenced tables.
//! Every field of the explicitly supported entities is checked; converted angles alone allow
//! Every field of the explicitly supported entities is checked; converted angles and interpolated spline controls allow
//! floating-point roundoff, never wrapping or geometric approximation. Blocks are visited once
//! as stored definitions, not recursively expanded, so cyclic references remain bounded.
//! Header defaults, generated objects and other drawing collections are outside this slice.
@@ -12,8 +12,7 @@ fn equal<T: PartialEq + Debug>(expected: &T, actual: &T, context: &str, field: &
assert_eq!(actual, expected, "{context}.{field}");
}
fn angle(expected: f64, actual: f64, context: &str, field: &str) {
// Two floating-point unit conversions, not a geometric approximation or angle wrapping.
fn roundoff(expected: f64, actual: f64, context: &str, field: &str) {
let tolerance = 8.0 * f64::EPSILON * expected.abs().max(1.0);
assert!(
expected.is_finite() && actual.is_finite() && (actual - expected).abs() <= tolerance,
@@ -144,7 +143,7 @@ fn linetype(expected: Option<&cadcraft_doc::Linetype>, actual: Option<&cadcraft_
equal(shape, &b.shape, &path, "shape");
equal(style, &b.style, &path, "style");
equal(scale, &b.scale, &path, "scale");
angle(*rotation, b.rotation, &path, "rotation");
roundoff(*rotation, b.rotation, &path, "rotation");
equal(offset, &b.offset, &path, "offset");
equal(absolute, &b.absolute, &path, "absolute");
}
@@ -167,8 +166,23 @@ fn entity(expected: &Entity, actual: &Entity, context: &str) {
(EntityKind::Arc(Arc { center, radius, start, end }), EntityKind::Arc(b)) => {
equal(center, &b.center, context, "arc.center");
equal(radius, &b.radius, context, "arc.radius");
angle(*start, b.start, context, "arc.start");
angle(*end, b.end, context, "arc.end");
roundoff(*start, b.start, context, "arc.start");
roundoff(*end, b.end, context, "arc.end");
}
(EntityKind::Spline(a), EntityKind::Spline(b)) if !a.fit.is_empty() => {
// DWG stores the fit points. The decoder interpolates the cubic controls for DXF.
let cadcraft_geom::Spline { degree, knots, control, weights, fit, closed, fit_opts } = a;
equal(degree, &b.degree, context, "spline.degree");
equal(knots, &b.knots, context, "spline.knots");
equal(weights, &b.weights, context, "spline.weights");
equal(fit, &b.fit, context, "spline.fit");
equal(closed, &b.closed, context, "spline.closed");
equal(fit_opts, &b.fit_opts, context, "spline.fit_opts");
equal(&control.len(), &b.control.len(), context, "spline.control.len");
for (p, q) in control.iter().zip(&b.control) {
roundoff(p.x, q.x, context, "spline.control.x");
roundoff(p.y, q.y, context, "spline.control.y");
}
}
(EntityKind::MText(a), EntityKind::MText(b)) => mtext(a, b, context),
(EntityKind::AttDef(a), EntityKind::AttDef(b)) => attrib(a, b, context),
@@ -204,8 +218,21 @@ fn entity(expected: &Entity, actual: &Entity, context: &str) {
fn common(expected: &Common, actual: &Common, context: &str) {
// No `..`: adding a field requires deciding its preservation contract here.
let Common { layer, color, linetype, lineweight, ltscale, transparency, visible, thickness, extrusion, plot_style, anno_scales, xdata } =
expected;
let Common {
layer,
color,
linetype,
lineweight,
ltscale,
transparency,
visible,
thickness,
extrusion,
plot_style,
anno_scales,
anno_moves,
xdata,
} = expected;
equal(layer, &actual.layer, context, "layer");
equal(color, &actual.color, context, "color");
equal(linetype, &actual.linetype, context, "linetype");
@@ -217,6 +244,7 @@ fn common(expected: &Common, actual: &Common, context: &str) {
equal(extrusion, &actual.extrusion, context, "extrusion");
equal(plot_style, &actual.plot_style, context, "plot_style");
equal(anno_scales, &actual.anno_scales, context, "anno_scales");
equal(anno_moves, &actual.anno_moves, context, "anno_moves");
equal(xdata, &actual.xdata, context, "xdata");
}
@@ -226,9 +254,9 @@ fn text(expected: &Text, actual: &Text, context: &str) {
equal(align_pt, &actual.align_pt, context, "align_pt");
equal(height, &actual.height, context, "height");
equal(value, &actual.value, context, "value");
angle(*rotation, actual.rotation, context, "rotation");
roundoff(*rotation, actual.rotation, context, "rotation");
equal(width_factor, &actual.width_factor, context, "width_factor");
angle(*oblique, actual.oblique, context, "oblique");
roundoff(*oblique, actual.oblique, context, "oblique");
equal(style, &actual.style, context, "style");
equal(halign, &actual.halign, context, "halign");
equal(valign, &actual.valign, context, "valign");
@@ -242,7 +270,7 @@ fn mtext(expected: &MText, actual: &MText, context: &str) {
equal(height, &actual.height, context, "mtext.height");
equal(width, &actual.width, context, "mtext.width");
equal(attach, &actual.attach, context, "mtext.attach");
angle(*rotation, actual.rotation, context, "mtext.rotation");
roundoff(*rotation, actual.rotation, context, "mtext.rotation");
equal(style, &actual.style, context, "mtext.style");
equal(contents, &actual.contents, context, "mtext.contents");
equal(line_spacing, &actual.line_spacing, context, "mtext.line_spacing");
@@ -274,7 +302,7 @@ fn insert(expected: &Insert, actual: &Insert, context: &str) {
equal(block, &actual.block, context, "insert.block");
equal(insert, &actual.insert, context, "insert.insert");
equal(scale, &actual.scale, context, "insert.scale");
angle(*rotation, actual.rotation, context, "insert.rotation");
roundoff(*rotation, actual.rotation, context, "insert.rotation");
equal(cols, &actual.cols, context, "insert.cols");
equal(rows, &actual.rows, context, "insert.rows");
equal(col_spacing, &actual.col_spacing, context, "insert.col_spacing");
@@ -375,9 +403,9 @@ fn comparison_rejects_block_and_attribute_dependency_losses() {
#[test]
fn angle_tolerance_does_not_hide_real_changes_or_nonfinite_values() {
angle(0.7, 0.7_f64.to_degrees().to_radians(), "self-test", "angle");
roundoff(0.7, 0.7_f64.to_degrees().to_radians(), "self-test", "angle");
for actual in [0.700001, f64::NAN, f64::INFINITY] {
assert!(std::panic::catch_unwind(|| angle(0.7, actual, "self-test", "angle")).is_err());
assert!(std::panic::catch_unwind(|| roundoff(0.7, actual, "self-test", "angle")).is_err());
}
}
+21 -1
View File
@@ -375,7 +375,27 @@ fn layer_states() {
}
#[test]
fn layouts_and_paperspace() {
collection(collections::layouts(), collections::assert_layouts);
let case = collections::layouts();
for version in Version::ALL {
let mut expected = case.drawing.clone();
if version >= Version::R2007 {
// DWG stores effective viewport lighting from R2007 onward. Preserve it for DXF export.
for layout in expected.layouts.iter_mut() {
let handles: Vec<_> = layout.entities.iter().map(|e| e.handle).collect();
for handle in handles {
layout.entities.modify(handle, |e| {
if let cadcraft_doc::EntityKind::Viewport(v) = &mut e.kind {
v.extra = [(292, "1"), (282, "1"), (141, "0.0"), (142, "0.0")]
.into_iter()
.map(|(code, value)| cadcraft_doc::RawTag { code, value: value.into() })
.collect();
}
});
}
}
}
super::check_version_with(&case.name, &case.drawing, &expected, version, collections::assert_layouts);
}
}
fn with_dimension_styles(cases: Vec<Case>) {
+78 -3
View File
@@ -395,9 +395,69 @@ fn hostile_viewport_ucs_groups_do_not_panic() {
assert_eq!((u.x_axis, u.y_axis), (Vec3::new(1.0, 0.0, 0.0), Vec3::new(0.0, 1.0, 0.0)));
}
#[test]
fn a_viewport_keeps_its_nondefault_style_sheet_and_ucs_icon_origin() {
let (d, h) = base();
let text = cadcraft_io::write_dxf(&d);
let groups = [(1, "monochrome.ctb".into()), (74, "1".into())];
let back = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
let (_, viewport) = the_viewport(&back);
assert!(viewport.extra.iter().any(|t| t.code == 1 && t.value == "monochrome.ctb"));
assert!(viewport.extra.iter().any(|t| t.code == 74 && t.value == "1"));
}
/// An explicit 282=1 selects two lights. A DXF consumer can interpret an omitted 282
/// as one light; keep the authored groups even when they match DWG-generated values.
#[test]
fn explicit_dxf_lighting_survives_save_and_reopen() {
let (d, h) = base();
let text = cadcraft_io::write_dxf(&d);
for (enabled, brightness, ambient) in [("1", "0.0", false), ("0", "0.0", false), ("1", "0.25", false), ("1", "0.0", true)] {
let mut groups = vec![(292, enabled.into()), (282, "1".into()), (141, brightness.into()), (142, "0.0".into())];
if ambient {
groups.push((63, "250".into()));
}
let drawing = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
let saved = cadcraft_io::write_dxf(&drawing);
let native = viewport_record(&saved, h);
for (code, value) in &groups {
assert_eq!(group(&native, &code.to_string()).and_then(num), num(value), "native DXF viewport group {code}");
}
let back = cadcraft_io::read_dxf(saved.as_bytes()).unwrap();
let (_, viewport) = the_viewport(&back);
for (code, value) in &groups {
assert!(viewport.extra.iter().any(|t| t.code == *code && num(&t.value) == num(value)), "{code}: {:?}", viewport.extra);
}
}
}
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
#[test]
fn dwg_preserves_explicit_viewport_lighting() {
cadcraft_io::dwg_worker::allow_in_process();
let (d, h) = base();
let text = cadcraft_io::write_dxf(&d);
for (enabled, brightness) in [("1", "0.0"), ("0", "0.0"), ("1", "0.25")] {
let groups = [(292, enabled.into()), (282, "1".into()), (141, brightness.into()), (142, "0.0".into())];
let drawing = cadcraft_io::read_dxf(inject(&text, h, &groups).as_bytes()).unwrap();
let bytes = cadcraft_io::write_with(
&drawing,
"lighting.dwg",
&cadcraft_io::SaveOptions { version: Some(cadcraft_io::Version::R2010), binary: false },
)
.unwrap();
let back = cadcraft_io::read(&bytes, "lighting.dwg").unwrap();
let (_, viewport) = the_viewport(&back);
for (code, value) in &groups {
let want = num(value).unwrap();
assert!(viewport.extra.iter().any(|t| t.code == *code && num(&t.value) == Some(want)), "{code}: {:?}", viewport.extra);
}
}
}
#[cfg(not(target_arch = "wasm32"))]
#[test]
fn a_default_viewport_reads_back_without_ucs_or_extras() {
fn a_default_dwg_viewport_exports_its_effective_lighting() {
cadcraft_io::dwg_worker::allow_in_process();
for version in [cadcraft_io::Version::R2000, cadcraft_io::Version::R2010] {
let (d, _) = base();
@@ -406,7 +466,17 @@ fn a_default_viewport_reads_back_without_ucs_or_extras() {
let (_, viewport) = the_viewport(&back);
assert!(viewport.ucs.is_none(), "{version}: {:?}", viewport.ucs);
assert!(!viewport.ucs_per_viewport, "{version}");
assert!(viewport.extra.is_empty(), "{version}: {:?}", viewport.extra);
let native = viewport_record(&cadcraft_io::write_dxf(&back), the_viewport(&back).0);
let lighting = [(292, "1"), (282, "1"), (141, "0.0"), (142, "0.0")];
if version >= cadcraft_io::Version::R2007 {
assert_eq!(viewport.extra.len(), lighting.len());
for (code, value) in lighting {
assert_eq!(group(&native, &code.to_string()).and_then(num), num(value), "exported DWG lighting {code}");
}
} else {
assert!(viewport.extra.is_empty(), "{version}: {:?}", viewport.extra);
assert!(group(&native, "282").is_none());
}
}
}
@@ -427,6 +497,11 @@ fn a_viewport_with_non_default_snap_keeps_it() {
for code in [14, 24] {
assert_eq!(viewport.extra.iter().find(|t| t.code == code).and_then(|t| num(&t.value)), Some(2.0), "{version}");
}
assert_eq!(viewport.extra.len(), 2, "only the non-default snap spacing remains: {version}: {:?}", viewport.extra);
let extras = viewport.extra.iter().map(|t| t.code).collect::<Vec<_>>();
let mut expected = vec![14, 24];
if version >= cadcraft_io::Version::R2007 {
expected.extend([292, 282, 141, 142]);
}
assert_eq!(extras, expected, "{version}");
}
}
+11 -2
View File
@@ -65,7 +65,16 @@ fn check(bytes: &[u8], name: &str) -> cadcraft_doc::Drawing {
assert_eq!(proxy.payload.bit_count, 9);
assert_eq!(proxy.payload.data(), [0xA5, 0x80]);
assert_eq!(proxy.graphics.data(), [0x12, 0x34, 0x56]);
let class = classes.get(usize::try_from(proxy.class_id - 500).unwrap()).unwrap();
// The DXF refers to the CLASSES section by ordinal, while the decoder renumbers
// that same proxy against its document class table.
let entities = sections.iter().find(|s| s.name == "ENTITIES").unwrap();
let records = craft_dxf::records(&entities.tags);
let (_, record) = records.iter().find(|(kind, _)| kind == "ACAD_PROXY_ENTITY").unwrap();
let file_id = record.iter().skip_while(|t| t.code != 100 || t.str() != "AcDbProxyEntity").find(|t| t.code == 91).unwrap().i64();
let class = classes.get(usize::try_from(file_id - 500).unwrap()).unwrap();
let decoded_class = decoded.classes.iter().find(|c| i32::from(c.class_number) == proxy.class_id).unwrap();
assert_eq!(decoded_class.dxf_name, "SPDSNOTEPOSITION");
assert_eq!(decoded_class.cpp_class_name, "mcsDbObjectNotePosition");
assert!(class.1.iter().any(|t| t.code == 1 && t.str() == "SPDSNOTEPOSITION"));
assert!(class.1.iter().any(|t| t.code == 2 && t.str() == "mcsDbObjectNotePosition"));
drawing
@@ -121,7 +130,7 @@ fn duplicate_names_keep_distinct_classes_for_entities_and_dictionary_objects() {
cadcraft_io::dwg_worker::allow_in_process();
let source = duplicate_class_dxf();
for binary in [false, true] {
let input = if binary { craft_dxf::write_binary(&craft_dxf::parse(&source).unwrap(), true) } else { source.clone() };
let input = if binary { craft_dxf::write_binary(&craft_dxf::parse(&source).unwrap(), true).unwrap() } else { source.clone() };
let mut drawing = cadcraft_io::read(&input, "source.dxf").unwrap();
for _ in 0..3 {
for name in ["copy.dxf", "copy.dwg"] {
+4
View File
@@ -11,6 +11,10 @@ workspace = true
[dependencies]
craft-mcp = { workspace = true }
craft-jsonrpc = { workspace = true }
# The live client: tool calls go to the open window while the ArtCraft Launcher's switch allows it.
craft-control = { workspace = true, features = ["agents"] }
# The challenge handshake of the window's agent server (`craft_automation::security`; no egui without `ui`).
craft-automation = { workspace = true }
cadcraft-engine = { workspace = true }
cadcraft-render = { workspace = true }
cadcraft-io = { workspace = true }
+107 -4
View File
@@ -2,6 +2,7 @@
use std::io::{BufRead, BufReader, Read, Write};
use std::net::{Ipv4Addr, SocketAddr, TcpStream, ToSocketAddrs};
use std::path::Path;
use std::sync::Arc;
use std::time::Duration;
@@ -18,6 +19,9 @@ pub trait Backend {
fn has_ui(&self) -> bool;
/// Describe the backend connection for client-facing status.
fn describe(&self) -> String;
/// The `agent_folders` tool's answer: the folders this session may open from and save to, and
/// whether files outside them are refused ([`crate::live::folders_reply`]).
fn agent_folders(&mut self) -> Result<Value, String>;
}
/// A running CADCraft app reached through its loopback control port.
@@ -35,6 +39,10 @@ pub struct Remote {
authed: bool,
/// Longest reply line accepted (`MAX_REPLY_LINE`; smaller in tests).
max_reply: usize,
/// The open window's agent server ([`Remote::signed_in`]): each connection signs in once with
/// the challenge handshake and this token, which never crosses the wire. `None`: the `--control`
/// server, which takes the token from its token file on every request.
handshake: Option<String>,
}
/// The port component of a `HOST:PORT` address, for locating the token file.
@@ -42,6 +50,15 @@ fn port_of(addr: &str) -> Option<u16> {
addr.rsplit(':').next().and_then(|p| p.parse::<u16>().ok())
}
/// How long a reply may take; the app answers a request within its own 60 s deadline.
const REPLY_WAIT: Duration = Duration::from_secs(90);
/// How long each sign-in reply of the agent server may take.
const SIGN_IN_WAIT: Duration = Duration::from_secs(10);
/// Longest sign-in reply read (two nonces and a proof).
const SIGN_IN_REPLY: usize = 64 * 1024;
/// How long a launched app has to open its control port.
const LAUNCH_WAIT: Duration = Duration::from_secs(30);
@@ -67,7 +84,17 @@ 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, authed: false, max_reply: MAX_REPLY_LINE };
let mut r = Self::lazy(addr, false);
r.reconnect()?;
Ok(r)
}
/// The open window's agent server at `addr` (`127.0.0.1:<port>` from the connection file the
/// app publishes while the ArtCraft Launcher's switch lets agents in), signed in with the
/// challenge handshake and `token` from the token file it names: the app proves it holds the
/// token before anything derived from it is sent, so a program that took the port of an app
/// that quit learns nothing.
pub fn signed_in(addr: &str, token: String) -> std::io::Result<Self> {
let mut r = Self { handshake: Some(token), ..Self::lazy(addr, false) };
r.reconnect()?;
Ok(r)
}
@@ -75,7 +102,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, authed: false, 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, handshake: None }
}
/// The per-session token for this port, read (and cached) from the owner-only token file. A
@@ -86,6 +113,10 @@ impl Remote {
/// peer: a name that also resolves elsewhere (`localhost` → `::1`, where another local account
/// may listen on the same port) must not be handed the desktop's credential (CWE-522).
fn token(&mut self) -> Option<&str> {
// The agent server took the handshake: no request carries the token.
if self.handshake.is_some() {
return None;
}
let port = port_of(&self.addr)?;
let peer = self.conn.as_ref().and_then(|(_, s)| s.peer_addr().ok());
if peer != Some(SocketAddr::from((Ipv4Addr::LOCALHOST, port))) {
@@ -131,9 +162,12 @@ impl Remote {
match TcpStream::connect_timeout(&sa, Duration::from_millis(800)) {
Ok(s) => {
s.set_nodelay(true).ok();
s.set_read_timeout(Some(Duration::from_secs(90))).ok();
s.set_read_timeout(Some(REPLY_WAIT)).ok();
let read = s.try_clone()?;
self.conn = Some((BufReader::new(read), s));
if let Some(token) = self.handshake.clone() {
return self.sign_in(&token).inspect_err(|_| self.conn = None);
}
return Ok(());
}
Err(e) => last = e,
@@ -141,6 +175,52 @@ impl Remote {
}
Err(last)
}
/// The challenge handshake of the agent server (`craft_automation::security`) on the new
/// connection: send a nonce, check the app's proof that it holds the token, then send this
/// side's proof.
fn sign_in(&mut self, token: &str) -> std::io::Result<()> {
use craft_automation::security::{AUTH_METHOD, CHALLENGE_METHOD, ProofRole, generate_nonce, handshake_proof, proof_matches};
let addr = self.addr.clone();
let refused =
|why: &str| std::io::Error::new(std::io::ErrorKind::PermissionDenied, format!("CADCraft at {addr} refused the agent connection: {why}"));
let client_nonce = generate_nonce().map_err(|e| std::io::Error::other(e.to_string()))?;
let challenge = self.sign_in_frame(CHALLENGE_METHOD, json!({"clientNonce": client_nonce}))?;
if challenge.get("ok") != Some(&Value::Bool(true)) {
return Err(refused(challenge.get("error").and_then(Value::as_str).unwrap_or("no challenge")));
}
let field = |key: &str| challenge.pointer(&format!("/result/{key}")).and_then(Value::as_str).unwrap_or_default().to_string();
let (server_nonce, server_proof) = (field("serverNonce"), field("serverProof"));
if !proof_matches(token, ProofRole::Server, &client_nonce, &server_nonce, &server_proof) {
return Err(std::io::Error::new(
std::io::ErrorKind::PermissionDenied,
format!("the program on {addr} did not prove it is the CADCraft that published the agent connection; start CADCraft again"),
));
}
let proof = handshake_proof(token, ProofRole::Client, &client_nonce, &server_nonce).map_err(|e| std::io::Error::other(e.to_string()))?;
let signed = self.sign_in_frame(AUTH_METHOD, json!({"proof": proof}))?;
if signed.get("ok") != Some(&Value::Bool(true)) {
return Err(refused(signed.get("error").and_then(Value::as_str).unwrap_or("authentication failed")));
}
self.authed = true;
Ok(())
}
/// One sign-in frame (id 0; requests count from 1) and its reply, within [`SIGN_IN_WAIT`].
fn sign_in_frame(&mut self, method: &str, params: Value) -> std::io::Result<Value> {
let addr = self.addr.clone();
let Some((reader, writer)) = self.conn.as_mut() else { return Err(std::io::Error::other("not connected")) };
writer.set_read_timeout(Some(SIGN_IN_WAIT)).ok();
writeln!(writer, "{}", json!({"id": 0, "method": method, "params": params}))?;
writer.flush()?;
let mut reply = String::new();
let n = read_reply_line(reader, &mut reply, SIGN_IN_REPLY)?;
writer.set_read_timeout(Some(REPLY_WAIT)).ok();
if n == 0 {
return Err(std::io::Error::new(std::io::ErrorKind::UnexpectedEof, format!("{addr} closed the connection during the sign-in")));
}
serde_json::from_str(&reply).map_err(|_| {
std::io::Error::new(std::io::ErrorKind::InvalidData, format!("{addr} did not answer the sign-in; is that CADCraft's agent connection?"))
})
}
/// On failure the flag says whether the request may already have reached the server.
fn roundtrip(&mut self, line: &str) -> Result<String, (std::io::Error, bool)> {
if self.conn.is_none() {
@@ -230,6 +310,11 @@ impl Remote {
}
self.set_token(req);
let line = req.to_string();
// The agent server refuses a longer line and closes the connection; nothing was sent.
if self.handshake.is_some() && line.len() > craft_automation::security::MAX_REQUEST_BYTES {
let why = format!("the request is longer than the {} bytes the agent connection takes", craft_automation::security::MAX_REQUEST_BYTES);
return Err((std::io::Error::new(std::io::ErrorKind::InvalidInput, why), false));
}
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);
@@ -333,7 +418,18 @@ impl Backend for Remote {
}
/// What this backend talks to, for messages.
fn describe(&self) -> String {
format!("connected to CADCraft at {}", self.addr)
if self.handshake.is_some() {
format!("the open CADCraft window at {}", self.addr)
} else {
format!("connected to CADCraft at {}", self.addr)
}
}
/// The window's agent server holds requests to Options › AI Agents' folders; `--control` to none.
fn agent_folders(&mut self) -> Result<Value, String> {
if self.handshake.is_some() {
return Err("the window holds agents to the folders of Options › AI Agents; `cadcraft-cli mcp` answers `agent_folders` for it".into());
}
Ok(crate::live::folders_reply(&craft_control::agents::AgentFolders::default(), false))
}
}
@@ -525,6 +621,13 @@ impl Backend for Headless {
fn describe(&self) -> String {
"headless CADCraft session".into()
}
/// The automation roots it runs in, if any.
fn agent_folders(&mut self) -> Result<Value, String> {
let mut folders = craft_control::agents::AgentFolders::default();
folders.read = self.roots.as_ref().and_then(|r| r.read_root().map(Path::to_path_buf));
folders.write = self.roots.as_ref().and_then(|r| r.write_root().map(Path::to_path_buf));
Ok(crate::live::folders_reply(&folders, self.roots.is_some()))
}
}
#[cfg(test)]
+2
View File
@@ -11,10 +11,12 @@
pub mod args;
mod backend;
pub mod control_token;
pub mod live;
mod server;
mod tools;
pub use backend::{Backend, Headless, Remote};
pub use live::{Live, LiveConfig};
pub use server::{PROTOCOL_VERSION, Server};
#[cfg(test)]
+344
View File
@@ -0,0 +1,344 @@
//! Plain `cadcraft-cli mcp` with the suite's `AI-MCP` flag: tools go to the open CADCraft window
//! while the ArtCraft Launcher's switch lets agents use it, found through the connection file the
//! app publishes in its settings folder, and otherwise to a session without a window, as `mcp`
//! always did (`--headless` forces that). The file is read again on every tool call, so the app may
//! start, quit or move to another port while the MCP client stays connected; the client's
//! configuration holds no port and no token.
//!
//! While agents may use the app but it is closed, Options › AI Agents › When CADCraft is closed (or
//! `--when-closed`) decides: start the app and wait for it, work without a window, or an error that
//! says what to do. A session that went headless stays headless for the rest of the MCP session, so
//! the drawing doesn't move under the agent.
//!
//! The lookup is the framework's, shared by every Craft app ([`craft_control::agents::Live`]); this
//! module supplies CADCraft's parts: where its settings are, its window client
//! ([`Remote::signed_in`]) and its headless session ([`Headless`]).
use std::path::{Path, PathBuf};
use std::sync::{Arc, Mutex, PoisonError};
use std::time::Duration;
use cadcraft_engine::agent_settings;
use cadcraft_engine::file_access::AutomationRoots;
use craft_control::agents::{self, AgentFolders, Consent, HeadlessFolders, Route, Window};
use serde_json::{Value, json};
pub use craft_control::agents::{LAUNCH_TIMEOUT, LaunchFn, WhenAppClosed, mcp_flag};
use crate::backend::{Backend, Headless, Remote};
/// The id the ArtCraft Launcher's app list names CADCraft by (its catalog id).
pub const LAUNCHER_APP_ID: &str = "cadcraft";
/// The app's name in the lookup's messages and in its default agent folder,
/// `Documents/ArtCraft/Agents/CADCraft`.
pub const APP_NAME: &str = "CADCraft";
/// The desktop app's file name beside the CLI (without `.exe`).
const APP_EXE: &str = "cadcraft";
/// Whether agents may use the open window now: with the suite's `AI-MCP` flag, the ArtCraft
/// Launcher's switch. CADCraft had no agent consent of its own before the switch (`--control` is a
/// launch option, not a consent), so without the flag agents get no window this way.
pub fn agents_allowed_now() -> bool {
agents::agents_allowed(agents::mcp_flag(), agents::launcher_allows(LAUNCHER_APP_ID), false)
}
/// The default agent folder, `Documents/ArtCraft/Agents/CADCraft`.
pub fn default_folder() -> Option<PathBuf> {
agents::default_folder(APP_NAME)
}
/// The folders the open window holds agent requests to: Options › AI Agents' folders, the default
/// agent folder for an empty one (made when used). The app uses the same.
pub fn window_folders(settings: &agent_settings::AgentSettings, default: Option<&Path>) -> AgentFolders {
settings.folders_with(default)
}
/// The `agent_folders` tool's answer: the folders, and whether files outside them are refused.
pub fn folders_reply(folders: &AgentFolders, confined: bool) -> Value {
let mut answer = agents::folders_answer(folders);
answer["confined"] = json!(confined);
if !confined {
answer["note"] = json!("This session is not held to folders: keep to the files the person gave you.");
}
answer
}
/// What [`Live`] needs from the CLI.
pub struct LiveConfig {
/// The app's settings folder: its connection file, token file and agent settings.
pub config_dir: PathBuf,
/// Overrides the app's closed-app choice (`--when-closed`).
pub when_closed: Option<WhenAppClosed>,
/// The CLI's `--automation-read-root` and `--automation-write-root`.
pub read_root: Option<PathBuf>,
pub write_root: Option<PathBuf>,
/// Starts the app; `None` when this install can't (no app beside the CLI).
pub launch: Option<LaunchFn>,
pub launch_timeout: Duration,
/// Whether the person lets agents use the open app ([`agents_allowed_now`]); tests replace it.
pub allowed: fn() -> bool,
/// The default agent folder for an empty folder setting ([`default_folder`]); tests replace it.
pub default_folder: Option<PathBuf>,
}
impl LiveConfig {
/// The lookup for the app with its settings in `config_dir`.
pub fn new(config_dir: PathBuf) -> Self {
LiveConfig {
config_dir,
when_closed: None,
read_root: None,
write_root: None,
launch: None,
launch_timeout: LAUNCH_TIMEOUT,
allowed: agents_allowed_now,
default_folder: default_folder(),
}
}
}
/// A session without a window and the folders it is held to.
struct HeadlessSession {
backend: Headless,
folders: AgentFolders,
confined: bool,
}
type Shared = agents::Live<Arc<Mutex<Remote>>, Arc<Mutex<HeadlessSession>>>;
/// The backend of plain `cadcraft-cli mcp` with the `AI-MCP` flag: each call goes where
/// [`craft_control::agents::Live::resolve`] says.
pub struct Live {
shared: Shared,
config_dir: PathBuf,
default_folder: Option<PathBuf>,
allowed: fn() -> bool,
}
impl Live {
/// The lookup with `cfg`; nothing is looked up until the first call.
pub fn new(cfg: LiveConfig) -> Self {
let LiveConfig { config_dir, when_closed, read_root, write_root, launch, launch_timeout, allowed, default_folder } = cfg;
let consent = move |dir: &Path| Consent::new(allowed(), agent_settings::load(dir));
let connect = |w: &Window| Remote::signed_in(&w.addr(), w.token.clone()).map(|r| Arc::new(Mutex::new(r))).map_err(|e| e.to_string());
let headless = move |folders: &HeadlessFolders| headless_session(folders, allowed()).map(|h| Arc::new(Mutex::new(h)));
let mut shared = agents::LiveConfig::new(APP_NAME, config_dir.clone(), consent, connect, headless);
shared.when_closed = when_closed;
shared.read_roots = read_root.into_iter().collect();
shared.write_root = write_root;
shared.launch = launch;
shared.launch_timeout = launch_timeout;
shared.default_folder = default_folder.clone();
Live { shared: agents::Live::new(shared), config_dir, default_folder, allowed }
}
}
/// The headless session for `folders`. Without folders it is held to none, as `mcp` always was,
/// unless agents are `allowed`: then the folders are the app's agent folders, and having none
/// (the default folder couldn't be made) refuses every file rather than none.
fn headless_session(folders: &HeadlessFolders, allowed: bool) -> Result<HeadlessSession, String> {
// The CLI takes one read root, and the agent settings name one read folder.
let read = folders.read.first().map(PathBuf::as_path);
let write = folders.write.as_deref();
let roots = match AutomationRoots::new(read, write)? {
Some(roots) => Some(roots),
None if allowed => Some(AutomationRoots::none()),
None => None,
};
let mut shown = AgentFolders::default();
shown.read = read.map(Path::to_path_buf);
shown.write = write.map(Path::to_path_buf);
Ok(HeadlessSession { confined: roots.is_some(), backend: Headless::default().with_automation_roots(roots), folders: shown })
}
impl Backend for Live {
fn call(&mut self, method: &str, params: Value) -> Result<Value, String> {
match self.shared.resolve()? {
Route::Window(window) => window.lock().unwrap_or_else(PoisonError::into_inner).call(method, params),
Route::Headless(session) => session.lock().unwrap_or_else(PoisonError::into_inner).backend.call(method, params),
}
}
/// A window may answer while agents are allowed and the session hasn't gone headless.
fn has_ui(&self) -> bool {
match self.shared.current() {
Some(Route::Window(_)) => true,
Some(Route::Headless(_)) => false,
None => (self.allowed)(),
}
}
fn describe(&self) -> String {
match self.shared.current() {
Some(Route::Window(window)) => window.lock().unwrap_or_else(PoisonError::into_inner).describe(),
Some(Route::Headless(session)) => session.lock().unwrap_or_else(PoisonError::into_inner).backend.describe(),
None => "the open CADCraft window while ArtCraft Launcher › Settings › AI agents lets agents use it, otherwise a headless session".into(),
}
}
fn agent_folders(&mut self) -> Result<Value, String> {
match self.shared.resolve()? {
Route::Window(_) => {
let settings = agent_settings::load(&self.config_dir);
Ok(folders_reply(&window_folders(&settings, self.default_folder.as_deref()), true))
}
Route::Headless(session) => {
let session = session.lock().unwrap_or_else(PoisonError::into_inner);
Ok(folders_reply(&session.folders, session.confined))
}
}
}
}
/// How to start the desktop app that ships with the CLI at `cli` (detached, with no standard
/// streams: the CLI's carry the MCP protocol, and the app must outlive the MCP client).
pub fn launcher(cli: &Path) -> Option<LaunchFn> {
agents::launcher(cli, APP_EXE)
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
use super::*;
use craft_automation::security::{AuthStep, ServerHandshake};
use craft_control::agents::{Connection, TOKEN_FILE, write_connection};
use std::io::{BufRead, BufReader, Write};
use std::net::TcpListener;
const TOKEN: &str = "0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef";
const OTHER: &str = "fedcba9876543210fedcba9876543210fedcba9876543210fedcba9876543210";
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("cadcraft-live-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// A stand-in for the window's agent server (`craft_automation::server`): the challenge
/// handshake with `token`, then every request answered `{"window": true}`. Returns the port and
/// every line it read.
fn agent_server(token: &'static str) -> (u16, Arc<Mutex<Vec<Value>>>) {
let listener = TcpListener::bind("127.0.0.1:0").unwrap();
let port = listener.local_addr().unwrap().port();
let seen = Arc::new(Mutex::new(Vec::new()));
let log = Arc::clone(&seen);
std::thread::spawn(move || {
for conn in listener.incoming() {
let Ok(conn) = conn else { continue };
let log = Arc::clone(&log);
std::thread::spawn(move || {
let mut out = conn.try_clone().unwrap();
let mut handshake = ServerHandshake::new();
let mut signed_in = false;
for line in BufReader::new(conn).lines() {
let Ok(line) = line else { return };
let req: Value = serde_json::from_str(&line).unwrap();
log.lock().unwrap().push(req.clone());
let reply = if signed_in {
json!({"id": req["id"], "ok": true, "result": {"window": true}})
} else {
let (reply, step) = handshake.reply(&line, token);
signed_in = step == AuthStep::Authenticated;
if step == AuthStep::Rejected {
let _ = writeln!(out, "{reply}");
return;
}
reply
};
if writeln!(out, "{reply}").is_err() {
return;
}
}
});
}
});
(port, seen)
}
/// Publish a window on `port` in `dir` with `token` in its token file, as the app's link does.
fn publish(dir: &Path, port: u16, token: &str) {
let token_file = dir.join(TOKEN_FILE);
std::fs::write(&token_file, token).unwrap();
#[cfg(unix)]
{
use std::os::unix::fs::PermissionsExt;
std::fs::set_permissions(&token_file, std::fs::Permissions::from_mode(0o600)).unwrap();
}
write_connection(dir, &Connection::new(port, token_file, "CADCraft test")).unwrap();
}
fn live(dir: &Path, allowed: fn() -> bool, when_closed: Option<WhenAppClosed>) -> Live {
let mut cfg = LiveConfig::new(dir.to_path_buf());
cfg.allowed = allowed;
cfg.when_closed = when_closed;
cfg.default_folder = Some(dir.join("Agents"));
Live::new(cfg)
}
/// With the window published, calls go to it after the challenge handshake, and nothing sent
/// carries the token.
#[test]
fn live_calls_go_to_the_open_window_while_the_switch_allows() {
let dir = temp("window");
let (port, seen) = agent_server(TOKEN);
publish(&dir, port, TOKEN);
let mut live = live(&dir, || true, None);
assert_eq!(live.call("ping", json!({})), Ok(json!({"window": true})));
assert_eq!(live.call("drawing.inspect", json!({})), Ok(json!({"window": true})));
assert!(live.has_ui());
let seen = seen.lock().unwrap();
assert!(seen.iter().any(|req| req["method"] == "drawing.inspect"), "{seen:?}");
assert!(!serde_json::to_string(&*seen).unwrap().contains(TOKEN), "the token crossed the wire: {seen:?}");
drop(seen);
let _ = std::fs::remove_dir_all(dir);
}
/// While the launcher's switch doesn't let agents in and no window is published, calls work
/// without a window, as plain `mcp` always did, held to no folders the command didn't give.
#[test]
fn live_without_the_switch_works_without_a_window() {
let dir = temp("no-switch");
let mut live = live(&dir, || false, None);
assert_eq!(live.call("ping", json!({})), Ok(json!("pong")));
assert!(!live.has_ui());
assert_eq!(live.agent_folders().unwrap()["confined"], json!(false));
let _ = std::fs::remove_dir_all(dir);
}
/// A connection file a crashed app left behind (nothing listens on its port) is not a window:
/// the closed-app choice decides, and a headless session is held to the agent folders.
#[test]
fn live_with_the_app_closed_follows_the_closed_app_choice() {
let dir = temp("closed");
let gone = TcpListener::bind("127.0.0.1:0").unwrap();
let port = gone.local_addr().unwrap().port();
drop(gone);
publish(&dir, port, TOKEN);
let err = live(&dir, || true, Some(WhenAppClosed::Error)).call("ping", json!({})).unwrap_err();
assert!(err.contains("isn't running"), "{err}");
let mut headless = live(&dir, || true, Some(WhenAppClosed::Headless));
assert_eq!(headless.call("ping", json!({})), Ok(json!("pong")));
let folders = headless.agent_folders().unwrap();
assert_eq!(folders["confined"], json!(true));
assert_eq!(folders["write_folder"], json!(dir.join("Agents").to_string_lossy()));
let outside = dir.parent().unwrap().join("outside.png");
let err = headless.call("ui.render", json!({"path": outside.to_string_lossy()})).unwrap_err();
assert!(err.contains("outside the write root"), "a file outside the agent folder is refused: {err}");
let inside = dir.join("Agents").join("plan.png");
assert!(headless.call("ui.render", json!({"path": inside.to_string_lossy()})).is_ok(), "one inside it is written");
let _ = std::fs::remove_dir_all(dir);
}
/// A program on the published port that doesn't hold the token gets nothing from the client:
/// it can't prove itself, so no request is sent.
#[test]
fn a_window_without_the_token_is_refused() {
let dir = temp("bad-token");
let (port, seen) = agent_server(OTHER);
publish(&dir, port, TOKEN);
let err = live(&dir, || true, Some(WhenAppClosed::Error)).call("drawing.inspect", json!({})).unwrap_err();
assert!(err.contains("did not prove"), "{err}");
assert!(seen.lock().unwrap().iter().all(|req| req["method"] != "drawing.inspect"));
let _ = std::fs::remove_dir_all(dir);
}
}
+2
View File
@@ -38,6 +38,7 @@ pub fn tool_definitions(has_ui: bool) -> Value {
json!({"name": "open", "description": "Open a DXF or DWG file.", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}, "required": ["path"]}}),
json!({"name": "save", "description": "Save the drawing (DXF or DWG by extension). A .svg, .png or .pdf path exports instead: the drawing keeps its name and unsaved changes.", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}}),
json!({"name": "cancel", "description": "Press Escape: cancel the running command (or clear the selection).", "inputSchema": {"type": "object", "properties": {}}}),
craft_control::agents::folders_tool(),
];
if has_ui {
tools.push(json!({"name": "screenshot", "description": "Screenshot the CADCraft window (PNG).", "inputSchema": {"type": "object", "properties": {"path": {"type": "string"}}}}));
@@ -137,6 +138,7 @@ pub fn call_tool(b: &mut dyn Backend, name: &str, args: &Value) -> Result<Value,
"open" => b.call("app.open", a),
"save" => b.call("app.save", a),
"cancel" => b.call("cmdline.key", json!({"key": "escape"})),
craft_control::agents::FOLDERS_TOOL => b.agent_folders(),
"screenshot" => b.call("ui.screenshot", a),
"ui_inspect" => b.call("ui.inspect", json!({})),
"ui_click" => b.call("ui.pointer", a),
+83
View File
@@ -0,0 +1,83 @@
//! The contents of a dimension's anonymous `*D` block: the dimension's graphics as plain objects.
use cadcraft_doc::{Common, Dimension, Line, MText, Solid};
use super::{Color, DimGeometry, Drawing, Entity, EntityKind, Handle, LineRole, Vec2, dimension_in};
/// Anonymous dimension blocks (`*D1`…) with the rendered geometry, as consumers expect.
///
/// The entities of the block of dimension `dm` on layer `layer`, with handle 0. The DXF/DWG
/// writer makes the blocks of a saved file with it.
pub fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Vec<Entity> {
// The dimension as drawn: its overrides, DIMSCALE (0 = the drawing's) and text font.
let style = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
let g = dimension_in(d, dm);
let mut out = Vec::new();
// Each part in its style colour (DIMCLRD, DIMCLRE, DIMCLRT), ByBlock when the style says so,
// as AutoCAD writes them: readers that draw the block drew every part ByBlock, i.e. in the
// dimension's own colour (#1052).
let in_color = |color: Color| Common { layer: layer.into(), color, ..Common::default() };
let (dim_c, ext_c, text_c) = (in_color(style.dim_line_color), in_color(style.ext_line_color), in_color(style.text_color));
let line_entities = |i: usize, l: &[Vec2]| -> Vec<Entity> {
let c = match g.line_roles.get(i) {
Some(LineRole::Ext) => &ext_c,
_ => &dim_c,
};
l.windows(2)
.filter_map(|seg| match seg {
[a, b] => Some(Entity { handle: Handle(0), common: c.clone(), kind: EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) }) }),
_ => None,
})
.collect()
};
// The text's marks (arc length symbol, DIMINSPECT frame) go after the text background.
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| !g.text_marks.contains(i)) {
out.extend(line_entities(i, l));
}
for t in &g.fills {
if let [a, b, cc] = t.as_slice() {
out.push(Entity {
handle: Handle(0),
common: dim_c.clone(),
kind: EntityKind::Solid(Solid { corners: [a.to3(0.0), b.to3(0.0), cc.to3(0.0), cc.to3(0.0)] }),
});
}
}
// DIMTFILL 2: the text background in DIMTFILLCLR, under the text and its marks (SOLID
// corners go 1, 2, 4, 3).
if style.text_fill == 2
&& let [p0, p1, p2, p3] = g.text_fill.as_slice()
{
out.push(Entity {
handle: Handle(0),
common: in_color(style.text_fill_color),
kind: EntityKind::Solid(Solid { corners: [p0.to3(0.0), p1.to3(0.0), p3.to3(0.0), p2.to3(0.0)] }),
});
}
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| g.text_marks.contains(i)) {
out.extend(line_entities(i, l));
}
// The text, and the part after `\X` below the dimension line as a second MTEXT, as AutoCAD
// writes it (#1055).
let texts = std::iter::once((g.value.clone(), g.text_pos)).chain(g.below.clone());
for (contents, at) in texts.filter(|(t, _)| !t.is_empty()) {
out.push(Entity {
handle: Handle(0),
common: text_c.clone(),
kind: EntityKind::MText(MText {
insert: at.to3(0.0),
height: g.text_height,
width: 0.0,
attach: 5,
rotation: g.text_angle,
style: style.text_style.clone(),
contents: DimGeometry::mtext_code(&contents),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}),
});
}
out
}
+2 -2
View File
@@ -82,8 +82,8 @@ fn entity_parts(b: &mut Builder, ctx: &Ctx, e: &Entity) {
};
match mode {
cadcraft_doc::AnnoDraw::Hidden => return,
cadcraft_doc::AnnoDraw::Scaled(f) => {
let mut scaled = cadcraft_doc::anno_scaled(e, f);
cadcraft_doc::AnnoDraw::Scaled { factor, by } => {
let mut scaled = cadcraft_doc::anno_placed(e, factor, by);
scaled.common.anno_scales.clear();
return entity_parts(b, ctx, &scaled);
}
+2
View File
@@ -590,6 +590,7 @@ pub use table::{
};
mod blocks;
mod dim_block;
mod dim_draw;
mod display;
mod draw;
@@ -598,6 +599,7 @@ mod props;
mod text_entity;
mod viewports;
pub use dim_block::dim_block_entities;
pub use dim_draw::{dim_text, dimension_in};
pub use display::{DImage, DPrim, DisplayList, Kind, MAX_TRANSPARENCY, NO_LAYER, PlotText, VIEWPORT_CONTENT, alpha};
pub use pipeline::{Options, build, build_entities, build_entities_in_viewport, build_plot};
+5 -2
View File
@@ -37,6 +37,9 @@ web-time = { workspace = true }
[target.'cfg(not(target_arch = "wasm32"))'.dependencies]
craft-update = { workspace = true }
# Agents in the open window: the agent link host and the Agents page of Options.
craft-automation = { workspace = true, features = ["ui", "agents"] }
craft-control = { workspace = true, features = ["agents"] }
[dev-dependencies]
# `Updater::ready_for_tests`.
@@ -44,8 +47,8 @@ craft-update = { workspace = true, features = ["screen-testing"] }
# The workspace `egui` dependency enables `default_fonts` and `monochrome_emoji_fonts` in
# production too; the tests exercise the same installed chain as the app.
egui_kittest = { workspace = true, features = ["wgpu", "snapshot"] }
# Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) translation in tests (same naga wgpu uses).
naga = { version = "30", features = ["wgsl-in", "glsl-out"] }
# Validates the canvas WGSL and its GLSL ES 3.0 (WebGL2) and Metal translations in tests (same naga wgpu uses).
naga = { version = "30", features = ["wgsl-in", "glsl-out", "msl-out"] }
[build-dependencies]
serde_json = { workspace = true }
+487
View File
@@ -0,0 +1,487 @@
//! Agents in the open window. While the ArtCraft Launcher's switch (Settings › AI agents) lets agents
//! use CADCraft, the app serves its control channel on loopback for them, with a token kept in its
//! settings folder, and publishes where in `agent-connection.json` beside it; `cadcraft-cli mcp`
//! reads that file on every tool call. When the switch turns off, the server stops and the file
//! goes, without a restart. The link, the switch and the Agents page are the framework's
//! (`craft_automation::agents`, `craft_automation::ui::agents`); CADCraft runs the requests through
//! its own control methods ([`crate::control::handle`]), held to the agent folders of Options › AI
//! Agents ([`Agents::roots`]), as the headless server is held to its automation roots.
//!
//! `cadcraft --control` manages its own server for the whole run instead; the Agents page then says
//! the launch options manage the connection.
use std::path::{Path, PathBuf};
use std::sync::Arc;
use std::sync::mpsc::Receiver;
use std::time::{Duration, Instant};
use cadcraft_engine::agent_settings::{self, AgentSettings};
use cadcraft_engine::file_access::AutomationRoots;
use craft_automation::agents::{AgentLink, AgentLinkStatus, AgentSwitch, LinkProblem};
use craft_ui::runtime::windows::WindowHost;
use serde_json::{Value, json};
use crate::control::ControlRequest;
/// The agent link, the switch it follows, the agent settings and the requests of the server it runs.
pub struct Agents {
link: Option<AgentLink>,
switch: Option<AgentSwitch>,
requests: Option<Receiver<craft_automation::ControlRequest>>,
/// `--control` runs a server of its own: the page names the launch options.
launch_flags: Option<u16>,
/// Where the agent settings are saved; `None`: nowhere (no settings folder).
settings_dir: Option<PathBuf>,
settings: AgentSettings,
/// The default agent folder for an empty folder setting, `Documents/ArtCraft/Agents/CADCraft`.
default_folder: Option<PathBuf>,
/// What agent requests may read and write, from the settings' folders.
roots: Arc<AutomationRoots>,
/// Another CADCraft window with the same settings folder serves agents: this one waits, and
/// takes over once that window has closed ([`Self::sync`]).
other_window: bool,
/// When the last look for another window was, and how often to look.
looked: Option<Instant>,
look_every: Duration,
/// The app named in a connection this window publishes again ([`Self::sync`]).
app: String,
/// The AI Agents tab was shown in a pass with agent folders in force (an agent opened or drove
/// it): until the person shows it afresh, nothing typed there is saved, also when a later pass
/// commits it ([`Self::page_shown`]).
page_tainted: bool,
/// The frame the tab was last shown in.
page_frame: Option<u64>,
}
/// How often a window that waits for another one looks whether that one has closed.
const LOOK_EVERY: Duration = Duration::from_secs(2);
/// Whether another running CADCraft window has published the agent connection in `dir`: one this
/// window must not replace, or closing it would leave that window unreachable.
fn other_window_serves(dir: &Path) -> bool {
use craft_control::agents::{PROBE_TIMEOUT, probe, read_connection};
read_connection(dir).ok().flatten().is_some_and(|c| c.pid != std::process::id() && probe(c.port, PROBE_TIMEOUT))
}
impl Default for Agents {
/// No link: agents get no window (a Nightly build, the tests).
fn default() -> Self {
Agents {
link: None,
switch: None,
requests: None,
launch_flags: None,
settings_dir: None,
settings: AgentSettings::default(),
default_folder: None,
roots: AutomationRoots::none(),
other_window: false,
looked: None,
look_every: LOOK_EVERY,
app: format!("CADCraft {}", cadcraft_engine::build_version()),
page_tainted: false,
page_frame: None,
}
}
}
impl Agents {
/// The link the app runs while `switch` lets agents in, with the agent settings saved in
/// `settings_dir`.
pub fn new(link: AgentLink, switch: AgentSwitch, settings_dir: Option<PathBuf>) -> Self {
let settings = settings_dir.as_deref().map(agent_settings::load).unwrap_or_default();
Agents {
link: Some(link),
switch: Some(switch),
settings_dir,
settings,
default_folder: craft_control::agents::default_folder("CADCraft"),
..Agents::default()
}
}
/// `cadcraft --control <port>` serves the control channel for the whole run: no agent link.
pub fn managed_by_launch(port: u16, switch: AgentSwitch, settings_dir: Option<PathBuf>) -> Self {
let settings = settings_dir.as_deref().map(agent_settings::load).unwrap_or_default();
Agents { switch: Some(switch), launch_flags: Some(port), settings_dir, settings, ..Agents::default() }
}
/// [`LOOK_EVERY`] replaced by `every` (tests).
#[doc(hidden)]
pub fn look_every(mut self, every: Duration) -> Self {
self.look_every = every;
self
}
/// The default agent folder replaced by `folder` (tests).
#[doc(hidden)]
pub fn with_default_folder(mut self, folder: Option<PathBuf>) -> Self {
self.default_folder = folder;
self
}
/// Where the link stands, for the Agents page and `ui.inspect`.
pub fn status(&self) -> AgentLinkStatus {
let mut status = self.link.as_ref().map(|link| link.status().clone()).unwrap_or_default();
if let Some(port) = self.launch_flags {
status.launch_flags = true;
status.port = Some(port);
} else if self.other_window && status.port.is_none() {
status.problem =
Some(LinkProblem::App("Another CADCraft window takes the agents; this one takes over when that window closes.".to_string()));
}
status
}
/// The suite's `AI-MCP` flag: the Agents page points to the launcher's switch.
pub fn mcp_flag(&self) -> bool {
self.switch.as_ref().is_some_and(AgentSwitch::mcp_flag)
}
/// Whether the launcher's switch lets agents use CADCraft now.
pub fn allowed(&self) -> bool {
// CADCraft had no consent of its own before the switch.
self.switch.as_ref().is_some_and(|switch| switch.allows(false))
}
/// The agent settings of Options › AI Agents.
pub fn settings(&self) -> &AgentSettings {
&self.settings
}
/// Options › AI Agents changed: save the settings for `cadcraft-cli mcp` too. The next
/// [`Self::sync`] applies them (another port, other folders). No command reaches this, and
/// while agent folders are in force (an agent request, or the frames that handle input an agent
/// queued, `CadApp::agent_input_roots`) it refuses, so an agent can't widen its own folders by
/// clicking and typing in the tab either.
pub fn set_settings(&mut self, settings: AgentSettings) -> Result<(), String> {
if self.page_tainted {
return Err(
"An AI agent used the AI Agents settings while they were open, so changes made there aren't saved; close Options, open it again and make the change yourself".to_string(),
);
}
if cadcraft_engine::file_access::current().is_some() {
return Err(
"The AI Agents settings can't be saved while an AI agent's work is running in CADCraft; save them again once it has finished"
.to_string(),
);
}
let saved = match &self.settings_dir {
Some(dir) => agent_settings::save(dir, &settings).map_err(|e| format!("couldn't save the agent settings: {e}")),
None => Err("couldn't save the agent settings: CADCraft has no settings folder".to_string()),
};
self.settings = settings;
saved
}
/// The AI Agents tab is shown in `frame`. Shown in a pass with agent folders in force (an agent
/// request or input), it stays tainted, refusing every save, until the person shows it afresh
/// (after a frame it wasn't shown in) with no agent folders in force.
pub(crate) fn page_shown(&mut self, frame: u64) {
let afresh = self.page_frame.is_none_or(|last| frame > last.saturating_add(1));
self.page_frame = Some(frame);
if cadcraft_engine::file_access::current().is_some() {
self.page_tainted = true;
} else if afresh {
self.page_tainted = false;
}
}
/// What agent requests may read and write.
pub fn roots(&self) -> Arc<AutomationRoots> {
Arc::clone(&self.roots)
}
/// `ui.inspect`'s `agents`: the link's status, the flag and the switch.
pub fn inspect(&self) -> Value {
let mut v = serde_json::to_value(self.status()).unwrap_or_default();
v["mcpFlag"] = json!(self.mcp_flag());
v["allowed"] = json!(self.allowed());
v
}
/// Once per frame: brings the link in line with the switch and Options › AI Agents (start, move,
/// stop, or nothing while neither changed), rebuilds the folders agent requests are held to when
/// that changed, then hands over the requests its server received as the app's own control
/// requests. A request whose client already gave up is dropped.
pub(crate) fn sync(&mut self, ctx: &egui::Context) -> Vec<ControlRequest> {
let allowed = self.allowed();
let Some(link) = self.link.as_mut() else { return Vec::new() };
// Before this window starts serving agents: another window that already does keeps the
// connection, and this one looks again now and then to take over once it has closed.
if allowed && link.status().port.is_none() {
let due = self.looked.is_none_or(|at| at.elapsed() >= self.look_every);
if due {
self.looked = Some(Instant::now());
self.other_window = self.settings_dir.as_deref().is_some_and(other_window_serves);
}
if self.other_window {
ctx.request_repaint_after(self.look_every);
return Vec::new();
}
}
let update = link.sync(allowed.then_some(&self.settings), &WindowHost::of(ctx));
if update.changed {
let folders = self.settings.folders_with(self.default_folder.as_deref());
let (roots, problem) = agent_settings::roots(folders.read.as_deref(), folders.write.as_deref());
self.roots = roots;
if let Some(problem) = problem {
log::warn!("agent folders: {problem}");
link.note(LinkProblem::App(format!("Agents can't use a folder: {problem}")));
}
}
// After the sync, so the frame that starts the server schedules its first check too.
// While serving: two windows that started at the same moment may both serve, and the
// connection names only one. If that one has closed (no file, or one nothing answers on),
// this window publishes its own again, so agents still find an open window.
if let (true, Some(port), Some(dir)) = (allowed, self.link.as_ref().and_then(|l| l.status().port), self.settings_dir.as_deref()) {
if self.looked.is_none_or(|at| at.elapsed() >= self.look_every) {
self.looked = Some(Instant::now());
let ours = craft_control::agents::read_connection(dir).ok().flatten().is_some_and(|c| c.pid == std::process::id() && c.port == port);
if !ours && !other_window_serves(dir) {
let connection = craft_control::agents::Connection::new(port, dir.join(craft_control::agents::TOKEN_FILE), self.app.clone());
if let Err(e) = craft_control::agents::write_connection(dir, &connection) {
log::warn!("couldn't publish the agent connection again: {e}");
}
}
}
// The next look runs even while nothing else draws a frame.
let since = self.looked.map_or(Duration::ZERO, |at| at.elapsed());
ctx.request_repaint_after(self.look_every.saturating_sub(since));
}
if update.stopped {
self.requests = None;
}
if let Some(requests) = update.requests {
self.requests = Some(requests);
}
let Some(requests) = &self.requests else { return Vec::new() };
requests.try_iter().filter(|req| req.dispatch.start()).map(|req| ControlRequest::with_reply(req.method, req.params, req.reply)).collect()
}
}
#[cfg(test)]
mod tests {
use super::*;
use craft_automation::agents::{TOKEN_FILE, read_connection};
use craft_automation::client::ControlClient;
use std::time::{Duration, Instant};
fn temp(name: &str) -> PathBuf {
let dir = std::env::temp_dir().join(format!("cadcraft-agents-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// The link follows the launcher's switch without a restart: on, it listens and publishes the
/// connection, and a client's request reaches the app as one of its own control requests, its
/// reply going back to that client; off, it stops and the connection file goes.
#[test]
fn the_link_follows_the_switch_and_hands_requests_to_the_app() {
let dir = temp("switch");
let ctx = egui::Context::default();
let link = AgentLink::new(Some(dir.clone()), "CADCraft test");
let mut agents = Agents::new(link, AgentSwitch::fixed(true, true), Some(dir.clone())).with_default_folder(Some(dir.join("agents")));
assert!(agents.sync(&ctx).is_empty());
let port = agents.status().port.expect("listening while the switch allows");
assert!(read_connection(&dir).unwrap().is_some_and(|c| c.port == port));
let token = std::fs::read_to_string(dir.join(TOKEN_FILE)).unwrap().trim().to_string();
let client = std::thread::spawn(move || {
ControlClient::connect(([127, 0, 0, 1], port).into(), &token).map_err(|e| format!("{e:?}"))?.call("ping", json!({}))
});
let deadline = Instant::now() + Duration::from_secs(20);
let req = loop {
if let Some(req) = agents.sync(&ctx).pop() {
break req;
}
assert!(Instant::now() < deadline, "the request never reached the app");
std::thread::sleep(Duration::from_millis(10));
};
assert_eq!(req.method, "ping");
req.reply.send(json!({"ok": true, "result": "pong"})).unwrap();
assert_eq!(client.join().unwrap(), Ok(json!("pong")));
agents.switch = Some(AgentSwitch::fixed(true, false));
agents.sync(&ctx);
assert_eq!(agents.status().port, None, "stopped when the switch turned off");
assert!(read_connection(&dir).unwrap().is_none(), "and its connection file is gone");
let _ = std::fs::remove_dir_all(dir);
}
/// A second window with the same settings folder doesn't replace the first one's connection
/// (closing it would leave the first unreachable); it takes over once the first has closed.
#[test]
fn a_second_window_waits_for_the_first_and_takes_over() {
let dir = temp("two-windows");
let ctx = egui::Context::default();
let window = || {
Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(true, true), Some(dir.clone()))
.with_default_folder(Some(dir.join("agents")))
.look_every(Duration::ZERO)
};
let mut first = window();
first.sync(&ctx);
let port = first.status().port.expect("the first window serves agents");
// The second window runs in this process too: name another process in the first's file.
let mut published = read_connection(&dir).unwrap().unwrap();
published.pid = std::process::id().wrapping_add(1);
craft_control::agents::write_connection(&dir, &published).unwrap();
let mut second = window();
second.sync(&ctx);
assert_eq!(second.status().port, None, "the second waits");
assert!(second.status().problem.is_some(), "and says why");
assert_eq!(read_connection(&dir).unwrap().map(|c| c.port), Some(port), "the first's connection stays");
drop(first);
let _ = std::fs::remove_file(dir.join(craft_control::agents::CONNECTION_FILE));
second.sync(&ctx);
let taken = second.status().port.expect("the second takes over once the first has closed");
assert_eq!(read_connection(&dir).unwrap().map(|c| c.port), Some(taken));
drop(second);
let _ = std::fs::remove_dir_all(dir);
}
/// Two windows that started at the same moment both serve; when the one the connection names
/// closes, the other publishes its own connection again.
#[test]
fn the_window_left_publishes_again_after_a_race() {
let dir = temp("race");
let ctx = egui::Context::default();
let window = || {
Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(true, true), Some(dir.clone()))
.with_default_folder(Some(dir.join("agents")))
.look_every(Duration::ZERO)
};
let (mut first, mut second) = (window(), window());
first.sync(&ctx);
let first_port = first.status().port.unwrap();
// The race: the second checked before the first published, so it serves too and replaces the file.
let _ = std::fs::remove_file(dir.join(craft_control::agents::CONNECTION_FILE));
second.sync(&ctx);
let second_port = second.status().port.unwrap();
assert_eq!(read_connection(&dir).unwrap().map(|c| c.port), Some(second_port));
drop(second);
assert!(read_connection(&dir).unwrap().is_none(), "the closed window took its connection with it");
first.sync(&ctx);
assert_eq!(read_connection(&dir).unwrap().map(|c| c.port), Some(first_port), "the window left publishes again");
drop(first);
let _ = std::fs::remove_dir_all(dir);
}
/// A serving window asks for a frame by its next look, so it publishes again after the other
/// window closed even when nothing else in the app draws.
#[test]
fn a_serving_window_schedules_its_next_look() {
let dir = temp("schedule");
let ctx = egui::Context::default();
let every = Duration::from_secs(30);
let mut agents = Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(true, true), Some(dir.clone()))
.with_default_folder(Some(dir.join("agents")))
.look_every(every);
// Idle frames first: a fresh context asks for a few of its own.
let delay = |out: &mut egui::FullOutput| {
out.textures_delta.clear();
out.viewport_output.get(&egui::ViewportId::ROOT).map_or(Duration::MAX, |v| v.repaint_delay)
};
let mut idle = Duration::ZERO;
for _ in 0..4 {
idle = delay(&mut ctx.run_ui(egui::RawInput::default(), |_| {}));
}
assert_eq!(idle, Duration::MAX, "the warmed-up idle context asks for no frame");
// The frame that starts the server schedules the first look, with no other frames run.
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
agents.sync(ui.ctx());
});
assert!(agents.status().port.is_some());
let first = delay(&mut out);
assert!(first <= every, "the startup frame schedules the first look: {first:?}");
// And each later idle frame the next one.
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
agents.sync(ui.ctx());
});
let next = delay(&mut out);
assert!(next <= every, "the next look is scheduled: {next:?}");
drop(agents);
let _ = std::fs::remove_dir_all(dir);
}
/// The AI Agents tab an agent opened or drove saves nothing, also from a later pass with no
/// agent folders in force (a field committing on focus loss), until the person shows it afresh.
#[test]
fn a_tab_an_agent_used_saves_nothing_until_shown_afresh() {
let dir = temp("taint");
let mut agents = Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(true, true), Some(dir.clone()));
let mut wider = agents.settings().clone();
wider.read_root = "/".into();
agents.page_shown(1);
let roots = AutomationRoots::none();
cadcraft_engine::file_access::confine(Some(&roots), || agents.page_shown(2));
agents.page_shown(3);
assert!(agents.set_settings(wider.clone()).is_err(), "a later unconfined pass of the same showing");
assert_ne!(agent_settings::load(&dir), wider);
agents.page_shown(6);
agents.set_settings(wider.clone()).unwrap();
assert_eq!(agent_settings::load(&dir), wider, "shown afresh by the person");
let _ = std::fs::remove_dir_all(dir);
}
/// While agent folders are in force (an agent's request or input), the agent settings can't be
/// changed, also not through the Options tab.
#[test]
fn agents_cannot_change_the_agent_settings() {
let dir = temp("refuse");
let mut agents = Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(true, true), Some(dir.clone()));
let mut wider = agents.settings().clone();
wider.write_root = "/".into();
let roots = AutomationRoots::none();
assert!(cadcraft_engine::file_access::confine(Some(&roots), || agents.set_settings(wider.clone())).is_err());
assert_ne!(agents.settings(), &wider);
assert_ne!(agent_settings::load(&dir), wider, "nothing saved");
agents.set_settings(wider.clone()).unwrap();
assert_eq!(agent_settings::load(&dir), wider, "the person can");
let _ = std::fs::remove_dir_all(dir);
}
/// Without the suite's `AI-MCP` flag CADCraft takes no agents this way: it had no consent of
/// its own before the launcher's switch.
#[test]
fn without_the_flag_nothing_listens() {
let dir = temp("no-flag");
let mut agents = Agents::new(AgentLink::new(Some(dir.clone()), "CADCraft test"), AgentSwitch::fixed(false, true), Some(dir.clone()));
agents.sync(&egui::Context::default());
assert_eq!(agents.status().port, None);
assert!(read_connection(&dir).unwrap().is_none());
let _ = std::fs::remove_dir_all(dir);
}
/// Agent requests are held to the agent folders, and a new folder in Options › AI Agents applies
/// while the link runs; what the dialog saves is what `cadcraft-cli mcp` reads.
#[test]
fn agent_requests_are_held_to_the_agent_folders() {
use cadcraft_engine::file_access::{check_read, check_write, confine};
let dir = temp("folders");
let (inbox, other) = (dir.join("inbox"), dir.join("other"));
std::fs::create_dir_all(&inbox).unwrap();
std::fs::create_dir_all(&other).unwrap();
let ctx = egui::Context::default();
let link = AgentLink::new(Some(dir.clone()), "CADCraft test");
let mut agents = Agents::new(link, AgentSwitch::fixed(true, true), Some(dir.clone())).with_default_folder(Some(inbox.clone()));
agents.sync(&ctx);
let roots = agents.roots();
confine(Some(&roots), || {
assert!(check_write(inbox.join("plan.dxf")).is_ok(), "the default agent folder");
assert!(check_read(other.join("plan.dxf")).is_err(), "nothing outside it");
});
let mut settings = agents.settings().clone();
settings.write_root = other.display().to_string();
agents.set_settings(settings.clone()).unwrap();
agents.sync(&ctx);
let roots = agents.roots();
confine(Some(&roots), || assert!(check_write(other.join("plan.dxf")).is_ok(), "the new write folder applies at once"));
assert_eq!(agent_settings::load(&dir), settings);
drop(agents);
let _ = std::fs::remove_dir_all(dir);
}
}
+2 -2
View File
@@ -62,7 +62,7 @@ pub(super) fn draw_selection_grips(app: &mut CadApp, painter: &egui::Painter, xf
if let Some(e) = st.doc.entity(*h)
&& st.shows(e)
{
let grips = e.kind.grips();
let grips = cadcraft_engine::grips::shown_grips(&st.doc, e, st.anno_view());
let count = grips.len();
for (gi, g) in grips.into_iter().enumerate() {
let sp = xf.to_screen(g);
@@ -182,7 +182,7 @@ pub(super) fn grip_at(app: &CadApp, xf: &Xf, hover: Option<Pos2>) -> Option<(Han
if !st.shows(e) || st.doc.layer(&e.common.layer).is_some_and(|l| l.locked) {
continue;
}
let grips = e.kind.grips();
let grips = cadcraft_engine::grips::shown_grips(&st.doc, e, st.anno_view());
let count = grips.len();
for (i, g) in grips.into_iter().enumerate() {
let sp = xf.to_screen(g);
+15 -4
View File
@@ -44,13 +44,25 @@ const TOOLBAR: &[&[(Icon, &str, &str, Option<&str>)]] = &[
/// Height of the macOS integrated title row (#161): the standard 28 pt title-bar band AppKit centres the traffic
/// lights in.
const MAC_TITLE_BAR: f32 = 28.0;
/// Height of the framework's title bar where it carries the window buttons (GNOME on Wayland, [`crate::title_bar`]):
/// the framework theme's `size.bar.title`.
const INTEGRATED_TITLE_BAR: f32 = 38.0;
/// The width of the toolbar's More button.
const MORE_WIDTH: f32 = 30.0;
/// Title row (with the integrated macOS title bar) and the Tool Bar.
/// Title row (with the integrated macOS title bar, or the framework's title bar with the window buttons where the
/// desktop leaves the frame to the app) and the Tool Bar.
pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
let t = Tokens::get();
let title_h = if app.integrated_titlebar { MAC_TITLE_BAR } else { 0.0 };
let mac = ui.ctx().os().is_mac();
// In full screen the framework's bar shows no window buttons, so the row goes too; the macOS row is unchanged.
let fullscreen = ui.ctx().input(|i| i.viewport().fullscreen.unwrap_or(false));
let title_h = match (app.integrated_titlebar, mac) {
(false, _) => 0.0,
(true, true) => MAC_TITLE_BAR,
(true, false) if fullscreen => 0.0,
(true, false) => INTEGRATED_TITLE_BAR,
};
let tb_h = if app.ui.show_toolbar { 34.0 } else { 0.0 };
egui::Panel::top("cc_title_toolbar").exact_size(title_h + tb_h).frame(egui::Frame::NONE.fill(t.chrome)).show(ui, |ui| {
let r = ui.max_rect();
@@ -70,10 +82,9 @@ pub fn title_and_toolbar(app: &mut CadApp, ui: &mut egui::Ui) {
}
if tb_h > 0.0 {
let row = Rect::from_min_size(pos2(r.left(), r.top() + title_h), vec2(r.width(), tb_h));
let mut x = r.left() + if app.integrated_titlebar { 120.0 } else { 12.0 };
let mut x = r.left() + if app.integrated_titlebar && mac { 120.0 } else { 12.0 };
let size = 26.0;
let mut clicked = None;
let mac = ui.ctx().os().is_mac();
let widths: Vec<_> = TOOLBAR.iter().map(|group| group.len() as f32 * (size + 6.0) - 6.0).collect();
let available = (row.right() - 12.0 - x).max(0.0);
let items: Vec<_> = widths.iter().enumerate().map(|(i, w)| FitItem::new(*w, i as u16, FitKeep::Free)).collect();
+30 -1
View File
@@ -55,6 +55,12 @@ impl ControlRequest {
(Self { method: method.into(), params, reply: tx, state: state.clone() }, PendingReply { rx, state })
}
/// A request from another transport that waits for `reply` itself (the agent link's server,
/// [`crate::agents`]), which has already claimed it to run.
pub fn with_reply(method: impl Into<String>, params: Value, reply: Sender<ControlResponse>) -> Self {
Self { method: method.into(), params, reply, state: Arc::new(AtomicU8::new(QUEUED)) }
}
/// Mark the request as started. False when the transport already gave up on it
/// ([`PendingReply::wait`] timed out): the app must then skip it, since the client was told it
/// did not run and may send it again.
@@ -291,10 +297,23 @@ pub fn inspect(app: &CadApp, ctx: &egui::Context) -> Value {
"snap": app.canvas.snap.map(|s| json!({"point": [s.point.x, s.point.y], "mode": s.name})),
"session": app.session.summary(),
"closePrompt": app.close_prompt(),
"agents": agents_json(app),
"perf": {"frameMs": app.frame_ms, "buildMs": app.canvas.build_ms, "drawMs": app.canvas.draw_ms, "meshMs": app.canvas.mesh_ms, "building": app.canvas.building(), "renderer": if app.canvas.gpu.is_some() { "gpu" } else { "cpu" }, "prims": app.canvas.list.as_ref().map(|l| l.prims.len()), "truncated": app.canvas.list.as_ref().map(|l| l.truncated), "uiFrames": app.ui_frames, "passIndex": ctx.current_pass_index()},
})
}
/// The agent link's state for `ui.inspect` (`port`, `launchFlags`, `error`, `mcpFlag`, `allowed`).
#[cfg(not(target_arch = "wasm32"))]
fn agents_json(app: &CadApp) -> Value {
app.agents.inspect()
}
/// The browser build takes no agents this way.
#[cfg(target_arch = "wasm32")]
fn agents_json(_: &CadApp) -> Value {
Value::Null
}
fn key_from(name: &str) -> Option<egui::Key> {
egui::Key::from_name(name).or(match name.to_ascii_lowercase().as_str() {
"enter" | "return" => Some(egui::Key::Enter),
@@ -503,7 +522,14 @@ fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -
ctx.send_viewport_cmd(egui::ViewportCommand::InnerSize(egui::vec2(w as f32, h as f32)));
ok(Value::Null)
}
"ui.screenshot" => Outcome::Screenshot { path: s("path").map(str::to_string) },
"ui.screenshot" => {
// Agents in the window write only in their folders (`file_access`; nothing is checked
// for `--control`).
if let Some(Err(e)) = s("path").map(cadcraft_engine::file_access::check_write) {
return err(e);
}
Outcome::Screenshot { path: s("path").map(str::to_string) }
}
"ui.render" => {
let w = f("width").unwrap_or(1600.0).clamp(16.0, 8192.0) as u32;
let h = f("height").unwrap_or(1000.0).clamp(16.0, 8192.0) as u32;
@@ -534,6 +560,9 @@ fn handle_request(app: &mut CadApp, ctx: &egui::Context, req: &ControlRequest) -
};
#[cfg(not(target_arch = "wasm32"))]
if let Some(path) = s("path") {
if let Err(e) = cadcraft_engine::file_access::check_write(path) {
return err(e);
}
let file = std::path::Path::new(&path);
let folder = cadcraft_engine::atomic_write::missing_folder(file);
if let Err(e) = cadcraft_engine::atomic_write::write_atomic_making_folders(file, &png) {
+9 -2
View File
@@ -37,14 +37,21 @@ pub struct UiFault {
impl CadApp {
/// [`CadApp::logic`] under the panic guard.
pub fn guarded_logic(&mut self, ctx: &egui::Context) {
self.guarded(ctx, |app| app.logic(ctx));
let roots = self.agent_input_roots.clone();
cadcraft_engine::file_access::confine(roots.as_ref(), || self.guarded(ctx, |app| app.logic(ctx)));
}
/// [`CadApp::ui`] under the panic guard, then the notice about any panic. Once the interface
/// has been given up on, only the window that closes the app is drawn.
pub fn guarded_ui(&mut self, ui: &mut egui::Ui) {
let ctx = ui.ctx().clone();
self.guarded(&ctx, |app| app.ui(ui));
let roots = self.agent_input_roots.clone();
cadcraft_engine::file_access::confine(roots.as_ref(), || self.guarded(&ctx, |app| app.ui(ui)));
// The input an agent queued has been handled and its LISP routine has ended: what the
// person does next is theirs.
if self.synthetic.is_empty() && !self.synthetic_injected && !self.session.lisp_running() {
self.agent_input_roots = None;
}
self.show_fault(&ctx);
}
+28
View File
@@ -1100,6 +1100,34 @@ mod tests {
}
}
/// The patched wgpu-hal (vendor/wgpu-hal, #1631) compiles with the newest Metal language the
/// Mac's compiler accepts, which can be as old as macOS 11's (2.3, LSMinimumSystemVersion in
/// packaging/macos/Info.plist.in), so the canvas shader must still translate at that version.
#[test]
#[allow(clippy::unwrap_used)]
fn shader_translates_for_the_oldest_metal_the_app_supports() {
let module = naga::front::wgsl::parse_str(SHADER).unwrap();
let info = naga::valid::Validator::new(naga::valid::ValidationFlags::all(), naga::valid::Capabilities::empty()).validate(&module).unwrap();
for (stage, entry) in
[(naga::ShaderStage::Vertex, "vs_line"), (naga::ShaderStage::Vertex, "vs_quad"), (naga::ShaderStage::Fragment, "fs_main")]
{
let options = naga::back::msl::Options { lang_version: (2, 3), ..Default::default() };
let pipeline = naga::back::msl::PipelineOptions { entry_point: Some((stage, entry.into())), ..Default::default() };
let (out, _) = naga::back::msl::write_string(&module, &info, &options, &pipeline).unwrap();
assert!(out.contains(entry), "{entry}");
}
}
/// A wgpu bump leaves the `[patch.crates-io]` copy of wgpu-hal unused (Cargo only warns) and
/// brings #1631 back: older Macs would ask the Metal compiler for a version it rejects again.
/// See vendor/wgpu-hal/CADCRAFT.md.
#[test]
fn wgpu_hal_is_the_patched_copy() {
let lock = include_str!("../../../Cargo.lock").replace("\r\n", "\n");
let hal: Vec<&str> = lock.split("[[package]]").filter(|p| p.contains("\nname = \"wgpu-hal\"\n")).collect();
assert!(!hal.is_empty() && hal.iter().all(|p| !p.contains("\nsource = ")), "wgpu-hal comes from a registry, not vendor/wgpu-hal");
}
/// `prims` polylines of `points` points each (all over the same vertices).
fn polylines(prims: usize, points: usize) -> DisplayList {
let mut l = list();
+2
View File
@@ -1504,6 +1504,8 @@ menu View عرض
This library has no drawings or blocks. لا تحتوي هذه المكتبة على رسومات أو كتل.
Only the first {n} are shown. يتم عرض أول {n} فقط.
The drawing changed. Close the window and open it again. تغيّر الرسم. أغلق النافذة وافتحها مرة أخرى.
Use system title bar استخدام شريط عنوان النظام
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. يعرض شريط عنوان بسيطاً لأزرار النافذة فوق شريط CADCraft نفسه. لا يرسم GNOME أشرطة العناوين للتطبيقات، لذا لا يتبع هذا الشريط سمته.
# ArtCraft feature naming
Additional Tools أدوات إضافية
Can't render this file because it contains an unexpected character in line 1336 and column 24.
+2
View File
@@ -1486,6 +1486,8 @@ menu Modify Izmijeni
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Crtež se promijenio. Zatvorite prozor i otvorite ga ponovo.
Use system title bar Koristi sistemsku naslovnu traku
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Prikaži osnovnu naslovnu traku za dugmad prozora iznad CADCraftove vlastite. GNOME ne crta naslovne trake za aplikacije, pa ova ne prati njegovu temu.
# ArtCraft feature naming
Additional Tools Dodatni alati
Can't render this file because it contains an unexpected character in line 1444 and column 24.
+2
View File
@@ -1471,6 +1471,8 @@ menu Modify Modifikace
This drawing has no blocks. Tento výkres neobsahuje žádné bloky.
This library has no drawings or blocks. Tato knihovna neobsahuje žádné výkresy ani bloky.
Only the first {n} are shown. Zobrazuje se pouze prvních {n}.
Use system title bar Použít systémové záhlaví okna
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Zobrazí nad záhlavím CADCraftu jednoduché záhlaví s tlačítky okna. GNOME aplikacím záhlaví nekreslí, takže toto nesleduje jeho motiv.
# ArtCraft feature naming
Additional Tools Další nástroje
Can't render this file because it contains an unexpected character in line 1407 and column 24.
+2
View File
@@ -1085,6 +1085,8 @@
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Die Zeichnung hat sich geändert. Schließen Sie das Fenster und öffnen Sie es erneut.
Use system title bar System-Titelleiste verwenden
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Eine einfache Titelleiste für die Fensterknöpfe über der von CADCraft anzeigen. GNOME zeichnet für Apps keine Titelleisten, daher folgt diese nicht seinem Design.
# ArtCraft feature naming
Additional Tools Zusätzliche Werkzeuge
1 # CADCraft German interface catalog — original translations by the CADCraft contributors.
1085
1086
1087
1088
1089
1090 # ArtCraft feature naming
1091
1092
+2
View File
@@ -1423,6 +1423,8 @@ menu View Προβολή
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Το σχέδιο άλλαξε. Κλείστε το παράθυρο και ανοίξτε το ξανά.
Use system title bar Χρήση της γραμμής τίτλου του συστήματος
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Εμφανίζει μια απλή γραμμή τίτλου με τα κουμπιά του παραθύρου πάνω από τη γραμμή του CADCraft. Το GNOME δεν σχεδιάζει γραμμές τίτλου για τις εφαρμογές, οπότε αυτή δεν ακολουθεί το θέμα του.
# ArtCraft feature naming
Additional Tools Πρόσθετα εργαλεία
Can't render this file because it contains an unexpected character in line 234 and column 24.
+2
View File
@@ -1303,6 +1303,8 @@
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. El dibujo cambió. Cierre la ventana y ábrala de nuevo.
Use system title bar Usar la barra de título del sistema
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Muestra una barra de título básica con los botones de la ventana encima de la de CADCraft. GNOME no dibuja barras de título para las aplicaciones, así que esta no sigue su tema.
# ArtCraft feature naming
Additional Tools Herramientas adicionales
1 # CADCraft Spanish interface catalog — original translations.
1303
1304
1305
1306
1307
1308 # ArtCraft feature naming
1309
1310
+2
View File
@@ -1065,6 +1065,8 @@
Press the keys Appuyez sur les touches
Back to CADCraft's shortcut Revenir au raccourci de CADCraft
A shortcut you give wins over CADCraft's own. Changes apply at once and are kept for next time. Un raccourci que vous définissez l'emporte sur celui de CADCraft. Les modifications s'appliquent tout de suite et sont conservées.
Use system title bar Utiliser la barre de titre du système
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Affiche une barre de titre simple avec les boutons de la fenêtre au-dessus de celle de CADCraft. GNOME ne dessine pas de barre de titre pour les applications, celle-ci ne suit donc pas son thème.
# ArtCraft feature naming
Additional Tools Outils supplémentaires
1 # CADCraft French interface catalog — original translations by @pechnikov2026-star; terminology review by @YannFR81.
1065
1066
1067
1068
1069
1070 # ArtCraft feature naming
1071
1072
+2
View File
@@ -1388,6 +1388,8 @@ menu View Nézet
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. A rajz megváltozott. Zárja be az ablakot, és nyissa meg újra.
Use system title bar A rendszer címsorának használata
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Egyszerű címsort jelenít meg az ablak gombjaival a CADCraft saját címsora fölött. A GNOME nem rajzol címsort az alkalmazásoknak, ezért ez nem követi a témáját.
# ArtCraft feature naming
Additional Tools További eszközök
Can't render this file because it contains an unexpected character in line 16 and column 72.
+2
View File
@@ -1434,6 +1434,8 @@ menu Modify Edita
ENTER INVIO
Shortcut Menu: always enabled Menu di scelta rapida: sempre attivo
Shortcut Menu: enabled when command options are present Menu di scelta rapida: attivo se il comando ha opzioni
Use system title bar Usa la barra del titolo di sistema
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Mostra una semplice barra del titolo con i pulsanti della finestra sopra quella di CADCraft. GNOME non disegna barre del titolo per le app, quindi questa non segue il suo tema.
Check for updates when CADCraft starts Controlla gli aggiornamenti all'avvio di CADCraft
Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks. Se disattivato, CADCraft non propone mai un aggiornamento da solo; Aiuto ▸ Verifica aggiornamenti… continua a controllare.
1 # CADCraft Italian interface catalog — original translations by Emanuele Bottelli (AI-assisted, Claude).
1434
1435
1436
1437
1438
1439
1440
1441 # ArtCraft feature naming
+2
View File
@@ -1519,6 +1519,8 @@ menu View ხედი
This drawing has no blocks. ამ ნახაზში ბლოკები არ არის.
This library has no drawings or blocks. ამ ბიბლიოთეკაში ნახაზები ან ბლოკები არ არის.
Only the first {n} are shown. ნაჩვენებია მხოლოდ პირველი {n}.
Use system title bar სისტემის სათაურის ზოლის გამოყენება
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. ფანჯრის ღილაკებისთვის მარტივი სათაურის ზოლის ჩვენება CADCraft-ის საკუთარი ზოლის ზემოთ. GNOME აპებისთვის სათაურის ზოლებს არ ხატავს, ამიტომ ეს ზოლი მის თემას არ მიჰყვება.
# ArtCraft feature naming
Additional Tools დამატებითი ხელსაწყოები
Can't render this file because it contains an unexpected character in line 10 and column 14.
+2
View File
@@ -1287,6 +1287,8 @@ menu Modify 수정
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. 도면이 변경되었습니다. 창을 닫고 다시 여십시오.
Use system title bar 시스템 제목 표시줄 사용
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. CADCraft의 제목 표시줄 위에 창 단추가 있는 기본 제목 표시줄을 표시합니다. GNOME은 앱의 제목 표시줄을 그리지 않으므로 이 표시줄은 테마를 따르지 않습니다.
# ArtCraft feature naming
Additional Tools 추가 도구
1 # CADCraft Korean interface catalog — original Korean translations.
1287
1288
1289
1290
1291
1292 # ArtCraft feature naming
1293
1294
+2
View File
@@ -2170,6 +2170,8 @@ menu Dimension Wymiarowanie
The current file doesn't look whole, so {name} stays as it is and the current file will be replaced. Bieżący plik wygląda na niekompletny, więc {name} pozostanie bez zmian, a bieżący plik zostanie zastąpiony.
The current file is kept as {name} until the next save. Bieżący plik zostanie zachowany jako {name} do następnego zapisu.
The drawing changed. Close the window and open it again. Rysunek został zmieniony. Zamknij okno i otwórz je ponownie.
Use system title bar Użyj systemowego paska tytułu
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Pokaż prosty pasek tytułu z przyciskami okna nad własnym paskiem CADCraft. GNOME nie rysuje pasków tytułu dla aplikacji, więc ten nie korzysta z jego motywu.
This format can't keep these objects yet: {objects}. Ten format nie potrafi jeszcze zachować tych obiektów: {objects}.
Turn on time-sensitive right-click Włącz obsługę prawego przycisku zależną od czasu
Turned off, a right-click while a command runs does what Right-Click Customization sets for Command mode. Po wyłączeniu tej opcji prawy przycisk podczas polecenia działa zgodnie z ustawieniami trybu polecenia w oknie Dostosowanie prawego przycisku myszy.
Can't render this file because it contains an unexpected character in line 832 and column 20.
+2
View File
@@ -1493,6 +1493,8 @@ menu View Exibir
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. O desenho mudou. Feche a janela e abra-a novamente.
Use system title bar Usar a barra de título do sistema
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Mostra uma barra de título simples com os botões da janela acima da do CADCraft. O GNOME não desenha barras de título para os aplicativos, então esta não segue o tema dele.
# ArtCraft feature naming
Additional Tools Ferramentas adicionais
Can't render this file because it contains an unexpected character in line 1441 and column 24.
+2
View File
@@ -1060,6 +1060,8 @@
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Чертёж изменился. Закройте окно и откройте его снова.
Use system title bar Использовать системный заголовок окна
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Показывает простой заголовок окна с кнопками над заголовком CADCraft. GNOME не рисует заголовки для приложений, поэтому этот не следует его теме.
# ArtCraft feature naming
Additional Tools Дополнительные инструменты
1 # CADCraft Russian interface catalog — original translations by @pechnikov2026-star.
1060
1061
1062
1063
1064
1065 # ArtCraft feature naming
1066
1067
+2
View File
@@ -1511,6 +1511,8 @@ menu Modify Ändra
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Ritningen har ändrats. Stäng fönstret och öppna det igen.
Use system title bar Använd systemets namnlist
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Visar en enkel namnlist med fönsterknapparna ovanför CADCrafts egen. GNOME ritar inga namnlister åt appar, så den här följer inte dess tema.
DView DView
Keyboard Shortcuts... Kortkommandon...
Multiple Insert Infoga flera
Can't render this file because it contains an unexpected character in line 1500 and column 24.
+2
View File
@@ -1391,6 +1391,8 @@ menu View Görünüm
Ctrl+Enter to apply Ctrl+Enter to apply
Edit Text Edit Text
The drawing changed. Close the window and open it again. Çizim değişti. Pencereyi kapatıp yeniden açın.
Use system title bar Sistem başlık çubuğunu kullan
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. CADCraft'ın başlık çubuğunun üstünde pencere düğmelerini içeren basit bir başlık çubuğu gösterir. GNOME uygulamalar için başlık çubuğu çizmediğinden bu çubuk onun temasına uymaz.
# ArtCraft feature naming
Additional Tools Ek Araçlar
Can't render this file because it contains an unexpected character in line 11 and column 13.
+2
View File
@@ -1468,6 +1468,8 @@
ENTER Клавіша Enter
Shortcut Menu: always enabled Контекстне меню: завжди
Shortcut Menu: enabled when command options are present Контекстне меню: коли команда має параметри
Use system title bar Використовувати системний заголовок вікна
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Показує простий заголовок вікна з кнопками над заголовком CADCraft. GNOME не малює заголовки для застосунків, тому цей не відповідає його темі.
Check for updates when CADCraft starts Перевіряти оновлення під час запуску CADCraft
Turned off, CADCraft never offers an update on its own; Help ▸ Check for Updates… still looks. Якщо вимкнено, CADCraft ніколи сам не пропонує оновлення; Довідка ▸ Перевірити оновлення… усе одно перевіряє.
Can't render this file because it contains an unexpected character in line 1404 and column 24.
+2
View File
@@ -1492,6 +1492,8 @@ menu Modify Hiệu chỉnh
Ctrl+Enter to apply Ctrl+Enter để áp dụng
Edit Text Sửa chữ
The drawing changed. Close the window and open it again. Bản vẽ đã thay đổi. Đóng cửa sổ và mở lại.
Use system title bar Dùng thanh tiêu đề của hệ thống
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. Hiện một thanh tiêu đề đơn giản cho các nút cửa sổ phía trên thanh của CADCraft. GNOME không vẽ thanh tiêu đề cho ứng dụng, nên thanh này không theo chủ đề của nó.
# Phase 1 of craft-i18n#401: the strings the translation_gaps report listed as missing for vi.
# Dimension Style Manager (DIMSTYLE)
<style overrides> <ghi đè kiểu>
Can't render this file because it contains an unexpected character in line 1445 and column 24.
+2
View File
@@ -1530,6 +1530,8 @@ menu View 视图
Ctrl+Enter to apply Ctrl+Enter 应用
Edit Text 编辑文字
The drawing changed. Close the window and open it again. 图纸已切换。请关闭窗口后重新打开。
Use system title bar 使用系统标题栏
Show a basic title bar for the window buttons above CADCraft's own. GNOME doesn't draw title bars for apps, so this one doesn't follow its theme. 在 CADCraft 自己的标题栏上方显示带窗口按钮的基本标题栏。GNOME 不为应用绘制标题栏,因此此标题栏不跟随其主题。
# ArtCraft feature naming
Additional Tools 其他工具
Can't render this file because it contains an unexpected character in line 1486 and column 24.
+180 -13
View File
@@ -17,6 +17,8 @@ pub const UPDATE_APP: craft_update::app::App = craft_update::app::App {
..craft_update::suite::CADCRAFT
};
#[cfg(not(target_arch = "wasm32"))]
pub mod agents;
pub mod aliasdlg;
pub mod animation;
pub mod attedit;
@@ -74,11 +76,13 @@ pub mod quick;
pub mod save_loss;
pub mod shortcut_menus;
pub mod theme;
pub mod title_bar;
#[cfg(not(target_arch = "wasm32"))]
pub mod updates_ui;
pub mod viewcube;
pub mod vpscale;
pub mod wblock;
mod window_edges;
pub mod exchange;
mod file_provider_app;
@@ -150,6 +154,10 @@ pub struct UiState {
pub last_lisp_dir: Option<String>,
/// The folder the Command Aliases dialog last imported a `.pgp` file from.
pub last_pgp_dir: Option<String>,
/// Options ▸ Display ▸ Use system title bar: where the desktop leaves the window frame to the app (GNOME on
/// Wayland), keep the desktop's frame instead of the framework's title bar ([`title_bar`]). Kept in the desktop
/// workspace file, which is read before the window opens.
pub system_title_bar: bool,
}
/// A DXF/DWG file version (2000 … 2018).
@@ -230,6 +238,7 @@ impl Default for UiState {
hatch_patterns: Default::default(),
last_lisp_dir: None,
last_pgp_dir: None,
system_title_bar: false,
}
}
}
@@ -323,7 +332,12 @@ pub struct CadApp {
/// Drawings being read on worker threads ([`opening`]).
pub opening: opening::Opening,
pub integrated_titlebar: bool,
/// Both frames of Use system title bar, where it applies ([`title_bar::TitleBar`]).
title_bar: Option<title_bar::TitleBar>,
control_rx: Option<Receiver<ControlRequest>>,
/// Agents in the open window through the ArtCraft Launcher's switch ([`agents`]).
#[cfg(not(target_arch = "wasm32"))]
pub agents: agents::Agents,
/// Fresh surface and identity snapshot (see [`capture`]).
pub(crate) capture_geometry: Option<capture::CaptureGeometry>,
/// Monotonic surface epoch, bumped whenever the window/viewport geometry changes.
@@ -352,7 +366,11 @@ pub struct CadApp {
/// The framework dialogs CADCraft keeps open (the update dialogs), run after its own UI.
pub framework_dialogs: craft_ui::dialog::DialogHost,
/// One synthetic batch has been put into `RawInput` and is waiting for a real `App::ui` call.
synthetic_injected: bool,
pub(crate) synthetic_injected: bool,
/// The agent folders in force while input an agent queued (`ui.click`, `ui.key`, `ui.text`…)
/// waits for the frames that handle it, or a LISP routine it started runs on in later slices,
/// so what they do is held to them as the request itself was ([`CadApp::guarded_ui`]).
pub(crate) agent_input_roots: Option<std::sync::Arc<cadcraft_engine::file_access::AutomationRoots>>,
/// Counts settled UI passes (one per painted frame; never hidden logic-only ticks or
/// discarded passes).
pub ui_frames: u64,
@@ -439,7 +457,10 @@ impl CadApp {
status: None,
opening: opening::Opening::default(),
integrated_titlebar: false,
title_bar: None,
control_rx: None,
#[cfg(not(target_arch = "wasm32"))]
agents: agents::Agents::default(),
capture_geometry: None,
capture_epoch: 0,
capture_identity_epoch: 0,
@@ -454,6 +475,7 @@ impl CadApp {
framework_host: framework::host(),
framework_dialogs: craft_ui::dialog::DialogHost::default(),
synthetic_injected: false,
agent_input_roots: None,
ui_frames: 0,
#[cfg(not(target_arch = "wasm32"))]
frame_cap: None,
@@ -1104,7 +1126,13 @@ impl CadApp {
}
// A long AutoLISP routine runs one bounded slice per frame, including hidden web/native
// ticks; it must not depend on a paint or `RequestPaintWhileHidden`.
self.session.lisp_tick();
// An agent's routine keeps its folders from its first slice on, also when the request that
// started it ran earlier in this same call (`drain_control`), after the frame's roots were
// taken (`guarded_logic`). A routine without agent roots runs as before.
match self.agent_input_roots.clone() {
Some(roots) => cadcraft_engine::file_access::confine(Some(&roots), || self.session.lisp_tick()),
None => self.session.lisp_tick(),
}
// Time-based and idempotent by its own deadline; keeps autosave alive while hidden.
self.autosave_tick(ctx);
#[cfg(not(target_arch = "wasm32"))]
@@ -1293,6 +1321,7 @@ impl CadApp {
self.sync_bars();
control::begin_frame(ui.ctx());
let t = theme::Tokens::get();
self.follow_title_bar(ui.ctx());
chrome::title_and_toolbar(self, ui);
if self.ui.in_window_menu {
menus::menu_bar(self, ui);
@@ -1326,31 +1355,66 @@ impl CadApp {
autosave::gpu_notice(self, ui.ctx());
autosave::failure_notice(self, ui.ctx());
self.run_framework_dialogs(ui);
// Last, so the edges' resize cursors win over the drawing area's.
window_edges::show(ui.ctx());
self.frame_ms = now_ms() - t0;
}
/// Drain each queued control request at most once (timed-out requests are skipped), dispatch it to `control::handle` or `capture::admit`, note the resulting capture identity and request a repaint.
fn drain_control(&mut self, ctx: &egui::Context) {
self.drain_agents(ctx);
let Some(rx) = self.control_rx.take() else { return };
while let Ok(req) = rx.try_recv() {
// Timed out while queued: the client was told it did not run (#345).
if !req.begin() {
continue;
}
let reply = req.reply.clone();
match control::handle(self, ctx, &req) {
control::Outcome::Done(v) => {
let _ = reply.send(v);
}
control::Outcome::Screenshot { path } => capture::admit(self, ctx, path, reply),
}
// A command can switch drawings or move the focus; a screenshot queued before it must
// see that transition even if a later command returns to the same drawing.
capture::note_identity(self, ctx);
ctx.request_repaint();
self.answer_control(ctx, &req, None);
}
self.control_rx = Some(rx);
}
/// The agent link's requests, each held to the agent folders ([`agents::Agents::roots`]).
#[cfg(not(target_arch = "wasm32"))]
fn drain_agents(&mut self, ctx: &egui::Context) {
let requests = self.agents.sync(ctx);
if requests.is_empty() {
return;
}
let roots = self.agents.roots();
for req in requests {
self.answer_control(ctx, &req, Some(&roots));
}
}
#[cfg(target_arch = "wasm32")]
fn drain_agents(&mut self, _: &egui::Context) {}
/// Run one control request, with `roots` in force while it runs, and send its reply (a
/// screenshot's once captured).
fn answer_control(
&mut self,
ctx: &egui::Context,
req: &ControlRequest,
roots: Option<&std::sync::Arc<cadcraft_engine::file_access::AutomationRoots>>,
) {
let reply = req.reply.clone();
match cadcraft_engine::file_access::confine(roots, || control::handle(self, ctx, req)) {
control::Outcome::Done(v) => {
let _ = reply.send(v);
}
control::Outcome::Screenshot { path } => capture::admit(self, ctx, path, reply),
}
// Input the agent queued, or a LISP routine it started that goes on in later frames' slices,
// stays held to its folders.
if roots.is_some() && (!self.synthetic.is_empty() || self.session.lisp_running()) {
self.agent_input_roots = roots.cloned();
}
// A command can switch drawings or move the focus; a screenshot queued before it must
// see that transition even if a later command returns to the same drawing.
capture::note_identity(self, ctx);
ctx.request_repaint();
}
}
/// Ask for a painted frame while no frame is being painted. Native eframe honours the viewport
@@ -1610,6 +1674,109 @@ mod tests {
assert!(third.events.iter().any(|event| matches!(event, egui::Event::Key { key: egui::Key::B, .. })));
}
/// Input an agent queues in the window (`ui.text`, `ui.key`, `ui.click`) is handled frames later,
/// so the agent folders stay in force until that input has gone through a UI pass; input from
/// `--control` (no roots) leaves nothing in force.
#[test]
fn agent_input_keeps_the_agent_folders_until_it_is_handled() {
let mut a = app();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
let (req, _reply) = control::ControlRequest::new("ui.text", json!({"text": "x"}));
a.answer_control(&ctx, &req, None);
assert!(a.agent_input_roots.is_none(), "--control input is not confined");
a.synthetic.clear();
let roots = cadcraft_engine::file_access::AutomationRoots::none();
let (req, _reply) = control::ControlRequest::new("ui.text", json!({"text": "x"}));
a.answer_control(&ctx, &req, Some(&roots));
assert!(a.agent_input_roots.is_some(), "in force while the text waits");
let mut raw = egui::RawInput::default();
a.raw_input_hook(&ctx, &mut raw);
let mut out = ctx.run_ui(raw, |ui| {
a.guarded_logic(ui.ctx());
a.guarded_ui(ui);
});
out.textures_delta.clear();
assert!(a.agent_input_roots.is_none(), "the text went through a UI pass");
// A `--control` request in a frame that holds an agent's roots is not held to them.
let outside = std::env::temp_dir().join(format!("cadcraft-control-unconfined-{}.png", std::process::id()));
let (req, reply) = control::ControlRequest::new("ui.render", json!({"path": outside.to_string_lossy()}));
a.session.new_drawing(false);
cadcraft_engine::file_access::confine(Some(&roots), || a.answer_control(&ctx, &req, None));
assert_eq!(reply.wait(std::time::Duration::from_secs(5))["ok"], true);
assert!(outside.is_file());
let _ = std::fs::remove_file(outside);
}
/// A routine an agent starts through the agent link, in a frame whose `logic` began with no
/// agent folders in force, writes nothing outside them in any later slice, the first one of the
/// same `logic` call included.
#[test]
fn an_agents_routine_is_confined_from_the_same_frame_on() {
use craft_automation::agents::{AgentLink, AgentSwitch, TOKEN_FILE};
let dir = std::env::temp_dir().join(format!("cadcraft-lisp-same-frame-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
let outside = dir.join("outside.txt");
let mut a = app();
a.session.new_drawing(false);
let link = AgentLink::new(Some(dir.clone()), "CADCraft test");
a.agents = agents::Agents::new(link, AgentSwitch::fixed(true, true), Some(dir.clone())).with_default_folder(Some(folder));
let ctx = egui::Context::default();
a.logic(&ctx);
let port = a.agents.status().port.unwrap();
let token = std::fs::read_to_string(dir.join(TOKEN_FILE)).unwrap().trim().to_string();
let path = outside.to_string_lossy().replace('\\', "/");
let text = format!("(progn (repeat 300000 (setq x 1)) (setq f (open \"{path}\" \"w\")) (if f (close f)) (prompt \"agent-routine-done\"))");
let agent = std::thread::spawn(move || {
craft_automation::client::ControlClient::connect(([127, 0, 0, 1], port).into(), &token)
.map_err(|e| format!("{e:?}"))?
.call("cmdline.input", json!({"text": text}))
});
let deadline = std::time::Instant::now() + std::time::Duration::from_secs(30);
while !agent.is_finished() || a.session.lisp_running() {
assert!(std::time::Instant::now() < deadline, "the routine never ended");
// `logic` alone, as `guarded_logic` with no roots taken: only the stored agent roots confine.
a.logic(&ctx);
std::thread::sleep(std::time::Duration::from_millis(2));
}
let reply = agent.join().expect("the agent thread");
assert!(reply.is_ok(), "the window took the request: {reply:?}");
assert!(a.session.log.iter().any(|l| l.contains("agent-routine-done")), "the routine ran past its file attempt: {:?}", a.session.log);
assert!(!outside.exists(), "the routine wrote outside the agent folders");
drop(a);
let _ = std::fs::remove_dir_all(dir);
}
/// A LISP routine an agent starts that runs past its first slice goes on in later frames, still
/// held to the agent folders until it ends.
#[test]
fn an_agents_long_lisp_routine_keeps_the_agent_folders() {
let mut a = app();
let ctx = egui::Context::default();
crate::framework::install_headless(&ctx);
a.session.new_drawing(false);
let roots = cadcraft_engine::file_access::AutomationRoots::none();
let (req, _reply) = control::ControlRequest::new("cmdline.input", json!({"text": "(repeat 300000 (setq x 1))"}));
a.answer_control(&ctx, &req, Some(&roots));
assert!(a.session.lisp_running(), "the routine outlives the request");
assert!(a.agent_input_roots.is_some(), "and keeps the agent folders");
for _ in 0..2000 {
if !a.session.lisp_running() {
break;
}
let mut out = ctx.run_ui(egui::RawInput::default(), |ui| {
a.guarded_logic(ui.ctx());
a.guarded_ui(ui);
});
out.textures_delta.clear();
}
assert!(!a.session.lisp_running(), "the routine ended");
assert!(a.agent_input_roots.is_none(), "then the folders are no longer in force");
}
#[test]
fn theme_choice_persists_and_drives_tokens() {
let mut a = app();

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