Commit Graph
3503 Commits
Author SHA1 Message Date
PanosandClaude Opus 5 9fe2e4fa58 fix(view): hold ZOOMFACTOR to its own range, finish the exponential zoom
The exponential camera step is the right call. `0.9 ^ delta` is strictly
positive for every real delta, in and out cancel exactly where the
subtraction lost a percent of the view on every round trip, and the file's
own header has promised an "exponential feel" since it was written. Three
surfaces were left behind it, and the wider range exposed a fourth thing.

The range of the system variable. 3 to 100 is the range ZOOMFACTOR has, and
the User Preferences page was built against it; `SETVAR ZOOMFACTOR` accepts
that and nothing else again. A faster wheel is the Options window's business
instead: the slider covers the variable's own range, the field beside it
reaches 500, and a read-out says what a notch actually does ("10.0% a
notch") so the number being set is readable rather than implied. A value
above 100 therefore lives only in this application's own configuration file,
where it is nobody else's to read, and a bare `SETVAR ZOOMFACTOR` still
reports it. The bounds and the clamp live in one place now
(`settings::clamp_zoom_factor`): four literal copies of `3, 100` are what
let a surface be missed in the first place.

A floating viewport in MSPACE. It zooms its own view through
`zoom_active_viewport`, which kept subtracting: the factor reached zero at
6.67 steps, so from ZOOMFACTOR 360 up every notch inside a viewport bottomed
out on the clamp — a tenfold jump a notch, and the top third of the slider
doing nothing at all. Exponential there too, from a base of 0.85 so the
default notch still moves a viewport the 15% it always has. Each surface
keeps its own long-standing feel rather than inheriting the other's.

The trackpad pinch. `pinch_zoom_steps` was calibrated against the
subtraction (`1 - step / 10 = 1 / (1 + m)`) so that a pinch of m leaves the
view exactly 1 + m times closer — the property docs/trackpad.md documents
and the reason the gesture tracks the fingers at all. Inverting the zoom law
by hand is what let the two drift apart, so the step is asked of the camera
now (`Camera::zoom_steps_for_ratio`), which cannot drift by construction.
`pinch_is_one_to_one` recomputed the old formula rather than the camera's,
so it kept passing through all of this; it zooms a real camera and measures
the distance it lands at instead.

Also: `zoom` had a floor and no ceiling, and zooming out multiplies. At
ZOOMFACTOR 500 a notch out is x2.4, so about ninety notches — a couple of
seconds of scrolling — ran the distance past what an f32 far plane
(`distance * 1000`) can hold, and the viewport went black on an infinite
projection. A degenerate pinch magnification of -1 or beyond reached the
same place through the other side. Both are bounded now.

Also: two doc comments quoted the linear law (`zoom_view_at_cursor` and the
one on `pinch_zoom_steps`), and docs/trackpad.md stated the pinch identity
and claimed the tests covered it against the camera. All updated, with what
a notch does and where each surface's range comes from written down.

Tests, each confirmed against the behaviour it describes: the zoom law at
every factor the application can hold (positive, monotonic in the setting,
in and out cancelling), the ceiling under a long scroll out in both
projections, the published inverse and what it does with a nonsense ratio,
the viewport factor and a real viewport zoomed three notches at the top of
the range, the SETVAR range including a value the Options field set, the
Options field (above 100, above the ceiling, cleared, not a number), its
agreement with the slider, Close putting both the value and the field back,
and the read-out's percentages. 1882 lib tests pass.

The two new Options strings are not in the locale catalog yet, so they
render in English until it is regenerated.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-10-02 10:51:26 +03:00
Hakan SevenandClaude Opus 5.5 558b5f6526 fix(attdef): SVG dialog buttons, upper-case tags from Properties, Cargo.toml blank line
#1574's dialog drew its pick, close, field and editor buttons with glyph
text (⌖ × ƒ …) that renders as tofu where the font lacks it; they use the
snap and close SVG icons and plain ASCII now. A tag set from Properties is
stored upper case like one from the dialogs, and the stray blank line the
PR left in Cargo.toml is gone.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-02 10:20:34 +03:00
Hakan Seven a1d0cf3873 Merge PR #1574 from ramox81/codex/attdef-parity: ATTDEF dialog, -ATTDEF, tag display, Properties and Block Definition ribbon
Conflicts with #1573: the locale files and the catalog take both PRs'
entries (one "Insertion Point" mapping kept); the Home and Insert Block
panels take #1574's layout with #1573's Insert Block gallery.
2026-10-02 10:17:54 +03:00
Hakan SevenandClaude Opus 5.5 369dc93029 fix(blocks-palette): message placeholders, SVG arrows, tests follow the new palette
#1573's five formatted block messages carried {}/{name} in every locale,
so the catalog never filled them and the UI printed the brace text; they
use the __ocs_fmt_0__ marker now. The Options collapse arrow, the library
up button and the folder picker are SVG icons instead of glyph text, and
the Details header drops its sort glyph. The contrast test follows the
cards to the weak surface pair and the palette test closes with
BLOCKSPALETTECLOSE, since BLOCKSPALETTE now only opens.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-02 10:15:43 +03:00
Hakan Seven 7a6908c7ca Merge PR #1573 from ramox81/codex/blocks-palette-parity: Blocks palette tabs, insertion options, drag insertion and -INSERT 2026-10-02 10:10:51 +03:00
Hakan Seven e8a4f1316f Merge PR #1577 from mechpanos/fix/zoom-cursor-and-extents: zoom cursor per navigation tool, and ZOOM EXTENTS frames everything 2026-10-02 10:06:43 +03:00
Hakan SevenandClaude Opus 5.5 09cd50ea62 fix(trim): polyline vertices are not cutting edges; self-cuts only as an edge
#1567 made every vertex a trim limit, so a polyline no edge crosses lost
the clicked segment and a trimmed piece stopped at the next corner instead
of running on to the next cutting edge. Vertices are no cuts again, a
polyline with no cut is left alone, and its own crossings cut it only when
it is among the cutting edges. The crossing window's unused pick corner is
dropped.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-02 10:06:10 +03:00
Hakan Seven 3bf8906ed3 Merge PR #1567 from gianlucafiore/fix/polyline-self-intersections: polyline self-intersection snapping and trimming 2026-10-02 10:04:11 +03:00
Hakan SevenandClaude Opus 5.5 65347de904 fix(commands): strip _/. name prefixes only when the name as written is unknown
#1584 stripped the prefixes before dispatch, which turned the ribbon's own
internal names (_PCCROPPOLY, _XREFEDIT, _PDFULSNAP, ...) into unknown
commands. A name is now tried as written and retried without its prefixes
only when no family handles it; the Start-tab gate judges the bare name.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-02 10:02:51 +03:00
Hakan Seven c7df841711 Merge PR #1584 from yztink/fix/scr-scripts: support .scr scripts, multi-line and single-line formats, and command prefixes 2026-10-02 10:00:01 +03:00
Hakan Seven db838e8645 Merge PR #1579 from mechpanos/fix/erased-image-placeholder-text: erasing a broken raster reference clears its placeholder text 2026-10-02 09:58:44 +03:00
Hakan Seven f44d03f472 Merge PR #1581 from F4brizi/feature/increase-zoomfactor-limit: expand ZOOMFACTOR range to 500 2026-10-02 09:58:36 +03:00
yztink f32d0422d2 fix(script): support AutoCAD .scr scripts with multi-line, single-line, and prefix handling 2026-10-01 23:34:15 -07:00
ramox81 53f2983e9c Merge remote-tracking branch 'origin/main' into codex/attdef-parity
# Conflicts:
#	Cargo.lock
#	src/modules/draw/draw/attdef.rs
2026-10-02 09:09:21 +03:00
Karim Jerbi 02c470aac7 feat(pdf): searchable text layer with per-style subset font embedding
Real BT/Tj text objects ride alongside the vector outlines (Tr 3,
zero visual change): runs preserved at layout time, TTF styles embedded
as allsorts subsets with ToUnicode, width-matched Tm, clip-culled.
WireModel literals moved to ..Default::default() tails.
2026-10-01 23:30:35 +01:00
F4brizi e131843826 feat(viewport): expand ZOOMFACTOR range to 500 2026-10-01 18:49:23 -03:00
Hakan SevenandClaude Opus 5.5 443b935a3f chore: bump codec d28fd71, kernel a03e4f0, graph 79bdc4b
Codec: PRs #71-#74 merged (MPOLYGON layout, multiline ATTDEF/ATTRIB DXF,
DXF MATERIAL/ACSH matrix, restorable SAT/SAB + history roots) and issues
#55 #64-#69 fixed. EntityType now boxes Surface, Extended, Table,
MultiLeader and Helix (2344 B -> 848 B per entity): construction sites
wrap in Box, the entity traits forward through Box, and the python
plugin generator converts with into(). Kernel: PR #70 (cuboid ring
winding).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-02 00:08:55 +03:00
Hakan SevenandClaude Opus 5.5 8c1471078d fix(control): unbounded entities no longer overflow the capture candidate area
An XLINE or RAY projects to saturated i32 corners; their difference
overflowed and panicked the debug build on every capture.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-02 00:08:55 +03:00
Karim Jerbi 9d53502b19 feat(mcp): implement 4-pillar auto-sync, dynamic introspection, and non-blocking validation
- Pillar 1 (Runtime Auto-Sync):
  * Add sync_agent_tool_schemas() in src/mcp.rs to atomically export live tool schemas & instructions to ~/.gemini/antigravity/mcp/opencadstudio/
  * Automatically invoke sync on MCP startup (mcp::run()) and GUI automation startup (transport::listen())
  * Add --sync-mcp-schemas CLI flag in src/cli.rs and src/main.rs

- Pillar 2 (Development Hook):
  * Strengthen export_agent_tool_schemas test in src/mcp.rs to assert all schema files and instructions.md exist and are in sync on every cargo test run

- Pillar 3 (In-Band Dynamic Introspection):
  * Add 'tools' to READ_OPS in src/mcp.rs and query match in src/app/control/mod.rs
  * Enable agents to dynamically query live tool definitions and instructions via ocs_read (op: 'tools') over MCP or raw socket

- Pillar 4 (Non-Blocking Validation):
  * Set additionalProperties: true on ocs_capture schema in src/mcp.rs to prevent rigid schema rejection of emerging options
2026-10-01 17:13:24 +01:00
Karim Jerbi 3c1c1364c6 fix(control,mcp): auto-restore minimized window on capture, add switch_document alias, and export schemas 2026-10-01 17:06:16 +01:00
PanosandClaude Opus 5 7e12dab89e fix(image): erasing a broken raster reference clears its placeholder text
A raster reference that cannot be resolved is the only framed entity whose
to_render emits a RenderObject::Text: the frame and its diagonals are lines,
but the saved file path becomes a real glyph run in the SDF text buffer.

gather_text_verts reuses the whole previous vertex buffer when
text_unchanged(epoch) says no text-bearing entity moved, and that asks
entity_affects_text_cache -- which enumerated Text, MText, Dimension,
MultiLeader, Leader, Table, Tolerance, attributes and Insert, but not
RasterImage. So an erase never raised CACHE_CATEGORY_TEXT, the stale buffer
was taken as valid, and the path kept drawing over empty space. The reuse
branch then re-stamps that buffer with the current epoch, which froze it
until a full rebuild. CACHE_CATEGORY_IMAGE did not cover the gap: it is set
from images.contains_key(handle), and a missing reference has no ImageModel
at all.

The same gap broke three more flows from the Added/Modified side: ATTACH of
a missing reference showed no text, MOVE and grip-drag left the text behind
while the frame followed, and UNDO after an erase did not bring it back.

entity_affects_text_cache now counts a RasterImage whose reference does not
resolve, reusing the converter's memoised resolve_image probe so the two
cannot disagree. Kept a probe rather than a blanket type match so a healthy
image does not rebuild every glyph in the drawing on each mouse move of a
grip-drag.

Four regression tests, each confirmed to fail without the fix. The main one
is end-to-end on the buffer the GPU draws: before, the erased placeholder
left 300 glyph vertices on screen (50 chars x 6).

Also: to_render ran the same resolve probe twice; now once, shared by the
outline and placeholder branches. Moved text_unchanged's doc comment off
draw_ranks_stable, where it had drifted, and recorded the rule that every
entity able to emit a GlyphRun must be declared there.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-10-01 17:42:38 +03:00
ramox81andClaude Opus 5.5 1c10e5be6a ATTDEF automation: edit_value and dismiss dialog fields
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 17:30:40 +03:00
Karim Jerbi 3075784f63 feat(mcp): implement multiscale pyramidal tiling protocol (DeepZoom)
- Add \PyramidLevelInfo\, \PyramidManifest\, \compute_pyramid_manifest\, \compute_tile_bounds\, and \point_to_tile\ in \ision.rs\
- Expose DeepZoom pyramid manifest resource at \cad://session/{session_id}/pyramid/manifest.json\
- Support on-demand and cached pyramidal tile resources at \cad://session/{session_id}/tile/{level}/{x}/{y}.png\ and \.json\
- Add \	ile: { level, x, y }\ and \pyramid_manifest: boolean\ to \ocs_capture\ with regional camera framing
- Enable LLM agents to inspect dense CAD drawings via multiscale resolution levels without exceeding context/tile token budgets
- Add unit tests for pyramid tiling math, manifest generation, resource listing/reading, and structured metadata formatting
2026-10-01 15:17:00 +01:00
ramox81andClaude Opus 5.5 7f55043210 ATTDEF dialog error band and multi-line editor; ATTDISP sets ATTMODE
Validation messages show in the dialogs, the Default value of a multi-line
definition can be edited in the multi-line text editor, "Specify on-screen"
is kept for the session, ATTDISP sets ATTMODE with the reference prompt
instead of changing the definitions, and Insert > Block gets the Edit
Attribute (Single / Multiple) and attribute display lists.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 17:11:45 +03:00
Karim Jerbi 350742f2b0 feat(mcp): add standardized spatial metadata schema and visual differential streaming
- Standardize spatial metadata under \_spatial\ with \CAD_WCS\ CRS, document units, forward/inverse affine matrices (\pixel_to_world_matrix\, \world_to_pixel_matrix\), camera projection, and world bounding bounds
- Implement visual differential engine (\compute_visual_diff\) detecting pixel-level changes between viewport frames
- Map dirty pixel bounding box directly to CAD world coordinates (\dirty_world_bounds\) using the spatial transform
- Add \diff\, \diff_mode\ ('highlight' | 'crop' | 'metadata_only'), and \
eset_diff_baseline\ parameters to \ocs_capture\
- Support high-efficiency dirty region cropping to drastically minimize vision token and bandwidth consumption
- Add unit tests for spatial projection, diff computation, tool schema, and structured metadata formatting
2026-10-01 14:48:31 +01:00
PanosandClaude Opus 5 d596b5a6be fix(view): zoom cursor per navigation tool, and ZOOM EXTENTS frames everything
Two viewport-navigation defects, both measured against commercial solutions.

The cursor stayed a hand during a zoom. `selection_overlay` took one boolean
for all three interactive navigation tools, so ZOOM Dynamic and ORBIT both
showed PAN's grab hand — which reads as "drag the sheet", the wrong promise
for either. Split it into a `NavCursor` enum: PAN keeps the open/closed hand,
ORBIT gets four-way arrows, and ZOOM Dynamic gets the magnifier carrying the
sign of the zoom actually under way — "+" dragging up, "-" dragging down,
latched with a 2 px dead zone so a hand held still cannot strobe the glyph.
ZOOM Dynamic also reused `box_anchor` to remember where a drag began, so a
selection marquee rubber-banded across the screen while the view zoomed; the
drawing is now suppressed, the state left alone for `reproject_box_anchor`.

ZOOM EXTENTS did not reach the whole drawing, for three separate reasons, now
answered by one shared `Scene::visible_block_bounds`:

  - A quartile filter dropped any wire whose centroid sat outside the
    inter-quartile consensus of the others. It was meant to stop one junk wire
    from a bad parse poisoning the box, but it could not tell parser junk from
    an outlying detail, a survey point, or a block placed away from the rest,
    and silently refused to frame them. Gone; the absolute 1e16 sentinel gate
    the paper path already used is the only filter, and the XLine / Ray display
    segments that motivated the heuristic are handled explicitly.

  - HATCH tessellates to no wires at all, and the model path never read the
    fill models, so a drawing whose outermost geometry is a fill — or which is
    nothing but fills — had nothing to frame. It now folds them in, reusing the
    renderer's own warm cache on the hot path rather than re-exploding every
    INSERT per ZOOM EXTENTS.

  - Inside a floating viewport the fit came from `compute_model_space_extents`,
    which walked only `key_vertices` — empty for every tessellated curve.
    Circles, arcs, ellipses and splines contributed nothing. Fixing it also
    corrects plot Extents, sheet-set framing, viewport auto-fit and SpaceMouse
    model bounds, which all inherited that blind spot.

Bounds stay f64 into the camera: a UTM drawing lost whole metres to the old
f32 round-trip. Drawing extents also no longer read the camera — the result is
cached per geometry epoch, and a floating viewport's camera is derived FROM
the extents, so `camera_for_viewport` recursed into a stack overflow.

`model_space_extents_mixed_entities_accuracy` asserted the curve-blind result;
it now asserts the true bounds.

Co-Authored-By: Claude Opus 5 <[email protected]>
2026-10-01 16:27:26 +03:00
Karim Jerbi bf7f37aaf4 feat(mcp): support MCP resources and resource delivery for captures
- Expose MCP resources/list and resources/read for active viewports, drawing state, and cached snapshots
- Introduce ResourceStore with SHA-256 content-addressed URIs (cad://session/{session_id}/snapshot/{hash}.png)
- Add delivery parameter (inline, resource, both) to ocs_capture tool schema
- Return standard MCP EmbeddedResource content block when delivery: 'resource' to avoid base64 context bloat
- Add comprehensive MCP unit tests for resource listing, blob reading, and tool result delivery modes
2026-10-01 14:03:34 +01:00
Karim Jerbi 6cc53c1001 feat(mcp): add Set-of-Marks grounding, regional framing, and 2-point image calibration
- Add Set-of-Marks (SoM) visual grounding (src/app/control/vision.rs):
  * Render high-contrast numbered badges on entity visual centroids in viewport captures
  * Project 3D entity bounds to 2D image coordinates with priority ranking (selected/size)
  * Return bidirectional grounding manifest (annotations / visible_entities) in capture and ocs_capture payloads mapping each badge to entity handle, layer, type, and world center

- Add regional viewport framing (src/app/control/mod.rs, src/mcp.rs):
  * Support view: region and bounds: [min_x, min_y, max_x, max_y] in capture and ocs_capture
  * Enable programmatic zoom and high-resolution inspection of specific rooms or local geometry

- Add 2-point raster image calibration (src/app/control/actions.rs, src/mcp_ops.rs):
  * Extend embed_image with optional source_points (pixel coords) and target_points (CAD coords)
  * Automatically calculate scale, world dimensions, and insertion origin at
  * Add unit test embed_image_calibrates_from_source_and_target_points
2026-10-01 13:27:22 +01:00
ramox81andClaude Opus 5.5 c992b73cdf ATTDEF: Fit/Align attribute text, TEXTSIZE, single-line restart
Align and Fit attributes run their text between the two baseline points,
an ATTDEF height becomes the next text height, and Multiple lines is not
carried to the next definition (measured).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 14:16:06 +03:00
ramox81andClaude Opus 5.5 c5790c74a9 ATTDEF: dialog, -ATTDEF prompts, tag display, Properties and ribbon
Attribute Definition dialog and Edit Attribute Definition dialog, -ATTDEF
with the reference prompts and modes (AFLAGS), tag shown in the drawing,
justification-aware grips, reworked Properties with validation, Home Block
slide-out and Insert Block Definition panel, and the codec patch for
ATTDEF DXF output and the R2013+ solid wire cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 13:55:32 +03:00
ramox81andClaude Opus 5.5 4ddef1f9ae Blocks palette: larger Options collapse arrow
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 11:30:28 +03:00
ramox81andClaude Opus 5.5 0826101c5e Blocks palette: tabs, options, drag insertion and -INSERT
Rebuild the Blocks palette with Current Drawing / Recent / Favorites /
Libraries tabs, wildcard filter, six views, insertion options, click and
drop insertion and a block context menu. INSERT opens the palette, the
new -INSERT runs on the command line, the ribbon Insert button becomes a
block gallery, and BLOCKMRULIST, BLOCKREDEFINEMODE, BLOCKNAVIGATE,
BLOCKSTATE, EXPLMODE and INSNAME are added.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 11:17:38 +03:00
Hakan SevenandClaude Opus 5.5 3dcebf0dc6 Merge pull request #1553 from ramox81/codex/pointcloud-attach
Point clouds: drawn from their scans, attached, cropped and stylized.

The fork's codec patch is resolved to the upstream pins: the point cloud
records landed in opencadcodec 5ef9376, carried through opencadkernel
68eeda1 and opencadgraph e204966.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 01:49:25 +03:00
Hakan SevenandClaude Opus 5.5 34dfee032d refactor(snap): keep the ellipse-arc parameter test private and plain
Only snap.rs uses it; the full-turn checks collapse into one.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 01:22:43 +03:00
Hakan Seven 66ca17e8fc Merge pull request #1551 from yztink/fix/ellipse-arc-tangent-snap-break
fix(snap): do not snap tangent across ellipse arc break
2026-10-01 01:21:34 +03:00
Hakan SevenandClaude Opus 5.5 9dd9b3eb8d test(icons): run the themed-handle timing benchmark only on request
It asserted a wall-clock race between two loops, which the parallel
suite's load lost now and then. The cache's behaviour stays pinned by
the entry-count tests.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 00:27:42 +03:00
Hakan SevenandClaude Opus 5.5 95a4419d0d fix(blocks): each dashed line in a block starts its own pattern
Block children of one style are batched into a single wire, and a
plinegen wire carries its dash distance across the joins. Every LINE
wire is plinegen, so each line in a block began mid-dash wherever the
previous one had stopped. PLINEGEN governs a wire's own breaks; a member
without any now enters its batch as non-plinegen.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 00:27:42 +03:00
Hakan SevenandClaude Opus 5.5 1f5a7e97a1 fix(dimension): a dimension drawn live matches its baked block
Once edited, a dimension is drawn live instead of from its *D block;
on the #898 drawing that differed in three places:

- Oblique / architectural-tick strokes were DIMASZ/2 to each side, the
  block's are DIMASZ/sqrt(2) (its unit stroke runs corner to corner).
- Arrowheads and ticks shared the dimension line's wire, so a dashed
  dim line broke its ticks into stubs. They get their own solid wire
  (and explode as lines as before).
- A diameter's user-positioned text was lifted by the DIMTAD offset even
  when the stored point already was the text's middle, as a file saved
  elsewhere writes it; it is lifted only when it lies on the leader
  (#1323's case).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 00:27:42 +03:00
Hakan SevenandClaude Opus 5.5 59651052f8 fix(dimension): oblique and architectural-tick arrow blocks fit as ticks
Only DIMTSZ > 0 counted as ticks, so a style drawing its strokes with
the _OBLIQUE / _ARCHTICK arrow block gave each stroke a full arrow's
room: an 18-long dimension with 4.8 arrows moved its strokes outside
and ran the dim line past the extension lines once it was drawn live
(after any edit, #898). Tick arrow blocks now count as ticks for fit
and DIMDLE, like the file's own baked block shows them.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-10-01 00:14:13 +03:00
Hakan SevenandClaude Opus 5.5 2a15a370f6 fix(dimension): an edited dimension keeps its layer's linetype
A dimension loaded from a file draws from its baked *D block, whose
lines are ByBlock and so take the dimension's linetype (ByLayer: the
layer's). Any edit - text colour, MATCHPROP, a grip - drops that block
and the dimension draws live, where a style with no DIMLTYPE/DIMLTEX1/2
drew solid: an edited dimension on a dashed layer turned solid (#898).
None or ByBlock now takes the dimension's own linetype, ByLayer its
layer's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-30 22:39:33 +03:00
Hakan SevenandClaude Opus 5.5 1fec34d84a fix(automation): TCP automation requires a session token
--http (headless and GUI-hosted) and --serve --port answered anything
that reached the loopback port, and the REST responses allowed every
web origin. Loopback is shared by every process and user on the
machine, so the port proved nothing.

- Every REST request now needs Authorization: Bearer <token>, and every
  --serve --port request line a "token" field; otherwise 401 /
  unauthorized (the socket is closed).
- The token is OCS_API_TOKEN when the launcher sets it, else 32 random
  bytes printed on stderr at startup; compared in constant time.
- No CORS headers are sent, so a web page cannot read an answer.
- stdio --serve and --mcp are unchanged (private to their parent / the
  GUI's own token).

GHSA-c27p-xfx2-9r5x

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-09-30 21:48:20 +03:00
gianlucafiore 2131f4390f fix(trim): support polyline self-intersections and box trimming 2026-09-30 15:35:51 -03:00
Karim Jerbi d0bfa48037 fix(units): clamp precision vars and their formatters
Bug:
SETVAR LUPREC and SETVAR AUPREC stored any parseable i16 verbatim, and
the header value flows through UnitContext into the per-call
formatters, which applied only a lower bound (.max(0)) with no upper
bound: format_length and format_angle rendered {:.*} with the raw
precision. SETVAR LUPREC 30000 therefore made format_length emit
30003-character strings on every properties and annotation formatting
call - a ~30 KB allocation per formatted value - while format_area in
the same file had long since capped itself with .min(15) and the units
dialog only ever offers 0-8 places. Negative values were also stored
verbatim.

Reproduce:
1. Command line: SETVAR LUPREC 30000 (or AUPREC 30000), then select
   something so the properties palette formats lengths/angles.
2. Before: the header stores 30000 and each formatted value is ~30 KB
   (the test measured 30003 chars for one length); -3 is stored as-is.
3. After: the setter stores 8 (0-8 range, echoed truthfully), -3
   stores 0, 5 stores 5 - and even a file carrying LUPREC 30000 in its
   header formats short output, because the formatters cap themselves.

Fix:
Two layers. The formatters get the cap format_area already uses:
format_signed_length and format_signed_angle now clamp with
.max(0).min(15), so every source - SETVAR, the units dialog, and
values carried in DWG/DXF files - produces bounded output on the hot
paths (15 matches the point past which f64 decimal output is
meaningless, which is why format_area was written that way). The
setters store x.clamp(0, 8) with the clamped value echoed back, the
same stay-inside-the-app's-own-UI-range rule SETVAR ISOLINES follows
against the Options slider. Architectural and fractional formats
ignore precision (fixed 1/64-inch resolution) and are unaffected.
Regression tests mirror the existing patterns: one forces hostile
precision through the formatters while saving and restoring the
thread-local unit context, one drives SETVAR through the command line
and checks the stored header values.
2026-09-30 19:15:50 +01:00
Karim Jerbi b1f4047f9c fix(plugins): degrade ensure_plugin_state instead of panicking
Bug:
The typed ensure_plugin_state helper and the object-safe trait method
it wraps turned two recoverable conditions into process deaths. On the
in-process host, the helper downcast the stored state with
.expect("plugin state type mismatch for plugin_id"), so registering
state under one plugin_id as one type and later asking for another
(e.g. a reloaded plugin version changes the type while the per-tab
state map survives) panicked the host. On out-of-process hosts
(ipc/client.rs, ipc/v4/client.rs) and on NullHost, the trait method
itself was implemented as a bare panic!("ensure_plugin_state is not
supported for out-of-process plugins..."), so any out-of-process
plugin calling the documented helper crashed its own runner process -
even though the sibling plugin_state_any and plugin_state_any_mut
methods on those same implementations already degrade to None
gracefully. The helper also used .expect("init called once") on the
initialiser closure.

Reproduce:
1. Out-of-process: a plugin whose runner calls ensure_plugin_state
   (&mut host, "my.id", ...).
2. Type mismatch: in an in-process plugin, ensure state under one id
   as u32, then ensure a different type under the same id.
3. Before: step 1 kills the plugin runner at the trait panic; step 2
   kills the host at the downcast expect. After: both get None, keep
   running, and existing state is untouched.

Fix:
Give the trait method a failure channel: ensure_plugin_state_any now
returns Option<&mut (dyn Any + Send + Sync)>, mirroring the sibling
plugin_state_any_mut on the same implementations, and the typed helper
returns Option<&mut T> (any?.downcast_mut). The panicking
implementations (ipc v3, ipc v4, NullHost, and the three never-called
test dummies) return None; the in-process app host wraps its real
storage in Some with unchanged insert-or-return semantics. The init
closure is now guarded by take() with a unit-Any fallback, so even an
implementation invoking it twice fails the typed downcast instead of
panicking. Object safety, argument types and vtable slot are
unchanged; external plugin sources get a compile error at the helper
and adopt Option handling on rebuild. Regression tests use catch_unwind
so they compile against both signatures: one per panic site (out-of-
process, NullHost, type mismatch), each additionally asserting the
None result and that pre-existing state survived.
2026-09-30 19:15:50 +01:00
Karim Jerbi c95d42a796 fix(mcp): evict tasks past their advertised ttl
Bug:
The MCP adapter advertises "ttlMs": 3_600_000 on every task it hands
out and answers "Unknown or expired taskId" for missing ids, but the
task store itself had no expiry logic: insert was a bare push_back with
no cap, no TTL and no cleanup anywhere, and get_mut the only other
method. Every tools/call that returns accepted/running stores a task
including a clone of the full request arguments JSON, so a client
looping on long-running calls grows the store without bound and the MCP
server process slowly leaks until it OOMs. The advertised number was
also hardcoded in two separate response sites with nothing behind it.

Reproduce:
1. Start OpenCADStudio --mcp, connect a client with the tasks
   capability, and issue tools/call calls that return accepted
   repeatedly - each one stores a task.
2. Before: the tasks queue grows monotonically for the process
   lifetime; a task inserted an hour ago is still handed back by
   tasks/get even though the server promised a one-hour ttl.
3. After: tasks older than the advertised ttl are gone, tasks/get on
   them returns the already-existing "Unknown or expired taskId"
   error, and the store holds at most one hour of task traffic.

Fix:
Enforce the value the server already advertises. Each McpTask is now
wrapped in a StoredTask with an expires_at deadline of insertion time
plus TASK_TTL_MS (3_600_000), a single constant that also feeds both
"ttlMs" response literals so the promise and the eviction rule cannot
drift apart. insert and get_mut both evict expired entries before
looking (retain on a monotonic Instant), so writes reclaim stale tasks
and reads stop resolving expired ids - the store only ever holds tasks
created within the last hour. The ttl runs from insertion rather than
being refreshed by polls: poll_task rewrites last_updated_at on every
working poll, so a sliding window would keep a stuck task alive forever
and reintroduce the leak. The expiration test injects the clock through
insert_at/get_mut_at, so it checks fresh, expired and evict-on-insert
behaviour without sleeping.
2026-09-30 19:15:50 +01:00
Karim Jerbi b19253374c fix(start): saturate the recent-limit plus step
Bug:
The keep-recent-files footer on the Start page builds its [-] [count]
[+] buttons eagerly while constructing the widget, and the [+] step was
written as plain shown + STEP while the [-] button next to it already
used saturating_sub. shown comes from the input box, whose handler
keeps every ASCII digit with no length cap - so typing
18446744073709551615 (2^64-1) parses to usize::MAX and the addition
overflowed during view(), before the button was ever clicked. Debug
builds panic with "attempt to add with overflow"; release builds (no
overflow checks) wrap to a small number and request a nonsense limit.
The clamp in set_recent_limit runs only after the value is computed.

Reproduce:
1. Start page -> "keep recent files" box -> type
   18446744073709551615.
2. Before: the next frame panics at widget construction (on render, no
   click needed); release builds wrap the step silently.
3. After: no panic; pressing Enter or [+] applies the clamped limit and
   the box resyncs to it.

Fix:
Mirror the [-] button: shown.saturating_add(STEP). At usize::MAX the
message carries usize::MAX, which the handler's existing
clamp-and-resync treats exactly like any other over-max entry, so both
step buttons are now saturating and the release-build wrap is closed as
well. on_submit has no arithmetic and needs no change. The regression
test calls start_page_content directly with the hostile string - it
fails at the same line instead of requiring a GUI session.
2026-09-30 19:15:49 +01:00
Karim Jerbi e15d801011 fix(tess): clamp isoline counts before they reach the kernel
Bug:
$ISOLINES (header i16) and Surface.u/v_isolines (file-controlled i16)
were only ever floored at 0, never capped, and were handed to the
tessellation kernel as the per-face isolate count - which draws
0..count isolines per face with no ceiling of its own. SETVAR ISOLINES
32767 (or a DWG carrying that header, or a Surface with u_isolines =
32767) turned every rebuild and every per-cursor preview of
PRESSPULL/REVOLVE/SWEEP/LOFT into a multi-million-vertex computation:
measured 4,259,966 edge vertices for one 12-unit cylinder preview.

Reproduce:
1. SETVAR ISOLINES 32767 (or open a DWG whose $ISOLINES is large, or
   edit a Surface whose u_isolines is 32767).
2. Draw a circle and start REVOLVE (or PRESSPULL/SWEEP/LOFT), or shade
   any 3D solid.
3. Before: the app allocates without bound - abort on memory failure or
   a permanent freeze; previews recompute on every mouse move.
4. After: previews stay interactive; a hostile header renders exactly
   like the largest value the Options slider can request.

Fix:
Cap each value at the ceiling this product already agrees on, where the
type changes from i16 to the kernel count: header $ISOLINES <= 64 (the
Options slider's own "Isolines per surface" range), Surface
u/v_isolines <= 200 (the plugin editor's writable range). One helper
(clamp_header_isolines) replaces all 11 copies of .max(0) as usize
across the entity/scene/control/display feed sites,
surface_isoline_counts clamps both axes, and SETVAR ISOLINES stores
x.clamp(0, 64) so the echo, slider and re-saved files agree with what
renders; file-sourced headers keep their raw stored value and are
clamped at consumption. Clamping is density-only: geometry, bounds and
saves are untouched. Three regression tests cover hostile surface
counts, the SETVAR entry, and a file-sourced header measured through
display tessellation (hostile renders like the slider ceiling, negative
renders like zero).
2026-09-30 19:15:49 +01:00
Karim Jerbi 438a46b80f fix(serve): drop idle socket clients so the accept loop keeps serving
Bug:
--serve in socket mode serves one client at a time: the accept loop
blocks in the per-client line read before it reaches the next
connection, and this path never called set_read_timeout - unlike
rest.rs, http_bridge.rs and control::transport, which all use 15
seconds. A client that connects and sends nothing held the read open
forever, wedging the port: every later client hung waiting for the
ready banner (the banner is written before the read loop, so the server
looked healthy while it was stuck).

Reproduce:
1. Start OpenCADStudio --serve --port 8765.
2. From any shell, connect and send nothing:
   python -c "import socket,time;socket.create_connection(('127.0.0.1',8765));time.sleep(3600)"
3. From a second shell, connect and wait for the banner.
4. Before: the second client hangs forever; the port never serves
   another connection.
5. After: the idle first client is disconnected 15 seconds after its
   last read, and the second client receives the ready banner.

Fix:
The one timeout this transport was missing: SERVE_IDLE_TIMEOUT = 15 s
(same value as the other transports), set on each accepted socket via
serve_socket_with_idle - a seam that also lets the regression test run
with 300 ms. A timed-out read surfaces as an error from lines_capped,
which the loop's existing let Ok(line) ... else break already turns
into "drop this client and accept the next one"; a partially read line
is discarded, which is correct because it was never dispatched. The
timeout only runs while a read is pending, so long server-side
operations do not spend the idle budget, and the document session
survives the reconnect. Regression test: an idle client must see EOF
and the following client must still get its banner.
2026-09-30 19:15:49 +01:00
Karim Jerbi 9b3842c0f2 fix(table): clamp formula range walks to the table
Bug:
evaluate_table_formula walked for row in r1.min(r2)..=r1.max(r2) across
columns with no bound, and table_cell_reference parses any usize -
=SUM(A1:A18446744073709551615) names about 1.8e19 rows. table.cell()
returns None outside the table, so results were correct; the loop just
never finished. The walk runs during tessellation, i.e. on the render
path - the app freezes permanently and cannot even be closed.

Reproduce:
1. Insert a table, double-click a cell.
2. Type =SUM(A1:A18446744073709551615) (or
   =SUM(A1:A1000000000) - a minutes-long freeze) and press Enter.
3. Before: the next repaint hangs forever.
4. After: the value appears immediately.

Fix:
The walk is clamped to the table's own rows/columns: row_end =
r1.max(r2).min(rows - 1) (same for columns). Every skipped cell was a
None, so the collected values - and every function's result
(SUM/AVERAGE/COUNT/MIN/MAX) - are identical; the loop now runs at most
rows x columns. start > end after clamping is an empty range, so
out-of-table references simply collect nothing (as before). The
regression test also asserts total evaluation time under 5 seconds,
turning any future un-clamped loop into a fast failure.
2026-09-30 19:15:49 +01:00
Karim Jerbi 2041d5f1ab fix(table): bound row and column counts by a cell budget
Bug:
The properties panel's Rows/Columns fields feed apply_geom_prop's grow
loops: number.round() as usize with no upper bound - and parse_f64
accepts up to 1e15. while rows.len() < requested { add_row() } pushes
rows until the allocator aborts. The magnitude validation in this path
governs geometry, not iteration counts.

Reproduce:
1. Insert a table, select it, open Properties -> Rows (or Columns).
2. Enter 1000000000000000 and commit.
3. Before: grows until "memory allocation failed".
4. After: the table grows to at most 1,000,000 cells (e.g. 100,000 rows
   x 10 columns) and stays responsive; a legitimate shrink to a smaller
   number still works exactly.

Fix:
One product budget, MAX_TABLE_CELLS = 1_000_000, applied per dimension:
grow_to = requested.min(budget / other_dimension) clamps the grow loops
only - the shrink loops keep the raw requested count, so shrinks stay
exact and the two loops cannot fight (grow_to <= requested by
construction). A table loaded over the budget is preserved: growth is
skipped and only an explicit smaller request shrinks it. The product,
not per-dimension caps, is what bounds memory regardless of which field
is set first. Tests cover overshoot at cap+10 and the 1e15 input for
both fields.
2026-09-30 19:15:49 +01:00