Compare commits

...
Author SHA1 Message Date
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 5ab5e6f343 Merge pull request #3768 from storytold/stack/e6
Land 4 reviewed PRs (stack e6)
2026-12-03 06:45:42 +01:00
FredApps 8698649da1 Merge main into stack/e6
Conflict: crates/engine/tests/it/main.rs (both new test modules kept: legacy_sysvars and lisp_answer_by_frames).
2026-12-03 06:25:12 +01:00
FredApps a6add77c5a Drop #3580 from this landing
Reverts the Merge #3580 commit (0d70d25f, first parent) and the landing fix that moved its
tests into tests/it (4ecd4aed). #3580 is not ready (changes still requested on 9bbe7b69) and lands
on its own. #3601, #3497 and #3503 stay.
2026-12-03 05:45:02 +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
Tanish Manku 4ecd4aed42 Landing fix: #3580's tests join each crate's tests/it binary (rule 30) 2026-12-02 14:19:42 -07:00
Tanish Manku 636dd26f07 Merge #3503 2026-12-02 14:19:34 -07:00
Tanish Manku 0d70d25f07 Merge #3580 2026-12-02 14:19:23 -07:00
Tanish Manku 15c8926c97 Merge #3497 2026-12-02 14:19:16 -07:00
Tanish Manku 300a64f711 Merge #3601 2026-12-02 14:19:13 -07:00
Magzhan ZhakudaandClaude Opus 5.5 27a9b91f3c Vertex identifier tests: move into the io harness (tests/it)
AGENTS.md rule 30: one integration test binary per crate. The five cases
move unchanged into crates/io/tests/it/lwpolyline_vertex_ids.rs, registered
in main.rs under the same target guard the separate binary had.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-12-02 15:50:44 +05:00
Magzhan Zhakuda e48f8805a5 Merge remote-tracking branch 'origin/main' into fix/lwpolyline-vertex-ids
# Conflicts:
#	crates/doc/src/foreign.rs
2026-12-02 15:44:22 +05:00
FredApps 9bbe7b69a3 Merge remote-tracking branch 'origin/main' into yan-3580 2026-12-02 08:59:06 +01:00
FredApps 8cde239e64 Text Style: Apply writes only the fields the dialog changed; a refused number says why
Apply and the unsaved-changes Yes sent the whole staged style, so a change made to another
field of the style by another route since the edit began was written back over. They now send
only the fields that differ from the style as the first edit found it.

A refused height, width factor or oblique angle went back to its value without a word. The
dialog now says what the field accepts, in a live region, until an entry is accepted. The shared
expr_field is unchanged.
2026-12-02 08:58:58 +01:00
code-compliant 15c3c9564a Answer two review findings: continue text with a usable height, name annotative rows
Enter at TEXT's start point does not continue with a height that neither the last text nor TEXTSIZE can give. An annotative style's row says so in its accessible name, which starts with the visible style name. The Escape test for another window now fails if any control of the dialog takes the focus.
2026-12-02 10:37:25 +08:00
FredApps f288082ff3 Merge main into ACADVER fix, keeping shared test registration 2026-12-02 02:35:24 +01:00
code-compliant 0fd046c4c1 Keep a click on an editor over the drawing from leaving the keys with the dialog
The grace for a closed list's last focused item now applies only to a list that a key closed. A list that a click closed gives the focus to what was clicked, so a click on an editor over the drawing while a list was open takes the keys from the dialog at once.
2026-12-02 07:20:37 +08:00
code-compliant 7bd33b7ff1 Give a closed list's focus back only to a control that is still there and enabled
The focus owed to the control that opened a list or menu is given two passes after the list closed, once what the choice did has been drawn: to the control if it is still there and enabled, else to the chosen style. A button the choice turned off, a row it hid and a style it deleted no longer take the focus back. The dialog keeps the keys through the passes in which the closed list's last item still looks focused.
2026-12-02 07:05:34 +08:00
code-compliant 9ce7cde286 Put the focus on the chosen style after Delete from the style list's menu
The menu's Delete removes the row that held the focus, as the Delete button does, so the focus goes to the chosen style here too.
2026-12-02 06:39:51 +08:00
code-compliant 0cf540495f Put the focus on the chosen style when Apply, Set Current or Delete turns itself off
Each of the three buttons disables itself after it works, and egui drops the focus of a control that turns off, so a person using the keyboard was left with no focused control. The focus now goes to the chosen style.
2026-12-02 06:23:44 +08:00
code-compliant 6050f3c396 Let the window under the pointer decide who has the keys, even when a list is open
A press counts for the dialog only when the dialog is the topmost window under the pointer, takes nothing from an item of an open list or menu, and takes the keys from the dialog for any other window, the drawing or a bar. So a click on another window's title bar that closes an open list no longer leaves the next Escape with the dialog.
2026-12-02 06:07:15 +08:00
code-compliant 3371028cdf Add a Rename button to Text Style and tighten who has the keys
Rename is now a button beside Delete, so it can be reached by the keyboard, and its field takes the focus when it shows; the focus returns to the styles when the rename ends. A choice made by key in the style filter list and the font style list closes the list. The dialog counts focus on a foreground layer as its own only while a list or menu is open, so an editor over the drawing keeps its Escape; and a click counts only when the dialog is the topmost window under the pointer, so a window over the dialog does not give it the keys.
2026-12-02 05:47:15 +08:00
code-compliant 206d40bc0d Give the focus back after any list or menu closes by a key, and skip a return target that is gone
One check after the dialog draws replaces the three per-box helpers: when a list or menu closed by Escape, Enter or Space while the dialog had the keys, the focus returns to the control of the dialog that last had it. A popup that closed earlier in the same pass still counts as open for the Escape test. The return target saved when the dialog opened is used only if it still exists (a menu item that opened the dialog is gone). The key ownership is updated before a drawing switch rebuilds the state.
2026-12-02 05:19:42 +08:00
code-compliant f796d5c8fc Remember who has the keys in the Text Style dialog
The dialog has the keys while the focus is in it, and keeps them when egui drops the focus (an Escape, a click on blank space, a control that goes away, a list or menu that closes). The focus moving to another window, or a click outside the dialog, takes them away, so an Escape for a command running in the drawing, or for another window, is left alone. A list closed by Escape, Enter or Space gives the focus back to its box only while the dialog has the keys.
2026-12-02 04:38:41 +08:00
code-compliant 03bf451124 Give the focus back to a combo box when Escape closes its list
egui drops the focus as an Escape arrives, so after the font or style list closed, nothing held the focus and the next Escape did not reach the dialog. The three lists now return the focus to their box when Escape closes them. One long line is split as rustfmt wants.
2026-12-02 04:15:50 +08:00
code-compliant 2659b44569 Keep the Text Style dialog's focus handling to its own keys, and name its preview
Escape closes or cancels something in the dialog only when the focus was in it one pass earlier (egui drops the focus as the key arrives), so an Escape for a command running in the drawing is left to the command. The dialog takes the focus again each time it opens, including after another dialog replaced it, and after a drawing switch removed the field that held it; the focus returns to what had it only if the dialog held it. When the filter hides the chosen style, the focus goes to the first style shown, or the filter. The style preview is named by its heading. The Tab test now checks every enabled control and the opposite order back, and the focus-return test checks the focus itself.
2026-12-02 03:53:54 +08:00
code-compliant e5f62c9546 Let Escape cancel the font list, the New page or a rename before it closes Text Style
The font list closes itself on Escape while the dialog draws, so the check that left it alone saw no open popup and the dialog closed as well. The state is now read before the dialog draws. On the New page and during a rename, Escape now acts as Cancel and puts the focus back on the styles, as it already did for the unsaved-changes question.
2026-12-02 03:10:01 +08:00
code-compliant f5a70b0e98 Regenerate the parity checklist for the new style commands
cargo xtask parity now counts 488 registered commands (the Text Style
commands this pull request adds among them) instead of 482. The file is
generated, so it is regenerated rather than edited.
2026-12-02 00:55:45 +08:00
code-compliant 13aa3a5cc6 test(acadver): move the ACADVER tests into the engine's shared integration binary
The five cases move from tests/acadver.rs to tests/it/acadver.rs unchanged, apart from the I/O
setup: the save case installs the suite's real file hooks (refedit_xref::hooks) in place of its
own copy, and uses a folder under Cargo's temporary directory for integration tests.
2026-12-01 23:47:22 +08:00
code-compliant 3fe6d7e954 test(sysvars): make the TEXTEVAL session check able to fail; put the $ names note on its list 2026-12-01 23:47:07 +08:00
code-compliant 5950cbce24 Keep the Chinese command labels main requires complete
Moving these two rows out made chinese_menus_and_commands_are_fully_translated
fail: both are labels of engine commands (-style and style.fonts), and that
test, which main already has, requires the zh catalog to name every command.
They stay here rather than moving to the craft-i18n pull request, rather than
weakening the check. The 26 Ukrainian rows are not required by any check and do
move.
2026-12-01 23:41:49 +08:00
code-compliant 88a3069ea2 Let the keyboard use the Text Style dialog and leave it
The dialog opened without taking the focus, so a person without a pointer was
left on the drawing behind it and every key went past the dialog; Escape did
nothing, so the only way out was to find a button; and the style filter was
named "List", which is not the heading a person sees over it.

The dialog now takes the focus on open, and on each page it shows (the
question, the new style's name, the styles). Escape closes it, cancelling an
unanswered question instead of dropping the edits, and closing gives the focus
back to what had it. The filter is named by its heading.

The tests drive open, choose, apply and the question with key events only, and
fail without these changes.
2026-12-01 22:33:56 +08:00
code-compliant 20e2efebf7 fix(sysvars): refuse text from programs and routines, read unknown DIMASSOC as off, save REGENMODE
DIMASO, TEXTEVAL and REGENMODE now take only a number from a program or a routine: numeric text
and booleans are refused. Digits typed at the SETVAR prompt, by hand or through (command), still
work.

DIMASO reads 1 only for DIMASSOC 1 or 2. For any other stored mode it reads 0, and DIMASO 1 turns
associativity on from it too.

A new drawing now has REGENMODE 1 in its header, so a save writes $REGENMODE.
2026-12-01 20:32:12 +08:00
code-compliant a193f64e04 style(tests): keep the module list in order after the merge 2026-12-01 20:32:11 +08:00
code-compliant 494dbd965b Take the new text fields from the previewed style
Main's Text gained backwards and upside_down; the dialog's preview sets them
from the style it draws, so a preview shows the effects the style has.
2026-12-01 20:17:01 +08:00
code-compliant bea1843497 Move the Text Style translations to the craft-i18n pull request
Feature pull requests add English only (AGENTS.md rule 16). The 26 Ukrainian
and 2 Simplified Chinese rows move to storytold/craft-i18n; the English keys,
the UI wiring and the managers/textstyle entry in the translation report stay
here, so the new strings show in English until the translations land.
2026-12-01 16:49:39 +08:00
code-compliant f9284510ea Merge remote-tracking branch 'origin/main' into assist/pr-1089-text-style 2026-12-01 14:53:48 +08:00
code-compliant 723997489a Merge remote-tracking branch 'origin/main' into fix/acadver-release-text 2026-12-01 14:45:18 +08:00
code-compliant 0bc5f721fb Merge remote-tracking branch 'origin/main' into fix/sysvars-dimaso-texteval-regenmode-popups 2026-12-01 14:45:16 +08:00
Magzhan ZhakudaandClaude Opus 5.5 e9ac879b83 Vertex identifiers: compare in the read orientation, skip application groups
Review follow-ups: the points kept with the identifiers are stored as the
reader gives them (mirrored in x when the normal points down), and only that
orientation matches, so a reversed polyline symmetric about x = 0 no longer
keeps its identifiers. A group 91 inside an application's 102 group is not
read as an identifier. The edit test asserts that no identifier is written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 03:17:09 +05:00
Magzhan ZhakudaandClaude Opus 5.5 ffde4b3bbe DXF/DWG: a lightweight polyline keeps its vertex identifiers
A LWPOLYLINE's vertex identifiers (group 91, DXF 2010 and later) were
dropped on read, so every save wrote the polyline without them. Geometric
constraints name a polyline's segments by them. They are now kept with the
entity's extras and written back (DXF 2010+, and DWG through the bridge)
while every vertex is where it was read; once a vertex is moved, added,
removed or reordered, none are written.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-28 02:43:43 +05:00
code-compliant 0db2d73e02 Fix Text Style lookup for extensionless fonts 2026-11-27 21:39:26 +08:00
code-compliant fcb2188143 Test text style changes before selection 2026-11-27 10:00:56 +08:00
code-compliant ab183249f9 Fix text style prompts and preserve drawing edits 2026-11-27 09:51:27 +08:00
code-compliant cd4912b003 Merge main and adapt text style preview 2026-11-27 08:40:51 +08:00
code-compliant 61d1f267cf Merge latest main into text-follows-style 2026-11-26 15:25:39 +08:00
code-compliant b9c9162b14 Merge main into text-follows-style 2026-11-26 15:18:53 +08:00
code-compliant bbf613e944 Merge remote-tracking branch 'origin/main' into fix/sysvars-dimaso-texteval-regenmode-popups
# Conflicts:
#	crates/engine/src/settings.rs
2026-11-25 20:24:51 +08:00
code-compliant 91acccc36a DIMASO: no change leaves the drawing unmodified; its remembered mode is not a variable and not a roundtrip loss 2026-11-25 20:04:14 +08:00
code-compliant dec54a9ded DIMASO keeps its remembered mode in the drawing header, so undo restores it; any number of $ before the four names 2026-11-25 18:22:02 +08:00
code-compliant 38a239b1e9 Keep DIMASO's remembered mode per drawing and take the DXF $ names
DIMASO remembered the DIMASSOC mode it turned off in the session settings,
so two open drawings switched between restored each other's mode: with 1 in
the first and 2 in the second, the first came back as 2. The remembered mode
now lives in the drawing's own state, which is not saved, so each open
drawing keeps its own.

$DIMASO, $TEXTEVAL, $REGENMODE and $POPUPS were unknown to getvar, and
setvar took $POPUPS and out-of-range $REGENMODE because only the header's
name lookup stripped the $. Those four names now read, take values and
report read-only exactly as their plain forms, in any case and with spaces
around them. No other name changes: $ANGBASE keeps LISP's radians (only the
plain name converts) and setvar $OSMODE is still not the session's OSMODE.

Tests: DIMASO 1 restores 1 in the first drawing and 2 in the second after
switching; each $ form reads, writes and refuses like its plain name,
including $REGENMODE 2 and $POPUPS; and $ANGBASE, $OSMODE keep their own
handling.
2026-11-25 17:55:54 +08:00
code-compliant 60ac79d4b5 Read and set the legacy variables DIMASO, TEXTEVAL, REGENMODE and POPUPS
DIMASO has no value of its own: it reports DIMASSOC as 0 or 1, and setting it to 0 turns DIMASSOC off while remembering the mode it had, so setting it back to 1 restores that mode (2 when none was seen). Every other value is refused and changes nothing.

TEXTEVAL is a session setting (0 by default) kept for routines that switch it around their prompts; no prompt reads it yet. REGENMODE is the drawing's, 1 by default, and is saved as $REGENMODE (group 70) and read back. POPUPS is read-only and always 1.
2026-11-25 17:35:54 +08:00
code-compliant a65a9b36b5 ACADVER: a $ in the name does not get past read-only; listings show the release text without a drawing 2026-11-25 16:46:10 +08:00
code-compliant 808ae34499 sysvars: ACADVER reports the program's release, not the file version
(getvar "ACADVER") and the GETVAR command gave the drawing's $ACADVER file
version code (AC1015), and SETVAR accepted a new value for it. AutoCAD
documents ACADVER as a read-only text variable holding the program's release
number, which (atof) reads back as a number.

GETVAR now gives "24.3s (CADCraft)" (24.3), and SETVAR and SETVAR's typed name
prompt report it as read-only. The drawing's $ACADVER is untouched, so a
drawing read from a 2000 DXF still saves as one.

Tests: crates/engine/tests/acadver.rs.
2026-11-25 16:07:18 +08:00
SlopapaloozaandClaude Opus 5.5 ebeee968b5 Review fixes: TEXT refuses an unknown justification; its params string
From CodeRabbit's reviews of #1089:
- TEXT's Justify question refuses an answer that is no option ("Invalid
  option keyword.") and asks again, as MTEXT's does; it kept the previous
  justification and went on. Enter leaves the question, as Style's does (it
  asked again, with Esc, which ends TEXT, the only way out).
- The `text` params string lost a line continuation (a run of spaces showed
  in the command list, the CLI and MCP).
- The hostile TEXT input test fails on a caught panic (an internal error)
  instead of discarding every result.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:22 -05:00
SlopapaloozaandClaude Opus 5.5 2eaf90df4b New text follows its style: fixed and paper heights, width factor, oblique, TEXT's Style option
TEXT, MTEXT and their JSON forms now set text the way its style says, as AutoCAD does:

- A fixed-height style (height > 0) isn't asked for a height: TEXT goes from the start point
  to the rotation, MTEXT starts at that height, and the JSON forms default to it (an explicit
  `height` is kept). TEXTSIZE is left alone. MTEXT's Style option takes a fixed style's height.
- An annotative style asks for "Specify paper text height", the size the text measures on
  paper.
- New TEXT takes the style's width factor and obliquing angle (it had 1 and 0). Later style
  changes don't change existing text, as in AutoCAD.
- TEXT's Style option works: a style name (made current, then the status line again) or ? to
  list the styles; an unknown name is refused and asked again.
- Enter at TEXT's start point continues directly below the last TEXT in the space, with its
  style, height, rotation and justification, and asks only for the text. With no text in
  the drawing it ends the command.
- The status line gives the height the style fixes and the justification in use.
- `text` takes `style` (default: the current style).

Left for later: Align and Fit take one point, not the baseline's two ends, and
the line being typed isn't previewed on the canvas.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:22 -05:00
SlopapaloozaandClaude Opus 5.5 d8cf5fbb62 -STYLE: imports by name, as #2239 requires
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:22 -05:00
SlopapaloozaandClaude Opus 5.5 bf3e607bd6 Review fixes: font files named in capitals; a rename keeps the waiting edits
From CodeRabbit's reviews of #1083:
- The dialog matched a style's font without its extension ("arialn")
  against the installed file's stem in its own case, so ARIALN.TTF wasn't
  found: the dialog said "not installed" and disabled Font Style for a font
  the renderer finds and draws. The stems are compared in any case now.
- Renaming the chosen style renames the edits waiting for Apply with it, so
  setting every value back no longer leaves Apply on (and Close asking)
  because of the old name.
- The preview is drawn on the drawing area's color (theme::Tokens), as the
  canvas is, instead of white or the raster default.
- Closing the dialog clears a New page or a rename left open, so the next
  STYLE opens on the styles.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 6042310fc7 Review fixes: -STYLE's annotative answers and big font, the dialog's rename
From CodeRabbit's review of #1083 (its finding on the text styles that
dimension overrides use is fixed in #954, where the rename that follows
them is):
- -STYLE: Enter at "Create annotative text style?" says yes, as the prompt
  now shows (it showed the style's current setting while Enter said yes),
  and No asks for the text height again instead of a paper height.
- -STYLE keeps the big font of the style a new one starts from.
- The Text Style dialog's Rename takes only a name the rename accepts, so a
  refused one no longer leaves the selection on no style and drops the
  edits waiting for Apply.
- The dialog test's "Styles in use" check now hides a style that exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 1ec5d20c84 Text Style dialog (STYLE) with installed fonts, and -STYLE
STYLE (ST, Format ▸ Text Style...) opens a Text Style dialog like AutoCAD's: the drawing's
text styles (all, or those in use; annotative ones marked) with a preview of the selected one,
and Set Current, New, Rename and Delete (off for Standard, the current style and styles in
use). The selected style's Font Name and Font Style are picked from the installed fonts by
family and style, with a search; Use Big Font is offered for SHX fonts; Annotative switches
Height to Paper Text Height; the effects are Upside down, Backwards, Width Factor and Oblique
Angle. Edits wait for Apply (one undo step), and choosing another style, Set Current, New or
Close with edits not applied asks whether to save them, as AutoCAD does. Match text
orientation to layout and Vertical are shown unavailable: CADCraft doesn't keep or draw them.

The fonts come from the fonts crate's new installed_fonts(), which reads only each font file's
table directory and naming table (typographic family and subfamily first, English names
preferred), so listing every installed font is cheap (145 faces in about 60 ms on Windows 11).
`style.fonts` gives the same list to MCP clients and scripts.

-STYLE asks in AutoCAD's order, so scripts written for AutoCAD run: name (or ? to list),
font, height or Annotative (then orientation and paper height), width factor, obliquing
angle, backwards, upside down, and vertical for SHX fonts; the style then becomes current.
Unusable answers are asked again. As JSON it takes the style command's parameters.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 723810f768 -DIMSTYLE: imports by name, as #2239 requires; the managers' modules in order
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 60e22f38c4 Review fixes: overrides written as taken, style names, the manager keeps a refused edit
From CodeRabbit's second to fourth reviews of #1042:
- dimstyle.overrides writes each header variable with the value the style
  took (a lineweight named ByLayer is -1), so SETVAR can't refuse one
  halfway through, after `clear` and the earlier values.
- -DIMSTYLE Save and Restore check the name before touching the drawing, so
  a refused call leaves no empty undo step, and Apply to objects none of
  which is a dimension makes none either.
- New dimension styles and renames take the names -DIMSTYLE takes (no `~`,
  which its Restore reads as "compare with", and no wildcards), in the
  `dimstyle` and `dimstyle.rename` commands and in the manager's New and
  Rename, which ask the engine (cmd::usable_dim_style_name). A style read
  from a file keeps its name.
- The manager's OK goes back to the list only when its commands succeed: a
  value the engine refuses keeps the editing page open with every edit.
- Compare offers the style overrides too (the current style with them), so
  comparing them with their style shows what they change.
- The manager opens on its list again after its window is closed, not on the
  page left open, and its preview is drawn on the drawing area's color
  (theme::Tokens), as the canvas is.
- The manager's Rename takes only a name the rename accepts, so renaming a
  style onto another's name no longer leaves the list on that other style.
- The -DIMSTYLE tests apply to a line that's there, and the hostile-input
  test fails on a caught panic (an internal error).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 ba63055fd3 Review fixes: -DIMSTYLE matcher, clear after checks, Override's whole set, ~ in names
From CodeRabbit's review of #1042:
- -DIMSTYLE's list matches style names with QSELECT's wildcard matcher (with
  one backtrack point) instead of a recursive one that a pattern of many `*`
  made exponential: one `list` call could hang the session.
- dimstyle.overrides checks every value (against the style alone when
  `clear` is given) before clearing, so a refused call keeps the overrides.
- The Dimension Style Manager's Override sends what differs from the style
  as the whole override set (`clear` first): a value set back to the style's
  drops its override, and undoing every override drops them all.
- A refused answer at -DIMSTYLE asks the same question again (a ~name that
  names no style used to fall back to the first prompt), and words at
  "Select dimension" ask for the dimension again.
- dimstyle.saveas takes names as -DIMSTYLE does, so no `~` (which Restore
  reads as "compare with").

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
eldrirandClaude Opus 5.5 cec2e0c04a Dimension Style Manager (DIMSTYLE) and -DIMSTYLE
DIMSTYLE (D, DST, DDIM, Format and Dimension menus) opens AutoCAD's Dimension Style Manager:
the drawing's styles (all, or those in use) with the current style's <style overrides> under it,
a preview drawn with the chosen settings, and Set Current, New, Modify, Override, Compare,
Rename and Delete. Modify, Override and New edit every style variable on AutoCAD's seven tabs
(Lines, Symbols and Arrows, Text, Fit, Primary Units, Alternate Units, Tolerances), from the
engine's table of dimension properties; a fixed-height text style shows the height it fixes.
OK changes the style, sets the current style's overrides, or creates the new style, each as one
undo step; programmatic calls never open the dialog.

-DIMSTYLE asks as AutoCAD does: ANnotative, Save (asks before redefining a name in use),
Restore (~name lists how a style differs from the current settings, or pick a dimension),
STatus, Variables, Apply and ?. As JSON it takes {option, ...}. dimstyle.overrides sets the
current style's overrides in one step, and changes nothing when one value is unusable.

An empty leader arrowhead now reads as closed filled, as it is drawn (it read as DIMBLK's).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 8fb5e95f15 Dimension style shortcut commands: imports by name, as #2239 requires
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
eldrirandClaude Opus 5.5 5f4a17cb7c Dimension shortcut menu: Remove Style Overrides, Dimension Style, Precision, Align Text
With dimensions selected, the canvas shortcut menu adds AutoCAD's dimension items:
Align Text ▸ (DIMTEDIT Home/Angle/Left/Center/Right), Dimension Style ▸ (the drawing's styles,
which the selected dimensions take, then Save as New Style), Precision ▸ (DIMDEC, or DIMADEC
for angular dimensions, as overrides) and Remove Style Overrides (available while one of them
overrides its style).

Two commands behind them: dimoverride.clear clears the selected dimensions' overrides, and
dimstyle.saveas makes a new dimension style of a dimension's settings, its overrides included,
gives it to the dimension and clears its overrides (the current style is unchanged). From the
menu it uses the selected dimension, or asks for one, then asks for the name.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:21 -05:00
SlopapaloozaandClaude Opus 5.5 1c02f239c3 Properties palette: the described rows' shared inputs in one struct, within #2239's limit
#2239 denies functions with more than seven arguments. `described_row` took eight; the drawing,
the handles, the angle settings and the shared text style now come together as `Rows`, which
the row destructures under the same names. Nothing changes in behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 ea0d0e9595 Review fixes: picking the color a row already has is no edit; directions typed as measured
From CodeRabbit's reviews of #994:
- The palette's color menu sent the color number while the row's value is
  the color's name, so picking the color a row already showed still ran
  properties.set (and made an undo step). The menu now compares by name and
  sends nothing for the color already set.
- A rotation (a direction row) typed in the palette is read as the drawing
  measures directions (AngleSettings::direction): a surveyor's bearing such
  as N45dE is absolute, and `<<a` / `<<<a` measure from +X counterclockwise.
  Both were turned by ANGBASE before (or refused, for `<<`).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
eldrirandClaude Opus 5.5 5c24bc3dcf Properties palette: text, mtext and dimension rows from properties.describe
The palette draws the groups the engine describes for text, mtext and dimensions after its own
General group, so a dimension's text height (and every other dimension style setting) is edited
there as an override of the selected dimensions, and TEXT and MTEXT get their style,
justification, obliquing, line spacing and position rows. Several objects of one type edit
together, with *VARIES* where they differ.

Rows read values as the command line does (distances in any unit format, angles in the
drawing's angle units); unreadable text and values the engine refuses are reported. An
overridden dimension row has its label in the accent color, and right-clicking it puts the
style's value back. A fixed-height text style's height shows read-only with the reason.

A few engine labels are renamed to translate cleanly and fit the label column; every label the
engine gives the palette has a Ukrainian row, and `cargo xtask i18n` reports any that go missing.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 5689203791 Dimensions: an explicit text rotation sizes the dimension line's gap
A linear or aligned dimension broke its line around the text as DIMTIH and DIMTOH turn it,
and only then applied an explicit text rotation (DIMTEDIT Angle, or Text rotation in the
Properties palette). Text turned along a vertical dimension line drew over the line, which
left a gap only the height of horizontal text, whatever the text offset (DIMGAP). The gap, the
fit check and the text's clearance now take the text as turned.

Found by testing #1042 (Dievartis). A test checks that no part of the dimension line crosses
text turned along it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 b99ea8905e properties.set: one function per kind of object, within #2239's clippy limits
#2239 denies a cognitive complexity over 30 and wildcard imports. properties.set's per-object
edit (complexity 90) becomes one function per kind of object (line, circle, arc, text and its
position, mtext and its line spacing, insert, dimension and its prefix and suffix, hatch) and
one for the properties every object has; what the call checked before any object changes
travels in a `Call`. set.rs and props.rs import by name. Nothing changes in behavior.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 c1c97ed00e Review fixes: SOLID drops the gradient, all objects checked first, Align rotation, DIMPOST rows
From CodeRabbit's second to fourth reviews of #954, and codyvogt (from #1371's):
- The Properties pattern edit and HATCHEDIT share one helper
  (hatch::set_pattern) and one rule for the names a hatch takes: SOLID drops
  a gradient fill too, a blank name changes nothing (it's reported as
  ignored), and a name no pattern has is refused, as HATCHEDIT refuses it (a hatch's own
  name matches in any case).
- properties.set refuses a call that names an object that isn't there before
  it edits any, so a bad handle late in the list no longer leaves the
  earlier objects edited.
- A prefix or suffix edit goes into the DIMPOST/DIMAPOST the dimension has
  after the call's other edits (its new style, cleared overrides), not the
  ones it had before.
- The prefix and suffix rows are marked overridden when DIMPOST or DIMAPOST
  is, and their "Use the style's value" clears that variable.
- Rotating aligned or fit TEXT turns its baseline's second point with it
  (the renderer takes their direction from the two points).
- Justify Align or Fit measures the baseline from the text as the call
  leaves it (its new contents, style, height, width factor and rotation).
- `scale` is an insert's or hatch's scale only; it no longer also becomes a
  DIMSCALE override of a dimension in the selection (that's `dimScale`).
- A text style that only a dimension's text style override names is in use,
  so style.delete refuses it (a rename follows those overrides already).
- Editing a text or dimension style redraws the dimensions read from a file
  only when the style changed: making it current keeps their geometry.
- docs/mcp.md's example finds the dimension's handle with query_entities
  before it describes and sets it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
SlopapaloozaandClaude Opus 5.5 a551f206e8 Review fixes: hatch pattern lines, closed-filled ends, measurements, layer after checks
From CodeRabbit's review of #954:
- A Properties pattern edit follows HATCHEDIT: a library pattern drops the
  hatch's own lines, a loaded .pat pattern brings its lines, and any other
  name keeps them (the moved code cleared them unconditionally).
- Closed filled chosen for Arrow 1 or Arrow 2 is stored as _CLOSEDFILLED: an
  empty per-end arrowhead draws DIMBLK's, so "" changed nothing under a tick.
- The Measurement row writes angles in the dimension's angle format
  (DIMAUNIT, DIMADEC, DIMAZIN) as the renderer does, and equal measurements
  written differently (units, precision) show *VARIES*.
- Text height with fixed-height text styles of different heights shows
  *VARIES* instead of the dimensions' shared DIMTXT.
- properties.set creates a new layer only after every check, so a refused
  call leaves no layer behind.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
eldrirandClaude Opus 5.5 b70c8609c9 Properties: describe and set every text, mtext and dimension property
properties.describe lists the Properties palette's rows for a selection: General for every
object; Text and Geometry for TEXT and MTEXT; Misc, Lines & Arrows, Text, Fit, Primary Units,
Alternate Units and Tolerances for dimensions. Each row carries the properties.set key that
changes it, the value the objects share (or *VARIES*), the value in the drawing's units, whether
it can be edited (a fixed-height text style makes a dimension's text height read-only and says
so), and for dimensions whether the dimension overrides its style there. A mixed selection gets
the General group; `type` limits the description to one object type.

properties.set takes those keys: TEXT style, justify (keeping the point the text is placed by),
oblique, positionX/Y/Z and the second point of aligned and fit text; MTEXT style, justify,
lineSpacing, lineSpacingDistance and lineSpacingStyle, position; dimension style variables by
field or DIM* name as overrides of each dimension, clearOverrides, clear, textRotation,
textPositionX/Y, prefix and suffix. The reply lists the keys no selected object took.

Editing a dimension style or a text style now redraws the dimensions read from files that use it
(they kept drawing, and saving, the *D block they were read with), and renaming a text style
follows a dimension's own text style override.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-04 22:53:20 -05:00
101 changed files with 3918 additions and 243 deletions
Generated
+96 -5
View File
@@ -759,6 +759,7 @@ dependencies = [
"cadcraft-ui-egui",
"chrono",
"clap",
"craft-automation",
"craft-nightly",
"craft-quit",
"craft-update",
@@ -781,6 +782,8 @@ dependencies = [
"winit",
"winresource",
"winsafe",
"x11-dl",
"xkbcommon-dl",
"zbus",
]
@@ -840,6 +843,7 @@ dependencies = [
"cadcraft-geom",
"cadcraft-io",
"cadcraft-render",
"craft-control",
"craft-csv",
"craft-docpath",
"craft-dxf",
@@ -908,6 +912,8 @@ dependencies = [
"cadcraft-io",
"cadcraft-render",
"clap",
"craft-automation",
"craft-control",
"craft-jsonrpc",
"craft-mcp",
"getrandom 0.4.3",
@@ -944,7 +950,9 @@ dependencies = [
"cadcraft-io",
"cadcraft-render",
"chrono",
"craft-automation",
"craft-behavior",
"craft-control",
"craft-host",
"craft-image-codecs",
"craft-keymap",
@@ -1379,6 +1387,16 @@ dependencies = [
"libc",
]
[[package]]
name = "craft-ai-agents"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-ai-integrations?rev=d94a3593adcff504eaaad9e5aee4c84fd2f07a72#d94a3593adcff504eaaad9e5aee4c84fd2f07a72"
dependencies = [
"dirs",
"serde",
"serde_json",
]
[[package]]
name = "craft-appkit"
version = "0.1.0"
@@ -1397,6 +1415,31 @@ dependencies = [
"rustix 1.1.6",
]
[[package]]
name = "craft-automation"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"base64 0.23.1",
"craft-behavior",
"craft-control",
"craft-host",
"craft-keymap",
"craft-platform",
"craft-theme",
"craft-ui",
"egui",
"getrandom 0.3.4",
"hmac",
"log",
"png 0.17.16",
"serde",
"serde_json",
"sha2",
"thiserror 2.0.21",
"web-time",
]
[[package]]
name = "craft-behavior"
version = "0.1.0"
@@ -1428,6 +1471,21 @@ name = "craft-codepage"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
[[package]]
name = "craft-control"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"craft-ai-agents",
"craft-atomic",
"craft-flags",
"dirs",
"getrandom 0.3.4",
"log",
"serde",
"serde_json",
]
[[package]]
name = "craft-csv"
version = "0.1.0"
@@ -1473,6 +1531,16 @@ dependencies = [
"thiserror 2.0.21",
]
[[package]]
name = "craft-flags"
version = "0.1.0"
source = "git+https://github.com/storytold/craft-libs?rev=8fa4db64a9bb943520259ea95331a303ba788f21#8fa4db64a9bb943520259ea95331a303ba788f21"
dependencies = [
"craft-atomic",
"dirs",
"toml_edit",
]
[[package]]
name = "craft-font-catalog"
version = "0.1.0"
@@ -1550,7 +1618,7 @@ dependencies = [
"image",
"image-webp",
"jpeg-encoder",
"png",
"png 0.18.1",
"rayon",
"serde_json",
"thiserror 2.0.21",
@@ -2105,6 +2173,7 @@ checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
dependencies = [
"block-buffer",
"crypto-common",
"subtle",
]
[[package]]
@@ -3271,6 +3340,15 @@ dependencies = [
"windows-sys 0.61.2",
]
[[package]]
name = "hmac"
version = "0.12.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
dependencies = [
"digest",
]
[[package]]
name = "http"
version = "1.5.0"
@@ -3620,7 +3698,7 @@ dependencies = [
"gif",
"moxcms",
"num-traits",
"png",
"png 0.18.1",
"qoi",
"tiff",
"zune-core",
@@ -3853,7 +3931,7 @@ dependencies = [
"imagesize 0.14.0",
"indexmap",
"pdf-writer",
"png",
"png 0.18.1",
"rustc-hash 2.1.3",
"siphasher",
"skrifa 0.42.1",
@@ -4154,7 +4232,7 @@ dependencies = [
"objc2-app-kit 0.3.2",
"objc2-core-foundation",
"objc2-foundation 0.3.2",
"png",
"png 0.18.1",
"thiserror 2.0.21",
"windows-sys 0.61.2",
]
@@ -5211,6 +5289,19 @@ dependencies = [
"time",
]
[[package]]
name = "png"
version = "0.17.16"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
dependencies = [
"bitflags 1.3.2",
"crc32fast",
"fdeflate",
"flate2",
"miniz_oxide 0.8.9",
]
[[package]]
name = "png"
version = "0.18.1"
@@ -6458,7 +6549,7 @@ dependencies = [
"bytemuck",
"cfg-if",
"log",
"png",
"png 0.18.1",
"tiny-skia-path",
]
+5
View File
@@ -33,6 +33,11 @@ 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" }
# 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 = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# 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 = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# SVG/SVGZ import and export geometry (craft-libs#778).
craft-svg = { git = "https://github.com/storytold/craft-libs", rev = "8fa4db64a9bb943520259ea95331a303ba788f21" }
# Which paths stored in a drawing (xrefs, data links) may be opened.
+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(
+8
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,6 +53,8 @@ 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"
+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)
+26
View File
@@ -45,6 +45,31 @@ pub struct ForeignExtra {
/// Unmodelled groups of the record's own last subclass, written just before its xdata. Filled
/// on save from the entity itself ([`crate::Viewport::extra`]), so that copies keep them.
pub tail: Vec<RawTag>,
/// A lightweight polyline's vertex identifiers (group 91, DXF 2010 and later) as read: one per
/// vertex in the polyline's order; empty when the file gave none. Geometric constraints name the
/// polyline's segments by them, so they are written back while the polyline's vertices are
/// where they were read ([`vertex_ids_for`]).
pub vertex_ids: Vec<VertexId>,
}
/// A vertex of a lightweight polyline as it was read: its identifier and its point as the
/// polyline has it once read (a polyline whose normal points down is read mirrored in x).
#[derive(Clone, Copy, Debug, Default, PartialEq)]
pub struct VertexId {
/// The identifier (group 91); 0 for a vertex without one.
pub id: i32,
pub x: f64,
pub y: f64,
}
/// The identifiers `kept` gives the vertices at `points`, in their order, while every vertex is
/// where it was read. `None` once a vertex was added, removed, moved or the order changed: the
/// identifiers no longer say which vertex is which.
pub fn vertex_ids_for(kept: &[VertexId], points: impl ExactSizeIterator<Item = (f64, f64)> + Clone) -> Option<Vec<i32>> {
if kept.is_empty() || kept.len() != points.len() {
return None;
}
kept.iter().zip(points).all(|(k, (x, y))| k.x == x && k.y == y).then(|| kept.iter().map(|k| k.id).collect())
}
impl ForeignExtra {
@@ -55,6 +80,7 @@ impl ForeignExtra {
&& self.color_book.is_none()
&& self.props.is_empty()
&& self.tail.is_empty()
&& self.vertex_ids.is_empty()
}
}
+2
View File
@@ -154,6 +154,8 @@ impl Header {
// Annotation scale of model space; annotative objects of other scales show (1) or not.
h.set_str("CANNOSCALE", "1:1");
h.set_i64("ANNOALLVISIBLE", 1);
// Written to DXF as $REGENMODE; a header variable the drawing lacks is not written.
h.set_i64("REGENMODE", 1);
h
}
+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,
};
+1 -1
View File
@@ -237,7 +237,7 @@ impl Interactive for SetvarM {
}
}
}
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &Value::String(t)) {
(Some(n), Input::Text(t)) => match crate::sysvars::set(s, &n, &crate::sysvars::typed_value(&n, t)) {
Ok(()) => {
s.touch();
Ok(Step::Done)
+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();
+7 -6
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
+4
View File
@@ -149,6 +149,9 @@ pub struct Settings {
/// ATTDIA: INSERT typed or from a menu asks for attribute values in the Edit Attributes
/// dialog; on by default, as in AutoCAD (Initial value 1).
pub attdia: bool,
/// TEXTEVAL: 1 lets a routine's input be read as LISP where it would be text (default: 0).
/// Kept for routines that switch it around their prompts; no prompt reads it yet.
pub texteval: bool,
}
impl Default for Settings {
@@ -220,6 +223,7 @@ impl Default for Settings {
auditctl: false,
attreq: true,
attdia: true,
texteval: false,
}
}
}
+109 -3
View File
@@ -7,7 +7,14 @@ use cadcraft_doc::library::{MIN_HATCH_PATTERN_SCALE, is_supported_hatch_pattern_
mod table;
/// ACADVER: the program's release, as a text AutoCAD documents it and `atof` reads back as a
/// number. A drawing's `$ACADVER` header is its file version, which is what a save writes, so the
/// two are separate values: `get` gives this text, `list` too, and the header stays as read.
pub const ACADVER_TEXT: &str = "24.3s (CADCraft)";
const SESSION_VARS: &[&str] = &[
// The release text, with or without a drawing (the header's `$ACADVER` is the file version).
"ACADVER",
"AUDITCTL",
"ATTREQ",
"OSMODE",
@@ -81,10 +88,54 @@ const SESSION_VARS: &[&str] = &[
"SAVETIME",
"SAVEFILEPATH",
"ISAVEBAK",
"DIMASO",
"TEXTEVAL",
"POPUPS",
];
pub fn get(s: &Session, name: &str) -> Option<Value> {
/// The DIMASSOC mode DIMASO turned off, kept in the drawing's header so undo restores it.
/// `CADCRAFT_` names are not listed by SYSVARS and no file writes this one.
const DIMASO_MODE: &str = "CADCRAFT_DIMASO_MODE";
/// The header key above, under any number of `$`: no variable of that name exists.
fn is_internal(n: &str) -> bool {
n.trim_start_matches('$') == DIMASO_MODE
}
/// The names this session also answers with DXF's `$` in front: the header writes them that way
/// (`$DIMASO`, `$TEXTEVAL`, `$REGENMODE`, `$POPUPS`), so a routine may type either form.
const DOLLAR_VARS: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"];
/// [`set`] takes only a number for these: a program's or a routine's text is refused. A value
/// typed at the command line arrives as text and goes through [`typed_value`] first.
const NUMBER_ONLY: &[&str] = &["DIMASO", "TEXTEVAL", "REGENMODE"];
/// The value of `text` typed at a SETVAR prompt for `name`: typed digits are a number for the
/// [`NUMBER_ONLY`] variables. Anything else stays text.
pub(crate) fn typed_value(name: &str, text: String) -> Value {
if NUMBER_ONLY.contains(&bare_name(name).as_str())
&& let Ok(number) = text.trim().parse::<i64>()
{
return json!(number);
}
Value::String(text)
}
/// `name` trimmed and upper case, without the `$` those names take. Every other name keeps the
/// `$` it was typed with: `$ANGBASE` stays a name of its own (LISP converts radians only for the
/// plain name) and `$OSMODE` is not the session's OSMODE.
fn bare_name(name: &str) -> String {
let n = name.trim().to_ascii_uppercase();
// Every leading `$`, as the header drops them all when it stores a value.
let rest = n.trim_start_matches('$');
if rest.len() < n.len() && DOLLAR_VARS.contains(&rest) { rest.to_string() } else { n }
}
pub fn get(s: &Session, name: &str) -> Option<Value> {
let n = bare_name(name);
if is_internal(&n) {
return None;
}
let st = &s.settings;
let v = match n.as_str() {
"OSMODE" => json!(st.osmode),
@@ -177,6 +228,12 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"SAVETIME" => json!(crate::autosave::savetime()),
"SAVEFILEPATH" => json!(crate::autosave::savefilepath()),
"ISAVEBAK" => json!(i32::from(crate::autosave::isavebak())),
// DIMASO is obsolete in AutoCAD and has no value of its own: it reports DIMASSOC.
"DIMASO" => json!(i32::from(matches!(dimassoc(s)?, 1 | 2))),
// Whether a prompt reads typed text as LISP (routines switch it around their prompts).
"TEXTEVAL" => json!(i32::from(st.texteval)),
// Dialogs are available (read-only; a batch session is still told 1, as AutoCAD does).
"POPUPS" => json!(1),
"CMDNAMES" => json!(s.running.as_ref().map(|r| r.id.to_ascii_uppercase()).unwrap_or_default()),
"DWGNAME" => json!(s.state().map(|d| d.title.clone()).unwrap_or_default()),
"DBMOD" => json!(s.state().map(|d| i32::from(d.is_dirty())).unwrap_or(0)),
@@ -189,6 +246,9 @@ pub fn get(s: &Session, name: &str) -> Option<Value> {
"DWGTITLED" => json!(s.state().map(|d| i32::from(d.path.is_some())).unwrap_or(0)),
"CMDACTIVE" => json!(i32::from(s.running.is_some())),
"TILEMODE" => json!(i32::from(s.state().is_ok_and(|d| d.space.layout().is_none()))),
// The release number as AutoCAD reports it, so `(atof (getvar "ACADVER"))` is 24.3; the
// drawing's own `$ACADVER` (its file version) is left alone for the save version.
"ACADVER" => json!(ACADVER_TEXT),
"PLATFORM" => json!(std::env::consts::OS),
"BLOCKEDITOR" => json!(i32::from(s.state().is_ok_and(|d| d.block_edit.is_some()))),
// The template NEW/QNEW start from (a profile setting, like FONTALT; "" = none).
@@ -257,6 +317,11 @@ fn dwg_prefix(path: &str) -> String {
}
}
/// DIMASSOC's value (0 off, 1 or 2 associative), read where DIMASO reports it from.
fn dimassoc(s: &Session) -> Option<i64> {
table::get(s, "DIMASSOC")?.as_i64()
}
fn as_bool(v: &Value) -> Option<bool> {
v.as_bool().or_else(|| v.as_i64().map(|i| i != 0)).or_else(|| v.as_str().and_then(|s| s.trim().parse::<i64>().ok()).map(|i| i != 0))
}
@@ -277,6 +342,7 @@ fn as_pt(v: &Value) -> Option<cadcraft_geom::Vec2> {
/// Variables `get` reports from session or drawing state that `set` can't change.
const READ_ONLY: &[&str] = &[
"ACADVER",
"CMDNAMES",
"DWGNAME",
"DWGPREFIX",
@@ -304,10 +370,15 @@ const READ_ONLY: &[&str] = &[
"UCSXDIR",
"UCSYDIR",
"WORLDUCS",
// Dialogs: a session always has them, so the variable is fixed (not saved).
"POPUPS",
];
pub fn is_read_only(name: &str) -> bool {
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(name.trim())) || table::is_read_only(&name.trim().to_ascii_uppercase())
// A header name's `$` is ignored: the header drops it when it stores a value, so `$ACADVER`
// would otherwise change ACADVER, and with it the version a save writes.
let n = name.trim().trim_start_matches('$').trim();
READ_ONLY.iter().any(|r| r.eq_ignore_ascii_case(n)) || table::is_read_only(&n.to_ascii_uppercase())
}
/// POLARADDANG as typed: up to ten angles in degrees separated by `;` (radians out); `None` when
@@ -325,11 +396,17 @@ pub fn format_angle_list(angles: &[f64]) -> String {
/// Set a system variable, refusing values out of its range and folders the automation roots can't hold.
pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
let n = name.trim().to_ascii_uppercase();
let n = bare_name(name);
if is_internal(&n) {
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("unknown variable `{n}`") });
}
if is_read_only(&n) {
return Err(EngineError::BadParams { cmd: "setvar".into(), msg: format!("{n} is read-only") });
}
let bad = || EngineError::BadParams { cmd: "setvar".into(), msg: format!("invalid value for {n}") };
if NUMBER_ONLY.contains(&n.as_str()) && !v.is_number() {
return Err(bad());
}
let st = &mut s.settings;
match n.as_str() {
"OSMODE" => {
@@ -436,6 +513,35 @@ pub fn set(s: &mut Session, name: &str, v: &Value) -> Result<()> {
}
"SAVEFILEPATH" => crate::autosave::set_savefilepath(v.as_str().ok_or_else(bad)?),
"ISAVEBAK" => crate::autosave::set_isavebak(as_bool(v).ok_or_else(bad)?),
// DIMASO has no value of its own: 0 turns DIMASSOC off (remembering the mode it had),
// 1 restores that mode (2 when none was seen), and 1 while it is on changes nothing. The
// mode it remembers is in the drawing's header ([`DIMASO_MODE`]), so each open drawing
// keeps its own and undo restores it with DIMASSOC; no file writes it.
"DIMASO" => {
let on = as_i(v).filter(|i| matches!(i, 0 | 1)).ok_or_else(bad)? == 1;
let mode = dimassoc(s).ok_or_else(bad)?;
// The drawing is touched only when DIMASSOC changes, so it is not marked modified
// and no undo step is left for a value it already has.
match (on, mode) {
(true, 1 | 2) | (false, 0) => {}
// Turned back on, from off or from a file's unknown mode: the mode it had.
(true, _) => {
let h = &mut s.doc_mut()?.header;
// Only a mode DIMASSOC takes: a file's value of anything else restores 2.
let restore = h.i64(DIMASO_MODE, 2);
h.set_i64("DIMASSOC", if matches!(restore, 1 | 2) { restore } else { 2 });
}
(false, _) => {
let h = &mut s.doc_mut()?.header;
if matches!(mode, 1 | 2) {
h.set_i64(DIMASO_MODE, mode);
}
h.set_i64("DIMASSOC", 0);
}
}
}
// Stored for routines that switch it around their prompts; no prompt reads it yet.
"TEXTEVAL" => st.texteval = small(v, 1).ok_or_else(bad)? == 1,
// A number is in degrees; text is an angle typed in AUNITS (SETVAR at the command line).
"ANGBASE" => {
let a = match v {
+2
View File
@@ -73,6 +73,8 @@ const HEADER: &[(&str, Kind, Def)] = &[
("PLINEWID", Kind::Real { min: 0.0, strict: false }, Def::Real(0.0)),
("POLYSIDES", Kind::Int(3, 1024), Def::Int(4)),
("PROJMODE", Kind::Choice(&[0, 1, 2]), Def::Int(1)),
// 1 regenerates the drawing after a command that changes it (stored, nothing reads it yet).
("REGENMODE", Kind::Choice(&[0, 1]), Def::Int(1)),
("REVCLOUDARCLEN", Kind::Real { min: 0.0, strict: true }, Def::Units(0.5, 15.0)),
("SPLINESEGS", Kind::Int(-32768, 32767), Def::Int(8)),
("SPLKNOTS", Kind::Choice(&[0, 1, 2]), Def::Int(0)),
+111
View File
@@ -0,0 +1,111 @@
//! ACADVER is the program's release as text, as AutoCAD documents it, so `(atof (getvar
//! "ACADVER"))` reads a number from it. It is read-only, and the drawing's `$ACADVER` stays the
//! file version a save writes, so a drawing read from a 2000 DXF saves as one.
use cadcraft_engine::Session;
use cadcraft_engine::lisp::value::Value;
use serde_json::json;
/// The release text `getvar` and `(getvar "ACADVER")` report.
const RELEASE: &str = "24.3s (CADCraft)";
/// A 2000 DXF (`$ACADVER` `AC1015`) holding one line.
const DXF: &str = "0\nSECTION\n2\nHEADER\n9\n$ACADVER\n1\nAC1015\n0\nENDSEC\n\
0\nSECTION\n2\nENTITIES\n\
0\nLINE\n8\n0\n10\n0.0\n20\n0.0\n30\n0.0\n11\n10.0\n21\n0.0\n31\n0.0\n\
0\nENDSEC\n0\nEOF\n";
/// A LISP expression's value, or its error message.
fn lisp(s: &mut Session, code: &str) -> Result<Value, String> {
match s.lisp_eval(code, false, true, Vec::new()) {
Ok(Some(Ok(v))) => Ok(v),
Ok(Some(Err(e))) => Err(e),
Ok(None) => Err("did not finish".into()),
Err(e) => Err(e.to_string()),
}
}
/// GETVAR's value.
fn getvar(s: &mut Session, name: &str) -> serde_json::Value {
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
}
/// The `$ACADVER` a DXF text declares.
fn file_version(text: &str) -> Option<String> {
let l: Vec<&str> = text.lines().map(str::trim).collect();
let at = l.windows(2).position(|w| w == ["9", "$ACADVER"])?;
l.get(at + 2).filter(|c| **c == "1").and_then(|_| l.get(at + 3)).map(|v| (*v).to_string())
}
#[test]
fn getvar_gives_the_release_text_and_atof_reads_the_number() {
let mut s = Session::new();
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(getvar(&mut s, "acadver"), json!(RELEASE), "lower-case names work");
assert!(matches!(lisp(&mut s, "(getvar \"ACADVER\")"), Ok(Value::Str(t)) if &*t == RELEASE), "a LISP string");
assert!(matches!(lisp(&mut s, "(atof (getvar \"ACADVER\"))"), Ok(Value::Real(r)) if (r - 24.3).abs() < 1e-9), "(atof) reads the release number");
}
#[test]
fn setvar_refuses_acadver_and_changes_nothing() {
let mut s = Session::new();
let before = s.state().unwrap().doc.header.str("ACADVER", "");
let e = s.execute("setvar", &json!({ "name": "ACADVER", "value": "AC1027" })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{e}");
assert!(lisp(&mut s, "(setvar \"ACADVER\" \"AC1027\")").is_err(), "AutoLISP's setvar too");
// Typed at the command line, SETVAR reports the variable as read-only at its name prompt.
s.cmdline("setvar acadver").unwrap();
assert!(s.log.iter().any(|l| l == &format!("ACADVER = {RELEASE} (read only)")), "{:?}", s.log);
// Neither the release text nor the drawing's file version moved.
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), before);
assert_eq!(before, "AC1032");
}
#[test]
fn a_2000_drawing_saves_as_2000() {
crate::refedit_xref::hooks();
let dir = std::path::Path::new(env!("CARGO_TARGET_TMPDIR")).join(format!("acadver-{}", std::process::id()));
std::fs::create_dir_all(&dir).unwrap();
let path = dir.join("r2000.dxf");
let name = path.to_string_lossy().into_owned();
let mut s = Session::empty();
s.open_drawing(cadcraft_io::read_dxf(DXF.as_bytes()).unwrap(), "r2000.dxf", Some(name.clone()));
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015", "read as 2000");
assert_eq!(cadcraft_io::save_version(&s.state().unwrap().doc), cadcraft_io::Version::R2000);
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE), "still the release text");
s.execute("qsave", &json!({})).unwrap();
let saved = std::fs::read_to_string(&path).unwrap();
assert_eq!(file_version(&saved).as_deref(), Some("AC1015"), "the file keeps its 2000 version");
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1015");
assert_eq!(getvar(&mut s, "ACADVER"), json!(RELEASE));
assert_eq!(cadcraft_io::read_dxf(saved.as_bytes()).unwrap().header.str("ACADVER", ""), "AC1015", "and reopens as 2000");
let _ = std::fs::remove_dir_all(&dir);
}
#[test]
fn a_dollar_name_cannot_change_the_file_version() {
let mut s = Session::new();
let e = s.execute("setvar", &json!({ "name": "$ACADVER", "value": "AC1027" })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{e}");
assert!(lisp(&mut s, "(setvar \"$ACADVER\" \"AC1015\")").is_err(), "AutoLISP's setvar too");
assert_eq!(s.state().unwrap().doc.header.str("ACADVER", ""), "AC1032", "the save version did not move");
assert!(cadcraft_engine::sysvars::is_read_only("$acadver"), "SETVAR's prompt sees it as read-only too");
// Other `$` names still reach the header as before, in LISP's units.
assert!(lisp(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
assert!(matches!(lisp(&mut s, "(getvar \"$ANGBASE\")"), Ok(Value::Real(r)) if (r - std::f64::consts::FRAC_PI_2).abs() < 1e-9));
let r = s.execute("setvar", &json!({ "name": "$OSMODE", "value": 9 })).unwrap();
assert_eq!(r["value"], json!(9), "{r}");
}
#[test]
fn listings_show_the_release_text_without_a_drawing() {
let mut s = Session::empty();
let all = s.execute("sysvars", &json!({})).unwrap();
let text = all.to_string();
assert!(text.contains(RELEASE), "{text}");
let mut s = Session::new();
let all = s.execute("sysvars", &json!({})).unwrap().to_string();
assert!(all.contains(RELEASE) && !all.contains("\"AC1032\""), "{all}");
}
+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)));
}
+386
View File
@@ -0,0 +1,386 @@
//! Legacy system variables a LISP routine saves and restores around its work: DIMASO (obsolete in
//! AutoCAD, which reports and sets DIMASSOC through it), TEXTEVAL, REGENMODE (kept in the drawing
//! and its DXF header) and POPUPS (read-only). Before them `(getvar "DIMASO")` read nil, so
//! `(setq o (getvar "DIMASO")) … (setvar "DIMASO" o)` failed and the routine left the drawing's
//! associativity changed.
use cadcraft_engine::Session;
use cadcraft_engine::lisp::value::{Value as LispValue, to_text};
use serde_json::{Value, json};
fn getvar(s: &mut Session, name: &str) -> Value {
s.execute("getvar", &json!({ "name": name })).unwrap()["value"].clone()
}
fn setvar(s: &mut Session, name: &str, value: Value) -> bool {
s.execute("setvar", &json!({ "name": name, "value": value })).is_ok()
}
/// The value of a LISP expression, or the error it left.
fn eval(s: &mut Session, src: &str) -> Result<LispValue, String> {
match s.lisp_eval(src, false, true, Vec::new()) {
Ok(Some(v)) => v,
Ok(None) => Err("no value".into()),
Err(e) => Err(e.to_string()),
}
}
/// `(getvar name)` as the integer a routine receives.
fn lisp_getvar(s: &mut Session, name: &str) -> i64 {
let v = eval(s, &format!("(getvar \"{name}\")")).unwrap_or_else(|e| panic!("{name}: {e}"));
let n = v.as_number().unwrap_or_else(|| panic!("{name} is not a number"));
assert_eq!(n.fract(), 0.0, "{name} is a whole number");
n as i64
}
/// `(setvar name value)` from LISP: whether it was accepted.
fn lisp_setvar(s: &mut Session, name: &str, value: &str) -> bool {
eval(s, &format!("(setvar \"{name}\" {value})")).is_ok()
}
/// The DXF pairs `(group code, value)` of a file, both trimmed.
fn pairs(text: &str) -> Vec<(i32, String)> {
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut out = Vec::new();
for chunk in lines.chunks(2) {
let [code, value] = chunk else { break };
let Ok(c) = code.parse::<i32>() else { continue };
out.push((c, (*value).to_string()));
}
out
}
/// The HEADER variable names a DXF text writes (the value after each group code 9).
fn header_names(text: &str) -> Vec<String> {
pairs(text).iter().filter(|(c, _)| *c == 9).map(|(_, v)| v.trim_start_matches('$').to_string()).collect()
}
/// The integer a header variable is written with, as `(group code, value)` after its name.
fn header_int(text: &str, name: &str) -> Option<(i32, String)> {
let ps = pairs(text);
let i = ps.iter().position(|(c, v)| *c == 9 && v.trim_start_matches('$') == name)?;
ps.get(i + 1).cloned()
}
#[test]
fn fresh_values_are_integers_a_routine_reads() {
let mut s = Session::new();
for (name, want) in [("DIMASO", 1), ("TEXTEVAL", 0), ("REGENMODE", 1), ("POPUPS", 1)] {
assert_eq!(getvar(&mut s, name), json!(want), "{name}");
assert_eq!(lisp_getvar(&mut s, name), want, "{name} through getvar");
let kind = eval(&mut s, &format!("(type (getvar \"{name}\"))")).unwrap();
assert_eq!(to_text(&kind, true), "INT", "{name} is an integer to LISP");
}
// The list a routine sees (`SETVAR ?`) carries them too.
let all = cadcraft_engine::sysvars::list(&s);
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
assert_eq!(all.get(name), Some(&getvar(&mut s, name)), "{name} listed");
}
}
#[test]
fn a_routine_saving_and_restoring_each_one_leaves_it_as_it_was() {
let mut s = Session::new();
for (name, changed) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
let before = lisp_getvar(&mut s, name);
// (setq o (getvar X)) … (setvar X o) must give back exactly what it read.
assert!(eval(&mut s, &format!("(setq o (getvar \"{name}\"))")).is_ok(), "{name} readable");
assert!(lisp_setvar(&mut s, name, changed), "{name} takes {changed}");
assert_ne!(lisp_getvar(&mut s, name), before, "{name} changed by {changed}");
assert!(eval(&mut s, &format!("(setvar \"{name}\" o)")).is_ok(), "{name} restored");
assert_eq!(lisp_getvar(&mut s, name), before, "{name} back to {before}");
}
// REGENMODE is the drawing's, kept in its header; TEXTEVAL only the session's.
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 1);
}
#[test]
fn dimaso_restores_the_dimassoc_mode_it_turned_off() {
// The routine's save/restore through DIMASO, for each associative mode.
for mode in [1, 2] {
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(mode)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1), "DIMASO follows DIMASSOC {mode}");
let o = eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number().unwrap();
assert!(lisp_setvar(&mut s, "DIMASO", "0"));
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "DIMASO 0 turns associativity off");
assert!(lisp_setvar(&mut s, "DIMASO", "1"));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(eval(&mut s, "(getvar \"DIMASSOC\")").unwrap().as_number(), Some(o), "DIMASO 1 puts back the DIMASSOC {mode} the routine read");
}
// Set directly, without ever switching it off first, DIMASO 1 leaves the mode alone.
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
// No non-zero mode was seen: turning associativity back on gives AutoCAD's 2.
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "none was seen: the default 2");
// A drawing whose saved DIMASSOC is no mode DIMASO can restore (a hostile file) gives 2.
let mut s = Session::new();
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
assert!(setvar(&mut s, "DIMASO", json!(0)));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
// Such a mode is not associative, and DIMASO 1 turns associativity on from it too.
s.doc_mut().unwrap().header.set_i64("DIMASSOC", 5);
assert_eq!(getvar(&mut s, "DIMASO"), json!(0));
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASO"), json!(1));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2));
}
#[test]
fn typed_setvar_still_takes_digits() {
for (name, digits) in [("DIMASO", "0"), ("TEXTEVAL", "1"), ("REGENMODE", "0")] {
let want = json!(digits.parse::<i64>().unwrap());
let dollar = format!("${name}");
// SETVAR with the name, the bare name, and the `$` form, as typed at the command line.
for lines in [vec!["setvar", name, digits], vec![name, digits], vec!["setvar", dollar.as_str(), digits]] {
let mut s = Session::new();
for line in &lines {
s.cmdline(line).unwrap();
}
assert_eq!(getvar(&mut s, name), want, "typed {lines:?}");
}
// A routine that types the command passes its answers the same way.
let mut s = Session::new();
eval(&mut s, &format!("(command \"SETVAR\" \"{name}\" \"{digits}\")")).unwrap();
assert_eq!(getvar(&mut s, name), want, "(command \"SETVAR\" {name})");
// Typed words are still refused.
let mut s = Session::new();
let before = getvar(&mut s, name);
for line in ["setvar", name, "two"] {
s.cmdline(line).unwrap();
}
assert_eq!(getvar(&mut s, name), before, "typed word refused for {name}");
}
}
#[test]
fn a_new_drawing_writes_regenmode() {
let mut s = Session::new();
// The first drawing, then a new metric and a new imperial one.
for metric in [None, Some(true), Some(false)] {
if let Some(metric) = metric {
s.new_drawing(metric);
}
let text = cadcraft_io::write_dxf(s.doc().unwrap());
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "1".to_string())), "new drawing, metric {metric:?}");
}
}
#[test]
fn hostile_values_are_refused_and_change_nothing() {
let mut s = Session::new();
for (name, v) in [
("REGENMODE", json!(2)),
("REGENMODE", json!(-1)),
("REGENMODE", json!(1.5)),
("REGENMODE", json!("two")),
("REGENMODE", Value::Null),
("TEXTEVAL", json!(-1)),
("TEXTEVAL", json!(2)),
("TEXTEVAL", json!("two")),
("TEXTEVAL", Value::Null),
("DIMASO", json!(3)),
("DIMASO", json!(-1)),
("DIMASO", json!(0.5)),
("DIMASO", json!("two")),
("DIMASO", Value::Null),
// Text a program or a routine passes is refused even when it spells a number.
("REGENMODE", json!("0")),
("TEXTEVAL", json!("1")),
("DIMASO", json!("0")),
("TEXTEVAL", json!(true)),
] {
let before = getvar(&mut s, name);
assert!(!setvar(&mut s, name, v.clone()), "{name} = {v} refused");
assert_eq!(getvar(&mut s, name), before, "{name} unchanged by {v}");
}
// The drawing's associativity is untouched by a refused DIMASO.
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(!setvar(&mut s, "DIMASO", json!(3)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1));
// The same through LISP, where nil and a NaN real arrive as values a variable can't take.
assert!(!lisp_setvar(&mut s, "REGENMODE", "nil"), "nil refused");
assert!(!lisp_setvar(&mut s, "DIMASO", "3"), "DIMASO 3 refused");
assert!(!lisp_setvar(&mut s, "DIMASO", "\"two\""), "DIMASO text refused");
for (name, v) in [("DIMASO", "\"0\""), ("TEXTEVAL", "\"1\""), ("REGENMODE", "\"0\"")] {
assert!(!lisp_setvar(&mut s, name, v), "{name} text {v} refused");
}
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "-1"), "TEXTEVAL -1 refused");
// (- (exp 1000) (exp 1000)) is NaN: not a number JSON can hold, so it is refused as one.
assert!(!lisp_setvar(&mut s, "TEXTEVAL", "(- (exp 1000) (exp 1000))"), "NaN refused");
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(0));
}
#[test]
fn popups_is_read_only() {
let mut s = Session::new();
assert!(cadcraft_engine::sysvars::is_read_only("popups"));
for v in [json!(1), json!(0), json!("1")] {
let e = s.execute("setvar", &json!({ "name": "POPUPS", "value": v })).unwrap_err().to_string();
assert!(e.contains("read-only"), "{v}: {e}");
}
assert!(!lisp_setvar(&mut s, "POPUPS", "0"));
assert_eq!(getvar(&mut s, "POPUPS"), json!(1));
}
#[test]
fn regenmode_is_saved_in_the_dxf_header_and_read_back() {
let mut s = Session::new();
assert!(setvar(&mut s, "REGENMODE", json!(0)));
let text = cadcraft_io::write_dxf(s.doc().unwrap());
assert!(header_names(&text).contains(&"REGENMODE".to_string()), "$REGENMODE is in the header (has {:?})", header_names(&text));
assert_eq!(header_int(&text, "REGENMODE"), Some((70, "0".to_string())), "$REGENMODE is group 70, 0");
// A reopened drawing has the value it was saved with, and saves it back.
let mut back = Session::new();
back.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "regenmode.dxf", None);
assert_eq!(getvar(&mut back, "REGENMODE"), json!(0));
let again = cadcraft_io::write_dxf(back.doc().unwrap());
assert_eq!(header_int(&again, "REGENMODE"), Some((70, "0".to_string())));
}
#[test]
fn texteval_dimaso_and_popups_are_not_saved() {
let mut s = Session::new();
assert!(setvar(&mut s, "TEXTEVAL", json!(1)));
let text = cadcraft_io::write_dxf(s.doc().unwrap());
let names = header_names(&text);
for name in ["TEXTEVAL", "DIMASO", "POPUPS"] {
assert!(!names.contains(&name.to_string()), "{name} is not a header variable (has {names:?})");
}
// TEXTEVAL is the session's: a drawing opened in this session does not bring its own value.
s.open_drawing(cadcraft_io::read_dxf(text.as_bytes()).unwrap(), "no_legacy_vars.dxf", None);
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "opening a drawing leaves the session's value");
}
#[test]
fn dimaso_remembers_the_mode_of_each_open_drawing() {
// The mode DIMASO turns off is the drawing's, not the session's: two open drawings switched
// between each put back the DIMASSOC mode they had.
let mut s = Session::new();
let first = s.active;
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
let second = s.new_drawing(true);
assert_eq!(second, first + 1);
assert!(setvar(&mut s, "DIMASSOC", json!(2)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
s.execute("document.switch", &json!({ "index": first })).unwrap();
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the first drawing restores its own mode");
s.execute("document.switch", &json!({ "index": second })).unwrap();
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(2), "the second drawing restores its own mode");
}
#[test]
fn the_dollar_forms_are_the_same_variables() {
// The DXF header writes these names with a `$` ($DIMASO, $TEXTEVAL, $REGENMODE, $POPUPS), so
// the command line takes them that way too, in any case and with spaces around them.
let mut s = Session::new();
for name in ["DIMASO", "TEXTEVAL", "REGENMODE", "POPUPS"] {
let plain = getvar(&mut s, name);
let dollar = format!("${name}");
assert_eq!(getvar(&mut s, &dollar), plain, "{dollar} reads like {name}");
let typed = format!(" ${} ", name.to_ascii_lowercase());
assert_eq!(getvar(&mut s, &typed), plain, "{typed:?} reads like {name}");
assert_eq!(cadcraft_engine::sysvars::is_read_only(&dollar), cadcraft_engine::sysvars::is_read_only(name), "{dollar} read-only as {name}");
}
// DIMASO through its DXF name still turns DIMASSOC off and puts its mode back.
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "$DIMASO", json!(0)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "$DIMASO 0 turns associativity off");
assert!(setvar(&mut s, " $dimaso ", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "$DIMASO 1 puts the mode back");
// TEXTEVAL: set under one name, read under the other.
assert!(setvar(&mut s, "$TEXTEVAL", json!(1)));
assert_eq!(getvar(&mut s, "TEXTEVAL"), json!(1), "$TEXTEVAL set TEXTEVAL");
assert!(setvar(&mut s, "TEXTEVAL", json!(0)));
assert_eq!(getvar(&mut s, "$TEXTEVAL"), json!(0));
// REGENMODE takes only the values its plain name takes, and stores the ones it takes.
assert!(!setvar(&mut s, "$REGENMODE", json!(2)), "$REGENMODE 2 is out of range");
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $REGENMODE changed nothing");
assert!(!setvar(&mut s, "$REGENMODE", json!(-1)), "$REGENMODE -1 is out of range");
assert!(setvar(&mut s, "$REGENMODE", json!(0)));
assert_eq!(getvar(&mut s, "$REGENMODE"), json!(0));
assert_eq!(getvar(&mut s, "REGENMODE"), json!(0));
assert_eq!(s.doc().unwrap().header.i64("REGENMODE", 1), 0, "$REGENMODE stored the drawing's value");
// POPUPS is read-only under its DXF name too.
for v in [json!(0), json!("1")] {
let e = s.execute("setvar", &json!({ "name": "$POPUPS", "value": v })).unwrap_err().to_string();
assert!(e.contains("read-only"), "$POPUPS {v}: {e}");
}
assert!(!lisp_setvar(&mut s, "$POPUPS", "0"));
assert_eq!(getvar(&mut s, "$POPUPS"), json!(1));
}
#[test]
fn other_dollar_names_keep_their_own_handling() {
// Only those four take a `$`: LISP's angle variables convert radians for the plain name, and
// `$OSMODE` stays a name of its own rather than becoming the session's OSMODE.
let mut s = Session::new();
assert!(eval(&mut s, "(setvar \"$ANGBASE\" (/ pi 2))").is_ok());
let base = eval(&mut s, "(getvar \"$ANGBASE\")").unwrap().as_number().unwrap_or(f64::NAN);
assert!((base - std::f64::consts::FRAC_PI_2).abs() < 1e-9, "(getvar \"$ANGBASE\") gives pi/2, not {base}");
let osmode = eval(&mut s, "(setvar \"$OSMODE\" 9)").unwrap();
assert_eq!(to_text(&osmode, true), "9", "(setvar \"$OSMODE\" 9) returns 9");
assert_eq!(getvar(&mut s, "OSMODE"), json!(4133), "$OSMODE is not the session's OSMODE");
assert_eq!(getvar(&mut s, "$OSMODE"), json!(9), "$OSMODE still reads back what it was set to");
}
#[test]
fn undo_puts_back_the_mode_dimaso_remembers() {
// The mode DIMASO remembers goes back with DIMASSOC when the changes are undone.
let mut s = Session::new();
for (name, v) in [("DIMASSOC", 1), ("DIMASO", 0), ("DIMASSOC", 2), ("DIMASO", 0)] {
assert!(setvar(&mut s, name, json!(v)), "{name} {v}");
}
s.cmdline("u").unwrap();
s.cmdline("u").unwrap();
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(0), "back to after the first DIMASO 0");
assert!(setvar(&mut s, "DIMASO", json!(1)));
assert_eq!(getvar(&mut s, "DIMASSOC"), json!(1), "the mode remembered then, not the later 2");
}
#[test]
fn repeated_dollars_are_the_same_variables() {
let mut s = Session::new();
assert!(!lisp_setvar(&mut s, "$$REGENMODE", "2"), "out of range under any number of $");
assert_eq!(getvar(&mut s, "REGENMODE"), json!(1), "a refused $$REGENMODE changed nothing");
assert!(!setvar(&mut s, "$$$POPUPS", json!(0)), "read-only under any number of $");
assert!(cadcraft_engine::sysvars::is_read_only("$$POPUPS"));
}
#[test]
fn dimaso_on_while_already_on_leaves_the_drawing_unmodified() {
let mut s = Session::new();
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "a fresh drawing");
assert!(setvar(&mut s, "DIMASO", json!(1)), "already on");
assert_eq!(getvar(&mut s, "DBMOD"), json!(0), "nothing changed, so not modified");
}
#[test]
fn the_remembered_mode_is_not_a_variable_and_is_not_reported_lost() {
let mut s = Session::new();
assert!(setvar(&mut s, "DIMASSOC", json!(1)));
assert!(setvar(&mut s, "DIMASO", json!(0)));
for name in ["CADCRAFT_DIMASO_MODE", "$CADCRAFT_DIMASO_MODE", "cadcraft_dimaso_mode"] {
assert!(s.execute("getvar", &json!({ "name": name })).is_err(), "{name} is not a variable");
assert!(!setvar(&mut s, name, json!(2)), "{name} cannot be set");
}
assert!(eval(&mut s, "(getvar \"CADCRAFT_DIMASO_MODE\")").map_or(true, |v| to_text(&v, false) == "nil"));
// Saved and read back, the drawing has lost nothing a save keeps.
let before = s.doc().unwrap().clone();
let after = cadcraft_io::read_dxf(cadcraft_io::write_dxf(&before).as_bytes()).unwrap();
let cmp = cadcraft_io::roundtrip::compare(&before, &after, &cadcraft_io::roundtrip::Options::default());
assert!(!cmp.differences.iter().any(|d| d.place.contains("DIMASO")), "{:?}", cmp.differences.iter().map(|d| &d.place).collect::<Vec<_>>());
}
+3
View File
@@ -1,10 +1,12 @@
#[path = "../support/temp_dir.rs"]
mod temp_dir;
mod acadver;
mod angle_prompts;
mod angle_settings;
mod annotate_options;
mod annotative;
mod annotative_positions;
mod arc_ctrl_direction;
mod array_commands;
mod array_counts;
@@ -104,6 +106,7 @@ mod layout_prompts;
mod leader_command;
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod leader_text_scale;
mod legacy_sysvars;
mod lisp_answer_by_frames;
mod lisp_corpus;
mod lisp_findfile;
+3 -1
View File
@@ -11,7 +11,9 @@ use cadcraft_engine::doc::{Block, Circle, Drawing, Entity, EntityKind, Handle, I
use cadcraft_engine::{Input, Session};
use serde_json::{Value, json};
fn hooks() {
/// The real file formats, for every test in this binary that opens or saves files (the hooks are
/// process-wide and the first ones set stay).
pub(crate) fn hooks() {
set_io(IoHooks {
read: |b, name| cadcraft_io::read(b, name).map_err(|e| e.to_string()),
write: |d, name| cadcraft_io::write(d, name).map_err(|e| e.to_string()),
+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;
}
});
}
+53 -1
View File
@@ -16,7 +16,9 @@ use std::borrow::Cow;
use std::collections::{BTreeMap, HashMap, HashSet};
use std::sync::Arc;
use cadcraft_doc::foreign::{Foreign, ForeignExtra, ForeignKey, ForeignObject, class_group, class_index, class_number, proxy_has_string_stream};
use cadcraft_doc::foreign::{
Foreign, ForeignExtra, ForeignKey, ForeignObject, VertexId, class_group, class_index, class_number, proxy_has_string_stream,
};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle, RawTag, Unknown};
use craft_dxf::{SectionRef, Tag, Version};
@@ -83,6 +85,8 @@ fn leader_acad_rest(chunk: &[Tag]) -> Vec<Tag> {
/// Most objects kept from one file.
const MAX_OBJECTS: usize = 1_000_000;
/// Most vertices of one polyline whose identifiers are kept.
const MAX_VERTEX_IDS: usize = 1_000_000;
/// Most xdata groups kept per record (AutoCAD allows 16 KB of xdata per object).
const MAX_XDATA_GROUPS: usize = cadcraft_doc::MAX_XDATA_GROUPS;
/// Longest ownership chain followed.
@@ -345,9 +349,57 @@ fn extra(kind: &str, tags: &[Tag], entity: bool, unknown: bool, kept: &HashSet<S
}
x.props = props.iter().filter(|t| matches!(t.code, 347 | 284)).map(raw).collect();
}
if entity && !unknown && kind == "LWPOLYLINE" {
x.vertex_ids = vertex_ids(tags);
}
x
}
/// A LWPOLYLINE record's vertices with their identifiers (group 91 after a vertex's point): one
/// per vertex, identifier 0 for a vertex without one; empty when no vertex has one
/// ([`ForeignExtra::vertex_ids`]). The points are as the reader gives them: mirrored in x when
/// the normal points down. Groups inside an application's `102 {` … `102 }` are not the
/// polyline's.
fn vertex_ids(tags: &[Tag]) -> Vec<VertexId> {
let mut in_app = false;
let own_tags: Vec<&Tag> = tags
.iter()
.take_while(|t| t.code < 1000)
.filter(|t| {
if t.code == 102 {
in_app = t.str().trim_start().starts_with('{');
return false;
}
!in_app
})
.collect();
let own = || own_tags.iter().copied();
let down = own().any(|t| t.code == 230 && t.f64() < 0.0);
if !own().any(|t| t.code == 91 && t.i64() != 0) {
return Vec::new();
}
let mut ids: Vec<VertexId> = Vec::new();
for t in own() {
match t.code {
// A polyline past the cap keeps none: identifiers for some of its vertices would be wrong.
10 if ids.len() >= MAX_VERTEX_IDS => return Vec::new(),
10 => ids.push(VertexId { id: 0, x: if down { -t.f64() } else { t.f64() }, y: 0.0 }),
20 => {
if let Some(last) = ids.last_mut() {
last.y = t.f64();
}
}
91 => {
if let Some(last) = ids.last_mut() {
last.id = i32::try_from(t.i64()).unwrap_or(0);
}
}
_ => {}
}
}
ids
}
/// Every entity of the drawing (model space, layouts, blocks).
fn all_entities(d: &Drawing) -> impl Iterator<Item = &Entity> {
std::iter::once(&d.model)
+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))
+9 -1
View File
@@ -169,7 +169,11 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
w.f(38, elevation);
}
thickness(w, e);
for v in &p.vertices {
// The vertex identifiers the file gave the polyline (DXF 2010 and later), while its
// vertices are where they were read: geometric constraints name its segments by them.
let kept = d.foreign.entities.get(&e.handle).map(|x| x.vertex_ids.as_slice()).filter(|_| cx.target >= Version::R2010);
let ids = kept.and_then(|kept| cadcraft_doc::foreign::vertex_ids_for(kept, p.vertices.iter().map(|v| (v.p.x, v.p.y))));
for (i, v) in p.vertices.iter().enumerate() {
w.p2(10, v.p);
if v.start_width != 0.0 || v.end_width != 0.0 {
w.f(40, v.start_width);
@@ -178,6 +182,9 @@ fn write_basic_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, paper: bo
if v.bulge != 0.0 {
w.f(42, v.bulge);
}
if let Some(id) = ids.as_ref().and_then(|ids| ids.get(i)).filter(|id| **id != 0) {
w.i(91, i64::from(*id));
}
}
}
EntityKind::MLine(m) => {
@@ -671,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);
+1
View File
@@ -51,6 +51,7 @@ const HEADER_VARS: &[(&str, i32)] = &[
("PSTYLEMODE", 290),
("INSUNITS", 70),
("MEASUREMENT", 70),
("REGENMODE", 70),
("PSLTSCALE", 70),
// The model view the drawing is saved at, as DXF keeps it in HEADER (the `*ACTIVE` VPORT
// record below repeats it). Written so a drawing opened on its saved view saves it back.
+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,
+13 -2
View File
@@ -287,8 +287,19 @@ impl<'o> Out<'o> {
/// Header variables that change on every save (time stamps, the handle seed, GUIDs): not
/// compared.
pub const VOLATILE_HEADER: &[&str] =
&["HANDSEED", "TDCREATE", "TDUCREATE", "TDUPDATE", "TDUUPDATE", "TDINDWG", "TDUSRTIMER", "VERSIONGUID", "FINGERPRINTGUID"];
/// `CADCRAFT_DIMASO_MODE` is the engine's memory of the mode DIMASO turned off; no file keeps it.
pub const VOLATILE_HEADER: &[&str] = &[
"HANDSEED",
"TDCREATE",
"TDUCREATE",
"TDUPDATE",
"TDUUPDATE",
"TDINDWG",
"TDUSRTIMER",
"VERSIONGUID",
"FINGERPRINTGUID",
"CADCRAFT_DIMASO_MODE",
];
/// Compare `before` (the drawing as first opened) with `after` (the same drawing saved and
/// reopened). Differences are reported as what `after` lost, gained or changed.
@@ -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);
}
}
+130
View File
@@ -0,0 +1,130 @@
//! A lightweight polyline keeps its vertex identifiers (LWPOLYLINE group 91 after a vertex, DXF
//! 2010 and later) through a save while its vertices are where they were read.
//! Geometric constraints name a polyline's segments by these identifiers. CADCraft's polyline has
//! none, so every save wrote the polyline without them, and what the constraints name was gone.
//!
//! The DWG is written here with acadrust, the identifiers out of order and the first vertex not
//! the smallest, as on a polyline that was edited in another program. The harness builds this
//! module only where acadrust builds (see `main.rs`).
use std::io::Cursor;
use acadrust::entities::{EntityType, LwPolyline, LwVertex};
use acadrust::{CadDocument, DxfVersion, Vector2};
use cadcraft_io::{SaveOptions, Version, read, write_with};
const VERTEX_IDS: [i32; 4] = [2, 5, 7, 1];
fn polyline_dwg() -> Vec<u8> {
polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], 1.0)
}
/// A DWG with one closed polyline at `points`, its normal along `normal_z` Z.
fn polyline_dwg_with(points: [(f64, f64); 4], normal_z: f64) -> Vec<u8> {
let mut doc = CadDocument::with_version(DxfVersion::AC1032);
let mut polyline = LwPolyline::new();
polyline.is_closed = true;
polyline.normal = acadrust::Vector3::new(0.0, 0.0, normal_z);
for (id, (x, y)) in VERTEX_IDS.iter().zip(points) {
polyline.vertices.push(LwVertex { vertex_id: *id, ..LwVertex::new(Vector2::new(x, y)) });
}
doc.add_entity(EntityType::LwPolyline(polyline)).expect("add the polyline");
acadrust::DwgWriter::write_to_vec(&doc).expect("write the DWG")
}
/// The vertex identifiers of the one lightweight polyline in DWG bytes.
fn vertex_ids_of(dwg: &[u8]) -> Vec<i32> {
let doc = acadrust::DwgReader::from_stream(Cursor::new(dwg.to_vec())).read().unwrap();
doc.entities()
.find_map(|e| match e {
EntityType::LwPolyline(p) => Some(p.vertices.iter().map(|v| v.vertex_id).collect()),
_ => None,
})
.expect("the polyline is in the DWG")
}
/// The vertex identifiers (groups 91) of the one LWPOLYLINE record in a DXF text.
fn dxf_vertex_ids(dxf: &[u8]) -> Vec<String> {
let text = String::from_utf8_lossy(dxf);
let lines: Vec<&str> = text.lines().map(str::trim).collect();
let mut pairs = lines.chunks(2).filter_map(|pair| Some((*pair.first()?, *pair.get(1)?)));
let record = pairs.by_ref().skip_while(|pair| *pair != ("0", "LWPOLYLINE")).skip(1);
record.take_while(|(code, _)| *code != "0").filter(|(code, _)| *code == "91").map(|(_, value)| value.to_string()).collect()
}
fn save(d: &cadcraft_doc::Drawing, name: &str, version: Version) -> Vec<u8> {
write_with(d, name, &SaveOptions { version: Some(version), binary: false }).unwrap()
}
#[test]
fn a_polyline_keeps_its_vertex_identifiers_through_a_save() {
cadcraft_io::dwg_worker::allow_in_process();
let dwg = polyline_dwg();
assert_eq!(vertex_ids_of(&dwg), VERTEX_IDS, "the fixture as acadrust reads it");
let d = read(&dwg, "polyline.dwg").unwrap();
for version in [Version::R2010, Version::R2018] {
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", version)), VERTEX_IDS, "DWG {version:?}");
}
assert_eq!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2018)), ["2", "5", "7", "1"]);
// A DXF before 2010 has no such group.
assert!(dxf_vertex_ids(&save(&d, "saved.dxf", Version::R2000)).is_empty());
let back = read(&save(&d, "saved.dxf", Version::R2018), "saved.dxf").unwrap();
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"], "read back from a DXF");
}
/// Once a vertex is elsewhere, the order is another or a vertex is gone, the identifiers no longer
/// say which vertex is which: none are written.
#[test]
fn an_edited_polyline_drops_its_vertex_identifiers() {
cadcraft_io::dwg_worker::allow_in_process();
let mut d = read(&polyline_dwg(), "polyline.dwg").unwrap();
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
let mut after = |edit: fn(&mut cadcraft_doc::LwPolyline)| {
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
edit(p);
}
}));
vertex_ids_of(&save(&d, "edited.dwg", Version::R2018))
};
assert_eq!(after(|p| p.vertices.reverse()), [0; 4], "reversed");
assert_eq!(after(|p| p.vertices.reverse()), VERTEX_IDS, "reversed back: every vertex is where it was read");
assert_eq!(after(|p| p.vertices[1].p.x += 1.0), [0; 4], "a vertex moved");
}
/// A polyline whose normal points down is read mirrored in x; untouched, it keeps its identifiers.
#[test]
fn a_polyline_facing_down_keeps_its_vertex_identifiers() {
cadcraft_io::dwg_worker::allow_in_process();
let d = read(&polyline_dwg_with([(0.0, 0.0), (40.0, 0.0), (40.0, 25.0), (0.0, 25.0)], -1.0), "down.dwg").unwrap();
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), VERTEX_IDS);
}
/// Reversed, a polyline symmetric about x = 0 has its mirror image's points: the identifiers still
/// no longer say which vertex is which.
#[test]
fn a_reversed_symmetric_polyline_drops_its_vertex_identifiers() {
cadcraft_io::dwg_worker::allow_in_process();
let mut d = read(&polyline_dwg_with([(-20.0, 0.0), (-20.0, 25.0), (20.0, 25.0), (20.0, 0.0)], 1.0), "sym.dwg").unwrap();
let handle = d.model.iter().find(|e| matches!(e.kind, cadcraft_doc::EntityKind::LwPolyline(_))).map(|e| e.handle).unwrap();
assert!(d.model.modify(handle, |e: &mut cadcraft_doc::Entity| {
if let cadcraft_doc::EntityKind::LwPolyline(p) = &mut e.kind {
p.vertices.reverse();
}
}));
assert_eq!(vertex_ids_of(&save(&d, "saved.dwg", Version::R2018)), [0; 4]);
}
/// A group 91 inside an application's `102 {` group of the record is not a vertex identifier.
#[test]
fn a_91_inside_an_application_group_is_not_an_identifier() {
cadcraft_io::dwg_worker::allow_in_process();
let d = read(&polyline_dwg(), "polyline.dwg").unwrap();
let dxf = String::from_utf8(save(&d, "saved.dxf", Version::R2018)).unwrap();
let mut lines: Vec<&str> = dxf.lines().collect();
let start = lines.windows(2).position(|pair| pair[0].trim() == "0" && pair[1].trim() == "LWPOLYLINE").unwrap();
// After the first vertex's identifier.
let at = (start..lines.len()).step_by(2).find(|i| lines[*i].trim() == "91").unwrap() + 2;
lines.splice(at..at, ["102", "{SOMEAPP", " 91", "9", "102", "}"]);
let back = read(lines.join("\n").as_bytes(), "app.dxf").unwrap();
assert_eq!(dxf_vertex_ids(&save(&back, "again.dxf", Version::R2018)), ["2", "5", "7", "1"]);
}
+2
View File
@@ -62,6 +62,8 @@ mod low_handseed;
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod ltype_dwg_dash_count;
mod ltype_element_cap;
#[cfg(not(any(target_arch = "wasm32", all(target_os = "freebsd", target_arch = "aarch64"))))]
mod lwpolyline_vertex_ids;
mod minsert_marker;
mod mleader_content;
mod mleader_roundtrip;
+16 -2
View File
@@ -204,8 +204,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 +230,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");
}
+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};
+3
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`.
+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);
}
+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();
+7
View File
@@ -21,6 +21,7 @@
//! | `rightClickDefault`, `rightClickEdit` | with the time-sensitive right-click off, a right-click with no command running and nothing (`Default`) or something (`Edit`) selected: `"menu"` (the shortcut menu, default) or `"repeat"` (the last command) |
//! | `rightClickCommand` | a right-click while a command runs, with the time-sensitive right-click off: `"menu"` (default), `"enter"`, or `"menuWithOptions"` (the menu when the prompt has options, else Enter) |
//! | `systemCursor` | keep the system cursor visible over the drawing area |
//! | `systemTitleBar` | 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 with the window buttons |
//! | `historyLines` | command-line history lines, 0–12 |
//! | `modelBackground`, `paperBackground` | `"#rrggbb"`, or `null` for the default |
//! | `selectionColor` | the colour selected objects are highlighted in: `"#rrggbb"`, or `null` for the theme's |
@@ -230,6 +231,7 @@ struct UiChanges {
language: Option<crate::i18n::Preference>,
save_format: Option<crate::SaveFormat>,
system_cursor: Option<bool>,
system_title_bar: Option<bool>,
history_lines: Option<usize>,
model_background: Option<Option<Color32>>,
paper_background: Option<Option<Color32>>,
@@ -268,6 +270,7 @@ fn parse_ui(key: &str, v: &Value, c: &mut UiChanges) -> Result<bool, String> {
}
"saveFormat" => c.save_format = Some(crate::SaveFormat::parse(text()?).ok_or("saveFormat must be dxf or dwg")?),
"systemCursor" => c.system_cursor = Some(v.as_bool().ok_or("systemCursor must be true or false")?),
"systemTitleBar" => c.system_title_bar = Some(v.as_bool().ok_or("systemTitleBar must be true or false")?),
"historyLines" => {
let n = v.as_u64().filter(|n| *n <= crate::cmdline::MAX_LINES as u64).ok_or("historyLines must be a whole number from 0 to 12")?;
c.history_lines = Some(n as usize);
@@ -330,6 +333,7 @@ fn ui_json(app: &CadApp) -> Map<String, Value> {
m.insert("interfaceLanguage".into(), json!(app.ui.interface_language.code()));
m.insert("saveFormat".into(), json!(app.ui.save_format.as_str()));
m.insert("systemCursor".into(), json!(app.ui.system_cursor));
m.insert("systemTitleBar".into(), json!(app.ui.system_title_bar));
m.insert("historyLines".into(), json!(app.ui.history_lines));
m.insert("modelBackground".into(), color_json(o.model_background));
m.insert("paperBackground".into(), color_json(o.paper_background));
@@ -389,6 +393,9 @@ fn run_json(app: &mut CadApp, params: &Value) -> Result<Value, String> {
if let Some(b) = ui.system_cursor {
app.ui.system_cursor = b;
}
if let Some(b) = ui.system_title_bar {
app.ui.system_title_bar = b;
}
if let Some(n) = ui.history_lines {
app.ui.history_lines = n;
}
+66 -1
View File
@@ -12,13 +12,14 @@ use crate::animation::AnimationPref;
use crate::theme::{ThemePref, Tokens};
/// The tabs: (id in the dialog name, label).
pub(super) const TABS: [(&str, &str); 6] = [
pub(super) const TABS: [(&str, &str); 7] = [
("display", "Display"),
("files", "Open and Save"),
("drafting", "Drafting"),
("selection", "Selection"),
("preferences", "User Preferences"),
("profiles", "Profiles"),
("agents", "AI Agents"),
];
const WIDTH: f32 = 580.0;
@@ -57,6 +58,7 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool
"selection" => selection(app, ui, &mut changes),
"preferences" => preferences(app, ui, &mut changes),
"profiles" => profiles(app, ui, &mut changes),
"agents" => agents(app, ui),
_ => display(app, ui, &mut changes),
}
// The same height on every tab, so switching tabs doesn't move the buttons.
@@ -85,6 +87,54 @@ pub fn dialog(app: &mut CadApp, ctx: &egui::Context, name: &str, open: &mut bool
}
}
/// AI Agents tab: the shared Agents page (`craft_automation::ui::agents`) over the agent settings.
/// Unlike the other tabs it doesn't go through OPTIONS: no command may change these settings, or an
/// agent in the window could widen its own folders. They are saved at once for `cadcraft-cli mcp`
/// too ([`crate::agents::Agents::set_settings`]).
#[cfg(not(target_arch = "wasm32"))]
fn agents(app: &mut CadApp, ui: &mut egui::Ui) {
use craft_ui::patterns::preferences::SettingsDraft;
if !app.agents.mcp_flag() {
// CADCraft had no agent consent of its own before the launcher's switch, so without the
// flag there is nothing to set here.
hint(
ui,
crate::tl!(
"AI apps reach the open CADCraft window once ArtCraft Launcher › Settings › AI agents is available on this computer. Until then they work with CADCraft without a window."
),
);
return;
}
app.agents.page_shown(ui.ctx().cumulative_frame_nr());
let mut draft = SettingsDraft::default();
if let Err(e) = draft.replace(&json!({ AGENTS_PAGE: app.agents.settings() })) {
hint(ui, &e.to_string());
return;
}
let status = app.agents.status();
let out = craft_automation::ui::agents::AgentsPage::new(AGENTS_PAGE, &mut draft, &status).mcp_flag(true).show(ui);
if !out.changed {
return;
}
let settings = draft.to::<Value>().and_then(|v| serde_json::from_value(v[AGENTS_PAGE].clone()).ok());
if let Some(settings) = settings
&& let Err(e) = app.agents.set_settings(settings)
{
log::warn!("{e}");
app.session.echo(e);
}
}
/// The browser build has no connection for agents.
#[cfg(target_arch = "wasm32")]
fn agents(_: &mut CadApp, ui: &mut egui::Ui) {
hint(ui, crate::tl!("AI apps work with the desktop app; the web version has no connection for them."));
}
/// The section of the Agents page's draft that holds the agent settings.
#[cfg(not(target_arch = "wasm32"))]
const AGENTS_PAGE: &str = "agents";
fn grid(ui: &mut egui::Ui, id: &str, add: impl FnOnce(&mut egui::Ui)) {
egui::Grid::new(id).num_columns(2).spacing(vec2(14.0, 8.0)).show(ui, add);
}
@@ -212,6 +262,21 @@ fn display(app: &CadApp, ui: &mut egui::Ui, changes: &mut Map<String, Value>) {
changes.insert("systemCursor".into(), json!(system_cursor));
}
hint(ui, crate::tl!("Screen magnifiers, screen readers and recorders follow the system cursor."));
// Only where the framework's title bar carries the window buttons (GNOME on Wayland); elsewhere
// the desktop draws the frame. `CADCRAFT_TITLEBAR` overrides the setting, so it isn't offered then.
if app.system_title_bar_applies() {
ui.add_space(6.0);
let mut system = app.ui.system_title_bar;
if ui.checkbox(&mut system, crate::tl!("Use system title bar")).changed() {
changes.insert("systemTitleBar".into(), json!(system));
}
hint(
ui,
crate::tl!(
"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."
),
);
}
}
/// Files tab: save format and default version, new-drawing units, autosave interval and autosave file location; edits accumulate in `changes`.
+1 -1
View File
@@ -1,4 +1,4 @@
//! Boolean environment switches (`CADCRAFT_VSYNC`, `CADCRAFT_WAYLAND`, ...): one parser, so every
//! Boolean environment switches (`CADCRAFT_VSYNC`, `CADCRAFT_X11`, ...): one parser, so every
//! variable accepts the same spellings.
/// `1/on/true/yes` or `0/off/false/no`, case- and space-insensitive. Blank or unset is `Default`;
+122
View File
@@ -0,0 +1,122 @@
//! Options ▸ Display ▸ Use system title bar: where the desktop leaves the window frame to the app (GNOME on
//! Wayland), the framework's title bar carries the window buttons, in the order of GNOME's `button-layout`; the
//! setting gives the window the desktop's frame instead, at once. craft-window decides the frame
//! (`policy::decide_for`), as on macOS ([`crate::framework::frame_decision`]).
use craft_host::target::Backend;
use craft_ui::runtime::windows::WindowHost;
use craft_window::policy::{self, Decision, TitleBarPref};
use crate::CadApp;
/// The window's frame for each value of Use system title bar, both decided at start-up from the desktop as it was
/// then, so the app's buttons come back in the desktop's `button-layout` order.
#[derive(Clone, Debug, PartialEq)]
pub struct TitleBar {
/// The frame with the setting off: the app's buttons.
app: Decision,
/// The frame with the setting on: the desktop's.
system: Decision,
/// The setting the window's frame follows now.
applied: bool,
}
impl TitleBar {
/// The frames for both values of the setting, or `None` to leave the frame to the desktop, as before. Only where
/// the desktop draws no frame (a Wayland compositor without server-side decorations: GNOME) or
/// `CADCRAFT_TITLEBAR` asks: the policy would also draw the app's buttons on desktops that frame their windows
/// (Windows, KDE), which is a decision for the whole suite rather than this setting.
#[must_use]
pub fn new(app: Decision, system: Decision, system_title_bar: bool) -> Option<Self> {
let leaves_frame_to_app = app.desktop.ssd == Some(false);
(leaves_frame_to_app || app.overridden.is_some()).then_some(Self { app, system, applied: system_title_bar })
}
/// The frame the window opens with.
#[must_use]
pub fn decision(&self) -> &Decision {
if self.applied { &self.system } else { &self.app }
}
/// `Some(true)` when `CADCRAFT_TITLEBAR` forced the app's buttons, `Some(false)` the desktop's frame; the setting
/// then changes nothing.
fn forced(&self) -> Option<bool> {
self.app.overridden
}
}
/// [`TitleBar::new`] for this desktop; `forced_x11` when the app opens its window through XWayland.
#[must_use]
pub fn decide(forced_x11: bool, system_title_bar: bool) -> Option<TitleBar> {
let backend = if forced_x11 { Backend::X11 } else { Backend::from_env() };
let decide = |pref| policy::decide_for(craft_window::Prefix::new("CADCRAFT"), backend, pref);
TitleBar::new(decide(TitleBarPref::Integrated), decide(TitleBarPref::System), system_title_bar)
}
impl CadApp {
/// The window opened with `title_bar`'s frame ([`decide`]): Use system title bar now changes it, and the title
/// row follows it.
pub fn set_title_bar(&mut self, title_bar: TitleBar) {
self.integrated_titlebar = crate::framework::draws_title_row(Some(title_bar.decision()));
self.title_bar = Some(title_bar);
}
/// Whether Use system title bar changes anything here: the framework decides the frame and `CADCRAFT_TITLEBAR`
/// doesn't.
pub(crate) fn system_title_bar_applies(&self) -> bool {
self.title_bar.as_ref().is_some_and(|t| t.forced().is_none())
}
/// Follow Use system title bar at once, before the title row is drawn: the window gets the setting's frame, and
/// the title row shows or goes with the window buttons.
pub(crate) fn follow_title_bar(&mut self, ctx: &egui::Context) {
let system = self.ui.system_title_bar;
let Some(t) = self.title_bar.as_mut().filter(|t| t.forced().is_none() && t.applied != system) else { return };
t.applied = system;
let decision = t.decision().clone();
self.integrated_titlebar = crate::framework::draws_title_row(Some(&decision));
WindowHost::of(ctx).set_root_frame(decision);
}
}
#[cfg(test)]
mod tests {
use super::TitleBar;
use craft_host::target::Backend;
use craft_window::policy::{self, TitleBarPref};
/// Both frames as GNOME on Wayland gives them: no server-side decorations and no override.
fn gnome() -> (policy::Decision, policy::Decision) {
let decide = |pref| {
let mut d = policy::decide_for(craft_window::Prefix::new("CADCRAFT_TEST_UNSET"), Backend::Wayland, pref);
d.desktop.ssd = Some(false);
d.overridden = None;
d
};
(decide(TitleBarPref::Integrated), decide(TitleBarPref::System))
}
#[test]
fn only_where_the_desktop_leaves_the_frame_to_the_app() {
let (app, system) = gnome();
assert!(TitleBar::new(app.clone(), system.clone(), false).is_some(), "GNOME on Wayland");
let mut framed = app.clone();
framed.desktop.ssd = Some(true);
assert!(TitleBar::new(framed.clone(), system.clone(), false).is_none(), "KDE and Sway draw their own frames");
framed.overridden = Some(true);
assert!(TitleBar::new(framed, system, false).is_some(), "CADCRAFT_TITLEBAR=app asks anyway");
}
#[test]
fn the_setting_picks_the_frame_and_the_override_beats_it() {
let (app, system) = gnome();
let t = TitleBar::new(app.clone(), system.clone(), false).unwrap();
assert_eq!(t.decision(), &app);
assert_eq!(t.forced(), None);
let t = TitleBar::new(app.clone(), system.clone(), true).unwrap();
assert_eq!(t.decision(), &system, "Use system title bar on: the desktop's frame");
let mut forced = app;
forced.overridden = Some(true);
assert_eq!(TitleBar::new(forced, system, true).unwrap().forced(), Some(true));
}
}
+116
View File
@@ -0,0 +1,116 @@
//! Resize edges for the framework's integrated frame ([`crate::title_bar`]: GNOME on Wayland, where the desktop draws
//! no frame). The framework gives the window buttons and the move band, but only a window built from its own shell
//! gets its resize grips; CADCraft hosts its own egui UI, so thin zones along the window's edges start the desktop's
//! resize here. The resize goes through the framework (`WindowAction::StartResize`), which gives the button release
//! back after the desktop's grab.
use craft_ui::runtime::windows::{ResizeEdge, WindowAction, WindowHost};
use craft_window::policy::Frame;
use egui::{Color32, CursorIcon, Pos2, Rect, Sense, Stroke, Vec2, ViewportId};
/// How far into the window an edge resizes it.
const EDGE: f32 = 5.0;
/// How far along an edge a corner reaches, so corners are easy to hit.
const CORNER: f32 = 16.0;
/// The resize zones of a window filling `rect`: edges `edge` deep, and each corner an L of two strips reaching
/// `corner` along both edges (a square would reach into the content).
fn zones(rect: Rect, edge: f32, corner: f32) -> Vec<(ResizeEdge, Rect)> {
let (l, r, t, b) = (rect.left(), rect.right(), rect.top(), rect.bottom());
// Never inverted, however small the window.
let zone = |x0: f32, x1: f32, y0: f32, y1: f32| Rect::from_min_max(Pos2::new(x0, y0), Pos2::new(x1.max(x0), y1.max(y0)));
vec![
(ResizeEdge::TopLeft, zone(l, l + corner, t, t + edge)),
(ResizeEdge::TopLeft, zone(l, l + edge, t + edge, t + corner)),
(ResizeEdge::TopRight, zone(r - corner, r, t, t + edge)),
(ResizeEdge::TopRight, zone(r - edge, r, t + edge, t + corner)),
(ResizeEdge::BottomLeft, zone(l, l + corner, b - edge, b)),
(ResizeEdge::BottomLeft, zone(l, l + edge, b - corner, b - edge)),
(ResizeEdge::BottomRight, zone(r - corner, r, b - edge, b)),
(ResizeEdge::BottomRight, zone(r - edge, r, b - corner, b - edge)),
(ResizeEdge::Top, zone(l + corner, r - corner, t, t + edge)),
(ResizeEdge::Bottom, zone(l + corner, r - corner, b - edge, b)),
(ResizeEdge::Left, zone(l, l + edge, t + corner, b - corner)),
(ResizeEdge::Right, zone(r - edge, r, t + corner, b - corner)),
]
}
fn cursor(edge: ResizeEdge) -> CursorIcon {
match edge {
ResizeEdge::Top => CursorIcon::ResizeNorth,
ResizeEdge::Bottom => CursorIcon::ResizeSouth,
ResizeEdge::Right => CursorIcon::ResizeEast,
ResizeEdge::Left => CursorIcon::ResizeWest,
ResizeEdge::TopRight => CursorIcon::ResizeNorthEast,
ResizeEdge::BottomRight => CursorIcon::ResizeSouthEast,
ResizeEdge::TopLeft => CursorIcon::ResizeNorthWest,
ResizeEdge::BottomLeft => CursorIcon::ResizeSouthWest,
_ => CursorIcon::Default,
}
}
/// Resize zones along the root window's edges and a hairline border, while the framework's integrated frame is the
/// window's and the window is neither maximized nor full screen. The zones sit above everything else (in the
/// foreground order), so a press there resizes instead of reaching the panel or canvas under it.
pub(crate) fn show(ctx: &egui::Context) {
let host = WindowHost::of(ctx);
if !matches!(host.frame(), Frame::Integrated(_)) {
return;
}
let (maximized, fullscreen) = ctx.input(|i| (i.viewport().maximized.unwrap_or(false), i.viewport().fullscreen.unwrap_or(false)));
if maximized || fullscreen {
return;
}
let screen = ctx.content_rect();
let dark = crate::theme::active() == egui::Theme::Dark;
egui::Area::new(egui::Id::unique("cadcraft_window_edges")).order(egui::Order::Foreground).fixed_pos(screen.min).interactable(true).show(
ctx,
|ui| {
ui.set_min_size(Vec2::ZERO);
for (n, (edge, rect)) in zones(screen, EDGE, CORNER).into_iter().enumerate() {
if rect.width() <= 0.0 || rect.height() <= 0.0 {
continue;
}
let response = ui.interact(rect, ui.scope_id().with(("edge", n)), Sense::drag()).on_hover_cursor(cursor(edge));
// Sensing only drags, a drag starts on the press itself.
if response.drag_started() {
host.act(ViewportId::ROOT, WindowAction::StartResize(edge));
}
}
// Without the desktop's frame or shadow, a hairline keeps the window apart from what's behind it.
ui.painter().rect_stroke(screen, 0.0, Stroke::new(1.0, Color32::from_black_alpha(if dark { 160 } else { 60 })), egui::StrokeKind::Inside);
},
);
}
#[cfg(test)]
mod tests {
use super::{ResizeEdge, zones};
use egui::{Pos2, Rect};
#[test]
fn resize_zones_line_the_edges_without_overlapping() {
let window = Rect::from_min_size(Pos2::ZERO, egui::vec2(800.0, 600.0));
let zones = zones(window, 5.0, 16.0);
let at = |x: f32, y: f32| zones.iter().filter(|(_, r)| r.contains(Pos2::new(x, y))).map(|(e, _)| *e).collect::<Vec<_>>();
assert_eq!(at(1.0, 1.0), [ResizeEdge::TopLeft]);
assert_eq!(at(2.0, 12.0), [ResizeEdge::TopLeft]);
assert_eq!(at(400.0, 2.0), [ResizeEdge::Top]);
assert_eq!(at(799.0, 300.0), [ResizeEdge::Right]);
assert_eq!(at(400.0, 599.0), [ResizeEdge::Bottom]);
assert_eq!(at(1.0, 300.0), [ResizeEdge::Left]);
assert_eq!(at(799.0, 599.0), [ResizeEdge::BottomRight]);
assert!(at(400.0, 300.0).is_empty(), "the middle of the window is left alone");
assert!(at(12.0, 12.0).is_empty(), "corners stay along the edges");
// Strips meet without overlapping.
for y in [0.5, 4.5, 5.5, 15.5, 16.5, 595.5] {
for x in [0.5, 4.5, 5.5, 15.5, 16.5, 795.5, 799.5] {
assert!(at(x, y).len() <= 1, "({x}, {y}): {:?}", at(x, y));
}
}
// A window smaller than its corners gets empty (not inverted) edge zones.
for (_, r) in super::zones(Rect::from_min_size(Pos2::ZERO, egui::vec2(20.0, 20.0)), 5.0, 16.0) {
assert!(r.width() >= 0.0 && r.height() >= 0.0);
}
}
}
+50
View File
@@ -0,0 +1,50 @@
//! Agents in the open window: a request through the agent link runs in the app, held to the agent
//! folders of Options › AI Agents.
use std::path::PathBuf;
use std::time::{Duration, Instant};
use cadcraft_engine::Session;
use cadcraft_ui_egui::agents::Agents;
use cadcraft_ui_egui::{CadApp, Services};
use craft_automation::agents::{AgentLink, AgentSwitch, TOKEN_FILE};
use craft_automation::client::ControlClient;
use serde_json::json;
/// A file an agent asks the window to write outside its folders is refused, one inside them is
/// written: the agent link's requests run inside the agent folders, as headless ones do.
#[test]
fn a_window_request_is_held_to_the_agent_folders() {
let dir = std::env::temp_dir().join(format!("cadcraft-agents-window-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
let mut app = CadApp::new(Session::new(), Services::default());
let link = AgentLink::new(Some(dir.clone()), "CADCraft test");
app.agents = Agents::new(link, AgentSwitch::fixed(true, true), Some(dir.clone())).with_default_folder(Some(folder.clone()));
let ctx = egui::Context::default();
app.logic(&ctx);
let port = app.agents.status().port.expect("the window takes agents while the switch allows");
let token = std::fs::read_to_string(dir.join(TOKEN_FILE)).unwrap().trim().to_string();
let (outside, inside): (PathBuf, PathBuf) = (dir.join("outside.png"), folder.join("inside.png"));
let paths = (outside.to_string_lossy().into_owned(), inside.to_string_lossy().into_owned());
let agent = std::thread::spawn(move || {
let mut client = ControlClient::connect(([127, 0, 0, 1], port).into(), &token).map_err(|e| format!("{e:?}"))?;
Ok::<_, String>((client.call("ui.render", json!({"path": paths.0})), client.call("ui.render", json!({"path": paths.1}))))
});
let deadline = Instant::now() + Duration::from_secs(30);
while !agent.is_finished() {
assert!(Instant::now() < deadline, "the window never answered");
app.logic(&ctx);
std::thread::sleep(Duration::from_millis(5));
}
let (refused, written) = agent.join().unwrap().unwrap();
let refused = refused.unwrap_err();
assert!(refused.contains("outside the write root"), "{refused}");
assert!(!outside.exists());
written.unwrap();
assert!(inside.is_file());
drop(app);
let _ = std::fs::remove_dir_all(dir);
}
@@ -71,3 +71,29 @@ fn unknown_method_points_to_control_methods() {
let e = r["error"].as_str().unwrap_or_default();
assert!(e.starts_with("unknown method `help`") && e.contains("control.methods"), "{e}");
}
/// An agent in the window (its requests run inside the agent folders) can't have `ui.render` or
/// `ui.screenshot` write a file outside them; inside them `ui.render` writes, and without roots
/// (`--control`) nothing is checked.
#[test]
fn files_written_for_agents_stay_in_their_folders() {
use cadcraft_engine::file_access::{AutomationRoots, confine};
let dir = std::env::temp_dir().join(format!("cadcraft-control-roots-{}", std::process::id()));
let folder = dir.join("agents");
std::fs::create_dir_all(&folder).unwrap();
let roots = AutomationRoots::new(None, Some(&folder)).unwrap();
let mut app = app();
let outside = dir.join("outside.png").to_string_lossy().into_owned();
let inside = folder.join("inside.png").to_string_lossy().into_owned();
confine(roots.as_ref(), || {
for method in ["ui.render", "ui.screenshot"] {
let v = call(&mut app, method, json!({"path": outside}));
assert_eq!(v["ok"], false, "{method}: {v}");
assert!(v["error"].as_str().unwrap_or_default().contains("outside the write root"), "{method}: {v}");
}
assert_eq!(call(&mut app, "ui.render", json!({"path": inside}))["ok"], true);
});
assert_eq!(call(&mut app, "ui.render", json!({"path": outside}))["ok"], true);
assert!(std::path::Path::new(&outside).is_file() && std::path::Path::new(&inside).is_file());
let _ = std::fs::remove_dir_all(dir);
}
+1
View File
@@ -1,3 +1,4 @@
mod agents_window;
mod animation_effects;
mod attedit_dialog;
mod block_description_palette;
+21
View File
@@ -313,3 +313,24 @@ fn reset_brings_back_hidden_menu_bar_toolbar_and_status_bar() {
assert_eq!(a.ui.show_command_line, d.show_command_line);
assert_eq!(a.ui.show_palettes, d.show_palettes);
}
/// With the suite's `AI-MCP` flag the AI Agents tab is the shared Agents page (folders and the
/// closed-app choice, no switch of its own); without it, one line pointing to the launcher.
#[test]
fn the_ai_agents_tab_shows_the_launchers_switch() {
use cadcraft_ui_egui::agents::Agents;
use craft_automation::agents::{AgentLink, AgentSwitch};
let ctx = egui::Context::default();
cadcraft_ui_egui::framework::install_headless(&ctx);
let mut a = app();
a.ui.dialog = Some("options:agents".into());
a.agents = Agents::new(AgentLink::new(None, "CADCraft test"), AgentSwitch::fixed(false, true), None);
let text = render(&mut a, &ctx);
assert!(text.contains("ArtCraft Launcher") && !text.contains("Folder agents can save to"), "{text}");
a.agents = Agents::new(AgentLink::new(None, "CADCraft test"), AgentSwitch::fixed(true, false), None);
let text = render(&mut a, &ctx);
for shown in ["Control Port", "Folder agents can open from", "Folder agents can save to", "is closed"] {
assert!(text.contains(shown), "{shown}: {text}");
}
assert!(!text.contains("Allow Agent Control"), "the launcher's switch decides: {text}");
}
+20
View File
@@ -114,6 +114,26 @@ The existing response is unchanged: `count` is all matches, `returned` is the pa
`entities` contains handles, layers and geometry. This query does not change selection, drawing
contents or undo history. `entities` is a command, not a top-level protocol method.
## The agent server
While the ArtCraft Launcher's switch lets agents use CADCraft, the app runs a second server for them
on `127.0.0.1` (Options › AI Agents › Control Port; 0 is any free port) and publishes it in
`agent-connection.json` in the settings folder: `{"version", "pid", "port", "tokenFile", "app"}`.
The token is in `agent-control.token` beside it, kept across launches. This server is the shared one
of the Craft apps (`craft_automation::server`), so it differs from `--control`:
- A connection signs in first, within 10 s: `{"id": 0, "method": "auth.challenge", "params":
{"clientNonce": "<hex>"}}` answers with `serverNonce` and `serverProof`, the app's proof that it
holds the token; the client checks it and sends `{"id": 0, "method": "auth", "params": {"proof":
"<hex>"}}`. Requests after that carry no `token`.
- A request line is at most 1 MiB; a timeout reply says in its `error` whether the request can still
have run (`timeout: not run` is safe to send again).
- Every request runs inside the agent folders (`docs/mcp.md`): `app.open`, `app.save`, commands that
read or write files, and the `path` of `ui.render` and `ui.screenshot` are refused outside them.
The methods and replies are the same as below. `ui.inspect` reports the agent link under `agents`:
`port`, `launchFlags` (`--control` manages the connection), `error`, `mcpFlag` and `allowed`.
## Extended data (xdata)
Other applications' extended data travels with an entity (it is read from the file, kept on
+56 -20
View File
@@ -4,33 +4,67 @@ CADCraft speaks the [Model Context Protocol](https://modelcontextprotocol.io) ov
## Start it
The ArtCraft Launcher adds CADCraft to your AI apps: turn on **ArtCraft Launcher › Settings › AI
agents**. It writes the MCP client entries itself (one `ArtCraft` entry in Claude Desktop, Claude
Code, Cursor and LM Studio); CADCraft writes no client configuration of its own.
```sh
# Headless: an in-process drawing session, no window.
# What the launcher's entry runs: the open CADCraft window while the launcher lets agents use it,
# otherwise a headless drawing session.
cadcraft-cli mcp
# Bridged to the running app (watch the agent draw):
cadcraft --control 7979 &
cadcraft-cli mcp --connect 127.0.0.1:7979
# Never the window: an in-process drawing session.
cadcraft-cli mcp --headless
```
An MCP client usually starts its servers when it starts, often before the app is open. With
`--lazy` the bridge starts anyway and reaches the app at the first tool call; until the app answers,
each call fails with a message saying how to open it. `--launch` also opens CADCraft (macOS) with
that control port at a call that finds nothing, and waits for it:
### Agents in the open window
```json
{ "mcpServers": { "cadcraft": { "command": "cadcraft-cli", "args": ["mcp", "--connect", "127.0.0.1:7979", "--launch"] } } }
```
While the launcher's switch names CADCraft (the suite's `AI-MCP` flag is on), the open app serves its
control channel on `127.0.0.1` for agents and publishes where in `agent-connection.json` in its
settings folder (`CADCRAFT_CONFIG_DIR`, a portable copy's `CADCraftData`, else `%APPDATA%\CADCraft`,
`~/Library/Application Support/CADCraft` or `~/.config/cadcraft`), with its token in
`agent-control.token` beside it (owner-only). When the switch turns off the server stops and the file
goes, without a restart.
`--connect` needs the app's `HOST:PORT`. Without one (or with an unknown argument) `cadcraft-cli mcp`
exits with an error instead of falling back to a headless session, so a client meant for the app
never edits a separate drawing by mistake. If the app can't be reached, startup fails too.
Plain `cadcraft-cli mcp` reads that file before every tool call, so the MCP client's configuration
holds no port and no token, and CADCraft may open, quit or change port while the client stays
connected:
Example client configuration (Claude Code / Claude Desktop):
- **CADCraft open:** the call goes to its window. The client signs in with a challenge handshake:
CADCraft first proves it holds the token, and the token itself never crosses the wire, so a
program that took the port of a CADCraft that quit gets nothing.
- **CADCraft closed, agents allowed:** Options › AI Agents › When CADCraft is closed decides, or
`--when-closed launch|headless|error`: open CADCraft and wait for it (up to 45 s), work without a
window, or an error saying to open it. A session that went headless stays headless, so the drawing
doesn't move under the agent.
- **Agents not allowed** (switch off, or no `AI-MCP` flag): a headless session, as `mcp` always was.
```json
{ "mcpServers": { "cadcraft": { "command": "cadcraft-cli", "args": ["mcp"] } } }
```
Agent requests in the window are held to the folders of **Options › AI Agents**: files are opened
only from the read folder (or the write folder) and saved only in the write folder, with the same
checks as the headless roots below. An empty folder setting is the default agent folder,
`Documents/ArtCraft/Agents/CADCraft` (made when first used). A folder that can't be used grants no
access through it (with neither usable, every file is refused, never none); a usable write folder
still allows reads inside it. What an agent's queued input (`ui.click`, `ui.key`, `ui.text`) or a
LISP routine it started does in later frames is held to the same folders. A headless session made because CADCraft is closed uses the
same folders unless `--automation-read-root` / `--automation-write-root` name others. The
`agent_folders` tool tells the agent which folders it has (`read_folder`, `write_folder`) and whether
files outside them are refused (`confined`).
Only you change these settings, in the Options dialog: the `options` command has no such keys, and
the tab refuses changes while an agent's request or input is being handled, so an agent can't widen
its own folders. The tab also shows whether agents can connect and on which port. With several CADCraft windows on
the same settings folder, the first one takes the agents; another takes over when it closes.
`cadcraft --control PORT` keeps its own server for the whole run; the tab then says the launch
options manage the connection. A Nightly build takes no agents this way.
### `--connect` (deprecated)
`cadcraft-cli mcp --connect HOST:PORT` still bridges to an app started with `--control PORT` for
one more release, and prints a deprecation line on stderr; plain `mcp` replaces it. `--lazy` reaches
the app at the first tool call instead of at startup, and `--launch` also opens CADCraft (macOS)
with that control port at a call that finds nothing. Without an address `cadcraft-cli mcp --connect`
exits with an error instead of falling back to a headless session. The `--control` server is held
to no folders (#1585).
## Confining file access
@@ -96,8 +130,9 @@ configuration works across the suite) keep the agent to the folders you give it:
given once (`--flag <dir>` or `--flag=<dir>`).
The flags confine the headless server. `--connect` with them is an error, since the server would
otherwise talk to an app that isn't confined; the app's control channel does not take them yet
(#1585). Without `--connect` the server writes the files itself, so every check happens here.
otherwise talk to an app that isn't confined; the app's `--control` channel does not take them yet
(#1585). The open window holds agents to its own folders instead (Options › AI Agents, above).
Headless, the server writes the files itself, so every check happens here.
A path is checked, then opened: another program on the computer that swaps in a link between the two
can still win that race, and a hard link can't be told from a file. Use the operating system's
@@ -121,6 +156,7 @@ sandbox as well if other programs can change these folders.
| `render {width?, height?, fit?, window?, background?, plot_style?}` | A PNG image of the drawing, or of just the area `window` `[[x0,y0],[x1,y1]]` (one sheet or room of a large drawing; 1600 px wide with the window's shape unless sized). `background`: `"dark"` (the canvas; the default without a plot style), `"white"` (the default with one, as a plot prints on paper), `"paper"` or `"#rrggbb"`; colour 7 is drawn white on a dark background and black on a light one, as on a plot. `plot_style`: a plot style table, e.g. `monochrome.ctb` (every colour black) or `grayscale.ctb`; `"none"` (or `""`) draws every object with its own properties, also in a layout that shows its own plot styles (without `plot_style` such a layout draws with its table, as on screen). An unknown value is refused. The result is an image content block (`content[0].type` is `"image"`), not text. |
| `find_text {contains?, query?, layer?, window?, limit?, offset?}` | The readable texts — TEXT, MTEXT without formatting codes, block attributes, multileaders — with text, insertion point, height, rotation, style, layer and handle; filtered by content (`contains`, or `query` as an alias; any case), layer and a window around the insertion points. Read-only (the `texts` command). |
| `new_drawing {metric?}`, `open {path}`, `save {path?}`, `cancel` | Files and Escape. `save` to a `.svg`, `.png` or `.pdf` path exports: the drawing keeps its name and unsaved changes. |
| `agent_folders` | The folders this session may open from (`read_folder`) and save to (`write_folder`), and whether files outside them are refused (`confined`). |
| `screenshot`, `ui_inspect`, `ui_click {x, y}` | Only when connected to the app. |
Resources: `cadcraft://drawing` (inspect JSON) and `cadcraft://commands` (catalog).
+5 -1
View File
@@ -24,7 +24,8 @@ description: |-
# The binaries link only glibc and libgcc_s directly. Windowing (X11/Wayland, xkbcommon) and the
# GPU (Vulkan, EGL/GL) are loaded at runtime, so they are dependencies/recommendations here
# rather than ELF NEEDED entries.
# rather than ELF NEEDED entries. On a Wayland desktop the app runs natively and needs X11 only
# with CADCRAFT_X11=1 (see main.rs), so the X11 libraries are recommendations.
overrides:
deb:
depends:
@@ -36,6 +37,7 @@ overrides:
- libwayland-client0
- libx11-6
- libx11-xcb1
- libxkbcommon-x11-0
- libxcursor1
- libxi6
- libxrandr2
@@ -48,6 +50,8 @@ overrides:
recommends:
- libwayland-client
- libX11
- libX11-xcb
- libxkbcommon-x11
- libXcursor
- libXi
- libXrandr

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