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
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
87 changed files with 3065 additions and 234 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)
+2
View File
@@ -19,6 +19,8 @@ cadcraft-constraints = { workspace = true }
cadcraft-fonts = { workspace = true }
cadcraft-render = { workspace = true }
craft-docpath = { workspace = true }
# The agent settings (Options › AI Agents) the app and `cadcraft-cli mcp` share.
craft-control = { workspace = true }
serde = { workspace = true }
serde_json = { workspace = true }
thiserror = { workspace = true }
+104
View File
@@ -0,0 +1,104 @@
//! The agent settings of Options › AI Agents, shared by the app and `cadcraft-cli mcp`: the
//! control port agents connect on, the folders they may open from and save to, and what the CLI
//! does while CADCraft is closed. They are kept in [`FILE`] in the settings folder, beside the
//! connection file the app publishes for agents, so the CLI reads them without the app.
//!
//! Only the person changes them, in the Options dialog: the OPTIONS JSON form has no such keys,
//! so an agent can't widen its own folders through a command.
use std::io;
use std::path::Path;
use std::sync::Arc;
pub use craft_control::agents::{AgentSettings, WhenAppClosed};
use crate::file_access::AutomationRoots;
/// The settings file in the settings folder.
pub const FILE: &str = "agent-settings.json";
/// The largest settings file read; the settings are a few short fields.
const MAX_BYTES: usize = 64 * 1024;
/// The agent settings saved in the settings folder `dir`; the defaults when none are saved or the
/// file can't be read (the reason is logged), so neither the app nor the CLI fails over them.
pub fn load(dir: &Path) -> AgentSettings {
let path = dir.join(FILE);
match crate::capped_read::read_capped(&path, MAX_BYTES) {
Ok(bytes) => serde_json::from_slice(&bytes).unwrap_or_else(|e| {
log::warn!("agent settings {}: {e}; using the defaults", path.display());
AgentSettings::default()
}),
Err(e) if e.kind() == io::ErrorKind::NotFound => AgentSettings::default(),
Err(e) => {
log::warn!("agent settings {}: {e}; using the defaults", path.display());
AgentSettings::default()
}
}
}
/// Saves `settings` in the settings folder `dir` (made if missing), replacing the file whole.
pub fn save(dir: &Path, settings: &AgentSettings) -> io::Result<()> {
let json = serde_json::to_vec_pretty(settings).map_err(io::Error::other)?;
crate::atomic_write::write_atomic_making_folders(&dir.join(FILE), &json)
}
/// The roots agent requests run in, for the agent folders `read` and `write`. A folder that is
/// missing or can't be opened grants nothing in its direction, and with neither every file is
/// refused: leaving the roots out would confine nothing. The error names the folders that could
/// not be used.
pub fn roots(read: Option<&Path>, write: Option<&Path>) -> (Arc<AutomationRoots>, Option<String>) {
let mut problems = Vec::new();
let read = read.filter(|r| AutomationRoots::new(Some(r), None).map_err(|e| problems.push(e)).is_ok());
let write = write.filter(|w| AutomationRoots::new(None, Some(w)).map_err(|e| problems.push(e)).is_ok());
let roots = AutomationRoots::new(read, write).ok().flatten().unwrap_or_else(AutomationRoots::none);
(roots, (!problems.is_empty()).then(|| problems.join("; ")))
}
#[cfg(test)]
mod tests {
#![allow(clippy::unwrap_used)]
use super::*;
use crate::file_access::{check_read, check_write, confine};
fn temp(name: &str) -> std::path::PathBuf {
let dir = std::env::temp_dir().join(format!("cadcraft-agent-settings-{name}-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
std::fs::create_dir_all(&dir).unwrap();
dir
}
/// What the dialog saves is what the CLI reads; a damaged file reads as the defaults.
#[test]
fn saved_settings_read_back_and_a_damaged_file_is_the_defaults() {
let dir = temp("round-trip");
let mut settings = AgentSettings::default();
settings.read_root = "/agents/in".into();
settings.when_app_closed = WhenAppClosed::Headless;
save(&dir, &settings).unwrap();
assert_eq!(load(&dir), settings);
std::fs::write(dir.join(FILE), b"{not json").unwrap();
assert_eq!(load(&dir), AgentSettings::default());
std::fs::remove_dir_all(dir).unwrap();
}
/// Agent folders that can't be used refuse every file instead of confining nothing.
#[test]
fn folders_that_cannot_be_used_refuse_every_file() {
let dir = temp("roots");
let file = dir.join("plan.dxf");
let (roots, problem) = roots(Some(&dir.join("missing")), None);
assert!(problem.is_some());
confine(Some(&roots), || {
assert!(check_read(&file).is_err());
assert!(check_write(&file).is_err());
});
let (roots, problem) = super::roots(Some(&dir), Some(&dir.join("gone")));
assert!(problem.is_some(), "the missing write folder is named");
confine(Some(&roots), || {
assert!(check_read(&file).is_ok(), "the usable read folder still applies");
assert!(check_write(&file).is_err());
});
std::fs::remove_dir_all(dir).unwrap();
}
}
+23 -2
View File
@@ -3,6 +3,7 @@
//! objects show (ANNOALLVISIBLE) and the current annotation scale (CANNOSCALE with
//! ANNOAUTOSCALE).
use cadcraft_doc::geom::Vec2;
use cadcraft_doc::{AnnoScale, Drawing, EntityKind, Handle, MAX_SCALES, is_annotative};
use serde_json::{Value, json};
@@ -136,6 +137,7 @@ fn remove_scale(d: &mut Drawing, h: Handle, name: &str) -> Removed {
return;
}
e.common.anno_scales.retain(|s| !s.name.eq_ignore_ascii_case(name));
e.common.anno_moves.retain(|m| !m.scale.eq_ignore_ascii_case(name));
r = Removed::Yes;
});
r
@@ -216,8 +218,27 @@ fn with_handles(s: &Session, p: &Value, mut extra: Value) -> Value {
fn run_annoreset(s: &mut Session, p: &Value) -> Result<Value> {
let (hs, _) = annotative_targets(s, p, "annoreset")?;
// One position serves every scale of an object, so they are always in step.
Ok(json!({ "objects": hs.len(), "message": format!("{} annotative object(s) synchronized", hs.len()) }))
// Every scale goes where the object shows now (in the active viewport, at its scale): that
// offset becomes the shared position.
let view = s.anno_view();
let d = s.doc_mut()?;
let mut moved = 0;
for h in &hs {
let Some(e) = d.entity(*h) else { continue };
if e.common.anno_moves.is_empty() || d.layer(&e.common.layer).is_some_and(|l| l.locked) {
continue;
}
let by = match d.anno_draw_in(e, view) {
cadcraft_doc::AnnoDraw::Scaled { by, .. } => by,
_ => Vec2::ZERO,
};
d.modify_entity(*h, |e| {
cadcraft_doc::shift_position(&mut e.kind, by);
e.common.anno_moves.clear();
})?;
moved += 1;
}
Ok(json!({ "objects": hs.len(), "reset": moved, "message": format!("{} annotative object(s) synchronized", hs.len()) }))
}
fn run_annoupdate(s: &mut Session, p: &Value) -> Result<Value> {
+1
View File
@@ -86,6 +86,7 @@ pub(crate) fn paste(s: &mut Session, m: &Mat3) -> Result<Vec<Handle>> {
let old_h = e.handle;
let mut e = adopt(d, e, &renames);
e.kind.transform(m);
e.common.transform_moves(m);
d.ensure_layer(&e.common.layer);
out.push(e.handle);
copies.push((old_h, e.handle));
+43 -26
View File
@@ -1,13 +1,13 @@
//! `grip.*` commands: the undoable, scriptable form of grip editing (see `crate::grips`).
use cadcraft_doc::{Entity, EntityKind, Handle};
use cadcraft_doc::{Drawing, Entity, EntityKind, Handle};
use cadcraft_geom::{Mat3, Vec2, Vec3};
use serde_json::{Value, json};
use super::curves;
use super::{CommandSpec, bad, bool_or, point_param, point_req, str_param, targets};
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, stretch_grip};
use crate::grips::{GripAction, GripMode, grip_action, mode_matrix, shown_grips, stretch_shown};
use crate::{EngineError, Result, Session};
pub fn specs() -> Vec<CommandSpec> {
@@ -46,25 +46,28 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
return Err(EngineError::Other("The object is on a locked layer.".into()));
}
let e = curves::entity(s, h)?;
let k = stretch_grip(&e.kind, i, to).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
let mut edits = vec![(h, k)];
let view = s.anno_view();
let doc = s.doc()?;
let ne = stretch_shown(doc, &e, i, to, view).ok_or_else(|| bad(cmd, "no such grip, or the result would be degenerate"))?;
let mut edits = vec![(h, ne)];
// The other `handles` with a grip on the same point stretch with it (connected objects stay
// connected); locked ones and edits that would be degenerate are left alone.
let from = e.kind.grips().get(i).copied().unwrap_or(to);
let from = shown_grips(doc, &e, view).get(i).copied().unwrap_or(to);
let tol = 1e-9 * (1.0 + from.len());
for o in targets(s, p)? {
if o == h || edits.iter().any(|(x, _)| *x == o) || curves::is_locked(s, o) {
continue;
}
let Ok(oe) = curves::entity(s, o) else { continue };
if let Some(j) = oe.kind.grips().iter().position(|g| g.near(from, tol))
&& let Some(k) = stretch_grip(&oe.kind, j, to)
if let Some(j) = shown_grips(doc, &oe, view).iter().position(|g| g.near(from, tol))
&& let Some(ne) = stretch_shown(doc, &oe, j, to, view)
{
edits.push((o, k));
edits.push((o, ne));
}
}
let d = s.doc_mut()?;
for (o, k) in &mut edits {
for (o, ne) in &mut edits {
let (k, moves) = (&mut ne.kind, &ne.common.anno_moves);
// A dimension's text moved by its grip: with DIMTMOVE 0 the dimension line follows.
if let cadcraft_doc::EntityKind::Dimension(dm) = k
&& let Some(cadcraft_doc::EntityKind::Dimension(old)) = d.entity(*o).map(|e| &e.kind)
@@ -73,14 +76,17 @@ fn stretch(s: &mut Session, cmd: &str, p: &Value) -> Result<Value> {
let st = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
st.follow_text(dm, d.header.f64("DIMSCALE", 1.0));
}
d.modify_entity(*o, |e| e.kind = k.clone())?;
d.modify_entity(*o, |e| {
e.kind = k.clone();
e.common.anno_moves = moves.clone();
})?;
}
Ok(json!({ "handle": h.hex(), "handles": edits.iter().map(|(o, _)| o.hex()).collect::<Vec<_>>() }))
}
/// Z coordinate of grip `index` on `kind` (matching `EntityKind::grips()` order), when the
/// entity stores a 3D position for that grip.
pub(super) fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
fn grip_z(kind: &EntityKind, index: usize) -> Option<f64> {
let text_z = |t: &cadcraft_doc::Text| match (t.halign, t.valign) {
(cadcraft_doc::HAlign::Left, cadcraft_doc::VAlign::Baseline) | (cadcraft_doc::HAlign::Aligned | cadcraft_doc::HAlign::Fit, _) => t.insert.z,
_ => t.align_pt.unwrap_or(t.insert).z,
@@ -151,10 +157,17 @@ fn base_point(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec2>
.or_else(|| hs.first().copied())
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
let i = index_param(cmd, p)?;
let g = curves::entity(s, h)?.kind.grips();
let g = shown_grips(s.doc()?, &curves::entity(s, h)?, s.anno_view());
g.get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))
}
/// The displayed grip's planar point and its Z, when the entity has one.
pub(super) fn shown_grip_location(d: &Drawing, e: &Entity, index: usize, view: Option<f64>) -> Option<(Vec2, Option<f64>)> {
let kind = d.anno_shown_in(e, view);
let point = kind.grips().get(index).copied()?;
Some((point, grip_z(&kind, index)))
}
/// 3D base point for SCALE: explicit `base` (with optional Z or ELEVATION), or the selected grip's
/// full 3D position so the grip stays stationary in all three coordinates.
fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec3> {
@@ -169,8 +182,8 @@ fn base_point_3d(s: &Session, cmd: &str, p: &Value, hs: &[Handle]) -> Result<Vec
.ok_or_else(|| bad(cmd, "`base` or `baseHandle` + `index` is required"))?;
let i = index_param(cmd, p)?;
let e = curves::entity(s, h)?;
let g = e.kind.grips().get(i).copied().ok_or_else(|| bad(cmd, "no such grip"))?;
Ok(match grip_z(&e.kind, i) {
let (g, z) = shown_grip_location(s.doc()?, &e, i, s.anno_view()).ok_or_else(|| bad(cmd, "no such grip"))?;
Ok(match z {
Some(z) => Vec3::new(g.x, g.y, z),
None => super::modify::at_elevation(s, g),
})
@@ -201,7 +214,7 @@ fn run_grip_stretch(s: &mut Session, p: &Value) -> Result<Value> {
None => {
let base = match point_param(p, "base") {
Some(b) => b,
None => curves::entity(s, h0)?.kind.grips().get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
None => shown_grips(s.doc()?, &curves::entity(s, h0)?, s.anno_view()).get(i0).copied().ok_or_else(|| bad(cmd, "no such grip"))?,
};
point_req(cmd, p, "to")? - base
}
@@ -245,8 +258,9 @@ const MAX_GRIPS: usize = 1000;
/// The objects as they'd be after moving the grips `hot` by `delta`, with the grips of `others`
/// that sit on a hot grip's point (connected objects stay connected). Locked objects and edits
/// that would be degenerate are left out; several hot grips of one object move together.
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, EntityKind)> {
pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle], delta: Vec2) -> Vec<(Handle, Entity)> {
let Ok(d) = s.doc() else { return Vec::new() };
let view = s.anno_view();
// Every grip to move, per object, with its target point.
let mut moves: Vec<(Handle, Vec<(usize, Vec2)>)> = Vec::new();
let mut add = |h: Handle, i: usize, to: Vec2| match moves.iter_mut().find(|(x, _)| *x == h) {
@@ -258,14 +272,14 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
None => moves.push((h, vec![(i, to)])),
};
for &(h, i) in hot.iter().take(MAX_GRIPS) {
let Some(from) = d.entity(h).and_then(|e| e.kind.grips().get(i).copied()) else { continue };
let Some(from) = d.entity(h).and_then(|e| shown_grips(d, e, view).get(i).copied()) else { continue };
add(h, i, from + delta);
let tol = 1e-9 * (1.0 + from.len());
for &o in others.iter().take(MAX_GRIPS) {
if o == h {
continue;
}
if let Some(j) = d.entity(o).and_then(|e| e.kind.grips().iter().position(|g| g.near(from, tol))) {
if let Some(j) = d.entity(o).and_then(|e| shown_grips(d, e, view).iter().position(|g| g.near(from, tol))) {
add(o, j, from + delta);
}
}
@@ -276,16 +290,16 @@ pub(super) fn stretched(s: &Session, hot: &[(Handle, usize)], others: &[Handle],
continue;
}
let Some(e) = d.entity(h) else { continue };
let mut k = e.kind.clone();
let mut ne = (**e).clone();
let mut changed = false;
for (i, to) in mv {
if let Some(nk) = stretch_grip(&k, i, to) {
k = nk;
if let Some(n) = stretch_shown(d, &ne, i, to, view) {
ne = n;
changed = true;
}
}
if changed {
out.push((h, k));
out.push((h, ne));
}
}
out
@@ -297,16 +311,19 @@ pub(super) fn stretch_grips(s: &mut Session, hot: &[(Handle, usize)], others: &[
let edits = stretched(s, hot, others, delta);
let d = s.doc_mut()?;
let mut out = Vec::new();
for (h, k) in edits {
for (h, ne) in edits {
if copy {
let (Some(sp), Some(e)) = (d.space_of(h), d.entity(h).map(|e| (**e).clone())) else { continue };
let Some(sp) = d.space_of(h) else { continue };
let nh = d.new_handle();
if let Some(st) = d.space_mut(&sp) {
st.push(Entity { handle: nh, kind: k, ..e });
st.push(Entity { handle: nh, ..ne });
out.push(nh);
}
} else {
d.modify_entity(h, |e| e.kind = k)?;
d.modify_entity(h, |e| {
e.kind = ne.kind;
e.common.anno_moves = ne.common.anno_moves;
})?;
out.push(h);
}
}
+10 -4
View File
@@ -104,14 +104,16 @@ impl GripEdit {
if self.hot.contains(&(h, i)) || self.hot.len() >= MAX_HOT {
return Ok(());
}
let p = s.grips_of(h)?.get(i).copied().ok_or_else(|| other("no such grip"))?;
let d = s.doc()?;
let e = d.entity(h).ok_or_else(|| other("no such object"))?;
let (p, z) = super::gripcmds::shown_grip_location(d, e, i, s.anno_view()).ok_or_else(|| other("no such grip"))?;
// After the lookup: a missing object or grip stays the error it was.
if !shown(s, h) {
return Ok(());
}
if self.hot.is_empty() {
self.base = p;
self.base_z = s.doc().ok().and_then(|d| d.entity(h)).and_then(|e| super::gripcmds::grip_z(&e.kind, i));
self.base_z = z;
self.targets.push(h);
self.targets.extend(s.selection().into_iter().filter(|x| *x != h && shown(s, *x)));
} else if !self.targets.contains(&h) {
@@ -131,7 +133,7 @@ impl GripEdit {
continue;
}
let Some(e) = st.doc.entity(h).filter(|e| st.shows(e)) else { continue };
let gs = e.kind.grips();
let gs = crate::grips::shown_grips(&st.doc, e, s.anno_view());
// The nearest grip of this object within the tolerance.
let best = gs
.iter()
@@ -491,7 +493,11 @@ impl Interactive for GripEdit {
};
let Ok(d) = s.doc() else { return Vec::new() };
let mut out: Vec<EntityKind> = if self.mode == GripMode::Stretch {
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base).into_iter().take(500).map(|(_, k)| k).collect()
super::gripcmds::stretched(s, &self.hot, &self.targets, c - base)
.into_iter()
.take(500)
.map(|(_, e)| d.anno_shown_in(&e, s.anno_view()))
.collect()
} else {
match self.matrix(c) {
Some(m) => self
+2 -1
View File
@@ -190,10 +190,11 @@ pub(crate) fn explode_kind(d: &cadcraft_doc::Drawing, e: &Entity) -> Option<Vec<
// An annotative object explodes into plain objects as it draws at the current annotation scale.
if cadcraft_doc::is_annotative(e) {
let mut se = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Scaled(f) => cadcraft_doc::anno_scaled(e, f),
cadcraft_doc::AnnoDraw::Scaled { factor, by } => cadcraft_doc::anno_placed(e, factor, by),
_ => e.clone(),
};
se.common.anno_scales.clear();
se.common.anno_moves.clear();
return explode_kind(d, &se);
}
match &e.kind {
+5 -1
View File
@@ -7,7 +7,10 @@ use super::{Entity, Handle, Mat3, Result, Session, Value, Vec2, bad, bool_or, er
pub(crate) fn transform_entities(s: &mut Session, hs: &[Handle], m: &Mat3, copy: bool) -> Result<Vec<Handle>> {
refuse_ole_frames(s, hs, m, copy)?;
edit_entities(s, hs, copy, |e| e.kind.transform(m))
edit_entities(s, hs, copy, |e| {
e.kind.transform(m);
e.common.transform_moves(m);
})
}
/// MIRROR's default hatch policy retains the fill direction while reflecting its boundary.
@@ -40,6 +43,7 @@ pub(crate) fn scale_entities(s: &mut Session, hs: &[Handle], base: Vec3, f: f64,
refuse_ole_frames(s, hs, &m, copy)?;
edit_entities(s, hs, copy, |e| {
e.kind.transform(&m);
e.common.transform_moves(&m);
e.kind.scale_heights(base.z, f);
e.common.thickness *= f;
})
+1
View File
@@ -202,6 +202,7 @@ fn chspace(s: &mut Session, hs: &[Handle], to: Option<&str>, vp: Option<Handle>)
}
let mut e = e;
e.kind.transform(&m);
e.common.transform_moves(&m);
d.remove_entity(*h);
if let Some(st) = d.space_mut(&target) {
st.push(e);
+2 -2
View File
@@ -70,8 +70,8 @@ pub(crate) fn editor_for(s: &Session, h: Handle) -> Option<crate::TextEditor> {
// Annotative text and dimensions are drawn scaled to the current annotation scale: the box
// follows what is drawn. Multiline text keeps its stored height (it is written back from it).
let scaled = match d.anno_draw(e) {
cadcraft_doc::AnnoDraw::Scaled(f) if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
Some(cadcraft_doc::anno_scaled(e, f))
cadcraft_doc::AnnoDraw::Scaled { factor, by } if matches!(e.kind, EntityKind::Text(_) | EntityKind::AttDef(_) | EntityKind::Dimension(_)) => {
Some(cadcraft_doc::anno_placed(e, factor, by))
}
_ => None,
};
+6
View File
@@ -171,6 +171,12 @@ impl DocState {
_ => None,
}
}
/// The annotation scale model space is edited at in the active MSPACE viewport: the
/// viewport's scale (drawing units per paper unit, as the renderer draws it there); `None`
/// outside one (the current annotation scale applies).
pub fn anno_view(&self) -> Option<f64> {
self.active_viewport().map(|(_, v)| v.view_height / v.height).filter(|f| f.is_finite() && *f > 0.0)
}
/// The layers frozen in the active MSPACE viewport (VPLAYER, "VP Freeze"): that viewport does
/// not draw their objects, so picks, selections and grips made through it leave them out.
/// Empty in paper space and on the Model tab.
+6
View File
@@ -74,6 +74,12 @@ impl AutomationRoots {
Ok(Some(Arc::new(Self { read, write })))
}
/// Roots that grant nothing: every read and write is refused. For agents whose folders can't
/// be used, where leaving the roots out would confine nothing.
pub fn none() -> Arc<Self> {
Arc::new(Self { read: None, write: None })
}
/// The read root, absolute with its links followed.
pub fn read_root(&self) -> Option<&Path> {
self.read.as_deref()
+3 -2
View File
@@ -185,8 +185,9 @@ pub fn grip_dims(s: &Session) -> Vec<GripDim> {
return Vec::new();
}
let Some((h, i)) = s.current_prompt().and_then(|p| p.grip) else { return Vec::new() };
let Some(e) = s.doc().ok().and_then(|d| d.entity(h)) else { return Vec::new() };
let all = dims_of(&e.kind, i);
let Ok(d) = s.doc() else { return Vec::new() };
let Some(e) = d.entity(h) else { return Vec::new() };
let all = dims_of(&d.anno_shown_in(e, s.anno_view()), i);
let st = &s.settings;
match st.dyndivis {
0 => all.into_iter().take(1).collect(),
+51 -2
View File
@@ -4,7 +4,7 @@
//! The UI calls [`Session::grip_edit`]; every edit runs through a `grip.*` command so it is
//! undoable and reachable from scripts, the control channel and MCP.
use cadcraft_doc::{DimKind, EntityKind, Handle, LwPolyline};
use cadcraft_doc::{DimKind, Drawing, Entity, EntityKind, Handle, LwPolyline};
use cadcraft_geom::{Arc, EPS, Mat3, Polyline, Vec2, Vec3, norm_angle};
use serde::{Deserialize, Serialize};
use serde_json::json;
@@ -564,10 +564,59 @@ impl Session {
/// Grip points of an object (the indices `grip_edit` takes).
pub fn grips_of(&self, handle: Handle) -> Result<Vec<Vec2>> {
self.doc()?.entity(handle).map(|e| e.kind.grips()).ok_or_else(|| EngineError::Other("no such object".into()))
let d = self.doc()?;
d.entity(handle).map(|e| shown_grips(d, e, self.anno_view())).ok_or_else(|| EngineError::Other("no such object".into()))
}
}
/// The grip points of `e` as it shows (the indices `grip_edit` takes): an annotative object's at
/// the annotation scale it shows at and its position there. `view`: the active viewport's scale
/// in MSPACE ([`crate::DocState::anno_view`]), else the current annotation scale applies.
pub fn shown_grips(d: &Drawing, e: &Entity, view: Option<f64>) -> Vec<Vec2> {
d.anno_shown_in(e, view).grips()
}
/// `e` with grip `index` of [`shown_grips`] moved to `to`, or `None` when that grip can't move
/// there. An annotative object's position grip moves it at the scale it shows at only when it
/// supports several scales; its other grips change its shape at every scale (the edit is taken
/// back to paper size).
pub fn stretch_shown(d: &Drawing, e: &Entity, index: usize, to: Vec2, view: Option<f64>) -> Option<Entity> {
let with = |kind: EntityKind| Some(Entity { kind, ..e.clone() });
let (Some(scale), cadcraft_doc::AnnoDraw::Scaled { factor, by }) = (d.anno_shown_scale_in(e, view), d.anno_draw_in(e, view)) else {
return with(stretch_grip(&e.kind, index, to)?);
};
let shown = cadcraft_doc::anno_placed(e, factor, by).kind;
let from = *shown.grips().get(index)?;
let delta = to - from;
if !delta.is_finite() {
return None;
}
if cadcraft_doc::is_position_grip(&e.kind, index) {
if e.common.anno_scales.len() > 1 {
let mut out = e.clone();
out.common.move_at(&scale.name, delta);
return Some(out);
}
let stored = *e.kind.grips().get(index)?;
return with(stretch_grip(&e.kind, index, stored + delta)?);
}
// A shape grip: stretch the object as it shows, then take it back to paper size.
let mut k = stretch_grip(&shown, index, to)?;
cadcraft_doc::shift_position(&mut k, -by);
let k = match (k, &e.kind) {
(EntityKind::Dimension(mut dm), EntityKind::Dimension(old)) => {
// A dimension's geometry isn't scaled: only its style scale was.
dm.overrides = old.overrides.clone();
if by != Vec2::ZERO {
dm.user_text_pos = old.user_text_pos;
}
EntityKind::Dimension(dm)
}
(k, _) => cadcraft_doc::anno_scaled(&Entity { kind: k, ..e.clone() }, 1.0 / factor).kind,
};
with(k)
}
/// Polyline helper kept public for the UI: segment midpoints are grips too.
pub fn polyline_grip_count(p: &LwPolyline) -> usize {
p.vertices.len() + Polyline { vertices: p.vertices.clone(), closed: p.closed }.segments().len().min(p.vertices.len())
+7
View File
@@ -7,6 +7,8 @@
//! [`Session::input`], [`Session::cmdline`]) exactly like typing at AutoCAD's command line.
#![deny(clippy::unwrap_used, clippy::expect_used, clippy::panic, clippy::unimplemented, clippy::todo, clippy::unreachable)]
#![forbid(unsafe_code)]
#[cfg(not(target_arch = "wasm32"))]
pub mod agent_settings;
pub mod array_live;
pub mod assoc;
@@ -416,6 +418,11 @@ impl Session {
Ok(h)
}
/// The annotation scale of the active MSPACE viewport ([`DocState::anno_view`]).
pub fn anno_view(&self) -> Option<f64> {
self.state().ok().and_then(DocState::anno_view)
}
/// World units per pixel at the current view.
pub fn pixel_size(&self) -> f64 {
let v = self.state().map(DocState::view).unwrap_or_default();
+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
+1 -1
View File
@@ -81,7 +81,7 @@ fn unsupported_scale_hides_unless_annoallvisible() {
let (mut s, h) = with_text();
setvar(&mut s, "CANNOSCALE", json!("1:20"));
// ANNOALLVISIBLE 1 (the default): shown, at the object's own scale.
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled(1.0));
assert_eq!(s.doc().unwrap().anno_draw(&entity(&s, h)), AnnoDraw::Scaled { factor: 1.0, by: cadcraft_engine::geom::Vec2::ZERO });
assert!(drawn_height(s.doc().unwrap(), h).is_some());
s.execute("annovisible.current", &json!({})).unwrap();
assert_eq!(s.doc().unwrap().header.i64("ANNOALLVISIBLE", 1), 0);
@@ -0,0 +1,221 @@
//! An annotative object can sit somewhere else at one of its scales: its grips move it at the
//! current annotation scale only (when it supports several), MOVE and ROTATE move every scale,
//! and ANNORESET puts every scale back where the current one is.
use cadcraft_engine::Session;
use cadcraft_engine::doc::{AnnoDraw, Entity, EntityKind, Handle};
use cadcraft_engine::geom::Vec2;
use serde_json::{Value, json};
fn setvar(s: &mut Session, name: &str, value: Value) {
s.execute("setvar", &json!({ "name": name, "value": value })).unwrap();
}
fn handle(r: &Value) -> Handle {
r["handle"].as_str().or_else(|| r["handles"][0].as_str()).and_then(Handle::parse_hex).unwrap()
}
fn entity(s: &Session, h: Handle) -> Entity {
(**s.doc().unwrap().entity(h).unwrap()).clone()
}
/// Annotative text at the origin supporting 1:1 and 1:50, with 1:50 current.
fn two_scales() -> (Session, Handle) {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:50"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).unwrap();
(s, h)
}
/// Where `h` shows at annotation scale `name`.
fn shown_at(s: &mut Session, h: Handle, name: &str) -> Vec2 {
setvar(s, "CANNOSCALE", json!(name));
let d = s.doc().unwrap();
match d.anno_shown(d.entity(h).unwrap()) {
EntityKind::Text(t) => t.insert.xy(),
EntityKind::MText(t) => t.insert.xy(),
EntityKind::MLeader(m) => m.landing.xy(),
EntityKind::Dimension(dm) => dm.text_mid.xy(),
k => panic!("{k:?}"),
}
}
fn near(a: Vec2, b: Vec2) -> bool {
a.dist(b) < 1e-9
}
#[test]
fn a_grip_moves_text_at_the_current_scale_only() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
// The grips show where the object is.
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::ZERO));
}
#[test]
fn grip_scale_keeps_the_displayed_annotation_pivot_and_its_elevation() {
let (mut s, h) = two_scales();
let (z, other_z) = (7.0, 2.0);
s.doc_mut().unwrap().header.set_f64("ELEVATION", other_z);
s.doc_mut()
.unwrap()
.modify_entity(h, |e| {
let EntityKind::Text(t) = &mut e.kind else { panic!("expected text") };
t.insert.z = z;
})
.unwrap();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
let pivot = s.grips_of(h).unwrap()[0];
assert!(near(pivot, Vec2::new(5.0, 5.0)));
let EntityKind::Text(before) = entity(&s, h).kind else { panic!("expected text") };
s.execute("grip.scale", &json!({ "handles": [h.hex()], "baseHandle": h.hex(), "index": 0, "factor": 2.0 })).unwrap();
let EntityKind::Text(after) = entity(&s, h).kind else { panic!("expected text") };
assert!(near(s.grips_of(h).unwrap()[0], pivot), "the displayed grip is stationary");
assert!((after.insert.z - z).abs() < 1e-9, "the selected grip's Z is stationary, not ELEVATION");
assert!((after.height - 2.0 * before.height).abs() < 1e-9, "the scale operation actually took effect");
}
#[test]
fn undo_takes_a_move_at_one_scale_back() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
assert_eq!(entity(&s, h).common.anno_moves.len(), 1);
s.execute("undo", &json!({})).unwrap();
assert!(entity(&s, h).common.anno_moves.is_empty());
}
#[test]
fn move_and_rotate_carry_every_scale() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
s.execute("move", &json!({ "handles": [h.hex()], "delta": [1, 0] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(6.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(1.0, 0.0)));
s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 90 })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(-5.0, 6.0)));
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(0.0, 1.0)));
}
#[test]
fn annoreset_puts_every_scale_at_the_current_one() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let r = s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
assert_eq!(r["reset"], 1, "{r}");
assert!(entity(&s, h).common.anno_moves.is_empty());
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(5.0, 5.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(5.0, 5.0)));
}
#[test]
fn removing_a_scale_drops_its_position() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
s.execute("objectscale", &json!({ "handles": [h.hex()], "delete": "1:50" })).unwrap();
assert!(entity(&s, h).common.anno_moves.is_empty());
}
#[test]
fn an_object_with_one_scale_moves_everywhere() {
let mut s = Session::new();
s.execute("style", &json!({ "name": "Notes", "annotative": true, "current": true })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let h = handle(&s.execute("text", &json!({ "at": [0, 0], "text": "NOTE", "height": 0.25 })).unwrap());
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
let e = entity(&s, h);
assert!(e.common.anno_moves.is_empty());
let EntityKind::Text(t) = &e.kind else { panic!() };
assert!(near(t.insert.xy(), Vec2::new(5.0, 5.0)));
}
#[test]
fn a_multileader_moves_its_content_and_keeps_its_arrowhead() {
let mut s = Session::new();
s.execute("mleaderstyle", &json!({ "name": "Anno", "annotative": true })).unwrap();
let h = handle(&s.execute("mleader", &json!({ "points": [[0, 0], [5, 5]], "text": "A" })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:50"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:50" })).unwrap();
let EntityKind::MLeader(m) = entity(&s, h).kind else { panic!() };
let landing = m.leaders.iter().map(Vec::len).sum::<usize>();
let to = m.landing.xy() + Vec2::new(2.0, 1.0);
s.execute("grip.move", &json!({ "handle": h.hex(), "index": landing, "to": [to.x, to.y] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:50"), to));
assert!(near(shown_at(&mut s, h, "1:1"), m.landing.xy()));
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let d = s.doc().unwrap();
let EntityKind::MLeader(shown) = d.anno_shown(d.entity(h).unwrap()) else { panic!() };
assert!(near(shown.leaders[0][0].xy(), Vec2::ZERO), "the arrowhead stays");
}
#[test]
fn a_dimension_moves_its_text_at_one_scale() {
let mut s = Session::new();
s.execute("dimstyle", &json!({ "name": "Anno", "annotative": true, "current": true })).unwrap();
let h = handle(&s.execute("dimaligned", &json!({ "p1": [0, 0], "p2": [10, 0], "at": [5, 2] })).unwrap());
setvar(&mut s, "CANNOSCALE", json!("1:2"));
s.execute("objectscale", &json!({ "handles": [h.hex()], "add": "1:2" })).unwrap();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 3, "to": [20, 20] })).unwrap();
assert!(near(shown_at(&mut s, h, "1:2"), Vec2::new(20.0, 20.0)));
let e = entity(&s, h);
let EntityKind::Dimension(dm) = &e.kind else { panic!() };
assert!(!near(dm.text_mid.xy(), Vec2::new(20.0, 20.0)), "the shared text position stays");
assert_eq!(e.common.anno_moves.len(), 1);
}
#[test]
fn shown_draws_through_the_offset() {
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:50"));
let d = s.doc().unwrap();
assert!(matches!(d.anno_draw(d.entity(h).unwrap()), AnnoDraw::Scaled { by, .. } if near(by, Vec2::new(5.0, 5.0))));
let b = cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0);
assert!(b.min.x > 4.0 && b.min.y > 4.0, "{b:?}");
}
#[test]
fn hostile_offsets_never_panic() {
let (mut s, h) = two_scales();
for to in [json!([1e308, -1e308]), json!([f64::MAX, 0]), json!(["x", 1])] {
let _ = s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": to }));
}
s.doc_mut().unwrap().modify_entity(h, |e| e.common.move_at("1:50", Vec2::new(f64::NAN, 1.0))).unwrap();
let _ = s.execute("annoreset", &json!({ "handles": [h.hex()] }));
let _ = s.execute("rotate", &json!({ "handles": [h.hex()], "base": [0, 0], "angle": 1e300 }));
let d = s.doc().unwrap();
let _ = cadcraft_engine::render::build(d, &cadcraft_engine::doc::Space::Model, &Default::default());
let _ = bounds(d, h);
}
fn bounds(d: &cadcraft_engine::doc::Drawing, h: Handle) -> cadcraft_engine::geom::Bounds2 {
cadcraft_engine::doc::entity_bounds(d, d.entity(h).unwrap(), 0)
}
#[test]
fn in_a_viewport_grips_and_annoreset_use_the_viewport_s_scale() {
// The text moved at 1:50; CANNOSCALE is 1:1 while a 1:50 viewport is active (MSPACE): the
// grips show where the viewport draws it, a grip moves it at 1:50, ANNORESET takes 1:50's place.
let (mut s, h) = two_scales();
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [5, 5] })).unwrap();
setvar(&mut s, "CANNOSCALE", json!("1:1"));
s.execute("layout.set", &json!({ "name": "Layout1" })).unwrap();
let vp = s.execute("mview", &json!({ "p1": [0, 0], "p2": [200, 100] })).unwrap();
let vh = vp["viewports"][0].as_str().and_then(Handle::parse_hex).unwrap();
s.execute("viewport.set", &json!({ "handle": vh.hex(), "scale": "1:50", "center": [0, 0] })).unwrap();
s.execute("mspace", &json!({ "handle": vh.hex() })).unwrap();
assert!((s.anno_view().unwrap() - 50.0).abs() < 1e-9);
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(5.0, 5.0)), "{:?}", s.grips_of(h));
s.execute("grip.move", &json!({ "handle": h.hex(), "index": 0, "to": [7, 7] })).unwrap();
assert!(near(s.grips_of(h).unwrap()[0], Vec2::new(7.0, 7.0)));
s.execute("annoreset", &json!({ "handles": [h.hex()] })).unwrap();
s.execute("pspace", &json!({})).unwrap();
s.execute("layout.set", &json!({ "name": "Model" })).unwrap();
// 1:1 was never moved by the grips, and now sits where 1:50 is.
assert!(near(shown_at(&mut s, h, "1:1"), Vec2::new(7.0, 7.0)));
assert!(near(shown_at(&mut s, h, "1:50"), Vec2::new(7.0, 7.0)));
}
+1
View File
@@ -6,6 +6,7 @@ mod angle_prompts;
mod angle_settings;
mod annotate_options;
mod annotative;
mod annotative_positions;
mod arc_ctrl_direction;
mod array_commands;
mod array_counts;
+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;
}
});
}
+1 -78
View File
@@ -1,6 +1,4 @@
use super::{
Block, Color, Common, Dimension, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext,
};
use super::{Block, Color, Common, Drawing, Entity, EntityKind, EntityStore, Handle, HashMap, Line, MText, Solid, Table, Vec2, Vec3, dxf_ext};
/// What happens to the dimension blocks read from a file (#495): a dimension that still names
/// its block is written with that block, under its name, and `*D` blocks nothing else
@@ -79,81 +77,6 @@ pub(super) fn reuse_handles(ents: &mut [Entity], old: &Block, taken: &mut std::c
}
}
/// Anonymous dimension blocks (`*D1`…) with the rendered geometry, as consumers expect.
pub(super) fn dim_block_entities(d: &Drawing, dm: &Dimension, layer: &str) -> Vec<Entity> {
// The dimension as drawn: its overrides, DIMSCALE (0 = the drawing's) and text font.
let style = d.dim_style(&dm.style).cloned().unwrap_or_default().with_overrides(&dm.overrides);
let g = cadcraft_render::dimension_in(d, dm);
let mut out = Vec::new();
// Each part in its style colour (DIMCLRD, DIMCLRE, DIMCLRT), ByBlock when the style says so,
// as AutoCAD writes them: readers that draw the block drew every part ByBlock, i.e. in the
// dimension's own colour (#1052).
let in_color = |color: Color| Common { layer: layer.into(), color, ..Common::default() };
let (dim_c, ext_c, text_c) = (in_color(style.dim_line_color), in_color(style.ext_line_color), in_color(style.text_color));
let line_entities = |i: usize, l: &[Vec2]| -> Vec<Entity> {
let c = match g.line_roles.get(i) {
Some(cadcraft_render::LineRole::Ext) => &ext_c,
_ => &dim_c,
};
l.windows(2)
.filter_map(|seg| match seg {
[a, b] => Some(Entity { handle: Handle(0), common: c.clone(), kind: EntityKind::Line(Line { a: a.to3(0.0), b: b.to3(0.0) }) }),
_ => None,
})
.collect()
};
// The text's marks (arc length symbol, DIMINSPECT frame) go after the text background.
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| !g.text_marks.contains(i)) {
out.extend(line_entities(i, l));
}
for t in &g.fills {
if let [a, b, cc] = t.as_slice() {
out.push(Entity {
handle: Handle(0),
common: dim_c.clone(),
kind: EntityKind::Solid(Solid { corners: [a.to3(0.0), b.to3(0.0), cc.to3(0.0), cc.to3(0.0)] }),
});
}
}
// DIMTFILL 2: the text background in DIMTFILLCLR, under the text and its marks (SOLID
// corners go 1, 2, 4, 3).
if style.text_fill == 2
&& let [p0, p1, p2, p3] = g.text_fill.as_slice()
{
out.push(Entity {
handle: Handle(0),
common: in_color(style.text_fill_color),
kind: EntityKind::Solid(Solid { corners: [p0.to3(0.0), p1.to3(0.0), p3.to3(0.0), p2.to3(0.0)] }),
});
}
for (i, l) in g.lines.iter().enumerate().filter(|(i, _)| g.text_marks.contains(i)) {
out.extend(line_entities(i, l));
}
// The text, and the part after `\X` below the dimension line as a second MTEXT, as AutoCAD
// writes it (#1055).
let texts = std::iter::once((g.value.clone(), g.text_pos)).chain(g.below.clone());
for (contents, at) in texts.filter(|(t, _)| !t.is_empty()) {
out.push(Entity {
handle: Handle(0),
common: text_c.clone(),
kind: EntityKind::MText(MText {
insert: at.to3(0.0),
height: g.text_height,
width: 0.0,
attach: 5,
rotation: g.text_angle,
style: style.text_style.clone(),
contents: cadcraft_render::DimGeometry::mtext_code(&contents),
line_spacing: 1.0,
line_spacing_exact: false,
columns: None,
background: None,
}),
});
}
out
}
/// Rows and columns written for a table (bounded like the renderer).
pub(super) fn table_size(t: &Table) -> (usize, usize) {
(t.row_heights.len().min(10_000), t.col_widths.len().min(10_000))
+1
View File
@@ -678,6 +678,7 @@ fn write_annotations_entity(w: &mut W, d: &Drawing, e: &Entity, owner: &str, pap
let mut tags = cx.mleader_tags(d, m);
if let Some(o) = cx.anno.objs.get(&e.handle) {
crate::dxf_anno::mleader_at(&mut tags, crate::dxf_anno::default_factor(o));
crate::dxf_anno::mleader_annotative(&mut tags);
}
w.t.extend(tags);
cx.anno_xdata(w, e);
+2 -1
View File
@@ -1,5 +1,5 @@
use super::assoc::std_assoc_refs;
use super::blocks::{arrow_block_entities, dim_block_entities, dim_block_plan, reuse_handles, table_block_entities};
use super::blocks::{arrow_block_entities, dim_block_plan, reuse_handles, table_block_entities};
use super::common::annotative_xdata;
use super::ctx::{AssocObj, Ctx};
use super::entity::{entity, hatch_reactors};
@@ -11,6 +11,7 @@ use super::{
Space, TableStyle, Tag, Ucs, Vec2, Vec3, Version, W, dxf_ext,
};
use super::{entity_handles, structural_start};
use cadcraft_render::dim_block_entities;
struct TableWritePlan<'a> {
d: &'a Drawing,
@@ -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);
}
}
+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
+8 -2
View File
@@ -1,7 +1,8 @@
#!/usr/bin/env bash
# Build, sign and (optionally) notarize the macOS release artifacts:
#
# $DIST/cadcraft-<version>-macos-<arch>.dmg CADCraft.app on a drag-to-Applications DMG
# $DIST/cadcraft-<version>-macos-<arch>.dmg CADCraft.app on a drag-to-Applications DMG, with
# cadcraft-cli in Contents/MacOS for the ArtCraft Launcher
# $DIST/cadcraft-cli-<version>-macos-<arch>.zip the headless CLI
#
# Usage: packaging/macos/package.sh [--arch universal|aarch64|x86_64] [--skip-build]
@@ -117,6 +118,9 @@ echo "==> assembling $APP"
mkdir -p "$APP/Contents/MacOS" "$APP/Contents/Resources"
# Executable and icon carry the display name (CFBundleExecutable / CFBundleIconFile).
cp "$WORK/bin/cadcraft" "$APP/Contents/MacOS/CADCraft"
# The CLI beside the app: the ArtCraft Launcher lists an installed app for AI agents only when
# `cadcraft-cli` sits next to its executable, and `cadcraft-cli mcp` starts the app from there.
cp "$WORK/bin/cadcraft-cli" "$APP/Contents/MacOS/cadcraft-cli"
cp "$ROOT/assets/app-icon/cadcraft.icns" "$APP/Contents/Resources/CADCraft.icns"
# The licences and the bundled dependency font notices are installed before the app is signed.
cp "$ROOT/LICENSE-MIT" "$ROOT/LICENSE-APACHE" "$ROOT/NOTICE" "$ROOT/ATTRIBUTION.md" \
@@ -130,7 +134,8 @@ plutil -lint "$APP/Contents/Info.plist"
printf 'APPL????' >"$APP/Contents/PkgInfo"
# Sign inside-out: nested code first, then the bundle itself (no --deep on the final signature).
# Today the only nested code is the main executable; frameworks/helpers would be signed here too.
# The nested code is the CLI and the main executable; frameworks/helpers would be signed here too.
sign --options runtime "$APP/Contents/MacOS/cadcraft-cli"
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP/Contents/MacOS/CADCraft"
sign --options runtime --entitlements "$HERE/entitlements.plist" "$APP"
codesign --verify --strict --deep --verbose=2 "$APP"
@@ -183,5 +188,6 @@ ditto -c -k --keepParent "$CLI_DIR" "$CLI_ZIP"
if [[ "$NOTARIZE" = 1 ]]; then notarize "$CLI_ZIP"; fi
"$WORK/bin/cadcraft-cli" --version
"$APP/Contents/MacOS/cadcraft-cli" --version
echo "==> done"
ls -lh "$DMG" "$CLI_ZIP"